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 ?
At a minimum I needed the init, add, commit, and push commands, but pygit also implements status, diff, cat-file, ls-files, and hash-object. The latter commands are useful in their own right, but they were also very helpful when debugging pygit. So let’s dive into the code!
Example git commit -m "First release of Hello World!" [master (root-commit) 221ec6e] First release of Hello World! 3 files changed, 26 insertions (+) create mode 100644 README.md create mode 100644 bluestyle.css create mode 100644 index.html The commit command performs a commit, and the -m " message " adds a message.
My version, called pygit, is written in Python (3.5+) and uses only standard library modules. It’s just over 500 lines of code, including blank lines and comments. At a minimum I needed the init, add, commit, and push commands, but pygit also implements status, diff, cat-file, ls-files, and hash-object.
You may check out the related API usage on the sidebar. You may also want to check out all available functions/classes of the module pygit2 , or try the search function .
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With