Skip to content

Commit

Permalink
Allow custom .pmgrc.yaml location via new PMG_CONFIG_FILE env var (
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh authored Jul 24, 2024
1 parent 5d925fe commit 1bdca30
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/pymatgen/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@
def _load_pmg_settings() -> dict[str, Any]:
settings: dict[str, Any] = {}

# PMG_CONFIG_FILE takes precedence over default settings location
settings_file = os.getenv("PMG_CONFIG_FILE") or SETTINGS_FILE

# Load .pmgrc.yaml file
yaml = YAML()
for file_path in (SETTINGS_FILE, OLD_SETTINGS_FILE):
for file_path in (settings_file, OLD_SETTINGS_FILE):
try:
with open(file_path, encoding="utf-8") as yml_file:
settings = yaml.load(yml_file) or {}
Expand Down
31 changes: 31 additions & 0 deletions tests/core/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,34 @@ def test_load_settings(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
# should return empty dict if file is invalid
settings_file.write_text("---")
assert _load_pmg_settings() == {}


def test_env_var_pmg_config_file(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:
custom_config_file = tmp_path / "custom_config.yaml"
custom_config_file.write_text("PMG_CUSTOM_SETTING: custom_value")

with monkeypatch.context() as ctx:
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
settings = _load_pmg_settings()
assert "PMG_CUSTOM_SETTING" in settings
assert settings["PMG_CUSTOM_SETTING"] == "custom_value"

# Test that PMG_CONFIG_FILE takes precedence over the default location
settings_file = tmp_path / ".pmgrc.yaml"
monkeypatch.setattr("pymatgen.core.SETTINGS_FILE", settings_file)
settings_file.write_text("PMG_DEFAULT_SETTING: default_value")
custom_config_file.write_text("PMG_CUSTOM_SETTING: custom_value")

with monkeypatch.context() as ctx:
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
settings = _load_pmg_settings()
assert "PMG_CUSTOM_SETTING" in settings
assert "PMG_DEFAULT_SETTING" not in settings
assert settings["PMG_CUSTOM_SETTING"] == "custom_value"

# Test that env vars still take precedence over the values specified in PMG_CONFIG_FILE
with monkeypatch.context() as ctx:
ctx.setenv("PMG_CONFIG_FILE", str(custom_config_file))
ctx.setenv("PMG_CUSTOM_SETTING", "env_value")
settings = _load_pmg_settings()
assert settings["PMG_CUSTOM_SETTING"] == "env_value"

0 comments on commit 1bdca30

Please sign in to comment.