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

Benjamin Mako Hill || Want to submit a patch?