# HG changeset patch
# User Philippe Pepiot <philippe.pepiot@logilab.fr>
# Date 1526564440 -7200
#      Thu May 17 15:40:40 2018 +0200
# Node ID 08caf7d50cab579473bfcbb773861cbc6ea38911
# Parent  15dc705464b1a922d584dd219cd8606fe83d53e6
Add a safe_hg() method to BaseTestSuite

This will be used for commands that may not exists in earliers mercurial
versions.

Move this logic to BaseTestSuite since we will use it when switching perf.py
based benchmarks to inherit from BaseTestSuite in next changesets

diff --git a/benchmarks/utils.py b/benchmarks/utils.py
--- a/benchmarks/utils.py
+++ b/benchmarks/utils.py
@@ -12,6 +12,11 @@
 REPOS = [d for d in os.listdir(REPOS_DIR)
          if os.path.isdir(os.path.join(REPOS_DIR, d, ".hg"))]
 
+
+class SkipResult(Exception):
+    pass
+
+
 # Backward compatibility for python 2.6
 if not hasattr(subprocess, 'check_output'):
     STDOUT = subprocess.STDOUT
@@ -210,6 +215,38 @@
             cmd = [self.hgpath] + list(args)
         return self.check_output(*cmd, **kwargs)
 
+    def safe_hg(self, command, *args, **kwargs):
+        """Run given command argument with hg and ignore unknown commands
+
+        This is to be used for commands that may not exist in earlier mercurial
+        versions.
+
+        When hg exit code is 255, test the command existence with 'hg help CMD'
+        to test command existence, if it also return 255, raise SkipResult
+        exception.
+
+        We expect `command` to be the hg command we want to run, either a list
+        of arguments required to run 'hg help' (for extensions etc).
+        """
+        if isinstance(command, (list, tuple)):
+            cmd = command
+        else:
+            cmd = [command]
+        try:
+            return self.hg(*(cmd + list(args)), **kwargs)
+        except subprocess.CalledProcessError as exc:
+            if exc.returncode == 255:
+                # test if it return 255 because the command does not exist
+                # or if it's another issue
+                try:
+                    self.hg(*(['help'] + command))
+                except subprocess.CalledProcessError as exc:
+                    if exc.returncode == 255:
+                        # command does not exist in this version of mercurial
+                        raise SkipResult()
+                    raise
+            raise
+
     def setup(self, repo_name, *args, **kwargs):
         venv = os.path.abspath(os.path.join(os.path.dirname(sys.executable), ".."))
         self.repo_name = repo_name