Skip to content

Instantly share code, notes, and snippets.

@pierremarc
Created September 19, 2012 15:21
Show Gist options
  • Save pierremarc/3750225 to your computer and use it in GitHub Desktop.
Save pierremarc/3750225 to your computer and use it in GitHub Desktop.
Add files to a repo with pygit2
"""
test commit creation with pygit2
To see the result:
rm -rf foo && python test_cc.py && cd foo/ && git log --graph --oneline --date-order --decorate --color --all && git status && cd ..
"""
import os
import sys
import pygit2
import stat
from time import time
data = 'This is an empty README file'
fn = 'README'
s = pygit2.Signature('Alice Author', '[email protected]', time(), 0)
r = pygit2.init_repository('foo', False)
bld = r.TreeBuilder()
t = bld.write()
c = r.create_commit('HEAD', s,s, 'Create master branch', t, [])
f = open(os.path.join(r.workdir,fn), 'w')
f.write(data)
f.close()
b = r.create_blob_fromfile(fn)
bld = r.TreeBuilder(r.head.tree)
bld.insert(fn, b, os.stat(fn).st_mode )
t = bld.write()
r.index.read()
r.index.add(fn)
r.index.write()
c = r.create_commit('HEAD', s,s, 'Added a README', t, [r.head.oid])
@yan12125
Copy link

PyGit2 API has changed a lot. This patch works for me:

diff --git a/test_cc.py b/test_cc.py
index cebc608..c214184 100644
--- a/test_cc.py
+++ b/test_cc.py
@@ -15,7 +15,7 @@ from time import time
 data = 'This is an empty README file'
 fn = 'README'

-s = pygit2.Signature('Alice Author', '[email protected]', time(), 0)
+s = pygit2.Signature('Alice Author', '[email protected]', int(time()), 0)

 r = pygit2.init_repository('foo', False)
 bld = r.TreeBuilder()
@@ -27,9 +27,9 @@ f = open(os.path.join(r.workdir,fn), 'w')
 f.write(data)
 f.close()

-b = r.create_blob_fromfile(fn)
-bld = r.TreeBuilder(r.head.tree)
-bld.insert(fn, b, os.stat(fn).st_mode )
+b = r.create_blob_fromworkdir(fn)
+bld = r.TreeBuilder()
+bld.insert(fn, b, os.stat(os.path.join('foo', fn)).st_mode )
 t = bld.write()

 r.index.read()
@@ -37,4 +37,4 @@ r.index.add(fn)
 r.index.write()


-c = r.create_commit('HEAD', s,s, 'Added a README', t, [r.head.oid])
+c = r.create_commit('HEAD', s,s, 'Added a README', t, [r.head.target])

I'm not sure what's the effect of dismiss the arguments for TreeBuilder()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment