#!/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)