Skip to content

Commit 101fb0d

Browse files
authored
Do not assume all 40 char strings are SHA1s (#14624) (#14648)
Backport #14624 GetCommit() assumes that all 40 char strings are SHA1s. This leads to an error if you try to do a PR on a branch which is 40 characters long. This PR attempts the SHA first - and if it fails will switch to using rev-parse. Fix #14470 Signed-off-by: Andrew Thornton <[email protected]>
1 parent 82637c2 commit 101fb0d

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

modules/git/repo_commit.go

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -129,19 +129,23 @@ func (repo *Repository) getCommit(id SHA1) (*Commit, error) {
129129

130130
// ConvertToSHA1 returns a Hash object from a potential ID string
131131
func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) {
132-
if len(commitID) != 40 {
133-
var err error
134-
actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
135-
if err != nil {
136-
if strings.Contains(err.Error(), "unknown revision or path") ||
137-
strings.Contains(err.Error(), "fatal: Needed a single revision") {
138-
return SHA1{}, ErrNotExist{commitID, ""}
139-
}
140-
return SHA1{}, err
132+
if len(commitID) == 40 {
133+
sha1, err := NewIDFromString(commitID)
134+
if err == nil {
135+
return sha1, nil
136+
}
137+
}
138+
139+
actualCommitID, err := NewCommand("rev-parse", "--verify", commitID).RunInDir(repo.Path)
140+
if err != nil {
141+
if strings.Contains(err.Error(), "unknown revision or path") ||
142+
strings.Contains(err.Error(), "fatal: Needed a single revision") {
143+
return SHA1{}, ErrNotExist{commitID, ""}
141144
}
142-
commitID = actualCommitID
145+
return SHA1{}, err
143146
}
144-
return NewIDFromString(commitID)
147+
148+
return NewIDFromString(actualCommitID)
145149
}
146150

147151
// GetCommit returns commit object of by ID string.

0 commit comments

Comments
 (0)