diff --git a/src/libvcs/cmd/git_filter.py b/src/libvcs/cmd/git_filter.py new file mode 100644 index 000000000..06ac1740e --- /dev/null +++ b/src/libvcs/cmd/git_filter.py @@ -0,0 +1,636 @@ +"""Typed Git object filters for partial clone and fetch operations.""" + +# Filter config exposes one predictable ValueError surface for type and value errors. +# ruff: noqa: TRY004 + +from __future__ import annotations + +import collections.abc +import dataclasses +import re +import typing as t + +_MAX_UINT = 2**64 - 1 +_MAX_NESTING = 32 +_GIT_ULONG_RE = re.compile( + r"[\t\v\f ]*\+?" + r"(?P0[xX][0-9a-fA-F]+|0[0-7]*|[1-9][0-9]*)" + r"(?P[kKmMgG]?)\Z" +) +_LIMIT_MULTIPLIERS = {"": 1, "k": 1024, "m": 1024**2, "g": 1024**3} +_OBJECT_TYPES = ("blob", "tree", "commit", "tag") +_RESERVED_NON_WHITESPACE = frozenset("~`!@#$^&*()[]{}\\;'\",<>?") + + +def _validate_uint(value: object, *, field: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + msg = f"{field} must be an integer" + raise ValueError(msg) + if not 0 <= value <= _MAX_UINT: + msg = f"{field} must be between 0 and {_MAX_UINT}" + raise ValueError(msg) + return value + + +def _parse_git_ulong(value: str, *, field: str) -> int: + match = _GIT_ULONG_RE.fullmatch(value) + if match is None: + msg = f"{field} must use Git unsigned-long syntax" + raise ValueError(msg) + raw_number = match.group("number") + if raw_number.lower().startswith("0x"): + base = 16 + elif len(raw_number) > 1 and raw_number.startswith("0"): + base = 8 + else: + base = 10 + number = int(raw_number, base) + multiplier = _LIMIT_MULTIPLIERS[match.group("unit").lower()] + if number > _MAX_UINT // multiplier: + msg = f"{field} must not exceed {_MAX_UINT}" + raise ValueError(msg) + return number * multiplier + + +def _validate_limit(value: object) -> None: + if isinstance(value, bool) or not isinstance(value, (int, str)): + msg = "limit must be an integer or Git unsigned-long string" + raise ValueError(msg) + if isinstance(value, int): + _validate_uint(value, field="limit") + return + _parse_git_ulong(value, field="limit") + + +def _validate_oid(value: object) -> None: + if not isinstance(value, str) or not value: + msg = "oid must be a nonempty string" + raise ValueError(msg) + if any(character in value for character in ("\x00", "\r", "\n")): + msg = "oid must not contain NUL or newlines" + raise ValueError(msg) + + +@dataclasses.dataclass(frozen=True, slots=True) +class BlobNone: + """Omit all blobs until Git needs them.""" + + kind: t.ClassVar[t.Literal["blob:none"]] = "blob:none" + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return "blob:none" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class BlobLimit: + """Omit blobs at or above a byte limit. + + Attributes + ---------- + limit : int | str + Byte threshold as an unsigned 64-bit integer or Git unsigned-long + string (such as ``"4m"`` or ``"001024"``). Plain decimal strings + normalize to ``int``. + """ + + limit: int | str + + kind: t.ClassVar[t.Literal["blob:limit"]] = "blob:limit" + + def __post_init__(self) -> None: + """Validate the limit against Git's unsigned-long grammar.""" + _validate_limit(self.limit) + if isinstance(self.limit, str) and re.fullmatch( + r"(?:0|[1-9][0-9]*)", self.limit + ): + object.__setattr__(self, "limit", int(self.limit)) + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return f"blob:limit={self.limit}" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class TreeDepth: + """Omit trees and blobs at or beyond a traversal depth. + + Attributes + ---------- + depth : int + Maximum unsigned 64-bit traversal depth (``0`` omits all trees and + blobs from the root commit). + """ + + depth: int + + kind: t.ClassVar[t.Literal["tree"]] = "tree" + + def __post_init__(self) -> None: + """Validate the traversal depth.""" + _validate_uint(self.depth, field="depth") + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return f"tree:{self.depth}" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class ObjectType: + """Include one Git object type. + + Attributes + ---------- + type : {"blob", "tree", "commit", "tag"} + Git object type retained during pack transfer. + """ + + type: t.Literal["blob", "tree", "commit", "tag"] + + kind: t.ClassVar[t.Literal["object:type"]] = "object:type" + + def __post_init__(self) -> None: + """Validate the object type.""" + if self.type not in _OBJECT_TYPES: + msg = "type must be blob, tree, commit, or tag" + raise ValueError(msg) + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return f"object:type={self.type}" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class SparseOid: + """Read sparse-checkout patterns from a Git object. + + Attributes + ---------- + oid : str + Object name or ref path holding sparse-checkout patterns on the remote. + """ + + oid: str + + kind: t.ClassVar[t.Literal["sparse:oid"]] = "sparse:oid" + + def __post_init__(self) -> None: + """Validate the object name.""" + _validate_oid(self.oid) + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return f"sparse:oid={self.oid}" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class Auto: + """Let Git choose the filter from server recommendations.""" + + kind: t.ClassVar[t.Literal["auto"]] = "auto" + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return "auto" + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +@dataclasses.dataclass(frozen=True, slots=True) +class Combine: + """Apply each child filter as one Git combine filter. + + Attributes + ---------- + filters : tuple[GitFilter, ...] + Nonempty tuple of child filters, excluding :class:`Auto`, nested at + most 32 levels deep. + """ + + filters: tuple[GitFilter, ...] + + kind: t.ClassVar[t.Literal["combine"]] = "combine" + + def __post_init__(self) -> None: + """Validate the child filters.""" + if not isinstance(self.filters, tuple) or not self.filters: + msg = "filters must be a nonempty tuple" + raise ValueError(msg) + for index, child in enumerate(self.filters): + if not isinstance(child, _FILTER_TYPES): + msg = f"filters[{index}] must be a Git filter" + raise ValueError(msg) + if isinstance(child, Auto): + msg = f"filters[{index}]: auto cannot be combined" + raise ValueError(msg) + stack = [(child, 1) for child in self.filters] + while stack: + child, depth = stack.pop() + if depth > _MAX_NESTING: + msg = f"filter nesting exceeds {_MAX_NESTING} levels" + raise ValueError(msg) + if isinstance(child, Combine): + stack.extend((nested, depth + 1) for nested in child.filters) + + def to_spec(self) -> str: + """Return Git's canonical filter specification.""" + return "combine:" + "+".join( + _encode_subfilter(child.to_spec()) for child in self.filters + ) + + def __str__(self) -> str: + """Return Git's canonical filter specification.""" + return self.to_spec() + + +GitFilter: t.TypeAlias = ( + BlobNone | BlobLimit | TreeDepth | ObjectType | SparseOid | Auto | Combine +) +"""A validated Git partial-clone filter.""" + +GitFilterInput: t.TypeAlias = ( + GitFilter + | str + | collections.abc.Mapping[str, object] + | collections.abc.Sequence[object] +) +"""A filter model, spec, kind-tagged mapping, or nonempty sequence.""" + +_FILTER_TYPES = (BlobNone, BlobLimit, TreeDepth, ObjectType, SparseOid, Auto, Combine) + + +def _encode_subfilter(spec: str) -> str: + encoded: list[str] = [] + for byte in spec.encode(): + character = chr(byte) + if ( + 32 < byte < 127 + and character not in _RESERVED_NON_WHITESPACE + and character not in "%+" + ): + encoded.append(character) + else: + encoded.append(f"%{byte:02X}") + return "".join(encoded) + + +def _decode_subfilter(spec: str) -> str: + decoded = bytearray() + index = 0 + while index < len(spec): + character = spec[index] + if character == "%": + escape = spec[index + 1 : index + 3] + if len(escape) != 2 or not all( + c in "0123456789abcdefABCDEF" for c in escape + ): + msg = "malformed percent escape in combine filter" + raise ValueError(msg) + decoded.append(int(escape, 16)) + index += 3 + continue + if ord(character) <= 32 or character in _RESERVED_NON_WHITESPACE: + msg = f"reserved character {character!r} in combine filter" + raise ValueError(msg) + decoded.extend(character.encode()) + index += 1 + if 0 in decoded: + msg = "NUL is not allowed in a filter" + raise ValueError(msg) + try: + return decoded.decode() + except UnicodeDecodeError as error: + msg = "combine filter is not valid UTF-8" + raise ValueError(msg) from error + + +_T = t.TypeVar("_T") + + +def _coerce_children( + items: collections.abc.Sequence[_T], + *, + label: str, + convert: collections.abc.Callable[[_T], GitFilter], +) -> tuple[GitFilter, ...]: + children: list[GitFilter] = [] + for index, item in enumerate(items): + try: + child = convert(item) + except ValueError as error: + msg = f"{label}[{index}]: {error}" + raise ValueError(msg) from None + if isinstance(child, Auto): + msg = f"{label}[{index}]: auto cannot be combined" + raise ValueError(msg) + children.append(child) + return tuple(children) + + +def _parse_filter(spec: str, *, depth: int) -> GitFilter: + if depth > _MAX_NESTING: + msg = f"filter nesting exceeds {_MAX_NESTING} levels" + raise ValueError(msg) + if not isinstance(spec, str) or not spec: + msg = "filter spec must be a nonempty string" + raise ValueError(msg) + if any(character in spec for character in ("\x00", "\r", "\n")): + msg = "filter spec must not contain NUL or newlines" + raise ValueError(msg) + if spec == "blob:none": + return BlobNone() + if spec.startswith("blob:limit="): + return BlobLimit(spec.removeprefix("blob:limit=")) + if spec.startswith("tree:"): + raw_depth = spec.removeprefix("tree:") + return TreeDepth(_parse_git_ulong(raw_depth, field="depth")) + if spec.startswith("object:type="): + raw_type = spec.removeprefix("object:type=") + if raw_type not in _OBJECT_TYPES: + msg = "type must be blob, tree, commit, or tag" + raise ValueError(msg) + return ObjectType(t.cast(t.Literal["blob", "tree", "commit", "tag"], raw_type)) + if spec.startswith("sparse:oid="): + return SparseOid(spec.removeprefix("sparse:oid=")) + if spec == "auto": + return Auto() + if spec.startswith("combine:"): + raw_children = spec.removeprefix("combine:").split("+") + if not raw_children or any(not child for child in raw_children): + msg = "combine filters must contain nonempty children" + raise ValueError(msg) + return Combine( + _coerce_children( + raw_children, + label="filters", + convert=lambda raw_child: _parse_filter( + _decode_subfilter(raw_child), depth=depth + 1 + ), + ) + ) + msg = f"invalid filter spec {spec!r}" + raise ValueError(msg) + + +def parse_filter(spec: str) -> GitFilter: + """Parse one Git filter specification without running Git. + + Parameters + ---------- + spec : str + Native ``--filter=`` string, including ``combine:`` percent + escapes. + + Returns + ------- + GitFilter + Validated filter model corresponding to ``spec``. + + Raises + ------ + ValueError + If ``spec`` is empty, contains NUL or newlines, exceeds 64-bit bounds + or 32 nesting levels, embeds ``auto`` inside ``combine:``, or violates + Git's filter grammar. + + Examples + -------- + >>> parse_filter("blob:limit=4m") + BlobLimit(limit='4m') + >>> parse_filter("combine:blob:none+tree:1") + Combine(filters=(BlobNone(), TreeDepth(depth=1))) + """ + return _parse_filter(spec, depth=0) + + +def _check_mapping_fields( + value: collections.abc.Mapping[str, object], + *, + expected: frozenset[str], +) -> None: + fields = set(value) + unexpected = fields - expected + missing = expected - fields + if unexpected: + msg = f"unsupported field {min(unexpected, key=str)!r}" + raise ValueError(msg) + if missing: + msg = f"missing field {min(missing)!r}" + raise ValueError(msg) + + +def _from_mapping( + value: collections.abc.Mapping[str, object], *, depth: int +) -> GitFilter: + if depth > _MAX_NESTING: + msg = f"filter nesting exceeds {_MAX_NESTING} levels" + raise ValueError(msg) + kind = value.get("kind") + if not isinstance(kind, str): + msg = "kind must be a string" + raise ValueError(msg) + if kind == "blob:none": + _check_mapping_fields(value, expected=frozenset(("kind",))) + return BlobNone() + if kind == "blob:limit": + _check_mapping_fields(value, expected=frozenset(("kind", "limit"))) + return BlobLimit(t.cast(int | str, value["limit"])) + if kind == "tree": + _check_mapping_fields(value, expected=frozenset(("kind", "depth"))) + return TreeDepth(t.cast(int, value["depth"])) + if kind == "object:type": + _check_mapping_fields(value, expected=frozenset(("kind", "type"))) + return ObjectType( + t.cast(t.Literal["blob", "tree", "commit", "tag"], value["type"]) + ) + if kind == "sparse:oid": + _check_mapping_fields(value, expected=frozenset(("kind", "oid"))) + return SparseOid(t.cast(str, value["oid"])) + if kind == "auto": + _check_mapping_fields(value, expected=frozenset(("kind",))) + return Auto() + if kind == "combine": + _check_mapping_fields(value, expected=frozenset(("kind", "filters"))) + raw_filters = value["filters"] + if ( + not isinstance(raw_filters, collections.abc.Sequence) + or isinstance(raw_filters, (str, bytes, bytearray)) + or not raw_filters + ): + msg = "filters must be a nonempty sequence" + raise ValueError(msg) + return Combine( + _coerce_children( + raw_filters, + label="filters", + convert=lambda raw_filter: _coerce_filter(raw_filter, depth=depth + 1), + ) + ) + msg = f"unknown kind {kind!r}" + raise ValueError(msg) + + +def from_mapping(value: collections.abc.Mapping[str, object]) -> GitFilter: + """Build one Git filter from a kind-tagged mapping. + + Parameters + ---------- + value : Mapping[str, object] + Mapping carrying ``"kind"`` and the exact required fields for that + filter kind. + + Returns + ------- + GitFilter + Validated filter model built from ``value``. + + Raises + ------ + ValueError + If ``"kind"`` is missing or unknown, any required field is absent or + unsupported, or field values fail filter validation. + + Examples + -------- + >>> from_mapping({"kind": "tree", "depth": 0}) + TreeDepth(depth=0) + """ + return _from_mapping(value, depth=0) + + +def _coerce_filter(value: object, *, depth: int) -> GitFilter: + if depth > _MAX_NESTING: + msg = f"filter nesting exceeds {_MAX_NESTING} levels" + raise ValueError(msg) + if isinstance(value, _FILTER_TYPES): + return value + if isinstance(value, str): + return _parse_filter(value, depth=depth) + if isinstance(value, collections.abc.Mapping): + return _from_mapping(value, depth=depth) + if isinstance(value, collections.abc.Sequence) and not isinstance( + value, (bytes, bytearray) + ): + if not value: + msg = "filter sequence must be nonempty" + raise ValueError(msg) + return Combine( + _coerce_children( + value, + label="filter", + convert=lambda item: _coerce_filter(item, depth=depth + 1), + ) + ) + msg = "filter must be a model, spec string, mapping, or nonempty sequence" + raise ValueError(msg) + + +def coerce_filter(value: object) -> GitFilter: + """Validate and convert one accepted filter value to a model. + + Parameters + ---------- + value : object + A filter dataclass, native spec string, kind-tagged mapping, or + nonempty sequence of non-``auto`` filter inputs. + + Returns + ------- + GitFilter + Validated filter model (sequences return :class:`Combine`). + + Raises + ------ + ValueError + If ``value`` is ``None``, empty, an unsupported type, or invalid under + Git's filter rules. + + Examples + -------- + >>> coerce_filter(["blob:none", {"kind": "tree", "depth": 1}]) + Combine(filters=(BlobNone(), TreeDepth(depth=1))) + """ + return _coerce_filter(value, depth=0) + + +def filter_specs(value: GitFilterInput | None) -> tuple[str, ...]: + """Return canonical specs, preserving one flag per sequence item. + + Parameters + ---------- + value : GitFilterInput | None + Optional filter input. Sequences emit one ``--filter`` spec per item + rather than collapsing into a single ``combine:`` spec. + + Returns + ------- + tuple[str, ...] + Canonical filter specifications, or ``()`` when ``value`` is ``None``. + + Raises + ------ + ValueError + If ``value`` or any sequence element fails filter validation, or if a + sequence contains ``auto``. + + Examples + -------- + >>> filter_specs(["blob:none", TreeDepth(2)]) + ('blob:none', 'tree:2') + >>> filter_specs(None) + () + """ + if value is None: + return () + if isinstance(value, collections.abc.Sequence) and not isinstance( + value, (str, bytes, bytearray) + ): + if not value: + msg = "filter sequence must be nonempty" + raise ValueError(msg) + filters = _coerce_children( + value, + label="filter", + convert=lambda item: _coerce_filter(item, depth=0), + ) + return tuple(item.to_spec() for item in filters) + return (coerce_filter(value).to_spec(),) + + +__all__ = [ + "Auto", + "BlobLimit", + "BlobNone", + "Combine", + "GitFilter", + "GitFilterInput", + "ObjectType", + "SparseOid", + "TreeDepth", + "coerce_filter", + "filter_specs", + "from_mapping", + "parse_filter", +] diff --git a/tests/cmd/test_git_filter.py b/tests/cmd/test_git_filter.py new file mode 100644 index 000000000..aed22b802 --- /dev/null +++ b/tests/cmd/test_git_filter.py @@ -0,0 +1,365 @@ +"""Tests for typed Git partial-clone filters.""" + +from __future__ import annotations + +import collections.abc +import dataclasses +import typing as t + +import pytest + +from libvcs import exc +from libvcs.cmd.git_filter import ( + Auto, + BlobLimit, + BlobNone, + Combine, + GitFilter, + ObjectType, + SparseOid, + TreeDepth, + coerce_filter, + filter_specs, + from_mapping, + parse_filter, +) + +if t.TYPE_CHECKING: + from libvcs.sync.git import GitSync + + +class FilterFixture(t.NamedTuple): + """Canonical filter model, kind tag, and spec tuple.""" + + test_id: str + model: GitFilter + kind: str + spec: str + + +FILTER_FIXTURES = [ + FilterFixture("blob-none", BlobNone(), "blob:none", "blob:none"), + FilterFixture("blob-limit-int", BlobLimit(1024), "blob:limit", "blob:limit=1024"), + FilterFixture( + "blob-limit-octal-string", + BlobLimit("001024"), + "blob:limit", + "blob:limit=001024", + ), + FilterFixture("blob-limit-unit", BlobLimit("4m"), "blob:limit", "blob:limit=4m"), + FilterFixture("tree-depth", TreeDepth(2), "tree", "tree:2"), + FilterFixture( + "object-type", ObjectType("commit"), "object:type", "object:type=commit" + ), + FilterFixture( + "sparse-oid", + SparseOid("refs/filters/base"), + "sparse:oid", + "sparse:oid=refs/filters/base", + ), + FilterFixture("auto", Auto(), "auto", "auto"), + FilterFixture( + "combine", + Combine((BlobNone(), TreeDepth(1))), + "combine", + "combine:blob:none+tree:1", + ), + FilterFixture( + "combine-escaped", + Combine((SparseOid("refs/filters/a b+c"),)), + "combine", + "combine:sparse:oid=refs/filters/a%20b%2Bc", + ), +] + + +@pytest.mark.parametrize( + ("model", "kind", "spec"), + [(fixture.model, fixture.kind, fixture.spec) for fixture in FILTER_FIXTURES], + ids=[fixture.test_id for fixture in FILTER_FIXTURES], +) +def test_filter_canonical_round_trip( + model: GitFilter, + kind: str, + spec: str, +) -> None: + """Each model exposes kind, renders via str()/to_spec(), and parses back.""" + assert model.kind == kind + assert model.to_spec() == spec + assert str(model) == spec + assert filter_specs(model) == (spec,) + assert parse_filter(spec) == model + assert coerce_filter(spec) == model + + +class NativeUlongFixture(t.NamedTuple): + """Alternate Git unsigned-long filter spec and canonical equivalents.""" + + test_id: str + native_spec: str + serialized_spec: str + equivalent_spec: str + + +NATIVE_ULONG_FIXTURES = [ + NativeUlongFixture( + "blob-octal", "blob:limit=010", "blob:limit=010", "blob:limit=8" + ), + NativeUlongFixture( + "blob-plus", "blob:limit=+10", "blob:limit=+10", "blob:limit=10" + ), + NativeUlongFixture( + "blob-hex", "blob:limit=0x10", "blob:limit=0x10", "blob:limit=16" + ), + NativeUlongFixture("blob-kib", "blob:limit=1K", "blob:limit=1K", "blob:limit=1024"), + NativeUlongFixture("tree-octal", "tree:010", "tree:8", "tree:8"), + NativeUlongFixture("tree-plus", "tree:+10", "tree:10", "tree:10"), + NativeUlongFixture("tree-hex", "tree:0x10", "tree:16", "tree:16"), + NativeUlongFixture("tree-kib", "tree:1K", "tree:1024", "tree:1024"), +] + + +@pytest.mark.parametrize( + ("native_spec", "serialized_spec", "equivalent_spec"), + [ + (fixture.native_spec, fixture.serialized_spec, fixture.equivalent_spec) + for fixture in NATIVE_ULONG_FIXTURES + ], + ids=[fixture.test_id for fixture in NATIVE_ULONG_FIXTURES], +) +def test_filter_parser_preserves_native_git_ulong_semantics( + native_spec: str, + serialized_spec: str, + equivalent_spec: str, + git_repo: GitSync, +) -> None: + """Accepted alternate integers select the same real Git objects.""" + parsed_spec = filter_specs(parse_filter(native_spec)) + + assert parsed_spec == (serialized_spec,) + assert git_repo.cmd.run( + ["rev-list", "--objects", f"--filter={native_spec}", "HEAD"] + ) == git_repo.cmd.run( + ["rev-list", "--objects", f"--filter={equivalent_spec}", "HEAD"] + ) + + +@pytest.mark.parametrize("spec", ["blob:limit=08", "tree:08"]) +def test_filter_parser_rejects_values_rejected_by_git( + spec: str, + git_repo: GitSync, +) -> None: + """Invalid octal values fail in libvcs and real Git.""" + with pytest.raises(ValueError): + parse_filter(spec) + with pytest.raises(exc.CommandError): + git_repo.cmd.run( + ["rev-list", "--objects", f"--filter={spec}", "HEAD"], + check_returncode=True, + ) + + +class MappingFixture(t.NamedTuple): + """Kind-tagged filter mapping and expected model.""" + + test_id: str + mapping: dict[str, object] + expected: GitFilter + + +MAPPING_FIXTURES = [ + MappingFixture("blob-none", {"kind": "blob:none"}, BlobNone()), + MappingFixture( + "blob-limit", {"kind": "blob:limit", "limit": "5k"}, BlobLimit("5k") + ), + MappingFixture("tree", {"kind": "tree", "depth": 3}, TreeDepth(3)), + MappingFixture( + "object-type", {"kind": "object:type", "type": "tag"}, ObjectType("tag") + ), + MappingFixture( + "sparse-oid", + {"kind": "sparse:oid", "oid": "refs/filters/base"}, + SparseOid("refs/filters/base"), + ), + MappingFixture("auto", {"kind": "auto"}, Auto()), + MappingFixture( + "combine", + { + "kind": "combine", + "filters": [ + {"kind": "blob:none"}, + {"kind": "tree", "depth": 2}, + ], + }, + Combine((BlobNone(), TreeDepth(2))), + ), +] + + +@pytest.mark.parametrize( + ("mapping", "expected"), + [(fixture.mapping, fixture.expected) for fixture in MAPPING_FIXTURES], + ids=[fixture.test_id for fixture in MAPPING_FIXTURES], +) +def test_filter_from_mapping( + mapping: dict[str, object], + expected: GitFilter, +) -> None: + """Kind-tagged mappings produce typed filters.""" + assert from_mapping(mapping) == expected + assert coerce_filter(mapping) == expected + + +def test_filter_sequence_is_a_combine_model_but_preserves_command_flags() -> None: + """Coercion combines a sequence while command serialization keeps its items.""" + value = ["blob:none", {"kind": "tree", "depth": 2}] + + assert coerce_filter(value) == Combine((BlobNone(), TreeDepth(2))) + assert filter_specs(value) == ("blob:none", "tree:2") + + +def test_filter_models_are_immutable() -> None: + """Filter values use slots and cannot change after validation.""" + value = BlobLimit(10) + + assert not hasattr(value, "__dict__") + with pytest.raises(dataclasses.FrozenInstanceError): + value.limit = 20 # type: ignore[misc] + + +class InvalidModelFixture(t.NamedTuple): + """Invalid direct filter constructor call and expected error match.""" + + test_id: str + factory: collections.abc.Callable[[], object] + match: str + + +INVALID_MODEL_FIXTURES = [ + InvalidModelFixture("limit-bool", lambda: BlobLimit(True), "limit"), + InvalidModelFixture("limit-negative", lambda: BlobLimit(-1), "limit"), + InvalidModelFixture("limit-bad-unit", lambda: BlobLimit("1t"), "limit"), + InvalidModelFixture( + "limit-uint64-overflow", lambda: BlobLimit("18446744073709551616"), "limit" + ), + InvalidModelFixture("depth-bool", lambda: TreeDepth(False), "depth"), + InvalidModelFixture("depth-negative", lambda: TreeDepth(-1), "depth"), + InvalidModelFixture( + "type-unknown", lambda: ObjectType(t.cast(t.Any, "delta")), "type" + ), + InvalidModelFixture("oid-empty", lambda: SparseOid(""), "oid"), + InvalidModelFixture("oid-newline", lambda: SparseOid("bad\nref"), "oid"), + InvalidModelFixture("combine-empty", lambda: Combine(()), "filters"), + InvalidModelFixture("combine-auto", lambda: Combine((Auto(),)), "auto"), +] + + +@pytest.mark.parametrize( + ("factory", "match"), + [(fixture.factory, fixture.match) for fixture in INVALID_MODEL_FIXTURES], + ids=[fixture.test_id for fixture in INVALID_MODEL_FIXTURES], +) +def test_filter_model_rejects_invalid_fields( + factory: collections.abc.Callable[[], object], + match: str, +) -> None: + """Direct model construction enforces the Git grammar.""" + with pytest.raises(ValueError, match=match): + factory() + + +class InvalidConfigFixture(t.NamedTuple): + """Invalid filter coercion value and expected error match.""" + + test_id: str + value: object + match: str + + +INVALID_CONFIG_FIXTURES = [ + InvalidConfigFixture("none", None, "filter"), + InvalidConfigFixture("empty-sequence", [], "nonempty"), + InvalidConfigFixture( + "sequence-with-auto", ["blob:none", "auto"], r"filter\[1\].*auto" + ), + InvalidConfigFixture("sequence-single-auto", [Auto()], r"filter\[0\].*auto"), + InvalidConfigFixture("sequence-invalid-item", ["blob:none", "wat"], r"filter\[1\]"), + InvalidConfigFixture( + "extra-field-blob-none", {"kind": "blob:none", "depth": 1}, "depth" + ), + InvalidConfigFixture("missing-limit", {"kind": "blob:limit"}, "limit"), + InvalidConfigFixture("wrong-field-tree", {"kind": "tree", "limit": 1}, "limit"), + InvalidConfigFixture("unknown-kind", {"kind": "unknown"}, "kind"), + InvalidConfigFixture( + "combine-empty-filters", {"kind": "combine", "filters": []}, "filters" + ), + InvalidConfigFixture( + "combine-string-filters", {"kind": "combine", "filters": "blob:none"}, "filters" + ), +] + + +@pytest.mark.parametrize( + ("value", "match"), + [(fixture.value, fixture.match) for fixture in INVALID_CONFIG_FIXTURES], + ids=[fixture.test_id for fixture in INVALID_CONFIG_FIXTURES], +) +def test_filter_coercion_rejects_invalid_config( + value: object, + match: str, +) -> None: + """Config errors name the bad field or list item.""" + with pytest.raises(ValueError, match=match): + coerce_filter(value) + + +@pytest.mark.parametrize( + "spec", + [ + "", + "blob:limit=-1", + "blob:limit=true", + "tree:-1", + "object:type=delta", + "sparse:oid=", + "blob:none\n", + "sparse:oid=bad\x00ref", + "combine:", + "combine:+blob:none", + "combine:blob:none+", + "combine:auto", + "combine:blob%", + "combine:blob%2", + "combine:blob%zz", + "combine:blob:none tree:1", + "combine:sparse:oid=bad%00ref", + ], +) +def test_parse_filter_rejects_malformed_specs(spec: str) -> None: + """Malformed filter specs fail without consulting Git.""" + with pytest.raises(ValueError): + parse_filter(spec) + + +def test_filter_specs_treats_none_as_no_filter() -> None: + """Only the optional command serializer accepts None.""" + assert filter_specs(None) == () + + +def test_filter_recursion_is_bounded() -> None: + """Nested config cannot recurse without limit.""" + value: dict[str, object] = {"kind": "blob:none"} + for _ in range(40): + value = {"kind": "combine", "filters": [value]} + + with pytest.raises(ValueError, match="nesting"): + coerce_filter(value) + + +def test_filter_model_recursion_is_bounded() -> None: + """Direct model construction has the same nesting limit as parsing.""" + value: GitFilter = BlobNone() + + with pytest.raises(ValueError, match="nesting"): + for _ in range(40): + value = Combine((value,))