[PATCH 2 of 3] basectx: implement __cmp__ that compares ctxs by revision ordering

Yuya Nishihara yuya at tcha.org
Fri Apr 10 09:54:49 CDT 2015


# HG changeset patch
# User Yuya Nishihara <yuya at tcha.org>
# Date 1428154963 -32400
#      Sat Apr 04 22:42:43 2015 +0900
# Node ID 5573f5b3f8941114b9aa14a56e27ab8d555e479b
# Parent  7b7efec2eafba7dde274316eb3c18a98ec6528b1
basectx: implement __cmp__ that compares ctxs by revision ordering

This exists for convenience. It allows us to do "ctxa < ctxb" in place of
"ctxa.rev() < ctxb.rev()" which can't handle committablectx.

If other isn't a basectx, it returns NotImplemented to tell that the binary
operation isn't satisfied and should fall back to another implementation.

diff --git a/mercurial/context.py b/mercurial/context.py
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -59,6 +59,11 @@ class basectx(object):
     def __ne__(self, other):
         return not (self == other)
 
+    def __cmp__(self, other):
+        if not isinstance(other, basectx):
+            return NotImplemented
+        return int(self) - int(other)
+
     def __contains__(self, key):
         return key in self._manifest
 
diff --git a/tests/test-context.py b/tests/test-context.py
--- a/tests/test-context.py
+++ b/tests/test-context.py
@@ -21,6 +21,7 @@ print "workingfilectx.date =", repo[None
 # test ordering: wctx should be the last
 wctx = repo[None]
 print "wctx.rev() = %r, but int(wctx) = %r" % (wctx.rev(), int(wctx))
+print "sort: %r" % [ctx.rev() for ctx in sorted([wctx, repo[-1], repo[0]])]
 
 # test memctx with non-ASCII commit message
 
diff --git a/tests/test-context.py.out b/tests/test-context.py.out
--- a/tests/test-context.py.out
+++ b/tests/test-context.py.out
@@ -1,5 +1,6 @@
 workingfilectx.date = (1000, 0)
 wctx.rev() = None, but int(wctx) = 1
+sort: [-1, 0, None]
 ASCII   : Gr?ezi!
 Latin-1 : Grüezi!
 UTF-8   : Grüezi!


More information about the Mercurial-devel mailing list