Skip to content

Commit 290ebe9

Browse files
committed
NewRepository(): verify that the repository exists
Verify that the Git repository exists and that `git rev-parse --git-dir` runs correctly. Distinguish between failures to run Git at all (probably because it was not in the path) versus failures *of* git (probably because the Git repository couldn't be found).
1 parent 0048e22 commit 290ebe9

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

git-sizer.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (v *NegatedBoolValue) IsBoolFlag() bool {
4343
func main() {
4444
err := mainImplementation()
4545
if err != nil {
46-
fmt.Fprintf(os.Stderr, "%s\n", err)
46+
fmt.Fprintf(os.Stderr, "error: %s\n", err)
4747
os.Exit(1)
4848
}
4949
}

sizes/git.go

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,35 @@ type Repository struct {
5757
}
5858

5959
func NewRepository(path string) (*Repository, error) {
60-
return &Repository{
61-
path: path,
62-
}, nil
60+
command := exec.Command(
61+
"git", "-C", path,
62+
"rev-parse", "--git-dir",
63+
)
64+
out, err := command.Output()
65+
if err != nil {
66+
switch err := err.(type) {
67+
case *exec.Error:
68+
return nil, errors.New(
69+
fmt.Sprintf(
70+
"could not run git (is it in your PATH?): %s",
71+
err.Err,
72+
),
73+
)
74+
case *exec.ExitError:
75+
return nil, errors.New(
76+
fmt.Sprintf(
77+
"git rev-parse failed: %s",
78+
err.Stderr,
79+
),
80+
)
81+
default:
82+
return nil, err
83+
}
84+
}
85+
repo := &Repository{
86+
path: string(bytes.TrimSpace(out)),
87+
}
88+
return repo, nil
6389
}
6490

6591
func (repo *Repository) Close() error {

0 commit comments

Comments
 (0)