Skip to content

Commit a6a8f66

Browse files
authored
Merge pull request go-git#374 from snebel29/feat/add-example
examples: added "tag find if head is tagged"
2 parents 99457e5 + 06a3e50 commit a6a8f66

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

_examples/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ Here you can find a list of annotated _go-git_ examples:
1919
- [branch](branch/main.go) - How to create and remove branches or any other kind of reference.
2020
- [tag](tag/main.go) - List/print repository tags.
2121
- [tag create and push](tag-create-push/main.go) - Create and push a new tag.
22+
- [tag find if head is tagged](find-if-any-tag-point-head/main.go) - Find if `HEAD` is tagged.
2223
- [remotes](remotes/main.go) - Working with remotes: adding, removing, etc.
2324
- [progress](progress/main.go) - Printing the progress information from the sideband.
2425
- [revision](revision/main.go) - Solve a revision into a commit.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
"github.com/go-git/go-git/v5"
8+
. "github.com/go-git/go-git/v5/_examples"
9+
"github.com/go-git/go-git/v5/plumbing"
10+
)
11+
12+
// Basic example of how to find if HEAD is tagged.
13+
func main() {
14+
CheckArgs("<path>")
15+
path := os.Args[1]
16+
17+
// We instantiate a new repository targeting the given path (the .git folder)
18+
r, err := git.PlainOpen(path)
19+
CheckIfError(err)
20+
21+
// Get HEAD reference to use for comparison later on.
22+
ref, err := r.Head()
23+
CheckIfError(err)
24+
25+
tags, err := r.Tags()
26+
CheckIfError(err)
27+
28+
// List all tags, both lightweight tags and annotated tags and see if some tag points to HEAD reference.
29+
err = tags.ForEach(func(t *plumbing.Reference) error {
30+
// This technique should work for both lightweight and annotated tags.
31+
revHash, err := r.ResolveRevision(plumbing.Revision(t.Name()))
32+
CheckIfError(err)
33+
if *revHash == ref.Hash() {
34+
fmt.Printf("Found tag %s with hash %s pointing to HEAD %s\n", t.Name().Short(), revHash, ref.Hash())
35+
}
36+
return nil
37+
})
38+
}

0 commit comments

Comments
 (0)