ycycoco 发表于 2018-9-17 13:30:52

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

#!/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 =
  #查找从上次提交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 =
  

  self.pushAuthor = pipe.strip("Author:").strip()
  self.pushTime = pipe.strip("Date:").strip()
  self.fileList.extend([ '/'.join(fileName.split("/")) 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()


页: [1]
查看完整版本: 利用git钩子,使用python语言获取提交的文件列表