Skip to content

Commit daee43b

Browse files
authored
Merge pull request #376 from ankurmittal/short-hash
Add support for getting short object Id
2 parents 7cd5a4e + 7caac1f commit daee43b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

object.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,20 @@ func (o *Object) Id() *Oid {
4949
return newOidFromC(C.git_object_id(o.ptr))
5050
}
5151

52+
func (o *Object) ShortId() (string, error) {
53+
resultBuf := C.git_buf{}
54+
55+
runtime.LockOSThread()
56+
defer runtime.UnlockOSThread()
57+
58+
ecode := C.git_object_short_id(&resultBuf, o.ptr)
59+
if ecode < 0 {
60+
return "", MakeGitError(ecode)
61+
}
62+
defer C.git_buf_free(&resultBuf)
63+
return C.GoString(resultBuf.ptr), nil
64+
}
65+
5266
func (o *Object) Type() ObjectType {
5367
return ObjectType(C.git_object_type(o.ptr))
5468
}

object_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package git
22

33
import (
4+
"strings"
45
"testing"
56
)
67

@@ -105,6 +106,32 @@ func TestObjectOwner(t *testing.T) {
105106
checkOwner(t, repo, tree.Object)
106107
}
107108

109+
func checkShortId(t *testing.T, Id, shortId string) {
110+
if len(shortId) < 7 || len(shortId) >= len(Id) {
111+
t.Fatal("bad shortId lenght %s", len(shortId))
112+
}
113+
114+
if !strings.HasPrefix(Id, shortId) {
115+
t.Fatalf("bad shortId, should be prefix of %s, but is %s\n", Id, shortId)
116+
}
117+
}
118+
119+
func TestObjectShortId(t *testing.T) {
120+
t.Parallel()
121+
repo := createTestRepo(t)
122+
defer cleanupTestRepo(t, repo)
123+
124+
commitId, _ := seedTestRepo(t, repo)
125+
126+
commit, err := repo.LookupCommit(commitId)
127+
checkFatal(t, err)
128+
129+
shortId, err := commit.ShortId()
130+
checkFatal(t, err)
131+
132+
checkShortId(t, commitId.String(), shortId)
133+
}
134+
108135
func TestObjectPeel(t *testing.T) {
109136
t.Parallel()
110137
repo := createTestRepo(t)

0 commit comments

Comments
 (0)