我看过这篇文章 (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();
}
我在做什么导致 merge 不起作用?
最佳答案
首先,git_checkout_options.checkout_strategy
有一个相当令人惊讶的默认值。它默认为试运行。因此,您可能希望将其更改为类似 GIT_CHECKOUT_SAFE
的内容。
要了解的第二件事是 git_merge 实际上并不提交 merge 。它仅为 merge 设置您的工作目录和索引。您仍然需要检查冲突并调用 git_commit_create
来完成 merge 。
但是,在这种特定情况下,您似乎并不真的需要 merge 。您的分支可以快进。调用 git_merge_analysis
来确定要进行哪种 merge 。要使用新的提取头在当前分支上快进调用 git_reference_set_target
。
关于c++ - 使用 libgit2 执行 Git Pull,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651287/