Git commit from python
I want to write a module in python (This is the learning project) to enhance my git experience. Is there a python module for various git commands? At least the basic ones (commit/diff/log/add)?
I saw GitPython but I couldn't find the support for (new) commits; i开发者_运维问答ts more of a repo browsing framework than a complete GIT interface. (Or did I miss something?)
Also, if there IS a python module for all this, will that be preferable, or executing the shell commands from python code?
In GitPython you create a commit from an index object.
In libgit2 you create a commit from a repository object.
You might also want to look at this question:
- Python Git Module experiences?
I think some python source could help beginners like me not to waste precious time on digging docs.
All commits will go to freshly created origin master
Here it is:
from git import Repo
import os
path = '/your/path/here'
if not os.path.exists(path):
os.makedirs(path)
os.chdir(path)
repo = Repo.init(path).git
index = Repo.init(path).index
for x in xrange (1,10):
fname = 'filename' + str(x)
f.open(fname, 'wb+')
f.write()
f.close()
repo.add(fname)
index.commit("initial commit")
Git is designed to consist of "plumbing" and "porcelain". Plumbing components form the foundation, low-level system: Managing objects, repositories, remotes, and so on. Porcelain, on the other hand, means more user-friendly high-level tools that use the plumbing.
Historically, only the most basic/performance-critical parts (mostly plumbing) were implemented in C, the rest used shell/perl scripts. To be more portable, more and more code was rewritten in C.
With this background, I would recommend to just use system calls to the git executable for your python wrapping. Consider your code as part of Git's porcelain. Compared to using a specialized library:
PRO
- No need to learn an API -- use the
git
commands you are familiar with - Complete set of tools -- you can use porcelain and are not restricted to low-level functionality
CONTRA
- Need to parse command line output from
git
calls. - Might be slower
This can be done with GitPython
Install it with:
pip install GitPython
And use it like this:
from git.repo import Repo
repo = Repo('/path/to/repository')
repo.index.add(['some_file'])
repo.index.commit('commit from python')
origin = repo.remotes[0]
origin.push()
Learn more in the documentation.
精彩评论