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