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 39bf463ca..d92d6a0fe 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 @@ -23,10 +23,7 @@ import java.io.PrintWriter; import java.io.Serializable; import java.util.Arrays; -import java.util.Collections; import java.util.Comparator; -import java.util.Map; -import java.util.TreeMap; import java.util.function.Consumer; import java.util.function.Supplier; import java.util.stream.Collectors; @@ -88,11 +85,32 @@ private static String asString(final Object[] args) { * @param helpCmd the help command to run when necessary. * @return a ReportConfiguration or {@code null} if Help was printed. * @throws IOException on error. + * @throws ParseException on option parsing error. */ - public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer helpCmd) throws IOException { + public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, final Consumer helpCmd) + throws IOException, ParseException { return parseCommands(workingDirectory, args, helpCmd, false); } + /** + * Parse the options into the command line. + * @param opts the option definitions. + * @param args the argument to apply the definitions to. + * @return the CommandLine + * @throws ParseException on option parsing error. + */ + //@VisibleForTesting + static CommandLine parseCommandLine(final Options opts, final String[] args) throws ParseException { + try { + return DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter()) + .setAllowPartialMatching(true).build().parse(opts, args); + } catch (ParseException e) { + DefaultLog.getInstance().error(e.getMessage()); + DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e); + throw e; + } + } + /** * Parses the standard options to create a ReportConfiguration. * @@ -104,20 +122,11 @@ public static ReportConfiguration parseCommands(final File workingDirectory, fin * @throws IOException on error. */ public static ReportConfiguration parseCommands(final File workingDirectory, final String[] args, - final Consumer helpCmd, final boolean noArgs) throws IOException { + final Consumer helpCmd, final boolean noArgs) throws IOException, ParseException { Options opts = buildOptions(); - CommandLine commandLine; - try { - commandLine = DefaultParser.builder().setDeprecatedHandler(DeprecationReporter.getLogReporter()) - .setAllowPartialMatching(true).build().parse(opts, args); - } catch (ParseException e) { - DefaultLog.getInstance().error(e.getMessage()); - DefaultLog.getInstance().error("Please use the \"--help\" option to see a list of valid commands and options.", e); - System.exit(1); - return null; // dummy return (won't be reached) to avoid Eclipse complaint about possible NPE - // for "commandLine" - } + CommandLine commandLine = parseCommandLine(buildOptions(), args); + Arg.processLogLevel(commandLine); @@ -157,13 +166,6 @@ static ReportConfiguration createConfiguration(final ArgumentContext argumentCon argumentContext.processArgs(); final ReportConfiguration configuration = argumentContext.getConfiguration(); final CommandLine commandLine = argumentContext.getCommandLine(); - if (Arg.DIR.isSelected()) { - try { - configuration.addSource(getReportable(commandLine.getParsedOptionValue(Arg.DIR.getSelected()), configuration)); - } catch (ParseException e) { - throw new ConfigurationException("Unable to set parse " + Arg.DIR.getSelected(), e); - } - } for (String s : commandLine.getArgs()) { IReportable reportable = getReportable(new File(s), configuration); if (reportable != null) { diff --git a/apache-rat-core/src/main/java/org/apache/rat/Report.java b/apache-rat-core/src/main/java/org/apache/rat/Report.java index 5f5f4cb35..6e69cf547 100644 --- a/apache-rat-core/src/main/java/org/apache/rat/Report.java +++ b/apache-rat-core/src/main/java/org/apache/rat/Report.java @@ -21,6 +21,7 @@ import java.io.File; import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; import org.apache.rat.document.RatDocumentAnalysisException; import org.apache.rat.help.Help; import org.apache.rat.utils.DefaultLog; @@ -48,19 +49,23 @@ public static void main(final String[] args) throws Exception { System.exit(0); } - ReportConfiguration configuration = OptionCollection.parseCommands(new File("."), args, Report::printUsage); - if (configuration != null) { - configuration.validate(DefaultLog.getInstance()::error); - Reporter reporter = new Reporter(configuration); - reporter.output(); - reporter.writeSummary(DefaultLog.getInstance().asWriter()); + try { + ReportConfiguration configuration = OptionCollection.parseCommands(new File("."), args, Report::printUsage); + if (configuration != null) { + configuration.validate(DefaultLog.getInstance()::error); + Reporter reporter = new Reporter(configuration); + reporter.output(); + reporter.writeSummary(DefaultLog.getInstance().asWriter()); - if (configuration.getClaimValidator().hasErrors()) { - configuration.getClaimValidator().logIssues(reporter.getClaimsStatistic()); - throw new RatDocumentAnalysisException(format("Issues with %s", - String.join(", ", - configuration.getClaimValidator().listIssues(reporter.getClaimsStatistic())))); + if (configuration.getClaimValidator().hasErrors()) { + configuration.getClaimValidator().logIssues(reporter.getClaimsStatistic()); + throw new RatDocumentAnalysisException(format("Issues with %s", + String.join(", ", + configuration.getClaimValidator().listIssues(reporter.getClaimsStatistic())))); + } } + } catch (ParseException e) { + System.exit(1); } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java index 87f7cd967..c5d947760 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/OptionCollectionTest.java @@ -30,7 +30,9 @@ import java.util.TreeMap; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.DeprecatedAttributes; import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.tuple.Pair; import org.apache.rat.commandline.ArgumentContext; @@ -177,38 +179,24 @@ void cleanUp() { } @Test - public void testDeprecatedUseLogged() throws IOException { - TestingLog log = new TestingLog(); - try { - DefaultLog.setInstance(log); - String[] args = {"--dir", "target", "-a"}; - ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, o -> fail("Help printed"), true); - assertThat(config).isNotNull(); - } finally { - DefaultLog.setInstance(null); - } - log.assertContainsExactly(1, "WARN: Option [-d, --dir] used. Deprecated for removal since 0.17: Use the standard '--'"); - log.assertContainsExactly(1, "WARN: Option [-a] used. Deprecated for removal since 0.17: Use --edit-license"); - } + public void testDeprecatedUseLogged() throws ParseException { + Options opts = OptionCollection.buildOptions(); + opts.addOption(Option.builder().longOpt("deprecated-option").deprecated(DeprecatedAttributes.builder().setDescription("Deprecation reason.") + .setForRemoval(true).setSince("1.0.0-SNAPSHOT").get()).build()); - @Test - public void testDirOptionCapturesDirectoryToScan() throws IOException { TestingLog log = new TestingLog(); - ReportConfiguration config; try { DefaultLog.setInstance(log); - String[] args = {"--dir", testPath.toFile().getAbsolutePath()}; - config = OptionCollection.parseCommands(testPath.toFile(), args, (o) -> { - }, true); + CommandLine commandLine = OptionCollection.parseCommandLine(opts, new String[]{"--deprecated-option", "."}); + commandLine.hasOption("--deprecated-option"); } finally { DefaultLog.setInstance(null); } - assertThat(config).isNotNull(); - log.assertContainsExactly(1,"WARN: Option [-d, --dir] used. Deprecated for removal since 0.17: Use the standard '--'"); + log.assertContainsExactly(1, "WARN: Option [--deprecated-option] used. Deprecated for removal since 1.0.0-SNAPSHOT: Deprecation reason."); } @Test - public void testShortenedOptions() throws IOException { + public void testShortenedOptions() throws IOException, ParseException { String[] args = {"--output-lic", "ALL"}; ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, (o) -> { }, true); @@ -227,7 +215,7 @@ public void testDefaultConfiguration() throws ParseException { @ParameterizedTest @ValueSource(strings = { ".", "./", "target", "./target" }) - public void getReportableTest(String fName) throws IOException { + public void getReportableTest(String fName) throws IOException, ParseException { File base = new File(fName); String expected = DocumentName.FSInfo.getDefault().normalize(base.getAbsolutePath()); ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), new String[]{fName}, o -> fail("Help called"), false); @@ -263,7 +251,7 @@ public void helpTest() { ReportConfiguration config = OptionCollection.parseCommands(testPath.toFile(), args, o -> helpCalled.set(true), true); assertThat(config).as("Should not have config").isNull(); assertThat(helpCalled.get()).as("Help was not called").isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -282,7 +270,7 @@ public CliOptionsProvider() { * @return A ReportConfiguration * @throws IOException on critical error. */ - protected final ReportConfiguration generateConfig(List> args) throws IOException { + protected final ReportConfiguration generateConfig(List> args) throws IOException, ParseException { helpCalled.set(false); List sArgs = new ArrayList<>(); for (Pair pair : args) { diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java index 8ff47a287..82343cf90 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReportConfigurationTest.java @@ -36,9 +36,11 @@ import java.net.URL; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.SortedSet; import java.util.function.Function; +import java.util.stream.Collectors; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.apache.rat.ReportConfiguration.NoCloseOutputStream; @@ -662,52 +664,54 @@ public void licenseDuplicateOptionsTest() { .isExactlyInstanceOf(IllegalArgumentException.class); } + /** * Validates that the configuration contains the default approved licenses. * @param config The configuration to test. */ - public static void validateDefaultApprovedLicenses(ReportConfiguration config) { - validateDefaultApprovedLicenses(config, 0); + public static void validateDefaultApprovedLicenses(ReportConfiguration config, String... additionalIds) { + validateLicenses(config, Arrays.asList(additionalIds), LicenseFilter.APPROVED, XMLConfigurationReaderTest.APPROVED_LICENSES); } - + /** - * Validates that the configuration contains the default approved licenses. - * @param config The configuration to test. + * Validates that the configuration contains all the default licenses along with any addiitonal licenses + * @param config the configuration to test. + * @param additionalLicenses Additional licence IDs that are expected. */ - public static void validateDefaultApprovedLicenses(ReportConfiguration config, int additionalIdCount) { - assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).hasSize(XMLConfigurationReaderTest.APPROVED_IDS.length + additionalIdCount); - for (String s : XMLConfigurationReaderTest.APPROVED_IDS) { - assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).contains(ILicenseFamily.makeCategory(s)); - } + public static void validateDefaultLicenses(ReportConfiguration config, String...additionalLicenses) { + validateLicenses(config, Arrays.asList(additionalLicenses), LicenseFilter.ALL, XMLConfigurationReaderTest.EXPECTED_LICENSES); } + private static void validateLicenses(ReportConfiguration config, List additionalIds, LicenseFilter filter, String[] approvedIds) { + List expected = new ArrayList<>(Arrays.asList(approvedIds)); + expected.addAll(additionalIds); + assertThat(config.getLicenses(filter).stream().map(ILicense::getId).collect(Collectors.toSet())).containsExactlyInAnyOrderElementsOf(expected); + } + + /** * Validates that the configuration contains the default license families. * @param config the configuration to test. */ public static void validateDefaultLicenseFamilies(ReportConfiguration config, String...additionalIds) { - assertThat(config.getLicenseFamilies(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_IDS.length + additionalIds.length); - List expected = new ArrayList<>(); - expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_IDS)); - expected.addAll(Arrays.asList(additionalIds)); - for (ILicenseFamily family : config.getLicenseFamilies(LicenseFilter.ALL)) { - assertThat(expected).contains(family.getFamilyCategory().trim()); - } + validateLicenseFamilies(config, Arrays.asList(additionalIds), LicenseFilter.ALL, XMLConfigurationReaderTest.EXPECTED_IDS); } /** - * Validates that the configuration contains the default licenses. + * Validates that the configuration contains the default license families. * @param config the configuration to test. */ - public static void validateDefaultLicenses(ReportConfiguration config, String...additionalLicenses) { - assertThat(config.getLicenses(LicenseFilter.ALL)).hasSize(XMLConfigurationReaderTest.EXPECTED_LICENSES.length + additionalLicenses.length); - List expected = new ArrayList<>(); - expected.addAll(Arrays.asList(XMLConfigurationReaderTest.EXPECTED_LICENSES)); - expected.addAll(Arrays.asList(additionalLicenses)); - for (ILicense license : config.getLicenses(LicenseFilter.ALL)) { - assertThat(expected).contains(license.getId()); - } + public static void validateDefaultApprovedLicenseFamilies(ReportConfiguration config, String...additionalIds) { + validateLicenseFamilies(config, Arrays.asList(additionalIds), LicenseFilter.APPROVED, XMLConfigurationReaderTest.APPROVED_IDS); } + + private static void validateLicenseFamilies(ReportConfiguration config, List additionalIds, LicenseFilter filter, String[] approvedIds) { + List expected = new ArrayList<>(Arrays.asList(approvedIds)); + expected.addAll(additionalIds); + assertThat(config.getLicenseFamilies(filter).stream().map(lf -> lf.getFamilyCategory().trim()) + .collect(Collectors.toSet())).containsExactlyInAnyOrderElementsOf(expected); + } + /** * Validates that the configuration matches the default. @@ -719,9 +723,10 @@ public static void validateDefault(ReportConfiguration config) { assertThat(config.getCopyrightMessage()).isNull(); assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull(); - validateDefaultApprovedLicenses(config); validateDefaultLicenseFamilies(config); + validateDefaultApprovedLicenseFamilies(config); validateDefaultLicenses(config); + validateDefaultApprovedLicenses(config); } /** diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java index 6cf7b458a..25f0dba74 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsProvider.java @@ -39,6 +39,7 @@ import javax.xml.xpath.XPathFactory; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -62,7 +63,6 @@ import org.apache.rat.testhelpers.XmlUtils; import org.apache.rat.utils.DefaultLog; import org.apache.rat.utils.Log; -import org.junit.jupiter.params.provider.ArgumentsProvider; import org.w3c.dom.Document; import org.xml.sax.SAXException; @@ -73,7 +73,7 @@ /** * A class to provide the Options and tests to the testOptionsUpdateConfig. */ -class ReporterOptionsProvider extends AbstractOptionsProvider implements ArgumentsProvider { +class ReporterOptionsProvider extends AbstractOptionsProvider { static File sourceDir; /** @@ -84,9 +84,6 @@ class ReporterOptionsProvider extends AbstractOptionsProvider implements Argumen public ReporterOptionsProvider() { super(ReporterOptionsTest.testPath.toFile()); processTestFunctionAnnotations(); - testMap.put("addLicense", this::addLicenseTest); - testMap.remove("add-license"); - testMap.put("dir", () -> DefaultLog.getInstance().info("--dir has no valid test")); super.validate(Collections.emptyList()); } @@ -99,11 +96,11 @@ public ReporterOptionsProvider() { * @throws IOException on critical error. */ @Override - protected final ReportConfiguration generateConfig(List> args) throws IOException { + protected final ReportConfiguration generateConfig(List> args) throws IOException, ParseException { return generateConfig(args, false); } - protected final ReportConfiguration generateConfig(List> args, boolean helpExpected) throws IOException { + protected final ReportConfiguration generateConfig(List> args, boolean helpExpected) throws IOException, ParseException { if (sourceDir == null) { throw new IOException("sourceDir not set"); } @@ -121,7 +118,7 @@ private void configureSourceDir(Option option) { FileUtils.mkDir(sourceDir); } - private void validateNoArgSetup() throws IOException, RatException { + private void validateNoArgSetup() throws IOException, ParseException, RatException { // verify that without args the report is ok. TestingLog log = new TestingLog(); DefaultLog.setInstance(log); @@ -137,11 +134,6 @@ private void validateNoArgSetup() throws IOException, RatException { } - @OptionCollectionTest.TestFunction - protected void addLicenseTest() { - editLicenseTest(Arg.EDIT_ADD.find("addLicense")); - } - @OptionCollectionTest.TestFunction protected void editLicenseTest() { editLicenseTest(Arg.EDIT_ADD.find("edit-license")); @@ -181,7 +173,7 @@ private void editLicenseTest(final Option option) { " * under the License.\n" + " */\n\n" + "class NoLicense {}"); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -213,7 +205,7 @@ private void execLicensesDeniedTest(final Option option, final String[] args) { ClaimStatistic claimStatistic = reporter.execute(); ClaimValidator validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).containsExactly("UNAPPROVED"); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -248,16 +240,11 @@ private void noDefaultsTest(final Option option) { ClaimValidator validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).containsExactlyInAnyOrder("DOCUMENT_TYPES", "LICENSE_CATEGORIES", "LICENSE_NAMES", "STANDARDS"); } - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void noDefaultLicensesTest() { - noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("no-default-licenses")); - } - @OptionCollectionTest.TestFunction protected void configurationNoDefaultsTest() { noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("configuration-no-defaults")); @@ -284,7 +271,7 @@ protected void counterMaxTest() { claimStatistic = reporter.execute(); validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).isEmpty(); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -311,7 +298,7 @@ protected void counterMinTest() { claimStatistic = reporter.execute(); validator = config.getClaimValidator(); assertThat(validator.listIssues(claimStatistic)).isEmpty(); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -340,7 +327,7 @@ private void execExcludeTest(final Option option, final String[] args) { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(3); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -351,21 +338,11 @@ private void excludeFileTest(final Option option) { execExcludeTest(option, new String[]{outputFile.getAbsolutePath()}); } - @OptionCollectionTest.TestFunction - protected void excludeFileTest() { - excludeFileTest(Arg.EXCLUDE_FILE.find("exclude-file")); - } - @OptionCollectionTest.TestFunction protected void inputExcludeFileTest() { excludeFileTest(Arg.EXCLUDE_FILE.find("input-exclude-file")); } - @OptionCollectionTest.TestFunction - protected void excludeTest() { - execExcludeTest(Arg.EXCLUDE.find("exclude"), EXCLUDE_ARGS); - } - @OptionCollectionTest.TestFunction protected void inputExcludeTest() { execExcludeTest(Arg.EXCLUDE.find("input-exclude"), EXCLUDE_ARGS); @@ -394,7 +371,7 @@ protected void inputExcludeSizeTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -429,7 +406,7 @@ protected void inputExcludeStdTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(4); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(5); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -488,7 +465,7 @@ protected void inputExcludeParsedScmTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(8); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -526,7 +503,7 @@ private void execIncludeTest(final Option option, final String[] args) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(3); // .gitignore is ignored by default as it is hidden but not counted assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -541,16 +518,6 @@ protected void inputIncludeFileTest() { includeFileTest(Arg.INCLUDE_FILE.find("input-include-file")); } - @OptionCollectionTest.TestFunction - protected void includesFileTest() { - includeFileTest(Arg.INCLUDE_FILE.find("includes-file")); - } - - @OptionCollectionTest.TestFunction - protected void includeTest() { - execIncludeTest(Arg.INCLUDE.find("include"), INCLUDE_ARGS); - } - @OptionCollectionTest.TestFunction protected void inputIncludeTest() { execIncludeTest(Arg.INCLUDE.find("input-include"), INCLUDE_ARGS); @@ -586,7 +553,7 @@ protected void inputIncludeStdTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(7); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -612,7 +579,7 @@ protected void inputSourceTest() { claimStatistic = reporter.execute(); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -646,7 +613,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -686,7 +653,7 @@ private void execLicenseFamiliesDeniedTest(final Option option, final String[] a assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -740,16 +707,11 @@ private void configTest(final Option option) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void licensesTest() { - configTest(Arg.CONFIGURATION.find("licenses")); - } - @OptionCollectionTest.TestFunction protected void configTest() { configTest(Arg.CONFIGURATION.find("config")); @@ -780,7 +742,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } @@ -798,37 +760,37 @@ protected void licensesApprovedTest() { new String[]{"GPL1"}); } - @OptionCollectionTest.TestFunction - protected void scanHiddenDirectoriesTest() { - Option option = Arg.INCLUDE_STD.find("scan-hidden-directories"); - Pair arg1 = ImmutablePair.of(option, null); - - try { - configureSourceDir(option); - - writeFile("apl.txt", "SPDX-License-Identifier: Apache-2.0"); - - File hiddenDir = new File(sourceDir, ".hiddendir"); - FileUtils.mkDir(hiddenDir); - FileUtils.writeFile(hiddenDir, "gpl.txt", Collections.singletonList("SPDX-License-Identifier: GPL-1.0-only")); - - ReportConfiguration config = generateConfig(); - Reporter reporter = new Reporter(config); - ClaimStatistic claimStatistic = reporter.execute(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); - - config = generateConfig(arg1); - reporter = new Reporter(config); - claimStatistic = reporter.execute(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - } catch (IOException | RatException e) { - fail(e.getMessage(), e); - } - } +// @OptionCollectionTest.TestFunction +// protected void inputIncludeStdTest() { +// Option option = Arg.INCLUDE_STD.find("input-include-std"); +// Pair arg1 = ImmutablePair.of(option, "HIDDEN_DIR"); +// +// try { +// configureSourceDir(option); +// +// writeFile("apl.txt", "SPDX-License-Identifier: Apache-2.0"); +// +// File hiddenDir = new File(sourceDir, ".hiddendir"); +// FileUtils.mkDir(hiddenDir); +// FileUtils.writeFile(hiddenDir, "gpl.txt", Collections.singletonList("SPDX-License-Identifier: GPL-1.0-only")); +// +// ReportConfiguration config = generateConfig(); +// Reporter reporter = new Reporter(config); +// ClaimStatistic claimStatistic = reporter.execute(); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(0); +// +// config = generateConfig(arg1); +// reporter = new Reporter(config); +// claimStatistic = reporter.execute(); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(2); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(1); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); +// } catch (IOException | RatException e) { +// fail(e.getMessage(), e); +// } +// } private void outTest(final Option option) { try { @@ -849,16 +811,11 @@ private void outTest(final Option option) { TextUtils.assertContainsExactly(1, "Apache License 2.0: 1 ", actualText); TextUtils.assertContainsExactly(1, "STANDARD: 1 ", actualText); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void outTest() { - outTest(Arg.OUTPUT_FILE.find("out")); - } - @OptionCollectionTest.TestFunction protected void outputFileTest() { outTest(Arg.OUTPUT_FILE.find("output-file")); @@ -920,58 +877,53 @@ private void styleSheetTest(final Option option) { String actualText = baos.toString(StandardCharsets.UTF_8.name()); TextUtils.assertContainsExactly(1, "Hello world", actualText); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); } } - @OptionCollectionTest.TestFunction - protected void stylesheetTest() { - styleSheetTest(Arg.OUTPUT_STYLE.find("stylesheet")); - } - @OptionCollectionTest.TestFunction protected void outputStyleTest() { styleSheetTest(Arg.OUTPUT_STYLE.find("output-style")); } - @OptionCollectionTest.TestFunction - protected void xmlTest() { - PrintStream origin = System.out; - Option option = Arg.OUTPUT_STYLE.find("xml"); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (PrintStream out = new PrintStream(baos)) { - System.setOut(out); - configureSourceDir(option); - // create a dummy stylesheet so that we match the stylesheet tests. - File file = writeFile("stylesheet", "\n" + - " \n" + - " Hello world\n" + - " \n" + - ""); - - ReportConfiguration config = generateConfig(ImmutablePair.of(option, null)); - Reporter reporter = new Reporter(config); - ClaimStatistic claimStatistic = reporter.output(); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0); - assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); - - String actualText = baos.toString(StandardCharsets.UTF_8.name()); - TextUtils.assertContainsExactly(1, "", actualText); - - try (InputStream expected = StyleSheets.getStyleSheet("xml").get(); - InputStream actual = config.getStyleSheet().get()) { - assertThat(IOUtils.contentEquals(expected, actual)).as("'xml' does not match").isTrue(); - } - } catch (IOException | RatException e) { - fail(e.getMessage(), e); - } finally { - System.setOut(origin); - } - } +// @OptionCollectionTest.TestFunction +// protected void xmlTest() { +// PrintStream origin = System.out; +// Option option = Arg.OUTPUT_STYLE.find("output-style"); +// ByteArrayOutputStream baos = new ByteArrayOutputStream(); +// try (PrintStream out = new PrintStream(baos)) { +// System.setOut(out); +// configureSourceDir(option); +// // create a dummy stylesheet so that we match the stylesheet tests. +// File file = writeFile("stylesheet", "\n" + +// " \n" + +// " Hello world\n" + +// " \n" + +// ""); +// +// ReportConfiguration config = generateConfig(ImmutablePair.of(option, null)); +// Reporter reporter = new Reporter(config); +// ClaimStatistic claimStatistic = reporter.output(); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(1); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.APPROVED)).isEqualTo(0); +// assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(1); +// +// String actualText = baos.toString(StandardCharsets.UTF_8.name()); +// TextUtils.assertContainsExactly(1, "", actualText); +// +// try (InputStream expected = StyleSheets.getStyleSheet("xml").get(); +// InputStream actual = config.getStyleSheet().get()) { +// assertThat(IOUtils.contentEquals(expected, actual)).as("'xml' does not match").isTrue(); +// } +// } catch (IOException | RatException e) { +// fail(e.getMessage(), e); +// } finally { +// System.setOut(origin); +// } +// } @OptionCollectionTest.TestFunction protected void logLevelTest() { @@ -992,7 +944,7 @@ protected void logLevelTest() { reporter = new Reporter(config); reporter.output(); TextUtils.assertContains("DEBUG", baos.toString(StandardCharsets.UTF_8.name())); - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); @@ -1033,17 +985,12 @@ private void listLicenses(final Option option) { throw new IllegalArgumentException("Unexpected filter: " + filter); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void listLicensesTest() { - listLicenses(Arg.OUTPUT_LICENSES.find("list-licenses")); - } - @OptionCollectionTest.TestFunction protected void outputLicensesTest() { listLicenses(Arg.OUTPUT_LICENSES.find("output-licenses")); @@ -1082,17 +1029,12 @@ private void listFamilies(final Option option) { throw new IllegalArgumentException("Unexpected filter: " + filter); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void listFamiliesTest() { - listFamilies(Arg.OUTPUT_FAMILIES.find("list-families")); - } - @OptionCollectionTest.TestFunction protected void outputFamiliesTest() { listFamilies(Arg.OUTPUT_FAMILIES.find("output-families")); @@ -1140,7 +1082,7 @@ private void archiveTest(final Option option) { throw new IllegalArgumentException("Unexpected processing " + proc); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException| RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } @@ -1195,7 +1137,7 @@ private void standardTest(final Option option) { throw new IllegalArgumentException("Unexpected processing " + proc); } } - } catch (IOException | RatException | SAXException | ParserConfigurationException | + } catch (IOException | ParseException | RatException | SAXException | ParserConfigurationException | XPathExpressionException e) { fail(e.getMessage(), e); } @@ -1245,26 +1187,16 @@ private void editCopyrightTest(final Option option, final Option extraOption) { TextUtils.assertNotContains(myCopyright, actualText); assertThat(newJavaFile).exists(); } - } catch (IOException | RatException e) { + } catch (IOException | ParseException | RatException e) { fail(e.getMessage(), e); } } - @OptionCollectionTest.TestFunction - protected void copyrightTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("copyright"), null); - } - @OptionCollectionTest.TestFunction protected void editCopyrightTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), null); } - @OptionCollectionTest.TestFunction - protected void forceTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), Arg.EDIT_OVERWRITE.find("force")); - } - @OptionCollectionTest.TestFunction protected void editOverwriteTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright"), Arg.EDIT_OVERWRITE.find("edit-overwrite")); @@ -1286,7 +1218,7 @@ public void helpTest() { assertThat(helpCalled.get()).as("Help was not called").isTrue(); new Help(System.out).printUsage(options); actualText = baos.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); @@ -1334,7 +1266,7 @@ protected void helpLicensesTest() { configureSourceDir(option); ReportConfiguration config = generateConfig(arg1); actualText = baos.toString(StandardCharsets.UTF_8.name()); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage(), e); } finally { System.setOut(origin); diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java index 9c7a389cc..575c0daea 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterOptionsTest.java @@ -24,6 +24,8 @@ import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; + +import org.apache.commons.cli.ParseException; import org.apache.rat.api.RatException; import org.apache.rat.report.claim.ClaimStatistic; import org.apache.rat.test.AbstractConfigurationOptionsProvider; @@ -98,7 +100,7 @@ void testRat362() { XmlUtils.mapOf("type", "IGNORED")); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.STANDARDS)).isEqualTo(0); assertThat(claimStatistic.getCounter(ClaimStatistic.Counter.IGNORED)).isEqualTo(2); - } catch (IOException | RatException | XPathExpressionException e) { + } catch (IOException | ParseException | RatException | XPathExpressionException e) { fail(e); } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java b/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java index 3de3e23e8..3ca56389e 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/ReporterTest.java @@ -137,7 +137,7 @@ public void testExecute() throws RatException, ParseException { @Test public void testOutputOption() throws Exception { File output = new File(tempDirectory, "test"); - CommandLine commandLine = new DefaultParser().parse(OptionCollection.buildOptions(), new String[]{"-o", output.getCanonicalPath(), basedir}); + CommandLine commandLine = new DefaultParser().parse(OptionCollection.buildOptions(), new String[]{"--output-file", output.getCanonicalPath(), basedir}); ArgumentContext ctxt = new ArgumentContext(new File("."), commandLine); ReportConfiguration config = OptionCollection.createConfiguration(ctxt); diff --git a/apache-rat-core/src/test/java/org/apache/rat/configuration/XMLConfigurationReaderTest.java b/apache-rat-core/src/test/java/org/apache/rat/configuration/XMLConfigurationReaderTest.java index 9176361f9..3b12eaa0c 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/configuration/XMLConfigurationReaderTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/configuration/XMLConfigurationReaderTest.java @@ -43,6 +43,7 @@ import org.apache.rat.configuration.builders.RegexBuilder; import org.apache.rat.configuration.builders.SpdxBuilder; import org.apache.rat.configuration.builders.TextBuilder; +import org.apache.rat.license.ILicenseFamily; import org.junit.jupiter.api.Test; public class XMLConfigurationReaderTest { @@ -56,6 +57,10 @@ public class XMLConfigurationReaderTest { public static final String[] EXPECTED_LICENSES = { "AL1.0", "AL1.1", "AL2.0", "BSD-3", "DOJO", "TMF", "CDDL1", "ILLUMOS", "GPL1", "GPL2", "GPL3", "MIT", "OASIS", "W3C", "W3CD" }; + public static final String[] APPROVED_LICENSES = { "AL1.0", "AL1.1", "AL2.0", "BSD-3", "DOJO", "TMF", "CDDL1", "ILLUMOS", + "MIT", "OASIS", "W3C", "W3CD" }; + + @Test public void approvedLicenseIdTest() throws URISyntaxException { XMLConfigurationReader reader = new XMLConfigurationReader(); @@ -63,9 +68,8 @@ public void approvedLicenseIdTest() throws URISyntaxException { assertThat(url).isNotNull(); reader.read(url.toURI()); - Collection readCategories = reader.approvedLicenseId(); - - assertArrayEquals(APPROVED_IDS, readCategories.toArray(new String[readCategories.size()])); + Collection actual = reader.approvedLicenseId(); + assertThat(actual).containsExactlyInAnyOrder(APPROVED_IDS); } @Test @@ -83,11 +87,13 @@ public void LicensesTest() throws URISyntaxException { public void LicenseFamiliesTest() throws URISyntaxException { XMLConfigurationReader reader = new XMLConfigurationReader(); URL url = XMLConfigurationReaderTest.class.getResource("/org/apache/rat/default.xml"); + assertNotNull(url); reader.read(url.toURI()); - Collection readCategories = reader.readFamilies().stream().map(x -> x.getFamilyCategory().trim()) + Collection actual = reader.readFamilies().stream().map(lf -> lf.getFamilyCategory().trim()) .collect(Collectors.toList()); - assertArrayEquals(EXPECTED_IDS, readCategories.toArray(new String[readCategories.size()])); + + assertThat(actual).containsExactlyInAnyOrder(EXPECTED_IDS); } private void checkMatcher(String name, Class clazz) { diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java deleted file mode 100644 index e00a6c685..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/ArrayCharFilterTest.java +++ /dev/null @@ -1,49 +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. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.BeforeEach; - -public class ArrayCharFilterTest { - - private static final char[] filtered = {'d', 'o', 'a'}; - private ArrayCharFilter filter; - - @BeforeEach - public void setUp() { - filter = new ArrayCharFilter(filtered); - } - - @Test - public void isFilteredOut() { - assertTrue(filter.isFilteredOut('a')); - assertFalse(filter.isFilteredOut('b')); - assertFalse(filter.isFilteredOut('c')); - assertTrue(filter.isFilteredOut('d')); - assertFalse(filter.isFilteredOut('e')); - assertFalse(filter.isFilteredOut('f')); - } - -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java deleted file mode 100644 index 19eb9a88e..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/FilteringSequenceFactoryTest.java +++ /dev/null @@ -1,81 +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. * - */ -package org.apache.rat.header; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -public class FilteringSequenceFactoryTest { - - private int capacity; - private FilteringSequenceFactory factory; - private SimpleCharFilter filter; - - @BeforeEach - public void setUp() { - capacity = 50; - filter = new SimpleCharFilter(); - factory = new FilteringSequenceFactory(capacity, filter); - } - - @Test - public void noFiltering() throws Exception { - final String INPUT = "Whatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output."); - reader = new StringReader(INPUT); - result = factory.filter(reader); - assertNotNull(result); - output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output. Independent of previous input"); - } - - @Test - public void filtering() throws Exception { - final String INPUT = "Whatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT, output, "No filtering so input equals output."); - filter.filterOut = true; - reader = new StringReader(INPUT); - result = factory.filter(reader); - assertNotNull(result); - assertEquals( 0, result.length(), "All filtered output is empty. Independent of previous input"); - } - - @Test - public void overCapacity() throws Exception { - final String INPUT = "WhateverWhateverWhateverWhateverWhateverWhateverWhateverWhateverWhateverWhatever"; - StringReader reader = new StringReader(INPUT); - CharSequence result = factory.filter(reader); - assertNotNull(result); - String output = result.toString(); - assertEquals(INPUT.substring(0, capacity), output, "No filtering so input equals output."); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java deleted file mode 100644 index f4b863b0e..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherTest.java +++ /dev/null @@ -1,98 +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. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HeaderMatcherTest { - - private HeaderMatcher matcher; - private SimpleCharFilter filter; - - @BeforeEach - public void setUp() { - filter = new SimpleCharFilter(); - matcher = new HeaderMatcher(filter, 20); - } - - @Test - public void simpleMatches() throws Exception { - Pattern hatPattern = Pattern.compile("(.*)hat(.*)"); - Pattern headPattern = Pattern.compile("head...."); - StringReader reader = new StringReader("The mad hatter"); - matcher.read(reader); - assertTrue(matcher.matches(hatPattern)); - assertFalse(matcher.matches(headPattern)); - reader = new StringReader("headache"); - matcher.read(reader); - assertFalse(matcher.matches(hatPattern)); - assertTrue(matcher.matches(headPattern)); - } - - @Test - public void filteredMatches() throws Exception { - Pattern capPattern = Pattern.compile("cap(.*)"); - StringReader reader = new StringReader("capped"); - matcher.read(reader); - assertTrue(matcher.matches(capPattern)); - filter.filterOut = true; - reader = new StringReader("capped"); - matcher.read(reader); - assertFalse(matcher.matches(capPattern)); - } - - @Test - public void noLines() throws Exception { - StringReader reader = new StringReader("None"); - matcher.read(reader); - assertEquals(0, matcher.lines(), "No lines read"); - } - - @Test - public void lines() throws Exception { - StringReader reader = new StringReader("One\n"); - matcher.read(reader); - assertEquals(1, matcher.lines(), "One line read"); - reader = new StringReader("One\nTwo"); - matcher.read(reader); - assertEquals( 1, matcher.lines(), "One line read"); - reader = new StringReader("One\nTwo\nThree"); - matcher.read(reader); - assertEquals( 2, matcher.lines(), "Two lines read"); - reader = new StringReader("One\nTwo\nThree\n"); - matcher.read(reader); - assertEquals( 3, matcher.lines(), "Three lines read"); - } - - @Test - public void tooManyLines() throws Exception { - StringReader reader = new StringReader("WhateverWhateverWhateverWhateverWhateverWhateverWhateverWhatever"); - matcher.read(reader); - assertEquals( -1, matcher.lines(), "Too many lines read"); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java b/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java deleted file mode 100644 index ada143f92..000000000 --- a/apache-rat-core/src/test/java/org/apache/rat/header/HeaderMatcherWithBeansTest.java +++ /dev/null @@ -1,79 +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. * - */ -package org.apache.rat.header; - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.StringReader; -import java.util.regex.Pattern; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HeaderMatcherWithBeansTest { - - private HeaderMatcher matcher; - private SimpleCharFilter filter; - private HeaderBean[] beans; - - @BeforeEach - public void setUp() { - HeaderBean[] beans = { - new HeaderBean(), - new HeaderBean(), - new HeaderBean() - }; - this.beans = beans; - filter = new SimpleCharFilter(); - matcher = new HeaderMatcher(filter, 20, beans); - } - - @Test - public void nulls() throws Exception { - beans[0].setMatch(false); - beans[1].setMatch(true); - beans[2].setMatch(false); - StringReader reader = new StringReader("Whatever"); - matcher.read(reader); - assertFalse(beans[0].isMatch(),"State preserved"); - assertTrue( beans[1].isMatch(),"State preserved"); - assertFalse(beans[2].isMatch(), "State preserved"); - beans[0].setMatch(true); - beans[1].setMatch(false); - beans[2].setMatch(true); - assertTrue(beans[0].isMatch(), "State preserved"); - assertFalse(beans[1].isMatch(), "State preserved"); - assertTrue(beans[2].isMatch(), "State preserved"); - } - - @Test - public void matches() throws Exception { - beans[0].setHeaderPattern(Pattern.compile("What(.*)")); - beans[1].setHeaderPattern(Pattern.compile("(.*)ever")); - beans[2].setHeaderPattern(Pattern.compile("What")); - StringReader reader = new StringReader("Whatever"); - matcher.read(reader); - assertTrue(beans[0].isMatch(), "Match header pattern"); - assertTrue(beans[1].isMatch(), "Match header pattern"); - assertFalse(beans[2].isMatch(), "Match header pattern"); - } -} diff --git a/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java b/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java index e3e994765..474ba053e 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java +++ b/apache-rat-core/src/test/java/org/apache/rat/help/HelpTest.java @@ -25,7 +25,10 @@ import org.junit.jupiter.api.Test; import java.io.StringWriter; +import java.util.Arrays; +import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; @@ -55,7 +58,7 @@ public void verifyAllOptionsListed() { @Test public void verifyArgumentsListed() { Options opts = OptionCollection.buildOptions(); - Set argTypes = OptionCollection.getArgumentTypes().keySet(); + Set argTypes = Arrays.stream(OptionCollection.ArgumentType.values()).map(OptionCollection.ArgumentType::getDisplayName).collect(Collectors.toSet()); StringWriter out = new StringWriter(); new Help(out).printUsage(opts); String result = out.toString(); diff --git a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java index 622878471..3168ab9f6 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractConfigurationOptionsProvider.java @@ -21,6 +21,7 @@ import java.nio.file.FileSystems; import java.nio.file.Path; import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -100,24 +101,16 @@ public static File setup(final File baseDir) { protected AbstractConfigurationOptionsProvider(final Collection unsupportedArgs, final File baseDir) { super(setup(baseDir)); - addTest(OptionCollectionTest.OptionTest.namedTest("addLicense", this::addLicenseTest)); addTest(OptionCollectionTest.OptionTest.namedTest("config", this::configTest)); addTest(OptionCollectionTest.OptionTest.namedTest("configuration-no-defaults", this::configurationNoDefaultsTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("copyright", this::copyrightTest)); addTest(OptionCollectionTest.OptionTest.namedTest("counter-min", this::counterMinTest)); addTest(OptionCollectionTest.OptionTest.namedTest("counter-max", this::counterMaxTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("dir", () -> DefaultLog.getInstance().info("--dir has no valid test"))); addTest(OptionCollectionTest.OptionTest.namedTest("dry-run", this::dryRunTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-copyright", this::editCopyrightTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-license", this::editLicenseTest)); addTest(OptionCollectionTest.OptionTest.namedTest("edit-overwrite", this::editOverwriteTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("exclude", this::excludeTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("exclude-file", this::excludeFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("force", this::forceTest)); addTest(OptionCollectionTest.OptionTest.namedTest("help", this::helpTest)); addTest(OptionCollectionTest.OptionTest.namedTest("help-licenses", this::helpLicenses)); - addTest(OptionCollectionTest.OptionTest.namedTest("include", this::includeTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("includes-file", this::includesFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude", this::inputExcludeTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude-file", this::inputExcludeFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("input-exclude-parsed-scm", this::inputExcludeParsedScmTest)); @@ -131,25 +124,17 @@ protected AbstractConfigurationOptionsProvider(final Collection unsuppor addTest(OptionCollectionTest.OptionTest.namedTest("license-families-approved-file", this::licenseFamiliesApprovedFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("license-families-denied", this::licenseFamiliesDeniedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("license-families-denied-file", this::licenseFamiliesDeniedFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("licenses", this::licensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-approved", this::licensesApprovedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-approved-file", this::licensesApprovedFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-denied", this::licensesDeniedTest)); addTest(OptionCollectionTest.OptionTest.namedTest("licenses-denied-file", this::licensesDeniedFileTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("list-families", this::listFamiliesTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("list-licenses", this::listLicensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("log-level", this::logLevelTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("no-default-licenses", this::noDefaultsTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("out", this::outTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-archive", this::outputArchiveTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-families", this::outputFamiliesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-file", this::outputFileTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-licenses", this::outputLicensesTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-standard", this::outputStandardTest)); addTest(OptionCollectionTest.OptionTest.namedTest("output-style", this::outputStyleTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("scan-hidden-directories", this::scanHiddenDirectoriesTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("stylesheet", this::styleSheetTest)); - addTest(OptionCollectionTest.OptionTest.namedTest("xml", this::xmlTest)); super.validate(unsupportedArgs); } @@ -171,7 +156,7 @@ private void execExcludeTest(final Option option, final String[] args) { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isFalse(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -181,18 +166,10 @@ private void excludeFileTest(final Option option) { execExcludeTest(option, new String[]{outputFile.getAbsolutePath()}); } - protected void excludeFileTest() { - excludeFileTest(Arg.EXCLUDE_FILE.find("exclude-file")); - } - protected void inputExcludeFileTest() { excludeFileTest(Arg.EXCLUDE_FILE.find("input-exclude-file")); } - protected void excludeTest() { - execExcludeTest(Arg.EXCLUDE.find("exclude"), EXCLUDE_ARGS); - } - protected void inputExcludeTest() { execExcludeTest(Arg.EXCLUDE.find("input-exclude"), EXCLUDE_ARGS); } @@ -213,7 +190,7 @@ protected void inputExcludeStdTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -249,7 +226,7 @@ protected void inputExcludeParsedScmTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -275,7 +252,7 @@ private void inputExcludeSizeTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -297,7 +274,7 @@ private void execIncludeTest(final Option option, final String[] args) { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -311,13 +288,6 @@ protected void inputIncludeFileTest() { includeFileTest(Arg.INCLUDE_FILE.find("input-include-file")); } - protected void includesFileTest() { - includeFileTest(Arg.INCLUDE_FILE.find("includes-file")); - } - - protected void includeTest() { - execIncludeTest(Arg.INCLUDE.find("include"), INCLUDE_ARGS); - } protected void inputIncludeTest() { execIncludeTest(Arg.INCLUDE.find("input-include"), INCLUDE_ARGS); @@ -341,7 +311,7 @@ protected void inputIncludeStdTest() { DocumentName docName = mkDocName(fname); assertThat(excluder.matches(docName)).as(() -> dump(option, fname, excluder, docName)).isTrue(); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -351,7 +321,7 @@ protected void inputSourceTest() { try { ReportConfiguration config = generateConfig(ImmutablePair.of(option, new String[]{baseDir.getAbsolutePath()})); assertThat(config.hasSource()).isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -363,7 +333,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { ReportConfiguration config = generateConfig(arg1); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).contains("one", "two"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } @@ -376,7 +346,7 @@ protected void execLicensesApprovedTest(final Option option, String[] args) { ReportConfiguration config = generateConfig(arg1, arg2); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).containsExactly("one", "two"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -387,7 +357,7 @@ protected void helpLicenses() { try (PrintStream out = new PrintStream(output)) { System.setOut(out); generateConfig(ImmutablePair.of(HELP_LICENSES.option(), null)); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } finally { System.setOut(origin); @@ -415,7 +385,7 @@ private void execLicensesDeniedTest(final Option option, final String[] args) { assertThat(config.getLicenseIds(LicenseSetFactory.LicenseFilter.ALL)).contains("ILLUMOS"); SortedSet result = config.getLicenseIds(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).doesNotContain("ILLUMOS"); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -437,7 +407,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] ReportConfiguration config = generateConfig(arg1); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).contains(catz); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } @@ -446,7 +416,7 @@ private void execLicenseFamiliesApprovedTest(final Option option, final String[] ReportConfiguration config = generateConfig(arg1, arg2); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).containsExactly(catz); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -469,7 +439,7 @@ private void execLicenseFamiliesDeniedTest(final Option option, final String[] a assertThat(config.getLicenseCategories(LicenseSetFactory.LicenseFilter.ALL)).contains(gpl); SortedSet result = config.getLicenseCategories(LicenseSetFactory.LicenseFilter.APPROVED); assertThat(result).doesNotContain(gpl); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -502,7 +472,7 @@ protected void counterMaxTest() { config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getClaimValidator().getMax(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(5); assertThat(config.getClaimValidator().getMax(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -524,7 +494,7 @@ protected void counterMinTest() { config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getClaimValidator().getMin(ClaimStatistic.Counter.UNAPPROVED)).isEqualTo(5); assertThat(config.getClaimValidator().getMin(ClaimStatistic.Counter.IGNORED)).isEqualTo(0); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -546,15 +516,11 @@ private void configTest(final Option option) { assertThat(set).hasSize(2); assertThat(LicenseSetFactory.search("ONE", "ONE", set)).isPresent(); assertThat(LicenseSetFactory.search("TWO", "TWO", set)).isPresent(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void licensesTest() { - configTest(Arg.CONFIGURATION.find("licenses")); - } - protected void configTest() { configTest(Arg.CONFIGURATION.find("config")); } @@ -565,15 +531,11 @@ private void noDefaultsTest(final Option arg) { assertThat(config.getLicenses(LicenseSetFactory.LicenseFilter.ALL)).isEmpty(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.getLicenses(LicenseSetFactory.LicenseFilter.ALL)).isNotEmpty(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void noDefaultsTest() { - noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("no-default-licenses")); - } - protected void configurationNoDefaultsTest() { noDefaultsTest(Arg.CONFIGURATION_NO_DEFAULTS.find("configuration-no-defaults")); } @@ -584,7 +546,7 @@ protected void dryRunTest() { assertThat(config.isDryRun()).isTrue(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.isDryRun()).isFalse(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -597,19 +559,14 @@ private void editCopyrightTest(final Option option) { Pair arg2 = ImmutablePair.of(Arg.EDIT_ADD.find("edit-license"), null); config = generateConfig(arg1, arg2); assertThat(config.getCopyrightMessage()).isEqualTo("MyCopyright"); - } catch (IOException e) { - e.printStackTrace(); + } catch (IOException | ParseException e) { if (e.getCause() != null) { - fail(e.getMessage() + ": " + e.getCause().getMessage()); + fail(e.getMessage() + ": " + e.getCause().getMessage(), e); } - fail(e.getMessage()); + fail(e.getMessage(), e); } } - protected void copyrightTest() { - editCopyrightTest(Arg.EDIT_COPYRIGHT.find("copyright")); - } - protected void editCopyrightTest() { editCopyrightTest(Arg.EDIT_COPYRIGHT.find("edit-copyright")); } @@ -620,15 +577,11 @@ private void editLicenseTest(final Option option) { assertThat(config.isAddingLicenses()).isTrue(); config = generateConfig(ImmutablePair.nullPair()); assertThat(config.isAddingLicenses()).isFalse(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void addLicenseTest() { - editLicenseTest(Arg.EDIT_ADD.find("addLicense")); - } - protected void editLicenseTest() { editLicenseTest(Arg.EDIT_ADD.find("edit-license")); } @@ -642,15 +595,11 @@ private void overwriteTest(final Option option) { config = generateConfig(arg1, arg2); assertThat(config.isAddingLicensesForced()).isTrue(); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void forceTest() { - overwriteTest(Arg.EDIT_OVERWRITE.find("force")); - } - protected void editOverwriteTest() { overwriteTest(Arg.EDIT_OVERWRITE.find("edit-overwrite")); } @@ -665,7 +614,7 @@ protected void logLevelTest() { args[0] = level.name(); generateConfig(ImmutablePair.of(option, args)); assertThat(DefaultLog.getInstance().getLevel()).isEqualTo(level); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -682,7 +631,7 @@ private void archiveTest(final Option option) { ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getArchiveProcessing()).isEqualTo(proc); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -698,16 +647,12 @@ private void listFamilies(final Option option) { args[0] = filter.name(); ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.listFamilies()).isEqualTo(filter); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } } - protected void listFamiliesTest() { - listFamilies(Arg.OUTPUT_FAMILIES.find("list-families")); - } - protected void outputFamiliesTest() { listFamilies(Arg.OUTPUT_FAMILIES.find("output-families")); } @@ -727,15 +672,11 @@ private void outTest(final Option option) { } catch (IOException e) { throw new RuntimeException(e); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void outTest() { - outTest(Arg.OUTPUT_FILE.find("out")); - } - protected void outputFileTest() { outTest(Arg.OUTPUT_FILE.find("output-file")); } @@ -747,16 +688,12 @@ private void listLicenses(final Option option) { args[0] = filter.name(); ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.listLicenses()).isEqualTo(filter); - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } } - protected void listLicensesTest() { - listLicenses(Arg.OUTPUT_LICENSES.find("list-licenses")); - } - protected void outputLicensesTest() { listLicenses(Arg.OUTPUT_LICENSES.find("output-licenses")); } @@ -769,7 +706,7 @@ private void standardTest(final Option option) { ReportConfiguration config = generateConfig(ImmutablePair.of(option, args)); assertThat(config.getStandardProcessing()).isEqualTo(proc); } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } @@ -799,38 +736,13 @@ private void styleSheetTest(final Option option) { assertThat(IOUtils.contentEquals(expected, actual)).as(() -> String.format("'%s' does not match", sheet)).isTrue(); } } - } catch (IOException e) { + } catch (IOException | ParseException e) { fail(e.getMessage()); } } - protected void styleSheetTest() { - styleSheetTest(Arg.OUTPUT_STYLE.find("stylesheet")); - } - protected void outputStyleTest() { styleSheetTest(Arg.OUTPUT_STYLE.find("output-style")); } - protected void scanHiddenDirectoriesTest() { - try { - ReportConfiguration config = generateConfig(ImmutablePair.of(Arg.INCLUDE_STD.find("scan-hidden-directories"), null)); - DocumentNameMatcher excluder = config.getDocumentExcluder(baseName()); - assertThat(excluder.matches(mkDocName(".file"))).as(".file").isTrue(); - } catch (IOException e) { - fail(e.getMessage()); - } - } - - protected void xmlTest() { - try { - ReportConfiguration config = generateConfig(ImmutablePair.of(Arg.OUTPUT_STYLE.find("xml"), null)); - try (InputStream expected = StyleSheets.getStyleSheet("xml").get(); - InputStream actual = config.getStyleSheet().get()) { - assertThat(IOUtils.contentEquals(expected, actual)).as("'xml' does not match").isTrue(); - } - } catch (IOException e) { - fail(e.getMessage()); - } - } } diff --git a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java index dac4b4150..7c70f3f77 100644 --- a/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java +++ b/apache-rat-core/src/test/java/org/apache/rat/test/AbstractOptionsProvider.java @@ -31,6 +31,7 @@ import java.util.TreeMap; import java.util.stream.Stream; import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.rat.OptionCollectionTest; @@ -135,7 +136,7 @@ private void verifyAllMethodsDefinedAndNeeded(final Collection unsupport } @SafeVarargs - protected final ReportConfiguration generateConfig(final Pair... args) throws IOException { + protected final ReportConfiguration generateConfig(final Pair... args) throws IOException, ParseException { List> options = Arrays.asList(args); return generateConfig(options); } @@ -148,7 +149,7 @@ protected final ReportConfiguration generateConfig(final Pair. * @return The generated ReportConfiguration. * @throws IOException on error. */ - protected abstract ReportConfiguration generateConfig(final List> args) throws IOException; + protected abstract ReportConfiguration generateConfig(final List> args) throws IOException, ParseException; /** * Converts each {@code Pair} into the option string and its arguments. diff --git a/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java b/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java index c3e38a8d5..3adf6f707 100644 --- a/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java +++ b/apache-rat-plugin/src/main/java/org/apache/rat/mp/AbstractRatMojo.java @@ -27,13 +27,13 @@ import java.util.Map; import org.apache.commons.cli.Option; +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.OptionCollection; import org.apache.rat.ReportConfiguration; import org.apache.rat.commandline.Arg; -import org.apache.rat.config.exclusion.StandardCollection; import org.apache.rat.document.DocumentName; import org.apache.rat.document.FileDocument; import org.apache.rat.license.ILicense; @@ -216,14 +216,11 @@ public void log(final Level level, final String msg) { } private void setIncludeExclude() { - if (excludeSubProjects && project != null && project.getModules() != null) { List subModules = new ArrayList<>(); project.getModules().forEach(s -> subModules.add(format("%s/**", s))); setInputExcludes(subModules.toArray(new String[0])); } - - List values = getValues(Arg.EXCLUDE); } protected ReportConfiguration getConfiguration() throws MojoExecutionException { @@ -254,7 +251,7 @@ protected ReportConfiguration getConfiguration() throws MojoExecutionException { new org.apache.rat.help.Licenses(config, new PrintWriter(log.asWriter())).printHelp(); } reportConfiguration = config; - } catch (IOException e) { + } catch (IOException | ParseException e) { throw new MojoExecutionException(e); } } diff --git a/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatCheckMojo.java b/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatCheckMojo.java index 76b79ec35..a43138a78 100644 --- a/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatCheckMojo.java +++ b/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatCheckMojo.java @@ -48,6 +48,7 @@ @Mojo(name = "check", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true) public class RatCheckMojo extends AbstractRatMojo { + /** The default output file if no other is specified. */ @Parameter(defaultValue = "${project.build.directory}/rat.txt", readonly = true) private File defaultReportFile; diff --git a/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatReportMojo.java b/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatReportMojo.java index 08935be67..7b3f242f9 100644 --- a/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatReportMojo.java +++ b/apache-rat-plugin/src/main/java/org/apache/rat/mp/RatReportMojo.java @@ -215,6 +215,20 @@ private SiteRenderingContext createSiteRenderingContext(final Locale locale) thr return context; } + /** + * Generate a report. + * + * @param sink the sink to use for the generation. + * @param locale the wanted locale to generate the report, could be null. + * @throws MavenReportException if any + * @deprecated use {@link #generate(Sink, SinkFactory, Locale)} instead. + */ + @Deprecated + @Override + public void generate(final org.codehaus.doxia.sink.Sink sink, final Locale locale) throws MavenReportException { + generate(sink, null, locale); + } + /** * This method is called when the report generation is invoked by * maven-site-plugin. diff --git a/apache-rat-plugin/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java b/apache-rat-plugin/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java index 0d10e37f5..7c760ece5 100644 --- a/apache-rat-plugin/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java +++ b/apache-rat-plugin/src/test/java/org/apache/rat/mp/RatCheckMojoTest.java @@ -33,6 +33,7 @@ import java.util.List; import java.util.Map; import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.commons.io.FileUtils; import org.apache.rat.ReportConfiguration; @@ -87,7 +88,7 @@ private RatCheckMojo getMojo(File pomFile) throws IOException { } catch (IOException e) { throw e; } catch (Exception e) { - throw new IOException(format("Unable to generate mojo for %s", pomFile), e); + throw new IOException(format("Unable to generate mojo for %s; %s", pomFile, e.getMessage()), e); } } @@ -133,12 +134,13 @@ void it1() throws Exception { ReportConfigurationTest.validateDefault(config); mojo.execute(); + Map data = new HashMap<>(); data.put(ClaimStatistic.Counter.ARCHIVES, "0"); data.put(ClaimStatistic.Counter.APPROVED, "1"); data.put(ClaimStatistic.Counter.BINARIES, "0"); data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); - data.put(ClaimStatistic.Counter.IGNORED, "2"); + data.put(ClaimStatistic.Counter.IGNORED, "1"); data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); data.put(ClaimStatistic.Counter.NOTICES, "0"); @@ -147,14 +149,7 @@ void it1() throws Exception { data.put(ClaimStatistic.Counter.UNKNOWN, "0"); org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); - XPath xPath = XPathFactory.newInstance().newXPath(); - - for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { - String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); - Map map = mapOf("approval", "true", "count", data.get(counter), - "description", counter.getDescription()); - XmlUtils.assertAttributes(document, xPath, xpath, map); - } + verifyDataMap(data, document); XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/.bzrignore']", mapOf("mediaType", "application/octet-stream", "type", "IGNORED")); @@ -180,13 +175,17 @@ private static Map mapOf(String... parts) { void it2() throws Exception { final RatCheckMojo mojo = newRatMojo("it2"); final File ratTxtFile = mojo.getRatTxtFile(); + + Map data = new HashMap<>(); + data.put(ClaimStatistic.Counter.ARCHIVES, "0"); + data.put(ClaimStatistic.Counter.NOTICES, "0"); + data.put(ClaimStatistic.Counter.BINARIES, "0"); + data.put(ClaimStatistic.Counter.STANDARDS, "2"); + data.put(ClaimStatistic.Counter.IGNORED, "0"); + + final String[] expected = { - "^Files with unapproved licenses\\s+\\*+\\s+\\Q/src.txt\\E\\s+", - ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 2, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), + "^Files with unapproved licenses[\\W\\*]+\\Q/src.txt\\E\\s+", ReporterTestUtils.apacheLicenseVersion2(1), ReporterTestUtils.unknownLicense(1), ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/src.txt") + @@ -215,11 +214,26 @@ void it3() throws Exception { final RatCheckMojo mojo = newRatMojo("it3"); final File ratTxtFile = mojo.getRatTxtFile(); + Map data = new HashMap<>(); + data.put(ClaimStatistic.Counter.APPROVED, "1"); + data.put(ClaimStatistic.Counter.ARCHIVES, "0"); + data.put(ClaimStatistic.Counter.BINARIES, "0"); + data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "1"); + data.put(ClaimStatistic.Counter.IGNORED, "0"); + data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "2"); + data.put(ClaimStatistic.Counter.LICENSE_NAMES, "2"); + data.put(ClaimStatistic.Counter.NOTICES, "0"); + data.put(ClaimStatistic.Counter.STANDARDS, "2"); + data.put(ClaimStatistic.Counter.UNAPPROVED, "1"); + data.put(ClaimStatistic.Counter.UNKNOWN, "1"); + ReportConfiguration config = mojo.getConfiguration(); assertThat(config.isAddingLicenses()).as("should be adding licenses").isTrue(); mojo.execute(); org.w3c.dom.Document document = XmlUtils.toDom(Files.newInputStream(ratTxtFile.toPath())); + verifyDataMap(data, document); + XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/pom.xml']", "type", "STANDARD"); XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", @@ -229,19 +243,18 @@ void it3() throws Exception { XmlUtils.assertAttributes(document, xPath, "/rat-report/resource[@name='/src.apt']", "type", "STANDARD"); - for (Document.Type type : Document.Type.values()) { - if (type == Document.Type.STANDARD) { - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='STANDARD']", "count", - "2"); - } else if (type == Document.Type.IGNORED) { - XmlUtils.assertAttributes(document, xPath, "/rat-report/statistics/documentType[@name='IGNORED']", "count", - "1"); - } else { - XmlUtils.assertIsNotPresent(document, xPath, format("/rat-report/statistics/documentType[@name='%s']", type)); - } - } } + private void verifyDataMap(Map data, org.w3c.dom.Document document) throws XPathExpressionException { + for (ClaimStatistic.Counter counter : ClaimStatistic.Counter.values()) { + String xpath = String.format("/rat-report/statistics/statistic[@name='%s']", counter.displayName()); + Map map = mapOf("approval", + "true", + "count", data.get(counter), + "description", counter.getDescription()); + XmlUtils.assertAttributes(document, xPath, xpath, map); + } + } /** * Tests defining licenses in configuration */ @@ -254,16 +267,15 @@ void it5() throws Exception { assertThat(config.isAddingLicenses()).as("Should not be adding licenses").isFalse(); assertThat(config.isAddingLicensesForced()).as("Should not be forcing licenses").isFalse(); - ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); - assertThat(config.getLicenseCategories(LicenseFilter.APPROVED)).doesNotContain(ILicenseFamily.makeCategory("YAL")) - .contains(ILicenseFamily.makeCategory("CC")); + ReportConfigurationTest.validateDefaultLicenses(config, "CC-BY-NC-ND", "YAL"); + ReportConfigurationTest.validateDefaultApprovedLicenses(config, "CC-BY-NC-ND"); + ReportConfigurationTest.validateDefaultApprovedLicenseFamilies(config, "CC"); ReportConfigurationTest.validateDefaultLicenseFamilies(config, "YAL", "CC"); assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNull(); assertThat(LicenseSetFactory.familySearch("YAL", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.APPROVED))).isNotNull(); assertThat(LicenseSetFactory.familySearch("CC", config.getLicenseFamilies(LicenseFilter.ALL))).isNotNull(); - ReportConfigurationTest.validateDefaultLicenses(config, "CC-BY-NC-ND", "YAL"); assertThat(LicenseSetFactory.search("YAL", "YAL", config.getLicenses(LicenseFilter.ALL))).isPresent(); mojo.execute(); @@ -273,7 +285,7 @@ void it5() throws Exception { data.put(ClaimStatistic.Counter.ARCHIVES, "0"); data.put(ClaimStatistic.Counter.BINARIES, "0"); data.put(ClaimStatistic.Counter.DOCUMENT_TYPES, "2"); - data.put(ClaimStatistic.Counter.IGNORED, "3"); + data.put(ClaimStatistic.Counter.IGNORED, "2"); data.put(ClaimStatistic.Counter.LICENSE_CATEGORIES, "1"); data.put(ClaimStatistic.Counter.LICENSE_NAMES, "1"); data.put(ClaimStatistic.Counter.NOTICES, "0"); @@ -315,17 +327,18 @@ void rat343() throws Exception { final File ratTxtFile = mojo.getRatTxtFile(); // POM reports AL, BSD and CC BYas BSD because it contains the BSD and CC BY strings final String[] expected = { - ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/pom.xml") + + ReporterTestUtils.documentOut(false, Document.Type.STANDARD, "/custom.xml") + ReporterTestUtils.APACHE_LICENSE + - ReporterTestUtils.licenseOut("BSD", "BSD") + - ReporterTestUtils.licenseOut("CC BY", "Creative Commons Attribution (Unapproved)"), + ReporterTestUtils.licenseOut("CC BY", "CC BY 4.0", "Creative Commons Attribution (Unapproved)"), ReporterTestUtils.counterText(ClaimStatistic.Counter.NOTICES, 0, false), ReporterTestUtils.counterText(ClaimStatistic.Counter.BINARIES, 0, false), ReporterTestUtils.counterText(ClaimStatistic.Counter.ARCHIVES, 0, false), - ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 1, false), + ReporterTestUtils.counterText(ClaimStatistic.Counter.STANDARDS, 2, false), ReporterTestUtils.counterText(ClaimStatistic.Counter.IGNORED, 1, false), - ReporterTestUtils.apacheLicenseVersion2(1), - "^BSD: 1 ", + ReporterTestUtils.counterText(ClaimStatistic.Counter.UNAPPROVED, 1, false), + ReporterTestUtils.counterText(ClaimStatistic.Counter.LICENSE_NAMES, 2, false), + ReporterTestUtils.counterText(ClaimStatistic.Counter.LICENSE_CATEGORIES, 2, false), + ReporterTestUtils.apacheLicenseVersion2(2), "^Creative Commons Attribution: 1 ", }; final String[] notExpected = { @@ -339,9 +352,9 @@ void rat343() throws Exception { assertThat(config.getCopyrightMessage()).isNull(); assertThat(config.getStyleSheet()).withFailMessage("Stylesheet should not be null").isNotNull(); - ReportConfigurationTest.validateDefaultApprovedLicenses(config, 1); - ReportConfigurationTest.validateDefaultLicenseFamilies(config, "BSD", "CC BY"); - ReportConfigurationTest.validateDefaultLicenses(config, "BSD", "CC BY"); + ReportConfigurationTest.validateDefaultApprovedLicenses(config); + ReportConfigurationTest.validateDefaultLicenseFamilies(config, "CC BY"); + ReportConfigurationTest.validateDefaultLicenses(config, "CC BY 4.0"); mojo.execute(); ensureRatReportIsCorrect(ratTxtFile, expected, notExpected); diff --git a/apache-rat-plugin/src/test/resources/unit/RAT-335/pom.xml b/apache-rat-plugin/src/test/resources/unit/RAT-335/pom.xml index 971cc544e..4ee9eeb62 100644 --- a/apache-rat-plugin/src/test/resources/unit/RAT-335/pom.xml +++ b/apache-rat-plugin/src/test/resources/unit/RAT-335/pom.xml @@ -28,15 +28,7 @@ @pom.version@ xml - - - **/.gitignore - - false - false - false - false - true + GIT diff --git a/apache-rat-plugin/src/test/resources/unit/RAT-343/custom.xml b/apache-rat-plugin/src/test/resources/unit/RAT-343/custom.xml new file mode 100644 index 000000000..c538b601a --- /dev/null +++ b/apache-rat-plugin/src/test/resources/unit/RAT-343/custom.xml @@ -0,0 +1,33 @@ + + + + + + + + + + creativecommons.org/licenses/by/4.0 + + + + + + + + diff --git a/apache-rat-plugin/src/test/resources/unit/RAT-343/pom.xml b/apache-rat-plugin/src/test/resources/unit/RAT-343/pom.xml index f1685b5f0..c54452772 100644 --- a/apache-rat-plugin/src/test/resources/unit/RAT-343/pom.xml +++ b/apache-rat-plugin/src/test/resources/unit/RAT-343/pom.xml @@ -27,64 +27,19 @@ apache-rat-plugin @pom.version@ - true - 1 - - - MIT - MIT - - - Licensed MIT - Licensed under MIT - Licensed under the MIT license - MIT/GPL2 Licensed - licensed under the MIT and GPL - MIT license - - - - BSD - BSD - - - BSD-style license - - - - CC BY - Creative Commons Attribution - - - creativecommons.org/licenses/by/4.0 - - - - - - MIT - - - BSD - - - CC BY - - - - BSD - - - **/*.mp3 - **/localhost.jks - **/node_modules/** - **/package-lock.json - **/target/** - **/.project - **/.classpath - **/.settings/** - .gitattributes - + UNAPPROVED:1 + custom.xml + + **/*.mp3 + **/localhost.jks + **/node_modules/** + **/package-lock.json + **/target/** + **/.project + **/.classpath + **/.settings/** + .gitattributes + diff --git a/apache-rat-plugin/src/test/resources/unit/RAT-362/pom.xml b/apache-rat-plugin/src/test/resources/unit/RAT-362/pom.xml index af34ad819..5c7ef150d 100644 --- a/apache-rat-plugin/src/test/resources/unit/RAT-362/pom.xml +++ b/apache-rat-plugin/src/test/resources/unit/RAT-362/pom.xml @@ -28,15 +28,7 @@ @pom.version@ xml - - - **/.gitignore - - false - false - false - false - true + GIT diff --git a/apache-rat-plugin/src/test/resources/unit/it1/pom.xml b/apache-rat-plugin/src/test/resources/unit/it1/pom.xml index b67387c9f..ed54c0ce4 100644 --- a/apache-rat-plugin/src/test/resources/unit/it1/pom.xml +++ b/apache-rat-plugin/src/test/resources/unit/it1/pom.xml @@ -28,6 +28,7 @@ @pom.version@ xml + BAZAAR diff --git a/apache-rat-plugin/src/test/resources/unit/it3/pom.xml b/apache-rat-plugin/src/test/resources/unit/it3/pom.xml index 1188a2d28..87432dd43 100644 --- a/apache-rat-plugin/src/test/resources/unit/it3/pom.xml +++ b/apache-rat-plugin/src/test/resources/unit/it3/pom.xml @@ -27,8 +27,10 @@ apache-rat-plugin @pom.version@ - 1 - true + Unapproved:1 + true + + xml diff --git a/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/AntOption.java b/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/AntOption.java index 4ddc1e9b2..b86380998 100644 --- a/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/AntOption.java +++ b/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/AntOption.java @@ -29,7 +29,6 @@ import java.util.Objects; import java.util.Set; import java.util.function.Predicate; -import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.commons.cli.Option; @@ -98,7 +97,6 @@ private static void updateConversionMap(final Arg arg, final Arg actualArg) { ATTRIBUTE_TYPES.add(File.class); Arg.getOptions().getOptions().stream().filter(o -> Objects.isNull(o.getLongOpt())).forEach(UNSUPPORTED_LIST::add); UNSUPPORTED_LIST.addAll(Arg.LOG_LEVEL.group().getOptions()); - UNSUPPORTED_LIST.addAll(Arg.DIR.group().getOptions()); UNSUPPORTED_LIST.add(OptionCollection.HELP); UNSUPPORTED_LIST.addAll(Arg.SOURCE.group().getOptions()); updateConversionMap(Arg.LICENSES_APPROVED_FILE, Arg.LICENSES_APPROVED); @@ -287,9 +285,11 @@ public String getComment(final boolean addParam) { arg = "The state"; } if (option.getArgName() != null) { - Supplier sup = OptionCollection.getArgumentTypes().get(option.getArgName()); - if (sup == null) { - throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ARGUMENT_TYPES", option.getArgName())); + String argName = option.getArgName().toUpperCase(Locale.ROOT); + try { + OptionCollection.ArgumentType.valueOf(argName); + } catch (IllegalArgumentException e) { + throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ArgumentType", option.getArgName())); } desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, option.hasArgs() ? "s" : "", option.hasArgs() ? "" : "a ", option.getArgName()); diff --git a/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/MavenOption.java b/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/MavenOption.java index 4644297ca..a386b7df2 100644 --- a/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/MavenOption.java +++ b/apache-rat-tools/src/main/java/org/apache/rat/documentation/options/MavenOption.java @@ -60,7 +60,6 @@ public class MavenOption extends AbstractOption { 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()); UNSUPPORTED_LIST.add(OptionCollection.HELP); diff --git a/apache-rat-tools/src/main/java/org/apache/rat/tools/AntDocumentation.java b/apache-rat-tools/src/main/java/org/apache/rat/tools/AntDocumentation.java index 9549bda63..4ad266dc5 100644 --- a/apache-rat-tools/src/main/java/org/apache/rat/tools/AntDocumentation.java +++ b/apache-rat-tools/src/main/java/org/apache/rat/tools/AntDocumentation.java @@ -30,9 +30,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.function.Predicate; -import java.util.function.Supplier; import org.apache.commons.io.IOUtils; @@ -151,8 +149,8 @@ private void printValueTypes() { List> table = new ArrayList<>(); table.add(Arrays.asList("Value Type", "Description")); - for (Map.Entry> argInfo : OptionCollection.getArgumentTypes().entrySet()) { - table.add(Arrays.asList(argInfo.getKey(), argInfo.getValue().get())); + for (OptionCollection.ArgumentType argumentType : OptionCollection.ArgumentType.values()) { + table.add(Arrays.asList(argumentType.getDisplayName(), argumentType.description().get())); } AptFormat.writeTable(writer, table, "*--+--+"); diff --git a/apache-rat-tools/src/main/java/org/apache/rat/tools/Documentation.java b/apache-rat-tools/src/main/java/org/apache/rat/tools/Documentation.java index ae8bbf094..02e74017d 100644 --- a/apache-rat-tools/src/main/java/org/apache/rat/tools/Documentation.java +++ b/apache-rat-tools/src/main/java/org/apache/rat/tools/Documentation.java @@ -24,6 +24,7 @@ import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; import org.apache.rat.OptionCollection; import org.apache.rat.ReportConfiguration; import org.apache.rat.help.AbstractHelp; @@ -44,8 +45,9 @@ private Documentation() { * Creates the documentation. Writes to the output specified by the -o or --out option. Defaults to {@code System.out}. * @param args the arguments. Try --help for help. * @throws IOException on error + * @throws ParseException on argument error. */ - public static void main(final String[] args) throws IOException { + public static void main(final String[] args) throws IOException, ParseException { ReportConfiguration config = OptionCollection.parseCommands(new File("."), args, Documentation::printUsage, true); if (config != null) { try (Writer writer = config.getWriter().get()) { diff --git a/apache-rat-tools/src/main/java/org/apache/rat/tools/MavenGenerator.java b/apache-rat-tools/src/main/java/org/apache/rat/tools/MavenGenerator.java index 20c5a58b2..4f1b8be84 100644 --- a/apache-rat-tools/src/main/java/org/apache/rat/tools/MavenGenerator.java +++ b/apache-rat-tools/src/main/java/org/apache/rat/tools/MavenGenerator.java @@ -25,8 +25,8 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Locale; import java.util.Map; -import java.util.function.Supplier; import org.apache.commons.cli.Option; import org.apache.commons.io.IOUtils; @@ -148,8 +148,9 @@ private static String getComment(final MavenOption option) { arg = "The state"; } if (option.hasArg() && option.getArgName() != null) { - Supplier sup = OptionCollection.getArgumentTypes().get(option.getArgName()); - if (sup == null) { + try { + OptionCollection.ArgumentType.valueOf(option.getArgName().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { throw new IllegalStateException(format("Argument type %s must be in OptionCollection.ARGUMENT_TYPES", option.getArgName())); } desc = format("%s Argument%s should be %s%s. (See Argument Types for clarification)", desc, option.hasArgs() ? "s" : "", diff --git a/apache-rat-tools/src/test/java/org/apache/rat/tools/NamingTest.java b/apache-rat-tools/src/test/java/org/apache/rat/tools/NamingTest.java index 501eb9c79..80eafe707 100644 --- a/apache-rat-tools/src/test/java/org/apache/rat/tools/NamingTest.java +++ b/apache-rat-tools/src/test/java/org/apache/rat/tools/NamingTest.java @@ -28,6 +28,7 @@ import org.apache.commons.io.IOUtils; import org.apache.rat.testhelpers.TextUtils; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.File; @@ -80,6 +81,7 @@ public void testCli() throws IOException, ParseException { } @Test + @Disabled("No deprecated options exist at this time") public void testCliDeprecated() throws IOException, ParseException { Naming.main(new String[]{"--cli", "--include-deprecated", file.getAbsolutePath()}); String result = readFile(file); @@ -148,6 +150,7 @@ public void testCliCsv() throws IOException, ParseException { } @Test + @Disabled("No deprecated options exist at this time") public void testCliCsvDeprecated() throws IOException, ParseException { Naming.main(new String[]{"--cli", "--csv", "--include-deprecated", file.getAbsolutePath()}); String result = readFile(file);