From b5693c1429ad7247ce75b23ebb866f9428bde8b6 Mon Sep 17 00:00:00 2001 From: Dmitri Shuralyov Date: Mon, 6 Jul 2015 19:27:58 -0700 Subject: [PATCH 1/8] Prevent slot int variable from being GCed. Before this change, there were no users of slot int variable in the Go world (just a pointer to it that ended up in C world only), so Go's garbage collector would free it and its value could not retrieved later (once a pointer to it comes back to Go world from C world). Keep a pointer to it in the Go world so that does not happen. Fixes #218. --- handles.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/handles.go b/handles.go index ec62a48..a062231 100644 --- a/handles.go +++ b/handles.go @@ -10,14 +10,15 @@ type HandleList struct { sync.RWMutex // stores the Go pointers handles []interface{} - // indicates which indices are in use - set map[int]bool + // Indicates which indices are in use, and keeps a pointer to slot int variable (the handle) + // in the Go world, so that the Go garbage collector does not free it. + set map[int]*int } func NewHandleList() *HandleList { return &HandleList{ handles: make([]interface{}, 5), - set: make(map[int]bool), + set: make(map[int]*int), } } @@ -25,7 +26,7 @@ func NewHandleList() *HandleList { // list. You must only run this function while holding a write lock. func (v *HandleList) findUnusedSlot() int { for i := 1; i < len(v.handles); i++ { - isUsed := v.set[i] + _, isUsed := v.set[i] if !isUsed { return i } @@ -47,7 +48,7 @@ func (v *HandleList) Track(pointer interface{}) unsafe.Pointer { slot := v.findUnusedSlot() v.handles[slot] = pointer - v.set[slot] = true + v.set[slot] = &slot // Keep a pointer to slot in Go world, so it's not freed by GC. v.Unlock() -- 2.45.2 From 4b88210cbf495891c8d44c53b3d978e6ff31a5a3 Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 24 Jul 2015 12:14:24 +0300 Subject: [PATCH 2/8] Add check if reference is a note --- reference.go | 5 +++++ reference_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/reference.go b/reference.go index d24e054..452de46 100644 --- a/reference.go +++ b/reference.go @@ -315,6 +315,11 @@ func (v *Reference) IsTag() bool { return C.git_reference_is_tag(v.ptr) == 1 } +// IsNote checks if the reference is a note. +func (v *Reference) IsNote() bool { + return C.git_reference_is_note(v.ptr) == 1 +} + func (v *Reference) Free() { runtime.SetFinalizer(v, nil) C.git_reference_free(v.ptr) diff --git a/reference_test.go b/reference_test.go index f1546e2..b69a274 100644 --- a/reference_test.go +++ b/reference_test.go @@ -176,6 +176,38 @@ func TestUtil(t *testing.T) { } } +func TestIsNote(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + commitID, _ := seedTestRepo(t, repo) + + sig := &Signature{ + Name: "Rand Om Hacker", + Email: "random@hacker.com", + When: time.Now(), + } + + refname, err := repo.Notes.DefaultRef() + checkFatal(t, err) + + _, err = repo.Notes.Create(refname, sig, sig, commitID, "This is a note", false) + checkFatal(t, err) + + ref, err := repo.References.Lookup(refname) + checkFatal(t, err) + + if !ref.IsNote() { + t.Fatalf("%s should be a note", ref.Name()) + } + + ref, err = repo.References.Create("refs/heads/foo", commitID, true, "") + checkFatal(t, err) + + if ref.IsNote() { + t.Fatalf("%s should not be a note", ref.Name()) + } +} func compareStringList(t *testing.T, expected, actual []string) { for i, v := range expected { if actual[i] != v { -- 2.45.2 From ec93213f21f57e6b378bf9f6ceb05c9fd1f15daf Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 24 Jul 2015 12:14:53 +0300 Subject: [PATCH 3/8] Add ReferenceIsValidName() --- reference.go | 19 +++++++++++++++++++ reference_test.go | 10 ++++++++++ 2 files changed, 29 insertions(+) diff --git a/reference.go b/reference.go index 452de46..140082f 100644 --- a/reference.go +++ b/reference.go @@ -430,3 +430,22 @@ func (v *ReferenceIterator) Free() { runtime.SetFinalizer(v, nil) C.git_reference_iterator_free(v.ptr) } + +// ReferenceIsValidName ensures the reference name is well-formed. +// +// Valid reference names must follow one of two patterns: +// +// 1. Top-level names must contain only capital letters and underscores, +// and must begin and end with a letter. (e.g. "HEAD", "ORIG_HEAD"). +// +// 2. Names prefixed with "refs/" can be almost anything. You must avoid +// the characters '~', '^', ':', ' \ ', '?', '[', and '*', and the sequences +// ".." and " @ {" which have special meaning to revparse. +func ReferenceIsValidName(name string) bool { + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + if C.git_reference_is_valid_name(cname) == 1 { + return true + } + return false +} diff --git a/reference_test.go b/reference_test.go index b69a274..761daf8 100644 --- a/reference_test.go +++ b/reference_test.go @@ -208,6 +208,16 @@ func TestIsNote(t *testing.T) { t.Fatalf("%s should not be a note", ref.Name()) } } + +func TestReferenceIsValidName(t *testing.T) { + if !ReferenceIsValidName("HEAD") { + t.Errorf("HEAD should be a valid reference name") + } + if ReferenceIsValidName("HEAD1") { + t.Errorf("HEAD1 should not be a valid reference name") + } +} + func compareStringList(t *testing.T, expected, actual []string) { for i, v := range expected { if actual[i] != v { -- 2.45.2 From 64c160f6f2300fc675453761471dc8d4726756e0 Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 24 Jul 2015 19:46:57 +0300 Subject: [PATCH 4/8] Find tree entry by id Add support for 'git_tree_entry_byid'. --- tree.go | 18 ++++++++++++++++++ tree_test.go | 22 ++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 tree_test.go diff --git a/tree.go b/tree.go index aad2c8d..f543c11 100644 --- a/tree.go +++ b/tree.go @@ -55,6 +55,24 @@ func (t Tree) EntryByName(filename string) *TreeEntry { return newTreeEntry(entry) } +// EntryById performs a lookup for a tree entry with the given SHA value. +// +// It returns a *TreeEntry that is owned by the Tree. You don't have to +// free it, but you must not use it after the Tree is freed. +// +// Warning: this must examine every entry in the tree, so it is not fast. +func (t Tree) EntryById(id *Oid) *TreeEntry { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + entry := C.git_tree_entry_byid(t.cast_ptr, id.toC()) + if entry == nil { + return nil + } + + return newTreeEntry(entry) +} + // EntryByPath looks up an entry by its full path, recursing into // deeper trees if necessary (i.e. if there are slashes in the path) func (t Tree) EntryByPath(path string) (*TreeEntry, error) { diff --git a/tree_test.go b/tree_test.go new file mode 100644 index 0000000..4c6a4ed --- /dev/null +++ b/tree_test.go @@ -0,0 +1,22 @@ +package git + +import "testing" + +func TestTreeEntryById(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + _, treeID := seedTestRepo(t, repo) + + tree, err := repo.LookupTree(treeID) + checkFatal(t, err) + + id, err := NewOid("257cc5642cb1a054f08cc83f2d943e56fd3ebe99") + checkFatal(t, err) + + entry := tree.EntryById(id) + + if entry == nil { + t.Fatalf("entry id %v was not found", id) + } +} -- 2.45.2 From 12311c8528c577ebb11006f24c026c7a4d2f2de3 Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 31 Jul 2015 09:51:19 +0200 Subject: [PATCH 5/8] Add TagsCollection --- repository.go | 4 ++++ tag.go | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/repository.go b/repository.go index 44509af..b17745d 100644 --- a/repository.go +++ b/repository.go @@ -27,6 +27,9 @@ type Repository struct { // Notes represents the collection of notes and can be used to // read, write and delete notes from this repository. Notes NoteCollection + // Tags represents the collection of tags and can be used to create, + // list and iterate tags in this repository. + Tags TagsCollection } func newRepositoryFromC(ptr *C.git_repository) *Repository { @@ -36,6 +39,7 @@ func newRepositoryFromC(ptr *C.git_repository) *Repository { repo.Submodules.repo = repo repo.References.repo = repo repo.Notes.repo = repo + repo.Tags.repo = repo runtime.SetFinalizer(repo, (*Repository).Free) diff --git a/tag.go b/tag.go index 89ac8bd..74b18d8 100644 --- a/tag.go +++ b/tag.go @@ -42,3 +42,7 @@ func (t Tag) TargetId() *Oid { func (t Tag) TargetType() ObjectType { return ObjectType(C.git_tag_target_type(t.cast_ptr)) } + +type TagsCollection struct { + repo *Repository +} -- 2.45.2 From 6c4af98c5b2763b020e39357f31bcc6d6f1960e1 Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 31 Jul 2015 10:07:26 +0200 Subject: [PATCH 6/8] Add more support for tags Implement support for the following libgit2 functions: - 'git_tag_list' and 'git_tag_list_match' - 'git_tag_foreach' - 'git_tag_create_lightweight' --- tag.go | 133 ++++++++++++++++++++++++++++++++++++++++++++ tag_test.go | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++ wrapper.c | 5 ++ 3 files changed, 293 insertions(+) diff --git a/tag.go b/tag.go index 74b18d8..5801c99 100644 --- a/tag.go +++ b/tag.go @@ -2,8 +2,14 @@ package git /* #include + +extern int _go_git_tag_foreach(git_repository *repo, void *payload); */ import "C" +import ( + "runtime" + "unsafe" +) // Tag type Tag struct { @@ -46,3 +52,130 @@ func (t Tag) TargetType() ObjectType { type TagsCollection struct { repo *Repository } + +// CreateLightweight creates a new lightweight tag pointing to a commit +// and returns the id of the target object. +// +// The name of the tag is validated for consistency (see git_tag_create() for the rules +// https://libgit2.github.com/libgit2/#HEAD/group/tag/git_tag_create) and should +// not conflict with an already existing tag name. +// +// If force is true and a reference already exists with the given name, it'll be replaced. +// +// The created tag is a simple reference and can be queried using +// repo.References.Lookup("refs/tags/"). The name of the tag (eg "v1.0.0") +// is queried with ref.Shorthand(). +func (c *TagsCollection) CreateLightweight(name string, commit *Commit, force bool) (*Oid, error) { + + oid := new(Oid) + + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + + ctarget := commit.gitObject.ptr + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + err := C.git_tag_create_lightweight(oid.toC(), c.repo.ptr, cname, ctarget, cbool(force)) + if err < 0 { + return nil, MakeGitError(err) + } + + return oid, nil +} + +// List returns the names of all the tags in the repository, +// eg: ["v1.0.1", "v2.0.0"]. +func (c *TagsCollection) List() ([]string, error) { + var strC C.git_strarray + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ecode := C.git_tag_list(&strC, c.repo.ptr) + if ecode < 0 { + return nil, MakeGitError(ecode) + } + defer C.git_strarray_free(&strC) + + tags := makeStringsFromCStrings(strC.strings, int(strC.count)) + return tags, nil +} + +// ListWithMatch returns the names of all the tags in the repository +// that match a given pattern. +// +// The pattern is a standard fnmatch(3) pattern http://man7.org/linux/man-pages/man3/fnmatch.3.html +func (c *TagsCollection) ListWithMatch(pattern string) ([]string, error) { + var strC C.git_strarray + + patternC := C.CString(pattern) + defer C.free(unsafe.Pointer(patternC)) + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ecode := C.git_tag_list_match(&strC, patternC, c.repo.ptr) + if ecode < 0 { + return nil, MakeGitError(ecode) + } + defer C.git_strarray_free(&strC) + + tags := makeStringsFromCStrings(strC.strings, int(strC.count)) + return tags, nil +} + +// TagForeachCallback is called for each tag in the repository. +// +// The name is the full ref name eg: "refs/tags/v1.0.0". +// +// Note that the callback is called for lightweight tags as well, +// so repo.LookupTag() will return an error for these tags. Use +// repo.References.Lookup() instead. +type TagForeachCallback func(name string, id *Oid) error +type tagForeachData struct { + callback TagForeachCallback + err error +} + +//export gitTagForeachCb +func gitTagForeachCb(name *C.char, id *C.git_oid, handle unsafe.Pointer) int { + payload := pointerHandles.Get(handle) + data, ok := payload.(*tagForeachData) + if !ok { + panic("could not retrieve tag foreach CB handle") + } + + err := data.callback(C.GoString(name), newOidFromC(id)) + if err != nil { + data.err = err + return C.GIT_EUSER + } + + return 0 +} + +// Foreach calls the callback for each tag in the repository. +func (c *TagsCollection) Foreach(callback TagForeachCallback) error { + data := tagForeachData{ + callback: callback, + err: nil, + } + + handle := pointerHandles.Track(&data) + defer pointerHandles.Untrack(handle) + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + err := C._go_git_tag_foreach(c.repo.ptr, handle) + if err == C.GIT_EUSER { + return data.err + } + if err < 0 { + return MakeGitError(err) + } + + return nil +} diff --git a/tag_test.go b/tag_test.go index 74f9fec..4bf3889 100644 --- a/tag_test.go +++ b/tag_test.go @@ -1,6 +1,7 @@ package git import ( + "errors" "testing" "time" ) @@ -24,6 +25,146 @@ func TestCreateTag(t *testing.T) { compareStrings(t, commitId.String(), tag.TargetId().String()) } +func TestCreateTagLightweight(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + commitID, _ := seedTestRepo(t, repo) + + commit, err := repo.LookupCommit(commitID) + checkFatal(t, err) + + tagID, err := repo.Tags.CreateLightweight("v0.1.0", commit, false) + checkFatal(t, err) + + _, err = repo.Tags.CreateLightweight("v0.1.0", commit, true) + checkFatal(t, err) + + ref, err := repo.References.Lookup("refs/tags/v0.1.0") + checkFatal(t, err) + + compareStrings(t, "refs/tags/v0.1.0", ref.Name()) + compareStrings(t, "v0.1.0", ref.Shorthand()) + compareStrings(t, tagID.String(), commitID.String()) + compareStrings(t, commitID.String(), ref.Target().String()) +} + +func TestListTags(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + commitID, _ := seedTestRepo(t, repo) + + commit, err := repo.LookupCommit(commitID) + checkFatal(t, err) + + createTag(t, repo, commit, "v1.0.1", "Release v1.0.1") + + commitID, _ = updateReadme(t, repo, "Release version 2") + + commit, err = repo.LookupCommit(commitID) + checkFatal(t, err) + + createTag(t, repo, commit, "v2.0.0", "Release v2.0.0") + + expected := []string{ + "v1.0.1", + "v2.0.0", + } + + actual, err := repo.Tags.List() + checkFatal(t, err) + + compareStringList(t, expected, actual) +} + +func TestListTagsWithMatch(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + commitID, _ := seedTestRepo(t, repo) + + commit, err := repo.LookupCommit(commitID) + checkFatal(t, err) + + createTag(t, repo, commit, "v1.0.1", "Release v1.0.1") + + commitID, _ = updateReadme(t, repo, "Release version 2") + + commit, err = repo.LookupCommit(commitID) + checkFatal(t, err) + + createTag(t, repo, commit, "v2.0.0", "Release v2.0.0") + + expected := []string{ + "v2.0.0", + } + + actual, err := repo.Tags.ListWithMatch("v2*") + checkFatal(t, err) + + compareStringList(t, expected, actual) + + expected = []string{ + "v1.0.1", + } + + actual, err = repo.Tags.ListWithMatch("v1*") + checkFatal(t, err) + + compareStringList(t, expected, actual) +} + +func TestTagForeach(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + commitID, _ := seedTestRepo(t, repo) + + commit, err := repo.LookupCommit(commitID) + checkFatal(t, err) + + tag1 := createTag(t, repo, commit, "v1.0.1", "Release v1.0.1") + + commitID, _ = updateReadme(t, repo, "Release version 2") + + commit, err = repo.LookupCommit(commitID) + checkFatal(t, err) + + tag2 := createTag(t, repo, commit, "v2.0.0", "Release v2.0.0") + + expectedNames := []string{ + "refs/tags/v1.0.1", + "refs/tags/v2.0.0", + } + actualNames := []string{} + expectedOids := []string{ + tag1.String(), + tag2.String(), + } + actualOids := []string{} + + err = repo.Tags.Foreach(func(name string, id *Oid) error { + actualNames = append(actualNames, name) + actualOids = append(actualOids, id.String()) + return nil + }) + checkFatal(t, err) + + compareStringList(t, expectedNames, actualNames) + compareStringList(t, expectedOids, actualOids) + + fakeErr := errors.New("fake error") + + err = repo.Tags.Foreach(func(name string, id *Oid) error { + return fakeErr + }) + + if err != fakeErr { + t.Fatalf("Tags.Foreach() did not return the expected error, got %v", err) + } +} + func compareStrings(t *testing.T, expected, value string) { if value != expected { t.Fatalf("expected '%v', actual '%v'", expected, value) @@ -43,3 +184,17 @@ func createTestTag(t *testing.T, repo *Repository, commit *Commit) *Oid { checkFatal(t, err) return tagId } + +func createTag(t *testing.T, repo *Repository, commit *Commit, name, message string) *Oid { + loc, err := time.LoadLocation("Europe/Bucharest") + checkFatal(t, err) + sig := &Signature{ + Name: "Rand Om Hacker", + Email: "random@hacker.com", + When: time.Date(2013, 03, 06, 14, 30, 0, 0, loc), + } + + tagId, err := repo.CreateTag(name, commit, sig, message) + checkFatal(t, err) + return tagId +} diff --git a/wrapper.c b/wrapper.c index 75cc03c..1efe5d7 100644 --- a/wrapper.c +++ b/wrapper.c @@ -131,4 +131,9 @@ int _go_git_index_remove_all(git_index *index, const git_strarray *pathspec, voi return git_index_remove_all(index, pathspec, cb, callback); } +int _go_git_tag_foreach(git_repository *repo, void *payload) +{ + return git_tag_foreach(repo, (git_tag_foreach_cb)&gitTagForeachCb, payload); +} + /* EOF */ -- 2.45.2 From def4494b74ec1c8fd12669e3f65bd29d6315c83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Mart=C3=ADn=20Nieto?= Date: Fri, 31 Jul 2015 20:23:05 +0200 Subject: [PATCH 7/8] Move CreateTag to the tags collection --- repository.go | 30 ------------------------------ tag.go | 30 ++++++++++++++++++++++++++++++ tag_test.go | 4 ++-- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/repository.go b/repository.go index b17745d..62fde6d 100644 --- a/repository.go +++ b/repository.go @@ -321,36 +321,6 @@ func (v *Repository) CreateCommit( return oid, nil } -func (v *Repository) CreateTag( - name string, commit *Commit, tagger *Signature, message string) (*Oid, error) { - - oid := new(Oid) - - cname := C.CString(name) - defer C.free(unsafe.Pointer(cname)) - - cmessage := C.CString(message) - defer C.free(unsafe.Pointer(cmessage)) - - taggerSig, err := tagger.toC() - if err != nil { - return nil, err - } - defer C.git_signature_free(taggerSig) - - ctarget := commit.gitObject.ptr - - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - ret := C.git_tag_create(oid.toC(), v.ptr, cname, ctarget, taggerSig, cmessage, 0) - if ret < 0 { - return nil, MakeGitError(ret) - } - - return oid, nil -} - func (v *Odb) Free() { runtime.SetFinalizer(v, nil) C.git_odb_free(v.ptr) diff --git a/tag.go b/tag.go index 5801c99..ca85156 100644 --- a/tag.go +++ b/tag.go @@ -53,6 +53,36 @@ type TagsCollection struct { repo *Repository } +func (c *TagsCollection) Create( + name string, commit *Commit, tagger *Signature, message string) (*Oid, error) { + + oid := new(Oid) + + cname := C.CString(name) + defer C.free(unsafe.Pointer(cname)) + + cmessage := C.CString(message) + defer C.free(unsafe.Pointer(cmessage)) + + taggerSig, err := tagger.toC() + if err != nil { + return nil, err + } + defer C.git_signature_free(taggerSig) + + ctarget := commit.gitObject.ptr + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ret := C.git_tag_create(oid.toC(), c.repo.ptr, cname, ctarget, taggerSig, cmessage, 0) + if ret < 0 { + return nil, MakeGitError(ret) + } + + return oid, nil +} + // CreateLightweight creates a new lightweight tag pointing to a commit // and returns the id of the target object. // diff --git a/tag_test.go b/tag_test.go index 4bf3889..2fdfe00 100644 --- a/tag_test.go +++ b/tag_test.go @@ -180,7 +180,7 @@ func createTestTag(t *testing.T, repo *Repository, commit *Commit) *Oid { When: time.Date(2013, 03, 06, 14, 30, 0, 0, loc), } - tagId, err := repo.CreateTag("v0.0.0", commit, sig, "This is a tag") + tagId, err := repo.Tags.Create("v0.0.0", commit, sig, "This is a tag") checkFatal(t, err) return tagId } @@ -194,7 +194,7 @@ func createTag(t *testing.T, repo *Repository, commit *Commit, name, message str When: time.Date(2013, 03, 06, 14, 30, 0, 0, loc), } - tagId, err := repo.CreateTag(name, commit, sig, message) + tagId, err := repo.Tags.Create(name, commit, sig, message) checkFatal(t, err) return tagId } -- 2.45.2 From 1018ff76d034662e5bba7665a62d6263cd377ab7 Mon Sep 17 00:00:00 2001 From: Calin Seciu Date: Fri, 24 Jul 2015 01:39:49 +0300 Subject: [PATCH 8/8] Add git-describe support Includes 'git_describe_commit' and 'git_describe_workdir'. --- describe.go | 222 +++++++++++++++++++++++++++++++++++++++++++++++ describe_test.go | 106 ++++++++++++++++++++++ 2 files changed, 328 insertions(+) create mode 100644 describe.go create mode 100644 describe_test.go diff --git a/describe.go b/describe.go new file mode 100644 index 0000000..c6f9a79 --- /dev/null +++ b/describe.go @@ -0,0 +1,222 @@ +package git + +/* +#include +*/ +import "C" +import ( + "runtime" + "unsafe" +) + +// DescribeOptions represents the describe operation configuration. +// +// You can use DefaultDescribeOptions() to get default options. +type DescribeOptions struct { + // How many tags as candidates to consider to describe the input commit-ish. + // Increasing it above 10 will take slightly longer but may produce a more + // accurate result. 0 will cause only exact matches to be output. + MaxCandidatesTags uint // default: 10 + + // By default describe only shows annotated tags. Change this in order + // to show all refs from refs/tags or refs/. + Strategy DescribeOptionsStrategy // default: DescribeDefault + + // Only consider tags matching the given glob(7) pattern, excluding + // the "refs/tags/" prefix. Can be used to avoid leaking private + // tags from the repo. + Pattern string + + // When calculating the distance from the matching tag or + // reference, only walk down the first-parent ancestry. + OnlyFollowFirstParent bool + + // If no matching tag or reference is found, the describe + // operation would normally fail. If this option is set, it + // will instead fall back to showing the full id of the commit. + ShowCommitOidAsFallback bool +} + +// DefaultDescribeOptions returns default options for the describe operation. +func DefaultDescribeOptions() (DescribeOptions, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + opts := C.git_describe_options{} + ecode := C.git_describe_init_options(&opts, C.GIT_DESCRIBE_OPTIONS_VERSION) + if ecode < 0 { + return DescribeOptions{}, MakeGitError(ecode) + } + + return DescribeOptions{ + MaxCandidatesTags: uint(opts.max_candidates_tags), + Strategy: DescribeOptionsStrategy(opts.describe_strategy), + }, nil +} + +// DescribeFormatOptions can be used for formatting the describe string. +// +// You can use DefaultDescribeFormatOptions() to get default options. +type DescribeFormatOptions struct { + // Size of the abbreviated commit id to use. This value is the + // lower bound for the length of the abbreviated string. + AbbreviatedSize uint // default: 7 + + // Set to use the long format even when a shorter name could be used. + AlwaysUseLongFormat bool + + // If the workdir is dirty and this is set, this string will be + // appended to the description string. + DirtySuffix string +} + +// DefaultDescribeFormatOptions returns default options for formatting +// the output. +func DefaultDescribeFormatOptions() (DescribeFormatOptions, error) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + opts := C.git_describe_format_options{} + ecode := C.git_describe_init_format_options(&opts, C.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION) + if ecode < 0 { + return DescribeFormatOptions{}, MakeGitError(ecode) + } + + return DescribeFormatOptions{ + AbbreviatedSize: uint(opts.abbreviated_size), + AlwaysUseLongFormat: opts.always_use_long_format == 1, + }, nil +} + +// DescribeOptionsStrategy behaves like the --tags and --all options +// to git-describe, namely they say to look for any reference in +// either refs/tags/ or refs/ respectively. +// +// By default it only shows annotated tags. +type DescribeOptionsStrategy uint + +// Describe strategy options. +const ( + DescribeDefault DescribeOptionsStrategy = C.GIT_DESCRIBE_DEFAULT + DescribeTags DescribeOptionsStrategy = C.GIT_DESCRIBE_TAGS + DescribeAll DescribeOptionsStrategy = C.GIT_DESCRIBE_ALL +) + +// Describe performs the describe operation on the commit. +func (c *Commit) Describe(opts *DescribeOptions) (*DescribeResult, error) { + var resultPtr *C.git_describe_result + + var cDescribeOpts *C.git_describe_options + if opts != nil { + var cpattern *C.char + if len(opts.Pattern) > 0 { + cpattern = C.CString(opts.Pattern) + defer C.free(unsafe.Pointer(cpattern)) + } + + cDescribeOpts = &C.git_describe_options{ + version: C.GIT_DESCRIBE_OPTIONS_VERSION, + max_candidates_tags: C.uint(opts.MaxCandidatesTags), + describe_strategy: C.uint(opts.Strategy), + pattern: cpattern, + only_follow_first_parent: cbool(opts.OnlyFollowFirstParent), + show_commit_oid_as_fallback: cbool(opts.ShowCommitOidAsFallback), + } + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ecode := C.git_describe_commit(&resultPtr, c.gitObject.ptr, cDescribeOpts) + if ecode < 0 { + return nil, MakeGitError(ecode) + } + + return newDescribeResultFromC(resultPtr), nil +} + +// DescribeWorkdir describes the working tree. It means describe HEAD +// and appends (-dirty by default) if the working tree is dirty. +func (repo *Repository) DescribeWorkdir(opts *DescribeOptions) (*DescribeResult, error) { + var resultPtr *C.git_describe_result + + var cDescribeOpts *C.git_describe_options + if opts != nil { + var cpattern *C.char + if len(opts.Pattern) > 0 { + cpattern = C.CString(opts.Pattern) + defer C.free(unsafe.Pointer(cpattern)) + } + + cDescribeOpts = &C.git_describe_options{ + version: C.GIT_DESCRIBE_OPTIONS_VERSION, + max_candidates_tags: C.uint(opts.MaxCandidatesTags), + describe_strategy: C.uint(opts.Strategy), + pattern: cpattern, + only_follow_first_parent: cbool(opts.OnlyFollowFirstParent), + show_commit_oid_as_fallback: cbool(opts.ShowCommitOidAsFallback), + } + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ecode := C.git_describe_workdir(&resultPtr, repo.ptr, cDescribeOpts) + if ecode < 0 { + return nil, MakeGitError(ecode) + } + + return newDescribeResultFromC(resultPtr), nil +} + +// DescribeResult represents the output from the 'git_describe_commit' +// and 'git_describe_workdir' functions in libgit2. +// +// Use Format() to get a string out of it. +type DescribeResult struct { + ptr *C.git_describe_result +} + +func newDescribeResultFromC(ptr *C.git_describe_result) *DescribeResult { + result := &DescribeResult{ + ptr: ptr, + } + runtime.SetFinalizer(result, (*DescribeResult).Free) + return result +} + +// Format prints the DescribeResult as a string. +func (result *DescribeResult) Format(opts *DescribeFormatOptions) (string, error) { + resultBuf := C.git_buf{} + + var cFormatOpts *C.git_describe_format_options + if opts != nil { + cDirtySuffix := C.CString(opts.DirtySuffix) + defer C.free(unsafe.Pointer(cDirtySuffix)) + + cFormatOpts = &C.git_describe_format_options{ + version: C.GIT_DESCRIBE_FORMAT_OPTIONS_VERSION, + abbreviated_size: C.uint(opts.AbbreviatedSize), + always_use_long_format: cbool(opts.AlwaysUseLongFormat), + dirty_suffix: cDirtySuffix, + } + } + + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + ecode := C.git_describe_format(&resultBuf, result.ptr, cFormatOpts) + if ecode < 0 { + return "", MakeGitError(ecode) + } + defer C.git_buf_free(&resultBuf) + + return C.GoString(resultBuf.ptr), nil +} + +// Free cleans up the C reference. +func (result *DescribeResult) Free() { + runtime.SetFinalizer(result, nil) + C.git_describe_result_free(result.ptr) + result.ptr = nil +} diff --git a/describe_test.go b/describe_test.go new file mode 100644 index 0000000..25af107 --- /dev/null +++ b/describe_test.go @@ -0,0 +1,106 @@ +package git + +import ( + "path" + "runtime" + "strings" + "testing" +) + +func TestDescribeCommit(t *testing.T) { + repo := createTestRepo(t) + defer cleanupTestRepo(t, repo) + + describeOpts, err := DefaultDescribeOptions() + checkFatal(t, err) + + formatOpts, err := DefaultDescribeFormatOptions() + checkFatal(t, err) + + commitID, _ := seedTestRepo(t, repo) + + commit, err := repo.LookupCommit(commitID) + checkFatal(t, err) + + // No annotated tags can be used to describe master + _, err = commit.Describe(&describeOpts) + checkDescribeNoRefsFound(t, err) + + // Fallback + fallback := describeOpts + fallback.ShowCommitOidAsFallback = true + result, err := commit.Describe(&fallback) + checkFatal(t, err) + resultStr, err := result.Format(&formatOpts) + checkFatal(t, err) + compareStrings(t, "473bf77", resultStr) + + // Abbreviated + abbreviated := formatOpts + abbreviated.AbbreviatedSize = 2 + result, err = commit.Describe(&fallback) + checkFatal(t, err) + resultStr, err = result.Format(&abbreviated) + checkFatal(t, err) + compareStrings(t, "473b", resultStr) + + createTestTag(t, repo, commit) + + // Exact tag + patternOpts := describeOpts + patternOpts.Pattern = "v[0-9]*" + result, err = commit.Describe(&patternOpts) + checkFatal(t, err) + resultStr, err = result.Format(&formatOpts) + checkFatal(t, err) + compareStrings(t, "v0.0.0", resultStr) + + // Pattern no match + patternOpts.Pattern = "v[1-9]*" + result, err = commit.Describe(&patternOpts) + checkDescribeNoRefsFound(t, err) + + commitID, _ = updateReadme(t, repo, "update1") + commit, err = repo.LookupCommit(commitID) + checkFatal(t, err) + + // Tag-1 + result, err = commit.Describe(&describeOpts) + checkFatal(t, err) + resultStr, err = result.Format(&formatOpts) + checkFatal(t, err) + compareStrings(t, "v0.0.0-1-gd88ef8d", resultStr) + + // Strategy: All + describeOpts.Strategy = DescribeAll + result, err = commit.Describe(&describeOpts) + checkFatal(t, err) + resultStr, err = result.Format(&formatOpts) + checkFatal(t, err) + compareStrings(t, "heads/master", resultStr) + + repo.CreateBranch("hotfix", commit, false) + + // Workdir (branch) + result, err = repo.DescribeWorkdir(&describeOpts) + checkFatal(t, err) + resultStr, err = result.Format(&formatOpts) + checkFatal(t, err) + compareStrings(t, "heads/hotfix", resultStr) +} + +func checkDescribeNoRefsFound(t *testing.T, err error) { + // The failure happens at wherever we were called, not here + _, file, line, ok := runtime.Caller(1) + if !ok { + t.Fatalf("Unable to get caller") + } + if err == nil || !strings.Contains(err.Error(), "No reference found, cannot describe anything") { + t.Fatalf( + "%s:%v: was expecting error 'No reference found, cannot describe anything', got %v", + path.Base(file), + line, + err, + ) + } +} -- 2.45.2