Instantly share code, notes, and snippets.

@dexbol dexbol/sync.py
Last active Dec 14, 2015

Embed
What would you like to do?
# coding=utf-8
''' svn post-commit hook. checkout the repository and synchronizate to the
working copy. you can add some feature that you demand, e.g. after all, restart
your web server persuades the code changes to take effect.
'''
import os
import logging
import sys
import tempfile
import subprocess
import re
import shutil
import argparse
logging.basicConfig(level=logging.DEBUG)
def getLogger():
logger = logging.getLogger(__name__)
ih = logging.FileHandler('/var/log/svn.log')
ih.setLevel(logging.INFO)
dh = logging.FileHandler('/var/log/svn-debug.log')
dh.setLevel(logging.DEBUG)
logger.addHandler(ih)
logger.addHandler(dh)
return logger
logger = getLogger()
def lookchange(repository):
pattern = re.compile(r'''^\s*(A|D|U)\s+([\w\.\/]+)\s*$''', re.VERBOSE)
changed = []
try:
result = subprocess.check_output(['svnlook', 'changed', repository])
logger.debug('svnlook change: \n' + result)
lines = result.split('\n')
for line in lines:
matchobj = re.search(pattern, line)
if matchobj:
flag = matchobj.group(1)
path = matchobj.group(2)
changed.append({
'flag': flag,
'path': path
})
logger.debug('add changed: ' + flag + ' ' + path)
except subprocess.CalledProcessError as e:
logger.error(e)
return changed
def checkout(repository, tempath):
try:
subprocess.check_call(['svn', 'checkout', '-q', 'file://' + repository,
tempath])
except subprocess.CalledProcessError as e:
logger.error(e)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('repos', action='store', help='svn repository path')
parser.add_argument('cp', action='store', help='working copy path')
args = vars(parser.parse_args())
logger.debug('parameter: ' + repr(args))
repository = args['repos']
working = args['cp']
tempath = tempfile.mkdtemp()
logger.debug('repository: ' + repository)
logger.debug('working cope: ' + working)
logger.debug('temporary path: ' + tempath)
checkout(repository, tempath)
changed = lookchange(repository)
for item in changed:
logger.debug('process changed: ' + repr(item))
flag = item['flag']
path = item['path']
working_path = working + os.sep + path
tempath_path = tempath + os.sep + path
if item['flag'] == 'D':
logger.debug('remove : ' + working_path)
os.remove(working_path) if os.path.isfile(working_path) else \
shutil.rmtree(working_path)
else:
logger.debug('overwrite : ' + working_path)
if os.path.exists(tempath_path):
shutil.move(tempath_path, working_path)
logger.debug('remove temporary path')
shutil.rmtree(tempath)
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment