Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sh-config CLI use environmental variable #487

Merged
merged 3 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions sentinelhub/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import click

from .config import DEFAULT_PROFILE, SHConfig
from .config import SHConfig
from .download import DownloadClient, DownloadRequest

FC = TypeVar("FC", bound=Callable[..., Any])
Expand Down Expand Up @@ -40,9 +40,9 @@ def _config_options(func: FC) -> FC:

@click.command()
@click.option("--show", is_flag=True, default=False, help="Show current configuration")
@click.option("--profile", default=DEFAULT_PROFILE, help="Selects profile to show/configure.")
@click.option("--profile", default=None, help="Selects profile to show/configure.")
@_config_options
def config(show: bool, profile: str, **params: Any) -> None:
def config(show: bool, profile: str | None, **params: Any) -> None:
"""Inspect and configure parameters in your local sentinelhub configuration file

\b
Expand Down
13 changes: 9 additions & 4 deletions sentinelhub/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ def __init__(self, profile: str | None = None, *, use_defaults: bool = False, **
:param use_defaults: Does not load the configuration file, returns config object with defaults only.
:param kwargs: Any fields of `SHConfig` to be updated. Overrides settings from `config.toml` and environment.
"""
if profile is None:
profile = os.environ.get(SH_PROFILE_ENV_VAR, default=DEFAULT_PROFILE)
profile = self._get_profile(profile)

if not use_defaults:
env_kwargs = {
Expand All @@ -141,12 +140,17 @@ def __repr__(self) -> str:
content = ",\n ".join(f"{key}={value!r}" for key, value in config_dict.items())
return f"{self.__class__.__name__}(\n {content},\n)"

@staticmethod
def _get_profile(profile: str | None) -> str:
return profile if profile is not None else os.environ.get(SH_PROFILE_ENV_VAR, default=DEFAULT_PROFILE)

@classmethod
def load(cls, profile: str = DEFAULT_PROFILE) -> SHConfig:
def load(cls, profile: str | None = None) -> SHConfig:
"""Loads configuration parameters from the config file at `SHConfig.get_config_location()`.

:param profile: Which profile to load from the configuration file.
"""
profile = cls._get_profile(profile)
filename = cls.get_config_location()
if not os.path.exists(filename):
cls(use_defaults=True).save(profile) # store default configuration to standard location
Expand All @@ -159,11 +163,12 @@ def load(cls, profile: str = DEFAULT_PROFILE) -> SHConfig:

return cls(use_defaults=True, **configurations_dict[profile])

def save(self, profile: str = DEFAULT_PROFILE) -> None:
def save(self, profile: str | None = None) -> None:
"""Saves configuration parameters to the config file at `SHConfig.get_config_location()`.

:param profile: Under which profile to save the configuration.
"""
profile = self._get_profile(profile)
file_path = Path(self.get_config_location())
file_path.parent.mkdir(parents=True, exist_ok=True)

Expand Down
8 changes: 8 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,16 @@ def test_profiles_from_env(monkeypatch: pytest.MonkeyPatch) -> None:

monkeypatch.setenv(SH_PROFILE_ENV_VAR, "beekeeper")
assert SHConfig().instance_id == "bee", "Environment profile is not used."
assert SHConfig.load().instance_id == "bee", "The load method does not respect the environment profile."
assert SHConfig(profile=DEFAULT_PROFILE).instance_id == "", "Explicit profile overrides environment."

config = SHConfig()
config.instance_id = "many bee"
config.save()

assert SHConfig(profile="beekeeper").instance_id == "many bee", "Save method does not respect the env profile."
assert SHConfig(profile=DEFAULT_PROFILE).instance_id == "", "Saving with env profile changed default profile."


def test_loading_unknown_profile_fails() -> None:
with pytest.raises(KeyError):
Expand Down