##// END OF EJS Templates
hgweb: fix unbundle....
Alexis S. L. Carvalho -
r2558:11203020 default
parent child Browse files
Show More
@@ -1,943 +1,944 b''
1 # hgweb/hgweb_mod.py - Web interface for a repository.
1 # hgweb/hgweb_mod.py - Web interface for a repository.
2 #
2 #
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 # Copyright 2005 Matt Mackall <mpm@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms
6 # This software may be used and distributed according to the terms
7 # of the GNU General Public License, incorporated herein by reference.
7 # of the GNU General Public License, incorporated herein by reference.
8
8
9 import os
9 import os
10 import os.path
10 import os.path
11 import mimetypes
11 import mimetypes
12 from mercurial.demandload import demandload
12 from mercurial.demandload import demandload
13 demandload(globals(), "re zlib ConfigParser mimetools cStringIO sys tempfile")
13 demandload(globals(), "re zlib ConfigParser mimetools cStringIO sys tempfile")
14 demandload(globals(), "mercurial:mdiff,ui,hg,util,archival,templater")
14 demandload(globals(), "mercurial:mdiff,ui,hg,util,archival,templater")
15 demandload(globals(), "mercurial.hgweb.common:get_mtime,staticfile")
15 demandload(globals(), "mercurial.hgweb.common:get_mtime,staticfile")
16 from mercurial.node import *
16 from mercurial.node import *
17 from mercurial.i18n import gettext as _
17 from mercurial.i18n import gettext as _
18
18
19 def _up(p):
19 def _up(p):
20 if p[0] != "/":
20 if p[0] != "/":
21 p = "/" + p
21 p = "/" + p
22 if p[-1] == "/":
22 if p[-1] == "/":
23 p = p[:-1]
23 p = p[:-1]
24 up = os.path.dirname(p)
24 up = os.path.dirname(p)
25 if up == "/":
25 if up == "/":
26 return "/"
26 return "/"
27 return up + "/"
27 return up + "/"
28
28
29 class hgweb(object):
29 class hgweb(object):
30 def __init__(self, repo, name=None):
30 def __init__(self, repo, name=None):
31 if type(repo) == type(""):
31 if type(repo) == type(""):
32 self.repo = hg.repository(ui.ui(), repo)
32 self.repo = hg.repository(ui.ui(), repo)
33 else:
33 else:
34 self.repo = repo
34 self.repo = repo
35
35
36 self.mtime = -1
36 self.mtime = -1
37 self.reponame = name
37 self.reponame = name
38 self.archives = 'zip', 'gz', 'bz2'
38 self.archives = 'zip', 'gz', 'bz2'
39 self.templatepath = self.repo.ui.config("web", "templates",
39 self.templatepath = self.repo.ui.config("web", "templates",
40 templater.templatepath())
40 templater.templatepath())
41
41
42 def refresh(self):
42 def refresh(self):
43 mtime = get_mtime(self.repo.root)
43 mtime = get_mtime(self.repo.root)
44 if mtime != self.mtime:
44 if mtime != self.mtime:
45 self.mtime = mtime
45 self.mtime = mtime
46 self.repo = hg.repository(self.repo.ui, self.repo.root)
46 self.repo = hg.repository(self.repo.ui, self.repo.root)
47 self.maxchanges = int(self.repo.ui.config("web", "maxchanges", 10))
47 self.maxchanges = int(self.repo.ui.config("web", "maxchanges", 10))
48 self.maxfiles = int(self.repo.ui.config("web", "maxfiles", 10))
48 self.maxfiles = int(self.repo.ui.config("web", "maxfiles", 10))
49 self.allowpull = self.repo.ui.configbool("web", "allowpull", True)
49 self.allowpull = self.repo.ui.configbool("web", "allowpull", True)
50
50
51 def archivelist(self, nodeid):
51 def archivelist(self, nodeid):
52 allowed = self.repo.ui.configlist("web", "allow_archive")
52 allowed = self.repo.ui.configlist("web", "allow_archive")
53 for i in self.archives:
53 for i in self.archives:
54 if i in allowed or self.repo.ui.configbool("web", "allow" + i):
54 if i in allowed or self.repo.ui.configbool("web", "allow" + i):
55 yield {"type" : i, "node" : nodeid, "url": ""}
55 yield {"type" : i, "node" : nodeid, "url": ""}
56
56
57 def listfiles(self, files, mf):
57 def listfiles(self, files, mf):
58 for f in files[:self.maxfiles]:
58 for f in files[:self.maxfiles]:
59 yield self.t("filenodelink", node=hex(mf[f]), file=f)
59 yield self.t("filenodelink", node=hex(mf[f]), file=f)
60 if len(files) > self.maxfiles:
60 if len(files) > self.maxfiles:
61 yield self.t("fileellipses")
61 yield self.t("fileellipses")
62
62
63 def listfilediffs(self, files, changeset):
63 def listfilediffs(self, files, changeset):
64 for f in files[:self.maxfiles]:
64 for f in files[:self.maxfiles]:
65 yield self.t("filedifflink", node=hex(changeset), file=f)
65 yield self.t("filedifflink", node=hex(changeset), file=f)
66 if len(files) > self.maxfiles:
66 if len(files) > self.maxfiles:
67 yield self.t("fileellipses")
67 yield self.t("fileellipses")
68
68
69 def siblings(self, siblings=[], rev=None, hiderev=None, **args):
69 def siblings(self, siblings=[], rev=None, hiderev=None, **args):
70 if not rev:
70 if not rev:
71 rev = lambda x: ""
71 rev = lambda x: ""
72 siblings = [s for s in siblings if s != nullid]
72 siblings = [s for s in siblings if s != nullid]
73 if len(siblings) == 1 and rev(siblings[0]) == hiderev:
73 if len(siblings) == 1 and rev(siblings[0]) == hiderev:
74 return
74 return
75 for s in siblings:
75 for s in siblings:
76 yield dict(node=hex(s), rev=rev(s), **args)
76 yield dict(node=hex(s), rev=rev(s), **args)
77
77
78 def renamelink(self, fl, node):
78 def renamelink(self, fl, node):
79 r = fl.renamed(node)
79 r = fl.renamed(node)
80 if r:
80 if r:
81 return [dict(file=r[0], node=hex(r[1]))]
81 return [dict(file=r[0], node=hex(r[1]))]
82 return []
82 return []
83
83
84 def showtag(self, t1, node=nullid, **args):
84 def showtag(self, t1, node=nullid, **args):
85 for t in self.repo.nodetags(node):
85 for t in self.repo.nodetags(node):
86 yield self.t(t1, tag=t, **args)
86 yield self.t(t1, tag=t, **args)
87
87
88 def diff(self, node1, node2, files):
88 def diff(self, node1, node2, files):
89 def filterfiles(filters, files):
89 def filterfiles(filters, files):
90 l = [x for x in files if x in filters]
90 l = [x for x in files if x in filters]
91
91
92 for t in filters:
92 for t in filters:
93 if t and t[-1] != os.sep:
93 if t and t[-1] != os.sep:
94 t += os.sep
94 t += os.sep
95 l += [x for x in files if x.startswith(t)]
95 l += [x for x in files if x.startswith(t)]
96 return l
96 return l
97
97
98 parity = [0]
98 parity = [0]
99 def diffblock(diff, f, fn):
99 def diffblock(diff, f, fn):
100 yield self.t("diffblock",
100 yield self.t("diffblock",
101 lines=prettyprintlines(diff),
101 lines=prettyprintlines(diff),
102 parity=parity[0],
102 parity=parity[0],
103 file=f,
103 file=f,
104 filenode=hex(fn or nullid))
104 filenode=hex(fn or nullid))
105 parity[0] = 1 - parity[0]
105 parity[0] = 1 - parity[0]
106
106
107 def prettyprintlines(diff):
107 def prettyprintlines(diff):
108 for l in diff.splitlines(1):
108 for l in diff.splitlines(1):
109 if l.startswith('+'):
109 if l.startswith('+'):
110 yield self.t("difflineplus", line=l)
110 yield self.t("difflineplus", line=l)
111 elif l.startswith('-'):
111 elif l.startswith('-'):
112 yield self.t("difflineminus", line=l)
112 yield self.t("difflineminus", line=l)
113 elif l.startswith('@'):
113 elif l.startswith('@'):
114 yield self.t("difflineat", line=l)
114 yield self.t("difflineat", line=l)
115 else:
115 else:
116 yield self.t("diffline", line=l)
116 yield self.t("diffline", line=l)
117
117
118 r = self.repo
118 r = self.repo
119 cl = r.changelog
119 cl = r.changelog
120 mf = r.manifest
120 mf = r.manifest
121 change1 = cl.read(node1)
121 change1 = cl.read(node1)
122 change2 = cl.read(node2)
122 change2 = cl.read(node2)
123 mmap1 = mf.read(change1[0])
123 mmap1 = mf.read(change1[0])
124 mmap2 = mf.read(change2[0])
124 mmap2 = mf.read(change2[0])
125 date1 = util.datestr(change1[2])
125 date1 = util.datestr(change1[2])
126 date2 = util.datestr(change2[2])
126 date2 = util.datestr(change2[2])
127
127
128 modified, added, removed, deleted, unknown = r.changes(node1, node2)
128 modified, added, removed, deleted, unknown = r.changes(node1, node2)
129 if files:
129 if files:
130 modified, added, removed = map(lambda x: filterfiles(files, x),
130 modified, added, removed = map(lambda x: filterfiles(files, x),
131 (modified, added, removed))
131 (modified, added, removed))
132
132
133 diffopts = self.repo.ui.diffopts()
133 diffopts = self.repo.ui.diffopts()
134 showfunc = diffopts['showfunc']
134 showfunc = diffopts['showfunc']
135 ignorews = diffopts['ignorews']
135 ignorews = diffopts['ignorews']
136 for f in modified:
136 for f in modified:
137 to = r.file(f).read(mmap1[f])
137 to = r.file(f).read(mmap1[f])
138 tn = r.file(f).read(mmap2[f])
138 tn = r.file(f).read(mmap2[f])
139 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
139 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
140 showfunc=showfunc, ignorews=ignorews), f, tn)
140 showfunc=showfunc, ignorews=ignorews), f, tn)
141 for f in added:
141 for f in added:
142 to = None
142 to = None
143 tn = r.file(f).read(mmap2[f])
143 tn = r.file(f).read(mmap2[f])
144 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
144 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
145 showfunc=showfunc, ignorews=ignorews), f, tn)
145 showfunc=showfunc, ignorews=ignorews), f, tn)
146 for f in removed:
146 for f in removed:
147 to = r.file(f).read(mmap1[f])
147 to = r.file(f).read(mmap1[f])
148 tn = None
148 tn = None
149 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
149 yield diffblock(mdiff.unidiff(to, date1, tn, date2, f,
150 showfunc=showfunc, ignorews=ignorews), f, tn)
150 showfunc=showfunc, ignorews=ignorews), f, tn)
151
151
152 def changelog(self, pos):
152 def changelog(self, pos):
153 def changenav(**map):
153 def changenav(**map):
154 def seq(factor, maxchanges=None):
154 def seq(factor, maxchanges=None):
155 if maxchanges:
155 if maxchanges:
156 yield maxchanges
156 yield maxchanges
157 if maxchanges >= 20 and maxchanges <= 40:
157 if maxchanges >= 20 and maxchanges <= 40:
158 yield 50
158 yield 50
159 else:
159 else:
160 yield 1 * factor
160 yield 1 * factor
161 yield 3 * factor
161 yield 3 * factor
162 for f in seq(factor * 10):
162 for f in seq(factor * 10):
163 yield f
163 yield f
164
164
165 l = []
165 l = []
166 last = 0
166 last = 0
167 for f in seq(1, self.maxchanges):
167 for f in seq(1, self.maxchanges):
168 if f < self.maxchanges or f <= last:
168 if f < self.maxchanges or f <= last:
169 continue
169 continue
170 if f > count:
170 if f > count:
171 break
171 break
172 last = f
172 last = f
173 r = "%d" % f
173 r = "%d" % f
174 if pos + f < count:
174 if pos + f < count:
175 l.append(("+" + r, pos + f))
175 l.append(("+" + r, pos + f))
176 if pos - f >= 0:
176 if pos - f >= 0:
177 l.insert(0, ("-" + r, pos - f))
177 l.insert(0, ("-" + r, pos - f))
178
178
179 yield {"rev": 0, "label": "(0)"}
179 yield {"rev": 0, "label": "(0)"}
180
180
181 for label, rev in l:
181 for label, rev in l:
182 yield {"label": label, "rev": rev}
182 yield {"label": label, "rev": rev}
183
183
184 yield {"label": "tip", "rev": "tip"}
184 yield {"label": "tip", "rev": "tip"}
185
185
186 def changelist(**map):
186 def changelist(**map):
187 parity = (start - end) & 1
187 parity = (start - end) & 1
188 cl = self.repo.changelog
188 cl = self.repo.changelog
189 l = [] # build a list in forward order for efficiency
189 l = [] # build a list in forward order for efficiency
190 for i in range(start, end):
190 for i in range(start, end):
191 n = cl.node(i)
191 n = cl.node(i)
192 changes = cl.read(n)
192 changes = cl.read(n)
193 hn = hex(n)
193 hn = hex(n)
194
194
195 l.insert(0, {"parity": parity,
195 l.insert(0, {"parity": parity,
196 "author": changes[1],
196 "author": changes[1],
197 "parent": self.siblings(cl.parents(n), cl.rev,
197 "parent": self.siblings(cl.parents(n), cl.rev,
198 cl.rev(n) - 1),
198 cl.rev(n) - 1),
199 "child": self.siblings(cl.children(n), cl.rev,
199 "child": self.siblings(cl.children(n), cl.rev,
200 cl.rev(n) + 1),
200 cl.rev(n) + 1),
201 "changelogtag": self.showtag("changelogtag",n),
201 "changelogtag": self.showtag("changelogtag",n),
202 "manifest": hex(changes[0]),
202 "manifest": hex(changes[0]),
203 "desc": changes[4],
203 "desc": changes[4],
204 "date": changes[2],
204 "date": changes[2],
205 "files": self.listfilediffs(changes[3], n),
205 "files": self.listfilediffs(changes[3], n),
206 "rev": i,
206 "rev": i,
207 "node": hn})
207 "node": hn})
208 parity = 1 - parity
208 parity = 1 - parity
209
209
210 for e in l:
210 for e in l:
211 yield e
211 yield e
212
212
213 cl = self.repo.changelog
213 cl = self.repo.changelog
214 mf = cl.read(cl.tip())[0]
214 mf = cl.read(cl.tip())[0]
215 count = cl.count()
215 count = cl.count()
216 start = max(0, pos - self.maxchanges + 1)
216 start = max(0, pos - self.maxchanges + 1)
217 end = min(count, start + self.maxchanges)
217 end = min(count, start + self.maxchanges)
218 pos = end - 1
218 pos = end - 1
219
219
220 yield self.t('changelog',
220 yield self.t('changelog',
221 changenav=changenav,
221 changenav=changenav,
222 manifest=hex(mf),
222 manifest=hex(mf),
223 rev=pos, changesets=count, entries=changelist,
223 rev=pos, changesets=count, entries=changelist,
224 archives=self.archivelist("tip"))
224 archives=self.archivelist("tip"))
225
225
226 def search(self, query):
226 def search(self, query):
227
227
228 def changelist(**map):
228 def changelist(**map):
229 cl = self.repo.changelog
229 cl = self.repo.changelog
230 count = 0
230 count = 0
231 qw = query.lower().split()
231 qw = query.lower().split()
232
232
233 def revgen():
233 def revgen():
234 for i in range(cl.count() - 1, 0, -100):
234 for i in range(cl.count() - 1, 0, -100):
235 l = []
235 l = []
236 for j in range(max(0, i - 100), i):
236 for j in range(max(0, i - 100), i):
237 n = cl.node(j)
237 n = cl.node(j)
238 changes = cl.read(n)
238 changes = cl.read(n)
239 l.append((n, j, changes))
239 l.append((n, j, changes))
240 l.reverse()
240 l.reverse()
241 for e in l:
241 for e in l:
242 yield e
242 yield e
243
243
244 for n, i, changes in revgen():
244 for n, i, changes in revgen():
245 miss = 0
245 miss = 0
246 for q in qw:
246 for q in qw:
247 if not (q in changes[1].lower() or
247 if not (q in changes[1].lower() or
248 q in changes[4].lower() or
248 q in changes[4].lower() or
249 q in " ".join(changes[3][:20]).lower()):
249 q in " ".join(changes[3][:20]).lower()):
250 miss = 1
250 miss = 1
251 break
251 break
252 if miss:
252 if miss:
253 continue
253 continue
254
254
255 count += 1
255 count += 1
256 hn = hex(n)
256 hn = hex(n)
257
257
258 yield self.t('searchentry',
258 yield self.t('searchentry',
259 parity=count & 1,
259 parity=count & 1,
260 author=changes[1],
260 author=changes[1],
261 parent=self.siblings(cl.parents(n), cl.rev),
261 parent=self.siblings(cl.parents(n), cl.rev),
262 child=self.siblings(cl.children(n), cl.rev),
262 child=self.siblings(cl.children(n), cl.rev),
263 changelogtag=self.showtag("changelogtag",n),
263 changelogtag=self.showtag("changelogtag",n),
264 manifest=hex(changes[0]),
264 manifest=hex(changes[0]),
265 desc=changes[4],
265 desc=changes[4],
266 date=changes[2],
266 date=changes[2],
267 files=self.listfilediffs(changes[3], n),
267 files=self.listfilediffs(changes[3], n),
268 rev=i,
268 rev=i,
269 node=hn)
269 node=hn)
270
270
271 if count >= self.maxchanges:
271 if count >= self.maxchanges:
272 break
272 break
273
273
274 cl = self.repo.changelog
274 cl = self.repo.changelog
275 mf = cl.read(cl.tip())[0]
275 mf = cl.read(cl.tip())[0]
276
276
277 yield self.t('search',
277 yield self.t('search',
278 query=query,
278 query=query,
279 manifest=hex(mf),
279 manifest=hex(mf),
280 entries=changelist)
280 entries=changelist)
281
281
282 def changeset(self, nodeid):
282 def changeset(self, nodeid):
283 cl = self.repo.changelog
283 cl = self.repo.changelog
284 n = self.repo.lookup(nodeid)
284 n = self.repo.lookup(nodeid)
285 nodeid = hex(n)
285 nodeid = hex(n)
286 changes = cl.read(n)
286 changes = cl.read(n)
287 p1 = cl.parents(n)[0]
287 p1 = cl.parents(n)[0]
288
288
289 files = []
289 files = []
290 mf = self.repo.manifest.read(changes[0])
290 mf = self.repo.manifest.read(changes[0])
291 for f in changes[3]:
291 for f in changes[3]:
292 files.append(self.t("filenodelink",
292 files.append(self.t("filenodelink",
293 filenode=hex(mf.get(f, nullid)), file=f))
293 filenode=hex(mf.get(f, nullid)), file=f))
294
294
295 def diff(**map):
295 def diff(**map):
296 yield self.diff(p1, n, None)
296 yield self.diff(p1, n, None)
297
297
298 yield self.t('changeset',
298 yield self.t('changeset',
299 diff=diff,
299 diff=diff,
300 rev=cl.rev(n),
300 rev=cl.rev(n),
301 node=nodeid,
301 node=nodeid,
302 parent=self.siblings(cl.parents(n), cl.rev),
302 parent=self.siblings(cl.parents(n), cl.rev),
303 child=self.siblings(cl.children(n), cl.rev),
303 child=self.siblings(cl.children(n), cl.rev),
304 changesettag=self.showtag("changesettag",n),
304 changesettag=self.showtag("changesettag",n),
305 manifest=hex(changes[0]),
305 manifest=hex(changes[0]),
306 author=changes[1],
306 author=changes[1],
307 desc=changes[4],
307 desc=changes[4],
308 date=changes[2],
308 date=changes[2],
309 files=files,
309 files=files,
310 archives=self.archivelist(nodeid))
310 archives=self.archivelist(nodeid))
311
311
312 def filelog(self, f, filenode):
312 def filelog(self, f, filenode):
313 cl = self.repo.changelog
313 cl = self.repo.changelog
314 fl = self.repo.file(f)
314 fl = self.repo.file(f)
315 filenode = hex(fl.lookup(filenode))
315 filenode = hex(fl.lookup(filenode))
316 count = fl.count()
316 count = fl.count()
317
317
318 def entries(**map):
318 def entries(**map):
319 l = []
319 l = []
320 parity = (count - 1) & 1
320 parity = (count - 1) & 1
321
321
322 for i in range(count):
322 for i in range(count):
323 n = fl.node(i)
323 n = fl.node(i)
324 lr = fl.linkrev(n)
324 lr = fl.linkrev(n)
325 cn = cl.node(lr)
325 cn = cl.node(lr)
326 cs = cl.read(cl.node(lr))
326 cs = cl.read(cl.node(lr))
327
327
328 l.insert(0, {"parity": parity,
328 l.insert(0, {"parity": parity,
329 "filenode": hex(n),
329 "filenode": hex(n),
330 "filerev": i,
330 "filerev": i,
331 "file": f,
331 "file": f,
332 "node": hex(cn),
332 "node": hex(cn),
333 "author": cs[1],
333 "author": cs[1],
334 "date": cs[2],
334 "date": cs[2],
335 "rename": self.renamelink(fl, n),
335 "rename": self.renamelink(fl, n),
336 "parent": self.siblings(fl.parents(n),
336 "parent": self.siblings(fl.parents(n),
337 fl.rev, file=f),
337 fl.rev, file=f),
338 "child": self.siblings(fl.children(n),
338 "child": self.siblings(fl.children(n),
339 fl.rev, file=f),
339 fl.rev, file=f),
340 "desc": cs[4]})
340 "desc": cs[4]})
341 parity = 1 - parity
341 parity = 1 - parity
342
342
343 for e in l:
343 for e in l:
344 yield e
344 yield e
345
345
346 yield self.t("filelog", file=f, filenode=filenode, entries=entries)
346 yield self.t("filelog", file=f, filenode=filenode, entries=entries)
347
347
348 def filerevision(self, f, node):
348 def filerevision(self, f, node):
349 fl = self.repo.file(f)
349 fl = self.repo.file(f)
350 n = fl.lookup(node)
350 n = fl.lookup(node)
351 node = hex(n)
351 node = hex(n)
352 text = fl.read(n)
352 text = fl.read(n)
353 changerev = fl.linkrev(n)
353 changerev = fl.linkrev(n)
354 cl = self.repo.changelog
354 cl = self.repo.changelog
355 cn = cl.node(changerev)
355 cn = cl.node(changerev)
356 cs = cl.read(cn)
356 cs = cl.read(cn)
357 mfn = cs[0]
357 mfn = cs[0]
358
358
359 mt = mimetypes.guess_type(f)[0]
359 mt = mimetypes.guess_type(f)[0]
360 rawtext = text
360 rawtext = text
361 if util.binary(text):
361 if util.binary(text):
362 mt = mt or 'application/octet-stream'
362 mt = mt or 'application/octet-stream'
363 text = "(binary:%s)" % mt
363 text = "(binary:%s)" % mt
364 mt = mt or 'text/plain'
364 mt = mt or 'text/plain'
365
365
366 def lines():
366 def lines():
367 for l, t in enumerate(text.splitlines(1)):
367 for l, t in enumerate(text.splitlines(1)):
368 yield {"line": t,
368 yield {"line": t,
369 "linenumber": "% 6d" % (l + 1),
369 "linenumber": "% 6d" % (l + 1),
370 "parity": l & 1}
370 "parity": l & 1}
371
371
372 yield self.t("filerevision",
372 yield self.t("filerevision",
373 file=f,
373 file=f,
374 filenode=node,
374 filenode=node,
375 path=_up(f),
375 path=_up(f),
376 text=lines(),
376 text=lines(),
377 raw=rawtext,
377 raw=rawtext,
378 mimetype=mt,
378 mimetype=mt,
379 rev=changerev,
379 rev=changerev,
380 node=hex(cn),
380 node=hex(cn),
381 manifest=hex(mfn),
381 manifest=hex(mfn),
382 author=cs[1],
382 author=cs[1],
383 date=cs[2],
383 date=cs[2],
384 parent=self.siblings(fl.parents(n), fl.rev, file=f),
384 parent=self.siblings(fl.parents(n), fl.rev, file=f),
385 child=self.siblings(fl.children(n), fl.rev, file=f),
385 child=self.siblings(fl.children(n), fl.rev, file=f),
386 rename=self.renamelink(fl, n),
386 rename=self.renamelink(fl, n),
387 permissions=self.repo.manifest.readflags(mfn)[f])
387 permissions=self.repo.manifest.readflags(mfn)[f])
388
388
389 def fileannotate(self, f, node):
389 def fileannotate(self, f, node):
390 bcache = {}
390 bcache = {}
391 ncache = {}
391 ncache = {}
392 fl = self.repo.file(f)
392 fl = self.repo.file(f)
393 n = fl.lookup(node)
393 n = fl.lookup(node)
394 node = hex(n)
394 node = hex(n)
395 changerev = fl.linkrev(n)
395 changerev = fl.linkrev(n)
396
396
397 cl = self.repo.changelog
397 cl = self.repo.changelog
398 cn = cl.node(changerev)
398 cn = cl.node(changerev)
399 cs = cl.read(cn)
399 cs = cl.read(cn)
400 mfn = cs[0]
400 mfn = cs[0]
401
401
402 def annotate(**map):
402 def annotate(**map):
403 parity = 1
403 parity = 1
404 last = None
404 last = None
405 for r, l in fl.annotate(n):
405 for r, l in fl.annotate(n):
406 try:
406 try:
407 cnode = ncache[r]
407 cnode = ncache[r]
408 except KeyError:
408 except KeyError:
409 cnode = ncache[r] = self.repo.changelog.node(r)
409 cnode = ncache[r] = self.repo.changelog.node(r)
410
410
411 try:
411 try:
412 name = bcache[r]
412 name = bcache[r]
413 except KeyError:
413 except KeyError:
414 cl = self.repo.changelog.read(cnode)
414 cl = self.repo.changelog.read(cnode)
415 bcache[r] = name = self.repo.ui.shortuser(cl[1])
415 bcache[r] = name = self.repo.ui.shortuser(cl[1])
416
416
417 if last != cnode:
417 if last != cnode:
418 parity = 1 - parity
418 parity = 1 - parity
419 last = cnode
419 last = cnode
420
420
421 yield {"parity": parity,
421 yield {"parity": parity,
422 "node": hex(cnode),
422 "node": hex(cnode),
423 "rev": r,
423 "rev": r,
424 "author": name,
424 "author": name,
425 "file": f,
425 "file": f,
426 "line": l}
426 "line": l}
427
427
428 yield self.t("fileannotate",
428 yield self.t("fileannotate",
429 file=f,
429 file=f,
430 filenode=node,
430 filenode=node,
431 annotate=annotate,
431 annotate=annotate,
432 path=_up(f),
432 path=_up(f),
433 rev=changerev,
433 rev=changerev,
434 node=hex(cn),
434 node=hex(cn),
435 manifest=hex(mfn),
435 manifest=hex(mfn),
436 author=cs[1],
436 author=cs[1],
437 date=cs[2],
437 date=cs[2],
438 rename=self.renamelink(fl, n),
438 rename=self.renamelink(fl, n),
439 parent=self.siblings(fl.parents(n), fl.rev, file=f),
439 parent=self.siblings(fl.parents(n), fl.rev, file=f),
440 child=self.siblings(fl.children(n), fl.rev, file=f),
440 child=self.siblings(fl.children(n), fl.rev, file=f),
441 permissions=self.repo.manifest.readflags(mfn)[f])
441 permissions=self.repo.manifest.readflags(mfn)[f])
442
442
443 def manifest(self, mnode, path):
443 def manifest(self, mnode, path):
444 man = self.repo.manifest
444 man = self.repo.manifest
445 mn = man.lookup(mnode)
445 mn = man.lookup(mnode)
446 mnode = hex(mn)
446 mnode = hex(mn)
447 mf = man.read(mn)
447 mf = man.read(mn)
448 rev = man.rev(mn)
448 rev = man.rev(mn)
449 changerev = man.linkrev(mn)
449 changerev = man.linkrev(mn)
450 node = self.repo.changelog.node(changerev)
450 node = self.repo.changelog.node(changerev)
451 mff = man.readflags(mn)
451 mff = man.readflags(mn)
452
452
453 files = {}
453 files = {}
454
454
455 p = path[1:]
455 p = path[1:]
456 if p and p[-1] != "/":
456 if p and p[-1] != "/":
457 p += "/"
457 p += "/"
458 l = len(p)
458 l = len(p)
459
459
460 for f,n in mf.items():
460 for f,n in mf.items():
461 if f[:l] != p:
461 if f[:l] != p:
462 continue
462 continue
463 remain = f[l:]
463 remain = f[l:]
464 if "/" in remain:
464 if "/" in remain:
465 short = remain[:remain.find("/") + 1] # bleah
465 short = remain[:remain.find("/") + 1] # bleah
466 files[short] = (f, None)
466 files[short] = (f, None)
467 else:
467 else:
468 short = os.path.basename(remain)
468 short = os.path.basename(remain)
469 files[short] = (f, n)
469 files[short] = (f, n)
470
470
471 def filelist(**map):
471 def filelist(**map):
472 parity = 0
472 parity = 0
473 fl = files.keys()
473 fl = files.keys()
474 fl.sort()
474 fl.sort()
475 for f in fl:
475 for f in fl:
476 full, fnode = files[f]
476 full, fnode = files[f]
477 if not fnode:
477 if not fnode:
478 continue
478 continue
479
479
480 yield {"file": full,
480 yield {"file": full,
481 "manifest": mnode,
481 "manifest": mnode,
482 "filenode": hex(fnode),
482 "filenode": hex(fnode),
483 "parity": parity,
483 "parity": parity,
484 "basename": f,
484 "basename": f,
485 "permissions": mff[full]}
485 "permissions": mff[full]}
486 parity = 1 - parity
486 parity = 1 - parity
487
487
488 def dirlist(**map):
488 def dirlist(**map):
489 parity = 0
489 parity = 0
490 fl = files.keys()
490 fl = files.keys()
491 fl.sort()
491 fl.sort()
492 for f in fl:
492 for f in fl:
493 full, fnode = files[f]
493 full, fnode = files[f]
494 if fnode:
494 if fnode:
495 continue
495 continue
496
496
497 yield {"parity": parity,
497 yield {"parity": parity,
498 "path": os.path.join(path, f),
498 "path": os.path.join(path, f),
499 "manifest": mnode,
499 "manifest": mnode,
500 "basename": f[:-1]}
500 "basename": f[:-1]}
501 parity = 1 - parity
501 parity = 1 - parity
502
502
503 yield self.t("manifest",
503 yield self.t("manifest",
504 manifest=mnode,
504 manifest=mnode,
505 rev=rev,
505 rev=rev,
506 node=hex(node),
506 node=hex(node),
507 path=path,
507 path=path,
508 up=_up(path),
508 up=_up(path),
509 fentries=filelist,
509 fentries=filelist,
510 dentries=dirlist,
510 dentries=dirlist,
511 archives=self.archivelist(hex(node)))
511 archives=self.archivelist(hex(node)))
512
512
513 def tags(self):
513 def tags(self):
514 cl = self.repo.changelog
514 cl = self.repo.changelog
515 mf = cl.read(cl.tip())[0]
515 mf = cl.read(cl.tip())[0]
516
516
517 i = self.repo.tagslist()
517 i = self.repo.tagslist()
518 i.reverse()
518 i.reverse()
519
519
520 def entries(notip=False, **map):
520 def entries(notip=False, **map):
521 parity = 0
521 parity = 0
522 for k,n in i:
522 for k,n in i:
523 if notip and k == "tip": continue
523 if notip and k == "tip": continue
524 yield {"parity": parity,
524 yield {"parity": parity,
525 "tag": k,
525 "tag": k,
526 "tagmanifest": hex(cl.read(n)[0]),
526 "tagmanifest": hex(cl.read(n)[0]),
527 "date": cl.read(n)[2],
527 "date": cl.read(n)[2],
528 "node": hex(n)}
528 "node": hex(n)}
529 parity = 1 - parity
529 parity = 1 - parity
530
530
531 yield self.t("tags",
531 yield self.t("tags",
532 manifest=hex(mf),
532 manifest=hex(mf),
533 entries=lambda **x: entries(False, **x),
533 entries=lambda **x: entries(False, **x),
534 entriesnotip=lambda **x: entries(True, **x))
534 entriesnotip=lambda **x: entries(True, **x))
535
535
536 def summary(self):
536 def summary(self):
537 cl = self.repo.changelog
537 cl = self.repo.changelog
538 mf = cl.read(cl.tip())[0]
538 mf = cl.read(cl.tip())[0]
539
539
540 i = self.repo.tagslist()
540 i = self.repo.tagslist()
541 i.reverse()
541 i.reverse()
542
542
543 def tagentries(**map):
543 def tagentries(**map):
544 parity = 0
544 parity = 0
545 count = 0
545 count = 0
546 for k,n in i:
546 for k,n in i:
547 if k == "tip": # skip tip
547 if k == "tip": # skip tip
548 continue;
548 continue;
549
549
550 count += 1
550 count += 1
551 if count > 10: # limit to 10 tags
551 if count > 10: # limit to 10 tags
552 break;
552 break;
553
553
554 c = cl.read(n)
554 c = cl.read(n)
555 m = c[0]
555 m = c[0]
556 t = c[2]
556 t = c[2]
557
557
558 yield self.t("tagentry",
558 yield self.t("tagentry",
559 parity = parity,
559 parity = parity,
560 tag = k,
560 tag = k,
561 node = hex(n),
561 node = hex(n),
562 date = t,
562 date = t,
563 tagmanifest = hex(m))
563 tagmanifest = hex(m))
564 parity = 1 - parity
564 parity = 1 - parity
565
565
566 def changelist(**map):
566 def changelist(**map):
567 parity = 0
567 parity = 0
568 cl = self.repo.changelog
568 cl = self.repo.changelog
569 l = [] # build a list in forward order for efficiency
569 l = [] # build a list in forward order for efficiency
570 for i in range(start, end):
570 for i in range(start, end):
571 n = cl.node(i)
571 n = cl.node(i)
572 changes = cl.read(n)
572 changes = cl.read(n)
573 hn = hex(n)
573 hn = hex(n)
574 t = changes[2]
574 t = changes[2]
575
575
576 l.insert(0, self.t(
576 l.insert(0, self.t(
577 'shortlogentry',
577 'shortlogentry',
578 parity = parity,
578 parity = parity,
579 author = changes[1],
579 author = changes[1],
580 manifest = hex(changes[0]),
580 manifest = hex(changes[0]),
581 desc = changes[4],
581 desc = changes[4],
582 date = t,
582 date = t,
583 rev = i,
583 rev = i,
584 node = hn))
584 node = hn))
585 parity = 1 - parity
585 parity = 1 - parity
586
586
587 yield l
587 yield l
588
588
589 cl = self.repo.changelog
589 cl = self.repo.changelog
590 mf = cl.read(cl.tip())[0]
590 mf = cl.read(cl.tip())[0]
591 count = cl.count()
591 count = cl.count()
592 start = max(0, count - self.maxchanges)
592 start = max(0, count - self.maxchanges)
593 end = min(count, start + self.maxchanges)
593 end = min(count, start + self.maxchanges)
594
594
595 yield self.t("summary",
595 yield self.t("summary",
596 desc = self.repo.ui.config("web", "description", "unknown"),
596 desc = self.repo.ui.config("web", "description", "unknown"),
597 owner = (self.repo.ui.config("ui", "username") or # preferred
597 owner = (self.repo.ui.config("ui", "username") or # preferred
598 self.repo.ui.config("web", "contact") or # deprecated
598 self.repo.ui.config("web", "contact") or # deprecated
599 self.repo.ui.config("web", "author", "unknown")), # also
599 self.repo.ui.config("web", "author", "unknown")), # also
600 lastchange = (0, 0), # FIXME
600 lastchange = (0, 0), # FIXME
601 manifest = hex(mf),
601 manifest = hex(mf),
602 tags = tagentries,
602 tags = tagentries,
603 shortlog = changelist)
603 shortlog = changelist)
604
604
605 def filediff(self, file, changeset):
605 def filediff(self, file, changeset):
606 cl = self.repo.changelog
606 cl = self.repo.changelog
607 n = self.repo.lookup(changeset)
607 n = self.repo.lookup(changeset)
608 changeset = hex(n)
608 changeset = hex(n)
609 p1 = cl.parents(n)[0]
609 p1 = cl.parents(n)[0]
610 cs = cl.read(n)
610 cs = cl.read(n)
611 mf = self.repo.manifest.read(cs[0])
611 mf = self.repo.manifest.read(cs[0])
612
612
613 def diff(**map):
613 def diff(**map):
614 yield self.diff(p1, n, [file])
614 yield self.diff(p1, n, [file])
615
615
616 yield self.t("filediff",
616 yield self.t("filediff",
617 file=file,
617 file=file,
618 filenode=hex(mf.get(file, nullid)),
618 filenode=hex(mf.get(file, nullid)),
619 node=changeset,
619 node=changeset,
620 rev=self.repo.changelog.rev(n),
620 rev=self.repo.changelog.rev(n),
621 parent=self.siblings(cl.parents(n), cl.rev),
621 parent=self.siblings(cl.parents(n), cl.rev),
622 child=self.siblings(cl.children(n), cl.rev),
622 child=self.siblings(cl.children(n), cl.rev),
623 diff=diff)
623 diff=diff)
624
624
625 archive_specs = {
625 archive_specs = {
626 'bz2': ('application/x-tar', 'tbz2', '.tar.bz2', None),
626 'bz2': ('application/x-tar', 'tbz2', '.tar.bz2', None),
627 'gz': ('application/x-tar', 'tgz', '.tar.gz', None),
627 'gz': ('application/x-tar', 'tgz', '.tar.gz', None),
628 'zip': ('application/zip', 'zip', '.zip', None),
628 'zip': ('application/zip', 'zip', '.zip', None),
629 }
629 }
630
630
631 def archive(self, req, cnode, type_):
631 def archive(self, req, cnode, type_):
632 reponame = re.sub(r"\W+", "-", os.path.basename(self.reponame))
632 reponame = re.sub(r"\W+", "-", os.path.basename(self.reponame))
633 name = "%s-%s" % (reponame, short(cnode))
633 name = "%s-%s" % (reponame, short(cnode))
634 mimetype, artype, extension, encoding = self.archive_specs[type_]
634 mimetype, artype, extension, encoding = self.archive_specs[type_]
635 headers = [('Content-type', mimetype),
635 headers = [('Content-type', mimetype),
636 ('Content-disposition', 'attachment; filename=%s%s' %
636 ('Content-disposition', 'attachment; filename=%s%s' %
637 (name, extension))]
637 (name, extension))]
638 if encoding:
638 if encoding:
639 headers.append(('Content-encoding', encoding))
639 headers.append(('Content-encoding', encoding))
640 req.header(headers)
640 req.header(headers)
641 archival.archive(self.repo, req.out, cnode, artype, prefix=name)
641 archival.archive(self.repo, req.out, cnode, artype, prefix=name)
642
642
643 # add tags to things
643 # add tags to things
644 # tags -> list of changesets corresponding to tags
644 # tags -> list of changesets corresponding to tags
645 # find tag, changeset, file
645 # find tag, changeset, file
646
646
647 def cleanpath(self, path):
647 def cleanpath(self, path):
648 p = util.normpath(path)
648 p = util.normpath(path)
649 if p[:2] == "..":
649 if p[:2] == "..":
650 raise Exception("suspicious path")
650 raise Exception("suspicious path")
651 return p
651 return p
652
652
653 def run(self):
653 def run(self):
654 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
654 if not os.environ.get('GATEWAY_INTERFACE', '').startswith("CGI/1."):
655 raise RuntimeError("This function is only intended to be called while running as a CGI script.")
655 raise RuntimeError("This function is only intended to be called while running as a CGI script.")
656 import mercurial.hgweb.wsgicgi as wsgicgi
656 import mercurial.hgweb.wsgicgi as wsgicgi
657 from request import wsgiapplication
657 from request import wsgiapplication
658 def make_web_app():
658 def make_web_app():
659 return self
659 return self
660 wsgicgi.launch(wsgiapplication(make_web_app))
660 wsgicgi.launch(wsgiapplication(make_web_app))
661
661
662 def run_wsgi(self, req):
662 def run_wsgi(self, req):
663 def header(**map):
663 def header(**map):
664 header_file = cStringIO.StringIO(''.join(self.t("header", **map)))
664 header_file = cStringIO.StringIO(''.join(self.t("header", **map)))
665 msg = mimetools.Message(header_file, 0)
665 msg = mimetools.Message(header_file, 0)
666 req.header(msg.items())
666 req.header(msg.items())
667 yield header_file.read()
667 yield header_file.read()
668
668
669 def rawfileheader(**map):
669 def rawfileheader(**map):
670 req.header([('Content-type', map['mimetype']),
670 req.header([('Content-type', map['mimetype']),
671 ('Content-disposition', 'filename=%s' % map['file']),
671 ('Content-disposition', 'filename=%s' % map['file']),
672 ('Content-length', str(len(map['raw'])))])
672 ('Content-length', str(len(map['raw'])))])
673 yield ''
673 yield ''
674
674
675 def footer(**map):
675 def footer(**map):
676 yield self.t("footer",
676 yield self.t("footer",
677 motd=self.repo.ui.config("web", "motd", ""),
677 motd=self.repo.ui.config("web", "motd", ""),
678 **map)
678 **map)
679
679
680 def expand_form(form):
680 def expand_form(form):
681 shortcuts = {
681 shortcuts = {
682 'cl': [('cmd', ['changelog']), ('rev', None)],
682 'cl': [('cmd', ['changelog']), ('rev', None)],
683 'cs': [('cmd', ['changeset']), ('node', None)],
683 'cs': [('cmd', ['changeset']), ('node', None)],
684 'f': [('cmd', ['file']), ('filenode', None)],
684 'f': [('cmd', ['file']), ('filenode', None)],
685 'fl': [('cmd', ['filelog']), ('filenode', None)],
685 'fl': [('cmd', ['filelog']), ('filenode', None)],
686 'fd': [('cmd', ['filediff']), ('node', None)],
686 'fd': [('cmd', ['filediff']), ('node', None)],
687 'fa': [('cmd', ['annotate']), ('filenode', None)],
687 'fa': [('cmd', ['annotate']), ('filenode', None)],
688 'mf': [('cmd', ['manifest']), ('manifest', None)],
688 'mf': [('cmd', ['manifest']), ('manifest', None)],
689 'ca': [('cmd', ['archive']), ('node', None)],
689 'ca': [('cmd', ['archive']), ('node', None)],
690 'tags': [('cmd', ['tags'])],
690 'tags': [('cmd', ['tags'])],
691 'tip': [('cmd', ['changeset']), ('node', ['tip'])],
691 'tip': [('cmd', ['changeset']), ('node', ['tip'])],
692 'static': [('cmd', ['static']), ('file', None)]
692 'static': [('cmd', ['static']), ('file', None)]
693 }
693 }
694
694
695 for k in shortcuts.iterkeys():
695 for k in shortcuts.iterkeys():
696 if form.has_key(k):
696 if form.has_key(k):
697 for name, value in shortcuts[k]:
697 for name, value in shortcuts[k]:
698 if value is None:
698 if value is None:
699 value = form[k]
699 value = form[k]
700 form[name] = value
700 form[name] = value
701 del form[k]
701 del form[k]
702
702
703 self.refresh()
703 self.refresh()
704
704
705 expand_form(req.form)
705 expand_form(req.form)
706
706
707 m = os.path.join(self.templatepath, "map")
707 m = os.path.join(self.templatepath, "map")
708 style = self.repo.ui.config("web", "style", "")
708 style = self.repo.ui.config("web", "style", "")
709 if req.form.has_key('style'):
709 if req.form.has_key('style'):
710 style = req.form['style'][0]
710 style = req.form['style'][0]
711 if style:
711 if style:
712 b = os.path.basename("map-" + style)
712 b = os.path.basename("map-" + style)
713 p = os.path.join(self.templatepath, b)
713 p = os.path.join(self.templatepath, b)
714 if os.path.isfile(p):
714 if os.path.isfile(p):
715 m = p
715 m = p
716
716
717 port = req.env["SERVER_PORT"]
717 port = req.env["SERVER_PORT"]
718 port = port != "80" and (":" + port) or ""
718 port = port != "80" and (":" + port) or ""
719 uri = req.env["REQUEST_URI"]
719 uri = req.env["REQUEST_URI"]
720 if "?" in uri:
720 if "?" in uri:
721 uri = uri.split("?")[0]
721 uri = uri.split("?")[0]
722 url = "http://%s%s%s" % (req.env["SERVER_NAME"], port, uri)
722 url = "http://%s%s%s" % (req.env["SERVER_NAME"], port, uri)
723 if not self.reponame:
723 if not self.reponame:
724 self.reponame = (self.repo.ui.config("web", "name")
724 self.reponame = (self.repo.ui.config("web", "name")
725 or uri.strip('/') or self.repo.root)
725 or uri.strip('/') or self.repo.root)
726
726
727 self.t = templater.templater(m, templater.common_filters,
727 self.t = templater.templater(m, templater.common_filters,
728 defaults={"url": url,
728 defaults={"url": url,
729 "repo": self.reponame,
729 "repo": self.reponame,
730 "header": header,
730 "header": header,
731 "footer": footer,
731 "footer": footer,
732 "rawfileheader": rawfileheader,
732 "rawfileheader": rawfileheader,
733 })
733 })
734
734
735 if not req.form.has_key('cmd'):
735 if not req.form.has_key('cmd'):
736 req.form['cmd'] = [self.t.cache['default'],]
736 req.form['cmd'] = [self.t.cache['default'],]
737
737
738 cmd = req.form['cmd'][0]
738 cmd = req.form['cmd'][0]
739
739
740 method = getattr(self, 'do_' + cmd, None)
740 method = getattr(self, 'do_' + cmd, None)
741 if method:
741 if method:
742 method(req)
742 method(req)
743 else:
743 else:
744 req.write(self.t("error"))
744 req.write(self.t("error"))
745
745
746 def do_changelog(self, req):
746 def do_changelog(self, req):
747 hi = self.repo.changelog.count() - 1
747 hi = self.repo.changelog.count() - 1
748 if req.form.has_key('rev'):
748 if req.form.has_key('rev'):
749 hi = req.form['rev'][0]
749 hi = req.form['rev'][0]
750 try:
750 try:
751 hi = self.repo.changelog.rev(self.repo.lookup(hi))
751 hi = self.repo.changelog.rev(self.repo.lookup(hi))
752 except hg.RepoError:
752 except hg.RepoError:
753 req.write(self.search(hi)) # XXX redirect to 404 page?
753 req.write(self.search(hi)) # XXX redirect to 404 page?
754 return
754 return
755
755
756 req.write(self.changelog(hi))
756 req.write(self.changelog(hi))
757
757
758 def do_changeset(self, req):
758 def do_changeset(self, req):
759 req.write(self.changeset(req.form['node'][0]))
759 req.write(self.changeset(req.form['node'][0]))
760
760
761 def do_manifest(self, req):
761 def do_manifest(self, req):
762 req.write(self.manifest(req.form['manifest'][0],
762 req.write(self.manifest(req.form['manifest'][0],
763 self.cleanpath(req.form['path'][0])))
763 self.cleanpath(req.form['path'][0])))
764
764
765 def do_tags(self, req):
765 def do_tags(self, req):
766 req.write(self.tags())
766 req.write(self.tags())
767
767
768 def do_summary(self, req):
768 def do_summary(self, req):
769 req.write(self.summary())
769 req.write(self.summary())
770
770
771 def do_filediff(self, req):
771 def do_filediff(self, req):
772 req.write(self.filediff(self.cleanpath(req.form['file'][0]),
772 req.write(self.filediff(self.cleanpath(req.form['file'][0]),
773 req.form['node'][0]))
773 req.form['node'][0]))
774
774
775 def do_file(self, req):
775 def do_file(self, req):
776 req.write(self.filerevision(self.cleanpath(req.form['file'][0]),
776 req.write(self.filerevision(self.cleanpath(req.form['file'][0]),
777 req.form['filenode'][0]))
777 req.form['filenode'][0]))
778
778
779 def do_annotate(self, req):
779 def do_annotate(self, req):
780 req.write(self.fileannotate(self.cleanpath(req.form['file'][0]),
780 req.write(self.fileannotate(self.cleanpath(req.form['file'][0]),
781 req.form['filenode'][0]))
781 req.form['filenode'][0]))
782
782
783 def do_filelog(self, req):
783 def do_filelog(self, req):
784 req.write(self.filelog(self.cleanpath(req.form['file'][0]),
784 req.write(self.filelog(self.cleanpath(req.form['file'][0]),
785 req.form['filenode'][0]))
785 req.form['filenode'][0]))
786
786
787 def do_heads(self, req):
787 def do_heads(self, req):
788 resp = " ".join(map(hex, self.repo.heads())) + "\n"
788 resp = " ".join(map(hex, self.repo.heads())) + "\n"
789 req.httphdr("application/mercurial-0.1", length=len(resp))
789 req.httphdr("application/mercurial-0.1", length=len(resp))
790 req.write(resp)
790 req.write(resp)
791
791
792 def do_branches(self, req):
792 def do_branches(self, req):
793 nodes = []
793 nodes = []
794 if req.form.has_key('nodes'):
794 if req.form.has_key('nodes'):
795 nodes = map(bin, req.form['nodes'][0].split(" "))
795 nodes = map(bin, req.form['nodes'][0].split(" "))
796 resp = cStringIO.StringIO()
796 resp = cStringIO.StringIO()
797 for b in self.repo.branches(nodes):
797 for b in self.repo.branches(nodes):
798 resp.write(" ".join(map(hex, b)) + "\n")
798 resp.write(" ".join(map(hex, b)) + "\n")
799 resp = resp.getvalue()
799 resp = resp.getvalue()
800 req.httphdr("application/mercurial-0.1", length=len(resp))
800 req.httphdr("application/mercurial-0.1", length=len(resp))
801 req.write(resp)
801 req.write(resp)
802
802
803 def do_between(self, req):
803 def do_between(self, req):
804 nodes = []
804 nodes = []
805 if req.form.has_key('pairs'):
805 if req.form.has_key('pairs'):
806 pairs = [map(bin, p.split("-"))
806 pairs = [map(bin, p.split("-"))
807 for p in req.form['pairs'][0].split(" ")]
807 for p in req.form['pairs'][0].split(" ")]
808 resp = cStringIO.StringIO()
808 resp = cStringIO.StringIO()
809 for b in self.repo.between(pairs):
809 for b in self.repo.between(pairs):
810 resp.write(" ".join(map(hex, b)) + "\n")
810 resp.write(" ".join(map(hex, b)) + "\n")
811 resp = resp.getvalue()
811 resp = resp.getvalue()
812 req.httphdr("application/mercurial-0.1", length=len(resp))
812 req.httphdr("application/mercurial-0.1", length=len(resp))
813 req.write(resp)
813 req.write(resp)
814
814
815 def do_changegroup(self, req):
815 def do_changegroup(self, req):
816 req.httphdr("application/mercurial-0.1")
816 req.httphdr("application/mercurial-0.1")
817 nodes = []
817 nodes = []
818 if not self.allowpull:
818 if not self.allowpull:
819 return
819 return
820
820
821 if req.form.has_key('roots'):
821 if req.form.has_key('roots'):
822 nodes = map(bin, req.form['roots'][0].split(" "))
822 nodes = map(bin, req.form['roots'][0].split(" "))
823
823
824 z = zlib.compressobj()
824 z = zlib.compressobj()
825 f = self.repo.changegroup(nodes, 'serve')
825 f = self.repo.changegroup(nodes, 'serve')
826 while 1:
826 while 1:
827 chunk = f.read(4096)
827 chunk = f.read(4096)
828 if not chunk:
828 if not chunk:
829 break
829 break
830 req.write(z.compress(chunk))
830 req.write(z.compress(chunk))
831
831
832 req.write(z.flush())
832 req.write(z.flush())
833
833
834 def do_archive(self, req):
834 def do_archive(self, req):
835 changeset = self.repo.lookup(req.form['node'][0])
835 changeset = self.repo.lookup(req.form['node'][0])
836 type_ = req.form['type'][0]
836 type_ = req.form['type'][0]
837 allowed = self.repo.ui.configlist("web", "allow_archive")
837 allowed = self.repo.ui.configlist("web", "allow_archive")
838 if (type_ in self.archives and (type_ in allowed or
838 if (type_ in self.archives and (type_ in allowed or
839 self.repo.ui.configbool("web", "allow" + type_, False))):
839 self.repo.ui.configbool("web", "allow" + type_, False))):
840 self.archive(req, changeset, type_)
840 self.archive(req, changeset, type_)
841 return
841 return
842
842
843 req.write(self.t("error"))
843 req.write(self.t("error"))
844
844
845 def do_static(self, req):
845 def do_static(self, req):
846 fname = req.form['file'][0]
846 fname = req.form['file'][0]
847 static = self.repo.ui.config("web", "static",
847 static = self.repo.ui.config("web", "static",
848 os.path.join(self.templatepath,
848 os.path.join(self.templatepath,
849 "static"))
849 "static"))
850 req.write(staticfile(static, fname, req)
850 req.write(staticfile(static, fname, req)
851 or self.t("error", error="%r not found" % fname))
851 or self.t("error", error="%r not found" % fname))
852
852
853 def do_capabilities(self, req):
853 def do_capabilities(self, req):
854 resp = 'unbundle'
854 resp = 'unbundle'
855 req.httphdr("application/mercurial-0.1", length=len(resp))
855 req.httphdr("application/mercurial-0.1", length=len(resp))
856 req.write(resp)
856 req.write(resp)
857
857
858 def check_perm(self, req, op, default):
858 def check_perm(self, req, op, default):
859 '''check permission for operation based on user auth.
859 '''check permission for operation based on user auth.
860 return true if op allowed, else false.
860 return true if op allowed, else false.
861 default is policy to use if no config given.'''
861 default is policy to use if no config given.'''
862
862
863 user = req.env.get('REMOTE_USER')
863 user = req.env.get('REMOTE_USER')
864
864
865 deny = self.repo.ui.configlist('web', 'deny_' + op)
865 deny = self.repo.ui.configlist('web', 'deny_' + op)
866 if deny and (not user or deny == ['*'] or user in deny):
866 if deny and (not user or deny == ['*'] or user in deny):
867 return False
867 return False
868
868
869 allow = self.repo.ui.configlist('web', 'allow_' + op)
869 allow = self.repo.ui.configlist('web', 'allow_' + op)
870 return (allow and (allow == ['*'] or user in allow)) or default
870 return (allow and (allow == ['*'] or user in allow)) or default
871
871
872 def do_unbundle(self, req):
872 def do_unbundle(self, req):
873 def bail(response, headers={}):
873 def bail(response, headers={}):
874 length = int(req.env['CONTENT_LENGTH'])
874 length = int(req.env['CONTENT_LENGTH'])
875 for s in util.filechunkiter(req, limit=length):
875 for s in util.filechunkiter(req, limit=length):
876 # drain incoming bundle, else client will not see
876 # drain incoming bundle, else client will not see
877 # response when run outside cgi script
877 # response when run outside cgi script
878 pass
878 pass
879 req.httphdr("application/mercurial-0.1", headers=headers)
879 req.httphdr("application/mercurial-0.1", headers=headers)
880 req.write('0\n')
880 req.write('0\n')
881 req.write(response)
881 req.write(response)
882
882
883 # require ssl by default, auth info cannot be sniffed and
883 # require ssl by default, auth info cannot be sniffed and
884 # replayed
884 # replayed
885 ssl_req = self.repo.ui.configbool('web', 'push_ssl', True)
885 ssl_req = self.repo.ui.configbool('web', 'push_ssl', True)
886 if ssl_req and not req.env.get('HTTPS'):
886 if ssl_req and not req.env.get('HTTPS'):
887 bail(_('ssl required\n'))
887 bail(_('ssl required\n'))
888 return
888 return
889
889
890 # do not allow push unless explicitly allowed
890 # do not allow push unless explicitly allowed
891 if not self.check_perm(req, 'push', False):
891 if not self.check_perm(req, 'push', False):
892 bail(_('push not authorized\n'),
892 bail(_('push not authorized\n'),
893 headers={'status': '401 Unauthorized'})
893 headers={'status': '401 Unauthorized'})
894 return
894 return
895
895
896 req.httphdr("application/mercurial-0.1")
896 req.httphdr("application/mercurial-0.1")
897
897
898 their_heads = req.form['heads'][0].split(' ')
898 their_heads = req.form['heads'][0].split(' ')
899
899
900 def check_heads():
900 def check_heads():
901 heads = map(hex, self.repo.heads())
901 heads = map(hex, self.repo.heads())
902 return their_heads == [hex('force')] or their_heads == heads
902 return their_heads == [hex('force')] or their_heads == heads
903
903
904 # fail early if possible
904 # fail early if possible
905 if not check_heads():
905 if not check_heads():
906 bail(_('unsynced changes\n'))
906 bail(_('unsynced changes\n'))
907 return
907 return
908
908
909 # do not lock repo until all changegroup data is
909 # do not lock repo until all changegroup data is
910 # streamed. save to temporary file.
910 # streamed. save to temporary file.
911
911
912 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
912 fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
913 fp = os.fdopen(fd, 'wb+')
913 fp = os.fdopen(fd, 'wb+')
914 try:
914 try:
915 length = int(req.env['CONTENT_LENGTH'])
915 length = int(req.env['CONTENT_LENGTH'])
916 for s in util.filechunkiter(req, limit=length):
916 for s in util.filechunkiter(req, limit=length):
917 fp.write(s)
917 fp.write(s)
918
918
919 lock = self.repo.lock()
919 lock = self.repo.lock()
920 try:
920 try:
921 if not check_heads():
921 if not check_heads():
922 req.write('0\n')
922 req.write('0\n')
923 req.write(_('unsynced changes\n'))
923 req.write(_('unsynced changes\n'))
924 return
924 return
925
925
926 fp.seek(0)
926 fp.seek(0)
927
927
928 # send addchangegroup output to client
928 # send addchangegroup output to client
929
929
930 old_stdout = sys.stdout
930 old_stdout = sys.stdout
931 sys.stdout = cStringIO.StringIO()
931 sys.stdout = cStringIO.StringIO()
932
932
933 try:
933 try:
934 ret = self.repo.addchangegroup(fp, 'serve')
934 ret = self.repo.addchangegroup(fp, 'serve')
935 req.write('%d\n' % ret)
936 req.write(sys.stdout.getvalue())
937 finally:
935 finally:
936 val = sys.stdout.getvalue()
938 sys.stdout = old_stdout
937 sys.stdout = old_stdout
938 req.write('%d\n' % ret)
939 req.write(val)
939 finally:
940 finally:
940 lock.release()
941 lock.release()
941 finally:
942 finally:
942 fp.close()
943 fp.close()
943 os.unlink(tempname)
944 os.unlink(tempname)
@@ -1,69 +1,70 b''
1 # hgweb/wsgicgi.py - CGI->WSGI translator
1 # hgweb/wsgicgi.py - CGI->WSGI translator
2 #
2 #
3 # Copyright 2006 Eric Hopper <hopper@omnifarious.org>
3 # Copyright 2006 Eric Hopper <hopper@omnifarious.org>
4 #
4 #
5 # This software may be used and distributed according to the terms
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7 #
7 #
8 # This was originally copied from the public domain code at
8 # This was originally copied from the public domain code at
9 # http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side
9 # http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side
10
10
11 import os, sys
11 import os, sys
12
12
13 def launch(application):
13 def launch(application):
14
14
15 environ = dict(os.environ.items())
15 environ = dict(os.environ.items())
16 environ['wsgi.input'] = sys.stdin
16 environ['wsgi.input'] = sys.stdin
17 environ['wsgi.errors'] = sys.stderr
17 environ['wsgi.errors'] = sys.stderr
18 environ['wsgi.version'] = (1,0)
18 environ['wsgi.version'] = (1,0)
19 environ['wsgi.multithread'] = False
19 environ['wsgi.multithread'] = False
20 environ['wsgi.multiprocess'] = True
20 environ['wsgi.multiprocess'] = True
21 environ['wsgi.run_once'] = True
21 environ['wsgi.run_once'] = True
22
22
23 if environ.get('HTTPS','off') in ('on','1'):
23 if environ.get('HTTPS','off') in ('on','1'):
24 environ['wsgi.url_scheme'] = 'https'
24 environ['wsgi.url_scheme'] = 'https'
25 else:
25 else:
26 environ['wsgi.url_scheme'] = 'http'
26 environ['wsgi.url_scheme'] = 'http'
27
27
28 headers_set = []
28 headers_set = []
29 headers_sent = []
29 headers_sent = []
30 out = sys.stdout
30
31
31 def write(data):
32 def write(data):
32 if not headers_set:
33 if not headers_set:
33 raise AssertionError("write() before start_response()")
34 raise AssertionError("write() before start_response()")
34
35
35 elif not headers_sent:
36 elif not headers_sent:
36 # Before the first output, send the stored headers
37 # Before the first output, send the stored headers
37 status, response_headers = headers_sent[:] = headers_set
38 status, response_headers = headers_sent[:] = headers_set
38 sys.stdout.write('Status: %s\r\n' % status)
39 out.write('Status: %s\r\n' % status)
39 for header in response_headers:
40 for header in response_headers:
40 sys.stdout.write('%s: %s\r\n' % header)
41 out.write('%s: %s\r\n' % header)
41 sys.stdout.write('\r\n')
42 out.write('\r\n')
42
43
43 sys.stdout.write(data)
44 out.write(data)
44 sys.stdout.flush()
45 out.flush()
45
46
46 def start_response(status,response_headers,exc_info=None):
47 def start_response(status,response_headers,exc_info=None):
47 if exc_info:
48 if exc_info:
48 try:
49 try:
49 if headers_sent:
50 if headers_sent:
50 # Re-raise original exception if headers sent
51 # Re-raise original exception if headers sent
51 raise exc_info[0], exc_info[1], exc_info[2]
52 raise exc_info[0], exc_info[1], exc_info[2]
52 finally:
53 finally:
53 exc_info = None # avoid dangling circular ref
54 exc_info = None # avoid dangling circular ref
54 elif headers_set:
55 elif headers_set:
55 raise AssertionError("Headers already set!")
56 raise AssertionError("Headers already set!")
56
57
57 headers_set[:] = [status,response_headers]
58 headers_set[:] = [status,response_headers]
58 return write
59 return write
59
60
60 result = application(environ, start_response)
61 result = application(environ, start_response)
61 try:
62 try:
62 for data in result:
63 for data in result:
63 if data: # don't send headers until body appears
64 if data: # don't send headers until body appears
64 write(data)
65 write(data)
65 if not headers_sent:
66 if not headers_sent:
66 write('') # send headers now if body was empty
67 write('') # send headers now if body was empty
67 finally:
68 finally:
68 if hasattr(result,'close'):
69 if hasattr(result,'close'):
69 result.close()
70 result.close()
General Comments 0
You need to be logged in to leave comments. Login now