Mercurial > public > mercurial-scm > hg
comparison mercurial/formatter.py @ 32580:35985d407d49
formatter: add helper to create a formatter optionally backed by file
To make things simple, openformatter() and maybereopen() have no support
for a plain object API. Callers must use the "with" statement.
Unlike cmdutil.makefileobj(), append mode ('ab') isn't supported by these
functions. This is because JSON output can't be simply concatenated. Perhaps
cmdutil.export() will have to build a {filename: [revs...]} map first and
write revs per file.
author | Yuya Nishihara <yuya@tcha.org> |
---|---|
date | Sat, 27 May 2017 17:40:18 +0900 |
parents | 012e0da5b759 |
children | e9bf3e132ea9 |
comparison
equal
deleted
inserted
replaced
32579:012e0da5b759 | 32580:35985d407d49 |
---|---|
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 contextlib | |
106 import itertools | 107 import itertools |
107 import os | 108 import os |
108 | 109 |
109 from .i18n import _ | 110 from .i18n import _ |
110 from .node import ( | 111 from .node import ( |
430 return debugformatter(ui, out, topic, opts) | 431 return debugformatter(ui, out, topic, opts) |
431 # deprecated config: ui.formatjson | 432 # deprecated config: ui.formatjson |
432 elif ui.configbool('ui', 'formatjson'): | 433 elif ui.configbool('ui', 'formatjson'): |
433 return jsonformatter(ui, out, topic, opts) | 434 return jsonformatter(ui, out, topic, opts) |
434 return plainformatter(ui, out, topic, opts) | 435 return plainformatter(ui, out, topic, opts) |
436 | |
437 @contextlib.contextmanager | |
438 def openformatter(ui, filename, topic, opts): | |
439 """Create a formatter that writes outputs to the specified file | |
440 | |
441 Must be invoked using the 'with' statement. | |
442 """ | |
443 with util.posixfile(filename, 'wb') as out: | |
444 with formatter(ui, out, topic, opts) as fm: | |
445 yield fm | |
446 | |
447 @contextlib.contextmanager | |
448 def _neverending(fm): | |
449 yield fm | |
450 | |
451 def maybereopen(fm, filename, opts): | |
452 """Create a formatter backed by file if filename specified, else return | |
453 the given formatter | |
454 | |
455 Must be invoked using the 'with' statement. This will never call fm.end() | |
456 of the given formatter. | |
457 """ | |
458 if filename: | |
459 return openformatter(fm._ui, filename, fm._topic, opts) | |
460 else: | |
461 return _neverending(fm) |