##// END OF EJS Templates
templater: use named function to expand template against mapping dict (API)...
Yuya Nishihara -
r37037:c97b936d default
parent child Browse files
Show More
@@ -198,7 +198,8 b' class requestcontext(object):'
198
198
199 def sendtemplate(self, name, **kwargs):
199 def sendtemplate(self, name, **kwargs):
200 """Helper function to send a response generated from a template."""
200 """Helper function to send a response generated from a template."""
201 self.res.setbodygen(self.tmpl(name, **kwargs))
201 kwargs = pycompat.byteskwargs(kwargs)
202 self.res.setbodygen(self.tmpl.generate(name, kwargs))
202 return self.res.sendresponse()
203 return self.res.sendresponse()
203
204
204 class hgweb(object):
205 class hgweb(object):
@@ -452,12 +452,12 b' class hgwebdir(object):'
452
452
453 # prefixes not found
453 # prefixes not found
454 res.status = '404 Not Found'
454 res.status = '404 Not Found'
455 res.setbodygen(tmpl('notfound', repo=virtual))
455 res.setbodygen(tmpl.generate('notfound', {'repo': virtual}))
456 return res.sendresponse()
456 return res.sendresponse()
457
457
458 except ErrorResponse as e:
458 except ErrorResponse as e:
459 res.status = statusmessage(e.code, pycompat.bytestr(e))
459 res.status = statusmessage(e.code, pycompat.bytestr(e))
460 res.setbodygen(tmpl('error', error=e.message or ''))
460 res.setbodygen(tmpl.generate('error', {'error': e.message or ''}))
461 return res.sendresponse()
461 return res.sendresponse()
462 finally:
462 finally:
463 tmpl = None
463 tmpl = None
@@ -485,15 +485,15 b' class hgwebdir(object):'
485 self.stripecount, sortcolumn=sortcolumn,
485 self.stripecount, sortcolumn=sortcolumn,
486 descending=descending, subdir=subdir)
486 descending=descending, subdir=subdir)
487
487
488 res.setbodygen(tmpl(
488 mapping = {
489 'index',
489 'entries': entries,
490 entries=entries,
490 'subdir': subdir,
491 subdir=subdir,
491 'pathdef': hgweb_mod.makebreadcrumb('/' + subdir, self.prefix),
492 pathdef=hgweb_mod.makebreadcrumb('/' + subdir, self.prefix),
492 'sortcolumn': sortcolumn,
493 sortcolumn=sortcolumn,
493 'descending': descending,
494 descending=descending,
494 }
495 **dict(sort)))
495 mapping.update(sort)
496
496 res.setbodygen(tmpl.generate('index', mapping))
497 return res.sendresponse()
497 return res.sendresponse()
498
498
499 def templater(self, req, nonce):
499 def templater(self, req, nonce):
@@ -294,12 +294,13 b' def _search(web):'
294 files = webutil.listfilediffs(web.tmpl, ctx.files(), n,
294 files = webutil.listfilediffs(web.tmpl, ctx.files(), n,
295 web.maxfiles)
295 web.maxfiles)
296
296
297 yield web.tmpl(
297 lm = webutil.commonentry(web.repo, ctx)
298 'searchentry',
298 lm.update({
299 parity=next(parity),
299 'parity': next(parity),
300 changelogtag=showtags,
300 'changelogtag': showtags,
301 files=files,
301 'files': files,
302 **pycompat.strkwargs(webutil.commonentry(web.repo, ctx)))
302 })
303 yield web.tmpl.generate('searchentry', lm)
303
304
304 if count >= revcount:
305 if count >= revcount:
305 break
306 break
@@ -719,12 +720,12 b' def summary(web):'
719 if count > 10: # limit to 10 tags
720 if count > 10: # limit to 10 tags
720 break
721 break
721
722
722 yield web.tmpl(
723 yield web.tmpl.generate('tagentry', {
723 'tagentry',
724 'parity': next(parity),
724 parity=next(parity),
725 'tag': k,
725 tag=k,
726 'node': hex(n),
726 node=hex(n),
727 'date': web.repo[n].date(),
727 date=web.repo[n].date())
728 })
728
729
729 def bookmarks(**map):
730 def bookmarks(**map):
730 parity = paritygen(web.stripecount)
731 parity = paritygen(web.stripecount)
@@ -745,11 +746,9 b' def summary(web):'
745 revs = web.repo.changelog.revs(start, end - 1)
746 revs = web.repo.changelog.revs(start, end - 1)
746 for i in revs:
747 for i in revs:
747 ctx = web.repo[i]
748 ctx = web.repo[i]
748
749 lm = webutil.commonentry(web.repo, ctx)
749 l.append(web.tmpl(
750 lm['parity'] = next(parity)
750 'shortlogentry',
751 l.append(web.tmpl.generate('shortlogentry', lm))
751 parity=next(parity),
752 **pycompat.strkwargs(webutil.commonentry(web.repo, ctx))))
753
752
754 for entry in reversed(l):
753 for entry in reversed(l):
755 yield entry
754 yield entry
@@ -243,12 +243,18 b' def nodebranchnodefault(ctx):'
243 return branches
243 return branches
244
244
245 def showtag(repo, tmpl, t1, node=nullid, **args):
245 def showtag(repo, tmpl, t1, node=nullid, **args):
246 args = pycompat.byteskwargs(args)
246 for t in repo.nodetags(node):
247 for t in repo.nodetags(node):
247 yield tmpl(t1, tag=t, **args)
248 lm = args.copy()
249 lm['tag'] = t
250 yield tmpl.generate(t1, lm)
248
251
249 def showbookmark(repo, tmpl, t1, node=nullid, **args):
252 def showbookmark(repo, tmpl, t1, node=nullid, **args):
253 args = pycompat.byteskwargs(args)
250 for t in repo.nodebookmarks(node):
254 for t in repo.nodebookmarks(node):
251 yield tmpl(t1, bookmark=t, **args)
255 lm = args.copy()
256 lm['bookmark'] = t
257 yield tmpl.generate(t1, lm)
252
258
253 def branchentries(repo, stripecount, limit=0):
259 def branchentries(repo, stripecount, limit=0):
254 tips = []
260 tips = []
@@ -443,9 +449,12 b' def changesetentry(web, ctx):'
443 parity = paritygen(web.stripecount)
449 parity = paritygen(web.stripecount)
444 for blockno, f in enumerate(ctx.files()):
450 for blockno, f in enumerate(ctx.files()):
445 template = 'filenodelink' if f in ctx else 'filenolink'
451 template = 'filenodelink' if f in ctx else 'filenolink'
446 files.append(web.tmpl(template,
452 files.append(web.tmpl.generate(template, {
447 node=ctx.hex(), file=f, blockno=blockno + 1,
453 'node': ctx.hex(),
448 parity=next(parity)))
454 'file': f,
455 'blockno': blockno + 1,
456 'parity': next(parity),
457 }))
449
458
450 basectx = basechangectx(web.repo, web.req)
459 basectx = basechangectx(web.repo, web.req)
451 if basectx is None:
460 if basectx is None:
@@ -476,9 +485,9 b' def changesetentry(web, ctx):'
476
485
477 def listfilediffs(tmpl, files, node, max):
486 def listfilediffs(tmpl, files, node, max):
478 for f in files[:max]:
487 for f in files[:max]:
479 yield tmpl('filedifflink', node=hex(node), file=f)
488 yield tmpl.generate('filedifflink', {'node': hex(node), 'file': f})
480 if len(files) > max:
489 if len(files) > max:
481 yield tmpl('fileellipses')
490 yield tmpl.generate('fileellipses', {})
482
491
483 def diffs(web, ctx, basectx, files, style, linerange=None,
492 def diffs(web, ctx, basectx, files, style, linerange=None,
484 lineidprefix=''):
493 lineidprefix=''):
@@ -494,12 +503,12 b' def diffs(web, ctx, basectx, files, styl'
494 ltype = "difflineat"
503 ltype = "difflineat"
495 else:
504 else:
496 ltype = "diffline"
505 ltype = "diffline"
497 yield web.tmpl(
506 yield web.tmpl.generate(ltype, {
498 ltype,
507 'line': l,
499 line=l,
508 'lineno': lineno,
500 lineno=lineno,
509 'lineid': lineidprefix + "l%s" % difflineno,
501 lineid=lineidprefix + "l%s" % difflineno,
510 'linenumber': "% 8s" % difflineno,
502 linenumber="% 8s" % difflineno)
511 })
503
512
504 repo = web.repo
513 repo = web.repo
505 if files:
514 if files:
@@ -524,8 +533,11 b' def diffs(web, ctx, basectx, files, styl'
524 continue
533 continue
525 lines.extend(hunklines)
534 lines.extend(hunklines)
526 if lines:
535 if lines:
527 yield web.tmpl('diffblock', parity=next(parity), blockno=blockno,
536 yield web.tmpl.generate('diffblock', {
528 lines=prettyprintlines(lines, blockno))
537 'parity': next(parity),
538 'blockno': blockno,
539 'lines': prettyprintlines(lines, blockno),
540 })
529
541
530 def compare(tmpl, context, leftlines, rightlines):
542 def compare(tmpl, context, leftlines, rightlines):
531 '''Generator function that provides side-by-side comparison data.'''
543 '''Generator function that provides side-by-side comparison data.'''
@@ -535,15 +547,16 b' def compare(tmpl, context, leftlines, ri'
535 lineid += rightlineno and ("r%d" % rightlineno) or ''
547 lineid += rightlineno and ("r%d" % rightlineno) or ''
536 llno = '%d' % leftlineno if leftlineno else ''
548 llno = '%d' % leftlineno if leftlineno else ''
537 rlno = '%d' % rightlineno if rightlineno else ''
549 rlno = '%d' % rightlineno if rightlineno else ''
538 return tmpl('comparisonline',
550 return tmpl.generate('comparisonline', {
539 type=type,
551 'type': type,
540 lineid=lineid,
552 'lineid': lineid,
541 leftlineno=leftlineno,
553 'leftlineno': leftlineno,
542 leftlinenumber="% 6s" % llno,
554 'leftlinenumber': "% 6s" % llno,
543 leftline=leftline or '',
555 'leftline': leftline or '',
544 rightlineno=rightlineno,
556 'rightlineno': rightlineno,
545 rightlinenumber="% 6s" % rlno,
557 'rightlinenumber': "% 6s" % rlno,
546 rightline=rightline or '')
558 'rightline': rightline or '',
559 })
547
560
548 def getblock(opcodes):
561 def getblock(opcodes):
549 for type, llo, lhi, rlo, rhi in opcodes:
562 for type, llo, lhi, rlo, rhi in opcodes:
@@ -573,10 +586,11 b' def compare(tmpl, context, leftlines, ri'
573
586
574 s = difflib.SequenceMatcher(None, leftlines, rightlines)
587 s = difflib.SequenceMatcher(None, leftlines, rightlines)
575 if context < 0:
588 if context < 0:
576 yield tmpl('comparisonblock', lines=getblock(s.get_opcodes()))
589 yield tmpl.generate('comparisonblock',
590 {'lines': getblock(s.get_opcodes())})
577 else:
591 else:
578 for oc in s.get_grouped_opcodes(n=context):
592 for oc in s.get_grouped_opcodes(n=context):
579 yield tmpl('comparisonblock', lines=getblock(oc))
593 yield tmpl.generate('comparisonblock', {'lines': getblock(oc)})
580
594
581 def diffstatgen(ctx, basectx):
595 def diffstatgen(ctx, basectx):
582 '''Generator function that provides the diffstat data.'''
596 '''Generator function that provides the diffstat data.'''
@@ -610,9 +624,15 b' def diffstat(tmpl, ctx, statgen, parity)'
610 template = 'diffstatlink' if filename in files else 'diffstatnolink'
624 template = 'diffstatlink' if filename in files else 'diffstatnolink'
611 total = adds + removes
625 total = adds + removes
612 fileno += 1
626 fileno += 1
613 yield tmpl(template, node=ctx.hex(), file=filename, fileno=fileno,
627 yield tmpl.generate(template, {
614 total=total, addpct=pct(adds), removepct=pct(removes),
628 'node': ctx.hex(),
615 parity=next(parity))
629 'file': filename,
630 'fileno': fileno,
631 'total': total,
632 'addpct': pct(adds),
633 'removepct': pct(removes),
634 'parity': next(parity),
635 })
616
636
617 class sessionvars(object):
637 class sessionvars(object):
618 def __init__(self, vars, start='?'):
638 def __init__(self, vars, start='?'):
@@ -478,7 +478,7 b' def showmanifest(context, mapping):'
478 mhex = hex(mnode)
478 mhex = hex(mnode)
479 mapping = mapping.copy()
479 mapping = mapping.copy()
480 mapping.update({'rev': mrev, 'node': mhex})
480 mapping.update({'rev': mrev, 'node': mhex})
481 f = templ('manifest', **pycompat.strkwargs(mapping))
481 f = templ.generate('manifest', mapping)
482 # TODO: perhaps 'ctx' should be dropped from mapping because manifest
482 # TODO: perhaps 'ctx' should be dropped from mapping because manifest
483 # rev and node are completely different from changeset's.
483 # rev and node are completely different from changeset's.
484 return _mappable(f, None, f, lambda x: {'rev': mrev, 'node': mhex})
484 return _mappable(f, None, f, lambda x: {'rev': mrev, 'node': mhex})
@@ -770,11 +770,11 b' class templater(object):'
770
770
771 def render(self, t, mapping):
771 def render(self, t, mapping):
772 """Render the specified named template and return result as string"""
772 """Render the specified named template and return result as string"""
773 mapping = pycompat.strkwargs(mapping)
773 return templateutil.stringify(self.generate(t, mapping))
774 return templateutil.stringify(self(t, **mapping))
775
774
776 def __call__(self, t, **mapping):
775 def generate(self, t, mapping):
777 mapping = pycompat.byteskwargs(mapping)
776 """Return a generator that renders the specified named template and
777 yields chunks"""
778 ttype = t in self.map and self.map[t][0] or 'default'
778 ttype = t in self.map and self.map[t][0] or 'default'
779 if ttype not in self.ecache:
779 if ttype not in self.ecache:
780 try:
780 try:
@@ -184,13 +184,12 b' def _showlist(name, values, templ, mappi'
184
184
185 expand 'end_foos'.
185 expand 'end_foos'.
186 '''
186 '''
187 strmapping = pycompat.strkwargs(mapping)
188 if not plural:
187 if not plural:
189 plural = name + 's'
188 plural = name + 's'
190 if not values:
189 if not values:
191 noname = 'no_' + plural
190 noname = 'no_' + plural
192 if noname in templ:
191 if noname in templ:
193 yield templ(noname, **strmapping)
192 yield templ.generate(noname, mapping)
194 return
193 return
195 if name not in templ:
194 if name not in templ:
196 if isinstance(values[0], bytes):
195 if isinstance(values[0], bytes):
@@ -203,7 +202,7 b' def _showlist(name, values, templ, mappi'
203 return
202 return
204 startname = 'start_' + plural
203 startname = 'start_' + plural
205 if startname in templ:
204 if startname in templ:
206 yield templ(startname, **strmapping)
205 yield templ.generate(startname, mapping)
207 vmapping = mapping.copy()
206 vmapping = mapping.copy()
208 def one(v, tag=name):
207 def one(v, tag=name):
209 try:
208 try:
@@ -218,7 +217,7 b' def _showlist(name, values, templ, mappi'
218 vmapping[a] = b
217 vmapping[a] = b
219 except (TypeError, ValueError):
218 except (TypeError, ValueError):
220 vmapping[name] = v
219 vmapping[name] = v
221 return templ(tag, **pycompat.strkwargs(vmapping))
220 return templ.generate(tag, vmapping)
222 lastname = 'last_' + name
221 lastname = 'last_' + name
223 if lastname in templ:
222 if lastname in templ:
224 last = values.pop()
223 last = values.pop()
@@ -230,7 +229,7 b' def _showlist(name, values, templ, mappi'
230 yield one(last, tag=lastname)
229 yield one(last, tag=lastname)
231 endname = 'end_' + plural
230 endname = 'end_' + plural
232 if endname in templ:
231 if endname in templ:
233 yield templ(endname, **strmapping)
232 yield templ.generate(endname, mapping)
234
233
235 def stringify(thing):
234 def stringify(thing):
236 """Turn values into bytes by converting into text and concatenating them"""
235 """Turn values into bytes by converting into text and concatenating them"""
General Comments 0
You need to be logged in to leave comments. Login now