From a979847280904a8ce7a17adbeb541646343f5d5c Mon Sep 17 00:00:00 2001 From: "Michael F." Date: Wed, 13 Dec 2023 17:15:28 +0100 Subject: [PATCH] access config values via cli --- src/graphsenselib/config/cli.py | 14 ++++++++++++++ src/graphsenselib/utils/generic.py | 14 ++++++++++++++ tests/utils/test_utils.py | 16 ++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/src/graphsenselib/config/cli.py b/src/graphsenselib/config/cli.py index 3228d26..5603afe 100644 --- a/src/graphsenselib/config/cli.py +++ b/src/graphsenselib/config/cli.py @@ -1,5 +1,6 @@ import click +from ..utils import subkey_get from ..utils.console import console from .config import config as cfg @@ -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.""" diff --git a/src/graphsenselib/utils/generic.py b/src/graphsenselib/utils/generic.py index 6af07a5..6a8e159 100644 --- a/src/graphsenselib/utils/generic.py +++ b/src/graphsenselib/utils/generic.py @@ -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) diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py index 8afd589..6397c80 100644 --- a/tests/utils/test_utils.py +++ b/tests/utils/test_utils.py @@ -7,6 +7,7 @@ remove_prefix, strip_0x, subkey_exists, + subkey_get, to_int, ) from graphsenselib.utils.errorhandling import CrashRecoverer @@ -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