15

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 ?

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
user1479699
  • 153
  • 1
  • 5
  • I don't see your code mentioning a branch somewhere, maybe you should specify that somewhere? – Thom Wiggers Apr 06 '15 at 10:48
  • The value of reference is 'ref/heads/master' – user1479699 Apr 06 '15 at 10:54
  • I'm having trouble finding decent documentation for pygit2, so I'm just guessing: I'm seeing you call various `write()` methods after doing some state changes. Does `create_commit()` write implicitly or are you forgetting to do that? – Thom Wiggers Apr 06 '15 at 10:56
  • I have tried to make: repository.index.write_tree() after create_commit but i ve got the same result – user1479699 Apr 06 '15 at 11:31

2 Answers2

7

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.

danilopopeye
  • 9,610
  • 1
  • 23
  • 31
Carlos Martín Nieto
  • 5,207
  • 1
  • 15
  • 16
2

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)
crab2313
  • 21
  • 1