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