1. 程式人生 > 實用技巧 >git 專案程式碼打包

git 專案程式碼打包

#!/usr/bin/env python
#coding=utf8
import sys
import re
import os
import subprocess
import shutil

base_path = '/tmp/test'
if not os.path.exists(base_path):
    os.makedirs(base_path)

# 使用正則獲取命令程式碼和要處理的分支資訊
actionfmt = r'^UP ?(\w+)?$'
# branches = ('master')

def getgitargs(*args):
    if args:
        return ['git', '--bare', '--git-dir', os.getcwd()] + list(args)
    return []

def callgit(*args):
    # cmd=['env', '-i'] + getgitargs(*args)
    cmd=getgitargs(*args)
    print(' '.join(cmd))
    return subprocess.check_output(cmd,
        universal_newlines=True, stderr=subprocess.STDOUT)

# 從提交資訊中得到要處理的真正分支
def getref(branch):
    commitmsg = callgit('log', branch, '--oneline', '-1')
    # matchobj = re.search(actionfmt, commitmsg)
    # if matchobj:
    #     if matchobj.group(1):
    #         return matchobj.group(1)
    #     return branch
    # return None
    print('commitmsg',commitmsg)
    return commitmsg.split(' ')[0]

# 將 server/src 備份到一個檔案
def archive(refname):
    tarfile = '%s/%s.tar'%(base_path, refname)
    callgit('archive', '-o', tarfile, refname)
    print('archive', '-o', tarfile, refname)
    return tarfile

# 解壓縮備份檔案到正確的資料夾
def tarxf(tarfile, refname, branch):
    refdir = os.path.join(base_path, branch)
    if os.path.exists(refdir):
        shutil.rmtree(refdir)
    args = ['tar', 'xf', tarfile, '-C', base_path]
    output = subprocess.check_output(args,
        stderr=subprocess.STDOUT, universal_newlines=True)
    shutil.move(os.path.join(base_path, 'src/'), refdir)
    print(os.path.join(base_path, 'src/'),'-->', refdir)
    os.remove(tarfile)
    return output

oldrev,newrev,refname = sys.stdin.readline().strip().split(' ')
print('oldref:%s, newrev:%s, refname:%s'%(oldrev, newrev, refname))

branch = refname.split('/')[-1]
# print(branch, 'in?',branches)
# if not branch in branches:
#     print('The branch "%s" is not in available list! '
#         'The list is %s.'%(branch, str(branches)))
#     exit(1)

try:
    refname = getref(branch)
    print('refname',refname)
    if refname:
        tarfile = archive(refname)
        succ = tarxf(tarfile, refname, branch)
        print('update [%s] by [%s] success.'%(branch, refname) )
        print('======= update [%s] by [%s] SUCCESS ======='%(branch, refname))
except subprocess.CalledProcessError as err:
    print('update [%s] by [%s] error: %s'%(branch, refname, err.output))
    print('======= update [%s] by [%s] ERROR ======='%(branch, refname))
    exit(1)

exit(0)