Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(config): match `[projects."…"]` keys by pattern, and carry forge there (#3701)
Maximilian Roos02a12c7f5955
diff --git a/dev/config.example.toml b/dev/config.example.tomlindex 3ec173201..e31e2814c 100644--- a/dev/config.example.toml+++ b/dev/config.example.toml@@ -249,6 +249,32 @@# step.copy-ignored.exclude = [".repo-local-cache/"]# aliases.deploy = "make deploy BRANCH={{ branch }}"#+# #### Matching several repositories with one entry+#+# A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.+#+# # Every repository on a self-hosted forge whose hostname carries no brand+# [projects."git.company.example/*"]+# forge.platform = "gitlab"+#+# # Everything under one namespace shares a layout+# [projects."git.company.example/platform/*"]+# worktree-path = ".worktrees/{{ branch | sanitize }}"+#+# Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.+#+# `approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.+#+# #### Forge platform and hostname+#+# `forge` names the forge for the matched repositories — the user-level counterpart of the project config's forge platform (https://worktrunk.dev/config/#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.+#+# [projects."git.company.example/*"]+# forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)+# forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it+#+# Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.+## Hooks support all three hook forms (https://worktrunk.dev/hook/#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:## # Single commanddiff --git a/dev/wt.example.toml b/dev/wt.example.tomlindex 246f82db0..b1312c333 100644--- a/dev/wt.example.toml+++ b/dev/wt.example.toml@@ -27,6 +27,8 @@# platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)# hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)#+# When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](@/config.md#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.+## ## Commit-message append [experimental]## `template-append` adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:diff --git a/docs/content/config.md b/docs/content/config.mdindex c784291a5..28165aaa7 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -357,6 +357,36 @@ step.copy-ignored.exclude = [".repo-local-cache/"]aliases.deploy = "make deploy BRANCH={{ branch }}"```+#### Matching several repositories with one entry++A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.++```toml+# Every repository on a self-hosted forge whose hostname carries no brand+[projects."git.company.example/*"]+forge.platform = "gitlab"++# Everything under one namespace shares a layout+[projects."git.company.example/platform/*"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+```++Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.++`approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.++#### Forge platform and hostname++`forge` names the forge for the matched repositories — the user-level counterpart of the project config's [forge platform](@/config.md#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.++```toml+[projects."git.company.example/*"]+forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)+forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it+```++Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.+Hooks support all three [hook forms](@/hook.md#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:```toml@@ -544,6 +574,8 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expehostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)```+When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](@/config.md#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.+## Commit-message append<span class="badge-experimental"></span>diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex 932edda30..e2529d6fb 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -354,6 +354,36 @@ step.copy-ignored.exclude = [".repo-local-cache/"]aliases.deploy = "make deploy BRANCH={{ branch }}"```+#### Matching several repositories with one entry++A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.++```toml+# Every repository on a self-hosted forge whose hostname carries no brand+[projects."git.company.example/*"]+forge.platform = "gitlab"++# Everything under one namespace shares a layout+[projects."git.company.example/platform/*"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+```++Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.++`approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.++#### Forge platform and hostname++`forge` names the forge for the matched repositories — the user-level counterpart of the project config's [forge platform](https://worktrunk.dev/config/#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.++```toml+[projects."git.company.example/*"]+forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)+forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it+```++Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.+Hooks support all three [hook forms](https://worktrunk.dev/hook/#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:```toml@@ -539,6 +569,8 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expehostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)```+When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](https://worktrunk.dev/config/#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.+## Commit-message append [experimental]`template-append` adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex 932edda30..e2529d6fb 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -354,6 +354,36 @@ step.copy-ignored.exclude = [".repo-local-cache/"]aliases.deploy = "make deploy BRANCH={{ branch }}"```+#### Matching several repositories with one entry++A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.++```toml+# Every repository on a self-hosted forge whose hostname carries no brand+[projects."git.company.example/*"]+forge.platform = "gitlab"++# Everything under one namespace shares a layout+[projects."git.company.example/platform/*"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+```++Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.++`approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.++#### Forge platform and hostname++`forge` names the forge for the matched repositories — the user-level counterpart of the project config's [forge platform](https://worktrunk.dev/config/#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.++```toml+[projects."git.company.example/*"]+forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)+forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it+```++Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.+Hooks support all three [hook forms](https://worktrunk.dev/hook/#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:```toml@@ -539,6 +569,8 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expehostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)```+When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](https://worktrunk.dev/config/#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.+## Commit-message append [experimental]`template-append` adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 72e206e39..22de2a66e 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -2224,6 +2224,36 @@ step.copy-ignored.exclude = [".repo-local-cache/"]aliases.deploy = "make deploy BRANCH={{ branch }}"```+#### Matching several repositories with one entry++A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.++```toml+# Every repository on a self-hosted forge whose hostname carries no brand+[projects."git.company.example/*"]+forge.platform = "gitlab"++# Everything under one namespace shares a layout+[projects."git.company.example/platform/*"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+```++Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.++`approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.++#### Forge platform and hostname++`forge` names the forge for the matched repositories — the user-level counterpart of the project config's [forge platform](@/config.md#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.++```toml+[projects."git.company.example/*"]+forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)+forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it+```++Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.+Hooks support all three [hook forms](@/hook.md#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:```toml@@ -2409,6 +2439,8 @@ platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (expehostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)```+When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](@/config.md#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.+## Commit-message append [experimental]`template-append` adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rsindex 454e3633e..12f508df8 100644--- a/src/commands/config/approvals.rs+++ b/src/commands/config/approvals.rs@@ -12,6 +12,7 @@ use strum::IntoEnumIterator;use worktrunk::HookType;use worktrunk::config::{Approvals, ProjectConfig, require_approvals_path};use worktrunk::git::{GitError, Repository};+use worktrunk::path::format_path_for_display;use worktrunk::styling::{INFO_SYMBOL, PROMPT_SYMBOL, eprintln, format_bash_with_gutter, format_heading, hint_message,info_message, success_message, warning_message,@@ -256,6 +257,7 @@ pub fn clear_approvals(global: bool, stale: bool) -> anyhow::Result<()> {if approval_count == 0 {eprintln!("{}", info_message("No approvals to clear for this project"));+ emit_pattern_entries_hint(&approvals, &project_id)?;return Ok(());}@@ -270,7 +272,29 @@ pub fn clear_approvals(global: bool, stale: bool) -> anyhow::Result<()> {if approval_count == 1 { "" } else { "s" })));+ emit_pattern_entries_hint(&approvals, &project_id)?;}Ok(())}++/// After a per-project clear — or one with nothing exact to remove — name the+/// hand-written pattern entries still approving commands for this project.+/// `clear` only ever touches the exact entry, so without this the approval+/// survives with nothing pointing at the entry supplying it.+fn emit_pattern_entries_hint(approvals: &Approvals, project_id: &str) -> anyhow::Result<()> {+ let keys = approvals.matching_pattern_keys(project_id);+ if keys.is_empty() {+ return Ok(());+ }+ let label = if keys.len() == 1 { "entry" } else { "entries" };+ let keys = keys.join(", ");+ let path = format_path_for_display(&require_approvals_path()?);+ eprintln!(+ "{}",+ hint_message(cformat!(+ "Commands approved by pattern {label} <underline>{keys}</> still apply; to change them, edit <underline>{path}</>"+ ))+ );+ Ok(())+}diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rsindex e204aaf48..0d9d21abd 100644--- a/src/commands/config/mod.rs+++ b/src/commands/config/mod.rs@@ -167,7 +167,7 @@ mod tests {@"[33m▲[39m [33mKey [1mskip-shell-integration-prompt[22m belongs in user config (will be ignored)[39m");// forge in user config should suggest project config- assert_snapshot!(warn_unknown_keys::<UserConfig>("[forge]\nplatform = \"github\"\n"), @"[33m▲[39m [33mKey [1mforge[22m belongs in project config (will be ignored)[39m");+ assert_snapshot!(warn_unknown_keys::<UserConfig>("[forge]\nplatform = \"github\"\n"), @r#"[33m▲[39m [33mKey [1mforge[22m belongs in project config (will be ignored); to set it from user config, add it under [projects."<id>"][39m"#);}#[test]diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsindex c0110741d..3fe0df55c 100644--- a/src/commands/config/show.rs+++ b/src/commands/config/show.rs@@ -449,7 +449,8 @@ fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;- // Check the CI tool for this repo's platform (project config, else remote URL).+ // Check the CI tool for this repo's platform (configured forge platform,+ // else remote URL).let repo = Repository::current()?;match repo.ci_platform(None) {Some(ForgeKind::GitHub) => {diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex eb37dc96d..6642a770b 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -804,7 +804,7 @@ pub fn handle_state_get(.and_then(|ci_branch| PrStatus::detect(&repo, &ci_branch, &branch_ref.commit_sha));if format == SwitchFormat::Json {- let ci_provider_override = repo.forge_platform_override();+ let ci_provider_override = repo.configured_forge_platform();let output = pr_status.as_ref().map(|pr| {super::super::list::json_output::JsonCi::from_pr_status(pr,diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex a10ce83a7..b7f5693fb 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -206,11 +206,7 @@ pub(super) fn detect_github_commit_checks(let (owner, repo_name) = branch_owner_repo(repo, branch)?;// Only pass --hostname when explicitly configured (for GHE / self-hosted)- let hostname = repo- .load_project_config()- .ok()- .flatten()- .and_then(|c| c.forge_hostname().map(String::from));+ let hostname = repo.forge_hostname();// Use GitHub's check-runs API to get all checks for this commitlet api_path = format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs");diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 755a96038..0163cccb4 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -477,7 +477,7 @@ fn worktree_state_to_json(impl JsonCi {/// Build a `JsonCi` from a [`PrStatus`], deriving the target-repo metadata/// from the PR/MR URL. `provider_override` is the configured- /// `[forge].platform` (see [`Repository::forge_platform_override`]); it lets+ /// `[forge].platform` (see [`Repository::configured_forge_platform`]); it lets/// a self-hosted instance whose host can't be auto-detected still report the/// right provider.pub(crate) fn from_pr_status(pr: &PrStatus, provider_override: Option<&str>) -> Self {@@ -572,7 +572,7 @@ pub fn to_json_items() -> Vec<JsonItem> {let mut all_vars = repo.all_vars_from_snapshot().unwrap_or_default();let repo_metadata = repo.repo_info();- let ci_provider_override = repo.forge_platform_override();+ let ci_provider_override = repo.configured_forge_platform();items.iter().map(|item| {diff --git a/src/commands/list/json_v2.rs b/src/commands/list/json_v2.rsindex 7c4a9d832..f3a727d17 100644--- a/src/commands/list/json_v2.rs+++ b/src/commands/list/json_v2.rs@@ -397,7 +397,7 @@ pub fn to_json_envelope() -> JsonEnvelope {let mut all_vars = repo.all_vars_from_snapshot().unwrap_or_default();let default_branch = repo.default_branch();- let ci_provider_override = repo.forge_platform_override();+ let ci_provider_override = repo.configured_forge_platform();let json_items = items.iter()diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 9540ee9a4..4c225c69a 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -964,7 +964,7 @@ fn run_json() -> Result<()> {}// No custom columns: the statusline path never expands `[list.custom-columns]`// (prompt hot path; its compact format has no column grid).- let ci_provider_override = repo.forge_platform_override();+ let ci_provider_override = repo.configured_forge_platform();// Output follows `wt list --format=json`: schema 1 is a bare// single-item array, schema 2 a single-item envelope.diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex a54d35998..44dee1d78 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -84,7 +84,9 @@ fn format_ref_context(info: &RemoteRefInfo) -> String {/// Choose which provider should handle `pr:<number>` resolution.////// Priority:-/// 1. `forge.platform` config (`github` / `gitea` / `azure-devops`)+/// 1. The configured `forge.platform` (`github` / `gitea` / `azure-devops`) —+/// the repository's own, else a matching user-config `[projects."…"]`+/// entry, via [`Repository::configured_forge_platform`]/// 2. Every configured raw remote, in GitHub > Gitea > Azure DevOps > GitLab/// order. [`ForgeKind::from_host`] classifies exact forge labels and Azure/// DevOps service-domain suffixes.@@ -96,10 +98,7 @@ fn format_ref_context(info: &RemoteRefInfo) -> String {/// GitHub error (with hint to set `forge.platform = "gitea"`), instead of a/// wrapped two-provider error.fn choose_pr_provider(repo: &Repository) -> anyhow::Result<&'static dyn RemoteRefProvider> {- if let Some(platform_raw) = repo- .load_project_config()?- .and_then(|c| c.forge_platform().map(str::to_string))- {+ if let Some(platform_raw) = repo.configured_forge_platform() {match platform_raw.to_ascii_lowercase().parse::<ForgeKind>() {Ok(ForgeKind::GitHub) => return Ok(&GITHUB_PROVIDER),Ok(ForgeKind::Gitea) => return Ok(&GITEA_PROVIDER),@@ -108,7 +107,8 @@ fn choose_pr_provider(repo: &Repository) -> anyhow::Result<&'static dyn RemoteRebail!("forge.platform is set to gitlab; use mr:<number> instead of pr:<number>")}Err(_) => bail!(- "Invalid forge.platform value `{platform_raw}` in .config/wt.toml; \+ "Invalid forge.platform value `{platform_raw}` (from `[forge]` in project \+ config or a `[projects]` entry in user config); \expected one of: github, gitlab, gitea, azure-devops"),}diff --git a/src/config/approvals.rs b/src/config/approvals.rsindex c44679998..62ffd11e9 100644--- a/src/config/approvals.rs+++ b/src/config/approvals.rs@@ -224,16 +224,21 @@ impl Approvals {////// Normalizes template variables before comparing, so approvals match/// regardless of whether they were saved with deprecated variable names.+ ///+ /// A `*` pattern key approves its commands for every project it matches,+ /// the same keys `[projects."…"]` settings use. Only a hand-written entry+ /// is ever a pattern: [`Self::approve_commands`] records under the exact+ /// project identifier and refuses one that contains `*`, so approving a+ /// command in one repository never widens to another.pub fn is_command_approved(&self, project: &str, command: &str) -> bool {let normalized_command = normalize_template_vars(command);- self.projects- .get(project)- .map(|p| {+ crate::config::matching_project_keys(&self.projects, project)+ .into_iter()+ .any(|p| {p.approved_commands.iter().any(|c| normalize_template_vars(c) == normalized_command)})- .unwrap_or(false)}/// Iterate over projects and their approved commands.@@ -243,9 +248,32 @@ impl Approvals {.map(|(id, p)| (id.as_str(), p.approved_commands.as_slice()))}+ /// Pattern keys whose approved commands cover `project` — the entries+ /// [`Self::is_command_approved`] consults beyond the exact one. Always+ /// hand-written (the write paths refuse `*`), so mutations never touch+ /// them; `wt config approvals clear` names them in a hint, making an+ /// approval that survives a clear traceable to the entry that supplies it.+ pub fn matching_pattern_keys(&self, project: &str) -> Vec<&str> {+ self.projects+ .iter()+ .filter(|(key, p)| {+ key.contains('*')+ && !p.approved_commands.is_empty()+ && super::user::project_match::matches(key, project)+ })+ .map(|(key, _)| key.as_str())+ .collect()+ }+/// Approved commands for `project` that match none of `templates` (after/// template-variable normalization) — approvals left behind when a config/// command was edited or removed.+ ///+ /// Reads the exact key only, unlike [`Self::is_command_approved`]. A+ /// pattern entry's commands are shared with every repository it matches,+ /// and this drives `wt config approvals clear --stale`, so judging them+ /// against one repository's config would let that repository revoke+ /// approvals the others still rely on.pub fn stale_approvals<'a>(&'a self, project: &str, templates: &[&str]) -> Vec<&'a str> {let normalized: Vec<_> = templates.iter()@@ -329,34 +357,36 @@ impl Approvals {Ok(approvals)}- /// Add an approved command and save.+ /// Add an approved command and save. See [`Self::approve_commands`].pub fn approve_command(&mut self,project: String,command: String,approvals_path: &Path,) -> Result<(), ConfigError> {- self.with_locked_mutation(approvals_path, |approvals| {- if approvals.is_command_approved(&project, &command) {- return false;- }- approvals- .projects- .entry(project)- .or_default()- .approved_commands- .push(command);- true- })+ self.approve_commands(project, vec![command], approvals_path)}/// Add multiple approved commands in a single locked operation.+ ///+ /// Refuses a `project` containing `*`: reads treat such a key as a pattern+ /// (see `config::user::project_match`), so a persisted entry would approve+ /// the commands for every repository the pattern matches. Refusing here is+ /// what makes pattern entries hand-written only — the guarantee+ /// [`Self::is_command_approved`] documents. The caller's approval still+ /// covers the current run; it just isn't remembered.pub fn approve_commands(&mut self,project: String,commands: Vec<String>,approvals_path: &Path,) -> Result<(), ConfigError> {+ if project.contains('*') {+ return Err(ConfigError(format!(+ "Cannot save approvals for `{project}`: `*` in the identifier reads as a \+ pattern, so the entry would apply to every repository it matches"+ )));+ }self.with_locked_mutation(approvals_path, |approvals| {let entry = approvals.projects.entry(project).or_default();let mut changed = false;@@ -499,6 +529,144 @@ mod tests {assert!(!approvals.is_command_approved("any/project", "any command"));}+ #[test]+ fn test_pattern_key_approves_every_project_it_matches() {+ // A hand-written pattern entry — the only way one appears, since every+ // write path keys by the exact identifier.+ let approvals: Approvals = toml::from_str(+ r#"+[projects."git.company.example/*"]+approved-commands = ["npm install"]+"#,+ )+ .unwrap();++ assert!(approvals.is_command_approved("git.company.example/owner/repo", "npm install"));+ assert!(+ approvals.is_command_approved("git.company.example/group/team/repo", "npm install")+ );+ assert!(!approvals.is_command_approved("github.com/owner/repo", "npm install"));+ assert!(!approvals.is_command_approved("git.company.example/owner/repo", "npm test"));+ }++ #[test]+ fn test_matching_pattern_keys_names_covering_entries() {+ let approvals: Approvals = toml::from_str(+ r#"+[projects."git.company.example/*"]+approved-commands = ["npm install"]++[projects."git.company.example/owner/repo"]+approved-commands = ["npm test"]++[projects."git.company.example/owner/*"]+approved-commands = []++[projects."github.com/*"]+approved-commands = ["make"]+"#,+ )+ .unwrap();++ // The exact key, a non-matching pattern, and a matching pattern with+ // no commands are all excluded — only entries actually supplying+ // approvals are worth naming.+ assert_eq!(+ approvals.matching_pattern_keys("git.company.example/owner/repo"),+ vec!["git.company.example/*"]+ );+ assert!(+ approvals+ .matching_pattern_keys("codeberg.org/owner/repo")+ .is_empty()+ );+ }++ #[test]+ fn test_approving_a_starred_identifier_is_refused() {+ // An identifier can itself contain `*` (a remote URL or no-remote+ // path-fallback with a star in it). Persisting it verbatim would+ // create an entry reads treat as a pattern — approving the command+ // for every repository the star matches — so the write is refused+ // and the caller's approval covers the current run only.+ let (_temp_dir, path) = test_dir();+ let mut approvals = Approvals::default();++ let err = approvals+ .approve_commands(+ "git.company.example/owner/re*po".to_string(),+ vec!["npm install".to_string()],+ &path,+ )+ .unwrap_err();+ assert!(err.to_string().contains("pattern"), "got: {err}");+ assert!(+ !approvals.is_command_approved("git.company.example/owner/re*po", "npm install"),+ "nothing may be recorded in memory"+ );+ assert!(!path.exists(), "nothing may be written to disk");+ }++ #[test]+ fn test_approving_under_a_pattern_writes_the_exact_key() {+ // Approving in one repository must not widen an existing pattern entry+ // to cover a command the user was only asked about once.+ let (_temp_dir, path) = test_dir();+ let mut approvals: Approvals = toml::from_str(+ r#"+[projects."git.company.example/*"]+approved-commands = ["npm install"]+"#,+ )+ .unwrap();+ // Mutations reload under the file lock, so the fixture has to be on+ // disk for the pattern entry to survive into the mutation.+ approvals.save_to(&path).unwrap();++ approvals+ .approve_command(+ "git.company.example/owner/repo".to_string(),+ "npm test".to_string(),+ &path,+ )+ .unwrap();++ assert!(approvals.is_command_approved("git.company.example/owner/repo", "npm test"));+ assert!(+ !approvals.is_command_approved("git.company.example/other/repo", "npm test"),+ "the pattern entry must not have absorbed the new approval"+ );+ }++ #[test]+ fn test_clearing_one_project_leaves_a_matching_pattern_intact() {+ let (_temp_dir, path) = test_dir();+ let mut approvals: Approvals = toml::from_str(+ r#"+[projects."git.company.example/*"]+approved-commands = ["npm install"]++[projects."git.company.example/owner/repo"]+approved-commands = ["npm test"]+"#,+ )+ .unwrap();+ approvals.save_to(&path).unwrap();++ approvals+ .revoke_project("git.company.example/owner/repo", &path)+ .unwrap();++ assert!(+ !approvals.is_command_approved("git.company.example/owner/repo", "npm test"),+ "the repository's own approval is gone"+ );+ assert!(+ approvals.is_command_approved("git.company.example/owner/repo", "npm install"),+ "the pattern entry other repositories share is untouched"+ );+ }+#[test]fn test_approve_and_check() {let (_temp_dir, path) = test_dir();diff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex c8c2af145..551b52473 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -1825,10 +1825,12 @@ pub fn nested_key_belongs_in<C: WorktrunkConfig>(path: &str) -> Option<&'static.then(C::Other::description)}-/// Note appended to a "belongs in user config" warning: a key placed in-/// project config that really lives in user config is usually an attempt to-/// scope a personal setting to one repo, which the `[projects."<id>"]` table-/// in user config does directly. Returns `None` for any other destination.+/// Note appended to a "belongs in the other config" warning when the+/// misplaced key also has a `[projects."<id>"]` form in user config, which is+/// usually what the user was reaching for. A user key in project config is an+/// attempt to scope a personal setting to one repo; a project key in user+/// config (`forge`) is an attempt to set it without touching the repo's+/// committed file. The `[projects."<id>"]` table does both directly.////// `key` is the misplaced key (`worktree-path`, or a dotted path like/// `list.columns`); the note only fires when its top-level segment is a field@@ -1843,9 +1845,19 @@ pub fn nested_key_belongs_in<C: WorktrunkConfig>(path: &str) -> Option<&'static/// hold only the `other_description` string, not the config type.pub fn scope_to_repo_note(other_description: &str, key: &str) -> Option<&'static str> {let top_level = key.split('.').next().unwrap_or(key);- (other_description == crate::config::UserConfig::description()- && crate::config::is_user_project_override_key(top_level))- .then_some(r#"to scope it to this repo, add it under [projects."<id>"] in user config"#)+ if !crate::config::is_user_project_override_key(top_level) {+ return None;+ }+ if other_description == crate::config::UserConfig::description() {+ return Some(r#"to scope it to this repo, add it under [projects."<id>"] in user config"#);+ }+ // The reverse redirect — a project-config key found in user config — earns+ // the note only for a whole top-level table (`forge`): its+ // `[projects."<id>"]` field has the same shape, so the move is valid as+ // written. A nested path (`list.url`) names a field the projects-entry+ // type doesn't have, and its correct home really is project config.+ (other_description == crate::config::ProjectConfig::description() && !key.contains('.'))+ .then_some(r#"to set it from user config, add it under [projects."<id>"]"#)}/// Classification of an unknown config key for warning purposes.@@ -4716,12 +4728,18 @@ ff = true}#[test]- fn test_scope_to_repo_note_only_for_user_config() {- // The note fires for user-config destinations whose top-level key is a- // `[projects."<id>"]` field, and nothing else.+ fn test_scope_to_repo_note_destinations() {+ // Toward user config, the note fires for any misplaced key whose+ // top-level segment is a `[projects."<id>"]` field.assert!(scope_to_repo_note("user config", "list.columns").is_some());assert!(scope_to_repo_note("user config", "worktree-path").is_some());++ // Toward project config, only a whole top-level table (`forge`) earns+ // it: the projects-entry `list` is the user type, which has no `url`,+ // so that advice would be wrong.+ assert!(scope_to_repo_note("project config", "forge").is_some());assert!(scope_to_repo_note("project config", "list.url").is_none());+ assert!(scope_to_repo_note("project config", "forge.platform").is_none());// Root-only user scalars have no `[projects."<id>"]` form, so following// the note would just yield a fresh "unknown field" — no note.diff --git a/src/config/mod.rs b/src/config/mod.rsindex 51677592b..1c8726354 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -171,12 +171,13 @@ pub use expansion::{pub use hooks::HooksConfig;pub use project::{ProjectCiConfig, ProjectCommitConfig, ProjectCommitGenerationConfig, ProjectConfig,- ProjectListConfig, valid_project_config_keys,+ ProjectForgeConfig, ProjectListConfig, valid_project_config_keys,};pub use unknown_tree::{UnknownAnalysis, UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,};pub(crate) use user::LoadError;+pub(crate) use user::project_match::matching_keys as matching_project_keys;pub use user::{CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListColumnConfig, ListConfig,MergeConfig, RemoveConfig, ResolvedConfig, StageMode, StepConfig, SwitchConfig,diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rsindex 43c625c8e..529a02511 100644--- a/src/config/user/accessors.rs+++ b/src/config/user/accessors.rs@@ -23,23 +23,46 @@ fn default_worktree_path() -> String {}impl UserConfig {+ /// Every `[projects."…"]` entry applying to `project`, least- to+ /// most-specific.+ ///+ /// A key matches literally or as a `*` pattern, so one entry can carry+ /// settings for a whole host. Callers apply the entries in order, letting+ /// the most specific win — see [`super::project_match`] for the matching+ /// and ordering rules.fn project_overrides(&self,project: Option<&str>,- ) -> Option<&super::sections::UserProjectOverrides> {- project.and_then(|p| self.projects.get(p))+ ) -> Vec<&super::sections::UserProjectOverrides> {+ project.map_or_else(Vec::new, |p| {+ super::project_match::matching_keys(&self.projects, p)+ })}fn merged_project_config<T: Merge + Clone>(&self,project: Option<&str>,global: &T,- project_config: impl FnOnce(&super::sections::UserProjectOverrides) -> &T,+ project_config: impl Fn(&super::sections::UserProjectOverrides) -> &T,) -> T {- match self.project_overrides(project).map(project_config) {- Some(proj) => global.merge_with(proj),- None => global.clone(),- }+ self.project_overrides(project)+ .into_iter()+ .fold(global.clone(), |merged, overrides| {+ merged.merge_with(project_config(overrides))+ })+ }++ /// The last value `field` yields across the entries applying to `project`,+ /// so the most specific entry that sets it wins.+ fn project_field<'a, T>(+ &'a self,+ project: Option<&str>,+ field: impl Fn(&'a super::sections::UserProjectOverrides) -> Option<T>,+ ) -> Option<T> {+ self.project_overrides(project)+ .into_iter()+ .filter_map(field)+ .next_back()}/// Returns the worktree path template, falling back to the default if not set.@@ -56,9 +79,7 @@ impl UserConfig {/// Returns true if the given project has an explicit worktree-path override.pub fn has_project_worktree_path(&self, project: &str) -> bool {- self.projects- .get(project)- .and_then(|p| p.worktree_path.as_ref())+ self.project_field(Some(project), |p| p.worktree_path.as_ref()).is_some()}@@ -67,12 +88,30 @@ impl UserConfig {/// Checks project-specific config first, falls back to global worktree-path,/// and finally to the default template if neither is set.pub fn worktree_path_for_project(&self, project: &str) -> String {- self.projects- .get(project)- .and_then(|p| p.worktree_path.clone())+ self.project_field(Some(project), |p| p.worktree_path.clone()).unwrap_or_else(|| self.worktree_path())}+ /// The forge platform set for a project under `[projects."…"].forge`.+ ///+ /// The user-level counterpart of the repository's own `[forge].platform`:+ /// a `[projects."git.company.example/*"]` entry names the forge for every+ /// repository on a host whose name carries no forge brand, without a+ /// `[forge]` block in each one. Read by+ /// [`Repository::ci_platform`](crate::git::Repository::ci_platform).+ pub fn forge_platform(&self, project: Option<&str>) -> Option<&str> {+ self.project_field(project, |p| p.forge.platform.as_deref())+ }++ /// The forge API hostname set for a project under `[projects."…"].forge`.+ ///+ /// Names the API server for a remote whose host is an SSH alias, or whose+ /// API lives on a different name. Both are facts about the host rather+ /// than the repository, which is why a pattern entry suits them.+ pub fn forge_hostname(&self, project: Option<&str>) -> Option<&str> {+ self.project_field(project, |p| p.forge.hostname.as_deref())+ }+/// Returns the commit generation config for a specific project.////// Merges project-specific settings with global settings, where project@@ -80,14 +119,13 @@ impl UserConfig {/// `[commit-generation]` sections are normalized into `[commit.generation]`/// during config loading.pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {- let global = self.commit.generation.clone().unwrap_or_default();- match self- .project_overrides(project)- .and_then(|config| config.commit.generation.as_ref())- {- Some(proj) => global.merge_with(proj),- None => global,- }+ self.project_overrides(project)+ .into_iter()+ .filter_map(|config| config.commit.generation.as_ref())+ .fold(+ self.commit.generation.clone().unwrap_or_default(),+ |merged, proj| merged.merge_with(proj),+ )}/// Returns the list config for a specific project.@@ -146,14 +184,13 @@ impl UserConfig {/// settings take precedence for fields that are set. Deprecated `[select]`/// sections are normalized into `[switch.picker]` during config loading.pub fn switch_picker(&self, project: Option<&str>) -> SwitchPickerConfig {- let global = self.switch.picker.clone().unwrap_or_default();- match self- .project_overrides(project)- .and_then(|config| config.switch.picker.as_ref())- {- Some(proj) => global.merge_with(proj),- None => global,- }+ self.project_overrides(project)+ .into_iter()+ .filter_map(|config| config.switch.picker.as_ref())+ .fold(+ self.switch.picker.clone().unwrap_or_default(),+ |merged, proj| merged.merge_with(proj),+ )}/// Returns effective hooks for a specific project.@@ -161,13 +198,11 @@ impl UserConfig {/// Merges global hooks with per-project hooks using append semantics./// Both global and per-project hooks run (global first, then per-project).pub fn hooks(&self, project: Option<&str>) -> HooksConfig {- let global = &self.hooks;- let project_hooks = self.project_overrides(project).map(|config| &config.hooks);-- match project_hooks {- Some(ph) => global.merge_with(ph),- None => global.clone(),- }+ self.project_overrides(project)+ .into_iter()+ .fold(self.hooks.clone(), |merged, config| {+ merged.merge_with(&config.hooks)+ })}/// Returns effective aliases for a specific project.@@ -176,7 +211,7 @@ impl UserConfig {/// semantics: both run on name collision (global first, then per-project).pub fn aliases(&self, project: Option<&str>) -> BTreeMap<String, CommandConfig> {let mut result = self.aliases.clone();- if let Some(proj) = self.project_overrides(project) {+ for proj in self.project_overrides(project) {crate::config::commands::append_aliases(&mut result, &proj.aliases);}resultdiff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 10fe4cbf9..02cef87fb 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -7,6 +7,7 @@ mod merge;pub(crate) mod mutation;mod path;mod persistence;+pub(crate) mod project_match;mod resolved;mod schema;mod sections;diff --git a/src/config/user/project_match.rs b/src/config/user/project_match.rsnew file mode 100644index 000000000..c518fe856--- /dev/null+++ b/src/config/user/project_match.rs@@ -0,0 +1,290 @@+//! Matching `[projects."<pattern>"]` keys against a repository's project+//! identifier.+//!+//! # What a key matches+//!+//! A key is either a literal project identifier (`github.com/owner/repo`) or a+//! pattern containing `*`, which stands for any run of characters — `/`+//! included, so `git.company.example/*` covers the nested-group identifier+//! `git.company.example/group/team/repo`. `*` is the only metacharacter; every+//! other character, `.` and `?` among them, is literal.+//!+//! The identifier being matched is [`Repository::project_identifier`], built+//! from the raw `remote.<name>.url` value. `url.insteadOf` rewrites are not+//! applied, so a pattern targets the hostname as it is spelled in+//! `.git/config`. This is the same string an exact key has always matched.+//!+//! [`Repository::project_identifier`]: crate::git::Repository::project_identifier+//!+//! # Ordering+//!+//! Several keys can match one repository. [`matching_keys`] returns them+//! least- to most-specific, so a caller that folds them in order lets the most+//! specific win, and the layering reads the same as global → project does+//! elsewhere in the config.+//!+//! Specificity is the number of literal (non-`*`) characters in the pattern:+//! `git.company.example/team/*` beats `git.company.example/*` beats `*`. A+//! literal key outranks any pattern outright — a pattern whose stars all match+//! empty (`github.com/owner/repo*`) ties the exact key on literal count, and+//! the exact key must still win. Equal-specificity patterns fall back to+//! lexicographic order so the result never depends on map iteration luck.+//!+//! # Where patterns do not apply+//!+//! Writes are always keyed by the exact identifier: `wt config approvals add`+//! records under `github.com/owner/repo`, never under a pattern that happens+//! to match it. Removals are exact for the same reason — one repository's+//! `wt config approvals clear` must not empty a pattern entry that other+//! repositories rely on. An identifier that itself contains `*` (a starred+//! remote URL, or a no-remote path fallback with a star in it) would turn a+//! verbatim write into a pattern entry, so `Approvals::approve_commands`+//! refuses it; pattern entries are hand-written, with no exception.++use std::collections::BTreeMap;++/// Whether `pattern` matches `identifier`, treating `*` as any run of+/// characters and every other character as a literal.+///+/// A hand-rolled glob rather than a compiled regex because accessors call+/// this per pattern key per invocation — `wt list` reaches it a few hundred+/// times — and regex compilation there measured ~0.7 ms per pattern key per+/// command.+pub(crate) fn matches(pattern: &str, identifier: &str) -> bool {+ // Greedy two-pointer glob: `*` first matches empty, then extends one byte+ // on each later mismatch. Only the most recent star ever needs revisiting,+ // because extending an earlier star can't let the identifier end any+ // sooner. Bytes are UTF-8-safe here: `*` never occurs inside a multibyte+ // sequence, and literal runs compare byte-for-byte. Every other byte —+ // `/` and newline included — is matchable, so the path-shaped identifier+ // a remoteless repository falls back to works on every platform that+ // permits one in a directory name.+ let (pattern, identifier) = (pattern.as_bytes(), identifier.as_bytes());+ let (mut p, mut i) = (0, 0);+ let mut retry: Option<(usize, usize)> = None;+ while i < identifier.len() {+ if pattern.get(p) == Some(&b'*') {+ retry = Some((p, i));+ p += 1;+ } else if pattern.get(p) == Some(&identifier[i]) {+ p += 1;+ i += 1;+ } else if let Some((star, matched)) = retry {+ p = star + 1;+ i = matched + 1;+ retry = Some((star, matched + 1));+ } else {+ return false;+ }+ }+ pattern[p..].iter().all(|b| *b == b'*')+}++/// The number of literal characters in `pattern` — its specificity rank.+fn literal_len(pattern: &str) -> usize {+ pattern.chars().filter(|c| *c != '*').count()+}++/// Every key of `projects` matching `identifier`, least- to most-specific.+///+/// A literal key sorts last, so a caller folding the results applies it over+/// any pattern that also matched.+pub(crate) fn matching_keys<'a, T>(+ projects: &'a BTreeMap<String, T>,+ identifier: &str,+) -> Vec<&'a T> {+ // The common case is a config with no patterns at all: take the exact hit+ // and skip the scan entirely.+ if !projects.keys().any(|key| key.contains('*')) {+ return projects.get(identifier).into_iter().collect();+ }++ // The bool ranks a literal key above any pattern it ties with on literal+ // count (one whose stars all matched empty).+ let mut matched: Vec<(usize, bool, &str, &T)> = projects+ .iter()+ .filter(|(key, _)| matches(key, identifier))+ .map(|(key, value)| (literal_len(key), !key.contains('*'), key.as_str(), value))+ .collect();+ matched.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));+ matched.into_iter().map(|(_, _, _, value)| value).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_literal_key_matches_only_itself() {+ assert!(matches("github.com/owner/repo", "github.com/owner/repo"));+ assert!(!matches("github.com/owner/repo", "github.com/owner/other"));+ // `.` is literal, not "any character".+ assert!(!matches("github.com/owner/repo", "githubXcom/owner/repo"));+ }++ #[test]+ fn test_star_spans_path_separators() {+ // The motivating case: one key for every repo on a host, including+ // nested GitLab groups.+ assert!(matches(+ "git.company.example/*",+ "git.company.example/owner/repo"+ ));+ assert!(matches(+ "git.company.example/*",+ "git.company.example/group/team/repo"+ ));+ assert!(!matches("git.company.example/*", "github.com/owner/repo"));+ }++ #[test]+ fn test_star_placement() {+ assert!(matches("*", "github.com/owner/repo"));+ assert!(matches("*/owner/*", "github.com/owner/repo"));+ assert!(matches("github.com/owner/repo*", "github.com/owner/repo"));+ // A bare host with no trailing separator is not a prefix match.+ assert!(!matches("git.company.example", "git.company.example/o/r"));+ }++ #[test]+ fn test_matching_keys_orders_least_to_most_specific() {+ let projects = BTreeMap::from([+ ("*".to_string(), "all"),+ ("git.company.example/*".to_string(), "host"),+ ("git.company.example/team/*".to_string(), "team"),+ ("git.company.example/team/repo".to_string(), "exact"),+ ("github.com/*".to_string(), "other-host"),+ ]);+ assert_eq!(+ matching_keys(&projects, "git.company.example/team/repo"),+ vec![&"all", &"host", &"team", &"exact"]+ );+ }++ #[test]+ fn test_matching_keys_without_patterns_is_exact() {+ let projects = BTreeMap::from([+ ("github.com/owner/repo".to_string(), "mine"),+ ("github.com/owner/other".to_string(), "theirs"),+ ]);+ assert_eq!(+ matching_keys(&projects, "github.com/owner/repo"),+ vec![&"mine"]+ );+ assert!(matching_keys(&projects, "github.com/owner/absent").is_empty());+ }++ #[test]+ fn test_multibyte_literals_and_identifiers() {+ // The glob walks bytes; multibyte literals still compare whole.+ assert!(matches("git.über.example/*", "git.über.example/owner/repo"));+ assert!(!matches(+ "git.über.example/*",+ "git.uber.example/owner/repo"+ ));+ assert!(matches("*/naïve", "github.com/owner/naïve"));+ }++ #[test]+ fn test_star_in_the_identifier() {+ // An identifier containing `*` is matched by a wildcard like any other+ // byte, and a starred key still covers the identical starred+ // identifier (its own star matches the literal `*`).+ assert!(matches("git.example/*", "git.example/owner/re*po"));+ assert!(matches(+ "git.example/owner/re*po",+ "git.example/owner/re*po"+ ));+ assert!(!matches(+ "git.example/owner/re*po",+ "git.example/other/repo"+ ));+ }++ /// Obviously-correct exponential reference for the differential test:+ /// a star matches empty or absorbs one more byte.+ fn matches_ref(pattern: &[u8], identifier: &[u8]) -> bool {+ match pattern.split_first() {+ None => identifier.is_empty(),+ Some((b'*', rest)) => {+ matches_ref(rest, identifier)+ || !identifier.is_empty() && matches_ref(pattern, &identifier[1..])+ }+ Some((byte, rest)) => match identifier.split_first() {+ Some((first, tail)) => first == byte && matches_ref(rest, tail),+ None => false,+ },+ }+ }++ #[test]+ fn test_differential_against_reference_matcher() {+ // Exhaustive over every pattern (≤5 chars of `a`/`b`/`*`) against+ // every identifier (≤6 of the same), pinning the backtracking glob to+ // the spec wholesale — multiple stars, star-in-identifier, and every+ // truncation case included. `/` needs no seat: the matcher treats all+ // non-`*` bytes alike.+ fn strings(alphabet: &[u8], max_len: usize) -> Vec<Vec<u8>> {+ let mut all: Vec<Vec<u8>> = vec![Vec::new()];+ let mut last = all.clone();+ for _ in 0..max_len {+ last = last+ .iter()+ .flat_map(|s| {+ alphabet.iter().map(move |c| {+ let mut s = s.clone();+ s.push(*c);+ s+ })+ })+ .collect();+ all.extend(last.iter().cloned());+ }+ all+ }++ for pattern in strings(b"ab*", 5) {+ let pattern = String::from_utf8(pattern).unwrap();+ for identifier in strings(b"ab*", 6) {+ let identifier = String::from_utf8(identifier).unwrap();+ assert_eq!(+ matches(&pattern, &identifier),+ matches_ref(pattern.as_bytes(), identifier.as_bytes()),+ "pattern {pattern:?} vs identifier {identifier:?}"+ );+ }+ }+ }++ #[test]+ fn test_literal_key_outranks_a_pattern_that_ties() {+ // `github.com/owner/repo*` matches the identifier with its star+ // matching empty, tying the exact key at 21 literal characters — and+ // sorting after it lexicographically. Specificity alone would let the+ // pattern win the fold; the literal-over-pattern rank keeps the exact+ // entry on top.+ let projects = BTreeMap::from([+ ("github.com/owner/repo".to_string(), "exact"),+ ("github.com/owner/repo*".to_string(), "pattern"),+ ]);+ assert_eq!(+ matching_keys(&projects, "github.com/owner/repo"),+ vec![&"pattern", &"exact"]+ );+ }++ #[test]+ fn test_equal_specificity_is_lexicographic() {+ // Both patterns have four literal characters, so neither outranks the+ // other and the tie breaks on the key itself — `*/b/c*` before+ // `*a/b/*`, whatever order the map was built in.+ let projects = BTreeMap::from([+ ("*a/b/*".to_string(), "star-a"),+ ("*/b/c*".to_string(), "star-slash"),+ ]);+ assert_eq!(+ matching_keys(&projects, "a/b/c"),+ vec![&"star-slash", &"star-a"]+ );+ }+}diff --git a/src/config/user/sections.rs b/src/config/user/sections.rsindex a3a7c9c8e..fc89b0772 100644--- a/src/config/user/sections.rs+++ b/src/config/user/sections.rs@@ -551,6 +551,11 @@ impl Merge for StepConfig {/// These are user preferences (not checked into git) that override/// the corresponding global settings when set.///+/// The key is a project identifier (`host/owner/repo`) or a `*` pattern+/// covering a set of them, so one entry can carry settings for every+/// repository on a host. Every matching entry applies, least- to+/// most-specific; the `project_match` module states the rules.+////// # TOML Format/// ```toml/// [projects."github.com/user/repo"]@@ -564,6 +569,10 @@ impl Merge for StepConfig {////// [projects."github.com/user/repo".merge]/// squash = false+///+/// # Every repository on a self-hosted forge whose name carries no brand+/// [projects."git.company.example/*"]+/// forge.platform = "gitlab"/// ```#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default, JsonSchema)]pub struct UserProjectOverrides {@@ -605,6 +614,15 @@ pub struct UserProjectOverrides {#[serde(default, skip_serializing_if = "is_default")]pub step: StepConfig,+ /// Forge platform and API hostname for the matched repositories.+ ///+ /// Same shape as the repository's own `[forge]` block, which wins field by+ /// field where both are set. Both fields describe the host rather than the+ /// repository, so a `*` pattern keyed to a hostname is the usual way to+ /// write them.+ #[serde(default, skip_serializing_if = "is_default")]+ pub forge: crate::config::ProjectForgeConfig,+#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]pub aliases: BTreeMap<String, CommandConfig>,}diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex b3ef25e71..1c4778bc1 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -1,5 +1,6 @@use super::*;use crate::config::HooksConfig;+use crate::config::commands::CommandConfig;use crate::git::HookType;use crate::testing::TestRepo;@@ -3688,3 +3689,136 @@ fn test_with_locked_mutation_propagates_save_error() {"expected save-side read error, got: {msg}");}++#[test]+fn test_pattern_project_key_applies_to_every_repo_on_a_host() {+ let config = UserConfig::load_from_str(+ r#"+worktree-path = "../{{ repo }}.{{ branch | sanitize }}"++[projects."git.company.example/*"]+worktree-path = ".worktrees/{{ branch | sanitize }}"++[projects."git.company.example/*".forge]+platform = "gitlab"+"#,+ )+ .unwrap();++ for project in [+ "git.company.example/owner/repo",+ "git.company.example/group/team/repo",+ ] {+ assert_eq!(+ config.worktree_path_for_project(project),+ ".worktrees/{{ branch | sanitize }}"+ );+ assert!(config.has_project_worktree_path(project));+ assert_eq!(config.forge_platform(Some(project)), Some("gitlab"));+ }++ // A repo on another host takes the global settings.+ assert_eq!(+ config.worktree_path_for_project("github.com/owner/repo"),+ "../{{ repo }}.{{ branch | sanitize }}"+ );+ assert_eq!(config.forge_platform(Some("github.com/owner/repo")), None);+}++#[test]+fn test_exact_project_key_wins_over_a_pattern_that_also_matches() {+ let config = UserConfig::load_from_str(+ r#"+[projects."git.company.example/*"]+worktree-path = "host"++[projects."git.company.example/team/*"]+worktree-path = "team"++[projects."git.company.example/team/repo"]+worktree-path = "exact"+"#,+ )+ .unwrap();++ assert_eq!(+ config.worktree_path_for_project("git.company.example/team/repo"),+ "exact"+ );+ assert_eq!(+ config.worktree_path_for_project("git.company.example/team/other"),+ "team"+ );+ assert_eq!(+ config.worktree_path_for_project("git.company.example/ops/thing"),+ "host"+ );+}++#[test]+fn test_pattern_and_exact_entries_layer_field_by_field() {+ // Each entry contributes the fields it sets; the more specific one wins+ // only where the two collide.+ let config = UserConfig::load_from_str(+ r#"+[projects."git.company.example/*".list]+full = true+branches = true++[projects."git.company.example/owner/repo".list]+branches = false+"#,+ )+ .unwrap();++ let list = config.list(Some("git.company.example/owner/repo"));+ assert_eq!(list.full, Some(true), "kept from the host-wide entry");+ assert_eq!(list.branches, Some(false), "overridden by the exact entry");+}++#[test]+fn test_pattern_and_exact_hooks_both_run() {+ // Hooks append rather than override, so a host-wide hook and a+ // repository-specific one both run, host-wide first.+ let config = UserConfig::load_from_str(+ r#"+[projects."git.company.example/*"]+post-switch = "host-setup"++[projects."git.company.example/owner/repo"]+post-switch = "repo-setup"+"#,+ )+ .unwrap();++ let hooks = config.hooks(Some("git.company.example/owner/repo"));+ let commands: Vec<&str> = hooks+ .post_switch+ .iter()+ .flat_map(CommandConfig::commands)+ .map(|c| c.template.as_str())+ .collect();+ assert_eq!(commands, vec!["host-setup", "repo-setup"]);+}++#[test]+fn test_forge_hostname_from_a_pattern_entry() {+ let config = UserConfig::load_from_str(+ r#"+[projects."work/*".forge]+platform = "github"+hostname = "github.company.example"+"#,+ )+ .unwrap();++ assert_eq!(+ config.forge_platform(Some("work/owner/repo")),+ Some("github")+ );+ assert_eq!(+ config.forge_hostname(Some("work/owner/repo")),+ Some("github.company.example")+ );+ assert_eq!(config.forge_hostname(None), None);+}diff --git a/src/git/ci_platform.rs b/src/git/ci_platform.rsindex 23363fcdf..55931084b 100644--- a/src/git/ci_platform.rs+++ b/src/git/ci_platform.rs@@ -1,9 +1,10 @@//! CI platform identification.//!//! [`ForgeKind`] names the forge a repository's CI runs on (GitHub, GitLab,-//! Gitea, or Azure DevOps). It comes from project config (`forge.platform`, or-//! the deprecated `ci.platform`) when set, otherwise from the remote URL host —-//! see [`Repository::ci_platform`].+//! Gitea, or Azure DevOps). It comes from the configured forge platform when+//! set — the repository's own `[forge].platform` (or the deprecated+//! `ci.platform`), else a matching user-config `[projects."…"].forge` entry —+//! otherwise from the remote URL host. See [`Repository::ci_platform`].use crate::git::{GitRemoteUrl, RefType, Repository};@@ -103,7 +104,9 @@ impl Repository {/// The CI platform for this repository, or `None` if it can't be determined.////// Priority order:- /// 1. Project config `forge.platform` (or the deprecated `ci.platform`)+ /// 1. The configured forge platform — the repository's `[forge].platform`+ /// (or the deprecated `ci.platform`), else a matching user-config+ /// `[projects."…"].forge.platform`/// 2. `remote_hint`'s effective URL host, when `remote_hint` is given/// 3. The primary remote's effective URL host///@@ -134,19 +137,20 @@ impl Repository {None}- /// The CI platform set in project config (`forge.platform` / `ci.platform`).+ /// The configured CI platform: the repository's `[forge].platform` (or the+ /// deprecated `ci.platform`), else a matching user-config+ /// `[projects."…"].forge.platform`.+ ///+ /// The repository's own block wins because it is the more specific of the+ /// two — a user entry keyed `git.company.example/*` states what the host+ /// is, and a repository that disagrees knows better.////// `None` when unset or unrecognized. Resolved once per repository handle,/// so an unrecognized value warns a single time rather than once per branch/// `wt list` probes.fn configured_ci_platform(&self) -> Option<ForgeKind> {*self.cache.configured_ci_platform.get_or_init(|| {- let raw = self- .project_config()- .ok()- .flatten()?- .forge_platform()- .map(str::to_string)?;+ let raw = self.configured_forge_platform()?;match raw.parse::<ForgeKind>() {Ok(platform) => {tracing::debug!(platform = %platform, "Using CI platform from config: {platform}");@@ -155,7 +159,7 @@ impl Repository {Err(_) => {tracing::warn!(value = %raw,- "Invalid CI platform in config: '{raw}'. Expected 'github', 'gitlab', 'gitea', or 'azure-devops'."+ "Invalid CI platform '{raw}' (from `[forge]` in project config or a `[projects]` entry in user config). Expected 'github', 'gitlab', 'gitea', or 'azure-devops'.");None}@@ -334,4 +338,117 @@ mod tests {let repo = Repository::at(test.root_path().to_path_buf()).unwrap();assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitHub));}++ /// Build a repo with `remote_url` and a user config carrying the given+ /// `[projects."<key>"].forge.platform` entries.+ ///+ /// Returns the `TestRepo` alongside the `Repository` so the caller keeps+ /// the checkout's tempdir alive for the duration of the test.+ fn repo_with_user_forge(+ remote_url: &str,+ entries: &[(&str, &str)],+ ) -> (crate::testing::TestRepo, Repository) {+ let test = crate::testing::TestRepo::new();+ test.run_git(&["remote", "add", "origin", remote_url]);++ let mut user_config = crate::config::UserConfig::default();+ for (key, platform) in entries {+ user_config+ .projects+ .entry((*key).to_string())+ .or_default()+ .forge = crate::config::ProjectForgeConfig {+ platform: Some((*platform).to_string()),+ hostname: None,+ };+ }++ let repo = Repository::at(test.root_path().to_path_buf()).unwrap();+ repo.cache+ .user_config+ .set(user_config)+ .expect("user config not yet initialized");+ (test, repo)+ }++ #[test]+ fn test_user_project_pattern_names_platform_for_a_whole_host() {+ // The motivating case: a self-hosted forge whose hostname carries no+ // brand resolves for every repo on it, with no `[forge]` block in any+ // of them. Built-in inference alone gives `None` here.+ let (_test, repo) = repo_with_user_forge(+ "https://git.company.example/owner/repo.git",+ &[("git.company.example/*", "gitlab")],+ );+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitLab));+ }++ #[test]+ fn test_user_project_pattern_covers_nested_groups() {+ let (_test, repo) = repo_with_user_forge(+ "https://git.company.example/group/team/repo.git",+ &[("git.company.example/*", "gitlab")],+ );+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitLab));+ }++ #[test]+ fn test_more_specific_user_pattern_wins() {+ // The Gitea instance lives under one namespace on an otherwise-GitLab+ // host, and the narrower entry is the one that applies.+ let (_test, repo) = repo_with_user_forge(+ "https://git.company.example/tools/repo.git",+ &[+ ("git.company.example/*", "gitlab"),+ ("git.company.example/tools/*", "gitea"),+ ],+ );+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::Gitea));+ }++ #[test]+ fn test_project_forge_overrides_user_pattern() {+ // A repository that names its own forge is more specific than an entry+ // describing the host.+ let test = crate::testing::TestRepo::new();+ test.run_git(&[+ "remote",+ "add",+ "origin",+ "https://git.company.example/owner/repo.git",+ ]);+ test.write_project_config("[forge]\nplatform = \"github\"\n");++ let mut user_config = crate::config::UserConfig::default();+ user_config+ .projects+ .entry("git.company.example/*".to_string())+ .or_default()+ .forge+ .platform = Some("gitlab".to_string());++ let repo = Repository::at(test.root_path().to_path_buf()).unwrap();+ repo.cache.user_config.set(user_config).unwrap();+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitHub));+ }++ #[test]+ fn test_unmatched_user_pattern_falls_through_to_inference() {+ let (_test, repo) = repo_with_user_forge(+ "https://gitlab.com/owner/repo.git",+ &[("git.company.example/*", "github")],+ );+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitLab));+ }++ #[test]+ fn test_invalid_user_platform_leaves_the_host_unresolved() {+ // An unrecognized value warns once and is dropped, rather than+ // resolving the host to a forge that doesn't exist.+ let (_test, repo) = repo_with_user_forge(+ "https://git.company.example/owner/repo.git",+ &[("git.company.example/*", "bitbucket")],+ );+ assert_eq!(repo.ci_platform(None), None);+ }}diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rsindex 6fa16bc71..88526a6f6 100644--- a/src/git/remote_ref/github.rs+++ b/src/git/remote_ref/github.rs@@ -127,11 +127,7 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefIlet api_path = format!("repos/{}/{}/pulls/{}", owner, repo_name, pr_number);// Only pass --hostname when explicitly configured (for GHE / self-hosted).- let hostname = repo- .load_project_config()- .ok()- .flatten()- .and_then(|c| c.forge_hostname().map(String::from));+ let hostname = repo.forge_hostname();let mut args = vec!["api", api_path.as_str()];if let Some(h) = &hostname {diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 16dc25556..ddecd9d9c 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -267,33 +267,69 @@ impl Repository {.and_then(GitRemoteUrl::parse)}- /// Configured `[forge].platform` override, if any.- ///- /// Local-only: reads (and may cache) project config. Every structured-output- /// path that derives a forge provider feeds this into the URL parser so a- /// self-hosted instance whose host can't be auto-detected reports the- /// configured provider instead of `unknown`. Centralized here so the three- /// call sites (`wt list`, `wt list statusline`, `wt config state ci-status`)- /// can't drift — see `repo_info` and `json_output::JsonCi`.- pub fn forge_platform_override(&self) -> Option<String> {- self.project_config()+ /// Configured forge platform: the repository's `[forge].platform` (or the+ /// deprecated `ci.platform`), else a user-config `[projects."…"].forge`+ /// entry matching this repository.+ ///+ /// Local-only: reads (and may cache) project and user config. Every path+ /// that derives a forge provider resolves it here — `wt list` and its+ /// statusline via `repo_info`, `wt switch pr:` when picking a provider,+ /// and CI-platform detection via `Repository::ci_platform` — so a+ /// self-hosted instance whose host carries no forge brand answers the same+ /// way everywhere instead of resolving in one command and reading+ /// `unknown` in the next.+ ///+ /// The repository's own block wins over a user entry: a+ /// `[projects."git.company.example/*"]` entry states what a host is, and a+ /// repository that names something else knows better.+ pub fn configured_forge_platform(&self) -> Option<String> {+ if let Some(platform) = self+ .project_config().ok().flatten().and_then(|config| config.forge_platform().map(str::to_string))+ {+ return Some(platform);+ }+ let project_id = self.project_identifier().ok()?;+ self.user_config()+ .forge_platform(Some(&project_id))+ .map(str::to_string)+ }++ /// The forge API hostname for GitHub Enterprise or self-hosted GitLab.+ ///+ /// The repository's `[forge].hostname`, else a matching user-config+ /// `[projects."…"].forge.hostname`. Passed to the forge CLI as+ /// `--hostname` when the remote's own host isn't the API server — an SSH+ /// alias, or an API on a different name.+ pub fn forge_hostname(&self) -> Option<String> {+ if let Some(hostname) = self+ .project_config()+ .ok()+ .flatten()+ .and_then(|config| config.forge_hostname().map(str::to_string))+ {+ return Some(hostname);+ }+ let project_id = self.project_identifier().ok()?;+ self.user_config()+ .forge_hostname(Some(&project_id))+ .map(str::to_string)}/// Repository metadata derived from the primary remote.///- /// Local-only: built from the cached primary remote URL and optional- /// `[forge].platform`, with no network access. This may load/cache project- /// config to inspect the configured forge platform. The returned+ /// Local-only: built from the cached primary remote URL and the configured+ /// forge platform, with no network access. This may load/cache project and+ /// user config to resolve that platform. The returned/// [`GitRepoInfo::remote`] names which local remote was used, so structured/// JSON can report it.pub fn repo_info(&self) -> Option<GitRepoInfo> {let remote = self.primary_remote().ok()?;let url = self.remote_url(&remote)?;let parsed = GitRemoteUrl::parse(&url)?;- let provider_override = self.forge_platform_override();+ let provider_override = self.configured_forge_platform();let mut info = parsed.repo_info(provider_override.as_deref())?;info.remote = Some(remote);Some(info)diff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rsindex b70dbc21d..a8271a772 100644--- a/tests/integration_tests/approvals.rs+++ b/tests/integration_tests/approvals.rs@@ -252,6 +252,58 @@ fn test_clear_approvals_global_with_approvals(repo: TestRepo) {);}+/// A hand-written pattern entry approves commands `clear` deliberately can't+/// touch; the hint names the entry so the surviving approval is traceable.+#[rstest]+fn test_clear_approvals_only_pattern_entry(repo: TestRepo) {+ // Remove origin so project_identifier uses the canonical worktree path —+ // matches what `Repository::project_identifier` computes at runtime.+ repo.run_git(&["remote", "remove", "origin"]);+ repo.commit("Initial commit");+ repo.write_project_config(r#"pre-start = "echo 'test'""#);+ repo.commit("Add config");++ // Written raw: pattern entries are hand-edited by definition (the write+ // paths refuse `*`).+ fs::write(+ repo.test_approvals_path(),+ "[projects.\"*\"]\napproved-commands = [\"echo 'test'\"]\n",+ )+ .unwrap();++ snapshot_clear_approvals("clear_approvals_only_pattern_entry", &repo, &[]);+}++/// Clearing the exact entry succeeds, and the hint says why `list` will still+/// show the pattern entry's command as approved.+#[rstest]+fn test_clear_approvals_exact_cleared_pattern_remains(repo: TestRepo) {+ // Remove origin so project_identifier uses the canonical worktree path —+ // matches what `Repository::project_identifier` computes at runtime.+ repo.run_git(&["remote", "remove", "origin"]);+ repo.commit("Initial commit");+ repo.write_project_config(r#"pre-start = "echo 'test'""#);+ repo.commit("Add config");++ fs::write(+ repo.test_approvals_path(),+ "[projects.\"*\"]\napproved-commands = [\"echo 'other'\"]\n",+ )+ .unwrap();+ // The exact entry rides the same file: mutations reload it from disk+ // under the lock, so the pattern entry survives alongside.+ let mut approvals = Approvals::default();+ approvals+ .approve_command(+ repo.project_id(),+ "echo 'test'".to_string(),+ repo.test_approvals_path(),+ )+ .unwrap();++ snapshot_clear_approvals("clear_approvals_exact_cleared_pattern_remains", &repo, &[]);+}+#[rstest]fn test_clear_approvals_after_clear(repo: TestRepo) {// Remove origin so project_identifier uses the canonical worktree path —diff --git a/tests/snapshots/integration__integration_tests__approvals__clear_approvals_exact_cleared_pattern_remains.snap b/tests/snapshots/integration__integration_tests__approvals__clear_approvals_exact_cleared_pattern_remains.snapnew file mode 100644index 000000000..73b0170cc--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__clear_approvals_exact_cleared_pattern_remains.snap@@ -0,0 +1,63 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - clear+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[32m✓[39m [32mCleared 1 approval for this project[39m+[2m↳[22m [2mCommands approved by pattern entry [4m*[24m still apply; to change them, edit [TEST_APPROVALS]diff --git a/tests/snapshots/integration__integration_tests__approvals__clear_approvals_only_pattern_entry.snap b/tests/snapshots/integration__integration_tests__approvals__clear_approvals_only_pattern_entry.snapnew file mode 100644index 000000000..3893686a3--- /dev/null+++ b/tests/snapshots/integration__integration_tests__approvals__clear_approvals_only_pattern_entry.snap@@ -0,0 +1,63 @@+---+source: tests/integration_tests/approvals.rs+info:+ program: wt+ args:+ - config+ - approvals+ - clear+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m No approvals to clear for this project+[2m↳[22m [2mCommands approved by pattern entry [4m*[24m still apply; to change them, edit [TEST_APPROVALS]diff --git a/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_configured_platform.snap b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_configured_platform.snapindex 59b769294..c22885250 100644--- a/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_configured_platform.snap+++ b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_configured_platform.snap@@ -67,6 +67,6 @@ exit_code: 0----- stderr -----[33m▲[39m [33mProject config: [1m[ci][22m is deprecated in favor of [1m[forge][22m[39m[2m↳[22m [2mTo see details, run [4mwt config show[24m; to apply updates, run [4mwt config update[24m[22m-[2m[W][22m Invalid CI platform in config: 'invalid_platform'. Expected 'github', 'gitlab', 'gitea', or 'azure-devops'.+[2m[W][22m Invalid CI platform 'invalid_platform' (from `[forge]` in project config or a `[projects]` entry in user config). Expected 'github', 'gitlab', 'gitea', or 'azure-devops'.[2m○[22m [2mShowing 5 worktrees, 1 with changes, 3 ahead[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex 81cc452bd..77142de96 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap@@ -324,6 +324,33 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[107m [0m [2m# step.copy-ignored.exclude = [".repo-local-cache/"][0m[107m [0m [2m# aliases.deploy = "make deploy BRANCH={{ branch }}"[0m[107m [0m [2m#[0m+[107m [0m [2m# #### Matching several repositories with one entry[0m+[107m [0m [2m#[0m+[107m [0m [2m# A key containing `*` matches any run of characters, `/` included, so one entry covers a whole host or namespace — including nested groups. `*` is the only wildcard; every other character, `.` among them, is literal.[0m+[107m [0m [2m#[0m+[107m [0m [2m# # Every repository on a self-hosted forge whose hostname carries no brand[0m+[107m [0m [2m# [projects."git.company.example/*"][0m+[107m [0m [2m# forge.platform = "gitlab"[0m+[107m [0m [2m#[0m+[107m [0m [2m# # Everything under one namespace shares a layout[0m+[107m [0m [2m# [projects."git.company.example/platform/*"][0m+[107m [0m [2m# worktree-path = ".worktrees/{{ branch | sanitize }}"[0m+[107m [0m [2m#[0m+[107m [0m [2m# Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start+[107m [0m with that string.[0m+[107m [0m [2m#[0m+[107m [0m [2m# `approved-commands` matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: `wt config approvals add` and the interactive prompt record under the exact identifier, and `wt config approvals clear` removes only that exact entry, leaving a pattern other repositories share intact.[0m+[107m [0m [2m#[0m+[107m [0m [2m# #### Forge platform and hostname[0m+[107m [0m [2m#[0m+[107m [0m [2m# `forge` names the forge for the matched repositories — the user-level counterpart of the project config's forge platform (https://worktrunk.dev/config/#forge-platform) block, for a self-hosted host whose name carries no `github`, `gitlab`, or `gitea` for detection to read.[0m+[107m [0m [2m#[0m+[107m [0m [2m# [projects."git.company.example/*"][0m+[107m [0m [2m# forge.platform = "gitlab" # or "github", "gitea" (experimental), "azure-devops" (experimental)[0m+[107m [0m [2m# forge.hostname = "api.git.company.example" # API host, when the remote's own host isn't it[0m+[107m [0m [2m#[0m+[107m [0m [2m# Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through `~/.ssh/config` — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own `[forge]` block still wins over any entry here, field by field: a repository that sets only `platform` still takes a matching entry's `hostname`.[0m+[107m [0m [2m#[0m[107m [0m [2m# Hooks support all three hook forms (https://worktrunk.dev/hook/#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:[0m[107m [0m [2m#[0m[107m [0m [2m# # Single command[0m@@ -498,6 +525,8 @@ With [2m--project[0m, creates [2m.config/wt.toml[0m in the current repositor[107m [0m [2m# platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)[0m[107m [0m [2m# hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)[0m[107m [0m [2m#[0m+[107m [0m [2m# When many repositories share one self-hosted host, name it once in user config with a [pattern-keyed `[projects]` entry](@/config.md#user-project-specific-settings) instead of repeating this block in each repo. A repository's own `[forge]` still wins, field by field.[0m+[107m [0m [2m#[0m[107m [0m [2m# ## Commit-message append [experimental][0m[107m [0m [2m#[0m[107m [0m [2m# `template-append` adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex c0253b9b4..4002bac08 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -372,6 +372,33 @@ Scalar values (like [2mworktree-path[0m) replace the global value; everything[107m [0m [2mstep.copy-ignored.exclude = [[0m[2m[32m".repo-local-cache/"[0m[2m][0m[107m [0m [2maliases.deploy = [0m[2m[32m"make deploy BRANCH={{ branch }}"[0m+[1mMatching several repositories with one entry[0m++A key containing [2m*[0m matches any run of characters, [2m/[0m included, so one entry covers a whole host or namespace — including nested groups. [2m*[0m is the only wildcard; every other character, [2m.[0m among them, is literal.++[107m [0m [2m# Every repository on a self-hosted forge whose hostname carries no brand[0m+[107m [0m [2m[36m[projects."git.company.example/*"][0m+[107m [0m [2mforge.platform = [0m[2m[32m"gitlab"[0m+[107m [0m+[107m [0m [2m# Everything under one namespace shares a layout[0m+[107m [0m [2m[36m[projects."git.company.example/platform/*"][0m+[107m [0m [2mworktree-path = [0m[2m[32m".worktrees/{{ branch | sanitize }}"[0m++Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — [2mgit.company.example/platform/*[0m over [2mgit.company.example/*[0m — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-[2m*[0m characters in the key. End a host-wide key with [2m/*[0m — a bare [2mgit.company.example*[0m also covers hosts whose names merely start with that+string.++[2mapproved-commands[0m matches the same way, so a pattern entry approves its commands for every repository it covers. Only a key written by hand is ever a pattern: [2mwt config approvals add[0m and the interactive prompt record under the exact identifier, and [2mwt config approvals clear[0m removes only that exact entry, leaving a pattern other repositories share intact.++[1mForge platform and hostname[0m++[2mforge[0m names the forge for the matched repositories — the user-level counterpart of the project config's forge platform block, for a self-hosted host whose name carries no [2mgithub[0m, [2mgitlab[0m, or [2mgitea[0m for detection to read.++[107m [0m [2m[36m[projects."git.company.example/*"][0m+[107m [0m [2mforge.platform = [0m[2m[32m"gitlab"[0m[2m [0m[2m# or "github", "gitea" (experimental), "azure-devops" (experimental)[0m+[107m [0m [2mforge.hostname = [0m[2m[32m"api.git.company.example"[0m[2m [0m[2m# API host, when the remote's own host isn't it[0m++Both fields describe the host rather than the repository, which is why a pattern keyed to a hostname suits them, and why an SSH alias resolved through [2m~/.ssh/config[0m — where the name in the remote URL is local to one machine — belongs here rather than in a repository's committed config. A repository's own [2m[forge][0m block still wins over any entry here, field by field: a repository that sets only [2mplatform[0m still takes a matching entry's [2mhostname[0m.+Hooks support all three hook forms. A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats [2mprojects."github.com/user/repo".post-start.server = "..."[0m and a [2m[projects."github.com/user/repo".post-start][0m table the same way:[107m [0m [2m# Single command[0m@@ -537,6 +564,8 @@ The forge is read from the remote's hostname: any host carrying [2mgithub[0m,[107m [0m [2mplatform = [0m[2m[32m"github"[0m[2m [0m[2m# or "gitlab", "gitea" (experimental), "azure-devops" (experimental)[0m[107m [0m [2mhostname = [0m[2m[32m"github.example.com"[0m[2m [0m[2m# Example: API host (GHE / self-hosted GitLab)[0m+When many repositories share one self-hosted host, name it once in user config with a pattern-keyed [2m[projects][0m entry instead of repeating this block in each repo. A repository's own [2m[forge][0m still wins, field by field.+[1m[32mCommit-message append [experimental][0m[2mtemplate-append[0m adds project-wide conventions to the LLM commit and squash prompts, shared so every teammate's LLM sees the same style guide:diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_forge_platform_invalid_bails.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_forge_platform_invalid_bails.snapindex 8894b5e6a..85f660736 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_forge_platform_invalid_bails.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_forge_platform_invalid_bails.snap@@ -7,12 +7,23 @@ info:- "pr:101"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test UserGIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"- GIT_CONFIG_SYSTEM: /dev/null+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: C@@ -35,6 +46,7 @@ info:WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -46,4 +58,4 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mInvalid forge.platform value `bitbucket` in .config/wt.toml; expected one of: github, gitlab, gitea, azure-devops[39m+[31m✗[39m [31mInvalid forge.platform value `bitbucket` (from `[forge]` in project config or a `[projects]` entry in user config); expected one of: github, gitlab, gitea, azure-devops[39m