How to get the ref/hash of tip of branch #926
Unanswered
manuel-koch
asked this question in
Q&A
Replies: 1 comment
-
Code for local branch package main
import (
"log"
"os"
"strings"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
)
const prefLocalBranch = `refs/heads/`
type branchInfo struct {
hash string
name string
}
func checkIfError(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
dir, err := os.Getwd()
checkIfError(err)
log.Printf("Opening %s…", dir)
r, err := git.PlainOpen(dir)
checkIfError(err)
refs, err := r.References()
checkIfError(err)
branches := []branchInfo{}
addIfBranch := func(cr *plumbing.Reference) {
if cr.Type() == plumbing.HashReference {
rn := cr.Name()
if strings.HasPrefix(rn.String(), prefLocalBranch) {
branches = append(
branches,
branchInfo{
hash: cr.Hash().String(),
name: rn.Short(),
},
)
}
}
}
refs.ForEach(
func(ref *plumbing.Reference) error {
addIfBranch(ref)
return nil
},
)
log.Println(branches)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I want the commit hash of a local/remote branch tip.
What would be an equivalent go-git code?
For a local branch:
git rev-list my-branch | head -1
or a remote branch:
git rev-list origin/my-branch | head -1
Beta Was this translation helpful? Give feedback.
All reactions