Skip to content

Commit

Permalink
Improve absolute path detection.
Browse files Browse the repository at this point in the history
Use URI to decode URI encoded absolute paths.
See jenkinsci/analysis-model#1021
  • Loading branch information
uhafner committed Feb 8, 2024
1 parent 077865c commit fe958b0
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/main/java/edu/hm/hafner/util/PathUtil.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package edu.hm.hafner.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
Expand Down Expand Up @@ -259,6 +261,15 @@ public String createAbsolutePath(@CheckForNull final String directory, final Str
* @return {@code true} if this path is an absolute path, {@code false} if a relative path
*/
public boolean isAbsolute(final String fileName) {
try {
URI uri = new URI(fileName);

Check warning on line 265 in src/main/java/edu/hm/hafner/util/PathUtil.java

View check run for this annotation

Jenkins (hafner.hm.edu) / Error Prone

Varifier

NORMAL: Consider using `var` here to avoid boilerplate.
Raw output
Did you mean: <pre><code>var uri = new URI(fileName);</code></pre><p><a href="https://errorprone.info/bugpattern/Varifier">See ErrorProne documentation.</a></p>
if (uri.isAbsolute()) {
return true;
}
}
catch (URISyntaxException ignored) {
// catch and ignore as system paths are not URI, and we need to check them separately
}
return FilenameUtils.getPrefixLength(fileName) > 0;
}

Expand Down
4 changes: 2 additions & 2 deletions src/test/java/edu/hm/hafner/util/PathUtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,11 @@ void shouldFindResourceFolder() {

@DisplayName("Should verify valid absolute paths")
@ParameterizedTest(name = "[{index}] path={0}")
@ValueSource(strings = {"/", "/tmp", "C:\\", "c:\\", "C:\\Tmp"})
@ValueSource(strings = {"/", "/tmp", "C:\\", "c:\\", "C:\\Tmp", "C:/tmp/absolute.txt", "file:///project/src/main/java/com/app/ui/model/Activity.kt"})
void shouldFindAbsolutePaths(final String path) {
var pathUtil = new PathUtil();

assertThat(pathUtil.isAbsolute(path)).isTrue();
assertThat(pathUtil.isAbsolute(path)).as("Show be detected as absolute path").isTrue();
}

@Test
Expand Down

0 comments on commit fe958b0

Please sign in to comment.