Personal notes. To see how Git works in Python, use the ** subprocess ** module ** Popen **.
class GitError(BaseException): pass
def git(cmd, *args):
command = ("git", cmd) + args
proc = Popen(command, stdin=-1,stdout=-1,stderr=-1)
out, err = proc.communicate()
if len(err) == 0:
return out.strip()
else:
raise GitError(err.strip())
Let's create a class called ** GitUtility ** that applies this.
from subprocess import Popen
class GitError(BaseException):
"""
This Error raises when git command runner has error.
"""
pass
class GitUtility(object):
"""
The GitUtility contains utility functions for operate git.
"""
def __init__(self):
return
def run(self, cmd, *args):
"""
This command is git command runner by subprocess.
Return output or raise GitError if runner has error.
"""
if isinstance(args[0], tuple):
# Avoid duplicate tuple
# ex. self.rev_parse("--show-toplevel")
# ->('git', 'rev-parse', ('--show-toplevel',))
command = ("git", cmd) + tuple([arg for arg in args[0]])
else:
command = ("git", cmd) + args
proc = Popen(command, stdin=-1,stdout=-1,stderr=-1)
out, err = proc.communicate()
if len(err) == 0:
return out.strip()
else:
raise GitError(err.strip())
def add(self, path):
"""
Run git add command
"""
self.run("add", path)
def commit(self, commit_msg):
"""
Run git commit
"""
return self.run("commit", "-m", commit_msg)
def rev_parse(self, *args):
"""
Run git rev-parse command
"""
return self.run("rev-parse", args)
def get_toplevel(self):
"""
Return git top level path using git rev-parse
"""
return self.rev_parse("--show-toplevel")
For example, you can want to commit automatically, or you can get the repository path using rev-parse
.
If you apply it more, you can parse the log or get the contents of the file at the time of a certain commit.
Recommended Posts