2012-02-21 02:42:47 +04:00
|
|
|
# formatter.py - generic output formatting for mercurial
|
|
|
|
#
|
|
|
|
# Copyright 2012 Matt Mackall <mpm@selenic.com>
|
|
|
|
#
|
|
|
|
# This software may be used and distributed according to the terms of the
|
|
|
|
# GNU General Public License version 2 or any later version.
|
|
|
|
|
2016-10-22 09:02:11 +03:00
|
|
|
"""Generic output formatting for Mercurial
|
|
|
|
|
|
|
|
The formatter provides API to show data in various ways. The following
|
|
|
|
functions should be used in place of ui.write():
|
|
|
|
|
|
|
|
- fm.write() for unconditional output
|
|
|
|
- fm.condwrite() to show some extra data conditionally in plain output
|
2017-02-25 11:00:07 +03:00
|
|
|
- fm.context() to provide changectx to template output
|
2016-10-22 09:02:11 +03:00
|
|
|
- fm.data() to provide extra data to JSON or template output
|
|
|
|
- fm.plain() to show raw text that isn't provided to JSON or template output
|
|
|
|
|
|
|
|
To show structured data (e.g. date tuples, dicts, lists), apply fm.format*()
|
|
|
|
beforehand so the data is converted to the appropriate data type. Use
|
|
|
|
fm.isplain() if you need to convert or format data conditionally which isn't
|
|
|
|
supported by the formatter API.
|
|
|
|
|
|
|
|
To build nested structure (i.e. a list of dicts), use fm.nested().
|
|
|
|
|
|
|
|
See also https://www.mercurial-scm.org/wiki/GenericTemplatingPlan
|
|
|
|
|
|
|
|
fm.condwrite() vs 'if cond:':
|
|
|
|
|
|
|
|
In most cases, use fm.condwrite() so users can selectively show the data
|
|
|
|
in template output. If it's costly to build data, use plain 'if cond:' with
|
|
|
|
fm.write().
|
|
|
|
|
|
|
|
fm.nested() vs fm.formatdict() (or fm.formatlist()):
|
|
|
|
|
|
|
|
fm.nested() should be used to form a tree structure (a list of dicts of
|
|
|
|
lists of dicts...) which can be accessed through template keywords, e.g.
|
|
|
|
"{foo % "{bar % {...}} {baz % {...}}"}". On the other hand, fm.formatdict()
|
|
|
|
exports a dict-type object to template, which can be accessed by e.g.
|
|
|
|
"{get(foo, key)}" function.
|
|
|
|
|
|
|
|
Doctest helper:
|
|
|
|
|
|
|
|
>>> def show(fn, verbose=False, **opts):
|
|
|
|
... import sys
|
|
|
|
... from . import ui as uimod
|
|
|
|
... ui = uimod.ui()
|
|
|
|
... ui.fout = sys.stdout # redirect to doctest
|
|
|
|
... ui.verbose = verbose
|
|
|
|
... return fn(ui, ui.formatter(fn.__name__, opts))
|
|
|
|
|
|
|
|
Basic example:
|
|
|
|
|
|
|
|
>>> def files(ui, fm):
|
|
|
|
... files = [('foo', 123, (0, 0)), ('bar', 456, (1, 0))]
|
|
|
|
... for f in files:
|
|
|
|
... fm.startitem()
|
|
|
|
... fm.write('path', '%s', f[0])
|
|
|
|
... fm.condwrite(ui.verbose, 'date', ' %s',
|
|
|
|
... fm.formatdate(f[2], '%Y-%m-%d %H:%M:%S'))
|
|
|
|
... fm.data(size=f[1])
|
|
|
|
... fm.plain('\\n')
|
|
|
|
... fm.end()
|
|
|
|
>>> show(files)
|
|
|
|
foo
|
|
|
|
bar
|
|
|
|
>>> show(files, verbose=True)
|
|
|
|
foo 1970-01-01 00:00:00
|
|
|
|
bar 1970-01-01 00:00:01
|
|
|
|
>>> show(files, template='json')
|
|
|
|
[
|
|
|
|
{
|
|
|
|
"date": [0, 0],
|
|
|
|
"path": "foo",
|
|
|
|
"size": 123
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"date": [1, 0],
|
|
|
|
"path": "bar",
|
|
|
|
"size": 456
|
|
|
|
}
|
|
|
|
]
|
|
|
|
>>> show(files, template='path: {path}\\ndate: {date|rfc3339date}\\n')
|
|
|
|
path: foo
|
|
|
|
date: 1970-01-01T00:00:00+00:00
|
|
|
|
path: bar
|
|
|
|
date: 1970-01-01T00:00:01+00:00
|
|
|
|
|
|
|
|
Nested example:
|
|
|
|
|
|
|
|
>>> def subrepos(ui, fm):
|
|
|
|
... fm.startitem()
|
|
|
|
... fm.write('repo', '[%s]\\n', 'baz')
|
|
|
|
... files(ui, fm.nested('files'))
|
|
|
|
... fm.end()
|
|
|
|
>>> show(subrepos)
|
|
|
|
[baz]
|
|
|
|
foo
|
|
|
|
bar
|
|
|
|
>>> show(subrepos, template='{repo}: {join(files % "{path}", ", ")}\\n')
|
|
|
|
baz: foo, bar
|
|
|
|
"""
|
|
|
|
|
2015-08-09 05:17:40 +03:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2015-06-10 22:29:13 +03:00
|
|
|
import os
|
2014-09-13 03:29:29 +04:00
|
|
|
|
2015-08-09 05:17:40 +03:00
|
|
|
from .i18n import _
|
|
|
|
from .node import (
|
|
|
|
hex,
|
|
|
|
short,
|
|
|
|
)
|
|
|
|
|
|
|
|
from . import (
|
|
|
|
encoding,
|
2015-10-08 22:55:45 +03:00
|
|
|
error,
|
formatter: add function to convert list to appropriate format (issue5217)
Before, it wasn't possible for formatter to handle array structure other
than date tuple. We've discussed that at the last sprint, which ended we
would probably want to allow only templatable data structure, i.e. a list
of dicts:
data(tags=[{'tag': a}, {'tag': b}, ...])
Unfortunately, it turned out not working well with template functions:
"{ifcontains(a, tags, ...)}"
^^^^^^^^^^^^^^^^^^
"a in tags", where tags should be a plain list/set of tags
So the formatter must at least know if the type [{}] was constructed from
a plain list or was actually a list of dicts.
This patch introduces new explicit interface to convert an array structure
to an appropriate data type for the current formatter, which can be used
as follows:
fm.write('tags', _('tags: %s\n'), fm.formatlist(tags, name='tag'))
No separate fm.data() call should be necessary.
2016-07-10 15:03:06 +03:00
|
|
|
templatekw,
|
2015-08-09 05:17:40 +03:00
|
|
|
templater,
|
2016-06-04 12:08:00 +03:00
|
|
|
util,
|
2015-08-09 05:17:40 +03:00
|
|
|
)
|
|
|
|
|
2016-06-04 12:08:00 +03:00
|
|
|
pickle = util.pickle
|
|
|
|
|
2016-08-15 07:51:14 +03:00
|
|
|
class _nullconverter(object):
|
|
|
|
'''convert non-primitive data types to be processed by formatter'''
|
|
|
|
@staticmethod
|
|
|
|
def formatdate(date, fmt):
|
|
|
|
'''convert date tuple to appropriate format'''
|
|
|
|
return date
|
|
|
|
@staticmethod
|
|
|
|
def formatdict(data, key, value, fmt, sep):
|
|
|
|
'''convert dict or key-value pairs to appropriate dict format'''
|
|
|
|
# use plain dict instead of util.sortdict so that data can be
|
|
|
|
# serialized as a builtin dict in pickle output
|
|
|
|
return dict(data)
|
|
|
|
@staticmethod
|
|
|
|
def formatlist(data, name, fmt, sep):
|
|
|
|
'''convert iterable to appropriate list format'''
|
|
|
|
return list(data)
|
|
|
|
|
2012-02-21 02:42:47 +04:00
|
|
|
class baseformatter(object):
|
2016-08-15 07:51:14 +03:00
|
|
|
def __init__(self, ui, topic, opts, converter):
|
2012-02-21 02:42:47 +04:00
|
|
|
self._ui = ui
|
|
|
|
self._topic = topic
|
|
|
|
self._style = opts.get("style")
|
|
|
|
self._template = opts.get("template")
|
2016-08-15 07:51:14 +03:00
|
|
|
self._converter = converter
|
2012-02-21 02:42:47 +04:00
|
|
|
self._item = None
|
2014-10-03 17:20:02 +04:00
|
|
|
# function to convert node to string suitable for this output
|
|
|
|
self.hexfunc = hex
|
2016-08-28 18:00:05 +03:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
def __exit__(self, exctype, excvalue, traceback):
|
|
|
|
if exctype is None:
|
|
|
|
self.end()
|
2012-02-21 02:42:47 +04:00
|
|
|
def _showitem(self):
|
|
|
|
'''show a formatted item once all data is collected'''
|
|
|
|
pass
|
|
|
|
def startitem(self):
|
|
|
|
'''begin an item in the format list'''
|
|
|
|
if self._item is not None:
|
|
|
|
self._showitem()
|
|
|
|
self._item = {}
|
2016-08-15 07:51:14 +03:00
|
|
|
def formatdate(self, date, fmt='%a %b %d %H:%M:%S %Y %1%2'):
|
2016-07-31 11:07:29 +03:00
|
|
|
'''convert date tuple to appropriate format'''
|
2016-08-15 07:51:14 +03:00
|
|
|
return self._converter.formatdate(date, fmt)
|
|
|
|
def formatdict(self, data, key='key', value='value', fmt='%s=%s', sep=' '):
|
2016-08-15 06:58:33 +03:00
|
|
|
'''convert dict or key-value pairs to appropriate dict format'''
|
2016-08-15 07:51:14 +03:00
|
|
|
return self._converter.formatdict(data, key, value, fmt, sep)
|
|
|
|
def formatlist(self, data, name, fmt='%s', sep=' '):
|
formatter: add function to convert list to appropriate format (issue5217)
Before, it wasn't possible for formatter to handle array structure other
than date tuple. We've discussed that at the last sprint, which ended we
would probably want to allow only templatable data structure, i.e. a list
of dicts:
data(tags=[{'tag': a}, {'tag': b}, ...])
Unfortunately, it turned out not working well with template functions:
"{ifcontains(a, tags, ...)}"
^^^^^^^^^^^^^^^^^^
"a in tags", where tags should be a plain list/set of tags
So the formatter must at least know if the type [{}] was constructed from
a plain list or was actually a list of dicts.
This patch introduces new explicit interface to convert an array structure
to an appropriate data type for the current formatter, which can be used
as follows:
fm.write('tags', _('tags: %s\n'), fm.formatlist(tags, name='tag'))
No separate fm.data() call should be necessary.
2016-07-10 15:03:06 +03:00
|
|
|
'''convert iterable to appropriate list format'''
|
2016-08-15 07:51:14 +03:00
|
|
|
# name is mandatory argument for now, but it could be optional if
|
|
|
|
# we have default template keyword, e.g. {item}
|
|
|
|
return self._converter.formatlist(data, name, fmt, sep)
|
2017-02-25 11:00:07 +03:00
|
|
|
def context(self, **ctxs):
|
|
|
|
'''insert context objects to be used to render template keywords'''
|
|
|
|
pass
|
2012-02-21 02:42:47 +04:00
|
|
|
def data(self, **data):
|
|
|
|
'''insert data into item that's not shown in default output'''
|
2012-09-21 07:30:59 +04:00
|
|
|
self._item.update(data)
|
2012-02-21 02:42:47 +04:00
|
|
|
def write(self, fields, deftext, *fielddata, **opts):
|
|
|
|
'''do default text output while assigning data to item'''
|
2015-09-23 15:51:48 +03:00
|
|
|
fieldkeys = fields.split()
|
|
|
|
assert len(fieldkeys) == len(fielddata)
|
2015-09-23 15:54:47 +03:00
|
|
|
self._item.update(zip(fieldkeys, fielddata))
|
2012-11-03 23:37:50 +04:00
|
|
|
def condwrite(self, cond, fields, deftext, *fielddata, **opts):
|
|
|
|
'''do conditional write (primarily for plain formatter)'''
|
2015-09-23 15:51:48 +03:00
|
|
|
fieldkeys = fields.split()
|
|
|
|
assert len(fieldkeys) == len(fielddata)
|
2015-09-23 15:54:47 +03:00
|
|
|
self._item.update(zip(fieldkeys, fielddata))
|
2012-02-21 02:42:47 +04:00
|
|
|
def plain(self, text, **opts):
|
|
|
|
'''show raw text for non-templated mode'''
|
|
|
|
pass
|
2016-08-29 18:19:09 +03:00
|
|
|
def isplain(self):
|
|
|
|
'''check for plain formatter usage'''
|
|
|
|
return False
|
formatter: add fm.nested(field) to either write or build sub items
We sometimes need to build nested items by formatter, but there was no
convenient way other than building and putting them manually by fm.data():
exts = []
for n, v in extensions:
fm.plain('%s %s\n' % (n, v))
exts.append({'name': n, 'ver': v})
fm.data(extensions=exts)
This should work for simple cases, but doing this would make it harder to
change the underlying data type for better templating support.
So this patch provides fm.nested(field), which returns new nested formatter
(or self if items aren't structured and just written to ui.) A nested formatter
stores items which will later be rendered by the parent formatter.
fn = fm.nested('extensions')
for n, v in extensions:
fn.startitem()
fn.write('name ver', '%s %s\n', n, v)
fn.end()
Nested items are directly exported to a template for now:
{extensions % "{name} {ver}\n"}
There's no {extensions} nor {join(extensions, sep)} yet. I have a plan for
them by extending fm.nested() API, but I want to revisit it after trying
out this API in the real world.
2016-03-13 13:59:39 +03:00
|
|
|
def nested(self, field):
|
|
|
|
'''sub formatter to store nested data in the specified field'''
|
|
|
|
self._item[field] = data = []
|
|
|
|
return _nestedformatter(self._ui, self._converter, data)
|
2012-02-21 02:42:47 +04:00
|
|
|
def end(self):
|
|
|
|
'''end output for the formatter'''
|
|
|
|
if self._item is not None:
|
|
|
|
self._showitem()
|
|
|
|
|
formatter: add fm.nested(field) to either write or build sub items
We sometimes need to build nested items by formatter, but there was no
convenient way other than building and putting them manually by fm.data():
exts = []
for n, v in extensions:
fm.plain('%s %s\n' % (n, v))
exts.append({'name': n, 'ver': v})
fm.data(extensions=exts)
This should work for simple cases, but doing this would make it harder to
change the underlying data type for better templating support.
So this patch provides fm.nested(field), which returns new nested formatter
(or self if items aren't structured and just written to ui.) A nested formatter
stores items which will later be rendered by the parent formatter.
fn = fm.nested('extensions')
for n, v in extensions:
fn.startitem()
fn.write('name ver', '%s %s\n', n, v)
fn.end()
Nested items are directly exported to a template for now:
{extensions % "{name} {ver}\n"}
There's no {extensions} nor {join(extensions, sep)} yet. I have a plan for
them by extending fm.nested() API, but I want to revisit it after trying
out this API in the real world.
2016-03-13 13:59:39 +03:00
|
|
|
class _nestedformatter(baseformatter):
|
|
|
|
'''build sub items and store them in the parent formatter'''
|
|
|
|
def __init__(self, ui, converter, data):
|
|
|
|
baseformatter.__init__(self, ui, topic='', opts={}, converter=converter)
|
|
|
|
self._data = data
|
|
|
|
def _showitem(self):
|
|
|
|
self._data.append(self._item)
|
|
|
|
|
2016-08-15 06:58:33 +03:00
|
|
|
def _iteritems(data):
|
|
|
|
'''iterate key-value pairs in stable order'''
|
|
|
|
if isinstance(data, dict):
|
|
|
|
return sorted(data.iteritems())
|
|
|
|
return data
|
|
|
|
|
2016-08-15 07:51:14 +03:00
|
|
|
class _plainconverter(object):
|
|
|
|
'''convert non-primitive data types to text'''
|
|
|
|
@staticmethod
|
|
|
|
def formatdate(date, fmt):
|
|
|
|
'''stringify date tuple in the given format'''
|
|
|
|
return util.datestr(date, fmt)
|
|
|
|
@staticmethod
|
|
|
|
def formatdict(data, key, value, fmt, sep):
|
|
|
|
'''stringify key-value pairs separated by sep'''
|
|
|
|
return sep.join(fmt % (k, v) for k, v in _iteritems(data))
|
|
|
|
@staticmethod
|
|
|
|
def formatlist(data, name, fmt, sep):
|
|
|
|
'''stringify iterable separated by sep'''
|
|
|
|
return sep.join(fmt % e for e in data)
|
|
|
|
|
2012-02-21 02:42:47 +04:00
|
|
|
class plainformatter(baseformatter):
|
|
|
|
'''the default text output scheme'''
|
|
|
|
def __init__(self, ui, topic, opts):
|
2016-08-15 07:51:14 +03:00
|
|
|
baseformatter.__init__(self, ui, topic, opts, _plainconverter)
|
2014-10-03 17:20:02 +04:00
|
|
|
if ui.debugflag:
|
|
|
|
self.hexfunc = hex
|
|
|
|
else:
|
|
|
|
self.hexfunc = short
|
2012-02-21 02:42:47 +04:00
|
|
|
def startitem(self):
|
|
|
|
pass
|
|
|
|
def data(self, **data):
|
|
|
|
pass
|
|
|
|
def write(self, fields, deftext, *fielddata, **opts):
|
|
|
|
self._ui.write(deftext % fielddata, **opts)
|
2012-11-03 23:37:50 +04:00
|
|
|
def condwrite(self, cond, fields, deftext, *fielddata, **opts):
|
|
|
|
'''do conditional write'''
|
|
|
|
if cond:
|
|
|
|
self._ui.write(deftext % fielddata, **opts)
|
2012-02-21 02:42:47 +04:00
|
|
|
def plain(self, text, **opts):
|
|
|
|
self._ui.write(text, **opts)
|
2016-08-29 18:19:09 +03:00
|
|
|
def isplain(self):
|
|
|
|
return True
|
formatter: add fm.nested(field) to either write or build sub items
We sometimes need to build nested items by formatter, but there was no
convenient way other than building and putting them manually by fm.data():
exts = []
for n, v in extensions:
fm.plain('%s %s\n' % (n, v))
exts.append({'name': n, 'ver': v})
fm.data(extensions=exts)
This should work for simple cases, but doing this would make it harder to
change the underlying data type for better templating support.
So this patch provides fm.nested(field), which returns new nested formatter
(or self if items aren't structured and just written to ui.) A nested formatter
stores items which will later be rendered by the parent formatter.
fn = fm.nested('extensions')
for n, v in extensions:
fn.startitem()
fn.write('name ver', '%s %s\n', n, v)
fn.end()
Nested items are directly exported to a template for now:
{extensions % "{name} {ver}\n"}
There's no {extensions} nor {join(extensions, sep)} yet. I have a plan for
them by extending fm.nested() API, but I want to revisit it after trying
out this API in the real world.
2016-03-13 13:59:39 +03:00
|
|
|
def nested(self, field):
|
|
|
|
# nested data will be directly written to ui
|
|
|
|
return self
|
2012-02-21 02:42:47 +04:00
|
|
|
def end(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class debugformatter(baseformatter):
|
2015-01-18 12:04:44 +03:00
|
|
|
def __init__(self, ui, out, topic, opts):
|
2016-08-15 07:51:14 +03:00
|
|
|
baseformatter.__init__(self, ui, topic, opts, _nullconverter)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out = out
|
|
|
|
self._out.write("%s = [\n" % self._topic)
|
2012-02-21 02:42:47 +04:00
|
|
|
def _showitem(self):
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write(" " + repr(self._item) + ",\n")
|
2012-02-21 02:42:47 +04:00
|
|
|
def end(self):
|
|
|
|
baseformatter.end(self)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write("]\n")
|
2012-02-21 02:42:47 +04:00
|
|
|
|
2014-09-13 03:36:38 +04:00
|
|
|
class pickleformatter(baseformatter):
|
2015-01-18 12:04:44 +03:00
|
|
|
def __init__(self, ui, out, topic, opts):
|
2016-08-15 07:51:14 +03:00
|
|
|
baseformatter.__init__(self, ui, topic, opts, _nullconverter)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out = out
|
2014-09-13 03:36:38 +04:00
|
|
|
self._data = []
|
|
|
|
def _showitem(self):
|
|
|
|
self._data.append(self._item)
|
|
|
|
def end(self):
|
|
|
|
baseformatter.end(self)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write(pickle.dumps(self._data))
|
2014-09-13 03:36:38 +04:00
|
|
|
|
2014-09-17 16:15:43 +04:00
|
|
|
def _jsonifyobj(v):
|
2016-08-15 06:58:33 +03:00
|
|
|
if isinstance(v, dict):
|
|
|
|
xs = ['"%s": %s' % (encoding.jsonescape(k), _jsonifyobj(u))
|
|
|
|
for k, u in sorted(v.iteritems())]
|
|
|
|
return '{' + ', '.join(xs) + '}'
|
|
|
|
elif isinstance(v, (list, tuple)):
|
2014-09-17 16:30:22 +04:00
|
|
|
return '[' + ', '.join(_jsonifyobj(e) for e in v) + ']'
|
2014-09-17 17:34:34 +04:00
|
|
|
elif v is None:
|
|
|
|
return 'null'
|
2014-10-02 18:20:59 +04:00
|
|
|
elif v is True:
|
|
|
|
return 'true'
|
|
|
|
elif v is False:
|
|
|
|
return 'false'
|
2017-03-14 04:31:29 +03:00
|
|
|
elif isinstance(v, (int, long, float)):
|
2014-09-17 17:21:01 +04:00
|
|
|
return str(v)
|
2014-09-17 16:15:43 +04:00
|
|
|
else:
|
|
|
|
return '"%s"' % encoding.jsonescape(v)
|
|
|
|
|
2014-09-13 03:29:29 +04:00
|
|
|
class jsonformatter(baseformatter):
|
2015-01-18 12:04:44 +03:00
|
|
|
def __init__(self, ui, out, topic, opts):
|
2016-08-15 07:51:14 +03:00
|
|
|
baseformatter.__init__(self, ui, topic, opts, _nullconverter)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out = out
|
|
|
|
self._out.write("[")
|
2017-03-10 02:38:00 +03:00
|
|
|
self._first = True
|
2014-09-13 03:29:29 +04:00
|
|
|
def _showitem(self):
|
2017-03-10 02:38:00 +03:00
|
|
|
if self._first:
|
|
|
|
self._first = False
|
2014-09-13 03:29:29 +04:00
|
|
|
else:
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write(",")
|
2014-09-13 03:29:29 +04:00
|
|
|
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write("\n {\n")
|
2014-09-13 03:29:29 +04:00
|
|
|
first = True
|
|
|
|
for k, v in sorted(self._item.items()):
|
|
|
|
if first:
|
|
|
|
first = False
|
|
|
|
else:
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write(",\n")
|
|
|
|
self._out.write(' "%s": %s' % (k, _jsonifyobj(v)))
|
|
|
|
self._out.write("\n }")
|
2014-09-13 03:29:29 +04:00
|
|
|
def end(self):
|
|
|
|
baseformatter.end(self)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write("\n]\n")
|
2014-09-13 03:29:29 +04:00
|
|
|
|
2016-08-15 07:51:14 +03:00
|
|
|
class _templateconverter(object):
|
|
|
|
'''convert non-primitive data types to be processed by templater'''
|
|
|
|
@staticmethod
|
|
|
|
def formatdate(date, fmt):
|
|
|
|
'''return date tuple'''
|
|
|
|
return date
|
formatter: add function to convert list to appropriate format (issue5217)
Before, it wasn't possible for formatter to handle array structure other
than date tuple. We've discussed that at the last sprint, which ended we
would probably want to allow only templatable data structure, i.e. a list
of dicts:
data(tags=[{'tag': a}, {'tag': b}, ...])
Unfortunately, it turned out not working well with template functions:
"{ifcontains(a, tags, ...)}"
^^^^^^^^^^^^^^^^^^
"a in tags", where tags should be a plain list/set of tags
So the formatter must at least know if the type [{}] was constructed from
a plain list or was actually a list of dicts.
This patch introduces new explicit interface to convert an array structure
to an appropriate data type for the current formatter, which can be used
as follows:
fm.write('tags', _('tags: %s\n'), fm.formatlist(tags, name='tag'))
No separate fm.data() call should be necessary.
2016-07-10 15:03:06 +03:00
|
|
|
@staticmethod
|
2016-08-15 07:51:14 +03:00
|
|
|
def formatdict(data, key, value, fmt, sep):
|
2016-08-15 06:58:33 +03:00
|
|
|
'''build object that can be evaluated as either plain string or dict'''
|
|
|
|
data = util.sortdict(_iteritems(data))
|
|
|
|
def f():
|
2016-08-15 07:51:14 +03:00
|
|
|
yield _plainconverter.formatdict(data, key, value, fmt, sep)
|
2016-08-15 06:58:33 +03:00
|
|
|
return templatekw._hybrid(f(), data, lambda k: {key: k, value: data[k]},
|
|
|
|
lambda d: fmt % (d[key], d[value]))
|
|
|
|
@staticmethod
|
2016-08-15 07:51:14 +03:00
|
|
|
def formatlist(data, name, fmt, sep):
|
formatter: add function to convert list to appropriate format (issue5217)
Before, it wasn't possible for formatter to handle array structure other
than date tuple. We've discussed that at the last sprint, which ended we
would probably want to allow only templatable data structure, i.e. a list
of dicts:
data(tags=[{'tag': a}, {'tag': b}, ...])
Unfortunately, it turned out not working well with template functions:
"{ifcontains(a, tags, ...)}"
^^^^^^^^^^^^^^^^^^
"a in tags", where tags should be a plain list/set of tags
So the formatter must at least know if the type [{}] was constructed from
a plain list or was actually a list of dicts.
This patch introduces new explicit interface to convert an array structure
to an appropriate data type for the current formatter, which can be used
as follows:
fm.write('tags', _('tags: %s\n'), fm.formatlist(tags, name='tag'))
No separate fm.data() call should be necessary.
2016-07-10 15:03:06 +03:00
|
|
|
'''build object that can be evaluated as either plain string or list'''
|
|
|
|
data = list(data)
|
|
|
|
def f():
|
2016-08-15 07:51:14 +03:00
|
|
|
yield _plainconverter.formatlist(data, name, fmt, sep)
|
formatter: add function to convert list to appropriate format (issue5217)
Before, it wasn't possible for formatter to handle array structure other
than date tuple. We've discussed that at the last sprint, which ended we
would probably want to allow only templatable data structure, i.e. a list
of dicts:
data(tags=[{'tag': a}, {'tag': b}, ...])
Unfortunately, it turned out not working well with template functions:
"{ifcontains(a, tags, ...)}"
^^^^^^^^^^^^^^^^^^
"a in tags", where tags should be a plain list/set of tags
So the formatter must at least know if the type [{}] was constructed from
a plain list or was actually a list of dicts.
This patch introduces new explicit interface to convert an array structure
to an appropriate data type for the current formatter, which can be used
as follows:
fm.write('tags', _('tags: %s\n'), fm.formatlist(tags, name='tag'))
No separate fm.data() call should be necessary.
2016-07-10 15:03:06 +03:00
|
|
|
return templatekw._hybrid(f(), data, lambda x: {name: x},
|
|
|
|
lambda d: fmt % d[name])
|
2015-06-10 22:33:38 +03:00
|
|
|
|
2016-08-15 07:51:14 +03:00
|
|
|
class templateformatter(baseformatter):
|
2015-01-18 12:04:44 +03:00
|
|
|
def __init__(self, ui, out, topic, opts):
|
2016-08-15 07:51:14 +03:00
|
|
|
baseformatter.__init__(self, ui, topic, opts, _templateconverter)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out = out
|
2016-08-15 07:51:14 +03:00
|
|
|
self._topic = topic
|
2017-02-25 11:00:07 +03:00
|
|
|
self._t = gettemplater(ui, topic, opts.get('template', ''),
|
|
|
|
cache=templatekw.defaulttempl)
|
|
|
|
self._cache = {} # for templatekw/funcs to store reusable data
|
|
|
|
def context(self, **ctxs):
|
|
|
|
'''insert context objects to be used to render template keywords'''
|
|
|
|
assert all(k == 'ctx' for k in ctxs)
|
|
|
|
self._item.update(ctxs)
|
2016-08-15 07:51:14 +03:00
|
|
|
def _showitem(self):
|
2017-02-25 11:00:07 +03:00
|
|
|
# TODO: add support for filectx. probably each template keyword or
|
|
|
|
# function will have to declare dependent resources. e.g.
|
|
|
|
# @templatekeyword(..., requires=('ctx',))
|
|
|
|
if 'ctx' in self._item:
|
|
|
|
props = templatekw.keywords.copy()
|
|
|
|
# explicitly-defined fields precede templatekw
|
|
|
|
props.update(self._item)
|
|
|
|
# but template resources must be always available
|
|
|
|
props['templ'] = self._t
|
|
|
|
props['repo'] = props['ctx'].repo()
|
|
|
|
props['revcache'] = {}
|
|
|
|
else:
|
|
|
|
props = self._item
|
|
|
|
g = self._t(self._topic, ui=self._ui, cache=self._cache, **props)
|
2015-01-18 12:04:44 +03:00
|
|
|
self._out.write(templater.stringify(g))
|
2016-08-15 07:51:14 +03:00
|
|
|
|
2015-06-10 22:29:13 +03:00
|
|
|
def lookuptemplate(ui, topic, tmpl):
|
|
|
|
# looks like a literal template?
|
|
|
|
if '{' in tmpl:
|
|
|
|
return tmpl, None
|
|
|
|
|
|
|
|
# perhaps a stock style?
|
|
|
|
if not os.path.split(tmpl)[0]:
|
|
|
|
mapname = (templater.templatepath('map-cmdline.' + tmpl)
|
|
|
|
or templater.templatepath(tmpl))
|
|
|
|
if mapname and os.path.isfile(mapname):
|
|
|
|
return None, mapname
|
|
|
|
|
|
|
|
# perhaps it's a reference to [templates]
|
|
|
|
t = ui.config('templates', tmpl)
|
|
|
|
if t:
|
2016-03-26 12:12:12 +03:00
|
|
|
return templater.unquotestring(t), None
|
2015-06-10 22:29:13 +03:00
|
|
|
|
|
|
|
if tmpl == 'list':
|
|
|
|
ui.write(_("available styles: %s\n") % templater.stylelist())
|
2015-10-08 22:55:45 +03:00
|
|
|
raise error.Abort(_("specify a template"))
|
2015-06-10 22:29:13 +03:00
|
|
|
|
|
|
|
# perhaps it's a path to a map or a template
|
|
|
|
if ('/' in tmpl or '\\' in tmpl) and os.path.isfile(tmpl):
|
|
|
|
# is it a mapfile for a style?
|
|
|
|
if os.path.basename(tmpl).startswith("map-"):
|
|
|
|
return None, os.path.realpath(tmpl)
|
|
|
|
tmpl = open(tmpl).read()
|
|
|
|
return tmpl, None
|
|
|
|
|
|
|
|
# constant string?
|
|
|
|
return tmpl, None
|
|
|
|
|
2017-02-25 11:00:07 +03:00
|
|
|
def gettemplater(ui, topic, spec, cache=None):
|
2015-06-10 22:30:18 +03:00
|
|
|
tmpl, mapfile = lookuptemplate(ui, topic, spec)
|
2016-04-03 17:26:48 +03:00
|
|
|
assert not (tmpl and mapfile)
|
|
|
|
if mapfile:
|
2017-02-25 11:00:07 +03:00
|
|
|
return templater.templater.frommapfile(mapfile, cache=cache)
|
|
|
|
return maketemplater(ui, topic, tmpl, cache=cache)
|
2016-04-10 11:23:09 +03:00
|
|
|
|
2017-02-25 16:04:30 +03:00
|
|
|
def maketemplater(ui, topic, tmpl, cache=None):
|
2016-04-10 11:23:09 +03:00
|
|
|
"""Create a templater from a string template 'tmpl'"""
|
2016-03-27 14:59:36 +03:00
|
|
|
aliases = ui.configitems('templatealias')
|
2017-02-25 16:04:30 +03:00
|
|
|
t = templater.templater(cache=cache, aliases=aliases)
|
2015-06-10 22:30:18 +03:00
|
|
|
if tmpl:
|
|
|
|
t.cache[topic] = tmpl
|
|
|
|
return t
|
|
|
|
|
2012-02-21 02:42:47 +04:00
|
|
|
def formatter(ui, topic, opts):
|
2014-09-13 03:29:29 +04:00
|
|
|
template = opts.get("template", "")
|
|
|
|
if template == "json":
|
2015-01-18 12:04:44 +03:00
|
|
|
return jsonformatter(ui, ui, topic, opts)
|
2014-09-13 03:36:38 +04:00
|
|
|
elif template == "pickle":
|
2015-01-18 12:04:44 +03:00
|
|
|
return pickleformatter(ui, ui, topic, opts)
|
2014-09-13 03:29:29 +04:00
|
|
|
elif template == "debug":
|
2015-01-18 12:04:44 +03:00
|
|
|
return debugformatter(ui, ui, topic, opts)
|
2014-09-13 03:29:29 +04:00
|
|
|
elif template != "":
|
2015-01-18 12:04:44 +03:00
|
|
|
return templateformatter(ui, ui, topic, opts)
|
2015-06-26 01:49:11 +03:00
|
|
|
# developer config: ui.formatdebug
|
2014-09-13 03:29:29 +04:00
|
|
|
elif ui.configbool('ui', 'formatdebug'):
|
2015-01-18 12:04:44 +03:00
|
|
|
return debugformatter(ui, ui, topic, opts)
|
2015-06-26 01:49:11 +03:00
|
|
|
# deprecated config: ui.formatjson
|
2014-09-13 03:29:29 +04:00
|
|
|
elif ui.configbool('ui', 'formatjson'):
|
2015-01-18 12:04:44 +03:00
|
|
|
return jsonformatter(ui, ui, topic, opts)
|
2012-02-21 02:42:47 +04:00
|
|
|
return plainformatter(ui, topic, opts)
|