Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 79 lines (60 sloc) 2.14 kb
757d134 @lirazsiri implemented cli wrapper for regular commands
lirazsiri authored
1 import os
2 import re
3 import sys
4 import imp
5
6 class _Commands(dict):
7 @staticmethod
8 def _list_commands(paths):
9 commands = set()
10 for path in paths:
11 for file in os.listdir(path):
12 m = re.match(r'^cmd_(.*)\.py[co]?$', file)
13 if not m:
14 continue
15 command = m.group(1)
16 commands.add(command)
17
18 return commands
19
20 @staticmethod
21 def _get_internals_module(name, path):
22 modname = "cmd_" + name
23 args = imp.find_module(modname, path)
24 return imp.load_module(modname, *args)
25
26 def __init__(self, path):
27 for command in self._list_commands(path):
28 self[command] = self._get_internals_module(command, path)
29
30 class CliWrapper:
31 DESCRIPTION = ""
32 PATH = None
33 COMMANDS_USAGE_ORDER = []
34
35 @classmethod
36 def _usage(cls, commands, e=None):
37 if e:
38 print >> sys.stderr, "error: " + str(e)
39
40 print >> sys.stderr, "Syntax: %s <command> [arguments]" % sys.argv[0]
41 print >> sys.stderr, cls.DESCRIPTION.strip()
42
43 print >> sys.stderr, "\nCommands: \n"
44
45 command_names = commands.keys()
46 command_names.sort()
47
48 maxlen = max([ len(name) for name in command_names ]) + 2
49 tpl = " %%-%ds %%s" % (maxlen)
50
51 def shortdesc(command):
52 return commands[command].__doc__.strip().split('\n')[0]
53
54 for command in cls.COMMANDS_USAGE_ORDER:
55 if command == '':
56 print >> sys.stderr
57 else:
58 print >> sys.stderr, tpl % (command, shortdesc(command))
59
60 for command in set(commands.keys()) - set(cls.COMMANDS_USAGE_ORDER):
61 print >> sys.stderr, tpl % (command, shortdesc(command))
62
63 sys.exit(1)
64
65 @classmethod
66 def main(cls):
67 commands = _Commands(cls.PATH)
68
69 args = sys.argv[1:]
70 if not args:
71 cls._usage(commands)
72
73 command = args[0]
74 if command not in commands:
75 cls._usage(commands, "no such command")
76
77 sys.argv = args
78 commands[command].main()
Something went wrong with that request. Please try again.