go-git在分支之间的差异

huangapple go评论102阅读模式
英文:

go-git diff between branches

问题

使用go-git可以获取两个分支之间的差异,或者例如当前分支和主分支之间的差异吗?

使用GIT可以获取当前分支和主分支之间的差异:

$ git diff master

以及两个分支之间的差异:

$ git diff master feature/branch

我在这个答案中找到了使用(*object.Commit).Patch的方法,但是它是在提交之间,而不是在分支之间。

英文:

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.

答案1

得分: 1

使用go-git,你可以从func (r *Repository) Branch(name string) (*config.Branch, error)获取一个分支。

或者获取一个引用:

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

从该引用中获取一个提交,每个分支都有一个。
这样,你就可以调用Patch()

英文:

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()

答案2

得分: -1

请尝试这个代码:

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)
}

希望对你有帮助!

英文:

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)
}

huangapple
  • 本文由 发表于 2021年12月2日 17:30:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/70196985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定