Make 'mw help' work properly
[mw] / src / mw / clicommands.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 getpass
20 import mw.api
21 import mw.metadir
22 from optparse import OptionParser, OptionGroup
23 import os
24 import sys
25
26
27 class CommandBase(object):
28
29     def __init__(self, name, description, usage=None):
30         self.me = os.path.basename(sys.argv[0])
31         self.description = description
32         if usage is None:
33             usage = '%prog ' + name
34         self.parser = OptionParser(usage=usage, description=description)
35         self.name = name
36         self.metadir = mw.metadir.Metadir()
37         global_options = OptionGroup(self.parser, "Global Options")
38         global_options.add_option('-u', '--use-auth', action='store_true',
39                                   dest='use_auth', help='force authentication '
40                                   'even if not required')
41         self.parser.add_option_group(global_options)
42         self.shortcuts = []
43
44     def main(self):
45         (self.options, self.args) = self.parser.parse_args()
46         self.args = self.args[1:] # don't need the first thing
47         self._do_command()
48
49     def _do_command(self):
50         pass
51
52     def _login(self):
53         user = raw_input('Username: ')
54         passwd = getpass.getpass()
55         result = self.api.call({'action': 'login',
56                                 'lgname': user,
57                                 'lgpassword': passwd})
58         if result['login']['result'] != 'Success':
59             raise Exception('Login error: %s' % result['login']['result'])
60
61     def _die_if_no_init(self):
62         if self.metadir.config is None:
63             print '%s: not a mw repo' % self.me
64             sys.exit(1)
65
66     def _api_setup(self):
67         self.api_url = self.metadir.config.get('remote', 'api_url')
68         self.api = mw.api.API(self.api_url)
69
70
71 class InitCommand(CommandBase):
72
73     def __init__(self):
74         usage = '%prog init API_URL'
75         CommandBase.__init__(self, 'init', 'start a mw repo', usage)
76
77     def _do_command(self):
78         if len(self.args) < 1:
79             self.parser.error('must have URL to remote api.php')
80         elif len(self.args) > 1:
81             self.parser.error('too many arguments')
82         self.metadir.create(self.args[0])
83
84
85 class PullCommand(CommandBase):
86
87     def __init__(self):
88         usage = '%prog fetch [options] PAGENAME ...'
89         CommandBase.__init__(self, 'pull', 'add remote pages to repo', usage)
90
91     def _do_command(self):
92         self._die_if_no_init()
93         self._api_setup()
94         pages = []
95         pages += self.args
96         for these_pages in [pages[i:i + 25] for i in range(0, len(pages), 25)]:
97             data = {
98                     'action': 'query',
99                     'titles': '|'.join(these_pages),
100                     'prop': 'info|revisions',
101                     'rvprop': 'ids|flags|timestamp|user|comment|content',
102             }
103             response = self.api.call(data)['query']['pages']
104             for pageid in response.keys():
105                 pagename = response[pageid]['title']
106                 if 'missing' in response[pageid].keys():
107                     print '%s: %s: page does not exist, file not created' % \
108                             (self.me, pagename)
109                     continue
110                 revids = [x['revid'] for x in response[pageid]['revisions']]
111                 revids.sort()
112                 self.metadir.pagedict_add(pagename, pageid, revids[-1])
113                 self.metadir.pages_add_rv(int(pageid),
114                                           response[pageid]['revisions'][0])
115                 filename = mw.api.pagename_to_filename(pagename)
116                 fd = file(os.path.join(self.metadir.root, filename + '.wiki'),
117                           'w')
118                 fd.write(response[pageid]['revisions'][0]['*'].encode('utf-8'))
119
120
121 class StatusCommand(CommandBase):
122
123     def __init__(self):
124         CommandBase.__init__(self, 'status', 'check repo status')
125         self.shortcuts.append('st')
126
127     def _do_command(self):
128         self._die_if_no_init()
129         status = self.metadir.working_dir_status()
130         for file in status:
131             print '%s %s' % (status[file], file)
132
133
134 class DiffCommand(CommandBase):
135
136     def __init__(self):
137         CommandBase.__init__(self, 'diff', 'diff wiki to working directory')
138
139     def _do_command(self):
140         self._die_if_no_init()

Benjamin Mako Hill || Want to submit a patch?