使用pygit2创建提交

使用pygit2创建提交,git,libgit2,pygit2,Git,Libgit2,Pygit2,我想对一个分支进行提交(例如master) 我正在使用pygit2(pygit2.clone\u repository) 然后更改存储库中的现有文件 之后,我运行此命令进行提交: index = repository.index index.add_all() index.write() author = pygit2.Signature(user_name, user_mail) commiter = pygit2.Signature(user_name, user_mail) tree =

我想对一个分支进行提交(例如master)

我正在使用
pygit2
pygit2.clone\u 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
分支主机上的

要提交的更改:
(使用“git重置磁头…”取消分级)
新文件:test.txt
修改后的文件似乎已添加以进行提交,但提交未成功。使用返回的Oid,我可以在pygit2存储库中找到commit属性

我错过什么了吗?

因为写作

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

你想做的是

tree = index.write_tree()

它将索引中的数据存储为存储库中的树(创建缺少的树),这是在运行类似于
git commit
的命令时发生的情况。然后,您可以像现在一样将此树传递给提交创建方法。

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

repo.head.set_target(oid)

我没有看到你的代码在某处提到分支,也许你应该在某处指定它?引用的值是'ref/heads/master',我很难找到pygit2的合适文档,所以我只是猜测:我看到你在做了一些状态更改后调用了各种
write()
方法。
create\u commit()
write是隐式的还是忘记了这么做?我尝试在create\u commit之后生成:repository.index.write\u tree(),但得到了相同的结果