src-d / go-git

Project has been moved to: https://github.com/go-git/go-git
https://github.com/go-git/go-git
Apache License 2.0
4.9k stars 541 forks source link

Proper way to get files for a branch? #1108

Open Broham opened 5 years ago

Broham commented 5 years ago

So far I've come up with the code below (which does work):

r, err := git.PlainOpen(repository)
handleError(err, fmt.Sprintf("Problem opening repository %s", repository))
branches, err := r.Branches()
handleError(err, "Problem accessing branches")
branches.ForEach(func(b *plumbing.Reference) error {
    fmt.Println("Branch:", b.Name(), "hash:", b.Hash())
    if b.Name == branchName {
        commit, _ := r.CommitObject(b.Hash())
        files, _ := commit.Files()
        files.ForEach(func(f *object.File) error {
            fmt.Println("File Name:", f.Name)
            return nil
        })
    }
    return nil
})

But the portion where I'm looping through all the branches and checking the name seems like it's not ideal. I had been hoping that I could get the files for a branch by using config.Branch like below:

branch, err := r.Branch(branchName)
// some how use this to get the hash that I care about
commit, _ := r.CommitObject(b.Hash())

But I can't figure out any way to get a hash from config.Branch. Is it possible to do what I'm trying in the second example or is the first example I provided the best way to get files for a branch?

saracen commented 5 years ago

You can get the reference to a branch without iteration:

ref, err := r.Reference(plumbing.ReferenceName("refs/heads/master"), false)

or

ref, err := r.Reference(plumbing.NewBranchReferenceName("master"), false)

So in full:

ref, err := r.Reference(plumbing.ReferenceName("refs/heads/master"), false)
if err != nil {
    panic(err)
}

commit, err := r.CommitObject(ref.Hash())
if err != nil {
    panic(err)
}

files, err := commit.Files()
if err != nil {
    panic(err)
}

files.ForEach(func(f *object.File) error {
    fmt.Println("File Name:", f.Name)
    return nil
})