View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one   *
3    * or more contributor license agreements.  See the NOTICE file *
4    * distributed with this work for additional information        *
5    * regarding copyright ownership.  The ASF licenses this file   *
6    * to you under the Apache License, Version 2.0 (the            *
7    * "License"); you may not use this file except in compliance   *
8    * with the License.  You may obtain a copy of the License at   *
9    *                                                              *
10   *   http://www.apache.org/licenses/LICENSE-2.0                 *
11   *                                                              *
12   * Unless required by applicable law or agreed to in writing,   *
13   * software distributed under the License is distributed on an  *
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
15   * KIND, either express or implied.  See the License for the    *
16   * specific language governing permissions and limitations      *
17   * under the License.                                           *
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   * The collection of standard options for the CLI as well as utility methods to manage them and methods to create the
61   * ReportConfiguration from the options and an array of arguments.
62   */
63  public final class OptionCollection {
64  
65      private OptionCollection() {
66          // do not instantiate
67      }
68  
69      /** The Option comparator to sort the help */
70      public static final Comparator<Option> OPTION_COMPARATOR = new OptionComparator();
71  
72      /** The Help option */
73      public static final Option HELP = new Option("?", "help", false, "Print help for the RAT command line interface and exit.");
74  
75      /** A mapping of {@code argName(value)} values to a description of those values. */
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       * Gets the mapping of {@code argName(value)} values to a description of those values.
87       * @return the mapping of {@code argName(value)} values to a description of those values.
88       * @deprecated use {@link ArgumentType}
89       */
90      @Deprecated
91      public static Map<String, Supplier<String>> getArgumentTypes() {
92          return Collections.unmodifiableMap(ARGUMENT_TYPES);
93      }
94  
95      /**
96       * Join a collection of objects together as a comma separated list of their string values.
97       * @param args the objects to join together.
98       * @return the comma separated string.
99       */
100     private static String asString(final Object[] args) {
101         return Arrays.stream(args).map(Object::toString).collect(Collectors.joining(", "));
102     }
103 
104     /**
105      * Parses the standard options to create a ReportConfiguration.
106      *
107      * @param workingDirectory The directory to resolve relative file names against.
108      * @param args the arguments to parse
109      * @param helpCmd the help command to run when necessary.
110      * @return a ReportConfiguration or {@code null} if Help was printed.
111      * @throws IOException on error.
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      * Parses the standard options to create a ReportConfiguration.
119      *
120      * @param workingDirectory The directory to resolve relative file names against.
121      * @param args the arguments to parse.
122      * @param helpCmd the help command to run when necessary.
123      * @param noArgs If {@code true} then the commands do not need extra arguments.
124      * @return a ReportConfiguration or {@code null} if Help was printed.
125      * @throws IOException on error.
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; // dummy return (won't be reached) to avoid Eclipse complaint about possible NPE
140             // for "commandLine"
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      * Create the report configuration.
170      * Note: this method is package private for testing.
171      * You probably want one of the {@code ParseCommands} methods.
172      * @param argumentContext The context to execute in.
173      * @return a ReportConfiguration
174      * @see #parseCommands(File, String[], Consumer)
175      * @see #parseCommands(File, String[], Consumer, boolean)
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      * Create an {@code Options} object from the list of defined Options.
199      * Mutually exclusive options must be listed in an OptionGroup.
200      * @return the Options comprised of the Options defined in this class.
201      */
202     public static Options buildOptions() {
203         return Arg.getOptions().addOption(HELP);
204     }
205 
206     /**
207      * Creates an IReportable object from the directory name and ReportConfiguration
208      * object.
209      *
210      * @param base the directory that contains the files to report on.
211      * @param config the ReportConfiguration.
212      * @return the IReportable instance containing the files.
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      * This class implements the {@code Comparator} interface for comparing Options.
238      */
239     private static final class OptionComparator implements Comparator<Option>, Serializable {
240         /** The serial version UID.  */
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          * Compares its two arguments for order. Returns a negative integer, zero, or a
251          * positive integer as the first argument is less than, equal to, or greater
252          * than the second.
253          *
254          * @param opt1 The first Option to be compared.
255          * @param opt2 The second Option to be compared.
256          * @return a negative integer, zero, or a positive integer as the first argument
257          * is less than, equal to, or greater than the second.
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          * A plain file.
268          */
269         FILE("File", () -> "A file name."),
270         /**
271          * An Integer.
272          */
273         INTEGER("Integer", () -> "An integer value."),
274         /**
275          * A directory or archive.
276          */
277         DIRORARCHIVE("DirOrArchive", () -> "A directory or archive file to scan."),
278         /**
279          * A matching expression.
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          * A license filter.
287          */
288         LICENSEFILTER("LicenseFilter", () -> format("A defined filter for the licenses to include. Valid values: %s.",
289                 asString(LicenseSetFactory.LicenseFilter.values()))),
290         /**
291          * A log level.
292          */
293         LOGLEVEL("LogLevel", () -> format("The log level to use. Valid values %s.", asString(Level.values()))),
294         /**
295          * A processing type.
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          * A style sheet.
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          * A license id.
310          */
311         LICENSEID("LicenseID", () -> "The ID for a license."),
312         /**
313          * A license family id.
314          */
315         FAMILYID("FamilyID", () -> "The ID for a license family."),
316         /**
317          * A standard collection name.
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          * A Counter pattern name
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          * A generic argument.
335          */
336         ARG("Arg", () -> "A string"),
337         /**
338          * No argument.
339          */
340         NONE("", () -> "");
341 
342         /**
343          * The display name
344          */
345         private final String displayName;
346         /**
347          * A supplier of the description
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 }