Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

examples: added "tag find if head is tagged" #374

Merged
merged 1 commit into from Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions _examples/README.md
Expand Up @@ -19,6 +19,7 @@ Here you can find a list of annotated _go-git_ examples:
- [branch](branch/main.go) - How to create and remove branches or any other kind of reference.
- [tag](tag/main.go) - List/print repository tags.
- [tag create and push](tag-create-push/main.go) - Create and push a new tag.
- [tag find if head is tagged](find-if-any-tag-point-head/main.go) - Find if `HEAD` is tagged.
- [remotes](remotes/main.go) - Working with remotes: adding, removing, etc.
- [progress](progress/main.go) - Printing the progress information from the sideband.
- [revision](revision/main.go) - Solve a revision into a commit.
Expand Down
38 changes: 38 additions & 0 deletions _examples/find-if-any-tag-point-head/main.go
@@ -0,0 +1,38 @@
package main

import (
"fmt"
"os"

"github.com/go-git/go-git/v5"
. "github.com/go-git/go-git/v5/_examples"
"github.com/go-git/go-git/v5/plumbing"
)

// Basic example of how to find if HEAD is tagged.
func main() {
CheckArgs("<path>")
path := os.Args[1]

// We instantiate a new repository targeting the given path (the .git folder)
r, err := git.PlainOpen(path)
CheckIfError(err)

// Get HEAD reference to use for comparison later on.
ref, err := r.Head()
CheckIfError(err)

tags, err := r.Tags()
CheckIfError(err)

// List all tags, both lightweight tags and annotated tags and see if some tag points to HEAD reference.
err = tags.ForEach(func(t *plumbing.Reference) error {
// This technique should work for both lightweight and annotated tags.
revHash, err := r.ResolveRevision(plumbing.Revision(t.Name()))
CheckIfError(err)
if *revHash == ref.Hash() {
fmt.Printf("Found tag %s with hash %s pointing to HEAD %s\n", t.Name().Short(), revHash, ref.Hash())
}
return nil
})
}