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   *   https://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.documentation.options;
20  
21  import java.io.File;
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Objects;
27  import java.util.Optional;
28  import java.util.Set;
29  import java.util.TreeMap;
30  import java.util.stream.Collectors;
31  
32  import org.apache.commons.cli.Option;
33  import org.apache.commons.lang3.StringUtils;
34  import org.apache.commons.text.WordUtils;
35  import org.apache.rat.OptionCollection;
36  import org.apache.rat.commandline.Arg;
37  import org.apache.rat.document.DocumentName;
38  import org.apache.rat.ui.UIOptionCollection;
39  
40  import static java.lang.String.format;
41  
42  /**
43   * The collection of AntOptions.
44   */
45  public final class AntOptionCollection extends UIOptionCollection<AntOption> {
46      /** mapping of standard name to non-conflicting name. */
47      static final Map<String, String> RENAME_MAP;
48      /**
49       * The format for an XML element.
50       */
51      private static final String DEFAULT_XML = "<%1$s>%%s</%1$s>%n";
52      /** Attributes that are required for example data. */
53      private static final Map<String, Map<String, String>> REQUIRED_ATTRIBUTES = new HashMap<>();
54      /** The list of data types that are specified as XML attributes in Ant build.xml documents. */
55      private static final List<Class<?>> ATTRIBUTE_TYPES = new ArrayList<>();
56      /** The map of option name conversions. */
57      private final Map<Option, Option> conversionMap;
58  
59      static {
60          RENAME_MAP = new HashMap<>();
61          RENAME_MAP.put("addLicense", "add-license");
62  
63          Map<String, String> attributes = new HashMap<>();
64          attributes.put("editLicense", "true");
65          REQUIRED_ATTRIBUTES.put("copyright", attributes);
66          REQUIRED_ATTRIBUTES.put("editCopyright", attributes);
67          REQUIRED_ATTRIBUTES.put("force", attributes);
68          REQUIRED_ATTRIBUTES.put("editOverwrite", attributes);
69  
70          // Types that are specified as XML attributes in Ant.
71          ATTRIBUTE_TYPES.add(String.class);
72          ATTRIBUTE_TYPES.add(String[].class);
73          ATTRIBUTE_TYPES.add(Integer.class);
74          ATTRIBUTE_TYPES.add(Long.class);
75          ATTRIBUTE_TYPES.add(File.class);
76          ATTRIBUTE_TYPES.add(DocumentName.class);
77      }
78  
79      /**
80       * Gets the map of standard Option names that are renamed to fit the Ant naming process.
81       * @return the map of renamed Options.
82       */
83      public static Map<String, String> getRenameMap() {
84          return new TreeMap<>(RENAME_MAP);
85      }
86  
87      /**
88       * Creates an instance of the AntOption Collection.
89       */
90      public AntOptionCollection() {
91          this(new Builder());
92      }
93  
94      /**
95       * Create an instance.
96       */
97      private AntOptionCollection(final Builder builder) {
98          super(new Builder());
99          conversionMap = builder.conversions;
100     }
101 
102     @Override
103     public String rename(final Option option) {
104         String key = super.rename(option);
105         return StringUtils.defaultIfEmpty(RENAME_MAP.get(key), key);
106     }
107 
108     /**
109      * Returns the set of AntOptions that the argument was converted from.
110      * @param antOption the AntOption to check.
111      * @return returns a Set of AntOptions that were converted to the argument. May be an empty set.
112      */
113     public Set<AntOption> convertedFrom(final AntOption antOption) {
114         return conversionMap.entrySet().stream().filter(e -> e.getValue().equals(antOption.getOption()))
115                 .map(e -> getMappedOption(e.getKey()))
116                 .filter(Optional::isPresent)
117                 .map(Optional::get)
118                 .collect(Collectors.toSet());
119     }
120 
121     /**
122      * If this option is converted to another option return that option otherwise
123      * return this option.
124      * @return the converted option.
125      */
126     public AntOption getActualAntOption(final AntOption antOption) {
127         Option opt = conversionMap.get(antOption.getOption());
128         return opt == null ? antOption : getMappedOption(opt).orElse(antOption);
129     }
130 
131     /**
132      * Returns {@code true} if this argument is an attribute to the Ant RAT call.
133      * @param antOption the AntOption to check.
134      * @return {@code true} if this argument is an attribute to the Ant RAT call.
135      */
136     public boolean isAttribute(final AntOption antOption) {
137         Option opt = antOption.getOption();
138         return (!opt.hasArg() || opt.getArgs() == 1) && convertedFrom(antOption).isEmpty() &&
139                 ATTRIBUTE_TYPES.contains(opt.getType());
140     }
141 
142     /**
143      * Gets a map of attributes that are required for the example data.
144      * @param name the attribute name to lookup.
145      * @return the map of attributes that are required for the example data.
146      */
147     public Map<String, String> getRequiredAttributes(final String name) {
148         return REQUIRED_ATTRIBUTES.get(name);
149     }
150 
151     /**
152      * Gets the Ant build type for the ArgumentType
153      * @param type ArgumentType to get the Ant build type for.
154      * @return the Ant build type for the ArgumentType
155      */
156     BuildType buildType(final OptionCollection.ArgumentType type) {
157         return switch (type) {
158             case FILE, DIRORARCHIVE -> new BuildType("filename") {
159                 @Override
160                 protected String getMethodFormat(final AntOption antOption) {
161                     return "  <fileset file='%s' />\n";
162                 }
163             };
164             case NONE -> new BuildType("");
165             case COUNTERPATTERN -> new BuildType("cntr");
166             case EXPRESSION -> new BuildType("expr");
167             case STANDARDCOLLECTION -> new BuildType("std");
168             case LICENSEID, FAMILYID -> new BuildType("lst");
169             default -> new BuildType(type.getDisplayName()) {
170                 @Override
171                 protected String getMethodFormat(final AntOption antOption) {
172                     return String.format(DEFAULT_XML, WordUtils.uncapitalize(antOption.getArgName()));
173                 }
174             };
175         };
176     }
177 
178     /**
179      * The Builder for the AntOptionCollection.
180      */
181     public static final class Builder extends UIOptionCollection.Builder<AntOption, Builder> {
182         /** Convert key to value type when generating code */
183         private final Map<Option, Option> conversions = new HashMap<>();
184 
185         private Builder() {
186             super(AntOption.AntOptionBuilder::new);
187             Arg.getOptions().getOptions()
188                     .stream().filter(o -> Objects.isNull(o.getLongOpt()))
189                     .forEach(this::unsupported);
190             unsupported(Arg.LOG_LEVEL)
191                     .unsupported(Arg.DIR)
192                     .unsupported(Arg.SOURCE)
193                     .unsupported(Arg.HELP_LICENSES)
194                     // conversions
195                     .convert(Arg.LICENSES_APPROVED_FILE, Arg.LICENSES_APPROVED)
196                     .convert(Arg.LICENSES_DENIED_FILE, Arg.LICENSES_DENIED)
197                     .convert(Arg.FAMILIES_APPROVED_FILE, Arg.FAMILIES_APPROVED)
198                     .convert(Arg.FAMILIES_DENIED_FILE, Arg.FAMILIES_DENIED)
199                     .convert(Arg.INCLUDE_FILE, Arg.INCLUDE)
200                     .convert(Arg.INCLUDE_STD, Arg.INCLUDE)
201                     .convert(Arg.EXCLUDE_FILE, Arg.EXCLUDE)
202                     .convert(Arg.EXCLUDE_STD, Arg.EXCLUDE);
203         }
204 
205         /**
206          * Converts one Arg type to another.
207          * @param from the Arg to convert from.
208          * @param to the Arg to convert to.
209          * @return this
210          */
211         public Builder convert(final Arg from, final Arg to) {
212             Option mapTo = to.option();
213             for (Option option : from.group().getOptions()) {
214                 if (!option.equals(mapTo) && !option.isDeprecated()) {
215                     conversions.put(option, mapTo);
216                 }
217             }
218             return self();
219         }
220     }
221 
222     /**
223      * A mapping of data type of XML format.
224      */
225     public static class BuildType {
226         /**
227          * The configuration tag for this build type.
228          */
229         private final String tag;
230         /**
231          * If {@code true} adds the tag as the test extension.
232          */
233         private final boolean addExt;
234 
235         /**
236          * The constructor for the build type.
237          *
238          * @param tag the XML tag for this data type.
239          */
240         BuildType(final String tag) {
241             this.tag = tag;
242             this.addExt = StringUtils.isNotEmpty(tag);
243         }
244 
245         /**
246          * Gets the method based on how many arguments an Ant option requires.
247          *
248          * @param antOption the Ant option to check.
249          * @return the method format for the option.
250          */
251         protected String getMethodFormat(final AntOption antOption) {
252             return String.format(DEFAULT_XML, tag);
253         }
254 
255         /**
256          * Gets a string comprising the Ant XML pattern for this data type and the number of arguments expected by the Ant option.
257          *
258          * @param delegateOption the Ant option that the call is delegated to.
259          * @param antOption      the actual Ant option.
260          * @param data           the data for the actual Ant option.
261          * @return the Ant XML pattern for this data type.
262          */
263         public String getXml(final AntOption delegateOption, final AntOption antOption, final String data) {
264             String fmt = getMethodFormat(antOption);
265             String value = data == null ? WordUtils.uncapitalize(antOption.getArgName()) : data;
266             String inner = format(fmt, value);
267             return format("<%1$s>%2$s</%1$s>%n", delegateOption.getName(), inner);
268         }
269 
270         /**
271          * Gets a string comprising the Ant XML pattern for the specified AntOption.
272          * @param antOption the ant option to get XML example for
273          * @param data the data for the option.
274          * @return an ANT XML formatted option.
275          */
276         public String getXml(final AntOption antOption, final String data) {
277             AntOption delegateOption = antOption.getActualAntOption();
278             if (delegateOption.isAttribute()) {
279                 return "";
280             } else {
281                 return format(getMethodFormat(antOption), data);
282             }
283         }
284 
285         /**
286          * Gets a test name for the AntOption.
287          * @param antOption the Ant Option being tested
288          * @return the test name for this type.
289          */
290         public String testName(final AntOption antOption) {
291             return addExt ? format("%s_%s", antOption.getName(), antOption.getArgName()) : antOption.getName();
292         }
293     }
294 }