功能说明:SVN的增、删、改操作可以同步相应的数据表。对文件的列表不需要遍历目录只需要读数据表提高查询效率。以下是代码
vi /opt/svndata/avatar/hooks/postcommit.py
- #!/usr/bin/env python
-
#-*-coding:utf-8-*-
-
"""
-
post-commit程序,实现对SVN的增、删、改的数据库同步
-
"""
-
import sys,os
-
import MySQLdb
-
import logging
-
from time import strftime, localtime
-
from optparse import OptionParser
-
"""
-
try:
-
error
-
except Exception,e:
-
logapp = Pubclilog()
-
logger,hdlr = logapp.iniLog()
-
logger.info(str(e))
-
hdlr.flush()
-
logger.removeHandler(hdlr)
-
return
-
-
"""
-
class Pubclilog():
-
def __init__(self):
-
self.logfile = '/tmp/ava_post_commit.txt'
-
def initLog(self):
-
logger = logging.getLogger()
-
filehandler = logging.FileHandler(self.logfile)
-
streamhandler = logging.StreamHandler()
-
fmt = logging.Formatter('%(asctime)s, %(funcName)s, %(message)s')
-
logger.setLevel(logging.DEBUG)
-
logger.addHandler(filehandler)
-
logger.addHandler(streamhandler)
-
return [logger,filehandler]
-
-
"""
-
程序处理主体
-
"""
-
class BaseSvn:
-
def __init__(self,log_switch,svnpath,svnrevision):
-
self.conn = MySQLdb.connect(db='avatar',host='10.xx.xxx.23', user='admin',passwd='123456',charset='utf8')
-
self.svnbin = "/usr/local/svn/bin"
-
self.log_switch=log_switch
-
self.svnpath = svnpath
-
self.svnrevision = svnrevision
-
-
"""
-
作用:调用svnlook获取作者与时间
-
2011-06-06 00:56:28 +0800 (Mon, 06 Jun 2011)
-
@return: ['作者','时间']
-
"""
-
def _svninfo(self):
-
cmd = '%s/svnlook author %s -r %s'% (self.svnbin, self.svnpath, self.svnrevision)
-
return [os.popen(cmd, 'r').readlines()[0].replace('\n',''),strftime("%Y-%m-%d %H:%M:%S",localtime())]
-
-
"""
-
作用:解析changed变更记录获取变更列表依据不同的类型进行相应的DB操作
- 说明:对文件的解析是不是可以进一步重构一下代码呢?感觉这个写起来有点怪怪的!
-
"""
-
def _svnpostdb(self):
-
logapp = Pubclilog()
-
logger,hdlr = logapp.initLog()
-
self.cursor = self.conn.cursor()
-
try:
-
author_time = self._svninfo()
-
cmd = '%s/svnlook changed %s -r %s'% (self.svnbin, self.svnpath, self.svnrevision)
-
content = os.popen(cmd).readlines()
-
for line in content:
-
svntype = line[0:1]
-
svncont = line.split(' ')[-1]
-
if svncont.count('/') == 1:
-
filename = svncont.split('/')[-1].strip()
-
if filename == "":
-
logger.info(line)
-
else:
-
firstle = filename[0]
-
if svntype == 'A':
-
sql = "insert into fileiso(filename,type,author,modifypl,modifytime) values('%s','%s','%s','%s','%s')" % (filename,firstle,author_time[0],author_time[0],author_time[1])
-
elif svntype == 'D':
-
sql = "delete from fileiso where filename = '%s' and type = '%s'" % (filename,firstle)
-
elif svntype == 'U':
-
sql = "update fileiso set modifynum=modifynum+1,modifypl='%s',modifytime='%s' where filename = '%s' and type = '%s'" % (author_time[0],author_time[1],filename,firstle)
-
self.cursor.execute(sql)
-
self.conn.commit()
-
else:
-
pass
-
hdlr.flush()
-
logger.removeHandler(hdlr)
-
-
except Exception,e:
-
logapp = Pubclilog()
-
logger,hdlr = logapp.initLog()
-
logger.info(str(e))
-
hdlr.flush()
-
logger.removeHandler(hdlr)
-
return
-
-
"""
-
应用启动
-
@param svnpath: 代码库目录
-
@param svnrevision:最新版本号
-
@param logswitch: 日志开关
-
@return :None
-
"""
-
def startpost(svnpath,svnrevision,logswitch='on'):
-
app=BaseSvn(logswitch,svnpath,svnrevision)
-
app._svnpostdb()
-
app=None
-
return None
-
-
-
if __name__ == '__main__':
-
"""
-
python postcommit.py -p /opt/svn/data -r 10
-
print opts.log_switch
-
print opts.path
-
print opts.revision
-
if opts.verbose:
-
print "SVN COMMIT-POST V1.0 Beta."
-
sys.exit()
-
"""
-
MSG_USAGE = "postcommit.py [-p][-r] -l [on|off] [-v]"
-
parser = OptionParser(MSG_USAGE)
-
parser.add_option("-l","--log",action="store",dest="log_switch",type="string",default="on")
-
parser.add_option("-p","--path", action="store", dest="path",help="SVN版本目录".decode('utf-8'))
-
parser.add_option("-r","--revision", action="store", dest="revision",help="SVN版本库号".decode('utf-8'))
-
parser.add_option("-v","--version", action="store_true", dest="verbose", help="versionlook".decode('utf-8'))
-
opts, args = parser.parse_args()
-
-
if opts.verbose:
-
print "Post-commit V1.0 beta."
-
sys.exit(0)
-
-
-
if opts.log_switch=="on":
-
log_switch="on"
-
else:
-
log_switch="off"
-
startpost(opts.path,opts.revision,log_switch)
-
sys.exit(0)
完了之后写到post-commit里面
#!/bin/bash
REPOS="$1"
TXN="$2"
/opt/svndata/avatar/hooks/postcommit.py -p $REPOS -r $TXN
注意postcommit.py赋上可执行权限。
阅读(6437) | 评论(0) | 转发(0) |