More restylizing crap (PEP 8 compliant)
[mw] / src / mw / metadir.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 bzrlib.diff
20 import codecs
21 import ConfigParser
22 import json
23 import mw.api
24 import os
25 from StringIO import StringIO
26 import sys
27
28
29 class Metadir(object):
30
31     def __init__(self):
32         self.me = os.path.basename(sys.argv[0])
33         root = os.getcwd()
34         while True:
35             if '.mw' in os.listdir(root):
36                 self.root = root
37                 break
38             head = os.path.split(root)[0]
39             if head == root:
40                 self.root = os.getcwd()
41                 break
42             root = head
43         self.location = os.path.join(self.root, '.mw')
44         self.config_loc = os.path.join(self.location, 'config')
45         if os.path.isdir(self.location) and \
46            os.path.isfile(self.config_loc):
47             self.config = ConfigParser.RawConfigParser()
48             self.config.read(self.config_loc)
49         else:
50             self.config = None
51
52     def save_config(self):
53         with open(self.config_loc, 'wb') as config_file:
54             self.config.write(config_file)
55
56     def create(self, api_url):
57         # create the directory
58         if os.path.isdir(self.location):
59             print '%s: you are already in a mw repo' % self.me
60             sys.exit(1)
61         else:
62             os.mkdir(self.location, 0755)
63         # metadir versioning
64         fd = file(os.path.join(self.location, 'version'), 'w')
65         fd.write('1') # XXX THIS API VERSION NOT LOCKED IN YET
66         fd.close()
67         # create config
68         self.config = ConfigParser.RawConfigParser()
69         self.config.add_section('remote')
70         self.config.set('remote', 'api_url', api_url)
71         self.save_config()
72         # create cache/
73         os.mkdir(os.path.join(self.location, 'cache'))
74         # create cache/pagedict
75         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'w')
76         fd.write(json.dumps({}))
77         fd.close()
78         # create cache/pages/
79         os.mkdir(os.path.join(self.location, 'cache', 'pages'), 0755)
80
81     def clean_page(self, pagename):
82         filename = mw.api.pagename_to_filename(pagename) + '.wiki'
83         cur_content = codecs.open(filename, 'r', 'utf-8').read()
84         if len(cur_content) != 0 and cur_content[-1] == '\n':
85             cur_content = cur_content[:-1]
86         fd = file(filename, 'w')
87         fd.write(cur_content.encode('utf-8'))
88         fd.close()
89
90     def pagedict_add(self, pagename, pageid, currentrv):
91         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'r+')
92         pagedict = json.loads(fd.read())
93         pagedict[pagename] = {'id': int(pageid), 'currentrv': int(currentrv)}
94         fd.seek(0)
95         fd.write(json.dumps(pagedict))
96         fd.truncate()
97         fd.close()
98
99     def get_pageid_from_pagename(self, pagename):
100         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'r')
101         pagedict = json.loads(fd.read())
102         pagename = pagename.decode('utf-8')
103         if pagename in pagedict.keys():
104             return pagedict[pagename]
105         else:
106             return None
107
108     def pages_add_rv(self, pageid, rv):
109         pagefile = os.path.join(self.location, 'cache', 'pages', str(pageid))
110         fd = file(pagefile, 'w+')
111         pagedata_raw = fd.read()
112         if pagedata_raw == '':
113             pagedata = {}
114         else:
115             pagedata = json.loads(pagedata_raw)
116         rvid = int(rv['revid'])
117         pagedata[rvid] = {
118                 'user': rv['user'],
119                 'timestamp': rv['timestamp'],
120         }
121         if '*' in rv.keys():
122             pagedata[rvid]['content'] = rv['*']
123         fd.seek(0)
124         fd.write(json.dumps(pagedata))
125         fd.truncate()
126         fd.close()
127
128     def pages_get_rv_list(self, pageid):
129         pagefile = os.path.join(self.location, 'cache', 'pages',
130                                 str(pageid['id']))
131         fd = file(pagefile, 'r')
132         pagedata = json.loads(fd.read())
133         rvs = [int(x) for x in pagedata.keys()]
134         rvs.sort()
135         return rvs
136
137     def pages_get_rv(self, pageid, rvid):
138         pagefile = os.path.join(self.location, 'cache', 'pages',
139                                 str(pageid['id']))
140         fd = file(pagefile, 'r')
141         pagedata = json.loads(fd.read())
142         return pagedata[str(rvid)]
143
144     def working_dir_status(self, files=None):
145         status = {}
146         check = []
147         if files == None or files == []:
148             for root, dirs, files in os.walk(self.root):
149                 if root == self.root:
150                     dirs.remove('.mw')
151                 for name in files:
152                     check.append(os.path.join(root, name))
153         else:
154             for file in files:
155                 check.append(os.path.join(os.getcwd(), file))
156         check.sort()
157         for full in check:
158             name = os.path.split(full)[1]
159             if name[-5:] == '.wiki':
160                 pagename = mw.api.filename_to_pagename(name[:-5])
161                 pageid = self.get_pageid_from_pagename(pagename)
162                 if not pageid:
163                     status[os.path.relpath(full, self.root)] = '?'
164                 else:
165                     rvid = self.pages_get_rv_list(pageid)[-1]
166                     rv = self.pages_get_rv(pageid, rvid)
167                     cur_content = codecs.open(full, 'r', 'utf-8').read()
168                     if (len(cur_content) != 0) and (cur_content[-1] == '\n'):
169                         cur_content = cur_content[:-1]
170                     if cur_content != rv['content']:
171                         status[os.path.relpath(full, self.root)] = 'U'
172         return status
173
174     def diff_rv_to_working(self, pagename, oldrvid=0, newrvid=0):
175         # oldrvid=0 means latest fetched revision
176         # newrvid=0 means working copy
177         filename = mw.api.pagename_to_filename(pagename) + '.wiki'
178         filename = filename.decode('utf-8')
179         pageid = self.get_pageid_from_pagename(pagename)
180         if not pageid:
181             raise ValueError('page named %s has not been fetched' % pagename)
182         else:
183             if oldrvid == 0:
184                 oldrvid = self.pages_get_rv_list(pageid)[-1]
185             oldrv = self.pages_get_rv(pageid, oldrvid)
186             oldname = 'a/%s (revision %i)' % (filename, oldrvid)
187             old = [i + '\n' for i in \
188                    oldrv['content'].encode('utf-8').split('\n')]
189             if newrvid == 0:
190                 cur_content = codecs.open(filename, 'r', 'utf-8').read()
191                 cur_content = cur_content.encode('utf-8')
192                 if (len(cur_content) != 0) and (cur_content[-1] == '\n'):
193                     cur_content = cur_content[:-1]
194                 newname = 'b/%s (working copy)' % filename
195                 new = [i + '\n' for i in cur_content.split('\n')]
196             else:
197                 newrv = self.pages_get_rv(pageid, newrvid)
198                 newname = 'b/%s (revision %i)' % (filename, newrvid)
199                 new = [i + '\n' for i in newrv['content'].split('\n')]
200             diff_fd = StringIO()
201             bzrlib.diff.internal_diff(oldname, old, newname, new, diff_fd)
202             diff = diff_fd.getvalue()
203             if diff[-1] == '\n':
204                 diff = diff[:-1]
205             return diff

Benjamin Mako Hill || Want to submit a patch?