PyGit2 - TreeBuilder.insert('name',blobid,GIT_FILEMODE_BLOB) vs index.add( 'path/to/file' )?

503 Views Asked by At

I'm a little confused about how to get started with PyGit2.

When adding files (plural) to a newly created repo, should I add them to index.add('path/to/file')
or would I be better off creating a TreeBuilder and using tb.insert( 'name',oid, GIT_FILEMODE_BLOB ) to add new content ?

If the second case, I am stumped as to how I create the tree object needed to commit to a newly created repo?

Anyone?

2

There are 2 best solutions below

0
On

Assuming your pygit2.Repository is called repo, try:

t_builder = repo.TreeBuilder()

More handy info with help(pygit2.TreeBuilder) from Python console.

0
On

You can do either ways.
I find the index.add() method straightforward.

You can fetch all the files to be added or removed to the index using Repository.status() as a dictionary. The dictionary contains the filename as key and status of file as value. Depending upon the status values deleted files will be needed to be removed from index using index.remove(filename).
Write this index to in-memory tree using index.write_tree() which will return a tree-id to be used in Repository.commit(). However for changes to be saved to disk use index.write() too.