This is an automated email from the ASF dual-hosted git repository. claude pushed a commit to branch feature/restructure in repository https://gitbox.apache.org/repos/asf/creadur-rat.git
commit 196f1d6883caf615042a0a7f5e39b4c863de0c6b Author: Claude Warren <[email protected]> AuthorDate: Thu Dec 25 09:23:11 2025 +0000 partial maven fix --- .../main/java/org/apache/rat/OptionCollection.java | 2 +- .../java/org/apache/rat/ui/AbstractOption.java | 2 +- .../main/java/org/apache/rat/ui/OptionFactory.java | 4 +- .../src/main/java/org/apache/rat/ui/SetArgs.java | 143 +++------ .../java/org/apache/rat/utils/CasedString.java | 10 + .../fileProcessors/GitIgnoreBuilderTest.java | 1 + .../resources/GitIgnoreBuilderTest/src/.gitignore | 10 + .../GitIgnoreBuilderTest/src/dir1/.gitignore | 3 + .../GitIgnoreBuilderTest/src/dir1/dir1.txt | 1 + .../GitIgnoreBuilderTest/src/dir1/file1.log | 1 + .../GitIgnoreBuilderTest/src/dir2/dir2.md | 1 + .../GitIgnoreBuilderTest/src/dir3/dir3.log | 1 + apache-rat-plugin-parent/impl/pom.xml | 31 +- .../java/org/apache/rat/mp/AbstractRatMojo.java | 323 ++------------------- .../main/java/org/apache/rat/mp/RatCheckMojo.java | 185 ++++-------- .../main/java/org/apache/rat/mp/RatReportMojo.java | 63 ++-- .../java/org/apache/rat/plugin/package-info.java | 24 -- apache-rat-plugin-parent/pom.xml | 13 +- apache-rat-plugin-parent/tools/pom.xml | 7 +- apache-rat-plugin-parent/tools/spotbugs-ignore.xml | 20 ++ .../java/org/apache/rat/maven/CodeGenerator.java | 224 ++++++++++++++ .../java/org/apache/rat/maven/MavenGenerator.java | 6 +- .../java/org/apache/rat/maven/MavenOption.java | 51 ++-- .../java/org/apache/rat/maven/TestGenerator.java | 84 +++--- .../org/apache/rat/maven/AbstractMaven.vm | 59 ++++ .../org/apache/rat/maven/AbstractMavenFunc.vm | 44 +++ .../resources/org/apache/rat/maven/TestFunc.vm | 10 - .../resources/org/apache/rat/maven/TestMethod.vm | 28 ++ .../test/java/org/apache/rat/maven/MavenTest.java | 63 ---- pom.xml | 1 - 30 files changed, 664 insertions(+), 751 deletions(-) diff --git a/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java b/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java index 88ecbeed..0ec7283e 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java +++ b/apache-rat-core/src/main/java/org/apache/rat/OptionCollection.java @@ -264,7 +264,7 @@ public final class OptionCollection { /** * A style sheet. */ - STYLESHEET("StyleSheet", () -> format("Either an external xsl file or one of the internal named sheets. Internal sheets are: %n%s", + STYLESHEET("StyleSheet", () -> format("Either an external XSLT file or one of the internal named sheets. Internal sheets are: %n%s", Arrays.stream(StyleSheets.values()) .map(v -> format("\t%s: %s%n", v.arg(), v.desc())) .collect(Collectors.joining(System.lineSeparator())))), diff --git a/apache-rat-core/src/main/java/org/apache/rat/ui/AbstractOption.java b/apache-rat-core/src/main/java/org/apache/rat/ui/AbstractOption.java index 0827d1cd..f714f866 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/ui/AbstractOption.java +++ b/apache-rat-core/src/main/java/org/apache/rat/ui/AbstractOption.java @@ -248,7 +248,7 @@ public abstract class AbstractOption<T extends AbstractOption<T>> { * @return the key value for the CLI argument map. */ public final String keyValue() { - return format("\"%s\"", StringUtils.defaultIfEmpty(option.getLongOpt(), option.getOpt())); + return StringUtils.defaultIfEmpty(option.getLongOpt(), option.getOpt()); } /** diff --git a/apache-rat-core/src/main/java/org/apache/rat/ui/OptionFactory.java b/apache-rat-core/src/main/java/org/apache/rat/ui/OptionFactory.java index bd8c8575..cc77680a 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/ui/OptionFactory.java +++ b/apache-rat-core/src/main/java/org/apache/rat/ui/OptionFactory.java @@ -72,7 +72,7 @@ public final class OptionFactory { */ public static <T extends AbstractOption<T>> Map<String, T> getOptionMap(final Config<T> config) { Map<String, T> result = new TreeMap<>(); - getOptionList(config).forEach(option -> result.put(AbstractOption.extractBaseName(option.getOption()), option)); + getOptions(config).forEach(option -> result.put(AbstractOption.extractBaseName(option.getOption()), option)); return result; } @@ -82,7 +82,7 @@ public final class OptionFactory { * @return a stream of AbstractOption implementations. * @param <T> the AbstractOption implementation. */ - public static <T extends AbstractOption<T>> Stream<T> getOptionList(final Config<T> config) { + public static <T extends AbstractOption<T>> Stream<T> getOptions(final Config<T> config) { return Arg.getOptions(config.additionalOptions).getOptions().stream().filter(config.getFilter()).map(config.mapper); } diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/BaseRatMojo.java b/apache-rat-core/src/main/java/org/apache/rat/ui/SetArgs.java similarity index 50% rename from apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/BaseRatMojo.java rename to apache-rat-core/src/main/java/org/apache/rat/ui/SetArgs.java index 0d2a86da..d4d09cab 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/BaseRatMojo.java +++ b/apache-rat-core/src/main/java/org/apache/rat/ui/SetArgs.java @@ -16,99 +16,60 @@ * specific language governing permissions and limitations * under the License. */ - -package org.apache.rat.plugin; - -import org.apache.commons.cli.Option; -import org.apache.commons.lang3.StringUtils; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.rat.commandline.Arg; -import org.apache.rat.DeprecationReporter; -import org.apache.rat.utils.CasedString; -import org.apache.rat.utils.DefaultLog; -import org.apache.rat.utils.Log; +package org.apache.rat.ui; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; -/* DO NOT EDIT - GENERATED FILE */ - -/** - * Generated class to provide Maven support for standard RAT command line options - */ -public abstract class BaseRatMojo extends AbstractMojo { - - private static final Map<String, String> xlateName = new HashMap<>(); - - private static final List<String> unsupportedArgs = new ArrayList<>(); - - private static final Map<String, String> deprecatedArgs = new HashMap<>(); +import org.apache.commons.cli.Option; +import org.apache.commons.lang3.StringUtils; +import org.apache.rat.DeprecationReporter; +import org.apache.rat.commandline.Arg; +import org.apache.rat.utils.DefaultLog; +import org.apache.rat.utils.Log; - static { - xlateName.put("addLicense", "add-license"); - unsupportedArgs.add("help"); - unsupportedArgs.add("dir"); - unsupportedArgs.add("log-level"); - deprecatedArgs.put("copyright", "Use of deprecated option 'copyright'. Deprecated for removal since 0.17: Use <editCopyright> instead."); - deprecatedArgs.put("force", "Use of deprecated option 'force'. Deprecated for removal since 0.17: Use <editOverwrite> instead."); - deprecatedArgs.put("addLicense", "Use of deprecated option 'addLicense'. Deprecated for removal since 0.17: Use <editLicense> instead."); - deprecatedArgs.put("licenses", "Use of deprecated option 'licenses'. Deprecated for removal since 0.17: Use <config> instead."); - deprecatedArgs.put("no-default-licenses", "Use of deprecated option 'noDefaultLicenses'. Deprecated for removal since 0.17: Use <configurationNoDefaults> instead."); - deprecatedArgs.put("exclude", "Use of deprecated option 'exclude'. Deprecated for removal since 0.17: Use <inputExclude> instead."); - deprecatedArgs.put("exclude-file", "Use of deprecated option 'excludeFile'. Deprecated for removal since 0.17: Use <inputExcludeFile> instead."); - deprecatedArgs.put("include", "Use of deprecated option 'include'. Deprecated for removal since 0.17: Use <inputInclude> instead."); - deprecatedArgs.put("includes-file", "Use of deprecated option 'includesFile'. Deprecated for removal since 0.17: Use <inputIncludeFile> instead."); - deprecatedArgs.put("scan-hidden-directories", "Use of deprecated option 'scanHiddenDirectories'. Deprecated for removal since 0.17: Use <inputIncludeStd> with 'HIDDEN_DIR' argument instead."); - deprecatedArgs.put("stylesheet", "Use of deprecated option 'stylesheet'. Deprecated for removal since 0.17: Use <outputStyle> instead."); - deprecatedArgs.put("xml", "Use of deprecated option 'xml'. Deprecated for removal since 0.17: Use <outputStyle> with the 'xml' argument instead."); - deprecatedArgs.put("list-licenses", "Use of deprecated option 'listLicenses'. Deprecated for removal since 0.17: Use <outputLicenses> instead."); - deprecatedArgs.put("list-families", "Use of deprecated option 'listFamilies'. Deprecated for removal since 0.17: Use <outputFamilies> instead."); - deprecatedArgs.put("out", "Use of deprecated option 'out'. Deprecated for removal since 0.17: Use <outputFile> instead."); - } +public final class SetArgs { /** - * Creates a Maven name from a long option. - * Will map excluded long options to null. - * @param longOpt the kebab name. - * @return The CamelCased name for Maven use. + * List of deprecated arguments and their deprecation notice. */ - public static String createName(String longOpt) { - String name = xlateName.get(longOpt); - return name != null ? name : new CasedString(CasedString.StringCase.KEBAB, longOpt).toCase(CasedString.StringCase.CAMEL); - } + private final Map<String, String> deprecatedArgs = new HashMap<>(); /** - * Creates a kebab case name from a camel case name. - * @param camelCase the camel case name to convert. - * @return the kebab format. + * A map of CLI-based arguments to values. */ - public static String toKebabForm(String camelCase) { - return new CasedString(CasedString.StringCase.CAMEL, camelCase).toCase(CasedString.StringCase.KEBAB); - } + private final Map<String, List<String>> args = new HashMap<>(); /** - * Returns the list of unsupported args. - * @return the list of kebab style names that are unsupported by the Maven UI. + * The arguments set by the UI for the current report execution. + * @param renameMap the map of renamed options. + * @param uiOptionList the list of AbstractOption implementations for this UI. */ - public static List<String> unsupportedArgs() { - return Collections.unmodifiableList(unsupportedArgs); + public SetArgs(final Map<String, String> renameMap, final List<? extends AbstractOption<?>> uiOptionList) { + for (AbstractOption<?> option : uiOptionList) { + if (option.isDeprecated()) { + deprecatedArgs.put(option.getName(), + String.format("Use of deprecated option '%s'. %s", option.getName(), option.getDeprecated())); + } + } + } + + public Set<Map.Entry<String, List<String>>> entrySet() { + return args.entrySet(); } - - ///////////////////////// Start common Arg manipulation code /** * Sets the deprecation report method. */ - private static void setDeprecationReporter() { + private void setDeprecationReporter() { DeprecationReporter.setLogReporter(opt -> { - String msg = deprecatedArgs.get(argsKey(opt)); + String msg = deprecatedArgs.get(AbstractOption.extractBaseName(opt)); if (msg == null) { DeprecationReporter.getDefault().accept(opt); } else { @@ -117,21 +78,12 @@ public abstract class BaseRatMojo extends AbstractMojo { }); } - private static String argsKey(Option opt) { - return StringUtils.defaultIfEmpty(opt.getLongOpt(), opt.getKey()); - } - - /** - * A map of CLI-based arguments to values. - */ - protected final Map<String, List<String>> args = new HashMap<>(); - /** * Gets the list of arguments prepared for the CLI code to parse. * @return the List of arguments for the CLI command line. */ - protected List<String> args() { - List<String> result = new ArrayList<>(); + public List<String> args() { + final List<String> result = new ArrayList<>(); for (Map.Entry<String, List<String>> entry : args.entrySet()) { result.add("--" + entry.getKey()); result.addAll(entry.getValue().stream().filter(Objects::nonNull).collect(Collectors.toList())); @@ -139,20 +91,20 @@ public abstract class BaseRatMojo extends AbstractMojo { return result; } - private boolean validateSet(String key) { - Arg arg = Arg.findArg(key); + private boolean validateSet(final String key) { + final Arg arg = Arg.findArg(key); if (arg != null) { - Option opt = arg.find(key); - Option main = arg.option(); + final Option opt = arg.find(key); + final Option main = arg.option(); if (opt.isDeprecated()) { - args.remove(argsKey(main)); + args.remove(AbstractOption.extractBaseName(main)); // deprecated options must be explicitly set so let it go. return true; } // non-deprecated options may have default so ignore it if another option has already been set. for (Option o : arg.group().getOptions()) { if (!o.equals(main)) { - if (args.containsKey(argsKey(o))) { + if (args.containsKey(AbstractOption.extractBaseName(o))) { return false; } } @@ -168,7 +120,7 @@ public abstract class BaseRatMojo extends AbstractMojo { * @param key the key for the map. * @param value the value to set. */ - protected void setArg(String key, String value) { + public void setArg(final String key, final String value) { if (value == null || StringUtils.isNotBlank(value)) { if (validateSet(key)) { List<String> values = new ArrayList<>(); @@ -186,7 +138,7 @@ public abstract class BaseRatMojo extends AbstractMojo { * @param key the key for the map. * @return the list of values for the key or {@code null} if not set. */ - public List<String> getArg(String key) { + public List<String> getArg(final String key) { return args.get(key); } @@ -197,7 +149,7 @@ public abstract class BaseRatMojo extends AbstractMojo { * @param key the key for the map. * @param value the array of values to set. */ - protected void addArg(String key, String[] value) { + public void addArg(final String key, final String[] value) { List<String> newValues = Arrays.stream(value).filter(StringUtils::isNotBlank).collect(Collectors.toList()); if (!newValues.isEmpty()) { if (validateSet(key)) { @@ -216,7 +168,7 @@ public abstract class BaseRatMojo extends AbstractMojo { * @param key the key for the map. * @param value the value to set. */ - protected void addArg(String key, String value) { + public void addArg(final String key, final String value) { if (StringUtils.isNotBlank(value)) { if (validateSet(key)) { List<String> values = args.get(key); @@ -236,16 +188,7 @@ public abstract class BaseRatMojo extends AbstractMojo { * Remove a key from the argument list. * @param key the key to remove from the map. */ - protected void removeArg(String key) { + public void removeArg(final String key) { args.remove(key); } - - ///////////////////////// End common Arg manipulation code - - protected BaseRatMojo() { - setDeprecationReporter(); - } - - /* GENERATED METHODS */ - - +} diff --git a/apache-rat-core/src/main/java/org/apache/rat/utils/CasedString.java b/apache-rat-core/src/main/java/org/apache/rat/utils/CasedString.java index 1e943a2d..c70ef0d2 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/utils/CasedString.java +++ b/apache-rat-core/src/main/java/org/apache/rat/utils/CasedString.java @@ -170,6 +170,16 @@ public class CasedString { this.stringCase = stringCase; } + /** + * A representation of a cased string and the identified case of that string. + * @param stringCase The {@code StringCase} that the {@code string} argument is in. + * @param parts The string parts. + */ + public CasedString(final StringCase stringCase, final String[] parts) { + this.string = parts == null ? null : stringCase.assemble(parts); + this.stringCase = stringCase; + } + /** * Returns an array of each of the segments in this CasedString. Segments are defined as the strings between * the separators in the CasedString. For the CAMEL case the segments are determined by the presence of a capital letter. diff --git a/apache-rat-core/src/test/java/org/apache/rat/config/exclusion/fileProcessors/GitIgnoreBuilderTest.java b/apache-rat-core/src/test/java/org/apache/rat/config/exclusion/fileProcessors/GitIgnoreBuilderTest.java index 8cc989ec..e403712b 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/config/exclusion/fileProcessors/GitIgnoreBuilderTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/config/exclusion/fileProcessors/GitIgnoreBuilderTest.java @@ -28,6 +28,7 @@ import org.apache.rat.config.exclusion.MatcherSet; import org.apache.rat.document.DocumentName; import org.apache.rat.document.DocumentNameMatcher; import org.apache.rat.document.FSInfoTest; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/.gitignore b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/.gitignore new file mode 100644 index 00000000..fff8c14b --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/.gitignore @@ -0,0 +1,10 @@ +*.md + +# This makes it ignore dir3/dir3.log and dir3/file3.log +*.log + +# This makes it "unignore" dir3/file3.log +!file*.log + +# Don't ignore xml files +!*.xml diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/.gitignore b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/.gitignore new file mode 100644 index 00000000..c700f8aa --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/.gitignore @@ -0,0 +1,3 @@ +*.txt +!dir1.md +file1.log diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/dir1.txt b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/dir1.txt new file mode 100644 index 00000000..a31cbc89 --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/dir1.txt @@ -0,0 +1 @@ +File without a valid license diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/file1.log b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/file1.log new file mode 100644 index 00000000..a31cbc89 --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir1/file1.log @@ -0,0 +1 @@ +File without a valid license diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir2/dir2.md b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir2/dir2.md new file mode 100644 index 00000000..a31cbc89 --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir2/dir2.md @@ -0,0 +1 @@ +File without a valid license diff --git a/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir3/dir3.log b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir3/dir3.log new file mode 100644 index 00000000..a31cbc89 --- /dev/null +++ b/apache-rat-core/src/test/resources/GitIgnoreBuilderTest/src/dir3/dir3.log @@ -0,0 +1 @@ +File without a valid license diff --git a/apache-rat-plugin-parent/impl/pom.xml b/apache-rat-plugin-parent/impl/pom.xml index 4042b78d..4a2bdf95 100644 --- a/apache-rat-plugin-parent/impl/pom.xml +++ b/apache-rat-plugin-parent/impl/pom.xml @@ -24,7 +24,7 @@ </parent> <artifactId>apache-rat-plugin</artifactId> <packaging>maven-plugin</packaging> - <name>Apache Creadur RAT::Plugin4Maven</name> + <name>Apache Creadur RAT::Maven plugin</name> <description>A plugin for Apache Maven that runs Apache RAT to audit the source to be distributed.</description> <inceptionYear>2007</inceptionYear> @@ -174,17 +174,15 @@ <artifactId>exec-maven-plugin</artifactId> <executions> <execution> - <id>Create BaseRatMojo</id> + <id>create-AbstractMaven</id> <goals> <goal>java</goal> </goals> <phase>generate-sources</phase> <configuration> - <mainClass>org.apache.rat.tools.MavenGenerator</mainClass> - <classpathScope>test</classpathScope> + <mainClass>org.apache.rat.maven.CodeGenerator</mainClass> <arguments> - <argument>org.apache.rat.plugin</argument> - <argument>BaseRatMojo</argument> + <argument>-p</argument> <argument>${project.build.sourceDirectory}</argument> </arguments> </configuration> @@ -277,6 +275,11 @@ </plugins> </build> <dependencies> + <dependency> + <groupId>org.apache.rat</groupId> + <artifactId>apache-rat-plugin-tools</artifactId> + <version>${project.version}</version> + </dependency> <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> @@ -286,17 +289,15 @@ <artifactId>apache-rat-core</artifactId> </dependency> <!-- rat tools in test scope so that it does not get bundled into the plugin --> +<!-- <dependency>--> +<!-- <groupId>org.apache.rat</groupId>--> +<!-- <artifactId>apache-rat-tools</artifactId>--> +<!-- <scope>test</scope>--> +<!-- </dependency>--> <dependency> <groupId>org.apache.rat</groupId> - <artifactId>apache-rat-tools</artifactId> - <scope>test</scope> - </dependency> - <dependency> - <groupId>org.apache.rat</groupId> - <artifactId>apache-rat-core</artifactId> - <type>test-jar</type> - <classifier>tests</classifier> - <scope>test</scope> + <artifactId>apache-rat-core-tests</artifactId> + <scope>compile</scope> </dependency> <dependency> <groupId>org.mockito</groupId> diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/AbstractRatMojo.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/AbstractRatMojo.java index ab2129c9..2e2ce3b2 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/AbstractRatMojo.java +++ b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/AbstractRatMojo.java @@ -21,39 +21,24 @@ package org.apache.rat.mp; import java.io.File; import java.io.IOException; import java.io.PrintWriter; -import java.net.URI; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.SortedSet; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import java.util.stream.Stream; import org.apache.commons.cli.Option; -import org.apache.commons.lang3.StringUtils; +import org.apache.commons.cli.ParseException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; -import org.apache.rat.Defaults; import org.apache.rat.OptionCollection; import org.apache.rat.ReportConfiguration; -import org.apache.rat.analysis.license.DeprecatedConfig; import org.apache.rat.commandline.Arg; -import org.apache.rat.config.exclusion.StandardCollection; -import org.apache.rat.configuration.Format; -import org.apache.rat.configuration.LicenseReader; -import org.apache.rat.configuration.MatcherReader; +import org.apache.rat.commandline.ArgumentContext; import org.apache.rat.document.DocumentName; import org.apache.rat.document.FileDocument; import org.apache.rat.license.ILicense; -import org.apache.rat.license.ILicenseFamily; -import org.apache.rat.license.LicenseSetFactory.LicenseFilter; -import org.apache.rat.license.SimpleLicenseFamily; -import org.apache.rat.plugin.BaseRatMojo; +import org.apache.rat.maven.AbstractMaven; import org.apache.rat.utils.DefaultLog; import org.apache.rat.utils.Log; import org.apache.rat.walker.DirectoryWalker; @@ -63,7 +48,7 @@ import static java.lang.String.format; /** * Abstract base class for Mojos, which are running Rat. */ -public abstract class AbstractRatMojo extends BaseRatMojo { +public abstract class AbstractRatMojo extends AbstractMaven { /** Report configuration for report */ private ReportConfiguration reportConfiguration; /** @@ -79,80 +64,9 @@ public abstract class AbstractRatMojo extends BaseRatMojo { @Parameter(property = "rat.verbose", defaultValue = "false") protected boolean verbose; - /** - * Specifies the licenses to accept. By default, these are added to the default - * licenses, unless you set <addDefaultLicenseMatchers> to false. Arguments should be - * file name of <Configs> file structure. - * @deprecated Use specific configuration under <configuration>. - * @since 0.8 - */ - @Parameter - @Deprecated - private String[] defaultLicenseFiles; - - /** - * Specifies the additional licenses file. - * @deprecated Use specific configuration under <configuration>. - */ - @Parameter - @Deprecated - private String[] additionalLicenseFiles; - - /** - * Whether to add the default list of licenses. - * @deprecated Deprecated for removal since 0.17: Use <configurationNoDefaults> instead (note the change of state). - */ - @Deprecated - @Parameter(property = "rat.addDefaultLicenses", name = "addDefaultLicenses") - public void setAddDefaultLicenses(final boolean addDefaultLicenses) { - setNoDefaultLicenses(!addDefaultLicenses); - } - - /** - * Whether to add the default list of license matchers. - * @deprecated Use specific configuration under <configuration>. - */ - @Deprecated - @Parameter(property = "rat.addDefaultLicenseMatchers") - private boolean addDefaultLicenseMatchers; - - /** The list of approved licenses - * @deprecated Use specific configuration under <configuration>. - */ - @Deprecated - @Parameter - private String[] approvedLicenses; - - /** The file of approved licenses - * @deprecated Use specific configuration under <configuration>. - */ - @Deprecated - @Parameter(property = "rat.approvedFile") - private String approvedLicenseFile; - - /** - * Specifies the license families to accept. - * - * @since 0.8 - * @deprecated Use LicenseFamily section of configuration file. - */ - @Deprecated - @Parameter - private SimpleLicenseFamily[] licenseFamilies; - - /** The list of license definitions. - * @deprecated Deprecated for removal since 0.17: Use specific configuration under <configuration>. See configuration file documentation. - */ - @Deprecated - @Parameter - private Object[] licenses; - - /** The list of family definitions. - * @deprecated Use specific configuration under <configuration>. - */ - @Deprecated - @Parameter - private Family[] families; + /** The xml output file. */ + @Parameter(defaultValue = "${project.build.directory}/.rat.xml", readonly = true) + protected File xmlOutputFile; /** * Specifies the include files character set. @@ -168,76 +82,6 @@ public abstract class AbstractRatMojo extends BaseRatMojo { @Parameter(property = "rat.excludesFileCharset", defaultValue = "${project.build.sourceEncoding}") private String excludesFileCharset; - /** - * Whether to use the default excludes when scanning for files. The default - * excludes are: - * <ul> - * <li>meta data files for source code management / revision control systems, - * see {@link org.apache.rat.config.exclusion.StandardCollection}</li> - * <li>temporary files used by Maven, see - * <a href="#useMavenDefaultExcludes">useMavenDefaultExcludes</a></li> - * <li>configuration files for Eclipse, see - * <a href="#useEclipseDefaultExcludes">useEclipseDefaultExcludes</a></li> - * <li>configuration files for IDEA, see - * <a href="#useIdeaDefaultExcludes">useIdeaDefaultExcludes</a></li> - * </ul> - * @deprecated When set to true specifies that the STANDARD_PATTERNS are excluded, as are - * the STANDARD_SCMS patterns. Use the various InputExclude and InputInclude elements to - * explicitly specify what to include or exclude. - */ - @Parameter(property = "rat.useDefaultExcludes", defaultValue = "true") - @Deprecated - private boolean useDefaultExcludes; - - /** - * Whether to use the Maven specific default excludes when scanning for files. - * Maven specific default excludes are given by the constant - * MAVEN_DEFAULT_EXCLUDES: The <code>target</code> directory, the - * <code>cobertura.ser</code> file, and so on. - * @deprecated When set to true specifies that the MAVEN patterns are excluded. - * Use "inputIncludeStd MAVEN" to override. - */ - @Parameter(property = "rat.useMavenDefaultExcludes", defaultValue = "true") - @Deprecated - private boolean useMavenDefaultExcludes; - - /** - * Whether to parse source code management system (SCM) ignore files and use - * their contents as excludes. At the moment this works for the following SCMs: - * - * @see org.apache.rat.config.exclusion.StandardCollection - * @deprecated When set to true specifies that the STANDARD_SCMS exclusion file - * processors are used to exclude files and directories (e.g. ".gitignore" or ".hgignore"). - * Use "inputIncludeStd STANDARD_SCMS" to override. - */ - @Parameter(property = "rat.parseSCMIgnoresAsExcludes", defaultValue = "true") - @Deprecated - private boolean parseSCMIgnoresAsExcludes; - - /** - * Whether to use the Eclipse specific default excludes when scanning for files. - * Eclipse specific default excludes are given by the constant - * ECLIPSE_DEFAULT_EXCLUDES: The <code>.classpath</code> and - * <code>.project</code> files, the <code>.settings</code> directory, and so on. - * @deprecated When set to true specifies that the ECLIPSE patterns are excluded. - * Use "inputIncludeStd ECLIPSE" to override. - */ - @Parameter(property = "rat.useEclipseDefaultExcludes", defaultValue = "true") - @Deprecated - private boolean useEclipseDefaultExcludes; - - /** - * Whether to use the IDEA specific default excludes when scanning for files. - * IDEA specific default excludes are given by the constant - * IDEA_DEFAULT_EXCLUDES: The <code>*.iml</code>, <code>*.ipr</code> and - * <code>*.iws</code> files and the <code>.idea</code> directory. - * @deprecated When set to true specifies that the IDEA patterns are excluded. - * Use "inputIncludeStd IDEA" to override. - */ - @Deprecated - @Parameter(property = "rat.useIdeaDefaultExcludes", defaultValue = "true") - private boolean useIdeaDefaultExcludes; - /** * Whether to exclude subprojects. This is recommended, if you want a separate * apache-rat-plugin report for each subproject. @@ -272,55 +116,6 @@ public abstract class AbstractRatMojo extends BaseRatMojo { return project; } - protected Defaults.Builder getDefaultsBuilder() { - Defaults.Builder result = Defaults.builder().noDefault(); - if (defaultLicenseFiles != null) { - for (String defaultLicenseFile : defaultLicenseFiles) { - result.add(defaultLicenseFile); - } - } - return result; - } - - @Deprecated // remove this for version 1.0 - private Stream<License> getLicenses() { - if (licenses == null) { - return Stream.empty(); - } - return Arrays.stream(licenses).filter(s -> s instanceof License).map(License.class::cast); - } - - @Deprecated // remove this for version 1.0 - private Stream<DeprecatedConfig> getDeprecatedConfigs() { - if (licenses == null) { - return Stream.empty(); - } - return Arrays.stream(licenses).filter(s -> s instanceof DeprecatedConfig).map(DeprecatedConfig.class::cast); - } - - @Deprecated // remove this for version 1.0 - private void reportDeprecatedProcessing() { - if (getDeprecatedConfigs().findAny().isPresent()) { - DefaultLog.getInstance().warn("Configuration uses deprecated configuration. You need to upgrade to v0.17 configuration options."); - } - } - - @Deprecated // remove this for version 1.0 - private void processLicenseFamilies(final ReportConfiguration config) { - List<ILicenseFamily> families = getDeprecatedConfigs().map(DeprecatedConfig::getLicenseFamily).filter(Objects::nonNull).collect(Collectors.toList()); - if (licenseFamilies != null) { - for (SimpleLicenseFamily slf : licenseFamilies) { - if (StringUtils.isBlank(slf.getFamilyCategory())) { - families.stream().filter(f -> f.getFamilyName().equalsIgnoreCase(slf.getFamilyName())).findFirst() - .ifPresent(config::addApprovedLicenseCategory); - } else { - config.addApprovedLicenseCategory(ILicenseFamily.builder().setLicenseFamilyCategory(slf.getFamilyCategory()) - .setLicenseFamilyName(StringUtils.defaultIfBlank(slf.getFamilyName(), slf.getFamilyCategory())) - .build()); - } - } - } - } /** * Reads values for the Arg. @@ -332,7 +127,7 @@ public abstract class AbstractRatMojo extends BaseRatMojo { List<String> result = new ArrayList<>(); for (Option option : arg.group().getOptions()) { if (option.getLongOpt() != null) { - List<String> args = getArg(option.getLongOpt()); + List<String> args = setArgs.getArg(option.getLongOpt()); if (args != null) { result.addAll(args); } @@ -348,7 +143,7 @@ public abstract class AbstractRatMojo extends BaseRatMojo { protected void removeKey(final Arg arg) { for (Option option : arg.group().getOptions()) { if (option.getLongOpt() != null) { - removeArg(option.getLongOpt()); + setArgs.removeArg(option.getLongOpt()); } } } @@ -433,36 +228,15 @@ public abstract class AbstractRatMojo extends BaseRatMojo { }; } + /** + * Processes the excludeSubProjects option and adds appropriate modules to the include/excludes + */ private void setIncludeExclude() { - if (excludeSubProjects && project != null && project.getModules() != null) { List<String> subModules = new ArrayList<>(); project.getModules().forEach(s -> subModules.add(format("%s/**", s))); setInputExcludes(subModules.toArray(new String[0])); } - - List<String> values = getValues(Arg.EXCLUDE); - if (values.isEmpty() && useDefaultExcludes) { - DefaultLog.getInstance().debug("Adding plexus default exclusions..."); - setInputExcludes(StandardCollection.STANDARD_PATTERNS.patterns().toArray(new String[0])); - - DefaultLog.getInstance().debug("Adding SCM default exclusions..."); - setInputExcludes(StandardCollection.STANDARD_SCMS.patterns().toArray(new String[0])); - } - - if (useMavenDefaultExcludes) { - setInputExcludeStd(StandardCollection.MAVEN.name()); - } - if (useEclipseDefaultExcludes) { - setInputExcludeStd(StandardCollection.ECLIPSE.name()); - } - if (useIdeaDefaultExcludes) { - setInputExcludeStd(StandardCollection.IDEA.name()); - } - - if (parseSCMIgnoresAsExcludes) { - setInputExcludeParsedScm(StandardCollection.STANDARD_SCMS.name()); - } } protected ReportConfiguration getConfiguration() throws MojoExecutionException { @@ -471,7 +245,7 @@ public abstract class AbstractRatMojo extends BaseRatMojo { try { if (getLog().isDebugEnabled()) { log.debug("Start BaseRatMojo Configuration options"); - for (Map.Entry<String, List<String>> entry : args.entrySet()) { + for (Map.Entry<String, List<String>> entry : setArgs.entrySet()) { log.debug(format(" * %s %s", entry.getKey(), String.join(", ", entry.getValue()))); } log.debug("End BaseRatMojo Configuration options"); @@ -481,75 +255,16 @@ public abstract class AbstractRatMojo extends BaseRatMojo { removeKey(Arg.HELP_LICENSES); setIncludeExclude(); - getLog().debug("Basedir is : " + basedir); - ReportConfiguration config = OptionCollection.parseCommands(basedir, args().toArray(new String[0]), - o -> getLog().warn("Help option not supported"), - true); - reportDeprecatedProcessing(); - - if (additionalLicenseFiles != null) { - for (String licenseFile : additionalLicenseFiles) { - URI uri = new File(licenseFile).toURI(); - Format fmt = Format.from(licenseFile); - MatcherReader mReader = fmt.matcherReader(); - if (mReader != null) { - mReader.addMatchers(uri); - } - LicenseReader lReader = fmt.licenseReader(); - if (lReader != null) { - lReader.addLicenses(uri); - config.addLicenses(lReader.readLicenses()); - config.addApprovedLicenseCategories(lReader.approvedLicenseId()); - } - } - } - if (families != null || getDeprecatedConfigs().findAny().isPresent()) { - if (log.isEnabled(Log.Level.DEBUG)) { - log.debug(format("%s license families loaded from pom", families.length)); - } - Consumer<ILicenseFamily> logger = super.getLog().isDebugEnabled() ? l -> log.debug(format("Family: %s", l)) - : l -> { - }; - - Consumer<ILicenseFamily> process = logger.andThen(config::addFamily); - getDeprecatedConfigs().map(DeprecatedConfig::getLicenseFamily).filter(Objects::nonNull).forEach(process); - if (families != null) { // TODO remove if check in v1.0 - Arrays.stream(families).map(Family::build).forEach(process); - } - } - - processLicenseFamilies(config); - - if (approvedLicenses != null && approvedLicenses.length > 0) { - Arrays.stream(approvedLicenses).forEach(config::addApprovedLicenseCategory); - } - - if (licenses != null) { - if (log.isEnabled(Log.Level.DEBUG)) { - log.debug(format("%s licenses loaded from pom", licenses.length)); - } - Consumer<ILicense> logger = log.isEnabled(Log.Level.DEBUG) ? l -> log.debug(format("License: %s", l)) - : l -> { - }; - Consumer<ILicense> addApproved = (approvedLicenses == null || approvedLicenses.length == 0) - ? l -> config.addApprovedLicenseCategory(l.getLicenseFamily()) - : l -> { - }; - - Consumer<ILicense> process = logger.andThen(config::addLicense).andThen(addApproved); - SortedSet<ILicenseFamily> families = config.getLicenseFamilies(LicenseFilter.ALL); - getDeprecatedConfigs().map(DeprecatedConfig::getLicense).filter(Objects::nonNull) - .map(x -> x.setLicenseFamilies(families).build()).forEach(process); - getLicenses().map(x -> x.build(families)).forEach(process); - } + ArgumentContext ctxt = OptionCollection.parseCommands(basedir, setArgs.args().toArray(new String[0])); DocumentName dirName = DocumentName.builder(basedir).build(); - config.addSource(new DirectoryWalker(new FileDocument(dirName, basedir, config.getDocumentExcluder(dirName)))); + ctxt.getConfiguration().addSource(new DirectoryWalker(new FileDocument(dirName, basedir, + ctxt.getConfiguration().getDocumentExcluder(dirName)))); if (helpLicenses) { - new org.apache.rat.help.Licenses(config, new PrintWriter(log.asWriter())).printHelp(); + new org.apache.rat.help.Licenses(ctxt.getConfiguration(), new PrintWriter(log.asWriter())).printHelp(); } - reportConfiguration = config; - } catch (IOException e) { + reportConfiguration = ctxt.getConfiguration(); + } catch (IOException | ParseException e) { throw new MojoExecutionException(e); } } diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatCheckMojo.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatCheckMojo.java index 7bd6b1da..e4686adf 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatCheckMojo.java +++ b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatCheckMojo.java @@ -20,12 +20,13 @@ package org.apache.rat.mp; import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileFilter; -import java.io.IOException; -import java.io.Writer; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.List; +import org.apache.commons.io.function.IOSupplier; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -33,6 +34,7 @@ import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.rat.ReportConfiguration; import org.apache.rat.Reporter; +import org.apache.rat.api.RatException; import org.apache.rat.commandline.Arg; import org.apache.rat.commandline.StyleSheets; import org.apache.rat.config.exclusion.StandardCollection; @@ -52,92 +54,12 @@ import static java.lang.String.format; @Mojo(name = "check", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true) public class RatCheckMojo extends AbstractRatMojo { - /** The default output file if no other is specified. - * @deprecated Use <outputFile> instead. - */ - @Deprecated - @Parameter(defaultValue = "${project.build.directory}/rat.txt") - private File defaultReportFile; - - /** - * The defined build directory - */ - @Parameter(defaultValue = "${project.build.directory}", readonly = true) - private String buildDirectory; - - /** - * Where to store the report. - * @deprecated Use 'out' property instead. - */ - @Deprecated - @Parameter - public void setReportFile(final File reportFile) { - if (!reportFile.getParentFile().exists() && !reportFile.getParentFile().mkdirs()) { - getLog().error("Unable to create directory " + reportFile.getParentFile()); - } - setOutputFile(reportFile.getAbsolutePath()); - } - - /** - * Output style of the report. Use "plain" (the default) for a plain text report - * or "xml" for the raw XML report. Alternatively you can give the path of an - * XSL transformation that will be applied on the raw XML to produce the report - * written to the output file. - * @deprecated Use setStyleSheet or xml instead. - */ - @Deprecated - @Parameter(property = "rat.outputStyle") - public void setReportStyle(final String value) { - if (value.equalsIgnoreCase("xml")) { - setXml(true); - } else if (value.equalsIgnoreCase("plain")) { - setStylesheet("plain-rat"); - } else { - setStylesheet(value); - } - } - - /** - * Maximum number of files with unapproved licenses. - * @deprecated Use <counterMax>Unapproved:value</counterMax>. - */ - @Deprecated - @Parameter(property = "rat.numUnapprovedLicenses", defaultValue = "0") - private int numUnapprovedLicenses; - - /** - * Whether to add license headers; possible values are {@code forced}, - * {@code true}, and {@code false} (default). - * @deprecated Use <editLicense> and <editOverwrite>. - */ - @Deprecated - @Parameter(property = "rat.addLicenseHeaders") - public void setAddLicenseHeaders(final String addLicenseHeaders) { - switch (addLicenseHeaders.trim().toUpperCase()) { - case "FALSE": - // do nothing; - break; - case "TRUE": - setAddLicense(true); - break; - case "FORCED": - setAddLicense(true); - setForce(true); - break; - default: - throw new IllegalArgumentException("Unknown addlicense header: " + addLicenseHeaders); - } - } - - /** - * Copyright message to add to license headers. - * @deprecated Deprecated for removal since 0.17: Use <editCopyright> instead. - */ - @Deprecated - @Parameter(property = "rat.copyrightMessage") - public void setCopyrightMessage(final String copyrightMessage) { - setCopyright(copyrightMessage); + public RatCheckMojo() { + super(); } + /** The default output file if no other is specified. */ + @Parameter(defaultValue = "${project.build.directory}/rat.txt", readonly = true) + private File defaultReportFile; /** * Will ignore RAT errors and display a log message if any. Its use is NOT @@ -161,27 +83,7 @@ public class RatCheckMojo extends AbstractRatMojo { /** The reporter that this mojo uses */ private Reporter reporter; - @Override - protected ReportConfiguration getConfiguration() throws MojoExecutionException { - ReportConfiguration result = super.getConfiguration(); - if (numUnapprovedLicenses > 0) { - result.getClaimValidator().setMax(ClaimStatistic.Counter.UNAPPROVED, numUnapprovedLicenses); - } - result.addExcludedCollection(StandardCollection.MAVEN); - if (StandardCollection.MAVEN.fileProcessorBuilder().hasNext()) { - result.addExcludedFileProcessor(StandardCollection.MAVEN); - } - if (StandardCollection.MAVEN.hasStaticDocumentNameMatcher()) { - StandardCollection.MAVEN.staticDocumentNameMatcher(); - } - - String buildDirAbsolutePath = new File(buildDirectory).getAbsolutePath(); - FileFilter buildFilter = f -> f.getAbsolutePath().startsWith(buildDirAbsolutePath); - result.addExcludedFilter(buildFilter); - - return result; - } - + Reporter.Output output; /** * Invoked by Maven to execute the Mojo. * @@ -198,7 +100,7 @@ public class RatCheckMojo extends AbstractRatMojo { } if (getValues(Arg.OUTPUT_FILE).isEmpty()) { - setArg(Arg.OUTPUT_FILE.option().getLongOpt(), defaultReportFile.getAbsolutePath()); + setArgs.setArg(Arg.OUTPUT_FILE.option().getLongOpt(), defaultReportFile.getAbsolutePath()); } try (Writer logWriter = DefaultLog.getInstance().asWriter()) { @@ -209,11 +111,15 @@ public class RatCheckMojo extends AbstractRatMojo { } try { this.reporter = new Reporter(config); - reporter.output(); + output = reporter.execute(); + writeMojoRatReport(output); if (verbose) { - reporter.writeSummary(logWriter); + output.writeSummary(DefaultLog.getInstance().asWriter()); } - check(config); + // produce the requested output. + output.format(config.getStyleSheet(), config.getOutput()); + // check for errors and fail if necessary + check(config, output); } catch (MojoFailureException e) { throw e; } catch (Exception e) { @@ -224,28 +130,41 @@ public class RatCheckMojo extends AbstractRatMojo { } } - protected void check(final ReportConfiguration config) throws MojoFailureException { - ClaimStatistic statistics = reporter.getClaimsStatistic(); + /** + * Saves the Maven Mojo version of the XML for later. + * @param output the output to write to the XML file. + */ + private void writeMojoRatReport(final Reporter.Output output) { + IOSupplier<OutputStream> outputStream = () -> Files.newOutputStream(xmlOutputFile.toPath()); + final IOSupplier<InputStream> stylesheet = StyleSheets.XML.getStyleSheet(); try { - reporter.writeSummary(DefaultLog.getInstance().asWriter(Log.Level.DEBUG)); - if (config.getClaimValidator().hasErrors()) { - config.getClaimValidator().logIssues(statistics); - if (consoleOutput && - !config.getClaimValidator().isValid(ClaimStatistic.Counter.UNAPPROVED, statistics.getCounter(ClaimStatistic.Counter.UNAPPROVED))) { - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - reporter.output(StyleSheets.UNAPPROVED_LICENSES.getStyleSheet(), () -> baos); - getLog().warn(baos.toString(StandardCharsets.UTF_8)); - } catch (RuntimeException rte) { - throw rte; - } catch (Exception e) { - getLog().warn("Unable to print the files with unapproved licenses to the console."); - } - } + output.format(stylesheet, outputStream); + } catch (RatException e) { + getLog().warn(e.getMessage(), e); + } + } + + protected void check(final ReportConfiguration config, final Reporter.Output output) throws MojoFailureException { + ClaimStatistic statistics = output.getStatistic(); + + if (config.getClaimValidator().hasErrors()) { + config.getClaimValidator().logIssues(statistics); + if (consoleOutput && + !config.getClaimValidator().isValid(ClaimStatistic.Counter.UNAPPROVED, statistics.getCounter(ClaimStatistic.Counter.UNAPPROVED))) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + output.format(StyleSheets.UNAPPROVED_LICENSES.getStyleSheet(), () -> baos); + getLog().warn(baos.toString(StandardCharsets.UTF_8.name())); + } catch (RuntimeException rte) { + throw rte; + } catch (Exception e) { + getLog().warn("Unable to print the files with unapproved licenses to the console."); + } + } - String msg = format("Counter(s) %s exceeded minimum or maximum values. See RAT report in: '%s'.", - String.join(", ", config.getClaimValidator().listIssues(statistics)), - getRatTxtFile()); + String msg = format("Counter(s) %s exceeded minimum or maximum values. See RAT report in: '%s'.", + String.join(", ", config.getClaimValidator().listIssues(statistics)), + getRatTxtFile()); if (!ignoreErrors) { throw new RatCheckException(msg); diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatReportMojo.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatReportMojo.java index 1e5a0f58..717a53c1 100644 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatReportMojo.java +++ b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/mp/RatReportMojo.java @@ -20,8 +20,13 @@ package org.apache.rat.mp; import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStreamWriter; +import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -31,10 +36,14 @@ import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + import org.apache.maven.artifact.Artifact; +import org.apache.maven.doxia.module.xhtml5.Xhtml5Parser; +import org.apache.maven.doxia.parser.ParseException; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkFactory; -import org.apache.maven.doxia.sink.impl.SinkEventAttributeSet; import org.apache.maven.doxia.site.SiteModel; import org.apache.maven.doxia.siterenderer.DocumentRenderingContext; import org.apache.maven.doxia.siterenderer.Renderer; @@ -51,15 +60,13 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.reporting.MavenMultiPageReport; import org.apache.maven.reporting.MavenReportException; -import org.apache.rat.ReportConfiguration; import org.apache.rat.Reporter; -import org.apache.rat.VersionInfo; import org.apache.rat.api.RatException; -import org.apache.rat.license.LicenseSetFactory.LicenseFilter; -import org.apache.rat.utils.DefaultLog; +import org.apache.rat.commandline.StyleSheets; import org.codehaus.plexus.util.ReaderFactory; import org.eclipse.aether.repository.ArtifactRepository; import org.eclipse.aether.repository.RemoteRepository; +import org.xml.sax.SAXException; import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; @@ -181,7 +188,6 @@ public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageRepo // render report getSiteRenderer().mergeDocumentIntoSite(writer, sink, siteContext); } - } // copy generated resources also @@ -403,6 +409,17 @@ public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageRepo return !skip; } + Reporter.Output readReportFile() throws MavenReportException { + File f = new File(outputDirectory, ".rat.xml"); + try (InputStream inputStream = new FileInputStream(f)) { + return new Reporter.Output(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream)); + } catch (FileNotFoundException e) { + throw new MavenReportException("Can not find RAT report file. Was reporter executed?"); + } catch (IOException | ParserConfigurationException | SAXException e) { + throw new MavenReportException("Can not read RAT report file."); + } + } + /** * Writes the report to the Doxia sink. * @@ -430,33 +447,15 @@ public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageRepo sink.link(bundle.getString("report.rat.url")); sink.text(bundle.getString("report.rat.fullName")); sink.link_(); - sink.text(" " + new VersionInfo(RatReportMojo.class)); - sink.text("."); - sink.paragraph_(); - - sink.paragraph(); - sink.verbatim(new SinkEventAttributeSet()); - try (Writer logWriter = DefaultLog.getInstance().asWriter()) { - try { - ReportConfiguration config = getConfiguration(); - config.setFrom(getDefaultsBuilder().build()); - logLicenses(config.getLicenses(LicenseFilter.ALL)); - if (verbose) { - config.reportExclusions(logWriter); - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - config.setOut(() -> baos); - Reporter reporter = new Reporter(config); - reporter.output(); - if (verbose) { - reporter.writeSummary(logWriter); - } - sink.text(baos.toString(StandardCharsets.UTF_8.name())); - } catch (IOException | MojoExecutionException | RatException e) { - throw new MavenReportException(e.getMessage(), e); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + File f = new File(outputDirectory, ".rat.xhtml5"); + try { + readReportFile().format(StyleSheets.XHTML5.getStyleSheet(), () -> Files.newOutputStream(f.toPath())); + try (Reader reader = new InputStreamReader(Files.newInputStream(f.toPath()), StandardCharsets.UTF_8)) { + new Xhtml5Parser().parse(reader, sink); } - } catch (IOException e) { - DefaultLog.getInstance().warn("Unable to close log writer", e); + } catch (RatException | IOException | ParseException e) { + throw new MavenReportException("Unable to create report: " + e.getMessage(), e); } sink.verbatim_(); sink.paragraph_(); diff --git a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/package-info.java b/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/package-info.java deleted file mode 100644 index 5401f154..00000000 --- a/apache-rat-plugin-parent/impl/src/main/java/org/apache/rat/plugin/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one * - * or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information * - * regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the * - * "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, * - * software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * - * KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations * - * under the License. * - */ - -/** - * Generated classes that define the Maven plugin functionality of RAT. - */ -package org.apache.rat.plugin; - diff --git a/apache-rat-plugin-parent/pom.xml b/apache-rat-plugin-parent/pom.xml index d746bda7..73f6d871 100644 --- a/apache-rat-plugin-parent/pom.xml +++ b/apache-rat-plugin-parent/pom.xml @@ -24,7 +24,7 @@ </parent> <artifactId>apache-rat-plugin-parent</artifactId> <packaging>pom</packaging> - <name>Apache Creadur RAT::Plugin4Maven</name> + <name>Apache Creadur RAT::Maven plugin parent</name> <description>A plugin for Apache Maven that runs Apache RAT to audit the source to be distributed.</description> <inceptionYear>2007</inceptionYear> @@ -45,6 +45,17 @@ </modules> <dependencyManagement> <dependencies> + <dependency> + <groupId>org.apache.rat</groupId> + <artifactId>apache-rat-core</artifactId> + <version>${rat.version}</version> + </dependency> + <dependency> + <groupId>org.apache.rat</groupId> + <artifactId>apache-rat-core-tests</artifactId> + <version>${rat.version}</version> + <scope>test</scope> + </dependency> <dependency> <groupId>org.apache.maven.plugin-tools</groupId> <artifactId>maven-plugin-annotations</artifactId> diff --git a/apache-rat-plugin-parent/tools/pom.xml b/apache-rat-plugin-parent/tools/pom.xml index ed2ee557..a3943bf9 100644 --- a/apache-rat-plugin-parent/tools/pom.xml +++ b/apache-rat-plugin-parent/tools/pom.xml @@ -24,7 +24,7 @@ </parent> <artifactId>apache-rat-plugin-tools</artifactId> <packaging>jar</packaging> - <name>Apache Creadur RAT::Tools</name> + <name>Apache Creadur RAT::Maven plugin Tools</name> <description>Tools to manage and report on RAT for Maven</description> <properties> @@ -88,9 +88,6 @@ <plugin> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-maven-plugin</artifactId> - <configuration> - <excludeFilterFile>spotbugs-ignore.xml</excludeFilterFile> - </configuration> </plugin> </plugins> </build> @@ -107,7 +104,7 @@ <dependency> <groupId>org.apache.rat</groupId> <artifactId>apache-rat-core-tests</artifactId> - <version>${rat.version}</version> + <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.velocity.tools</groupId> diff --git a/apache-rat-plugin-parent/tools/spotbugs-ignore.xml b/apache-rat-plugin-parent/tools/spotbugs-ignore.xml new file mode 100644 index 00000000..39e672f5 --- /dev/null +++ b/apache-rat-plugin-parent/tools/spotbugs-ignore.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<FindBugsFilter> + +</FindBugsFilter> diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java new file mode 100644 index 00000000..008145cf --- /dev/null +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/CodeGenerator.java @@ -0,0 +1,224 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.rat.maven; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.WordUtils; +import org.apache.rat.DeprecationReporter; +import org.apache.rat.testhelpers.FileUtils; +import org.apache.rat.ui.OptionFactory; +import org.apache.rat.utils.CasedString; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeConstants; + +import static java.lang.String.format; +import static org.apache.rat.OptionCollection.ArgumentType.NONE; + +/** + * Generates the ${code org.apache.rat.maven.AbstractMaven} source code. + */ +public final class CodeGenerator { + /** The Syntax for this command */ + private static final String SYNTAX = String.format("java -cp ... %s [options]", CodeGenerator.class.getName()); + /** The package name for this AbstractMaven file */ + private final CasedString packageName = new CasedString(CasedString.StringCase.DOT, "org.apache.rat.maven");; + /** The base source directory */ + private final String baseDirectory; + /** The template for the methods within {@code AbstractMaven}. */ + private final Template methodTemplate; + /** The template for the {@code AbstractMaven.java} file */ + private final Template javaTemplate; + + /** + * private constructor. + * @param baseDirectory The base source directory. + */ + private CodeGenerator(final String baseDirectory) { + this.baseDirectory = baseDirectory; + + final VelocityEngine velocityEngine = new VelocityEngine(); + velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); + velocityEngine.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + velocityEngine.init(); + + // retrieve the templates + final String[] nameParts = CasedString.StringCase.DOT.getSegments(CodeGenerator.class.getName()); + final String templatePath = CasedString.StringCase.SLASH.assemble(Arrays.copyOf(nameParts, nameParts.length - 1)); + methodTemplate = velocityEngine.getTemplate(templatePath + "/AbstractMavenFunc.vm"); + javaTemplate = velocityEngine.getTemplate(templatePath + "/AbstractMaven.vm"); + } + + /** + * Gets the options for the command line. + * @return the command line options. + */ + private static Options getOptions() { + return new Options() + .addOption(Option.builder("h").longOpt("help").desc("Print this message").build()) + .addOption(Option.builder("p").longOpt("path").required().hasArg().desc("The path to the base of the generated java code directory").build()); + } + + /** + * Executable entry point. + * @param args the arguments for the executable + * @throws IOException on IO error. + */ + public static void main(final String[] args) throws IOException { + CommandLine commandLine = null; + try { + commandLine = DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter()) + .build().parse(getOptions(), args); + } catch (ParseException pe) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp(SYNTAX, pe.getMessage(), getOptions(), ""); + System.exit(1); + } + + if (commandLine.hasOption("h")) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp(SYNTAX, getOptions()); + System.exit(0); + } + CodeGenerator codeGenerator = new CodeGenerator(commandLine.getOptionValue("p")); + codeGenerator.execute(); + } + + /** + * Executes the code generation. + * @throws IOException on IO error + */ + private void execute() throws IOException { + final String methods = gatherMethods(); + final VelocityContext context = new VelocityContext(); + context.put("methods", methods); + File javaFile = Paths.get(baseDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)) + .resolve("AbstractMaven.java").toFile(); + FileUtils.mkDir(javaFile.getParentFile()); + try (FileWriter fileWriter = new FileWriter(javaFile)) { + javaTemplate.merge(context, fileWriter); + } + } + + /** + * Creates the description for a method. + * @param mavenOption the option generating the method. + * @return the description for the method in {@code AbstractMaven.java}. + */ + private String createDesc(final MavenOption mavenOption) { + String desc = mavenOption.getDescription(); + if (desc == null) { + throw new IllegalStateException(format("Description for %s may not be null", mavenOption.getName())); + } + if (!desc.contains(".")) { + throw new IllegalStateException(format("First sentence of description for %s must end with a '.'", mavenOption.getName())); + } + if (mavenOption.getArgType() != NONE) { + desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, mavenOption.hasArgs() ? "s" : "", + mavenOption.hasArgs() ? "" : "a ", mavenOption.getArgName()); + } + return desc; + } + + /** + * Gets the argument descrption for the method in {@code AbstractMaven.java}. + * @param mavenOption the maven option generating the method. + * @param desc the description of the argument. + * @return the argument description for the method in {@code AbstractMaven.java}. + */ + private String createArgDesc(final MavenOption mavenOption, final String desc) { + if (mavenOption.hasArg()) { + String argDesc = desc.substring(desc.indexOf(" ") + 1, desc.indexOf(".") + 1); + return WordUtils.capitalize(argDesc.substring(0, 1)) + argDesc.substring(1); + } else { + return "The state"; + } + } + + /** + * Gets method name for the method in {@code AbstractMaven.java}. + * @param mavenOption the maven option generating the method. + * @return the method name description for the method in {@code AbstractMaven.java}. + */ + private String createMethodName(final MavenOption mavenOption) { + String fname = WordUtils.capitalize(mavenOption.getName()); + return (mavenOption.hasArgs() && !(fname.endsWith("s") || fname.endsWith("Approved") || fname.endsWith("Denied"))) ? + fname + "s" : fname; + } + + /** + * Gets parameter annotation for the method in {@code AbstractMaven.java}. + * @param mavenOption the maven option generating the method. + * @param methodName the method name. + * @return the method name description for the method in {@code AbstractMaven.java}. + */ + private String createParameterAnnotation(final MavenOption mavenOption, final String methodName) { + StringBuilder sb = new StringBuilder("@Parameter"); + String property = mavenOption.hasArgs() ? null : format("property = \"rat.%s\"", methodName); + String defaultValue = mavenOption.isDeprecated() ? null : mavenOption.getDefaultValue(); + if (property != null || defaultValue != null) { + sb.append("("); + if (property != null) { + sb.append(property).append(defaultValue != null ? ", " : StringUtils.EMPTY); + } + if (defaultValue != null) { + sb.append(format("defaultValue = \"%s\"", defaultValue)); + } + sb.append(")"); + } + return sb.toString(); + } + + /** + * Gathers all method definitions into a single string. + * @return the definition of all the methods. + */ + private String gatherMethods() { + final VelocityContext context = new VelocityContext(); + final StringWriter methodWriter = new StringWriter(); + for (MavenOption mavenOption : OptionFactory.getOptions(MavenOption.FACTORY_CONFIG).collect(Collectors.toList())) { + context.put("option", mavenOption); + String desc = createDesc(mavenOption); + context.put("desc", desc); + context.put("argDesc", createArgDesc(mavenOption, desc)); + String functionName = createMethodName(mavenOption); + context.put("fname", functionName); + context.put("parameterAnnotation", createParameterAnnotation(mavenOption, functionName)); + context.put("args", (mavenOption.hasArg() ? "String" : "boolean") + (mavenOption.hasArgs() ? "[]" : "")); + + methodTemplate.merge(context, methodWriter); + } + return methodWriter.toString(); + } +} diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenGenerator.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenGenerator.java index 6020bcdd..c2aa2b36 100644 --- a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenGenerator.java +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenGenerator.java @@ -90,9 +90,9 @@ public final class MavenGenerator { for (Map.Entry<String, String> entry : MavenOption.getRenameMap().entrySet()) { writer.append(format(" xlateName.put(\"%s\", \"%s\");%n", entry.getKey(), entry.getValue())); } - for (Option option : MavenOption.getFilteredOptions()) { - writer.append(format(" unsupportedArgs.add(\"%s\");%n", argsKey(option))); - } +// for (Option option : MavenOption.getFilteredOptions()) { +// writer.append(format(" unsupportedArgs.add(\"%s\");%n", argsKey(option))); +// } for (MavenOption option : options) { if (option.isDeprecated()) { writer.append(format(" deprecatedArgs.put(\"%s\", \"%s\");%n", argsKey(option.getOption()), diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenOption.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenOption.java index 1327e00b..5c0d5633 100644 --- a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenOption.java +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/MavenOption.java @@ -30,11 +30,14 @@ import java.util.stream.Collectors; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; +import org.apache.commons.collections4.map.UnmodifiableMap; +import org.apache.commons.collections4.set.UnmodifiableSet; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.WordUtils; import org.apache.rat.OptionCollection; import org.apache.rat.commandline.Arg; import org.apache.rat.ui.AbstractOption; +import org.apache.rat.ui.OptionFactory; import org.apache.rat.utils.CasedString; import static java.lang.String.format; @@ -42,32 +45,45 @@ import static java.lang.String.format; /** * A representation of a CLI option as a Maven option */ -public class MavenOption extends AbstractOption<MavenOption> { +public final class MavenOption extends AbstractOption<MavenOption> { + /** * Default values for CLI options */ - static final Map<Arg, String> DEFAULT_VALUES = new HashMap<>(); + public static final UnmodifiableMap<Arg, String> DEFAULT_VALUES; /** * List of CLI options that are not supported by Maven. */ - static final Set<Option> UNSUPPORTED_LIST = new HashSet<>(); + public static final UnmodifiableSet<Option> UNSUPPORTED_SET; /** A mapping of external name to internal name if not standard. */ - static final Map<String, String> RENAME_MAP = new HashMap<>(); + public static final UnmodifiableMap<String, String> RENAME_MAP; /** The additional options for the maven plugin */ static final Options ADDITIONAL_OPTIONS = new Options(); /** * Filter to remove options not supported by Maven. */ - private static final Predicate<Option> MAVEN_FILTER; + static final Predicate<Option> MAVEN_FILTER; + /** + * The OptionFactory configuration for MavenOptions. + */ + public static final OptionFactory.Config<MavenOption> FACTORY_CONFIG; - static { - RENAME_MAP.put("addLicense", "add-license"); - DEFAULT_VALUES.put(Arg.OUTPUT_FILE, "${project.build.directory}/rat.txt"); - UNSUPPORTED_LIST.addAll(Arg.DIR.group().getOptions()); - UNSUPPORTED_LIST.addAll(Arg.LOG_LEVEL.group().getOptions()); - Set<Option> filteredOptions = getFilteredOptions(); - MAVEN_FILTER = option -> !(filteredOptions.contains(option) || option.getLongOpt() == null); + static { + HashMap<String, String> map = new HashMap<>(); + map.put("addLicense", "add-license"); + RENAME_MAP = (UnmodifiableMap<String, String>) UnmodifiableMap.unmodifiableMap(map); + HashMap<Arg, String> values = new HashMap<>(); + values.put(Arg.OUTPUT_FILE, "${project.build.directory}/rat.txt"); + DEFAULT_VALUES = (UnmodifiableMap<Arg, String>) UnmodifiableMap.unmodifiableMap(values); + + Set<Option> unsupportedOptions = new HashSet<>(); + unsupportedOptions.addAll(Arg.DIR.group().getOptions()); + unsupportedOptions.addAll(Arg.LOG_LEVEL.group().getOptions()); + UNSUPPORTED_SET = (UnmodifiableSet<Option>) UnmodifiableSet.unmodifiableSet(unsupportedOptions); + + MAVEN_FILTER = option -> !(UNSUPPORTED_SET.contains(option) || option.getLongOpt() == null); + FACTORY_CONFIG = new OptionFactory.Config<>(MavenOption.MAVEN_FILTER, MavenOption::new, MavenOption.ADDITIONAL_OPTIONS); } public static List<MavenOption> getMavenOptions() { @@ -88,15 +104,6 @@ public class MavenOption extends AbstractOption<MavenOption> { return Collections.unmodifiableMap(RENAME_MAP); } - /** - * Gets the set of options that are not supported by Maven. - * - * @return The set of options that are not supported by Maven. - */ - public static Set<Option> getFilteredOptions() { - return Collections.unmodifiableSet(UNSUPPORTED_LIST); - } - /** * Creates the Maven element name for the specified option. * @param option The option to process. @@ -171,7 +178,7 @@ public class MavenOption extends AbstractOption<MavenOption> { @Override public String getExample() { - if (UNSUPPORTED_LIST.contains(option)) { + if (UNSUPPORTED_SET.contains(option)) { return "-- not supported --"; } if (hasArg()) { diff --git a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java index b7a84dd5..a44a915a 100644 --- a/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java +++ b/apache-rat-plugin-parent/tools/src/main/java/org/apache/rat/maven/TestGenerator.java @@ -25,7 +25,6 @@ import java.io.StringWriter; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; -import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; @@ -45,17 +44,28 @@ import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; +/** + * Generates the Maven mojo tests. + */ public final class TestGenerator { + /** They syntax for this command */ private static final String SYNTAX = String.format("java -cp ... %s [options]", TestGenerator.class.getName()); + /** The velocity engine to generated files */ private final VelocityEngine velocityEngine; + /** The package name as a cased string */ private final CasedString packageName; + /** The resource directory where the test resources will be written */ private final String resourceDirectory; + /** The directory where the test classes will be written*/ private final String testDirectory; + /** The template for the pom.xml files */ private final Template pomTemplate; + /** The template for the test class file */ private final Template javaTemplate; - private final Template funcTemplate; + /** The template for the methods within the test class */ + private final Template methodTemplate; - private TestGenerator(String packageName, String resourceDirectory, String testDirectory) { + private TestGenerator(final String packageName, final String resourceDirectory, final String testDirectory) { this.packageName = new CasedString(CasedString.StringCase.DOT, packageName); this.resourceDirectory = resourceDirectory; this.testDirectory = testDirectory; @@ -71,18 +81,22 @@ public final class TestGenerator { pomTemplate = velocityEngine.getTemplate(casedTemplateName.toCase(CasedString.StringCase.SLASH) + ".vm"); nameParts[nameParts.length - 1] = "TestJava.vm"; javaTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); - nameParts[nameParts.length - 1] = "TestFunc.vm"; - funcTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); - } - - private Path testPath() { - return Paths.get(testDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)); + nameParts[nameParts.length - 1] = "TestMethod.vm"; + methodTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); } + /** + * Gets the resource path. + * @return the resource path. + */ private Path resourcePath() { return Paths.get(resourceDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)); } + /** + * Gets the command line options for this executable. + * @return the command line options. + */ private static Options getOptions() { return new Options() .addOption(Option.builder("r").longOpt("resources").required().hasArg().desc("The path to the base resource directory").build()) @@ -91,9 +105,13 @@ public final class TestGenerator { .addOption(Option.builder("p").longOpt("package").required().hasArg().desc("The package name to generate").build()); } - - - public static void main(final String[] args) throws IOException, ParseException { + /** + * The main code. + * + * @param args The arguments from the command line. + * @throws IOException on IO error. + */ + public static void main(final String[] args) throws IOException { CommandLine commandLine = null; try { @@ -114,25 +132,12 @@ public final class TestGenerator { commandLine.getOptionValue("r"), commandLine.getOptionValue("t")); testGenerator.execute(); -// -// // create the basePath -// final String packageName = args[1]; -// final CasedString casedPackageName = new CasedString(CasedString.StringCase.DOT, packageName); -// final Path basePath = Paths.get(args[0]).resolve(casedPackageName.toCase(CasedString.StringCase.SLASH)); -// -// VelocityEngine velocityEngine = initializeVelocityEngine(); -// -// // retrieve templates -// CasedString casedTemplateName = new CasedString(CasedString.StringCase.DOT, TestGenerator.class.getName()); -// String[] nameParts = Arrays.copyOf(casedTemplateName.getSegments(), casedTemplateName.getSegments().length); -// Template pomTemplate = velocityEngine.getTemplate(casedTemplateName.toCase(CasedString.StringCase.SLASH) + ".vm"); -// nameParts[nameParts.length - 1] = "TestJava.vm"; -// Template javaTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); -// nameParts[nameParts.length - 1] = "TestFunc.vm"; -// Template funcTemplate = velocityEngine.getTemplate(CasedString.StringCase.SLASH.assemble(nameParts)); - } + /** + * Execute the generation. + * @throws IOException on IO error. + */ private void execute() throws IOException { VelocityContext context = new VelocityContext(); context.put("packageName", packageName.toString()); @@ -144,7 +149,12 @@ public final class TestGenerator { writeTestFile(context); } - private void writeTestFile(VelocityContext context) throws IOException { + /** + * Write the {@code MavenTest.java} file + * @param context + * @throws IOException + */ + private void writeTestFile(final VelocityContext context) throws IOException { File javaFile = Paths.get(testDirectory).resolve(packageName.toCase(CasedString.StringCase.SLASH)) .resolve("MavenTest.java").toFile(); try (FileWriter fileWriter = new FileWriter(javaFile)) { @@ -152,11 +162,18 @@ public final class TestGenerator { } } - private String writeTestPoms(VelocityContext context) throws IOException { + /** + * Write the test poms for all the supported options. + * Generates method definitions (one for each pom file) to be included in {@code MavenTest.java}. + * @param context het velocity context. + * @return a String comprising all the method definitions. + * @throws IOException + */ + private String writeTestPoms(final VelocityContext context) throws IOException { StringWriter funcCode = new StringWriter(); - for (final TestData testData : new ReportTestDataProvider().getOptionTests(MavenOption.UNSUPPORTED_LIST)) { + for (final TestData testData : new ReportTestDataProvider().getOptionTests(MavenOption.UNSUPPORTED_SET)) { context.put("pomFile", testData.getTestName() + "/pom.xml"); Path testPath = resourcePath().resolve(testData.getTestName()); context.put("baseDir", testPath.toFile().getAbsolutePath()); @@ -181,10 +198,9 @@ public final class TestGenerator { pomTemplate.merge(context, writer); } - funcTemplate.merge(context, funcCode); + methodTemplate.merge(context, funcCode); } return funcCode.toString(); } - } diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMaven.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMaven.vm new file mode 100644 index 00000000..cdc14c26 --- /dev/null +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMaven.vm @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.rat.maven; + +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.rat.ui.OptionFactory; +import org.apache.rat.ui.SetArgs; +import org.apache.rat.utils.CasedString; + +import java.util.List; +import java.util.stream.Collectors; + +/* DO NOT EDIT - GENERATED FILE */ + +/** + * Generated class to provide Maven support for standard RAT command line options + */ +public abstract class AbstractMaven extends AbstractMojo { + + protected final SetArgs setArgs; + + protected AbstractMaven() { + List<MavenOption> mavenList = OptionFactory.getOptions(MavenOption.FACTORY_CONFIG).collect(Collectors.toList()); + setArgs = new SetArgs(MavenOption.RENAME_MAP, mavenList); + } + + + /** + * Creates a kebab case name from a camel case name. + * @param camelCase the camel case name to convert. + * @return the kebab format. + */ + public static String toKebabForm(String camelCase) { + return new CasedString(CasedString.StringCase.CAMEL, camelCase).toCase(CasedString.StringCase.KEBAB); + } + + + /* GENERATED METHODS */ + +${methods} +} diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMavenFunc.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMavenFunc.vm new file mode 100644 index 00000000..e7a940d2 --- /dev/null +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/AbstractMavenFunc.vm @@ -0,0 +1,44 @@ +#* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *# + /** + * ${desc} + * @param ${option.getName} ${argDesc} +#if (${option.isDeprecated}) + * @deprecated ${option.getDeprecated} +#end + */ +#if (${option.isDeprecated}) + @Deprecated +#end + ${parameterAnnotation} + public void set${fname}(${args} ${option.getName}) { +#if (${option.hasArg}) + #if (${option.hasArgs}) + setArgs.addArg("${option.keyValue}", ${option.getName}); + #else + setArgs.setArg("${option.keyValue}", ${option.getName}); + #end +#else + if (${option.getName}) { + setArgs.setArg("${option.keyValue}", null); + } else { + setArgs.removeArg("${option.keyValue}"); + } +#end + } diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestFunc.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestFunc.vm deleted file mode 100644 index 4e1fd514..00000000 --- a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestFunc.vm +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Generated test for ${testName} - */ -@Test -@InjectMojo(goal = "validate", pom = "${pomFile}") -public void ${funcName}Test(RatCheckMojo mojo) { - TestData testData = testDataMap.get("${testName}"); - ValidatorData validatorData = new ValidatorData(mojo.getOutput(), mojo.getConfiguration(), "${baseDir}"); - testData.getValidator().accept(validatorData); -} diff --git a/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm new file mode 100644 index 00000000..304e5318 --- /dev/null +++ b/apache-rat-plugin-parent/tools/src/main/resources/org/apache/rat/maven/TestMethod.vm @@ -0,0 +1,28 @@ +#* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + *# +/** + * Generated test for ${testName} + */ +@Test +@InjectMojo(goal = "validate", pom = "${pomFile}") +public void ${funcName}Test(RatCheckMojo mojo) { + TestData testData = testDataMap.get("${testName}"); + ValidatorData validatorData = new ValidatorData(mojo.getOutput(), mojo.getConfiguration(), "${baseDir}"); + testData.getValidator().accept(validatorData); +} diff --git a/apache-rat-plugin-parent/tools/src/test/java/org/apache/rat/maven/MavenTest.java b/apache-rat-plugin-parent/tools/src/test/java/org/apache/rat/maven/MavenTest.java deleted file mode 100644 index c7dce2da..00000000 --- a/apache-rat-plugin-parent/tools/src/test/java/org/apache/rat/maven/MavenTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.apache.rat.maven;/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Fail.fail; - -import java.nio.file.Path; -import java.util.Map; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; -import org.apache.maven.api.plugin.testing.InjectMojo; -import org.apache.maven.api.plugin.testing.MojoTest; -import org.apache.rat.testhelpers.data.ReportTestDataProvider; -import org.apache.rat.testhelpers.data.TestData; -import org.apache.rat.testhelpers.data.ValidatorData; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledOnOs; -import org.junit.jupiter.api.condition.OS; -import org.junit.jupiter.api.io.TempDir; - -@MojoTest -public class MavenTest { - - @TempDir - static Path tempDir; - - static ReportTestDataProvider reportTestDataProvider = new ReportTestDataProvider(); - - - final Map<String, TestData> testDataMap = reportTestDataProvider.getOptionTestMap(MavenOption.UNSUPPORTED_LIST); - - private final static XPath xPath = XPathFactory.newInstance().newXPath(); - - @AfterAll - @EnabledOnOs(OS.WINDOWS) - static void cleanup() { - System.gc(); // hacky workaround for windows bug. - } - - @Test - @InjectMojo(goal = "validate", pom = "${pomFile}") - public void ${testName}Test(RatCheckMojo mojo) { - TestData testData = testDataMap.get(${testName}); - ValidatorData validatorData = new ValidatorData(mojo.getOutput(), mojo.getConfiguration(), ${baseDir}); - testData.getValidator().accept(validatorData); - } -} diff --git a/pom.xml b/pom.xml index 10aa1f14..5adf0270 100644 --- a/pom.xml +++ b/pom.xml @@ -974,7 +974,6 @@ agnostic home for software distribution comprehension and audit tools. <module>apache-rat-plugin-parent</module> <module>apache-rat-tasks</module> <module>apache-rat</module> - <module>apache-rat-tools</module> </modules> <licenses> <license>
