Refactor error handling in ReadBranchConfig to avoid panic

This commit is contained in:
Tyler McGoffin 2025-01-09 11:45:45 -08:00
parent e1423cdbbf
commit 48d45d0b9d
2 changed files with 12 additions and 12 deletions

View file

@ -391,11 +391,13 @@ func (c *Client) ReadBranchConfig(ctx context.Context, branch string) (BranchCon
out, err := cmd.Output()
if err != nil {
// This will error if no matches are found but the git command still ran successfully. We only
// want to return an error if the command failed to run, usually and ExitError, which will be
// indicated by output on Stderr.
if err.(*GitError).Stderr != "" {
return BranchConfig{}, err
// This is the error we expect if the git command does not run successfully.
// Note: err is non-nil if the command is successful but has no output
var gitError *GitError
if errors.As(err, &gitError) {
if gitError.Stderr != "" {
return BranchConfig{}, err
}
}
return BranchConfig{}, nil
}

View file

@ -750,7 +750,7 @@ func TestClientReadBranchConfig(t *testing.T) {
cmdStderr: "git error message",
branch: "trunk",
wantBranchConfig: BranchConfig{},
wantError: &GitError{ExitCode: 1, Stderr: "git error message"},
wantError: &GitError{},
},
{
name: "git config runs successfully but returns no output",
@ -773,12 +773,10 @@ func TestClientReadBranchConfig(t *testing.T) {
wantCmdArgs := fmt.Sprintf("path/to/git config --get-regexp ^branch\\.%s\\.(remote|merge|gh-merge-base)$", tt.branch)
assert.Equal(t, wantCmdArgs, strings.Join(cmd.Args[3:], " "))
assert.Equal(t, tt.wantBranchConfig, branchConfig)
if err != nil {
if tt.wantError == nil {
t.Fatalf("expected no error but got %v", err)
}
assert.Equal(t, tt.wantError.ExitCode, err.(*GitError).ExitCode)
assert.Equal(t, tt.wantError.Stderr, err.(*GitError).Stderr)
if tt.wantError != nil {
assert.ErrorAs(t, err, &tt.wantError)
} else {
assert.NoError(t, err)
}
})
}