[轉] 利用git鈎子,使用python語言獲取提交的文件列表


項目有個需求,需要獲取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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM