]> Repositories - Adafruit_Blinka-hackapet.git/blobdiff - src/adafruit_blinka/__init__.py
Add load_settings_toml
[Adafruit_Blinka-hackapet.git] / src / adafruit_blinka / __init__.py
index a4ef21542d610b3c649ecda0541033e753bf58d1..e3cc50c69a8570bae983c043283c58aa048a7edb 100755 (executable)
@@ -8,6 +8,13 @@
 * Author(s): cefn
 """
 
+import os
+
+try:
+    import tomllib
+except ImportError:
+    import toml as tomllib
+
 
 class Enum:
     """
@@ -74,6 +81,41 @@ class Lockable(ContextManaged):
             self._locked = False
 
 
+def load_settings_toml(*, return_toml=False):
+    """Load values from settings.toml into os.environ, so that os.getenv returns them."""
+    if not os.path.isfile("settings.toml"):
+        raise FileNotFoundError("settings.toml not cound in current directory.")
+
+    print("settings.toml found. Updating environment variables:")
+    with open("settings.toml", "rb") as toml_file:
+        try:
+            settings = tomllib.load(toml_file)
+        except tomllib.TOMLDecodeError as e:
+            raise tomllib.TOMLDecodeError("Error with settings.toml file.") from e
+
+    invalid_types = set()
+    for key, value in settings.items():
+        if not isinstance(value, (bool, int, float, str)):
+            invalid_types.add(type(value).__name__)
+    if invalid_types:
+        invalid_types_string = ", ".join(invalid_types)
+        raise ValueError(
+            f"The types: '{invalid_types_string}' are not supported in settings.toml."
+        )
+
+    for key, value in settings.items():
+        key = str(key)
+        if key in os.environ:
+            print(f" - {key} already exists in environment")
+            continue
+        os.environ[key] = str(value)
+        print(f" - {key} added")
+
+    if return_toml:
+        return settings
+    return None
+
+
 def patch_system():
     """Patch modules that may be different due to the platform."""
     # pylint: disable=import-outside-toplevel