From 48214e069c10c9c9aa339a426fe79695539616b0 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 6 Dec 2026 05:39:07 -0600 Subject: [PATCH] scopes,cli(refactor): Use project containment why: vcspull is a declarative VCS synchronizer with no shell hook or template execution, so interactive directory trust prompts, non-TTY VCSPullError aborts, and mutable $XDG_STATE_HOME/vcspull/trusted state added friction without buying anything structural containment cannot provide (#619). what: - Enforce structural project containment in load_scoped_configs() and project_config_contained(), skipping out-of-directory project files with a one-line warning (suppressed on --json / --ndjson streams) - Remove vcspull trust, --trust-project, VCSPULL_YES, ensure_config_trusted(), and the trusted-directories state file - Report skipped project files in vcspull config ls as (outside directory, skipped) - Add ADR 0002, redirect cli/trust.md to configuration/scopes.md, and update CLI/config docs, MIGRATION, CHANGES, and tests --- CHANGES | 37 ++- MIGRATION | 41 +++- docs/_ext/vcspull_output_lexer.py | 6 +- docs/cli/add.md | 7 +- docs/cli/config.md | 23 +- docs/cli/discover.md | 15 +- docs/cli/fmt.md | 6 +- docs/cli/index.md | 13 +- docs/cli/list.md | 7 +- docs/cli/migrate.md | 6 +- docs/cli/search.md | 5 +- docs/cli/status.md | 7 +- docs/cli/sync.md | 8 +- docs/cli/trust.md | 64 ------ docs/cli/worktree/index.md | 5 +- docs/cli/worktree/list.md | 5 +- docs/cli/worktree/sync.md | 3 +- docs/configuration/index.md | 5 +- docs/configuration/scopes.md | 111 ++++----- docs/internals/api/cli/config.md | 8 +- docs/internals/api/scopes.md | 9 +- .../0002-structural-project-containment.md | 174 ++++++++++++++ docs/project/adr/index.md | 1 + docs/redirects.txt | 3 + src/vcspull/_internal/scopes.py | 212 ++---------------- src/vcspull/cli/__init__.py | 80 +------ src/vcspull/cli/_formatter.py | 3 - src/vcspull/cli/add.py | 63 +----- src/vcspull/cli/config.py | 136 +++-------- src/vcspull/cli/discover.py | 15 +- src/vcspull/cli/fmt.py | 14 +- src/vcspull/cli/import_cmd/_common.py | 14 +- src/vcspull/cli/import_cmd/codeberg.py | 1 - src/vcspull/cli/import_cmd/codecommit.py | 1 - src/vcspull/cli/import_cmd/forgejo.py | 1 - src/vcspull/cli/import_cmd/gitea.py | 1 - src/vcspull/cli/import_cmd/github.py | 1 - src/vcspull/cli/import_cmd/gitlab.py | 1 - src/vcspull/cli/list.py | 5 +- src/vcspull/cli/migrate.py | 14 +- src/vcspull/cli/search.py | 5 +- src/vcspull/cli/status.py | 5 +- src/vcspull/cli/sync.py | 5 +- src/vcspull/cli/worktree.py | 4 +- src/vcspull/config.py | 181 +++++---------- tests/_internal/remotes/test_gitlab.py | 1 - tests/cli/test_add.py | 2 - tests/cli/test_config.py | 139 ++++++------ tests/cli/test_discover.py | 2 - tests/cli/test_import_repos.py | 2 - tests/docs/_ext/test_vcspull_output_lexer.py | 5 - tests/test_scopes.py | 123 ++++------ 52 files changed, 595 insertions(+), 1010 deletions(-) delete mode 100644 docs/cli/trust.md create mode 100644 docs/project/adr/0002-structural-project-containment.md diff --git a/CHANGES b/CHANGES index 7281d1653..f24ab4ca1 100644 --- a/CHANGES +++ b/CHANGES @@ -38,6 +38,27 @@ $ uvx --from 'vcspull' --prerelease allow vcspull _Notes on upcoming releases will be added here_ +### Breaking changes + +#### Structural project containment replaces `vcspull trust` (#619) + +{ref}`Configuration scope resolution ` now enforces structural +project containment ({ref}`ADR 0002 `) +instead of interactive or stateful directory trust: + +- Upward-walked `.vcspull.{yaml,yml,json}` project files whose checkout + destinations stay at or beneath their own directory continue to load + automatically. +- Discovered project files with destinations outside their own directory are + skipped with a one-line warning naming `-f FILE` and user configuration (or + silently when `--json` / `--ndjson` writes to `stdout`), and appear in + {ref}`cli-config` (`vcspull config ls`) as `(outside directory, skipped)`. +- `vcspull trust`, `--trust-project`, `VCSPULL_YES`, + `$XDG_STATE_HOME/vcspull/trusted`, and `vcspull.config.ensure_config_trusted` + are removed; {func}`~vcspull.config.project_config_contained` replaces + `ensure_config_trusted` for configuration writers, and {ref}`migration` covers + switching cross-directory manifests to `-f FILE` or `~/.config/vcspull/`. + ### Fixes #### Symlinked user configuration deduplication (#600) @@ -154,8 +175,8 @@ remaining entries (#598). vcspull v1.70.0 resolves configuration across system, user, and ancestor project scopes ({ref}`config-scopes`) with consent-gated project checkouts, -adding {ref}`cli-config` (`vcspull config ls`) and {ref}`cli-trust` (`vcspull -trust`). {ref}`cli-sync` updates matched repositories concurrently by default +adding {ref}`cli-config` (`vcspull config ls`) and `vcspull trust`. +{ref}`cli-sync` updates matched repositories concurrently by default with `--jobs` (`-j`) and a multi-row terminal progress footer, while {ref}`cli-fmt` adds `--style {concise,standard,verbose}` to convert entries across URL strings, standard mappings, and verbose remote definitions. Public @@ -238,16 +259,16 @@ Project configurations whose checkout destinations stay inside their own directory load without prompting. Escaping project configurations require consent, persisted per project directory in `$XDG_STATE_HOME/vcspull/trusted` (`~/.local/state/vcspull/trusted` by default). {ref}`cli-config` (`vcspull -config ls`) inspects active files and overrides, {ref}`cli-trust` (`vcspull -trust`) manages trusted project directories, `--no-project` -(`VCSPULL_NO_PROJECT=1`) skips ancestor project files, and `--trust-project` -(`VCSPULL_YES=1`) authorizes escaping project files without prompting. +config ls`) inspects active files and overrides, `vcspull trust` manages trusted +project directories, `--no-project` (`VCSPULL_NO_PROJECT=1`) skips ancestor +project files, and `--trust-project` (`VCSPULL_YES=1`) authorizes escaping +project files without prompting. In Python, {mod}`vcspull.config` exposes {func}`~vcspull.config.load_scoped_configs`, {func}`~vcspull.config.repo_destinations`, -{func}`~vcspull.config.source_escapes`, and -{func}`~vcspull.config.ensure_config_trusted`. CLI commands report actionable +{func}`~vcspull.config.source_escapes`, and `vcspull.config.ensure_config_trusted`. +CLI commands report actionable {exc}`~vcspull.exc.VCSPullError` failures on stderr as `vcspull: ` instead of a traceback unless `--log-level debug` is set. diff --git a/MIGRATION b/MIGRATION index e7fddb8b0..342dfcbbf 100644 --- a/MIGRATION +++ b/MIGRATION @@ -23,6 +23,41 @@ well. +### Structural project containment replaces `vcspull trust` + +Upward-walked `.vcspull.{yaml,yml,json}` project files are now governed by +structural path containment ({ref}`ADR 0002 `): +project files whose destinations stay inside their own directory load +automatically, while discovered project files targeting paths outside their +directory are skipped with a one-line warning (or silently under `--json` / +`--ndjson`). `vcspull trust`, `--trust-project`, `VCSPULL_YES`, +`$XDG_STATE_HOME/vcspull/trusted`, and `vcspull.config.ensure_config_trusted` +are removed; {func}`vcspull.config.project_config_contained` replaces +`ensure_config_trusted` for configuration writers. + +Manifests that intentionally manage checkouts outside their own directory should +be passed explicitly with `--file` or placed (or symlinked) under +`~/.vcspull.yaml` or `~/.config/vcspull/`. + +Before: + +```console +$ vcspull trust ~/work/meta && vcspull sync --trust-project --all +``` + +After: + +```console +$ vcspull sync --file ~/work/meta/.vcspull.yaml --all +``` + +Or link the manifest into your user configuration directory so every command +loads it automatically: + +```console +$ ln -s ~/work/meta/.vcspull.yaml ~/.config/vcspull/meta.yaml && vcspull sync --all +``` + ## vcspull 1.70.0 (2026-11-29) ### Exceptions renamed with an `Error` suffix @@ -72,9 +107,9 @@ exits `1` when standard input is not a terminal. Non-interactive callers and CI jobs running inside directories that contain escaping project configurations can pre-authorize a project directory with -{ref}`vcspull trust `, pass `--trust-project` (or export -`VCSPULL_YES=1`), pass `--no-project` (or export `VCSPULL_NO_PROJECT=1`) to -skip project configurations, or pass `--file` to load a single explicit file: +`vcspull trust`, pass `--trust-project` (or export `VCSPULL_YES=1`), pass +`--no-project` (or export `VCSPULL_NO_PROJECT=1`) to skip project +configurations, or pass `--file` to load a single explicit file: ```console $ vcspull --no-project sync --all diff --git a/docs/_ext/vcspull_output_lexer.py b/docs/_ext/vcspull_output_lexer.py index 8621a3004..955daf5f4 100644 --- a/docs/_ext/vcspull_output_lexer.py +++ b/docs/_ext/vcspull_output_lexer.py @@ -57,8 +57,8 @@ class VcspullOutputLexer(RegexLexer): (Token.Comment, '•') >>> tokens[2] (Token.Name.Function, 'flask') - >>> [tok for tok in lexer.get_tokens("vcspull trust") if tok[1].strip()] - [(Token.Name.Builtin, 'vcspull'), (Token.Name.Builtin, 'trust')] + >>> [tok for tok in lexer.get_tokens("vcspull config") if tok[1].strip()] + [(Token.Name.Builtin, 'vcspull'), (Token.Name.Builtin, 'config')] """ name = "vcspull Output" @@ -139,7 +139,7 @@ class VcspullOutputLexer(RegexLexer): ( ( r"\b(sync|list|add|status|search|discover|fmt|" - r"migrate|import|worktree|config|trust)\b(?=\s|$)" + r"migrate|import|worktree|config)\b(?=\s|$)" ), Name.Builtin, ), diff --git a/docs/cli/add.md b/docs/cli/add.md index 265f0b9f3..5e838813e 100644 --- a/docs/cli/add.md +++ b/docs/cli/add.md @@ -243,10 +243,9 @@ and the `.vcspull.*` files above your working directory. See {ref}`config-scopes` for the full order. `add` writes to your user configuration by default, and falls back to -creating `./.vcspull.yaml` when you have none. When writing to an existing -`./.vcspull.yaml` whose entries escape its own directory, pass -`--trust-project` (or export `VCSPULL_YES=1`) to authorize the file without -prompting. +creating `./.vcspull.yaml` when you have none. When an existing +`./.vcspull.yaml` targets paths outside its own directory, pass `-f` / `--file` +to modify it explicitly. Specify a file explicitly with `-f/--file`: diff --git a/docs/cli/config.md b/docs/cli/config.md index f4c87305a..e354302c1 100644 --- a/docs/cli/config.md +++ b/docs/cli/config.md @@ -5,7 +5,7 @@ vcspull rarely reads just one file. `vcspull config ls` answers the question that follows from that: standing here, which files are in effect, and which one wins? Reach for it when `vcspull sync` picks up a repository you did not -expect, or refuses one you did. +expect, or skips a project file you did. ## Command @@ -32,27 +32,20 @@ Rows run weakest to strongest, the same order declares; "overridden" is how many of those a nearer file replaced. The final line is the total you will actually sync. -## Diagnosing a refusal +## Diagnosing a skipped project file -A project config that would check a repository out beyond its own directory -needs {ref}`trust ` before it loads. `config ls` shows it rather -than dropping it, and never prompts — this is the command you run *because* -something else refused: +A discovered project config whose destinations resolve outside its own directory +is skipped during {ref}`scope resolution `. `config ls` keeps it +visible in place rather than omitting it, so you can see why its entries are not +in effect: ```vcspull-output user ~/.vcspull.yaml 2 repos project ~/work/proj/.vcspull.yaml 1 repo -project ~/work/proj/escaping/.vcspull.yaml 1 repo (untrusted) +project ~/work/proj/escaping/.vcspull.yaml 1 repo (outside directory, skipped) 3 repositories in effect. -Untrusted configs are not loaded. Allow one with 'vcspull trust DIR'. -``` - -Pass `--trust-project` (or export `VCSPULL_YES=1`) to preview effective counts -as if untrusted project configs were authorized: - -```console -$ vcspull config ls --trust-project +Skipped project configs target paths outside their directory; pass '-f FILE' or link them in user config. ``` ## Ignoring the project scope diff --git a/docs/cli/discover.md b/docs/cli/discover.md index 6d3ee18f8..203fe01b1 100644 --- a/docs/cli/discover.md +++ b/docs/cli/discover.md @@ -139,7 +139,7 @@ it when consolidating checkouts or standardizing workspace labels: $ vcspull discover ~ --recursive --workspace ~/code/ --yes ``` -## Choosing configuration files and project trust +## Choosing configuration files Specify a target configuration file with `--file` (`-f`): @@ -150,15 +150,10 @@ $ vcspull discover ~/company \ ``` Without `--file`, `discover` writes to `~/.vcspull.yaml` when present, or falls -back to `./.vcspull.yaml` (creating the file if it does not exist). When writing -to an existing project-scoped `.vcspull.yaml` whose entries escape its own -directory, vcspull runs the {ref}`project trust check ` first; -pass `--trust-project` (or export `VCSPULL_YES=1`) to authorize it without -prompting in automation: - -```console -$ vcspull discover . --yes --trust-project -``` +back to `./.vcspull.yaml` (creating the file if it does not exist). When an +existing project-scoped `.vcspull.yaml` targets paths outside its own directory, +vcspull enforces {ref}`project containment ` and requires +`--file` (`-f`) to modify that file explicitly. ## Repository detection diff --git a/docs/cli/fmt.md b/docs/cli/fmt.md index 209dd2a15..f648ca292 100644 --- a/docs/cli/fmt.md +++ b/docs/cli/fmt.md @@ -159,9 +159,9 @@ files. Each formatted file is reported individually: $ vcspull fmt --all --write ``` -Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) to skip ancestor project files, or -`--trust-project` (`VCSPULL_YES=1`) to authorize discovered project files whose -destinations escape their directory without prompting: +Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) to skip ancestor project files +(project files targeting paths outside their directory are skipped automatically +unless named with `--file`): ```console $ vcspull fmt --all --no-project --write diff --git a/docs/cli/index.md b/docs/cli/index.md index f728604c4..8eccb2926 100644 --- a/docs/cli/index.md +++ b/docs/cli/index.md @@ -73,12 +73,6 @@ {ref}`vcspull config ` shows which config files are in effect. ::: -:::{grid-item-card} Trust -:link: trust -:link-type: doc -{ref}`vcspull trust ` allows a project config to act outside its directory. -::: - :::{grid-item-card} Completion :link: completion :link-type: doc @@ -102,7 +96,6 @@ worktree/index fmt migrate config -trust ``` ```{toctree} @@ -124,10 +117,6 @@ Top-level options apply across subcommands: - `--no-project` (or `VCSPULL_NO_PROJECT=1`) skips ancestor `.vcspull.*` files during {ref}`scope resolution `. Accepted before or after any subcommand that resolves configuration scopes. -- `--trust-project` (or `VCSPULL_YES=1`) authorizes project configurations whose - checkout destinations resolve outside their own directory without prompting; - see {ref}`cli-trust`. Accepted before or after any subcommand that acts on - project configurations. (cli-main)= @@ -144,5 +133,5 @@ Top-level options apply across subcommands: :no-description: subparser_name : @replace - See :ref:`cli-sync`, :ref:`cli-add`, :ref:`cli-import`, :ref:`cli-discover`, :ref:`cli-list`, :ref:`cli-search`, :ref:`cli-status`, :ref:`cli-worktree`, :ref:`cli-fmt`, :ref:`cli-migrate`, :ref:`cli-config`, :ref:`cli-trust` + See :ref:`cli-sync`, :ref:`cli-add`, :ref:`cli-import`, :ref:`cli-discover`, :ref:`cli-list`, :ref:`cli-search`, :ref:`cli-status`, :ref:`cli-worktree`, :ref:`cli-fmt`, :ref:`cli-migrate`, :ref:`cli-config` ``` diff --git a/docs/cli/list.md b/docs/cli/list.md index c861ae904..f4e60bce6 100644 --- a/docs/cli/list.md +++ b/docs/cli/list.md @@ -178,17 +178,12 @@ $ vcspull list --file ~/projects/.vcspull.yaml ``` Skip ancestor `.vcspull.*` project configs with `--no-project` (or export -`VCSPULL_NO_PROJECT=1`), and authorize escaping project configs without -prompting with `--trust-project` (or export `VCSPULL_YES=1`): +`VCSPULL_NO_PROJECT=1`): ```console $ vcspull list --no-project ``` -```console -$ vcspull list --trust-project -``` - ## Workspace filtering Filter repositories by workspace root with `-w/--workspace/--workspace-root`: diff --git a/docs/cli/migrate.md b/docs/cli/migrate.md index cbd8aa5ef..d72b39abe 100644 --- a/docs/cli/migrate.md +++ b/docs/cli/migrate.md @@ -85,9 +85,9 @@ files: $ vcspull migrate --all --write ``` -Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) to skip ancestor project files, or -`--trust-project` (`VCSPULL_YES=1`) to authorize discovered project files whose -destinations escape their directory without prompting: +Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) to skip ancestor project files +(project files targeting paths outside their directory are skipped automatically +unless named with `--file`): ```console $ vcspull migrate --all --no-project --write diff --git a/docs/cli/search.md b/docs/cli/search.md index 8554e3fa5..2a938c165 100644 --- a/docs/cli/search.md +++ b/docs/cli/search.md @@ -132,9 +132,8 @@ $ vcspull search --ndjson django ## Choosing configuration files and workspace filtering By default, `search` unions every active {ref}`configuration scope `. -Replace the stack with a single file via `--file` (`-f`), skip ancestor project -configs with `--no-project` (`VCSPULL_NO_PROJECT=1`), or authorize escaping -project configs non-interactively with `--trust-project` (`VCSPULL_YES=1`): +Replace the stack with a single file via `--file` (`-f`), or skip ancestor +project configs with `--no-project` (`VCSPULL_NO_PROJECT=1`): ```console $ vcspull search --file ~/projects/.vcspull.yaml django diff --git a/docs/cli/status.md b/docs/cli/status.md index d0dabb139..43497eaa4 100644 --- a/docs/cli/status.md +++ b/docs/cli/status.md @@ -286,17 +286,12 @@ $ vcspull status --file ~/projects/.vcspull.yaml ``` Skip ancestor `.vcspull.*` project configs with `--no-project` -(`VCSPULL_NO_PROJECT=1`), or authorize escaping project configs without -prompting with `--trust-project` (`VCSPULL_YES=1`): +(`VCSPULL_NO_PROJECT=1`): ```console $ vcspull status --no-project ``` -```console -$ vcspull status --trust-project -``` - ## Workspace filtering Filter repositories by workspace root with `-w/--workspace` or `--workspace-root`: diff --git a/docs/cli/sync.md b/docs/cli/sync.md index 26e4be0fe..a2b6529e0 100644 --- a/docs/cli/sync.md +++ b/docs/cli/sync.md @@ -177,18 +177,12 @@ $ vcspull sync --file ~/projects/.vcspull.yaml --all ``` Ignore ancestor project configs for one run with `--no-project` -(`VCSPULL_NO_PROJECT=1`), or pre-authorize an escaping project config in CI -with `--trust-project` (`VCSPULL_YES=1`; see {ref}`cli-trust` — this never -authorizes `dirty: discard`): +(`VCSPULL_NO_PROJECT=1`): ```console $ vcspull sync --no-project --all ``` -```console -$ vcspull sync --trust-project --all -``` - ## Workspace filtering Filter repositories by workspace root with `-w`, `--workspace`, or diff --git a/docs/cli/trust.md b/docs/cli/trust.md deleted file mode 100644 index f1b20626e..000000000 --- a/docs/cli/trust.md +++ /dev/null @@ -1,64 +0,0 @@ -(cli-trust)= - -# vcspull trust - -A `.vcspull.yaml` inside a repository you cloned is code somebody else wrote, -and it names paths on your disk. vcspull loads such a file silently as long as -every repository it declares lands inside that file's own directory. When one -does not, vcspull asks — and `vcspull trust` is how you answer ahead of time, -or take the answer back. - -Most people never run this command. See {ref}`config-scopes` for when the -question comes up at all. - -## Command - -```{eval-rst} -.. argparse:: - :module: vcspull.cli - :func: create_parser - :prog: vcspull - :path: trust -``` - -## Allowing a project - -Trust the current directory when no path is given, or name an explicit project -directory: - -```vcspull-console -$ vcspull trust -trusted ~/work/api -``` - -```vcspull-console -$ vcspull trust ~/work/api -trusted ~/work/api -``` - -Trust is recorded per *directory*, not per file, so a second config in the -same project does not ask again. The trade-off is real: a configuration -committed to that directory can now direct your checkouts anywhere on disk, -including after somebody else edits it. - -## Reviewing and revoking - -```vcspull-console -$ vcspull trust --show -~/work/api -``` - -```vcspull-console -$ vcspull trust --untrust ~/work/api -untrusted ~/work/api -``` - -The record lives in `$XDG_STATE_HOME/vcspull/trusted` -(`~/.local/state/vcspull/trusted` when `XDG_STATE_HOME` is unset), one -directory per line. - -## In automation - -There is no prompt without a terminal — a sync in CI fails loudly rather than -blocking on a question nobody can see. To accept without asking, pass -`--trust-project` or export `VCSPULL_YES=1`. diff --git a/docs/cli/worktree/index.md b/docs/cli/worktree/index.md index 99d2de430..3ab19438c 100644 --- a/docs/cli/worktree/index.md +++ b/docs/cli/worktree/index.md @@ -199,9 +199,8 @@ $ vcspull worktree list --workspace ~/code/ By default, `worktree` subcommands resolve the active {ref}`configuration scopes `. Specify a single configuration file -with `--file` (`-f`), skip ancestor project files with `--no-project` -(`VCSPULL_NO_PROJECT=1`), or authorize escaping project files without prompting -with `--trust-project` (`VCSPULL_YES=1`): +with `--file` (`-f`), or skip ancestor project files with `--no-project` +(`VCSPULL_NO_PROJECT=1`): ```console $ vcspull worktree list --file ~/projects/.vcspull.yaml diff --git a/docs/cli/worktree/list.md b/docs/cli/worktree/list.md index 7fbf7239e..40fb75373 100644 --- a/docs/cli/worktree/list.md +++ b/docs/cli/worktree/list.md @@ -35,9 +35,8 @@ Each worktree is displayed with a status symbol: `vcspull worktree list` resolves {ref}`configuration scopes ` unless `--file` (`-f`) is given, and inspects local repository metadata without -fetching from remotes. Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) or -`--trust-project` (`VCSPULL_YES=1`) on `vcspull` or `vcspull worktree` to -control project scope discovery. +fetching from remotes. Pass `--no-project` (`VCSPULL_NO_PROJECT=1`) on +`vcspull` or `vcspull worktree` to omit ancestor project files. ## Filtering diff --git a/docs/cli/worktree/sync.md b/docs/cli/worktree/sync.md index f1b5e59cf..b90f95b18 100644 --- a/docs/cli/worktree/sync.md +++ b/docs/cli/worktree/sync.md @@ -54,8 +54,7 @@ Live `vcspull worktree sync` exits with status `1` when any worktree is blocked (`⚠`) or encounters an error (`✗`), while `--dry-run` previews exit `0`. `vcspull worktree sync` resolves {ref}`configuration scopes ` unless `--file` (`-f`) is passed; use `--no-project` (`VCSPULL_NO_PROJECT=1`) -or `--trust-project` (`VCSPULL_YES=1`) on `vcspull` or `vcspull worktree` to -control project scope loading. +on `vcspull` or `vcspull worktree` to omit ancestor project files. Both commands print retained recovery identity after success or failure. JSON and NDJSON include update/preservation states, ordered errors, diff --git a/docs/configuration/index.md b/docs/configuration/index.md index 2460628c1..1edd93d86 100644 --- a/docs/configuration/index.md +++ b/docs/configuration/index.md @@ -20,7 +20,7 @@ Most users can start with one `~/.vcspull.yaml` file: :::{grid-item-card} Configuration scopes :link: scopes :link-type: doc -Where vcspull looks, in what order, and how project configs are trusted. +Where vcspull looks, in what order, and how project configs stay contained. ::: :::{grid-item-card} Repository aliases @@ -65,8 +65,7 @@ vcspull resolves configuration across four scopes (weakest to strongest): Pass `--file ./path/to/file.yaml` to any CLI subcommand (such as {ref}`vcspull sync `) to replace the entire scope stack with a single explicit file. See {ref}`config-scopes` for precedence rules, how overlapping -entries merge, and when project configs ask for {ref}`trust ` before -acting. +entries merge, and how project configs are confined to their own directory. [xdg]: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html diff --git a/docs/configuration/scopes.md b/docs/configuration/scopes.md index 8c9646347..ec43685f5 100644 --- a/docs/configuration/scopes.md +++ b/docs/configuration/scopes.md @@ -16,12 +16,12 @@ stop reading. Nothing below changes what one file does. Weakest to strongest. Every scope that exists contributes, and a repository named by more than one scope comes from the strongest. -| Scope | Where | Trust | +| Scope | Where | Containment | | --- | --- | --- | -| system | `/etc/vcspull/*.{yaml,yml,json}` | automatic | -| user directory | `$VCSPULL_CONFIGDIR`, else `$XDG_CONFIG_HOME/vcspull/`, else `~/.config/vcspull/`, else `~/.vcspull/` — the first that exists | automatic | -| user dotfile | `~/.vcspull.yaml` or `~/.vcspull.json` | automatic | -| project | `.vcspull.{yaml,yml,json}` in each ancestor of your working directory, outermost first | gated | +| system | `/etc/vcspull/*.{yaml,yml,json}` | unrestricted | +| user directory | `$VCSPULL_CONFIGDIR`, else `$XDG_CONFIG_HOME/vcspull/`, else `~/.config/vcspull/`, else `~/.vcspull/` — the first that exists | unrestricted | +| user dotfile | `~/.vcspull.yaml` or `~/.vcspull.json` | unrestricted | +| project | `.vcspull.{yaml,yml,json}` in each ancestor of your working directory, outermost first | inside project directory | Passing `-f/--file` replaces that entire stack with the one file you name, so existing scripts and CI jobs behave exactly as they always have. Symlinked user @@ -102,84 +102,56 @@ guard for the project tier: a project `.vcspull.*` file never removes or replaces an alias declared in a user or system file, so your personal handle keeps working inside a project that redefines the entry. -## Trusting a project config +## Project containment -A configuration is a set of destination paths, so a `.vcspull.yaml` inside a -repository you just cloned could name `~/.ssh/` as a workspace root and have -`vcspull sync` clone into it. The project scope is the only scope that can -arrive with untrusted code, so it is the only one vcspull gates. +A configuration is a set of destination paths, so an unchecked `.vcspull.yaml` +inside a repository you just cloned could name `~/.ssh/` as a workspace root and +have `vcspull sync` clone into it. The project scope is the only scope that can +arrive inside an untrusted checkout, so vcspull confines it structurally to its +own directory ({ref}`ADR 0002 `). -The gate is containment: a project config is *contained* when every -repository it declares would be checked out at or beneath the directory -holding that config. The check runs over destinations, not over the workspace -roots you wrote — a repository entry can override its destination with -`path:` and never consult its workspace root at all — and it expands `~`, -environment variables, and symlinks on both sides first. A config targeting -`./vendor/` or a sibling checkout is contained, and loads silently. This is -the overwhelming majority of them, which is what keeps the gate from becoming -a nag. +A project config is *contained* when every repository it declares would be +checked out at or beneath the directory holding that config. The check runs over +destinations, not over the workspace roots you wrote — a repository entry can +override its destination with `path:` and never consult its workspace root at +all — and it expands `~`, environment variables, and symlinks on both sides +first. A config targeting `./vendor/` or a subdirectory is contained, and loads +automatically with no prompt and no state file. -A config that escapes its own directory asks once: +A discovered project config whose destinations resolve outside its directory is +skipped with a one-line warning, while your `system`, `user`, and contained +`project` configs still load: ```vcspull-output -! ~/work/proj/escaping/.vcspull.yaml would check repositories out outside its directory: - ~/.ssh/evil - Trust this config? [y/N/always] +skipping ~/work/proj/escaping/.vcspull.yaml: project configs cannot target paths outside ~/work/proj/escaping (pass -f ~/work/proj/escaping/.vcspull.yaml or link it in user config) ``` -Answering `always` records the project *directory*, not the file, so adding a -second config to a project you already trust does not ask again. The record -lives in `$XDG_STATE_HOME/vcspull/trusted` (`~/.local/state/vcspull/trusted` -when `XDG_STATE_HOME` is unset). +Commands running with `--json` or `--ndjson` skip escaping project configs +silently so `stdout` stays valid JSON. {ref}`vcspull config ls ` +shows skipped project files in place as `(outside directory, skipped)` so you +can see why an entry did not join the stack. -Without a terminal there is no prompt — vcspull fails with the whole remedy in -one line, because a sync in CI must never block on a question nobody can see: - -```vcspull-output -vcspull: ~/work/proj/escaping/.vcspull.yaml would check repositories out outside its directory (~/.ssh/evil) and there is no terminal to confirm on. Run 'vcspull trust ~/work/proj/escaping' to allow it, pass --trust-project, or use --no-project to skip project configs. -``` - -When you do want to accept non-interactively, pass `--trust-project` or export -`VCSPULL_YES=1`. That switch is deliberately its own word rather than a -general `--yes`: an unrelated confirmation flag must never become a standing -grant to write outside a directory. - -Trusting a directory is not free. It means a configuration committed to that -directory can direct your checkouts anywhere on disk, including next time, -when somebody else has edited it. Trust the project, not just the file you -read. - -The same check guards the commands that write: {ref}`add `, -{ref}`discover `, {ref}`fmt `, and -{ref}`migrate `. A repository that ships a config redirecting -your writes deserves the same question as one redirecting your clones. Naming -a file with `-f/--file` is consent and skips the gate, the same way `--file` -skips the scope stack on the read side. - -Manage the record directly with {ref}`vcspull trust ` (omitting -`DIR` trusts the current directory): +When a manifest intentionally manages repositories across unrelated directories +on disk, either pass it explicitly with `-f` / `--file`: ```console -$ vcspull trust +$ vcspull sync --file ~/work/meta/.vcspull.yaml --all ``` -```console -$ vcspull trust ~/work/api -``` +or place (or symlink) it in `~/.vcspull.yaml` or `~/.config/vcspull/`, where +user-scoped configurations may target any path on disk. -```console -$ vcspull trust --untrust ~/work/api -``` - -```console -$ vcspull trust --show -``` +The same containment boundary protects the commands that write: +{ref}`add `, {ref}`discover `, {ref}`fmt `, and +{ref}`migrate `. An existing escaping project file is skipped by +`fmt --all` and `migrate --all` and refused as a default write target unless you +name it explicitly with `-f/--file`. ## For the Python reader Everything above is one function. {func}`vcspull.config.load_scoped_configs` -resolves the stack, merges it, and runs the trust gate, returning the same -list of entries the CLI syncs: +resolves the stack, enforces project containment, and merges the active scopes, +returning the same list of entries the CLI syncs: ```python from vcspull.config import load_scoped_configs @@ -188,11 +160,12 @@ repos = load_scoped_configs() ``` Pass `config_path` to replace the stack the way `--file` does, -`include_project=False` for `--no-project`, or `cwd` to resolve as if you were +`include_project=False` for `--no-project`, `report=False` to suppress skip +warnings on machine-readable streams, or `cwd` to resolve as if you were standing somewhere else. Two lower-level pieces are worth knowing if you are building on this. {func}`vcspull.config.repo_destinations` answers "where would this check out?" for a list of entries, honouring `path:` overrides — it is what the -containment check reads. {func}`vcspull.config.ensure_config_trusted` is the -gate the write commands call, and returns `False` when the user declines. +containment check reads. {func}`vcspull.config.project_config_contained` checks +whether a write command may modify a target file without `--file`. diff --git a/docs/internals/api/cli/config.md b/docs/internals/api/cli/config.md index 01ccb3644..888eb5166 100644 --- a/docs/internals/api/cli/config.md +++ b/docs/internals/api/cli/config.md @@ -1,8 +1,8 @@ -# Config and trust command internals +# Config command internals -{mod}`vcspull.cli.config` implements {ref}`vcspull config ` and -{ref}`vcspull trust ` — reporting active configuration scopes and -managing the trusted project directory state file. +{mod}`vcspull.cli.config` implements {ref}`vcspull config ` — +reporting active configuration scopes, overridden entries, skipped project +files, and handle diagnostics. ```{eval-rst} .. automodule:: vcspull.cli.config diff --git a/docs/internals/api/scopes.md b/docs/internals/api/scopes.md index c763a3a49..c484b0d53 100644 --- a/docs/internals/api/scopes.md +++ b/docs/internals/api/scopes.md @@ -7,11 +7,10 @@ If you need an internal API stabilized please [file an issue](https://github.com ::: {mod}`vcspull._internal.scopes` resolves active configuration files across -system, user, and ancestor project scopes and evaluates destination containment -against the trusted project directory set — the resolver beneath -{func}`vcspull.config.load_scoped_configs`, {ref}`vcspull config `, -and {ref}`vcspull trust `. See {ref}`config-scopes` for user-facing -semantics. +system, user, and ancestor project scopes and evaluates structural destination +containment — the resolver beneath {func}`vcspull.config.load_scoped_configs` +and {ref}`vcspull config `. See {ref}`config-scopes` and +{ref}`ADR 0002 ` for user-facing semantics. ```{eval-rst} .. automodule:: vcspull._internal.scopes diff --git a/docs/project/adr/0002-structural-project-containment.md b/docs/project/adr/0002-structural-project-containment.md new file mode 100644 index 000000000..6c3347fe8 --- /dev/null +++ b/docs/project/adr/0002-structural-project-containment.md @@ -0,0 +1,174 @@ +(adr-structural-project-containment)= + +# ADR 0002: Structural project containment + +## Status + +Accepted. 2026-12-06. + +## Context + +{ref}`Configuration scopes ` resolve configuration files from +`system`, `user`, and upward-walked `project` directories (`#564`). Unlike +`/etc/vcspull/` or `~/.vcspull.yaml`, a `.vcspull.yaml` in the `project` scope +can arrive inside a repository you just cloned. Because a vcspull entry chooses +its checkout path on disk — either through its workspace-root section or an +entry-level `path:` override — an unchecked `.vcspull.yaml` inside a cloned +checkout could direct `vcspull sync` to clone into `~/.ssh/` or replace an entry +outside that checkout through nearest-wins precedence. + +v1.70.0 guarded against that by gating out-of-directory project files behind an +interactive `[y/N/always]` prompt, persisting approved project directories in +`$XDG_STATE_HOME/vcspull/trusted`, and shipping `vcspull trust`, +`--trust-project`, and `VCSPULL_YES=1`. When standard input was not a terminal, +loading an untrusted escaping project file raised +{exc}`~vcspull.exc.VCSPullError` and exited `1`. + +Using that mechanism across real workspaces exposed three structural mismatches +(`#600`, `#619`): + +- **Threat model mismatch.** Tools such as `mise` require explicit directory + trust because `mise activate` hooks into shell directory changes (`cd`) and + evaluates templates, environment variables, and task scripts automatically. + Declarative tools such as `uv`, by contrast, validate project files by schema + and confine project configuration to the project workspace without a `trust` + subcommand, interactive prompt, or external state file. `vcspull` has no shell + hook and executes no code or templates from YAML or JSON; its only upward-walk + hazard is a project file targeting paths outside its own directory. +- **Unbounded prompts and non-TTY failures.** Listing every escaping destination + before prompting flooded terminals on large multi-workspace manifests (`#600`), + and aborting non-interactive runs with exit `1` broke cron jobs, scripts, and + CI pipelines whenever a working directory happened to sit beneath an escaping + `.vcspull.yaml`. +- **Hidden mutable state.** Recording trust in `$XDG_STATE_HOME/vcspull/trusted` + made command behaviour depend on machine-local state outside the configuration + files themselves, and granting directory trust gave future commits in that + project standing permission to target arbitrary paths on disk. + +## Decision + +Upward-walked `project` configurations are governed by structural path +containment rather than interactive or stateful trust. + +### Scope boundaries + +1. `system` (`/etc/vcspull/*.{yaml,yml,json}`), `user` (the active user + configuration directory and `~/.vcspull.{yaml,json}`, including symlinked + dotfiles), and explicit `-f` / `--file` manifests may target any destination + path on disk. +2. A discovered `project` `.vcspull.{yaml,yml,json}` file is *contained* when + every repository destination it declares resolves at or beneath the directory + holding that file. Destination checks run on expanded entries — after + applying entry-level `path:` overrides, `~`, environment variables, and + following symlinks on both the destination and the project directory. +3. Contained `project` files join the scope stack automatically with no prompt + and no state file. + +### Out-of-directory project files + +4. A discovered `project` `.vcspull.*` file with one or more destinations + outside its directory is skipped when resolving the scope stack across + {ref}`vcspull sync `, {ref}`vcspull list `, + {ref}`vcspull status `, {ref}`vcspull search `, + {ref}`vcspull worktree `, `vcspull fmt --all`, + `vcspull migrate --all`, and writer handle checks. Remaining `system`, + `user`, and contained `project` files still load, and the command does not + prompt or fail. +5. In human-readable output, skipping an escaping project file logs one warning + line naming the skipped file, the directory boundary, `-f FILE`, and user + configuration: + + ```text + skipping ~/work/proj/.vcspull.yaml: project configs cannot target paths outside ~/work/proj (pass -f ~/work/proj/.vcspull.yaml or link it in user config) + ``` + +6. Commands emitting `--json` or `--ndjson` on `stdout` suppress that warning so + machine-readable streams stay valid JSON. +7. Single-file write commands ({ref}`vcspull add `, + {ref}`vcspull discover `, {ref}`vcspull fmt `, + {ref}`vcspull migrate `) refuse to modify an existing escaping + project file discovered by default, leaving the file untouched unless + `-f FILE` names it explicitly. + +### Diagnostics and overrides + +8. {ref}`vcspull config ls ` keeps skipped project files visible in + place as `(outside directory, skipped)` with a one-line explanation at the + bottom of the report. +9. `--no-project` and `VCSPULL_NO_PROJECT=1` remain available to skip upward + project discovery altogether. +10. Multi-directory workspace manifests that intentionally sync checkouts across + unrelated paths belong in `~/.vcspull.yaml`, `~/.config/vcspull/*.yaml` + (including symlinks to a versioned manifest), or an explicit + `vcspull sync --file path/to/repos.yaml` invocation. + +### Removed surfaces + +11. `vcspull trust`, `--trust-project`, `VCSPULL_YES`, + `$XDG_STATE_HOME/vcspull/trusted`, and + `vcspull.config.ensure_config_trusted` are removed. + {func}`vcspull.config.project_config_contained` replaces + `ensure_config_trusted` as the containment check for configuration writers. + +## Options considered + +### Structural project containment (chosen) + +Project files manage checkouts inside their own directory tree without ceremony, +and personal or machine-wide manifests manage checkouts anywhere on disk from +`user`, `system`, or `-f` scope. Nothing prompts, nothing blocks non-TTY +callers, and behaviour is a pure function of the files on disk and command-line +flags. + +The trade-off is that an upward-walked `.vcspull.yaml` inside `~/work/meta` +cannot sync `~/other/repo` unless invoked with `-f ~/work/meta/.vcspull.yaml` or +linked into `~/.config/vcspull/`. Rule 10 accepts that: cross-directory +workspace manifests describe user layout rather than a single self-contained +project checkout. + +### Interactive trust prompt and state file with bounded previews + +Keeping `vcspull trust` and `$XDG_STATE_HOME/vcspull/trusted` while truncating +the destination list in the prompt was prototyped for `#600`. Rejected: + +- Truncating the prompt hides most of the destinations the user is being asked + to authorize while preserving the stateful prompt machinery. +- Non-TTY runs inside a directory with an untrusted project file still fail with + exit `1`, breaking automation even when the user only wanted their + `~/.vcspull.yaml` entries. +- Approving a directory grants standing permission to future edits of + `.vcspull.yaml` in that directory. + +### Unconditional loading of all project files + +Loading every ancestor `.vcspull.*` file regardless of destination paths. +Rejected: + +- A `.vcspull.yaml` inside an untrusted checkout could write into `~/.ssh/` or + repoint a user checkout outside the project directory on the next + `vcspull sync`. + +## Consequences + +- Contained project `.vcspull.*` files work identically to v1.70.0–v1.72.0: + zero prompts, zero flags, and automatic upward discovery. +- Escaping project `.vcspull.*` files no longer prompt or abort non-TTY runs; + they are skipped with a one-line warning (or shown as skipped in + `vcspull config ls`) unless passed via `-f`. +- Existing scripts passing `vcspull trust`, `--trust-project`, or `VCSPULL_YES` + must switch to `--file FILE` or link the manifest under `~/.config/vcspull/`; + `vcspull trust` and `--trust-project` now exit `2` as unrecognized arguments, + and `$XDG_STATE_HOME/vcspull/trusted` is no longer read or written. + +## References + +- [#619](https://github.com/vcs-python/vcspull/issues/619): Replace + `vcspull trust` with structural project containment +- [#600](https://github.com/vcs-python/vcspull/issues/600): Symlinked + `~/.vcspull.yaml` triggers unbounded project trust prompt +- [#564](https://github.com/vcs-python/vcspull/issues/564): Configuration + scopes (`system`, `user`, `project`) +- [#592](https://github.com/vcs-python/vcspull/issues/592): Configuration and + CLI roadmap +- {ref}`config-scopes`: scope precedence, merging, and containment +- {ref}`cli-config`: `vcspull config ls` diagnostics diff --git a/docs/project/adr/index.md b/docs/project/adr/index.md index 3fee5d977..4ef562d11 100644 --- a/docs/project/adr/index.md +++ b/docs/project/adr/index.md @@ -8,4 +8,5 @@ Significant design decisions and their rationale. :maxdepth: 1 0001-repository-aliases +0002-structural-project-containment ``` diff --git a/docs/redirects.txt b/docs/redirects.txt index a86693b44..6a3c5ab95 100644 --- a/docs/redirects.txt +++ b/docs/redirects.txt @@ -21,3 +21,6 @@ # developing.md -> project/contributing.md "developing.md" "project/contributing.md" + +# cli/trust.md -> configuration/scopes.md +"cli/trust.md" "configuration/scopes.md" diff --git a/src/vcspull/_internal/scopes.py b/src/vcspull/_internal/scopes.py index 88ca514c5..952d91df6 100644 --- a/src/vcspull/_internal/scopes.py +++ b/src/vcspull/_internal/scopes.py @@ -1,6 +1,6 @@ -"""Configuration scope resolution and project trust. +"""Configuration scope resolution and structural project containment. -vcspull reads configuration from four scopes. Weakest first, every scope is +vcspull reads configuration from three scopes. Weakest first, every scope is unioned into one stack: ============ ========================================================= @@ -13,10 +13,8 @@ ============ ========================================================= Everything here is a resolver: it decides *which* files participate and -*whether* a project file may act, never what a file means. Nothing in this -module parses repository entries, and nothing prompts — a caller that needs -consent gets the list of offending destinations from :func:`requires_trust` -and decides how to ask. +*whether* a project file's destinations stay inside its directory, never what a +file means. """ from __future__ import annotations @@ -31,7 +29,7 @@ from collections.abc import Iterable, Mapping ConfigScope = t.Literal["system", "user", "project", "external"] -"""Where a configuration file lives, and therefore how much it is trusted.""" +"""Where a configuration file lives in the scope stack.""" CONFIG_SUFFIXES: t.Final = (".yaml", ".yml", ".json") """Recognized config suffixes, weakest first within a single directory.""" @@ -80,27 +78,8 @@ class ConfigSource(t.NamedTuple): path: pathlib.Path """Absolute path to the configuration file.""" - trust_root: pathlib.Path - """Directory whose trust governs this file. Its own directory, for a - project config; the containing scope directory otherwise.""" - - @property - def gated(self) -> bool: - """Return ``True`` when this source needs a containment check. - - Examples - -------- - >>> project = ConfigSource( - ... "project", pathlib.Path("/w/.vcspull.yaml"), pathlib.Path("/w") - ... ) - >>> project.gated - True - >>> ConfigSource( - ... "user", pathlib.Path("/h/.vcspull.yaml"), pathlib.Path("/h") - ... ).gated - False - """ - return self.scope == "project" + root: pathlib.Path + """Directory governing containment for a project file, or the scope directory.""" def env_flag(name: str, environ: Mapping[str, str] = os.environ) -> bool: @@ -115,11 +94,11 @@ def env_flag(name: str, environ: Mapping[str, str] = os.environ) -> bool: Examples -------- - >>> env_flag("VCSPULL_YES", {"VCSPULL_YES": "1"}) + >>> env_flag("VCSPULL_NO_PROJECT", {"VCSPULL_NO_PROJECT": "1"}) True - >>> env_flag("VCSPULL_YES", {"VCSPULL_YES": "0"}) + >>> env_flag("VCSPULL_NO_PROJECT", {"VCSPULL_NO_PROJECT": "0"}) False - >>> env_flag("VCSPULL_YES", {}) + >>> env_flag("VCSPULL_NO_PROJECT", {}) False """ return environ.get(name, "").strip().lower() in _TRUTHY @@ -314,13 +293,13 @@ def resolve_sources( def _append_source( scope: ConfigScope, path: pathlib.Path, - trust_root: pathlib.Path, + root: pathlib.Path, ) -> None: real_path = _real(path) if real_path in seen: return seen.add(real_path) - sources.append(ConfigSource(scope, path, trust_root)) + sources.append(ConfigSource(scope, path, root)) for path in _config_files_in(SYSTEM_CONFIG_DIR): _append_source("system", path, SYSTEM_CONFIG_DIR) @@ -531,9 +510,10 @@ def escaping_destinations( """Return the repository destinations that resolve outside *config_dir*. A configuration is *contained* when every repository it declares would be - checked out at or beneath the directory holding it. Containment is what - keeps the trust gate quiet for the overwhelming majority of project - configs, which target ``./vendor`` or a sibling checkout. + checked out at or beneath the directory holding it. Containment decides + whether a discovered project configuration joins the stack automatically: + entries inside ``./vendor`` or a subdirectory load, while entries outside + *config_dir* are skipped. The check is over destinations rather than the workspace-root keys, because a repository entry may override its destination with ``path:`` and never @@ -581,163 +561,3 @@ def escaping_destinations( escaping.append(resolved) return tuple(dict.fromkeys(escaping)) - - -def requires_trust( - source: ConfigSource, - destinations: Iterable[pathlib.Path], - *, - cwd: pathlib.Path, - trusted: frozenset[pathlib.Path], -) -> tuple[pathlib.Path, ...]: - """Return the destinations that need explicit consent before loading. - - Empty means the source may load silently: system, user, and explicit - configurations are automatic, an already-trusted project directory is - remembered, and a contained project config never asks. - - Parameters - ---------- - source : ConfigSource - Source under consideration. - destinations : Iterable[pathlib.Path] - Checkout destinations that file declares. - cwd : pathlib.Path - Working directory, used to resolve relative destinations. - trusted : frozenset of pathlib.Path - Resolved directories from :func:`read_trusted`. - - Examples - -------- - >>> project = tmp_path / "project" - >>> project.mkdir() - >>> source = ConfigSource("project", project / ".vcspull.yaml", project) - >>> escaping = [pathlib.Path("~/.ssh/evil")] - >>> requires_trust( - ... source, escaping, cwd=project, trusted=frozenset() - ... ) == (_real(pathlib.Path("~/.ssh/evil")),) - True - - A user-scope source is never gated, and neither is a trusted directory: - - >>> user = ConfigSource("user", tmp_path / "u.yaml", tmp_path) - >>> requires_trust(user, escaping, cwd=project, trusted=frozenset()) - () - >>> requires_trust( - ... source, escaping, cwd=project, trusted=frozenset({_real(project)}) - ... ) - () - """ - if not source.gated: - return () - if _real(source.trust_root) in trusted: - return () - return escaping_destinations( - destinations, - config_dir=source.trust_root, - cwd=cwd, - ) - - -def trust_state_file( - *, - home: pathlib.Path | None = None, - environ: Mapping[str, str] = os.environ, -) -> pathlib.Path: - """Return the file recording trusted project directories. - - Parameters - ---------- - home : pathlib.Path, optional - User home directory. Defaults to :meth:`pathlib.Path.home`. - environ : Mapping[str, str] - Environment to read from. Defaults to :data:`os.environ`. - - Examples - -------- - >>> trust_state_file( - ... home=pathlib.Path("/home/u"), environ={"XDG_STATE_HOME": "/state"} - ... ) - PosixPath('/state/vcspull/trusted') - >>> trust_state_file(home=pathlib.Path("/home/u"), environ={}) - PosixPath('/home/u/.local/state/vcspull/trusted') - """ - home = (home or pathlib.Path.home()).expanduser() - state_home = environ.get("XDG_STATE_HOME") - base = ( - pathlib.Path(state_home).expanduser() - if state_home - else home / ".local" / "state" - ) - return base / "vcspull" / "trusted" - - -def read_trusted(state_file: pathlib.Path) -> frozenset[pathlib.Path]: - """Return the trusted project directories recorded in *state_file*. - - A missing or unreadable state file means nothing is trusted yet. - - Examples - -------- - >>> read_trusted(tmp_path / "never-written") - frozenset() - >>> state = tmp_path / "trusted" - >>> write_trusted(state, [pathlib.Path("/w/api")]) - >>> read_trusted(state) - frozenset({PosixPath('/w/api')}) - """ - try: - content = state_file.read_text(encoding="utf-8") - except OSError: - return frozenset() - return frozenset( - pathlib.Path(line.strip()) for line in content.splitlines() if line.strip() - ) - - -def write_trusted( - state_file: pathlib.Path, - directories: Iterable[pathlib.Path], -) -> None: - """Record *directories* as the complete set of trusted project directories. - - Examples - -------- - >>> state = tmp_path / "state" / "trusted" - >>> write_trusted(state, [pathlib.Path("/w/b"), pathlib.Path("/w/a")]) - >>> state.read_text(encoding="utf-8").splitlines() - ['/w/a', '/w/b'] - """ - state_file.parent.mkdir(parents=True, exist_ok=True) - lines = sorted(str(directory) for directory in directories) - state_file.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8") - - -def trust_directory(state_file: pathlib.Path, directory: pathlib.Path) -> None: - """Add *directory* to the trusted set. - - The project directory is recorded rather than the file, so a second config - in an already-trusted project does not ask again. - - Examples - -------- - >>> state = tmp_path / "trusted" - >>> trust_directory(state, tmp_path / "api") - >>> _real(tmp_path / "api") in read_trusted(state) - True - """ - write_trusted(state_file, read_trusted(state_file) | {_real(directory)}) - - -def untrust_directory(state_file: pathlib.Path, directory: pathlib.Path) -> None: - """Remove *directory* from the trusted set. - - Examples - -------- - >>> state = tmp_path / "trusted" - >>> trust_directory(state, tmp_path / "api") - >>> untrust_directory(state, tmp_path / "api") - >>> read_trusted(state) - frozenset() - """ - write_trusted(state_file, read_trusted(state_file) - {_real(directory)}) diff --git a/src/vcspull/cli/__init__.py b/src/vcspull/cli/__init__.py index 2a6a4c325..a377d2d41 100644 --- a/src/vcspull/cli/__init__.py +++ b/src/vcspull/cli/__init__.py @@ -22,8 +22,6 @@ from .config import ( config_ls, create_config_subparser, - create_trust_subparser, - trust_command, ) from .discover import create_discover_subparser, discover_repos from .fmt import create_fmt_subparser, format_config_file @@ -388,28 +386,6 @@ def build_description( ), ) -TRUST_DESCRIPTION = build_description( - """ - Trust a project directory's configuration. - - A project config that would check a repository out beyond its own - directory needs your consent before vcspull will act on it. Trust is - recorded per directory, so a second config in the same project does not - re-ask. - """, - ( - ( - None, - [ - "vcspull trust", - "vcspull trust ~/work/api", - "vcspull trust --untrust ~/work/api", - "vcspull trust --show", - ], - ), - ), -) - WORKTREE_DESCRIPTION = build_description( """ Manage git worktrees for repositories. @@ -431,31 +407,9 @@ def build_description( ) -def _trust_parser() -> argparse.ArgumentParser: - """Return the shared parent parser carrying ``--trust-project``. - - Every command that may act on a project ``.vcspull.*`` accepts the trust - bypass, and the root parser inherits it too, so both - ``vcspull --trust-project sync`` and ``vcspull sync --trust-project`` - parse. ``SUPPRESS`` keeps the subcommand from clobbering a value the root - already set. - """ - parser = argparse.ArgumentParser(add_help=False) - parser.add_argument( - "--trust-project", - action="store_true", - default=argparse.SUPPRESS, - help=( - "load project configs that check repositories out beyond their " - "own directory (also VCSPULL_YES=1)" - ), - ) - return parser - - -def _scope_parser(trust: argparse.ArgumentParser) -> argparse.ArgumentParser: +def _scope_parser() -> argparse.ArgumentParser: """Return the shared parent parser for commands that resolve the stack.""" - parser = argparse.ArgumentParser(add_help=False, parents=[trust]) + parser = argparse.ArgumentParser(add_help=False) parser.add_argument( "--no-project", action="store_true", @@ -479,8 +433,7 @@ def create_parser( return_subparsers: bool = False, ) -> argparse.ArgumentParser | tuple[argparse.ArgumentParser, SubparserTuple]: """Create CLI argument parser for vcspull.""" - trust_parent = _trust_parser() - scope_parent = _scope_parser(trust_parent) + scope_parent = _scope_parser() parser = argparse.ArgumentParser( prog="vcspull", @@ -549,7 +502,7 @@ def create_parser( help="add a single repository", formatter_class=VcspullHelpFormatter, description=ADD_DESCRIPTION, - parents=[trust_parent], + parents=[scope_parent], ) create_add_subparser(add_parser) @@ -603,15 +556,6 @@ def create_parser( ) create_config_subparser(config_parser, scope_parent) - # Trust command - trust_parser = subparsers.add_parser( - "trust", - help="trust a project directory's configuration", - formatter_class=VcspullHelpFormatter, - description=TRUST_DESCRIPTION, - ) - create_trust_subparser(trust_parser) - # Worktree command worktree_parser = subparsers.add_parser( "worktree", @@ -644,7 +588,7 @@ def cli(_args: builtins.list[str] | None = None) -> None: """CLI entry point for vcspull. A :exc:`vcspull.exc.VCSPullError` is the tool telling you something - actionable — an untrusted project config, an unreadable file — so it is + actionable — an invalid configuration, an unreadable file — so it is reported as one line rather than a traceback. Run with ``--log-level debug`` to see the stack. """ @@ -714,7 +658,6 @@ def _run(_args: builtins.list[str] | None) -> None: jobs=getattr(args, "jobs", None), yes=getattr(args, "yes", False), include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) elif args.subparser_name == "list": list_repos( @@ -727,7 +670,6 @@ def _run(_args: builtins.list[str] | None) -> None: color=args.color, include_worktrees=getattr(args, "include_worktrees", False), include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) elif args.subparser_name == "status": status_repos( @@ -741,7 +683,6 @@ def _run(_args: builtins.list[str] | None) -> None: concurrent=not getattr(args, "no_concurrent", False), max_concurrent=getattr(args, "max_concurrent", None), include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) elif args.subparser_name == "search": if not args.query_terms: @@ -762,7 +703,6 @@ def _run(_args: builtins.list[str] | None) -> None: invert_match=getattr(args, "invert_match", False), match_any=getattr(args, "match_any", False), include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) elif args.subparser_name == "add": if not args.repo_path: @@ -779,7 +719,6 @@ def _run(_args: builtins.list[str] | None) -> None: recursive=args.recursive, workspace_root_override=args.workspace_root_path, yes=args.yes, - trust_project=getattr(args, "trust_project", False), dry_run=args.dry_run, merge_duplicates=args.merge_duplicates, include_worktrees=getattr(args, "include_worktrees", False), @@ -796,7 +735,6 @@ def _run(_args: builtins.list[str] | None) -> None: merge_roots=args.merge_roots, style=ConfigStyle(args.style) if args.style else None, include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) if result: raise SystemExit(result) @@ -806,7 +744,6 @@ def _run(_args: builtins.list[str] | None) -> None: args.write, args.all, include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) if result: raise SystemExit(result) @@ -824,13 +761,6 @@ def _run(_args: builtins.list[str] | None) -> None: return config_ls( include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), - ) - elif args.subparser_name == "trust": - trust_command( - args.directory, - untrust=args.untrust, - show=args.show, ) elif args.subparser_name == "worktree": handle_worktree_command(args) diff --git a/src/vcspull/cli/_formatter.py b/src/vcspull/cli/_formatter.py index 0725a8342..9d9a7c818 100644 --- a/src/vcspull/cli/_formatter.py +++ b/src/vcspull/cli/_formatter.py @@ -87,10 +87,7 @@ "--https", "--no-log-file", "--include-worktrees", - "--trust-project", "--no-project", - "--untrust", - "--show", "--sync", "--prune", "--prune-untracked", diff --git a/src/vcspull/cli/add.py b/src/vcspull/cli/add.py index ea94d9cef..658ecb3c8 100644 --- a/src/vcspull/cli/add.py +++ b/src/vcspull/cli/add.py @@ -33,11 +33,9 @@ canonicalize_workspace_path, check_alias_conflict, effective_entries, - ensure_config_trusted, entry_directory, expand_dir, expand_single_entry, - file_scope, find_home_config_files, get_pin_reason, is_pinned_for_op, @@ -45,6 +43,7 @@ loader_order, merge_duplicate_workspace_roots, normalize_config_file_path, + project_config_contained, project_handle_warning, render_config_items, resolve_clone_depth, @@ -1035,7 +1034,6 @@ def _plan_alias_target( known: collections.abc.Sequence[KnownEntry], cwd: pathlib.Path, include_project: bool = True, - trust_project: bool = False, ) -> _AliasPlan: """Resolve which entry ``add PATH --alias X`` edits, or why it refuses. @@ -1053,7 +1051,6 @@ def _plan_alias_target( stack_scope: dict[str, ScopeLabel] = {} files: list[pathlib.Path] = [] known_real = {os.path.realpath(entry.file) for entry in known} - consent = trust_project or scopes.env_flag("VCSPULL_YES") for source_path, source_scope in active_scope_files( cwd=cwd, include_project=include_project ): @@ -1063,7 +1060,6 @@ def _plan_alias_target( if ( source_scope == "project" and real not in known_real - and not consent and source_escapes( scopes.ConfigSource("project", source_path, source_path.parent), cwd=cwd, @@ -1825,7 +1821,6 @@ def _preflight_alias( config_file_path: pathlib.Path, explicit: bool, include_project: bool, - trust_project: bool, cwd: pathlib.Path, report_unreadable: bool = True, flags: _AttachFlags | None = None, @@ -1842,7 +1837,6 @@ def _preflight_alias( known = known_entries_for_writer( cwd=cwd, include_project=include_project, - trust_project=trust_project, report=report_unreadable, expanded=expanded, ) @@ -1854,7 +1848,6 @@ def _preflight_alias( known=known, cwd=cwd, include_project=include_project, - trust_project=trust_project, ) if plan.refusal: return _Preflight( @@ -1976,7 +1969,7 @@ class _ConfiguredForAttach(t.NamedTuple): expanded : dict[str, list[ConfigDict]] Cached expanded repository entries by real file path. problems : list[str] - Diagnostics for unreadable or untrusted scope files. + Diagnostics for unreadable or skipped scope files. """ known: list[KnownEntry] @@ -2006,13 +1999,11 @@ def _configured_for_attach( if resolution.ambiguous or resolution.path is None: return None include_project = not getattr(args, "no_project", False) - trust_project = getattr(args, "trust_project", False) expanded: dict[str, list[ConfigDict]] = {} problems: list[str] = [] known = known_entries_for_writer( cwd=cwd, include_project=include_project, - trust_project=trust_project, report=False, expanded=expanded, problems=problems, @@ -2024,23 +2015,10 @@ def _configured_for_attach( known=known, cwd=cwd, include_project=include_project, - trust_project=trust_project, ) return _ConfiguredForAttach(known, plan, expanded, problems) -def _trust_may_ask( - config_file_path: pathlib.Path, - *, - named: bool, - trust_project: bool, -) -> bool: - """Return whether :func:`ensure_config_trusted` may have waited for input.""" - if named or trust_project or scopes.env_flag("VCSPULL_YES"): - return False - return config_file_path.is_file() and file_scope(config_file_path) == "project" - - def handle_add_command(args: argparse.Namespace) -> None: """Entry point for the ``vcspull add`` CLI command.""" repo_input = getattr(args, "repo_path", None) @@ -2238,7 +2216,6 @@ def announce_placement() -> None: config_file_path=config_file_path, explicit=bool(getattr(args, "config", None)), include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), cwd=cwd, flags=_AttachFlags( pin=pin_rev, @@ -2457,7 +2434,6 @@ def announce_placement() -> None: workspace_root_path=workspace_root_input, dry_run=args.dry_run, merge_duplicates=args.merge_duplicates, - trust_project=getattr(args, "trust_project", False), rev=effective_rev, shallow=shallow, depth=depth, @@ -2478,7 +2454,6 @@ def add_repo( dry_run: bool, *, merge_duplicates: bool = True, - trust_project: bool = False, rev: str | None = None, shallow: bool = False, depth: int | None = None, @@ -2566,7 +2541,6 @@ def add_repo( config_file_path=config_file_path, explicit=named, include_project=include_project, - trust_project=trust_project, cwd=cwd, report_unreadable=report_unreadable, flags=attach_flags, @@ -2586,35 +2560,20 @@ def add_repo( log.error("%s", preflight.refusal) return - if not ensure_config_trusted( + display_config_path = str(PrivatePath(config_file_path)) + if not project_config_contained( config_file_path, - trust_project=trust_project, + cwd=cwd, explicit=bool(config_file_path_str), + report=False, ): - return - - if alias is not None and _trust_may_ask( - config_file_path, named=named, trust_project=trust_project - ): - preflight = _preflight_alias( - name=name, - alias=alias, - workspace_path=workspace_path, - checkout=checkout, - config_file_path=config_file_path, - explicit=named, - include_project=include_project, - trust_project=trust_project, - cwd=cwd, - report_unreadable=False, - flags=attach_flags, - path_mode=path is not None, + root = PrivatePath(os.path.realpath(config_file_path.parent)) + msg = ( + f"refusing to modify {display_config_path}: project configs cannot " + f"target paths outside {root} (pass -f {display_config_path})" ) - if preflight.refusal: - log.error("%s", preflight.refusal) - return + raise VCSPullError(msg) - display_config_path = str(PrivatePath(config_file_path)) if alias is not None and preflight is not None and preflight.located is not None: attach_file = preflight.plan.target or config_file_path _attach_alias( diff --git a/src/vcspull/cli/config.py b/src/vcspull/cli/config.py index 185c04090..e7f78e650 100644 --- a/src/vcspull/cli/config.py +++ b/src/vcspull/cli/config.py @@ -1,10 +1,9 @@ -"""Configuration scope introspection and project trust for vcspull.""" +"""Configuration scope introspection for vcspull.""" from __future__ import annotations import collections.abc import logging -import os import pathlib import typing as t @@ -40,8 +39,8 @@ def create_config_subparser( parser : argparse.ArgumentParser The ``config`` command parser. scope_parent : argparse.ArgumentParser - Shared parent carrying ``--no-project`` and ``--trust-project``, so - they parse after ``ls`` as well as before ``config``. + Shared parent carrying ``--no-project``, so it parses after ``ls`` as + well as before ``config``. """ subparsers = parser.add_subparsers(dest="config_command") subparsers.add_parser( @@ -51,27 +50,6 @@ def create_config_subparser( ) -def create_trust_subparser(parser: argparse.ArgumentParser) -> None: - """Create ``vcspull trust`` argument subparser.""" - parser.add_argument( - "directory", - metavar="DIR", - nargs="?", - help="project directory to trust (default: current directory)", - ) - group = parser.add_mutually_exclusive_group() - group.add_argument( - "--untrust", - action="store_true", - help="remove the directory from the trusted set", - ) - group.add_argument( - "--show", - action="store_true", - help="print the trusted project directories and exit", - ) - - def _plural(count: int, singular: str, plural: str | None = None) -> str: """Return *count* with a correctly inflected noun. @@ -87,20 +65,20 @@ def _plural(count: int, singular: str, plural: str | None = None) -> str: return f"{count} {singular if count == 1 else plural or singular + 's'}" -def _note(declared: int, effective: int, *, untrusted: bool) -> str: +def _note(declared: int, effective: int, *, skipped: bool) -> str: """Return the parenthetical explaining why a file's count is not its whole. Examples -------- - >>> _note(2, 2, untrusted=False) + >>> _note(2, 2, skipped=False) '' - >>> _note(2, 1, untrusted=False) + >>> _note(2, 1, skipped=False) ' (1 overridden)' - >>> _note(2, 0, untrusted=True) - ' (untrusted)' + >>> _note(2, 0, skipped=True) + ' (outside directory, skipped)' """ - if untrusted: - return " (untrusted)" + if skipped: + return " (outside directory, skipped)" overridden = declared - effective return f" ({overridden} overridden)" if overridden else "" @@ -141,14 +119,15 @@ class _ScopeRow(t.NamedTuple): Display path of the configuration file. declared : list[pathlib.Path] Merge identities declared in the configuration file. - untrusted : bool - Whether the file is an escaping project config awaiting trust. + skipped : bool + Whether the file is a project config skipped for targeting paths outside + its directory. """ scope: str path: str declared: list[pathlib.Path] - untrusted: bool + skipped: bool _AUDIT_SECTIONS = ( @@ -170,13 +149,12 @@ def _print_handle_audit( sources: collections.abc.Sequence[scopes.ConfigSource], *, cwd: pathlib.Path, - trust_project: bool, ) -> None: """Print every handle notice of the merge, grouped by kind.""" by_path = {source.path: source for source in sources} def gate(path: pathlib.Path, _repos: collections.abc.Sequence[ConfigDict]) -> bool: - return trust_project or not source_escapes(by_path[path], cwd=cwd) + return not source_escapes(by_path[path], cwd=cwd) try: notices = handle_notices( @@ -202,23 +180,20 @@ def gate(path: pathlib.Path, _repos: collections.abc.Sequence[ConfigDict]) -> bo def config_ls( *, include_project: bool = True, - trust_project: bool = False, cwd: pathlib.Path | None = None, ) -> None: """Print the configuration scopes in effect, weakest first. Each row is a file, its scope, and how many repositories it declares. A file whose entries are overridden by a nearer one says so, and a project - file awaiting trust is listed as untrusted rather than silently dropped — - this is the command you reach for when ``vcspull list`` refuses to load - something. + file whose destinations resolve outside its directory is shown as skipped + rather than omitted — this is the command you reach for when a project file + did not join the stack. Parameters ---------- include_project : bool Set ``False`` to show the stack as ``--no-project`` resolves it. - trust_project : bool - Treat escaping project configs as trusted, as ``--trust-project`` does. cwd : pathlib.Path, optional Working directory. Defaults to :meth:`pathlib.Path.cwd`. """ @@ -234,11 +209,11 @@ def config_ls( for index, source in enumerate(sources): declared = _declared_repos(source.path, cwd) - untrusted = not trust_project and bool(source_escapes(source, cwd=cwd)) + skipped = bool(source_escapes(source, cwd=cwd)) rows.append( - _ScopeRow(source.scope, str(PrivatePath(source.path)), declared, untrusted), + _ScopeRow(source.scope, str(PrivatePath(source.path)), declared, skipped), ) - if untrusted: + if skipped: continue for key in declared: winner[key] = index @@ -251,69 +226,14 @@ def config_ls( count = _plural(len(row.declared), "repo") + _note( len(row.declared), effective, - untrusted=row.untrusted, + skipped=row.skipped, ) print(f"{row.scope:<{scope_width}} {row.path:<{path_width}} {count}") print(f"\n{_plural(len(winner), 'repository', 'repositories')} in effect.") - _print_handle_audit(sources, cwd=cwd, trust_project=trust_project) - if any(row.untrusted for row in rows): - print("Untrusted configs are not loaded. Allow one with 'vcspull trust DIR'.") - - -def trust_command( - directory: str | None, - *, - untrust: bool = False, - show: bool = False, - state_file: pathlib.Path | None = None, -) -> None: - """Record, remove, or print trusted project directories. - - Parameters - ---------- - directory : str | None - Directory to trust or untrust. Defaults to the current directory. - untrust : bool - Remove the directory instead of adding it. - show : bool - Print the trusted set and make no change. - state_file : pathlib.Path, optional - File holding the record. Defaults to - :func:`vcspull._internal.scopes.trust_state_file`. - - Examples - -------- - >>> state = tmp_path / "trusted" - >>> trust_command(None, show=True, state_file=state) - no trusted project directories - >>> api = tmp_path / "api" - >>> api.mkdir() - >>> trust_command(str(api), state_file=state) # doctest: +ELLIPSIS - trusted ...api - >>> scopes.read_trusted(state) == frozenset({api}) - True - >>> trust_command(str(api), untrust=True, state_file=state) # doctest: +ELLIPSIS - untrusted ...api - >>> scopes.read_trusted(state) - frozenset() - """ - state_file = state_file or scopes.trust_state_file() - - if show: - trusted = sorted(scopes.read_trusted(state_file)) - if not trusted: - print("no trusted project directories") - for entry in trusted: - print(PrivatePath(entry)) - return - - raw = pathlib.Path(directory).expanduser() if directory else pathlib.Path.cwd() - target = PrivatePath(os.path.realpath(raw)) - - if untrust: - scopes.untrust_directory(state_file, raw) - print(f"untrusted {target}") - else: - scopes.trust_directory(state_file, raw) - print(f"trusted {target}") + _print_handle_audit(sources, cwd=cwd) + if any(row.skipped for row in rows): + print( + "Skipped project configs target paths outside their directory; " + "pass '-f FILE' or link them in user config." + ) diff --git a/src/vcspull/cli/discover.py b/src/vcspull/cli/discover.py index d0808af54..13327023e 100644 --- a/src/vcspull/cli/discover.py +++ b/src/vcspull/cli/discover.py @@ -21,7 +21,6 @@ build_repo_entry, canonicalize_workspace_path, check_alias_conflict, - ensure_config_trusted, expand_dir, find_home_config_files, find_raw_entry_at_checkout, @@ -31,6 +30,7 @@ merge_duplicate_workspace_roots, normalize_config_file_path, normalize_workspace_roots, + project_config_contained, project_handle_warning, resolve_clone_depth, save_config, @@ -312,7 +312,6 @@ def discover_repos( yes: bool, dry_run: bool, *, - trust_project: bool = False, merge_duplicates: bool = True, include_worktrees: bool = False, rev: str | None = None, @@ -387,13 +386,18 @@ def discover_repos( config_scope = classify_scope(config_file_path, cwd=cwd, home=home) allow_relative_workspace = config_scope == "project" - if not ensure_config_trusted( + if not project_config_contained( config_file_path, cwd=cwd, - trust_project=trust_project, explicit=bool(config_file_path_str), + report=False, ): - return + root = PrivatePath(os.path.realpath(config_file_path.parent)) + msg = ( + f"refusing to modify {display_config_path}: project configs cannot " + f"target paths outside {root} (pass -f {display_config_path})" + ) + raise VCSPullError(msg) raw_config: dict[str, object] duplicate_root_occurrences: dict[str, list[object]] @@ -623,7 +627,6 @@ def discover_repos( known = known_entries_for_writer( cwd=cwd, include_project=include_project, - trust_project=trust_project, ) explicit_target = bool(config_file_path_str) target_in_stack = not explicit_target or os.path.realpath(config_file_path) in { diff --git a/src/vcspull/cli/fmt.py b/src/vcspull/cli/fmt.py index e38af2e1d..b01c77d6e 100644 --- a/src/vcspull/cli/fmt.py +++ b/src/vcspull/cli/fmt.py @@ -20,7 +20,6 @@ from vcspull.config import ( canonicalize_workspace_path, duplicate_alias_drops, - ensure_config_trusted, file_handle_notices, file_scope, find_home_config_files, @@ -29,6 +28,7 @@ migrate_repo_entry, normalize_config_file_path, normalize_workspace_roots, + project_config_contained, save_config, ) from vcspull.types import ConfigStyle @@ -394,7 +394,6 @@ def format_single_config( *, merge_roots: bool, style: ConfigStyle | None = None, - trust_project: bool = False, explicit: bool = True, ) -> bool: """Format a single vcspull configuration file. @@ -407,8 +406,6 @@ def format_single_config( Whether to write changes back to file merge_roots : bool Merge duplicate workspace roots when True (default behavior) - trust_project : bool - Trust an escaping project config without prompting. explicit : bool The caller named this file with ``--file``. @@ -432,9 +429,8 @@ def format_single_config( ) return False - if not ensure_config_trusted( + if not project_config_contained( config_file_path, - trust_project=trust_project, explicit=explicit, ): return False @@ -712,7 +708,6 @@ def format_config_file( merge_roots: bool = True, style: ConfigStyle | None = None, include_project: bool = True, - trust_project: bool = False, ) -> int: """Format vcspull configuration file(s). @@ -730,8 +725,6 @@ def format_config_file( Optional target output style for repository entries include_project : bool Include ``.vcspull.*`` files found above the working directory. - trust_project : bool - Trust escaping project configs without prompting. Returns ------- @@ -747,6 +740,7 @@ def format_config_file( cwd=cwd, include_project=include_project, ) + if project_config_contained(source.path, cwd=cwd, explicit=False) ] if not config_files: @@ -787,7 +781,6 @@ def format_config_file( write, merge_roots=merge_roots, style=style, - trust_project=trust_project, explicit=False, ): success_count += 1 @@ -845,7 +838,6 @@ def format_config_file( write, merge_roots=merge_roots, style=style, - trust_project=trust_project, explicit=bool(config_file_path_str), ) ) diff --git a/src/vcspull/cli/import_cmd/_common.py b/src/vcspull/cli/import_cmd/_common.py index c9313d011..59c03e6ab 100644 --- a/src/vcspull/cli/import_cmd/_common.py +++ b/src/vcspull/cli/import_cmd/_common.py @@ -631,15 +631,6 @@ def _create_shared_parent() -> argparse.ArgumentParser: default="auto", help="When to use colors (default: auto)", ) - parent.add_argument( - "--trust-project", - action="store_true", - default=argparse.SUPPRESS, - help=( - "load project configs that check repositories out beyond their " - "own directory (also VCSPULL_YES=1)" - ), - ) parent.add_argument( "--no-project", action="store_true", @@ -772,7 +763,6 @@ def _run_import( prune_untracked: bool = False, import_source: str | None = None, include_project: bool = True, - trust_project: bool = False, ) -> int: """Run the import workflow for a single service. @@ -839,8 +829,6 @@ def _run_import( and stale tagged entries are pruned when ``sync`` is True. include_project : bool Whether project configs count when checking for handle collisions. - trust_project : bool - Whether escaping project configs are trusted without prompting. Returns ------- @@ -1082,7 +1070,7 @@ def _run_import( known = known_entries_for_writer( cwd=cwd, include_project=include_project, - trust_project=trust_project, + report=is_human, ) target_in_stack = not explicit_target or os.path.realpath(config_file_path) in { os.path.realpath(file) diff --git a/src/vcspull/cli/import_cmd/codeberg.py b/src/vcspull/cli/import_cmd/codeberg.py index 9be7ed0ce..d28d88e99 100644 --- a/src/vcspull/cli/import_cmd/codeberg.py +++ b/src/vcspull/cli/import_cmd/codeberg.py @@ -86,5 +86,4 @@ def handle_codeberg(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"codeberg:{args.target}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/import_cmd/codecommit.py b/src/vcspull/cli/import_cmd/codecommit.py index 07d70408b..4e532adf2 100644 --- a/src/vcspull/cli/import_cmd/codecommit.py +++ b/src/vcspull/cli/import_cmd/codecommit.py @@ -106,5 +106,4 @@ def handle_codecommit(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"codecommit:{getattr(args, 'target', '') or '*'}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/import_cmd/forgejo.py b/src/vcspull/cli/import_cmd/forgejo.py index 495d08969..85549dbfe 100644 --- a/src/vcspull/cli/import_cmd/forgejo.py +++ b/src/vcspull/cli/import_cmd/forgejo.py @@ -93,5 +93,4 @@ def handle_forgejo(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"forgejo:{args.target}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/import_cmd/gitea.py b/src/vcspull/cli/import_cmd/gitea.py index c63435d5d..4a6d4ff08 100644 --- a/src/vcspull/cli/import_cmd/gitea.py +++ b/src/vcspull/cli/import_cmd/gitea.py @@ -93,5 +93,4 @@ def handle_gitea(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"gitea:{args.target}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/import_cmd/github.py b/src/vcspull/cli/import_cmd/github.py index e47ee1b95..124dcaed9 100644 --- a/src/vcspull/cli/import_cmd/github.py +++ b/src/vcspull/cli/import_cmd/github.py @@ -95,5 +95,4 @@ def handle_github(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"github:{args.target}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/import_cmd/gitlab.py b/src/vcspull/cli/import_cmd/gitlab.py index fca1fd90d..416ef6173 100644 --- a/src/vcspull/cli/import_cmd/gitlab.py +++ b/src/vcspull/cli/import_cmd/gitlab.py @@ -129,5 +129,4 @@ def handle_gitlab(args: argparse.Namespace) -> int: prune_untracked=getattr(args, "prune_untracked", False), import_source=f"gitlab:{normalized_target}", include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), ) diff --git a/src/vcspull/cli/list.py b/src/vcspull/cli/list.py index d6e477f32..4c7a8ced5 100644 --- a/src/vcspull/cli/list.py +++ b/src/vcspull/cli/list.py @@ -90,7 +90,6 @@ def list_repos( color: str, include_worktrees: bool = False, include_project: bool = True, - trust_project: bool = False, ) -> None: """List configured repositories. @@ -114,14 +113,12 @@ def list_repos( Include configured worktrees in the listing (default: False) include_project : bool Include ``.vcspull.*`` files found above the working directory - trust_project : bool - Trust project configs that check repositories out beyond their directory """ # Load configs configs = load_scoped_configs( config_path, include_project=include_project, - trust_project=trust_project, + report=not (output_json or output_ndjson), terms=repo_patterns or (), ) diff --git a/src/vcspull/cli/migrate.py b/src/vcspull/cli/migrate.py index 66f5a544d..11465286c 100644 --- a/src/vcspull/cli/migrate.py +++ b/src/vcspull/cli/migrate.py @@ -18,10 +18,10 @@ ) from vcspull._internal.private_path import PrivatePath from vcspull.config import ( - ensure_config_trusted, find_home_config_files, migrate_repo_entry, normalize_config_file_path, + project_config_contained, save_config, save_config_yaml_with_items, ) @@ -122,7 +122,6 @@ def migrate_single_config( config_file_path: pathlib.Path, write: bool, *, - trust_project: bool = False, explicit: bool = True, ) -> bool: """Migrate a single vcspull configuration file. @@ -133,8 +132,6 @@ def migrate_single_config( Path to config file. write : bool Whether to write changes back to file. - trust_project : bool - Trust an escaping project config without prompting. explicit : bool The caller named this file with ``--file``. @@ -156,9 +153,8 @@ def migrate_single_config( ) return False - if not ensure_config_trusted( + if not project_config_contained( config_file_path, - trust_project=trust_project, explicit=explicit, ): return False @@ -308,7 +304,6 @@ def migrate_config_file( migrate_all: bool = False, *, include_project: bool = True, - trust_project: bool = False, ) -> int: """Migrate configuration files and return zero when every file succeeds. @@ -322,8 +317,6 @@ def migrate_config_file( If True, migrate all discovered config files. include_project : bool Include ``.vcspull.*`` files found above the working directory. - trust_project : bool - Trust escaping project configs without prompting. Returns ------- @@ -338,6 +331,7 @@ def migrate_config_file( cwd=cwd, include_project=include_project, ) + if project_config_contained(source.path, cwd=cwd, explicit=False) ] if not config_files: @@ -373,7 +367,6 @@ def migrate_config_file( if migrate_single_config( config_file, write, - trust_project=trust_project, explicit=False, ): success_count += 1 @@ -424,7 +417,6 @@ def migrate_config_file( not migrate_single_config( config_file_path, write, - trust_project=trust_project, explicit=bool(config_file_path_str), ) ) diff --git a/src/vcspull/cli/search.py b/src/vcspull/cli/search.py index 6f7799e17..fb925dc89 100644 --- a/src/vcspull/cli/search.py +++ b/src/vcspull/cli/search.py @@ -660,7 +660,6 @@ def search_repos( match_any: bool, emit_output: bool = True, include_project: bool = True, - trust_project: bool = False, ) -> list[dict[str, t.Any]]: """Search configured repositories. @@ -696,8 +695,6 @@ def search_repos( Whether to emit human/JSON output include_project : bool Include ``.vcspull.*`` files found above the working directory - trust_project : bool - Trust project configs that check repositories out beyond their directory Returns ------- @@ -735,7 +732,7 @@ def search_repos( configs = load_scoped_configs( config_path, include_project=include_project, - trust_project=trust_project, + report=emit_output and not (output_json or output_ndjson), notices_out=notices, ) diff --git a/src/vcspull/cli/status.py b/src/vcspull/cli/status.py index 79d528fb6..92ccd16c2 100644 --- a/src/vcspull/cli/status.py +++ b/src/vcspull/cli/status.py @@ -439,7 +439,6 @@ def status_repos( concurrent: bool = True, max_concurrent: int | None = None, include_project: bool = True, - trust_project: bool = False, ) -> None: """Check status of configured repositories. @@ -465,14 +464,12 @@ def status_repos( Maximum concurrent status checks (default: based on CPU count) include_project : bool Include ``.vcspull.*`` files found above the working directory - trust_project : bool - Trust project configs that check repositories out beyond their directory """ # Load configs configs = load_scoped_configs( config_path, include_project=include_project, - trust_project=trust_project, + report=not (output_json or output_ndjson), terms=repo_patterns or (), ) diff --git a/src/vcspull/cli/sync.py b/src/vcspull/cli/sync.py index 4e94cb791..ffb1cb89d 100644 --- a/src/vcspull/cli/sync.py +++ b/src/vcspull/cli/sync.py @@ -1425,7 +1425,6 @@ def sync( jobs: int | None = None, yes: bool = False, include_project: bool = True, - trust_project: bool = False, ) -> None: """Entry point for ``vcspull sync``.""" # Prevent git from blocking on credential prompts during batch sync @@ -1483,7 +1482,6 @@ def sync( jobs=resolved_jobs, yes=yes, include_project=include_project, - trust_project=trust_project, ) except KeyboardInterrupt as err: # Catch Ctrl-C from ANY phase of the sync -- the repo loop (where @@ -1541,7 +1539,6 @@ def _sync_impl( jobs: int = 1, yes: bool = False, include_project: bool = True, - trust_project: bool = False, ) -> None: """Run the core body of :func:`sync`. @@ -1585,8 +1582,8 @@ def _sync_impl( configs = load_scoped_configs( config, include_project=include_project, - trust_project=trust_project, warn_legacy_options=True, + report=not (output_json or output_ndjson), terms=name_terms, ) found_repos: list[ConfigDict] = [] diff --git a/src/vcspull/cli/worktree.py b/src/vcspull/cli/worktree.py index ede72a52d..1a93bcc87 100644 --- a/src/vcspull/cli/worktree.py +++ b/src/vcspull/cli/worktree.py @@ -170,7 +170,9 @@ def handle_worktree_command(args: argparse.Namespace) -> None: configs = load_scoped_configs( config_path, include_project=not getattr(args, "no_project", False), - trust_project=getattr(args, "trust_project", False), + report=not ( + getattr(args, "output_json", False) or getattr(args, "output_ndjson", False) + ), terms=args.repo_patterns or (), ) diff --git a/src/vcspull/config.py b/src/vcspull/config.py index 2e474d83f..5dfc14bf5 100644 --- a/src/vcspull/config.py +++ b/src/vcspull/config.py @@ -12,7 +12,6 @@ import os import pathlib import subprocess -import sys import tempfile import typing as t from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence @@ -1589,22 +1588,35 @@ def _entries_diverge(displaced: ConfigDict, winner: ConfigDict) -> bool: ) +def _warn_escaping_project_source(source: scopes.ConfigSource) -> None: + """Emit a one-line warning when a discovered project config escapes its root.""" + cfg = PrivatePath(source.path) + root = PrivatePath(os.path.realpath(source.root)) + log.warning( + "skipping %s: project configs cannot target paths outside %s " + "(pass -f %s or link it in user config)", + cfg, + root, + cfg, + ) + + def load_scoped_configs( config_path: pathlib.Path | None = None, *, cwd: pathlib.Path | None = None, include_project: bool = True, - trust_project: bool = False, warn_legacy_options: bool = True, + report: bool = True, terms: Sequence[str] = (), notices_out: list[HandleNotice] | None = None, ) -> list[ConfigDict]: """Return every repository the configuration scopes in effect define. An explicit *config_path* replaces the whole stack. Otherwise the system, - user, and project scopes are unioned nearest-wins, and each project config - that would check a repository out beyond its own directory must be trusted - first. + user, and project scopes are unioned nearest-wins, and any project config + whose destinations resolve outside its own directory is skipped with a + warning. Parameters ---------- @@ -1614,21 +1626,16 @@ def load_scoped_configs( Working directory the project walk starts from. include_project : bool Set ``False`` to skip the project scope entirely (``--no-project``). - trust_project : bool - Trust escaping project configs without prompting - (``--trust-project``). warn_legacy_options : bool Warn about entries still using top-level ``rev``/``shallow``/``depth``. + report : bool + Log warnings when skipping out-of-directory project configs. Set + ``False`` when emitting machine-readable ``--json`` / ``--ndjson`` + streams on ``stdout``. terms : Sequence[str] Terms of the command; see :func:`load_configs`. notices_out : list of HandleNotice, optional Receives every handle notice; see :func:`load_configs`. - - Raises - ------ - exc.VCSPullError - When an escaping project config cannot be confirmed because there is no - terminal to ask on. """ cwd = cwd or pathlib.Path.cwd() @@ -1644,25 +1651,21 @@ def load_scoped_configs( sources = scopes.resolve_sources(cwd=cwd, include_project=include_project) by_path = {source.path: source for source in sources} - state_file = scopes.trust_state_file() - trusted = scopes.read_trusted(state_file) def gate(path: pathlib.Path, repos: Sequence[ConfigDict]) -> bool: source = by_path[path] - escaping = scopes.requires_trust( - source, + if source.scope != "project": + return True + escaping = scopes.escaping_destinations( repo_destinations(repos), + config_dir=source.root, cwd=cwd, - trusted=trusted, ) if not escaping: return True - return _authorize_config( - source, - escaping, - state_file=state_file, - trust_project=trust_project, - ) + if report: + _warn_escaping_project_source(source) + return False return load_configs( [source.path for source in sources], @@ -1781,7 +1784,6 @@ def _load_known_entries( *, cwd: pathlib.Path | None = None, include_project: bool = True, - trust_project: bool = False, report: bool = True, expanded: dict[str, list[ConfigDict]] | None = None, problems: list[str] | None = None, @@ -1789,8 +1791,6 @@ def _load_known_entries( """Return effective post-merge entries across the configuration scopes in effect.""" cwd = cwd or pathlib.Path.cwd() sources = scopes.resolve_sources(cwd=cwd, include_project=include_project) - trusted = scopes.read_trusted(scopes.trust_state_file()) - consent = trust_project or scopes.env_flag("VCSPULL_YES") valid_sources: list[scopes.ConfigSource] = [] cached = expanded if expanded is not None else {} for source in sources: @@ -1823,17 +1823,20 @@ def _load_known_entries( log.warning("%s", line) continue cached[os.path.realpath(source.path)] = repos - escaping = scopes.requires_trust( - source, - repo_destinations(repos), - cwd=cwd, - trusted=trusted, + escaping = ( + scopes.escaping_destinations( + repo_destinations(repos), + config_dir=source.root, + cwd=cwd, + ) + if source.scope == "project" + else () ) - if escaping and not consent: + if escaping: line = ( - f"{PrivatePath(source.path)} is an untrusted project config; " - "handles in it were not checked (pass --trust-project to " - "include it)" + f"{PrivatePath(source.path)} targets paths outside " + f"{PrivatePath(os.path.realpath(source.root))} and was skipped; " + "handles in it were not checked" ) if problems is not None: problems.append(line) @@ -2113,7 +2116,6 @@ def known_entries_for_writer( *, cwd: pathlib.Path | None = None, include_project: bool = True, - trust_project: bool = False, report: bool = True, expanded: dict[str, list[ConfigDict]] | None = None, problems: list[str] | None = None, @@ -2135,7 +2137,6 @@ def known_entries_for_writer( return _load_known_entries( cwd=cwd, include_project=include_project, - trust_project=trust_project, report=report, expanded=expanded, problems=problems, @@ -2167,10 +2168,10 @@ def source_escapes( *, cwd: pathlib.Path, ) -> tuple[pathlib.Path, ...]: - """Return the destinations *source* declares that need consent, if any. + """Return the destinations *source* declares outside its project directory. - Never prompts and never raises, so a reporting command can ask the same - question the loader does without changing anything. + Never raises, so a reporting command can inspect the same structural + containment boundary the loader enforces. Parameters ---------- @@ -2179,6 +2180,8 @@ def source_escapes( cwd : pathlib.Path Working directory, used to resolve relative destinations. """ + if source.scope != "project": + return () try: content, _duplicates, _items = DuplicateAwareConfigReader.load_with_duplicates( source.path, @@ -2199,33 +2202,27 @@ def source_escapes( # An unreadable config declares no destinations, so it cannot escape. # Let the caller's own load report the real parse error. return () - return scopes.requires_trust( - source, + return scopes.escaping_destinations( destinations, + config_dir=source.root, cwd=cwd, - trusted=scopes.read_trusted(scopes.trust_state_file()), ) -def ensure_config_trusted( +def project_config_contained( config_path: pathlib.Path, *, cwd: pathlib.Path | None = None, - trust_project: bool = False, explicit: bool = False, + report: bool = True, ) -> bool: - """Return whether a write command may target *config_path*. - - A repository that ships a configuration redirecting your writes deserves - the same gate as one that redirects your clones, so ``add``, ``discover``, - ``fmt``, and ``migrate`` ask this before touching a project file vcspull - found on its own. Files that do not exist yet, and files outside the - project scope, are always allowed. + """Return whether a write command may modify *config_path*. - Naming a file with ``--file`` is consent, and *explicit* says so. The read - path does not gate ``--file`` either — it replaces the stack rather than - joining the project tier — and gating a reformat of a file you named while - ``vcspull sync --file`` clones from it freely would be incoherent. + ``add``, ``discover``, ``fmt``, and ``migrate`` call this before touching a + project file discovered without ``--file``. Files that do not exist yet, + explicit ``--file`` targets, and files outside the project scope are + allowed; an existing project file whose entries escape its directory is + skipped. Parameters ---------- @@ -2233,16 +2230,16 @@ def ensure_config_trusted( File the command is about to read or rewrite. cwd : pathlib.Path, optional Working directory. Defaults to :meth:`pathlib.Path.cwd`. - trust_project : bool - Trust an escaping config without prompting (``--trust-project``). explicit : bool The caller named this file with ``--file``. + report : bool + Log a one-line warning when *config_path* is an escaping project file. Examples -------- - A file that does not exist yet is not a project config anybody shipped: + A file that does not exist yet is not an escaping project config: - >>> ensure_config_trusted(tmp_path / "brand-new.yaml", cwd=tmp_path) + >>> project_config_contained(tmp_path / "brand-new.yaml", cwd=tmp_path) True """ cwd = cwd or pathlib.Path.cwd() @@ -2259,64 +2256,10 @@ def ensure_config_trusted( return True source = scopes.ConfigSource("project", anchor, anchor.parent) - escaping = source_escapes(source, cwd=cwd) - if not escaping: - return True - return _authorize_config( - source, - escaping, - state_file=scopes.trust_state_file(), - trust_project=trust_project, - ) - - -def _authorize_config( - source: scopes.ConfigSource, - escaping: Sequence[pathlib.Path], - *, - state_file: pathlib.Path, - trust_project: bool, -) -> bool: - """Ask whether an escaping project config may act, and remember ``always``. - - Raises - ------ - exc.VCSPullError - When there is no terminal to prompt on. A sync must never block on a - hidden prompt, so this is a hard error rather than a silent skip. - """ - config = PrivatePath(source.path) - directory = PrivatePath(os.path.realpath(source.trust_root)) - - if trust_project or scopes.env_flag("VCSPULL_YES"): - log.debug("trusting %s without prompting", config) + if not source_escapes(source, cwd=cwd): return True - - if not sys.stdin.isatty(): - listed = ", ".join(str(PrivatePath(path)) for path in escaping) - msg = ( - f"{config} would check repositories out outside its directory " - f"({listed}) and there is no terminal to confirm on. " - f"Run 'vcspull trust {directory}' to allow it, pass " - "--trust-project, or use --no-project to skip project configs." - ) - raise exc.VCSPullError(msg) - - print( - f"! {config} would check repositories out outside its directory:", - file=sys.stderr, - ) - for path in escaping: - print(f" {PrivatePath(path)}", file=sys.stderr) - answer = input(" Trust this config? [y/N/always] ").strip().lower() - - if answer == "always": - scopes.trust_directory(state_file, source.trust_root) - return True - if answer in {"y", "yes"}: - return True - - log.warning("skipping untrusted config %s", config) + if report: + _warn_escaping_project_source(source) return False diff --git a/tests/_internal/remotes/test_gitlab.py b/tests/_internal/remotes/test_gitlab.py index 49efe6316..0a2ce2509 100644 --- a/tests/_internal/remotes/test_gitlab.py +++ b/tests/_internal/remotes/test_gitlab.py @@ -2843,7 +2843,6 @@ def urlopen_router( prune=False, prune_untracked=False, no_project=False, - trust_project=False, ) assert handle_gitlab(args) == 0 diff --git a/tests/cli/test_add.py b/tests/cli/test_add.py index 4d2f47d1b..a902e9677 100644 --- a/tests/cli/test_add.py +++ b/tests/cli/test_add.py @@ -2517,11 +2517,9 @@ def _alias_sandbox( ) -> pathlib.Path: """Isolate HOME, XDG, and cwd in *tmp_path*.""" monkeypatch.setenv("HOME", str(tmp_path)) - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) monkeypatch.setenv("GIT_CONFIG_GLOBAL", "/dev/null") monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) - monkeypatch.delenv("VCSPULL_YES", raising=False) monkeypatch.chdir(tmp_path) return tmp_path diff --git a/tests/cli/test_config.py b/tests/cli/test_config.py index 644fb6a5d..9d40ed783 100644 --- a/tests/cli/test_config.py +++ b/tests/cli/test_config.py @@ -1,7 +1,8 @@ -"""Tests for ``vcspull config ls``, ``vcspull trust``, and the scope flags.""" +"""Tests for ``vcspull config ls``, project containment, and the scope flags.""" from __future__ import annotations +import json import pathlib import textwrap import typing as t @@ -9,7 +10,6 @@ import pytest from tests.helpers import write_config -from vcspull._internal import scopes from vcspull.cli import cli @@ -18,7 +18,7 @@ def scoped_cli( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, ) -> pathlib.Path: - """Give one test its own home, trust record, and project tree. + """Give one test its own home and project tree. Return the project directory, already the working directory. The user config declares ``flask`` and ``click`` under the project's vendor @@ -30,7 +30,6 @@ def scoped_cli( project.mkdir(parents=True) monkeypatch.setenv("HOME", str(home)) monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config")) - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) monkeypatch.delenv("VCSPULL_CEILING_PATHS", raising=False) monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) monkeypatch.chdir(project) @@ -94,22 +93,21 @@ def test_config_ls_marks_overridden_entries( assert "1 repo\n" in out -def test_config_ls_marks_an_untrusted_project_config( +def test_config_ls_marks_a_skipped_project_config( scoped_cli: pathlib.Path, capsys: pytest.CaptureFixture[str], ) -> None: - """``config ls`` diagnoses the refusal instead of reproducing it. - - ``vcspull list`` raises on this tree, so the command you reach for to find - out why must not raise, prompt, or quietly omit the file. - """ + """``config ls`` keeps escaping project files visible as skipped.""" _escaping(scoped_cli) cli(["config", "ls"]) out = capsys.readouterr().out - assert "(untrusted)" in out - assert "vcspull trust" in out + assert "(outside directory, skipped)" in out + assert ( + "Skipped project configs target paths outside their directory; " + "pass '-f FILE' or link them in user config." + ) in out def test_config_ls_honours_no_project( @@ -152,14 +150,6 @@ class ScopeFlagFixture(t.NamedTuple): SCOPE_FLAG_FIXTURES: list[ScopeFlagFixture] = [ ScopeFlagFixture(test_id="root-no-project", argv=["--no-project", "list"]), ScopeFlagFixture(test_id="subcommand-no-project", argv=["list", "--no-project"]), - ScopeFlagFixture( - test_id="root-trust-project", - argv=["--trust-project", "list"], - ), - ScopeFlagFixture( - test_id="subcommand-trust-project", - argv=["list", "--trust-project"], - ), ] @@ -182,86 +172,102 @@ def test_scope_flags_parse_in_either_position( assert "flask" in capsys.readouterr().out -def test_untrusted_config_reports_one_line_and_exits( - scoped_cli: pathlib.Path, - capsys: pytest.CaptureFixture[str], -) -> None: - """A refusal is an actionable sentence, not a traceback.""" - _escaping(scoped_cli) +class RemovedTrustFixture(t.NamedTuple): + """Fixture for removed trust CLI subcommand and option spellings.""" - with pytest.raises(SystemExit) as excinfo: - cli(["list"]) + test_id: str + argv: list[str] - captured = capsys.readouterr() - assert excinfo.value.code == 1 - assert len(captured.err.strip().splitlines()) == 1 - assert "vcspull trust" in captured.err + +REMOVED_TRUST_FIXTURES: list[RemovedTrustFixture] = [ + RemovedTrustFixture(test_id="trust-subcommand", argv=["trust"]), + RemovedTrustFixture( + test_id="root-trust-project", + argv=["--trust-project", "list"], + ), + RemovedTrustFixture( + test_id="subcommand-trust-project", + argv=["list", "--trust-project"], + ), +] -def test_trust_records_shows_and_forgets( +@pytest.mark.parametrize( + list(RemovedTrustFixture._fields), + REMOVED_TRUST_FIXTURES, + ids=[fixture.test_id for fixture in REMOVED_TRUST_FIXTURES], +) +def test_removed_trust_subcommand_and_flag_exit_2( + test_id: str, + argv: list[str], scoped_cli: pathlib.Path, - capsys: pytest.CaptureFixture[str], ) -> None: - """``trust``, ``--show``, and ``--untrust`` round-trip one directory.""" - cli(["trust", str(scoped_cli)]) - assert scopes.read_trusted(scopes.trust_state_file()) == frozenset( - {scoped_cli.resolve()}, - ) - - capsys.readouterr() - cli(["trust", "--show"]) - assert str(scoped_cli.resolve()) in capsys.readouterr().out.replace( - "~", - str(pathlib.Path.home()), - ) + """Removed trust CLI surfaces fail as unrecognized arguments (exit 2).""" + with pytest.raises(SystemExit) as excinfo: + cli(argv) - cli(["trust", "--untrust", str(scoped_cli)]) - assert scopes.read_trusted(scopes.trust_state_file()) == frozenset() + assert excinfo.value.code == 2 -def test_trusting_the_project_lets_it_load( +def test_list_skips_escaping_project_config_and_keeps_json_stdout_clean( scoped_cli: pathlib.Path, capsys: pytest.CaptureFixture[str], ) -> None: - """Trust is what turns the refusal into a load.""" - _escaping(scoped_cli) - cli(["trust", str(scoped_cli)]) - capsys.readouterr() + """Escaping project configs warn once in human output and stay silent in JSON.""" + escaping = _escaping(scoped_cli) cli(["list"]) + human_out = capsys.readouterr().out + assert "skipping " in human_out + assert "flask" in human_out + assert "evil" not in human_out - assert "evil" in capsys.readouterr().out + cli(["list", "--json"]) + payload = json.loads(capsys.readouterr().out) + assert [entry["name"] for entry in payload] == ["flask", "click"] + cli(["list", "-f", str(escaping), "--json"]) + explicit_payload = json.loads(capsys.readouterr().out) + assert [entry["name"] for entry in explicit_payload] == ["evil"] -def test_fmt_write_is_gated_on_a_discovered_project_config( + +def test_fmt_write_skips_discovered_escaping_project_config( scoped_cli: pathlib.Path, capsys: pytest.CaptureFixture[str], ) -> None: - """``fmt --write`` runs through the same gate every other command does.""" + """``fmt --write`` leaves discovered escaping project configs untouched.""" escaping = _escaping(scoped_cli) before = escaping.read_text(encoding="utf-8") - with pytest.raises(SystemExit): - cli(["fmt", "--all", "--write"]) + cli(["fmt", "--all", "--write"]) + assert escaping.read_text(encoding="utf-8") == before + (pathlib.Path.home() / ".vcspull.yaml").unlink() + capsys.readouterr() + with pytest.raises(SystemExit) as excinfo: + cli(["fmt", "--write"]) + assert excinfo.value.code == 1 assert escaping.read_text(encoding="utf-8") == before -def test_discover_yes_does_not_grant_trust( +def test_discover_yes_refuses_escaping_project_config_without_explicit_file( scoped_cli: pathlib.Path, + capsys: pytest.CaptureFixture[str], ) -> None: - """``discover --yes`` skips *its own* prompt, never the trust gate. - - The two questions are unrelated, and conflating them would let a routine - import flag authorize a config that writes outside its directory. - """ + """``discover --yes`` refuses to rewrite an escaping project file without ``-f``.""" (pathlib.Path.home() / ".vcspull.yaml").unlink() - _escaping(scoped_cli) + escaping = _escaping(scoped_cli) + before = escaping.read_text(encoding="utf-8") (scoped_cli / "vendor").mkdir() - with pytest.raises(SystemExit): + with pytest.raises(SystemExit) as excinfo: cli(["discover", str(scoped_cli / "vendor"), "--yes"]) + captured = capsys.readouterr() + assert excinfo.value.code == 1 + assert "refusing to modify" in captured.err + assert escaping.read_text(encoding="utf-8") == before + def test_config_ls_audits_shared_kept_ignored_lost_and_dropped_aliases( scoped_cli: pathlib.Path, @@ -352,7 +358,6 @@ def test_config_ls_in_dotfiles_repo_lists_symlinked_user_config_once( dotfiles.mkdir(parents=True) monkeypatch.setenv("HOME", str(home)) monkeypatch.setenv("XDG_CONFIG_HOME", str(home / ".config")) - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) monkeypatch.delenv("VCSPULL_CEILING_PATHS", raising=False) monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) monkeypatch.chdir(dotfiles) diff --git a/tests/cli/test_discover.py b/tests/cli/test_discover.py index b187d3dd1..b56517bf4 100644 --- a/tests/cli/test_discover.py +++ b/tests/cli/test_discover.py @@ -1273,8 +1273,6 @@ def test_discover_shared_handle_refusal_project_warning_and_aliased_checkout( ) -> None: """``discover`` skips shared handles, warns on project, and skips aliased repos.""" monkeypatch.setenv("HOME", str(tmp_path)) - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) - monkeypatch.setenv("VCSPULL_YES", "1") monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) diff --git a/tests/cli/test_import_repos.py b/tests/cli/test_import_repos.py index b1b696a2d..f44578917 100644 --- a/tests/cli/test_import_repos.py +++ b/tests/cli/test_import_repos.py @@ -5080,8 +5080,6 @@ def test_import_shared_handle_refusal_project_warning_and_aliased_checkout( """``import`` skips shared handles, warns on project, and keeps aliased repos.""" caplog.set_level(logging.INFO) monkeypatch.setenv("HOME", str(tmp_path)) - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) - monkeypatch.setenv("VCSPULL_YES", "1") monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) monkeypatch.delenv("VCSPULL_NO_PROJECT", raising=False) diff --git a/tests/docs/_ext/test_vcspull_output_lexer.py b/tests/docs/_ext/test_vcspull_output_lexer.py index 6160f95ba..9cf57025b 100644 --- a/tests/docs/_ext/test_vcspull_output_lexer.py +++ b/tests/docs/_ext/test_vcspull_output_lexer.py @@ -426,11 +426,6 @@ class SubcommandOutputFixture(t.NamedTuple): subcommand="config", input_text="vcspull config ls", ), - SubcommandOutputFixture( - test_id="trust_subcommand", - subcommand="trust", - input_text="Allow one with vcspull trust ~/work/api", - ), ] diff --git a/tests/test_scopes.py b/tests/test_scopes.py index 127742d22..99350f48c 100644 --- a/tests/test_scopes.py +++ b/tests/test_scopes.py @@ -1,11 +1,10 @@ -"""Tests for configuration scope resolution, merging, and project trust.""" +"""Tests for configuration scope resolution, merging, and project containment.""" from __future__ import annotations -import io +import logging import os import pathlib -import sys import textwrap import typing as t @@ -198,103 +197,64 @@ def test_explicit_file_replaces_the_whole_stack( assert [repo["name"] for repo in repos] == ["solo"] -def test_escaping_project_config_errors_without_a_tty( +def test_escaping_project_config_is_skipped_with_one_line_warning( scoped_tree: pathlib.Path, + caplog: pytest.LogCaptureFixture, ) -> None: - """No terminal means a hard error naming ``vcspull trust``, never a hang.""" + """An escaping project config is skipped with a warning; other scopes load.""" write_config( scoped_tree.parent / ".vcspull.yaml", "~/.ssh/:\n payload: git+https://example.com/payload.git\n", ) - with pytest.raises(exc.VCSPullError, match="vcspull trust"): - config.load_scoped_configs(cwd=scoped_tree) + with caplog.at_level(logging.WARNING, logger="vcspull.config"): + repos = _by_name(config.load_scoped_configs(cwd=scoped_tree)) + + skip_warnings = [ + r.getMessage() for r in caplog.records if r.getMessage().startswith("skipping ") + ] + assert "payload" not in repos + assert {"flask", "shared", "outer", "inner"} <= repos.keys() + assert len(skip_warnings) == 1 + assert "project configs cannot target paths outside" in skip_warnings[0] + assert "pass -f " in skip_warnings[0] -def test_escaping_project_config_loads_with_trust_project( +def test_escaping_project_config_loads_when_named_explicitly( scoped_tree: pathlib.Path, + caplog: pytest.LogCaptureFixture, ) -> None: - """``--trust-project`` accepts an escaping config non-interactively.""" - write_config( + """Explicit ``-f`` / *config_path* loads an out-of-directory manifest.""" + escaping = write_config( scoped_tree.parent / ".vcspull.yaml", "~/.ssh/:\n payload: git+https://example.com/payload.git\n", ) - repos = _by_name(config.load_scoped_configs(cwd=scoped_tree, trust_project=True)) - - assert "payload" in repos - - -class _Tty(io.StringIO): - """Stand-in for an interactive stdin.""" - - def isatty(self) -> bool: - """Report an interactive terminal.""" - return True + with caplog.at_level(logging.WARNING, logger="vcspull.config"): + repos = _by_name(config.load_scoped_configs(escaping, cwd=scoped_tree)) + assert list(repos) == ["payload"] + assert caplog.records == [] -class TrustAnswerFixture(t.NamedTuple): - """Fixture for the interactive trust prompt.""" - test_id: str - answer: str - loads: bool - remembers: bool - - -TRUST_ANSWER_FIXTURES: list[TrustAnswerFixture] = [ - TrustAnswerFixture(test_id="declined", answer="n", loads=False, remembers=False), - TrustAnswerFixture( - test_id="empty-declines", answer="", loads=False, remembers=False - ), - TrustAnswerFixture( - test_id="accepted-once", answer="y", loads=True, remembers=False - ), - TrustAnswerFixture(test_id="always", answer="always", loads=True, remembers=True), -] - - -@pytest.mark.parametrize( - list(TrustAnswerFixture._fields), - TRUST_ANSWER_FIXTURES, - ids=[fixture.test_id for fixture in TRUST_ANSWER_FIXTURES], -) -def test_trust_prompt_answers( - test_id: str, - answer: str, - loads: bool, - remembers: bool, +def test_escaping_project_config_report_false_suppresses_warning( scoped_tree: pathlib.Path, - monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, ) -> None: - """The prompt gates the file, and ``always`` remembers the directory.""" - project = scoped_tree.parent + """``report=False`` skips escaping project configs silently for JSON streams.""" write_config( - project / ".vcspull.yaml", + scoped_tree.parent / ".vcspull.yaml", "~/.ssh/:\n payload: git+https://example.com/payload.git\n", ) - monkeypatch.setattr(sys, "stdin", _Tty()) - monkeypatch.setattr("builtins.input", lambda _prompt="": answer) - - repos = _by_name(config.load_scoped_configs(cwd=scoped_tree)) - trusted = scopes.read_trusted(scopes.trust_state_file()) - - assert ("payload" in repos) is loads - assert (project.resolve() in trusted) is remembers - -def test_trusted_directory_skips_the_prompt( - scoped_tree: pathlib.Path, -) -> None: - """A remembered project directory loads without asking again.""" - project = scoped_tree.parent - write_config( - project / ".vcspull.yaml", - "~/.ssh/:\n payload: git+https://example.com/payload.git\n", - ) - scopes.trust_directory(scopes.trust_state_file(), project) + with caplog.at_level(logging.WARNING, logger="vcspull.config"): + repos = _by_name(config.load_scoped_configs(cwd=scoped_tree, report=False)) - assert "payload" in _by_name(config.load_scoped_configs(cwd=scoped_tree)) + skip_warnings = [ + r.getMessage() for r in caplog.records if r.getMessage().startswith("skipping ") + ] + assert "payload" not in repos + assert skip_warnings == [] class DivergenceFixture(t.NamedTuple): @@ -422,12 +382,13 @@ def resolved(entry: str) -> pathlib.Path: def test_path_override_cannot_smuggle_a_destination_out( scoped_tree: pathlib.Path, + caplog: pytest.LogCaptureFixture, ) -> None: """A contained workspace root does not license an escaping ``path:``. ``extract_repos`` honours a per-entry ``path:`` and never consults the workspace root, so a gate reading only the top-level keys would clone this - into ``~/.ssh`` without asking. + into ``~/.ssh``. """ write_config( scoped_tree.parent / ".vcspull.yaml", @@ -441,8 +402,14 @@ def test_path_override_cannot_smuggle_a_destination_out( ), ) - with pytest.raises(exc.VCSPullError, match="vcspull trust"): - config.load_scoped_configs(cwd=scoped_tree) + with caplog.at_level(logging.WARNING, logger="vcspull.config"): + repos = _by_name(config.load_scoped_configs(cwd=scoped_tree)) + + skip_warnings = [ + r.getMessage() for r in caplog.records if r.getMessage().startswith("skipping ") + ] + assert "evil" not in repos + assert len(skip_warnings) == 1 def test_symlinked_home_stops_the_walk_and_loads_once(