fox-it / dissect.target

The Dissect module tying all other Dissect modules together. It provides a programming API and command line tools which allow easy access to various data sources inside disk images or file collections (a.k.a. targets).
GNU Affero General Public License v3.0
44 stars 46 forks source link

Improve target configuration object to behave like a magic dictionary #772

Open Schamper opened 2 months ago

Schamper commented 2 months ago

Currently it behaves/is a module type to allow for easy attribute access, but this is annoying when attributes may or may not exist yet. For example: https://github.com/fox-it/dissect.target/blob/98d33d0d12762dc1bf97eefddd54357581d8336e/dissect/target/helpers/cache.py#L85

Ideally it behaves like a magic dictionary with the nice methods of a dictionary, but the magic attribute access like a module.

https://github.com/fox-it/dissect.target/blob/main/dissect/target/helpers/config.py

JSCU-CNI commented 2 months ago

Is it acceptable to invoke the config as follows?

foo = target._config.get("FOO")

Because in that case the following patch should suffice:

diff --git a/dissect/target/helpers/config.py b/dissect/target/helpers/config.py
index 7a1cc3f..3a1868a 100644
--- a/dissect/target/helpers/config.py
+++ b/dissect/target/helpers/config.py
@@ -6,6 +6,7 @@ import importlib.util
 import logging
 from pathlib import Path
 from types import ModuleType
+from typing import Any

 log = logging.getLogger(__name__)

@@ -26,6 +27,10 @@ def load(paths: list[Path | str] | Path | str | None) -> ModuleType:
         config_values = _parse_ast(config_file.read_bytes())
         config.__dict__.update(config_values)

+    def get(self, value: str) -> Any | None:
+        return getattr(self, value, None)
+    config.get = get.__get__(config)
+
     return config