Commits

Anonymous committed 1065b26

Now it uses hg api instead of actual hg commands.
Now it uses "hg st" instead of "hg update -c" to check uncommitted contents.

  • Participants
  • Parent commits 40dad62

Comments (0)

Files changed (2)

 - Group0:
     prjname: 4CX01P
     syncdirs: U:\ V:\ X:\ Y:\ Z:\
+- BTOA_For_Win7:
+    prjname: BTOA
+    syncdirs: 'U: V: X: Y: Z: P: S: D: A:'
 #!/usr/bin/env python
 
 """HgMon.py -- Monitoring directory change and sync project directories upon
-request. """
+request.
+
+If CHANGED.FLG is in the project directory, the script will try to commit it,
+then sync (hg push) to other directories of the same project. If any conflict
+files are found, it will create a branch named by date and time, commit the
+conflicts to the branch, then branch to default and update the previous push
+content.
+
+If LOCKED.FLG is in the project directory, the script will ignore the directory,
+no change will be pushed or synchronized to the project.
+
+Content format of CHANGED.FLG is "User Message String", e.g.,
+    Joel Changed something.
+
+The first word in the message is treated as user name, other strings are treated
+as commit messages.
+    
+"""
 
 import os
 import time
 import yaml
 import logging
+import logging.handlers
 from datetime import datetime
-import logging.handlers
 from subprocess import Popen, PIPE
-from functools import wraps
+# from functools import wraps
+from mercurial import ui, hg, commands
+
+def confirm_project(project_dir):
+    "Make sure project directory actually exists and create one if it doesn't."
+    if os.path.exists(project_dir):
+        if not os.path.isdir(project_dir): 
+            try: shutil.rmtree(project_dir)
+            except:
+                print "Unable to remove non-project directory %s" % project_dir
+            try:
+                os.makedirs(project_dir)
+            except:
+                print "Unable to create project directory %s" % project_dir
+    else:   # path not exist
+        try: os.makedirs(project_dir)
+        except:
+            print "Unable to create project directory %s" % project_dir
+
+def parse_flag(chflag):
+    "change flag file -> user, comment"
+    with open(chflag, 'r') as fh:
+        user, comment = tuple(
+            fh.readline().strip().split(' ', 1))
+    return user, comment
 
 def auto_branch_name():
     "generates branch name based on datetime.now()"
             grouplist.append(set(map(lambda x: os.path.join(x, pname), sdirs)))
     return grouplist
 
-def parse_flag(chflag):
-    "change flag file -> user, comment"
-    with open(chflag, 'r') as fh:
-        user, comment = tuple(
-            fh.readline().strip().split(' ', 1))
-    return user, comment
+def hg_init(dest):
+    return commands.init(ui.ui(), dest=dest)
+
+def hg_commit(u, dest, comment):
+    repo = hg.repository(u, dest)
+    return commands.commit(u, repo, message=comment, addremove=True)
+
+def hg_push(u, src, dest):
+    src_repo = hg.repository(u, src)
+    dest_repo = hg.repository(u, dest)
+    return commands.push(u, src_repo, dest, force=True)
+
+def hg_update_branch(u, dest, br_name=None):
+    repo = hg.repository(u, dest)
+    return commands.update(u, repo, node=br_name)
+
+def hg_update_c(u, dest):
+    repo = hg.repository(u, dest)
+    return commands.update(u, repo, check=True)
+
+def hg_status_is_modified(u, dest):
+    repo = hg.repository(u, dest)
+    return not commands.status(u, repo)
+    # Patched commands.py to get this working.
+    # Appended the two lines in module function commands.status()
+    ## if len(filter(lambda x: len(x)!=0, stat)) == 0: return True
+    ## else: return False
+    # I heard it's always good to return something in your function.
     
-def log_hg(func):
-    "Simple logging decorator."
-    @wraps(func)
-    def wrapper(*args, **kwargs):
-        logging.basicConfig(filename=os.path.join(os.getcwd(), 'hgmon.log'),
-                            level=logging.DEBUG,
-                            format="[%(asctime)s] - %(message)s",)
-        returncode, stdout, stderr = func(*args, **kwargs)
-        if returncode == 0:
-            logging.info("%s executed with %s" % (func.__name__, args))
-            for line in stdout:
-                logging.debug(line)
-        else:
-            logging.error("%s failed with args %s" %(func.__name__, args))
-            for line in stdout:
-                logging.error(line)
-            for line in stderr:
-                logging.error(line)
-    return wrapper
+def hg_branch(u, dest, br_name):
+    repo = hg.repository(u, dest)
+    return commands.branch(u, repo, label=br_name)
 
-@log_hg
-def hg_init(d, out=PIPE):
-    "Initiating hg repo"
-    hgcmd = Popen('hg init',
-                     stdout=out, stderr=out, shell=True,
-                     cwd=d,
-                     env={'PATH': os.environ['PATH']}
-                    )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
- 
-@log_hg
-def hg_commit(d, user, comment, out=PIPE):
-    "hg commit -A -u 'user' -m 'comment'"
-    hgcmd = Popen('hg commit -A -m "%s"' % comment,
-                   stdout=out, stderr=out, shell=True,
-                   cwd=d,
-                   env={'HGUSER': user,
-                        'PATH': os.environ['PATH']}
-                   )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
-
-@log_hg
-def hg_push(d, user, dest, out=PIPE):
-    "hg push -f"
-    hgcmd = Popen('hg push -f %s' % dest,
-                    stdout=out, stderr=out, shell=True,
-                    cwd=d,
-                    env={'HGUSER': user,
-                         'PATH': os.environ['PATH']}
-                   )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
-
-@log_hg
-def hg_update_branch(d, user, br_name=None, out=PIPE):
-    '''hg update'''
-    hgcmd = Popen('hg update %s' % (br_name if br_name else ''),
-                    stdout=out, stderr=out, shell=True,
-                    cwd=d,
-                    env={'HGUSER': user,
-                         'PATH': os.environ['PATH']}
-                   )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
-
-#@log_hg
-def hg_update_c(d, user, out=PIPE):
-    "hg update -c"
-    hgcmd = Popen('hg update -c',
-                 stdout=out, stderr=out, shell=True,
-                 cwd=d,
-                 env={'HGUSER': user,
-                      'PATH': os.environ['PATH']}
-                 )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
-
-@log_hg
-def hg_branch(d, user, branch_name, out=PIPE):
-    "hg update branch_name"
-    hgcmd = Popen('hg branch %s' % auto_branch_name(),
-                 stdout=out, stderr=out, shell=True,
-                 cwd=d,
-                 env={'HGUSER': user,
-                      'PATH': os.environ['PATH']}
-                 )
-    return hgcmd.wait(), hgcmd.stdout, hgcmd.stderr
-
-@log_hg
-def hg_autobranch(d, user, out=PIPE):
-    "branch to auto_branch, commit, branch back to default"
-    returncode, stdout, stderr = hg_update_c(d, user)
-    if returncode == -1:
-        hg_branch(d, user, auto_branch_name())
-        hg_commit(d, user, 'auto commit')
-        return hg_update_branch(d, user, br_name='default')
-    return returncode, stdout, stderr
+def hg_autobranch(u, dest):
+    if hg_status_is_modified(u, dest):
+        hg_branch(u, dest, auto_branch_name())
+        hg_commit(u, dest, 'auto commit')
+        return hg_update_branch(u, dest, br_name='default')
+    else:
+        hg_update_branch(u, dest, br_name='default')
 
 if __name__ == '__main__':
     configfile = 'config.yaml'
     flagfile = 'CHANGED.FLG'
+    lockfile = 'LOCK.FLG'
     while True:
         grouplist = loadconfig(configfile)
         for group in grouplist:
             for project_dir in group:
+                confirm_project(project_dir)
                 chflag = os.path.join(project_dir, flagfile)
                 hgflag = os.path.join(project_dir, '.hg')
-                if not os.path.isdir(project_dir): os.mkdir(project_dir)
+                lockfile = os.path.join(project_dir, lockfile)
+                if os.path.exists(lockfile): continue
                 if not os.path.exists(hgflag):
                     hg_init(project_dir)
-                    #modify_config(project_dir)
                 if os.path.exists(chflag):
                     time.sleep(0.2)
                     user, comment = parse_flag(chflag)
+                    os.environ['HGUSER'] = user
+                    u = ui.ui()
                     os.remove(chflag)
-                    hg_commit(project_dir, user, comment)
+                    hg_commit(u, project_dir, comment)
                     syncgroup = group.copy()
                     syncgroup.remove(project_dir)
                     for syncdir in syncgroup:
-                        hg_push(project_dir, user, syncdir)
-                        hg_autobranch(syncdir, user)
+                        if os.path.exists(lockfile):
+                            continue
+                        hg_push(u, project_dir, syncdir)
+                        hg_autobranch(u, syncdir)
         time.sleep(10)
-