user1479699
user1479699

Reputation: 153

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 pygit2 (pygit2.clone_repository)

Then I change an existing file in the repository.

Afterwards I run this to make a commit:

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])

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 ?

Upvotes: 15

Views: 4424

Answers (2)

crab2313
crab2313

Reputation: 21

The problem is you just create the commit, but haven't update your HEAD reference. After create the commit, manually update your HEAD reference can fix this issue.

repo.head.set_target(oid)

Upvotes: 2

Carlos Mart&#237;n Nieto
Carlos Mart&#237;n Nieto

Reputation: 5277

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.

Upvotes: 7

Related Questions