[转] 利用git钩子,使用python语言获取提交的文件列表

时间:2023-03-08 17:08:52

项目有个需求,需要获取push到远程版本库的文件列表,并对文件进行特定分析。很自然的想到,要利用git钩子来触发一个脚本,实现获取文件列表的功能。比较着急使用该功能,就用python配合一些git命令写了一个脚本出来,等想到更好的方法后再对脚本进行修改。

#!/usr/bin/env python
#coding=utf-8
'''
该脚本在pre-receive或post-receive钩子中被调用,也可以直接将该文件作为git的钩子使用
若钩子为shell脚本,则需要加入以下代码调用该脚本:
while read line;do
echo $line | python $PATH/pre-receive.py
done
当用户执行git push的时候会在远程版本库上触发此脚本
该脚本的主要作用:获取用户提交至版本库的文件列表,提交者及时间信息
''' import sys,subprocess __author__ = "liuzhenwei" class Trigger(object): def __init__(self):
'''
初始化文件列表信息,提交者信息,提交时间,当前操作的分支
'''
self.pushAuthor = ""
self.pushTime = ""
self.fileList = []
self.ref = "" def __getGitInfo(self):
'''
'''
self.oldObject,self.newObject,self.ref = sys.stdin.readline().strip().split(' ') def __getPushInfo(self):
'''
git show命令获取push作者,时间,以及文件列表
文件的路径为相对于版本库根目录的一个相对路径
''' rev = subprocess.Popen('git rev-list '+self.newObject,shell=True,stdout=subprocess.PIPE)
revList = rev.stdout.readlines()
revList = [x.strip() for x in revList] #查找从上次提交self.oldObject之后还有多少次提交,即本次push提交的object列表
indexOld = revList.index(self.oldObject)
pushList = revList[:indexOld] #循环获取每次提交的文件列表
for pObject in pushList:
p = subprocess.Popen('git show '+pObject,shell=True,stdout=subprocess.PIPE)
pipe = p.stdout.readlines()
pipe = [x.strip() for x in pipe] self.pushAuthor = pipe[1].strip("Author:").strip()
self.pushTime = pipe[2].strip("Date:").strip() self.fileList.extend([ '/'.join(fileName.split("/")[1:]) for fileName in pipe if fileName.startswith("+++") and not fileName.endswith("null")]) def getGitPushInfo(self):
'''
返回文件列表信息,提交者信息,提交时间
'''
self.__getGitInfo()
self.__getPushInfo() print "Time:",self.pushTime
print "Author:",self.pushAuthor
print "Ref:",self.ref
print "Files:",self.fileList if __name__ == "__main__":
t = Trigger()
t.getGitPushInfo()

转自:http://diannaowa.blog.51cto.com/3219919/1671384