Skip to content

Commit 29fc882

Browse files
committed
Repository.GitPath(): new method, extracted from NewRepository()
Add a method `Repository.GitPath(relPath)`, which invokes `git rev-parse --git-path $relPath` to find the path to a file within the Git repository. In `NewRepository()`, instantiate the `Repository` object earlier so that the new method can be used to find the path to `shallow`.
1 parent c20cbb8 commit 29fc882

1 file changed

Lines changed: 26 additions & 12 deletions

File tree

git/git.go

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -66,25 +66,22 @@ func NewRepository(path string) (*Repository, error) {
6666
}
6767
gitDir := smartJoin(path, string(bytes.TrimSpace(out)))
6868

69-
//nolint:gosec // `gitBin` is chosen carefully.
70-
cmd = exec.Command(gitBin, "rev-parse", "--git-path", "shallow")
71-
cmd.Dir = gitDir
72-
out, err = cmd.Output()
69+
repo := Repository{
70+
gitDir: gitDir,
71+
gitBin: gitBin,
72+
}
73+
74+
shallow, err := repo.GitPath("shallow")
7375
if err != nil {
74-
return nil, fmt.Errorf(
75-
"could not run 'git rev-parse --git-path shallow': %w", err,
76-
)
76+
return nil, err
7777
}
78-
shallow := smartJoin(gitDir, string(bytes.TrimSpace(out)))
78+
7979
_, err = os.Lstat(shallow)
8080
if err == nil {
8181
return nil, errors.New("this appears to be a shallow clone; full clone required")
8282
}
8383

84-
return &Repository{
85-
gitDir: gitDir,
86-
gitBin: gitBin,
87-
}, nil
84+
return &repo, nil
8885
}
8986

9087
func (repo *Repository) GitCommand(callerArgs ...string) *exec.Cmd {
@@ -119,3 +116,20 @@ func (repo *Repository) GitCommand(callerArgs ...string) *exec.Cmd {
119116
func (repo *Repository) GitDir() string {
120117
return repo.gitDir
121118
}
119+
120+
// GitPath returns that path of a file within the git repository, by
121+
// calling `git rev-parse --git-path $relPath`. The returned path is
122+
// relative to the current directory.
123+
func (repo *Repository) GitPath(relPath string) (string, error) {
124+
cmd := repo.GitCommand("rev-parse", "--git-path", relPath)
125+
out, err := cmd.Output()
126+
if err != nil {
127+
return "", fmt.Errorf(
128+
"running 'git rev-parse --git-path %s': %w", relPath, err,
129+
)
130+
}
131+
// `git rev-parse --git-path` is documented to return the path
132+
// relative to the current directory. Since we haven't changed the
133+
// current directory, we can use it as-is:
134+
return string(bytes.TrimSpace(out)), nil
135+
}

0 commit comments

Comments
 (0)