-->

Doing git fetch && git merge from remote with git2

2019-07-20 23:34发布

问题:

I'm using libgit2/git2go v0.22 and trying to implement something similar to a "git pull" from a remote repository. In this case The working directory doesn't write anything: no changes, no commits, no push. It will only pull data from the remote.

Using git2go I can clone the remote repository, load/lookup a remote origin, fetch the remote, list remote headers, etc. It seems that the only step not working is the merge. My code looks like this (i'm ommiting the error handling):

repo, err:= git.OpenRepository(sitesConfig.Sites[SiteName].Path)
remote, err:= repo.LookupRemote("origin")
err = remote.SetCallbacks(&rcbs)
err = remote.Connect(git.ConnectDirectionFetch)
err = remote.ConnectFetch()

remote_master, err := repo.LookupReference("refs/remotes/origin/master")
mergeRemoteHead, err := repo.AnnotatedCommitFromRef(remote_master)
mergeHeads := make([]*git.AnnotatedCommit, 1)
mergeHeads[0] = mergeRemoteHead
err = repo.Merge(mergeHeads, nil, nil)
repo.StateCleanup()

No errors appear when running this code, but the working directory is not updated. Using "git pull" and "git fetch && git marge origin/master" on the same directory worked fine.

Is something missing? A final commit?

回答1:

You are asking to connect to the remote twice (err = remote.Connect(git.ConnectDirectionFetch) and err = remote.ConnectFetch()), but you're not asking it for anything. Instead of trying to connect twice, use the all-in-one fetch method

remote.Fetch(nil, nil, nil)

to connect, download and update the remote-tracking branches. Then you can check whether there was an update and merge or do whatever you need.



标签: go libgit2