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

全部博文(264)

文章存档

2011年(264)

分类: Python/Ruby

2011-06-16 13:13:28

  1. #!/usr/bin/env python
  2. #-*-coding:utf-8-*-
  3. """
  4. initdate 实现将线上的SVN数据拉到DB中
  5. 1.遍历目录
  6. 2.解析作者、最后修改时间、最后修改人、修订次数、`filename` 、类型
  7. """
  8. import sys,os
  9. from subprocess import Popen, PIPE
  10. import MySQLdb,time
  11. import logging,locale
  12. from time import strftime, localtime
  13. from optparse import OptionParser
  14. locale_encoding = locale.getpreferredencoding()
  15. try:
  16.     from xml.etree import cElementTree as ET
  17. except ImportError:
  18.     try:
  19.         from xml.etree import ElementTree as ET
  20.     except ImportError:
  21.         try:
  22.             import cElementTree as ET
  23.         except ImportError:
  24.             from elementtree import ElementTree as ET
  25. svn_log_args = ['log', '--xml', '-v','--username','111','--password','111','--no-auth-cache']

  26. class Pubclilog():
  27.     def __init__(self):
  28.         self.logfile = '/tmp/initdate.txt'
  29.     def initLog(self):
  30.         logger = logging.getLogger()
  31.         filehandler = logging.FileHandler(self.logfile)
  32.         streamhandler = logging.StreamHandler()
  33.         fmt = logging.Formatter('%(asctime)s, %(funcName)s, %(message)s')
  34.         logger.setLevel(logging.DEBUG)
  35.         logger.addHandler(filehandler)
  36.         logger.addHandler(streamhandler)
  37.         return [logger,filehandler]

  38. if os.name == "nt":
  39.     def find_program(name):
  40.         # See MSDN for the REAL search order.
  41.         base, ext = os.path.splitext(name)
  42.         if ext:
  43.             exts = [ext]
  44.         else:
  45.             exts = ['.bat', '.exe']
  46.         for directory in os.environ['PATH'].split(os.pathsep):
  47.             for e in exts:
  48.                 fname = os.path.join(directory, base + e)
  49.                 if os.path.exists(fname):
  50.                     return fname
  51.         return None
  52. else:
  53.     def find_program(name):
  54.         """
  55.         Find the name of the program for Popen.
  56.         On Unix, popen isn't picky about having absolute paths.
  57.         """
  58.         return name

  59. def shell_quote(s):
  60.     if os.name == "nt":
  61.         q = '"'
  62.     else:
  63.         q = "'"
  64.     return q + s.replace('\\', '\\\\').replace("'", "'\"'\"'") + q

  65. """
  66. 程序处理主体
  67. """
  68. class BaseSvn:
  69.     def __init__(self,log_switch,svnpath):
  70.         self.conn = MySQLdb.connect(db='111',host='10.11.114.111', user='admin',passwd='123456',charset='utf8')
  71.         self.svnbin = "/usr/local/svn/bin"
  72.         self.log_switch=log_switch
  73.         self.svnpath = svnpath
  74.     
  75.     
  76.     def _svn_date_to_timestamp(self,svn_date):
  77.         date = svn_date.split('.', 2)[0]
  78.         time_tuple = time.strptime(date, "%Y-%m-%dT%H:%M:%S")
  79.         return strftime("%Y-%m-%d %H:%M:%S",(time_tuple))
  80.     
  81.     """返回作者、最后修改人、最后修改时间"""
  82.     def parse_svn_log_xml(self,xml_string):
  83.         d = {}
  84.         tree = ET.fromstring(xml_string)
  85.         tmp = tree.findall('logentry')
  86.         """第一个元素即为作者"""
  87.         author = tmp[0].find('author')
  88.         d['author'] = author is not None and author.text or None
  89.         lastml = tmp[len(tmp) - 1].find('author')
  90.         d['lastml'] = lastml is not None and lastml.text or None
  91.         lastmt = tmp[len(tmp) - 1].find('date')
  92.         d['lastmt'] = lastmt is not None and self._svn_date_to_timestamp(lastmt.text) or None
  93.         d['modifcount'] = len(tmp)
  94.         return d


  95.     """运行SVN命令"""
  96.     def run_svn(self,args, fail_if_stderr=False, encoding="utf-8"):
  97.         def _transform_arg(a):
  98.             if isinstance(a, unicode):
  99.                 a = a.encode(encoding or locale_encoding)
  100.             elif not isinstance(a, str):
  101.                 a = str(a)
  102.             return a
  103.         t_args = map(_transform_arg, args)
  104.         cmd = find_program("/usr/local/svn/bin/svn")
  105.         cmd_string = str(" ".join(map(shell_quote, [cmd] + t_args)))
  106.         print cmd_string
  107.         pipe = Popen([cmd] + t_args, executable=cmd, stdout=PIPE, stderr=PIPE)
  108.         out, err = pipe.communicate()
  109.         if pipe.returncode != 0 or (fail_if_stderr and err.strip()):
  110.             print("External program failed (return code %d): %s\n%s"
  111.                 % (pipe.returncode, cmd_string, err))
  112.             return "error"
  113.         return out
  114.     def run_svn_log(self,svn_url_or_wc, rev_start=0, rev_end=0, stop_on_copy=False):
  115.         if stop_on_copy:
  116.             args = ['--stop-on-copy']
  117.         else:
  118.             args = []
  119.         args += [svn_url_or_wc]
  120.         xml_string = self.run_svn(svn_log_args + args)
  121.         return self.parse_svn_log_xml(xml_string)
  122.     
  123.         """
  124.     作用:解析指定的工作拷贝目录的全部文件
  125.     """
  126.     def _svnpostdb(self):
  127.         logapp = Pubclilog()
  128.         logger,hdlr = logapp.initLog()
  129.         self.cursor = self.conn.cursor()
  130.         try:
  131.             logger.info("Starting+++++++++++++++++++++")
  132.             for root,dirs,files in os.walk(self.svnpath):
  133.                 for f in files:
  134.                     if root.find('.svn') > 0:pass
  135.                     else:
  136.                         absoulepath = root+"/"+f
  137.                         firstle = f[0]
  138.                         myresult = self.run_svn_log(absoulepath)
  139.                         sql = "insert into `11111` (filename,filetype,author,lastpl,lastmt,`modifynum` ) values('%s','%s','%s','%s','%s',%d)" % (f,firstle,myresult.get('author'),myresult.get('lastml'),myresult.get('lastmt'),int(myresult.get('modifcount')))
  140.                         self.cursor.execute(sql)
  141.             self.conn.commit()
  142.             logger.info("End+++++++++++++++++++++")
  143.             hdlr.flush()
  144.             logger.removeHandler(hdlr)
  145.         except Exception,e:
  146.             if self.log_switch=="on":
  147.                 logapp = Pubclilog()
  148.                 logger,hdlr = logapp.initLog()
  149.                 logger.info(str(e))
  150.                 hdlr.flush()
  151.                 logger.removeHandler(hdlr)
  152.                 return
  153.             
  154.     def __del__(self):
  155.         try:
  156.             self.cursor.close()
  157.             self.conn.close()
  158.         except Exception,e:
  159.             pass

  160. """
  161. 应用启动
  162. @param svnpath: 代码库目录
  163. @param svnrevision:最新版本号
  164. @param logswitch: 日志开关
  165. @return :None
  166. """
  167. def startpost(**args):
  168.     app=BaseSvn(args.get('logswitch'),args.get('svnpath'))
  169.     app._svnpostdb()
  170.     app=None
  171.     return None


  172. if __name__ == '__main__':
  173.     """
  174.     python postcommit.py -p /opt/svn/data -r 10
  175.     print opts.log_switch
  176.     print opts.path
  177.     print opts.revision
  178.     if opts.verbose:
  179.         print "SVN COMMIT-POST V1.0 Beta."
  180.         sys.exit()
  181.     """
  182.     MSG_USAGE = "initdate.py [-p] -l [on|off] [-v]"
  183.     parser = OptionParser(MSG_USAGE)
  184.     parser.add_option("-l","--log",action="store",dest="log_switch",type="string",default="on")
  185.     parser.add_option("-p","--path", action="store", dest="path",help="SVN本地目录".decode('utf-8'))
  186.     parser.add_option("-v","--version", action="store_true", dest="verbose", help="versionlook".decode('utf-8'))
  187.     opts, args = parser.parse_args()
  188.     
  189.     if opts.verbose:
  190.         print "initdate V1.0 beta."
  191.         sys.exit(0)
  192.     
  193.     if opts.log_switch=="on":
  194.         log_switch="on"
  195.     else:
  196.         log_switch="off"
  197.     startpost(svnpath=opts.path,logswitch=log_switch)
  198.     sys.exit(0)
阅读(1842) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~