6

I am trying to use pygit2 library.

seems I got stuck on the first step. its documentation doesn't explain how to create a blob and add it to a tree. It is mostly around how to work with an existing git repository but I want to create one and add blobs, commits, ... to my repo. Is it possible to create a blob from a file directly or should I read the file contents and set blob.data?

from pygit2 import Repository
from pygit2 import init_repository

bare = False
repo = init_repository('test', bare)

How can I create and add blobs or trees to the repository?

1 Answer 1

7

The python bindings don't let you create a blob from a file directly, so you'll have to read in the file to memory and use Repository.write(pygit2.GIT_OBJ_BLOB, filecontents) to create the blob.

You can then create trees with the TreeBuilder, for example, like

import pygit2 as g

repo = g.Repository('.')
# grab the file from wherever and store in 'contents'
oid = repo.write(g.GIT_OBJ_BLOB, contents)
bld = repo.TreeBuilder()
# attributes is whether it's a file or dir, 100644, 100755 or 040000
bld.insert('file.txt', oid, attributes)
treeoid = bld.write()
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a lot, how can I learn more about pygit2? none of what you mentioned is in pygit2 document, How did you learn how to use it?
@PeqiHash Carlos is one of the developers of libgit2
If you changed a file do you still add the whole file to the repo as a blob and then reference that oid with an insert using TreeBuilder...or is there something to do with a patch here?
Patches exist on a different level. The full contents of each version of a file are contained in a blob. If you update it, you need to update the blob and any tree leading from it up to the root.
How to handle it if the file may be inside a subdirectory (and the directory may or may not exist yet)? It seems that I cannot write bld.insert('path/to/file.txt', oid, attributes).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.