Skip to content

Commit

Permalink
Add function to resolve short commit ID to full SHA1 (go-gitea#122)
Browse files Browse the repository at this point in the history
* Add function to resolve short commit ID to full SHA1

* Add tests for GetFullCommitID
  • Loading branch information
lafriks authored Jun 12, 2018
1 parent 31f4b8e commit 466ac24
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
16 changes: 16 additions & 0 deletions commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,19 @@ func (c *Commit) GetSubModule(entryname string) (*SubModule, error) {
}
return nil, nil
}

// GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.
func GetFullCommitID(repoPath, shortID string) (string, error) {
if len(shortID) >= 40 {
return shortID, nil
}

commitID, err := NewCommand("rev-parse", shortID).RunInDir(repoPath)
if err != nil {
if strings.Contains(err.Error(), "exit status 128") {
return "", ErrNotExist{shortID, ""}
}
return "", err
}
return strings.TrimSpace(commitID), nil
}
14 changes: 14 additions & 0 deletions commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,17 @@ func TestCommitsCount(t *testing.T) {
commitsCount, _ := CommitsCount(".", "d86a90f801dbe279db095437a8c7ea42c60e8d98")
assert.Equal(t, int64(3), commitsCount)
}

func TestGetFullCommitID(t *testing.T) {
id, err := GetFullCommitID(".", "d86a90f8")
assert.NoError(t, err)
assert.Equal(t, "d86a90f801dbe279db095437a8c7ea42c60e8d98", id)
}

func TestGetFullCommitIDError(t *testing.T) {
id, err := GetFullCommitID(".", "unknown")
assert.Empty(t, id)
if assert.Error(t, err) {
assert.EqualError(t, err, "object does not exist [id: unknown, rel_path: ]")
}
}

0 comments on commit 466ac24

Please sign in to comment.