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.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   * The collection of standard options for the CLI as well as utility methods to manage them and methods to create the
60   * ReportConfiguration from the options and an array of arguments.
61   */
62  public final class OptionCollection {
63  
64      private OptionCollection() {
65          // do not instantiate
66      }
67  
68      /** The Option comparator to sort the help */
69      public static final Comparator<Option> OPTION_COMPARATOR = new OptionComparator();
70  
71      /** The Help option */
72      public static final Option HELP = new Option("?", "help", false, "Print help for the RAT command line interface and exit.");
73  
74      /** Provide license definition listing */
75      public static final Option HELP_LICENSES = Option.builder().longOpt("help-licenses")
76              .desc("Print help for the RAT command line interface and exit.").build();
77  
78      /** A mapping of {@code argName(value)} values to a description of those values. */
79      @Deprecated
80      private static final Map<String, Supplier<String>> ARGUMENT_TYPES;
81      static {
82          ARGUMENT_TYPES = new TreeMap<>();
83          for (ArgumentType argType : ArgumentType.values()) {
84              ARGUMENT_TYPES.put(argType.getDisplayName(), argType.description);
85          }
86      }
87  
88      /**
89       * Gets the mapping of {@code argName(value)} values to a description of those values.
90       * @return the mapping of {@code argName(value)} values to a description of those values.
91       * @deprecated use {@link ArgumentType}
92       */
93      @Deprecated
94      public static Map<String, Supplier<String>> getArgumentTypes() {
95          return Collections.unmodifiableMap(ARGUMENT_TYPES);
96      }
97  
98      /**
99       * Join a collection of objects together as a comma separated list of their string values.
100      * @param args the objects to join together.
101      * @return the comma separated string.
102      */
103     private static String asString(final Object[] args) {
104         return Arrays.stream(args).map(Object::toString).collect(Collectors.joining(", "));
105     }
106 
107     /**
108      * Parses the standard options to create a ReportConfiguration.
109      *
110      * @param workingDirectory The directory to resolve relative file names against.
111      * @param args the arguments to parse
112      * @param helpCmd the help command to run when necessary.
113      * @return a ReportConfiguration or {@code null} if Help was printed.
114      * @throws IOException on error.
115      */
116     public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer<Options> helpCmd) throws IOException {
117         return parseCommands(workingDirectory, args, helpCmd, false);
118     }
119 
120     /**
121      * Parses the standard options to create a ReportConfiguration.
122      *
123      * @param workingDirectory The directory to resolve relative file names against.
124      * @param args the arguments to parse
125      * @param helpCmd the help command to run when necessary.
126      * @param noArgs If true then the commands do not need extra arguments
127      * @return a ReportConfiguration or {@code null} if Help was printed.
128      * @throws IOException on error.
129      */
130     public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args,
131                                                     final Consumer<Options> helpCmd, final boolean noArgs) throws IOException {
132         Options opts = buildOptions();
133         CommandLine commandLine;
134         try {
135             commandLine = DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter())
136                     .setAllowPartialMatching(true).build().parse(opts, args);
137         } catch (ParseException e) {
138             DefaultLog.getInstance().error(e.getMessage());
139             DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e);
140             System.exit(1);
141             return null; // dummy return (won't be reached) to avoid Eclipse complaint about possible NPE
142             // for "commandLine"
143         }
144 
145         Arg.processLogLevel(commandLine);
146 
147         ArgumentContext argumentContext = new ArgumentContext(workingDirectory, commandLine);
148         if (commandLine.hasOption(HELP)) {
149             helpCmd.accept(opts);
150             return null;
151         }
152 
153         if (commandLine.hasOption(HELP_LICENSES)) {
154             new Licenses(createConfiguration(argumentContext), new PrintWriter(System.out)).printHelp();
155             return null;
156         }
157 
158         if (commandLine.hasOption(Arg.HELP_LICENSES.option())) {
159             new Licenses(createConfiguration(argumentContext), new PrintWriter(System.out)).printHelp();
160             return null;
161         }
162 
163         ReportConfiguration configuration = createConfiguration(argumentContext);
164         if (!noArgs && !configuration.hasSource()) {
165             String msg = "No directories or files specified for scanning. Did you forget to close a multi-argument option?";
166             DefaultLog.getInstance().error(msg);
167             helpCmd.accept(opts);
168             throw new ConfigurationException(msg);
169         }
170 
171         return configuration;
172     }
173 
174     /**
175      * Create the report configuration.
176      * Note: this method is package private for testing.
177      * You probably want one of the {@code ParseCommands} methods.
178      * @param argumentContext The context to execute in.
179      * @return a ReportConfiguration
180      * @see #parseCommands(File, String[], Consumer)
181      * @see #parseCommands(File, String[], Consumer, boolean)
182      */
183     static ReportConfiguration createConfiguration(final ArgumentContext argumentContext) {
184         argumentContext.processArgs();
185         final ReportConfiguration configuration = argumentContext.getConfiguration();
186         final CommandLine commandLine = argumentContext.getCommandLine();
187         if (Arg.DIR.isSelected()) {
188             try {
189                 configuration.addSource(getReportable(commandLine.getParsedOptionValue(Arg.DIR.getSelected()), configuration));
190             } catch (ParseException e) {
191                 throw new ConfigurationException("Unable to set parse " + Arg.DIR.getSelected(), e);
192             }
193         }
194         for (String s : commandLine.getArgs()) {
195             IReportable reportable = getReportable(new File(s), configuration);
196             if (reportable != null) {
197                 configuration.addSource(reportable);
198             }
199         }
200         return configuration;
201     }
202 
203     /**
204      * Create an {@code Options} object from the list of defined Options.
205      * Mutually exclusive options must be listed in an OptionGroup.
206      * @return the Options comprised of the Options defined in this class.
207      */
208     public static Options buildOptions() {
209         return Arg.getOptions().addOption(HELP);
210     }
211 
212     /**
213      * Creates an IReportable object from the directory name and ReportConfiguration
214      * object.
215      *
216      * @param base the directory that contains the files to report on.
217      * @param config the ReportConfiguration.
218      * @return the IReportable instance containing the files.
219      */
220     static IReportable getReportable(final File base, final ReportConfiguration config) {
221         File absBase = base.getAbsoluteFile();
222         DocumentName documentName = DocumentName.builder(absBase).build();
223         if (!absBase.exists()) {
224             DefaultLog.getInstance().error("Directory '" + documentName + "' does not exist.");
225             return null;
226         }
227         DocumentNameMatcher documentExcluder = config.getDocumentExcluder(documentName);
228 
229         Document doc = new FileDocument(documentName, absBase, documentExcluder);
230         if (!documentExcluder.matches(doc.getName())) {
231             DefaultLog.getInstance().error("Directory '" + documentName + "' is in excluded list.");
232             return null;
233         }
234 
235         if (absBase.isDirectory()) {
236             return new DirectoryWalker(doc);
237         }
238 
239         return new ArchiveWalker(doc);
240     }
241 
242     /**
243      * This class implements the {@code Comparator} interface for comparing Options.
244      */
245     private static final class OptionComparator implements Comparator<Option>, Serializable {
246         /** The serial version UID.  */
247         private static final long serialVersionUID = 5305467873966684014L;
248 
249         private String getKey(final Option opt) {
250             String key = opt.getOpt();
251             key = key == null ? opt.getLongOpt() : key;
252             return key;
253         }
254 
255         /**
256          * Compares its two arguments for order. Returns a negative integer, zero, or a
257          * positive integer as the first argument is less than, equal to, or greater
258          * than the second.
259          *
260          * @param opt1 The first Option to be compared.
261          * @param opt2 The second Option to be compared.
262          * @return a negative integer, zero, or a positive integer as the first argument
263          * is less than, equal to, or greater than the second.
264          */
265         @Override
266         public int compare(final Option opt1, final Option opt2) {
267             return getKey(opt1).compareToIgnoreCase(getKey(opt2));
268         }
269     }
270 
271     public enum ArgumentType {
272         /**
273          * A plain file.
274          */
275         FILE("File", () -> "A file name."),
276         /**
277          * An Integer.
278          */
279         INTEGER("Integer", () -> "An integer value."),
280         /**
281          * A directory or archive.
282          */
283         DIRORARCHIVE("DirOrArchive", () -> "A directory or archive file to scan."),
284         /**
285          * A matching expression.
286          */
287         EXPRESSION("Expression", () -> "A file matching pattern usually of the form used in Ant build files and " +
288                 "'.gitignore' files (see https://ant.apache.org/manual/dirtasks.html#patterns for examples). " +
289                 "Regular expression patterns may be specified by surrounding the pattern with '%regex[' and ']'. " +
290                 "For example '%regex[[A-Z].*]' would match files and directories that start with uppercase latin letters."),
291         /**
292          * A license filter.
293          */
294         LICENSEFILTER("LicenseFilter", () -> format("A defined filter for the licenses to include. Valid values: %s.",
295                 asString(LicenseSetFactory.LicenseFilter.values()))),
296         /**
297          * A log level.
298          */
299         LOGLEVEL("LogLevel", () -> format("The log level to use. Valid values %s.", asString(Level.values()))),
300         /**
301          * A processing type.
302          */
303         PROCESSINGTYPE("ProcessingType", () -> format("Specifies how to process file types. Valid values are: %s%n",
304                 Arrays.stream(ReportConfiguration.Processing.values())
305                         .map(v -> format("\t%s: %s", v.name(), v.desc()))
306                         .collect(Collectors.joining(System.lineSeparator())))),
307         /**
308          * A style sheet.
309          */
310         STYLESHEET("StyleSheet", () -> format("Either an external xsl file or one of the internal named sheets. Internal sheets are: %s",
311                 Arrays.stream(StyleSheets.values())
312                         .map(v -> format("\t%s: %s", v.arg(), v.desc()))
313                         .collect(Collectors.joining(System.lineSeparator())))),
314         /**
315          * A license id.
316          */
317         LICENSEID("LicenseID", () -> "The ID for a license."),
318         /**
319          * A license family id.
320          */
321         FAMILYID("FamilyID", () -> "The ID for a license family."),
322         /**
323          * A standard collection name.
324          */
325         STANDARDCOLLECTION("StandardCollection", () -> format("Defines standard expression patterns (see above). Valid values are: %s%n",
326                 Arrays.stream(StandardCollection.values())
327                         .map(v -> format("\t%s: %s", v.name(), v.desc()))
328                         .collect(Collectors.joining(System.lineSeparator())))),
329         /**
330          * A Counter pattern name
331          */
332         COUNTERPATTERN("CounterPattern", () -> format("A pattern comprising one of the following prefixes followed by " +
333                         "a colon and a count (e.g. %s:5).  Prefixes are %n%s.", ClaimStatistic.Counter.UNAPPROVED,
334                 Arrays.stream(ClaimStatistic.Counter.values())
335                         .map(v -> format("\t%s: %s Default range [%s, %s]", v.name(), v.getDescription(),
336                                 v.getDefaultMinValue(),
337                                 v.getDefaultMaxValue() == -1 ? "unlimited" : v.getDefaultMaxValue()))
338                         .collect(Collectors.joining(System.lineSeparator())))),
339         /**
340          * A generic argument.
341          */
342         ARG("Arg", () -> "A string"),
343         /**
344          * No argument.
345          */
346         NONE("", () -> "");
347 
348         /**
349          * The display name
350          */
351         private final String displayName;
352         /**
353          * A supplier of the description
354          */
355         private final Supplier<String> description;
356 
357         ArgumentType(final String name,
358                      final Supplier<String> description) {
359             this.displayName = name;
360             this.description = description;
361         }
362 
363         public String getDisplayName() {
364             return displayName;
365         }
366 
367         public Supplier<String> description() {
368             return description;
369         }
370     }
371 }