formatter: add context manager interface for convenience
authorYuya Nishihara <yuya@tcha.org>
Mon, 29 Aug 2016 00:00:05 +0900
changeset 29882 307b20e5e505
parent 29881 12f8bef59bfa
child 29883 0c8c388c7d62
formatter: add context manager interface for convenience And port "hg files" to test it. As you can see, extra indent is necessary to port to this API. I don't think we should switch every fm.formatter() call to "with" statement.
mercurial/commands.py
mercurial/formatter.py
--- a/mercurial/commands.py	Fri Aug 26 21:06:31 2016 +0200
+++ b/mercurial/commands.py	Mon Aug 29 00:00:05 2016 +0900
@@ -3963,15 +3963,11 @@
     end = '\n'
     if opts.get('print0'):
         end = '\0'
-    fm = ui.formatter('files', opts)
     fmt = '%s' + end
 
     m = scmutil.match(ctx, pats, opts)
-    ret = cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
-
-    fm.end()
-
-    return ret
+    with ui.formatter('files', opts) as fm:
+        return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
 
 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
 def forget(ui, repo, *pats, **opts):
--- a/mercurial/formatter.py	Fri Aug 26 21:06:31 2016 +0200
+++ b/mercurial/formatter.py	Mon Aug 29 00:00:05 2016 +0900
@@ -52,6 +52,11 @@
         self._item = None
         # function to convert node to string suitable for this output
         self.hexfunc = hex
+    def __enter__(self):
+        return self
+    def __exit__(self, exctype, excvalue, traceback):
+        if exctype is None:
+            self.end()
     def __nonzero__(self):
         '''return False if we're not doing real templating so we can
         skip extra work'''