【问题标题】:Doing a Git Pull with libgit2使用 libgit2 进行 Git 拉取
【发布时间】:2016-09-23 01:40:25
【问题描述】:

我已经查看了这篇文章 (libgit2 (fetch & merge & commit)) 中的答案,但我正在努力让 Git Pull 工作。我没有收到错误消息。 Fetch 似乎可以工作,但没有发生 Merge。执行 Git 状态显示我的分支落后 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();
}

我在做什么导致合并不起作用?

【问题讨论】:

    标签: c++ git libgit2


    【解决方案1】:

    首先,git_checkout_options.checkout_strategy 有一个相当惊人的默认值。它默认为空运行。所以你可能想把它改成GIT_CHECKOUT_SAFE

    要理解的第二件事是 git_merge 实际上并没有提交合并。它仅设置您的工作目录和索引以进行合并。您仍然需要检查冲突并调用git_commit_create 来完成合并。

    但是,在这种特定情况下,您似乎并不真的需要合并。您的分支可以快进。致电git_merge_analysis 确定要执行哪种合并。使用新的 fetch head 在当前分支上快进调用git_reference_set_target

    【讨论】:

    • 谢谢杰森。我已经尝试过您的建议进行提交。我将本地和远程分支都指定为父分支,但它使本地存储库在远程之前提交一个提交,而“git pull”不会发生这种情况。
    • 本地分支应该在提交合并后提前提交。但是,我没有认识到您实际上并不需要合并,因为您的本地历史并没有与远程历史分道扬镳。你可以快进。我会相应地更新我的答案。
    • 如果你只是用新的 fetch head 做git_reference_set_target(),它不会像git pull 那样更新工作树。
    • 是的,您还必须在设置参考目标后使用git_checkout_head 之类的内容进行结帐。
    • 我经历了git_checkout_options.checkout_strategy这个奇怪的行为,打开了这个bug报告:github.com/libgit2/libgit2/issues/5803 看来默认是适合一些非dry-run操作的,比如git_apply。跨度>
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多