Skip to content

Commit

Permalink
Merge pull request #921 from uhafner/is-absolute
Browse files Browse the repository at this point in the history
Improve absolute path detection
  • Loading branch information
uhafner authored Feb 19, 2024
2 parents ac9d669 + fe958b0 commit 3e9fcbb
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);
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 3e9fcbb

Please sign in to comment.