fetch: Handle pages that do not exist
[mw] / src / mw / cli.py
1 ###
2 # mw - VCS-like nonsense for MediaWiki websites
3 # Copyright (C) 2009  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, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 ###
19
20 import inspect
21 import mw.clicommands
22 import os
23 import sys
24 from pprint import pprint
25
26 class CLI(object):
27     def __init__(self):
28         self.me = os.path.basename(sys.argv[0])
29         self.commands = {}
30         self.shortcuts = {}
31         for name in mw.clicommands.__dict__:
32             if name == 'CommandBase':
33                 continue
34             clazz = mw.clicommands.__dict__[name]
35             if isinstance(clazz, type) and \
36                issubclass(clazz, mw.clicommands.CommandBase):
37                 cmd = clazz()
38                 self.commands[cmd.name] = cmd
39                 self.shortcuts[cmd.name] = cmd.shortcuts
40         self.all_commands = {}
41         self.all_commands.update(self.commands)
42         for command in self.shortcuts:
43             for shortcut in self.shortcuts[command]:
44                 self.all_commands[shortcut] = self.commands[command]
45
46     def usage(self):
47         print 'usage: %s [subcommand]' % self.me
48         print
49         for name in self.commands:
50             cmd = self.commands[name]
51             if len(cmd.shortcuts) > 0:
52                 full = name + ' (' + ' '.join(cmd.shortcuts) + ')'
53             else:
54                 full = name
55             print("\t%-14s %-25s" % (full, cmd.description))
56         print
57         sys.exit(1)
58
59     def main(self):
60         # determine what the subcommand is
61         if len(sys.argv) > 1:
62             if sys.argv[1] in self.all_commands:
63                 the_command = sys.argv[1] # SWEET ACTION
64             elif sys.argv[1] in ['--help', '-h']:
65                 self.usage()
66             else:
67                 print '%s: invalid subcommand: %s' % (self.me, sys.argv[1])
68                 self.usage()
69         if len(sys.argv) == 1:
70             self.usage()
71         # woo let's go
72         self.all_commands[the_command].main()

Benjamin Mako Hill || Want to submit a patch?