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, StandardCharsets.UTF_8)) {
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("""
113                                     protected %s() {
114                                         setDeprecationReporter();
115                                     }%n""", className));
116                         break;
117                     case "${class}":
118                         writer.append(format("public abstract class %s extends AbstractMojo {%n", className));
119                         break;
120                     case "${commonArgs}":
121                         try (InputStream argsTpl = MavenGenerator.class.getResourceAsStream("/Args.tpl")) {
122                             if (argsTpl == null) {
123                                 throw new RuntimeException("Args.tpl not found");
124                             }
125                             IOUtils.copy(argsTpl, writer, StandardCharsets.UTF_8);
126                         }
127                         break;
128                     default:
129                         writer.append(line).append(System.lineSeparator());
130                         break;
131                 }
132             }
133         }
134     }
135 
136     private static String getComment(final MavenOption option) {
137         String desc = option.getDescription();
138         if (desc == null) {
139             throw new IllegalStateException(format("Description for %s may not be null", option.getName()));
140         }
141         if (!desc.contains(".")) {
142             throw new IllegalStateException(format("First sentence of description for %s must end with a '.'", option.getName()));
143         }
144         String arg;
145         if (option.hasArg()) {
146             arg = desc.substring(desc.indexOf(" ") + 1, desc.indexOf(".") + 1);
147             arg = WordUtils.capitalize(arg.substring(0, 1)) + arg.substring(1);
148         } else {
149             arg = "The state";
150         }
151         if (option.hasArg() && option.getArgName() != null) {
152             Supplier<String> sup = OptionCollection.getArgumentTypes().get(option.getArgName());
153             if (sup == null) {
154                 throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ARGUMENT_TYPES", option.getArgName()));
155             }
156             desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, option.hasArgs() ? "s" : "",
157                     option.hasArgs() ? "" : "a ", option.getArgName());
158         }
159         StringBuilder sb = new StringBuilder()
160             .append(format("    /**%n     * %s%n     * @param %s %s%n", StringEscapeUtils.escapeHtml4(desc),
161                     option.getName(),  StringEscapeUtils.escapeHtml4(arg)));
162         if (option.isDeprecated()) {
163             sb.append(format("     * @deprecated %s%n", StringEscapeUtils.escapeHtml4(option.getDeprecated())));
164         }
165         return sb.append(format("     */%n")).toString();
166     }
167 
168     private static void writeMethods(final FileWriter writer, final List<MavenOption> options) throws IOException {
169         for (MavenOption option : options) {
170             writer.append(getComment(option))
171                     .append(option.getMethodSignature("    ", option.hasArgs())).append(" {").append(System.lineSeparator())
172                     .append(getBody(option))
173                     .append("    }").append(System.lineSeparator());
174             if (option.hasArgs()) {
175                 // create multi argument method
176                 writer.append(getComment(option))
177                         .append(option.getMethodSignature("    ", false)).append(" {").append(System.lineSeparator())
178                         .append(getBody(option))
179                         .append("    }").append(System.lineSeparator());
180             }
181         }
182     }
183 
184     private static String getBody(final MavenOption option) {
185         if (option.hasArg()) {
186             return format("        %sArg(%s, %s);%n", option.hasArgs() ? "add" : "set", option.keyValue(), option.getName());
187         } else {
188             return format("        if (%1$s) {%n            setArg(%2$s, null);%n" +
189                             "        } else {%n            removeArg(%2$s);%n        }%n",
190                     option.getName(), option.keyValue());
191         }
192     }
193 }