From fe958b09d06352d7d4dd4ef9f628df4f07938be3 Mon Sep 17 00:00:00 2001 From: Ulli Hafner Date: Thu, 8 Feb 2024 21:41:07 +0100 Subject: [PATCH] Improve absolute path detection. Use URI to decode URI encoded absolute paths. See https://github.com/jenkinsci/analysis-model/pull/1021 --- src/main/java/edu/hm/hafner/util/PathUtil.java | 11 +++++++++++ src/test/java/edu/hm/hafner/util/PathUtilTest.java | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/edu/hm/hafner/util/PathUtil.java b/src/main/java/edu/hm/hafner/util/PathUtil.java index 8e7fb007..e15fb8dd 100644 --- a/src/main/java/edu/hm/hafner/util/PathUtil.java +++ b/src/main/java/edu/hm/hafner/util/PathUtil.java @@ -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; @@ -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); + 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; } diff --git a/src/test/java/edu/hm/hafner/util/PathUtilTest.java b/src/test/java/edu/hm/hafner/util/PathUtilTest.java index 505cab28..0c594479 100644 --- a/src/test/java/edu/hm/hafner/util/PathUtilTest.java +++ b/src/test/java/edu/hm/hafner/util/PathUtilTest.java @@ -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