Commits

Wang Dingwei  committed 76a3478

Now all functions use hg.commands

  • Participants
  • Parent commits 2aadd40

Comments (0)

Files changed (6)

 import logging.handlers
 from configparser import ConfigParser
 
+from mercurial import ui
+
+
 VERSION = '0.7'
 CONFIG_FILE = 'settings.ini'
 LOGNAME = 'hgsync.log'
 
 logger = get_logger()
 config = Config(CONFIG_FILE)
-
+ui = ui.ui()
 import os
 import logging, logging.config
 from datetime import datetime
-from functools import wraps
-from mercurial import cmdutil, ui, commands, patch, hg
+from mercurial import commands, hg
 
 from config import logger
 
+
 def auto_branch_name(dest):
     "generates branch name based on datetime.now()"
     for piece in dest.split(os.path.sep):
         if piece != '': break
+
     now = datetime.now()
-    d, t = now.date(), now.time()
-    dstr = '/'.join([str(d.year)[2:],
-                    str(d.month).zfill(2),
-                    str(d.day).zfill(2)])
-    tstr = ':'.join([str(t.hour).zfill(2),
-                    str(t.minute).zfill(2),
-                    str(t.second).zfill(2)])
-    return '-'.join([dstr, tstr, piece])
+    return now.strftime('%Y-%m-%d_%H:%M:%S')
 
-def init(dest):
-    "hg init dest"
-    return commands.init(ui.ui(), dest=dest)
 
-def diff(dest, u=ui.ui()):
-    "prints diff log"
-    repo = hg.repository(u, dest)
-    m = cmdutil.match(repo)
-    node1, node2 = cmdutil.revpair(repo, 0)
-    return patch.diff(repo, node1, node2, match=m)
+def init(ui, dest):
+    "Initiate hg repo in dest."
+    commands.init(ui, dest=dest)
 
-def commit(dest, comment, u=ui.ui()):
+
+def diff(ui, dest):
+    "Returns diff output for destpath"
+    repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    commands.diff(ui, repo)
+    return ui.popbuffer()
+
+
+def commit(ui, dest, user, comment):
     "hg commit"
     logger.info("commiting for %s" % dest)
     logger.info("Message: %s" % comment)
-    repo = hg.repository(u, dest)
-    return commands.commit(u, repo, message=comment, addremove=True)
+    repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    commands.commit(ui, repo, user=user, message=comment, addremove=True)
+    ui.flush()
+    return
 
-def hg_log(dest, outfile, pats='', opts={'rev':None}):
-    repo = hg.repository(ui.ui(), dest)
-    matchfn = cmdutil.match(repo, pats, opts)    
-    def prep(ctx, fns):
-        rev = ctx.rev()
-        parents = [p for p in repo.changelog.parentrevs(rev)
-                   if p != nullrev]
-        if opts.get('no_merges') and len(parents) == 2:
-            return
-        if opts.get('only_merges') and len(parents) != 2:
-            return
-        if opts.get('only_branch') and ctx.branch() not in opts['only_branch']:
-            return
-        if df and not df(ctx.date()[0]):
-            return
-        if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
-            return
-        if opts.get('keyword'):
-            for k in [kw.lower() for kw in opts['keyword']]:
-                if (k in ctx.user().lower() or
-                    k in ctx.description().lower() or
-                    k in " ".join(ctx.files()).lower()):
-                    break
-            else:
-                return
-    printer = cmdutil.changeset_printer(ui.ui(), repo, False, None, False)
-    with open(os.path.join(dest, outfile), 'w') as f:
-        for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
-            f.write(printer.show(repo.changectx(ctx)))
 
-def push(src, dest, u=ui.ui()):
+def log(ui, dest):
+    repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    commands.log(ui, repo)
+    return ui.popbuffer()
+
+
+def push(ui, src, dest):
     "hg push -f"
-    src_repo = hg.repository(u, src)
-    dest_repo = hg.repository(u, dest)
-    return src_repo.push(dest_repo, force=True)
+    src_repo = hg.repository(ui, src)
+    dest_repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    src_repo.push(dest_repo, force=True)
+    ui.flush()
+    return
 
-def update_branch(dest, br_name=None, u=ui.ui()):
-    "hg update br_name"
-    repo = hg.repository(u, dest)
-    return commands.update(u, repo, node=br_name)
 
-def branch(dest, br_name, u=ui.ui()):
+def pull(ui, src, dest):
+    "hg pull from src to dest"
+    src_repo = hg.repository(ui, src)
+    dest_repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    src_repo.pull(dest_repo)
+    ui.flush()
+
+
+def update(ui, dest, br_name=None, rev=None):
+    """update to specific branch or rev.
+    Note: Uncommitted changes are discarded!"""
+    repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    commands.update(ui, repo, node=br_name, rev=rev, clean=True)
+    ui.flush()
+    return
+
+
+def branch(ui, dest, br_name):
     "hg branch br_name"
-    repo = hg.repository(u, dest)
-    return commands.branch(u, repo, label=br_name, force=True)
+    repo = hg.repository(ui, dest)
+    ui.pushbuffer()
+    commands.branch(ui, repo, label=br_name, force=True)
+    ui.flush()
+    return
 
-def autobranch(dest, u=ui.ui()):
+
+def autobranch(ui, dest):
     "Create new branch if repo is changed"
-    if repo_is_changed(dest, u):
-        br_name = auto_branch_name(dest)
-        logger.info("branch to %s, name %s" % (dest, br_name))
-        branch(dest, br_name, u=u)
-        commit(dest, 'auto commit', u)
-        update_branch(dest, br_name='default', u=u)
-        return True
-    else:
-        update_branch(dest, br_name='default', u=u)
-        return False
+    br_name = auto_branch_name(dest)
+    logger.info("branch to %s, name %s" % (dest, br_name))
+    branch(ui, dest, br_name)
+    commit(ui, dest, 'auto commit')
+    update_branch(ui, dest, br_name='default')
 
-def repo_is_changed(dest, u=ui.ui()):
+
+def repo_is_changed(ui, dest):
     "'hg status' stripped down. Return true if the repo is changed."
-    repo = hg.repository(u, dest)
-    node1, node2 = cmdutil.revpair(repo, 0)
-    m = cmdutil.match(repo)
-    stat = repo.status(node1, node2, m, False, False, True)
+    repo = hg.repository(ui, dest)
+    stat = repo.status()
     return len(filter(lambda x: len(x)!=0, stat)) != 0
 
-def autosync(project_dir, syncgroup, u=ui.ui()):
+
+def autosync(ui, project_dir, syncgroup, user, message):
     "Recursively synchronizes changes of all project dirs"
+    ui.pushbuffer()
+    commit(ui, project_dir, user, message)
     for syncdir in syncgroup:
         logger.info("Synchronizing %s" % syncdir)
-        push(project_dir, syncdir, u)
-        branched = autobranch(syncdir, u)
-        if branched:
+        if repo_is_changed(ui, syncdir):
+            autobranch(ui, syncdir)
             logger.info("Auto branch created on %s" % syncdir)
             logger.info("Synchronizing back..")
-            autosync(syncdir, syncgroup, u)
+            autosync(ui, syncdir, syncgroup, message)
             break
+        else:
+            push(ui, project_dir, syncdir)
+            update(ui, syncdir, br_name='default')
+
+    ui.flush()
+    return
+
+def rollback(ui, project_dir, rev):
+    update(ui, dest, rev=rev)
+    return
+
+def hg_log(ui, project_dir, logname):
+    with open(os.path.join(project_dir, logname), 'w') as f:
+        f.write(log(ui, project_dir))
 import os
 import time
-from config import logger, config
-from hgsync import autosync, 
+from config import logger, config, ui
+from hgsync import autosync
 
 def with_doing(func):
     "Decorator to add 'doing' flags for all actions."
         flag = os.path.join(path, 'SYNC'!)
         def parse_flag(flag):
             with open(flag) as f:
-                user, comment = tuple(f.readline().strip().split(' ', 1))
-            return user, comment
+                user, msg = tuple(f.readline().strip().split(' ', 1))
+            return user, msg
         user, comment = parse_flag(flag)
+
         os.remove(flag)
         dest_dirs = self.dirs.remove(path)
-        autosync(path, dest_dirs)
+        autosync(ui, path, dest_dirs, user, msg)
     
     @with_doing
     def rollback(self, path):
         def parse_flag(flag):
             with open(flag) as f:
                 user, rev = tuple(f.readline().strip().split(' ', 1))
-            return user, rev          
+            return user, int(rev)          
         user, rev = parse_flag(flag)
         os.remove(flag)
-        rollback(path, user, rev)
+        rollback(ui, path, user, rev=rev)
     
     @with_doing
     def getlog(self, path):
         flag = os.path.join(path, 'STAT!')
         rev = parse_flag(flag)
         os.remove(flag)
-        hg_log(path, 'CHANGES.LOG')
+        hg_log(ui, path, 'CHANGES.LOG')
 
 
 def main():

File logconfig.ini

-[loggers]
-keys=root,SyncLog
-
-[handlers]
-keys=consoleHandler,fileHandler
-
-[formatters]
-keys=fmt1
-
-[logger_root]
-level=DEBUG
-handlers=consoleHandler
-
-[logger_SyncLog]
-level=DEBUG
-handlers=consoleHandler,fileHandler
-qualname=SyncLog
-propagate=0
-
-[handler_consoleHandler]
-class=StreamHandler
-level=DEBUG
-formatter=fmt1
-args=(sys.stdout,)
-
-[handler_fileHandler]
-class=FileHandler
-level=DEBUG
-formatter=fmt1
-args=('hgmon.log', 'a')
-
-[formatter_fmt1]
-format=[%(asctime)s] %(message)s
-datefmt=
-
-[fake]

File settings.ini

+[DEFAULT]
+all=\\192.168.200.1
+    \\192.168.200.2
+    \\192.168.200.3
+    \\192.168.200.4
+    \\192.168.200.16
+    \\192.168.200.17
+    \\192.168.200.18
+    \\192.168.200.20
+    \\192.168.200.21
+    \\192.168.200.22
+    \\192.168.200.23
+
+[IMAGE\IMAGE\LAYER]
+location=%(all)s

File templates/hgignore.template

 *.err
 *.bak
 SYNC!
+BACK!
+STAT!
 LOCKED!
 DOING
+ERROR
 
 syntax: regexp
 # File extension longer than 3 letters.
-.*\.[A-Z0-9]{4,}
+# .*\.[A-Z0-9]{4,}