diff --git a/src/main/java/pl/project13/maven/git/GitDirLocator.java b/src/main/java/pl/project13/maven/git/GitDirLocator.java index d196eb9d..c8cb62ba 100644 --- a/src/main/java/pl/project13/maven/git/GitDirLocator.java +++ b/src/main/java/pl/project13/maven/git/GitDirLocator.java @@ -23,6 +23,7 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.*; +import java.nio.file.Path; import java.util.List; /** @@ -127,7 +128,7 @@ private File processGitDirFile(@Nonnull File file) { } // All seems ok so return the "gitdir" value read from the file. - File gitDir = new File(parts[1]); + File gitDir = resolveWorktree(new File(parts[1])); if (gitDir.isAbsolute()) { // gitdir value is an absolute path. Return as-is return gitDir; @@ -140,6 +141,21 @@ private File processGitDirFile(@Nonnull File file) { } } + /** + * If the file looks like the location of a worktree, return the .git folder of the git repository of the worktree. + * If not, return the file as is. + */ + static File resolveWorktree(File fileLocation) { + Path parent = fileLocation.toPath().getParent(); + if (parent == null) { + return fileLocation; + } + if (parent.endsWith(Path.of(".git", "worktrees"))) { + return parent.getParent().toFile(); + } + return fileLocation; + } + /** * Helper method to validate that the specified {@code File} is an existing directory. * @param fileLocation The {@code File} that should be checked if it's actually an existing directory. diff --git a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java index 0b4fc657..09e86087 100644 --- a/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java +++ b/src/test/java/pl/project13/maven/git/GitDirLocatorTest.java @@ -58,4 +58,13 @@ public void shouldUseTheManuallySpecifiedDirectory() throws Exception { } } + @Test + public void testWorktreeResolution() { + String[] noopCases = {"", "a", "a/b", ".git/worktrees", ".git/worktrees/", "a.git/worktrees/b"}; + for (String path : noopCases) { + assertThat(GitDirLocator.resolveWorktree(new File(path))).isEqualTo(new File(path)); + } + assertThat(GitDirLocator.resolveWorktree(new File("a/.git/worktrees/b"))).isEqualTo(new File("a/.git")); + assertThat(GitDirLocator.resolveWorktree(new File("/a/.git/worktrees/b"))).isEqualTo(new File("/a/.git")); + } }