user1479699 user1479699 - 1 year ago 134
Git Question

Create a commit using pygit2

I would like to make a commit on a branch (master for example).

I am making a repository clone using


Then I change an existing file in the repository.

Afterwards I run this to make a commit:

index = repository.index
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])

But when i go to the repository and run
git status

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

The modified file seems to be added for commit but the commit did not succeed. Using the returned Oid i can find the commit attribute in the pygit2 repository.

Did I miss something ?

Answer Source

By writing

tree = repository.TreeBuilder().write()

you are creating an empty tree and you're then giving this as the tree for the commit, which means that you've deleted every file (which you can see if you run git show HEAD after running your code).

What you want to do instead is

tree = index.write_tree()

which stores the data in the index as a tree (creating whichever are missing) in the repository and is what happens when you run a command like git commit. You can then pass this tree in to the commit-creation method like you're doing now.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download