1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.rat;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.io.Serializable;
25 import java.nio.charset.StandardCharsets;
26 import java.util.Arrays;
27 import java.util.Collections;
28 import java.util.Comparator;
29 import java.util.Map;
30 import java.util.TreeMap;
31 import java.util.function.Consumer;
32 import java.util.function.Supplier;
33 import java.util.stream.Collectors;
34
35 import org.apache.commons.cli.CommandLine;
36 import org.apache.commons.cli.DefaultParser;
37 import org.apache.commons.cli.Option;
38 import org.apache.commons.cli.Options;
39 import org.apache.commons.cli.ParseException;
40 import org.apache.rat.api.Document;
41 import org.apache.rat.commandline.Arg;
42 import org.apache.rat.commandline.ArgumentContext;
43 import org.apache.rat.commandline.StyleSheets;
44 import org.apache.rat.config.exclusion.StandardCollection;
45 import org.apache.rat.document.DocumentName;
46 import org.apache.rat.document.DocumentNameMatcher;
47 import org.apache.rat.document.FileDocument;
48 import org.apache.rat.help.Licenses;
49 import org.apache.rat.license.LicenseSetFactory;
50 import org.apache.rat.report.IReportable;
51 import org.apache.rat.report.claim.ClaimStatistic;
52 import org.apache.rat.utils.DefaultLog;
53 import org.apache.rat.utils.Log.Level;
54 import org.apache.rat.walker.ArchiveWalker;
55 import org.apache.rat.walker.DirectoryWalker;
56
57 import static java.lang.String.format;
58
59
60
61
62
63 public final class OptionCollection {
64
65 private OptionCollection() {
66
67 }
68
69
70 public static final Comparator<Option> OPTION_COMPARATOR = new OptionComparator();
71
72
73 public static final Option HELP = new Option("?", "help", false, "Print help for the RAT command line interface and exit.");
74
75
76 @Deprecated
77 private static final Map<String, Supplier<String>> ARGUMENT_TYPES;
78 static {
79 ARGUMENT_TYPES = new TreeMap<>();
80 for (ArgumentType argType : ArgumentType.values()) {
81 ARGUMENT_TYPES.put(argType.getDisplayName(), argType.description);
82 }
83 }
84
85
86
87
88
89
90 @Deprecated
91 public static Map<String, Supplier<String>> getArgumentTypes() {
92 return Collections.unmodifiableMap(ARGUMENT_TYPES);
93 }
94
95
96
97
98
99
100 private static String asString(final Object[] args) {
101 return Arrays.stream(args).map(Object::toString).collect(Collectors.joining(", "));
102 }
103
104
105
106
107
108
109
110
111
112
113 public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer<Options> helpCmd) throws IOException {
114 return parseCommands(workingDirectory, args, helpCmd, false);
115 }
116
117
118
119
120
121
122
123
124
125
126
127 public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args,
128 final Consumer<Options> helpCmd, final boolean noArgs) throws IOException {
129
130 Options opts = buildOptions();
131 CommandLine commandLine;
132 try {
133 commandLine = DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter())
134 .setAllowPartialMatching(true).build().parse(opts, args);
135 } catch (ParseException e) {
136 DefaultLog.getInstance().error(e.getMessage());
137 DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e);
138 System.exit(1);
139 return null;
140
141 }
142
143 Arg.processLogLevel(commandLine);
144
145 ArgumentContext argumentContext = new ArgumentContext(workingDirectory, commandLine);
146
147 if (commandLine.hasOption(HELP)) {
148 helpCmd.accept(opts);
149 return null;
150 }
151
152 if (commandLine.hasOption(Arg.HELP_LICENSES.option())) {
153 new Licenses(createConfiguration(argumentContext), new PrintWriter(System.out, false, StandardCharsets.UTF_8)).printHelp();
154 return null;
155 }
156
157 ReportConfiguration configuration = createConfiguration(argumentContext);
158 if (!noArgs && !configuration.hasSource()) {
159 String msg = "No directories or files specified for scanning. Did you forget to close a multi-argument option?";
160 DefaultLog.getInstance().error(msg);
161 helpCmd.accept(opts);
162 return null;
163 }
164
165 return configuration;
166 }
167
168
169
170
171
172
173
174
175
176
177 static ReportConfiguration createConfiguration(final ArgumentContext argumentContext) {
178 argumentContext.processArgs();
179 final ReportConfiguration configuration = argumentContext.getConfiguration();
180 final CommandLine commandLine = argumentContext.getCommandLine();
181 if (Arg.DIR.isSelected()) {
182 try {
183 configuration.addSource(getReportable(commandLine.getParsedOptionValue(Arg.DIR.getSelected()), configuration));
184 } catch (ParseException e) {
185 throw new ConfigurationException("Unable to set parse " + Arg.DIR.getSelected(), e);
186 }
187 }
188 for (String s : commandLine.getArgs()) {
189 IReportable reportable = getReportable(new File(s), configuration);
190 if (reportable != null) {
191 configuration.addSource(reportable);
192 }
193 }
194 return configuration;
195 }
196
197
198
199
200
201
202 public static Options buildOptions() {
203 return Arg.getOptions().addOption(HELP);
204 }
205
206
207
208
209
210
211
212
213
214 static IReportable getReportable(final File base, final ReportConfiguration config) {
215 File absBase = base.getAbsoluteFile();
216 DocumentName documentName = DocumentName.builder(absBase).build();
217 if (!absBase.exists()) {
218 DefaultLog.getInstance().error("Directory '" + documentName + "' does not exist.");
219 return null;
220 }
221 DocumentNameMatcher documentExcluder = config.getDocumentExcluder(documentName);
222
223 Document doc = new FileDocument(documentName, absBase, documentExcluder);
224 if (!documentExcluder.matches(doc.getName())) {
225 DefaultLog.getInstance().error("Directory '" + documentName + "' is in excluded list.");
226 return null;
227 }
228
229 if (absBase.isDirectory()) {
230 return new DirectoryWalker(doc);
231 }
232
233 return new ArchiveWalker(doc);
234 }
235
236
237
238
239 private static final class OptionComparator implements Comparator<Option>, Serializable {
240
241 private static final long serialVersionUID = 5305467873966684014L;
242
243 private String getKey(final Option opt) {
244 String key = opt.getOpt();
245 key = key == null ? opt.getLongOpt() : key;
246 return key;
247 }
248
249
250
251
252
253
254
255
256
257
258
259 @Override
260 public int compare(final Option opt1, final Option opt2) {
261 return getKey(opt1).compareToIgnoreCase(getKey(opt2));
262 }
263 }
264
265 public enum ArgumentType {
266
267
268
269 FILE("File", () -> "A file name."),
270
271
272
273 INTEGER("Integer", () -> "An integer value."),
274
275
276
277 DIRORARCHIVE("DirOrArchive", () -> "A directory or archive file to scan."),
278
279
280
281 EXPRESSION("Expression", () -> "A file matching pattern usually of the form used in Ant build files and " +
282 "'.gitignore' files (see https://ant.apache.org/manual/dirtasks.html#patterns for examples). " +
283 "Regular expression patterns may be specified by surrounding the pattern with '%regex[' and ']'. " +
284 "For example '%regex[[A-Z].*]' would match files and directories that start with uppercase latin letters."),
285
286
287
288 LICENSEFILTER("LicenseFilter", () -> format("A defined filter for the licenses to include. Valid values: %s.",
289 asString(LicenseSetFactory.LicenseFilter.values()))),
290
291
292
293 LOGLEVEL("LogLevel", () -> format("The log level to use. Valid values %s.", asString(Level.values()))),
294
295
296
297 PROCESSINGTYPE("ProcessingType", () -> format("Specifies how to process file types. Valid values are: %s%n",
298 Arrays.stream(ReportConfiguration.Processing.values())
299 .map(v -> format("\t%s: %s", v.name(), v.desc()))
300 .collect(Collectors.joining(System.lineSeparator())))),
301
302
303
304 STYLESHEET("StyleSheet", () -> format("Either an external xsl file or one of the internal named sheets. Internal sheets are: %n%s",
305 Arrays.stream(StyleSheets.values())
306 .map(v -> format("\t%s: %s%n", v.arg(), v.desc()))
307 .collect(Collectors.joining(System.lineSeparator())))),
308
309
310
311 LICENSEID("LicenseID", () -> "The ID for a license."),
312
313
314
315 FAMILYID("FamilyID", () -> "The ID for a license family."),
316
317
318
319 STANDARDCOLLECTION("StandardCollection", () -> format("Defines standard expression patterns (see above). Valid values are: %n%s%n",
320 Arrays.stream(StandardCollection.values())
321 .map(v -> format("\t%s: %s%n", v.name(), v.desc()))
322 .collect(Collectors.joining(System.lineSeparator())))),
323
324
325
326 COUNTERPATTERN("CounterPattern", () -> format("A pattern comprising one of the following prefixes followed by " +
327 "a colon and a count (e.g. %s:5). Prefixes are %n%s.", ClaimStatistic.Counter.UNAPPROVED,
328 Arrays.stream(ClaimStatistic.Counter.values())
329 .map(v -> format("\t%s: %s Default range [%s, %s]%n", v.name(), v.getDescription(),
330 v.getDefaultMinValue(),
331 v.getDefaultMaxValue() == -1 ? "unlimited" : v.getDefaultMaxValue()))
332 .collect(Collectors.joining(System.lineSeparator())))),
333
334
335
336 ARG("Arg", () -> "A string"),
337
338
339
340 NONE("", () -> "");
341
342
343
344
345 private final String displayName;
346
347
348
349 private final Supplier<String> description;
350
351 ArgumentType(final String name,
352 final Supplier<String> description) {
353 this.displayName = name;
354 this.description = description;
355 }
356
357 public String getDisplayName() {
358 return displayName;
359 }
360
361 public Supplier<String> description() {
362 return description;
363 }
364 }
365 }