Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MPMD-336] Replace deprecated calls to PMD #66

Merged
merged 1 commit into from May 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -41,7 +41,9 @@
* from a pmd execution.
*
* @author Andreas Dangel
* @deprecated not used anymore
*/
@Deprecated
public class PmdCollectingRenderer extends AbstractRenderer
{
private List<ProcessingError> errors = Collections.synchronizedList( new ArrayList<>() );
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/org/apache/maven/plugins/pmd/PmdReport.java
Expand Up @@ -434,7 +434,7 @@ protected String getSourceEncoding()
* @return comma separated list of absolute file paths of ruleset files
* @throws MavenReportException if a ruleset could not be found
*/
private String resolveRulesets() throws MavenReportException
private List<String> resolveRulesets() throws MavenReportException
{
// configure ResourceManager - will search for urls (URLResourceLoader) and files in various directories:
// in the directory of the current project's pom file - note: extensions might replace the pom file on the fly
Expand Down Expand Up @@ -466,7 +466,7 @@ private String resolveRulesets() throws MavenReportException
{
throw new MavenReportException( e.getMessage(), e );
}
return StringUtils.join( sets, "," );
return Arrays.asList( sets );
}

private String determineRulesetFilename( String ruleset )
Expand Down
122 changes: 69 additions & 53 deletions src/main/java/org/apache/maven/plugins/pmd/exec/PmdExecutor.java
Expand Up @@ -29,25 +29,20 @@
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.pmd.ExcludeViolationsFromFile;
import org.apache.maven.plugins.pmd.PmdCollectingRenderer;
import org.apache.maven.reporting.MavenReportException;
import org.codehaus.plexus.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sourceforge.pmd.PMD;
import net.sourceforge.pmd.PmdAnalysis;
import net.sourceforge.pmd.PMDConfiguration;
import net.sourceforge.pmd.Report;
import net.sourceforge.pmd.RulePriority;
import net.sourceforge.pmd.RuleSet;
import net.sourceforge.pmd.RuleSetLoadException;
import net.sourceforge.pmd.RuleSetLoader;
import net.sourceforge.pmd.RuleViolation;
Expand All @@ -63,8 +58,7 @@
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.TextRenderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
import net.sourceforge.pmd.util.datasource.DataSource;
import net.sourceforge.pmd.util.datasource.FileDataSource;
import net.sourceforge.pmd.util.Predicate;

/**
* Executes PMD with the configuration provided via {@link PmdRequest}.
Expand Down Expand Up @@ -146,13 +140,13 @@ private static PmdResult fork( PmdRequest request )

/**
* Execute PMD analysis from CLI.
*
*
* <p>
* Single arg with the filename to the serialized {@link PmdRequest}.
*
*
* <p>
* Exit-code: 0 = success, 1 = failure in executing
*
*
* @param args
*/
public static void main( String[] args )
Expand Down Expand Up @@ -211,14 +205,9 @@ private PmdResult run() throws MavenReportException
{
configuration.setSourceEncoding( request.getSourceEncoding() );
}
try
{
configuration.prependClasspath( request.getAuxClasspath() );
}
catch ( IOException e )
{
throw new MavenReportException( e.getMessage(), e );
}

configuration.prependAuxClasspath( request.getAuxClasspath() );

if ( request.getSuppressMarker() != null )
{
configuration.setSuppressMarker( request.getSuppressMarker() );
Expand All @@ -240,15 +229,10 @@ private PmdResult run() throws MavenReportException
configuration.setBenchmark( true );
}
List<File> files = request.getFiles();
List<DataSource> dataSources = new ArrayList<>( files.size() );
for ( File f : files )
{
dataSources.add( new FileDataSource( f ) );
}

PmdCollectingRenderer renderer = new PmdCollectingRenderer();
Report report = null;

if ( StringUtils.isBlank( request.getRulesets() ) )
if ( request.getRulesets().isEmpty() )
{
LOG.debug( "Skipping PMD execution as no rulesets are defined." );
}
Expand All @@ -261,7 +245,7 @@ private PmdResult run() throws MavenReportException

try
{
processFilesWithPMD( configuration, dataSources, renderer );
report = processFilesWithPMD( configuration, files );
}
finally
{
Expand Down Expand Up @@ -290,21 +274,21 @@ private PmdResult run() throws MavenReportException
}
}

if ( renderer.hasErrors() )
if ( report != null && !report.getProcessingErrors().isEmpty() )
{
List<Report.ProcessingError> errors = report.getProcessingErrors();
if ( !request.isSkipPmdError() )
{
LOG.error( "PMD processing errors:" );
LOG.error( renderer.getErrorsAsString( request.isDebugEnabled() ) );
throw new MavenReportException( "Found " + renderer.getErrors().size() + " PMD processing errors" );
LOG.error( getErrorsAsString( errors, request.isDebugEnabled() ) );
throw new MavenReportException( "Found " + errors.size()
+ " PMD processing errors" );
}
LOG.warn( "There are {} PMD processing errors:", renderer.getErrors().size() );
LOG.warn( renderer.getErrorsAsString( request.isDebugEnabled() ) );
LOG.warn( "There are {} PMD processing errors:", errors.size() );
LOG.warn( getErrorsAsString( errors, request.isDebugEnabled() ) );
}

removeExcludedViolations( renderer.getViolations() );

Report report = renderer.asReport();
report = removeExcludedViolations( report );
// always write XML report, as this might be needed by the check mojo
// we need to output it even if the file list is empty or we have no violations
// so the "check" goals can check for violations
Expand All @@ -323,6 +307,25 @@ private PmdResult run() throws MavenReportException
return new PmdResult( new File( request.getTargetDirectory(), "pmd.xml" ), request.getOutputEncoding() );
}

/**
* Gets the errors as a single string. Each error is in its own line.
* @param withDetails if <code>true</code> then add the error details additionally (contains e.g. the stacktrace)
* @return the errors as string
*/
private String getErrorsAsString( List<Report.ProcessingError> errors, boolean withDetails )
{
List<String> errorsAsString = new ArrayList<>( errors.size() );
for ( Report.ProcessingError error : errors )
{
errorsAsString.add( error.getFile() + ": " + error.getMsg() );
if ( withDetails )
{
errorsAsString.add( error.getDetail() );
adangel marked this conversation as resolved.
Show resolved Hide resolved
}
}
return String.join( System.lineSeparator(), errorsAsString );
}

private void writeBenchmarkReport( TimingReport timingReport, String benchmarkOutputLocation, String encoding )
{
try ( Writer writer = new OutputStreamWriter( new FileOutputStream( benchmarkOutputLocation ), encoding ) )
Expand All @@ -336,28 +339,31 @@ private void writeBenchmarkReport( TimingReport timingReport, String benchmarkOu
}
}

private void processFilesWithPMD( PMDConfiguration pmdConfiguration, List<DataSource> dataSources,
PmdCollectingRenderer renderer ) throws MavenReportException
private Report processFilesWithPMD( PMDConfiguration pmdConfiguration, List<File> files )
throws MavenReportException
{
Report report = null;
RuleSetLoader rulesetLoader = RuleSetLoader.fromPmdConfig( pmdConfiguration )
.warnDeprecated( true );
List<RuleSet> rulesets;
try
{
// load the ruleset once to log out any deprecated rules as warnings
rulesets = rulesetLoader.loadFromResources(
Arrays.asList( pmdConfiguration.getRuleSets().split( "\\s*,\\s*" ) ) );
rulesetLoader.loadFromResources( pmdConfiguration.getRuleSetPaths() );
}
catch ( RuleSetLoadException e1 )
{
throw new MavenReportException( "The ruleset could not be loaded", e1 );
}

try
try ( PmdAnalysis pmdAnalysis = PmdAnalysis.create( pmdConfiguration ) )
{
for ( File file : files )
{
pmdAnalysis.files().addFile( file.toPath() );
}
LOG.debug( "Executing PMD..." );
PMD.processFiles( pmdConfiguration, rulesets, dataSources, Arrays.<Renderer>asList( renderer ) );
LOG.debug( "PMD finished. Found {} violations.", renderer.getViolations().size() );
report = pmdAnalysis.performAnalysisAndCollectReport();
LOG.debug( "PMD finished. Found {} violations.", report.getViolations().size() );
}
catch ( Exception e )
{
Expand All @@ -367,7 +373,9 @@ private void processFilesWithPMD( PMDConfiguration pmdConfiguration, List<DataSo
throw new MavenReportException( message, e );
}
LOG.warn( message, e );

}
return report;
}

/**
Expand Down Expand Up @@ -412,7 +420,10 @@ private File writeReport( Report report, Renderer r ) throws MavenReportExceptio
{
r.setWriter( writer );
r.start();
r.renderFileReport( report );
if ( report != null )
{
r.renderFileReport( report );
}
r.end();
r.flush();
}
Expand Down Expand Up @@ -480,9 +491,14 @@ else if ( !"".equals( format ) && !"none".equals( format ) )
return result;
}

private void removeExcludedViolations( List<RuleViolation> violations )
private Report removeExcludedViolations( Report report )
throws MavenReportException
{
if ( report == null )
{
return null;
}

ExcludeViolationsFromFile excludeFromFile = new ExcludeViolationsFromFile();

try
Expand All @@ -496,19 +512,19 @@ private void removeExcludedViolations( List<RuleViolation> violations )

LOG.debug( "Removing excluded violations. Using {} configured exclusions.",
excludeFromFile.countExclusions() );
int violationsBefore = violations.size();
int violationsBefore = report.getViolations().size();

Iterator<RuleViolation> iterator = violations.iterator();
while ( iterator.hasNext() )
Report filtered = report.filterViolations( new Predicate<RuleViolation>()
{
RuleViolation rv = iterator.next();
if ( excludeFromFile.isExcludedFromFailure( rv ) )
@Override
public boolean test( RuleViolation ruleViolation )
{
iterator.remove();
return !excludeFromFile.isExcludedFromFailure( ruleViolation );
}
}
} );

int numberOfExcludedViolations = violationsBefore - violations.size();
int numberOfExcludedViolations = violationsBefore - filtered.getViolations().size();
LOG.debug( "Excluded {} violations.", numberOfExcludedViolations );
return filtered;
}
}
Expand Up @@ -45,7 +45,7 @@ public class PmdRequest implements Serializable
private String auxClasspath;
private String suppressMarker;
private String analysisCacheLocation;
private String rulesets;
private List<String> rulesets;
private String sourceEncoding;
private List<File> files = new ArrayList<>();

Expand Down Expand Up @@ -114,7 +114,7 @@ public void setAnalysisCacheLocation( String analysisCacheLocation )
this.analysisCacheLocation = analysisCacheLocation;
}

public void setRulesets( String rulesets )
public void setRulesets( List<String> rulesets )
{
this.rulesets = rulesets;
}
Expand Down Expand Up @@ -223,7 +223,7 @@ public String getAnalysisCacheLocation()
return analysisCacheLocation;
}

public String getRulesets()
public List<String> getRulesets()
{
return rulesets;
}
Expand Down
13 changes: 8 additions & 5 deletions src/site/markdown/releasenotes.md
Expand Up @@ -39,6 +39,9 @@ under the License.
### 📝 Documentation updates
* [MPMD-333](https://issues.apache.org/jira/browse/MPMD-333) - Add release notes documentation

### 👻 Maintenance
* [MPMD-336](https://issues.apache.org/jira/browse/MPMD-336) - Replace deprecated calls to PMD

### 📦 Dependency updates
* [MPMD-329](https://issues.apache.org/jira/browse/MPMD-329) - Upgrade to PMD 6.45.0
* [MPMD-330](https://issues.apache.org/jira/browse/MPMD-330) - Upgrade Maven Parent to 35
Expand All @@ -50,7 +53,7 @@ under the License.
**Release Date:** 2022-02-05

**JIRA:** [Release Notes - Maven PMD Plugin - Version 3.16.0](https://issues.apache.org/jira/projects/MPMD/versions/12350599)

**GitHub:** <https://github.com/apache/maven-pmd-plugin/releases/tag/maven-pmd-plugin-3.16.0>

### 🐛 Bug Fixes
Expand All @@ -70,7 +73,7 @@ under the License.
## Version 3.15.0

**Release Date:** 2021-09-06

**JIRA:** [Release Notes - Maven PMD Plugin - Version 3.15.0](https://issues.apache.org/jira/projects/MPMD/versions/12349432)

### 🐛 Bug Fixes
Expand Down Expand Up @@ -98,7 +101,7 @@ under the License.
## Version 3.14.0

**Release Date:** 2020-10-24

**JIRA:** [Release Notes - Maven PMD Plugin - Version 3.14.0](https://issues.apache.org/jira/projects/MPMD/versions/12346940)

### 🐛 Bug Fixes
Expand All @@ -119,7 +122,7 @@ under the License.
## Version 3.13.0

**Release Date:** 2020-01-25

**JIRA:** [Release Notes - Maven PMD Plugin - Version 3.13.0](https://issues.apache.org/jira/projects/MPMD/versions/12345409)

### 🐛 Bug Fixes
Expand Down Expand Up @@ -147,7 +150,7 @@ under the License.
## Version 3.12.0

**Release Date:** 2019-04-11

**JIRA:** [Release Notes - Maven PMD Plugin - Version 3.12.0](https://issues.apache.org/jira/projects/MPMD/versions/12344380)

### 🐛 Bug Fixes
Expand Down