Create commit with pygit2

I would like to commit on a branch (e.g. master).

I am doing repository cloning using pygit2 ( pygit2.clone_repository )

Then I modify the existing file in the repository.

Then 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 is apparently added for commit, but the commit failed. Using the returned Oid, I can find the commit attribute in the pygit2 repository.

Did I miss something?

+6
source share
2 answers

By writing

 tree = repository.TreeBuilder().write() 

you create an empty tree and then point it as a tree to commit, which means you deleted every file (which you can see if you ran git show HEAD after running your code).

Instead you want

 tree = index.write_tree() 

which stores the data in the index as a tree (creating depending on what is missing) in the repository, and this happens when you run a command like git commit . You can then pass this tree to the commit creation method, as of now.

+3
source

The problem is that you are just creating a commit, but not updating the HEAD link. After creating the commit, manually update the HEAD link to fix this problem.

 repo.head.set_target(oid) 
0
source

Source: https://habr.com/ru/post/984737/


All Articles