Skip to content

Commit

Permalink
Merge pull request #642 from jkylling/resolve-worktree-git-dir
Browse files Browse the repository at this point in the history
Resolve worktree .git files to repository .git directory
  • Loading branch information
TheSnoozer authored Oct 3, 2023
2 parents 59415bf + b1d8440 commit 4feba8d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/main/java/pl/project13/maven/git/GitDirLocator.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.*;
import java.nio.file.Path;
import java.util.List;

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/pl/project13/maven/git/GitDirLocatorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}
}

0 comments on commit 4feba8d

Please sign in to comment.