Skip to content

Commit 466ac24

Browse files
authored
Add function to resolve short commit ID to full SHA1 (go-gitea#122)
* Add function to resolve short commit ID to full SHA1 * Add tests for GetFullCommitID
1 parent 31f4b8e commit 466ac24

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

commit.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,3 +274,19 @@ func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
274274
}
275275
return nil, nil
276276
}
277+
278+
// GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
279+
func GetFullCommitID(repoPath, shortID string) (string, error) {
280+
if len(shortID) >= 40 {
281+
return shortID, nil
282+
}
283+
284+
commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
285+
if err != nil {
286+
if strings.Contains(err.Error(), "exit status 128") {
287+
return "", ErrNotExist{shortID, ""}
288+
}
289+
return "", err
290+
}
291+
return strings.TrimSpace(commitID), nil
292+
}

commit_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,17 @@ func TestCommitsCount(t *testing.T) {
1414
commitsCount, _ := CommitsCount(".", "d86a90f801dbe279db095437a8c7ea42c60e8d98")
1515
assert.Equal(t, int64(3), commitsCount)
1616
}
17+
18+
func TestGetFullCommitID(t *testing.T) {
19+
id, err := GetFullCommitID(".", "d86a90f8")
20+
assert.NoError(t, err)
21+
assert.Equal(t, "d86a90f801dbe279db095437a8c7ea42c60e8d98", id)
22+
}
23+
24+
func TestGetFullCommitIDError(t *testing.T) {
25+
id, err := GetFullCommitID(".", "unknown")
26+
assert.Empty(t, id)
27+
if assert.Error(t, err) {
28+
assert.EqualError(t, err, "object does not exist [id: unknown, rel_path: ]")
29+
}
30+
}

0 commit comments

Comments
 (0)