Merge pull request #4363 from adangel/pmd7-pr-4214
[cli] Add --relativize-paths-with option (pmd7)
This commit is contained in:
commit
ea17dd9a67
36 files changed
+761
-183
No files matched your search
@@ -122,7 +122,8 @@ The tool comes with a rather extensive help text, simply running with `--help`!
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="-language,-l"
|
||||
option_arg="lang"
|
||||
description="Specify the language PMD should use. Used together with `-version`. See also [Supported Languages](#supported-languages)."
|
||||
description="Specify the language PMD should use. Used together with `-version`. See also [Supported Languages](#supported-languages).
|
||||
<p><span class=\"label label-default\">Deprecated</span> since PMD 6.52.0. Use `--use-version` instead.</p>"
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="--minimum-priority"
|
||||
option_arg="priority"
|
||||
@@ -147,13 +148,17 @@ The tool comes with a rather extensive help text, simply running with `--help`!
|
||||
description="Specifies a property for the report renderer. The option can be specified several times.
|
||||
<p>Using `--help` will provide a complete list of supported properties for each report format</p>"
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="--relativize-paths-with,-z"
|
||||
option_arg="path"
|
||||
description="Path relative to which directories are rendered in the report. This option allows
|
||||
shortening directories in the report; without it, paths are rendered as mentioned in the source directory (option \"--dir\").
|
||||
The option can be repeated, in which case the shortest relative path will be used.
|
||||
If the root path is mentioned (e.g. \"/\" or \"C:\\\"), then the paths will be rendered as absolute."
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="--report-file,-r"
|
||||
option_arg="path"
|
||||
description="Path to a file to which report output is written. The file is created if it does not exist. If this option is not specified, the report is rendered to standard output."
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="--short-names"
|
||||
description="Prints shortened filenames in the report."
|
||||
%}
|
||||
{% include custom/cli_option_row.html options="--show-suppressed"
|
||||
description="Causes the suppressed rule violations to be added to the report."
|
||||
%}
|
||||
|
||||
@@ -77,11 +77,6 @@ The examples below won't repeat this taskdef element, as this is always required
|
||||
<td>The rule priority threshold; rules with lower priority than they will not be used</td>
|
||||
<td>No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>shortFilenames</td>
|
||||
<td>Places truncated filenames in the report. This can reduce your report file size by 15%-20%.</td>
|
||||
<td>No</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>failuresPropertyName</td>
|
||||
<td>A property name to plug the number of rule violations into when the task finishes</td>
|
||||
@@ -187,7 +182,7 @@ automatically and the latest language version is used.
|
||||
|
||||
<target name="pmd">
|
||||
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
|
||||
<pmd shortFilenames="true">
|
||||
<pmd>
|
||||
<ruleset>rulesets/java/quickstart.xml</ruleset>
|
||||
<ruleset>config/my-ruleset.xml</ruleset>
|
||||
<fileset dir="/usr/local/j2sdk1.4.1_01/src/">
|
||||
@@ -199,6 +194,11 @@ automatically and the latest language version is used.
|
||||
`fileset` nested element - specify the actual java source files, that PMD should analyze. You can use multiple
|
||||
fileset elements. See [FileSet](https://ant.apache.org/manual/Types/fileset.html) for the syntax and usage.
|
||||
|
||||
`relativizePathsWith` nested element - configures the paths relative to which directories are rendered in the report.
|
||||
This option allows shortening directories in the report; without it, paths are rendered as absolute paths.
|
||||
The option can be repeated, in which case the shortest relative path will be used.
|
||||
It is a [path-like structure](https://ant.apache.org/manual/using.html#path).
|
||||
|
||||
### Language version selection
|
||||
|
||||
PMD selects the language automatically using the file extension. If multiple versions of a language are
|
||||
@@ -410,7 +410,7 @@ An HTML report with the "linkPrefix" and "linePrefix" properties:
|
||||
|
||||
<target name="pmd">
|
||||
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
|
||||
<pmd rulesetfiles="rulesets/java/quickstart.xml" shortFilenames="true">
|
||||
<pmd rulesetfiles="rulesets/java/quickstart.xml">
|
||||
<formatter type="html" toFile="pmd_report.html">
|
||||
<param name="linkPrefix" value="https://maven.apache.org/plugins/maven-pmd-plugin/xref/"/>
|
||||
<param name="linePrefix" value="L"/>
|
||||
@@ -418,6 +418,9 @@ An HTML report with the "linkPrefix" and "linePrefix" properties:
|
||||
<fileset dir="/usr/local/j2sdk1.4.1_01/src/">
|
||||
<include name="java/lang/*.java"/>
|
||||
</fileset>
|
||||
<relativizePathsWith>
|
||||
<pathelement location="/usr/local/j2sdk1.4.1_01/src/"/>
|
||||
</relativizePathsWith>
|
||||
</pmd>
|
||||
</target>
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ See [the example report](report-examples/html-report-v2.html).
|
||||
* apex-bestpractices
|
||||
* [#2669](https://github.com/pmd/pmd/issues/2669): \[apex] UnusedLocalVariable false positive in dynamic SOQL
|
||||
* core
|
||||
* [#4026](https://github.com/pmd/pmd/issues/4026): \[cli] Filenames printed as absolute paths in the report despite parameter `--short-names`
|
||||
* [#4279](https://github.com/pmd/pmd/issues/4279): \[core] Can not set ruleset property value to empty
|
||||
* [#4329](https://github.com/pmd/pmd/pull/4329): \[core] Refactor usage of snakeyaml
|
||||
* [#4340](https://github.com/pmd/pmd/issues/4340): \[core] Allow to filter found matches in CPDReport
|
||||
@@ -38,6 +39,13 @@ See [the example report](report-examples/html-report-v2.html).
|
||||
|
||||
### API Changes
|
||||
|
||||
#### PMD CLI
|
||||
|
||||
* PMD now supports a new `--relativize-paths-with` flag (or short `-z`), which replaces `--short-names`.
|
||||
It serves the same purpose: Shortening the pathnames in the reports. However, with the new flag it's possible
|
||||
to explicitly define one or more pathnames that should be used as the base when creating relative paths.
|
||||
The old flag `--short-names` is deprecated.
|
||||
|
||||
#### Deprecated APIs
|
||||
|
||||
##### For removal
|
||||
@@ -57,6 +65,14 @@ See [the example report](report-examples/html-report-v2.html).
|
||||
functionality as unit tests.
|
||||
* {% jdoc core::cpd.CPDConfiguration.LanguageConverter %}
|
||||
|
||||
* {% jdoc !!core::lang.document.FileCollector#addZipFile(java.nio.file.Path) %} has been deprecated. It is replaced
|
||||
by {% jdoc !!core::lang.document.FileCollector#addZipFileWithContent(java.nio.file.Path) %} which directly adds the
|
||||
content of the zip file for analysis.
|
||||
|
||||
* {% jdoc !!core::PMDConfiguration#setReportShortNames(boolean) %} and
|
||||
{% jdoc !!core::PMDConfiguration#isReportShortNames() %} have been deprecated for removal.
|
||||
Use {% jdoc !!core::PMDConfiguration#addRelativizeRoot(java.nio.file.Path) %} instead.
|
||||
|
||||
##### Internal APIs
|
||||
|
||||
* {% jdoc core::renderers.CSVWriter %}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
package net.sourceforge.pmd.ant;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
@@ -14,8 +15,10 @@ import org.apache.tools.ant.Task;
|
||||
import org.apache.tools.ant.types.FileSet;
|
||||
import org.apache.tools.ant.types.Path;
|
||||
import org.apache.tools.ant.types.Reference;
|
||||
import org.apache.tools.ant.types.Resource;
|
||||
|
||||
import net.sourceforge.pmd.RulePriority;
|
||||
import net.sourceforge.pmd.annotation.InternalApi;
|
||||
import net.sourceforge.pmd.ant.internal.PMDTaskImpl;
|
||||
|
||||
/**
|
||||
@@ -30,7 +33,7 @@ public class PMDTask extends Task {
|
||||
private final List<FileSet> filesets = new ArrayList<>();
|
||||
private boolean failOnError;
|
||||
private boolean failOnRuleViolation;
|
||||
private boolean shortFilenames;
|
||||
private final List<Path> relativizePathsWith = new ArrayList<>();
|
||||
private String suppressMarker;
|
||||
private String rulesetFiles;
|
||||
private boolean noRuleSetCompatibility;
|
||||
@@ -94,10 +97,6 @@ public class PMDTask extends Task {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public void setShortFilenames(boolean reportShortNames) {
|
||||
this.shortFilenames = reportShortNames;
|
||||
}
|
||||
|
||||
public void setSuppressMarker(String suppressMarker) {
|
||||
this.suppressMarker = suppressMarker;
|
||||
}
|
||||
@@ -207,10 +206,6 @@ public class PMDTask extends Task {
|
||||
return failOnRuleViolation;
|
||||
}
|
||||
|
||||
public boolean isShortFilenames() {
|
||||
return shortFilenames;
|
||||
}
|
||||
|
||||
public String getSuppressMarker() {
|
||||
return suppressMarker;
|
||||
}
|
||||
@@ -271,4 +266,23 @@ public class PMDTask extends Task {
|
||||
public void setNoCache(boolean noCache) {
|
||||
this.noCache = noCache;
|
||||
}
|
||||
|
||||
public void addRelativizePathsWith(Path relativizePathsWith) {
|
||||
this.relativizePathsWith.add(relativizePathsWith);
|
||||
}
|
||||
|
||||
public List<Path> getRelativizePathsWith() {
|
||||
return relativizePathsWith;
|
||||
}
|
||||
|
||||
@InternalApi
|
||||
public List<java.nio.file.Path> getRelativizeRoots() {
|
||||
List<java.nio.file.Path> paths = new ArrayList<>();
|
||||
for (Path path : getRelativizePathsWith()) {
|
||||
for (Resource resource : path) {
|
||||
paths.add(Paths.get(resource.toString()));
|
||||
}
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ public class PMDTaskImpl {
|
||||
private Project project;
|
||||
|
||||
public PMDTaskImpl(PMDTask task) {
|
||||
configuration.setReportShortNames(task.isShortFilenames());
|
||||
configuration.addRelativizeRoots(task.getRelativizeRoots());
|
||||
if (task.getSuppressMarker() != null) {
|
||||
configuration.setSuppressMarker(task.getSuppressMarker());
|
||||
}
|
||||
@@ -103,7 +103,6 @@ public class PMDTaskImpl {
|
||||
project.log("Setting suppress marker to be " + configuration.getSuppressMarker(), Project.MSG_VERBOSE);
|
||||
}
|
||||
|
||||
|
||||
List<String> ruleSetPaths = expandRuleSetPaths(configuration.getRuleSetPaths());
|
||||
// don't let PmdAnalysis.create create rulesets itself.
|
||||
configuration.setRuleSets(Collections.emptyList());
|
||||
@@ -116,9 +115,6 @@ public class PMDTaskImpl {
|
||||
|
||||
for (FileSet fileset : filesets) {
|
||||
DirectoryScanner ds = fileset.getDirectoryScanner(project);
|
||||
if (configuration.isReportShortNames()) {
|
||||
pmd.files().relativizeWith(ds.getBasedir().getPath());
|
||||
}
|
||||
for (String srcFile : ds.getIncludedFiles()) {
|
||||
pmd.files().addFile(ds.getBasedir().toPath().resolve(srcFile));
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -69,14 +70,14 @@ class PMDTaskTest extends AbstractAntTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testWithShortFilenames() throws IOException {
|
||||
executeTarget("testWithShortFilenames");
|
||||
void testRelativizeWith() throws IOException {
|
||||
executeTarget("testRelativizeWith");
|
||||
|
||||
try (InputStream in = Files.newInputStream(Paths.get("target/pmd-ant-test.txt"))) {
|
||||
String actual = IOUtil.readToString(in, StandardCharsets.UTF_8);
|
||||
// remove any trailing newline
|
||||
actual = actual.trim();
|
||||
assertThat(actual, containsString("sample.dummy:1:\tSampleXPathRule:\tTest Rule 2"));
|
||||
actual = actual.replaceAll("\n|\r", "");
|
||||
assertThat(actual, containsString("src" + File.separator + "sample.dummy:1:\tSampleXPathRule:\tTest Rule 2"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,25 +25,31 @@
|
||||
<pmd />
|
||||
</target>
|
||||
|
||||
<target name="testWithShortFilenames">
|
||||
<pmd noCache="true" shortFilenames="true">
|
||||
<target name="testRelativizeWith">
|
||||
<pmd noCache="true">
|
||||
<!-- note: this ruleset is in pmd-core/src/test/resources -->
|
||||
<ruleset>rulesets/dummy/basic.xml</ruleset>
|
||||
<formatter type="text" toFile="${pmd.home}/target/pmd-ant-test.txt" />
|
||||
<fileset dir="${pmd.home}/src/test/resources/net/sourceforge/pmd/ant/src">
|
||||
<fileset dir="${pmd.home}/src/test/resources/net/sourceforge/pmd/ant/">
|
||||
<include name="**/*dummy"/>
|
||||
</fileset>
|
||||
<relativizePathsWith>
|
||||
<pathelement location="${pmd.home}/src/test/resources/net/sourceforge/pmd/ant"/>
|
||||
</relativizePathsWith>
|
||||
</pmd>
|
||||
</target>
|
||||
|
||||
<target name="testXmlFormatter">
|
||||
<pmd noCache="true" shortFilenames="true">
|
||||
<pmd noCache="true">
|
||||
<!-- note: this ruleset is in pmd-core/src/test/resources -->
|
||||
<ruleset>rulesets/dummy/basic.xml</ruleset>
|
||||
<formatter type="xml" toFile="${pmd.home}/target/pmd-ant-xml.xml" />
|
||||
<fileset dir="${pmd.home}/src/test/resources/net/sourceforge/pmd/ant/src">
|
||||
<include name="**/*dummy"/>
|
||||
</fileset>
|
||||
<relativizePathsWith>
|
||||
<pathelement location="${pmd.home}/src/test/resources/net/sourceforge/pmd/ant/src"/>
|
||||
</relativizePathsWith>
|
||||
</pmd>
|
||||
</target>
|
||||
</project>
|
||||
@@ -7,6 +7,7 @@ package net.sourceforge.pmd.cli.commands.internal;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
@@ -84,7 +85,7 @@ public class PmdCommand extends AbstractAnalysisPmdSubcommand {
|
||||
|
||||
private boolean benchmark;
|
||||
|
||||
private boolean shortnames;
|
||||
private List<Path> relativizeRootPaths;
|
||||
|
||||
private boolean showSuppressed;
|
||||
|
||||
@@ -140,9 +141,21 @@ public class PmdCommand extends AbstractAnalysisPmdSubcommand {
|
||||
this.benchmark = benchmark;
|
||||
}
|
||||
|
||||
@Option(names = "--short-names", description = "Prints shortened filenames in the report.")
|
||||
public void setShortnames(final boolean shortnames) {
|
||||
this.shortnames = shortnames;
|
||||
@Option(names = { "--relativize-paths-with", "-z"}, description = "Path relative to which directories are rendered in the report. "
|
||||
+ "This option allows shortening directories in the report; "
|
||||
+ "without it, paths are rendered as mentioned in the source directory (option \"--dir\"). "
|
||||
+ "The option can be repeated, in which case the shortest relative path will be used. "
|
||||
+ "If the root path is mentioned (e.g. \"/\" or \"C:\\\"), then the paths will be rendered as absolute.",
|
||||
arity = "1..*", split = ",")
|
||||
public void setRelativizePathsWith(List<Path> rootPaths) {
|
||||
this.relativizeRootPaths = rootPaths;
|
||||
|
||||
for (Path path : this.relativizeRootPaths) {
|
||||
if (Files.isRegularFile(path)) {
|
||||
throw new ParameterException(spec.commandLine(),
|
||||
"Expected a directory path for option '--relativize-paths-with', found a file: " + path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Option(names = "--show-suppressed", description = "Report should show suppressed rule violations.")
|
||||
@@ -272,7 +285,9 @@ public class PmdCommand extends AbstractAnalysisPmdSubcommand {
|
||||
configuration.setMinimumPriority(minimumPriority);
|
||||
configuration.setReportFile(reportFile);
|
||||
configuration.setReportProperties(properties);
|
||||
configuration.setReportShortNames(shortnames);
|
||||
if (relativizeRootPaths != null) {
|
||||
configuration.addRelativizeRoots(relativizeRootPaths);
|
||||
}
|
||||
configuration.setRuleSets(rulesets);
|
||||
configuration.setRuleSetFactoryCompatibilityEnabled(!this.noRuleSetCompatibility);
|
||||
configuration.setShowSuppressedViolations(showSuppressed);
|
||||
|
||||
@@ -11,13 +11,16 @@ import static net.sourceforge.pmd.util.CollectionUtil.listOf;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.containsStringIgnoringCase;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintStream;
|
||||
@@ -26,23 +29,28 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import net.sourceforge.pmd.RuleContext;
|
||||
import net.sourceforge.pmd.cli.internal.CliExitCode;
|
||||
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
|
||||
import net.sourceforge.pmd.lang.ast.Node;
|
||||
import net.sourceforge.pmd.lang.rule.MockRule;
|
||||
import net.sourceforge.pmd.util.IOUtil;
|
||||
|
||||
import com.github.stefanbirkner.systemlambda.SystemLambda;
|
||||
|
||||
class PmdCliTest extends BaseCliTest {
|
||||
|
||||
private static final String DUMMY_RULESET_WITH_VIOLATIONS = "net/sourceforge/pmd/cli/FakeRuleset2.xml";
|
||||
static final String RULESET_WITH_VIOLATION = "net/sourceforge/pmd/cli/RuleSetWithViolations.xml";
|
||||
private static final String RULESET_NO_VIOLATIONS = "net/sourceforge/pmd/cli/FakeRuleset.xml";
|
||||
private static final String NOT_A_RULESET = "ThisRuleSetDoesNotExist.xml";
|
||||
@@ -52,8 +60,8 @@ class PmdCliTest extends BaseCliTest {
|
||||
private Path tempDir;
|
||||
private Path srcDir;
|
||||
|
||||
@AfterAll
|
||||
static void resetLogging() {
|
||||
@AfterEach
|
||||
void resetLogging() {
|
||||
// reset logging in case "--debug" changed the logging properties
|
||||
// See also Slf4jSimpleConfigurationForAnt
|
||||
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null);
|
||||
@@ -61,12 +69,8 @@ class PmdCliTest extends BaseCliTest {
|
||||
|
||||
@BeforeEach
|
||||
void setup() throws IOException {
|
||||
// set current directory to wd
|
||||
Path root = tempRoot();
|
||||
System.setProperty("user.dir", root.toString());
|
||||
|
||||
// create a few files
|
||||
srcDir = Files.createDirectories(root.resolve("src"));
|
||||
srcDir = Files.createDirectories(tempRoot().resolve("src"));
|
||||
writeString(srcDir.resolve("someSource.dummy"), "dummy text");
|
||||
}
|
||||
|
||||
@@ -311,7 +315,7 @@ class PmdCliTest extends BaseCliTest {
|
||||
Path zipArchive = createTemporaryZipArchive("sources.zip");
|
||||
CliExecutionResult result = runCli(VIOLATIONS_FOUND, "--dir", zipArchive.toString(), "--rulesets", "rulesets/dummy/basic.xml");
|
||||
result.checkStdErr(not(containsStringIgnoringCase("Cannot open zip file")));
|
||||
String reportPath = IOUtil.normalizePath(zipArchive + "!/someSource.dummy");
|
||||
String reportPath = IOUtil.normalizePath(zipArchive.toString()) + "!/someSource.dummy";
|
||||
result.checkStdOut(containsString(reportPath + ":1:\tSampleXPathRule:\tTest Rule 2"));
|
||||
}
|
||||
|
||||
@@ -320,7 +324,7 @@ class PmdCliTest extends BaseCliTest {
|
||||
Path jarArchive = createTemporaryZipArchive("sources.jar");
|
||||
CliExecutionResult result = runCli(VIOLATIONS_FOUND, "--dir", jarArchive.toString(), "--rulesets", "rulesets/dummy/basic.xml");
|
||||
result.checkStdErr(not(containsStringIgnoringCase("Cannot open zip file")));
|
||||
String reportPath = IOUtil.normalizePath(jarArchive + "!/someSource.dummy");
|
||||
String reportPath = IOUtil.normalizePath(jarArchive.toString()) + "!/someSource.dummy";
|
||||
result.checkStdOut(containsString(reportPath + ":1:\tSampleXPathRule:\tTest Rule 2"));
|
||||
}
|
||||
|
||||
@@ -335,6 +339,131 @@ class PmdCliTest extends BaseCliTest {
|
||||
return zipArchive;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoRelativizeWithAbsoluteSrcDir() throws Exception {
|
||||
assertTrue(srcDir.isAbsolute(), "srcDir should be absolute");
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS)
|
||||
.verify(result -> result.checkStdOut(
|
||||
containsString(srcDir.resolve("someSource.dummy").toString())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoRelativizeWithRelativeSrcDir() throws Exception {
|
||||
// Note, that we can't reliably change the current working directory for the current java process
|
||||
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
|
||||
Path cwd = Paths.get(".").toRealPath();
|
||||
assertThat(cwd.toString(), endsWith("pmd-cli"));
|
||||
String relativeSrcDir = "src/test/resources/net/sourceforge/pmd/cli/src";
|
||||
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
|
||||
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", relativeSrcDir, "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS)
|
||||
.verify(result -> result.checkStdOut(
|
||||
containsString("\n" + IOUtil.normalizePath(relativeSrcDir + "/somefile.dummy"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testNoRelativizeWithRelativeSrcDirParent() throws Exception {
|
||||
// Note, that we can't reliably change the current working directory for the current java process
|
||||
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
|
||||
Path cwd = Paths.get(".").toRealPath();
|
||||
assertThat(cwd.toString(), endsWith("pmd-cli"));
|
||||
String relativeSrcDir = IOUtil.normalizePath("src/test/resources/net/sourceforge/pmd/cli/src");
|
||||
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
|
||||
|
||||
// use the parent directory
|
||||
String relativeSrcDirWithParent = relativeSrcDir + File.separator + "..";
|
||||
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", relativeSrcDirWithParent, "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS)
|
||||
.verify(result -> result.checkStdOut(
|
||||
containsString("\n" + relativeSrcDirWithParent + IOUtil.normalizePath("/src/somefile.dummy"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithRootRelativeSrcDir() throws Exception {
|
||||
// Note, that we can't reliably change the current working directory for the current java process
|
||||
// therefore we use the current directory and make sure, we are at the correct place - in pmd-core
|
||||
Path cwd = Paths.get(".").toRealPath();
|
||||
assertThat(cwd.toString(), endsWith("pmd-cli"));
|
||||
String relativeSrcDir = "src/test/resources/net/sourceforge/pmd/cli/src";
|
||||
assertTrue(Files.isDirectory(cwd.resolve(relativeSrcDir)));
|
||||
|
||||
String root = cwd.getRoot().toString();
|
||||
String absoluteSrcPath = cwd.resolve(relativeSrcDir).resolve("somefile.dummy").toString();
|
||||
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", relativeSrcDir, "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "--relativize-paths-with", root)
|
||||
.verify(result -> result.checkStdOut(
|
||||
containsString("\n" + absoluteSrcPath))
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWith() throws Exception {
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.getParent().toString())
|
||||
.verify(result -> {
|
||||
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
|
||||
result.checkStdOut(startsWith(IOUtil.normalizePath("src/someSource.dummy")));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithSymLink() throws Exception {
|
||||
// srcDir = /tmp/junit123/src
|
||||
// symlinkedSrcDir = /tmp/junit123/sources -> /tmp/junit123/src
|
||||
Path symlinkedSrcDir = Files.createSymbolicLink(tempRoot().resolve("sources"), srcDir);
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", symlinkedSrcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "-z", symlinkedSrcDir.toString())
|
||||
.verify(result -> {
|
||||
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
|
||||
result.checkStdOut(not(containsString(symlinkedSrcDir.resolve("someSource.dummy").toString())));
|
||||
result.checkStdOut(startsWith("someSource.dummy"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithSymLinkParent() throws Exception {
|
||||
// srcDir = /tmp/junit123/src
|
||||
// symlinkedSrcDir = /tmp/junit-relativize-with-123 -> /tmp/junit123/src
|
||||
Path tempPath = Files.createTempDirectory("junit-relativize-with-");
|
||||
Files.delete(tempPath);
|
||||
Path symlinkedSrcDir = Files.createSymbolicLink(tempPath, srcDir);
|
||||
// relativizing against parent of symlinkedSrcDir: /tmp
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", symlinkedSrcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "-z", symlinkedSrcDir.getParent().toString())
|
||||
.verify(result -> {
|
||||
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
|
||||
result.checkStdOut(not(containsString(symlinkedSrcDir.resolve("someSource.dummy").toString())));
|
||||
// base path is symlinkedSrcDir without /tmp: e.g. junit-relativize-with-123
|
||||
String basePath = symlinkedSrcDir.getParent().relativize(symlinkedSrcDir).toString();
|
||||
result.checkStdOut(startsWith(basePath + File.separator + "someSource.dummy"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithMultiple() throws Exception {
|
||||
runCli(CliExitCode.VIOLATIONS_FOUND, "--dir", srcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.getParent().toString() + "," + srcDir.toString())
|
||||
.verify(result -> {
|
||||
result.checkStdOut(not(containsString(srcDir.resolve("someSource.dummy").toString())));
|
||||
result.checkStdOut(startsWith("someSource.dummy"));
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithFileIsError() throws Exception {
|
||||
runCli(CliExitCode.USAGE_ERROR, "--dir", srcDir.toString(), "--rulesets",
|
||||
DUMMY_RULESET_WITH_VIOLATIONS, "-z", srcDir.resolve("someSource.dummy").toString())
|
||||
.verify(result -> result.checkStdErr(
|
||||
containsString(
|
||||
"Expected a directory path for option '--relativize-paths-with', found a file: "
|
||||
+ srcDir.resolve("someSource.dummy"))
|
||||
));
|
||||
}
|
||||
|
||||
// utilities
|
||||
private Path tempRoot() {
|
||||
return tempDir;
|
||||
@@ -361,4 +490,11 @@ class PmdCliTest extends BaseCliTest {
|
||||
"check", "--no-cache", "--no-progress"
|
||||
);
|
||||
}
|
||||
|
||||
public static class FooRule extends MockRule {
|
||||
@Override
|
||||
public void apply(Node node, RuleContext ctx) {
|
||||
ctx.addViolation(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="Test Ruleset" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>
|
||||
Ruleset used by net.sourceforge.pmd.cli.PmdCliTest
|
||||
</description>
|
||||
|
||||
<rule name="Ruleset3Rule1" language="dummy" since="1.0" message="Test Rule 1" class="net.sourceforge.pmd.cli.PmdCliTest$FooRule"
|
||||
externalInfoUrl="${pmd.website.baseurl}/rules/test/TestRuleset3.xml#Ruleset3Rule1">
|
||||
<description>
|
||||
Just for test
|
||||
</description>
|
||||
<priority>3</priority>
|
||||
<example>
|
||||
<![CDATA[
|
||||
]]>
|
||||
</example>
|
||||
</rule>
|
||||
|
||||
</ruleset>
|
||||
@@ -0,0 +1 @@
|
||||
Another file for testing
|
||||
@@ -0,0 +1 @@
|
||||
Some file for testing
|
||||
@@ -0,0 +1 @@
|
||||
Some file for testing
|
||||
@@ -0,0 +1 @@
|
||||
Some file for testing
|
||||
@@ -0,0 +1 @@
|
||||
Some file for testing
|
||||
@@ -0,0 +1 @@
|
||||
Some file for testing
|
||||
@@ -16,6 +16,7 @@ import java.util.Map.Entry;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.commons.lang3.exception.ExceptionUtils;
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -155,9 +156,17 @@ public final class PMD {
|
||||
return StatusCode.ERROR;
|
||||
}
|
||||
|
||||
PMDConfiguration configuration = Objects.requireNonNull(
|
||||
parseResult.toConfiguration()
|
||||
);
|
||||
PMDConfiguration configuration = null;
|
||||
try {
|
||||
configuration = Objects.requireNonNull(
|
||||
parseResult.toConfiguration()
|
||||
);
|
||||
} catch (IllegalArgumentException e) {
|
||||
System.err.println("Cannot start analysis: " + e);
|
||||
log.debug(ExceptionUtils.getStackTrace(e));
|
||||
return StatusCode.ERROR;
|
||||
}
|
||||
|
||||
MessageReporter pmdReporter = setupMessageReporter(configuration);
|
||||
configuration.setReporter(pmdReporter);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ package net.sourceforge.pmd;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
@@ -78,8 +79,8 @@ import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
|
||||
* <ul>
|
||||
* <li>The renderer format to use for Reports. {@link #getReportFormat()}</li>
|
||||
* <li>The file to which the Report should render. {@link #getReportFile()}</li>
|
||||
* <li>An indicator of whether to use File short names in Reports, defaults to
|
||||
* <code>false</code>. {@link #isReportShortNames()}</li>
|
||||
* <li>Configure the root paths that are used to relativize file names in reports via {@link #addRelativizeRoot(Path)}.
|
||||
* This enables to get short names in reports.</li>
|
||||
* <li>The initialization properties to use when creating a Renderer instance.
|
||||
* {@link #getReportProperties()}</li>
|
||||
* <li>An indicator of whether to show suppressed Rule violations in Reports.
|
||||
@@ -122,7 +123,6 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
// Reporting options
|
||||
private String reportFormat;
|
||||
private Path reportFile;
|
||||
private boolean reportShortNames = false;
|
||||
private Properties reportProperties = new Properties();
|
||||
private boolean showSuppressedViolations = false;
|
||||
private boolean failOnViolation = true;
|
||||
@@ -134,6 +134,7 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
private AnalysisCache analysisCache = new NoopAnalysisCache();
|
||||
private boolean ignoreIncrementalAnalysis;
|
||||
private final LanguageRegistry langRegistry;
|
||||
private final List<Path> relativizeRoots = new ArrayList<>();
|
||||
|
||||
public PMDConfiguration() {
|
||||
this(DEFAULT_REGISTRY);
|
||||
@@ -483,7 +484,7 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
* @param inputPaths The comma separated list.
|
||||
*
|
||||
* @throws NullPointerException If the parameter is null
|
||||
* @deprecated Use {@link #setInputPaths(List)} or {@link #addInputPath(String)}
|
||||
* @deprecated Use {@link #setInputPathList(List)} or {@link #addInputPath(Path)}
|
||||
*/
|
||||
@Deprecated
|
||||
public void setInputPaths(String inputPaths) {
|
||||
@@ -600,25 +601,6 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
this.inputUri = inputUri;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get whether to use File short names in Reports.
|
||||
*
|
||||
* @return <code>true</code> when using short names in reports.
|
||||
*/
|
||||
public boolean isReportShortNames() {
|
||||
return reportShortNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set whether to use File short names in Reports.
|
||||
*
|
||||
* @param reportShortNames
|
||||
* <code>true</code> when using short names in reports.
|
||||
*/
|
||||
public void setReportShortNames(boolean reportShortNames) {
|
||||
this.reportShortNames = reportShortNames;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Renderer instance based upon the configured reporting options.
|
||||
* No writer is created.
|
||||
@@ -882,8 +864,8 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
*/
|
||||
public void setAnalysisCacheLocation(final String cacheLocation) {
|
||||
setAnalysisCache(cacheLocation == null
|
||||
? new NoopAnalysisCache()
|
||||
: new FileAnalysisCache(new File(cacheLocation)));
|
||||
? new NoopAnalysisCache()
|
||||
: new FileAnalysisCache(new File(cacheLocation)));
|
||||
}
|
||||
|
||||
|
||||
@@ -909,4 +891,56 @@ public class PMDConfiguration extends AbstractConfiguration {
|
||||
public boolean isIgnoreIncrementalAnalysis() {
|
||||
return ignoreIncrementalAnalysis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the path used to shorten paths output in the report.
|
||||
* The path does not need to exist. If it exists, it must point
|
||||
* to a directory and not a file. See {@link #getRelativizeRoots()}
|
||||
* for the interpretation.
|
||||
*
|
||||
* <p>If several paths are added, the shortest paths possible are
|
||||
* built.
|
||||
*
|
||||
* @param path A path
|
||||
*
|
||||
* @throws IllegalArgumentException If the path points to a file, and not a directory
|
||||
* @throws NullPointerException If the path is null
|
||||
*/
|
||||
public void addRelativizeRoot(Path path) {
|
||||
// Note: the given path is not further modified or resolved. E.g. there is no special handling for symlinks.
|
||||
// The goal is, that if the user inputs a path, PMD should output in terms of that path, not it's resolution.
|
||||
this.relativizeRoots.add(Objects.requireNonNull(path));
|
||||
|
||||
if (Files.isRegularFile(path)) {
|
||||
throw new IllegalArgumentException("Relativize root should be a directory: " + path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add several paths to shorten paths that are output in the report.
|
||||
* See {@link #addRelativizeRoot(Path)}.
|
||||
*
|
||||
* @param paths A list of non-null paths
|
||||
*
|
||||
* @throws IllegalArgumentException If any path points to a file, and not a directory
|
||||
* @throws NullPointerException If the list, or any path in the list is null
|
||||
*/
|
||||
public void addRelativizeRoots(List<Path> paths) {
|
||||
for (Path path : paths) {
|
||||
addRelativizeRoot(path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the paths used to shorten paths output in the report.
|
||||
* <ul>
|
||||
* <li>If the list is empty, then paths are not touched
|
||||
* <li>If the list is non-empty, then source file paths are relativized with all the items in the list.
|
||||
* The shortest of these relative paths is taken as the display name of the file.
|
||||
* </ul>
|
||||
*/
|
||||
public List<Path> getRelativizeRoots() {
|
||||
return Collections.unmodifiableList(relativizeRoots);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package net.sourceforge.pmd;
|
||||
|
||||
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
@@ -99,6 +100,10 @@ public final class PmdAnalysis implements AutoCloseable {
|
||||
config.getLanguageVersionDiscoverer(),
|
||||
reporter
|
||||
);
|
||||
|
||||
for (Path path : config.getRelativizeRoots()) {
|
||||
this.collector.relativizeWith(path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
package net.sourceforge.pmd.cli;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -35,6 +38,7 @@ import com.beust.jcommander.validators.PositiveInteger;
|
||||
@InternalApi
|
||||
public class PMDParameters {
|
||||
|
||||
static final String RELATIVIZE_PATHS_WITH = "--relativize-paths-with";
|
||||
@Parameter(names = { "--rulesets", "-rulesets", "-R" },
|
||||
description = "Path to a ruleset xml file. "
|
||||
+ "The path may reference a resource on the classpath of the application, be a local file system path, or a URL. "
|
||||
@@ -99,9 +103,6 @@ public class PMDParameters {
|
||||
@Parameter(names = { "--stress", "-stress", "-S" }, description = "Performs a stress test.")
|
||||
private boolean stress = false;
|
||||
|
||||
@Parameter(names = { "--short-names", "-shortnames" }, description = "Prints shortened filenames in the report.")
|
||||
private boolean shortnames = false;
|
||||
|
||||
@Parameter(names = { "--show-suppressed", "-showsuppressed" }, description = "Report should show suppressed rule violations.")
|
||||
private boolean showsuppressed = false;
|
||||
|
||||
@@ -125,6 +126,17 @@ public class PMDParameters {
|
||||
+ "If this option is not specified, the report is rendered to standard output.")
|
||||
private String reportfile = null;
|
||||
|
||||
@Parameter(names = { RELATIVIZE_PATHS_WITH, "-z" },
|
||||
variableArity = true,
|
||||
description = "Path relative to which directories are rendered in the report. "
|
||||
+ "This option allows shortening directories in the report; "
|
||||
+ "without it, paths are rendered as mentioned in the source directory (option \"--dir\"). "
|
||||
+ "The option can be repeated, in which case the shortest relative path will be used. "
|
||||
+ "If the root path is mentioned (e.g. \"/\" or \"C:\\\"), then the paths will be rendered as absolute.",
|
||||
validateValueWith = PathToRelativizeRootValidator.class,
|
||||
converter = StringToPathConverter.class)
|
||||
private List<Path> relativizePathRoot = new ArrayList<>();
|
||||
|
||||
@Parameter(names = { "-version", "-v" }, description = "Specify version of a language PMD should use.")
|
||||
private String version = null;
|
||||
|
||||
@@ -203,6 +215,23 @@ public class PMDParameters {
|
||||
}
|
||||
}
|
||||
|
||||
public static class PathToRelativizeRootValidator implements IValueValidator<List<Path>> {
|
||||
@Override
|
||||
public void validate(String name, List<Path> value) throws ParameterException {
|
||||
for (Path p : value) {
|
||||
if (Files.isRegularFile(p)) {
|
||||
throw new ParameterException("Expected a directory path for option " + name + ", found a file: " + p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringToPathConverter implements IStringConverter<Path> {
|
||||
@Override
|
||||
public Path convert(String value) {
|
||||
return Paths.get(value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts these parameters into a configuration.
|
||||
@@ -236,10 +265,10 @@ public class PMDParameters {
|
||||
configuration.setReportFormat(this.getFormat());
|
||||
configuration.setBenchmark(this.isBenchmark());
|
||||
configuration.setDebug(this.isDebug());
|
||||
configuration.addRelativizeRoots(this.relativizePathRoot);
|
||||
configuration.setMinimumPriority(this.getMinimumPriority());
|
||||
configuration.setReportFile(this.getReportfile());
|
||||
configuration.setReportProperties(this.getProperties());
|
||||
configuration.setReportShortNames(this.isShortnames());
|
||||
configuration.setRuleSets(Arrays.asList(this.getRulesets().split(",")));
|
||||
configuration.setRuleSetFactoryCompatibilityEnabled(!this.noRuleSetCompatibility);
|
||||
configuration.setShowSuppressedViolations(this.isShowsuppressed());
|
||||
@@ -321,10 +350,6 @@ public class PMDParameters {
|
||||
return stress;
|
||||
}
|
||||
|
||||
public boolean isShortnames() {
|
||||
return shortnames;
|
||||
}
|
||||
|
||||
public boolean isShowsuppressed() {
|
||||
return showsuppressed;
|
||||
}
|
||||
|
||||
@@ -143,6 +143,7 @@ public final class PmdParametersParseResult {
|
||||
/** Map of deprecated option to suggested replacement. */
|
||||
private static final Map<String, String> SUGGESTED_REPLACEMENT;
|
||||
|
||||
|
||||
static {
|
||||
Map<String, String> m = new LinkedHashMap<>();
|
||||
|
||||
@@ -159,7 +160,8 @@ public final class PmdParametersParseResult {
|
||||
m.put("-threads", "--threads");
|
||||
m.put("-benchmark", "--benchmark");
|
||||
m.put("-stress", "--stress");
|
||||
m.put("-shortnames", "--short-names");
|
||||
m.put("-shortnames", PMDParameters.RELATIVIZE_PATHS_WITH);
|
||||
m.put("--short-names", PMDParameters.RELATIVIZE_PATHS_WITH);
|
||||
m.put("-showsuppressed", "--show-suppressed");
|
||||
m.put("-suppressmarker", "--suppress-marker");
|
||||
m.put("-minimumpriority", "--minimum-priority");
|
||||
|
||||
@@ -7,7 +7,6 @@ package net.sourceforge.pmd.internal.util;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.net.URI;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.SQLException;
|
||||
@@ -42,12 +41,14 @@ public final class FileCollectionUtil {
|
||||
collector.setCharset(configuration.getSourceEncoding());
|
||||
}
|
||||
|
||||
|
||||
collectFiles(collector, configuration.getInputPathList());
|
||||
|
||||
if (configuration.getUri() != null) {
|
||||
collectDB(collector, configuration.getUri());
|
||||
}
|
||||
|
||||
|
||||
if (configuration.getInputFile() != null) {
|
||||
collectFileList(collector, configuration.getInputFile());
|
||||
}
|
||||
@@ -104,15 +105,7 @@ public final class FileCollectionUtil {
|
||||
LOG.debug("Adding directory {}.", path);
|
||||
collector.addDirectory(path);
|
||||
} else if (pathStr.endsWith(".zip") || pathStr.endsWith(".jar")) {
|
||||
LOG.debug("Adding zip file {}.", path);
|
||||
@SuppressWarnings("PMD.CloseResource")
|
||||
FileSystem fs = collector.addZipFile(path);
|
||||
if (fs == null) {
|
||||
return;
|
||||
}
|
||||
for (Path zipRoot : fs.getRootDirectories()) {
|
||||
collector.addFileOrDirectory(zipRoot);
|
||||
}
|
||||
collector.addZipFileWithContent(path);
|
||||
} else if (Files.isRegularFile(path)) {
|
||||
LOG.debug("Adding regular file {}.", path);
|
||||
collector.addFile(path);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -5,16 +5,13 @@
|
||||
package net.sourceforge.pmd.lang.document;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.checkerframework.checker.nullness.qual.Nullable;
|
||||
|
||||
import net.sourceforge.pmd.internal.util.AssertionUtil;
|
||||
import net.sourceforge.pmd.internal.util.BaseCloseable;
|
||||
@@ -28,18 +25,19 @@ class NioTextFile extends BaseCloseable implements TextFile {
|
||||
private final Path path;
|
||||
private final Charset charset;
|
||||
private final LanguageVersion languageVersion;
|
||||
private final @Nullable String displayName;
|
||||
private final String displayName;
|
||||
private final String pathId;
|
||||
private boolean readOnly;
|
||||
|
||||
NioTextFile(Path path,
|
||||
Charset charset,
|
||||
LanguageVersion languageVersion,
|
||||
@Nullable String displayName,
|
||||
String displayName,
|
||||
boolean readOnly) {
|
||||
AssertionUtil.requireParamNotNull("path", path);
|
||||
AssertionUtil.requireParamNotNull("charset", charset);
|
||||
AssertionUtil.requireParamNotNull("language version", languageVersion);
|
||||
AssertionUtil.requireParamNotNull("display name", displayName);
|
||||
|
||||
this.displayName = displayName;
|
||||
this.readOnly = readOnly;
|
||||
@@ -57,13 +55,7 @@ class NioTextFile extends BaseCloseable implements TextFile {
|
||||
|
||||
@Override
|
||||
public @NonNull String getDisplayName() {
|
||||
if (displayName != null) {
|
||||
return displayName;
|
||||
}
|
||||
if ("jar".equals(path.toUri().getScheme())) {
|
||||
return new File(URI.create(path.toUri().getSchemeSpecificPart()).getPath()).toString();
|
||||
}
|
||||
return path.toString();
|
||||
return displayName;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -160,7 +160,9 @@ public interface TextFile extends Closeable {
|
||||
* @throws NullPointerException If any parameter is null
|
||||
*/
|
||||
static TextFile forPath(Path path, Charset charset, LanguageVersion languageVersion) {
|
||||
return builderForPath(path, charset, languageVersion).build();
|
||||
return builderForPath(path, charset, languageVersion)
|
||||
.withDisplayName(path.toString())
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,7 +196,9 @@ public interface TextFile extends Closeable {
|
||||
* @throws NullPointerException If any parameter is null
|
||||
*/
|
||||
static TextFile forCharSeq(CharSequence charseq, String pathId, LanguageVersion languageVersion) {
|
||||
return builderForCharSeq(charseq, pathId, languageVersion).build();
|
||||
return builderForCharSeq(charseq, pathId, languageVersion)
|
||||
.withDisplayName(pathId)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -226,7 +230,9 @@ public interface TextFile extends Closeable {
|
||||
* @throws NullPointerException If any parameter is null
|
||||
*/
|
||||
static TextFile forReader(Reader reader, String pathId, LanguageVersion languageVersion) {
|
||||
return builderForReader(reader, pathId, languageVersion).build();
|
||||
return builderForReader(reader, pathId, languageVersion)
|
||||
.withDisplayName(pathId)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -277,7 +283,7 @@ public interface TextFile extends Closeable {
|
||||
|
||||
@Override
|
||||
public @NonNull String getDisplayName() {
|
||||
return ds.getNiceFileName(config.isReportShortNames(), shortPaths);
|
||||
return ds.getNiceFileName(false, shortPaths);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -15,10 +15,9 @@ import net.sourceforge.pmd.util.datasource.internal.PathDataSource;
|
||||
public class FileDataSource extends PathDataSource {
|
||||
|
||||
/**
|
||||
* @param file
|
||||
* the file to read
|
||||
* @param file the file to read
|
||||
*/
|
||||
public FileDataSource(File file) {
|
||||
super(file.toPath());
|
||||
super(file.toPath(), null);
|
||||
}
|
||||
}
|
||||
+13
@@ -21,13 +21,23 @@ import net.sourceforge.pmd.internal.util.ShortFilenameUtil;
|
||||
*/
|
||||
//TODO This class (and all other DataSources) can be probably removed with PMD 7 in favor of TextFile
|
||||
public class PathDataSource extends AbstractDataSource {
|
||||
private final String displayName;
|
||||
|
||||
private final Path path;
|
||||
|
||||
/**
|
||||
* @param path the file to read
|
||||
*/
|
||||
public PathDataSource(Path path) {
|
||||
this(path, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path the file to read
|
||||
*/
|
||||
public PathDataSource(Path path, String displayName) {
|
||||
this.path = path;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -56,6 +66,9 @@ public class PathDataSource extends AbstractDataSource {
|
||||
}
|
||||
|
||||
private String glomName(boolean shortNames, String inputPaths) {
|
||||
if (displayName != null) {
|
||||
return displayName;
|
||||
}
|
||||
if (shortNames) {
|
||||
if (inputPaths != null) {
|
||||
List<String> inputPathPrefixes = Arrays.asList(inputPaths.split(","));
|
||||
|
||||
@@ -167,14 +167,6 @@ class PmdConfigurationTest {
|
||||
assertEquals(expected, configuration.getInputPathList(), "Changed input paths");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReportShortNames() {
|
||||
PMDConfiguration configuration = new PMDConfiguration();
|
||||
assertEquals(false, configuration.isReportShortNames(), "Default report short names");
|
||||
configuration.setReportShortNames(true);
|
||||
assertEquals(true, configuration.isReportShortNames(), "Changed report short names");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReportFormat() {
|
||||
PMDConfiguration configuration = new PMDConfiguration();
|
||||
|
||||
@@ -6,6 +6,7 @@ package net.sourceforge.pmd.cli;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
@@ -15,14 +16,17 @@ import org.checkerframework.checker.nullness.qual.NonNull;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import net.sourceforge.pmd.PMDConfiguration;
|
||||
import net.sourceforge.pmd.PmdAnalysis;
|
||||
import net.sourceforge.pmd.internal.util.FileCollectionUtil;
|
||||
import net.sourceforge.pmd.lang.LanguageRegistry;
|
||||
import net.sourceforge.pmd.lang.LanguageVersionDiscoverer;
|
||||
import net.sourceforge.pmd.lang.document.FileCollector;
|
||||
import net.sourceforge.pmd.lang.document.TextFile;
|
||||
import net.sourceforge.pmd.util.IOUtil;
|
||||
import net.sourceforge.pmd.util.log.internal.NoopReporter;
|
||||
|
||||
class PMDFilelistTest {
|
||||
private static final String RESOURCE_PREFIX = "src/test/resources/net/sourceforge/pmd/cli/";
|
||||
|
||||
private @NonNull FileCollector newCollector() {
|
||||
return FileCollector.newCollector(new LanguageVersionDiscoverer(LanguageRegistry.PMD), new NoopReporter());
|
||||
@@ -36,7 +40,7 @@ class PMDFilelistTest {
|
||||
void testGetApplicableFiles() {
|
||||
FileCollector collector = newCollector();
|
||||
|
||||
collectFileList(collector, "src/test/resources/net/sourceforge/pmd/cli/filelist.txt");
|
||||
collectFileList(collector, RESOURCE_PREFIX + "filelist.txt");
|
||||
|
||||
List<TextFile> applicableFiles = collector.getCollectedFiles();
|
||||
assertThat(applicableFiles, hasSize(2));
|
||||
@@ -48,13 +52,13 @@ class PMDFilelistTest {
|
||||
void testGetApplicableFilesMultipleLines() {
|
||||
FileCollector collector = newCollector();
|
||||
|
||||
collectFileList(collector, "src/test/resources/net/sourceforge/pmd/cli/filelist2.txt");
|
||||
collectFileList(collector, RESOURCE_PREFIX + "filelist2.txt");
|
||||
|
||||
List<TextFile> applicableFiles = collector.getCollectedFiles();
|
||||
assertThat(applicableFiles, hasSize(3));
|
||||
// note: the file has 3 entries, but one is duplicated, resulting in 2 individual files
|
||||
assertThat(applicableFiles, hasSize(2));
|
||||
assertThat(applicableFiles.get(0).getPathId(), endsWith("anotherfile.dummy"));
|
||||
assertThat(applicableFiles.get(1).getPathId(), endsWith("somefile.dummy"));
|
||||
assertThat(applicableFiles.get(2).getPathId(), endsWith("somefile.dummy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,8 +66,8 @@ class PMDFilelistTest {
|
||||
FileCollector collector = newCollector();
|
||||
|
||||
PMDConfiguration configuration = new PMDConfiguration();
|
||||
configuration.setInputFilePath("src/test/resources/net/sourceforge/pmd/cli/filelist3.txt");
|
||||
configuration.setIgnoreFilePath("src/test/resources/net/sourceforge/pmd/cli/ignorelist.txt");
|
||||
configuration.setInputFilePath(RESOURCE_PREFIX + "filelist3.txt");
|
||||
configuration.setIgnoreFilePath(RESOURCE_PREFIX + "ignorelist.txt");
|
||||
FileCollectionUtil.collectFiles(configuration, collector);
|
||||
|
||||
List<TextFile> applicableFiles = collector.getCollectedFiles();
|
||||
@@ -73,11 +77,67 @@ class PMDFilelistTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetApplicableFilesWithDirAndIgnores() {
|
||||
void testRelativizeWith() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist2.txt"));
|
||||
conf.addRelativizeRoot(Paths.get("src/test/resources"));
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(2));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(IOUtil.normalizePath("net/sourceforge/pmd/cli/src/anotherfile.dummy")));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo(IOUtil.normalizePath("net/sourceforge/pmd/cli/src/somefile.dummy")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithOtherDir() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist4.txt"));
|
||||
conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX + "src"));
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(".." + IOUtil.normalizePath("/otherSrc/somefile.dummy")));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo("anotherfile.dummy"));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo("somefile.dummy"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRelativizeWithSeveralDirs() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist4.txt"));
|
||||
conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX + "src"));
|
||||
conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX + "otherSrc"));
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo("somefile.dummy"));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo("anotherfile.dummy"));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo("somefile.dummy"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUseAbsolutePaths() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist4.txt"));
|
||||
conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX).toAbsolutePath().getRoot());
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(Paths.get(RESOURCE_PREFIX, "otherSrc", "somefile.dummy").toAbsolutePath().toString()));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo(Paths.get(RESOURCE_PREFIX, "src", "anotherfile.dummy").toAbsolutePath().toString()));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo(Paths.get(RESOURCE_PREFIX, "src", "somefile.dummy").toAbsolutePath().toString()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void testGetApplicableFilesWithDirAndIgnores() {
|
||||
PMDConfiguration configuration = new PMDConfiguration();
|
||||
configuration.setInputPaths("src/test/resources/net/sourceforge/pmd/cli/src");
|
||||
configuration.setIgnoreFilePath("src/test/resources/net/sourceforge/pmd/cli/ignorelist.txt");
|
||||
configuration.setInputPaths(RESOURCE_PREFIX + "src");
|
||||
configuration.setIgnoreFilePath(RESOURCE_PREFIX + "ignorelist.txt");
|
||||
|
||||
FileCollector collector = newCollector();
|
||||
FileCollectionUtil.collectFiles(configuration, collector);
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
|
||||
*/
|
||||
|
||||
package net.sourceforge.pmd.cli;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import net.sourceforge.pmd.PMDConfiguration;
|
||||
import net.sourceforge.pmd.PmdAnalysis;
|
||||
import net.sourceforge.pmd.lang.document.TextFile;
|
||||
import net.sourceforge.pmd.util.IOUtil;
|
||||
|
||||
public class ZipFileTest {
|
||||
|
||||
private static final String ZIP_PATH = "src/test/resources/net/sourceforge/pmd/cli/zipWithSources.zip";
|
||||
private final Path zipPath = Paths.get(ZIP_PATH);
|
||||
|
||||
@Test
|
||||
public void testZipFile() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.addInputPath(zipPath);
|
||||
// no relativizeRoot paths configured -> we use the relative path
|
||||
String reportPath = zipPath.toString();
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(reportPath + "!/otherSrc/somefile.dummy"));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo(reportPath + "!/src/somefile.dummy"));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo(reportPath + "!/src/somefile1.dummy"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testZipFileRelativizeWith() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.addInputPath(zipPath);
|
||||
conf.addRelativizeRoot(Paths.get("src/test/resources"));
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
String baseZipPath = IOUtil.normalizePath("net/sourceforge/pmd/cli/zipWithSources.zip");
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(baseZipPath + "!/otherSrc/somefile.dummy"));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo(baseZipPath + "!/src/somefile.dummy"));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo(baseZipPath + "!/src/somefile1.dummy"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testZipFileRelativizeWithRoot() {
|
||||
PMDConfiguration conf = new PMDConfiguration();
|
||||
conf.addInputPath(zipPath);
|
||||
// this configures "/" as the relativizeRoot -> result are absolute paths
|
||||
conf.addRelativizeRoot(zipPath.toAbsolutePath().getRoot());
|
||||
String reportPath = zipPath.toAbsolutePath().toString();
|
||||
try (PmdAnalysis pmd = PmdAnalysis.create(conf)) {
|
||||
List<TextFile> files = pmd.files().getCollectedFiles();
|
||||
assertThat(files, hasSize(3));
|
||||
assertThat(files.get(0).getDisplayName(), equalTo(reportPath + "!/otherSrc/somefile.dummy"));
|
||||
assertThat(files.get(1).getDisplayName(), equalTo(reportPath + "!/src/somefile.dummy"));
|
||||
assertThat(files.get(2).getDisplayName(), equalTo(reportPath + "!/src/somefile1.dummy"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 30 of 36 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user