Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1424247
  • 博文数量: 264
  • 博客积分: 5810
  • 博客等级: 大校
  • 技术积分: 3528
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-13 17:15
文章分类

全部博文(264)

文章存档

2011年(264)

分类: Python/Ruby

2011-06-09 19:30:09

功能说明:SVN的增、删、改操作可以同步相应的数据表。对文件的列表不需要遍历目录只需要读数据表提高查询效率。以下是代码
vi /opt/svndata/avatar/hooks/postcommit.py
  1. #!/usr/bin/env python
  2. #-*-coding:utf-8-*-
  3. """
  4. post-commit程序,实现对SVN的增、删、改的数据库同步
  5. """
  6. import sys,os
  7. import MySQLdb
  8. import logging
  9. from time import strftime, localtime
  10. from optparse import OptionParser
  11. """
  12. try:
  13.     error
  14. except Exception,e:
  15.     logapp = Pubclilog()
  16.     logger,hdlr = logapp.iniLog()
  17.     logger.info(str(e))
  18.     hdlr.flush()
  19.     logger.removeHandler(hdlr)
  20.     return

  21. """
  22. class Pubclilog():
  23.     def __init__(self):
  24.         self.logfile = '/tmp/ava_post_commit.txt'
  25.     def initLog(self):
  26.         logger = logging.getLogger()
  27.         filehandler = logging.FileHandler(self.logfile)
  28.         streamhandler = logging.StreamHandler()
  29.         fmt = logging.Formatter('%(asctime)s, %(funcName)s, %(message)s')
  30.         logger.setLevel(logging.DEBUG)
  31.         logger.addHandler(filehandler)
  32.         logger.addHandler(streamhandler)
  33.         return [logger,filehandler]

  34. """
  35. 程序处理主体
  36. """
  37. class BaseSvn:
  38.     def __init__(self,log_switch,svnpath,svnrevision):
  39.         self.conn = MySQLdb.connect(db='avatar',host='10.xx.xxx.23', user='admin',passwd='123456',charset='utf8')
  40.         self.svnbin = "/usr/local/svn/bin"
  41.         self.log_switch=log_switch
  42.         self.svnpath = svnpath
  43.         self.svnrevision = svnrevision
  44.     
  45.     """
  46.     作用:调用svnlook获取作者与时间
  47.     2011-06-06 00:56:28 +0800 (Mon, 06 Jun 2011)
  48.     @return: ['作者','时间']
  49.     """
  50.     def _svninfo(self):
  51.         cmd = '%s/svnlook author %s -r %s'% (self.svnbin, self.svnpath, self.svnrevision)
  52.         return [os.popen(cmd, 'r').readlines()[0].replace('\n',''),strftime("%Y-%m-%d %H:%M:%S",localtime())]
  53.     
  54.     """
  55.     作用:解析changed变更记录获取变更列表依据不同的类型进行相应的DB操作
  56.     说明:对文件的解析是不是可以进一步重构一下代码呢?感觉这个写起来有点怪怪的!
  57.     """
  58.     def _svnpostdb(self):
  59.         logapp = Pubclilog()
  60.         logger,hdlr = logapp.initLog()
  61.         self.cursor = self.conn.cursor()
  62.         try:
  63.             author_time = self._svninfo()
  64.             cmd = '%s/svnlook changed %s -r %s'% (self.svnbin, self.svnpath, self.svnrevision)
  65.             content = os.popen(cmd).readlines()
  66.             for line in content:
  67.                 svntype = line[0:1]
  68.                 svncont = line.split(' ')[-1]
  69.                 if svncont.count('/') == 1:
  70.                     filename = svncont.split('/')[-1].strip()
  71.                     if filename == "":
  72.                         logger.info(line)
  73.                     else:
  74.                         firstle = filename[0]
  75.                         if svntype == 'A':
  76.                             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])
  77.                         elif svntype == 'D':
  78.                             sql = "delete from fileiso where filename = '%s' and type = '%s'" % (filename,firstle)
  79.                         elif svntype == 'U':
  80.                             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)
  81.                         self.cursor.execute(sql)
  82.                         self.conn.commit()
  83.                 else:
  84.                     pass
  85.             hdlr.flush()
  86.             logger.removeHandler(hdlr)
  87.             
  88.         except Exception,e:
  89.             logapp = Pubclilog()
  90.             logger,hdlr = logapp.initLog()
  91.             logger.info(str(e))
  92.             hdlr.flush()
  93.             logger.removeHandler(hdlr)
  94.             return

  95. """
  96. 应用启动
  97. @param svnpath: 代码库目录
  98. @param svnrevision:最新版本号
  99. @param logswitch: 日志开关
  100. @return :None
  101. """
  102. def startpost(svnpath,svnrevision,logswitch='on'):
  103.     app=BaseSvn(logswitch,svnpath,svnrevision)
  104.     app._svnpostdb()
  105.     app=None
  106.     return None


  107. if __name__ == '__main__':
  108.     """
  109.     python postcommit.py -p /opt/svn/data -r 10
  110.     print opts.log_switch
  111.     print opts.path
  112.     print opts.revision
  113.     if opts.verbose:
  114.         print "SVN COMMIT-POST V1.0 Beta."
  115.         sys.exit()
  116.     """
  117.     MSG_USAGE = "postcommit.py [-p][-r] -l [on|off] [-v]"
  118.     parser = OptionParser(MSG_USAGE)
  119.     parser.add_option("-l","--log",action="store",dest="log_switch",type="string",default="on")
  120.     parser.add_option("-p","--path", action="store", dest="path",help="SVN版本目录".decode('utf-8'))
  121.     parser.add_option("-r","--revision", action="store", dest="revision",help="SVN版本库号".decode('utf-8'))
  122.     parser.add_option("-v","--version", action="store_true", dest="verbose", help="versionlook".decode('utf-8'))
  123.     opts, args = parser.parse_args()
  124.     
  125.     if opts.verbose:
  126.         print "Post-commit V1.0 beta."
  127.         sys.exit(0)

  128.     
  129.     if opts.log_switch=="on":
  130.         log_switch="on"
  131.     else:
  132.         log_switch="off"
  133.     startpost(opts.path,opts.revision,log_switch)
  134.     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) |
给主人留下些什么吧!~~