Skip to content

Commit 97ffa4e

Browse files
meekrosoftclaude
andcommitted
green: New() resolves HEAD in git worktrees
Enable EnableDotGitCommonDir in go-git's PlainOpenWithOptions so that ref resolution follows the commondir chain. Without this, HEAD in a linked worktree points to a branch whose ref lives in the main repo's .git/refs, and go-git fails with "reference not found". Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent ed0badf commit 97ffa4e

2 files changed

Lines changed: 29 additions & 1 deletion

File tree

internal/gitview/gitView.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ const redactedCommitInfoValue = "**REDACTED**"
4949
// repository is bare or a normal one. If the path doesn't contain a valid
5050
// repository ErrRepositoryNotExists is returned
5151
func New(repositoryRoot string) (*GitView, error) {
52-
repository, err := git.PlainOpen(repositoryRoot)
52+
repository, err := git.PlainOpenWithOptions(repositoryRoot, &git.PlainOpenOptions{
53+
EnableDotGitCommonDir: true,
54+
})
5355
if err != nil {
5456
return nil, fmt.Errorf("failed to open git repository at %s: %v", repositoryRoot, err)
5557
}

internal/gitview/gitView_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package gitview
33
import (
44
"fmt"
55
"os"
6+
"os/exec"
67
"path/filepath"
78
"testing"
89

@@ -54,6 +55,31 @@ func (suite *GitViewTestSuite) TestNewGitView() {
5455
require.Error(suite.T(), err)
5556
}
5657

58+
func (suite *GitViewTestSuite) TestNewGitViewFromWorktree() {
59+
dirPath := filepath.Join(suite.tmpDir, "repoName")
60+
_, _, err := initializeRepoAndCommit(dirPath, 1)
61+
require.NoError(suite.T(), err)
62+
63+
worktreePath := filepath.Join(suite.tmpDir, "myWorktree")
64+
cmd := exec.Command("git", "worktree", "add", "-b", "worktree-branch", worktreePath)
65+
cmd.Dir = dirPath
66+
output, err := cmd.CombinedOutput()
67+
require.NoError(suite.T(), err, "git worktree add failed: %s", string(output))
68+
69+
gv, err := New(worktreePath)
70+
require.NoError(suite.T(), err)
71+
require.NotNil(suite.T(), gv)
72+
73+
branchName, err := gv.BranchName()
74+
require.NoError(suite.T(), err)
75+
require.Equal(suite.T(), "worktree-branch", branchName)
76+
77+
commitInfo, err := gv.GetCommitInfoFromCommitSHA("HEAD", true, []string{})
78+
require.NoError(suite.T(), err)
79+
require.NotEmpty(suite.T(), commitInfo.Sha1)
80+
require.Equal(suite.T(), "worktree-branch", commitInfo.Branch)
81+
}
82+
5783
func (suite *GitViewTestSuite) TestCommitsBetween() {
5884
for i, t := range []struct {
5985
name string

0 commit comments

Comments
 (0)