33c4177d0ceac2ec134fbc46dc669879e6abf636
[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         else:
35             usage = '%%prog %s %s' % (name, usage)
36         self.parser = OptionParser(usage=usage, description=description)
37         self.name = name
38         self.metadir = mw.metadir.Metadir()
39         #global_options = OptionGroup(self.parser, "Global Options")
40         #global_options.add_option('-u', '--use-auth', action='store_true',
41         #                          dest='use_auth', help='force authentication '
42         #                          'even if not required')
43         #self.parser.add_option_group(global_options)
44         self.shortcuts = []
45
46     def main(self):
47         (self.options, self.args) = self.parser.parse_args()
48         self.args = self.args[1:] # don't need the first thing
49         self._do_command()
50
51     def _do_command(self):
52         pass
53
54     def _login(self):
55         user = raw_input('Username: ')
56         passwd = getpass.getpass()
57         result = self.api.call({'action': 'login',
58                                 'lgname': user,
59                                 'lgpassword': passwd})
60         if result['login']['result'] == 'Success':
61             # cookies are saved to a file
62             print 'Login successful! (yay)'
63         else:
64             print 'Login failed: %s' % result['login']['result']
65
66     def _die_if_no_init(self):
67         if self.metadir.config is None:
68             print '%s: not a mw repo' % self.me
69             sys.exit(1)
70
71     def _api_setup(self):
72         self.api_url = self.metadir.config.get('remote', 'api_url')
73         self.api = mw.api.API(self.api_url, self.metadir)
74
75
76 class InitCommand(CommandBase):
77
78     def __init__(self):
79         usage = 'API_URL'
80         CommandBase.__init__(self, 'init', 'start a mw repo', usage)
81
82     def _do_command(self):
83         if len(self.args) < 1:
84             self.parser.error('must have URL to remote api.php')
85         elif len(self.args) > 1:
86             self.parser.error('too many arguments')
87         self.metadir.create(self.args[0])
88
89
90 class LoginCommand(CommandBase):
91
92     def __init__(self):
93         CommandBase.__init__(self, 'login', 'authenticate with wiki')
94
95     def _do_command(self):
96         self._die_if_no_init()
97         self._api_setup()
98         self._login()
99
100
101 class LogoutCommand(CommandBase):
102
103     def __init__(self):
104         CommandBase.__init__(self, 'logout', 'forget authentication')
105
106     def _do_command(self):
107         self._die_if_no_init()
108         try:
109             os.unlink(os.path.join(self.metadir.location, 'cookies'))
110         except OSError:
111             pass
112
113
114 class PullCommand(CommandBase):
115
116     def __init__(self):
117         usage = '[options] PAGENAME ...'
118         CommandBase.__init__(self, 'pull', 'add remote pages to repo', usage)
119
120     def _do_command(self):
121         self._die_if_no_init()
122         self._api_setup()
123         pages = []
124         pages += self.args
125         for these_pages in [pages[i:i + 25] for i in range(0, len(pages), 25)]:
126             data = {
127                     'action': 'query',
128                     'titles': '|'.join(these_pages),
129                     'prop': 'info|revisions',
130                     'rvprop': 'ids|flags|timestamp|user|comment|content',
131             }
132             response = self.api.call(data)['query']['pages']
133             for pageid in response.keys():
134                 pagename = response[pageid]['title']
135                 if 'missing' in response[pageid].keys():
136                     print '%s: %s: page does not exist, file not created' % \
137                             (self.me, pagename)
138                     continue
139                 revids = [x['revid'] for x in response[pageid]['revisions']]
140                 revids.sort()
141                 self.metadir.pagedict_add(pagename, pageid, revids[-1])
142                 self.metadir.pages_add_rv(int(pageid),
143                                           response[pageid]['revisions'][0])
144                 filename = mw.api.pagename_to_filename(pagename)
145                 fd = file(os.path.join(self.metadir.root, filename + '.wiki'),
146                           'w')
147                 fd.write(response[pageid]['revisions'][0]['*'].encode('utf-8'))
148
149
150 class StatusCommand(CommandBase):
151
152     def __init__(self):
153         CommandBase.__init__(self, 'status', 'check repo status')
154         self.shortcuts.append('st')
155
156     def _do_command(self):
157         self._die_if_no_init()
158         status = self.metadir.working_dir_status()
159         for file in status:
160             print '%s %s' % (status[file], file)
161
162
163 class DiffCommand(CommandBase):
164
165     def __init__(self):
166         CommandBase.__init__(self, 'diff', 'diff wiki to working directory')
167
168     def _do_command(self):
169         self._die_if_no_init()
170         status = self.metadir.working_dir_status()
171         for file in status:
172             if status[file] == 'U':
173                 print self.metadir.diff_rv_to_working(
174                     mw.api.filename_to_pagename(file[:-5])
175                 ),
176
177
178 class CommitCommand(CommandBase):
179
180     def __init__(self):
181         CommandBase.__init__(self, 'commit', 'commit changes to wiki')
182         self.shortcuts.append('ci')
183
184     def _do_command(self):
185         self._die_if_no_init()
186         self._api_setup()

Benjamin Mako Hill || Want to submit a patch?