Mercurial > python-hglib
comparison hglib/util.py @ 3:d7903b923217
util: add cmdbuilder, a helper function to generate the command to run
author | Idan Kamara <idankk86@gmail.com> |
---|---|
date | Tue, 09 Aug 2011 00:39:25 +0300 |
parents | 79f88b4db15f |
children | 3ac38d500d68 |
comparison
equal
deleted
inserted
replaced
2:5fa34c3ac9a0 | 3:d7903b923217 |
---|---|
2 | 2 |
3 def grouper(n, iterable): | 3 def grouper(n, iterable): |
4 ''' list(grouper(2, range(4))) -> [(0, 1), (2, 3)] ''' | 4 ''' list(grouper(2, range(4))) -> [(0, 1), (2, 3)] ''' |
5 args = [iter(iterable)] * n | 5 args = [iter(iterable)] * n |
6 return itertools.izip(*args) | 6 return itertools.izip(*args) |
7 | |
8 def cmdbuilder(name, *args, **kwargs): | |
9 """ | |
10 A helper for building the command arguments | |
11 | |
12 args are the positional arguments | |
13 | |
14 kwargs are the options | |
15 keys that are single lettered are prepended with '-', others with '--', | |
16 underscores are replaced with dashes | |
17 | |
18 keys with False boolean values are ignored, lists add the key multiple times | |
19 | |
20 None arguments are skipped | |
21 | |
22 >>> cmdbuilder('cmd', a=True, b=False, c=None) | |
23 ['cmd', '-a'] | |
24 >>> cmdbuilder('cmd', long=True) | |
25 ['cmd', '--long'] | |
26 >>> cmdbuilder('cmd', str='s') | |
27 ['cmd', '--str', 's'] | |
28 >>> cmdbuilder('cmd', d_ash=True) | |
29 ['cmd', '--d-ash'] | |
30 >>> cmdbuilder('cmd', _=True) | |
31 ['cmd', '-'] | |
32 >>> cmdbuilder('cmd', list=[1, 2]) | |
33 ['cmd', '--list', '1', '--list', '2'] | |
34 >>> cmdbuilder('cmd', None) | |
35 ['cmd'] | |
36 """ | |
37 cmd = [name] | |
38 for arg, val in kwargs.items(): | |
39 if val is None: | |
40 continue | |
41 | |
42 arg = arg.replace('_', '-') | |
43 if arg != '-': | |
44 arg = '-' + arg if len(arg) == 1 else '--' + arg | |
45 if isinstance(val, bool): | |
46 if val: | |
47 cmd.append(arg) | |
48 elif isinstance(val, list): | |
49 for v in val: | |
50 cmd.append(arg) | |
51 cmd.append(str(v)) | |
52 else: | |
53 cmd.append(arg) | |
54 cmd.append(str(val)) | |
55 | |
56 for a in args: | |
57 if a is not None: | |
58 cmd.append(a) | |
59 | |
60 return cmd |