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.tools;
20  
21  import java.io.File;
22  import java.io.FileWriter;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.io.InputStreamReader;
26  import java.nio.charset.StandardCharsets;
27  import java.util.ArrayList;
28  import java.util.HashMap;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.function.Predicate;
33  import java.util.function.Supplier;
34  import java.util.stream.Collectors;
35  
36  import org.apache.commons.cli.Option;
37  import org.apache.commons.io.IOUtils;
38  import org.apache.commons.io.LineIterator;
39  import org.apache.commons.lang3.StringUtils;
40  import org.apache.commons.text.StringEscapeUtils;
41  import org.apache.commons.text.WordUtils;
42  import org.apache.rat.OptionCollection;
43  import org.apache.rat.commandline.Arg;
44  import org.apache.rat.utils.CasedString;
45  import org.apache.rat.utils.CasedString.StringCase;
46  
47  import static java.lang.String.format;
48  
49  /**
50   * A simple tool to convert CLI options to Maven Mojo base class
51   */
52  public final class MavenGenerator {
53  
54      /** A mapping of external name to internal name if not standard */
55      private static final Map<String, String> RENAME_MAP = new HashMap<>();
56  
57      /** List of CLI Options that are not supported by Maven. */
58      private static final List<Option> MAVEN_FILTER_LIST = new ArrayList<>();
59  
60      static {
61          RENAME_MAP.put("addLicense", "add-license");
62  
63          MAVEN_FILTER_LIST.addAll(Arg.DIR.group().getOptions());
64          MAVEN_FILTER_LIST.addAll(Arg.LOG_LEVEL.group().getOptions());
65          MAVEN_FILTER_LIST.add(OptionCollection.HELP);
66      }
67  
68      /**
69       * Filter to remove Options not supported by Maven.
70       */
71      private static final Predicate<Option> MAVEN_FILTER = option -> !(MAVEN_FILTER_LIST.contains(option) || option.getLongOpt() == null);
72  
73      /**
74       * Returns the Option predicate that removes all unsupported Options for the Maven UI.
75       * @return the Option predicate that removes all unsupported Options for the Maven UI.
76       */
77      public static Predicate<Option> getFilter() {
78          return MAVEN_FILTER;
79      }
80  
81      private MavenGenerator() {
82      }
83  
84      /**
85       * Creates the Maven MojoClass
86       * Requires 3 arguments:
87       * <ol>
88       *     <li>the package name for the class</li>
89       *     <li>the simple class name</li>
90       *     <li>the directory in which to write the class file.</li>
91       * </ol>
92       *
93       * @param args the arguments
94       * @throws IOException on error
95       */
96      public static void main(final String[] args) throws IOException {
97          if (args == null || args.length < 3) {
98              System.err.println("At least three arguments are required: package, simple class name, target directory.");
99              return;
100         }
101 
102         String packageName = args[0];
103         String className = args[1];
104         String destDir = args[2];
105         List<MavenOption> options = OptionCollection.buildOptions().getOptions().stream().filter(MAVEN_FILTER)
106                 .map(MavenOption::new).collect(Collectors.toList());
107         String pkgName = String.join(File.separator, new CasedString(StringCase.DOT, packageName).getSegments());
108         File file = new File(new File(new File(destDir), pkgName), className + ".java");
109         System.out.println("Creating " + file);
110         file.getParentFile().mkdirs();
111         try (InputStream template = MavenGenerator.class.getResourceAsStream("/Maven.tpl");
112              FileWriter writer = new FileWriter(file)) {
113             if (template == null) {
114                 throw new RuntimeException("Template /Maven.tpl not found");
115             }
116             LineIterator iter = IOUtils.lineIterator(new InputStreamReader(template, StandardCharsets.UTF_8));
117             while (iter.hasNext()) {
118                 String line = iter.next();
119                 switch (line.trim()) {
120                     case "${static}":
121                         for (Map.Entry<String, String> entry : RENAME_MAP.entrySet()) {
122                             writer.append(format("        xlateName.put(\"%s\", \"%s\");%n", entry.getKey(), entry.getValue()));
123                         }
124                         for (Option option : MAVEN_FILTER_LIST) {
125                             writer.append(format("        unsupportedArgs.add(\"%s\");%n", StringUtils.defaultIfEmpty(option.getLongOpt(), option.getOpt())));
126                         }
127                         break;
128                     case "${methods}":
129                         writeMethods(writer, options);
130                         break;
131                     case "${package}":
132                         writer.append(format("package %s;%n", packageName));
133                         break;
134                     case "${constructor}":
135                         writer.append(format("    protected %s() {}%n", className));
136                         break;
137                     case "${class}":
138                         writer.append(format("public abstract class %s extends AbstractMojo {%n", className));
139                         break;
140                     case "${commonArgs}":
141                         try (InputStream argsTpl = MavenGenerator.class.getResourceAsStream("/Args.tpl")) {
142                             if (argsTpl == null) {
143                                 throw new RuntimeException("Args.tpl not found");
144                             }
145                             IOUtils.copy(argsTpl, writer, StandardCharsets.UTF_8);
146                         }
147                         break;
148                     default:
149                         writer.append(line).append(System.lineSeparator());
150                         break;
151                 }
152             }
153         }
154     }
155 
156     private static String getComment(final MavenOption option) {
157         String desc = option.getDescription();
158         if (desc == null) {
159             throw new IllegalStateException(format("Description for %s may not be null", option.getName()));
160         }
161         if (!desc.contains(".")) {
162             throw new IllegalStateException(format("First sentence of description for %s must end with a '.'", option.getName()));
163         }
164         String arg;
165         if (option.hasArg()) {
166             arg = desc.substring(desc.indexOf(" "), desc.indexOf(".") + 1);
167             arg = WordUtils.capitalize(arg.substring(0, 1)) + arg.substring(1);
168         } else {
169             arg = "the state";
170         }
171         if (option.hasArg() && option.getArgName() != null) {
172             Supplier<String> sup = OptionCollection.getArgumentTypes().get(option.getArgName());
173             if (sup == null) {
174                 throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ARGUMENT_TYPES", option.getArgName()));
175             }
176             desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, option.hasArgs() ? "s" : "",
177                     option.hasArgs() ? "" : "a ", option.getArgName());
178         }
179         StringBuilder sb = new StringBuilder()
180             .append(format("    /**%n     * %s%n     * @param %s %s%n", StringEscapeUtils.escapeHtml4(desc),
181                     option.getName(),  StringEscapeUtils.escapeHtml4(arg)));
182         if (option.isDeprecated()) {
183             sb.append(format("     * @deprecated %s%n", StringEscapeUtils.escapeHtml4(option.getDeprecated())));
184         }
185         return sb.append(format("     */%n")).toString();
186     }
187 
188     private static void writeMethods(final FileWriter writer, final List<MavenOption> options) throws IOException {
189         for (MavenOption option : options) {
190             writer.append(getComment(option))
191                     .append(option.getMethodSignature("    ", option.hasArgs())).append(" {").append(System.lineSeparator())
192                     .append(getBody(option))
193                     .append("    }").append(System.lineSeparator());
194             if (option.hasArgs()) {
195                 // create multi argument method
196                 writer.append(getComment(option))
197                         .append(option.getMethodSignature("    ", false)).append(" {").append(System.lineSeparator())
198                         .append(getBody(option))
199                         .append("    }").append(System.lineSeparator());
200             }
201         }
202     }
203 
204     private static String getBody(final MavenOption option) {
205         if (option.hasArg()) {
206             return format("        %sArg(%s, %s);%n", option.hasArgs() ? "add" : "set", option.keyValue(), option.getName());
207         } else {
208             return format("        if (%1$s) {%n            setArg(%2$s, null);%n" +
209                             "        } else {%n            removeArg(%2$s);%n        }%n",
210                     option.getName(), option.keyValue());
211         }
212     }
213 
214     /**
215      * Creates the Maven element name for the specified option.
216      * @param option The option to process.
217      * @return the Maven based name in camel-case syntax.
218      */
219     static String createName(final Option option) {
220         String name = StringUtils.defaultIfEmpty(option.getLongOpt(), option.getOpt());
221         name = StringUtils.defaultIfEmpty(RENAME_MAP.get(name), name).toLowerCase(Locale.ROOT);
222         return new CasedString(StringCase.KEBAB, name).toCase(StringCase.CAMEL);
223     }
224 }