From 2d7e200db172644181ff14e49faf1cd42698a552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 13:08:14 +0100 Subject: [PATCH 01/14] add PathId class --- .../pmd/ant/internal/PMDTaskImpl.java | 2 +- .../sourceforge/pmd/cpd/ApexTokenizer.java | 3 +- .../pmd/lang/apex/ast/ApexParser.java | 2 +- .../pmd/lang/apex/ast/CompilerService.java | 2 +- .../pmd/lang/apex/ast/ApexParserTest.java | 8 -- .../main/java/net/sourceforge/pmd/Report.java | 7 +- .../java/net/sourceforge/pmd/RuleSet.java | 2 +- .../java/net/sourceforge/pmd/RuleSets.java | 2 +- .../net/sourceforge/pmd/RuleViolation.java | 2 +- .../pmd/cache/AbstractAnalysisCache.java | 18 ++- .../sourceforge/pmd/cache/AnalysisCache.java | 3 +- .../pmd/cache/AnalysisCacheListener.java | 3 +- .../pmd/cache/CachedRuleViolation.java | 41 ++++--- .../pmd/cache/FileAnalysisCache.java | 31 +++-- .../pmd/cache/NoopAnalysisCache.java | 4 +- .../net/sourceforge/pmd/cpd/TokenEntry.java | 2 +- .../pmd/cpd/internal/AntlrTokenizer.java | 2 +- .../pmd/cpd/internal/JavaCCTokenizer.java | 6 +- .../pmd/internal/util/FileCollectionUtil.java | 3 +- .../pmd/lang/ast/FileAnalysisException.java | 12 +- .../net/sourceforge/pmd/lang/ast/Parser.java | 2 +- .../pmd/lang/ast/TokenMgrError.java | 5 +- .../ast/impl/antlr4/AntlrTokenManager.java | 2 +- .../ast/impl/javacc/JjtreeParserAdapter.java | 2 +- .../pmd/lang/document/BaseMappedDocument.java | 7 +- .../pmd/lang/document/CpdCompat.java | 2 +- .../pmd/lang/document/FileCollector.java | 7 +- .../pmd/lang/document/FileLocation.java | 14 +-- .../pmd/lang/document/NioTextFile.java | 15 +-- .../sourceforge/pmd/lang/document/PathId.java | 108 ++++++++++++++++++ .../pmd/lang/document/ReaderTextFile.java | 19 ++- .../pmd/lang/document/RootTextDocument.java | 14 +-- .../pmd/lang/document/StringTextFile.java | 14 +-- .../pmd/lang/document/TextDocument.java | 14 ++- .../pmd/lang/document/TextFile.java | 29 ++--- .../pmd/lang/document/TextFileBuilder.java | 26 +---- .../pmd/lang/impl/PmdRunnable.java | 4 +- .../lang/rule/internal/RuleApplicator.java | 2 +- .../xpath/internal/FileNameXPathFunction.java | 6 +- .../pmd/reporting/GlobalAnalysisListener.java | 3 +- .../pmd/util/treeexport/TreeExporter.java | 3 +- .../net/sourceforge/pmd/AbstractRuleTest.java | 11 +- .../sourceforge/pmd/DummyParsingHelper.java | 7 +- .../net/sourceforge/pmd/PmdAnalysisTest.java | 7 +- .../java/net/sourceforge/pmd/ReportTest.java | 6 +- .../pmd/RuleViolationComparatorTest.java | 3 +- .../sourceforge/pmd/RuleViolationTest.java | 12 +- .../pmd/cache/FileAnalysisCacheTest.java | 47 ++++---- .../sourceforge/pmd/cli/PMDFilelistTest.java | 26 +++-- .../token/internal/BaseTokenFilterTest.java | 4 +- .../sourceforge/pmd/lang/ast/DummyNode.java | 4 +- .../pmd/lang/document/FileLocationTest.java | 8 +- .../pmd/lang/document/SimpleTestTextFile.java | 2 +- .../pmd/lang/document/TextFilesTest.java | 17 ++- .../pmd/lang/rule/XPathRuleTest.java | 3 +- .../pmd/processor/GlobalListenerTest.java | 15 ++- .../processor/MultiThreadProcessorTest.java | 5 +- .../pmd/processor/PmdRunnableTest.java | 3 +- .../pmd/renderers/AbstractRendererTest.java | 9 +- .../pmd/renderers/XMLRendererTest.java | 4 +- .../pmd/renderers/XSLTRendererTest.java | 3 +- .../pmd/cpd/CppCharStreamTest.java | 4 +- .../pmd/lang/html/ast/HtmlTokenizer.java | 3 +- .../pmd/lang/ast/test/BaseParsingHelper.kt | 4 +- .../pmd/testframework/RuleTst.java | 3 +- 65 files changed, 374 insertions(+), 289 deletions(-) create mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java index f3d2d5e17b..e68dc62e44 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java @@ -177,7 +177,7 @@ public class PMDTaskImpl { @Override public FileAnalysisListener startFileAnalysis(TextFile dataSource) { - String name = dataSource.getDisplayName(); + String name = dataSource.getPathId().toUriString(); project.log("Processing file " + name, Project.MSG_VERBOSE); return FileAnalysisListener.noop(); } diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java b/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java index afe8db0b3f..e449fe0a2e 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java @@ -13,6 +13,7 @@ import org.antlr.runtime.Token; import net.sourceforge.pmd.lang.apex.ApexJorjeLogging; import net.sourceforge.pmd.lang.ast.TokenMgrError; +import net.sourceforge.pmd.lang.document.PathId; import apex.jorje.parser.impl.ApexLexer; @@ -42,7 +43,7 @@ public class ApexTokenizer implements Tokenizer { ApexLexer lexer = new ApexLexer(ass) { @Override public void emitErrorMessage(String msg) { - throw new TokenMgrError(getLine(), getCharPositionInLine(), getSourceName(), msg, null); + throw new TokenMgrError(getLine(), getCharPositionInLine(), PathId.fromPathLikeString(getSourceName()), msg, null); } }; diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java index f2b173e329..6605aef54c 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java @@ -32,7 +32,7 @@ public final class ApexParser implements Parser { final ApexTreeBuilder treeBuilder = new ApexTreeBuilder(task, (ApexLanguageProcessor) task.getLanguageProcessor()); return treeBuilder.buildTree(astRoot); } catch (apex.jorje.services.exception.ParseException e) { - throw new ParseException(e).setFileName(task.getFileDisplayName()); + throw new ParseException(e).setFileName(task.getTextDocument().getPathId()); } } } diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java index ea74530d85..6de5f1aa1c 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java @@ -63,7 +63,7 @@ class CompilerService { public Compilation parseApex(TextDocument document) { SourceFile sourceFile = SourceFile.builder() .setBody(document.getText().toString()) - .setKnownName(document.getDisplayName()) + .setKnownName(document.getPathId().toUriString()) .build(); ApexCompiler compiler = ApexCompiler.builder().setInput(createCompilationInput(Collections.singletonList(sourceFile))).build(); compiler.compile(CompilerStage.POST_TYPE_RESOLVE); diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTest.java index 965167dfd9..bf3ed86d04 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTest.java @@ -45,14 +45,6 @@ class ApexParserTest extends ApexParserTestBase { assertEquals(4, methods.size()); } - @Test - void fileName() { - String code = "class Outer { class Inner {}}"; - - ASTUserClass rootNode = (ASTUserClass) parse(code, "src/filename.cls"); - - assertEquals("src/filename.cls", rootNode.getTextDocument().getDisplayName()); - } private final String testCodeForLineNumbers = "public class SimpleClass {\n" // line 1 diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index 97ab04b9d1..64806e2840 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -18,6 +18,7 @@ import java.util.function.Predicate; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.annotation.InternalApi; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.AbstractAccumulatingRenderer; import net.sourceforge.pmd.reporting.FileAnalysisListener; @@ -102,7 +103,7 @@ public final class Report { public static class ProcessingError { private final Throwable error; - private final String file; + private final PathId file; /** * Creates a new processing error @@ -112,7 +113,7 @@ public final class Report { * @param file * the file during which the error occurred */ - public ProcessingError(Throwable error, String file) { + public ProcessingError(Throwable error, PathId file) { this.error = error; this.file = file; } @@ -133,7 +134,7 @@ public final class Report { } public String getFile() { - return file; + return file.toUriString(); } public Throwable getError() { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index 723f5216eb..3c2fbd00f7 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -626,7 +626,7 @@ public class RuleSet implements ChecksumAware { * false otherwise */ boolean applies(TextFile file) { - return applies(file.getDisplayName()); + return applies(file.getPathId().getFileName()); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java index c44b86d146..d77b24b8d7 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java @@ -154,7 +154,7 @@ public class RuleSets { } for (RuleSet ruleSet : ruleSets) { - if (ruleSet.applies(root.getTextDocument().getPathId())) { + if (ruleSet.applies(root.getTextDocument().getPathId().getFileName())) { ruleApplicator.apply(ruleSet.getRules(), listener); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java index 7dcabfed54..8f4d712867 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java @@ -85,7 +85,7 @@ public interface RuleViolation { * @return The source file name. */ default String getFilename() { - return getLocation().getFileName(); + return getLocation().getFileName().toUriString(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java index a70042753e..c93b52c49b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java @@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -34,7 +35,9 @@ import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; import net.sourceforge.pmd.cache.internal.ClasspathFingerprinter; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; +import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.reporting.FileAnalysisListener; /** @@ -49,8 +52,8 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { protected static final Logger LOG = LoggerFactory.getLogger(AbstractAnalysisCache.class); protected static final ClasspathFingerprinter FINGERPRINTER = new ClasspathFingerprinter(); protected final String pmdVersion; - protected final ConcurrentMap fileResultsCache = new ConcurrentHashMap<>(); - protected final ConcurrentMap updatedResultsCache = new ConcurrentHashMap<>(); + protected final ConcurrentMap fileResultsCache = new ConcurrentHashMap<>(); + protected final ConcurrentMap updatedResultsCache = new ConcurrentHashMap<>(); protected final CachedRuleMapper ruleMapper = new CachedRuleMapper(); protected long rulesetChecksum; protected long auxClassPathChecksum; @@ -76,13 +79,6 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { if (upToDate) { LOG.trace("Incremental Analysis cache HIT"); - /* - * Update cached violation "filename" to match the appropriate text document, - * so we can honor relativized paths for the current run - */ - final String displayName = document.getDisplayName(); - cachedResult.getViolations().forEach(v -> ((CachedRuleViolation) v).setFileDisplayName(displayName)); - // copy results over updatedResult = cachedResult; } else { @@ -125,7 +121,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override - public void checkValidity(final RuleSets ruleSets, final ClassLoader auxclassPathClassLoader) { + public void checkValidity(final RuleSets ruleSets, final ClassLoader auxclassPathClassLoader, Set files) { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "validity check")) { boolean cacheIsValid = cacheExists(); @@ -222,7 +218,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public FileAnalysisListener startFileAnalysis(TextDocument file) { - final String fileName = file.getPathId(); + final PathId fileName = file.getPathId(); return new FileAnalysisListener() { @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java index 675df7b7f8..8240cba597 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java @@ -6,6 +6,7 @@ package net.sourceforge.pmd.cache; import java.io.IOException; import java.util.List; +import java.util.Set; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; @@ -64,7 +65,7 @@ public interface AnalysisCache { * @param ruleSets The rulesets configured for this analysis. * @param auxclassPathClassLoader The class loader for auxclasspath configured for this analysis. */ - void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader); + void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Set files); /** * Returns a listener that will be used like in {@link GlobalAnalysisListener#startFileAnalysis(TextFile)}. diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java index 1718ec3f1f..1630c47fa9 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java @@ -5,6 +5,7 @@ package net.sourceforge.pmd.cache; import java.io.IOException; +import java.util.Collections; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.annotation.InternalApi; @@ -23,7 +24,7 @@ public class AnalysisCacheListener implements GlobalAnalysisListener { public AnalysisCacheListener(AnalysisCache cache, RuleSets ruleSets, ClassLoader classLoader) { this.cache = cache; - cache.checkValidity(ruleSets, classLoader); + cache.checkValidity(ruleSets, classLoader, Collections.emptySet()); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java index 13f7504b08..fb90bb84e9 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java @@ -18,6 +18,7 @@ import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.util.StringUtil; @@ -38,10 +39,10 @@ public final class CachedRuleViolation implements RuleViolation { private final String ruleTargetLanguage; private final Map additionalInfo; - private FileLocation location; + private final FileLocation location; private CachedRuleViolation(final CachedRuleMapper mapper, final String description, - final String filePathId, final String ruleClassName, final String ruleName, + final PathId filePathId, final String ruleClassName, final String ruleName, final String ruleTargetLanguage, final int beginLine, final int beginColumn, final int endLine, final int endColumn, final Map additionalInfo) { @@ -54,11 +55,6 @@ public final class CachedRuleViolation implements RuleViolation { this.additionalInfo = additionalInfo; } - void setFileDisplayName(String displayName) { - this.location = FileLocation.range(displayName, - TextRange2d.range2d(getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn())); - } - @Override public Rule getRule() { // The mapper may be initialized after cache is loaded, so use it lazily @@ -83,23 +79,26 @@ public final class CachedRuleViolation implements RuleViolation { /** * Helper method to load a {@link CachedRuleViolation} from an input stream. * - * @param stream The stream from which to load the violation. + * @param stream The stream from which to load the violation. * @param filePathId The name of the file on which this rule was reported. - * @param mapper The mapper to be used to obtain rule instances from the active rulesets. + * @param mapper The mapper to be used to obtain rule instances from the active rulesets. + * * @return The loaded rule violation. - * @throws IOException */ - /* package */ static CachedRuleViolation loadFromStream(final DataInputStream stream, - final String filePathId, final CachedRuleMapper mapper) throws IOException { - final String description = stream.readUTF(); - final String ruleClassName = stream.readUTF(); - final String ruleName = stream.readUTF(); - final String ruleTargetLanguage = stream.readUTF(); - final int beginLine = stream.readInt(); - final int beginColumn = stream.readInt(); - final int endLine = stream.readInt(); - final int endColumn = stream.readInt(); - final Map additionalInfo = readAdditionalInfo(stream); + /* package */ + static CachedRuleViolation loadFromStream( + DataInputStream stream, + PathId filePathId, CachedRuleMapper mapper) throws IOException { + + String description = stream.readUTF(); + String ruleClassName = stream.readUTF(); + String ruleName = stream.readUTF(); + String ruleTargetLanguage = stream.readUTF(); + int beginLine = stream.readInt(); + int beginColumn = stream.readInt(); + int endLine = stream.readInt(); + int endColumn = stream.readInt(); + Map additionalInfo = readAdditionalInfo(stream); return new CachedRuleViolation(mapper, description, filePathId, ruleClassName, ruleName, ruleTargetLanguage, beginLine, beginColumn, endLine, endColumn, additionalInfo); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java index 630dbf3093..ab960b60f2 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java @@ -15,6 +15,8 @@ import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.RuleSets; @@ -23,6 +25,8 @@ import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.benchmark.TimeTracker; import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; +import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.TextFile; /** * An analysis cache backed by a regular file. @@ -45,17 +49,22 @@ public class FileAnalysisCache extends AbstractAnalysisCache { } @Override - public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader) { + public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Set files) { // load cached data before checking for validity - loadFromFile(cacheFile); - super.checkValidity(ruleSets, auxclassPathClassLoader); + loadFromFile(cacheFile, files); + super.checkValidity(ruleSets, auxclassPathClassLoader, files); } /** * Loads cache data from the given file. + * * @param cacheFile The file which backs the file analysis cache. */ - private void loadFromFile(final File cacheFile) { + private void loadFromFile(final File cacheFile, Set files) { + Map idMap = + files.stream().map(TextFile::getPathId) + .collect(Collectors.toMap(PathId::toUriString, id -> id)); + try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "load")) { if (cacheExists()) { try ( @@ -75,15 +84,21 @@ public class FileAnalysisCache extends AbstractAnalysisCache { // Cached results while (inputStream.available() > 0) { final String filePathId = inputStream.readUTF(); + PathId pathId = idMap.get(filePathId); + if (pathId == null) { + LOG.debug("File {} is in the cache but is not part of the analysis", + filePathId); + pathId = PathId.fromPathLikeString(filePathId); + } final long checksum = inputStream.readLong(); final int countViolations = inputStream.readInt(); final List violations = new ArrayList<>(countViolations); for (int i = 0; i < countViolations; i++) { - violations.add(CachedRuleViolation.loadFromStream(inputStream, filePathId, ruleMapper)); + violations.add(CachedRuleViolation.loadFromStream(inputStream, pathId, ruleMapper)); } - fileResultsCache.put(filePathId, new AnalysisResult(checksum, violations)); + fileResultsCache.put(pathId, new AnalysisResult(checksum, violations)); } LOG.debug("Analysis cache loaded from {}", cacheFile); @@ -129,10 +144,10 @@ public class FileAnalysisCache extends AbstractAnalysisCache { outputStream.writeLong(auxClassPathChecksum); outputStream.writeLong(executionClassPathChecksum); - for (final Map.Entry resultEntry : updatedResultsCache.entrySet()) { + for (final Map.Entry resultEntry : updatedResultsCache.entrySet()) { final List violations = resultEntry.getValue().getViolations(); - outputStream.writeUTF(resultEntry.getKey()); // the path id + outputStream.writeUTF(resultEntry.getKey().toUriString()); // the path id outputStream.writeLong(resultEntry.getValue().getFileChecksum()); outputStream.writeInt(violations.size()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java index 827b7e5c4f..89764769bb 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java @@ -6,11 +6,13 @@ package net.sourceforge.pmd.cache; import java.util.Collections; import java.util.List; +import java.util.Set; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.document.TextDocument; +import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.reporting.FileAnalysisListener; /** @@ -38,7 +40,7 @@ public class NoopAnalysisCache implements AnalysisCache { } @Override - public void checkValidity(final RuleSets ruleSets, final ClassLoader classLoader) { + public void checkValidity(final RuleSets ruleSets, final ClassLoader classLoader, Set files) { // noop } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java index 2d5ad99b4a..3d9ccd4d0a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java @@ -78,7 +78,7 @@ public class TokenEntry implements Comparable { } public TokenEntry(String image, FileLocation location) { - this(image, location.getFileName(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); + this(image, location.getFileName().getNiceFileName(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); } private boolean isOk(int coord) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java index b09703881a..8833fccaf9 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java @@ -32,7 +32,7 @@ public abstract class AntlrTokenizer implements Tokenizer { public void tokenize(final SourceCode sourceCode, final Tokens tokenEntries) { try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { - CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getDisplayName()); + CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getNiceFileName()); final AntlrTokenManager tokenManager = new AntlrTokenManager(getLexerForSource(charStream), textDoc); final AntlrTokenFilter tokenFilter = getTokenFilter(tokenManager); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java index 3c45b96033..b702fde142 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java @@ -19,6 +19,7 @@ import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument.TokenDocumentBehavior; import net.sourceforge.pmd.lang.document.CpdCompat; import net.sourceforge.pmd.lang.document.TextDocument; +import net.sourceforge.pmd.lang.document.TextFile; public abstract class JavaCCTokenizer implements Tokenizer { @@ -47,7 +48,8 @@ public abstract class JavaCCTokenizer implements Tokenizer { @Override public void tokenize(SourceCode sourceCode, Tokens tokenEntries) throws IOException { - try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { + TextFile textFile = CpdCompat.cpdCompat(sourceCode); + try (TextDocument textDoc = TextDocument.create(textFile)) { TokenManager tokenManager = getLexerForSource(textDoc); final TokenFilter tokenFilter = getTokenFilter(tokenManager); JavaccToken currentToken = tokenFilter.getNextToken(); @@ -56,7 +58,7 @@ public abstract class JavaCCTokenizer implements Tokenizer { currentToken = tokenFilter.getNextToken(); } } catch (FileAnalysisException e) { - throw e.setFileName(sourceCode.getFileName()); + throw e.setFileName(textFile.getPathId()); } finally { tokenEntries.add(TokenEntry.getEOF()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java index efa42a1df1..782de1e71b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java @@ -17,6 +17,7 @@ import org.slf4j.LoggerFactory; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.lang.document.FileCollector; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.util.database.DBMSMetadata; import net.sourceforge.pmd.util.database.DBURI; import net.sourceforge.pmd.util.database.SourceObject; @@ -126,7 +127,7 @@ public final class FileCollectionUtil { try (Reader sourceCode = dbmsMetadata.getSourceCode(sourceObject)) { String source = IOUtil.readToString(sourceCode); - collector.addSourceFile(source, falseFilePath); + collector.addSourceFile(PathId.fromPathLikeString(falseFilePath), source); } catch (SQLException ex) { collector.getReporter().warnEx("Cannot get SourceCode for {} - skipping ...", new Object[] { falseFilePath }, diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java index 0c7f9de52c..a0d869b740 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java @@ -9,7 +9,7 @@ import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; -import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.lang.document.PathId; /** * An exception that occurs while processing a file. Subtypes include @@ -22,7 +22,7 @@ import net.sourceforge.pmd.lang.document.TextFile; */ public class FileAnalysisException extends RuntimeException { - private String filename = TextFile.UNKNOWN_FILENAME; + private PathId filename = PathId.UNKNOWN; public FileAnalysisException() { super(); @@ -40,19 +40,19 @@ public class FileAnalysisException extends RuntimeException { super(message, cause); } - public FileAnalysisException setFileName(String filename) { + public FileAnalysisException setFileName(PathId filename) { this.filename = Objects.requireNonNull(filename); return this; } protected boolean hasFileName() { - return !TextFile.UNKNOWN_FILENAME.equals(filename); + return !PathId.UNKNOWN.equals(filename); } /** * The name of the file in which the error occurred. */ - public @NonNull String getFileName() { + public @NonNull PathId getFileName() { return filename; } @@ -83,7 +83,7 @@ public class FileAnalysisException extends RuntimeException { * * @return An exception */ - public static FileAnalysisException wrap(@NonNull String filename, @NonNull String message, @NonNull Throwable cause) { + public static FileAnalysisException wrap(@NonNull PathId filename, @NonNull String message, @NonNull Throwable cause) { if (cause instanceof FileAnalysisException) { return ((FileAnalysisException) cause).setFileName(filename); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java index d62980562a..ab9bc5f201 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java @@ -59,7 +59,7 @@ public interface Parser { * not be interpreted, it may not be a file-system path. */ public String getFileDisplayName() { - return textDoc.getDisplayName(); + return textDoc.getPathId().getNiceFileName(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java index 06dd3b01a1..61202727ef 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java @@ -7,6 +7,7 @@ package net.sourceforge.pmd.lang.ast; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.InternalApi; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.util.StringUtil; /** @@ -26,7 +27,7 @@ public final class TokenMgrError extends FileAnalysisException { * @param message Message of the error * @param cause Cause of the error, if any */ - public TokenMgrError(int line, int column, @Nullable String filename, String message, @Nullable Throwable cause) { + public TokenMgrError(int line, int column, @Nullable PathId filename, String message, @Nullable Throwable cause) { super(message, cause); this.line = line; this.column = column; @@ -71,7 +72,7 @@ public final class TokenMgrError extends FileAnalysisException { * @return A new exception */ @Override - public TokenMgrError setFileName(String filename) { + public TokenMgrError setFileName(PathId filename) { super.setFileName(filename); return this; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java index bc5ad370e7..3710fc728c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java @@ -63,7 +63,7 @@ public class AntlrTokenManager implements TokenManager { final int charPositionInLine, final String msg, final RecognitionException ex) { - throw new TokenMgrError(line, charPositionInLine, textDoc.getDisplayName(), msg, ex); + throw new TokenMgrError(line, charPositionInLine, textDoc.getPathId(), msg, ex); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java index 60d701bba9..9720acde9b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java @@ -35,7 +35,7 @@ public abstract class JjtreeParserAdapter implements Parser // Finally, do the parsing return parseImpl(charStream, task); } catch (FileAnalysisException tme) { - throw tme.setFileName(task.getFileDisplayName()); + throw tme.setFileName(task.getTextDocument().getPathId()); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java index d6e8fc9e8e..8e5aac3ba1 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java @@ -26,15 +26,10 @@ abstract class BaseMappedDocument implements TextDocument { } @Override - public String getPathId() { + public PathId getPathId() { return base.getPathId(); } - @Override - public String getDisplayName() { - return base.getDisplayName(); - } - @Override public Chars sliceOriginalText(TextRegion region) { return base.sliceOriginalText(inputRegion(region)); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java index 9b0a19f12c..6328a65c06 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java @@ -33,7 +33,7 @@ public final class CpdCompat { public static TextFile cpdCompat(SourceCode sourceCode) { return TextFile.forCharSeq( sourceCode.getCodeBuffer(), - sourceCode.getFileName(), + PathId.fromPathLikeString("fname1.dummy"), dummyVersion() ); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index 516851b167..97e6e005ea 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -155,7 +155,6 @@ public final class FileCollector implements AutoCloseable { LanguageVersion languageVersion = discoverLanguage(file.toString()); return languageVersion != null && addFileImpl(TextFile.builderForPath(file, charset, languageVersion) - .withDisplayName(getDisplayName(file)) .build()); } @@ -178,7 +177,6 @@ public final class FileCollector implements AutoCloseable { LanguageVersion lv = discoverer.getDefaultLanguageVersion(language); Objects.requireNonNull(lv); return addFileImpl(TextFile.builderForPath(file, charset, lv) - .withDisplayName(getDisplayName(file)) .build()); } @@ -200,14 +198,13 @@ public final class FileCollector implements AutoCloseable { * * @return True if the file has been added */ - public boolean addSourceFile(String pathId, String sourceContents) { + public boolean addSourceFile(PathId pathId, String sourceContents) { AssertionUtil.requireParamNotNull("sourceContents", sourceContents); AssertionUtil.requireParamNotNull("pathId", pathId); - LanguageVersion version = discoverLanguage(pathId); + LanguageVersion version = discoverLanguage(pathId.getFileName()); return version != null && addFileImpl(TextFile.builderForCharSeq(sourceContents, pathId, version) - .withDisplayName(pathId) .build()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java index 57768ac833..ad798c0dbe 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java @@ -41,14 +41,14 @@ public final class FileLocation { private final int endLine; private final int beginColumn; private final int endColumn; - private final String fileName; + private final PathId fileName; private final @Nullable TextRegion region; - FileLocation(String fileName, int beginLine, int beginColumn, int endLine, int endColumn) { + FileLocation(PathId fileName, int beginLine, int beginColumn, int endLine, int endColumn) { this(fileName, beginLine, beginColumn, endLine, endColumn, null); } - FileLocation(String fileName, int beginLine, int beginColumn, int endLine, int endColumn, @Nullable TextRegion region) { + FileLocation(PathId fileName, int beginLine, int beginColumn, int endLine, int endColumn, @Nullable TextRegion region) { this.fileName = Objects.requireNonNull(fileName); this.beginLine = AssertionUtil.requireOver1("Begin line", beginLine); this.endLine = AssertionUtil.requireOver1("End line", endLine); @@ -71,7 +71,7 @@ public final class FileLocation { * File name of this position. This is a display name, it shouldn't * be parsed as a Path. */ - public String getFileName() { + public PathId getFileName() { return fileName; } @@ -145,7 +145,7 @@ public final class FileLocation { * @throws IllegalArgumentException If the line and column are not correctly ordered * @throws IllegalArgumentException If the start offset or length are negative */ - public static FileLocation range(String fileName, TextRange2d range2d) { + public static FileLocation range(PathId fileName, TextRange2d range2d) { TextPos2d start = range2d.getStartPos(); TextPos2d end = range2d.getEndPos(); return new FileLocation(fileName, @@ -164,9 +164,9 @@ public final class FileLocation { * * @return A new location * - * @throws IllegalArgumentException See {@link #range(String, int, int, int, int)} + * @throws IllegalArgumentException See {@link #range(PathId, TextRange2d)} */ - public static FileLocation caret(String fileName, int line, int column) { + public static FileLocation caret(PathId fileName, int line, int column) { return new FileLocation(fileName, line, column, line, column); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java index 34f6a71bc5..f74964e751 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java @@ -25,28 +25,24 @@ class NioTextFile extends BaseCloseable implements TextFile { private final Path path; private final Charset charset; private final LanguageVersion languageVersion; - private final String displayName; - private final String pathId; + private final PathId pathId; private boolean readOnly; NioTextFile(Path path, Charset charset, LanguageVersion languageVersion, - 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; this.path = path; this.charset = charset; this.languageVersion = languageVersion; // using the URI here, that handles files inside zip archives automatically (schema "jar:file:...!/path/inside/zip") // normalization ensures cannonical paths - this.pathId = path.normalize().toUri().toString(); + this.pathId = PathId.fromPath(path); } @Override @@ -55,12 +51,7 @@ class NioTextFile extends BaseCloseable implements TextFile { } @Override - public @NonNull String getDisplayName() { - return displayName; - } - - @Override - public String getPathId() { + public PathId getPathId() { return pathId; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java new file mode 100644 index 0000000000..86ef8d7590 --- /dev/null +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java @@ -0,0 +1,108 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.document; + +import java.nio.file.Path; + +/** + * A virtual path for a {@link TextFile}. + * + * @author Clément Fournier + */ +public interface PathId extends Comparable { + + /** + * The name used for a file that has no name. This is mostly only + * relevant for unit tests. + */ + PathId UNKNOWN = fromPathLikeString("(unknown file)"); + + String toUriString(); + + String getFileName(); + String getNiceFileName(); + + + @Override + boolean equals(Object o); + + + @Override + default int compareTo(PathId o) { + return this.toUriString().compareTo(o.toUriString()); + } + + PathId STDIN = new PathId() { + @Override + public String toUriString() { + return "stdin"; + } + + @Override + public String getFileName() { + return "stdin"; + } + + @Override + public String getNiceFileName() { + return "stdin"; + } + }; + + static PathId fromPathLikeString(String str) { + String[] segments = str.split("[/\\\\]"); + if (segments.length == 0) { + throw new IllegalArgumentException("Invalid path id: '" + str + "'"); + } + String fname = segments[segments.length - 1]; + return new PathId() { + @Override + public String toUriString() { + return str; + } + + @Override + public String getFileName() { + return fname; + } + + @Override + public String getNiceFileName() { + return str; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof PathId + && ((PathId) obj).toUriString().equals(this.toUriString()); + } + }; + } + + static PathId fromPath(Path path) { + return new PathId() { + @Override + public String toUriString() { + return path.normalize().toUri().toString(); + } + + @Override + public String getFileName() { + return path.getFileName().toString(); + } + + @Override + public String getNiceFileName() { + return path.toString(); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof PathId + && ((PathId) obj).toUriString().equals(this.toUriString()); + } + }; + } +} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java index d23ae6494e..b31ccaf776 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java @@ -17,28 +17,23 @@ import net.sourceforge.pmd.util.AssertionUtil; */ class ReaderTextFile implements TextFile { - private final String name; + private final PathId pathId; private final LanguageVersion languageVersion; private final Reader reader; - ReaderTextFile(Reader reader, @NonNull String name, LanguageVersion languageVersion) { + ReaderTextFile(Reader reader, @NonNull PathId pathId, LanguageVersion languageVersion) { AssertionUtil.requireParamNotNull("reader", reader); - AssertionUtil.requireParamNotNull("file name", name); + AssertionUtil.requireParamNotNull("path id", pathId); AssertionUtil.requireParamNotNull("language version", languageVersion); this.reader = reader; this.languageVersion = languageVersion; - this.name = name; + this.pathId = pathId; } @Override - public @NonNull String getDisplayName() { - return name; - } - - @Override - public String getPathId() { - return name; + public PathId getPathId() { + return pathId; } @Override @@ -58,7 +53,7 @@ class ReaderTextFile implements TextFile { @Override public String toString() { - return "ReaderTextFile[" + name + "]"; + return "ReaderTextFile[" + pathId + "]"; } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java index be09e85419..8f0b7d29ca 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java @@ -27,18 +27,15 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { private final LanguageVersion langVersion; - private final String fileName; - private final String pathId; + private final PathId pathId; RootTextDocument(TextFile backend) throws IOException { this.backend = backend; this.content = backend.readContents(); this.langVersion = backend.getLanguageVersion(); - this.fileName = backend.getDisplayName(); this.pathId = backend.getPathId(); Objects.requireNonNull(langVersion, "Null language version for file " + backend); - Objects.requireNonNull(fileName, "Null display name for file " + backend); Objects.requireNonNull(pathId, "Null path id for file " + backend); } @@ -48,12 +45,7 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { } @Override - public String getDisplayName() { - return fileName; - } - - @Override - public String getPathId() { + public PathId getPathId() { return pathId; } @@ -79,7 +71,7 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { : positioner.lineColFromOffset(region.getEndOffset(), false); return new FileLocation( - fileName, + pathId, bpos.getLine(), bpos.getColumn(), epos.getLine(), diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java index 7c288ff04b..58935a070c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java @@ -16,17 +16,17 @@ import net.sourceforge.pmd.util.StringUtil; class StringTextFile implements TextFile { private final TextFileContent content; - private final String name; + private final PathId pathId; private final LanguageVersion languageVersion; - StringTextFile(CharSequence source, String name, LanguageVersion languageVersion) { + StringTextFile(CharSequence source, PathId pathId, LanguageVersion languageVersion) { AssertionUtil.requireParamNotNull("source text", source); - AssertionUtil.requireParamNotNull("file name", name); + AssertionUtil.requireParamNotNull("file name", pathId); AssertionUtil.requireParamNotNull("language version", languageVersion); this.languageVersion = languageVersion; this.content = TextFileContent.fromCharSeq(source); - this.name = name; + this.pathId = pathId; } @Override @@ -36,12 +36,12 @@ class StringTextFile implements TextFile { @Override public @NonNull String getDisplayName() { - return name; + return pathId.toUriString(); } @Override - public String getPathId() { - return name; + public PathId getPathId() { + return pathId; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java index 153f43e360..dc353f7166 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java @@ -88,12 +88,14 @@ public interface TextDocument extends Closeable { /** * Returns {@link TextFile#getPathId()} for the text file backing this document. */ - String getPathId(); + PathId getPathId(); /** * Returns {@link TextFile#getDisplayName()} for the text file backing this document. */ - String getDisplayName(); + default String getDisplayName() { + return getPathId().getNiceFileName(); + } /** @@ -261,10 +263,10 @@ public interface TextDocument extends Closeable { /** * Returns a read-only document for the given text. * - * @see TextFile#forCharSeq(CharSequence, String, LanguageVersion) + * @see TextFile#forCharSeq(CharSequence, PathId, LanguageVersion) */ static TextDocument readOnlyString(final CharSequence source, LanguageVersion lv) { - return readOnlyString(source, TextFile.UNKNOWN_FILENAME, lv); + return readOnlyString(source, PathId.UNKNOWN, lv); } /** @@ -274,10 +276,10 @@ public interface TextDocument extends Closeable { * but doesn't throw {@link IOException}, as such text files will * not throw. * - * @see TextFile#forCharSeq(CharSequence, String, LanguageVersion) + * @see TextFile#forCharSeq(CharSequence, PathId, LanguageVersion) */ @SuppressWarnings("PMD.CloseResource") - static TextDocument readOnlyString(@NonNull CharSequence source, @NonNull String filename, @NonNull LanguageVersion lv) { + static TextDocument readOnlyString(@NonNull CharSequence source, @NonNull PathId filename, @NonNull LanguageVersion lv) { TextFile textFile = TextFile.forCharSeq(source, filename, lv); try { return create(textFile); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index a4c2bfacdf..899b15bcc2 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -44,12 +44,6 @@ import net.sourceforge.pmd.util.datasource.DataSource; */ public interface TextFile extends Closeable { - /** - * The name used for a file that has no name. This is mostly only - * relevant for unit tests. - */ - String UNKNOWN_FILENAME = "(unknown file)"; - /** * Returns the language version which should be used to process this @@ -76,7 +70,7 @@ public interface TextFile extends Closeable { *

Basically this may be implemented as a URL, or a file path. It * is used to index violation caches. */ - String getPathId(); + PathId getPathId(); /** @@ -85,8 +79,9 @@ public interface TextFile extends Closeable { * to a directory or so, it may also not be normalized. Use * {@link #getPathId()} when you want an identifier. */ - @NonNull - String getDisplayName(); + default @NonNull String getDisplayName() { + return getPathId().getNiceFileName(); + } /** @@ -161,7 +156,6 @@ public interface TextFile extends Closeable { */ static TextFile forPath(Path path, Charset charset, LanguageVersion languageVersion) { return builderForPath(path, charset, languageVersion) - .withDisplayName(path.toString()) .build(); } @@ -195,9 +189,8 @@ public interface TextFile extends Closeable { * * @throws NullPointerException If any parameter is null */ - static TextFile forCharSeq(CharSequence charseq, String pathId, LanguageVersion languageVersion) { + static TextFile forCharSeq(CharSequence charseq, PathId pathId, LanguageVersion languageVersion) { return builderForCharSeq(charseq, pathId, languageVersion) - .withDisplayName(pathId) .build(); } @@ -212,7 +205,7 @@ public interface TextFile extends Closeable { * * @throws NullPointerException If any parameter is null */ - static TextFileBuilder builderForCharSeq(CharSequence charseq, String pathId, LanguageVersion languageVersion) { + static TextFileBuilder builderForCharSeq(CharSequence charseq, PathId pathId, LanguageVersion languageVersion) { return new ForCharSeq(charseq, pathId, languageVersion); } @@ -229,9 +222,8 @@ public interface TextFile extends Closeable { * * @throws NullPointerException If any parameter is null */ - static TextFile forReader(Reader reader, String pathId, LanguageVersion languageVersion) { + static TextFile forReader(Reader reader, PathId pathId, LanguageVersion languageVersion) { return builderForReader(reader, pathId, languageVersion) - .withDisplayName(pathId) .build(); } @@ -248,7 +240,7 @@ public interface TextFile extends Closeable { * * @throws NullPointerException If any parameter is null */ - static TextFileBuilder builderForReader(Reader reader, String pathId, LanguageVersion languageVersion) { + static TextFileBuilder builderForReader(Reader reader, PathId pathId, LanguageVersion languageVersion) { return new ForReader(languageVersion, reader, pathId); } @@ -264,6 +256,7 @@ public interface TextFile extends Closeable { @DeprecatedUntil700 static TextFile dataSourceCompat(DataSource ds, PMDConfiguration config) { String pathId = ds.getNiceFileName(false, null); + PathId pathId2 = PathId.fromPathLikeString(pathId); LanguageVersion languageVersion = config.getLanguageVersionOfFile(pathId); if (languageVersion == null) { throw new NullPointerException("no language version detected for " + pathId); @@ -277,8 +270,8 @@ public interface TextFile extends Closeable { } @Override - public String getPathId() { - return pathId; + public PathId getPathId() { + return pathId2; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java index b8e146a91a..e1e7242321 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java @@ -8,8 +8,6 @@ import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Path; -import org.checkerframework.checker.nullness.qual.Nullable; - import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.util.AssertionUtil; @@ -21,7 +19,6 @@ import net.sourceforge.pmd.util.AssertionUtil; public abstract class TextFileBuilder { protected final LanguageVersion languageVersion; - protected @Nullable String displayName; TextFileBuilder(LanguageVersion languageVersion) { this.languageVersion = AssertionUtil.requireParamNotNull("language version", languageVersion); @@ -39,19 +36,6 @@ public abstract class TextFileBuilder { } - /** - * Sets a custom display name for the new file. If null, or this is - * never called, the display name defaults to the path ID. - * - * @param displayName A display name - * - * @return This builder - */ - public TextFileBuilder withDisplayName(@Nullable String displayName) { - this.displayName = displayName; - return this; - } - /** * Creates and returns the new text file. */ @@ -77,16 +61,16 @@ public abstract class TextFileBuilder { @Override public TextFile build() { - return new NioTextFile(path, charset, languageVersion, displayName, readOnly); + return new NioTextFile(path, charset, languageVersion, readOnly); } } static class ForCharSeq extends TextFileBuilder { private final CharSequence charSequence; - private final String pathId; + private final PathId pathId; - ForCharSeq(CharSequence charSequence, String pathId, LanguageVersion languageVersion) { + ForCharSeq(CharSequence charSequence, PathId pathId, LanguageVersion languageVersion) { super(languageVersion); this.charSequence = AssertionUtil.requireParamNotNull("charseq", charSequence); this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); @@ -101,9 +85,9 @@ public abstract class TextFileBuilder { static class ForReader extends TextFileBuilder { private final Reader reader; - private final String pathId; + private final PathId pathId; - ForReader(LanguageVersion languageVersion, Reader reader, String pathId) { + ForReader(LanguageVersion languageVersion, Reader reader, PathId pathId) { super(languageVersion); this.reader = AssertionUtil.requireParamNotNull("reader", reader); this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java index 3e9a428544..d11e34bedf 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java @@ -85,7 +85,7 @@ abstract class PmdRunnable implements Runnable { // The listener handles logging if needed, // it may also rethrow the error, as a FileAnalysisException (which we let through below) - completeListener.onError(new Report.ProcessingError(e, textFile.getDisplayName())); + completeListener.onError(new Report.ProcessingError(e, textFile.getPathId())); } } } @@ -95,7 +95,7 @@ abstract class PmdRunnable implements Runnable { } catch (FileAnalysisException e) { throw e; // bubble managed exceptions, they were already reported } catch (Exception e) { - throw FileAnalysisException.wrap(textFile.getDisplayName(), "An unknown exception occurred", e); + throw FileAnalysisException.wrap(textFile.getPathId(), "An unknown exception occurred", e); } TimeTracker.finishThread(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java index e6382d7e2a..c2661628ad 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java @@ -106,7 +106,7 @@ public class RuleApplicator { private void reportException(FileAnalysisListener listener, Rule rule, Node node, Throwable e) { // The listener handles logging if needed, // it may also rethrow the error. - listener.onError(new ProcessingError(e, node.getTextDocument().getDisplayName())); + listener.onError(new ProcessingError(e, node.getTextDocument().getPathId())); // fixme - maybe duplicated logging LOG.warn("Exception applying rule {} on file {}, continuing with next rule", rule.getName(), node.getTextDocument().getPathId(), e); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java index 3dc3294328..2805a76b1b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java @@ -4,7 +4,6 @@ package net.sourceforge.pmd.lang.rule.xpath.internal; -import java.nio.file.Paths; import java.util.Objects; import net.sourceforge.pmd.lang.ast.Node; @@ -57,11 +56,10 @@ public final class FileNameXPathFunction extends AbstractXPathFunctionDef { RootNode root = node.getRoot(); Objects.requireNonNull(root, "No root node in tree?"); - String fileName = root.getTextDocument().getDisplayName(); + String fileName = root.getTextDocument().getPathId().getFileName(); Objects.requireNonNull(fileName, "File name was not set"); - String simpleFilename = Paths.get(fileName).getFileName().toString(); - return new StringValue(simpleFilename); + return new StringValue(fileName); } }; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java index 6738110a0e..d456bdf7d0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java @@ -17,6 +17,7 @@ import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.ast.FileAnalysisException; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.util.AssertionUtil; @@ -197,7 +198,7 @@ public interface GlobalAnalysisListener extends AutoCloseable { @Override public FileAnalysisListener startFileAnalysis(TextFile file) { - String filename = file.getPathId(); // capture the filename instead of the file + PathId filename = file.getPathId(); // capture the filename instead of the file return new FileAnalysisListener() { @Override public void onRuleViolation(RuleViolation violation) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java index 3c7e4edb0a..509051713a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java @@ -23,6 +23,7 @@ import net.sourceforge.pmd.lang.ast.Parser; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.RootNode; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.xpath.Attribute; @@ -73,7 +74,7 @@ public class TreeExporter { TextFile textFile; if (configuration.isReadStdin()) { io.stderr.println("Reading from stdin..."); - textFile = TextFile.forReader(readFromSystemIn(), "stdin", langVersion); + textFile = TextFile.forReader(readFromSystemIn(), PathId.STDIN, langVersion); } else { textFile = TextFile.forPath(configuration.getFile(), configuration.getSourceEncoding(), langVersion); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java index 7058041d45..d7b5cb73b5 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; @@ -77,11 +78,11 @@ class AbstractRuleTest { void testCreateRV() { MyRule r = new MyRule(); r.setRuleSetName("foo"); - DummyRootNode s = helper.parse("abc()", "filename"); + DummyRootNode s = helper.parse("abc()", PathId.fromPathLikeString("abc")); RuleViolation rv = new ParametricRuleViolation(r, s, r.getMessage()); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); - assertEquals("filename", rv.getFilename(), "Filename mismatch!"); + assertEquals("abc", rv.getFilename(), "Filename mismatch!"); assertEquals(r, rv.getRule(), "Rule object mismatch!"); assertEquals("my rule msg", rv.getDescription(), "Rule msg mismatch!"); assertEquals("foo", rv.getRule().getRuleSetName(), "RuleSet name mismatch!"); @@ -90,7 +91,7 @@ class AbstractRuleTest { @Test void testCreateRV2() { MyRule r = new MyRule(); - DummyRootNode s = helper.parse("abc()", "filename"); + DummyRootNode s = helper.parse("abc()", PathId.fromPathLikeString("filename")); RuleViolation rv = new ParametricRuleViolation(r, s, "specificdescription"); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); assertEquals("filename", rv.getFilename(), "Filename mismatch!"); @@ -109,7 +110,7 @@ class AbstractRuleTest { r.definePropertyDescriptor(PropertyFactory.intProperty("testInt").desc("description").require(inRange(0, 100)).defaultValue(10).build()); r.setMessage("Message ${packageName} ${className} ${methodName} ${variableName} ${testInt} ${noSuchProperty}"); - DummyRootNode s = helper.parse("abc()", "filename"); + DummyRootNode s = helper.parse("abc()", PathId.UNKNOWN); RuleViolation rv = getReportForRuleApply(r, s).getViolations().get(0); assertEquals("Message foo ${className} ${methodName} ${variableName} 10 ${noSuchProperty}", rv.getDescription()); @@ -117,7 +118,7 @@ class AbstractRuleTest { @Test void testRuleSuppress() { - DummyRootNode n = helper.parse("abc()", "filename") + DummyRootNode n = helper.parse("abc()", PathId.UNKNOWN) .withNoPmdComments(Collections.singletonMap(1, "ohio")); FileAnalysisListener listener = mock(FileAnalysisListener.class); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java index 15fc832461..73d6c3bea5 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java @@ -19,8 +19,8 @@ import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; -import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.util.log.MessageReporter; /** @@ -35,10 +35,13 @@ public class DummyParsingHelper implements Extension, BeforeEachCallback, AfterE } public DummyRootNode parse(String code) { - return parse(code, TextFile.UNKNOWN_FILENAME); + return parse(code, PathId.UNKNOWN); } public DummyRootNode parse(String code, String filename) { + return parse(code, PathId.fromPathLikeString(filename)); + } + public DummyRootNode parse(String code, PathId filename) { LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion(); ParserTask task = new ParserTask( TextDocument.readOnlyString(code, filename, version), diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java index e0ef291766..8da10a4ab7 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java @@ -28,6 +28,7 @@ import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.SimpleTestTextFile; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.renderers.Renderer; @@ -93,7 +94,7 @@ class PmdAnalysisTest { config.setForceLanguageVersion(DummyLanguageModule.getInstance().getVersionWhereParserThrows()); try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(RuleSet.forSingleRule(new MockRule())); - pmd.files().addSourceFile("file", "some source"); + pmd.files().addSourceFile(PathId.fromPathLikeString("file"), "some source"); ReportStats stats = pmd.runAndReturnStats(); assertEquals(1, stats.getNumErrors(), "Errors"); @@ -116,7 +117,7 @@ class PmdAnalysisTest { } })); - pmd.files().addSourceFile("file", "some source"); + pmd.files().addSourceFile(PathId.fromPathLikeString("fname1.dummy"), "some source"); ReportStats stats = pmd.runAndReturnStats(); // the error number here is only for FileAnalysisException, so @@ -156,7 +157,7 @@ class PmdAnalysisTest { try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(ruleset); - pmd.files().addFile(new SimpleTestTextFile("test content foo", "foo.txt", language.getDefaultVersion())); + pmd.files().addFile(new SimpleTestTextFile("test content foo", PathId.fromPathLikeString("foo.txt"), language.getDefaultVersion())); Report report = pmd.performAnalysisAndCollectReport(); for (Report.ProcessingError error : report.getProcessingErrors()) { System.out.println("error = " + error.getMsg() + ": " + error.getDetail()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java index e2bd21c114..91f7846576 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java @@ -18,8 +18,8 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; -import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; import net.sourceforge.pmd.renderers.Renderer; @@ -113,14 +113,14 @@ class ReportTest { private static FileLocation getNode(int line, int column, String filename) { - return FileLocation.range(filename, TextRange2d.range2d(line, column, line, column)); + return FileLocation.caret(PathId.fromPathLikeString(filename), line, column); } public static String render(Renderer renderer, Consumer listenerEffects) { return renderGlobal(renderer, globalListener -> { LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion(); - TextFile dummyFile = TextFile.forCharSeq("dummyText", "file", dummyVersion); + TextFile dummyFile = TextFile.forCharSeq("dummyText", PathId.fromPathLikeString("file"), dummyVersion); try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) { listenerEffects.accept(fal); } catch (Exception e) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java index 33ff6a03d9..d6bba2906b 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java @@ -17,6 +17,7 @@ import java.util.Random; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -71,7 +72,7 @@ class RuleViolationComparatorTest { private RuleViolation createJavaRuleViolation(Rule rule, String fileName, int beginLine, String description, int beginColumn, int endLine, int endColumn) { - FileLocation loc = FileLocation.range(fileName, TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); + FileLocation loc = FileLocation.range(PathId.fromPathLikeString(fileName), TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); return new ParametricRuleViolation(rule, loc, description, Collections.emptyMap()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java index a686d4f115..96449b0cb3 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java @@ -16,7 +16,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.lang.ast.DummyNode; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -25,11 +25,12 @@ class RuleViolationTest { @RegisterExtension private final DummyParsingHelper helper = new DummyParsingHelper(); + private PathId filename = PathId.fromPathLikeString("filename"); @Test void testConstructor1() { Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); - DummyRootNode s = helper.parse("abcd", "filename"); + DummyRootNode s = helper.parse("abcd", filename); RuleViolation r = new ParametricRuleViolation(rule, s, rule.getMessage()); assertEquals(rule, r.getRule(), "object mismatch"); assertEquals(1, r.getBeginLine(), "line number is wrong"); @@ -39,7 +40,7 @@ class RuleViolationTest { @Test void testConstructor2() { Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); - DummyRootNode s = helper.parse("abcd", "filename"); + DummyRootNode s = helper.parse("abcd", filename); RuleViolation r = new ParametricRuleViolation(rule, s, "description"); assertEquals(rule, r.getRule(), "object mismatch"); assertEquals(1, r.getBeginLine(), "line number is wrong"); @@ -51,8 +52,8 @@ class RuleViolationTest { void testComparatorWithDifferentFilenames() { Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); Comparator comp = RuleViolation.DEFAULT_COMPARATOR; - DummyNode s = helper.parse("(abc)", "filename1").getFirstChild(); - DummyNode s1 = helper.parse("(abc)", "filename2").getFirstChild(); + DummyNode s = helper.parse("(abc)", PathId.fromPathLikeString("f1")).getFirstChild(); + DummyNode s1 = helper.parse("(abc)", PathId.fromPathLikeString("f2")).getFirstChild(); RuleViolation r1 = new ParametricRuleViolation(rule, s, "description"); RuleViolation r2 = new ParametricRuleViolation(rule, s1, "description"); assertEquals(-1, comp.compare(r1, r2)); @@ -76,7 +77,6 @@ class RuleViolationTest { void testComparatorWithSameFileSameLines() { Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); Comparator comp = RuleViolation.DEFAULT_COMPARATOR; - String filename = TextFile.UNKNOWN_FILENAME; FileLocation loc = FileLocation.range(filename, TextRange2d.range2d(10, 1, 15, 10)); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index 9424c3be2f..88fea5eef5 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -39,6 +39,7 @@ import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextFileContent; @@ -112,15 +113,15 @@ class FileAnalysisCacheTest { @Test void testStorePersistsFilesWithViolations() throws IOException { final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class)); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); final FileAnalysisListener cacheListener = cache.startFileAnalysis(sourceFile); cache.isUpToDate(sourceFile); final RuleViolation rv = mock(RuleViolation.class); - when(rv.getFilename()).thenReturn(sourceFile.getDisplayName()); + when(rv.getFilename()).thenReturn(sourceFile.getPathId().toUriString()); final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); - when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getDisplayName(), textLocation)); + when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getPathId(), textLocation)); final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS); when(rule.getLanguage()).thenReturn(mock(Language.class)); when(rv.getRule()).thenReturn(rule); @@ -129,7 +130,7 @@ class FileAnalysisCacheTest { cache.persist(); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class)); + reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file with violations is not up to date"); @@ -157,32 +158,28 @@ class FileAnalysisCacheTest { final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); TextFile mockFile = mock(TextFile.class); - when(mockFile.getDisplayName()).thenReturn("display0"); - when(mockFile.getPathId()).thenReturn("pathId"); + when(mockFile.getPathId()).thenReturn(PathId.fromPathLikeString("a/bc")); when(mockFile.getLanguageVersion()).thenReturn(dummyVersion); when(mockFile.readContents()).thenReturn(TextFileContent.fromCharSeq("abc")); final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class)); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); try (TextDocument doc0 = TextDocument.create(mockFile)) { cache.isUpToDate(doc0); try (FileAnalysisListener listener = cache.startFileAnalysis(doc0)) { - listener.onRuleViolation(new ParametricRuleViolation(rule, FileLocation.range(doc0.getDisplayName(), textLocation), "message")); + listener.onRuleViolation(new ParametricRuleViolation(rule, FileLocation.range(doc0.getPathId(), textLocation), "message")); } } finally { cache.persist(); } reloadWithOneViolation(mockFile); - // now try with another display name - when(mockFile.getDisplayName()).thenReturn("display2"); - reloadWithOneViolation(mockFile); } private void reloadWithOneViolation(TextFile mockFile) throws IOException { final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class)); + reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); try (TextDocument doc1 = TextDocument.create(mockFile)) { assertTrue(reloadedCache.isUpToDate(doc1), "Cache believes unmodified file with violations is not up to date"); @@ -202,7 +199,7 @@ class FileAnalysisCacheTest { setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date without ruleset / classpath changes"); } @@ -219,7 +216,7 @@ class FileAnalysisCacheTest { when(cl.getURLs()).thenReturn(new URL[] { classpathFile.toURI().toURL(), }); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date without ruleset / classpath changes"); } @@ -233,7 +230,7 @@ class FileAnalysisCacheTest { final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); when(rs.getChecksum()).thenReturn(1L); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is up to date after ruleset changed"); } @@ -248,7 +245,7 @@ class FileAnalysisCacheTest { final FileAnalysisCache analysisCache = new FileAnalysisCache(newCacheFile); when(cl.getURLs()).thenReturn(new URL[] {}); - analysisCache.checkValidity(rs, cl); + analysisCache.checkValidity(rs, cl, Collections.emptySet()); assertTrue(analysisCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date after non-existing auxclasspath entry removed"); } @@ -263,7 +260,7 @@ class FileAnalysisCacheTest { final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); when(cl.getURLs()).thenReturn(new URL[] { Files.createTempFile(tempFolder, null, null).toFile().toURI().toURL(), }); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date after auxclasspath changed when no rule cares"); } @@ -286,7 +283,7 @@ class FileAnalysisCacheTest { final net.sourceforge.pmd.Rule r = mock(net.sourceforge.pmd.Rule.class); when(r.getLanguage()).thenReturn(mock(Language.class)); when(rs.getAllRules()).thenReturn(Collections.singleton(r)); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is up to date after auxclasspath changed"); } @@ -309,7 +306,7 @@ class FileAnalysisCacheTest { Files.write(classpathFile.toPath(), "some text".getBytes()); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes cache is up to date when a auxclasspath file changed"); } @@ -325,7 +322,7 @@ class FileAnalysisCacheTest { final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); try { - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); } catch (final Exception e) { fail("Validity check failed when classpath includes non-existing directories"); } @@ -347,7 +344,7 @@ class FileAnalysisCacheTest { System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + classpathFile.getAbsolutePath()); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes cache is up to date when the classpath changed"); }); @@ -371,7 +368,7 @@ class FileAnalysisCacheTest { Files.write(classpathFile.toPath(), "some other text".getBytes()); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes cache is up to date when a classpath file changed"); }); @@ -415,7 +412,7 @@ class FileAnalysisCacheTest { createZipFile(classpathJar1.getName(), 2); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl); + reloadedCache.checkValidity(rs, cl, Collections.emptySet()); assertFalse(reloadedCache.isUpToDate(sourceFile), "Cache believes cache is up to date when the classpath changed"); }); @@ -433,7 +430,7 @@ class FileAnalysisCacheTest { setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class), sourceFile); final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class)); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); assertTrue(cache.isUpToDate(sourceFile), "Cache believes a known, unchanged file is not up to date"); } @@ -459,7 +456,7 @@ class FileAnalysisCacheTest { final TextDocument... files) throws IOException { // Setup a cache file with an entry for an empty Source.java with no violations final FileAnalysisCache cache = new FileAnalysisCache(cacheFile); - cache.checkValidity(ruleSets, classLoader); + cache.checkValidity(ruleSets, classLoader, Collections.emptySet()); for (final TextDocument f : files) { cache.isUpToDate(f); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index 85aa0b5dbd..739dd09071 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -5,9 +5,9 @@ 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 static org.hamcrest.Matchers.is; import java.nio.file.Paths; import java.util.List; @@ -44,8 +44,8 @@ class PMDFilelistTest { List applicableFiles = collector.getCollectedFiles(); assertThat(applicableFiles, hasSize(2)); - assertThat(applicableFiles.get(0).getPathId(), endsWith("anotherfile.dummy")); - assertThat(applicableFiles.get(1).getPathId(), endsWith("somefile.dummy")); + assertThat(applicableFiles.get(0).getPathId().getFileName(), equalTo("anotherfile.dummy")); + assertThat(applicableFiles.get(1).getPathId().getFileName(), equalTo("somefile.dummy")); } @Test @@ -57,8 +57,12 @@ class PMDFilelistTest { List applicableFiles = collector.getCollectedFiles(); // 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")); + assertFilenameIs(applicableFiles.get(0), "anotherfile.dummy"); + assertFilenameIs(applicableFiles.get(1), "somefile.dummy"); + } + + private static void assertFilenameIs(TextFile textFile, String suffix) { + assertThat(textFile.getPathId().getFileName(), is(suffix)); } @Test @@ -72,8 +76,8 @@ class PMDFilelistTest { List applicableFiles = collector.getCollectedFiles(); assertThat(applicableFiles, hasSize(2)); - assertThat(applicableFiles.get(0).getPathId(), endsWith("somefile2.dummy")); - assertThat(applicableFiles.get(1).getPathId(), endsWith("somefile4.dummy")); + assertFilenameIs(applicableFiles.get(0), "somefile2.dummy"); + assertFilenameIs(applicableFiles.get(1), "somefile4.dummy"); } @Test @@ -144,10 +148,10 @@ class PMDFilelistTest { List applicableFiles = collector.getCollectedFiles(); assertThat(applicableFiles, hasSize(4)); - assertThat(applicableFiles.get(0).getPathId(), endsWith("anotherfile.dummy")); - assertThat(applicableFiles.get(1).getPathId(), endsWith("somefile.dummy")); - assertThat(applicableFiles.get(2).getPathId(), endsWith("somefile2.dummy")); - assertThat(applicableFiles.get(3).getPathId(), endsWith("somefile4.dummy")); + assertFilenameIs(applicableFiles.get(0), "anotherfile.dummy"); + assertFilenameIs(applicableFiles.get(1), "somefile.dummy"); + assertFilenameIs(applicableFiles.get(2), "somefile2.dummy"); + assertFilenameIs(applicableFiles.get(3), "somefile4.dummy"); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java index 114fd8ccc4..1800f44ad3 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.ast.GenericToken; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.document.TextRegion; @@ -61,7 +61,7 @@ class BaseTokenFilterTest { @Override public FileLocation getReportLocation() { - return FileLocation.range(TextFile.UNKNOWN_FILENAME, TextRange2d.range2d(1, 1, 1, 1)); + return FileLocation.range(PathId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 1)); } @Override diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java index a34af527c5..95303cd86b 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java @@ -16,8 +16,8 @@ import net.sourceforge.pmd.lang.LanguageProcessorRegistry; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.impl.AbstractNode; import net.sourceforge.pmd.lang.ast.impl.GenericNode; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; -import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextRegion; import net.sourceforge.pmd.lang.rule.xpath.Attribute; @@ -133,7 +133,7 @@ public class DummyNode extends AbstractNode { public DummyRootNode() { TextDocument document = TextDocument.readOnlyString( "dummy text", - TextFile.UNKNOWN_FILENAME, + PathId.UNKNOWN, DummyLanguageModule.getInstance().getDefaultVersion() ); astInfo = new AstInfo<>( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java index e3d90fb99b..8ef339c813 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java @@ -15,9 +15,11 @@ import org.junit.jupiter.api.Test; */ class FileLocationTest { + public static final PathId FNAME = PathId.fromPathLikeString("fname"); + @Test void testSimple() { - FileLocation loc = FileLocation.range("fname", TextRange2d.range2d(1, 1, 1, 2)); + FileLocation loc = FileLocation.range(FNAME, TextRange2d.range2d(1, 1, 1, 2)); assertEquals("fname", loc.getFileName()); assertEquals(1, loc.getStartLine()); assertEquals(1, loc.getStartColumn()); @@ -28,13 +30,13 @@ class FileLocationTest { @Test void testToRange() { TextRange2d range2d = TextRange2d.range2d(1, 1, 1, 2); - FileLocation loc = FileLocation.range("fname", range2d); + FileLocation loc = FileLocation.range(FNAME, range2d); assertEquals(range2d, loc.toRange2d()); } @Test void testToString() { - FileLocation loc = FileLocation.range("fname", TextRange2d.range2d(1, 1, 1, 2)); + FileLocation loc = FileLocation.range(FNAME, TextRange2d.range2d(1, 1, 1, 2)); assertEquals( "line 1, column 1", diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java index 69aa3cd196..09ef7aeaf2 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java @@ -11,7 +11,7 @@ import net.sourceforge.pmd.lang.LanguageVersion; */ public class SimpleTestTextFile extends StringTextFile { - public SimpleTestTextFile(String content, String pathId, LanguageVersion languageVersion) { + public SimpleTestTextFile(String content, PathId pathId, LanguageVersion languageVersion) { super(content, pathId, languageVersion); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java index ed0721292d..03be860717 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java @@ -49,7 +49,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content").toAbsolutePath(); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { - try (TextFile stringTf = TextFile.forCharSeq("some content", file.toUri().toString(), dummyVersion())) { + try (TextFile stringTf = TextFile.forCharSeq("some content", PathId.fromPath(file), dummyVersion())) { assertEquals(tf.getPathId(), stringTf.getPathId()); // despite same path id, they are different implementations @@ -57,7 +57,7 @@ class TextFilesTest { assertNotEquals(stringTf, tf); // identical, but string text files use identity - assertNotEquals(stringTf, TextFile.forCharSeq("some content", file.toString(), dummyVersion())); + assertNotEquals(stringTf, TextFile.forCharSeq("some content", PathId.fromPath(file), dummyVersion())); // those are identical so are equals assertNotSame(tf, tfPrime); @@ -144,7 +144,6 @@ class TextFilesTest { void testNioFileExplicitReadOnly() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion()) - .withDisplayName(file.toString()) .asReadOnly().build()) { assertTrue(tf.isReadOnly(), "readonly"); @@ -167,10 +166,8 @@ class TextFilesTest { void testNioFileBuilder() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion()) - .withDisplayName("aname") .build()) { assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId()); - assertEquals("aname", tf.getDisplayName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } @@ -187,7 +184,7 @@ class TextFilesTest { @Test void testReaderFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); - try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), "filename", dummyVersion())) { + try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), PathId.UNKNOWN, dummyVersion())) { assertEquals("filename", tf.getPathId()); assertEquals("filename", tf.getDisplayName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); @@ -198,7 +195,7 @@ class TextFilesTest { @Test void testReaderFileIsReadOnly() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); - try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), "filename", dummyVersion())) { + try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), PathId.UNKNOWN, dummyVersion())) { assertTrue(tf.isReadOnly(), "readonly"); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( TextFileContent.fromCharSeq("new content") @@ -208,7 +205,7 @@ class TextFilesTest { @Test void testStringFileEscape() throws IOException { - try (TextFile tf = TextFile.forCharSeq("cont\r\nents", "filename", dummyVersion())) { + try (TextFile tf = TextFile.forCharSeq("cont\r\nents", PathId.UNKNOWN, dummyVersion())) { assertEquals("filename", tf.getPathId()); assertEquals("filename", tf.getDisplayName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); @@ -221,7 +218,7 @@ class TextFilesTest { @Test void testStringFileCanBeReadMultipleTimes() throws IOException { - try (TextFile tf = TextFile.forCharSeq("contents", "filename", dummyVersion())) { + try (TextFile tf = TextFile.forCharSeq("contents", PathId.UNKNOWN, dummyVersion())) { assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); @@ -230,7 +227,7 @@ class TextFilesTest { @Test void testStringFileIsReadonly() throws IOException { - try (TextFile tf = TextFile.forCharSeq("contents", "filename", dummyVersion())) { + try (TextFile tf = TextFile.forCharSeq("contents", PathId.UNKNOWN, dummyVersion())) { assertTrue(tf.isReadOnly(), "readonly"); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( TextFileContent.fromCharSeq("new content") diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java index db7379a963..ccbb20cdb2 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java @@ -19,7 +19,6 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.lang.ast.DummyNode; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.DummyNodeWithDeprecatedAttribute; -import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextRegion; import net.sourceforge.pmd.lang.rule.xpath.XPathVersion; @@ -145,7 +144,7 @@ class XPathRuleTest { DummyRootNode newNode() { - DummyRootNode root = newRoot(TextFile.UNKNOWN_FILENAME); + DummyRootNode root = newRoot("file"); DummyNode dummy = new DummyNodeWithDeprecatedAttribute(); root.addChild(dummy, 0); dummy.setRegion(TextRegion.fromOffsetLength(0, 1)); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index 9fcebd99ed..bf3a058c58 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -12,6 +12,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.Collections; + import org.checkerframework.checker.nullness.qual.NonNull; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -26,6 +28,7 @@ import net.sourceforge.pmd.cache.AnalysisCache; import net.sourceforge.pmd.cache.NoopAnalysisCache; import net.sourceforge.pmd.lang.ast.FileAnalysisException; import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener.ViolationCounterListener; @@ -76,7 +79,7 @@ class GlobalListenerTest { MyFooRule rule = new MyFooRule(); runPmd(config, GlobalAnalysisListener.noop(), rule); - verify(mockCache).checkValidity(any(), any()); + verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); verify(mockCache, times(1)).persist(); verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any()); } @@ -92,7 +95,7 @@ class GlobalListenerTest { runPmd(config, GlobalAnalysisListener.noop(), rule); // cache methods are called regardless - verify(mockCache).checkValidity(any(), any()); + verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); verify(mockCache, times(1)).persist(); verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any()); } @@ -114,7 +117,7 @@ class GlobalListenerTest { assertEquals("fname1.dummy", exception.getFileName()); // cache methods are called regardless - verify(mockCache).checkValidity(any(), any()); + verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); verify(mockCache, times(1)).persist(); verify(mockCache, times(1)).isUpToDate(any()); } @@ -131,9 +134,9 @@ class GlobalListenerTest { private void runPmd(PMDConfiguration config, GlobalAnalysisListener listener, Rule rule) { try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(RuleSet.forSingleRule(rule)); - pmd.files().addSourceFile("fname1.dummy", "abc"); - pmd.files().addSourceFile("fname2.dummy", "abcd"); - pmd.files().addSourceFile("fname21.dummy", "abcd"); + pmd.files().addSourceFile(PathId.fromPathLikeString("fname1.dummy"), "abc"); + pmd.files().addSourceFile(PathId.fromPathLikeString("fname2.dummy"), "abcd"); + pmd.files().addSourceFile(PathId.fromPathLikeString("fname21.dummy"), "abcd"); pmd.addListener(listener); pmd.performAnalysis(); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java index 0bfc95124c..0177874c76 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java @@ -19,6 +19,7 @@ import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.reporting.FileAnalysisListener; @@ -33,8 +34,8 @@ class MultiThreadProcessorTest { configuration.setThreads(2); PmdAnalysis pmd = PmdAnalysis.create(configuration); LanguageVersion lv = DummyLanguageModule.getInstance().getDefaultVersion(); - pmd.files().addFile(TextFile.forCharSeq("abc", "file1-violation.dummy", lv)); - pmd.files().addFile(TextFile.forCharSeq("DEF", "file2-foo.dummy", lv)); + pmd.files().addFile(TextFile.forCharSeq("abc", PathId.fromPathLikeString("file1-violation.dummy"), lv)); + pmd.files().addFile(TextFile.forCharSeq("DEF", PathId.fromPathLikeString("file2-foo.dummy"), lv)); reportListener = new SimpleReportListener(); GlobalAnalysisListener listener = GlobalAnalysisListener.tee(listOf( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java index e61b2be631..e0c93c2104 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java @@ -38,6 +38,7 @@ import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.Parser; import net.sourceforge.pmd.lang.ast.RootNode; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.util.ContextedAssertionError; @@ -74,7 +75,7 @@ class PmdRunnableTest { configuration.setForceLanguageVersion(lv); configuration.setIgnoreIncrementalAnalysis(true); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { - pmd.files().addSourceFile("test.dummy", "foo"); + pmd.files().addSourceFile(PathId.fromPathLikeString("file.dummy"), "foo"); pmd.addRuleSet(RuleSet.forSingleRule(rule)); return pmd.performAnalysisAndCollectReport(); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java index 286fa35370..f4abe64e49 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java @@ -33,6 +33,7 @@ import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -101,7 +102,7 @@ abstract class AbstractRendererTest { protected FileLocation createLocation(int beginLine, int beginColumn, int endLine, int endColumn) { TextRange2d range2d = TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn); - return FileLocation.range(getSourceCodeFilename(), range2d); + return FileLocation.range(PathId.fromPathLikeString(getSourceCodeFilename()), range2d); } protected RuleViolation newRuleViolation(int beginLine, int beginColumn, int endLine, int endColumn, Rule rule) { @@ -175,14 +176,14 @@ abstract class AbstractRendererTest { @Test void testError() throws Exception { - Report.ProcessingError err = new Report.ProcessingError(new RuntimeException("Error"), "file"); + Report.ProcessingError err = new Report.ProcessingError(new RuntimeException("Error"), PathId.fromPathLikeString("file")); String actual = render(it -> it.onError(err)); assertEquals(filter(getExpectedError(err)), filter(actual)); } @Test void testErrorWithoutMessage() throws Exception { - Report.ProcessingError err = new Report.ProcessingError(new NullPointerException(), "file"); + Report.ProcessingError err = new Report.ProcessingError(new NullPointerException(), PathId.fromPathLikeString("file")); String actual = render(it -> it.onError(err)); assertEquals(filter(getExpectedErrorWithoutMessage(err)), filter(actual)); } @@ -207,7 +208,7 @@ abstract class AbstractRendererTest { return renderGlobal(renderer, globalListener -> { LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion(); - TextFile dummyFile = TextFile.forCharSeq("dummyText", "file", version); + TextFile dummyFile = TextFile.forCharSeq("dummyText", PathId.fromPathLikeString("fname1.dummy"), version); try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) { listenerEffects.accept(fal); } catch (Exception e) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java index 1407613d4d..21f4b5f1cb 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java @@ -31,6 +31,7 @@ import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -91,7 +92,8 @@ class XMLRendererTest extends AbstractRendererTest { } private RuleViolation createRuleViolation(String description) { - FileLocation loc = FileLocation.range(getSourceCodeFilename(), TextRange2d.range2d(1, 1, 1, 1)); + FileLocation loc = FileLocation.range(PathId.fromPathLikeString(getSourceCodeFilename()), + TextRange2d.range2d(1, 1, 1, 1)); return new ParametricRuleViolation(new FooRule(), loc, description); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java index 150f74ce45..36ccc51337 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java @@ -12,6 +12,7 @@ import net.sourceforge.pmd.FooRule; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -57,7 +58,7 @@ class XSLTRendererTest extends AbstractRendererTest { @Test void testDefaultStylesheet() throws Exception { XSLTRenderer renderer = new XSLTRenderer(); - FileLocation loc = FileLocation.range("file", TextRange2d.range2d(1, 1, 1, 2)); + FileLocation loc = FileLocation.range(PathId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 2)); RuleViolation rv = new ParametricRuleViolation(new FooRule(), loc, "violation message"); String result = renderReport(renderer, it -> it.onRuleViolation(rv)); assertTrue(result.contains("violation message")); diff --git a/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java b/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java index 3546db9e6c..f9ce473958 100644 --- a/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java +++ b/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java @@ -13,14 +13,14 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream; import net.sourceforge.pmd.lang.document.CpdCompat; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; -import net.sourceforge.pmd.lang.document.TextFile; class CppCharStreamTest { @NonNull public CharStream charStreamFor(String source) throws IOException { - TextDocument textDoc = TextDocument.readOnlyString(source, TextFile.UNKNOWN_FILENAME, CpdCompat.dummyVersion()); + TextDocument textDoc = TextDocument.readOnlyString(source, PathId.UNKNOWN, CpdCompat.dummyVersion()); return CharStream.create(textDoc, new CPPTokenizer().tokenBehavior()); } diff --git a/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java b/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java index e7fad1cbe9..84cf1b80b7 100644 --- a/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java +++ b/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java @@ -15,6 +15,7 @@ import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.LanguageProcessorRegistry; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.html.HtmlLanguageModule; @@ -28,7 +29,7 @@ public class HtmlTokenizer implements Tokenizer { try (LanguageProcessor processor = html.createProcessor(html.newPropertyBundle()); TextFile tf = TextFile.forCharSeq( sourceCode.getCodeBuffer(), - sourceCode.getFileName(), + PathId.fromPathLikeString(sourceCode.getFileName()), html.getDefaultVersion() ); TextDocument textDoc = TextDocument.create(tf)) { diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt index db9367730d..d350a49c1a 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt @@ -10,8 +10,8 @@ import net.sourceforge.pmd.lang.ast.Node import net.sourceforge.pmd.lang.ast.Parser.ParserTask import net.sourceforge.pmd.lang.ast.RootNode import net.sourceforge.pmd.lang.ast.SemanticErrorReporter +import net.sourceforge.pmd.lang.document.PathId import net.sourceforge.pmd.lang.document.TextDocument -import net.sourceforge.pmd.lang.document.TextFile import net.sourceforge.pmd.lang.rule.XPathRule import net.sourceforge.pmd.lang.rule.xpath.XPathVersion import net.sourceforge.pmd.reporting.GlobalAnalysisListener @@ -118,7 +118,7 @@ abstract class BaseParsingHelper, T : RootNode fun parse( sourceCode: String, version: String? = null, - fileName: String = TextFile.UNKNOWN_FILENAME + fileName: String = PathId.UNKNOWN ): T { val lversion = if (version == null) defaultVersion else getVersion(version) val params = params.copy(defaultVerString = lversion.version) diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java index 5c3041c7dc..cfc3865be9 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java @@ -33,6 +33,7 @@ import net.sourceforge.pmd.RuleSetLoadException; import net.sourceforge.pmd.RuleSetLoader; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.LanguageVersion; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.renderers.TextRenderer; @@ -229,7 +230,7 @@ public abstract class RuleTst { configuration.prependAuxClasspath("."); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { - pmd.files().addFile(TextFile.forCharSeq(code, "testFile", languageVersion)); + pmd.files().addFile(TextFile.forCharSeq(code, PathId.fromPathLikeString("file"), languageVersion)); pmd.addRuleSet(RuleSet.forSingleRule(rule)); pmd.addListener(GlobalAnalysisListener.exceptionThrower()); return pmd.performAnalysisAndCollectReport(); From 82df565ccc35e6268f71e949e0bdcb4dfda5d7e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 18:35:10 +0100 Subject: [PATCH 02/14] Fix displayname logic in FileCollector --- .../pmd/lang/document/FileCollector.java | 162 ++++++++---------- .../sourceforge/pmd/lang/document/PathId.java | 18 ++ .../pmd/lang/document/TextFile.java | 1 + .../pmd/renderers/FileNameRenderer.java | 24 +++ .../sourceforge/pmd/cli/PMDFilelistTest.java | 63 +++---- .../pmd/lang/document/FileCollectorTest.java | 9 +- 6 files changed, 154 insertions(+), 123 deletions(-) create mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index 97e6e005ea..b780894847 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -22,6 +22,7 @@ import java.nio.file.ProviderNotFoundException; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; @@ -32,6 +33,7 @@ import java.util.List; import java.util.Objects; import java.util.Set; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,6 +44,7 @@ import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; +import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.util.AssertionUtil; import net.sourceforge.pmd.util.log.MessageReporter; @@ -62,8 +65,6 @@ public final class FileCollector implements AutoCloseable { private final LanguageVersionDiscoverer discoverer; private final MessageReporter reporter; private final String outerFsDisplayName; - @Deprecated - private final List legacyRelativizeRoots = new ArrayList<>(); private final List relativizeRootPaths = new ArrayList<>(); private boolean closed; @@ -154,8 +155,8 @@ public final class FileCollector implements AutoCloseable { } LanguageVersion languageVersion = discoverLanguage(file.toString()); return languageVersion != null - && addFileImpl(TextFile.builderForPath(file, charset, languageVersion) - .build()); + && addFileImpl(TextFile.builderForPath(file, charset, languageVersion) + .build()); } /** @@ -177,7 +178,7 @@ public final class FileCollector implements AutoCloseable { LanguageVersion lv = discoverer.getDefaultLanguageVersion(language); Objects.requireNonNull(lv); return addFileImpl(TextFile.builderForPath(file, charset, lv) - .build()); + .build()); } /** @@ -204,8 +205,8 @@ public final class FileCollector implements AutoCloseable { LanguageVersion version = discoverLanguage(pathId.getFileName()); return version != null - && addFileImpl(TextFile.builderForCharSeq(sourceContents, pathId, version) - .build()); + && addFileImpl(TextFile.builderForCharSeq(sourceContents, pathId, version) + .build()); } private boolean addFileImpl(TextFile textFile) { @@ -255,74 +256,54 @@ public final class FileCollector implements AutoCloseable { return true; } - private String getDisplayName(Path file) { - String localDisplayName = getLocalDisplayName(file); - if (outerFsDisplayName != null) { - return outerFsDisplayName + "!" + localDisplayName; - } - return localDisplayName; - } - - private String getLocalDisplayName(Path file) { - if (!relativizeRootPaths.isEmpty()) { - // takes precedence over legacy behavior - return getDisplayName(file, relativizeRootPaths); - } - return getDisplayNameLegacy(file, legacyRelativizeRoots); - } - - /** - * Return the textfile's display name. - * - *

package private for test only

- */ - static String getDisplayNameLegacy(Path file, List relativizeRoots) { - String fileName = file.toString(); - for (String root : relativizeRoots) { - if (file.startsWith(root)) { - if (fileName.startsWith(File.separator, root.length())) { - // remove following '/' - return fileName.substring(root.length() + 1); - } - return fileName.substring(root.length()); - } - } - return fileName; - } - /** * Return the textfile's display name. Takes the shortest path we * can construct from the relativize roots. * *

package private for test only

*/ - static String getDisplayName(Path file, List relativizeRoots) { - Path best = file; + static String getDisplayName(PathId file, List relativizeRoots) { + String best = file.toAbsolutePath(); for (Path root : relativizeRoots) { - Path candidate; if (isFileSystemRoot(root)) { // Absolutize the path. Since the relativize roots are // sorted by ascending length, this should be the first in the list // (so another root can override it). best = file.toAbsolutePath(); continue; - } else { - if (!root.getFileSystem().equals(file.getFileSystem())) { - // maybe the file is in a zip - root = file.getFileSystem().getPath(root.toString()); // SUPPRESS CHECKSTYLE ModifiedControlVariable - } - if (root.isAbsolute() != file.isAbsolute()) { // this causes IllegalArgumentException - root = root.toAbsolutePath(); // SUPPRESS CHECKSTYLE ModifiedControlVariable - file = file.toAbsolutePath(); - } - candidate = root.relativize(file); } - // take the shortest path. - if (candidate.getNameCount() < best.getNameCount()) { - best = candidate; + + String relative = relativizePath(root.toAbsolutePath().toString(), file.toAbsolutePath()); + if (countSegments(relative) < countSegments(best)) { + best = relative; } } - return best.toString(); + return best; + } + + private static int countSegments(String best) { + return StringUtils.countMatches(best, File.separatorChar); + } + + private static String relativizePath(String base, String other) { + String[] baseSegments = base.split("[/\\\\]"); + String[] otherSegments = other.split("[/\\\\]"); + int prefixLength = 0; + int maxi = Math.min(baseSegments.length, otherSegments.length); + while (prefixLength < maxi && baseSegments[prefixLength].equals(otherSegments[prefixLength])) { + prefixLength++; + } + + if (prefixLength == 0) { + return other; + } + + List relative = new ArrayList<>(); + for (int i = prefixLength; i < baseSegments.length; i++) { + relative.add(".."); + } + relative.addAll(Arrays.asList(otherSegments).subList(prefixLength, otherSegments.length)); + return String.join(File.separator, relative); } /** Return whether the path is the root path (/). */ @@ -448,7 +429,7 @@ public final class FileCollector implements AutoCloseable { /** A collector that prefixes the display name of the files it will contain with the path of the zip. */ @Experimental private FileCollector newZipCollector(Path zipFilePath) { - String zipDisplayName = getDisplayName(zipFilePath); + String zipDisplayName = getFileNameRenderer().getDisplayName(PathId.fromPath(zipFilePath)); return new FileCollector(discoverer, reporter, zipDisplayName); } @@ -464,24 +445,6 @@ public final class FileCollector implements AutoCloseable { this.charset = Objects.requireNonNull(charset); } - /** - * Add a prefix that is used to relativize file paths as their display name. - * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, - * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} - * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a - * display name of {@code main/java/org/foo.java}. - * - *

This only matters for files added from a {@link Path} object. - * - * @param prefix Prefix to relativize (if a directory, include a trailing slash) - * - * @deprecated Use {@link #relativizeWith(Path)} - */ - @Deprecated - public void relativizeWith(String prefix) { - this.legacyRelativizeRoots.add(Objects.requireNonNull(prefix)); - } - /** * Add a prefix that is used to relativize file paths as their display name. * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, @@ -495,15 +458,42 @@ public final class FileCollector implements AutoCloseable { */ public void relativizeWith(Path path) { this.relativizeRootPaths.add(Objects.requireNonNull(path)); - Collections.sort(relativizeRootPaths, new Comparator() { - @Override - public int compare(Path o1, Path o2) { - int lengthCmp = Integer.compare(o1.getNameCount(), o2.getNameCount()); - return lengthCmp == 0 ? o1.compareTo(o2) : lengthCmp; - } - }); + this.relativizeRootPaths.sort(Comparator.comparingInt(Path::getNameCount).thenComparing(o -> o)); } + // todo doc + String getDisplayName(PathId pathId) { + return getDisplayName(pathId, this.relativizeRootPaths); + } + + String getDisplayName(TextFile file) { + return getDisplayName(file.getPathId()); + } + + // todo doc + public FileNameRenderer getFileNameRenderer() { + return new FileNameRenderer() { + private final List relativizeRootPaths = new ArrayList<>(FileCollector.this.relativizeRootPaths); + + @Override + public String getDisplayName(PathId pathId) { + String localDisplayName = getLocalDisplayName(pathId); + if (outerFsDisplayName != null) { + return outerFsDisplayName + "!" + localDisplayName; + } + return localDisplayName; + } + + private String getLocalDisplayName(PathId file) { + if (!relativizeRootPaths.isEmpty()) { + return FileCollector.getDisplayName(file, relativizeRootPaths); + } + return file.toString(); + } + }; + } + + // filtering /** @@ -511,7 +501,7 @@ public final class FileCollector implements AutoCloseable { */ public void exclude(FileCollector excludeCollector) { Set toExclude = new HashSet<>(excludeCollector.allFilesToProcess); - for (Iterator iterator = allFilesToProcess.iterator(); iterator.hasNext();) { + for (Iterator iterator = allFilesToProcess.iterator(); iterator.hasNext(); ) { TextFile file = iterator.next(); if (toExclude.contains(file)) { LOG.trace("Excluding file {}", file.getPathId()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java index 86ef8d7590..6cd7fe64e3 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java @@ -5,6 +5,7 @@ package net.sourceforge.pmd.lang.document; import java.nio.file.Path; +import java.nio.file.Paths; /** * A virtual path for a {@link TextFile}. @@ -24,6 +25,8 @@ public interface PathId extends Comparable { String getFileName(); String getNiceFileName(); + String toAbsolutePath(); + @Override boolean equals(Object o); @@ -35,6 +38,11 @@ public interface PathId extends Comparable { } PathId STDIN = new PathId() { + @Override + public String toAbsolutePath() { + return "stdin"; + } + @Override public String toUriString() { return "stdin"; @@ -58,6 +66,11 @@ public interface PathId extends Comparable { } String fname = segments[segments.length - 1]; return new PathId() { + @Override + public String toAbsolutePath() { + return Paths.get(str).toAbsolutePath().toString(); + } + @Override public String toUriString() { return str; @@ -83,6 +96,11 @@ public interface PathId extends Comparable { static PathId fromPath(Path path) { return new PathId() { + @Override + public String toAbsolutePath() { + return path.normalize().toAbsolutePath().toString(); + } + @Override public String toUriString() { return path.normalize().toUri().toString(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index 899b15bcc2..ee323c84c6 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -79,6 +79,7 @@ public interface TextFile extends Closeable { * to a directory or so, it may also not be normalized. Use * {@link #getPathId()} when you want an identifier. */ + @Deprecated default @NonNull String getDisplayName() { return getPathId().getNiceFileName(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java new file mode 100644 index 0000000000..21100712a1 --- /dev/null +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java @@ -0,0 +1,24 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.renderers; + +import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.TextFile; + +/** + * Renders a {@link PathId} into a display name. + * + * @author Clément Fournier + */ +public interface FileNameRenderer { + + + String getDisplayName(PathId pathId); + + default String getDisplayName(TextFile textFile) { + return getDisplayName(textFile.getPathId()); + } + +} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index 739dd09071..bef98cd221 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -4,11 +4,13 @@ package net.sourceforge.pmd.cli; +import static net.sourceforge.pmd.internal.util.FileCollectionUtil.collectFileList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @@ -26,21 +28,18 @@ import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.util.log.MessageReporter; class PMDFilelistTest { - private static final String RESOURCE_PREFIX = "src/test/resources/net/sourceforge/pmd/cli/"; + + private static final Path RESOURCES = Paths.get("src/test/resources/net/sourceforge/pmd/cli/"); private @NonNull FileCollector newCollector() { return FileCollector.newCollector(new LanguageVersionDiscoverer(LanguageRegistry.PMD), MessageReporter.quiet()); } - private static void collectFileList(FileCollector collector, String x) { - FileCollectionUtil.collectFileList(collector, Paths.get(x)); - } - @Test void testGetApplicableFiles() { FileCollector collector = newCollector(); - collectFileList(collector, RESOURCE_PREFIX + "filelist.txt"); + collectFileList(collector, RESOURCES.resolve("filelist.txt")); List applicableFiles = collector.getCollectedFiles(); assertThat(applicableFiles, hasSize(2)); @@ -52,7 +51,7 @@ class PMDFilelistTest { void testGetApplicableFilesMultipleLines() { FileCollector collector = newCollector(); - collectFileList(collector, RESOURCE_PREFIX + "filelist2.txt"); + collectFileList(collector, RESOURCES.resolve("filelist2.txt")); List applicableFiles = collector.getCollectedFiles(); // note: the file has 3 entries, but one is duplicated, resulting in 2 individual files @@ -70,8 +69,8 @@ class PMDFilelistTest { FileCollector collector = newCollector(); PMDConfiguration configuration = new PMDConfiguration(); - configuration.setInputFilePath(RESOURCE_PREFIX + "filelist3.txt"); - configuration.setIgnoreFilePath(RESOURCE_PREFIX + "ignorelist.txt"); + configuration.setInputFilePath(RESOURCES.resolve("filelist3.txt")); + configuration.setIgnoreFilePath(RESOURCES.resolve("ignorelist.txt")); FileCollectionUtil.collectFiles(configuration, collector); List applicableFiles = collector.getCollectedFiles(); @@ -83,56 +82,60 @@ class PMDFilelistTest { @Test void testRelativizeWith() { PMDConfiguration conf = new PMDConfiguration(); - conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist2.txt")); + conf.setInputFilePath(RESOURCES.resolve("filelist2.txt")); conf.addRelativizeRoot(Paths.get("src/test/resources")); try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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"))); + assertHasName(files.get(0), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/anotherfile.dummy"), pmd.files()); + assertHasName(files.get(1), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/somefile.dummy"), pmd.files()); } } + private static void assertHasName(TextFile textFile, String expected, FileCollector files) { + assertThat(files.getFileNameRenderer().getDisplayName(textFile), equalTo(expected)); + } + @Test void testRelativizeWithOtherDir() { PMDConfiguration conf = new PMDConfiguration(); - conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist4.txt")); - conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX + "src")); + conf.setInputFilePath(RESOURCES.resolve("filelist4.txt")); + conf.addRelativizeRoot(RESOURCES.resolve("src")); try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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")); + assertHasName(files.get(0), ".." + IOUtil.normalizePath("/otherSrc/somefile.dummy"), pmd.files()); + assertHasName(files.get(1), "anotherfile.dummy", pmd.files()); + assertHasName(files.get(2), "somefile.dummy", pmd.files()); } } @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")); + conf.setInputFilePath(RESOURCES.resolve("filelist4.txt")); + conf.addRelativizeRoot(RESOURCES.resolve("src")); + conf.addRelativizeRoot(RESOURCES.resolve("otherSrc")); try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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")); + assertHasName(files.get(0), "somefile.dummy", pmd.files()); + assertHasName(files.get(1), "anotherfile.dummy", pmd.files()); + assertHasName(files.get(2), "somefile.dummy", pmd.files()); } } @Test void testUseAbsolutePaths() { PMDConfiguration conf = new PMDConfiguration(); - conf.setInputFilePath(Paths.get(RESOURCE_PREFIX + "filelist4.txt")); - conf.addRelativizeRoot(Paths.get(RESOURCE_PREFIX).toAbsolutePath().getRoot()); + conf.setInputFilePath(RESOURCES.resolve("filelist4.txt")); + conf.addRelativizeRoot(RESOURCES.toAbsolutePath().getRoot()); try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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())); + assertHasName(files.get(0), RESOURCES.resolve("otherSrc/somefile.dummy").toAbsolutePath().toString(), pmd.files()); + assertHasName(files.get(1), RESOURCES.resolve("src/anotherfile.dummy").toAbsolutePath().toString(), pmd.files()); + assertHasName(files.get(2), RESOURCES.resolve("src/somefile.dummy").toAbsolutePath().toString(), pmd.files()); } } @@ -140,8 +143,8 @@ class PMDFilelistTest { @Test void testGetApplicableFilesWithDirAndIgnores() { PMDConfiguration configuration = new PMDConfiguration(); - configuration.setInputPaths(RESOURCE_PREFIX + "src"); - configuration.setIgnoreFilePath(RESOURCE_PREFIX + "ignorelist.txt"); + configuration.addInputPath(RESOURCES.resolve("src")); + configuration.setIgnoreFilePath(RESOURCES.resolve("ignorelist.txt")); FileCollector collector = newCollector(); FileCollectionUtil.collectFiles(configuration, collector); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index f9879c92b3..ac44ce0d78 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -94,15 +94,10 @@ class FileCollectorTest { assertCollected(collector, listOf("src/foo.dummy", "src/x/bar.dummy")); } - @Test - void testRelativizeLegacy() { - String displayName = FileCollector.getDisplayNameLegacy(Paths.get("a", "b", "c"), listOf(Paths.get("a").toString())); - assertEquals(displayName, Paths.get("b", "c").toString()); - } @Test void testRelativize() { - String displayName = FileCollector.getDisplayName(Paths.get("a", "b", "c"), listOf(Paths.get("a"))); + String displayName = FileCollector.getDisplayName(PathId.fromPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); assertEquals(displayName, Paths.get("b", "c").toString()); } @@ -139,7 +134,7 @@ class FileCollectorTest { private FileCollector newCollector(LanguageVersion forcedVersion) { LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD, forcedVersion); FileCollector collector = FileCollector.newCollector(discoverer, new TestMessageReporter()); - collector.relativizeWith(tempFolder.toAbsolutePath().toString()); + collector.relativizeWith(tempFolder.toAbsolutePath()); return collector; } } From 28f6c01d515f096c4c1e45868739f65a3d22935f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 19:14:01 +0100 Subject: [PATCH 03/14] Fix tests in pmd-core --- .../java/net/sourceforge/pmd/RuleContext.java | 2 +- .../java/net/sourceforge/pmd/RuleSet.java | 7 +- .../java/net/sourceforge/pmd/RuleSets.java | 10 +-- .../net/sourceforge/pmd/RuleViolation.java | 10 ++- .../net/sourceforge/pmd/cpd/TokenEntry.java | 2 +- .../pmd/cpd/internal/AntlrTokenizer.java | 2 +- .../net/sourceforge/pmd/lang/ast/Parser.java | 2 +- .../impl/javacc/MalformedSourceException.java | 2 +- .../pmd/lang/document/FileCollector.java | 29 +++---- .../pmd/lang/document/FileLocation.java | 9 +-- .../pmd/lang/document/NioTextFile.java | 4 +- .../sourceforge/pmd/lang/document/PathId.java | 78 +++++++++++++++++-- .../pmd/lang/document/TextDocument.java | 2 +- .../pmd/lang/document/TextFile.java | 2 +- .../pmd/lang/document/TextFileBuilder.java | 27 ++++++- .../sourceforge/pmd/DummyParsingHelper.java | 1 + .../pmd/cache/FileAnalysisCacheTest.java | 10 ++- .../sourceforge/pmd/cli/PMDFilelistTest.java | 2 +- .../net/sourceforge/pmd/cli/ZipFileTest.java | 20 ++--- .../pmd/lang/document/FileCollectorTest.java | 33 +++----- .../pmd/lang/document/FileLocationTest.java | 2 +- .../pmd/lang/document/NioTextFileTest.java | 2 +- .../pmd/lang/document/TextFilesTest.java | 23 +++--- .../pmd/processor/GlobalListenerTest.java | 10 +-- .../pmd/processor/PmdRunnableTest.java | 2 +- .../java/ast/internal/ReportingStrategy.java | 2 +- 26 files changed, 186 insertions(+), 109 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleContext.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleContext.java index 3023026f6b..905d38474f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleContext.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleContext.java @@ -141,7 +141,7 @@ public final class RuleContext { FileLocation location = node.getReportLocation(); if (beginLine != -1 && endLine != -1) { - location = FileLocation.range(location.getFileName(), TextRange2d.range2d(beginLine, 1, endLine, 1)); + location = FileLocation.range(location.getFileId(), TextRange2d.range2d(beginLine, 1, endLine, 1)); } final Map extraVariables = ViolationDecorator.apply(handler.getViolationDecorator(), node); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index 3c2fbd00f7..8affadcbe2 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -24,6 +24,7 @@ import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.cache.ChecksumAware; import net.sourceforge.pmd.internal.util.PredicateUtil; import net.sourceforge.pmd.lang.LanguageVersion; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; @@ -609,8 +610,8 @@ public class RuleSet implements ChecksumAware { */ // TODO get rid of this overload @InternalApi - public boolean applies(String qualFileName) { - return filter.test(qualFileName); + public boolean applies(PathId qualFileName) { + return filter.test(qualFileName.toAbsolutePath()); } /** @@ -626,7 +627,7 @@ public class RuleSet implements ChecksumAware { * false otherwise */ boolean applies(TextFile file) { - return applies(file.getPathId().getFileName()); + return applies(file.getPathId()); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java index d77b24b8d7..cde200cc8f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java @@ -136,10 +136,10 @@ public class RuleSets { * Apply all applicable rules to the compilation units. Applicable means the * language of the rules must match the language of the source (@see * applies). - * @param root - * the List of compilation units; the type these must have, - * depends on the source language - * @param listener + * + * @param root the List of compilation units; the type these must have, + * depends on the source language + * @param listener Listener that will handle events while analysing. */ public void apply(RootNode root, FileAnalysisListener listener) { if (ruleApplicator == null) { @@ -154,7 +154,7 @@ public class RuleSets { } for (RuleSet ruleSet : ruleSets) { - if (ruleSet.applies(root.getTextDocument().getPathId().getFileName())) { + if (ruleSet.applies(root.getTextDocument().getPathId())) { ruleApplicator.apply(ruleSet.getRules(), listener); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java index 8f4d712867..c1cd869ad0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java @@ -9,6 +9,7 @@ import java.util.Map; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.lang.document.PathId; /** * A RuleViolation is created by a Rule when it identifies a violation of the @@ -83,9 +84,16 @@ public interface RuleViolation { * Get the source file name in which this violation was identified. * * @return The source file name. + * + * @deprecated Use {@link FileLocation#getFileId()} */ + @Deprecated default String getFilename() { - return getLocation().getFileName().toUriString(); + return getLocation().getFileId().toUriString(); + } + + default PathId getFileId() { + return getLocation().getFileId(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java index 3d9ccd4d0a..fb4fe2b2e8 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java @@ -78,7 +78,7 @@ public class TokenEntry implements Comparable { } public TokenEntry(String image, FileLocation location) { - this(image, location.getFileName().getNiceFileName(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); + this(image, location.getFileId().getOriginalFileName(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); } private boolean isOk(int coord) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java index 8833fccaf9..29a8e19202 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java @@ -32,7 +32,7 @@ public abstract class AntlrTokenizer implements Tokenizer { public void tokenize(final SourceCode sourceCode, final Tokens tokenEntries) { try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { - CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getNiceFileName()); + CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getOriginalFileName()); final AntlrTokenManager tokenManager = new AntlrTokenManager(getLexerForSource(charStream), textDoc); final AntlrTokenFilter tokenFilter = getTokenFilter(tokenManager); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java index ab9bc5f201..53c1f997a0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java @@ -59,7 +59,7 @@ public interface Parser { * not be interpreted, it may not be a file-system path. */ public String getFileDisplayName() { - return textDoc.getPathId().getNiceFileName(); + return textDoc.getPathId().getOriginalFileName(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java index bc3471861e..664198d9dd 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java @@ -20,7 +20,7 @@ public class MalformedSourceException extends FileAnalysisException { public MalformedSourceException(String message, Throwable cause, FileLocation fileLocation) { super(message, cause); this.location = Objects.requireNonNull(fileLocation); - setFileName(fileLocation.getFileName()); + setFileName(fileLocation.getFileId()); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index b780894847..e79417f1c7 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -64,16 +64,16 @@ public final class FileCollector implements AutoCloseable { private Charset charset = StandardCharsets.UTF_8; private final LanguageVersionDiscoverer discoverer; private final MessageReporter reporter; - private final String outerFsDisplayName; + private final PathId outerFsPath; private final List relativizeRootPaths = new ArrayList<>(); private boolean closed; // construction - private FileCollector(LanguageVersionDiscoverer discoverer, MessageReporter reporter, String outerFsDisplayName) { + private FileCollector(LanguageVersionDiscoverer discoverer, MessageReporter reporter, PathId outerFsPath) { this.discoverer = discoverer; this.reporter = reporter; - this.outerFsDisplayName = outerFsDisplayName; + this.outerFsPath = outerFsPath; } /** @@ -156,6 +156,7 @@ public final class FileCollector implements AutoCloseable { LanguageVersion languageVersion = discoverLanguage(file.toString()); return languageVersion != null && addFileImpl(TextFile.builderForPath(file, charset, languageVersion) + .setParentFsPath(outerFsPath) .build()); } @@ -178,6 +179,7 @@ public final class FileCollector implements AutoCloseable { LanguageVersion lv = discoverer.getDefaultLanguageVersion(language); Objects.requireNonNull(lv); return addFileImpl(TextFile.builderForPath(file, charset, lv) + .setParentFsPath(outerFsPath) .build()); } @@ -206,6 +208,7 @@ public final class FileCollector implements AutoCloseable { LanguageVersion version = discoverLanguage(pathId.getFileName()); return version != null && addFileImpl(TextFile.builderForCharSeq(sourceContents, pathId, version) + .setParentFsPath(outerFsPath) .build()); } @@ -429,8 +432,7 @@ public final class FileCollector implements AutoCloseable { /** A collector that prefixes the display name of the files it will contain with the path of the zip. */ @Experimental private FileCollector newZipCollector(Path zipFilePath) { - String zipDisplayName = getFileNameRenderer().getDisplayName(PathId.fromPath(zipFilePath)); - return new FileCollector(discoverer, reporter, zipDisplayName); + return new FileCollector(discoverer, reporter, PathId.forPath(zipFilePath)); } // configuration @@ -461,15 +463,6 @@ public final class FileCollector implements AutoCloseable { this.relativizeRootPaths.sort(Comparator.comparingInt(Path::getNameCount).thenComparing(o -> o)); } - // todo doc - String getDisplayName(PathId pathId) { - return getDisplayName(pathId, this.relativizeRootPaths); - } - - String getDisplayName(TextFile file) { - return getDisplayName(file.getPathId()); - } - // todo doc public FileNameRenderer getFileNameRenderer() { return new FileNameRenderer() { @@ -478,8 +471,8 @@ public final class FileCollector implements AutoCloseable { @Override public String getDisplayName(PathId pathId) { String localDisplayName = getLocalDisplayName(pathId); - if (outerFsDisplayName != null) { - return outerFsDisplayName + "!" + localDisplayName; + if (pathId.getParentFsPath() != null) { + return getDisplayName(pathId.getParentFsPath()) + "!" + localDisplayName; } return localDisplayName; } @@ -488,7 +481,7 @@ public final class FileCollector implements AutoCloseable { if (!relativizeRootPaths.isEmpty()) { return FileCollector.getDisplayName(file, relativizeRootPaths); } - return file.toString(); + return file.getOriginalFileName(); } }; } @@ -501,7 +494,7 @@ public final class FileCollector implements AutoCloseable { */ public void exclude(FileCollector excludeCollector) { Set toExclude = new HashSet<>(excludeCollector.allFilesToProcess); - for (Iterator iterator = allFilesToProcess.iterator(); iterator.hasNext(); ) { + for (Iterator iterator = allFilesToProcess.iterator(); iterator.hasNext();) { TextFile file = iterator.next(); if (toExclude.contains(file)) { LOG.trace("Excluding file {}", file.getPathId()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java index ad798c0dbe..3cdf7b90db 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java @@ -35,7 +35,7 @@ public final class FileLocation { public static final Comparator COMPARATOR = - Comparator.comparing(FileLocation::getFileName).thenComparing(COORDS_COMPARATOR); + Comparator.comparing(FileLocation::getFileId).thenComparing(COORDS_COMPARATOR); private final int beginLine; private final int endLine; @@ -68,10 +68,9 @@ public final class FileLocation { } /** - * File name of this position. This is a display name, it shouldn't - * be parsed as a Path. + * File name of this position. */ - public PathId getFileName() { + public PathId getFileId() { return fileName; } @@ -134,7 +133,7 @@ public final class FileLocation { * Formats the start position as e.g. {@code "/path/to/file:1:2"}. */ public String startPosToStringWithFile() { - return getFileName() + ":" + getStartPos().toDisplayStringWithColon(); + return getFileId().getOriginalFileName() + ":" + getStartPos().toDisplayStringWithColon(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java index f74964e751..197c197f90 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java @@ -12,6 +12,7 @@ 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.BaseCloseable; import net.sourceforge.pmd.lang.LanguageVersion; @@ -29,6 +30,7 @@ class NioTextFile extends BaseCloseable implements TextFile { private boolean readOnly; NioTextFile(Path path, + @Nullable PathId parentFsPath, Charset charset, LanguageVersion languageVersion, boolean readOnly) { @@ -42,7 +44,7 @@ class NioTextFile extends BaseCloseable implements TextFile { this.languageVersion = languageVersion; // using the URI here, that handles files inside zip archives automatically (schema "jar:file:...!/path/inside/zip") // normalization ensures cannonical paths - this.pathId = PathId.fromPath(path); + this.pathId = PathId.forPath(path, parentFsPath); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java index 6cd7fe64e3..b142375258 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java @@ -7,6 +7,8 @@ package net.sourceforge.pmd.lang.document; import java.nio.file.Path; import java.nio.file.Paths; +import org.checkerframework.checker.nullness.qual.Nullable; + /** * A virtual path for a {@link TextFile}. * @@ -20,10 +22,13 @@ public interface PathId extends Comparable { */ PathId UNKNOWN = fromPathLikeString("(unknown file)"); + @Nullable PathId getParentFsPath(); + String toUriString(); String getFileName(); - String getNiceFileName(); + + String getOriginalFileName(); String toAbsolutePath(); @@ -54,9 +59,14 @@ public interface PathId extends Comparable { } @Override - public String getNiceFileName() { + public String getOriginalFileName() { return "stdin"; } + + @Override + public @Nullable PathId getParentFsPath() { + return null; + } }; static PathId fromPathLikeString(String str) { @@ -82,7 +92,7 @@ public interface PathId extends Comparable { } @Override - public String getNiceFileName() { + public String getOriginalFileName() { return str; } @@ -91,10 +101,20 @@ public interface PathId extends Comparable { return obj instanceof PathId && ((PathId) obj).toUriString().equals(this.toUriString()); } + + @Override + public int hashCode() { + return toUriString().hashCode(); + } + + @Override + public @Nullable PathId getParentFsPath() { + return null; + } }; } - static PathId fromPath(Path path) { + static PathId forPath(Path path, @Nullable PathId fsPath) { return new PathId() { @Override public String toAbsolutePath() { @@ -112,15 +132,63 @@ public interface PathId extends Comparable { } @Override - public String getNiceFileName() { + public String getOriginalFileName() { return path.toString(); } + @Override + public @Nullable PathId getParentFsPath() { + return fsPath; + } + @Override public boolean equals(Object obj) { return obj instanceof PathId && ((PathId) obj).toUriString().equals(this.toUriString()); } + + @Override + public int hashCode() { + return toUriString().hashCode(); + } + + @Override + public String toString() { + return "PathId.forPath(" + path + ")"; + } + }; + } + + static PathId forPath(Path path) { + return forPath(path, null); + } + + static PathId asChildOf(PathId self, PathId parentFsPath) { + return new PathId() { + @Override + public @Nullable PathId getParentFsPath() { + return parentFsPath; + } + + @Override + public String toUriString() { + return self.toUriString(); + } + + @Override + public String getFileName() { + return self.getFileName(); + } + + @Override + public String getOriginalFileName() { + return self.getOriginalFileName(); + } + + @Override + public String toAbsolutePath() { + return self.toAbsolutePath(); + } }; } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java index dc353f7166..3d66609b20 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java @@ -94,7 +94,7 @@ public interface TextDocument extends Closeable { * Returns {@link TextFile#getDisplayName()} for the text file backing this document. */ default String getDisplayName() { - return getPathId().getNiceFileName(); + return getPathId().getOriginalFileName(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index ee323c84c6..cb74b1413e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -81,7 +81,7 @@ public interface TextFile extends Closeable { */ @Deprecated default @NonNull String getDisplayName() { - return getPathId().getNiceFileName(); + return getPathId().getOriginalFileName(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java index e1e7242321..69382079de 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java @@ -8,6 +8,8 @@ import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Path; +import org.checkerframework.checker.nullness.qual.Nullable; + import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.util.AssertionUtil; @@ -19,6 +21,7 @@ import net.sourceforge.pmd.util.AssertionUtil; public abstract class TextFileBuilder { protected final LanguageVersion languageVersion; + protected PathId parentFsId; TextFileBuilder(LanguageVersion languageVersion) { this.languageVersion = AssertionUtil.requireParamNotNull("language version", languageVersion); @@ -35,6 +38,11 @@ public abstract class TextFileBuilder { return this; } + public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { + parentFsId = pathId; + return this; + } + /** * Creates and returns the new text file. @@ -61,14 +69,14 @@ public abstract class TextFileBuilder { @Override public TextFile build() { - return new NioTextFile(path, charset, languageVersion, readOnly); + return new NioTextFile(path, parentFsId, charset, languageVersion, readOnly); } } static class ForCharSeq extends TextFileBuilder { private final CharSequence charSequence; - private final PathId pathId; + private PathId pathId; ForCharSeq(CharSequence charSequence, PathId pathId, LanguageVersion languageVersion) { super(languageVersion); @@ -76,6 +84,12 @@ public abstract class TextFileBuilder { this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); } + @Override + public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { + this.pathId = PathId.asChildOf(this.pathId, pathId); + return super.setParentFsPath(pathId); + } + @Override public TextFile build() { return new StringTextFile(charSequence, pathId, languageVersion); @@ -85,7 +99,7 @@ public abstract class TextFileBuilder { static class ForReader extends TextFileBuilder { private final Reader reader; - private final PathId pathId; + private PathId pathId; ForReader(LanguageVersion languageVersion, Reader reader, PathId pathId) { super(languageVersion); @@ -93,6 +107,13 @@ public abstract class TextFileBuilder { this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); } + @Override + public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { + this.pathId = PathId.asChildOf(this.pathId, pathId); + return super.setParentFsPath(pathId); + } + + @Override public TextFile build() { return new ReaderTextFile(reader, pathId, languageVersion); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java index 73d6c3bea5..91136144ab 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java @@ -41,6 +41,7 @@ public class DummyParsingHelper implements Extension, BeforeEachCallback, AfterE public DummyRootNode parse(String code, String filename) { return parse(code, PathId.fromPathLikeString(filename)); } + public DummyRootNode parse(String code, PathId filename) { LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion(); ParserTask task = new ParserTask( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index 88fea5eef5..7912052135 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -6,9 +6,11 @@ package net.sourceforge.pmd.cache; import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties; import static net.sourceforge.pmd.util.CollectionUtil.listOf; +import static net.sourceforge.pmd.util.CollectionUtil.setOf; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; @@ -113,7 +115,7 @@ class FileAnalysisCacheTest { @Test void testStorePersistsFilesWithViolations() throws IOException { final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend)); final FileAnalysisListener cacheListener = cache.startFileAnalysis(sourceFile); cache.isUpToDate(sourceFile); @@ -130,14 +132,14 @@ class FileAnalysisCacheTest { cache.persist(); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); + reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend)); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file with violations is not up to date"); final List cachedViolations = reloadedCache.getCachedViolations(sourceFile); assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch"); final RuleViolation cachedViolation = cachedViolations.get(0); - assertEquals(sourceFile.getDisplayName(), cachedViolation.getFilename()); + assertSame(sourceFile.getPathId(), cachedViolation.getFileId()); assertEquals(textLocation.getStartLine(), cachedViolation.getBeginLine()); assertEquals(textLocation.getStartColumn(), cachedViolation.getBeginColumn()); assertEquals(textLocation.getEndLine(), cachedViolation.getEndLine()); @@ -186,7 +188,7 @@ class FileAnalysisCacheTest { List cachedViolations = reloadedCache.getCachedViolations(doc1); assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch"); final RuleViolation cachedViolation = cachedViolations.get(0); - assertEquals(mockFile.getDisplayName(), cachedViolation.getFilename()); + assertEquals(mockFile.getPathId(), cachedViolation.getLocation().getFileId()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index bef98cd221..52826a7175 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -92,7 +92,7 @@ class PMDFilelistTest { } } - private static void assertHasName(TextFile textFile, String expected, FileCollector files) { + public static void assertHasName(TextFile textFile, String expected, FileCollector files) { assertThat(files.getFileNameRenderer().getDisplayName(textFile), equalTo(expected)); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java index 6e7426a73c..f2a8934081 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java @@ -4,8 +4,8 @@ package net.sourceforge.pmd.cli; +import static net.sourceforge.pmd.cli.PMDFilelistTest.assertHasName; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import java.nio.file.Path; @@ -33,9 +33,9 @@ class ZipFileTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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")); + assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd.files()); + assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd.files()); + assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd.files()); } } @@ -48,9 +48,9 @@ class ZipFileTest { List 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")); + assertHasName(files.get(0), baseZipPath + "!/otherSrc/somefile.dummy", pmd.files()); + assertHasName(files.get(1), baseZipPath + "!/src/somefile.dummy", pmd.files()); + assertHasName(files.get(2), baseZipPath + "!/src/somefile1.dummy", pmd.files()); } } @@ -64,9 +64,9 @@ class ZipFileTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List 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")); + assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd.files()); + assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd.files()); + assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd.files()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index ac44ce0d78..c731ec3204 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -9,15 +9,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -27,6 +23,7 @@ import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; +import net.sourceforge.pmd.util.CollectionUtil; /** * @author Clément Fournier @@ -46,7 +43,7 @@ class FileCollectorTest { assertTrue(collector.addFile(foo), "should be dummy language"); assertFalse(collector.addFile(bar), "should be unknown language"); - assertCollected(collector, listOf("foo.dummy")); + assertCollected(collector, listOf(PathId.forPath(foo))); } @Test @@ -58,7 +55,7 @@ class FileCollectorTest { FileCollector collector = newCollector(dummy.getDefaultVersion()); assertTrue(collector.addFile(bar, dummy), "should be unknown language"); - assertCollected(collector, listOf("bar.unknown")); + assertCollected(collector, listOf(PathId.forPath(bar))); assertNoErrors(collector); } @@ -83,21 +80,21 @@ class FileCollectorTest { @Test void testAddDirectory() throws IOException { Path root = tempFolder; - newFile(root, "src/foo.dummy"); + Path foo = newFile(root, "src/foo.dummy"); newFile(root, "src/bar.unknown"); - newFile(root, "src/x/bar.dummy"); + Path bar = newFile(root, "src/x/bar.dummy"); FileCollector collector = newCollector(); collector.addDirectory(root.resolve("src")); - assertCollected(collector, listOf("src/foo.dummy", "src/x/bar.dummy")); + assertCollected(collector, listOf(PathId.forPath(foo), PathId.forPath(bar))); } @Test void testRelativize() { - String displayName = FileCollector.getDisplayName(PathId.fromPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); + String displayName = FileCollector.getDisplayName(PathId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); assertEquals(displayName, Paths.get("b", "c").toString()); } @@ -108,19 +105,9 @@ class FileCollectorTest { return resolved; } - private void assertCollected(FileCollector collector, List relPaths) { - Map actual = new LinkedHashMap<>(); - for (TextFile file : collector.getCollectedFiles()) { - actual.put(file.getDisplayName(), file.getLanguageVersion().getTerseName()); - } - - relPaths = new ArrayList<>(relPaths); - for (int i = 0; i < relPaths.size(); i++) { - // normalize, we want display names to be platform-specific - relPaths.set(i, relPaths.get(i).replace('/', File.separatorChar)); - } - - assertEquals(relPaths, new ArrayList<>(actual.keySet())); + private void assertCollected(FileCollector collector, List expected) { + List actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getPathId); + assertEquals(expected, actual); } private void assertNoErrors(FileCollector collector) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java index 8ef339c813..96cb53acaf 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java @@ -20,7 +20,7 @@ class FileLocationTest { @Test void testSimple() { FileLocation loc = FileLocation.range(FNAME, TextRange2d.range2d(1, 1, 1, 2)); - assertEquals("fname", loc.getFileName()); + assertEquals(FNAME, loc.getFileId()); assertEquals(1, loc.getStartLine()); assertEquals(1, loc.getStartColumn()); assertEquals(1, loc.getEndLine()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java index 4cf26d092e..087ab92f28 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java @@ -41,7 +41,7 @@ class NioTextFileTest { assertEquals(1, collectedFiles.size()); TextFile textFile = collectedFiles.get(0); assertEquals(zipArchive.toAbsolutePath() + "!/path/inside/someSource.dummy", - textFile.getDisplayName()); + collector.getFileNameRenderer().getDisplayName(textFile)); } } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java index 03be860717..ba94ccd781 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java @@ -37,8 +37,9 @@ class TextFilesTest { void testNioFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { - assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId()); - assertEquals(file.toString(), tf.getDisplayName()); + assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId().toUriString()); + assertEquals(file.toString(), tf.getPathId().getOriginalFileName()); + assertEquals(file.getFileName().toString(), tf.getPathId().getFileName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } @@ -49,7 +50,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content").toAbsolutePath(); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { - try (TextFile stringTf = TextFile.forCharSeq("some content", PathId.fromPath(file), dummyVersion())) { + try (TextFile stringTf = TextFile.forCharSeq("some content", PathId.forPath(file), dummyVersion())) { assertEquals(tf.getPathId(), stringTf.getPathId()); // despite same path id, they are different implementations @@ -57,7 +58,7 @@ class TextFilesTest { assertNotEquals(stringTf, tf); // identical, but string text files use identity - assertNotEquals(stringTf, TextFile.forCharSeq("some content", PathId.fromPath(file), dummyVersion())); + assertNotEquals(stringTf, TextFile.forCharSeq("some content", PathId.forPath(file), dummyVersion())); // those are identical so are equals assertNotSame(tf, tfPrime); @@ -74,8 +75,7 @@ class TextFilesTest { DataSource ds = DataSource.forString("text", "filename.dummy"); PMDConfiguration config = new PMDConfiguration(); try (TextFile tf = TextFile.dataSourceCompat(ds, config)) { - assertEquals("filename.dummy", tf.getPathId()); - assertEquals("filename.dummy", tf.getDisplayName()); + assertEquals("filename.dummy", tf.getPathId().getFileName()); assertEquals(DummyLanguageModule.getInstance().getDefaultVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("text"), tf.readContents().getNormalizedText()); } @@ -89,8 +89,7 @@ class TextFilesTest { PMDConfiguration config = new PMDConfiguration(); config.setForceLanguageVersion(DummyLanguageModule.getInstance().getDefaultVersion()); try (TextFile tf = TextFile.dataSourceCompat(ds, config)) { - assertEquals(ds.getNiceFileName(false, null), tf.getPathId()); - assertEquals(ds.getNiceFileName(false, null), tf.getDisplayName()); + assertEquals(ds.getNiceFileName(false, null), tf.getPathId().getOriginalFileName()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } } @@ -167,7 +166,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion()) .build()) { - assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId()); + assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId().toUriString()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } @@ -185,8 +184,7 @@ class TextFilesTest { void testReaderFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), PathId.UNKNOWN, dummyVersion())) { - assertEquals("filename", tf.getPathId()); - assertEquals("filename", tf.getDisplayName()); + assertEquals(PathId.UNKNOWN, tf.getPathId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText()); } @@ -206,8 +204,7 @@ class TextFilesTest { @Test void testStringFileEscape() throws IOException { try (TextFile tf = TextFile.forCharSeq("cont\r\nents", PathId.UNKNOWN, dummyVersion())) { - assertEquals("filename", tf.getPathId()); - assertEquals("filename", tf.getDisplayName()); + assertEquals(PathId.UNKNOWN, tf.getPathId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("cont\nents"), tf.readContents().getNormalizedText()); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index bf3a058c58..cb0acc1531 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -12,8 +12,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.util.Collections; - import org.checkerframework.checker.nullness.qual.NonNull; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -79,7 +77,7 @@ class GlobalListenerTest { MyFooRule rule = new MyFooRule(); runPmd(config, GlobalAnalysisListener.noop(), rule); - verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); + verify(mockCache).checkValidity(any(), any(), any()); verify(mockCache, times(1)).persist(); verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any()); } @@ -95,7 +93,7 @@ class GlobalListenerTest { runPmd(config, GlobalAnalysisListener.noop(), rule); // cache methods are called regardless - verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); + verify(mockCache).checkValidity(any(), any(), any()); verify(mockCache, times(1)).persist(); verify(mockCache, times(NUM_DATA_SOURCES)).isUpToDate(any()); } @@ -114,10 +112,10 @@ class GlobalListenerTest { runPmd(config, listener, rule); }); - assertEquals("fname1.dummy", exception.getFileName()); + assertEquals("fname1.dummy", exception.getFileName().getOriginalFileName()); // cache methods are called regardless - verify(mockCache).checkValidity(any(), any(), Collections.emptySet()); + verify(mockCache).checkValidity(any(), any(), any()); verify(mockCache, times(1)).persist(); verify(mockCache, times(1)).isUpToDate(any()); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java index e0c93c2104..26d932b8ac 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java @@ -75,7 +75,7 @@ class PmdRunnableTest { configuration.setForceLanguageVersion(lv); configuration.setIgnoreIncrementalAnalysis(true); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { - pmd.files().addSourceFile(PathId.fromPathLikeString("file.dummy"), "foo"); + pmd.files().addSourceFile(PathId.fromPathLikeString("test.dummy"), "foo"); pmd.addRuleSet(RuleSet.forSingleRule(rule)); return pmd.performAnalysisAndCollectReport(); } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java index 51a5851cf7..2fc8e0a895 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java @@ -52,7 +52,7 @@ public interface ReportingStrategy { @Override public void report(Node node, String message, Void acc) { - throw new ParseException(node.getReportLocation().startPosToString() + ": " + message); + throw new ParseException(message).setFileName(node.getTextDocument().getPathId()); } }; } From f7ec779f94957628d8b9410c2f3ab2947f5a30d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 19:35:06 +0100 Subject: [PATCH 04/14] Fix renderers --- .../main/java/net/sourceforge/pmd/Report.java | 4 ++-- .../net/sourceforge/pmd/RuleViolation.java | 13 ++---------- .../net/sourceforge/pmd/cpd/TokenEntry.java | 2 +- .../pmd/cpd/internal/AntlrTokenizer.java | 2 +- .../net/sourceforge/pmd/lang/ast/Parser.java | 2 +- .../pmd/lang/document/FileCollector.java | 2 +- .../pmd/lang/document/FileLocation.java | 2 +- .../sourceforge/pmd/lang/document/PathId.java | 16 +++++++------- .../pmd/lang/document/TextDocument.java | 2 +- .../pmd/lang/document/TextFile.java | 2 +- .../lang/rule/ParametricRuleViolation.java | 2 +- .../pmd/renderers/AbstractRenderer.java | 21 +++++++++---------- .../pmd/renderers/CSVRenderer.java | 2 +- .../pmd/renderers/CodeClimateRenderer.java | 2 +- .../pmd/renderers/EmacsRenderer.java | 2 +- .../pmd/renderers/HTMLRenderer.java | 11 +++++----- .../pmd/renderers/IDEAJRenderer.java | 5 +++-- .../pmd/renderers/JsonRenderer.java | 6 +++--- .../sourceforge/pmd/renderers/Renderer.java | 2 ++ .../pmd/renderers/TextColorRenderer.java | 4 ++-- .../pmd/renderers/TextPadRenderer.java | 2 +- .../pmd/renderers/TextRenderer.java | 6 +++--- .../pmd/renderers/VBHTMLRenderer.java | 4 ++-- .../pmd/renderers/XMLRenderer.java | 6 +++--- .../internal/sarif/SarifLogBuilder.java | 4 ++-- .../net/sourceforge/pmd/AbstractRuleTest.java | 4 ++-- .../java/net/sourceforge/pmd/RuleSetTest.java | 3 +-- .../sourceforge/pmd/RuleViolationTest.java | 5 +++-- .../pmd/cache/FileAnalysisCacheTest.java | 1 - .../pmd/lang/document/TextFilesTest.java | 4 ++-- .../pmd/processor/GlobalListenerTest.java | 2 +- .../pmd/renderers/SarifRendererTest.java | 2 +- .../pmd/renderers/VBHTMLRendererTest.java | 2 +- .../sarif/expected-error-nomessage.sarif.json | 4 ++-- .../renderers/sarif/expected-error.sarif.json | 4 ++-- .../expected-multiple-locations.sarif.json | 8 +++---- .../sarif/expected-multiple.sarif.json | 6 +++--- .../pmd/renderers/sarif/expected.sarif.json | 4 ++-- .../pmd/lang/ast/test/BaseParsingHelper.kt | 14 ++++++++----- 39 files changed, 94 insertions(+), 95 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index 64806e2840..4d197011b0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -133,8 +133,8 @@ public final class Report { } } - public String getFile() { - return file.toUriString(); + public PathId getFileId() { + return file; } public Throwable getError() { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java index c1cd869ad0..881c65b73c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java @@ -30,7 +30,7 @@ public interface RuleViolation { * in an unspecified order. */ Comparator DEFAULT_COMPARATOR = - Comparator.comparing(RuleViolation::getFilename) + Comparator.comparing(RuleViolation::getFileId) .thenComparingInt(RuleViolation::getBeginLine) .thenComparingInt(RuleViolation::getBeginColumn) .thenComparing(RuleViolation::getDescription, Comparator.nullsLast(Comparator.naturalOrder())) @@ -81,17 +81,8 @@ public interface RuleViolation { FileLocation getLocation(); /** - * Get the source file name in which this violation was identified. - * - * @return The source file name. - * - * @deprecated Use {@link FileLocation#getFileId()} + * Return the ID of the file where the violation was found. */ - @Deprecated - default String getFilename() { - return getLocation().getFileId().toUriString(); - } - default PathId getFileId() { return getLocation().getFileId(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java index fb4fe2b2e8..9102a7f92d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/TokenEntry.java @@ -78,7 +78,7 @@ public class TokenEntry implements Comparable { } public TokenEntry(String image, FileLocation location) { - this(image, location.getFileId().getOriginalFileName(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); + this(image, location.getFileId().getOriginalPath(), location.getStartLine(), location.getStartColumn(), location.getEndColumn()); } private boolean isOk(int coord) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java index 29a8e19202..7693a7a39b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java @@ -32,7 +32,7 @@ public abstract class AntlrTokenizer implements Tokenizer { public void tokenize(final SourceCode sourceCode, final Tokens tokenEntries) { try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { - CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getOriginalFileName()); + CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getOriginalPath()); final AntlrTokenManager tokenManager = new AntlrTokenManager(getLexerForSource(charStream), textDoc); final AntlrTokenFilter tokenFilter = getTokenFilter(tokenManager); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java index 53c1f997a0..292c81e012 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java @@ -59,7 +59,7 @@ public interface Parser { * not be interpreted, it may not be a file-system path. */ public String getFileDisplayName() { - return textDoc.getPathId().getOriginalFileName(); + return textDoc.getPathId().getOriginalPath(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index e79417f1c7..1c2da3d80c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -481,7 +481,7 @@ public final class FileCollector implements AutoCloseable { if (!relativizeRootPaths.isEmpty()) { return FileCollector.getDisplayName(file, relativizeRootPaths); } - return file.getOriginalFileName(); + return file.getOriginalPath(); } }; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java index 3cdf7b90db..d7f7864776 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java @@ -133,7 +133,7 @@ public final class FileLocation { * Formats the start position as e.g. {@code "/path/to/file:1:2"}. */ public String startPosToStringWithFile() { - return getFileId().getOriginalFileName() + ":" + getStartPos().toDisplayStringWithColon(); + return getFileId().getOriginalPath() + ":" + getStartPos().toDisplayStringWithColon(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java index b142375258..c532f1deea 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java @@ -28,7 +28,7 @@ public interface PathId extends Comparable { String getFileName(); - String getOriginalFileName(); + String getOriginalPath(); String toAbsolutePath(); @@ -59,7 +59,7 @@ public interface PathId extends Comparable { } @Override - public String getOriginalFileName() { + public String getOriginalPath() { return "stdin"; } @@ -83,7 +83,9 @@ public interface PathId extends Comparable { @Override public String toUriString() { - return str; + // this is mostly just to make sure that renderers do + // not use that by default. + return "unknown://" + str; } @Override @@ -92,7 +94,7 @@ public interface PathId extends Comparable { } @Override - public String getOriginalFileName() { + public String getOriginalPath() { return str; } @@ -132,7 +134,7 @@ public interface PathId extends Comparable { } @Override - public String getOriginalFileName() { + public String getOriginalPath() { return path.toString(); } @@ -181,8 +183,8 @@ public interface PathId extends Comparable { } @Override - public String getOriginalFileName() { - return self.getOriginalFileName(); + public String getOriginalPath() { + return self.getOriginalPath(); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java index 3d66609b20..6af1a2cbf1 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java @@ -94,7 +94,7 @@ public interface TextDocument extends Closeable { * Returns {@link TextFile#getDisplayName()} for the text file backing this document. */ default String getDisplayName() { - return getPathId().getOriginalFileName(); + return getPathId().getOriginalPath(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index cb74b1413e..ac1ec1279e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -81,7 +81,7 @@ public interface TextFile extends Closeable { */ @Deprecated default @NonNull String getDisplayName() { - return getPathId().getOriginalFileName(); + return getPathId().getOriginalPath(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java index aeca48672b..6697ff7728 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/ParametricRuleViolation.java @@ -81,6 +81,6 @@ public class ParametricRuleViolation implements RuleViolation { @Override public String toString() { - return getFilename() + ':' + getRule() + ':' + getDescription() + ':' + getLocation().startPosToString(); + return getLocation().startPosToStringWithFile() + ':' + getRule() + ':' + getDescription(); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java index 4b8d01d02c..733e751cea 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java @@ -7,10 +7,9 @@ package net.sourceforge.pmd.renderers; import java.io.PrintWriter; import java.io.Writer; -import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.annotation.Experimental; -import net.sourceforge.pmd.cli.PMDParameters; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.properties.AbstractPropertySource; /** @@ -22,6 +21,7 @@ public abstract class AbstractRenderer extends AbstractPropertySource implements protected boolean showSuppressedViolations = true; protected PrintWriter writer; + private FileNameRenderer fileNameRenderer = PathId::getOriginalPath; public AbstractRenderer(String name, String description) { this.name = name; @@ -63,20 +63,19 @@ public abstract class AbstractRenderer extends AbstractPropertySource implements this.showSuppressedViolations = showSuppressedViolations; } + @Override + public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { + this.fileNameRenderer = fileNameRenderer; + } + /** * Determines the filename that should be used in the report depending on the * option "shortnames". If the option is enabled, then the filename in the report * is without the directory prefix of the directories, that have been analyzed. - * If the option "shortnames" is not enabled, then the inputFileName is returned as-is. - * - * @param inputFileName - * @return - * - * @see PMDConfiguration#isReportShortNames() - * @see PMDParameters#isShortnames() + * If the option "shortnames" is not enabled, then the fileId is returned as-is. */ - protected String determineFileName(String inputFileName) { - return inputFileName; // now the TextFile always has a short display name if it was created so. + protected String determineFileName(PathId fileId) { + return fileNameRenderer.getDisplayName(fileId); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVRenderer.java index cdddd67065..dfbd93bcb3 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CSVRenderer.java @@ -43,7 +43,7 @@ public class CSVRenderer extends AbstractIncrementingRenderer { private final ColumnDescriptor[] allColumns = new ColumnDescriptor[] { newColDescriptor("problem", "Problem", (idx, rv, cr) -> Integer.toString(idx)), newColDescriptor("package", "Package", (idx, rv, cr) -> rv.getAdditionalInfo().getOrDefault(RuleViolation.PACKAGE_NAME, "")), - newColDescriptor("file", "File", (idx, rv, cr) -> determineFileName(rv.getFilename())), + newColDescriptor("file", "File", (idx, rv, cr) -> determineFileName(rv.getFileId())), newColDescriptor("priority", "Priority", (idx, rv, cr) -> Integer.toString(rv.getRule().getPriority().getPriority())), newColDescriptor("line", "Line", (idx, rv, cr) -> Integer.toString(rv.getBeginLine())), newColDescriptor("desc", "Description", (idx, rv, cr) -> StringUtils.replaceChars(rv.getDescription(), '\"', '\'')), diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateRenderer.java index 7bd956c2cb..0f886bbabb 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/CodeClimateRenderer.java @@ -105,7 +105,7 @@ public class CodeClimateRenderer extends AbstractIncrementingRenderer { } private CodeClimateIssue.Location getLocation(RuleViolation rv) { - String pathWithoutCcRoot = StringUtils.removeStartIgnoreCase(determineFileName(rv.getFilename()), "/code/"); + String pathWithoutCcRoot = StringUtils.removeStartIgnoreCase(determineFileName(rv.getFileId()), "/code/"); return new CodeClimateIssue.Location(pathWithoutCcRoot, rv.getBeginLine(), rv.getEndLine()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmacsRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmacsRenderer.java index 7af6f21dd2..943c34a0ff 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmacsRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/EmacsRenderer.java @@ -33,7 +33,7 @@ public class EmacsRenderer extends AbstractIncrementingRenderer { while (violations.hasNext()) { RuleViolation rv = violations.next(); buf.setLength(0); - buf.append(determineFileName(rv.getFilename())); + buf.append(determineFileName(rv.getFileId())); buf.append(':').append(Integer.toString(rv.getBeginLine())); buf.append(": ").append(rv.getDescription()).append(EOL); writer.write(buf.toString()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java index b37a3754f8..b33aaba855 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java @@ -17,6 +17,7 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.properties.StringProperty; @@ -131,7 +132,7 @@ public class HTMLRenderer extends AbstractIncrementingRenderer { buf.append("> ").append(System.lineSeparator()); buf.append("").append(violationCount).append("").append(System.lineSeparator()); buf.append("") - .append(renderFileName(rv.getFilename(), rv.getBeginLine())) + .append(renderFileName(rv.getFileId(), rv.getBeginLine())) .append("") .append(System.lineSeparator()); buf.append("").append(rv.getBeginLine()).append("").append(System.lineSeparator()); @@ -153,8 +154,8 @@ public class HTMLRenderer extends AbstractIncrementingRenderer { } } - private String renderFileName(String filename, int beginLine) { - return maybeWrap(StringEscapeUtils.escapeHtml4(determineFileName(filename)), + private String renderFileName(PathId fileId, int beginLine) { + return maybeWrap(StringEscapeUtils.escapeHtml4(determineFileName(fileId)), linePrefix == null || beginLine < 0 ? "" : linePrefix + beginLine); } @@ -188,7 +189,7 @@ public class HTMLRenderer extends AbstractIncrementingRenderer { } colorize = !colorize; buf.append("> ").append(System.lineSeparator()); - buf.append("").append(renderFileName(pe.getFile(), -1)).append("").append(System.lineSeparator()); + buf.append("").append(renderFileName(pe.getFileId(), -1)).append("").append(System.lineSeparator()); buf.append("

").append(pe.getDetail()).append("
").append(System.lineSeparator()); buf.append("").append(System.lineSeparator()); writer.write(buf.toString()); @@ -217,7 +218,7 @@ public class HTMLRenderer extends AbstractIncrementingRenderer { colorize = !colorize; buf.append("> ").append(System.lineSeparator()); RuleViolation rv = sv.getRuleViolation(); - buf.append("").append(renderFileName(rv.getFilename(), rv.getBeginLine())).append("").append(System.lineSeparator()); + buf.append("").append(renderFileName(rv.getFileId(), rv.getBeginLine())).append("").append(System.lineSeparator()); buf.append("").append(rv.getBeginLine()).append("").append(System.lineSeparator()); buf.append("").append(renderRuleName(rv.getRule())).append("").append(System.lineSeparator()); buf.append("").append(sv.getSuppressor().getId()).append("").append(System.lineSeparator()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java index a6f38bcd04..54c8196beb 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java @@ -69,8 +69,9 @@ public class IDEAJRenderer extends AbstractIncrementingRenderer { buf.setLength(0); RuleViolation rv = violations.next(); buf.append(rv.getDescription()).append(System.lineSeparator()); - buf.append(" at ").append(getFullyQualifiedClassName(rv.getFilename(), sourcePath)).append(".method("); - buf.append(getSimpleFileName(rv.getFilename())).append(':').append(rv.getBeginLine()).append(')'); + // todo is this the right thing? vvvvvvvvvvvvvvvvvvvvvv + buf.append(" at ").append(getFullyQualifiedClassName(rv.getFileId().getOriginalPath(), sourcePath)).append(".method("); + buf.append(rv.getFileId().getFileName()).append(':').append(rv.getBeginLine()).append(')'); writer.println(buf); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/JsonRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/JsonRenderer.java index a4075daf83..d793cb7fe7 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/JsonRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/JsonRenderer.java @@ -70,7 +70,7 @@ public class JsonRenderer extends AbstractIncrementingRenderer { while (violations.hasNext()) { RuleViolation rv = violations.next(); - String nextFilename = determineFileName(rv.getFilename()); + String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { @@ -129,7 +129,7 @@ public class JsonRenderer extends AbstractIncrementingRenderer { if (!this.suppressed.isEmpty()) { for (Report.SuppressedViolation s : this.suppressed) { RuleViolation rv = s.getRuleViolation(); - String nextFilename = determineFileName(rv.getFilename()); + String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { @@ -152,7 +152,7 @@ public class JsonRenderer extends AbstractIncrementingRenderer { jsonWriter.name("processingErrors").beginArray(); for (Report.ProcessingError error : this.errors) { jsonWriter.beginObject(); - jsonWriter.name("filename").value(error.getFile()); + jsonWriter.name("filename").value(determineFileName(error.getFileId())); jsonWriter.name("message").value(error.getMsg()); jsonWriter.name("detail").value(error.getDetail()); jsonWriter.endObject(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java index 6f8b86b9f2..9f9bd8f37b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java @@ -108,6 +108,8 @@ public interface Renderer extends PropertySource { */ Writer getWriter(); + void setFileNameRenderer(FileNameRenderer fileNameRenderer); + /** * Set the Writer for the Renderer. * diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java index f05038c32f..cb78a79871 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextColorRenderer.java @@ -130,7 +130,7 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { for (RuleViolation rv : report.getViolations()) { buf.setLength(0); numberOfWarnings++; - String nextFile = determineFileName(rv.getFilename()); + String nextFile = determineFileName(rv.getFileId()); if (!nextFile.equals(lastFile)) { lastFile = nextFile; buf.append(this.yellowBold) @@ -184,7 +184,7 @@ public class TextColorRenderer extends AbstractAccumulatingRenderer { for (ProcessingError error : report.getProcessingErrors()) { buf.setLength(0); numberOfErrors++; - String nextFile = determineFileName(error.getFile()); + String nextFile = determineFileName(error.getFileId()); if (!nextFile.equals(lastFile)) { lastFile = nextFile; buf.append(this.redBold) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextPadRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextPadRenderer.java index 3a106f140a..0b68d66206 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextPadRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextPadRenderer.java @@ -54,7 +54,7 @@ public class TextPadRenderer extends AbstractIncrementingRenderer { RuleViolation rv = violations.next(); buf.setLength(0); // Filename - buf.append(determineFileName(rv.getFilename())).append("("); + buf.append(determineFileName(rv.getFileId())).append("("); // Line number buf.append(rv.getBeginLine()).append(", "); // Name of violated rule diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextRenderer.java index a011ba0747..04702540fc 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/TextRenderer.java @@ -37,7 +37,7 @@ public class TextRenderer extends AbstractIncrementingRenderer { while (violations.hasNext()) { buf.setLength(0); RuleViolation rv = violations.next(); - buf.append(determineFileName(rv.getFilename())); + buf.append(determineFileName(rv.getFileId())); buf.append(SMALL_SEPARATOR).append(rv.getBeginLine()); buf.append(MEDIUM_SEPARATOR).append(rv.getRule().getName()); buf.append(MEDIUM_SEPARATOR).append(rv.getDescription()); @@ -51,7 +51,7 @@ public class TextRenderer extends AbstractIncrementingRenderer { for (Report.ProcessingError error : errors) { buf.setLength(0); - buf.append(determineFileName(error.getFile())); + buf.append(determineFileName(error.getFileId())); buf.append(LARGE_SEPARATOR).append(error.getMsg()); writer.println(buf); } @@ -62,7 +62,7 @@ public class TextRenderer extends AbstractIncrementingRenderer { .append(" rule violation suppressed by ") .append(excluded.getSuppressor().getId()) .append(" in ") - .append(determineFileName(excluded.getRuleViolation().getFilename())); + .append(determineFileName(excluded.getRuleViolation().getFileId())); writer.println(buf); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/VBHTMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/VBHTMLRenderer.java index 37a2d13930..ae7a5f7927 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/VBHTMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/VBHTMLRenderer.java @@ -47,7 +47,7 @@ public class VBHTMLRenderer extends AbstractIncrementingRenderer { while (violations.hasNext()) { sb.setLength(0); RuleViolation rv = violations.next(); - String nextFilename = determineFileName(rv.getFilename()); + String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { sb.append("
"); @@ -97,7 +97,7 @@ public class VBHTMLRenderer extends AbstractIncrementingRenderer { sb.append(""); } colorize = !colorize; - sb.append("").append(determineFileName(error.getFile())).append(""); + sb.append("").append(determineFileName(error.getFileId())).append(""); sb.append("
").append(error.getDetail()).append("
"); } sb.append(""); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java index a7330de0df..ef3ac7f0de 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java @@ -145,7 +145,7 @@ public class XMLRenderer extends AbstractIncrementingRenderer { // rule violations while (violations.hasNext()) { RuleViolation rv = violations.next(); - String nextFilename = determineFileName(rv.getFilename()); + String nextFilename = determineFileName(rv.getFileId()); if (!nextFilename.equals(filename)) { // New File if (filename != null) { @@ -194,7 +194,7 @@ public class XMLRenderer extends AbstractIncrementingRenderer { for (Report.ProcessingError pe : errors) { writeNewLine(); xmlWriter.writeStartElement("error"); - xmlWriter.writeAttribute("filename", determineFileName(pe.getFile())); + xmlWriter.writeAttribute("filename", determineFileName(pe.getFileId())); xmlWriter.writeAttribute("msg", pe.getMsg()); writeNewLine(); xmlWriter.writeCData(pe.getDetail()); @@ -207,7 +207,7 @@ public class XMLRenderer extends AbstractIncrementingRenderer { for (Report.SuppressedViolation s : suppressed) { writeNewLine(); xmlWriter.writeStartElement("suppressedviolation"); - xmlWriter.writeAttribute("filename", determineFileName(s.getRuleViolation().getFilename())); + xmlWriter.writeAttribute("filename", determineFileName(s.getRuleViolation().getFileId())); xmlWriter.writeAttribute("suppressiontype", s.getSuppressor().getId().toLowerCase(Locale.ROOT)); xmlWriter.writeAttribute("msg", s.getRuleViolation().getDescription()); xmlWriter.writeAttribute("usermsg", s.getUserMessage() == null ? "" : s.getUserMessage()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLogBuilder.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLogBuilder.java index 23fa770a0c..1367412578 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLogBuilder.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/internal/sarif/SarifLogBuilder.java @@ -58,7 +58,7 @@ public class SarifLogBuilder { public SarifLogBuilder addRunTimeError(Report.ProcessingError error) { ArtifactLocation artifactLocation = ArtifactLocation.builder() - .uri(error.getFile()) + .uri(error.getFileId().toUriString()) .build(); PhysicalLocation physicalLocation = PhysicalLocation.builder() @@ -147,7 +147,7 @@ public class SarifLogBuilder { private Location getRuleViolationLocation(RuleViolation rv) { ArtifactLocation artifactLocation = ArtifactLocation.builder() - .uri(rv.getFilename()) + .uri(rv.getFileId().toUriString()) .build(); Region region = Region.builder() diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java index d7b5cb73b5..035a7dea12 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java @@ -82,7 +82,7 @@ class AbstractRuleTest { RuleViolation rv = new ParametricRuleViolation(r, s, r.getMessage()); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); - assertEquals("abc", rv.getFilename(), "Filename mismatch!"); + assertEquals("abc", rv.getFileId().getOriginalPath(), "Filename mismatch!"); assertEquals(r, rv.getRule(), "Rule object mismatch!"); assertEquals("my rule msg", rv.getDescription(), "Rule msg mismatch!"); assertEquals("foo", rv.getRule().getRuleSetName(), "RuleSet name mismatch!"); @@ -94,7 +94,7 @@ class AbstractRuleTest { DummyRootNode s = helper.parse("abc()", PathId.fromPathLikeString("filename")); RuleViolation rv = new ParametricRuleViolation(r, s, "specificdescription"); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); - assertEquals("filename", rv.getFilename(), "Filename mismatch!"); + assertEquals("filename", rv.getFileId().getOriginalPath(), "Filename mismatch!"); assertEquals(r, rv.getRule(), "Rule object mismatch!"); assertEquals("specificdescription", rv.getDescription(), "Rule description mismatch!"); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java index 5b73af9b9b..ca94ab2f1f 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetTest.java @@ -42,7 +42,6 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleSet.RuleSetBuilder; -import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Node; @@ -531,7 +530,7 @@ class RuleSetTest { assertThat(error.getMsg(), containsString("java.lang.IllegalStateException: Test exception while applying rule\n")); assertThat(error.getMsg(), containsString("Rule applied on node=dummyRootNode[@Image=Foo]")); assertThat(error.getError().getCause(), instanceOf(IllegalStateException.class)); - assertThat(IOUtil.normalizePath(error.getFile()), equalTo("samplefile.dummy")); + assertThat(error.getFileId().getFileName(), equalTo("samplefile.dummy")); assertThat(report.getViolations(), hasSize(1)); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java index 96449b0cb3..d3197b743d 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java @@ -6,6 +6,7 @@ package net.sourceforge.pmd; import static net.sourceforge.pmd.ReportTest.violation; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Comparator; @@ -34,7 +35,7 @@ class RuleViolationTest { RuleViolation r = new ParametricRuleViolation(rule, s, rule.getMessage()); assertEquals(rule, r.getRule(), "object mismatch"); assertEquals(1, r.getBeginLine(), "line number is wrong"); - assertEquals("filename", r.getFilename(), "filename is wrong"); + assertSame(filename, r.getFileId(), "filename is wrong"); } @Test @@ -44,7 +45,7 @@ class RuleViolationTest { RuleViolation r = new ParametricRuleViolation(rule, s, "description"); assertEquals(rule, r.getRule(), "object mismatch"); assertEquals(1, r.getBeginLine(), "line number is wrong"); - assertEquals("filename", r.getFilename(), "filename is wrong"); + assertSame(filename, r.getFileId(), "filename is wrong"); assertEquals("description", r.getDescription(), "description is wrong"); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index 7912052135..a2b8a12bf0 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -121,7 +121,6 @@ class FileAnalysisCacheTest { cache.isUpToDate(sourceFile); final RuleViolation rv = mock(RuleViolation.class); - when(rv.getFilename()).thenReturn(sourceFile.getPathId().toUriString()); final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getPathId(), textLocation)); final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java index ba94ccd781..f2365e6734 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java @@ -38,7 +38,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId().toUriString()); - assertEquals(file.toString(), tf.getPathId().getOriginalFileName()); + assertEquals(file.toString(), tf.getPathId().getOriginalPath()); assertEquals(file.getFileName().toString(), tf.getPathId().getFileName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); @@ -89,7 +89,7 @@ class TextFilesTest { PMDConfiguration config = new PMDConfiguration(); config.setForceLanguageVersion(DummyLanguageModule.getInstance().getDefaultVersion()); try (TextFile tf = TextFile.dataSourceCompat(ds, config)) { - assertEquals(ds.getNiceFileName(false, null), tf.getPathId().getOriginalFileName()); + assertEquals(ds.getNiceFileName(false, null), tf.getPathId().getOriginalPath()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index cb0acc1531..6e6ae326cd 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -112,7 +112,7 @@ class GlobalListenerTest { runPmd(config, listener, rule); }); - assertEquals("fname1.dummy", exception.getFileName().getOriginalFileName()); + assertEquals("fname1.dummy", exception.getFileName().getOriginalPath()); // cache methods are called regardless verify(mockCache).checkValidity(any(), any(), any()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SarifRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SarifRendererTest.java index a3b786f8a0..4b54b4fe5a 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SarifRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/SarifRendererTest.java @@ -110,6 +110,6 @@ class SarifRendererTest extends AbstractRendererTest { } protected String readFile(String relativePath) { - return super.readFile("sarif/" + relativePath); + return super.readFile("sarif/" + relativePath).trim(); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/VBHTMLRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/VBHTMLRendererTest.java index fd7d5e1daa..0d473841ac 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/VBHTMLRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/VBHTMLRendererTest.java @@ -75,7 +75,7 @@ class VBHTMLRendererTest extends AbstractRendererTest { + "#RowColor1 { background-color: #eeeeee; }" + EOL + "#RowColor2 { background-color: white; }" + EOL + "-->

 Problems found
" - + error.getFile() + "
" + error.getDetail() + "
" + EOL; + + error.getFileId().getOriginalPath() + "
" + error.getDetail() + "
" + EOL; } @Override diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error-nomessage.sarif.json b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error-nomessage.sarif.json index 6b7ad4c6fc..820c78a15d 100644 --- a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error-nomessage.sarif.json +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error-nomessage.sarif.json @@ -22,7 +22,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "file" + "uri": "unknown://file" } } } @@ -39,4 +39,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error.sarif.json b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error.sarif.json index 84ef17fe38..35155a5aac 100644 --- a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error.sarif.json +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-error.sarif.json @@ -22,7 +22,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "file" + "uri": "unknown://file" } } } @@ -39,4 +39,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple-locations.sarif.json b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple-locations.sarif.json index 7b54693e8d..fc2061b4e0 100644 --- a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple-locations.sarif.json +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple-locations.sarif.json @@ -61,7 +61,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 1, @@ -83,7 +83,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 2, @@ -105,7 +105,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 5, @@ -127,4 +127,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple.sarif.json b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple.sarif.json index 8fcab6485e..06f5a29a7d 100644 --- a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple.sarif.json +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected-multiple.sarif.json @@ -61,7 +61,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 1, @@ -83,7 +83,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 1, @@ -105,4 +105,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected.sarif.json b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected.sarif.json index 7395beb6d8..3d82f299ac 100644 --- a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected.sarif.json +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/sarif/expected.sarif.json @@ -42,7 +42,7 @@ { "physicalLocation": { "artifactLocation": { - "uri": "notAvailable.ext" + "uri": "unknown://notAvailable.ext" }, "region": { "startLine": 1, @@ -64,4 +64,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt index d350a49c1a..bffb8473c4 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt @@ -118,7 +118,7 @@ abstract class BaseParsingHelper, T : RootNode fun parse( sourceCode: String, version: String? = null, - fileName: String = PathId.UNKNOWN + fileName: PathId = PathId.UNKNOWN ): T { val lversion = if (version == null) defaultVersion else getVersion(version) val params = params.copy(defaultVerString = lversion.version) @@ -159,14 +159,18 @@ abstract class BaseParsingHelper, T : RootNode */ @JvmOverloads open fun parseResource(resource: String, version: String? = null): T = - parse(readResource(resource), version, fileName = resource) + parse( + readResource(resource), + version, + fileName = PathId.fromPathLikeString(params.resourcePrefix + resource) + ) /** * Fetches and [parse]s the [path]. */ @JvmOverloads open fun parseFile(path: Path, version: String? = null): T = - parse(IOUtil.readToString(Files.newBufferedReader(path)), version, fileName = path.toAbsolutePath().toString()) + parse(IOUtil.readToString(Files.newBufferedReader(path)), version, fileName = PathId.forPath(path)) /** * Fetches the source of the given [clazz]. @@ -224,7 +228,7 @@ abstract class BaseParsingHelper, T : RootNode fun executeRule( rule: Rule, code: String, - fileName: String = "testfile.${language.extensions[0]}" + fileName: PathId = PathId.fromPathLikeString("testfile.${language.extensions[0]}") ): Report { if (rule.language == null) rule.language = language @@ -251,6 +255,6 @@ abstract class BaseParsingHelper, T : RootNode executeRule( rule, code = Files.newBufferedReader(path).readText(), - fileName = path.toString() + fileName = PathId.forPath(path) ) } From b88297ea7e2ee116e66a4aec4c60c1c9e69aaef6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 19:57:48 +0100 Subject: [PATCH 05/14] Fix cache tests --- .../pmd/renderers/IDEAJRenderer.java | 4 -- .../pmd/cache/FileAnalysisCacheTest.java | 49 +++++++++---------- 2 files changed, 23 insertions(+), 30 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java index 54c8196beb..9aa2b5f12a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java @@ -94,10 +94,6 @@ public class IDEAJRenderer extends AbstractIncrementingRenderer { return className.substring(0, className.length() - 5); } - private String getSimpleFileName(String fileName) { - return fileName.substring(fileName.lastIndexOf(FILE_SEPARATOR) + 1); - } - private static class SourcePath { private Set paths = new HashSet<>(); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index a2b8a12bf0..7e153b00fa 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -164,7 +164,7 @@ class FileAnalysisCacheTest { when(mockFile.readContents()).thenReturn(TextFileContent.fromCharSeq("abc")); final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend)); try (TextDocument doc0 = TextDocument.create(mockFile)) { cache.isUpToDate(doc0); @@ -180,7 +180,7 @@ class FileAnalysisCacheTest { private void reloadWithOneViolation(TextFile mockFile) throws IOException { final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); + reloadedCache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(mockFile)); try (TextDocument doc1 = TextDocument.create(mockFile)) { assertTrue(reloadedCache.isUpToDate(doc1), "Cache believes unmodified file with violations is not up to date"); @@ -197,10 +197,10 @@ class FileAnalysisCacheTest { final RuleSets rs = mock(RuleSets.class); final ClassLoader cl = mock(ClassLoader.class); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl, Collections.emptySet()); + reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend)); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date without ruleset / classpath changes"); } @@ -211,13 +211,13 @@ class FileAnalysisCacheTest { final URLClassLoader cl = mock(URLClassLoader.class); when(cl.getURLs()).thenReturn(new URL[] {}); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final File classpathFile = Files.createTempFile(tempFolder, null, "foo.xml").toFile(); when(cl.getURLs()).thenReturn(new URL[] { classpathFile.toURI().toURL(), }); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); - reloadedCache.checkValidity(rs, cl, Collections.emptySet()); + reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend)); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date without ruleset / classpath changes"); } @@ -227,7 +227,7 @@ class FileAnalysisCacheTest { final RuleSets rs = mock(RuleSets.class); final ClassLoader cl = mock(ClassLoader.class); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); when(rs.getChecksum()).thenReturn(1L); @@ -242,11 +242,11 @@ class FileAnalysisCacheTest { final URLClassLoader cl = mock(URLClassLoader.class); when(cl.getURLs()).thenReturn(new URL[] { tempFolder.resolve("non-existing-dir").toFile().toURI().toURL(), }); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final FileAnalysisCache analysisCache = new FileAnalysisCache(newCacheFile); when(cl.getURLs()).thenReturn(new URL[] {}); - analysisCache.checkValidity(rs, cl, Collections.emptySet()); + analysisCache.checkValidity(rs, cl, setOf(sourceFileBackend)); assertTrue(analysisCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date after non-existing auxclasspath entry removed"); } @@ -257,11 +257,11 @@ class FileAnalysisCacheTest { final URLClassLoader cl = mock(URLClassLoader.class); when(cl.getURLs()).thenReturn(new URL[] { }); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); when(cl.getURLs()).thenReturn(new URL[] { Files.createTempFile(tempFolder, null, null).toFile().toURI().toURL(), }); - reloadedCache.checkValidity(rs, cl, Collections.emptySet()); + reloadedCache.checkValidity(rs, cl, setOf(sourceFileBackend)); assertTrue(reloadedCache.isUpToDate(sourceFile), "Cache believes unmodified file is not up to date after auxclasspath changed when no rule cares"); } @@ -272,7 +272,7 @@ class FileAnalysisCacheTest { final URLClassLoader cl = mock(URLClassLoader.class); when(cl.getURLs()).thenReturn(new URL[] { }); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); final FileAnalysisCache reloadedCache = new FileAnalysisCache(newCacheFile); final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile(); @@ -301,7 +301,7 @@ class FileAnalysisCacheTest { when(r.getLanguage()).thenReturn(mock(Language.class)); when(rs.getAllRules()).thenReturn(Collections.singleton(r)); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); // Edit the auxclasspath referenced file Files.write(classpathFile.toPath(), "some text".getBytes()); @@ -338,7 +338,7 @@ class FileAnalysisCacheTest { final File classpathFile = Files.createTempFile(tempFolder, null, "foo.class").toFile(); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); // Edit the classpath referenced file Files.write(classpathFile.toPath(), "some text".getBytes()); @@ -363,7 +363,7 @@ class FileAnalysisCacheTest { Files.write(classpathFile.toPath(), "some text".getBytes()); System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + classpathFile.getAbsolutePath()); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); // Change the file's contents Files.write(classpathFile.toPath(), "some other text".getBytes()); @@ -380,7 +380,7 @@ class FileAnalysisCacheTest { restoreSystemProperties(() -> { final RuleSets rs = mock(RuleSets.class); final ClassLoader cl = mock(ClassLoader.class); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); // Prepare two class files createZipFile("mylib1.jar"); @@ -406,7 +406,7 @@ class FileAnalysisCacheTest { System.setProperty("java.class.path", System.getProperty("java.class.path") + File.pathSeparator + tempFolder.toFile().getAbsolutePath() + "/*"); - setupCacheWithFiles(newCacheFile, rs, cl, sourceFile); + setupCacheWithFiles(newCacheFile, rs, cl); // Change one file's contents (ie: adding more entries) classpathJar1.delete(); @@ -428,17 +428,17 @@ class FileAnalysisCacheTest { @Test void testFileIsUpToDate() throws IOException { - setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class), sourceFile); + setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class)); final FileAnalysisCache cache = new FileAnalysisCache(newCacheFile); - cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), Collections.emptySet()); + cache.checkValidity(mock(RuleSets.class), mock(ClassLoader.class), setOf(sourceFileBackend)); assertTrue(cache.isUpToDate(sourceFile), "Cache believes a known, unchanged file is not up to date"); } @Test void testFileIsNotUpToDateWhenEdited() throws IOException { - setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class), sourceFile); + setupCacheWithFiles(newCacheFile, mock(RuleSets.class), mock(ClassLoader.class)); // Edit the file TextFileContent text = TextFileContent.fromCharSeq("some text"); @@ -453,15 +453,12 @@ class FileAnalysisCacheTest { private void setupCacheWithFiles(final File cacheFile, final RuleSets ruleSets, - final ClassLoader classLoader, - final TextDocument... files) throws IOException { + final ClassLoader classLoader) throws IOException { // Setup a cache file with an entry for an empty Source.java with no violations final FileAnalysisCache cache = new FileAnalysisCache(cacheFile); - cache.checkValidity(ruleSets, classLoader, Collections.emptySet()); + cache.checkValidity(ruleSets, classLoader, setOf(sourceFileBackend)); - for (final TextDocument f : files) { - cache.isUpToDate(f); - } + cache.isUpToDate(sourceFile); cache.persist(); } From a4024c0021f34130fdbb432d3fc57916e96ff08d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 21:55:05 +0100 Subject: [PATCH 06/14] Fix more things --- .../java/net/sourceforge/pmd/ant/Formatter.java | 12 ++++++++++++ .../pmd/ant/internal/PMDTaskImpl.java | 1 + .../net/sourceforge/pmd/ant/PMDTaskTest.java | 17 ++++++++++------- .../java/net/sourceforge/pmd/PmdAnalysis.java | 4 +++- .../pmd/renderers/IDEAJRenderer.java | 6 +++--- .../net/sourceforge/pmd/renderers/Renderer.java | 11 +++++++++++ .../sourceforge/pmd/renderers/XMLRenderer.java | 6 ++++++ .../pmd/reporting/ListenerInitializer.java | 7 ++++++- .../pmd/lang/java/ast/ParserCornersTest.java | 3 ++- .../pmd/cpd/test/CpdTextComparisonTest.kt | 8 +++++--- .../pmd/test/BaseTextComparisonTest.kt | 5 +++-- 11 files changed, 62 insertions(+), 18 deletions(-) diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java index 6c14fd7356..f90fcf7f6b 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java @@ -29,10 +29,12 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.renderers.RendererFactory; import net.sourceforge.pmd.reporting.FileAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; +import net.sourceforge.pmd.reporting.ListenerInitializer; @InternalApi public class Formatter { @@ -253,6 +255,16 @@ public class Formatter { return new GlobalAnalysisListener() { final GlobalAnalysisListener listener = renderer.newListener(); + @Override + public ListenerInitializer initializer() { + return new ListenerInitializer() { + @Override + public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { + renderer.setFileNameRenderer(fileNameRenderer); + } + }; + } + @Override public FileAnalysisListener startFileAnalysis(TextFile file) { return listener.startFileAnalysis(file); diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java index e68dc62e44..a6e48e9f9d 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java @@ -120,6 +120,7 @@ public class PMDTaskImpl { } } + @SuppressWarnings("PMD.CloseResource") ReportStatsListener reportStatsListener = new ReportStatsListener(); pmd.addListener(getListener(reportStatsListener)); diff --git a/pmd-ant/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java b/pmd-ant/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java index 819aebf084..78217c1a17 100644 --- a/pmd-ant/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java +++ b/pmd-ant/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java @@ -17,6 +17,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import org.apache.tools.ant.BuildException; +import org.checkerframework.checker.nullness.qual.NonNull; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -87,15 +88,17 @@ class PMDTaskTest extends AbstractAntTest { try (InputStream in = Files.newInputStream(Paths.get("target/pmd-ant-xml.xml")); InputStream expectedStream = PMDTaskTest.class.getResourceAsStream("xml/expected-pmd-ant-xml.xml")) { - String actual = IOUtil.readToString(in, StandardCharsets.UTF_8); - actual = actual.replaceFirst("timestamp=\"[^\"]+\"", "timestamp=\"\""); - actual = actual.replaceFirst("\\.xsd\" version=\"[^\"]+\"", ".xsd\" version=\"\""); - - String expected = IOUtil.readToString(expectedStream, StandardCharsets.UTF_8); - expected = expected.replaceFirst("timestamp=\"[^\"]+\"", "timestamp=\"\""); - expected = expected.replaceFirst("\\.xsd\" version=\"[^\"]+\"", ".xsd\" version=\"\""); + String actual = readAndNormalize(in); + String expected = readAndNormalize(expectedStream); assertEquals(expected, actual); } } + + private static @NonNull String readAndNormalize(InputStream expectedStream) throws IOException { + String expected = IOUtil.readToString(expectedStream, StandardCharsets.UTF_8); + expected = expected.replaceFirst("timestamp=\"[^\"]+\"", "timestamp=\"\""); + expected = expected.replaceFirst("\\.xsd\" version=\"[^\"]+\"", ".xsd\" version=\"\""); + return expected; + } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index d2c9ad4a77..a73c7cf089 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -333,6 +333,7 @@ public final class PmdAnalysis implements AutoCloseable { // Initialize listeners try (ListenerInitializer initializer = listener.initializer()) { initializer.setNumberOfFilesToAnalyze(textFiles.size()); + initializer.setFileNameRenderer(files().getFileNameRenderer()); } } catch (Exception e) { reporter.errorEx("Exception while initializing analysis listeners", e); @@ -395,7 +396,7 @@ public final class PmdAnalysis implements AutoCloseable { } - private static GlobalAnalysisListener createComposedRendererListener(List renderers) throws Exception { + private GlobalAnalysisListener createComposedRendererListener(List renderers) throws Exception { if (renderers.isEmpty()) { return GlobalAnalysisListener.noop(); } @@ -403,6 +404,7 @@ public final class PmdAnalysis implements AutoCloseable { List rendererListeners = new ArrayList<>(renderers.size()); for (Renderer renderer : renderers) { try { + renderer.setFileNameRenderer(files().getFileNameRenderer()); @SuppressWarnings("PMD.CloseResource") GlobalAnalysisListener listener = Objects.requireNonNull(renderer.newListener(), "Renderer should provide non-null listener"); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java index 9aa2b5f12a..424c46783d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/IDEAJRenderer.java @@ -69,8 +69,8 @@ public class IDEAJRenderer extends AbstractIncrementingRenderer { buf.setLength(0); RuleViolation rv = violations.next(); buf.append(rv.getDescription()).append(System.lineSeparator()); - // todo is this the right thing? vvvvvvvvvvvvvvvvvvvvvv - buf.append(" at ").append(getFullyQualifiedClassName(rv.getFileId().getOriginalPath(), sourcePath)).append(".method("); + // todo is this the right thing? vvvvvvvvvvvvvvvv + buf.append(" at ").append(getFullyQualifiedClassName(rv.getFileId().toAbsolutePath(), sourcePath)).append(".method("); buf.append(rv.getFileId().getFileName()).append(':').append(rv.getBeginLine()).append(')'); writer.println(buf); } @@ -91,7 +91,7 @@ public class IDEAJRenderer extends AbstractIncrementingRenderer { private String getFullyQualifiedClassName(String fileName, SourcePath sourcePath) { String classNameWithSlashes = sourcePath.clipPath(fileName); String className = classNameWithSlashes.replace(FILE_SEPARATOR.charAt(0), '.'); - return className.substring(0, className.length() - 5); + return className.substring(0, className.length() - ".java".length()); } private static class SourcePath { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java index 9f9bd8f37b..91ce73223f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java @@ -23,6 +23,7 @@ import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertySource; import net.sourceforge.pmd.reporting.FileAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; +import net.sourceforge.pmd.reporting.ListenerInitializer; /** * This is an interface for rendering a Report. When a Renderer is being @@ -204,6 +205,16 @@ public interface Renderer extends PropertySource { configErrorReport.onConfigError(error); } + @Override + public ListenerInitializer initializer() { + return new ListenerInitializer() { + @Override + public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { + Renderer.this.setFileNameRenderer(fileNameRenderer); + } + }; + } + @Override public FileAnalysisListener startFileAnalysis(TextFile file) { Renderer renderer = Renderer.this; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java index ef3ac7f0de..e2060e3a8f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java @@ -28,6 +28,7 @@ import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil; @@ -187,6 +188,11 @@ public class XMLRenderer extends AbstractIncrementingRenderer { } } + @Override + protected String determineFileName(PathId fileId) { + return super.determineFileName(fileId); + } + @Override public void end() throws IOException { try { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java index 2ae8547c8e..397a7da08d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java @@ -9,12 +9,13 @@ import java.util.Collection; import java.util.List; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.util.AssertionUtil; /** * An initializer for {@link GlobalAnalysisListener} that gets notified of * general analysis parameters. - * + * * Each method will be called exactly once, before any events on the {@link GlobalAnalysisListener} */ public interface ListenerInitializer extends AutoCloseable { @@ -26,6 +27,10 @@ public interface ListenerInitializer extends AutoCloseable { // noop } + default void setFileNameRenderer(FileNameRenderer fileNameRenderer) { + // noop + } + /** * Signals the end of initialization: no further calls will be made * to this object. diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java index e55c56314b..0b7f8f552e 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java @@ -21,6 +21,7 @@ import org.junit.jupiter.api.Timeout; import net.sourceforge.pmd.lang.ast.ParseException; import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException; import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper; +import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest; import net.sourceforge.pmd.lang.java.JavaParsingHelper; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; @@ -44,7 +45,7 @@ class ParserCornersTest extends BaseJavaTreeDumpTest { @Test void testInvalidUnicodeEscape() { MalformedSourceException thrown = assertThrows(MalformedSourceException.class, // previously Error - () -> java.parse("\\u00k0", null, "x/filename.java")); + () -> java.parse("\\u00k0", null, PathId.fromPathLikeString("x/filename.java"))); assertThat(thrown.getMessage(), startsWith("Source format error in file 'x/filename.java' at line 1, column 1: Invalid unicode escape")); } diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt index 2a09f7874f..41ac1f7be8 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt @@ -10,6 +10,8 @@ import net.sourceforge.pmd.cpd.TokenEntry import net.sourceforge.pmd.cpd.Tokenizer import net.sourceforge.pmd.cpd.Tokens import net.sourceforge.pmd.lang.ast.TokenMgrError +import net.sourceforge.pmd.lang.document.PathId +import net.sourceforge.pmd.lang.document.TextFile import net.sourceforge.pmd.test.BaseTextComparisonTest import org.apache.commons.lang3.StringUtils import java.util.* @@ -47,7 +49,7 @@ abstract class CpdTextComparisonTest( @JvmOverloads fun doTest(fileBaseName: String, expectedSuffix: String = "", properties: Properties = defaultProperties()) { super.doTest(fileBaseName, expectedSuffix) { fileData -> - val sourceCode = SourceCode(SourceCode.StringCodeLoader(fileData.fileText, fileData.fileName)) + val sourceCode = sourceCodeOf(fileData) val tokens = Tokens().also { val tokenizer = newTokenizer(properties) tokenizer.tokenize(sourceCode, it) @@ -60,7 +62,7 @@ abstract class CpdTextComparisonTest( @JvmOverloads fun expectTokenMgrError( source: String, - fileName: String = SourceCode.StringCodeLoader.DEFAULT_NAME, + fileName: PathId = PathId.UNKNOWN, properties: Properties = defaultProperties() ): TokenMgrError = expectTokenMgrError(FileData(fileName, source), properties) @@ -149,7 +151,7 @@ abstract class CpdTextComparisonTest( fun sourceCodeOf(str: String): SourceCode = SourceCode(SourceCode.StringCodeLoader(str)) fun sourceCodeOf(fileData: FileData): SourceCode = - SourceCode(SourceCode.StringCodeLoader(fileData.fileText, fileData.fileName)) + SourceCode(SourceCode.StringCodeLoader(fileData.fileText, fileData.fileName.toAbsolutePath())) fun tokenize(tokenizer: Tokenizer, str: String): Tokens = Tokens().also { diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt index cb45c4ed41..d82d74e59a 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt @@ -4,6 +4,7 @@ package net.sourceforge.pmd.test +import net.sourceforge.pmd.lang.document.PathId import java.nio.file.Path import java.nio.file.Paths import kotlin.test.assertEquals @@ -27,7 +28,7 @@ abstract class BaseTextComparisonTest { /** Extension that the unparsed source file is supposed to have. */ protected abstract val extensionIncludingDot: String - data class FileData(val fileName:String, val fileText:String) + data class FileData(val fileName:PathId, val fileText:String) /** * Executes the test. The test files are looked up using the [parser]. @@ -66,7 +67,7 @@ abstract class BaseTextComparisonTest { } val sourceText = sourceFile.readText(Charsets.UTF_8).normalize() - return FileData(fileName = sourceFile.toString(), fileText = sourceText) + return FileData(fileName = PathId.forPath(sourceFile.toPath()), fileText = sourceText) } protected open fun String.normalize() = replace( From 37e2f8f208ed9df39df5d157eb2cdd9b1f1a188d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 22:49:45 +0100 Subject: [PATCH 07/14] Improve jjt error messages --- javacc-wrapper.xml | 5 ++ .../pmd/lang/apex/ast/ApexParser.java | 4 +- .../pmd/cpd/internal/JavaCCTokenizer.java | 2 +- .../pmd/lang/ast/FileAnalysisException.java | 35 +++++++---- .../pmd/lang/ast/ParseException.java | 37 +++++++----- .../pmd/lang/ast/TokenMgrError.java | 14 +++-- .../ast/impl/javacc/JjtreeParserAdapter.java | 2 +- .../impl/javacc/MalformedSourceException.java | 8 ++- .../pmd/lang/document/CpdCompat.java | 2 +- .../pmd/renderers/XMLRenderer.java | 6 -- .../pmd/processor/GlobalListenerTest.java | 2 +- pmd-java/etc/grammar/Java.jjt | 60 ++++++------------- .../java/ast/internal/ReportingStrategy.java | 2 +- .../pmd/lang/java/ast/JDKVersionTest.java | 5 +- pmd-plsql/etc/grammar/PLSQL.jjt | 10 ++-- pmd-vm/etc/grammar/Vm.jjt | 17 +++--- 16 files changed, 105 insertions(+), 106 deletions(-) diff --git a/javacc-wrapper.xml b/javacc-wrapper.xml index c7f1d7eead..c92827a482 100644 --- a/javacc-wrapper.xml +++ b/javacc-wrapper.xml @@ -246,6 +246,11 @@ + + + + + diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java index 6605aef54c..180b04e6f5 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java @@ -9,6 +9,7 @@ import net.sourceforge.pmd.lang.apex.ApexJorjeLogging; import net.sourceforge.pmd.lang.apex.ApexLanguageProcessor; import net.sourceforge.pmd.lang.ast.ParseException; import net.sourceforge.pmd.lang.ast.Parser; +import net.sourceforge.pmd.lang.document.FileLocation; import apex.jorje.data.Locations; import apex.jorje.semantic.ast.compilation.Compilation; @@ -32,7 +33,8 @@ public final class ApexParser implements Parser { final ApexTreeBuilder treeBuilder = new ApexTreeBuilder(task, (ApexLanguageProcessor) task.getLanguageProcessor()); return treeBuilder.buildTree(astRoot); } catch (apex.jorje.services.exception.ParseException e) { - throw new ParseException(e).setFileName(task.getTextDocument().getPathId()); + FileLocation loc = FileLocation.caret(task.getTextDocument().getPathId(), e.getLoc().getLine(), e.getLoc().getColumn()); + throw new ParseException(e).withLocation(loc); } } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java index b702fde142..f85f739734 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java @@ -58,7 +58,7 @@ public abstract class JavaCCTokenizer implements Tokenizer { currentToken = tokenFilter.getNextToken(); } } catch (FileAnalysisException e) { - throw e.setFileName(textFile.getPathId()); + throw e.setFileId(textFile.getPathId()); } finally { tokenEntries.add(TokenEntry.getEOF()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java index a0d869b740..6263d3a945 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java @@ -8,7 +8,9 @@ import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; +import org.checkerframework.checker.nullness.qual.Nullable; +import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.PathId; /** @@ -22,7 +24,7 @@ import net.sourceforge.pmd.lang.document.PathId; */ public class FileAnalysisException extends RuntimeException { - private PathId filename = PathId.UNKNOWN; + private PathId fileId = PathId.UNKNOWN; public FileAnalysisException() { super(); @@ -40,24 +42,24 @@ public class FileAnalysisException extends RuntimeException { super(message, cause); } - public FileAnalysisException setFileName(PathId filename) { - this.filename = Objects.requireNonNull(filename); + public FileAnalysisException setFileId(PathId fileId) { + this.fileId = Objects.requireNonNull(fileId); return this; } protected boolean hasFileName() { - return !PathId.UNKNOWN.equals(filename); + return !PathId.UNKNOWN.equals(fileId); } /** * The name of the file in which the error occurred. */ - public @NonNull PathId getFileName() { - return filename; + public @NonNull PathId getFileId() { + return fileId; } @Override - public String getMessage() { + public final String getMessage() { return errorKind() + StringUtils.uncapitalize(positionToString()) + ": " + super.getMessage(); } @@ -65,11 +67,20 @@ public class FileAnalysisException extends RuntimeException { return "Error"; } - protected String positionToString() { + protected @Nullable FileLocation location() { + return null; + } + + private String positionToString() { + String result = ""; if (hasFileName()) { - return " in file '" + getFileName() + "'"; + result += " in file '" + getFileId().getOriginalPath() + "'"; } - return ""; + FileLocation loc = location(); + if (loc != null) { + result += loc.startPosToString(); + } + return result; } @@ -85,11 +96,11 @@ public class FileAnalysisException extends RuntimeException { */ public static FileAnalysisException wrap(@NonNull PathId filename, @NonNull String message, @NonNull Throwable cause) { if (cause instanceof FileAnalysisException) { - return ((FileAnalysisException) cause).setFileName(filename); + return ((FileAnalysisException) cause).setFileId(filename); } String fullMessage = "In file '" + filename + "': " + message; - return new FileAnalysisException(fullMessage, cause).setFileName(filename); + return new FileAnalysisException(fullMessage, cause).setFileId(filename); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/ParseException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/ParseException.java index 8b27689406..1cbf565158 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/ParseException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/ParseException.java @@ -14,6 +14,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccTokenDocument; import net.sourceforge.pmd.lang.document.FileLocation; +import net.sourceforge.pmd.reporting.Reportable; import net.sourceforge.pmd.util.StringUtil; public class ParseException extends FileAnalysisException { @@ -23,26 +24,16 @@ public class ParseException extends FileAnalysisException { * this object has been created due to a parse error, the token * followng this token will (therefore) be the first error token. */ - public final @Nullable GenericToken currentToken; - - public ParseException() { - super(); - this.currentToken = null; - } + private @Nullable FileLocation location; public ParseException(String message) { super(message); - this.currentToken = null; + this.location = null; } public ParseException(Throwable cause) { super(cause); - this.currentToken = null; - } - - public ParseException(String message, JavaccToken token) { - super(message); - this.currentToken = token; + this.location = null; } /** @@ -51,14 +42,30 @@ public class ParseException extends FileAnalysisException { public ParseException(@NonNull JavaccToken currentTokenVal, int[][] expectedTokenSequencesVal) { super(makeMessage(currentTokenVal, expectedTokenSequencesVal)); - currentToken = currentTokenVal; + location = currentTokenVal.getNext().getReportLocation(); } + public ParseException withLocation(FileLocation loc) { + location = loc; + super.setFileId(loc.getFileId()); + return this; + } + + public ParseException withLocation(Reportable reportable) { + return withLocation(reportable.getReportLocation()); + } + + @Override protected String errorKind() { return "Parse exception"; } + @Override + protected @Nullable FileLocation location() { + return location; + } + /** * It uses "currentToken" and "expectedTokenSequences" to generate a parse * error message and returns it. If this object has been created @@ -123,8 +130,6 @@ public class ParseException extends FileAnalysisException { if (maxSize > 1) { retval.append(']'); } - FileLocation loc = currentToken.next.getReportLocation(); - retval.append(" at ").append(loc.getStartPos().toDisplayStringInEnglish()); retval.append('.').append(eol); if (expectedTokenSequences.length == 1) { retval.append("Was expecting:").append(eol).append(" "); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java index 61202727ef..1b24be4fed 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java @@ -4,9 +4,11 @@ package net.sourceforge.pmd.lang.ast; +import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.InternalApi; +import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.util.StringUtil; @@ -32,7 +34,7 @@ public final class TokenMgrError extends FileAnalysisException { this.line = line; this.column = column; if (filename != null) { - super.setFileName(filename); + super.setFileId(filename); } } @@ -55,8 +57,8 @@ public final class TokenMgrError extends FileAnalysisException { } @Override - protected String positionToString() { - return super.positionToString() + " at line " + line + ", column " + column; + protected @NonNull FileLocation location() { + return FileLocation.caret(getFileId(), line, column); } @Override @@ -67,13 +69,13 @@ public final class TokenMgrError extends FileAnalysisException { /** * Replace the file name of this error. * - * @param filename New filename + * @param fileId New filename * * @return A new exception */ @Override - public TokenMgrError setFileName(PathId filename) { - super.setFileName(filename); + public TokenMgrError setFileId(PathId fileId) { + super.setFileId(fileId); return this; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java index 9720acde9b..85dfe0b770 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java @@ -35,7 +35,7 @@ public abstract class JjtreeParserAdapter implements Parser // Finally, do the parsing return parseImpl(charStream, task); } catch (FileAnalysisException tme) { - throw tme.setFileName(task.getTextDocument().getPathId()); + throw tme.setFileId(task.getTextDocument().getPathId()); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java index 664198d9dd..05927d6d90 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/MalformedSourceException.java @@ -6,6 +6,8 @@ package net.sourceforge.pmd.lang.ast.impl.javacc; import java.util.Objects; +import org.checkerframework.checker.nullness.qual.NonNull; + import net.sourceforge.pmd.lang.ast.FileAnalysisException; import net.sourceforge.pmd.lang.document.FileLocation; @@ -20,12 +22,12 @@ public class MalformedSourceException extends FileAnalysisException { public MalformedSourceException(String message, Throwable cause, FileLocation fileLocation) { super(message, cause); this.location = Objects.requireNonNull(fileLocation); - setFileName(fileLocation.getFileId()); + setFileId(fileLocation.getFileId()); } @Override - protected String positionToString() { - return super.positionToString() + " at " + location.startPosToString(); + protected @NonNull FileLocation location() { + return location; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java index 6328a65c06..60732a4e2d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java @@ -33,7 +33,7 @@ public final class CpdCompat { public static TextFile cpdCompat(SourceCode sourceCode) { return TextFile.forCharSeq( sourceCode.getCodeBuffer(), - PathId.fromPathLikeString("fname1.dummy"), + PathId.fromPathLikeString(sourceCode.getFileName()), dummyVersion() ); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java index e2060e3a8f..ef3ac7f0de 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/XMLRenderer.java @@ -28,7 +28,6 @@ import net.sourceforge.pmd.PMDVersion; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.util.StringUtil; @@ -188,11 +187,6 @@ public class XMLRenderer extends AbstractIncrementingRenderer { } } - @Override - protected String determineFileName(PathId fileId) { - return super.determineFileName(fileId); - } - @Override public void end() throws IOException { try { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index 6e6ae326cd..24d162c0ff 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -112,7 +112,7 @@ class GlobalListenerTest { runPmd(config, listener, rule); }); - assertEquals("fname1.dummy", exception.getFileName().getOriginalPath()); + assertEquals("fname1.dummy", exception.getFileId().getOriginalPath()); // cache methods are called regardless verify(mockCache).checkValidity(any(), any(), any()); diff --git a/pmd-java/etc/grammar/Java.jjt b/pmd-java/etc/grammar/Java.jjt index dbd990f157..8461a07438 100644 --- a/pmd-java/etc/grammar/Java.jjt +++ b/pmd-java/etc/grammar/Java.jjt @@ -311,13 +311,7 @@ class JavaParserImpl { } private void throwParseException(String message) { - int line = -1; - int col = -1; - if (jj_lastpos != null) { - line = jj_lastpos.beginLine; - col = jj_lastpos.beginColumn; - } - throw new ParseException("Line " + line + ", Column " + col + ": " + message); + throw new ParseException(message).withLocation(token); } @@ -1105,30 +1099,18 @@ void ImplementsList(): } void PermittedSubclasses() #PermitsList: +{} { - Token t; -} -{ - t = { - if (!"permits".equals(t.image)) { - throw new ParseException("ERROR: expecting permits"); - } - } + softKeyword("permits") ClassOrInterfaceType() ( "," ClassOrInterfaceType() )* } void EnumDeclaration(): +{} { - JavaccToken t; -} -{ - t = { - if (!"enum".equals(t.image)) { - throw new ParseException("ERROR: expecting enum"); - } - } - t= {jjtThis.setImage(t.image);} + softKeyword("enum") + {setLastTokenImage(jjtThis);} [ ImplementsList() ] EnumBody() } @@ -1150,16 +1132,10 @@ void EnumConstant(): } void RecordDeclaration(): +{} { - JavaccToken t; -} -{ - t = { - if (!"record".equals(t.image)) { - throw new ParseException("ERROR: expecting record"); - } - } - t= {jjtThis.setImage(t.image);} + softKeyword("record") + {setLastTokenImage(jjtThis);} [ TypeParameters() ] RecordHeader() [ ImplementsList() ] @@ -2493,16 +2469,9 @@ void CaseLabelElement(ASTSwitchLabel label) #void: } void Guard() #SwitchGuard: +{} { - Token t; -} -{ - t = { - if (!"when".equals(t.image)) { - throw new ParseException("ERROR: expected 'when'"); - } - } - + softKeyword("when") Expression() } @@ -2890,3 +2859,10 @@ void VariableAccess(): {} { } void TypeExpression(): {} { } void PatternExpression(): {} { } void LocalClassStatement(): {} { TypeDeclaration() } + +void softKeyword(String name) #void: {} { + { + if (!getToken(0).getImageCs().contentEquals(name)) + throwParseException("Expecting keyword '" + name + "'"); + } +} diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java index 2fc8e0a895..4ee3a41fcf 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/ast/internal/ReportingStrategy.java @@ -52,7 +52,7 @@ public interface ReportingStrategy { @Override public void report(Node node, String message, Void acc) { - throw new ParseException(message).setFileName(node.getTextDocument().getPathId()); + throw new ParseException(message).withLocation(node); } }; } diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JDKVersionTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JDKVersionTest.java index 0335406aef..7bf3afb56b 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JDKVersionTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JDKVersionTest.java @@ -4,10 +4,11 @@ package net.sourceforge.pmd.lang.java.ast; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; @@ -309,7 +310,7 @@ class JDKVersionTest extends BaseJavaTreeDumpTest { @Test void jdk7PrivateMethodInnerClassInterface2() { ParseException thrown = assertThrows(ParseException.class, () -> java7.parseResource("private_method_in_inner_class_interface2.java")); - assertTrue(thrown.getMessage().contains("line 19")); + assertThat(thrown.getMessage(), containsString("line 19")); } @Override diff --git a/pmd-plsql/etc/grammar/PLSQL.jjt b/pmd-plsql/etc/grammar/PLSQL.jjt index 41fbefea0c..057bdb85c5 100644 --- a/pmd-plsql/etc/grammar/PLSQL.jjt +++ b/pmd-plsql/etc/grammar/PLSQL.jjt @@ -719,9 +719,8 @@ ASTMethodDeclarator MethodDeclarator() : { throw new ParseException("FUNCTION must RETURN a value or must be WRAPPED : found \"" + nextToken.getImage() - + "\" at line "+nextToken.getBeginLine() - + ", column "+nextToken.getBeginColumn() - ); + + "\"" + ).withLocation(nextToken); } } // There is no RETURN for a WRAPPED object @@ -5428,9 +5427,8 @@ void KEYWORD(String id) #void: { if (!token.getImage().equalsIgnoreCase(id)) { String eol = System.getProperty("line.separator", "\n"); - throw new ParseException("Encountered \"" + token.getImage() + "\" at line " - + token.getBeginLine() + ", column " + token.getBeginColumn() + "." + eol - + "Was expecting: " + id); + throw new ParseException("Encountered \"" + token.getImage() + "\" " + + "Was expecting: " + id).withLocation(token); } } } diff --git a/pmd-vm/etc/grammar/Vm.jjt b/pmd-vm/etc/grammar/Vm.jjt index 678ed8de31..5492f2b98e 100644 --- a/pmd-vm/etc/grammar/Vm.jjt +++ b/pmd-vm/etc/grammar/Vm.jjt @@ -66,6 +66,9 @@ import net.sourceforge.pmd.lang.ast.impl.javacc.JavaccToken; */ public class VmParserImpl { + private void throwParseException(String message) { + throw new ParseException(message).withLocation(token); + } /** * Check whether there is a left parenthesis with leading optional * whitespaces. This method is used in the semantic look ahead of @@ -1174,14 +1177,14 @@ VmNode Directive() : else if (!jjtThis.isDirective()) { // not a real directive, but maybe a Velocimacro - throw new ParseException("Invalid arg #" - + argPos + " in VM " + t.getImage(), t); + throwParseException("Invalid arg #" + + argPos + " in VM " + t.getImage()); } /* if #foreach and it's the 2nd arg, ok */ else if (jjtThis.isDirective() && (!"foreach".equals(jjtThis.getDirectiveName()) || argPos != 1)) { - throw new ParseException("Invalid arg #" - + argPos + " in directive " + t.getImage(), t); + throwParseException("Invalid arg #" + + argPos + " in directive " + t.getImage()); } else { @@ -1195,9 +1198,9 @@ VmNode Directive() : { /* if a VM and it's the 0th arg, not ok */ - throw new ParseException("Invalid first arg" + throwParseException("Invalid first arg" + " in #macro() directive - must be a" - + " word token (no ' or double quote surrounding)", t); + + " word token (no ' or double quote surrounding)"); } } @@ -1218,7 +1221,7 @@ VmNode Directive() : { // VELOCITY-667 We get here if we have a "#macro" construct // without parenthesis which is a parse error - throw new ParseException("A macro declaration requires at least a name argument", t); + throwParseException("A macro declaration requires at least a name argument"); } /** From 129b111ee6a5c1b6455f1d742813c5965fddb705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 23:20:49 +0100 Subject: [PATCH 08/14] Rename PathId -> FileId --- .../sourceforge/pmd/cpd/ApexTokenizer.java | 4 +- .../main/java/net/sourceforge/pmd/Report.java | 8 ++-- .../java/net/sourceforge/pmd/RuleSet.java | 4 +- .../net/sourceforge/pmd/RuleViolation.java | 4 +- .../pmd/cache/AbstractAnalysisCache.java | 8 ++-- .../pmd/cache/CachedRuleViolation.java | 12 +++--- .../pmd/cache/FileAnalysisCache.java | 18 ++++----- .../pmd/internal/util/FileCollectionUtil.java | 4 +- .../pmd/lang/ast/FileAnalysisException.java | 12 +++--- .../pmd/lang/ast/TokenMgrError.java | 6 +-- .../pmd/lang/document/BaseMappedDocument.java | 2 +- .../pmd/lang/document/CpdCompat.java | 2 +- .../pmd/lang/document/FileCollector.java | 26 ++++++------ .../document/{PathId.java => FileId.java} | 40 +++++++++---------- .../pmd/lang/document/FileLocation.java | 14 +++---- .../pmd/lang/document/NioTextFile.java | 10 ++--- .../pmd/lang/document/ReaderTextFile.java | 14 +++---- .../pmd/lang/document/RootTextDocument.java | 12 +++--- .../pmd/lang/document/StringTextFile.java | 14 +++---- .../pmd/lang/document/TextDocument.java | 10 ++--- .../pmd/lang/document/TextFile.java | 32 +++++++-------- .../pmd/lang/document/TextFileBuilder.java | 34 ++++++++-------- .../pmd/renderers/AbstractRenderer.java | 6 +-- .../pmd/renderers/FileNameRenderer.java | 6 +-- .../pmd/renderers/HTMLRenderer.java | 4 +- .../pmd/reporting/GlobalAnalysisListener.java | 4 +- .../pmd/util/treeexport/TreeExporter.java | 4 +- .../net/sourceforge/pmd/AbstractRuleTest.java | 10 ++--- .../sourceforge/pmd/DummyParsingHelper.java | 8 ++-- .../net/sourceforge/pmd/PmdAnalysisTest.java | 8 ++-- .../java/net/sourceforge/pmd/ReportTest.java | 6 +-- .../pmd/RuleViolationComparatorTest.java | 4 +- .../sourceforge/pmd/RuleViolationTest.java | 8 ++-- .../pmd/cache/FileAnalysisCacheTest.java | 4 +- .../token/internal/BaseTokenFilterTest.java | 4 +- .../sourceforge/pmd/lang/ast/DummyNode.java | 4 +- .../pmd/lang/document/FileCollectorTest.java | 12 +++--- .../pmd/lang/document/FileLocationTest.java | 2 +- .../pmd/lang/document/SimpleTestTextFile.java | 4 +- .../pmd/lang/document/TextFilesTest.java | 18 ++++----- .../pmd/processor/GlobalListenerTest.java | 8 ++-- .../processor/MultiThreadProcessorTest.java | 6 +-- .../pmd/processor/PmdRunnableTest.java | 4 +- .../pmd/renderers/AbstractRendererTest.java | 10 ++--- .../pmd/renderers/XMLRendererTest.java | 4 +- .../pmd/renderers/XSLTRendererTest.java | 4 +- .../pmd/cpd/CppCharStreamTest.java | 4 +- .../pmd/lang/html/ast/HtmlTokenizer.java | 4 +- .../pmd/lang/java/ast/ParserCornersTest.java | 4 +- .../pmd/cpd/test/CpdTextComparisonTest.kt | 4 +- .../pmd/lang/ast/test/BaseParsingHelper.kt | 12 +++--- .../pmd/test/BaseTextComparisonTest.kt | 6 +-- .../pmd/testframework/RuleTst.java | 4 +- 53 files changed, 240 insertions(+), 240 deletions(-) rename pmd-core/src/main/java/net/sourceforge/pmd/lang/document/{PathId.java => FileId.java} (80%) diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java b/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java index e449fe0a2e..f6dd4496af 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/cpd/ApexTokenizer.java @@ -13,7 +13,7 @@ import org.antlr.runtime.Token; import net.sourceforge.pmd.lang.apex.ApexJorjeLogging; import net.sourceforge.pmd.lang.ast.TokenMgrError; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import apex.jorje.parser.impl.ApexLexer; @@ -43,7 +43,7 @@ public class ApexTokenizer implements Tokenizer { ApexLexer lexer = new ApexLexer(ass) { @Override public void emitErrorMessage(String msg) { - throw new TokenMgrError(getLine(), getCharPositionInLine(), PathId.fromPathLikeString(getSourceName()), msg, null); + throw new TokenMgrError(getLine(), getCharPositionInLine(), FileId.fromPathLikeString(getSourceName()), msg, null); } }; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java index 4d197011b0..33c2257f44 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/Report.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/Report.java @@ -18,7 +18,7 @@ import java.util.function.Predicate; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.annotation.InternalApi; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.AbstractAccumulatingRenderer; import net.sourceforge.pmd.reporting.FileAnalysisListener; @@ -103,7 +103,7 @@ public final class Report { public static class ProcessingError { private final Throwable error; - private final PathId file; + private final FileId file; /** * Creates a new processing error @@ -113,7 +113,7 @@ public final class Report { * @param file * the file during which the error occurred */ - public ProcessingError(Throwable error, PathId file) { + public ProcessingError(Throwable error, FileId file) { this.error = error; this.file = file; } @@ -133,7 +133,7 @@ public final class Report { } } - public PathId getFileId() { + public FileId getFileId() { return file; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index 8affadcbe2..664161f250 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -24,7 +24,7 @@ import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.cache.ChecksumAware; import net.sourceforge.pmd.internal.util.PredicateUtil; import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.RuleReference; import net.sourceforge.pmd.lang.rule.XPathRule; @@ -610,7 +610,7 @@ public class RuleSet implements ChecksumAware { */ // TODO get rid of this overload @InternalApi - public boolean applies(PathId qualFileName) { + public boolean applies(FileId qualFileName) { return filter.test(qualFileName.toAbsolutePath()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java index 881c65b73c..9caa906250 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java @@ -9,7 +9,7 @@ import java.util.Map; import net.sourceforge.pmd.annotation.DeprecatedUntil700; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; /** * A RuleViolation is created by a Rule when it identifies a violation of the @@ -83,7 +83,7 @@ public interface RuleViolation { /** * Return the ID of the file where the violation was found. */ - default PathId getFileId() { + default FileId getFileId() { return getLocation().getFileId(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java index c93b52c49b..b687a6106e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java @@ -35,7 +35,7 @@ import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; import net.sourceforge.pmd.cache.internal.ClasspathFingerprinter; import net.sourceforge.pmd.internal.util.IOUtil; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.reporting.FileAnalysisListener; @@ -52,8 +52,8 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { protected static final Logger LOG = LoggerFactory.getLogger(AbstractAnalysisCache.class); protected static final ClasspathFingerprinter FINGERPRINTER = new ClasspathFingerprinter(); protected final String pmdVersion; - protected final ConcurrentMap fileResultsCache = new ConcurrentHashMap<>(); - protected final ConcurrentMap updatedResultsCache = new ConcurrentHashMap<>(); + protected final ConcurrentMap fileResultsCache = new ConcurrentHashMap<>(); + protected final ConcurrentMap updatedResultsCache = new ConcurrentHashMap<>(); protected final CachedRuleMapper ruleMapper = new CachedRuleMapper(); protected long rulesetChecksum; protected long auxClassPathChecksum; @@ -218,7 +218,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public FileAnalysisListener startFileAnalysis(TextDocument file) { - final PathId fileName = file.getPathId(); + final FileId fileName = file.getPathId(); return new FileAnalysisListener() { @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java index fb90bb84e9..f53d56492e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/CachedRuleViolation.java @@ -17,8 +17,8 @@ import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.annotation.InternalApi; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.util.StringUtil; @@ -42,13 +42,13 @@ public final class CachedRuleViolation implements RuleViolation { private final FileLocation location; private CachedRuleViolation(final CachedRuleMapper mapper, final String description, - final PathId filePathId, final String ruleClassName, final String ruleName, + final FileId fileFileId, final String ruleClassName, final String ruleName, final String ruleTargetLanguage, final int beginLine, final int beginColumn, final int endLine, final int endColumn, final Map additionalInfo) { this.mapper = mapper; this.description = description; - this.location = FileLocation.range(filePathId, TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); + this.location = FileLocation.range(fileFileId, TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); this.ruleClassName = ruleClassName; this.ruleName = ruleName; this.ruleTargetLanguage = ruleTargetLanguage; @@ -80,7 +80,7 @@ public final class CachedRuleViolation implements RuleViolation { * Helper method to load a {@link CachedRuleViolation} from an input stream. * * @param stream The stream from which to load the violation. - * @param filePathId The name of the file on which this rule was reported. + * @param fileFileId The name of the file on which this rule was reported. * @param mapper The mapper to be used to obtain rule instances from the active rulesets. * * @return The loaded rule violation. @@ -88,7 +88,7 @@ public final class CachedRuleViolation implements RuleViolation { /* package */ static CachedRuleViolation loadFromStream( DataInputStream stream, - PathId filePathId, CachedRuleMapper mapper) throws IOException { + FileId fileFileId, CachedRuleMapper mapper) throws IOException { String description = stream.readUTF(); String ruleClassName = stream.readUTF(); @@ -99,7 +99,7 @@ public final class CachedRuleViolation implements RuleViolation { int endLine = stream.readInt(); int endColumn = stream.readInt(); Map additionalInfo = readAdditionalInfo(stream); - return new CachedRuleViolation(mapper, description, filePathId, ruleClassName, ruleName, ruleTargetLanguage, + return new CachedRuleViolation(mapper, description, fileFileId, ruleClassName, ruleName, ruleTargetLanguage, beginLine, beginColumn, endLine, endColumn, additionalInfo); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java index ab960b60f2..b81ef227c6 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java @@ -25,7 +25,7 @@ import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.benchmark.TimeTracker; import net.sourceforge.pmd.benchmark.TimedOperation; import net.sourceforge.pmd.benchmark.TimedOperationCategory; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** @@ -61,9 +61,9 @@ public class FileAnalysisCache extends AbstractAnalysisCache { * @param cacheFile The file which backs the file analysis cache. */ private void loadFromFile(final File cacheFile, Set files) { - Map idMap = + Map idMap = files.stream().map(TextFile::getPathId) - .collect(Collectors.toMap(PathId::toUriString, id -> id)); + .collect(Collectors.toMap(FileId::toUriString, id -> id)); try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "load")) { if (cacheExists()) { @@ -84,21 +84,21 @@ public class FileAnalysisCache extends AbstractAnalysisCache { // Cached results while (inputStream.available() > 0) { final String filePathId = inputStream.readUTF(); - PathId pathId = idMap.get(filePathId); - if (pathId == null) { + FileId fileId = idMap.get(filePathId); + if (fileId == null) { LOG.debug("File {} is in the cache but is not part of the analysis", filePathId); - pathId = PathId.fromPathLikeString(filePathId); + fileId = FileId.fromPathLikeString(filePathId); } final long checksum = inputStream.readLong(); final int countViolations = inputStream.readInt(); final List violations = new ArrayList<>(countViolations); for (int i = 0; i < countViolations; i++) { - violations.add(CachedRuleViolation.loadFromStream(inputStream, pathId, ruleMapper)); + violations.add(CachedRuleViolation.loadFromStream(inputStream, fileId, ruleMapper)); } - fileResultsCache.put(pathId, new AnalysisResult(checksum, violations)); + fileResultsCache.put(fileId, new AnalysisResult(checksum, violations)); } LOG.debug("Analysis cache loaded from {}", cacheFile); @@ -144,7 +144,7 @@ public class FileAnalysisCache extends AbstractAnalysisCache { outputStream.writeLong(auxClassPathChecksum); outputStream.writeLong(executionClassPathChecksum); - for (final Map.Entry resultEntry : updatedResultsCache.entrySet()) { + for (final Map.Entry resultEntry : updatedResultsCache.entrySet()) { final List violations = resultEntry.getValue().getViolations(); outputStream.writeUTF(resultEntry.getKey().toUriString()); // the path id diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java b/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java index 782de1e71b..aea6bb238a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/internal/util/FileCollectionUtil.java @@ -17,7 +17,7 @@ import org.slf4j.LoggerFactory; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.lang.document.FileCollector; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.util.database.DBMSMetadata; import net.sourceforge.pmd.util.database.DBURI; import net.sourceforge.pmd.util.database.SourceObject; @@ -127,7 +127,7 @@ public final class FileCollectionUtil { try (Reader sourceCode = dbmsMetadata.getSourceCode(sourceObject)) { String source = IOUtil.readToString(sourceCode); - collector.addSourceFile(PathId.fromPathLikeString(falseFilePath), source); + collector.addSourceFile(FileId.fromPathLikeString(falseFilePath), source); } catch (SQLException ex) { collector.getReporter().warnEx("Cannot get SourceCode for {} - skipping ...", new Object[] { falseFilePath }, diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java index 6263d3a945..3e2f780aca 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java @@ -10,8 +10,8 @@ import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; /** * An exception that occurs while processing a file. Subtypes include @@ -24,7 +24,7 @@ import net.sourceforge.pmd.lang.document.PathId; */ public class FileAnalysisException extends RuntimeException { - private PathId fileId = PathId.UNKNOWN; + private FileId fileId = FileId.UNKNOWN; public FileAnalysisException() { super(); @@ -42,19 +42,19 @@ public class FileAnalysisException extends RuntimeException { super(message, cause); } - public FileAnalysisException setFileId(PathId fileId) { + public FileAnalysisException setFileId(FileId fileId) { this.fileId = Objects.requireNonNull(fileId); return this; } protected boolean hasFileName() { - return !PathId.UNKNOWN.equals(fileId); + return !FileId.UNKNOWN.equals(fileId); } /** * The name of the file in which the error occurred. */ - public @NonNull PathId getFileId() { + public @NonNull FileId getFileId() { return fileId; } @@ -94,7 +94,7 @@ public class FileAnalysisException extends RuntimeException { * * @return An exception */ - public static FileAnalysisException wrap(@NonNull PathId filename, @NonNull String message, @NonNull Throwable cause) { + public static FileAnalysisException wrap(@NonNull FileId filename, @NonNull String message, @NonNull Throwable cause) { if (cause instanceof FileAnalysisException) { return ((FileAnalysisException) cause).setFileId(filename); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java index 1b24be4fed..ba2bf564a1 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java @@ -9,7 +9,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.util.StringUtil; /** @@ -29,7 +29,7 @@ public final class TokenMgrError extends FileAnalysisException { * @param message Message of the error * @param cause Cause of the error, if any */ - public TokenMgrError(int line, int column, @Nullable PathId filename, String message, @Nullable Throwable cause) { + public TokenMgrError(int line, int column, @Nullable FileId filename, String message, @Nullable Throwable cause) { super(message, cause); this.line = line; this.column = column; @@ -74,7 +74,7 @@ public final class TokenMgrError extends FileAnalysisException { * @return A new exception */ @Override - public TokenMgrError setFileId(PathId fileId) { + public TokenMgrError setFileId(FileId fileId) { super.setFileId(fileId); return this; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java index 8e5aac3ba1..45e08af5f0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java @@ -26,7 +26,7 @@ abstract class BaseMappedDocument implements TextDocument { } @Override - public PathId getPathId() { + public FileId getPathId() { return base.getPathId(); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java index 60732a4e2d..2342232d47 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/CpdCompat.java @@ -33,7 +33,7 @@ public final class CpdCompat { public static TextFile cpdCompat(SourceCode sourceCode) { return TextFile.forCharSeq( sourceCode.getCodeBuffer(), - PathId.fromPathLikeString(sourceCode.getFileName()), + FileId.fromPathLikeString(sourceCode.getFileName()), dummyVersion() ); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index 1c2da3d80c..a2458737af 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -64,13 +64,13 @@ public final class FileCollector implements AutoCloseable { private Charset charset = StandardCharsets.UTF_8; private final LanguageVersionDiscoverer discoverer; private final MessageReporter reporter; - private final PathId outerFsPath; + private final FileId outerFsPath; private final List relativizeRootPaths = new ArrayList<>(); private boolean closed; // construction - private FileCollector(LanguageVersionDiscoverer discoverer, MessageReporter reporter, PathId outerFsPath) { + private FileCollector(LanguageVersionDiscoverer discoverer, MessageReporter reporter, FileId outerFsPath) { this.discoverer = discoverer; this.reporter = reporter; this.outerFsPath = outerFsPath; @@ -201,13 +201,13 @@ public final class FileCollector implements AutoCloseable { * * @return True if the file has been added */ - public boolean addSourceFile(PathId pathId, String sourceContents) { + public boolean addSourceFile(FileId fileId, String sourceContents) { AssertionUtil.requireParamNotNull("sourceContents", sourceContents); - AssertionUtil.requireParamNotNull("pathId", pathId); + AssertionUtil.requireParamNotNull("pathId", fileId); - LanguageVersion version = discoverLanguage(pathId.getFileName()); + LanguageVersion version = discoverLanguage(fileId.getFileName()); return version != null - && addFileImpl(TextFile.builderForCharSeq(sourceContents, pathId, version) + && addFileImpl(TextFile.builderForCharSeq(sourceContents, fileId, version) .setParentFsPath(outerFsPath) .build()); } @@ -265,7 +265,7 @@ public final class FileCollector implements AutoCloseable { * *

package private for test only

*/ - static String getDisplayName(PathId file, List relativizeRoots) { + static String getDisplayName(FileId file, List relativizeRoots) { String best = file.toAbsolutePath(); for (Path root : relativizeRoots) { if (isFileSystemRoot(root)) { @@ -432,7 +432,7 @@ public final class FileCollector implements AutoCloseable { /** A collector that prefixes the display name of the files it will contain with the path of the zip. */ @Experimental private FileCollector newZipCollector(Path zipFilePath) { - return new FileCollector(discoverer, reporter, PathId.forPath(zipFilePath)); + return new FileCollector(discoverer, reporter, FileId.forPath(zipFilePath)); } // configuration @@ -469,15 +469,15 @@ public final class FileCollector implements AutoCloseable { private final List relativizeRootPaths = new ArrayList<>(FileCollector.this.relativizeRootPaths); @Override - public String getDisplayName(PathId pathId) { - String localDisplayName = getLocalDisplayName(pathId); - if (pathId.getParentFsPath() != null) { - return getDisplayName(pathId.getParentFsPath()) + "!" + localDisplayName; + public String getDisplayName(FileId fileId) { + String localDisplayName = getLocalDisplayName(fileId); + if (fileId.getParentFsPath() != null) { + return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; } return localDisplayName; } - private String getLocalDisplayName(PathId file) { + private String getLocalDisplayName(FileId file) { if (!relativizeRootPaths.isEmpty()) { return FileCollector.getDisplayName(file, relativizeRootPaths); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java similarity index 80% rename from pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java rename to pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java index c532f1deea..3e438755aa 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/PathId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java @@ -14,15 +14,15 @@ import org.checkerframework.checker.nullness.qual.Nullable; * * @author Clément Fournier */ -public interface PathId extends Comparable { +public interface FileId extends Comparable { /** * The name used for a file that has no name. This is mostly only * relevant for unit tests. */ - PathId UNKNOWN = fromPathLikeString("(unknown file)"); + FileId UNKNOWN = fromPathLikeString("(unknown file)"); - @Nullable PathId getParentFsPath(); + @Nullable FileId getParentFsPath(); String toUriString(); @@ -38,11 +38,11 @@ public interface PathId extends Comparable { @Override - default int compareTo(PathId o) { + default int compareTo(FileId o) { return this.toUriString().compareTo(o.toUriString()); } - PathId STDIN = new PathId() { + FileId STDIN = new FileId() { @Override public String toAbsolutePath() { return "stdin"; @@ -64,18 +64,18 @@ public interface PathId extends Comparable { } @Override - public @Nullable PathId getParentFsPath() { + public @Nullable FileId getParentFsPath() { return null; } }; - static PathId fromPathLikeString(String str) { + static FileId fromPathLikeString(String str) { String[] segments = str.split("[/\\\\]"); if (segments.length == 0) { throw new IllegalArgumentException("Invalid path id: '" + str + "'"); } String fname = segments[segments.length - 1]; - return new PathId() { + return new FileId() { @Override public String toAbsolutePath() { return Paths.get(str).toAbsolutePath().toString(); @@ -100,8 +100,8 @@ public interface PathId extends Comparable { @Override public boolean equals(Object obj) { - return obj instanceof PathId - && ((PathId) obj).toUriString().equals(this.toUriString()); + return obj instanceof FileId + && ((FileId) obj).toUriString().equals(this.toUriString()); } @Override @@ -110,14 +110,14 @@ public interface PathId extends Comparable { } @Override - public @Nullable PathId getParentFsPath() { + public @Nullable FileId getParentFsPath() { return null; } }; } - static PathId forPath(Path path, @Nullable PathId fsPath) { - return new PathId() { + static FileId forPath(Path path, @Nullable FileId fsPath) { + return new FileId() { @Override public String toAbsolutePath() { return path.normalize().toAbsolutePath().toString(); @@ -139,14 +139,14 @@ public interface PathId extends Comparable { } @Override - public @Nullable PathId getParentFsPath() { + public @Nullable FileId getParentFsPath() { return fsPath; } @Override public boolean equals(Object obj) { - return obj instanceof PathId - && ((PathId) obj).toUriString().equals(this.toUriString()); + return obj instanceof FileId + && ((FileId) obj).toUriString().equals(this.toUriString()); } @Override @@ -161,14 +161,14 @@ public interface PathId extends Comparable { }; } - static PathId forPath(Path path) { + static FileId forPath(Path path) { return forPath(path, null); } - static PathId asChildOf(PathId self, PathId parentFsPath) { - return new PathId() { + static FileId asChildOf(FileId self, FileId parentFsPath) { + return new FileId() { @Override - public @Nullable PathId getParentFsPath() { + public @Nullable FileId getParentFsPath() { return parentFsPath; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java index d7f7864776..e480e4817d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileLocation.java @@ -41,14 +41,14 @@ public final class FileLocation { private final int endLine; private final int beginColumn; private final int endColumn; - private final PathId fileName; + private final FileId fileName; private final @Nullable TextRegion region; - FileLocation(PathId fileName, int beginLine, int beginColumn, int endLine, int endColumn) { + FileLocation(FileId fileName, int beginLine, int beginColumn, int endLine, int endColumn) { this(fileName, beginLine, beginColumn, endLine, endColumn, null); } - FileLocation(PathId fileName, int beginLine, int beginColumn, int endLine, int endColumn, @Nullable TextRegion region) { + FileLocation(FileId fileName, int beginLine, int beginColumn, int endLine, int endColumn, @Nullable TextRegion region) { this.fileName = Objects.requireNonNull(fileName); this.beginLine = AssertionUtil.requireOver1("Begin line", beginLine); this.endLine = AssertionUtil.requireOver1("End line", endLine); @@ -70,7 +70,7 @@ public final class FileLocation { /** * File name of this position. */ - public PathId getFileId() { + public FileId getFileId() { return fileName; } @@ -144,7 +144,7 @@ public final class FileLocation { * @throws IllegalArgumentException If the line and column are not correctly ordered * @throws IllegalArgumentException If the start offset or length are negative */ - public static FileLocation range(PathId fileName, TextRange2d range2d) { + public static FileLocation range(FileId fileName, TextRange2d range2d) { TextPos2d start = range2d.getStartPos(); TextPos2d end = range2d.getEndPos(); return new FileLocation(fileName, @@ -163,9 +163,9 @@ public final class FileLocation { * * @return A new location * - * @throws IllegalArgumentException See {@link #range(PathId, TextRange2d)} + * @throws IllegalArgumentException See {@link #range(FileId, TextRange2d)} */ - public static FileLocation caret(PathId fileName, int line, int column) { + public static FileLocation caret(FileId fileName, int line, int column) { return new FileLocation(fileName, line, column, line, column); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java index 197c197f90..7f7b517078 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java @@ -26,11 +26,11 @@ class NioTextFile extends BaseCloseable implements TextFile { private final Path path; private final Charset charset; private final LanguageVersion languageVersion; - private final PathId pathId; + private final FileId fileId; private boolean readOnly; NioTextFile(Path path, - @Nullable PathId parentFsPath, + @Nullable FileId parentFsPath, Charset charset, LanguageVersion languageVersion, boolean readOnly) { @@ -44,7 +44,7 @@ class NioTextFile extends BaseCloseable implements TextFile { this.languageVersion = languageVersion; // using the URI here, that handles files inside zip archives automatically (schema "jar:file:...!/path/inside/zip") // normalization ensures cannonical paths - this.pathId = PathId.forPath(path, parentFsPath); + this.fileId = FileId.forPath(path, parentFsPath); } @Override @@ -53,8 +53,8 @@ class NioTextFile extends BaseCloseable implements TextFile { } @Override - public PathId getPathId() { - return pathId; + public FileId getPathId() { + return fileId; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java index b31ccaf776..a1583903ae 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java @@ -17,23 +17,23 @@ import net.sourceforge.pmd.util.AssertionUtil; */ class ReaderTextFile implements TextFile { - private final PathId pathId; + private final FileId fileId; private final LanguageVersion languageVersion; private final Reader reader; - ReaderTextFile(Reader reader, @NonNull PathId pathId, LanguageVersion languageVersion) { + ReaderTextFile(Reader reader, @NonNull FileId fileId, LanguageVersion languageVersion) { AssertionUtil.requireParamNotNull("reader", reader); - AssertionUtil.requireParamNotNull("path id", pathId); + AssertionUtil.requireParamNotNull("path id", fileId); AssertionUtil.requireParamNotNull("language version", languageVersion); this.reader = reader; this.languageVersion = languageVersion; - this.pathId = pathId; + this.fileId = fileId; } @Override - public PathId getPathId() { - return pathId; + public FileId getPathId() { + return fileId; } @Override @@ -53,7 +53,7 @@ class ReaderTextFile implements TextFile { @Override public String toString() { - return "ReaderTextFile[" + pathId + "]"; + return "ReaderTextFile[" + fileId + "]"; } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java index 8f0b7d29ca..afbe72bc37 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java @@ -27,16 +27,16 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { private final LanguageVersion langVersion; - private final PathId pathId; + private final FileId fileId; RootTextDocument(TextFile backend) throws IOException { this.backend = backend; this.content = backend.readContents(); this.langVersion = backend.getLanguageVersion(); - this.pathId = backend.getPathId(); + this.fileId = backend.getPathId(); Objects.requireNonNull(langVersion, "Null language version for file " + backend); - Objects.requireNonNull(pathId, "Null path id for file " + backend); + Objects.requireNonNull(fileId, "Null path id for file " + backend); } @Override @@ -45,8 +45,8 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { } @Override - public PathId getPathId() { - return pathId; + public FileId getPathId() { + return fileId; } @Override @@ -71,7 +71,7 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { : positioner.lineColFromOffset(region.getEndOffset(), false); return new FileLocation( - pathId, + fileId, bpos.getLine(), bpos.getColumn(), epos.getLine(), diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java index 58935a070c..b78ab18615 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java @@ -16,17 +16,17 @@ import net.sourceforge.pmd.util.StringUtil; class StringTextFile implements TextFile { private final TextFileContent content; - private final PathId pathId; + private final FileId fileId; private final LanguageVersion languageVersion; - StringTextFile(CharSequence source, PathId pathId, LanguageVersion languageVersion) { + StringTextFile(CharSequence source, FileId fileId, LanguageVersion languageVersion) { AssertionUtil.requireParamNotNull("source text", source); - AssertionUtil.requireParamNotNull("file name", pathId); + AssertionUtil.requireParamNotNull("file name", fileId); AssertionUtil.requireParamNotNull("language version", languageVersion); this.languageVersion = languageVersion; this.content = TextFileContent.fromCharSeq(source); - this.pathId = pathId; + this.fileId = fileId; } @Override @@ -36,12 +36,12 @@ class StringTextFile implements TextFile { @Override public @NonNull String getDisplayName() { - return pathId.toUriString(); + return fileId.toUriString(); } @Override - public PathId getPathId() { - return pathId; + public FileId getPathId() { + return fileId; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java index 6af1a2cbf1..7aa6ea5dd2 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java @@ -88,7 +88,7 @@ public interface TextDocument extends Closeable { /** * Returns {@link TextFile#getPathId()} for the text file backing this document. */ - PathId getPathId(); + FileId getPathId(); /** * Returns {@link TextFile#getDisplayName()} for the text file backing this document. @@ -263,10 +263,10 @@ public interface TextDocument extends Closeable { /** * Returns a read-only document for the given text. * - * @see TextFile#forCharSeq(CharSequence, PathId, LanguageVersion) + * @see TextFile#forCharSeq(CharSequence, FileId, LanguageVersion) */ static TextDocument readOnlyString(final CharSequence source, LanguageVersion lv) { - return readOnlyString(source, PathId.UNKNOWN, lv); + return readOnlyString(source, FileId.UNKNOWN, lv); } /** @@ -276,10 +276,10 @@ public interface TextDocument extends Closeable { * but doesn't throw {@link IOException}, as such text files will * not throw. * - * @see TextFile#forCharSeq(CharSequence, PathId, LanguageVersion) + * @see TextFile#forCharSeq(CharSequence, FileId, LanguageVersion) */ @SuppressWarnings("PMD.CloseResource") - static TextDocument readOnlyString(@NonNull CharSequence source, @NonNull PathId filename, @NonNull LanguageVersion lv) { + static TextDocument readOnlyString(@NonNull CharSequence source, @NonNull FileId filename, @NonNull LanguageVersion lv) { TextFile textFile = TextFile.forCharSeq(source, filename, lv); try { return create(textFile); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index ac1ec1279e..8aea8fa217 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -70,7 +70,7 @@ public interface TextFile extends Closeable { *

Basically this may be implemented as a URL, or a file path. It * is used to index violation caches. */ - PathId getPathId(); + FileId getPathId(); /** @@ -185,13 +185,13 @@ public interface TextFile extends Closeable { * may not produce exactly the same char sequence. * * @param charseq Text of the file - * @param pathId File name to use as path id + * @param fileId File name to use as path id * @param languageVersion Language version * * @throws NullPointerException If any parameter is null */ - static TextFile forCharSeq(CharSequence charseq, PathId pathId, LanguageVersion languageVersion) { - return builderForCharSeq(charseq, pathId, languageVersion) + static TextFile forCharSeq(CharSequence charseq, FileId fileId, LanguageVersion languageVersion) { + return builderForCharSeq(charseq, fileId, languageVersion) .build(); } @@ -201,13 +201,13 @@ public interface TextFile extends Closeable { * may not produce exactly the same char sequence. * * @param charseq Text of the file - * @param pathId File name to use as path id + * @param fileId File name to use as path id * @param languageVersion Language version * * @throws NullPointerException If any parameter is null */ - static TextFileBuilder builderForCharSeq(CharSequence charseq, PathId pathId, LanguageVersion languageVersion) { - return new ForCharSeq(charseq, pathId, languageVersion); + static TextFileBuilder builderForCharSeq(CharSequence charseq, FileId fileId, LanguageVersion languageVersion) { + return new ForCharSeq(charseq, fileId, languageVersion); } /** @@ -218,13 +218,13 @@ public interface TextFile extends Closeable { * throw an {@link IOException}. * * @param reader Text of the file - * @param pathId File name to use as path id + * @param fileId File name to use as path id * @param languageVersion Language version * * @throws NullPointerException If any parameter is null */ - static TextFile forReader(Reader reader, PathId pathId, LanguageVersion languageVersion) { - return builderForReader(reader, pathId, languageVersion) + static TextFile forReader(Reader reader, FileId fileId, LanguageVersion languageVersion) { + return builderForReader(reader, fileId, languageVersion) .build(); } @@ -236,13 +236,13 @@ public interface TextFile extends Closeable { * throw an {@link IOException}. * * @param reader Text of the file - * @param pathId File name to use as path id + * @param fileId File name to use as path id * @param languageVersion Language version * * @throws NullPointerException If any parameter is null */ - static TextFileBuilder builderForReader(Reader reader, PathId pathId, LanguageVersion languageVersion) { - return new ForReader(languageVersion, reader, pathId); + static TextFileBuilder builderForReader(Reader reader, FileId fileId, LanguageVersion languageVersion) { + return new ForReader(languageVersion, reader, fileId); } /** @@ -257,7 +257,7 @@ public interface TextFile extends Closeable { @DeprecatedUntil700 static TextFile dataSourceCompat(DataSource ds, PMDConfiguration config) { String pathId = ds.getNiceFileName(false, null); - PathId pathId2 = PathId.fromPathLikeString(pathId); + FileId fileId2 = FileId.fromPathLikeString(pathId); LanguageVersion languageVersion = config.getLanguageVersionOfFile(pathId); if (languageVersion == null) { throw new NullPointerException("no language version detected for " + pathId); @@ -271,8 +271,8 @@ public interface TextFile extends Closeable { } @Override - public PathId getPathId() { - return pathId2; + public FileId getPathId() { + return fileId2; } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java index 69382079de..c6dd94116f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFileBuilder.java @@ -21,7 +21,7 @@ import net.sourceforge.pmd.util.AssertionUtil; public abstract class TextFileBuilder { protected final LanguageVersion languageVersion; - protected PathId parentFsId; + protected FileId parentFsId; TextFileBuilder(LanguageVersion languageVersion) { this.languageVersion = AssertionUtil.requireParamNotNull("language version", languageVersion); @@ -38,8 +38,8 @@ public abstract class TextFileBuilder { return this; } - public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { - parentFsId = pathId; + public TextFileBuilder setParentFsPath(@Nullable FileId fileId) { + parentFsId = fileId; return this; } @@ -76,47 +76,47 @@ public abstract class TextFileBuilder { static class ForCharSeq extends TextFileBuilder { private final CharSequence charSequence; - private PathId pathId; + private FileId fileId; - ForCharSeq(CharSequence charSequence, PathId pathId, LanguageVersion languageVersion) { + ForCharSeq(CharSequence charSequence, FileId fileId, LanguageVersion languageVersion) { super(languageVersion); this.charSequence = AssertionUtil.requireParamNotNull("charseq", charSequence); - this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); + this.fileId = AssertionUtil.requireParamNotNull("path ID", fileId); } @Override - public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { - this.pathId = PathId.asChildOf(this.pathId, pathId); - return super.setParentFsPath(pathId); + public TextFileBuilder setParentFsPath(@Nullable FileId fileId) { + this.fileId = FileId.asChildOf(this.fileId, fileId); + return super.setParentFsPath(fileId); } @Override public TextFile build() { - return new StringTextFile(charSequence, pathId, languageVersion); + return new StringTextFile(charSequence, fileId, languageVersion); } } static class ForReader extends TextFileBuilder { private final Reader reader; - private PathId pathId; + private FileId fileId; - ForReader(LanguageVersion languageVersion, Reader reader, PathId pathId) { + ForReader(LanguageVersion languageVersion, Reader reader, FileId fileId) { super(languageVersion); this.reader = AssertionUtil.requireParamNotNull("reader", reader); - this.pathId = AssertionUtil.requireParamNotNull("path ID", pathId); + this.fileId = AssertionUtil.requireParamNotNull("path ID", fileId); } @Override - public TextFileBuilder setParentFsPath(@Nullable PathId pathId) { - this.pathId = PathId.asChildOf(this.pathId, pathId); - return super.setParentFsPath(pathId); + public TextFileBuilder setParentFsPath(@Nullable FileId fileId) { + this.fileId = FileId.asChildOf(this.fileId, fileId); + return super.setParentFsPath(fileId); } @Override public TextFile build() { - return new ReaderTextFile(reader, pathId, languageVersion); + return new ReaderTextFile(reader, fileId, languageVersion); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java index 733e751cea..9f532e623b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java @@ -9,7 +9,7 @@ import java.io.Writer; import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.internal.util.IOUtil; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.properties.AbstractPropertySource; /** @@ -21,7 +21,7 @@ public abstract class AbstractRenderer extends AbstractPropertySource implements protected boolean showSuppressedViolations = true; protected PrintWriter writer; - private FileNameRenderer fileNameRenderer = PathId::getOriginalPath; + private FileNameRenderer fileNameRenderer = FileId::getOriginalPath; public AbstractRenderer(String name, String description) { this.name = name; @@ -74,7 +74,7 @@ public abstract class AbstractRenderer extends AbstractPropertySource implements * is without the directory prefix of the directories, that have been analyzed. * If the option "shortnames" is not enabled, then the fileId is returned as-is. */ - protected String determineFileName(PathId fileId) { + protected String determineFileName(FileId fileId) { return fileNameRenderer.getDisplayName(fileId); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java index 21100712a1..72a9c0634f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java @@ -4,18 +4,18 @@ package net.sourceforge.pmd.renderers; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** - * Renders a {@link PathId} into a display name. + * Renders a {@link FileId} into a display name. * * @author Clément Fournier */ public interface FileNameRenderer { - String getDisplayName(PathId pathId); + String getDisplayName(FileId fileId); default String getDisplayName(TextFile textFile) { return getDisplayName(textFile.getPathId()); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java index b33aaba855..9b654bc325 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/HTMLRenderer.java @@ -17,7 +17,7 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Rule; import net.sourceforge.pmd.RuleViolation; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.properties.StringProperty; @@ -154,7 +154,7 @@ public class HTMLRenderer extends AbstractIncrementingRenderer { } } - private String renderFileName(PathId fileId, int beginLine) { + private String renderFileName(FileId fileId, int beginLine) { return maybeWrap(StringEscapeUtils.escapeHtml4(determineFileName(fileId)), linePrefix == null || beginLine < 0 ? "" : linePrefix + beginLine); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java index d456bdf7d0..c7689c3b1c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java @@ -17,7 +17,7 @@ import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.ast.FileAnalysisException; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.util.AssertionUtil; @@ -198,7 +198,7 @@ public interface GlobalAnalysisListener extends AutoCloseable { @Override public FileAnalysisListener startFileAnalysis(TextFile file) { - PathId filename = file.getPathId(); // capture the filename instead of the file + FileId filename = file.getPathId(); // capture the filename instead of the file return new FileAnalysisListener() { @Override public void onRuleViolation(RuleViolation violation) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java index 509051713a..4028683c09 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/treeexport/TreeExporter.java @@ -23,7 +23,7 @@ import net.sourceforge.pmd.lang.ast.Parser; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.RootNode; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.xpath.Attribute; @@ -74,7 +74,7 @@ public class TreeExporter { TextFile textFile; if (configuration.isReadStdin()) { io.stderr.println("Reading from stdin..."); - textFile = TextFile.forReader(readFromSystemIn(), PathId.STDIN, langVersion); + textFile = TextFile.forReader(readFromSystemIn(), FileId.STDIN, langVersion); } else { textFile = TextFile.forPath(configuration.getFile(), configuration.getSourceEncoding(), langVersion); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java index 035a7dea12..ce4095ad38 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; import net.sourceforge.pmd.properties.PropertyDescriptor; @@ -78,7 +78,7 @@ class AbstractRuleTest { void testCreateRV() { MyRule r = new MyRule(); r.setRuleSetName("foo"); - DummyRootNode s = helper.parse("abc()", PathId.fromPathLikeString("abc")); + DummyRootNode s = helper.parse("abc()", FileId.fromPathLikeString("abc")); RuleViolation rv = new ParametricRuleViolation(r, s, r.getMessage()); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); @@ -91,7 +91,7 @@ class AbstractRuleTest { @Test void testCreateRV2() { MyRule r = new MyRule(); - DummyRootNode s = helper.parse("abc()", PathId.fromPathLikeString("filename")); + DummyRootNode s = helper.parse("abc()", FileId.fromPathLikeString("filename")); RuleViolation rv = new ParametricRuleViolation(r, s, "specificdescription"); assertEquals(1, rv.getBeginLine(), "Line number mismatch!"); assertEquals("filename", rv.getFileId().getOriginalPath(), "Filename mismatch!"); @@ -110,7 +110,7 @@ class AbstractRuleTest { r.definePropertyDescriptor(PropertyFactory.intProperty("testInt").desc("description").require(inRange(0, 100)).defaultValue(10).build()); r.setMessage("Message ${packageName} ${className} ${methodName} ${variableName} ${testInt} ${noSuchProperty}"); - DummyRootNode s = helper.parse("abc()", PathId.UNKNOWN); + DummyRootNode s = helper.parse("abc()", FileId.UNKNOWN); RuleViolation rv = getReportForRuleApply(r, s).getViolations().get(0); assertEquals("Message foo ${className} ${methodName} ${variableName} 10 ${noSuchProperty}", rv.getDescription()); @@ -118,7 +118,7 @@ class AbstractRuleTest { @Test void testRuleSuppress() { - DummyRootNode n = helper.parse("abc()", PathId.UNKNOWN) + DummyRootNode n = helper.parse("abc()", FileId.UNKNOWN) .withNoPmdComments(Collections.singletonMap(1, "ohio")); FileAnalysisListener listener = mock(FileAnalysisListener.class); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java index 91136144ab..417de87663 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/DummyParsingHelper.java @@ -19,7 +19,7 @@ import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.util.log.MessageReporter; @@ -35,14 +35,14 @@ public class DummyParsingHelper implements Extension, BeforeEachCallback, AfterE } public DummyRootNode parse(String code) { - return parse(code, PathId.UNKNOWN); + return parse(code, FileId.UNKNOWN); } public DummyRootNode parse(String code, String filename) { - return parse(code, PathId.fromPathLikeString(filename)); + return parse(code, FileId.fromPathLikeString(filename)); } - public DummyRootNode parse(String code, PathId filename) { + public DummyRootNode parse(String code, FileId filename) { LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion(); ParserTask task = new ParserTask( TextDocument.readOnlyString(code, filename, version), diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java index 8da10a4ab7..aff2ddc9e6 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java @@ -28,7 +28,7 @@ import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.SimpleTestTextFile; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.renderers.Renderer; @@ -94,7 +94,7 @@ class PmdAnalysisTest { config.setForceLanguageVersion(DummyLanguageModule.getInstance().getVersionWhereParserThrows()); try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(RuleSet.forSingleRule(new MockRule())); - pmd.files().addSourceFile(PathId.fromPathLikeString("file"), "some source"); + pmd.files().addSourceFile(FileId.fromPathLikeString("file"), "some source"); ReportStats stats = pmd.runAndReturnStats(); assertEquals(1, stats.getNumErrors(), "Errors"); @@ -117,7 +117,7 @@ class PmdAnalysisTest { } })); - pmd.files().addSourceFile(PathId.fromPathLikeString("fname1.dummy"), "some source"); + pmd.files().addSourceFile(FileId.fromPathLikeString("fname1.dummy"), "some source"); ReportStats stats = pmd.runAndReturnStats(); // the error number here is only for FileAnalysisException, so @@ -157,7 +157,7 @@ class PmdAnalysisTest { try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(ruleset); - pmd.files().addFile(new SimpleTestTextFile("test content foo", PathId.fromPathLikeString("foo.txt"), language.getDefaultVersion())); + pmd.files().addFile(new SimpleTestTextFile("test content foo", FileId.fromPathLikeString("foo.txt"), language.getDefaultVersion())); Report report = pmd.performAnalysisAndCollectReport(); for (Report.ProcessingError error : report.getProcessingErrors()) { System.out.println("error = " + error.getMsg() + ": " + error.getDetail()); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java index 91f7846576..f2d4e7b916 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java @@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -113,14 +113,14 @@ class ReportTest { private static FileLocation getNode(int line, int column, String filename) { - return FileLocation.caret(PathId.fromPathLikeString(filename), line, column); + return FileLocation.caret(FileId.fromPathLikeString(filename), line, column); } public static String render(Renderer renderer, Consumer listenerEffects) { return renderGlobal(renderer, globalListener -> { LanguageVersion dummyVersion = DummyLanguageModule.getInstance().getDefaultVersion(); - TextFile dummyFile = TextFile.forCharSeq("dummyText", PathId.fromPathLikeString("file"), dummyVersion); + TextFile dummyFile = TextFile.forCharSeq("dummyText", FileId.fromPathLikeString("file"), dummyVersion); try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) { listenerEffects.accept(fal); } catch (Exception e) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java index d6bba2906b..994552bd28 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java @@ -17,7 +17,7 @@ import java.util.Random; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -72,7 +72,7 @@ class RuleViolationComparatorTest { private RuleViolation createJavaRuleViolation(Rule rule, String fileName, int beginLine, String description, int beginColumn, int endLine, int endColumn) { - FileLocation loc = FileLocation.range(PathId.fromPathLikeString(fileName), TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); + FileLocation loc = FileLocation.range(FileId.fromPathLikeString(fileName), TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn)); return new ParametricRuleViolation(rule, loc, description, Collections.emptyMap()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java index d3197b743d..278b888d7e 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationTest.java @@ -16,8 +16,8 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.lang.ast.DummyNode; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -26,7 +26,7 @@ class RuleViolationTest { @RegisterExtension private final DummyParsingHelper helper = new DummyParsingHelper(); - private PathId filename = PathId.fromPathLikeString("filename"); + private FileId filename = FileId.fromPathLikeString("filename"); @Test void testConstructor1() { @@ -53,8 +53,8 @@ class RuleViolationTest { void testComparatorWithDifferentFilenames() { Rule rule = new MockRule("name", "desc", "msg", "rulesetname"); Comparator comp = RuleViolation.DEFAULT_COMPARATOR; - DummyNode s = helper.parse("(abc)", PathId.fromPathLikeString("f1")).getFirstChild(); - DummyNode s1 = helper.parse("(abc)", PathId.fromPathLikeString("f2")).getFirstChild(); + DummyNode s = helper.parse("(abc)", FileId.fromPathLikeString("f1")).getFirstChild(); + DummyNode s1 = helper.parse("(abc)", FileId.fromPathLikeString("f2")).getFirstChild(); RuleViolation r1 = new ParametricRuleViolation(rule, s, "description"); RuleViolation r2 = new ParametricRuleViolation(rule, s1, "description"); assertEquals(-1, comp.compare(r1, r2)); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index 7e153b00fa..4d303fd92c 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -40,8 +40,8 @@ import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextFileContent; @@ -159,7 +159,7 @@ class FileAnalysisCacheTest { final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); TextFile mockFile = mock(TextFile.class); - when(mockFile.getPathId()).thenReturn(PathId.fromPathLikeString("a/bc")); + when(mockFile.getPathId()).thenReturn(FileId.fromPathLikeString("a/bc")); when(mockFile.getLanguageVersion()).thenReturn(dummyVersion); when(mockFile.readContents()).thenReturn(TextFileContent.fromCharSeq("abc")); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java index 1800f44ad3..67489f0ae7 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/token/internal/BaseTokenFilterTest.java @@ -19,8 +19,8 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.ast.GenericToken; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.document.TextRegion; @@ -61,7 +61,7 @@ class BaseTokenFilterTest { @Override public FileLocation getReportLocation() { - return FileLocation.range(PathId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 1)); + return FileLocation.range(FileId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 1)); } @Override diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java index 95303cd86b..fd2bc56496 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/ast/DummyNode.java @@ -16,7 +16,7 @@ import net.sourceforge.pmd.lang.LanguageProcessorRegistry; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.impl.AbstractNode; import net.sourceforge.pmd.lang.ast.impl.GenericNode; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextRegion; import net.sourceforge.pmd.lang.rule.xpath.Attribute; @@ -133,7 +133,7 @@ public class DummyNode extends AbstractNode { public DummyRootNode() { TextDocument document = TextDocument.readOnlyString( "dummy text", - PathId.UNKNOWN, + FileId.UNKNOWN, DummyLanguageModule.getInstance().getDefaultVersion() ); astInfo = new AstInfo<>( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index c731ec3204..71fa4e30a3 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -43,7 +43,7 @@ class FileCollectorTest { assertTrue(collector.addFile(foo), "should be dummy language"); assertFalse(collector.addFile(bar), "should be unknown language"); - assertCollected(collector, listOf(PathId.forPath(foo))); + assertCollected(collector, listOf(FileId.forPath(foo))); } @Test @@ -55,7 +55,7 @@ class FileCollectorTest { FileCollector collector = newCollector(dummy.getDefaultVersion()); assertTrue(collector.addFile(bar, dummy), "should be unknown language"); - assertCollected(collector, listOf(PathId.forPath(bar))); + assertCollected(collector, listOf(FileId.forPath(bar))); assertNoErrors(collector); } @@ -88,13 +88,13 @@ class FileCollectorTest { collector.addDirectory(root.resolve("src")); - assertCollected(collector, listOf(PathId.forPath(foo), PathId.forPath(bar))); + assertCollected(collector, listOf(FileId.forPath(foo), FileId.forPath(bar))); } @Test void testRelativize() { - String displayName = FileCollector.getDisplayName(PathId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); + String displayName = FileCollector.getDisplayName(FileId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); assertEquals(displayName, Paths.get("b", "c").toString()); } @@ -105,8 +105,8 @@ class FileCollectorTest { return resolved; } - private void assertCollected(FileCollector collector, List expected) { - List actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getPathId); + private void assertCollected(FileCollector collector, List expected) { + List actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getPathId); assertEquals(expected, actual); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java index 96cb53acaf..c0d2384623 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileLocationTest.java @@ -15,7 +15,7 @@ import org.junit.jupiter.api.Test; */ class FileLocationTest { - public static final PathId FNAME = PathId.fromPathLikeString("fname"); + public static final FileId FNAME = FileId.fromPathLikeString("fname"); @Test void testSimple() { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java index 09ef7aeaf2..cba128fc82 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/SimpleTestTextFile.java @@ -11,7 +11,7 @@ import net.sourceforge.pmd.lang.LanguageVersion; */ public class SimpleTestTextFile extends StringTextFile { - public SimpleTestTextFile(String content, PathId pathId, LanguageVersion languageVersion) { - super(content, pathId, languageVersion); + public SimpleTestTextFile(String content, FileId fileId, LanguageVersion languageVersion) { + super(content, fileId, languageVersion); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java index f2365e6734..af5926d516 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java @@ -50,7 +50,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content").toAbsolutePath(); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { - try (TextFile stringTf = TextFile.forCharSeq("some content", PathId.forPath(file), dummyVersion())) { + try (TextFile stringTf = TextFile.forCharSeq("some content", FileId.forPath(file), dummyVersion())) { assertEquals(tf.getPathId(), stringTf.getPathId()); // despite same path id, they are different implementations @@ -58,7 +58,7 @@ class TextFilesTest { assertNotEquals(stringTf, tf); // identical, but string text files use identity - assertNotEquals(stringTf, TextFile.forCharSeq("some content", PathId.forPath(file), dummyVersion())); + assertNotEquals(stringTf, TextFile.forCharSeq("some content", FileId.forPath(file), dummyVersion())); // those are identical so are equals assertNotSame(tf, tfPrime); @@ -183,8 +183,8 @@ class TextFilesTest { @Test void testReaderFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); - try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), PathId.UNKNOWN, dummyVersion())) { - assertEquals(PathId.UNKNOWN, tf.getPathId()); + try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), FileId.UNKNOWN, dummyVersion())) { + assertEquals(FileId.UNKNOWN, tf.getPathId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText()); } @@ -193,7 +193,7 @@ class TextFilesTest { @Test void testReaderFileIsReadOnly() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); - try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), PathId.UNKNOWN, dummyVersion())) { + try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), FileId.UNKNOWN, dummyVersion())) { assertTrue(tf.isReadOnly(), "readonly"); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( TextFileContent.fromCharSeq("new content") @@ -203,8 +203,8 @@ class TextFilesTest { @Test void testStringFileEscape() throws IOException { - try (TextFile tf = TextFile.forCharSeq("cont\r\nents", PathId.UNKNOWN, dummyVersion())) { - assertEquals(PathId.UNKNOWN, tf.getPathId()); + try (TextFile tf = TextFile.forCharSeq("cont\r\nents", FileId.UNKNOWN, dummyVersion())) { + assertEquals(FileId.UNKNOWN, tf.getPathId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("cont\nents"), tf.readContents().getNormalizedText()); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( @@ -215,7 +215,7 @@ class TextFilesTest { @Test void testStringFileCanBeReadMultipleTimes() throws IOException { - try (TextFile tf = TextFile.forCharSeq("contents", PathId.UNKNOWN, dummyVersion())) { + try (TextFile tf = TextFile.forCharSeq("contents", FileId.UNKNOWN, dummyVersion())) { assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); assertEquals(Chars.wrap("contents"), tf.readContents().getNormalizedText()); @@ -224,7 +224,7 @@ class TextFilesTest { @Test void testStringFileIsReadonly() throws IOException { - try (TextFile tf = TextFile.forCharSeq("contents", PathId.UNKNOWN, dummyVersion())) { + try (TextFile tf = TextFile.forCharSeq("contents", FileId.UNKNOWN, dummyVersion())) { assertTrue(tf.isReadOnly(), "readonly"); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( TextFileContent.fromCharSeq("new content") diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index 24d162c0ff..30a0978c9e 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -26,7 +26,7 @@ import net.sourceforge.pmd.cache.AnalysisCache; import net.sourceforge.pmd.cache.NoopAnalysisCache; import net.sourceforge.pmd.lang.ast.FileAnalysisException; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener.ViolationCounterListener; @@ -132,9 +132,9 @@ class GlobalListenerTest { private void runPmd(PMDConfiguration config, GlobalAnalysisListener listener, Rule rule) { try (PmdAnalysis pmd = PmdAnalysis.create(config)) { pmd.addRuleSet(RuleSet.forSingleRule(rule)); - pmd.files().addSourceFile(PathId.fromPathLikeString("fname1.dummy"), "abc"); - pmd.files().addSourceFile(PathId.fromPathLikeString("fname2.dummy"), "abcd"); - pmd.files().addSourceFile(PathId.fromPathLikeString("fname21.dummy"), "abcd"); + pmd.files().addSourceFile(FileId.fromPathLikeString("fname1.dummy"), "abc"); + pmd.files().addSourceFile(FileId.fromPathLikeString("fname2.dummy"), "abcd"); + pmd.files().addSourceFile(FileId.fromPathLikeString("fname21.dummy"), "abcd"); pmd.addListener(listener); pmd.performAnalysis(); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java index 0177874c76..07ce390a0d 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java @@ -19,7 +19,7 @@ import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.reporting.FileAnalysisListener; @@ -34,8 +34,8 @@ class MultiThreadProcessorTest { configuration.setThreads(2); PmdAnalysis pmd = PmdAnalysis.create(configuration); LanguageVersion lv = DummyLanguageModule.getInstance().getDefaultVersion(); - pmd.files().addFile(TextFile.forCharSeq("abc", PathId.fromPathLikeString("file1-violation.dummy"), lv)); - pmd.files().addFile(TextFile.forCharSeq("DEF", PathId.fromPathLikeString("file2-foo.dummy"), lv)); + pmd.files().addFile(TextFile.forCharSeq("abc", FileId.fromPathLikeString("file1-violation.dummy"), lv)); + pmd.files().addFile(TextFile.forCharSeq("DEF", FileId.fromPathLikeString("file2-foo.dummy"), lv)); reportListener = new SimpleReportListener(); GlobalAnalysisListener listener = GlobalAnalysisListener.tee(listOf( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java index 26d932b8ac..c50e05b86e 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/PmdRunnableTest.java @@ -38,7 +38,7 @@ import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.Parser; import net.sourceforge.pmd.lang.ast.RootNode; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.impl.SimpleLanguageModuleBase; import net.sourceforge.pmd.lang.rule.AbstractRule; import net.sourceforge.pmd.util.ContextedAssertionError; @@ -75,7 +75,7 @@ class PmdRunnableTest { configuration.setForceLanguageVersion(lv); configuration.setIgnoreIncrementalAnalysis(true); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { - pmd.files().addSourceFile(PathId.fromPathLikeString("test.dummy"), "foo"); + pmd.files().addSourceFile(FileId.fromPathLikeString("test.dummy"), "foo"); pmd.addRuleSet(RuleSet.forSingleRule(rule)); return pmd.performAnalysisAndCollectReport(); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java index f4abe64e49..411be7336a 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/AbstractRendererTest.java @@ -32,8 +32,8 @@ import net.sourceforge.pmd.RuleWithProperties; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -102,7 +102,7 @@ abstract class AbstractRendererTest { protected FileLocation createLocation(int beginLine, int beginColumn, int endLine, int endColumn) { TextRange2d range2d = TextRange2d.range2d(beginLine, beginColumn, endLine, endColumn); - return FileLocation.range(PathId.fromPathLikeString(getSourceCodeFilename()), range2d); + return FileLocation.range(FileId.fromPathLikeString(getSourceCodeFilename()), range2d); } protected RuleViolation newRuleViolation(int beginLine, int beginColumn, int endLine, int endColumn, Rule rule) { @@ -176,14 +176,14 @@ abstract class AbstractRendererTest { @Test void testError() throws Exception { - Report.ProcessingError err = new Report.ProcessingError(new RuntimeException("Error"), PathId.fromPathLikeString("file")); + Report.ProcessingError err = new Report.ProcessingError(new RuntimeException("Error"), FileId.fromPathLikeString("file")); String actual = render(it -> it.onError(err)); assertEquals(filter(getExpectedError(err)), filter(actual)); } @Test void testErrorWithoutMessage() throws Exception { - Report.ProcessingError err = new Report.ProcessingError(new NullPointerException(), PathId.fromPathLikeString("file")); + Report.ProcessingError err = new Report.ProcessingError(new NullPointerException(), FileId.fromPathLikeString("file")); String actual = render(it -> it.onError(err)); assertEquals(filter(getExpectedErrorWithoutMessage(err)), filter(actual)); } @@ -208,7 +208,7 @@ abstract class AbstractRendererTest { return renderGlobal(renderer, globalListener -> { LanguageVersion version = DummyLanguageModule.getInstance().getDefaultVersion(); - TextFile dummyFile = TextFile.forCharSeq("dummyText", PathId.fromPathLikeString("fname1.dummy"), version); + TextFile dummyFile = TextFile.forCharSeq("dummyText", FileId.fromPathLikeString("fname1.dummy"), version); try (FileAnalysisListener fal = globalListener.startFileAnalysis(dummyFile)) { listenerEffects.accept(fal); } catch (Exception e) { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java index 21f4b5f1cb..482f3508dd 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XMLRendererTest.java @@ -30,8 +30,8 @@ import net.sourceforge.pmd.Report.ConfigurationError; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -92,7 +92,7 @@ class XMLRendererTest extends AbstractRendererTest { } private RuleViolation createRuleViolation(String description) { - FileLocation loc = FileLocation.range(PathId.fromPathLikeString(getSourceCodeFilename()), + FileLocation loc = FileLocation.range(FileId.fromPathLikeString(getSourceCodeFilename()), TextRange2d.range2d(1, 1, 1, 1)); return new ParametricRuleViolation(new FooRule(), loc, description); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java index 36ccc51337..db22cb95ee 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java @@ -11,8 +11,8 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.FooRule; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.FileLocation; -import net.sourceforge.pmd.lang.document.PathId; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; @@ -58,7 +58,7 @@ class XSLTRendererTest extends AbstractRendererTest { @Test void testDefaultStylesheet() throws Exception { XSLTRenderer renderer = new XSLTRenderer(); - FileLocation loc = FileLocation.range(PathId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 2)); + FileLocation loc = FileLocation.range(FileId.UNKNOWN, TextRange2d.range2d(1, 1, 1, 2)); RuleViolation rv = new ParametricRuleViolation(new FooRule(), loc, "violation message"); String result = renderReport(renderer, it -> it.onRuleViolation(rv)); assertTrue(result.contains("violation message")); diff --git a/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java b/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java index f9ce473958..771f9b175e 100644 --- a/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java +++ b/pmd-cpp/src/test/java/net/sourceforge/pmd/cpd/CppCharStreamTest.java @@ -13,14 +13,14 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.ast.impl.javacc.CharStream; import net.sourceforge.pmd.lang.document.CpdCompat; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; class CppCharStreamTest { @NonNull public CharStream charStreamFor(String source) throws IOException { - TextDocument textDoc = TextDocument.readOnlyString(source, PathId.UNKNOWN, CpdCompat.dummyVersion()); + TextDocument textDoc = TextDocument.readOnlyString(source, FileId.UNKNOWN, CpdCompat.dummyVersion()); return CharStream.create(textDoc, new CPPTokenizer().tokenBehavior()); } diff --git a/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java b/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java index 84cf1b80b7..c48b45210e 100644 --- a/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java +++ b/pmd-html/src/main/java/net/sourceforge/pmd/lang/html/ast/HtmlTokenizer.java @@ -15,7 +15,7 @@ import net.sourceforge.pmd.lang.LanguageProcessor; import net.sourceforge.pmd.lang.LanguageProcessorRegistry; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.SemanticErrorReporter; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextDocument; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.html.HtmlLanguageModule; @@ -29,7 +29,7 @@ public class HtmlTokenizer implements Tokenizer { try (LanguageProcessor processor = html.createProcessor(html.newPropertyBundle()); TextFile tf = TextFile.forCharSeq( sourceCode.getCodeBuffer(), - PathId.fromPathLikeString(sourceCode.getFileName()), + FileId.fromPathLikeString(sourceCode.getFileName()), html.getDefaultVersion() ); TextDocument textDoc = TextDocument.create(tf)) { diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java index 0b7f8f552e..094ca77681 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/ParserCornersTest.java @@ -21,7 +21,7 @@ import org.junit.jupiter.api.Timeout; import net.sourceforge.pmd.lang.ast.ParseException; import net.sourceforge.pmd.lang.ast.impl.javacc.MalformedSourceException; import net.sourceforge.pmd.lang.ast.test.BaseParsingHelper; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.java.BaseJavaTreeDumpTest; import net.sourceforge.pmd.lang.java.JavaParsingHelper; import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr; @@ -45,7 +45,7 @@ class ParserCornersTest extends BaseJavaTreeDumpTest { @Test void testInvalidUnicodeEscape() { MalformedSourceException thrown = assertThrows(MalformedSourceException.class, // previously Error - () -> java.parse("\\u00k0", null, PathId.fromPathLikeString("x/filename.java"))); + () -> java.parse("\\u00k0", null, FileId.fromPathLikeString("x/filename.java"))); assertThat(thrown.getMessage(), startsWith("Source format error in file 'x/filename.java' at line 1, column 1: Invalid unicode escape")); } diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt index 41ac1f7be8..742022abbe 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt @@ -10,7 +10,7 @@ import net.sourceforge.pmd.cpd.TokenEntry import net.sourceforge.pmd.cpd.Tokenizer import net.sourceforge.pmd.cpd.Tokens import net.sourceforge.pmd.lang.ast.TokenMgrError -import net.sourceforge.pmd.lang.document.PathId +import net.sourceforge.pmd.lang.document.FileId import net.sourceforge.pmd.lang.document.TextFile import net.sourceforge.pmd.test.BaseTextComparisonTest import org.apache.commons.lang3.StringUtils @@ -62,7 +62,7 @@ abstract class CpdTextComparisonTest( @JvmOverloads fun expectTokenMgrError( source: String, - fileName: PathId = PathId.UNKNOWN, + fileName: FileId = FileId.UNKNOWN, properties: Properties = defaultProperties() ): TokenMgrError = expectTokenMgrError(FileData(fileName, source), properties) diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt index bffb8473c4..a9d789d0c7 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/lang/ast/test/BaseParsingHelper.kt @@ -10,7 +10,7 @@ import net.sourceforge.pmd.lang.ast.Node import net.sourceforge.pmd.lang.ast.Parser.ParserTask import net.sourceforge.pmd.lang.ast.RootNode import net.sourceforge.pmd.lang.ast.SemanticErrorReporter -import net.sourceforge.pmd.lang.document.PathId +import net.sourceforge.pmd.lang.document.FileId import net.sourceforge.pmd.lang.document.TextDocument import net.sourceforge.pmd.lang.rule.XPathRule import net.sourceforge.pmd.lang.rule.xpath.XPathVersion @@ -118,7 +118,7 @@ abstract class BaseParsingHelper, T : RootNode fun parse( sourceCode: String, version: String? = null, - fileName: PathId = PathId.UNKNOWN + fileName: FileId = FileId.UNKNOWN ): T { val lversion = if (version == null) defaultVersion else getVersion(version) val params = params.copy(defaultVerString = lversion.version) @@ -162,7 +162,7 @@ abstract class BaseParsingHelper, T : RootNode parse( readResource(resource), version, - fileName = PathId.fromPathLikeString(params.resourcePrefix + resource) + fileName = FileId.fromPathLikeString(params.resourcePrefix + resource) ) /** @@ -170,7 +170,7 @@ abstract class BaseParsingHelper, T : RootNode */ @JvmOverloads open fun parseFile(path: Path, version: String? = null): T = - parse(IOUtil.readToString(Files.newBufferedReader(path)), version, fileName = PathId.forPath(path)) + parse(IOUtil.readToString(Files.newBufferedReader(path)), version, fileName = FileId.forPath(path)) /** * Fetches the source of the given [clazz]. @@ -228,7 +228,7 @@ abstract class BaseParsingHelper, T : RootNode fun executeRule( rule: Rule, code: String, - fileName: PathId = PathId.fromPathLikeString("testfile.${language.extensions[0]}") + fileName: FileId = FileId.fromPathLikeString("testfile.${language.extensions[0]}") ): Report { if (rule.language == null) rule.language = language @@ -255,6 +255,6 @@ abstract class BaseParsingHelper, T : RootNode executeRule( rule, code = Files.newBufferedReader(path).readText(), - fileName = PathId.forPath(path) + fileName = FileId.forPath(path) ) } diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt index d82d74e59a..4226f25e48 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/test/BaseTextComparisonTest.kt @@ -4,7 +4,7 @@ package net.sourceforge.pmd.test -import net.sourceforge.pmd.lang.document.PathId +import net.sourceforge.pmd.lang.document.FileId import java.nio.file.Path import java.nio.file.Paths import kotlin.test.assertEquals @@ -28,7 +28,7 @@ abstract class BaseTextComparisonTest { /** Extension that the unparsed source file is supposed to have. */ protected abstract val extensionIncludingDot: String - data class FileData(val fileName:PathId, val fileText:String) + data class FileData(val fileName: FileId, val fileText:String) /** * Executes the test. The test files are looked up using the [parser]. @@ -67,7 +67,7 @@ abstract class BaseTextComparisonTest { } val sourceText = sourceFile.readText(Charsets.UTF_8).normalize() - return FileData(fileName = PathId.forPath(sourceFile.toPath()), fileText = sourceText) + return FileData(fileName = FileId.forPath(sourceFile.toPath()), fileText = sourceText) } protected open fun String.normalize() = replace( diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java index cfc3865be9..d944cce12f 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java @@ -33,7 +33,7 @@ import net.sourceforge.pmd.RuleSetLoadException; import net.sourceforge.pmd.RuleSetLoader; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.document.PathId; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.renderers.TextRenderer; @@ -230,7 +230,7 @@ public abstract class RuleTst { configuration.prependAuxClasspath("."); try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) { - pmd.files().addFile(TextFile.forCharSeq(code, PathId.fromPathLikeString("file"), languageVersion)); + pmd.files().addFile(TextFile.forCharSeq(code, FileId.fromPathLikeString("file"), languageVersion)); pmd.addRuleSet(RuleSet.forSingleRule(rule)); pmd.addListener(GlobalAnalysisListener.exceptionThrower()); return pmd.performAnalysisAndCollectReport(); From a8c481e2ac1b276e67b05abf07aec5fb7cd19de3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 23:29:45 +0100 Subject: [PATCH 09/14] Move getFileNameRenderer from FileCollector --- .../java/net/sourceforge/pmd/PmdAnalysis.java | 106 +++++++++++++++++- .../pmd/lang/document/FileCollector.java | 100 ----------------- .../sourceforge/pmd/cli/PMDFilelistTest.java | 26 ++--- .../net/sourceforge/pmd/cli/ZipFileTest.java | 18 +-- .../pmd/lang/document/FileCollectorTest.java | 7 +- .../pmd/lang/document/NioTextFileTest.java | 15 +-- .../pmd/cpd/test/CpdTextComparisonTest.kt | 1 - 7 files changed, 136 insertions(+), 137 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index a73c7cf089..a5a06f4659 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -6,10 +6,13 @@ package net.sourceforge.pmd; import static net.sourceforge.pmd.util.CollectionUtil.listOf; +import java.io.File; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -17,6 +20,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; @@ -41,7 +45,9 @@ import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; import net.sourceforge.pmd.lang.document.FileCollector; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.ListenerInitializer; @@ -110,7 +116,7 @@ public final class PmdAnalysis implements AutoCloseable { ); for (Path path : config.getRelativizeRoots()) { - this.collector.relativizeWith(path); + this.relativizeWith(path); } } @@ -283,6 +289,45 @@ public final class PmdAnalysis implements AutoCloseable { return langProperties.computeIfAbsent(language, Language::newPropertyBundle); } + private final List relativizeRootPaths = new ArrayList<>(); + /** + * Add a prefix that is used to relativize file paths as their display name. + * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, + * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} + * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a + * display name of {@code main/java/org/foo.java}. + * + *

This only matters for files added from a {@link Path} object. + * + * @param path Path with which to relativize + */ + public void relativizeWith(Path path) { + this.relativizeRootPaths.add(Objects.requireNonNull(path)); + this.relativizeRootPaths.sort(Comparator.naturalOrder()); + } + + public FileNameRenderer getFileNameRenderer() { + return new FileNameRenderer() { + private final List relativizeRootPaths = new ArrayList<>(PmdAnalysis.this.relativizeRootPaths); + + @Override + public String getDisplayName(FileId fileId) { + String localDisplayName = getLocalDisplayName(fileId); + if (fileId.getParentFsPath() != null) { + return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; + } + return localDisplayName; + } + + private String getLocalDisplayName(FileId file) { + if (!relativizeRootPaths.isEmpty()) { + return PmdAnalysis.getDisplayName(file, relativizeRootPaths); + } + return file.getOriginalPath(); + } + }; + } + /** * Run PMD with the current state of this instance. This will start * and finish the registered renderers, and close all @@ -333,7 +378,7 @@ public final class PmdAnalysis implements AutoCloseable { // Initialize listeners try (ListenerInitializer initializer = listener.initializer()) { initializer.setNumberOfFilesToAnalyze(textFiles.size()); - initializer.setFileNameRenderer(files().getFileNameRenderer()); + initializer.setFileNameRenderer(getFileNameRenderer()); } } catch (Exception e) { reporter.errorEx("Exception while initializing analysis listeners", e); @@ -404,7 +449,7 @@ public final class PmdAnalysis implements AutoCloseable { List rendererListeners = new ArrayList<>(renderers.size()); for (Renderer renderer : renderers) { try { - renderer.setFileNameRenderer(files().getFileNameRenderer()); + renderer.setFileNameRenderer(getFileNameRenderer()); @SuppressWarnings("PMD.CloseResource") GlobalAnalysisListener listener = Objects.requireNonNull(renderer.newListener(), "Renderer should provide non-null listener"); @@ -553,4 +598,59 @@ public final class PmdAnalysis implements AutoCloseable { + "https://pmd.github.io/{0}/pmd_userdocs_incremental_analysis.html", version); } } + + /** + * Return the textfile's display name. Takes the shortest path we + * can construct from the relativize roots. + * + *

package private for test only

+ */ + public static String getDisplayName(FileId file, List relativizeRoots) { + String best = file.toAbsolutePath(); + for (Path root : relativizeRoots) { + if (isFileSystemRoot(root)) { + // Absolutize the path. Since the relativize roots are + // sorted by ascending length, this should be the first in the list + // (so another root can override it). + best = file.toAbsolutePath(); + continue; + } + + String relative = relativizePath(root.toAbsolutePath().toString(), file.toAbsolutePath()); + if (countSegments(relative) < countSegments(best)) { + best = relative; + } + } + return best; + } + + private static int countSegments(String best) { + return StringUtils.countMatches(best, File.separatorChar); + } + + private static String relativizePath(String base, String other) { + String[] baseSegments = base.split("[/\\\\]"); + String[] otherSegments = other.split("[/\\\\]"); + int prefixLength = 0; + int maxi = Math.min(baseSegments.length, otherSegments.length); + while (prefixLength < maxi && baseSegments[prefixLength].equals(otherSegments[prefixLength])) { + prefixLength++; + } + + if (prefixLength == 0) { + return other; + } + + List relative = new ArrayList<>(); + for (int i = prefixLength; i < baseSegments.length; i++) { + relative.add(".."); + } + relative.addAll(Arrays.asList(otherSegments).subList(prefixLength, otherSegments.length)); + return String.join(File.separator, relative); + } + + /** Return whether the path is the root path (/). */ + private static boolean isFileSystemRoot(Path root) { + return root.isAbsolute() && root.getNameCount() == 0; + } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index a2458737af..21a8a8d98e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -5,7 +5,6 @@ package net.sourceforge.pmd.lang.document; import java.io.Closeable; -import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.charset.Charset; @@ -22,7 +21,6 @@ import java.nio.file.ProviderNotFoundException; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; @@ -33,7 +31,6 @@ import java.util.List; import java.util.Objects; import java.util.Set; -import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,7 +41,6 @@ import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; -import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.util.AssertionUtil; import net.sourceforge.pmd.util.log.MessageReporter; @@ -65,7 +61,6 @@ public final class FileCollector implements AutoCloseable { private final LanguageVersionDiscoverer discoverer; private final MessageReporter reporter; private final FileId outerFsPath; - private final List relativizeRootPaths = new ArrayList<>(); private boolean closed; // construction @@ -92,7 +87,6 @@ public final class FileCollector implements AutoCloseable { public FileCollector newCollector(MessageReporter logger) { FileCollector fileCollector = new FileCollector(discoverer, logger, null); fileCollector.charset = this.charset; - fileCollector.relativizeRootPaths.addAll(this.relativizeRootPaths); return fileCollector; } @@ -259,61 +253,6 @@ public final class FileCollector implements AutoCloseable { return true; } - /** - * Return the textfile's display name. Takes the shortest path we - * can construct from the relativize roots. - * - *

package private for test only

- */ - static String getDisplayName(FileId file, List relativizeRoots) { - String best = file.toAbsolutePath(); - for (Path root : relativizeRoots) { - if (isFileSystemRoot(root)) { - // Absolutize the path. Since the relativize roots are - // sorted by ascending length, this should be the first in the list - // (so another root can override it). - best = file.toAbsolutePath(); - continue; - } - - String relative = relativizePath(root.toAbsolutePath().toString(), file.toAbsolutePath()); - if (countSegments(relative) < countSegments(best)) { - best = relative; - } - } - return best; - } - - private static int countSegments(String best) { - return StringUtils.countMatches(best, File.separatorChar); - } - - private static String relativizePath(String base, String other) { - String[] baseSegments = base.split("[/\\\\]"); - String[] otherSegments = other.split("[/\\\\]"); - int prefixLength = 0; - int maxi = Math.min(baseSegments.length, otherSegments.length); - while (prefixLength < maxi && baseSegments[prefixLength].equals(otherSegments[prefixLength])) { - prefixLength++; - } - - if (prefixLength == 0) { - return other; - } - - List relative = new ArrayList<>(); - for (int i = prefixLength; i < baseSegments.length; i++) { - relative.add(".."); - } - relative.addAll(Arrays.asList(otherSegments).subList(prefixLength, otherSegments.length)); - return String.join(File.separator, relative); - } - - /** Return whether the path is the root path (/). */ - private static boolean isFileSystemRoot(Path root) { - return root.isAbsolute() && root.getNameCount() == 0; - } - /** * Add a directory recursively using {@link #addFile(Path)} on @@ -447,45 +386,6 @@ public final class FileCollector implements AutoCloseable { this.charset = Objects.requireNonNull(charset); } - /** - * Add a prefix that is used to relativize file paths as their display name. - * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, - * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} - * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a - * display name of {@code main/java/org/foo.java}. - * - *

This only matters for files added from a {@link Path} object. - * - * @param path Path with which to relativize - */ - public void relativizeWith(Path path) { - this.relativizeRootPaths.add(Objects.requireNonNull(path)); - this.relativizeRootPaths.sort(Comparator.comparingInt(Path::getNameCount).thenComparing(o -> o)); - } - - // todo doc - public FileNameRenderer getFileNameRenderer() { - return new FileNameRenderer() { - private final List relativizeRootPaths = new ArrayList<>(FileCollector.this.relativizeRootPaths); - - @Override - public String getDisplayName(FileId fileId) { - String localDisplayName = getLocalDisplayName(fileId); - if (fileId.getParentFsPath() != null) { - return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; - } - return localDisplayName; - } - - private String getLocalDisplayName(FileId file) { - if (!relativizeRootPaths.isEmpty()) { - return FileCollector.getDisplayName(file, relativizeRootPaths); - } - return file.getOriginalPath(); - } - }; - } - // filtering diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index 52826a7175..d61b9d552c 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -87,13 +87,13 @@ class PMDFilelistTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(2)); - assertHasName(files.get(0), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/anotherfile.dummy"), pmd.files()); - assertHasName(files.get(1), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/somefile.dummy"), pmd.files()); + assertHasName(files.get(0), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/anotherfile.dummy"), pmd); + assertHasName(files.get(1), IOUtil.normalizePath("net/sourceforge/pmd/cli/src/somefile.dummy"), pmd); } } - public static void assertHasName(TextFile textFile, String expected, FileCollector files) { - assertThat(files.getFileNameRenderer().getDisplayName(textFile), equalTo(expected)); + public static void assertHasName(TextFile textFile, String expected, PmdAnalysis pmd) { + assertThat(pmd.getFileNameRenderer().getDisplayName(textFile), equalTo(expected)); } @Test @@ -104,9 +104,9 @@ class PMDFilelistTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); - assertHasName(files.get(0), ".." + IOUtil.normalizePath("/otherSrc/somefile.dummy"), pmd.files()); - assertHasName(files.get(1), "anotherfile.dummy", pmd.files()); - assertHasName(files.get(2), "somefile.dummy", pmd.files()); + assertHasName(files.get(0), ".." + IOUtil.normalizePath("/otherSrc/somefile.dummy"), pmd); + assertHasName(files.get(1), "anotherfile.dummy", pmd); + assertHasName(files.get(2), "somefile.dummy", pmd); } } @@ -119,9 +119,9 @@ class PMDFilelistTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); - assertHasName(files.get(0), "somefile.dummy", pmd.files()); - assertHasName(files.get(1), "anotherfile.dummy", pmd.files()); - assertHasName(files.get(2), "somefile.dummy", pmd.files()); + assertHasName(files.get(0), "somefile.dummy", pmd); + assertHasName(files.get(1), "anotherfile.dummy", pmd); + assertHasName(files.get(2), "somefile.dummy", pmd); } } @@ -133,9 +133,9 @@ class PMDFilelistTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); - assertHasName(files.get(0), RESOURCES.resolve("otherSrc/somefile.dummy").toAbsolutePath().toString(), pmd.files()); - assertHasName(files.get(1), RESOURCES.resolve("src/anotherfile.dummy").toAbsolutePath().toString(), pmd.files()); - assertHasName(files.get(2), RESOURCES.resolve("src/somefile.dummy").toAbsolutePath().toString(), pmd.files()); + assertHasName(files.get(0), RESOURCES.resolve("otherSrc/somefile.dummy").toAbsolutePath().toString(), pmd); + assertHasName(files.get(1), RESOURCES.resolve("src/anotherfile.dummy").toAbsolutePath().toString(), pmd); + assertHasName(files.get(2), RESOURCES.resolve("src/somefile.dummy").toAbsolutePath().toString(), pmd); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java index f2a8934081..03f6720cf9 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java @@ -33,9 +33,9 @@ class ZipFileTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); - assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd.files()); - assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd.files()); - assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd.files()); + assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd); + assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd); + assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd); } } @@ -48,9 +48,9 @@ class ZipFileTest { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); String baseZipPath = IOUtil.normalizePath("net/sourceforge/pmd/cli/zipWithSources.zip"); - assertHasName(files.get(0), baseZipPath + "!/otherSrc/somefile.dummy", pmd.files()); - assertHasName(files.get(1), baseZipPath + "!/src/somefile.dummy", pmd.files()); - assertHasName(files.get(2), baseZipPath + "!/src/somefile1.dummy", pmd.files()); + assertHasName(files.get(0), baseZipPath + "!/otherSrc/somefile.dummy", pmd); + assertHasName(files.get(1), baseZipPath + "!/src/somefile.dummy", pmd); + assertHasName(files.get(2), baseZipPath + "!/src/somefile1.dummy", pmd); } } @@ -64,9 +64,9 @@ class ZipFileTest { try (PmdAnalysis pmd = PmdAnalysis.create(conf)) { List files = pmd.files().getCollectedFiles(); assertThat(files, hasSize(3)); - assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd.files()); - assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd.files()); - assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd.files()); + assertHasName(files.get(0), reportPath + "!/otherSrc/somefile.dummy", pmd); + assertHasName(files.get(1), reportPath + "!/src/somefile.dummy", pmd); + assertHasName(files.get(2), reportPath + "!/src/somefile1.dummy", pmd); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index 71fa4e30a3..a6b47cb18e 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -18,6 +18,7 @@ import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -94,7 +95,7 @@ class FileCollectorTest { @Test void testRelativize() { - String displayName = FileCollector.getDisplayName(FileId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); + String displayName = PmdAnalysis.getDisplayName(FileId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); assertEquals(displayName, Paths.get("b", "c").toString()); } @@ -120,8 +121,6 @@ class FileCollectorTest { private FileCollector newCollector(LanguageVersion forcedVersion) { LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD, forcedVersion); - FileCollector collector = FileCollector.newCollector(discoverer, new TestMessageReporter()); - collector.relativizeWith(tempFolder.toAbsolutePath()); - return collector; + return FileCollector.newCollector(discoverer, new TestMessageReporter()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java index 087ab92f28..7c73f69feb 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java @@ -16,8 +16,8 @@ import java.util.zip.ZipOutputStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import net.sourceforge.pmd.lang.LanguageRegistry; -import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; +import net.sourceforge.pmd.PMDConfiguration; +import net.sourceforge.pmd.PmdAnalysis; class NioTextFileTest { @@ -34,14 +34,15 @@ class NioTextFileTest { zipOutputStream.closeEntry(); } - LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer(LanguageRegistry.PMD, null); - try (FileCollector collector = FileCollector.newCollector(discoverer, new TestMessageReporter())) { - collector.addZipFileWithContent(zipArchive); - List collectedFiles = collector.getCollectedFiles(); + PMDConfiguration config = new PMDConfiguration(); + config.setReporter(new TestMessageReporter()); + try (PmdAnalysis pmd = PmdAnalysis.create(config)) { + pmd.files().addZipFileWithContent(zipArchive); + List collectedFiles = pmd.files().getCollectedFiles(); assertEquals(1, collectedFiles.size()); TextFile textFile = collectedFiles.get(0); assertEquals(zipArchive.toAbsolutePath() + "!/path/inside/someSource.dummy", - collector.getFileNameRenderer().getDisplayName(textFile)); + pmd.getFileNameRenderer().getDisplayName(textFile)); } } } diff --git a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt index 742022abbe..c2e9d003c1 100644 --- a/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt +++ b/pmd-lang-test/src/main/kotlin/net/sourceforge/pmd/cpd/test/CpdTextComparisonTest.kt @@ -11,7 +11,6 @@ import net.sourceforge.pmd.cpd.Tokenizer import net.sourceforge.pmd.cpd.Tokens import net.sourceforge.pmd.lang.ast.TokenMgrError import net.sourceforge.pmd.lang.document.FileId -import net.sourceforge.pmd.lang.document.TextFile import net.sourceforge.pmd.test.BaseTextComparisonTest import org.apache.commons.lang3.StringUtils import java.util.* From a09532e1740e81a710dcb5a87a7940cda9701743 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Sun, 19 Mar 2023 23:36:07 +0100 Subject: [PATCH 10/14] Move out into own class --- .../net/sourceforge/pmd/ant/Formatter.java | 2 +- .../java/net/sourceforge/pmd/PmdAnalysis.java | 53 ++++-------------- .../pmd/renderers/AbstractRenderer.java | 1 + .../sourceforge/pmd/renderers/Renderer.java | 1 + .../ConfigurableFileNameRenderer.java | 55 +++++++++++++++++++ .../FileNameRenderer.java | 5 +- .../pmd/reporting/ListenerInitializer.java | 1 - .../sourceforge/pmd/cli/PMDFilelistTest.java | 2 +- .../pmd/lang/document/NioTextFileTest.java | 2 +- 9 files changed, 73 insertions(+), 49 deletions(-) create mode 100644 pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java rename pmd-core/src/main/java/net/sourceforge/pmd/{renderers => reporting}/FileNameRenderer.java (80%) diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java index f90fcf7f6b..8201ef9878 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java @@ -29,7 +29,7 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.TextFile; -import net.sourceforge.pmd.renderers.FileNameRenderer; +import net.sourceforge.pmd.reporting.FileNameRenderer; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.renderers.RendererFactory; import net.sourceforge.pmd.reporting.FileAnalysisListener; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index a5a06f4659..249c089df0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -12,7 +12,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -47,8 +46,8 @@ import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; import net.sourceforge.pmd.lang.document.FileCollector; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; -import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.renderers.Renderer; +import net.sourceforge.pmd.reporting.ConfigurableFileNameRenderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.ListenerInitializer; import net.sourceforge.pmd.reporting.ReportStats; @@ -100,6 +99,7 @@ public final class PmdAnalysis implements AutoCloseable { private final Map langProperties = new HashMap<>(); private boolean closed; + private final ConfigurableFileNameRenderer fileNameRenderer = new ConfigurableFileNameRenderer(); /** * Constructs a new instance. The files paths (input files, filelist, @@ -115,9 +115,6 @@ public final class PmdAnalysis implements AutoCloseable { reporter ); - for (Path path : config.getRelativizeRoots()) { - this.relativizeWith(path); - } } /** @@ -171,6 +168,10 @@ public final class PmdAnalysis implements AutoCloseable { } } + for (Path path : config.getRelativizeRoots()) { + pmd.fileNameRenderer.relativizeWith(path); + } + return pmd; } @@ -289,43 +290,9 @@ public final class PmdAnalysis implements AutoCloseable { return langProperties.computeIfAbsent(language, Language::newPropertyBundle); } - private final List relativizeRootPaths = new ArrayList<>(); - /** - * Add a prefix that is used to relativize file paths as their display name. - * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, - * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} - * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a - * display name of {@code main/java/org/foo.java}. - * - *

This only matters for files added from a {@link Path} object. - * - * @param path Path with which to relativize - */ - public void relativizeWith(Path path) { - this.relativizeRootPaths.add(Objects.requireNonNull(path)); - this.relativizeRootPaths.sort(Comparator.naturalOrder()); - } - public FileNameRenderer getFileNameRenderer() { - return new FileNameRenderer() { - private final List relativizeRootPaths = new ArrayList<>(PmdAnalysis.this.relativizeRootPaths); - - @Override - public String getDisplayName(FileId fileId) { - String localDisplayName = getLocalDisplayName(fileId); - if (fileId.getParentFsPath() != null) { - return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; - } - return localDisplayName; - } - - private String getLocalDisplayName(FileId file) { - if (!relativizeRootPaths.isEmpty()) { - return PmdAnalysis.getDisplayName(file, relativizeRootPaths); - } - return file.getOriginalPath(); - } - }; + public ConfigurableFileNameRenderer fileNameRenderer() { + return fileNameRenderer; } /** @@ -378,7 +345,7 @@ public final class PmdAnalysis implements AutoCloseable { // Initialize listeners try (ListenerInitializer initializer = listener.initializer()) { initializer.setNumberOfFilesToAnalyze(textFiles.size()); - initializer.setFileNameRenderer(getFileNameRenderer()); + initializer.setFileNameRenderer(fileNameRenderer()); } } catch (Exception e) { reporter.errorEx("Exception while initializing analysis listeners", e); @@ -449,7 +416,7 @@ public final class PmdAnalysis implements AutoCloseable { List rendererListeners = new ArrayList<>(renderers.size()); for (Renderer renderer : renderers) { try { - renderer.setFileNameRenderer(getFileNameRenderer()); + renderer.setFileNameRenderer(fileNameRenderer()); @SuppressWarnings("PMD.CloseResource") GlobalAnalysisListener listener = Objects.requireNonNull(renderer.newListener(), "Renderer should provide non-null listener"); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java index 9f532e623b..57f4a69b45 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java @@ -11,6 +11,7 @@ import net.sourceforge.pmd.annotation.Experimental; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.properties.AbstractPropertySource; +import net.sourceforge.pmd.reporting.FileNameRenderer; /** * Abstract base class for {@link Renderer} implementations. diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java index 91ce73223f..ff84c4eff5 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/Renderer.java @@ -22,6 +22,7 @@ import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sourceforge.pmd.properties.PropertySource; import net.sourceforge.pmd.reporting.FileAnalysisListener; +import net.sourceforge.pmd.reporting.FileNameRenderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.ListenerInitializer; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java new file mode 100644 index 0000000000..87fb306440 --- /dev/null +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java @@ -0,0 +1,55 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.reporting; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Objects; + +import net.sourceforge.pmd.PmdAnalysis; +import net.sourceforge.pmd.lang.document.FileId; +import net.sourceforge.pmd.lang.document.TextFile; + +/** + * @author Clément Fournier + */ +public class ConfigurableFileNameRenderer implements FileNameRenderer { + + private final List relativizeRootPaths = new ArrayList<>(); + + /** + * Add a prefix that is used to relativize file paths as their display name. + * For instance, when adding a file {@code /tmp/src/main/java/org/foo.java}, + * and relativizing with {@code /tmp/src/}, the registered {@link TextFile} + * will have a path id of {@code /tmp/src/main/java/org/foo.java}, and a + * display name of {@code main/java/org/foo.java}. + * + *

This only matters for files added from a {@link Path} object. + * + * @param path Path with which to relativize + */ + public void relativizeWith(Path path) { + this.relativizeRootPaths.add(Objects.requireNonNull(path)); + this.relativizeRootPaths.sort(Comparator.naturalOrder()); + } + + @Override + public String getDisplayName(FileId fileId) { + String localDisplayName = getLocalDisplayName(fileId); + if (fileId.getParentFsPath() != null) { + return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; + } + return localDisplayName; + } + + private String getLocalDisplayName(FileId file) { + if (!relativizeRootPaths.isEmpty()) { + return PmdAnalysis.getDisplayName(file, relativizeRootPaths); + } + return file.getOriginalPath(); + } +} diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java similarity index 80% rename from pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java rename to pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java index 72a9c0634f..98b3c2c79a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/FileNameRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java @@ -2,13 +2,13 @@ * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -package net.sourceforge.pmd.renderers; +package net.sourceforge.pmd.reporting; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** - * Renders a {@link FileId} into a display name. + * Renders a {@link FileId} into a display name for the file. * * @author Clément Fournier */ @@ -17,6 +17,7 @@ public interface FileNameRenderer { String getDisplayName(FileId fileId); + default String getDisplayName(TextFile textFile) { return getDisplayName(textFile.getPathId()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java index 397a7da08d..56a6d2e68f 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java @@ -9,7 +9,6 @@ import java.util.Collection; import java.util.List; import net.sourceforge.pmd.internal.util.IOUtil; -import net.sourceforge.pmd.renderers.FileNameRenderer; import net.sourceforge.pmd.util.AssertionUtil; /** diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index d61b9d552c..cb30ddc4b8 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -93,7 +93,7 @@ class PMDFilelistTest { } public static void assertHasName(TextFile textFile, String expected, PmdAnalysis pmd) { - assertThat(pmd.getFileNameRenderer().getDisplayName(textFile), equalTo(expected)); + assertThat(pmd.fileNameRenderer().getDisplayName(textFile), equalTo(expected)); } @Test diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java index 7c73f69feb..f2b4c4264b 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java @@ -42,7 +42,7 @@ class NioTextFileTest { assertEquals(1, collectedFiles.size()); TextFile textFile = collectedFiles.get(0); assertEquals(zipArchive.toAbsolutePath() + "!/path/inside/someSource.dummy", - pmd.getFileNameRenderer().getDisplayName(textFile)); + pmd.fileNameRenderer().getDisplayName(textFile)); } } } From 7bcb7026dc023597f48a8698aa7e574e89241512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Mon, 20 Mar 2023 12:10:08 +0100 Subject: [PATCH 11/14] Lint --- pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java | 2 +- .../main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java | 2 +- pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java | 2 +- .../java/net/sourceforge/pmd/RuleViolationComparatorTest.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java index 9caa906250..3b0f1518a7 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleViolation.java @@ -8,8 +8,8 @@ import java.util.Comparator; import java.util.Map; import net.sourceforge.pmd.annotation.DeprecatedUntil700; -import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.FileId; +import net.sourceforge.pmd.lang.document.FileLocation; /** * A RuleViolation is created by a Rule when it identifies a violation of the diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java index ba2bf564a1..d4115e77b3 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/TokenMgrError.java @@ -8,8 +8,8 @@ import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import net.sourceforge.pmd.annotation.InternalApi; -import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.FileId; +import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.util.StringUtil; /** diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java index f2d4e7b916..b3a10c642d 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java @@ -17,8 +17,8 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.FileId; +import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java index 994552bd28..8e431d4a7f 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleViolationComparatorTest.java @@ -16,8 +16,8 @@ import java.util.Random; import org.junit.jupiter.api.Test; -import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.FileId; +import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.MockRule; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; From ad219c9967ceb311e47554686c01585a3abbebb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Mon, 20 Mar 2023 12:17:14 +0100 Subject: [PATCH 12/14] Move members around --- .../net/sourceforge/pmd/ant/Formatter.java | 2 +- .../java/net/sourceforge/pmd/PmdAnalysis.java | 58 ----------------- .../ConfigurableFileNameRenderer.java | 62 ++++++++++++++++++- .../pmd/lang/document/FileCollectorTest.java | 7 --- .../ConfigurableFileNameRendererTest.java | 39 ++++++++++++ 5 files changed, 100 insertions(+), 68 deletions(-) create mode 100644 pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java index 8201ef9878..cbdea6ac17 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/Formatter.java @@ -29,10 +29,10 @@ import net.sourceforge.pmd.Report; import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.TextFile; -import net.sourceforge.pmd.reporting.FileNameRenderer; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.renderers.RendererFactory; import net.sourceforge.pmd.reporting.FileAnalysisListener; +import net.sourceforge.pmd.reporting.FileNameRenderer; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; import net.sourceforge.pmd.reporting.ListenerInitializer; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index 249c089df0..6b4af459f1 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -6,10 +6,8 @@ package net.sourceforge.pmd; import static net.sourceforge.pmd.util.CollectionUtil.listOf; -import java.io.File; import java.nio.file.Path; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -19,7 +17,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; @@ -44,7 +41,6 @@ import net.sourceforge.pmd.lang.LanguageRegistry; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.LanguageVersionDiscoverer; import net.sourceforge.pmd.lang.document.FileCollector; -import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.reporting.ConfigurableFileNameRenderer; @@ -566,58 +562,4 @@ public final class PmdAnalysis implements AutoCloseable { } } - /** - * Return the textfile's display name. Takes the shortest path we - * can construct from the relativize roots. - * - *

package private for test only

- */ - public static String getDisplayName(FileId file, List relativizeRoots) { - String best = file.toAbsolutePath(); - for (Path root : relativizeRoots) { - if (isFileSystemRoot(root)) { - // Absolutize the path. Since the relativize roots are - // sorted by ascending length, this should be the first in the list - // (so another root can override it). - best = file.toAbsolutePath(); - continue; - } - - String relative = relativizePath(root.toAbsolutePath().toString(), file.toAbsolutePath()); - if (countSegments(relative) < countSegments(best)) { - best = relative; - } - } - return best; - } - - private static int countSegments(String best) { - return StringUtils.countMatches(best, File.separatorChar); - } - - private static String relativizePath(String base, String other) { - String[] baseSegments = base.split("[/\\\\]"); - String[] otherSegments = other.split("[/\\\\]"); - int prefixLength = 0; - int maxi = Math.min(baseSegments.length, otherSegments.length); - while (prefixLength < maxi && baseSegments[prefixLength].equals(otherSegments[prefixLength])) { - prefixLength++; - } - - if (prefixLength == 0) { - return other; - } - - List relative = new ArrayList<>(); - for (int i = prefixLength; i < baseSegments.length; i++) { - relative.add(".."); - } - relative.addAll(Arrays.asList(otherSegments).subList(prefixLength, otherSegments.length)); - return String.join(File.separator, relative); - } - - /** Return whether the path is the root path (/). */ - private static boolean isFileSystemRoot(Path root) { - return root.isAbsolute() && root.getNameCount() == 0; - } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java index 87fb306440..b40b019b7b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java @@ -4,13 +4,16 @@ package net.sourceforge.pmd.reporting; +import java.io.File; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; -import net.sourceforge.pmd.PmdAnalysis; +import org.apache.commons.lang3.StringUtils; + import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; @@ -48,8 +51,63 @@ public class ConfigurableFileNameRenderer implements FileNameRenderer { private String getLocalDisplayName(FileId file) { if (!relativizeRootPaths.isEmpty()) { - return PmdAnalysis.getDisplayName(file, relativizeRootPaths); + return getDisplayName(file, relativizeRootPaths); } return file.getOriginalPath(); } + + private static int countSegments(String best) { + return StringUtils.countMatches(best, File.separatorChar); + } + + static String relativizePath(String base, String other) { + String[] baseSegments = base.split("[/\\\\]"); + String[] otherSegments = other.split("[/\\\\]"); + int prefixLength = 0; + int maxi = Math.min(baseSegments.length, otherSegments.length); + while (prefixLength < maxi && baseSegments[prefixLength].equals(otherSegments[prefixLength])) { + prefixLength++; + } + + if (prefixLength == 0) { + return other; + } + + List relative = new ArrayList<>(); + for (int i = prefixLength; i < baseSegments.length; i++) { + relative.add(".."); + } + relative.addAll(Arrays.asList(otherSegments).subList(prefixLength, otherSegments.length)); + return String.join(File.separator, relative); + } + + /** Return whether the path is the root path (/). */ + private static boolean isFileSystemRoot(Path root) { + return root.isAbsolute() && root.getNameCount() == 0; + } + + /** + * Return the textfile's display name. Takes the shortest path we + * can construct from the relativize roots. + * + *

package private for test only

+ */ + static String getDisplayName(FileId file, List relativizeRoots) { + String best = file.toAbsolutePath(); + for (Path root : relativizeRoots) { + if (isFileSystemRoot(root)) { + // Absolutize the path. Since the relativize roots are + // sorted by ascending length, this should be the first in the list + // (so another root can override it). + best = file.toAbsolutePath(); + continue; + } + + String relative = relativizePath(root.toAbsolutePath().toString(), file.toAbsolutePath()); + if (countSegments(relative) < countSegments(best)) { + best = relative; + } + } + return best; + } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index a6b47cb18e..234e4ecd60 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -12,13 +12,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.lang.DummyLanguageModule; import net.sourceforge.pmd.lang.Language; import net.sourceforge.pmd.lang.LanguageRegistry; @@ -93,11 +91,6 @@ class FileCollectorTest { } - @Test - void testRelativize() { - String displayName = PmdAnalysis.getDisplayName(FileId.forPath(Paths.get("a", "b", "c")), listOf(Paths.get("a"))); - assertEquals(displayName, Paths.get("b", "c").toString()); - } private Path newFile(Path root, String path) throws IOException { Path resolved = root.resolve(path); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java new file mode 100644 index 0000000000..a33c32d340 --- /dev/null +++ b/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java @@ -0,0 +1,39 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.reporting; + +import static net.sourceforge.pmd.reporting.ConfigurableFileNameRenderer.getDisplayName; +import static net.sourceforge.pmd.util.CollectionUtil.listOf; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.jupiter.api.Test; + +import net.sourceforge.pmd.lang.document.FileId; + +/** + * @author Clément Fournier + */ +public class ConfigurableFileNameRendererTest { + + @Test + void testRelativize() { + FileId file = FileId.forPath(Paths.get("a", "b", "c")); + String displayName = getDisplayName(file, listOf(Paths.get("a"))); + assertEquals(displayName, Paths.get("b", "c").toString()); + } + + @Test + void testRelativizeWithRoot() { + Path path = Paths.get("a", "b", "c"); + FileId file = FileId.forPath(path); + String displayName = getDisplayName(file, listOf(Paths.get("/"))); + assertEquals(path.toAbsolutePath().toString(), + displayName); + } + +} From b71e1711e5af4945c689ef329ae740b241f22163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Mon, 20 Mar 2023 12:43:09 +0100 Subject: [PATCH 13/14] Cleanups and renamings --- .../pmd/ant/internal/PMDTaskImpl.java | 2 +- .../pmd/lang/apex/ast/ASTApexFile.java | 11 +- .../pmd/lang/apex/ast/ApexParser.java | 2 +- .../pmd/lang/apex/ast/CompilerService.java | 2 +- .../lang/apex/ast/ASTSwitchStatementTest.java | 2 +- .../pmd/lang/apex/ast/ApexParserTestBase.java | 7 -- .../pmd/lang/apex/rule/ApexXPathRuleTest.java | 3 +- .../java/net/sourceforge/pmd/PmdAnalysis.java | 1 - .../java/net/sourceforge/pmd/RuleSet.java | 2 +- .../java/net/sourceforge/pmd/RuleSets.java | 2 +- .../pmd/cache/AbstractAnalysisCache.java | 10 +- .../pmd/cache/FileAnalysisCache.java | 2 +- .../pmd/cpd/internal/AntlrTokenizer.java | 2 +- .../pmd/cpd/internal/JavaCCTokenizer.java | 2 +- .../pmd/lang/ast/FileAnalysisException.java | 2 +- .../net/sourceforge/pmd/lang/ast/Parser.java | 2 +- .../ast/impl/antlr4/AntlrTokenManager.java | 2 +- .../ast/impl/javacc/JjtreeParserAdapter.java | 2 +- .../pmd/lang/document/BaseMappedDocument.java | 4 +- .../pmd/lang/document/FileCollector.java | 10 +- .../sourceforge/pmd/lang/document/FileId.java | 112 +++++++++++++++--- .../pmd/lang/document/NioTextFile.java | 2 +- .../lang/document/ReadOnlyFileException.java | 2 +- .../pmd/lang/document/ReaderTextFile.java | 2 +- .../pmd/lang/document/RootTextDocument.java | 4 +- .../pmd/lang/document/StringTextFile.java | 7 +- .../pmd/lang/document/TextDocument.java | 11 +- .../pmd/lang/document/TextFile.java | 37 ++---- .../pmd/lang/impl/PmdRunnable.java | 10 +- .../lang/rule/internal/RuleApplicator.java | 4 +- .../xpath/internal/FileNameXPathFunction.java | 2 +- .../pmd/renderers/AbstractRenderer.java | 2 +- .../ConfigurableFileNameRenderer.java | 8 +- .../pmd/reporting/FileNameRenderer.java | 16 ++- .../pmd/reporting/GlobalAnalysisListener.java | 7 +- .../pmd/reporting/ListenerInitializer.java | 22 +++- .../pmd/cache/FileAnalysisCacheTest.java | 10 +- .../sourceforge/pmd/cli/PMDFilelistTest.java | 6 +- .../pmd/lang/document/FileCollectorTest.java | 2 +- .../pmd/lang/document/TextFilesTest.java | 18 +-- .../pmd/processor/GlobalListenerTest.java | 2 +- .../processor/MultiThreadProcessorTest.java | 2 +- .../ConfigurableFileNameRendererTest.java | 5 +- .../sourceforge/pmd/cpd/GroovyTokenizer.java | 5 +- .../java/rule/internal/TypeResTestRule.java | 5 +- .../sourceforge/pmd/cpd/ScalaTokenizer.java | 6 +- .../pmd/lang/xml/rule/XmlXPathRuleTest.java | 3 +- 47 files changed, 222 insertions(+), 162 deletions(-) diff --git a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java index a6e48e9f9d..d1c9778964 100644 --- a/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java +++ b/pmd-ant/src/main/java/net/sourceforge/pmd/ant/internal/PMDTaskImpl.java @@ -178,7 +178,7 @@ public class PMDTaskImpl { @Override public FileAnalysisListener startFileAnalysis(TextFile dataSource) { - String name = dataSource.getPathId().toUriString(); + String name = dataSource.getFileId().toUriString(); project.log("Processing file " + name, Project.MSG_VERBOSE); return FileAnalysisListener.noop(); } diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTApexFile.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTApexFile.java index 1a2c708dfd..003100961c 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTApexFile.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ASTApexFile.java @@ -4,8 +4,6 @@ package net.sourceforge.pmd.lang.apex.ast; -import java.net.URI; -import java.nio.file.Paths; import java.util.List; import java.util.Map; @@ -16,6 +14,7 @@ import net.sourceforge.pmd.lang.apex.multifile.ApexMultifileAnalysis; import net.sourceforge.pmd.lang.ast.AstInfo; import net.sourceforge.pmd.lang.ast.Parser.ParserTask; import net.sourceforge.pmd.lang.ast.RootNode; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextRegion; import apex.jorje.semantic.ast.AstNode; @@ -63,11 +62,7 @@ public final class ASTApexFile extends AbstractApexNode implements Root } public List getGlobalIssues() { - String filename = getAstInfo().getTextDocument().getPathId(); - if (filename.length() > 7 && "file://".equalsIgnoreCase(filename.substring(0, 7))) { - URI uri = URI.create(filename); - filename = Paths.get(uri).toString(); - } - return multifileAnalysis.getFileIssues(filename); + FileId fileId = getAstInfo().getTextDocument().getFileId(); + return multifileAnalysis.getFileIssues(fileId.toAbsolutePath()); } } diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java index 180b04e6f5..6d95b1858d 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/ApexParser.java @@ -33,7 +33,7 @@ public final class ApexParser implements Parser { final ApexTreeBuilder treeBuilder = new ApexTreeBuilder(task, (ApexLanguageProcessor) task.getLanguageProcessor()); return treeBuilder.buildTree(astRoot); } catch (apex.jorje.services.exception.ParseException e) { - FileLocation loc = FileLocation.caret(task.getTextDocument().getPathId(), e.getLoc().getLine(), e.getLoc().getColumn()); + FileLocation loc = FileLocation.caret(task.getTextDocument().getFileId(), e.getLoc().getLine(), e.getLoc().getColumn()); throw new ParseException(e).withLocation(loc); } } diff --git a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java index 6de5f1aa1c..9270659fce 100644 --- a/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java +++ b/pmd-apex/src/main/java/net/sourceforge/pmd/lang/apex/ast/CompilerService.java @@ -63,7 +63,7 @@ class CompilerService { public Compilation parseApex(TextDocument document) { SourceFile sourceFile = SourceFile.builder() .setBody(document.getText().toString()) - .setKnownName(document.getPathId().toUriString()) + .setKnownName(document.getFileId().toUriString()) .build(); ApexCompiler compiler = ApexCompiler.builder().setInput(createCompilationInput(Collections.singletonList(sourceFile))).build(); compiler.compile(CompilerStage.POST_TYPE_RESOLVE); diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ASTSwitchStatementTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ASTSwitchStatementTest.java index 28feed0833..e8105608e5 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ASTSwitchStatementTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ASTSwitchStatementTest.java @@ -15,7 +15,7 @@ class ASTSwitchStatementTest extends ApexParserTestBase { @Test void testExamples() { - ApexNode node = parseResource("SwitchStatements.cls"); + ApexNode node = apex.parseResource("SwitchStatements.cls").getMainNode(); List switchStatements = node.findDescendantsOfType(ASTSwitchStatement.class); assertEquals(4, switchStatements.size()); diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTestBase.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTestBase.java index 6ad7de0e66..8943aedd9e 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTestBase.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexParserTestBase.java @@ -13,11 +13,4 @@ public class ApexParserTestBase { return apex.parse(code).getMainNode(); } - protected ASTUserClassOrInterface parse(String code, String fileName) { - return apex.parse(code, null, fileName).getMainNode(); - } - - protected ASTUserClassOrInterface parseResource(String code) { - return apex.parseResource(code).getMainNode(); - } } diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/rule/ApexXPathRuleTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/rule/ApexXPathRuleTest.java index b13d5aa921..09346eb0f7 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/rule/ApexXPathRuleTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/rule/ApexXPathRuleTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.lang.apex.ast.ApexParserTestBase; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.rule.XPathRule; /** @@ -26,7 +27,7 @@ class ApexXPathRuleTest extends ApexParserTestBase { void testFileNameInXpath() { Report report = apex.executeRule(makeXPath("/UserClass[pmd:fileName() = 'Foo.cls']"), "class Foo {}", - "src/Foo.cls"); + FileId.fromPathLikeString("src/Foo.cls")); assertSize(report, 1); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index 6b4af459f1..9c245da8f3 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -412,7 +412,6 @@ public final class PmdAnalysis implements AutoCloseable { List rendererListeners = new ArrayList<>(renderers.size()); for (Renderer renderer : renderers) { try { - renderer.setFileNameRenderer(fileNameRenderer()); @SuppressWarnings("PMD.CloseResource") GlobalAnalysisListener listener = Objects.requireNonNull(renderer.newListener(), "Renderer should provide non-null listener"); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java index 664161f250..c87cc6cb69 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSet.java @@ -627,7 +627,7 @@ public class RuleSet implements ChecksumAware { * false otherwise */ boolean applies(TextFile file) { - return applies(file.getPathId()); + return applies(file.getFileId()); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java index cde200cc8f..5a118bca1a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/RuleSets.java @@ -154,7 +154,7 @@ public class RuleSets { } for (RuleSet ruleSet : ruleSets) { - if (ruleSet.applies(root.getTextDocument().getPathId())) { + if (ruleSet.applies(root.getTextDocument().getFileId())) { ruleApplicator.apply(ruleSet.getRules(), listener); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java index b687a6106e..e41ff46677 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java @@ -69,7 +69,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public boolean isUpToDate(final TextDocument document) { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "up-to-date check")) { - final AnalysisResult cachedResult = fileResultsCache.get(document.getPathId()); + final AnalysisResult cachedResult = fileResultsCache.get(document.getFileId()); final AnalysisResult updatedResult; // is this a known file? has it changed? @@ -89,7 +89,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { updatedResult = new AnalysisResult(document.getCheckSum(), new ArrayList<>()); } - updatedResultsCache.put(document.getPathId(), updatedResult); + updatedResultsCache.put(document.getFileId(), updatedResult); return upToDate; } @@ -97,7 +97,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public List getCachedViolations(final TextDocument sourceFile) { - final AnalysisResult analysisResult = fileResultsCache.get(sourceFile.getPathId()); + final AnalysisResult analysisResult = fileResultsCache.get(sourceFile.getFileId()); if (analysisResult == null) { // new file, avoid nulls @@ -109,7 +109,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public void analysisFailed(final TextDocument sourceFile) { - updatedResultsCache.remove(sourceFile.getPathId()); + updatedResultsCache.remove(sourceFile.getFileId()); } @@ -218,7 +218,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override public FileAnalysisListener startFileAnalysis(TextDocument file) { - final FileId fileName = file.getPathId(); + final FileId fileName = file.getFileId(); return new FileAnalysisListener() { @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java index b81ef227c6..68df8f6715 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java @@ -62,7 +62,7 @@ public class FileAnalysisCache extends AbstractAnalysisCache { */ private void loadFromFile(final File cacheFile, Set files) { Map idMap = - files.stream().map(TextFile::getPathId) + files.stream().map(TextFile::getFileId) .collect(Collectors.toMap(FileId::toUriString, id -> id)); try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "load")) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java index 7693a7a39b..23235df0e0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/AntlrTokenizer.java @@ -32,7 +32,7 @@ public abstract class AntlrTokenizer implements Tokenizer { public void tokenize(final SourceCode sourceCode, final Tokens tokenEntries) { try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { - CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getPathId().getOriginalPath()); + CharStream charStream = CharStreams.fromString(textDoc.getText().toString(), textDoc.getFileId().getOriginalPath()); final AntlrTokenManager tokenManager = new AntlrTokenManager(getLexerForSource(charStream), textDoc); final AntlrTokenFilter tokenFilter = getTokenFilter(tokenManager); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java index f85f739734..083780a33a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cpd/internal/JavaCCTokenizer.java @@ -58,7 +58,7 @@ public abstract class JavaCCTokenizer implements Tokenizer { currentToken = tokenFilter.getNextToken(); } } catch (FileAnalysisException e) { - throw e.setFileId(textFile.getPathId()); + throw e.setFileId(textFile.getFileId()); } finally { tokenEntries.add(TokenEntry.getEOF()); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java index 3e2f780aca..db2fdefc2d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/FileAnalysisException.java @@ -78,7 +78,7 @@ public class FileAnalysisException extends RuntimeException { } FileLocation loc = location(); if (loc != null) { - result += loc.startPosToString(); + result += " at " + loc.startPosToString(); } return result; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java index 292c81e012..ef0cd3aa7e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/Parser.java @@ -59,7 +59,7 @@ public interface Parser { * not be interpreted, it may not be a file-system path. */ public String getFileDisplayName() { - return textDoc.getPathId().getOriginalPath(); + return textDoc.getFileId().getOriginalPath(); } /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java index 3710fc728c..6233d29a11 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/antlr4/AntlrTokenManager.java @@ -63,7 +63,7 @@ public class AntlrTokenManager implements TokenManager { final int charPositionInLine, final String msg, final RecognitionException ex) { - throw new TokenMgrError(line, charPositionInLine, textDoc.getPathId(), msg, ex); + throw new TokenMgrError(line, charPositionInLine, textDoc.getFileId(), msg, ex); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java index 85dfe0b770..3838c48655 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/ast/impl/javacc/JjtreeParserAdapter.java @@ -35,7 +35,7 @@ public abstract class JjtreeParserAdapter implements Parser // Finally, do the parsing return parseImpl(charStream, task); } catch (FileAnalysisException tme) { - throw tme.setFileId(task.getTextDocument().getPathId()); + throw tme.setFileId(task.getTextDocument().getFileId()); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java index 45e08af5f0..bb4bf3e522 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/BaseMappedDocument.java @@ -26,8 +26,8 @@ abstract class BaseMappedDocument implements TextDocument { } @Override - public FileId getPathId() { - return base.getPathId(); + public FileId getFileId() { + return base.getFileId(); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java index 21a8a8d98e..b5cd3bc7c4 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileCollector.java @@ -103,7 +103,7 @@ public final class FileCollector implements AutoCloseable { throw new IllegalStateException("Collector was closed!"); } List allFilesToProcess = new ArrayList<>(this.allFilesToProcess); - allFilesToProcess.sort(Comparator.comparing(TextFile::getPathId)); + allFilesToProcess.sort(Comparator.comparing(TextFile::getFileId)); return Collections.unmodifiableList(allFilesToProcess); } @@ -207,7 +207,7 @@ public final class FileCollector implements AutoCloseable { } private boolean addFileImpl(TextFile textFile) { - LOG.trace("Adding file {} (lang: {}) ", textFile.getPathId(), textFile.getLanguageVersion().getTerseName()); + LOG.trace("Adding file {} (lang: {}) ", textFile.getFileId().toAbsolutePath(), textFile.getLanguageVersion().getTerseName()); if (allFilesToProcess.add(textFile)) { return true; } @@ -244,7 +244,7 @@ public final class FileCollector implements AutoCloseable { if (!fileVersion.equals(contextVersion)) { reporter.error( "Cannot add file {0}: version ''{1}'' does not match ''{2}''", - textFile.getPathId(), + textFile.getFileId(), fileVersion, contextVersion ); @@ -397,7 +397,7 @@ public final class FileCollector implements AutoCloseable { for (Iterator iterator = allFilesToProcess.iterator(); iterator.hasNext();) { TextFile file = iterator.next(); if (toExclude.contains(file)) { - LOG.trace("Excluding file {}", file.getPathId()); + LOG.trace("Excluding file {}", file.getFileId()); iterator.remove(); } } @@ -423,7 +423,7 @@ public final class FileCollector implements AutoCloseable { TextFile file = iterator.next(); Language lang = file.getLanguageVersion().getLanguage(); if (!languages.contains(lang)) { - LOG.trace("Filtering out {}, no rules for language {}", file.getPathId(), lang); + LOG.trace("Filtering out {}, no rules for language {}", file.getFileId(), lang); iterator.remove(); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java index 3e438755aa..b2c3db842e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/FileId.java @@ -9,39 +9,57 @@ import java.nio.file.Paths; import org.checkerframework.checker.nullness.qual.Nullable; +import net.sourceforge.pmd.RuleViolation; +import net.sourceforge.pmd.renderers.Renderer; + /** - * A virtual path for a {@link TextFile}. + * An identifier for a {@link TextFile}. This is not a path, but provides + * several methods to be rendered into path-like strings in different formats + * (for use mostly by {@link Renderer} instances). File IDs are used to + * identify files e.g. in {@link RuleViolation}, {@link FileLocation}, {@link TextFile}. + * + *

Note that the addressed file may not be an actual file on a file system. + * For instance, you can create file ids from strings ({@link #fromPathLikeString(String)}), + * or use {@link #STDIN} to address standard input. The rendering methods + * of this interface (like {@link #toAbsolutePath()}) do not have to return + * actual paths for those exotic files, and operate on a best-effort basis. * * @author Clément Fournier */ public interface FileId extends Comparable { /** - * The name used for a file that has no name. This is mostly only + * The name used for an unknown file. This is mostly only * relevant for unit tests. */ - FileId UNKNOWN = fromPathLikeString("(unknown file)"); + FileId UNKNOWN = new FileId() { + @Override + public String getFileName() { + return "(unknown)"; + } - @Nullable FileId getParentFsPath(); + @Override + public String getOriginalPath() { + return "(unknown)"; + } - String toUriString(); + @Override + public String toAbsolutePath() { + return getOriginalPath(); + } - String getFileName(); + @Override + public String toUriString() { + return "file://" + getOriginalPath(); + } - String getOriginalPath(); - - String toAbsolutePath(); - - - @Override - boolean equals(Object o); - - - @Override - default int compareTo(FileId o) { - return this.toUriString().compareTo(o.toUriString()); - } + @Override + public @Nullable FileId getParentFsPath() { + return null; + } + }; + /** The virtual file ID for standard input. */ FileId STDIN = new FileId() { @Override public String toAbsolutePath() { @@ -69,6 +87,62 @@ public interface FileId extends Comparable { } }; + + /** + * Return the simple file name, like {@link Path#getFileName()}. + * This includes the extension. + */ + String getFileName(); + + /** + * Return the path as it was input by the user. This may be a + * relative or absolute path. + */ + String getOriginalPath(); + + /** + * Return an absolute path to this file in its containing file system. + * If the file is in a zip file, then this returns a path from the + * zip root, and does not include the path of the zip itself. + */ + String toAbsolutePath(); + + /** + * Return a string that looks like a URI pointing to this file. + * TODO what does this do for a zip file? + */ + String toUriString(); + + /** + * If this file is in a nested filesystem (eg a zip file), return + * the file ID of the container in the outer file system. Return + * null if this is in the root file system. + */ + @Nullable FileId getParentFsPath(); + + + /** + * Two file IDs are equal if they have the same {@link #toUriString()}. + * + * @param o Object + */ + @Override + boolean equals(Object o); + + + @Override + default int compareTo(FileId o) { + return this.toAbsolutePath().compareTo(o.toAbsolutePath()); + } + + /** + * This method is intentionally only meant for debugging, and its output + * is unspecified. Code that needs a string representation should use one + * of the named string conversion methods. + */ + @Override + String toString(); + static FileId fromPathLikeString(String str) { String[] segments = str.split("[/\\\\]"); if (segments.length == 0) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java index 7f7b517078..e68e4cacec 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/NioTextFile.java @@ -53,7 +53,7 @@ class NioTextFile extends BaseCloseable implements TextFile { } @Override - public FileId getPathId() { + public FileId getFileId() { return fileId; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReadOnlyFileException.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReadOnlyFileException.java index df27cb13c1..73f088454b 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReadOnlyFileException.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReadOnlyFileException.java @@ -11,7 +11,7 @@ package net.sourceforge.pmd.lang.document; public class ReadOnlyFileException extends UnsupportedOperationException { public ReadOnlyFileException(TextFile textFile) { - super("Read only: " + textFile.getPathId()); + super("Read only: " + textFile.getFileId()); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java index a1583903ae..45c634bd9a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/ReaderTextFile.java @@ -32,7 +32,7 @@ class ReaderTextFile implements TextFile { } @Override - public FileId getPathId() { + public FileId getFileId() { return fileId; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java index afbe72bc37..05bfe407e9 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/RootTextDocument.java @@ -33,7 +33,7 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { this.backend = backend; this.content = backend.readContents(); this.langVersion = backend.getLanguageVersion(); - this.fileId = backend.getPathId(); + this.fileId = backend.getFileId(); Objects.requireNonNull(langVersion, "Null language version for file " + backend); Objects.requireNonNull(fileId, "Null path id for file " + backend); @@ -45,7 +45,7 @@ final class RootTextDocument extends BaseCloseable implements TextDocument { } @Override - public FileId getPathId() { + public FileId getFileId() { return fileId; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java index b78ab18615..d95f7e5ffa 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/StringTextFile.java @@ -35,12 +35,7 @@ class StringTextFile implements TextFile { } @Override - public @NonNull String getDisplayName() { - return fileId.toUriString(); - } - - @Override - public FileId getPathId() { + public FileId getFileId() { return fileId; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java index 7aa6ea5dd2..b465062c01 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextDocument.java @@ -86,16 +86,9 @@ public interface TextDocument extends Closeable { LanguageVersion getLanguageVersion(); /** - * Returns {@link TextFile#getPathId()} for the text file backing this document. + * Returns {@link TextFile#getFileId()} for the text file backing this document. */ - FileId getPathId(); - - /** - * Returns {@link TextFile#getDisplayName()} for the text file backing this document. - */ - default String getDisplayName() { - return getPathId().getOriginalPath(); - } + FileId getFileId(); /** diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java index 8aea8fa217..62a2cb45cb 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/document/TextFile.java @@ -13,7 +13,6 @@ import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.Charset; import java.nio.file.Path; -import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; @@ -48,7 +47,7 @@ public interface TextFile extends Closeable { /** * Returns the language version which should be used to process this * file. This is a property of the file, which allows sources for - * several different language versions to be processed in the same + * different language versions to be processed in the same * PMD run. It also makes it so, that the file extension is not interpreted * to find out the language version after the initial file collection * phase. @@ -60,29 +59,13 @@ public interface TextFile extends Closeable { /** - * Returns an identifier for the path of this file. This should not + * Returns an identifier for this file. This should not * be interpreted as a {@link File}, it may not be a file on this - * filesystem. The only requirement for this method, is that two - * distinct text files should have distinct path IDs, and that from - * one analysis to the next, the path ID of logically identical files - * be the same. - * - *

Basically this may be implemented as a URL, or a file path. It - * is used to index violation caches. + * filesystem. Two distinct text files should have distinct path IDs, + * and from one analysis to the next, the path ID of logically identical + * files should be the same. */ - FileId getPathId(); - - - /** - * Returns a display name for the file. This name is used for - * reporting and should not be interpreted. It may be relative - * to a directory or so, it may also not be normalized. Use - * {@link #getPathId()} when you want an identifier. - */ - @Deprecated - default @NonNull String getDisplayName() { - return getPathId().getOriginalPath(); - } + FileId getFileId(); /** @@ -262,7 +245,6 @@ public interface TextFile extends Closeable { if (languageVersion == null) { throw new NullPointerException("no language version detected for " + pathId); } - String shortPaths = config.getInputPathList().stream().map(Path::toString).collect(Collectors.joining(",")); class DataSourceTextFile extends BaseCloseable implements TextFile { @Override @@ -271,15 +253,10 @@ public interface TextFile extends Closeable { } @Override - public FileId getPathId() { + public FileId getFileId() { return fileId2; } - @Override - public @NonNull String getDisplayName() { - return ds.getNiceFileName(false, shortPaths); - } - @Override public TextFileContent readContents() throws IOException { ensureOpen(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java index d11e34bedf..4db84426c6 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/impl/PmdRunnable.java @@ -70,12 +70,12 @@ abstract class PmdRunnable implements Runnable { FileAnalysisListener completeListener = FileAnalysisListener.tee(listOf(listener, cacheListener)); if (analysisCache.isUpToDate(textDocument)) { - LOG.trace("Skipping file (lang: {}) because it was found in the cache: {}", textFile.getLanguageVersion(), textFile.getPathId()); + LOG.trace("Skipping file (lang: {}) because it was found in the cache: {}", textFile.getLanguageVersion(), textFile.getFileId().toAbsolutePath()); // note: no cache listener here // vvvvvvvv reportCachedRuleViolations(listener, textDocument); } else { - LOG.trace("Processing file (lang: {}): {}", textFile.getLanguageVersion(), textFile.getPathId()); + LOG.trace("Processing file (lang: {}): {}", textFile.getLanguageVersion(), textFile.getFileId().toAbsolutePath()); try { processSource(completeListener, textDocument, ruleSets); } catch (Exception | StackOverflowError | AssertionError e) { @@ -85,17 +85,17 @@ abstract class PmdRunnable implements Runnable { // The listener handles logging if needed, // it may also rethrow the error, as a FileAnalysisException (which we let through below) - completeListener.onError(new Report.ProcessingError(e, textFile.getPathId())); + completeListener.onError(new Report.ProcessingError(e, textFile.getFileId())); } } } } else { - LOG.trace("Skipping file (lang: {}) because no rule applies: {}", textFile.getLanguageVersion(), textFile.getPathId()); + LOG.trace("Skipping file (lang: {}) because no rule applies: {}", textFile.getLanguageVersion(), textFile.getFileId()); } } catch (FileAnalysisException e) { throw e; // bubble managed exceptions, they were already reported } catch (Exception e) { - throw FileAnalysisException.wrap(textFile.getPathId(), "An unknown exception occurred", e); + throw FileAnalysisException.wrap(textFile.getFileId(), "An unknown exception occurred", e); } TimeTracker.finishThread(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java index c2661628ad..299794bb68 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/internal/RuleApplicator.java @@ -106,10 +106,10 @@ public class RuleApplicator { private void reportException(FileAnalysisListener listener, Rule rule, Node node, Throwable e) { // The listener handles logging if needed, // it may also rethrow the error. - listener.onError(new ProcessingError(e, node.getTextDocument().getPathId())); + listener.onError(new ProcessingError(e, node.getTextDocument().getFileId())); // fixme - maybe duplicated logging - LOG.warn("Exception applying rule {} on file {}, continuing with next rule", rule.getName(), node.getTextDocument().getPathId(), e); + LOG.warn("Exception applying rule {} on file {}, continuing with next rule", rule.getName(), node.getTextDocument().getFileId(), e); String nodeToString = StringUtil.elide(node.toString(), 600, " ... (truncated)"); LOG.warn("Exception occurred on node {}", nodeToString); } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java index 2805a76b1b..97131458e1 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/xpath/internal/FileNameXPathFunction.java @@ -56,7 +56,7 @@ public final class FileNameXPathFunction extends AbstractXPathFunctionDef { RootNode root = node.getRoot(); Objects.requireNonNull(root, "No root node in tree?"); - String fileName = root.getTextDocument().getPathId().getFileName(); + String fileName = root.getTextDocument().getFileId().getFileName(); Objects.requireNonNull(fileName, "File name was not set"); return new StringValue(fileName); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java index 57f4a69b45..58f5628135 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/renderers/AbstractRenderer.java @@ -22,7 +22,7 @@ public abstract class AbstractRenderer extends AbstractPropertySource implements protected boolean showSuppressedViolations = true; protected PrintWriter writer; - private FileNameRenderer fileNameRenderer = FileId::getOriginalPath; + private FileNameRenderer fileNameRenderer = fileId -> fileId.getOriginalPath(); public AbstractRenderer(String name, String description) { this.name = name; diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java index b40b019b7b..7d5b2ad168 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRenderer.java @@ -13,6 +13,7 @@ import java.util.List; import java.util.Objects; import org.apache.commons.lang3.StringUtils; +import org.checkerframework.checker.nullness.qual.NonNull; import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; @@ -41,10 +42,11 @@ public class ConfigurableFileNameRenderer implements FileNameRenderer { } @Override - public String getDisplayName(FileId fileId) { + public String getDisplayName(@NonNull FileId fileId) { String localDisplayName = getLocalDisplayName(fileId); - if (fileId.getParentFsPath() != null) { - return getDisplayName(fileId.getParentFsPath()) + "!" + localDisplayName; + FileId parent = fileId.getParentFsPath(); + if (parent != null) { + return getDisplayName(parent) + "!" + localDisplayName; } return localDisplayName; } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java index 98b3c2c79a..87b5fe3571 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/FileNameRenderer.java @@ -4,22 +4,30 @@ package net.sourceforge.pmd.reporting; +import org.checkerframework.checker.nullness.qual.NonNull; + import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.document.TextFile; /** - * Renders a {@link FileId} into a display name for the file. + * Strategy to render a {@link FileId} into a display name. This is used + * to prettify file names in renderers using relative paths eg. * * @author Clément Fournier */ public interface FileNameRenderer { - String getDisplayName(FileId fileId); + /** + * Return a display name for the given file id. + * @param fileId A file id + * @return A display name + */ + String getDisplayName(@NonNull FileId fileId); - default String getDisplayName(TextFile textFile) { - return getDisplayName(textFile.getPathId()); + default String getDisplayName(@NonNull TextFile textFile) { + return getDisplayName(textFile.getFileId()); } } diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java index c7689c3b1c..2f9ae9632e 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/GlobalAnalysisListener.java @@ -29,7 +29,7 @@ import net.sourceforge.pmd.util.CollectionUtil; * for each analyzed file, which themselves handle events like violations, * in their file. Thread-safety is required. * - * The listener may provide a {@link ListenerInitializer} to get context + *

The listener may provide a {@link ListenerInitializer} to get context * information on the analysis before events start occurring. * *

Listeners are the main API to obtain results of an analysis. The @@ -43,7 +43,8 @@ import net.sourceforge.pmd.util.CollectionUtil; public interface GlobalAnalysisListener extends AutoCloseable { /** - * Provides an initializer to gather analysis context before events start occurring. + * Provides an initializer to gather analysis context before events + * start occurring. * * @return A listener initializer. */ @@ -198,7 +199,7 @@ public interface GlobalAnalysisListener extends AutoCloseable { @Override public FileAnalysisListener startFileAnalysis(TextFile file) { - FileId filename = file.getPathId(); // capture the filename instead of the file + FileId filename = file.getFileId(); // capture the filename instead of the file return new FileAnalysisListener() { @Override public void onRuleViolation(RuleViolation violation) { diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java index 56a6d2e68f..1fd58cbfba 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/reporting/ListenerInitializer.java @@ -9,13 +9,19 @@ import java.util.Collection; import java.util.List; import net.sourceforge.pmd.internal.util.IOUtil; +import net.sourceforge.pmd.lang.document.TextFile; +import net.sourceforge.pmd.renderers.Renderer; import net.sourceforge.pmd.util.AssertionUtil; /** * An initializer for {@link GlobalAnalysisListener} that gets notified of * general analysis parameters. * - * Each method will be called exactly once, before any events on the {@link GlobalAnalysisListener} + *

Each method will be called exactly once, before any events on the + * {@link GlobalAnalysisListener}. The order of calls is unspecified, + * except that {@link #close()} is called last, and before + * {@link GlobalAnalysisListener#startFileAnalysis(TextFile)} is called + * for the first time. */ public interface ListenerInitializer extends AutoCloseable { @@ -26,6 +32,13 @@ public interface ListenerInitializer extends AutoCloseable { // noop } + /** + * Notify this listener that the given {@link FileNameRenderer} will + * be used by default for this analysis. This is mostly only relevant + * for {@link Renderer} listeners. + * + * @param fileNameRenderer The renderer + */ default void setFileNameRenderer(FileNameRenderer fileNameRenderer) { // noop } @@ -84,6 +97,13 @@ public interface ListenerInitializer extends AutoCloseable { } } + @Override + public void setFileNameRenderer(FileNameRenderer fileNameRenderer) { + for (ListenerInitializer initializer : list) { + initializer.setFileNameRenderer(fileNameRenderer); + } + } + @Override public void close() throws Exception { Exception composed = IOUtil.closeAll(list); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java index 4d303fd92c..171219ad1f 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cache/FileAnalysisCacheTest.java @@ -122,7 +122,7 @@ class FileAnalysisCacheTest { final RuleViolation rv = mock(RuleViolation.class); final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); - when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getPathId(), textLocation)); + when(rv.getLocation()).thenReturn(FileLocation.range(sourceFile.getFileId(), textLocation)); final net.sourceforge.pmd.Rule rule = mock(net.sourceforge.pmd.Rule.class, Mockito.RETURNS_SMART_NULLS); when(rule.getLanguage()).thenReturn(mock(Language.class)); when(rv.getRule()).thenReturn(rule); @@ -138,7 +138,7 @@ class FileAnalysisCacheTest { final List cachedViolations = reloadedCache.getCachedViolations(sourceFile); assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch"); final RuleViolation cachedViolation = cachedViolations.get(0); - assertSame(sourceFile.getPathId(), cachedViolation.getFileId()); + assertSame(sourceFile.getFileId(), cachedViolation.getFileId()); assertEquals(textLocation.getStartLine(), cachedViolation.getBeginLine()); assertEquals(textLocation.getStartColumn(), cachedViolation.getBeginColumn()); assertEquals(textLocation.getEndLine(), cachedViolation.getEndLine()); @@ -159,7 +159,7 @@ class FileAnalysisCacheTest { final TextRange2d textLocation = TextRange2d.range2d(1, 2, 3, 4); TextFile mockFile = mock(TextFile.class); - when(mockFile.getPathId()).thenReturn(FileId.fromPathLikeString("a/bc")); + when(mockFile.getFileId()).thenReturn(FileId.fromPathLikeString("a/bc")); when(mockFile.getLanguageVersion()).thenReturn(dummyVersion); when(mockFile.readContents()).thenReturn(TextFileContent.fromCharSeq("abc")); @@ -169,7 +169,7 @@ class FileAnalysisCacheTest { try (TextDocument doc0 = TextDocument.create(mockFile)) { cache.isUpToDate(doc0); try (FileAnalysisListener listener = cache.startFileAnalysis(doc0)) { - listener.onRuleViolation(new ParametricRuleViolation(rule, FileLocation.range(doc0.getPathId(), textLocation), "message")); + listener.onRuleViolation(new ParametricRuleViolation(rule, FileLocation.range(doc0.getFileId(), textLocation), "message")); } } finally { cache.persist(); @@ -187,7 +187,7 @@ class FileAnalysisCacheTest { List cachedViolations = reloadedCache.getCachedViolations(doc1); assertEquals(1, cachedViolations.size(), "Cached rule violations count mismatch"); final RuleViolation cachedViolation = cachedViolations.get(0); - assertEquals(mockFile.getPathId(), cachedViolation.getLocation().getFileId()); + assertEquals(mockFile.getFileId(), cachedViolation.getLocation().getFileId()); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java index cb30ddc4b8..b3693969d1 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/PMDFilelistTest.java @@ -43,8 +43,8 @@ class PMDFilelistTest { List applicableFiles = collector.getCollectedFiles(); assertThat(applicableFiles, hasSize(2)); - assertThat(applicableFiles.get(0).getPathId().getFileName(), equalTo("anotherfile.dummy")); - assertThat(applicableFiles.get(1).getPathId().getFileName(), equalTo("somefile.dummy")); + assertThat(applicableFiles.get(0).getFileId().getFileName(), equalTo("anotherfile.dummy")); + assertThat(applicableFiles.get(1).getFileId().getFileName(), equalTo("somefile.dummy")); } @Test @@ -61,7 +61,7 @@ class PMDFilelistTest { } private static void assertFilenameIs(TextFile textFile, String suffix) { - assertThat(textFile.getPathId().getFileName(), is(suffix)); + assertThat(textFile.getFileId().getFileName(), is(suffix)); } @Test diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java index 234e4ecd60..fc17eadf12 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/FileCollectorTest.java @@ -100,7 +100,7 @@ class FileCollectorTest { } private void assertCollected(FileCollector collector, List expected) { - List actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getPathId); + List actual = CollectionUtil.map(collector.getCollectedFiles(), TextFile::getFileId); assertEquals(expected, actual); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java index af5926d516..8ad57628c4 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/TextFilesTest.java @@ -37,9 +37,9 @@ class TextFilesTest { void testNioFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { - assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId().toUriString()); - assertEquals(file.toString(), tf.getPathId().getOriginalPath()); - assertEquals(file.getFileName().toString(), tf.getPathId().getFileName()); + assertEquals(file.toAbsolutePath().toUri().toString(), tf.getFileId().toUriString()); + assertEquals(file.toString(), tf.getFileId().getOriginalPath()); + assertEquals(file.getFileName().toString(), tf.getFileId().getFileName()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } @@ -51,7 +51,7 @@ class TextFilesTest { try (TextFile tf = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { try (TextFile tfPrime = TextFile.forPath(file, StandardCharsets.UTF_8, dummyVersion())) { try (TextFile stringTf = TextFile.forCharSeq("some content", FileId.forPath(file), dummyVersion())) { - assertEquals(tf.getPathId(), stringTf.getPathId()); + assertEquals(tf.getFileId(), stringTf.getFileId()); // despite same path id, they are different implementations assertNotEquals(tf, stringTf); @@ -75,7 +75,7 @@ class TextFilesTest { DataSource ds = DataSource.forString("text", "filename.dummy"); PMDConfiguration config = new PMDConfiguration(); try (TextFile tf = TextFile.dataSourceCompat(ds, config)) { - assertEquals("filename.dummy", tf.getPathId().getFileName()); + assertEquals("filename.dummy", tf.getFileId().getFileName()); assertEquals(DummyLanguageModule.getInstance().getDefaultVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("text"), tf.readContents().getNormalizedText()); } @@ -89,7 +89,7 @@ class TextFilesTest { PMDConfiguration config = new PMDConfiguration(); config.setForceLanguageVersion(DummyLanguageModule.getInstance().getDefaultVersion()); try (TextFile tf = TextFile.dataSourceCompat(ds, config)) { - assertEquals(ds.getNiceFileName(false, null), tf.getPathId().getOriginalPath()); + assertEquals(ds.getNiceFileName(false, null), tf.getFileId().getOriginalPath()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } } @@ -166,7 +166,7 @@ class TextFilesTest { Path file = makeTmpFile(StandardCharsets.UTF_8, "some content"); try (TextFile tf = TextFile.builderForPath(file, StandardCharsets.UTF_8, dummyVersion()) .build()) { - assertEquals(file.toAbsolutePath().toUri().toString(), tf.getPathId().toUriString()); + assertEquals(file.toAbsolutePath().toUri().toString(), tf.getFileId().toUriString()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some content"), tf.readContents().getNormalizedText()); } @@ -184,7 +184,7 @@ class TextFilesTest { void testReaderFile() throws IOException { Path file = makeTmpFile(StandardCharsets.UTF_8, "some\r\ncontent"); try (TextFile tf = TextFile.forReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), FileId.UNKNOWN, dummyVersion())) { - assertEquals(FileId.UNKNOWN, tf.getPathId()); + assertEquals(FileId.UNKNOWN, tf.getFileId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("some\ncontent"), tf.readContents().getNormalizedText()); } @@ -204,7 +204,7 @@ class TextFilesTest { @Test void testStringFileEscape() throws IOException { try (TextFile tf = TextFile.forCharSeq("cont\r\nents", FileId.UNKNOWN, dummyVersion())) { - assertEquals(FileId.UNKNOWN, tf.getPathId()); + assertEquals(FileId.UNKNOWN, tf.getFileId()); assertEquals(dummyVersion(), tf.getLanguageVersion()); assertEquals(Chars.wrap("cont\nents"), tf.readContents().getNormalizedText()); assertThrows(ReadOnlyFileException.class, () -> tf.writeContents( diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java index 30a0978c9e..9609d45a78 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/GlobalListenerTest.java @@ -145,7 +145,7 @@ class GlobalListenerTest { @Override public void apply(Node node, RuleContext ctx) { - if (node.getTextDocument().getDisplayName().contains("1")) { + if (node.getTextDocument().getFileId().getFileName().contains("1")) { ctx.addViolation(node); } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java index 07ce390a0d..11c1d66854 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/processor/MultiThreadProcessorTest.java @@ -91,7 +91,7 @@ class MultiThreadProcessorTest { public void apply(Node target, RuleContext ctx) { count.incrementAndGet(); - if (target.getTextDocument().getDisplayName().contains("violation")) { + if (target.getTextDocument().getFileId().getOriginalPath().contains("violation")) { hasViolation = true; } else { letTheOtherThreadRun(10); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java index a33c32d340..5198262477 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/reporting/ConfigurableFileNameRendererTest.java @@ -15,10 +15,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.document.FileId; -/** - * @author Clément Fournier - */ -public class ConfigurableFileNameRendererTest { +class ConfigurableFileNameRendererTest { @Test void testRelativize() { diff --git a/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyTokenizer.java b/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyTokenizer.java index 654342e2b6..c9d3512825 100644 --- a/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyTokenizer.java +++ b/pmd-groovy/src/main/java/net/sourceforge/pmd/cpd/GroovyTokenizer.java @@ -10,6 +10,8 @@ import org.codehaus.groovy.antlr.SourceInfo; import org.codehaus.groovy.antlr.parser.GroovyLexer; import net.sourceforge.pmd.lang.ast.TokenMgrError; +import net.sourceforge.pmd.lang.document.CpdCompat; +import net.sourceforge.pmd.lang.document.FileId; import groovyjarjarantlr.Token; import groovyjarjarantlr.TokenStream; @@ -24,6 +26,7 @@ public class GroovyTokenizer implements Tokenizer { public void tokenize(SourceCode sourceCode, Tokens tokenEntries) { StringBuilder buffer = sourceCode.getCodeBuffer(); + FileId fileId = CpdCompat.cpdCompat(sourceCode).getFileId(); GroovyLexer lexer = new GroovyLexer(new StringReader(buffer.toString())); TokenStream tokenStream = lexer.plumb(); @@ -51,7 +54,7 @@ public class GroovyTokenizer implements Tokenizer { // they are correctly handled // when CPD is executed with the '--skipLexicalErrors' command line // option - throw new TokenMgrError(lexer.getLine(), lexer.getColumn(), lexer.getFilename(), err.getMessage(), err); + throw new TokenMgrError(lexer.getLine(), lexer.getColumn(), fileId, err.getMessage(), err); } finally { tokenEntries.add(TokenEntry.getEOF()); } diff --git a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/TypeResTestRule.java b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/TypeResTestRule.java index 63ac824684..00908a858b 100644 --- a/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/TypeResTestRule.java +++ b/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/rule/internal/TypeResTestRule.java @@ -100,9 +100,8 @@ public class TypeResTestRule extends AbstractJavaRule { } - @NonNull - public String position(JavaNode node) { - return "In: " + node.getTextDocument().getDisplayName() + ":" + node.getBeginLine() + ":" + node.getBeginColumn(); + public @NonNull String position(JavaNode node) { + return "In: " + node.getReportLocation().startPosToStringWithFile(); } @Override diff --git a/pmd-scala-modules/pmd-scala-common/src/main/java/net/sourceforge/pmd/cpd/ScalaTokenizer.java b/pmd-scala-modules/pmd-scala-common/src/main/java/net/sourceforge/pmd/cpd/ScalaTokenizer.java index 060f24cbd4..842d26b297 100644 --- a/pmd-scala-modules/pmd-scala-common/src/main/java/net/sourceforge/pmd/cpd/ScalaTokenizer.java +++ b/pmd-scala-modules/pmd-scala-common/src/main/java/net/sourceforge/pmd/cpd/ScalaTokenizer.java @@ -15,6 +15,7 @@ import net.sourceforge.pmd.lang.TokenManager; import net.sourceforge.pmd.lang.ast.TokenMgrError; import net.sourceforge.pmd.lang.document.CpdCompat; import net.sourceforge.pmd.lang.document.TextDocument; +import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.lang.scala.ScalaLanguageModule; import scala.collection.Iterator; @@ -65,7 +66,8 @@ public class ScalaTokenizer implements Tokenizer { public void tokenize(SourceCode sourceCode, Tokens tokenEntries) throws IOException { - try (TextDocument textDoc = TextDocument.create(CpdCompat.cpdCompat(sourceCode))) { + TextFile textFile = CpdCompat.cpdCompat(sourceCode); + try (TextDocument textDoc = TextDocument.create(textFile)) { String fullCode = textDoc.getText().toString(); // create the input file for scala @@ -92,7 +94,7 @@ public class ScalaTokenizer implements Tokenizer { // cannot catch it as it's a checked exception and Scala sneaky throws TokenizeException tokE = (TokenizeException) e; Position pos = tokE.pos(); - throw new TokenMgrError(pos.startLine() + 1, pos.startColumn() + 1, sourceCode.getFileName(), "Scalameta threw", tokE); + throw new TokenMgrError(pos.startLine() + 1, pos.startColumn() + 1, textFile.getFileId(), "Scalameta threw", tokE); } else { throw e; } diff --git a/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/rule/XmlXPathRuleTest.java b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/rule/XmlXPathRuleTest.java index 886d73d919..36bdb5fb49 100644 --- a/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/rule/XmlXPathRuleTest.java +++ b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/rule/XmlXPathRuleTest.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.lang.document.FileId; import net.sourceforge.pmd.lang.xml.XmlParsingHelper; class XmlXPathRuleTest { @@ -44,7 +45,7 @@ class XmlXPathRuleTest { void testFileNameInXpath() { Report report = xml.executeRule(makeXPath("//b[pmd:fileName() = 'Foo.xml']"), "", - "src/Foo.xml"); + FileId.fromPathLikeString("src/Foo.xml")); assertSize(report, 1); } From 9eb5ac9a1f0455c85a76f01737941ff7c48b53cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Fournier?= Date: Mon, 20 Mar 2023 13:54:16 +0100 Subject: [PATCH 14/14] Fix checkValidity call --- .../src/main/java/net/sourceforge/pmd/PmdAnalysis.java | 5 ++++- .../net/sourceforge/pmd/cache/AbstractAnalysisCache.java | 4 ++-- .../java/net/sourceforge/pmd/cache/AnalysisCache.java | 7 +++++-- .../net/sourceforge/pmd/cache/AnalysisCacheListener.java | 7 ++++--- .../java/net/sourceforge/pmd/cache/FileAnalysisCache.java | 8 +++++--- .../java/net/sourceforge/pmd/cache/NoopAnalysisCache.java | 4 ++-- 6 files changed, 22 insertions(+), 13 deletions(-) diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java index 9c245da8f3..1d94f97c0c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/PmdAnalysis.java @@ -332,7 +332,10 @@ public final class PmdAnalysis implements AutoCloseable { GlobalAnalysisListener listener; try { @SuppressWarnings("PMD.CloseResource") - AnalysisCacheListener cacheListener = new AnalysisCacheListener(configuration.getAnalysisCache(), rulesets, configuration.getClassLoader()); + AnalysisCacheListener cacheListener = new AnalysisCacheListener(configuration.getAnalysisCache(), + rulesets, + configuration.getClassLoader(), + textFiles); listener = GlobalAnalysisListener.tee(listOf(createComposedRendererListener(renderers), GlobalAnalysisListener.tee(listeners), GlobalAnalysisListener.tee(extraListeners), diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java index e41ff46677..7a8b7a9498 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AbstractAnalysisCache.java @@ -15,10 +15,10 @@ import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -121,7 +121,7 @@ public abstract class AbstractAnalysisCache implements AnalysisCache { @Override - public void checkValidity(final RuleSets ruleSets, final ClassLoader auxclassPathClassLoader, Set files) { + public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection files) { try (TimedOperation ignored = TimeTracker.startOperation(TimedOperationCategory.ANALYSIS_CACHE, "validity check")) { boolean cacheIsValid = cacheExists(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java index 8240cba597..2b7e0e1b5a 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCache.java @@ -5,8 +5,8 @@ package net.sourceforge.pmd.cache; import java.io.IOException; +import java.util.Collection; import java.util.List; -import java.util.Set; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; @@ -64,8 +64,11 @@ public interface AnalysisCache { * * @param ruleSets The rulesets configured for this analysis. * @param auxclassPathClassLoader The class loader for auxclasspath configured for this analysis. + * @param files Set of files in the current analysis. File + * records in the cache are matched to the file + * IDs of these files. */ - void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Set files); + void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection files); /** * Returns a listener that will be used like in {@link GlobalAnalysisListener#startFileAnalysis(TextFile)}. diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java index 1630c47fa9..702631244c 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/AnalysisCacheListener.java @@ -5,7 +5,7 @@ package net.sourceforge.pmd.cache; import java.io.IOException; -import java.util.Collections; +import java.util.Collection; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.annotation.InternalApi; @@ -22,9 +22,10 @@ public class AnalysisCacheListener implements GlobalAnalysisListener { private final AnalysisCache cache; - public AnalysisCacheListener(AnalysisCache cache, RuleSets ruleSets, ClassLoader classLoader) { + public AnalysisCacheListener(AnalysisCache cache, RuleSets ruleSets, ClassLoader classLoader, + Collection textFiles) { this.cache = cache; - cache.checkValidity(ruleSets, classLoader, Collections.emptySet()); + cache.checkValidity(ruleSets, classLoader, textFiles); } @Override diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java index 68df8f6715..a4fe617ed0 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/FileAnalysisCache.java @@ -13,9 +13,9 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; import net.sourceforge.pmd.PMDVersion; @@ -49,7 +49,7 @@ public class FileAnalysisCache extends AbstractAnalysisCache { } @Override - public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Set files) { + public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection files) { // load cached data before checking for validity loadFromFile(cacheFile, files); super.checkValidity(ruleSets, auxclassPathClassLoader, files); @@ -60,7 +60,7 @@ public class FileAnalysisCache extends AbstractAnalysisCache { * * @param cacheFile The file which backs the file analysis cache. */ - private void loadFromFile(final File cacheFile, Set files) { + private void loadFromFile(final File cacheFile, Collection files) { Map idMap = files.stream().map(TextFile::getFileId) .collect(Collectors.toMap(FileId::toUriString, id -> id)); @@ -88,6 +88,8 @@ public class FileAnalysisCache extends AbstractAnalysisCache { if (fileId == null) { LOG.debug("File {} is in the cache but is not part of the analysis", filePathId); + // todo we wrote a URI, if this happens several times we will be + // prepending unknown:// several times. fileId = FileId.fromPathLikeString(filePathId); } final long checksum = inputStream.readLong(); diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java b/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java index 89764769bb..ea8896501d 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/cache/NoopAnalysisCache.java @@ -4,9 +4,9 @@ package net.sourceforge.pmd.cache; +import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Set; import net.sourceforge.pmd.RuleSets; import net.sourceforge.pmd.RuleViolation; @@ -40,7 +40,7 @@ public class NoopAnalysisCache implements AnalysisCache { } @Override - public void checkValidity(final RuleSets ruleSets, final ClassLoader classLoader, Set files) { + public void checkValidity(RuleSets ruleSets, ClassLoader auxclassPathClassLoader, Collection files) { // noop }