[PATCH 2 of 4 hglib] util: add cmdbuilder, a helper function to generate the command to run
Idan Kamara
idankk86 at gmail.com
Fri Aug 5 10:42:39 CDT 2011
# HG changeset patch
# User Idan Kamara <idankk86 at gmail.com>
# Date 1312558484 -10800
# Node ID 9bfd61e1ab1c76b1407b1264cb509e4827e5da58
# Parent 4d6f25a3a6483a1ba2359a24613217ac8f14bdbe
util: add cmdbuilder, a helper function to generate the command to run
diff -r 4d6f25a3a648 -r 9bfd61e1ab1c hglib/util.py
--- a/hglib/util.py Sat Jul 23 22:55:39 2011 +0300
+++ b/hglib/util.py Fri Aug 05 18:34:44 2011 +0300
@@ -2,3 +2,57 @@
''' list(grouper(2, range(4))) -> [[0, 1], [2, 3]] '''
for i in xrange(0, len(iterable), n):
yield iterable[i:i+n]
+
+def cmdbuilder(name, *args, **kwargs):
+ """
+ A helper for building the command arguments
+
+ args are the positional arguments
+
+ kwargs are the options
+ keys that are single lettered are prepended with '-', others with '--',
+ underscores are replaced with dashes
+
+ keys with False boolean values are ignored, lists add the key multiple times
+
+ None arguments are skipped
+
+ >>> cmdbuilder('cmd', a=True, b=False, c=None)
+ ['cmd', '-a']
+ >>> cmdbuilder('cmd', long=True)
+ ['cmd', '--long']
+ >>> cmdbuilder('cmd', str='s')
+ ['cmd', '--str', 's']
+ >>> cmdbuilder('cmd', d_ash=True)
+ ['cmd', '--d-ash']
+ >>> cmdbuilder('cmd', _=True)
+ ['cmd', '-']
+ >>> cmdbuilder('cmd', list=[1, 2])
+ ['cmd', '--list', '1', '--list', '2']
+ >>> cmdbuilder('cmd', None)
+ ['cmd']
+ """
+ cmd = [name]
+ for arg, val in kwargs.items():
+ if val is None:
+ continue
+
+ arg = arg.replace('_', '-')
+ if arg != '-':
+ arg = '-' + arg if len(arg) == 1 else '--' + arg
+ if isinstance(val, bool):
+ if val:
+ cmd.append(arg)
+ elif isinstance(val, list):
+ for v in val:
+ cmd.append(arg)
+ cmd.append(str(v))
+ else:
+ cmd.append(arg)
+ cmd.append(str(val))
+
+ for a in args:
+ if a is not None:
+ cmd.append(a)
+
+ return cmd
More information about the Mercurial-devel
mailing list