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

Benjamin Mako Hill || Want to submit a patch?