##// END OF EJS Templates
hgweb: drop useless **args from webutil.showtag() and showbookmark()...
Yuya Nishihara -
r37929:ec03f3aa default
parent child Browse files
Show More
@@ -1,739 +1,735 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 from __future__ import absolute_import
10 10
11 11 import copy
12 12 import difflib
13 13 import os
14 14 import re
15 15
16 16 from ..i18n import _
17 17 from ..node import hex, nullid, short
18 18
19 19 from .common import (
20 20 ErrorResponse,
21 21 HTTP_BAD_REQUEST,
22 22 HTTP_NOT_FOUND,
23 23 paritygen,
24 24 )
25 25
26 26 from .. import (
27 27 context,
28 28 error,
29 29 match,
30 30 mdiff,
31 31 obsutil,
32 32 patch,
33 33 pathutil,
34 34 pycompat,
35 35 scmutil,
36 36 templatefilters,
37 37 templatekw,
38 38 templateutil,
39 39 ui as uimod,
40 40 util,
41 41 )
42 42
43 43 from ..utils import (
44 44 stringutil,
45 45 )
46 46
47 47 archivespecs = util.sortdict((
48 48 ('zip', ('application/zip', 'zip', '.zip', None)),
49 49 ('gz', ('application/x-gzip', 'tgz', '.tar.gz', None)),
50 50 ('bz2', ('application/x-bzip2', 'tbz2', '.tar.bz2', None)),
51 51 ))
52 52
53 53 def archivelist(ui, nodeid, url=None):
54 54 allowed = ui.configlist('web', 'allow_archive', untrusted=True)
55 55 archives = []
56 56
57 57 for typ, spec in archivespecs.iteritems():
58 58 if typ in allowed or ui.configbool('web', 'allow' + typ,
59 59 untrusted=True):
60 60 archives.append({
61 61 'type': typ,
62 62 'extension': spec[2],
63 63 'node': nodeid,
64 64 'url': url,
65 65 })
66 66
67 67 return templateutil.mappinglist(archives)
68 68
69 69 def up(p):
70 70 if p[0:1] != "/":
71 71 p = "/" + p
72 72 if p[-1:] == "/":
73 73 p = p[:-1]
74 74 up = os.path.dirname(p)
75 75 if up == "/":
76 76 return "/"
77 77 return up + "/"
78 78
79 79 def _navseq(step, firststep=None):
80 80 if firststep:
81 81 yield firststep
82 82 if firststep >= 20 and firststep <= 40:
83 83 firststep = 50
84 84 yield firststep
85 85 assert step > 0
86 86 assert firststep > 0
87 87 while step <= firststep:
88 88 step *= 10
89 89 while True:
90 90 yield 1 * step
91 91 yield 3 * step
92 92 step *= 10
93 93
94 94 class revnav(object):
95 95
96 96 def __init__(self, repo):
97 97 """Navigation generation object
98 98
99 99 :repo: repo object we generate nav for
100 100 """
101 101 # used for hex generation
102 102 self._revlog = repo.changelog
103 103
104 104 def __nonzero__(self):
105 105 """return True if any revision to navigate over"""
106 106 return self._first() is not None
107 107
108 108 __bool__ = __nonzero__
109 109
110 110 def _first(self):
111 111 """return the minimum non-filtered changeset or None"""
112 112 try:
113 113 return next(iter(self._revlog))
114 114 except StopIteration:
115 115 return None
116 116
117 117 def hex(self, rev):
118 118 return hex(self._revlog.node(rev))
119 119
120 120 def gen(self, pos, pagelen, limit):
121 121 """computes label and revision id for navigation link
122 122
123 123 :pos: is the revision relative to which we generate navigation.
124 124 :pagelen: the size of each navigation page
125 125 :limit: how far shall we link
126 126
127 127 The return is:
128 128 - a single element mappinglist
129 129 - containing a dictionary with a `before` and `after` key
130 130 - values are dictionaries with `label` and `node` keys
131 131 """
132 132 if not self:
133 133 # empty repo
134 134 return templateutil.mappinglist([
135 135 {'before': templateutil.mappinglist([]),
136 136 'after': templateutil.mappinglist([])},
137 137 ])
138 138
139 139 targets = []
140 140 for f in _navseq(1, pagelen):
141 141 if f > limit:
142 142 break
143 143 targets.append(pos + f)
144 144 targets.append(pos - f)
145 145 targets.sort()
146 146
147 147 first = self._first()
148 148 navbefore = [{'label': '(%i)' % first, 'node': self.hex(first)}]
149 149 navafter = []
150 150 for rev in targets:
151 151 if rev not in self._revlog:
152 152 continue
153 153 if pos < rev < limit:
154 154 navafter.append({'label': '+%d' % abs(rev - pos),
155 155 'node': self.hex(rev)})
156 156 if 0 < rev < pos:
157 157 navbefore.append({'label': '-%d' % abs(rev - pos),
158 158 'node': self.hex(rev)})
159 159
160 160 navafter.append({'label': 'tip', 'node': 'tip'})
161 161
162 162 # TODO: maybe this can be a scalar object supporting tomap()
163 163 return templateutil.mappinglist([
164 164 {'before': templateutil.mappinglist(navbefore),
165 165 'after': templateutil.mappinglist(navafter)},
166 166 ])
167 167
168 168 class filerevnav(revnav):
169 169
170 170 def __init__(self, repo, path):
171 171 """Navigation generation object
172 172
173 173 :repo: repo object we generate nav for
174 174 :path: path of the file we generate nav for
175 175 """
176 176 # used for iteration
177 177 self._changelog = repo.unfiltered().changelog
178 178 # used for hex generation
179 179 self._revlog = repo.file(path)
180 180
181 181 def hex(self, rev):
182 182 return hex(self._changelog.node(self._revlog.linkrev(rev)))
183 183
184 184 # TODO: maybe this can be a wrapper class for changectx/filectx list, which
185 185 # yields {'ctx': ctx}
186 186 def _ctxsgen(context, ctxs):
187 187 for s in ctxs:
188 188 d = {
189 189 'node': s.hex(),
190 190 'rev': s.rev(),
191 191 'user': s.user(),
192 192 'date': s.date(),
193 193 'description': s.description(),
194 194 'branch': s.branch(),
195 195 }
196 196 if util.safehasattr(s, 'path'):
197 197 d['file'] = s.path()
198 198 yield d
199 199
200 200 def _siblings(siblings=None, hiderev=None):
201 201 if siblings is None:
202 202 siblings = []
203 203 siblings = [s for s in siblings if s.node() != nullid]
204 204 if len(siblings) == 1 and siblings[0].rev() == hiderev:
205 205 siblings = []
206 206 return templateutil.mappinggenerator(_ctxsgen, args=(siblings,))
207 207
208 208 def difffeatureopts(req, ui, section):
209 209 diffopts = patch.difffeatureopts(ui, untrusted=True,
210 210 section=section, whitespace=True)
211 211
212 212 for k in ('ignorews', 'ignorewsamount', 'ignorewseol', 'ignoreblanklines'):
213 213 v = req.qsparams.get(k)
214 214 if v is not None:
215 215 v = stringutil.parsebool(v)
216 216 setattr(diffopts, k, v if v is not None else True)
217 217
218 218 return diffopts
219 219
220 220 def annotate(req, fctx, ui):
221 221 diffopts = difffeatureopts(req, ui, 'annotate')
222 222 return fctx.annotate(follow=True, diffopts=diffopts)
223 223
224 224 def parents(ctx, hide=None):
225 225 if isinstance(ctx, context.basefilectx):
226 226 introrev = ctx.introrev()
227 227 if ctx.changectx().rev() != introrev:
228 228 return _siblings([ctx.repo()[introrev]], hide)
229 229 return _siblings(ctx.parents(), hide)
230 230
231 231 def children(ctx, hide=None):
232 232 return _siblings(ctx.children(), hide)
233 233
234 234 def renamelink(fctx):
235 235 r = fctx.renamed()
236 236 if r:
237 237 return templateutil.mappinglist([{'file': r[0], 'node': hex(r[1])}])
238 238 return templateutil.mappinglist([])
239 239
240 240 def nodetagsdict(repo, node):
241 241 return templateutil.hybridlist(repo.nodetags(node), name='name')
242 242
243 243 def nodebookmarksdict(repo, node):
244 244 return templateutil.hybridlist(repo.nodebookmarks(node), name='name')
245 245
246 246 def nodebranchdict(repo, ctx):
247 247 branches = []
248 248 branch = ctx.branch()
249 249 # If this is an empty repo, ctx.node() == nullid,
250 250 # ctx.branch() == 'default'.
251 251 try:
252 252 branchnode = repo.branchtip(branch)
253 253 except error.RepoLookupError:
254 254 branchnode = None
255 255 if branchnode == ctx.node():
256 256 branches.append(branch)
257 257 return templateutil.hybridlist(branches, name='name')
258 258
259 259 def nodeinbranch(repo, ctx):
260 260 branches = []
261 261 branch = ctx.branch()
262 262 try:
263 263 branchnode = repo.branchtip(branch)
264 264 except error.RepoLookupError:
265 265 branchnode = None
266 266 if branch != 'default' and branchnode != ctx.node():
267 267 branches.append(branch)
268 268 return templateutil.hybridlist(branches, name='name')
269 269
270 270 def nodebranchnodefault(ctx):
271 271 branches = []
272 272 branch = ctx.branch()
273 273 if branch != 'default':
274 274 branches.append(branch)
275 275 return templateutil.hybridlist(branches, name='name')
276 276
277 def showtag(repo, tmpl, t1, node=nullid, **args):
278 args = pycompat.byteskwargs(args)
277 def showtag(repo, tmpl, t1, node=nullid):
279 278 for t in repo.nodetags(node):
280 lm = args.copy()
281 lm['tag'] = t
279 lm = {'tag': t}
282 280 yield tmpl.generate(t1, lm)
283 281
284 def showbookmark(repo, tmpl, t1, node=nullid, **args):
285 args = pycompat.byteskwargs(args)
282 def showbookmark(repo, tmpl, t1, node=nullid):
286 283 for t in repo.nodebookmarks(node):
287 lm = args.copy()
288 lm['bookmark'] = t
284 lm = {'bookmark': t}
289 285 yield tmpl.generate(t1, lm)
290 286
291 287 def branchentries(repo, stripecount, limit=0):
292 288 tips = []
293 289 heads = repo.heads()
294 290 parity = paritygen(stripecount)
295 291 sortkey = lambda item: (not item[1], item[0].rev())
296 292
297 293 def entries(**map):
298 294 count = 0
299 295 if not tips:
300 296 for tag, hs, tip, closed in repo.branchmap().iterbranches():
301 297 tips.append((repo[tip], closed))
302 298 for ctx, closed in sorted(tips, key=sortkey, reverse=True):
303 299 if limit > 0 and count >= limit:
304 300 return
305 301 count += 1
306 302 if closed:
307 303 status = 'closed'
308 304 elif ctx.node() not in heads:
309 305 status = 'inactive'
310 306 else:
311 307 status = 'open'
312 308 yield {
313 309 'parity': next(parity),
314 310 'branch': ctx.branch(),
315 311 'status': status,
316 312 'node': ctx.hex(),
317 313 'date': ctx.date()
318 314 }
319 315
320 316 return entries
321 317
322 318 def cleanpath(repo, path):
323 319 path = path.lstrip('/')
324 320 return pathutil.canonpath(repo.root, '', path)
325 321
326 322 def changectx(repo, req):
327 323 changeid = "tip"
328 324 if 'node' in req.qsparams:
329 325 changeid = req.qsparams['node']
330 326 ipos = changeid.find(':')
331 327 if ipos != -1:
332 328 changeid = changeid[(ipos + 1):]
333 329
334 330 return scmutil.revsymbol(repo, changeid)
335 331
336 332 def basechangectx(repo, req):
337 333 if 'node' in req.qsparams:
338 334 changeid = req.qsparams['node']
339 335 ipos = changeid.find(':')
340 336 if ipos != -1:
341 337 changeid = changeid[:ipos]
342 338 return scmutil.revsymbol(repo, changeid)
343 339
344 340 return None
345 341
346 342 def filectx(repo, req):
347 343 if 'file' not in req.qsparams:
348 344 raise ErrorResponse(HTTP_NOT_FOUND, 'file not given')
349 345 path = cleanpath(repo, req.qsparams['file'])
350 346 if 'node' in req.qsparams:
351 347 changeid = req.qsparams['node']
352 348 elif 'filenode' in req.qsparams:
353 349 changeid = req.qsparams['filenode']
354 350 else:
355 351 raise ErrorResponse(HTTP_NOT_FOUND, 'node or filenode not given')
356 352 try:
357 353 fctx = scmutil.revsymbol(repo, changeid)[path]
358 354 except error.RepoError:
359 355 fctx = repo.filectx(path, fileid=changeid)
360 356
361 357 return fctx
362 358
363 359 def linerange(req):
364 360 linerange = req.qsparams.getall('linerange')
365 361 if not linerange:
366 362 return None
367 363 if len(linerange) > 1:
368 364 raise ErrorResponse(HTTP_BAD_REQUEST,
369 365 'redundant linerange parameter')
370 366 try:
371 367 fromline, toline = map(int, linerange[0].split(':', 1))
372 368 except ValueError:
373 369 raise ErrorResponse(HTTP_BAD_REQUEST,
374 370 'invalid linerange parameter')
375 371 try:
376 372 return util.processlinerange(fromline, toline)
377 373 except error.ParseError as exc:
378 374 raise ErrorResponse(HTTP_BAD_REQUEST, pycompat.bytestr(exc))
379 375
380 376 def formatlinerange(fromline, toline):
381 377 return '%d:%d' % (fromline + 1, toline)
382 378
383 379 def succsandmarkers(context, mapping):
384 380 repo = context.resource(mapping, 'repo')
385 381 itemmappings = templatekw.showsuccsandmarkers(context, mapping)
386 382 for item in itemmappings.tovalue(context, mapping):
387 383 item['successors'] = _siblings(repo[successor]
388 384 for successor in item['successors'])
389 385 yield item
390 386
391 387 # teach templater succsandmarkers is switched to (context, mapping) API
392 388 succsandmarkers._requires = {'repo', 'ctx'}
393 389
394 390 def whyunstable(context, mapping):
395 391 repo = context.resource(mapping, 'repo')
396 392 ctx = context.resource(mapping, 'ctx')
397 393
398 394 entries = obsutil.whyunstable(repo, ctx)
399 395 for entry in entries:
400 396 if entry.get('divergentnodes'):
401 397 entry['divergentnodes'] = _siblings(entry['divergentnodes'])
402 398 yield entry
403 399
404 400 whyunstable._requires = {'repo', 'ctx'}
405 401
406 402 def commonentry(repo, ctx):
407 403 node = ctx.node()
408 404 return {
409 405 # TODO: perhaps ctx.changectx() should be assigned if ctx is a
410 406 # filectx, but I'm not pretty sure if that would always work because
411 407 # fctx.parents() != fctx.changectx.parents() for example.
412 408 'ctx': ctx,
413 409 'rev': ctx.rev(),
414 410 'node': hex(node),
415 411 'author': ctx.user(),
416 412 'desc': ctx.description(),
417 413 'date': ctx.date(),
418 414 'extra': ctx.extra(),
419 415 'phase': ctx.phasestr(),
420 416 'obsolete': ctx.obsolete(),
421 417 'succsandmarkers': succsandmarkers,
422 418 'instabilities': [{"instability": i} for i in ctx.instabilities()],
423 419 'whyunstable': whyunstable,
424 420 'branch': nodebranchnodefault(ctx),
425 421 'inbranch': nodeinbranch(repo, ctx),
426 422 'branches': nodebranchdict(repo, ctx),
427 423 'tags': nodetagsdict(repo, node),
428 424 'bookmarks': nodebookmarksdict(repo, node),
429 425 'parent': lambda **x: parents(ctx),
430 426 'child': lambda **x: children(ctx),
431 427 }
432 428
433 429 def changelistentry(web, ctx):
434 430 '''Obtain a dictionary to be used for entries in a changelist.
435 431
436 432 This function is called when producing items for the "entries" list passed
437 433 to the "shortlog" and "changelog" templates.
438 434 '''
439 435 repo = web.repo
440 436 rev = ctx.rev()
441 437 n = ctx.node()
442 438 showtags = showtag(repo, web.tmpl, 'changelogtag', n)
443 439 files = listfilediffs(web.tmpl, ctx.files(), n, web.maxfiles)
444 440
445 441 entry = commonentry(repo, ctx)
446 442 entry.update(
447 443 allparents=lambda **x: parents(ctx),
448 444 parent=lambda **x: parents(ctx, rev - 1),
449 445 child=lambda **x: children(ctx, rev + 1),
450 446 changelogtag=showtags,
451 447 files=files,
452 448 )
453 449 return entry
454 450
455 451 def symrevorshortnode(req, ctx):
456 452 if 'node' in req.qsparams:
457 453 return templatefilters.revescape(req.qsparams['node'])
458 454 else:
459 455 return short(ctx.node())
460 456
461 457 def changesetentry(web, ctx):
462 458 '''Obtain a dictionary to be used to render the "changeset" template.'''
463 459
464 460 showtags = showtag(web.repo, web.tmpl, 'changesettag', ctx.node())
465 461 showbookmarks = showbookmark(web.repo, web.tmpl, 'changesetbookmark',
466 462 ctx.node())
467 463 showbranch = nodebranchnodefault(ctx)
468 464
469 465 files = []
470 466 parity = paritygen(web.stripecount)
471 467 for blockno, f in enumerate(ctx.files()):
472 468 template = 'filenodelink' if f in ctx else 'filenolink'
473 469 files.append(web.tmpl.generate(template, {
474 470 'node': ctx.hex(),
475 471 'file': f,
476 472 'blockno': blockno + 1,
477 473 'parity': next(parity),
478 474 }))
479 475
480 476 basectx = basechangectx(web.repo, web.req)
481 477 if basectx is None:
482 478 basectx = ctx.p1()
483 479
484 480 style = web.config('web', 'style')
485 481 if 'style' in web.req.qsparams:
486 482 style = web.req.qsparams['style']
487 483
488 484 diff = diffs(web, ctx, basectx, None, style)
489 485
490 486 parity = paritygen(web.stripecount)
491 487 diffstatsgen = diffstatgen(ctx, basectx)
492 488 diffstats = diffstat(web.tmpl, ctx, diffstatsgen, parity)
493 489
494 490 return dict(
495 491 diff=diff,
496 492 symrev=symrevorshortnode(web.req, ctx),
497 493 basenode=basectx.hex(),
498 494 changesettag=showtags,
499 495 changesetbookmark=showbookmarks,
500 496 changesetbranch=showbranch,
501 497 files=files,
502 498 diffsummary=lambda **x: diffsummary(diffstatsgen),
503 499 diffstat=diffstats,
504 500 archives=web.archivelist(ctx.hex()),
505 501 **pycompat.strkwargs(commonentry(web.repo, ctx)))
506 502
507 503 def listfilediffs(tmpl, files, node, max):
508 504 for f in files[:max]:
509 505 yield tmpl.generate('filedifflink', {'node': hex(node), 'file': f})
510 506 if len(files) > max:
511 507 yield tmpl.generate('fileellipses', {})
512 508
513 509 def diffs(web, ctx, basectx, files, style, linerange=None,
514 510 lineidprefix=''):
515 511
516 512 def prettyprintlines(lines, blockno):
517 513 for lineno, l in enumerate(lines, 1):
518 514 difflineno = "%d.%d" % (blockno, lineno)
519 515 if l.startswith('+'):
520 516 ltype = "difflineplus"
521 517 elif l.startswith('-'):
522 518 ltype = "difflineminus"
523 519 elif l.startswith('@'):
524 520 ltype = "difflineat"
525 521 else:
526 522 ltype = "diffline"
527 523 yield web.tmpl.generate(ltype, {
528 524 'line': l,
529 525 'lineno': lineno,
530 526 'lineid': lineidprefix + "l%s" % difflineno,
531 527 'linenumber': "% 8s" % difflineno,
532 528 })
533 529
534 530 repo = web.repo
535 531 if files:
536 532 m = match.exact(repo.root, repo.getcwd(), files)
537 533 else:
538 534 m = match.always(repo.root, repo.getcwd())
539 535
540 536 diffopts = patch.diffopts(repo.ui, untrusted=True)
541 537 node1 = basectx.node()
542 538 node2 = ctx.node()
543 539 parity = paritygen(web.stripecount)
544 540
545 541 diffhunks = patch.diffhunks(repo, node1, node2, m, opts=diffopts)
546 542 for blockno, (fctx1, fctx2, header, hunks) in enumerate(diffhunks, 1):
547 543 if style != 'raw':
548 544 header = header[1:]
549 545 lines = [h + '\n' for h in header]
550 546 for hunkrange, hunklines in hunks:
551 547 if linerange is not None and hunkrange is not None:
552 548 s1, l1, s2, l2 = hunkrange
553 549 if not mdiff.hunkinrange((s2, l2), linerange):
554 550 continue
555 551 lines.extend(hunklines)
556 552 if lines:
557 553 yield web.tmpl.generate('diffblock', {
558 554 'parity': next(parity),
559 555 'blockno': blockno,
560 556 'lines': prettyprintlines(lines, blockno),
561 557 })
562 558
563 559 def compare(tmpl, context, leftlines, rightlines):
564 560 '''Generator function that provides side-by-side comparison data.'''
565 561
566 562 def compline(type, leftlineno, leftline, rightlineno, rightline):
567 563 lineid = leftlineno and ("l%d" % leftlineno) or ''
568 564 lineid += rightlineno and ("r%d" % rightlineno) or ''
569 565 llno = '%d' % leftlineno if leftlineno else ''
570 566 rlno = '%d' % rightlineno if rightlineno else ''
571 567 return tmpl.generate('comparisonline', {
572 568 'type': type,
573 569 'lineid': lineid,
574 570 'leftlineno': leftlineno,
575 571 'leftlinenumber': "% 6s" % llno,
576 572 'leftline': leftline or '',
577 573 'rightlineno': rightlineno,
578 574 'rightlinenumber': "% 6s" % rlno,
579 575 'rightline': rightline or '',
580 576 })
581 577
582 578 def getblock(opcodes):
583 579 for type, llo, lhi, rlo, rhi in opcodes:
584 580 len1 = lhi - llo
585 581 len2 = rhi - rlo
586 582 count = min(len1, len2)
587 583 for i in xrange(count):
588 584 yield compline(type=type,
589 585 leftlineno=llo + i + 1,
590 586 leftline=leftlines[llo + i],
591 587 rightlineno=rlo + i + 1,
592 588 rightline=rightlines[rlo + i])
593 589 if len1 > len2:
594 590 for i in xrange(llo + count, lhi):
595 591 yield compline(type=type,
596 592 leftlineno=i + 1,
597 593 leftline=leftlines[i],
598 594 rightlineno=None,
599 595 rightline=None)
600 596 elif len2 > len1:
601 597 for i in xrange(rlo + count, rhi):
602 598 yield compline(type=type,
603 599 leftlineno=None,
604 600 leftline=None,
605 601 rightlineno=i + 1,
606 602 rightline=rightlines[i])
607 603
608 604 s = difflib.SequenceMatcher(None, leftlines, rightlines)
609 605 if context < 0:
610 606 yield tmpl.generate('comparisonblock',
611 607 {'lines': getblock(s.get_opcodes())})
612 608 else:
613 609 for oc in s.get_grouped_opcodes(n=context):
614 610 yield tmpl.generate('comparisonblock', {'lines': getblock(oc)})
615 611
616 612 def diffstatgen(ctx, basectx):
617 613 '''Generator function that provides the diffstat data.'''
618 614
619 615 stats = patch.diffstatdata(
620 616 util.iterlines(ctx.diff(basectx, noprefix=False)))
621 617 maxname, maxtotal, addtotal, removetotal, binary = patch.diffstatsum(stats)
622 618 while True:
623 619 yield stats, maxname, maxtotal, addtotal, removetotal, binary
624 620
625 621 def diffsummary(statgen):
626 622 '''Return a short summary of the diff.'''
627 623
628 624 stats, maxname, maxtotal, addtotal, removetotal, binary = next(statgen)
629 625 return _(' %d files changed, %d insertions(+), %d deletions(-)\n') % (
630 626 len(stats), addtotal, removetotal)
631 627
632 628 def diffstat(tmpl, ctx, statgen, parity):
633 629 '''Return a diffstat template for each file in the diff.'''
634 630
635 631 stats, maxname, maxtotal, addtotal, removetotal, binary = next(statgen)
636 632 files = ctx.files()
637 633
638 634 def pct(i):
639 635 if maxtotal == 0:
640 636 return 0
641 637 return (float(i) / maxtotal) * 100
642 638
643 639 fileno = 0
644 640 for filename, adds, removes, isbinary in stats:
645 641 template = 'diffstatlink' if filename in files else 'diffstatnolink'
646 642 total = adds + removes
647 643 fileno += 1
648 644 yield tmpl.generate(template, {
649 645 'node': ctx.hex(),
650 646 'file': filename,
651 647 'fileno': fileno,
652 648 'total': total,
653 649 'addpct': pct(adds),
654 650 'removepct': pct(removes),
655 651 'parity': next(parity),
656 652 })
657 653
658 654 class sessionvars(templateutil.wrapped):
659 655 def __init__(self, vars, start='?'):
660 656 self._start = start
661 657 self._vars = vars
662 658
663 659 def __getitem__(self, key):
664 660 return self._vars[key]
665 661
666 662 def __setitem__(self, key, value):
667 663 self._vars[key] = value
668 664
669 665 def __copy__(self):
670 666 return sessionvars(copy.copy(self._vars), self._start)
671 667
672 668 def itermaps(self, context):
673 669 separator = self._start
674 670 for key, value in sorted(self._vars.iteritems()):
675 671 yield {'name': key,
676 672 'value': pycompat.bytestr(value),
677 673 'separator': separator,
678 674 }
679 675 separator = '&'
680 676
681 677 def join(self, context, mapping, sep):
682 678 # could be '{separator}{name}={value|urlescape}'
683 679 raise error.ParseError(_('not displayable without template'))
684 680
685 681 def show(self, context, mapping):
686 682 return self.join(context, '')
687 683
688 684 def tovalue(self, context, mapping):
689 685 return self._vars
690 686
691 687 class wsgiui(uimod.ui):
692 688 # default termwidth breaks under mod_wsgi
693 689 def termwidth(self):
694 690 return 80
695 691
696 692 def getwebsubs(repo):
697 693 websubtable = []
698 694 websubdefs = repo.ui.configitems('websub')
699 695 # we must maintain interhg backwards compatibility
700 696 websubdefs += repo.ui.configitems('interhg')
701 697 for key, pattern in websubdefs:
702 698 # grab the delimiter from the character after the "s"
703 699 unesc = pattern[1:2]
704 700 delim = re.escape(unesc)
705 701
706 702 # identify portions of the pattern, taking care to avoid escaped
707 703 # delimiters. the replace format and flags are optional, but
708 704 # delimiters are required.
709 705 match = re.match(
710 706 br'^s%s(.+)(?:(?<=\\\\)|(?<!\\))%s(.*)%s([ilmsux])*$'
711 707 % (delim, delim, delim), pattern)
712 708 if not match:
713 709 repo.ui.warn(_("websub: invalid pattern for %s: %s\n")
714 710 % (key, pattern))
715 711 continue
716 712
717 713 # we need to unescape the delimiter for regexp and format
718 714 delim_re = re.compile(br'(?<!\\)\\%s' % delim)
719 715 regexp = delim_re.sub(unesc, match.group(1))
720 716 format = delim_re.sub(unesc, match.group(2))
721 717
722 718 # the pattern allows for 6 regexp flags, so set them if necessary
723 719 flagin = match.group(3)
724 720 flags = 0
725 721 if flagin:
726 722 for flag in flagin.upper():
727 723 flags |= re.__dict__[flag]
728 724
729 725 try:
730 726 regexp = re.compile(regexp, flags)
731 727 websubtable.append((regexp, format))
732 728 except re.error:
733 729 repo.ui.warn(_("websub: invalid regexp for %s: %s\n")
734 730 % (key, regexp))
735 731 return websubtable
736 732
737 733 def getgraphnode(repo, ctx):
738 734 return (templatekw.getgraphnodecurrent(repo, ctx) +
739 735 templatekw.getgraphnodesymbol(ctx))
General Comments 0
You need to be logged in to leave comments. Login now