2

It's possible with go-git to get the differences between two branches, or, for instance, current branch and master?

With GIT you can get diff between current branch and master:

$ git diff master

And between two branches:

$ git diff master feature/branch

I've find this answer to use (*object.Commit).Patch, but is between commits, not branches.

p3quod
  • 1,449
  • 3
  • 13
  • 15
  • I find it is usually much easier to invoke `git` with `exec.Command()` and parse what you need from the output of the process. – Zyl Dec 02 '21 at 09:35

2 Answers2

1

Using go-git, you can get a Branch from func (r *Repository) Branch(name string) (*config.Branch, error)

Or get a ref:

ref := plumbing.NewHashReference("refs/heads/my-branch", headRef.Hash())

Get a Commit from that ref, one for each branch.
That way, you can call Patch()

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
-1

Try this one

func CompareMainNHead() {
    repo, err := git.PlainOpen("./")
    if err != nil {
        log.Fatal(err)
    }

    ref, err := repo.Head()
    if err != nil {
        log.Fatal(err)
    }

    refMain, err := repo.Reference("refs/heads/main", false)
    if err != nil {
        log.Fatal(err)
    }

    commCur, err := repo.CommitObject(ref.Hash())
    treeCur, err := commCur.Tree()

    commMain, err := repo.CommitObject(refMain.Hash())
    treeMain, err := commMain.Tree()

    changes, err := object.DiffTree(treeCur, treeMain)
    fmt.Println(changes)
    diff, _ := commCur.MergeBase(commMain)
    fmt.Println("diff: ", diff)
}