如何使用pygit2移除指定提交?现有方案遇GitError报错
问题:用pygit2实现移除指定提交遇到困境
背景
在原生Git中,移除指定提交可以执行以下命令:
git rebase --onto SHA^ SHA
但pygit2库中没有直接对应的方法。
第一种尝试:基于merge_trees实现
参考pygit2文档,尝试使用merge_trees来实现该功能,写出如下代码:
def deleteCommit(repo, commitId): delete_commit = repo[commitId] head = repo.head base = repo.merge_base(delete_commit.id, head.target) delete_commit_tree = repo.get(delete_commit).tree head_tree = repo.get(head.target).tree base_tree = repo.get(base).tree index = repo.merge_trees(base_tree, head_tree, delete_commit_tree) tree_id = index.write_tree(repo)
第二种尝试:基于repo.walk()实现
尝试用repo.walk()编写解决方案,但运行时触发错误,代码如下:
def deleteCommit(repo, commitId): # 获取要重写的分支 branch = repo.lookup_branch(repo.head.shorthand) branch_ref = repo.lookup_reference(branch.name) # 获取分支尖端之前的提交历史 commits = list(repo.walk(branch.target, GIT_SORT_TOPOLOGICAL)) # 创建包含所需更改的新树 tree = repo.TreeBuilder().write() for commit in commits: if commitId != str(commit.id): commitOid = git.Oid(hex=commitId) if commitOid in commit.parent_ids: commit.parent_ids.remove(commitOid) repo.create_commit( branch_ref.name, # 无reflog消息 commit.author, # 使用默认签名 commit.committer, # 使用默认签名 commit.message, # 提交消息 tree, # 使用新树 commit.parent_ids, ) else: repo.references.delete(f'refs/commits/{commit.hex}') # 将分支指向新提交 branch_ref.set_target(tree)
触发的错误
pygit2.GitError: 创建提交失败:当前尖端不是第一个父提交
内容的提问来源于stack exchange,提问作者Nameless
相关产品推荐
相关产品推荐

