Skip to content

Bulk asynchronous downloader for multiple file hosts

fix: CLI additive args (#2084)

NTFSvolume6951fe59744f
diff --git a/cyberdrop_dl/config/__init__.py b/cyberdrop_dl/config/__init__.py
index 9d56c048b..f7a406232 100644
--- a/cyberdrop_dl/config/__init__.py
+++ b/cyberdrop_dl/config/__init__.py
@@ -12,7 +12,7 @@ from pydantic import AfterValidator, BaseModel, Field, NonNegativeInt, PositiveI
from cyberdrop_dl.config.appdata import AppData
from cyberdrop_dl.constants import DEFAULT_PARAMETER
from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup, InvalidYamlError
-from cyberdrop_dl.models import ConfigModel, merge_dicts, merge_models
+from cyberdrop_dl.models import AdditiveArg, ConfigModel, merge_dicts, merge_models
from cyberdrop_dl.models.types import ByteSizeSerilized # noqa: TC001
from cyberdrop_dl.models.validators import to_bytesize
from cyberdrop_dl.utils import cleanup
@@ -45,6 +45,9 @@ class Files:
Config().save_to(Files.DEFAULT)
+_ADDITIVE_ARGS: tuple[tuple[str, ...], ...] | None = None
+
+
@Parameter(name="*")
class Config(ConfigModel, title="cyberdrop-dl config"):
__final__: Literal[True] = True
@@ -178,10 +181,17 @@ class Config(ConfigModel, title="cyberdrop-dl config"):
cleanup.rm_empty_dirs(self.logs.effective_log_folder)
self._resolved = True
+ def _additive_args(self) -> tuple[tuple[str, ...], ...]:
+ global _ADDITIVE_ARGS # noqa: PLW0603
+ if _ADDITIVE_ARGS is None:
+ _ADDITIVE_ARGS = tuple(sorted(AdditiveArg.resolve(self))) # pyright: ignore[reportConstantRedefinition]
+ return _ADDITIVE_ARGS
+
def __or__(self, other: Config) -> Config:
if not isinstance(other, Config):
return NotImplemented
- me = merge_models(self, other)
+
+ me = merge_models(self, other, self._additive_args())
me._sources = self._sources
me.logs._created_at = self.logs._created_at
return me
@@ -213,18 +223,6 @@ def _resolve_paths(model: BaseModel) -> None:
_resolve_paths(field_value)
-def merge_additive_args[T: list[str] | tuple[str, ...]](cli_values: T, config_values: Iterable[str]) -> T:
- match cli_values:
- case ["+", *_]:
- new_values = set(config_values).union(cli_values)
- case ["-", *_]:
- new_values = set(config_values) - set(cli_values)
- case _:
- return cli_values
-
- return type(cli_values)(sorted(new_values - {"+", "-"}))
-
-
def _coerce(*, config: Config | None = None) -> Config:
if config is None:
return Config()
diff --git a/cyberdrop_dl/models/__init__.py b/cyberdrop_dl/models/__init__.py
index b584709b1..38e60f19a 100644
--- a/cyberdrop_dl/models/__init__.py
+++ b/cyberdrop_dl/models/__init__.py
@@ -2,14 +2,18 @@
import logging
import time
-from typing import Any, ClassVar, TypedDict, override
+import warnings
+from collections.abc import Generator, Iterable
+from typing import Any, ClassVar, Final, Self, TypedDict, final, get_args, get_origin, override
from cyclopts import Parameter
+from cyclopts.annotations import resolve
from pydantic import AnyUrl, BaseModel, Secret, SerializationInfo, TypeAdapter, model_serializer, model_validator
+from pydantic.fields import FieldInfo
from cyberdrop_dl import env
from cyberdrop_dl.constants import DEFAULT_PARAMETER
-from cyberdrop_dl.utils import fast_cache
+from cyberdrop_dl.utils import fast_cache, operators
logger = logging.getLogger(__name__)
@@ -136,11 +140,29 @@ class AppriseURL(ConfigModel):
return {"url": url, "tags": tags}
-def merge_dicts(dict1: dict[str, Any], dict2: dict[str, Any]) -> dict[str, Any]:
+def merge_dicts(
+ dict1: dict[str, Any],
+ dict2: dict[str, Any],
+ additive_keys: Iterable[tuple[str, ...]] = (),
+) -> dict[str, Any]:
+ for keys in additive_keys:
+ get = operators.nested_itemgetter(*keys)
+ try:
+ current_value, new_value = get(dict1), get(dict2)
+ except KeyError:
+ continue
+ else:
+ new_value = merge_additive_args(current_value, new_value)
+ operators.nested_itemsetter(*keys)(dict2, new_value)
+
+ return _merge_dicts(dict1, dict2)
+
+
+def _merge_dicts(dict1: dict[str, Any], dict2: dict[str, Any]) -> dict[str, Any]:
for key, val in dict1.items():
if isinstance(val, dict):
if key in dict2 and isinstance(dict2[key], dict):
- merge_dicts(val, dict2[key])
+ _merge_dicts(val, dict2[key])
elif key in dict2:
dict1[key] = dict2[key]
@@ -151,10 +173,14 @@ def merge_dicts(dict1: dict[str, Any], dict2: dict[str, Any]) -> dict[str, Any]:
return dict1
-def merge_models[M: BaseModel](default: M, new: M) -> M:
- default_dict = default.model_dump()
- new_dict = new.model_dump(exclude_unset=True)
- updated_dict = merge_dicts(default_dict, new_dict)
+def merge_models[M: BaseModel](
+ default: M,
+ new: M,
+ additive_keys: Iterable[tuple[str, ...]] = (),
+) -> M:
+ current_data = default.model_dump()
+ new_data = new.model_dump(exclude_unset=True)
+ updated_dict = merge_dicts(current_data, new_data, additive_keys)
return default.model_validate(updated_dict)
@@ -164,3 +190,92 @@ def type_adapter[T](cls: type[T]) -> TypeAdapter[T]:
Type adapters are cached. Multiple calls return the same adapter"""
return TypeAdapter(cls)
+
+
+def merge_additive_args[T: list[str] | tuple[str, ...] | set[str]](current_values: Iterable[str], overrides: T) -> T:
+ if isinstance(overrides, set):
+ if "+" in overrides:
+ new_values = set(current_values).union(overrides)
+ elif "-" in overrides:
+ new_values = set(current_values) - set(overrides)
+ else:
+ return overrides
+ else:
+ match overrides:
+ case ["+", *_]:
+ new_values = set(current_values).union(overrides)
+ case ["-", *_]:
+ new_values = set(current_values) - set(overrides)
+ case _:
+ return overrides
+
+ return type(overrides)(sorted(new_values - {"+", "-"}))
+
+
+class FieldMetadata:
+ IGNORE: Final = "<IGNORE>"
+
+ def __init__(self, **data: Any) -> None:
+ self.data: dict[str, Any] = data
+
+ @override
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}(data={self.data!r})"
+
+ @classmethod
+ def get(cls, field: FieldInfo) -> Self | None:
+ if field.metadata:
+ for data in field.metadata:
+ if type(data) is cls:
+ return data
+
+ @classmethod
+ def _check(cls, field: FieldInfo) -> bool:
+ return cls.get(field) is not None
+
+ @classmethod
+ def resolve(cls, model: BaseModel) -> Generator[tuple[str, ...]]:
+ for name in cls._resolve(model):
+ if cls.IGNORE not in name:
+ yield tuple(name.split("."))
+
+ @classmethod
+ def _resolve(cls, model: BaseModel) -> Generator[str]:
+ for name, field in type(model).model_fields.items():
+ if cls._check(field):
+ yield name
+ continue
+
+ with warnings.catch_warnings(action="ignore"):
+ value = getattr(model, name)
+
+ if isinstance(value, BaseModel):
+ for inner_name in cls._resolve(value):
+ yield f"{name}.{inner_name}"
+
+
+@final
+class AdditiveArg(FieldMetadata):
+ @override
+ @classmethod
+ def _check(cls, field: FieldInfo) -> bool:
+ if get_origin(field.annotation) in {set, list, tuple}:
+ arg = resolve(get_args(field.annotation)[0])
+ all_args = get_args(arg) or [arg]
+ if all(map(_is_str, all_args)):
+ return True
+
+ return super()._check(field)
+
+
+def _is_str(type_: object) -> bool:
+ type_ = resolve(type_)
+ if type_ is str:
+ return True
+ try:
+ return issubclass(type_, str)
+ except Exception: # noqa: BLE001
+ try:
+ return isinstance(type_, str)
+ except Exception: # noqa: BLE001
+ return False
diff --git a/cyberdrop_dl/utils/operators.py b/cyberdrop_dl/utils/operators.py
new file mode 100644
index 000000000..86654dce5
--- /dev/null
+++ b/cyberdrop_dl/utils/operators.py
@@ -0,0 +1,43 @@
+from __future__ import annotations
+
+from typing import Any, final
+
+
+@final
+class nested_itemgetter: # noqa: N801
+ def __init__(self, key: str, *keys: str) -> None:
+ self.keys: tuple[str, ...] = key, *keys
+
+ def __call__(self, obj: Any) -> Any:
+ path: list[str] = []
+ for key in self.keys:
+ path.append(key)
+ try:
+ obj = obj[key]
+ except (KeyError, TypeError):
+ raise KeyError(str(path)) from None
+
+ return obj
+
+ def __repr__(self) -> str:
+ return f"{type(self).__name__}({', '.join(map(repr, self.keys))})"
+
+
+@final
+class nested_itemsetter: # noqa: N801
+ def __init__(self, key: str, *keys: str) -> None:
+ self.keys = key, *keys
+ self._lead_keys = self.keys[:-1]
+ self._tail = self.keys[-1]
+
+ __repr__ = nested_itemgetter.__repr__
+
+ def __call__(self, obj: Any, value: Any) -> Any:
+ for key in self._lead_keys:
+ try:
+ obj = obj[key]
+ except KeyError:
+ obj[key] = {}
+ obj = obj[key]
+
+ obj[self._tail] = value
diff --git a/tests/test_config.py b/tests/test_config.py
index a5c44086d..bd71e3612 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -12,12 +12,12 @@ from cyclopts.exceptions import UnknownOptionError
from pydantic import BaseModel
import cyberdrop_dl.commands.scrape
-from cyberdrop_dl.config import Config, Files, _resolve_paths, merge_additive_args, settings
+from cyberdrop_dl.config import Config, Files, _resolve_paths, settings
from cyberdrop_dl.config.appdata import AppData
from cyberdrop_dl.config.auth import Authentication, Notifications
from cyberdrop_dl.config.filters import Filters, _FileFilter
from cyberdrop_dl.exceptions import CDLConfigRuntimeErrorsGroup
-from cyberdrop_dl.models import AppriseURL, merge_dicts
+from cyberdrop_dl.models import AppriseURL, merge_additive_args, merge_dicts
def test_config_equality() -> None:
@@ -131,6 +131,24 @@ class TestMergeDicts:
expected = {"a": {"x": 1}}
assert merge_dicts(dict1, dict2) == expected
+ def test_additive_args_add(self) -> None:
+ dict1 = {"a": {"b": [1, 2]}}
+ dict2 = {"a": {"b": ["+", 3, 4]}}
+ additive_keys = (("a", "b"),)
+ assert merge_dicts(dict1, dict2, additive_keys) == {"a": {"b": [1, 2, 3, 4]}}
+
+ def test_additive_args_remove(self) -> None:
+ dict1 = {"a": {"b": [1, 2]}}
+ dict2 = {"a": {"b": ["-", 1]}}
+ additive_keys = (("a", "b"),)
+ assert merge_dicts(dict1, dict2, additive_keys) == {"a": {"b": [2]}}
+
+ def test_additive_args_override(self) -> None:
+ dict1 = {"a": {"b": [1, 2]}}
+ dict2 = {"a": {"b": [3, 1]}}
+ additive_keys = (("a", "b"),)
+ assert merge_dicts(dict1, dict2, additive_keys) == {"a": {"b": [3, 1]}}
+
class TestRuntimeLogsConfig:
@staticmethod
@@ -247,7 +265,7 @@ def test_additive_args(
cli_args: list[str] | tuple[str, ...],
expected: list[str] | tuple[str, ...],
) -> None:
- result = merge_additive_args(cli_args, config_args)
+ result = merge_additive_args(config_args, cli_args)
assert type(result) is type(expected)
assert result == expected
@@ -370,3 +388,15 @@ def test_config_union() -> None:
assert config.filters.files.audio is True
assert config_2.filters.files.audio is False
assert config | config_2 == Config(ignore_history=True, dump_json=True, filters=filters)
+
+
+def test_additive_args_list() -> None:
+ args = Config()._additive_args()
+ assert args == (
+ ("crawlers", "bandcamp", "formats"),
+ ("crawlers", "disabled"),
+ ("filters", "only_hosts"),
+ ("filters", "skip_hosts"),
+ ("hashing", "algorithms"),
+ ("jdownloader", "whitelist"),
+ )
diff --git a/tests/test_utils.py b/tests/test_utils.py
index 727d6cd23..7b3b17d70 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -10,7 +10,7 @@ import pytest
from cyberdrop_dl.exceptions import InvalidExtensionError, NoExtensionError
from cyberdrop_dl.filepath import get_filename_and_ext
from cyberdrop_dl.url_objects import AbsoluteHttpURL
-from cyberdrop_dl.utils import text_editor
+from cyberdrop_dl.utils import operators, text_editor
from cyberdrop_dl.utils._url import fix_multi_slashes, parse_http_url
@@ -181,3 +181,37 @@ class TestTextEditor:
cmd = text_editor._find_unix_editor()
assert cmd
assert cmd == text_editor._editor_cmd()
+
+
+def test_operators_nested_itemgetter() -> None:
+ data = {}
+
+ get = operators.nested_itemgetter("a", "b")
+ with pytest.raises(KeyError, match=r"['a']"):
+ get(data)
+
+ data = {
+ "a": 1,
+ "c": 2,
+ }
+
+ with pytest.raises(KeyError, match=r"['a', 'b']"):
+ get(data)
+
+ data = {
+ "a": {
+ "b": 1,
+ },
+ "c": 2,
+ }
+
+ assert get(data) == 1
+
+
+def test_operators_nested_itemsetter() -> None:
+ data = {}
+
+ update = operators.nested_itemsetter("a", "b")
+ update(data, 2)
+
+ assert data == {"a": {"b": 2}}