mercurial/fancyopts.py
changeset 0 9117c6561b0b
child 164 2e87f04880ab
equal deleted inserted replaced
-1:000000000000 0:9117c6561b0b
       
     1 import sys, os, getopt
       
     2 
       
     3 def fancyopts(args, options, state, syntax=''):
       
     4     long=[]
       
     5     short=''
       
     6     map={}
       
     7     dt={}
       
     8 
       
     9     def help(state, opt, arg, options=options, syntax=syntax):
       
    10         print "Usage: ", syntax
       
    11 
       
    12         for s, l, d, c in options:
       
    13             opt=' '
       
    14             if s: opt = opt + '-' + s + ' '
       
    15             if l: opt = opt + '--' + l + ' '
       
    16             if d: opt = opt + '(' + str(d) + ')'
       
    17             print opt
       
    18             if c: print '   %s' % c
       
    19         sys.exit(0)
       
    20 
       
    21     if len(args) == 0:
       
    22         help(state, None, args)
       
    23 
       
    24     options=[('h', 'help', help, 'Show usage info')] + options
       
    25     
       
    26     for s, l, d, c in options:
       
    27         map['-'+s] = map['--'+l]=l
       
    28         state[l] = d
       
    29         dt[l] = type(d)
       
    30         if not d is None and not type(d) is type(help): s, l=s+':', l+'='      
       
    31         if s: short = short + s
       
    32         if l: long.append(l)
       
    33 
       
    34     if os.environ.has_key("HG_OPTS"):
       
    35         args = os.environ["HG_OPTS"].split() + args
       
    36 
       
    37     try:
       
    38         opts, args = getopt.getopt(args, short, long)
       
    39     except getopt.GetoptError:
       
    40         help(state, None, args)
       
    41         sys.exit(-1)
       
    42 
       
    43     for opt, arg in opts:
       
    44         if dt[map[opt]] is type(help): state[map[opt]](state,map[opt],arg)
       
    45         elif dt[map[opt]] is type(1): state[map[opt]] = int(arg)
       
    46         elif dt[map[opt]] is type(''): state[map[opt]] = arg
       
    47         elif dt[map[opt]] is type([]): state[map[opt]].append(arg)
       
    48         elif dt[map[opt]] is type(None): state[map[opt]] = 1
       
    49         
       
    50     return args
       
    51