##// END OF EJS Templates
hgweb: move hex creation into an object method...
Pierre-Yves David -
r18405:1eaf0d01 default
parent child Browse files
Show More
@@ -1,370 +1,371 b''
1 1 # hgweb/webutil.py - utility library for the web interface.
2 2 #
3 3 # Copyright 21 May 2005 - (c) 2005 Jake Edge <jake@edge2.net>
4 4 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 import os, copy
10 10 from mercurial import match, patch, scmutil, error, ui, util
11 11 from mercurial.i18n import _
12 12 from mercurial.node import hex, nullid
13 13 from common import ErrorResponse
14 14 from common import HTTP_NOT_FOUND
15 15 import difflib
16 16
17 17 def up(p):
18 18 if p[0] != "/":
19 19 p = "/" + p
20 20 if p[-1] == "/":
21 21 p = p[:-1]
22 22 up = os.path.dirname(p)
23 23 if up == "/":
24 24 return "/"
25 25 return up + "/"
26 26
27 27 def _navseq(step, firststep=None):
28 28 if firststep:
29 29 yield firststep
30 30 if firststep >= 20 and firststep <= 40:
31 31 firststep = 50
32 32 yield firststep
33 33 assert step > 0
34 34 assert firststep > 0
35 35 while step <= firststep:
36 36 step *= 10
37 37 while True:
38 38 yield 1 * step
39 39 yield 3 * step
40 40 step *= 10
41 41
42 42 class revnav(object):
43 43
44 44 def __init__(self, nodefunc):
45 45 """Navigation generation object
46 46
47 47 :nodefun: factory for a changectx from a revision
48 48 """
49 49 self.nodefunc = nodefunc
50 50
51 def hex(self, rev):
52 return self.nodefunc(rev).hex()
53
51 54 def gen(self, pos, pagelen, limit):
52 55 """computes label and revision id for navigation link
53 56
54 57 :pos: is the revision relative to which we generate navigation.
55 58 :pagelen: the size of each navigation page
56 59 :limit: how far shall we link
57 60
58 61 The return is:
59 62 - a single element tuple
60 63 - containing a dictionary with a `before` and `after` key
61 64 - values are generator functions taking arbitrary number of kwargs
62 65 - yield items are dictionaries with `label` and `node` keys
63 66 """
64 67
65 68 navbefore = []
66 69 navafter = []
67 70
68 71 for f in _navseq(1, pagelen):
69 72 if f > limit:
70 73 break
71 74 if pos + f < limit:
72 navafter.append(("+%d" % f,
73 hex(self.nodefunc(pos + f).node())))
75 navafter.append(("+%d" % f, self.hex(pos + f)))
74 76 if pos - f >= 0:
75 navbefore.insert(0, ("-%d" % f,
76 hex(self.nodefunc(pos - f).node())))
77 navbefore.insert(0, ("-%d" % f, self.hex(pos - f)))
77 78
78 79 navafter.append(("tip", "tip"))
79 80 try:
80 navbefore.insert(0, ("(0)", hex(self.nodefunc(0).node())))
81 navbefore.insert(0, ("(0)", self.hex(0)))
81 82 except error.RepoError:
82 83 pass
83 84
84 85 data = lambda i: {"label": i[0], "node": i[1]}
85 86 return ({'before': lambda **map: (data(i) for i in navbefore),
86 87 'after': lambda **map: (data(i) for i in navafter)},)
87 88
88 89 def _siblings(siblings=[], hiderev=None):
89 90 siblings = [s for s in siblings if s.node() != nullid]
90 91 if len(siblings) == 1 and siblings[0].rev() == hiderev:
91 92 return
92 93 for s in siblings:
93 94 d = {'node': s.hex(), 'rev': s.rev()}
94 95 d['user'] = s.user()
95 96 d['date'] = s.date()
96 97 d['description'] = s.description()
97 98 d['branch'] = s.branch()
98 99 if util.safehasattr(s, 'path'):
99 100 d['file'] = s.path()
100 101 yield d
101 102
102 103 def parents(ctx, hide=None):
103 104 return _siblings(ctx.parents(), hide)
104 105
105 106 def children(ctx, hide=None):
106 107 return _siblings(ctx.children(), hide)
107 108
108 109 def renamelink(fctx):
109 110 r = fctx.renamed()
110 111 if r:
111 112 return [dict(file=r[0], node=hex(r[1]))]
112 113 return []
113 114
114 115 def nodetagsdict(repo, node):
115 116 return [{"name": i} for i in repo.nodetags(node)]
116 117
117 118 def nodebookmarksdict(repo, node):
118 119 return [{"name": i} for i in repo.nodebookmarks(node)]
119 120
120 121 def nodebranchdict(repo, ctx):
121 122 branches = []
122 123 branch = ctx.branch()
123 124 # If this is an empty repo, ctx.node() == nullid,
124 125 # ctx.branch() == 'default'.
125 126 try:
126 127 branchnode = repo.branchtip(branch)
127 128 except error.RepoLookupError:
128 129 branchnode = None
129 130 if branchnode == ctx.node():
130 131 branches.append({"name": branch})
131 132 return branches
132 133
133 134 def nodeinbranch(repo, ctx):
134 135 branches = []
135 136 branch = ctx.branch()
136 137 try:
137 138 branchnode = repo.branchtip(branch)
138 139 except error.RepoLookupError:
139 140 branchnode = None
140 141 if branch != 'default' and branchnode != ctx.node():
141 142 branches.append({"name": branch})
142 143 return branches
143 144
144 145 def nodebranchnodefault(ctx):
145 146 branches = []
146 147 branch = ctx.branch()
147 148 if branch != 'default':
148 149 branches.append({"name": branch})
149 150 return branches
150 151
151 152 def showtag(repo, tmpl, t1, node=nullid, **args):
152 153 for t in repo.nodetags(node):
153 154 yield tmpl(t1, tag=t, **args)
154 155
155 156 def showbookmark(repo, tmpl, t1, node=nullid, **args):
156 157 for t in repo.nodebookmarks(node):
157 158 yield tmpl(t1, bookmark=t, **args)
158 159
159 160 def cleanpath(repo, path):
160 161 path = path.lstrip('/')
161 162 return scmutil.canonpath(repo.root, '', path)
162 163
163 164 def changeidctx (repo, changeid):
164 165 try:
165 166 ctx = repo[changeid]
166 167 except error.RepoError:
167 168 man = repo.manifest
168 169 ctx = repo[man.linkrev(man.rev(man.lookup(changeid)))]
169 170
170 171 return ctx
171 172
172 173 def changectx (repo, req):
173 174 changeid = "tip"
174 175 if 'node' in req.form:
175 176 changeid = req.form['node'][0]
176 177 ipos=changeid.find(':')
177 178 if ipos != -1:
178 179 changeid = changeid[(ipos + 1):]
179 180 elif 'manifest' in req.form:
180 181 changeid = req.form['manifest'][0]
181 182
182 183 return changeidctx(repo, changeid)
183 184
184 185 def basechangectx(repo, req):
185 186 if 'node' in req.form:
186 187 changeid = req.form['node'][0]
187 188 ipos=changeid.find(':')
188 189 if ipos != -1:
189 190 changeid = changeid[:ipos]
190 191 return changeidctx(repo, changeid)
191 192
192 193 return None
193 194
194 195 def filectx(repo, req):
195 196 if 'file' not in req.form:
196 197 raise ErrorResponse(HTTP_NOT_FOUND, 'file not given')
197 198 path = cleanpath(repo, req.form['file'][0])
198 199 if 'node' in req.form:
199 200 changeid = req.form['node'][0]
200 201 elif 'filenode' in req.form:
201 202 changeid = req.form['filenode'][0]
202 203 else:
203 204 raise ErrorResponse(HTTP_NOT_FOUND, 'node or filenode not given')
204 205 try:
205 206 fctx = repo[changeid][path]
206 207 except error.RepoError:
207 208 fctx = repo.filectx(path, fileid=changeid)
208 209
209 210 return fctx
210 211
211 212 def listfilediffs(tmpl, files, node, max):
212 213 for f in files[:max]:
213 214 yield tmpl('filedifflink', node=hex(node), file=f)
214 215 if len(files) > max:
215 216 yield tmpl('fileellipses')
216 217
217 218 def diffs(repo, tmpl, ctx, basectx, files, parity, style):
218 219
219 220 def countgen():
220 221 start = 1
221 222 while True:
222 223 yield start
223 224 start += 1
224 225
225 226 blockcount = countgen()
226 227 def prettyprintlines(diff, blockno):
227 228 for lineno, l in enumerate(diff.splitlines(True)):
228 229 lineno = "%d.%d" % (blockno, lineno + 1)
229 230 if l.startswith('+'):
230 231 ltype = "difflineplus"
231 232 elif l.startswith('-'):
232 233 ltype = "difflineminus"
233 234 elif l.startswith('@'):
234 235 ltype = "difflineat"
235 236 else:
236 237 ltype = "diffline"
237 238 yield tmpl(ltype,
238 239 line=l,
239 240 lineid="l%s" % lineno,
240 241 linenumber="% 8s" % lineno)
241 242
242 243 if files:
243 244 m = match.exact(repo.root, repo.getcwd(), files)
244 245 else:
245 246 m = match.always(repo.root, repo.getcwd())
246 247
247 248 diffopts = patch.diffopts(repo.ui, untrusted=True)
248 249 if basectx is None:
249 250 parents = ctx.parents()
250 251 node1 = parents and parents[0].node() or nullid
251 252 else:
252 253 node1 = basectx.node()
253 254 node2 = ctx.node()
254 255
255 256 block = []
256 257 for chunk in patch.diff(repo, node1, node2, m, opts=diffopts):
257 258 if chunk.startswith('diff') and block:
258 259 blockno = blockcount.next()
259 260 yield tmpl('diffblock', parity=parity.next(), blockno=blockno,
260 261 lines=prettyprintlines(''.join(block), blockno))
261 262 block = []
262 263 if chunk.startswith('diff') and style != 'raw':
263 264 chunk = ''.join(chunk.splitlines(True)[1:])
264 265 block.append(chunk)
265 266 blockno = blockcount.next()
266 267 yield tmpl('diffblock', parity=parity.next(), blockno=blockno,
267 268 lines=prettyprintlines(''.join(block), blockno))
268 269
269 270 def compare(tmpl, context, leftlines, rightlines):
270 271 '''Generator function that provides side-by-side comparison data.'''
271 272
272 273 def compline(type, leftlineno, leftline, rightlineno, rightline):
273 274 lineid = leftlineno and ("l%s" % leftlineno) or ''
274 275 lineid += rightlineno and ("r%s" % rightlineno) or ''
275 276 return tmpl('comparisonline',
276 277 type=type,
277 278 lineid=lineid,
278 279 leftlinenumber="% 6s" % (leftlineno or ''),
279 280 leftline=leftline or '',
280 281 rightlinenumber="% 6s" % (rightlineno or ''),
281 282 rightline=rightline or '')
282 283
283 284 def getblock(opcodes):
284 285 for type, llo, lhi, rlo, rhi in opcodes:
285 286 len1 = lhi - llo
286 287 len2 = rhi - rlo
287 288 count = min(len1, len2)
288 289 for i in xrange(count):
289 290 yield compline(type=type,
290 291 leftlineno=llo + i + 1,
291 292 leftline=leftlines[llo + i],
292 293 rightlineno=rlo + i + 1,
293 294 rightline=rightlines[rlo + i])
294 295 if len1 > len2:
295 296 for i in xrange(llo + count, lhi):
296 297 yield compline(type=type,
297 298 leftlineno=i + 1,
298 299 leftline=leftlines[i],
299 300 rightlineno=None,
300 301 rightline=None)
301 302 elif len2 > len1:
302 303 for i in xrange(rlo + count, rhi):
303 304 yield compline(type=type,
304 305 leftlineno=None,
305 306 leftline=None,
306 307 rightlineno=i + 1,
307 308 rightline=rightlines[i])
308 309
309 310 s = difflib.SequenceMatcher(None, leftlines, rightlines)
310 311 if context < 0:
311 312 yield tmpl('comparisonblock', lines=getblock(s.get_opcodes()))
312 313 else:
313 314 for oc in s.get_grouped_opcodes(n=context):
314 315 yield tmpl('comparisonblock', lines=getblock(oc))
315 316
316 317 def diffstatgen(ctx, basectx):
317 318 '''Generator function that provides the diffstat data.'''
318 319
319 320 stats = patch.diffstatdata(util.iterlines(ctx.diff(basectx)))
320 321 maxname, maxtotal, addtotal, removetotal, binary = patch.diffstatsum(stats)
321 322 while True:
322 323 yield stats, maxname, maxtotal, addtotal, removetotal, binary
323 324
324 325 def diffsummary(statgen):
325 326 '''Return a short summary of the diff.'''
326 327
327 328 stats, maxname, maxtotal, addtotal, removetotal, binary = statgen.next()
328 329 return _(' %d files changed, %d insertions(+), %d deletions(-)\n') % (
329 330 len(stats), addtotal, removetotal)
330 331
331 332 def diffstat(tmpl, ctx, statgen, parity):
332 333 '''Return a diffstat template for each file in the diff.'''
333 334
334 335 stats, maxname, maxtotal, addtotal, removetotal, binary = statgen.next()
335 336 files = ctx.files()
336 337
337 338 def pct(i):
338 339 if maxtotal == 0:
339 340 return 0
340 341 return (float(i) / maxtotal) * 100
341 342
342 343 fileno = 0
343 344 for filename, adds, removes, isbinary in stats:
344 345 template = filename in files and 'diffstatlink' or 'diffstatnolink'
345 346 total = adds + removes
346 347 fileno += 1
347 348 yield tmpl(template, node=ctx.hex(), file=filename, fileno=fileno,
348 349 total=total, addpct=pct(adds), removepct=pct(removes),
349 350 parity=parity.next())
350 351
351 352 class sessionvars(object):
352 353 def __init__(self, vars, start='?'):
353 354 self.start = start
354 355 self.vars = vars
355 356 def __getitem__(self, key):
356 357 return self.vars[key]
357 358 def __setitem__(self, key, value):
358 359 self.vars[key] = value
359 360 def __copy__(self):
360 361 return sessionvars(copy.copy(self.vars), self.start)
361 362 def __iter__(self):
362 363 separator = self.start
363 364 for key, value in sorted(self.vars.iteritems()):
364 365 yield {'name': key, 'value': str(value), 'separator': separator}
365 366 separator = '&'
366 367
367 368 class wsgiui(ui.ui):
368 369 # default termwidth breaks under mod_wsgi
369 370 def termwidth(self):
370 371 return 80
General Comments 0
You need to be logged in to leave comments. Login now