PEP 8 compliance
[mw] / src / mw / cli.py
1 ###
2 # mw - VCS-like nonsense for MediaWiki websites
3 # Copyright (C) 2010  Ian Weller <ian@ianweller.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with this program.  If not, see <http://www.gnu.org/licenses/>.
17 ###
18
19 import mw.clicommands
20 import os
21 import sys
22
23
24 class CLI(object):
25
26     def __init__(self):
27         self.me = os.path.basename(sys.argv[0])
28         self.commands = {}
29         self.shortcuts = {}
30         for name in mw.clicommands.__dict__:
31             if name == 'CommandBase':
32                 continue
33             clazz = mw.clicommands.__dict__[name]
34             if isinstance(clazz, type) and \
35                issubclass(clazz, mw.clicommands.CommandBase):
36                 cmd = clazz()
37                 self.commands[cmd.name] = cmd
38                 self.shortcuts[cmd.name] = cmd.shortcuts
39         self.all_commands = {}
40         self.all_commands.update(self.commands)
41         for command in self.shortcuts:
42             for shortcut in self.shortcuts[command]:
43                 self.all_commands[shortcut] = self.commands[command]
44
45     def usage(self):
46         print 'usage: %s [subcommand]' % self.me
47         print
48         commands = self.commands.keys()
49         commands.sort()
50         for name in commands:
51             cmd = self.commands[name]
52             if len(cmd.shortcuts) > 0:
53                 full = name + ' (' + ' '.join(cmd.shortcuts) + ')'
54             else:
55                 full = name
56             print("\t%-14s %-25s" % (full, cmd.description))
57         print
58         sys.exit(1)
59
60     def main(self):
61         # determine what the subcommand is
62         if len(sys.argv) > 1:
63             if sys.argv[1] in self.all_commands:
64                 the_command = sys.argv[1]  # SWEET ACTION
65             elif sys.argv[1] in ['--help', '-h', 'help']:
66                 self.usage()
67             else:
68                 print '%s: invalid subcommand: %s' % (self.me, sys.argv[1])
69                 self.usage()
70         if len(sys.argv) == 1:
71             self.usage()
72         # woo let's go
73         self.all_commands[the_command].main()

Benjamin Mako Hill || Want to submit a patch?