comparison mercurial/formatter.py @ 31807:e6eb86b154c5

templater: provide loop counter as "index" keyword This was originally written for JSON templating where we would have to be careful to not add extra comma, but seems generally useful. Inner loop started by % operator has its own counter.
author Yuya Nishihara <yuya@tcha.org>
date Fri, 22 Apr 2016 21:46:33 +0900
parents dca9b6922514
children 21f129354dd0
comparison
equal deleted inserted replaced
31806:8f203b491bb5 31807:e6eb86b154c5
101 baz: foo, bar 101 baz: foo, bar
102 """ 102 """
103 103
104 from __future__ import absolute_import 104 from __future__ import absolute_import
105 105
106 import itertools
106 import os 107 import os
107 108
108 from .i18n import _ 109 from .i18n import _
109 from .node import ( 110 from .node import (
110 hex, 111 hex,
336 baseformatter.__init__(self, ui, topic, opts, _templateconverter) 337 baseformatter.__init__(self, ui, topic, opts, _templateconverter)
337 self._out = out 338 self._out = out
338 self._topic = topic 339 self._topic = topic
339 self._t = gettemplater(ui, topic, opts.get('template', ''), 340 self._t = gettemplater(ui, topic, opts.get('template', ''),
340 cache=templatekw.defaulttempl) 341 cache=templatekw.defaulttempl)
342 self._counter = itertools.count()
341 self._cache = {} # for templatekw/funcs to store reusable data 343 self._cache = {} # for templatekw/funcs to store reusable data
342 def context(self, **ctxs): 344 def context(self, **ctxs):
343 '''insert context objects to be used to render template keywords''' 345 '''insert context objects to be used to render template keywords'''
344 assert all(k == 'ctx' for k in ctxs) 346 assert all(k == 'ctx' for k in ctxs)
345 self._item.update(ctxs) 347 self._item.update(ctxs)
348 # function will have to declare dependent resources. e.g. 350 # function will have to declare dependent resources. e.g.
349 # @templatekeyword(..., requires=('ctx',)) 351 # @templatekeyword(..., requires=('ctx',))
350 props = {} 352 props = {}
351 if 'ctx' in self._item: 353 if 'ctx' in self._item:
352 props.update(templatekw.keywords) 354 props.update(templatekw.keywords)
355 props['index'] = next(self._counter)
353 # explicitly-defined fields precede templatekw 356 # explicitly-defined fields precede templatekw
354 props.update(self._item) 357 props.update(self._item)
355 if 'ctx' in self._item: 358 if 'ctx' in self._item:
356 # but template resources must be always available 359 # but template resources must be always available
357 props['templ'] = self._t 360 props['templ'] = self._t