comparison mercurial/templatekw.py @ 34328:dd28b1f55eb8

templatekw: just pass underlying value (or key) to joinfmt() function Before, iter(hybrid) was proxied to hybrid.gen, which generated formatted strings. That's why we had to apply joinfmt() to the dicts generated by hybrid.itermaps(). Since this weird API was fixed at a0f2d83f8083, we can get rid of the makemap() calls from join().
author Yuya Nishihara <yuya@tcha.org>
date Sun, 24 Sep 2017 15:22:46 +0900
parents 4647e0a8d3d7
children 89aec1834a86
comparison
equal deleted inserted replaced
34327:4647e0a8d3d7 34328:dd28b1f55eb8
46 @util.propertycache 46 @util.propertycache
47 def gen(self): 47 def gen(self):
48 return self._defaultgen() 48 return self._defaultgen()
49 def _defaultgen(self): 49 def _defaultgen(self):
50 """Generator to stringify this as {join(self, ' ')}""" 50 """Generator to stringify this as {join(self, ' ')}"""
51 for i, d in enumerate(self.itermaps()): 51 for i, x in enumerate(self._values):
52 if i > 0: 52 if i > 0:
53 yield ' ' 53 yield ' '
54 yield self.joinfmt(d) 54 yield self.joinfmt(x)
55 def itermaps(self): 55 def itermaps(self):
56 makemap = self._makemap 56 makemap = self._makemap
57 for x in self._values: 57 for x in self._values:
58 yield makemap(x) 58 yield makemap(x)
59 def __contains__(self, x): 59 def __contains__(self, x):
71 return getattr(self._values, name) 71 return getattr(self._values, name)
72 72
73 def hybriddict(data, key='key', value='value', fmt='%s=%s', gen=None): 73 def hybriddict(data, key='key', value='value', fmt='%s=%s', gen=None):
74 """Wrap data to support both dict-like and string-like operations""" 74 """Wrap data to support both dict-like and string-like operations"""
75 return _hybrid(gen, data, lambda k: {key: k, value: data[k]}, 75 return _hybrid(gen, data, lambda k: {key: k, value: data[k]},
76 lambda d: fmt % (d[key], d[value])) 76 lambda k: fmt % (k, data[k]))
77 77
78 def hybridlist(data, name, fmt='%s', gen=None): 78 def hybridlist(data, name, fmt='%s', gen=None):
79 """Wrap data to support both list-like and string-like operations""" 79 """Wrap data to support both list-like and string-like operations"""
80 return _hybrid(gen, data, lambda x: {name: x}, lambda d: fmt % d[name]) 80 return _hybrid(gen, data, lambda x: {name: x}, lambda x: fmt % x)
81 81
82 def unwraphybrid(thing): 82 def unwraphybrid(thing):
83 """Return an object which can be stringified possibly by using a legacy 83 """Return an object which can be stringified possibly by using a legacy
84 template""" 84 template"""
85 if not util.safehasattr(thing, 'gen'): 85 if not util.safehasattr(thing, 'gen'):
313 repo = args['ctx']._repo 313 repo = args['ctx']._repo
314 bookmarks = args['ctx'].bookmarks() 314 bookmarks = args['ctx'].bookmarks()
315 active = repo._activebookmark 315 active = repo._activebookmark
316 makemap = lambda v: {'bookmark': v, 'active': active, 'current': active} 316 makemap = lambda v: {'bookmark': v, 'active': active, 'current': active}
317 f = _showlist('bookmark', bookmarks, args) 317 f = _showlist('bookmark', bookmarks, args)
318 return _hybrid(f, bookmarks, makemap, lambda x: x['bookmark']) 318 return _hybrid(f, bookmarks, makemap, pycompat.identity)
319 319
320 @templatekeyword('children') 320 @templatekeyword('children')
321 def showchildren(**args): 321 def showchildren(**args):
322 """List of strings. The children of the changeset.""" 322 """List of strings. The children of the changeset."""
323 args = pycompat.byteskwargs(args) 323 args = pycompat.byteskwargs(args)
382 extras = util.sortdict((k, extras[k]) for k in sorted(extras)) 382 extras = util.sortdict((k, extras[k]) for k in sorted(extras))
383 makemap = lambda k: {'key': k, 'value': extras[k]} 383 makemap = lambda k: {'key': k, 'value': extras[k]}
384 c = [makemap(k) for k in extras] 384 c = [makemap(k) for k in extras]
385 f = _showlist('extra', c, args, plural='extras') 385 f = _showlist('extra', c, args, plural='extras')
386 return _hybrid(f, extras, makemap, 386 return _hybrid(f, extras, makemap,
387 lambda x: '%s=%s' % (x['key'], util.escapestr(x['value']))) 387 lambda k: '%s=%s' % (k, util.escapestr(extras[k])))
388 388
389 @templatekeyword('file_adds') 389 @templatekeyword('file_adds')
390 def showfileadds(**args): 390 def showfileadds(**args):
391 """List of strings. Files added by this changeset.""" 391 """List of strings. Files added by this changeset."""
392 args = pycompat.byteskwargs(args) 392 args = pycompat.byteskwargs(args)
508 'tag': v 508 'tag': v
509 } 509 }
510 510
511 tags = latesttags[2] 511 tags = latesttags[2]
512 f = _showlist('latesttag', tags, args, separator=':') 512 f = _showlist('latesttag', tags, args, separator=':')
513 return _hybrid(f, tags, makemap, lambda x: x['latesttag']) 513 return _hybrid(f, tags, makemap, pycompat.identity)
514 514
515 @templatekeyword('latesttagdistance') 515 @templatekeyword('latesttagdistance')
516 def showlatesttagdistance(repo, ctx, templ, cache, **args): 516 def showlatesttagdistance(repo, ctx, templ, cache, **args):
517 """Integer. Longest path to the latest tag.""" 517 """Integer. Longest path to the latest tag."""
518 return getlatesttags(repo, ctx, cache)[1] 518 return getlatesttags(repo, ctx, cache)[1]
582 'names': namespaces[ns], 582 'names': namespaces[ns],
583 'builtin': builtins[ns], 583 'builtin': builtins[ns],
584 'colorname': colornames[ns], 584 'colorname': colornames[ns],
585 } 585 }
586 586
587 return _hybrid(f, namespaces, makemap, lambda x: x['namespace']) 587 return _hybrid(f, namespaces, makemap, pycompat.identity)
588 588
589 @templatekeyword('node') 589 @templatekeyword('node')
590 def shownode(repo, ctx, templ, **args): 590 def shownode(repo, ctx, templ, **args):
591 """String. The changeset identification hash, as a 40 hexadecimal 591 """String. The changeset identification hash, as a 40 hexadecimal
592 digit string. 592 digit string.
616 paths[k] = hybriddict(d, gen=f()) 616 paths[k] = hybriddict(d, gen=f())
617 617
618 # no hybriddict() since d['path'] can't be formatted as a string. perhaps 618 # no hybriddict() since d['path'] can't be formatted as a string. perhaps
619 # hybriddict() should call templatefilters.stringify(d[value]). 619 # hybriddict() should call templatefilters.stringify(d[value]).
620 return _hybrid(None, paths, lambda k: {'name': k, 'path': paths[k]}, 620 return _hybrid(None, paths, lambda k: {'name': k, 'path': paths[k]},
621 lambda d: '%s=%s' % (d['name'], d['path']['url'])) 621 lambda k: '%s=%s' % (k, paths[k]['url']))
622 622
623 @templatekeyword("predecessors") 623 @templatekeyword("predecessors")
624 def showpredecessors(repo, ctx, **args): 624 def showpredecessors(repo, ctx, **args):
625 """Returns the list if the closest visible successors 625 """Returns the list if the closest visible successors
626 """ 626 """
627 predecessors = sorted(obsutil.closestpredecessors(repo, ctx.node())) 627 predecessors = sorted(obsutil.closestpredecessors(repo, ctx.node()))
628 predecessors = map(hex, predecessors) 628 predecessors = map(hex, predecessors)
629 629
630 return _hybrid(None, predecessors, 630 return _hybrid(None, predecessors,
631 lambda x: {'ctx': repo[x], 'revcache': {}}, 631 lambda x: {'ctx': repo[x], 'revcache': {}},
632 lambda d: scmutil.formatchangeid(d['ctx'])) 632 lambda x: scmutil.formatchangeid(repo[x]))
633 633
634 @templatekeyword("successorssets") 634 @templatekeyword("successorssets")
635 def showsuccessorssets(repo, ctx, **args): 635 def showsuccessorssets(repo, ctx, **args):
636 """Returns a string of sets of successors for a changectx 636 """Returns a string of sets of successors for a changectx
637 637
645 ssets = [[hex(n) for n in ss] for ss in ssets] 645 ssets = [[hex(n) for n in ss] for ss in ssets]
646 646
647 data = [] 647 data = []
648 for ss in ssets: 648 for ss in ssets:
649 h = _hybrid(None, ss, lambda x: {'ctx': repo[x], 'revcache': {}}, 649 h = _hybrid(None, ss, lambda x: {'ctx': repo[x], 'revcache': {}},
650 lambda d: scmutil.formatchangeid(d['ctx'])) 650 lambda x: scmutil.formatchangeid(repo[x]))
651 data.append(h) 651 data.append(h)
652 652
653 # Format the successorssets 653 # Format the successorssets
654 def render(d): 654 def render(d):
655 t = [] 655 t = []
659 659
660 def gen(data): 660 def gen(data):
661 yield "; ".join(render(d) for d in data) 661 yield "; ".join(render(d) for d in data)
662 662
663 return _hybrid(gen(data), data, lambda x: {'successorset': x}, 663 return _hybrid(gen(data), data, lambda x: {'successorset': x},
664 lambda d: d["successorset"]) 664 pycompat.identity)
665 665
666 @templatekeyword("succsandmarkers") 666 @templatekeyword("succsandmarkers")
667 def showsuccsandmarkers(repo, ctx, **args): 667 def showsuccsandmarkers(repo, ctx, **args):
668 """Returns a list of dict for each final successor of ctx. 668 """Returns a list of dict for each final successor of ctx.
669 669
685 successors = i['successors'] 685 successors = i['successors']
686 686
687 successors = [hex(n) for n in successors] 687 successors = [hex(n) for n in successors]
688 successors = _hybrid(None, successors, 688 successors = _hybrid(None, successors,
689 lambda x: {'ctx': repo[x], 'revcache': {}}, 689 lambda x: {'ctx': repo[x], 'revcache': {}},
690 lambda d: scmutil.formatchangeid(d['ctx'])) 690 lambda x: scmutil.formatchangeid(repo[x]))
691 691
692 # Format markers 692 # Format markers
693 finalmarkers = [] 693 finalmarkers = []
694 for m in i['markers']: 694 for m in i['markers']:
695 hexprec = hex(m[0]) 695 hexprec = hex(m[0])
701 finalmarkers.append(newmarker) 701 finalmarkers.append(newmarker)
702 702
703 data.append({'successors': successors, 'markers': finalmarkers}) 703 data.append({'successors': successors, 'markers': finalmarkers})
704 704
705 f = _showlist('succsandmarkers', data, args) 705 f = _showlist('succsandmarkers', data, args)
706 return _hybrid(f, data, lambda x: x, lambda d: d) 706 return _hybrid(f, data, lambda x: x, pycompat.identity)
707 707
708 @templatekeyword('p1rev') 708 @templatekeyword('p1rev')
709 def showp1rev(repo, ctx, templ, **args): 709 def showp1rev(repo, ctx, templ, **args):
710 """Integer. The repository-local revision number of the changeset's 710 """Integer. The repository-local revision number of the changeset's
711 first parent, or -1 if the changeset has no parents.""" 711 first parent, or -1 if the changeset has no parents."""
746 ('node', p.hex()), 746 ('node', p.hex()),
747 ('phase', p.phasestr())] 747 ('phase', p.phasestr())]
748 for p in pctxs] 748 for p in pctxs]
749 f = _showlist('parent', parents, args) 749 f = _showlist('parent', parents, args)
750 return _hybrid(f, prevs, lambda x: {'ctx': repo[int(x)], 'revcache': {}}, 750 return _hybrid(f, prevs, lambda x: {'ctx': repo[int(x)], 'revcache': {}},
751 lambda d: scmutil.formatchangeid(d['ctx'])) 751 lambda x: scmutil.formatchangeid(repo[int(x)]))
752 752
753 @templatekeyword('phase') 753 @templatekeyword('phase')
754 def showphase(repo, ctx, templ, **args): 754 def showphase(repo, ctx, templ, **args):
755 """String. The changeset phase name.""" 755 """String. The changeset phase name."""
756 return ctx.phasestr() 756 return ctx.phasestr()
773 # ifcontains() needs a list of str 773 # ifcontains() needs a list of str
774 revs = ["%d" % r for r in revs] 774 revs = ["%d" % r for r in revs]
775 f = _showlist(name, revs, args) 775 f = _showlist(name, revs, args)
776 return _hybrid(f, revs, 776 return _hybrid(f, revs,
777 lambda x: {name: x, 'ctx': repo[int(x)], 'revcache': {}}, 777 lambda x: {name: x, 'ctx': repo[int(x)], 'revcache': {}},
778 lambda d: d[name]) 778 pycompat.identity)
779 779
780 @templatekeyword('subrepos') 780 @templatekeyword('subrepos')
781 def showsubrepos(**args): 781 def showsubrepos(**args):
782 """List of strings. Updated subrepositories in the changeset.""" 782 """List of strings. Updated subrepositories in the changeset."""
783 args = pycompat.byteskwargs(args) 783 args = pycompat.byteskwargs(args)