Tuesday, October 4, 2011

Git in Python using Subprocess


I already introduced you the DVCS used in my project, Git. Git is a powerful open source tool which is used for the version control system. It is developed by the Linus Torvards who has already gifted us the powerful kernel of Linux. In this post, I want to describe you how I integrated git with python.

We need to import subprocess module for this. We are calling the git commands using the subprocess.

import subprocess
from subprocess import call

Subprocess allows us to call the command that run in terminal. We know the command for displaying files in the current directory is “ls”. For calling “ls” from the python program using the subprocess module,

subprocess.Popen(["ls"],cwd = accpath)

cwd is the current working directory. We need to specify the path of the current directory like /home/ajay/Documents. It can be assigned to a variable like accpath.

dirpath = os.path.dirname(os.path.realpath('articles'))
accpath = dirpath + '/articles'

In my project I need to initialize the git repository first. So I need to write the following code,

subprocess.Popen(["git","init"],cwd = accpath)

Now I need to write the proper codes for calling the git commands, whenever an article is created/modified. When an article is created, the following codes are used to add the modified files and to commit them.

subprocess.Popen(["git","add",title.lower()],cwd = accpath)
subprocess.Popen(["git","commit","-m","'committed'"],cwd = accpath)

title.lower() is used save the article name in small letters.

Now we need to save the details of hash codes of particular commits, because we need that hash code in order to perform rollbacks in future. So we need to extract the hash code from each commit. Git log command helps to see the commits and its hash codes. "git log -p -1” command displays the last commit and its hash code. We need to save that message in a file. Use the following code for that.

p = subprocess.Popen(["git","log","-p","-1"], cwd = accpath, stdout = subprocess.PIPE,)
stdout_value = p.communicate()[0]
t1 = repr(stdout_value)

Now “t1” has the message which is displayed by entering "git log -p -1”. We need to extract the hash code from it using the regular expressions. I will write post about regular expression soon.

The same commands can be used whenever an article is modified. I will post more issues I faced during the project development.

Thanks

AJAY

1 comment: