git-artemis
changeset 74 b6093d6385a5
parent 73 b78234a1bf04
equal deleted inserted replaced
72:285b24804d97 74:b6093d6385a5
       
     1 #!/usr/bin/env python
       
     2 # coding: utf-8
       
     3 
       
     4 # use artemis with git
       
     5 #  John Kozak <jgak@thameslighter.net> 2016
       
     6 
       
     7 import artemis
       
     8 
       
     9 import os
       
    10 import sys
       
    11 import tempfile
       
    12 import subprocess
       
    13 from argparse import ArgumentParser
       
    14 from collections import namedtuple
       
    15 
       
    16 # munge arguments and pass on to artemis
       
    17 def iadd(args,repo,ui):
       
    18     id = args.id
       
    19     d  = dict(args.__dict__)
       
    20     del d['id']
       
    21     artemis.iadd(ui,repo,id,**d)
       
    22 
       
    23 def ilist(args,repo,ui):
       
    24     artemis.ilist(ui,repo,**args.__dict__)
       
    25 
       
    26 def ishow(args,repo,ui):
       
    27     id = args.id
       
    28     d  = dict(args.__dict__)
       
    29     del d['id']
       
    30     artemis.ishow(ui,repo,id,**d)
       
    31 
       
    32 
       
    33 class Repo(object):
       
    34     """Implement a subset of hgext's Repo object in git."""
       
    35     def __init__(self):
       
    36         git_sp    = subprocess.Popen(['git','rev-parse','--show-toplevel'],stdout=subprocess.PIPE)
       
    37         self.root = git_sp.communicate()[0].rstrip()
       
    38 
       
    39 
       
    40 class UI(object):
       
    41     """Implement a subset of hgext's UI object in git."""
       
    42     def __init__(self,config):
       
    43         self._config  = config
       
    44         self.verbose  = True
       
    45     def config(self,group,name,**opts):
       
    46         if group=='artemis':
       
    47             return self._config.get(name,opts['default'])
       
    48         else:
       
    49             raise NotFound(group,name)
       
    50     def configitems(self,_):
       
    51         return self._config.items()
       
    52     def write(self,s):
       
    53         print s,
       
    54     def warn(self,s):
       
    55         print s,
       
    56     def status(self,s):
       
    57         print s,
       
    58     def username(self):
       
    59         sp = subprocess.Popen(['git','config','user.name'],stdout=subprocess.PIPE)
       
    60         return sp.communicate()[0].rstrip()
       
    61     def edit(self,text,user):
       
    62         fd,fn = tempfile.mkstemp(suffix='.txt')
       
    63         try:
       
    64             os.write(fd,text)
       
    65             os.close(fd)
       
    66             rc = subprocess.call("%s '%s'"%(os.environ['EDITOR'],fn),shell=True)
       
    67             if rc!=0:
       
    68                 raise Exception('edit failed')
       
    69             else:
       
    70                 return file(fn).read()
       
    71         finally:
       
    72             os.unlink(fn)
       
    73 
       
    74 
       
    75 # Monkeypatch the hg commands object to implement git equivalent functionality.
       
    76 # It would be nice to disable the commands we don't re-implement.
       
    77 def git_add(ui,repo,path):
       
    78     rc = subprocess.call("git add '%s'"%(path,),shell=True)
       
    79     if rc!=0:
       
    80         raise Exception("git add failed")
       
    81 def git_commit(ui,repo,path):
       
    82     rc = subprocess.call("git commit -m 'commit from artemis' -- '%s'"%(path,),shell=True)
       
    83     if rc!=0:
       
    84         raise Exception("git commit failed")
       
    85 #artemis.commands.clear()  # how to do this?
       
    86 artemis.commands.add    = git_add
       
    87 artemis.commands.commit = git_commit
       
    88 
       
    89 
       
    90 def _build_argparse_from_cmdtable():
       
    91     """Build an ArgumentParser equivalent to artemis' cmdtable.
       
    92        This is a bit hacky."""
       
    93     parser     = ArgumentParser()
       
    94     subparsers = parser.add_subparsers(help="simple issue tracker")
       
    95     for k,v in artemis.cmdtable.items():
       
    96         assert k[0]=='i'
       
    97         n  = k[1:]
       
    98         sp = subparsers.add_parser(n)
       
    99         for f in v[1]:
       
   100             args   = ([] if f[0]=='' else ['-'+f[0]])+['--'+f[1]]
       
   101             kwargs = {'help':f[3]}
       
   102             if f[2] in [False,None]:
       
   103                 kwargs['action']  = 'store_true'
       
   104             elif f[2]==[]:
       
   105                 kwargs['action']  = 'append'
       
   106                 kwargs['default'] = []
       
   107             else:
       
   108                 kwargs['action']  = 'store'
       
   109             if isinstance(f[2],basestring):
       
   110                 kwargs['default'] = ''
       
   111             sp.add_argument(*args,**kwargs)
       
   112         sc = v[2].split(' ')
       
   113         assert sc[0]=='hg'
       
   114         assert sc[1]==k
       
   115         assert sc[2]=='[OPTIONS]'
       
   116         for a in sc[3:]:
       
   117             kwargs = {'action':'store'}
       
   118             n      = a
       
   119             if a[0]=='[':
       
   120                 assert a[-1]==']'
       
   121                 n               = a[1:-1]
       
   122                 kwargs['nargs'] = '?'
       
   123                 if n=='COMMENT':
       
   124                     kwargs['default'] = 0
       
   125             sp.add_argument(n.lower(),**kwargs)
       
   126         sp.set_defaults(func=globals()[k])
       
   127     return parser
       
   128 
       
   129 
       
   130 if __name__=='__main__':
       
   131     repo   = Repo()
       
   132     ui     = UI({'issues':artemis.default_issues_dir})
       
   133     parser = _build_argparse_from_cmdtable()
       
   134     args   = parser.parse_args()
       
   135     args.func(args,repo,ui)