From ad6644a66318cb65ec48121aa36d47684bc660c4 Mon Sep 17 00:00:00 2001
From: Nicolas Dandrimont <nicolas@dandrimont.eu>
Date: Wed, 21 Jun 2023 14:53:17 +0200
Subject: [PATCH] opam: retrieve opam from $PATH with shutil.which

The default behavior of subprocess is to pull executables from a
hardcoded list, which doesn't work when opam is installed manually in
the user's home directory.
---
 swh/lister/opam/lister.py | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)

diff --git a/swh/lister/opam/lister.py b/swh/lister/opam/lister.py
index 6b54e669..75253133 100644
--- a/swh/lister/opam/lister.py
+++ b/swh/lister/opam/lister.py
@@ -6,6 +6,7 @@
 import io
 import logging
 import os
+import shutil
 from subprocess import PIPE, Popen, call
 from typing import Any, Dict, Iterator, Optional
 
@@ -20,6 +21,19 @@ logger = logging.getLogger(__name__)
 PageType = str
 
 
+def opam() -> str:
+    """Get the path to the opam executable.
+
+    Raises:
+      EnvironmentError if no opam executable is found
+    """
+    ret = shutil.which("opam")
+    if not ret:
+        raise EnvironmentError("No opam executable found in path {os.environ['PATH']}")
+
+    return ret
+
+
 class OpamLister(StatelessLister[PageType]):
     """
     List all repositories hosted on an opam repository.
@@ -71,7 +85,7 @@ class OpamLister(StatelessLister[PageType]):
         # Actually list opam instance data
         proc = Popen(
             [
-                "opam",
+                opam(),
                 "list",
                 "--all",
                 "--no-switch",
@@ -124,7 +138,7 @@ def opam_init(opam_root: str, instance: str, url: str, env: Dict[str, Any]) -> N
     """
     if not os.path.exists(opam_root) or not os.listdir(opam_root):
         command = [
-            "opam",
+            opam(),
             "init",
             "--reinit",
             "--bare",
@@ -138,7 +152,7 @@ def opam_init(opam_root: str, instance: str, url: str, env: Dict[str, Any]) -> N
         # The repository exists and is populated, we just add another instance in the
         # repository. If it's already setup, it's a noop
         command = [
-            "opam",
+            opam(),
             "repository",
             "add",
             "--root",
-- 
GitLab