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.CharArrayWriter;
22  import java.io.FileWriter;
23  import java.io.IOException;
24  import java.io.OutputStreamWriter;
25  import java.io.PrintWriter;
26  import java.io.Writer;
27  import java.nio.charset.StandardCharsets;
28  import java.util.ArrayList;
29  import java.util.Arrays;
30  import java.util.Deque;
31  import java.util.LinkedList;
32  import java.util.List;
33  import java.util.function.Function;
34  import java.util.function.Predicate;
35  
36  import org.apache.commons.cli.CommandLine;
37  import org.apache.commons.cli.DefaultParser;
38  import org.apache.commons.cli.HelpFormatter;
39  import org.apache.commons.cli.Option;
40  import org.apache.commons.cli.Options;
41  import org.apache.commons.cli.ParseException;
42  import org.apache.commons.csv.CSVFormat;
43  import org.apache.commons.csv.CSVPrinter;
44  import org.apache.commons.csv.QuoteMode;
45  import org.apache.commons.lang3.StringUtils;
46  import org.apache.rat.OptionCollection;
47  import org.apache.rat.help.AbstractHelp;
48  
49  /**
50   * A simple tool to convert CLI options to Maven and Ant format and produce a CSV file.
51   * <br>
52   * Options
53   * <ul>
54   *     <li>--ant   Produces Ant options in result</li>
55   *     <li>--maven Produces Maven options in result</li>
56   *     <li>--csv   Produces CSV output text</li>
57   * </ul>
58   * Note: if neither --ant nor --maven are included both will be listed.
59   */
60  public final class Naming {
61  
62      private Naming() { }
63      /** The maximum width of the output. */
64      private static final Option WIDTH = Option.builder().longOpt("width").type(Integer.class)
65              .desc("Set the display width of the output").hasArg().build();
66      /** Option to output Maven names. */
67      private static final Option MAVEN = Option.builder().longOpt("maven").desc("Produce Maven name mapping").build();
68      /** Option to output Ant names. */
69      private static final Option ANT = Option.builder().longOpt("ant").desc("Produce Ant name mapping").build();
70      /** Option to output CSV format. */
71      private static final Option CSV = Option.builder().longOpt("csv").desc("Produce CSV format").build();
72      /** Options to output cli names. */
73      private static final Option CLI = Option.builder().longOpt("cli").desc("Produce CLI name mapping").build();
74      /** Option for including deprecated options. */
75      private static final Option INCLUDE_DEPRECATED = Option.builder().longOpt("include-deprecated")
76              .desc("Include deprecated options.").build();
77      /** The all option. */
78      private static final Options OPTIONS = new Options().addOption(MAVEN).addOption(ANT).addOption(CLI)
79              .addOption(CSV)
80              .addOption(INCLUDE_DEPRECATED)
81              .addOption(WIDTH);
82  
83      /**
84       * Creates the CSV file.
85       * Requires 1 argument:
86       * <ol>
87       *    <li>the name of the output file with path if desired</li>
88       * </ol>
89       * @throws IOException on error
90       * @param args arguments, only 1 is required.
91       */
92      public static void main(final String[] args) throws IOException, ParseException {
93          if (args == null || args.length < 1) {
94              System.err.println("At least one argument is required: path to file is missing.");
95              return;
96          }
97          CommandLine cl = DefaultParser.builder().build().parse(OPTIONS, args);
98          int width = Math.max(cl.getParsedOptionValue(WIDTH, AbstractHelp.HELP_WIDTH), AbstractHelp.HELP_WIDTH);
99  
100         boolean showMaven = cl.hasOption(MAVEN);
101 
102         boolean showAnt = cl.hasOption(ANT);
103         boolean includeDeprecated = cl.hasOption(INCLUDE_DEPRECATED);
104         Predicate<Option> filter = o -> o.hasLongOpt() && (!o.isDeprecated() || includeDeprecated);
105 
106         List<String> columns = new ArrayList<>();
107 
108         if (cl.hasOption(CLI)) {
109             columns.add("CLI");
110         }
111 
112         if (showAnt) {
113             columns.add("Ant");
114         }
115 
116         if (showMaven) {
117             columns.add("Maven");
118         }
119         columns.add("Description");
120         columns.add("Argument Type");
121 
122         Function<Option, String> descriptionFunction;
123 
124         if (cl.hasOption(CLI) || !showAnt && !showMaven) {
125             descriptionFunction = o -> {
126                 StringBuilder desc = new StringBuilder();
127             if (o.isDeprecated()) {
128                 desc.append("[").append(o.getDeprecated().toString()).append("] ");
129             }
130             return desc.append(StringUtils.defaultIfEmpty(o.getDescription(), "")).toString();
131             };
132         } else if (showAnt) {
133             descriptionFunction = o -> {
134                 StringBuilder desc = new StringBuilder();
135                 AntOption antOption = new AntOption(o);
136                 if (antOption.isDeprecated()) {
137                     desc.append("[").append(antOption.getDeprecated()).append("] ");
138                 }
139                 return desc.append(StringUtils.defaultIfEmpty(antOption.getDescription(), "")).toString();
140             };
141         } else {
142             descriptionFunction = o -> {
143                 StringBuilder desc = new StringBuilder();
144                 MavenOption mavenOption = new MavenOption(o);
145                 if (mavenOption.isDeprecated()) {
146                     desc.append("[").append(mavenOption.getDeprecated()).append("] ");
147                 }
148                 return desc.append(StringUtils.defaultIfEmpty(mavenOption.getDescription(), "")).toString();
149             };
150         }
151 
152         try (Writer underWriter = cl.getArgs().length != 0 ? new FileWriter(cl.getArgs()[0]) : new OutputStreamWriter(System.out, StandardCharsets.UTF_8)) {
153             if (cl.hasOption(CSV)) {
154                 printCSV(columns, filter, cl.hasOption(CLI), showMaven, showAnt, descriptionFunction, underWriter);
155             }
156             else {
157                 printText(columns, filter, cl.hasOption(CLI), showMaven, showAnt, descriptionFunction, underWriter, width);
158             }
159         }
160     }
161 
162     private static List<String> fillColumns(final List<String> columns, final Option option, final boolean addCLI, final boolean showMaven,
163                                             final boolean showAnt, final Function<Option, String> descriptionFunction) {
164         if (addCLI) {
165             if (option.hasLongOpt()) {
166                 columns.add("--" + option.getLongOpt());
167             } else {
168                 columns.add("-" + option.getOpt());
169             }
170         }
171         if (showAnt) {
172             columns.add(new AntOption(option).getExample());
173         }
174         if (showMaven) {
175             columns.add(new MavenOption(option).getExample());
176         }
177 
178         columns.add(descriptionFunction.apply(option));
179         columns.add(option.hasArgName() ? option.getArgName() : option.hasArgs() ? "Strings" : option.hasArg() ? "String" : "-- none --");
180         columns.add(option.hasArgName() ? option.getArgName() : option.hasArgs() ? "Strings" : option.hasArg() ? "String" : "-- none --");
181         columns.add(option.hasArgName() ? option.getArgName() : option.hasArgs() ? "Strings" : option.hasArg() ? "String" : "-- none --");
182         return columns;
183     }
184 
185     private static void printCSV(final List<String> columns, final Predicate<Option> filter, final boolean addCLI, final boolean showMaven,
186                                  final boolean showAnt, final Function<Option, String> descriptionFunction,
187                                  final Writer underWriter) throws IOException {
188         try (CSVPrinter printer = new CSVPrinter(underWriter, CSVFormat.DEFAULT.builder().setQuoteMode(QuoteMode.ALL).get())) {
189             printer.printRecord(columns);
190             for (Option option : OptionCollection.buildOptions().getOptions()) {
191                 if (filter.test(option)) {
192                     columns.clear();
193                     printer.printRecord(fillColumns(columns, option, addCLI, showMaven, showAnt, descriptionFunction));
194                 }
195             }
196         }
197     }
198 
199     private static int[] calculateColumnWidth(final int width, final int columnCount, final List<List<String>> page) {
200         int[] columnWidth = new int[columnCount];
201         for (List<String> row : page) {
202             for (int i = 0; i < columnCount; i++) {
203                 columnWidth[i] = Math.max(columnWidth[i], row.get(i).length());
204             }
205         }
206         int extra = 0;
207         int averageWidth = (width - ((columnCount - 1) * 2)) / columnCount;
208         int[] overage = new int[columnCount];
209         int totalOverage = 0;
210         for (int i = 0; i < columnCount; i++) {
211             if (columnWidth[i] < averageWidth) {
212                 extra += averageWidth - columnWidth[i];
213             } else if (columnWidth[i] > averageWidth) {
214                 overage[i] = columnWidth[i] - averageWidth;
215                 totalOverage += overage[i];
216             }
217         }
218 
219         for (int i = 0; i < columnCount; i++) {
220             if (overage[i] > 0) {
221                 int addl = (int) (extra * overage[i] * 1.0 / totalOverage);
222                 columnWidth[i] = averageWidth + addl;
223             }
224         }
225         return columnWidth;
226     }
227 
228     private static void printText(final List<String> columns, final Predicate<Option> filter, final boolean addCLI,
229                                   final boolean showMaven, final boolean showAnt,
230                                   final Function<Option, String> descriptionFunction, final Writer underWriter, final int width) throws IOException {
231         List<List<String>> page = new ArrayList<>();
232 
233         int columnCount = columns.size();
234         page.add(columns);
235 
236         for (Option option : OptionCollection.buildOptions().getOptions()) {
237             if (filter.test(option)) {
238                 page.add(fillColumns(new ArrayList<>(), option, addCLI, showMaven, showAnt, descriptionFunction));
239             }
240         }
241         int[] columnWidth = calculateColumnWidth(width, columnCount, page);
242         HelpFormatter helpFormatter;
243         helpFormatter = new HelpFormatter.Builder().get();
244         helpFormatter.setWidth(width);
245 
246 
247         List<Deque<String>> entries = new ArrayList<>();
248         CharArrayWriter cWriter = new CharArrayWriter();
249 
250         // process one line at a time
251         for (List<String> cols : page) {
252             entries.clear();
253             PrintWriter writer = new PrintWriter(cWriter);
254             // print each column into a block of strings.
255             for (int i = 0; i < columnCount; i++) {
256                 String col = cols.get(i);
257                 // split on end of line within a column
258                 for (String line : col.split("\\v")) {
259                     helpFormatter.printWrapped(writer, columnWidth[i], 2, line);
260                 }
261                 writer.flush();
262                 // please the block of strings into a queue.
263                 Deque<String> entryLines = new LinkedList<>(Arrays.asList(cWriter.toString().split("\\v")));
264                 // put the queue into the entries for this line.
265                 entries.add(entryLines);
266                 cWriter.reset();
267             }
268             // print the entries by printing the items from the queues until all queues are empty.
269             boolean cont = true;
270             while (cont) {
271                 cont = false;
272                 for (int columnNumber = 0; columnNumber < entries.size(); columnNumber++) {
273                     Deque<String> queue = entries.get(columnNumber);
274                     if (queue.isEmpty()) {
275                         underWriter.append(AbstractHelp.createPadding(columnWidth[columnNumber] + 2));
276                     } else {
277                         String ln = queue.pop();
278                         underWriter.append(ln);
279                         underWriter.append(AbstractHelp.createPadding(columnWidth[columnNumber] - ln.length() + 2));
280                         if (!queue.isEmpty()) {
281                             cont = true;
282                         }
283                     }
284                 }
285                 underWriter.append(System.lineSeparator());
286             }
287             underWriter.append(System.lineSeparator());
288         }
289     }
290 }