Explorar el Código

refactor: improve error on missing attributes

Sam Jaffe hace 3 semanas
padre
commit
13d16f3d43
Se han modificado 2 ficheros con 17 adiciones y 3 borrados
  1. 3 0
      src/cipy/common.py
  2. 14 3
      src/cipy/context.py

+ 3 - 0
src/cipy/common.py

@@ -29,3 +29,6 @@ class Ref:
         self.path = pathstr.split(".")
         if not self.path:
             raise ValueError("References must be of the form A.B.C etc.")
+
+    def __repr__(self) -> str:
+        return "Ref({})".format(".".join(self.path))

+ 14 - 3
src/cipy/context.py

@@ -48,6 +48,19 @@ class Results(SimpleNamespace):
         return self.__getattribute__(subscript)
 
 
+def _chain_attrs(context: Any, ref: Ref) -> Any:
+    try:
+        for token in ref.path:
+            if isinstance(context, dict):
+                context = context[token]
+            else:
+                context = getattr(context, token)
+        return context
+    except (KeyError, AttributeError):
+        reason = "NULL object" if context is None else "not found"
+        raise AttributeError(f"unable to find {ref} item \"{token}\": {reason}")
+
+
 class Context(SimpleNamespace):
     """Wrapper class for the context of the CI runtime"""
 
@@ -66,9 +79,7 @@ class Context(SimpleNamespace):
             assert len(arg.path) == 2
             return os.environ.get(arg.path[1])
 
-        return reduce(  # type: ignore[return-value]
-            lambda o, a: o[a] if isinstance(o, dict) else getattr(o, a), arg.path, self
-        )
+        return _chain_attrs(self, arg)
 
     @overload
     def fabricate(