summaryrefslogtreecommitdiff
path: root/support/latex-dependency-grapher/source/main/java/ch/bfh/lpdg/InteractionHandler.java
blob: 9175364b8250b5ec12ae5cfcb647d9cd4b02951a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package ch.bfh.lpdg;

import org.apache.commons.cli.*;

import java.io.File;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class InteractionHandler {

    //Definition of all the possible options. Short with one letter, or longer with one word.
    private static final String PathOption = "p";
    private static final String HelpOption = "h";
    private static final String DepthOption = "d";
    private static final String OverwriteOption = "o";
    private static final String MinimizeOption = "m";
    private static final String LicenseOptionLong = "license";
    private static final String DebugOptionLong = "debug";
    private boolean isSingleFile = false;
    private boolean isDebug = false;
    private boolean overwriteFlag = false;
    private boolean minimizeFlag = false;
    private final Options options;
    private final String userDirectory;
    private String path;
    private int depth = 5;

    public boolean hasOverwriteFlag() {
        return overwriteFlag;
    }

    public boolean hasMinimizeFlag() {
        return minimizeFlag;
    }

    public String  getPath() {
        return this.path;
    }

    public int  getDepth() {
        return this.depth;
    }

    public void setPath(final String path) {
        this.path = path;
    }

    public String getUserDirectory() {
        return userDirectory;
    }

    public final static InteractionHandler INSTANCE = new InteractionHandler();

    public static InteractionHandler getInstance() {
        return INSTANCE;
    }

    private InteractionHandler() {
        //The default value is the current directory where the application was called from.
        userDirectory = System.getProperty("user.dir");
        path = userDirectory;

        options = InitOptions();
    }

    private static Options InitOptions() {
        Options options = new Options();

        options.addOption(Option.builder(HelpOption)
                .desc("Print this message and quit.")
                .longOpt("help").build());

        options.addOption(Option.builder(DepthOption)
                .hasArg()
                .argName("Depth")
                .desc("The depth of the scan. Default value is 5.")
                .longOpt("depth").build());

        options.addOption(Option.builder(OverwriteOption)
                .desc("Overwrite the input file(s), with a version that only includes the necessary packages.")
                .longOpt("overwrite").build());

        options.addOption(Option.builder(MinimizeOption)
                .desc("Creates a minimized version of the input file(s), with only the necessary packages.")
                .longOpt("minimize").build());

        options.addOption(Option.builder(PathOption)
                .desc("File or path to be scanned. The default value is the current working directory.")
                .hasArg()
                .argName("Path")
                .longOpt("Path").build());

        options.addOption(Option.builder()
                .desc("Print the Licensing information and quit.")
                .longOpt(LicenseOptionLong).build());

        options.addOption(Option.builder()
                .desc("Print debug information.")
                .longOpt(DebugOptionLong).build());

        return options;
    }

    public void handleOptions(String[] args) throws ParseException {
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(DebugOptionLong)) {
            this.isDebug = true;
            printDebugMessage("Debugging.");
        }

        if (cmd.hasOption(HelpOption)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar LatexDependencyGrapher", "Scan your Latex file(s) to find unused pacakges and create a graph of your dependencies." , options, "");
            printDebugMessage("HelpOption called.");
            System.exit(0);
        }

        if (cmd.hasOption(PathOption)) {
            path = cmd.getOptionValue(PathOption);
            printDebugMessage("PathOption called. Values is: " + path);
            if (path.isBlank() || path.isEmpty())
                throw new MissingArgumentException("The value for the path is missing.");
        }

        if (cmd.hasOption(DepthOption)) {
            depth = Integer.parseInt(cmd.getOptionValue(DepthOption));
            printDebugMessage("DepthOption called. Values is: " + depth);
        }

        if (cmd.hasOption(LicenseOptionLong)) {
            System.out.println("This project uses the Apache Commons CLI Library, which is licensed under Apache License 2.0. See more in the NOTICE.txt File.");
            printDebugMessage("LicenseOption called. Values is: " + path);
            System.exit(0);
        }

        if (cmd.hasOption(MinimizeOption)) {
            minimizeFlag = true;
            printDebugMessage("MinimizeOption called.");
        }

        if (cmd.hasOption(OverwriteOption)) {
            overwriteFlag = true;
            printDebugMessage("OverwriteOption called.");
        }

        var validateResult = validatePath(path);
        if (!validateResult)
            throw new InvalidParameterException("The given path is invalid: " + path);
    }

    public List<File> getFiles() {
        List<File> files;
        if (isSingleFile) {
            if (path.endsWith(".sty") || path.endsWith(".cls") || path.endsWith(".tex")) {
                files = new ArrayList<>() {{
                    add(new File(path));
                }};
            } else
                throw new IllegalArgumentException("The given Path is not a LaTeX-File.");
        } else
            files = loadLatexFiles();

        return files;
    }

    public void printDebugMessage(String msg) {
        if (this.isDebug)
            System.out.println("\u001B[33m" + "DEBUG: " + msg + "\u001B[0m");
    }

    private Boolean validatePath(String path) {
        if (path == null) {
            printDebugMessage("Path is null.");
            return false;
        }
        File file = new File(path);
        printDebugMessage("Filepath: " + file.getAbsolutePath());
        if (!file.isDirectory()) {
            printDebugMessage("Path is not a directory");
            isSingleFile = file.exists();
            file = file.getParentFile();
        } else {
            isSingleFile = false;
        }

        if(isSingleFile)
        {
            printDebugMessage("The path is a single file.");
            if(!(path.endsWith(".sty") || path.endsWith(".cls") || path.endsWith(".tex")))
            {
                throw new IllegalArgumentException("The given Path is not a LaTeX-File.");
            }
        }

        return file != null && file.exists();
    }

    private List<File> loadLatexFiles() {

        if (isSingleFile)
            throw new IllegalCallerException("This method should only be called to load the LaTeX-Files from a directory.");

        List<File> latexFiles = new ArrayList<>();
        File directory = new File(path);
        if (directory.isDirectory()) {
            File[] files = directory.listFiles((dir, name) -> name.endsWith(".sty") || name.endsWith(".cls") || name.endsWith(".tex"));
            if (files != null) {
                latexFiles.addAll(Arrays.asList(files));
            }
        }

        return latexFiles;
    }
}