diff --git a/cats/configure.py b/cats/configure.py index ba52e3c..dc30491 100644 --- a/cats/configure.py +++ b/cats/configure.py @@ -12,6 +12,7 @@ import logging import sys +import os from collections.abc import Mapping from typing import Any, Optional @@ -76,7 +77,16 @@ def config_from_file(configpath="") -> Mapping[str, Any]: return yaml.safe_load(f) logging.info(f"Using provided config file: {configpath}\n") else: - # if no path provided, look for `config.yml` in current directory + # if no path provided, try to use config environment variable + cfile = os.getenv("CATS_CONFIG_FILE") + if cfile is not None: + try: + with open(cfile, "r") as f: + return yaml.safe_load(f) + logging.info("Using config.yml found in CATS_CONFIG_FILE\n") + except FileNotFoundError: + logging.warning("CATS_CONFIG_FILE config file not found") + # if no path provided and no env variable, look for `config.yml` in current directory try: with open("config.yml", "r") as f: return yaml.safe_load(f) diff --git a/docs/source/quickstart.rst b/docs/source/quickstart.rst index f9b04e2..2a46ada 100644 --- a/docs/source/quickstart.rst +++ b/docs/source/quickstart.rst @@ -45,7 +45,9 @@ Use the ``--config`` option to specify a path to the configuration file, relative to the current directory. In case of a missing location command line argument, ``cats`` looks -for a file named ``config.yaml`` or ``config.yml`` in the current directory. +first in the ``CATS_CONFIG_FILE`` environment variable and if that +is not set it looks for a file named ``config.yaml`` or ``config.yml`` +in the current directory. .. code-block:: shell @@ -67,7 +69,16 @@ machine IP address: Carbon intensity if job started now = 117.95 gCO2eq/kWh Carbon intensity at optimal time = 60.93 gCO2eq/kWh - Use --format=json to get this in machine readable format +Use --format=json to get this in machine readable format + +.. code-block::console + + # location information is provided by the file + # specified in $CATS_CONFIG_FILE + # If not, it looks for ./config.yaml + # otherwise 'cats' errors out. + export CATS_CONFIG_FILE=/path/to/config.yaml + cats --duration 480 Displaying carbon footprint estimates diff --git a/tests/test_configure.py b/tests/test_configure.py index 37fede2..e159271 100644 --- a/tests/test_configure.py +++ b/tests/test_configure.py @@ -50,6 +50,12 @@ def test_config_from_file_default(local_config_file): assert configmapping == CATS_CONFIG +def test_config_from_env(local_config_file): + os.environ["CATS_CONFIG_FILE"] = str(local_config_file / "config.yml") + configmapping = config_from_file() + assert configmapping == CATS_CONFIG + + @patch("cats.configure.requests") def test_get_location_from_config_or_args(mock_requests): expected_location = "SW7"