Patchwork [5,of,6] filemerge: add a cleaner API around filemerge

login
register
mail settings
Submitter Siddharth Agarwal
Date Oct. 9, 2015, 6:46 p.m.
Message ID <9e90b12aded615f7d16c.1444416372@dev6666.prn1.facebook.com>
Download mbox | patch
Permalink /patch/10921/
State Accepted
Headers show

Comments

Siddharth Agarwal - Oct. 9, 2015, 6:46 p.m.
# HG changeset patch
# User Siddharth Agarwal <sid0@fb.com>
# Date 1444372470 25200
#      Thu Oct 08 23:34:30 2015 -0700
# Node ID 9e90b12aded615f7d16c042637a69f4b85847a9b
# Parent  8c8b25e411786aaba611a00fe3882f783e1c592c
filemerge: add a cleaner API around filemerge

The generator-based implementation is easy to understand but quite ugly to use.
This higher-level class exposes a much nicer API.

We don't go overboard with API contract checks because this is only going to be
used from one spot.

Patch

diff --git a/mercurial/filemerge.py b/mercurial/filemerge.py
--- a/mercurial/filemerge.py
+++ b/mercurial/filemerge.py
@@ -580,5 +580,34 @@  def _check(r, ui, tool, fcd, files):
 
     return r
 
+class mergectx(object):
+    """context for a 3-way merge in the working directory
+
+    This is a wrapper around the filemerge generator, with a nicer API."""
+
+    # states the generator can be in
+    none = 0
+    premerged = 1
+    merged = 2
+    def __init__(self, *args, **kwargs):
+        self._mgen = filemerge(*args, **kwargs)
+    def premerge(self):
+        '''return (paused, return value)'''
+        try:
+            next(self._mgen)
+            return True, 1
+        except StopIteration as e:
+            self._mgen = None
+            return False, e.args[0]
+    def merge(self):
+        try:
+            next(self._mgen)
+            raise RuntimeError('filemerge should only yield once')
+        except StopIteration as e:
+            self._mgen = None
+            return e.args[0]
+    def close(self):
+        self._mgen.close()
+
 # tell hggettext to extract docstrings from these functions:
 i18nfunctions = internals.values()