Skip to content

Commit b1d8440

Browse files
committed
Resolve worktree .git files to repository .git directory
1 parent e09fddc commit b1d8440

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/main/java/pl/project13/maven/git/GitDirLocator.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import javax.annotation.Nonnull;
2424
import javax.annotation.Nullable;
2525
import java.io.*;
26+
import java.nio.file.Path;
2627
import java.util.List;
2728

2829
/**
@@ -127,7 +128,7 @@ private File processGitDirFile(@Nonnull File file) {
127128
}
128129

129130
// All seems ok so return the "gitdir" value read from the file.
130-
File gitDir = new File(parts[1]);
131+
File gitDir = resolveWorktree(new File(parts[1]));
131132
if (gitDir.isAbsolute()) {
132133
// gitdir value is an absolute path. Return as-is
133134
return gitDir;
@@ -140,6 +141,21 @@ private File processGitDirFile(@Nonnull File file) {
140141
}
141142
}
142143

144+
/**
145+
* If the file looks like the location of a worktree, return the .git folder of the git repository of the worktree.
146+
* If not, return the file as is.
147+
*/
148+
static File resolveWorktree(File fileLocation) {
149+
Path parent = fileLocation.toPath().getParent();
150+
if (parent == null) {
151+
return fileLocation;
152+
}
153+
if (parent.endsWith(Path.of(".git", "worktrees"))) {
154+
return parent.getParent().toFile();
155+
}
156+
return fileLocation;
157+
}
158+
143159
/**
144160
* Helper method to validate that the specified {@code File} is an existing directory.
145161
* @param fileLocation The {@code File} that should be checked if it's actually an existing directory.

src/test/java/pl/project13/maven/git/GitDirLocatorTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,4 +58,13 @@ public void shouldUseTheManuallySpecifiedDirectory() throws Exception {
5858
}
5959
}
6060

61+
@Test
62+
public void testWorktreeResolution() {
63+
String[] noopCases = {"", "a", "a/b", ".git/worktrees", ".git/worktrees/", "a.git/worktrees/b"};
64+
for (String path : noopCases) {
65+
assertThat(GitDirLocator.resolveWorktree(new File(path))).isEqualTo(new File(path));
66+
}
67+
assertThat(GitDirLocator.resolveWorktree(new File("a/.git/worktrees/b"))).isEqualTo(new File("a/.git"));
68+
assertThat(GitDirLocator.resolveWorktree(new File("/a/.git/worktrees/b"))).isEqualTo(new File("/a/.git"));
69+
}
6170
}

0 commit comments

Comments
 (0)