使用libgit2进行Git Pull操作

6

我查看了这篇帖子中的答案 (libgit2 (fetch & merge & commit)),但是我无法让Git Pull工作。我没有收到错误消息。Fetch似乎正常工作,但合并没有发生。执行Git Status后显示我的分支落后1个提交...

On branch Branch_1_1.
Your branch is behind 'origin/Branch_1_1' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)
nothing to commit, working directory clean

我的代码如下...

static int fetchhead_ref_cb(const char *name, const char *url,
   const git_oid *oid, unsigned int is_merge, void *payload)

{
   if ( is_merge )
   {
      strcpy_s( branchToMerge, 100, name );
      memcpy( &branchOidToMerge, oid, sizeof( git_oid ) );
   }
   return 0;
}

void GitPull()
{
   git_libgit2_init();

   git_repository *repo = NULL;
   git_remote *remote;

   int error = git_repository_open( &repo, "C:\\work\\GitTestRepos\\Repo1" );
   CHECK_FOR_ERROR

   error = git_remote_lookup( &remote, repo, "origin" );
   CHECK_FOR_ERROR

   git_fetch_options options = GIT_FETCH_OPTIONS_INIT;
   error = git_remote_fetch( remote, NULL, &options, NULL );
   CHECK_FOR_ERROR

   git_repository_fetchhead_foreach( repo, fetchhead_ref_cb, NULL );

   git_merge_options merge_options = GIT_MERGE_OPTIONS_INIT;
   git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT;
   git_annotated_commit *heads[ 1 ];
   git_reference *ref;

   error = git_annotated_commit_lookup( &heads[ 0 ], repo, &branchOidToMerge );
   CHECK_FOR_ERROR
   error = git_merge( repo, (const git_annotated_commit **)heads, 1, &merge_options, &checkout_options );
   CHECK_FOR_ERROR

   git_annotated_commit_free( heads[ 0 ] );
   git_repository_state_cleanup( repo );
   git_libgit2_shutdown();
}

我做了什么导致合并无法工作?

1个回答

4

首先,git_checkout_options.checkout_strategy 的默认值相当令人惊讶,它默认为 dry run 模式。因此,您可能需要将其更改为类似于 GIT_CHECKOUT_SAFE 的内容。

第二点需要了解的是,git_merge 并不实际提交合并。它只是设置您的工作目录和索引以进行合并操作。您仍然需要检查冲突并调用 git_commit_create 来完成合并。

但是,在这种特定情况下,看起来您并不真正需要进行合并操作。您的分支可以快速向前移动。调用 git_merge_analysis 来确定要执行哪种类型的合并操作。要快进,请使用新的获取头文件调用 git_reference_set_target 在当前分支上。


谢谢Jason。我尝试了你的建议进行提交。我指定本地和远程分支作为父级,但它会使本地仓库比远程多一个提交,这在“git pull”中不会发生。 - Anthony
本地分支在合并后应该领先一个提交。然而,我没有意识到你实际上不需要合并,因为你的本地历史与远程历史没有分歧。你可以快进。我会相应地更新我的回答。 - Jason Haslam
如果你只是使用新的拉取头执行 git_reference_set_target(),它不会像 git pull 一样更新工作树。 - Timmmm
是的,在设置参考目标后,您还需要使用类似于“git_checkout_head”的命令进行检出。 - Jason Haslam
我遇到了git_checkout_options.checkout_strategy的奇怪行为并打开了这个错误报告:https://github.com/libgit2/libgit2/issues/5803。看起来默认设置适用于一些非干运行操作,如`git_apply`。 - Aaron Franke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接