Skip to content

Commit

Permalink
access config values via cli
Browse files Browse the repository at this point in the history
  • Loading branch information
soad003 committed Dec 13, 2023
1 parent 16617cc commit a979847
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/graphsenselib/config/cli.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import click

from ..utils import subkey_get
from ..utils.console import console
from .config import config as cfg

Expand All @@ -25,6 +26,19 @@ def show(json):
console.print(cfg.text())


@config.command("get")
@click.option(
"--path",
help="path in the config file sep. is a dot (.)",
type=str,
required=True,
default=False,
)
def get(path):
"""Prints the configuration used in the environment."""
console.print(subkey_get(cfg.dict(), path.split(".")))


@config.command("path")
def path():
"""Prints the path where the config is loaded from."""
Expand Down
14 changes: 14 additions & 0 deletions src/graphsenselib/utils/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,5 +133,19 @@ def subkey_exists(item, key_list) -> bool:
return False


def subkey_get(item, key_list) -> bool:
if item is None and len(key_list) > 0:
return item
if not key_list:
return item
h, *rest = key_list
if h.isdigit() and isinstance(item, list) and int(h) < len(item):
return subkey_get(item[int(h)], rest)
elif h in item:
return subkey_get(item[h], rest)
else:
return None


def first_or_default(seq: Sequence[object], pred, default=None):
return next(filter(pred, seq), default)
16 changes: 16 additions & 0 deletions tests/utils/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
remove_prefix,
strip_0x,
subkey_exists,
subkey_get,
to_int,
)
from graphsenselib.utils.errorhandling import CrashRecoverer
Expand Down Expand Up @@ -97,6 +98,21 @@ def test_subkey_exists():
assert subkey_exists({"abc": {"cbd": None}}, ["abc", "cbd"]) is True


def test_subkey_get():
assert subkey_get({}, ["abc"]) is None
assert subkey_get({"abc": None}, ["abc"]) is None
assert subkey_get({"abc": []}, ["abc", "cbd"]) is None
assert subkey_get({"abc": {"cbd": 1}}, ["abc", "cbd"]) == 1
assert subkey_get({"abc": {"cbd": "string"}}, ["abc", "cbd"]) == "string"
assert (
subkey_get({"abc": {"cbd": ["a", "b"], "bbb": [1, 2, 3]}}, ["abc", "cbd", "1"])
== "b"
)
assert subkey_get(
{"abc": {"cbd": ["a", "b"], "bbb": [1, 2, 3]}}, ["abc", "bbb"]
) == [1, 2, 3]


def test_first_or_default():
assert first_or_default([1, 2, 3], lambda x: x > 2, default=10) == 3
assert first_or_default([1, 2, 3], lambda x: x > 5, default=10) == 10
Expand Down

0 comments on commit a979847

Please sign in to comment.