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.List;
28  import java.util.Map;
29  import java.util.function.Supplier;
30  
31  import org.apache.commons.cli.Option;
32  import org.apache.commons.io.IOUtils;
33  import org.apache.commons.io.LineIterator;
34  import org.apache.commons.lang3.StringUtils;
35  import org.apache.commons.text.StringEscapeUtils;
36  import org.apache.commons.text.WordUtils;
37  import org.apache.rat.OptionCollection;
38  import org.apache.rat.documentation.options.MavenOption;
39  import org.apache.rat.utils.CasedString;
40  import org.apache.rat.utils.CasedString.StringCase;
41  
42  import static java.lang.String.format;
43  
44  /**
45   * A simple tool to convert CLI options to a Maven Mojo base class.
46   */
47  public final class MavenGenerator {
48  
49      private MavenGenerator() {
50      }
51  
52      private static String argsKey(final Option option) {
53          return StringUtils.defaultIfEmpty(option.getLongOpt(), option.getOpt());
54      }
55  
56      /**
57       * Creates the Maven MojoClass
58       * Requires 3 arguments:
59       * <ol>
60       *     <li>the package name for the class</li>
61       *     <li>the simple class name</li>
62       *     <li>the directory in which to write the class file.</li>
63       * </ol>
64       *
65       * @param args the arguments
66       * @throws IOException on error
67       */
68      public static void main(final String[] args) throws IOException {
69          if (args == null || args.length < 3) {
70              System.err.println("At least three arguments are required: package, simple class name, target directory.");
71              return;
72          }
73  
74          String packageName = args[0];
75          String className = args[1];
76          String destDir = args[2];
77          List<MavenOption> options = MavenOption.getMavenOptions();
78          String pkgName = String.join(File.separator, new CasedString(StringCase.DOT, packageName).getSegments());
79          File file = new File(new File(new File(destDir), pkgName), className + ".java");
80          System.out.println("Creating " + file);
81          file.getParentFile().mkdirs();
82          try (InputStream template = MavenGenerator.class.getResourceAsStream("/Maven.tpl");
83               FileWriter writer = new FileWriter(file)) {
84              if (template == null) {
85                  throw new RuntimeException("Template /Maven.tpl not found");
86              }
87              LineIterator iter = IOUtils.lineIterator(new InputStreamReader(template, StandardCharsets.UTF_8));
88              while (iter.hasNext()) {
89                  String line = iter.next();
90                  switch (line.trim()) {
91                      case "${static}":
92                          for (Map.Entry<String, String> entry : MavenOption.getRenameMap().entrySet()) {
93                              writer.append(format("        xlateName.put(\"%s\", \"%s\");%n", entry.getKey(), entry.getValue()));
94                          }
95                          for (Option option : MavenOption.getFilteredOptions()) {
96                              writer.append(format("        unsupportedArgs.add(\"%s\");%n", argsKey(option)));
97                          }
98                          for (MavenOption option : options) {
99                              if (option.isDeprecated()) {
100                                 writer.append(format("        deprecatedArgs.put(\"%s\", \"%s\");%n", argsKey(option.getOption()),
101                                         format("Use of deprecated option '%s'. %s", option.getName(), option.getDeprecated())));
102                             }
103                         }
104                         break;
105                     case "${methods}":
106                         writeMethods(writer, options);
107                         break;
108                     case "${package}":
109                         writer.append(format("package %s;%n", packageName));
110                         break;
111                     case "${constructor}":
112                         writer.append(format("    protected %s() {\n" +
113                                 "        setDeprecationReporter();\n" +
114                                 "    }%n", className));
115                         break;
116                     case "${class}":
117                         writer.append(format("public abstract class %s extends AbstractMojo {%n", className));
118                         break;
119                     case "${commonArgs}":
120                         try (InputStream argsTpl = MavenGenerator.class.getResourceAsStream("/Args.tpl")) {
121                             if (argsTpl == null) {
122                                 throw new RuntimeException("Args.tpl not found");
123                             }
124                             IOUtils.copy(argsTpl, writer, StandardCharsets.UTF_8);
125                         }
126                         break;
127                     default:
128                         writer.append(line).append(System.lineSeparator());
129                         break;
130                 }
131             }
132         }
133     }
134 
135     private static String getComment(final MavenOption option) {
136         String desc = option.getDescription();
137         if (desc == null) {
138             throw new IllegalStateException(format("Description for %s may not be null", option.getName()));
139         }
140         if (!desc.contains(".")) {
141             throw new IllegalStateException(format("First sentence of description for %s must end with a '.'", option.getName()));
142         }
143         String arg;
144         if (option.hasArg()) {
145             arg = desc.substring(desc.indexOf(" ") + 1, desc.indexOf(".") + 1);
146             arg = WordUtils.capitalize(arg.substring(0, 1)) + arg.substring(1);
147         } else {
148             arg = "The state";
149         }
150         if (option.hasArg() && option.getArgName() != null) {
151             Supplier<String> sup = OptionCollection.getArgumentTypes().get(option.getArgName());
152             if (sup == null) {
153                 throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ARGUMENT_TYPES", option.getArgName()));
154             }
155             desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, option.hasArgs() ? "s" : "",
156                     option.hasArgs() ? "" : "a ", option.getArgName());
157         }
158         StringBuilder sb = new StringBuilder()
159             .append(format("    /**%n     * %s%n     * @param %s %s%n", StringEscapeUtils.escapeHtml4(desc),
160                     option.getName(),  StringEscapeUtils.escapeHtml4(arg)));
161         if (option.isDeprecated()) {
162             sb.append(format("     * @deprecated %s%n", StringEscapeUtils.escapeHtml4(option.getDeprecated())));
163         }
164         return sb.append(format("     */%n")).toString();
165     }
166 
167     private static void writeMethods(final FileWriter writer, final List<MavenOption> options) throws IOException {
168         for (MavenOption option : options) {
169             writer.append(getComment(option))
170                     .append(option.getMethodSignature("    ", option.hasArgs())).append(" {").append(System.lineSeparator())
171                     .append(getBody(option))
172                     .append("    }").append(System.lineSeparator());
173             if (option.hasArgs()) {
174                 // create multi argument method
175                 writer.append(getComment(option))
176                         .append(option.getMethodSignature("    ", false)).append(" {").append(System.lineSeparator())
177                         .append(getBody(option))
178                         .append("    }").append(System.lineSeparator());
179             }
180         }
181     }
182 
183     private static String getBody(final MavenOption option) {
184         if (option.hasArg()) {
185             return format("        %sArg(%s, %s);%n", option.hasArgs() ? "add" : "set", option.keyValue(), option.getName());
186         } else {
187             return format("        if (%1$s) {%n            setArg(%2$s, null);%n" +
188                             "        } else {%n            removeArg(%2$s);%n        }%n",
189                     option.getName(), option.keyValue());
190         }
191     }
192 }