Alphabetize command listing on --help
[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 create(self, api_url):
53         # create the directory
54         if os.path.isdir(self.location):
55             print '%s: you are already in a mw repo' % self.me
56             sys.exit(1)
57         else:
58             os.mkdir(self.location, 0755)
59         # metadir versioning
60         fd = file(os.path.join(self.location, 'version'), 'w')
61         fd.write('1') # XXX THIS API VERSION NOT LOCKED IN YET
62         fd.close()
63         # create config
64         self.config = ConfigParser.RawConfigParser()
65         self.config.add_section('remote')
66         self.config.set('remote', 'api_url', api_url)
67         with open(self.config_loc, 'wb') as config_file:
68             self.config.write(config_file)
69         # create cache/
70         os.mkdir(os.path.join(self.location, 'cache'))
71         # create cache/pagedict
72         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'w')
73         fd.write(json.dumps({}))
74         fd.close()
75         # create cache/pages/
76         os.mkdir(os.path.join(self.location, 'cache', 'pages'), 0755)
77
78     def pagedict_add(self, pagename, pageid, currentrv):
79         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'r+')
80         pagedict = json.loads(fd.read())
81         pagedict[pagename] = {'id': int(pageid), 'currentrv': int(currentrv)}
82         fd.seek(0)
83         fd.write(json.dumps(pagedict))
84         fd.truncate()
85         fd.close()
86
87     def get_pageid_from_pagename(self, pagename):
88         fd = file(os.path.join(self.location, 'cache', 'pagedict'), 'r')
89         pagedict = json.loads(fd.read())
90         if pagename in pagedict.keys():
91             return pagedict[pagename]
92         else:
93             return None
94
95     def pages_add_rv(self, pageid, rv):
96         pagefile = os.path.join(self.location, 'cache', 'pages', str(pageid))
97         fd = file(pagefile, 'w+')
98         pagedata_raw = fd.read()
99         if pagedata_raw == '':
100             pagedata = {}
101         else:
102             pagedata = json.loads(pagedata_raw)
103         rvid = int(rv['revid'])
104         pagedata[rvid] = {
105                 'user': rv['user'], 'timestamp': rv['timestamp']
106         }
107         if '*' in rv.keys():
108             pagedata[rvid]['content'] = rv['*']
109         fd.seek(0)
110         fd.write(json.dumps(pagedata))
111         fd.truncate()
112         fd.close()
113
114     def pages_get_rv_list(self, pageid):
115         pagefile = os.path.join(self.location, 'cache', 'pages',
116                                 str(pageid['id']))
117         fd = file(pagefile, 'r')
118         pagedata = json.loads(fd.read())
119         rvs = [int(x) for x in pagedata.keys()]
120         rvs.sort()
121         return rvs
122
123     def pages_get_rv(self, pageid, rvid):
124         pagefile = os.path.join(self.location, 'cache', 'pages',
125                                 str(pageid['id']))
126         fd = file(pagefile, 'r')
127         pagedata = json.loads(fd.read())
128         return pagedata[str(rvid)]
129
130     def working_dir_status(self):
131         status = {}
132         check = []
133         for root, dirs, files in os.walk(self.root):
134             if root == self.root:
135                 dirs.remove('.mw')
136             for name in files:
137                 check.append(os.path.join(root, name))
138         check.sort()
139         for full in check:
140             name = os.path.split(full)[1]
141             if name[-5:] == '.wiki':
142                 pagename = mw.api.filename_to_pagename(name[:-5])
143                 pageid = self.get_pageid_from_pagename(pagename)
144                 if not pageid:
145                     status[os.path.relpath(full, self.root)] = '?'
146                 else:
147                     rvid = self.pages_get_rv_list(pageid)[-1]
148                     rv = self.pages_get_rv(pageid, rvid)
149                     cur_content = codecs.open(full, 'r', 'utf-8').read()
150                     if cur_content[-1] == '\n':
151                         cur_content = cur_content[:-1]
152                     if cur_content != rv['content']:
153                         status[os.path.relpath(full, self.root)] = 'U'
154         return status
155
156     def diff_rv_to_working(self, pagename, oldrvid=0, newrvid=0):
157         # oldrvid=0 means latest fetched revision
158         # newrvid=0 means working copy
159         filename = mw.api.pagename_to_filename(pagename) + '.wiki'
160         pageid = self.get_pageid_from_pagename(pagename)
161         if not pageid:
162             raise ValueError('page named %s has not been fetched' % pagename)
163         else:
164             if oldrvid == 0:
165                 oldrvid = self.pages_get_rv_list(pageid)[-1]
166             oldrv = self.pages_get_rv(pageid, oldrvid)
167             oldname = 'a/%s (revision %i)' % (filename, oldrvid)
168             old = [i+'\n' for i in oldrv['content'].split('\n')]
169             if newrvid == 0:
170                 cur_content = codecs.open(filename, 'r', 'utf-8').read()
171                 if cur_content[-1] == '\n':
172                     cur_content = cur_content[:-1]
173                 newname = 'b/%s (working copy)' % filename
174                 new = [i+'\n' for i in cur_content.split('\n')]
175             else:
176                 newrv = self.pages_get_rv(pageid, newrvid)
177                 newname = 'b/%s (revision %i)' % (filename, newrvid)
178                 new = [i+'\n' for i in newrv['content'].split('\n')]
179             diff_fd = StringIO()
180             bzrlib.diff.internal_diff(oldname, old, newname, new, diff_fd)
181             diff_fd.seek(0)
182             diff = diff_fd.read()
183             if diff[-1] == '\n':
184                 diff = diff[:-1]
185             return diff

Benjamin Mako Hill || Want to submit a patch?