zoukankan      html  css  js  c++  java
  • [转] 利用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

  • 相关阅读:
    js数组的基本用法及数组根据下标(数值或字符)移除元素
    Oracle备份一张表
    linux中常见的文件操作命令
    java图片二进制相互转换
    getParameterMap的使用
    前端常用
    Oracle 常用
    JAVA中int、String的类型转换
    MySQL 5.7 新特性大全和未来展望
    你有自己的Web缓存知识体系吗?
  • 原文地址:https://www.cnblogs.com/K2154952/p/5963184.html
Copyright © 2011-2022 走看看