使用pygit2创建提交

时间:2015-04-06 10:41:16

标签: git libgit2 pygit2

我想在分支上进行提交(例如master)。

我正在使用pygit2pygit2.clone_repository

制作存储库克隆

然后我更改了存储库中的现有文件。

之后我运行它来进行提交:

index = repository.index
index.add_all()
index.write()
author = pygit2.Signature(user_name, user_mail)
commiter = pygit2.Signature(user_name, user_mail)
tree = repository.TreeBuilder().write()
oid = repository.create_commit(reference, author, commiter, message,tree,[repository.head.get_object().hex])

但是当我去存储库并运行git status

On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file:   test.txt

修改后的文件似乎是为了提交添加的,但是提交没有成功。使用返回的Oid,我可以在pygit2存储库中找到commit属性。

我错过了什么吗?

2 个答案:

答案 0 :(得分:4)

写作

tree = repository.TreeBuilder().write()

您正在创建一个空树,然后您将其作为提交树,这意味着您已删除了每个文件(如果您在运行代码后运行git show HEAD,则可以看到该文件)

你要做的是

tree = index.write_tree()

将数据作为树存储在索引中(创建缺少的任何一个),并且当您运行git commit之类的命令时会发生这种情况。然后,您可以像现在一样将此树传递给提交创建方法。

答案 1 :(得分:1)

问题是你只是创建了提交,但还没有更新你的HEAD引用。创建提交后,手动更新HEAD引用可以解决此问题。

repo.head.set_target(oid)