Replaced List with Collection whenever applicable.

Added rule priority configuration.

Cleaned up tests
This commit is contained in:
Erik C. Thauvin 2024-06-22 11:10:46 -07:00
parent 0e55b2774a
commit 709943e23b
Signed by: erik
GPG key ID: 776702A6A2DA330E
8 changed files with 679 additions and 174 deletions

View file

@ -1,9 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="PmdOperation" type="Application" factoryName="Application" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="rife.bld.extension.PmdOperation" />
<module name="app" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

View file

@ -1,13 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run Tests" type="JUnit" factoryName="JUnit">
<module name="app" />
<option name="PACKAGE_NAME" value="moog" />
<option name="MAIN_CLASS_NAME" value="rife.bld.extension" />
<option name="METHOD_NAME" value="" />
<option name="TEST_OBJECT" value="directory" />
<dir value="$PROJECT_DIR$/src/test/java" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
</component>

View file

@ -1,6 +1,5 @@
# [bld](https://rife2.com/bld) Extension to Perform Static Code Analysis with [PMD](https://pmd.github.io/) # [bld](https://rife2.com/bld) Extension to Perform Static Code Analysis with [PMD](https://pmd.github.io/)
[![License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![License](https://img.shields.io/badge/license-Apache%20License%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
[![Java](https://img.shields.io/badge/java-17%2B-blue)](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html) [![Java](https://img.shields.io/badge/java-17%2B-blue)](https://www.oracle.com/java/technologies/javase/jdk17-archive-downloads.html)
[![bld](https://img.shields.io/badge/1.9.1-FA9052?label=bld&labelColor=2392FF)](https://rife2.com/bld) [![bld](https://img.shields.io/badge/1.9.1-FA9052?label=bld&labelColor=2392FF)](https://rife2.com/bld)
@ -33,7 +32,7 @@ public void pmdMain() throws Exception {
new PmdOperation() new PmdOperation()
.fromProject(this) .fromProject(this)
.failOnViolation(true) .failOnViolation(true)
.inputPaths(srcMainDirectory().toPath()) .inputPaths(srcMainDirectory())
.ruleSets("config/pmd.xml", "category/java/errorprone.xml") .ruleSets("config/pmd.xml", "category/java/errorprone.xml")
.execute(); .execute();
} }

109
config/pmd.xml Normal file
View file

@ -0,0 +1,109 @@
<?xml version="1.0"?>
<ruleset name="erik"
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>Erik's Ruleset</description>
<!-- BEST PRACTICES -->
<rule ref="category/java/bestpractices.xml">
<exclude name="AvoidPrintStackTrace"/>
<exclude name="JUnit4TestShouldUseTestAnnotation"/>
<exclude name="JUnitTestContainsTooManyAsserts"/>
<exclude name="GuardLogStatement"/>
</rule>
<rule ref="category/java/bestpractices.xml/MissingOverride">
<properties>
<property name="violationSuppressXPath"
value="//MethodDeclaration[@Name='hashCode' or @Name='equals' or @Name='toString']"/>
</properties>
</rule>
<!-- CODE STYLE -->
<rule ref="category/java/codestyle.xml">
<exclude name="AtLeastOneConstructor"/>
<exclude name="ClassNamingConventions"/>
<exclude name="CommentDefaultAccessModifier"/>
<exclude name="ConfusingTernary"/>
<exclude name="FieldNamingConventions"/>
<exclude name="LocalVariableCouldBeFinal"/>
<exclude name="LongVariable"/>
<exclude name="MethodArgumentCouldBeFinal"/>
<exclude name="OnlyOneReturn"/>
<exclude name="PackageCase"/>
<exclude name="ShortClassName"/>
<exclude name="ShortMethodName"/>
<exclude name="ShortVariable"/>
<exclude name="UseExplicitTypes"/>
<exclude name="UseUnderscoresInNumericLiterals"/>
<exclude name="UselessParentheses"/>
</rule>
<rule ref="category/java/codestyle.xml/UnnecessaryImport">
<properties>
<property name="violationSuppressRegex" value="Unused (static|.*\.\*).*"/>
</properties>
</rule>
<!-- DESIGN -->
<rule ref="category/java/design.xml">
<exclude name="AvoidCatchingGenericException"/>
<exclude name="AvoidDeeplyNestedIfStmts"/>
<exclude name="AvoidUncheckedExceptionsInSignatures"/>
<exclude name="CognitiveComplexity"/>
<exclude name="CyclomaticComplexity"/>
<exclude name="ExcessiveParameterList"/>
<exclude name="ExcessivePublicCount"/>
<exclude name="GodClass"/>
<exclude name="LawOfDemeter"/>
<exclude name="LoosePackageCoupling"/>
<exclude name="NPathComplexity"/>
<exclude name="NcssCount"/>
<exclude name="TooManyFields"/>
<exclude name="TooManyMethods"/>
<exclude name="UseObjectForClearerAPI"/>
</rule>
<!-- DOCUMENTATION -->
<rule ref="category/java/documentation.xml">
<exclude name="CommentRequired"/>
<exclude name="CommentSize"/>
</rule>
<!-- ERROR PRONE -->
<rule ref="category/java/errorprone.xml">
<exclude name="AssignmentInOperand"/>
<exclude name="AvoidCatchingNPE"/>
<exclude name="AvoidDuplicateLiterals"/>
<exclude name="AvoidFieldNameMatchingMethodName"/>
<exclude name="AvoidFieldNameMatchingTypeName"/>
<exclude name="AvoidLiteralsInIfCondition"/>
<exclude name="NullAssignment"/>
</rule>
<rule ref="category/java/errorprone.xml/AssignmentInOperand">
<properties>
<property name="allowWhile" value="true"/>
<property name="allowFor" value="true"/>
<property name="allowIf" value="true"/>
</properties>
</rule>
<rule ref="category/java/errorprone.xml/AvoidDuplicateLiterals">
<properties>
<property name="skipAnnotations" value="true"/>
</properties>
</rule>
<!-- MULTITHREADING -->
<rule ref="category/java/multithreading.xml">
</rule>
<!-- PERFORMANCE -->
<rule ref="category/java/performance.xml">
</rule>
<!-- SECURITY -->
<rule ref="category/java/security.xml">
</rule>
</ruleset>

View file

@ -32,7 +32,7 @@ public class PmdOperationBuild extends Project {
public PmdOperationBuild() { public PmdOperationBuild() {
pkg = "rife.bld.extension"; pkg = "rife.bld.extension";
name = "bld-pmd"; name = "bld-pmd";
version = version(1, 0, 1); version = version(1, 1, 0, "SNAPSHOT");
javaRelease = 17; javaRelease = 17;

View file

@ -23,6 +23,7 @@ import net.sourceforge.pmd.lang.rule.RulePriority;
import rife.bld.BaseProject; import rife.bld.BaseProject;
import rife.bld.operations.AbstractOperation; import rife.bld.operations.AbstractOperation;
import java.io.File;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@ -41,6 +42,8 @@ import java.util.logging.Logger;
public class PmdOperation extends AbstractOperation<PmdOperation> { public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* The default rule set. * The default rule set.
* <p>
* Set to: {@code rulesets/java/quickstart.xml}
*/ */
public static final String RULE_SET_DEFAULT = "rulesets/java/quickstart.xml"; public static final String RULE_SET_DEFAULT = "rulesets/java/quickstart.xml";
private static final Logger LOGGER = Logger.getLogger(PmdOperation.class.getName()); private static final Logger LOGGER = Logger.getLogger(PmdOperation.class.getName());
@ -48,115 +51,83 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* The input paths (source) list. * The input paths (source) list.
*/ */
final List<Path> inputPaths_ = new ArrayList<>(); private final Collection<Path> inputPaths_ = new ArrayList<>();
/** /**
* The relative roots paths. * The relative roots paths.
*/ */
final List<Path> relativizeRoots_ = new ArrayList<>(); private final Collection<Path> relativizeRoots_ = new ArrayList<>();
/**
* The rule priority.
*/
final RulePriority rulePriority_ = RulePriority.LOW;
/** /**
* The rule sets list. * The rule sets list.
*/ */
final List<String> ruleSets_ = new ArrayList<>(); private final Collection<String> ruleSets_ = new ArrayList<>();
/** /**
* The cache location. * The cache location.
*/ */
Path cache_; private Path cache_;
/** /**
* The encoding. * The encoding.
*/ */
Charset encoding_ = StandardCharsets.UTF_8; private Charset encoding_ = StandardCharsets.UTF_8;
/** /**
* The fail on violation toggle. * The fail on violation toggle.
*/ */
boolean failOnViolation_; private boolean failOnViolation_;
/** /**
* The forced language. * The forced language.
*/ */
LanguageVersion forcedLanguageVersion_; private LanguageVersion forcedLanguageVersion_;
/** /**
* The path of the ignore file * The path of the ignore file
*/ */
Path ignoreFile_; private Path ignoreFile_;
/** /**
* The include line number toggle. * The include line number toggle.
*/ */
boolean includeLineNumber_ = true; private boolean includeLineNumber_ = true;
/** /**
* The incremental analysis toggle. * The incremental analysis toggle.
*/ */
boolean incrementalAnalysis_ = true; private boolean incrementalAnalysis_ = true;
/** /**
* The input URI. * The input URI.
*/ */
URI inputUri_; private URI inputUri_;
/** /**
* The default language version(s). * The default language version(s).
*/ */
List<LanguageVersion> languageVersions_; private Collection<LanguageVersion> languageVersions_ = new ArrayList<>();
/**
* The path to the report page.
*/
Path reportFile_;
/**
* The report format.
*/
String reportFormat_ = "text";
/**
* The report properties.
*/
Properties reportProperties_ = null;
/**
* The show suppressed flag.
*/
boolean showSuppressed_;
/**
* THe suppressed marker.
*/
String suppressedMarker_ = "NOPMD";
/**
* The number of threads.
*/
int threads_ = 1;
/** /**
* The project reference. * The project reference.
*/ */
private BaseProject project_; private BaseProject project_;
/** /**
* Adds paths to source files, or directories containing source files to analyze. * The path to the report page.
*/ */
public PmdOperation addInputPath(Path... inputPath) { private Path reportFile_;
inputPaths_.addAll(List.of(inputPath));
return this;
}
/** /**
* Adds paths to source files, or directories containing source files to analyze. * The report format.
*/ */
public PmdOperation addInputPath(Collection<Path> inputPath) { private String reportFormat_ = "text";
inputPaths_.addAll(inputPath);
return this;
}
/** /**
* Adds several paths to shorten paths that are output in the report. * The report properties.
*/ */
public PmdOperation addRelativizeRoot(Path... relativeRoot) { private Properties reportProperties_;
relativizeRoots_.addAll(List.of(relativeRoot));
return this;
}
/** /**
* Adds several paths to shorten paths that are output in the report. * The rule priority.
*/ */
public PmdOperation addRelativizeRoot(Collection<Path> relativeRoot) { private RulePriority rulePriority_ = RulePriority.LOW;
relativizeRoots_.addAll(relativeRoot); /**
return this; * The show suppressed flag.
} */
private boolean showSuppressed_;
/**
* THe suppressed marker.
*/
private String suppressedMarker_ = "NOPMD";
/**
* The number of threads.
*/
private int threads_ = 1;
/** /**
* Adds new rule set paths. * Adds new rule set paths.
@ -173,6 +144,10 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
* <li>{@code category/java/performance.xml}</li> * <li>{@code category/java/performance.xml}</li>
* <li>{@code category/java/security.xml}</li> * <li>{@code category/java/security.xml}</li>
* </ul> * </ul>
*
* @param ruleSet one or more rule set
* @return this operation
* @see #ruleSets(String...)
*/ */
public PmdOperation addRuleSet(String... ruleSet) { public PmdOperation addRuleSet(String... ruleSet) {
ruleSets_.addAll(List.of(ruleSet)); ruleSets_.addAll(List.of(ruleSet));
@ -194,9 +169,13 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
* <li>{@code category/java/performance.xml}</li> * <li>{@code category/java/performance.xml}</li>
* <li>{@code category/java/security.xml}</li> * <li>{@code category/java/security.xml}</li>
* </ul> * </ul>
*
* @param ruleSet one or more rule set
* @return this operation
* @see #ruleSets(Collection
*/ */
public PmdOperation addRuleSet(Collection<String> ruleSets) { public PmdOperation addRuleSet(Collection<String> ruleSet) {
ruleSets_.addAll(ruleSets); ruleSets_.addAll(ruleSet);
return this; return this;
} }
@ -209,17 +188,23 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets the default language to be used for all input files. * Sets the default language version to be used for all input files.
*
* @param languageVersion one or more language version
* @return this operation
*/ */
public PmdOperation defaultLanguage(LanguageVersion... languageVersion) { public PmdOperation defaultLanguageVersions(LanguageVersion... languageVersion) {
languageVersions_.addAll(List.of(languageVersion)); languageVersions_.addAll(List.of(languageVersion));
return this; return this;
} }
/** /**
* Sets the default language to be used for all input files. * Sets the default language version to be used for all input files.
*
* @param languageVersion the language versions
* @return this operation
*/ */
public PmdOperation defaultLanguage(Collection<LanguageVersion> languageVersion) { public PmdOperation defaultLanguageVersions(Collection<LanguageVersion> languageVersion) {
languageVersions_.addAll(languageVersion); languageVersions_.addAll(languageVersion);
return this; return this;
} }
@ -268,8 +253,11 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* Forces a language to be used for all input files, irrespective of file names. * Forces a language to be used for all input files, irrespective of file names.
*
* @param languageVersion the language version
* @return this operation
*/ */
public PmdOperation forceVersion(LanguageVersion languageVersion) { public PmdOperation forceLanguageVersion(LanguageVersion languageVersion) {
forcedLanguageVersion_ = languageVersion; forcedLanguageVersion_ = languageVersion;
return this; return this;
} }
@ -290,24 +278,51 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
* <li>ruleSets={@code [rulesets/java/quickstart.xml]}</li> * <li>ruleSets={@code [rulesets/java/quickstart.xml]}</li>
* <li>suppressedMarker={@code NOPMD}</li> * <li>suppressedMarker={@code NOPMD}</li>
* </ul> * </ul>
*
* @param project the project
* @return this operation
*/ */
public PmdOperation fromProject(BaseProject project) { public PmdOperation fromProject(BaseProject project) {
project_ = project; project_ = project;
inputPaths_.add(project.srcMainDirectory().toPath()); inputPaths(project.srcMainDirectory(), project.srcTestDirectory());
inputPaths_.add(project.srcTestDirectory().toPath());
ruleSets_.add(RULE_SET_DEFAULT); ruleSets_.add(RULE_SET_DEFAULT);
return this; return this;
} }
/** /**
* Sets the path to the file containing a list of files to ignore, one path per line. * Sets the path to the file containing a list of files to ignore, one path per line.
*
* @param ignoreFile the ignore file path
* @return this operation
*/ */
public PmdOperation ignoreFile(Path ignoreFile) { public PmdOperation ignoreFile(Path ignoreFile) {
ignoreFile_ = ignoreFile; ignoreFile_ = ignoreFile;
return this; return this;
} }
/**
* Sets the path to the file containing a list of files to ignore, one path per line.
*
* @param ignoreFile the ignore file path
* @return this operation
*/
public PmdOperation ignoreFile(File ignoreFile) {
ignoreFile_ = ignoreFile.toPath();
return this;
}
/**
* Sets the path to the file containing a list of files to ignore, one path per line.
*
* @param ignoreFile the ignore file path
* @return this operation
*/
public PmdOperation ignoreFile(String ignoreFile) {
ignoreFile_ = Paths.get(ignoreFile);
return this;
}
/** /**
* Enables or disables including the line number for the beginning of the violation in the analyzed source file URI. * Enables or disables including the line number for the beginning of the violation in the analyzed source file URI.
* <p> * <p>
@ -330,6 +345,9 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* Creates a new initialized configuration. * Creates a new initialized configuration.
*
* @param commandName the command name
* @return this operation
*/ */
public PMDConfiguration initConfiguration(String commandName) { public PMDConfiguration initConfiguration(String commandName) {
PMDConfiguration config = new PMDConfiguration(); PMDConfiguration config = new PMDConfiguration();
@ -344,7 +362,7 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
config.setFailOnViolation(failOnViolation_); config.setFailOnViolation(failOnViolation_);
if (languageVersions_ != null) { if (languageVersions_ != null) {
config.setDefaultLanguageVersions(languageVersions_); config.setDefaultLanguageVersions(languageVersions_.stream().toList());
} }
if (forcedLanguageVersion_ != null) { if (forcedLanguageVersion_ != null) {
@ -360,9 +378,8 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
if (inputPaths_.isEmpty()) { if (inputPaths_.isEmpty()) {
throw new IllegalArgumentException(commandName + ": InputPaths required."); throw new IllegalArgumentException(commandName + ": InputPaths required.");
} else { } else {
config.setInputPathList(inputPaths_); config.setInputPathList(inputPaths_.stream().toList());
} }
if (reportProperties_ != null) { if (reportProperties_ != null) {
config.setReportProperties(reportProperties_); config.setReportProperties(reportProperties_);
} }
@ -381,9 +398,9 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
config.setReportFile(reportFile_); config.setReportFile(reportFile_);
} }
config.addRelativizeRoots(relativizeRoots_); config.addRelativizeRoots(relativizeRoots_.stream().toList());
config.setReportFormat(reportFormat_); config.setReportFormat(reportFormat_);
config.setRuleSets(ruleSets_); config.setRuleSets(ruleSets_.stream().toList());
config.setShowSuppressedViolations(showSuppressed_); config.setShowSuppressedViolations(showSuppressed_);
config.setSourceEncoding(encoding_); config.setSourceEncoding(encoding_);
config.setSuppressMarker(suppressedMarker_); config.setSuppressMarker(suppressedMarker_);
@ -393,8 +410,11 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets the to source files, or directories containing source files to analyze. * Sets paths to source files, or directories containing source files to analyze.
* Previously set paths will be disregarded. *
* @param inputPath one or more paths
* @return this operation
* @see #addInputPaths(Path...)
*/ */
public PmdOperation inputPaths(Path... inputPath) { public PmdOperation inputPaths(Path... inputPath) {
inputPaths_.clear(); inputPaths_.clear();
@ -403,18 +423,154 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets the to source files, or directories containing source files to analyze. * Sets paths to source files, or directories containing source files to analyze.
* Previously set paths will be disregarded. * <p>
* Previous entries are disregarded.
*
* @param inputPath one or more paths
* @return this operation
* @see #addInputPaths(File...)
*/
public PmdOperation inputPaths(File... inputPath) {
inputPaths_.clear();
inputPaths_.addAll(Arrays.stream(inputPath).map(File::toPath).toList());
return this;
}
/**
* Sets paths to source files, or directories containing source files to analyze.
* <p>
* Previous entries are disregarded.
* @param inputPath one or more paths
* @return this operation
* @see #addInputPaths(String...)
*/
public PmdOperation inputPaths(String... inputPath) {
inputPaths_.clear();
inputPaths_.addAll(Arrays.stream(inputPath).map(Paths::get).toList());
return this;
}
/**
* Sets paths to source files, or directories containing source files to analyze.
* <p>
* Previous entries are disregarded.
* @param inputPath the input paths
* @return this operation
* @see #addInputPaths(Collection)
*/ */
public PmdOperation inputPaths(Collection<Path> inputPath) { public PmdOperation inputPaths(Collection<Path> inputPath) {
inputPaths_.clear(); inputPaths_.clear();
inputPaths_.addAll(inputPath); inputPaths_.addAll(inputPath);
return this; return this;
} }
/**
* Adds paths to source files, or directories containing source files to analyze.\
*
* @param inputPath one or more paths
* @return this operation
* @see #inputPaths(Path...)
*/
public PmdOperation addInputPaths(Path... inputPath) {
inputPaths_.addAll(List.of(inputPath));
return this;
}
/**
* Adds paths to source files, or directories containing source files to analyze.
*
* @param inputPath one or more paths
* @return this operation
* @see #inputPaths(File...)
*/
public PmdOperation addInputPaths(File... inputPath) {
inputPaths_.addAll(Arrays.stream(inputPath).map(File::toPath).toList());
return this;
}
/**
* Adds paths to source files, or directories containing source files to analyze.
*
* @param inputPath one or more paths
* @return this operation
* @see #addInputPaths(String...)
*/
public PmdOperation addInputPaths(String... inputPath) {
inputPaths_.addAll(Arrays.stream(inputPath).map(Paths::get).toList());
return this;
}
/**
* Adds paths to source files, or directories containing source files to analyze.
*
* @param inputPath the input paths
* @return this operation
* @see #inputPaths(Collection)
*/
public PmdOperation addInputPaths(Collection<Path> inputPath) {
inputPaths_.addAll(inputPath);
return this;
}
/**
* Returns paths to source files, or directories containing source files to analyze.
*
* @return the input paths
*/
public Collection<Path> inputPaths() {
return inputPaths_;
}
/**
* Sets the default language versions.
*
* @param languageVersion one or more language versions
* @return this operation
*/
public PmdOperation languageVersions(LanguageVersion... languageVersion) {
languageVersions_.addAll(List.of(languageVersion));
return this;
}
/**
* Sets the default language versions.
*
* @param languageVersions the language versions
* @return this operation
*/
public PmdOperation languageVersions(Collection<LanguageVersion> languageVersions) {
languageVersions_ = languageVersions;
return this;
}
/**
* Returns the default language versions.
*
* @return the language versions
*/
public Collection<LanguageVersion> languageVersions() {
return languageVersions_;
}
/**
* Sets the minimum priority threshold when loading Rules from RuleSets.
*
* @return this operation
*/
public PmdOperation minimumPriority(RulePriority priority) {
rulePriority_ = priority;
return this;
}
/** /**
* Performs the PMD analysis with the given config. * Performs the PMD analysis with the given config.
*
* @param commandName the command name
* @param config the configuration
* @return the number of errors
* @throws RuntimeException if an error occurs
*/ */
@SuppressWarnings({"PMD.CloseResource", "PMD.AvoidInstantiatingObjectsInLoops"})
public int performPmdAnalysis(String commandName, PMDConfiguration config) throws RuntimeException { public int performPmdAnalysis(String commandName, PMDConfiguration config) throws RuntimeException {
var pmd = PmdAnalysis.create(config); var pmd = PmdAnalysis.create(config);
var report = pmd.performAnalysisAndCollectReport(); var report = pmd.performAnalysisAndCollectReport();
@ -470,25 +626,105 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets several paths to shorten paths that are output in the report. Previous relative paths will be disregarded. * Adds several paths to shorten paths that are output in the report.
*
* @param relativeRoot one or more relative root paths
* @return this operations
*/ */
public PmdOperation relativizeRoots(Path... relativeRoot) { public PmdOperation relativizeRoots(Path... relativeRoot) {
relativizeRoots_.clear();
relativizeRoots_.addAll(List.of(relativeRoot)); relativizeRoots_.addAll(List.of(relativeRoot));
return this; return this;
} }
/** /**
* Sets several paths to shorten paths that are output in the report. Previous relative paths will be disregarded. * Adds several paths to shorten paths that are output in the report.
*
* @param relativeRoot one or more relative root paths
* @return this operations
*/
public PmdOperation relativizeRoots(File... relativeRoot) {
relativizeRoots_.addAll(Arrays.stream(relativeRoot).map(File::toPath).toList());
return this;
}
/**
* Adds several paths to shorten paths that are output in the report.
*
* @param relativeRoot one or more relative root paths
* @return this operations
*/
public PmdOperation relativizeRoots(String... relativeRoot) {
relativizeRoots_.addAll(Arrays.stream(relativeRoot).map(Paths::get).toList());
return this;
}
/**
* Adds several paths to shorten paths that are output in the report.
*
* @param relativeRoot the relative root paths
* @return this operations
*/ */
public PmdOperation relativizeRoots(Collection<Path> relativeRoot) { public PmdOperation relativizeRoots(Collection<Path> relativeRoot) {
relativizeRoots_.clear();
relativizeRoots_.addAll(relativeRoot); relativizeRoots_.addAll(relativeRoot);
return this; return this;
} }
/**
* Returns paths to shorten paths that are output in the report.
*
* @return the relative root paths
*/
public Collection<Path> relativizeRoots() {
return relativizeRoots_;
}
/**
* Sets the path to the report page.
*
* @param reportFile the report file path
* @return this operation
*/
public PmdOperation reportFile(Path reportFile) {
reportFile_ = reportFile;
return this;
}
/**
* Sets the path to the report page.
*
* @param reportFile the report file path
* @return this operation
*/
public PmdOperation reportFile(File reportFile) {
reportFile_ = reportFile.toPath();
return this;
}
/**
* Sets the path to the report page.
*
* @param reportFile the report file path
* @return this operation
*/
public PmdOperation reportFile(String reportFile) {
reportFile_ = Paths.get(reportFile);
return this;
}
/**
* Returns the path to the report page.
*
* @return the path
*/
public Path reportFile() {
return reportFile_;
}
/** /**
* Sets the output format of the analysis report. The default is {@code text}. * Sets the output format of the analysis report. The default is {@code text}.
*
* @param reportFormat the report format
* @return this operation
*/ */
public PmdOperation reportFormat(String reportFormat) { public PmdOperation reportFormat(String reportFormat) {
reportFormat_ = reportFormat; reportFormat_ = reportFormat;
@ -496,7 +732,10 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Set the Report properties. These are used to create the Renderer. * Sets the Report properties. These are used to create the Renderer.
*
* @param reportProperties the report properties
* @return this operation
*/ */
public PmdOperation reportProperties(Properties reportProperties) { public PmdOperation reportProperties(Properties reportProperties) {
reportProperties_ = reportProperties; reportProperties_ = reportProperties;
@ -504,7 +743,7 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets the rule set path(s), disregarding any previously set paths. * Sets new rule set paths, disregarding any previous entries.
* <p> * <p>
* The built-in rule set paths are: * The built-in rule set paths are:
* <ul> * <ul>
@ -518,15 +757,19 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
* <li>{@code category/java/performance.xml}</li> * <li>{@code category/java/performance.xml}</li>
* <li>{@code category/java/security.xml}</li> * <li>{@code category/java/security.xml}</li>
* </ul> * </ul>
*
* @param ruleSet one or more rule set
* @return this operation
* @see #addRuleSet(String...)
*/ */
public PmdOperation ruleSets(String... ruleSet) { public PmdOperation ruleSets(String... ruleSet) {
ruleSets_.clear(); ruleSets_.clear();
ruleSets_.addAll(Arrays.asList(ruleSet)); ruleSets_.addAll(List.of(ruleSet));
return this; return this;
} }
/** /**
* Sets the rule set path(s), disregarding any previously set paths. * Sets new rule set paths, disregarding any previous entries.
* <p> * <p>
* The built-in rule set paths are: * The built-in rule set paths are:
* <ul> * <ul>
@ -540,15 +783,31 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
* <li>{@code category/java/performance.xml}</li> * <li>{@code category/java/performance.xml}</li>
* <li>{@code category/java/security.xml}</li> * <li>{@code category/java/security.xml}</li>
* </ul> * </ul>
*
* @param ruleSet one or more rule set
* @return this operation
* @see #addRuleSet(Collection)
*/ */
public PmdOperation ruleSets(Collection<String> ruleSets) { public PmdOperation ruleSets(Collection<String> ruleSet) {
ruleSets_.clear(); ruleSets_.clear();
ruleSets_.addAll(ruleSets); ruleSets_.addAll(ruleSet);
return this; return this;
} }
/**
* Returns the rule set paths.
*
* @return the rule sets
*/
public Collection<String> ruleSets() {
return ruleSets_;
}
/** /**
* Enables or disables adding the suppressed rule violations to the report. * Enables or disables adding the suppressed rule violations to the report.
*
* @param showSuppressed {@code true} or {@code false}
* @return this operation
*/ */
public PmdOperation showSuppressed(boolean showSuppressed) { public PmdOperation showSuppressed(boolean showSuppressed) {
showSuppressed_ = showSuppressed; showSuppressed_ = showSuppressed;
@ -557,6 +816,9 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* Specifies the comment token that marks lines which should be ignored. The default is {@code NOPMD}. * Specifies the comment token that marks lines which should be ignored. The default is {@code NOPMD}.
*
* @param suppressedMarker the suppressed marker
* @return this operation
*/ */
public PmdOperation suppressedMarker(String suppressedMarker) { public PmdOperation suppressedMarker(String suppressedMarker) {
suppressedMarker_ = suppressedMarker; suppressedMarker_ = suppressedMarker;
@ -564,7 +826,10 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
} }
/** /**
* Sets the number of threads to be used. The default is {code 1}. * Sets the number of threads to be used. The default is {@code 1}.
*
* @param threads the number of threads
* @return this operation
*/ */
public PmdOperation threads(int threads) { public PmdOperation threads(int threads) {
threads_ = threads; threads_ = threads;
@ -573,6 +838,9 @@ public class PmdOperation extends AbstractOperation<PmdOperation> {
/** /**
* Sets the input URI to process for source code objects. * Sets the input URI to process for source code objects.
*
* @param inputUri the input URI
* @return this operation
*/ */
public PmdOperation uri(URI inputUri) { public PmdOperation uri(URI inputUri) {
inputUri_ = inputUri; inputUri_ = inputUri;

View file

@ -17,15 +17,23 @@
package rife.bld.extension; package rife.bld.extension;
import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.lang.LanguageRegistry;
import net.sourceforge.pmd.lang.rule.RulePriority;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import rife.bld.BaseProject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.List;
import java.util.Properties;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatCode;
@ -38,36 +46,86 @@ import static org.assertj.core.api.Assertions.assertThatCode;
*/ */
class PmdOperationTest { class PmdOperationTest {
static final String CATEGORY_FOO = "category/foo.xml"; static final String CATEGORY_FOO = "category/foo.xml";
static final String CODE_STYLE = "category/java/codestyle.xml";
static final Path CODE_STYLE_SAMPLE = Path.of("src/test/resources/java/CodeStyle.java"); static final Path CODE_STYLE_SAMPLE = Path.of("src/test/resources/java/CodeStyle.java");
static final int CODING_STYLE_ERRORS = 13; static final String CODE_STYLE_XML = "category/java/codestyle.xml";
static final String COMMAND_NAME = "pmd"; static final String COMMAND_NAME = "pmd";
static final String ERROR_PRONE = "category/java/errorprone.xml"; static final String DESIGN_XML = "category/java/design.xml";
static final int ERROR_PRONE_ERRORS = 6; static final String DOCUMENTATION_XML = "category/java/documentation.xml";
static final Path ERROR_PRONE_SAMPLE = Path.of("src/test/resources/java/ErrorProne.java"); static final Path ERROR_PRONE_SAMPLE = Path.of("src/test/resources/java/ErrorProne.java");
static final String ERROR_PRONE_XML = "category/java/errorprone.xml";
static final String PERFORMANCE_XML = "category/java/performance.xml";
static final String SECURITY_XML = "category/java/security.xml";
static final String TEST = "test"; static final String TEST = "test";
PmdOperation newPmdOperation() { PmdOperation newPmdOperation() {
final PmdOperation pmdOperation = new PmdOperation(); return new PmdOperation()
pmdOperation.inputPaths(Path.of("src/main"), Path.of("src/test")); .inputPaths(Path.of("src/main"), Path.of("src/test"))
pmdOperation.reportFile_ = Paths.get("build", COMMAND_NAME, "pmd-test-report.txt"); .cache(Paths.get("build", COMMAND_NAME, "pmd-cache"))
pmdOperation.cache_ = Paths.get("build", COMMAND_NAME, "pmd-cache"); .failOnViolation(false)
pmdOperation.failOnViolation_ = false; .reportFile(Paths.get("build", COMMAND_NAME, "pmd-test-report.txt"));
return pmdOperation;
} }
@Test @Test
void testAddInputPaths() { void testAddInputPath() {
var pmd = newPmdOperation().ruleSets(PmdOperation.RULE_SET_DEFAULT, CODE_STYLE).inputPaths(ERROR_PRONE_SAMPLE) var project = new BaseProject();
.addInputPath(CODE_STYLE_SAMPLE); var pmd = new PmdOperation().fromProject(project);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(36);
assertThat(pmd.inputPaths()).as("default").containsExactly(project.srcMainDirectory().toPath(),
project.srcTestDirectory().toPath());
var err = pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME));
pmd.inputPaths().clear();
pmd.addInputPaths(project.srcMainDirectory());
assertThat(pmd.inputPaths()).as("main").containsExactly(project.srcMainDirectory().toPath());
pmd.inputPaths().clear();
pmd.addInputPaths(project.srcMainDirectory().toPath(), project.srcTestDirectory().toPath());
assertThat(pmd.inputPaths()).as("toPath(main, test)").containsExactly(project.srcMainDirectory().toPath(),
project.srcTestDirectory().toPath());
pmd.inputPaths().clear();
pmd.addInputPaths(List.of(project.srcMainDirectory().toPath(), project.srcTestDirectory().toPath()));
assertThat(pmd.inputPaths()).as("List(main, test)").containsExactly(
project.srcMainDirectory().toPath(),
project.srcTestDirectory().toPath());
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
.isGreaterThan(0).isEqualTo(err);
}
@Test
void testAddRuleSets() {
var pmd = new PmdOperation().fromProject(new BaseProject());
assertThat(pmd.ruleSets()).containsExactly(PmdOperation.RULE_SET_DEFAULT);
pmd.addRuleSet(ERROR_PRONE_XML);
assertThat(pmd.ruleSets()).containsExactly(PmdOperation.RULE_SET_DEFAULT, ERROR_PRONE_XML);
var err = pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME));
pmd.ruleSets().clear();
pmd.addRuleSet(List.of(PmdOperation.RULE_SET_DEFAULT, ERROR_PRONE_XML));
assertThat(pmd.ruleSets()).as("collection")
.containsExactly(PmdOperation.RULE_SET_DEFAULT, ERROR_PRONE_XML);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
.isGreaterThan(0).isEqualTo(err);
} }
@Test @Test
void testCache() { void testCache() {
var cache = Path.of("build/pmd/temp-cache"); var cache = Path.of("build/pmd/temp-cache");
var pmd = newPmdOperation().ruleSets(CODE_STYLE).inputPaths(CODE_STYLE_SAMPLE).cache(cache); var pmd = newPmdOperation().ruleSets(CODE_STYLE_XML).inputPaths(List.of(CODE_STYLE_SAMPLE)).cache(cache);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(CODING_STYLE_ERRORS); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
var f = cache.toFile(); var f = cache.toFile();
assertThat(f.exists()).as("file exits").isTrue(); assertThat(f.exists()).as("file exits").isTrue();
assertThat(f.delete()).as("delete file").isTrue(); assertThat(f.delete()).as("delete file").isTrue();
@ -75,7 +133,7 @@ class PmdOperationTest {
@Test @Test
void testEncoding() { void testEncoding() {
PmdOperation pmd = newPmdOperation().ruleSets(CATEGORY_FOO).encoding("UTF-16"); var pmd = newPmdOperation().ruleSets(CATEGORY_FOO).encoding("UTF-16");
PMDConfiguration config = pmd.initConfiguration(COMMAND_NAME); PMDConfiguration config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.getSourceEncoding()).as("UTF-16").isEqualTo(StandardCharsets.UTF_16); assertThat(config.getSourceEncoding()).as("UTF-16").isEqualTo(StandardCharsets.UTF_16);
@ -84,19 +142,45 @@ class PmdOperationTest {
assertThat(config.getSourceEncoding()).as("ISO_8859").isEqualTo(StandardCharsets.ISO_8859_1); assertThat(config.getSourceEncoding()).as("ISO_8859").isEqualTo(StandardCharsets.ISO_8859_1);
} }
@Test
void testExecute() {
var pmd = new PmdOperation().fromProject(new BaseProject());
assertThat(pmd.inputPaths()).containsExactly(Paths.get("src/main").toAbsolutePath(),
Paths.get("src/test").toAbsolutePath());
pmd.inputPaths().clear();
pmd.inputPaths("src/main/java", "src/test/java")
.ruleSets("config/pmd.xml");
assertThat(pmd.ruleSets()).containsExactly("config/pmd.xml");
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0);
}
@Test @Test
void testFailOnValidation() { void testFailOnValidation() {
var pmd = newPmdOperation().ruleSets("category/java/documentation.xml") var pmd = newPmdOperation().ruleSets(DOCUMENTATION_XML)
.inputPaths(Path.of("src/test/resources/java/Documentation.java")); .inputPaths(Path.of("src/test/resources/java/Documentation.java"));
assertThatCode(() -> pmd.failOnViolation(true).performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)) assertThatCode(() -> pmd.failOnViolation(true).performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
).isInstanceOf(RuntimeException.class).hasMessageContaining('[' + TEST + ']'); .isInstanceOf(RuntimeException.class).hasMessageContaining('[' + TEST + ']');
} }
@Test @Test
void testIgnoreFile() { void testIgnoreFile() {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE, CODE_STYLE).inputPaths(ERROR_PRONE_SAMPLE, CODE_STYLE_SAMPLE) var pmd = newPmdOperation()
.ruleSets(ERROR_PRONE_XML, CODE_STYLE_XML)
.ignoreFile(Path.of("src/test/resources/ignore.txt")); .ignoreFile(Path.of("src/test/resources/ignore.txt"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
pmd.inputPaths().clear();
pmd.inputPaths(ERROR_PRONE_SAMPLE, CODE_STYLE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0);
pmd.ruleSets().clear();
pmd.inputPaths().clear();
assertThat(pmd.inputPaths(ERROR_PRONE_SAMPLE)
.ignoreFile(new File("src/test/resources/ignore-single.txt"))
.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0);
} }
@Test @Test
@ -106,108 +190,174 @@ class PmdOperationTest {
assertThat(config.isIgnoreIncrementalAnalysis()).isFalse(); assertThat(config.isIgnoreIncrementalAnalysis()).isFalse();
} }
@Test
void testInputPaths() {
var pmd = newPmdOperation()
.ruleSets(PmdOperation.RULE_SET_DEFAULT, CODE_STYLE_XML)
.inputPaths(ERROR_PRONE_SAMPLE, CODE_STYLE_SAMPLE);
assertThat(pmd.inputPaths()).contains(ERROR_PRONE_SAMPLE, CODE_STYLE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
}
@Test @Test
void testJavaBestPractices() { void testJavaBestPractices() {
var pmd = newPmdOperation().ruleSets("category/java/bestpractices.xml") var pmd = newPmdOperation().ruleSets("category/java/bestpractices.xml")
.inputPaths(Path.of("src/test/resources/java/BestPractices.java")); .inputPaths(Path.of("src/test/resources/java/BestPractices.java"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(11); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaCodeStyle() { void testJavaCodeStyle() {
var pmd = newPmdOperation().ruleSets(CODE_STYLE).inputPaths(CODE_STYLE_SAMPLE); var pmd = newPmdOperation().ruleSets(CODE_STYLE_XML).inputPaths(CODE_STYLE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(CODING_STYLE_ERRORS); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaCodeStyleAndErrorProne() { void testJavaCodeStyleAndErrorProne() {
var pmd = newPmdOperation().ruleSets(CODE_STYLE).inputPaths(CODE_STYLE_SAMPLE); var pmd = newPmdOperation().ruleSets(CODE_STYLE_XML).inputPaths(CODE_STYLE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))) assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
.as("code style").isEqualTo(CODING_STYLE_ERRORS); .as("code style").isGreaterThan(0);
pmd = pmd.addRuleSet(ERROR_PRONE).addInputPath(ERROR_PRONE_SAMPLE); pmd = pmd.ruleSets(ERROR_PRONE_XML).inputPaths(ERROR_PRONE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))) assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
.as("code style + error prone").isEqualTo(29); .as("code style + error prone").isGreaterThan(0);
} }
@Test @Test
void testJavaDesign() { void testJavaDesign() {
var pmd = newPmdOperation().ruleSets("category/java/design.xml") var pmd = newPmdOperation()
.inputPaths(Path.of("src/test/resources/java/Design.java")) .ruleSets(DESIGN_XML)
.inputPaths("src/test/resources/java/Design.java")
.cache(Path.of("build/pmd/design-cache")); .cache(Path.of("build/pmd/design-cache"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(4); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaDocumentation() { void testJavaDocumentation() {
var pmd = newPmdOperation().ruleSets("category/java/documentation.xml") var pmd = newPmdOperation()
.ruleSets(DOCUMENTATION_XML)
.inputPaths(Path.of("src/test/resources/java/Documentation.java")); .inputPaths(Path.of("src/test/resources/java/Documentation.java"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(4); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaErrorProne() { void testJavaErrorProne() {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).inputPaths(ERROR_PRONE_SAMPLE); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).inputPaths(ERROR_PRONE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(ERROR_PRONE_ERRORS); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaMultiThreading() { void testJavaMultiThreading() {
var pmd = newPmdOperation().ruleSets("category/java/multithreading.xml") var pmd = newPmdOperation().ruleSets("category/java/multithreading.xml")
.inputPaths(Path.of("src/test/resources/java/MultiThreading.java")); .inputPaths(Path.of("src/test/resources/java/MultiThreading.java"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(3); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaPerformance() { void testJavaPerformance() {
var pmd = newPmdOperation().ruleSets("category/java/performance.xml") var pmd = newPmdOperation()
.ruleSets(PERFORMANCE_XML)
.inputPaths(Path.of("src/test/resources/java/Performance.java")); .inputPaths(Path.of("src/test/resources/java/Performance.java"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(9); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaQuickStart() { void testJavaQuickStart() {
var pmd = newPmdOperation().ruleSets("rulesets/java/quickstart.xml") var pmd = newPmdOperation().ruleSets(PmdOperation.RULE_SET_DEFAULT)
.inputPaths(Path.of("src/test/resources/java")); .inputPaths(new File("src/test/resources/java/"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(34); assertThat(pmd.ruleSets()).containsExactly(PmdOperation.RULE_SET_DEFAULT);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
@Test @Test
void testJavaSecurity() { void testJavaSecurity() {
var pmd = newPmdOperation().ruleSets("category/java/security.xml") var pmd = newPmdOperation().ruleSets(SECURITY_XML)
.inputPaths(Path.of("src/test/resources/java/Security.java")); .inputPaths(Path.of("src/test/resources/java/Security.java"));
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(1); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
}
@Test
void testLanguageVersions() {
var language = LanguageRegistry.PMD.getLanguageById("java");
assertThat(language).isNotNull();
var pmd = newPmdOperation()
.forceLanguageVersion(language.getLatestVersion())
.defaultLanguageVersions(language.getVersions())
.languageVersions(language.getVersion("22"))
.ruleSets(PmdOperation.RULE_SET_DEFAULT);
assertThat(pmd.languageVersions()).contains(language.getDefaultVersion());
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
assertThat(pmd.defaultLanguageVersions(language.getVersion("17"), language.getVersion("21"))
.languageVersions(language.getVersions()).performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME)))
.as("17 & 21").isGreaterThan(0);
} }
@Test @Test
void testMainOperation() { void testMainOperation() {
var pmd = newPmdOperation().inputPaths(Path.of("src/main")) var pmd = newPmdOperation().inputPaths(new File("src/main"))
.performPmdAnalysis(TEST, newPmdOperation().initConfiguration(COMMAND_NAME)); .performPmdAnalysis(TEST, newPmdOperation().initConfiguration(COMMAND_NAME));
assertThat(pmd).isEqualTo(0); assertThat(pmd).isEqualTo(0);
} }
@Test
void testPriority() {
var pmd = newPmdOperation().inputPaths(CODE_STYLE_SAMPLE).minimumPriority(RulePriority.HIGH);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0);
}
@Test @Test
void testRelativizeRoots() { void testRelativizeRoots() {
var foo = Path.of("foo/bar"); var foo = Path.of("foo/bar");
var bar = Path.of("bar/foo"); var bar = Path.of("bar/foo");
var baz = Path.of("baz/foz");
var pmd = newPmdOperation().ruleSets(CATEGORY_FOO).relativizeRoots(foo).addRelativizeRoot(bar); var pmd = newPmdOperation().ruleSets(List.of(CATEGORY_FOO)).relativizeRoots(foo).relativizeRoots(bar.toFile())
.relativizeRoots(baz.toString()).relativizeRoots(List.of(foo, bar, baz));
var config = pmd.initConfiguration(COMMAND_NAME); var config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.getRelativizeRoots()).contains(foo).contains(bar); assertThat(config.getRelativizeRoots()).isEqualTo(pmd.relativizeRoots());
assertThat(config.getRelativizeRoots()).containsExactly(foo, bar, baz, foo, bar, baz);
}
@Test
void testReportFile() throws FileNotFoundException {
var report = new File("build", "pmd-report-file");
report.deleteOnExit();
var pmd = newPmdOperation().ruleSets(List.of(ERROR_PRONE_XML, DESIGN_XML)).reportFile(report);
pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME));
assertThat(report).exists();
try (var writer = new PrintWriter(report)) {
writer.write("");
}
assertThat(report).isEmpty();
pmd.reportFile(report.getAbsolutePath()).performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME));
assertThat(report).isNotEmpty();
} }
@Test @Test
void testReportFormat() throws IOException { void testReportFormat() throws IOException {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).reportFormat("xml").inputPaths(ERROR_PRONE_SAMPLE); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).reportFormat("xml").inputPaths(ERROR_PRONE_SAMPLE);
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(ERROR_PRONE_ERRORS); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
try (var br = Files.newBufferedReader(pmd.reportFile_)) { try (var br = Files.newBufferedReader(pmd.reportFile())) {
assertThat(br.readLine()).as("xml report").startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); assertThat(br.readLine()).as("xml report").startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
} }
} }
@Test
void testReportProperties() {
var pmd = newPmdOperation().ruleSets(CODE_STYLE_XML, ERROR_PRONE_XML)
.includeLineNumber(true)
.reportProperties(new Properties());
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
}
@Test @Test
void testRuleSetsConfigFile() { void testRuleSetsConfigFile() {
var pmd = newPmdOperation().ruleSets("src/test/resources/pmd.xml") var pmd = newPmdOperation().ruleSets("src/test/resources/pmd.xml")
.ignoreFile(Path.of("src/test/resources/ignore-all.txt")); .ignoreFile("src/test/resources/ignore-all.txt");
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0);
} }
@ -219,21 +369,21 @@ class PmdOperationTest {
@Test @Test
void testShowSuppressed() { void testShowSuppressed() {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).showSuppressed(true); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).showSuppressed(true);
var config = pmd.initConfiguration(COMMAND_NAME); var config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.isShowSuppressedViolations()).isTrue(); assertThat(config.isShowSuppressedViolations()).isTrue();
} }
@Test @Test
void testSuppressedMarker() { void testSuppressedMarker() {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).suppressedMarker(TEST); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).suppressedMarker(TEST);
var config = pmd.initConfiguration(COMMAND_NAME); var config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.getSuppressMarker()).isEqualTo(TEST); assertThat(config.getSuppressMarker()).isEqualTo(TEST);
} }
@Test @Test
void testThreads() { void testThreads() {
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).threads(5); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).threads(5);
var config = pmd.initConfiguration(COMMAND_NAME); var config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.getThreads()).isEqualTo(5); assertThat(config.getThreads()).isEqualTo(5);
} }
@ -241,15 +391,15 @@ class PmdOperationTest {
@Test @Test
void testUri() throws URISyntaxException { void testUri() throws URISyntaxException {
var uri = new URI("https://example.com"); var uri = new URI("https://example.com");
var pmd = newPmdOperation().ruleSets(ERROR_PRONE).uri(uri); var pmd = newPmdOperation().ruleSets(ERROR_PRONE_XML).uri(uri);
var config = pmd.initConfiguration(COMMAND_NAME); var config = pmd.initConfiguration(COMMAND_NAME);
assertThat(config.getUri()).isEqualTo(uri); assertThat(config.getUri()).isEqualTo(uri);
} }
@Test @Test
void testXml() { void testXml() {
var pmd = newPmdOperation().inputPaths(Path.of("src/test/resources/pmd.xml")) var pmd = newPmdOperation().addInputPaths("src/test/resources/pmd.xml")
.ruleSets("src/test/resources/xml/basic.xml"); .ruleSets("src/test/resources/xml/basic.xml");
assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isEqualTo(0); assertThat(pmd.performPmdAnalysis(TEST, pmd.initConfiguration(COMMAND_NAME))).isGreaterThan(0);
} }
} }

View file

@ -0,0 +1 @@
src/test/resources/java/ErrorProne.java