Skip to content

Commit fce4efa

Browse files
authored
git(feat[filter]): Support partial-clone filters (#561)
why: Large repositories need object-filtered clones, fetches, and submodule updates without hand-escaped --filter flags. what: - Accept typed _filter inputs on Git.clone(), Git.fetch(), and GitSubmoduleCmd.update(), flattening multi-item submodule filters - Reject nonempty _filter on Git.pull() and Auto inside submodule updates - Accept git_filter on GitSync and guard Auto when submodule gitlinks exist - Document partial-clone filters in Sphinx with executable doctests Fixes #553
2 parents 67b6c23 + 8df7762 commit fce4efa

9 files changed

Lines changed: 537 additions & 8 deletions

File tree

‎CHANGES‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@ _Notes on the upcoming release will go here._
2727
Python 3.10 reached end-of-life in October 2026. libvcs now requires Python
2828
3.11 or newer.
2929

30+
### What's new
31+
32+
#### Typed Git filters validate partial clones before execution (#561)
33+
34+
{mod}`libvcs.cmd.git_filter` provides frozen models for Git's `blob:none`,
35+
`blob:limit`, `tree`, `object:type`, `sparse:oid`, `auto`, and `combine`
36+
filters. Specs and kind-tagged mappings parse into the same models, with
37+
validation for numeric ranges, combine escaping, recursion, incompatible
38+
`auto` filters, and field names. Every model exposes `.kind`, `.to_spec()`,
39+
and `str(filter)`.
40+
41+
{meth}`~libvcs.cmd.git.Git.clone`, {meth}`~libvcs.cmd.git.Git.fetch`, and
42+
{meth}`~libvcs.cmd.git.GitSubmoduleCmd.update` accept models, strings,
43+
mappings, and sequences through `_filter`. Clone and fetch preserve repeated
44+
filter arguments; submodule update combines them so Git applies every filter.
45+
{meth}`~libvcs.cmd.git.Git.pull` rejects filters because native Git does not
46+
support them.
47+
48+
{class}`~libvcs.sync.git.GitSync` accepts `git_filter`, validates values before
49+
creating a checkout, and applies them to the initial clone and its submodules.
50+
3051
### Fixes
3152

3253
#### Drain command output while the process runs (#559)

‎MIGRATION‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,25 @@ _Notes on the upcoming release will be added here_
2424

2525
<!-- Maintainers, insert migration notes for the next release here -->
2626

27+
### Git partial-clone filters have typed models
28+
29+
String `_filter` arguments remain valid. Callers that build filters from
30+
configuration can replace unchecked strings with models or kind-tagged
31+
mappings from `libvcs.cmd.git_filter`:
32+
33+
```python
34+
>>> from libvcs.cmd.git_filter import BlobLimit
35+
>>> BlobLimit("4m")
36+
BlobLimit(limit='4m')
37+
```
38+
39+
`GitSync(git_filter=...)` validates the value during construction, applies it
40+
to the initial clone and new submodules, and leaves existing checkout filters
41+
unchanged during updates. `Auto` requires Git 2.54 or newer. If the cloned
42+
repository contains gitlinks, `GitSync` retains the parent clone and raises
43+
before submodule initialization because Git's submodule command rejects
44+
`auto`. Use an explicit filter for repositories with submodules.
45+
2746
### pytest fixtures: `gitconfig` / `hgconfig` renamed to `vcs_gitconfig` / `vcs_hgconfig` (#528)
2847

2948
- pytest: `gitconfig` renamed to `vcs_gitconfig`

‎docs/cmd/git/filter.md‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
(git-partial-clone-filters)=
2+
3+
# Partial-clone filters
4+
5+
{mod}`libvcs.cmd.git_filter` validates Git object filters before a command
6+
creates a checkout or starts a process. The frozen models cover Git's current
7+
filter grammar:
8+
9+
| Model | Git specification | Meaning |
10+
| --- | --- | --- |
11+
| {class}`~libvcs.cmd.git_filter.BlobNone` | `blob:none` | Omit blobs until Git needs them |
12+
| {class}`~libvcs.cmd.git_filter.BlobLimit` | `blob:limit=n[KMG]` | Omit blobs at or above the byte limit |
13+
| {class}`~libvcs.cmd.git_filter.TreeDepth` | `tree:n` | Omit trees and blobs at depth `n` or deeper |
14+
| {class}`~libvcs.cmd.git_filter.ObjectType` | `object:type=TYPE` | Include one of `blob`, `tree`, `commit`, or `tag` |
15+
| {class}`~libvcs.cmd.git_filter.SparseOid` | `sparse:oid=OID` | Read sparse patterns from an object |
16+
| {class}`~libvcs.cmd.git_filter.Auto` | `auto` | Ask Git to choose a server-recommended filter |
17+
| {class}`~libvcs.cmd.git_filter.Combine` | `combine:FILTER+FILTER` | Apply every encoded child filter |
18+
19+
Build a model directly, parse a Git specification, or coerce a kind-tagged
20+
mapping:
21+
22+
```python
23+
>>> from libvcs.cmd.git_filter import BlobLimit, coerce_filter, parse_filter
24+
>>> BlobLimit("4m")
25+
BlobLimit(limit='4m')
26+
>>> str(BlobLimit("4m")), BlobLimit("4m").kind
27+
('blob:limit=4m', 'blob:limit')
28+
>>> parse_filter("tree:2")
29+
TreeDepth(depth=2)
30+
>>> coerce_filter({"kind": "object:type", "type": "commit"})
31+
ObjectType(type='commit')
32+
```
33+
34+
{func}`~libvcs.cmd.git_filter.coerce_filter` turns a nonempty sequence into a
35+
{class}`~libvcs.cmd.git_filter.Combine`. Clone and fetch preserve a top-level
36+
sequence as repeated flags. Submodule update emits one equivalent `combine:`
37+
specification because Git otherwise keeps only the last repeated filter.
38+
39+
```python
40+
>>> from libvcs.cmd.git_filter import (
41+
... BlobNone,
42+
... TreeDepth,
43+
... coerce_filter,
44+
... filter_specs,
45+
... )
46+
>>> coerce_filter([BlobNone(), TreeDepth(1)])
47+
Combine(filters=(BlobNone(), TreeDepth(depth=1)))
48+
>>> filter_specs([BlobNone(), TreeDepth(1)])
49+
('blob:none', 'tree:1')
50+
```
51+
52+
Pass the same accepted values to `_filter` on
53+
{meth}`~libvcs.cmd.git.Git.clone`, {meth}`~libvcs.cmd.git.Git.fetch`, or
54+
{meth}`~libvcs.cmd.git.GitSubmoduleCmd.update`. Existing string values remain
55+
valid. Native `git pull` has no filter option, so
56+
{meth}`~libvcs.cmd.git.Git.pull` rejects every nonempty filter. Call
57+
{meth}`~libvcs.cmd.git.Git.fetch` with the filter before an unfiltered pull.
58+
59+
## Validation limits
60+
61+
Explicit integer values range from zero through `18446744073709551615`.
62+
Textual values use Git's unsigned-long syntax: decimal, leading-zero octal, or
63+
`0x` hexadecimal with an optional leading plus sign. A case-insensitive `K`,
64+
`M`, or `G` suffix uses powers of 1024, and the expanded value must remain in
65+
range. Boolean values are not integers for these fields.
66+
67+
Combine filters percent-encode whitespace, percent, plus, and Git's reserved
68+
characters. Parsing rejects malformed escapes, decoded NUL bytes, empty child
69+
filters, and nesting beyond 32 levels. `auto` cannot be combined with another
70+
filter.
71+
72+
`auto` requires Git 2.54 or newer. libvcs passes it only to `git clone` and
73+
`git fetch`; an older Git reports the capability error. `git pull` rejects all
74+
filters, and `git submodule update` rejects `auto` before starting Git.
75+
76+
```{eval-rst}
77+
.. automodule:: libvcs.cmd.git_filter
78+
:members:
79+
:show-inheritance:
80+
```

‎docs/cmd/git/index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ True
6161
:caption: Subcommands
6262
:maxdepth: 1
6363
64+
filter
6465
submodule
6566
remote
6667
stash

‎docs/sync/git.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,32 @@ Compare to:
1212
[`salt.states.git`](https://docs.saltproject.io/en/latest/ref/states/all/salt.states.git.html),
1313
[`ansible.builtin.git`](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/git_module.html)
1414

15+
## Partial clones
16+
17+
Pass any {ref}`validated Git filter <git-partial-clone-filters>` as
18+
`git_filter` when constructing {class}`~libvcs.sync.git.GitSync`. The filter
19+
applies to the initial clone and to submodules created during that obtain. An
20+
existing checkout keeps its configured partial-clone filter during updates.
21+
22+
```python
23+
>>> from libvcs.cmd.git_filter import BlobNone
24+
>>> from libvcs.sync.git import GitSync
25+
>>> repo = GitSync(
26+
... url="https://example.com/project.git",
27+
... path=tmp_path / "project",
28+
... git_filter=BlobNone(),
29+
... )
30+
>>> repo.git_filter
31+
('blob:none',)
32+
```
33+
34+
{class}`~libvcs.cmd.git_filter.Auto` is available for the initial clone with
35+
Git 2.54 or newer. After cloning, `GitSync` checks the index for submodule
36+
gitlinks. With no gitlinks, the empty submodule update runs without a filter.
37+
If gitlinks exist, obtain raises `ValueError` before initializing them and
38+
leaves the parent clone at the destination. Existing checkout updates do not
39+
change their configured filter.
40+
1541
```{eval-rst}
1642
.. automodule:: libvcs.sync.git
1743
:members:

‎src/libvcs/cmd/git.py‎

Lines changed: 65 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,41 @@
1919
run,
2020
)
2121
from libvcs._internal.types import StrOrBytesPath, StrPath
22+
from libvcs.cmd.git_filter import (
23+
Auto,
24+
Combine,
25+
GitFilter,
26+
GitFilterInput,
27+
coerce_filter,
28+
filter_specs,
29+
)
2230

2331
_CMD = StrOrBytesPath | Sequence[StrOrBytesPath]
2432

2533

34+
def _filter_flags(
35+
value: GitFilterInput | None,
36+
*,
37+
allow_auto: bool,
38+
combine_multiple: bool = False,
39+
) -> list[str]:
40+
specs = filter_specs(value)
41+
if not allow_auto and any(spec == Auto().to_spec() for spec in specs):
42+
msg = "auto filter is not supported by this Git command"
43+
raise ValueError(msg)
44+
if combine_multiple and len(specs) > 1:
45+
pending = [coerce_filter(spec) for spec in reversed(specs)]
46+
filters: list[GitFilter] = []
47+
while pending:
48+
child = pending.pop()
49+
if isinstance(child, Combine):
50+
pending.extend(reversed(child.filters))
51+
else:
52+
filters.append(child)
53+
specs = (Combine(tuple(filters)).to_spec(),)
54+
return [f"--filter={spec}" for spec in specs]
55+
56+
2657
class Git:
2758
"""Run commands directly on a git repository."""
2859

@@ -328,6 +359,7 @@ def clone(
328359
no_remote_submodules: bool | None = None,
329360
verbose: bool | None = None,
330361
quiet: bool | None = None,
362+
_filter: GitFilterInput | None = None,
331363
# Pass-through to run
332364
config: dict[str, t.Any] | None = None,
333365
log_in_real_time: bool = False,
@@ -348,6 +380,9 @@ def clone(
348380
Separate repository (.git/ ) from working tree
349381
force : bool, optional
350382
force operation to run
383+
_filter : GitFilterInput | None, optional
384+
Partial-clone object filter model, spec string, mapping, or
385+
sequence of filters; emits one ``--filter=<spec>`` per item.
351386
make_parents : bool, default: ``True``
352387
Creates checkout directory (`:attr:`self.path`) if it doesn't already exist.
353388
@@ -367,8 +402,7 @@ def clone(
367402
local_flags.append(f"--template={template}")
368403
if separate_git_dir is not None:
369404
local_flags.append(f"--separate-git-dir={separate_git_dir!s}")
370-
if (_filter := kwargs.pop("_filter", None)) is not None:
371-
local_flags.append(f"--filter={_filter}")
405+
local_flags.extend(_filter_flags(_filter, allow_auto=True))
372406
if depth is not None:
373407
local_flags.extend(["--depth", str(depth)])
374408
if branch is not None:
@@ -477,12 +511,19 @@ def fetch(
477511
show_forced_updates: bool | None = None,
478512
no_show_forced_updates: bool | None = None,
479513
negotiate_only: bool | None = None,
514+
_filter: GitFilterInput | None = None,
480515
# libvcs special behavior
481516
check_returncode: bool | None = None,
482517
**kwargs: t.Any,
483518
) -> str:
484519
"""Download from repo. Wraps `git fetch <https://git-scm.com/docs/git-fetch>`_.
485520
521+
Parameters
522+
----------
523+
_filter : GitFilterInput | None, optional
524+
Partial-clone object filter model, spec string, mapping, or
525+
sequence of filters; emits one ``--filter=<spec>`` per item.
526+
486527
Examples
487528
--------
488529
>>> git = Git(path=example_git_repo.path)
@@ -503,8 +544,7 @@ def fetch(
503544

504545
if submodule_prefix is not None:
505546
local_flags.append(f"--submodule-prefix={submodule_prefix!r}")
506-
if (_filter := kwargs.pop("_filter", None)) is not None:
507-
local_flags.append(f"--filter={_filter}")
547+
local_flags.extend(_filter_flags(_filter, allow_auto=True))
508548
if depth is not None:
509549
local_flags.extend(["--depth", depth])
510550
if deepen is not None:
@@ -891,6 +931,7 @@ def pull(
891931
show_forced_updates: bool | None = None,
892932
no_show_forced_updates: bool | None = None,
893933
negotiate_only: bool | None = None,
934+
_filter: GitFilterInput | None = None,
894935
# Pass-through to run
895936
log_in_real_time: bool = False,
896937
check_returncode: bool | None = None,
@@ -899,6 +940,12 @@ def pull(
899940
) -> str:
900941
"""Download from repo. Wraps `git pull <https://git-scm.com/docs/git-pull>`_.
901942
943+
Parameters
944+
----------
945+
_filter : GitFilterInput | None, optional
946+
Rejected with :exc:`ValueError` when nonempty because native
947+
``git pull`` omits ``--filter``; call :meth:`Git.fetch` first.
948+
902949
Examples
903950
--------
904951
>>> git = Git(path=example_git_repo.path)
@@ -999,8 +1046,9 @@ def pull(
9991046
#
10001047
if submodule_prefix is not None:
10011048
local_flags.append(f"--submodule-prefix={submodule_prefix!r}")
1002-
if (_filter := kwargs.pop("_filter", None)) is not None:
1003-
local_flags.append(f"--filter={_filter}")
1049+
if filter_specs(_filter):
1050+
msg = "git pull does not accept filters; call Git.fetch with _filter first"
1051+
raise ValueError(msg)
10041052
if depth is not None:
10051053
local_flags.extend(["--depth", depth])
10061054
if deepen is not None:
@@ -2532,13 +2580,21 @@ def update(
25322580
rebase: bool | None = None,
25332581
merge: bool | None = None,
25342582
recursive: bool | None = None,
2583+
_filter: GitFilterInput | None = None,
25352584
# Pass-through to run()
25362585
log_in_real_time: bool = False,
25372586
check_returncode: bool | None = None,
25382587
**kwargs: t.Any,
25392588
) -> str:
25402589
"""Git submodule update.
25412590
2591+
Parameters
2592+
----------
2593+
_filter : GitFilterInput | None, optional
2594+
Partial-clone object filter applied to initialized submodules;
2595+
multiple items flatten into one ``combine:`` flag, and ``auto`` is
2596+
rejected with :exc:`ValueError`.
2597+
25422598
Examples
25432599
--------
25442600
>>> GitSubmoduleCmd(path=example_git_repo.path).update()
@@ -2577,8 +2633,9 @@ def update(
25772633
local_flags.append("--rebase")
25782634
elif merge is True:
25792635
local_flags.append("--merge")
2580-
if (_filter := kwargs.pop("_filter", None)) is not None:
2581-
local_flags.append(f"--filter={_filter}")
2636+
local_flags.extend(
2637+
_filter_flags(_filter, allow_auto=False, combine_multiple=True)
2638+
)
25822639

25832640
return self.run(
25842641
"update",

0 commit comments

Comments
 (0)