-->

How can I check if pull is needed using libgit2 in

2019-07-30 14:21发布

问题:

I want to check if I have the latest version of program. I have my program shared to bitbucket.org , and I want my c++ code to write me if I need to pull the latest version, or I already have the latest version.

回答1:

First, you have to fetch to get the state of the remote tracking branches. There isn't any other way to check if your branch has been updated on the remote. Many tools automatically fetch periodically (like every 10 minutes) for this purpose.

Then compare your local branch with its upstream. One way to do that with libgit2 is to use the revwalk functionality. If you git_revwalk_push_ref the upstream and git_revwalk_hide_ref the local branch then walk over the range, you can count how many commits behind your local branch is. Do the opposite to get the number of commits ahead.

Example:

git_revwalk *walker;
git_revwalk_new(&walker, repo);
git_revwalk_push_ref(walker, "refs/remotes/origin/master");
git_revwalk_hide_ref(walker, "refs/heads/master");

git_oid id;
int count = 0;
while (!git_revwalk_next(&id, walker))
    ++count;

// 'count' is the difference between remote and local