Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(config): keep approvals and [projects] entries saved under v0.80.0 identifiers (#4526)

Maximilian Roos15b1ed10ce8a
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index e8bc5ddb0..62911cf40 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -412,7 +412,7 @@ pub(crate) fn load_aliases(
) -> AliasMap {
let project_id = repo.and_then(|r| r.project_identifier().ok());
let mut result: AliasMap = user_config
- .aliases(project_id.as_deref())
+ .aliases(project_id.as_ref())
.into_iter()
.map(|(n, c)| {
(
@@ -894,7 +894,7 @@ pub(crate) fn load_aliases_for_listing() -> Vec<(String, CommandConfig, HookSour
let user_aliases = UserConfig::load()
.ok()
- .map(|uc| uc.aliases(project_id.as_deref()))
+ .map(|uc| uc.aliases(project_id.as_ref()))
.unwrap_or_default();
let project_aliases = repo
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index a6ab39bfa..454e0c54d 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -22,7 +22,7 @@ use std::path::Path;
use anyhow::Context;
use color_print::cformat;
-use worktrunk::config::{Approvals, require_approvals_path};
+use worktrunk::config::{Approvals, ProjectId, require_approvals_path};
use worktrunk::git::{GitError, HookType};
use worktrunk::styling::{
INFO_SYMBOL, WARNING_SYMBOL, eprint, eprintln, format_heading, hint_message, prompt_message,
@@ -48,7 +48,7 @@ use worktrunk::config::HookSource;
/// file never aborts a `--yes` run.
pub fn approve_command_batch(
commands: &[ApprovableCommand],
- project_id: &str,
+ project_id: &ProjectId,
yes: bool,
) -> anyhow::Result<bool> {
if yes {
@@ -197,7 +197,7 @@ fn prompt_for_batch_approval_with_header(
pub fn approve_alias_commands(
commands: &worktrunk::config::CommandConfig,
alias_name: &str,
- project_id: &str,
+ project_id: &ProjectId,
yes: bool,
) -> anyhow::Result<bool> {
let cmds: Vec<_> = commands
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index bbd3d2334..222b57e1f 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -221,13 +221,13 @@ impl<'a> CommandContext<'a> {
///
/// Uses the remote URL if available, otherwise the canonical repository path.
/// Returns None only if the path is not valid UTF-8.
- pub fn project_id(&self) -> Option<String> {
+ pub fn project_id(&self) -> Option<worktrunk::config::ProjectId> {
self.repo.project_identifier().ok()
}
/// Get the commit generation config, merging project-specific settings.
pub fn commit_generation(&self) -> worktrunk::config::CommitGenerationConfig {
- self.config.commit_generation(self.project_id().as_deref())
+ self.config.commit_generation(self.project_id().as_ref())
}
}
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index a014a3b41..4ffcdcbf9 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -230,7 +230,7 @@ impl CommitOptions<'_> {
wt.ensure_no_unmerged_paths("commit")?;
let project_config = self.ctx.repo.load_project_config()?;
- let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_deref());
+ let user_hooks = self.ctx.config.hooks(self.ctx.project_id().as_ref());
let any_hooks_exist = user_hooks.get(HookType::PreCommit).is_some()
|| project_config
.as_ref()
diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rs
index fa8915a12..def888112 100644
--- a/src/commands/config/alias.rs
+++ b/src/commands/config/alias.rs
@@ -251,7 +251,7 @@ fn entries_for_name(
) -> Vec<(CommandConfig, HookSource)> {
let project_id = repo.project_identifier().ok();
let mut entries = Vec::new();
- if let Some(cfg) = user_config.aliases(project_id.as_deref()).get(name) {
+ if let Some(cfg) = user_config.aliases(project_id.as_ref()).get(name) {
entries.push((cfg.clone(), HookSource::User));
}
if let Some(pc) = project_config
diff --git a/src/commands/config/approvals.rs b/src/commands/config/approvals.rs
index 53176ab2d..9f8db8ee5 100644
--- a/src/commands/config/approvals.rs
+++ b/src/commands/config/approvals.rs
@@ -10,7 +10,7 @@ use anyhow::Context;
use color_print::cformat;
use strum::IntoEnumIterator;
use worktrunk::HookType;
-use worktrunk::config::{Approvals, ProjectConfig, require_approvals_path};
+use worktrunk::config::{Approvals, ProjectConfig, ProjectId, require_approvals_path};
use worktrunk::git::{GitError, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{
@@ -251,7 +251,11 @@ pub fn add_approvals(show_all: bool, yes: bool) -> anyhow::Result<()> {
.map(|cmd| cmd.command.template.clone())
.collect();
approvals
- .approve_commands(project_id, templates, &require_approvals_path()?)
+ .approve_commands(
+ project_id.to_string(),
+ templates,
+ &require_approvals_path()?,
+ )
.context("Failed to save command approval")?;
eprintln!("{}", success_message("Commands approved & saved to config"));
@@ -328,12 +332,7 @@ pub fn clear_approvals(global: bool, stale: bool) -> anyhow::Result<()> {
let repo = Repository::current()?;
let project_id = repo.project_identifier()?;
- // Count approvals before clearing
- let approval_count = approvals
- .projects()
- .find(|(id, _)| *id == project_id)
- .map(|(_, cmds)| cmds.len())
- .unwrap_or(0);
+ let approval_count = approvals.exact_approval_count(&project_id);
if approval_count == 0 {
eprintln!("{}", info_message("No approvals to clear for this project"));
@@ -362,7 +361,7 @@ pub fn clear_approvals(global: bool, stale: bool) -> anyhow::Result<()> {
/// 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<()> {
+fn emit_pattern_entries_hint(approvals: &Approvals, project_id: &ProjectId) -> anyhow::Result<()> {
let keys = approvals.matching_pattern_keys(project_id);
if keys.is_empty() {
return Ok(());
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index b3d309f69..0f5d5b58a 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -191,7 +191,7 @@ fn handle_config_show_json() -> anyhow::Result<()> {
{
invalid = true;
}
- let identifier = repo.project_identifier().ok();
+ let identifier = repo.project_identifier().ok().map(|id| id.to_string());
let exists = on_disk.as_ref().is_some_and(|path| path.exists()) || object_store_exists;
(path, exists, config, identifier)
} else {
@@ -640,7 +640,7 @@ fn render_diagnostics(out: &mut String, repo: Option<&Repository>) -> anyhow::Re
// Test commit generation - use effective config for current project
let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.and_then(|repo| repo.project_identifier().ok());
- let commit_config = config.commit_generation(project_id.as_deref());
+ let commit_config = config.commit_generation(project_id.as_ref());
if !commit_config.is_configured() {
writeln!(out, "{}", info_message("Commit generation not configured"))?;
diff --git a/src/commands/context.rs b/src/commands/context.rs
index 201361107..a85b4bf3a 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -121,12 +121,12 @@ impl CommandEnv {
///
/// Uses the remote URL if available, otherwise the canonical repository path.
/// Returns None only if the path is not valid UTF-8.
- pub fn project_id(&self) -> Option<String> {
+ pub fn project_id(&self) -> Option<worktrunk::config::ProjectId> {
self.repo.project_identifier().ok()
}
/// Get all resolved config with defaults applied.
pub fn resolved(&self) -> worktrunk::config::ResolvedConfig {
- self.config.resolved(self.project_id().as_deref())
+ self.config.resolved(self.project_id().as_ref())
}
}
diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rs
index 6645b21ab..588b1c12f 100644
--- a/src/commands/hook_commands.rs
+++ b/src/commands/hook_commands.rs
@@ -11,7 +11,7 @@ use color_print::cformat;
use strum::IntoEnumIterator;
use worktrunk::HookType;
use worktrunk::config::{
- ALIAS_ARGS_KEY, Approvals, CommandConfig, ProjectConfig, UserConfig, binds_cli_var,
+ ALIAS_ARGS_KEY, Approvals, CommandConfig, ProjectConfig, ProjectId, UserConfig, binds_cli_var,
referenced_vars_for_config,
};
use worktrunk::git::Repository;
@@ -240,7 +240,7 @@ pub fn run_hook(
}
// Get effective user hooks (global + per-project merged)
- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
+ let user_hooks = ctx.config.hooks(ctx.project_id().as_ref());
let user_config = user_hooks.get(hook_type);
let proj_config = project_config.as_ref().and_then(|c| c.hooks.get(hook_type));
// No hooks configured: warn and exit successfully. Running hooks that
@@ -395,7 +395,7 @@ pub fn handle_hook_show(
config,
project_config,
&approvals,
- project_id.as_deref(),
+ project_id.as_ref(),
filter,
ctx.as_ref(),
);
@@ -408,7 +408,7 @@ pub fn handle_hook_show(
&mut output,
config,
&approvals,
- project_id.as_deref(),
+ project_id.as_ref(),
filter,
ctx.as_ref(),
)?;
@@ -420,7 +420,7 @@ pub fn handle_hook_show(
&repo,
project_config,
&approvals,
- project_id.as_deref(),
+ project_id.as_ref(),
filter,
ctx.as_ref(),
)?;
@@ -440,7 +440,7 @@ fn emit_hook_show_json(
user_config: &UserConfig,
project_config: Option<&ProjectConfig>,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
filter: Option<HookType>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
@@ -502,7 +502,7 @@ fn render_user_hooks(
out: &mut String,
config: &UserConfig,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
filter: Option<HookType>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
@@ -546,7 +546,7 @@ fn render_project_hooks(
repo: &Repository,
project_config: Option<&ProjectConfig>,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
filter: Option<HookType>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
@@ -595,7 +595,7 @@ fn render_hook_section(
hooks: &[(HookType, &CommandConfig)],
source: HookSource,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
filter: Option<HookType>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<()> {
@@ -625,7 +625,7 @@ fn render_hook_commands(
config: &CommandConfig,
source: HookSource,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
ctx: Option<&CommandContext>,
) -> anyhow::Result<bool> {
let mut wrote_any = false;
@@ -658,7 +658,7 @@ fn render_hook_commands(
fn needs_approval(
source: HookSource,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
template: &str,
) -> bool {
match source {
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rs
index 7723d6697..7a10b322d 100644
--- a/src/commands/hook_plan.rs
+++ b/src/commands/hook_plan.rs
@@ -46,7 +46,7 @@ use std::path::{Path, PathBuf};
use anyhow::Context as _;
use worktrunk::HookType;
-use worktrunk::config::{Approvals, Command, CommandConfig, ProjectConfig, UserConfig};
+use worktrunk::config::{Approvals, Command, CommandConfig, ProjectConfig, ProjectId, UserConfig};
use worktrunk::git::add_hook_skip_hint;
use super::command_approval::approve_command_batch;
@@ -91,7 +91,7 @@ pub struct HookPlanBuilder<'a> {
entries: Vec<PlanEntry>,
project_config: Option<&'a ProjectConfig>,
user: &'a UserConfig,
- project_id: Option<&'a str>,
+ project_id: Option<&'a ProjectId>,
}
impl<'a> HookPlanBuilder<'a> {
@@ -103,7 +103,7 @@ impl<'a> HookPlanBuilder<'a> {
pub fn new(
project_config: Option<&'a ProjectConfig>,
user: &'a UserConfig,
- project_id: Option<&'a str>,
+ project_id: Option<&'a ProjectId>,
) -> Self {
Self {
entries: Vec::new(),
@@ -203,7 +203,7 @@ impl HookPlan {
/// path that has something to approve requires it.
pub fn approve(
self,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
yes: bool,
) -> anyhow::Result<Option<ApprovedHookPlan>> {
let approvable = self.approvable();
@@ -236,7 +236,7 @@ impl HookPlan {
pub fn approve_readonly(
self,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
) -> ApprovedHookPlan {
let mut entries = self.entries;
for entry in &mut entries {
@@ -260,7 +260,7 @@ impl HookPlan {
pub fn unapproved_project_commands(
&self,
approvals: &Approvals,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
) -> Vec<String> {
let Some(pid) = project_id else {
return Vec::new();
@@ -442,7 +442,7 @@ mod tests {
// `--yes` ⇒ approved without writing approvals.
let plan = builder
.finish()
- .approve(Some("proj"), true)
+ .approve(Some(&ProjectId::from("proj")), true)
.unwrap()
.expect("yes-approval never declines");
@@ -480,7 +480,7 @@ mod tests {
let plan = builder
.finish()
// Empty approvals ⇒ the project pipeline is unapproved.
- .approve_readonly(&Approvals::default(), Some("proj"));
+ .approve_readonly(&Approvals::default(), Some(&ProjectId::from("proj")));
let sel = plan.lookup(HookType::PreRemove, Path::new("/wt"));
assert_eq!(
@@ -504,7 +504,9 @@ mod tests {
.unwrap();
let mut builder = HookPlanBuilder::new(Some(&proj), &user, None);
builder.add(Path::new("/wt"), &[HookType::PreRemove]);
- let plan = builder.finish().approve_readonly(&approvals, Some("proj"));
+ let plan = builder
+ .finish()
+ .approve_readonly(&approvals, Some(&ProjectId::from("proj")));
let sel = plan.lookup(HookType::PreRemove, Path::new("/wt"));
assert_eq!(
sel.iter().map(|(s, _)| *s).collect::<Vec<_>>(),
@@ -530,7 +532,7 @@ mod tests {
builder.add(Path::new("/dest"), &[HookType::PostMerge]);
let plan = builder
.finish()
- .approve(Some("proj"), true)
+ .approve(Some(&ProjectId::from("proj")), true)
.unwrap()
.unwrap();
let sources: Vec<_> = plan
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 47f7db773..5b11b760f 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -359,7 +359,7 @@ impl<'a> HookAnnouncer<'a> {
display_path: Option<&Path>,
) -> anyhow::Result<()> {
let project_config = ctx.repo.load_project_config()?;
- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
+ let user_hooks = ctx.config.hooks(ctx.project_id().as_ref());
let flat = prepare_and_check(
ctx,
user_hooks.get(hook_type),
@@ -758,7 +758,7 @@ pub(crate) fn execute_hook(
failure_strategy: FailureStrategy,
) -> anyhow::Result<bool> {
let project_config = ctx.repo.load_project_config()?;
- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
+ let user_hooks = ctx.config.hooks(ctx.project_id().as_ref());
run_hooks_foreground(
ctx,
user_hooks.get(hook_type),
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index ca900685b..1ddebafa1 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -7,7 +7,7 @@ use std::path::Path;
use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
-use worktrunk::config::{MergeConfig, UserConfig};
+use worktrunk::config::{MergeConfig, ProjectId, UserConfig};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{eprintln, info_message};
@@ -107,7 +107,7 @@ fn approve_merge_plan(
config: &UserConfig,
feature_root: &Path,
destination_path: &Path,
- project_id: &str,
+ project_id: &ProjectId,
verify: bool,
will_remove: bool,
will_switch: bool,
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 7e0a4ee4e..115a0cfa9 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -1330,7 +1330,7 @@ fn approved_removal_plan(
// pipeline can be matched against approvals — `approve_readonly` then
// drops them (fail-closed), rather than aborting the picker removal.
let project_id = repo.project_identifier().ok();
- let pid = project_id.as_deref();
+ let pid = project_id.as_ref();
let user = repo.user_config();
let project_config = repo.load_project_config()?;
@@ -3972,7 +3972,7 @@ pub mod tests {
let approvals_path = approvals_dir.path().join("approvals.toml");
let mut approvals = Approvals::default();
approvals
- .approve_commands(pid, vec!["false".to_string()], &approvals_path)
+ .approve_commands(pid.to_string(), vec!["false".to_string()], &approvals_path)
.unwrap();
// Build the row from the git-reported worktree path, not the raw temp
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 130dd28b5..9f50b18d5 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -338,7 +338,7 @@ pub fn validate_candidates(
worktree.stage(StageMode::All)?;
// Commit using shared pipeline
let project_id = repo.project_identifier().ok();
- let commit_config = config.commit_generation(project_id.as_deref());
+ let commit_config = config.commit_generation(project_id.as_ref());
CommitGenerator::new(&commit_config, project_append).commit_staged_changes(
&worktree,
false, // show_progress - already showing "Committing changes in..."
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index 9a2a495ab..8bf60b30b 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -386,7 +386,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
let project = repo.project_identifier().ok();
let cli_override = flag_pair(args.delete_branch, args.no_delete_branch);
let delete_branch =
- cli_override.unwrap_or_else(|| config.remove(project.as_deref()).delete_branch());
+ cli_override.unwrap_or_else(|| config.remove(project.as_ref()).delete_branch());
// Validate conflicting flags
if !delete_branch && args.force_delete {
@@ -423,7 +423,7 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
// up empty and `approve` never needs it). Matches the pre-plan
// behaviour where the empty-batch fast path ran first.
let project_id = repo.project_identifier().ok();
- let pid = project_id.as_deref();
+ let pid = project_id.as_ref();
let project_config = repo.load_project_config()?;
let mut builder = HookPlanBuilder::new(project_config.as_ref(), &config, pid);
for &wt_path in removed_worktree_paths {
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 5ec818bd9..d2d4a941b 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -33,7 +33,7 @@ use color_print::cformat;
use crossbeam_channel as chan;
use rayon::prelude::*;
use worktrunk::HookType;
-use worktrunk::config::{Approvals, ProjectConfig, UserConfig};
+use worktrunk::config::{Approvals, ProjectConfig, ProjectId, UserConfig};
use worktrunk::git::{
BranchDeletionMode, IntegrationReason, RefSnapshot, Repository, WorktreeInfo,
};
@@ -928,7 +928,7 @@ fn build_pessimistic_plan(
current_root: &Path,
project_config: Option<&ProjectConfig>,
user_config: &UserConfig,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
) -> anyhow::Result<HookPlan> {
let mut builder = HookPlanBuilder::new(project_config, user_config, project_id);
let mut has_current = false;
@@ -958,7 +958,7 @@ fn unapproved_for_hook(
hook_type: HookType,
project_config: Option<&ProjectConfig>,
user_config: &UserConfig,
- project_id: Option<&str>,
+ project_id: Option<&ProjectId>,
approvals: &Approvals,
) -> Vec<String> {
let Ok(home) = repo.home_path() else {
@@ -1115,7 +1115,7 @@ pub fn step_prune(
// (`wt config approvals add`) or remove individually
// (`wt -C <wt> remove`). Unapproved hooks never run silently.
let project_id_owned = repo.project_identifier().ok();
- let project_id = project_id_owned.as_deref();
+ let project_id = project_id_owned.as_ref();
let project_config = repo.load_project_config()?;
let approvals = if yes {
Approvals::default()
diff --git a/src/commands/step/relocate.rs b/src/commands/step/relocate.rs
index a993a8a1b..ba6e2547b 100644
--- a/src/commands/step/relocate.rs
+++ b/src/commands/step/relocate.rs
@@ -100,7 +100,7 @@ pub fn step_relocate(
use super::super::command_approval::approve_commit_template_append;
use super::super::command_executor::CommandContext;
let project_id = repo.project_identifier().ok();
- let commit_config = config.commit_generation(project_id.as_deref());
+ let commit_config = config.commit_generation(project_id.as_ref());
if commit_config.is_configured() {
let ctx = CommandContext::new(&repo, &config, None, &repo_path, false);
approve_commit_template_append(&ctx)?
diff --git a/src/commands/step/shared.rs b/src/commands/step/shared.rs
index 58d40d5e9..ff0c19867 100644
--- a/src/commands/step/shared.rs
+++ b/src/commands/step/shared.rs
@@ -92,7 +92,7 @@ pub(super) fn resolve_copy_ignored_config(repo: &Repository) -> anyhow::Result<C
config = config.merged_with(project_copy_ignored);
}
let project_id = repo.project_identifier().ok();
- config = config.merged_with(&user_config.copy_ignored(project_id.as_deref()));
+ config = config.merged_with(&user_config.copy_ignored(project_id.as_ref()));
Ok(config)
}
diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rs
index 95f481732..c1feffba5 100644
--- a/src/commands/step/squash.rs
+++ b/src/commands/step/squash.rs
@@ -139,7 +139,7 @@ pub fn handle_squash_in(
// Check if any pre-commit hooks exist (needed for skip message and approval)
let project_config = repo.load_project_config()?;
- let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());
+ let user_hooks = ctx.config.hooks(ctx.project_id().as_ref());
let any_hooks_exist = user_hooks.get(HookType::PreCommit).is_some()
|| project_config
.as_ref()
@@ -509,7 +509,7 @@ fn preview_squash(
let repo = Repository::current()?;
let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.project_identifier().ok();
- let commit_config = config.commit_generation(project_id.as_deref());
+ let commit_config = config.commit_generation(project_id.as_ref());
let integration_target = repo.require_target_ref(target)?;
// #3519: preview against the same upstream-aware span the real squash uses.
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 0da55d93a..dd962c986 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -1713,7 +1713,7 @@ fn approve_switch_hooks(
// when the project identifier can't be resolved (the plan ends up empty
// and `approve` never needs it).
let project_id = repo.project_identifier().ok();
- let pid = project_id.as_deref();
+ let pid = project_id.as_ref();
let project_config = repo.load_project_config()?;
let mut builder = HookPlanBuilder::new(project_config.as_ref(), config, pid);
builder.add(
@@ -2129,7 +2129,7 @@ fn run_switch(
// Now that we have the repo, we can resolve project-specific config.
let change_dir = change_dir_flag.unwrap_or_else(|| {
let project_id = repo.project_identifier().ok();
- config.resolved(project_id.as_deref()).switch.cd()
+ config.resolved(project_id.as_ref()).switch.cd()
});
// Build switch suggestion context for enriching error hints with --path/--execute/trailing args.
@@ -2287,7 +2287,7 @@ fn validate_switch_templates(
}
let project_config = repo.load_project_config()?;
- let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());
+ let user_hooks = config.hooks(repo.project_identifier().ok().as_ref());
for &hook_type in switch_post_hook_types(plan.is_create()) {
let user_cfg = user_hooks.get(hook_type);
diff --git a/src/config/approvals.rs b/src/config/approvals.rs
index e1debca6f..73319d985 100644
--- a/src/config/approvals.rs
+++ b/src/config/approvals.rs
@@ -24,7 +24,7 @@ use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
-use super::ConfigError;
+use super::{ConfigError, ProjectId};
use crate::config::deprecation::normalize_template_vars;
use crate::path::format_path_for_display;
@@ -228,7 +228,7 @@ impl Approvals {
/// 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 {
+ pub fn is_command_approved(&self, project: &ProjectId, command: &str) -> bool {
let normalized_command = normalize_template_vars(command);
crate::config::matching_project_keys(&self.projects, project)
.into_iter()
@@ -247,17 +247,19 @@ impl Approvals {
}
/// Pattern keys whose approved commands cover `project` — the entries
- /// [`Self::is_command_approved`] consults beyond the exact one. Always
+ /// [`Self::is_command_approved`] consults beyond the exact ones. 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> {
+ pub fn matching_pattern_keys(&self, project: &ProjectId) -> Vec<&str> {
self.projects
.iter()
.filter(|(key, p)| {
key.contains('*')
&& !p.approved_commands.is_empty()
- && super::user::project_match::matches(key, project)
+ && project
+ .exact_keys()
+ .any(|id| super::user::project_match::matches(key, id))
})
.map(|(key, _)| key.as_str())
.collect()
@@ -267,26 +269,30 @@ impl Approvals {
/// 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> {
+ /// Reads the exact keys only (the current and legacy identifiers),
+ /// 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: &ProjectId, templates: &[&str]) -> Vec<&'a str> {
let normalized: Vec<_> = templates
.iter()
.map(|t| normalize_template_vars(t))
.collect();
- self.projects
- .get(project)
- .map(|p| {
- p.approved_commands
- .iter()
- .filter(|c| !normalized.contains(&normalize_template_vars(c)))
- .map(String::as_str)
- .collect()
- })
- .unwrap_or_default()
+ let mut stale: Vec<&str> = Vec::new();
+ for command in project
+ .exact_keys()
+ .filter_map(|key| self.projects.get(key))
+ .flat_map(|p| &p.approved_commands)
+ {
+ if !normalized.contains(&normalize_template_vars(command))
+ && !stale.contains(&command.as_str())
+ {
+ stale.push(command);
+ }
+ }
+ stale
}
}
@@ -393,25 +399,35 @@ impl Approvals {
})
}
- /// Remove all approvals for a project and save.
+ /// Remove all approvals for a project and save, including any saved under
+ /// its legacy identifier.
pub fn revoke_project(
&mut self,
- project: &str,
+ project: &ProjectId,
approvals_path: &Path,
) -> Result<(), ConfigError> {
- let project = project.to_string();
self.with_locked_mutation(approvals_path, |approvals| {
- let Some(project_config) = approvals.projects.get_mut(&project) else {
- return false;
- };
- if project_config.approved_commands.is_empty() {
- return false;
+ let mut changed = false;
+ for key in project.exact_keys() {
+ changed |= approvals
+ .projects
+ .remove(key)
+ .is_some_and(|p| !p.approved_commands.is_empty());
}
- approvals.projects.remove(&project);
- true
+ changed
})
}
+ /// The number of approvals saved for `project` under its exact keys —
+ /// what [`Self::revoke_project`] removes.
+ pub fn exact_approval_count(&self, project: &ProjectId) -> usize {
+ project
+ .exact_keys()
+ .filter_map(|key| self.projects.get(key))
+ .map(|p| p.approved_commands.len())
+ .sum()
+ }
+
/// Remove approvals for `project` that match none of `templates` (the
/// project's current command set) and save. Returns the removed commands.
///
@@ -420,7 +436,7 @@ impl Approvals {
/// this call is never removed by mistake.
pub fn revoke_stale(
&mut self,
- project: &str,
+ project: &ProjectId,
templates: &[&str],
approvals_path: &Path,
) -> Result<Vec<String>, ConfigError> {
@@ -434,14 +450,16 @@ impl Approvals {
if stale.is_empty() {
return false;
}
- let Some(project_config) = approvals.projects.get_mut(project) else {
- return false;
- };
- project_config
- .approved_commands
- .retain(|c| !stale.contains(c));
- if project_config.approved_commands.is_empty() {
- approvals.projects.remove(project);
+ for key in project.exact_keys() {
+ let Some(project_config) = approvals.projects.get_mut(key) else {
+ continue;
+ };
+ project_config
+ .approved_commands
+ .retain(|c| !stale.contains(c));
+ if project_config.approved_commands.is_empty() {
+ approvals.projects.remove(key);
+ }
}
removed = stale;
true
@@ -514,7 +532,7 @@ mod tests {
#[test]
fn test_empty_approvals() {
let approvals = Approvals::default();
- assert!(!approvals.is_command_approved("any/project", "any command"));
+ assert!(!approvals.is_command_approved(&"any/project".into(), "any command"));
}
#[test]
@@ -529,12 +547,17 @@ 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")
+ approvals.is_command_approved(&"git.company.example/owner/repo".into(), "npm install")
+ );
+ assert!(
+ approvals
+ .is_command_approved(&"git.company.example/group/team/repo".into(), "npm install")
+ );
+ assert!(!approvals.is_command_approved(&"github.com/owner/repo".into(), "npm install"));
+ assert!(
+ !approvals.is_command_approved(&"git.company.example/owner/repo".into(), "npm test")
);
- assert!(!approvals.is_command_approved("github.com/owner/repo", "npm install"));
- assert!(!approvals.is_command_approved("git.company.example/owner/repo", "npm test"));
}
#[test]
@@ -560,12 +583,12 @@ approved-commands = ["make"]
// no commands are all excluded — only entries actually supplying
// approvals are worth naming.
assert_eq!(
- approvals.matching_pattern_keys("git.company.example/owner/repo"),
+ approvals.matching_pattern_keys(&"git.company.example/owner/repo".into()),
vec!["git.company.example/*"]
);
assert!(
approvals
- .matching_pattern_keys("codeberg.org/owner/repo")
+ .matching_pattern_keys(&"codeberg.org/owner/repo".into())
.is_empty()
);
}
@@ -589,7 +612,8 @@ approved-commands = ["make"]
.unwrap_err();
assert!(err.to_string().contains("pattern"), "got: {err}");
assert!(
- !approvals.is_command_approved("git.company.example/owner/re*po", "npm install"),
+ !approvals
+ .is_command_approved(&"git.company.example/owner/re*po".into(), "npm install"),
"nothing may be recorded in memory"
);
assert!(!path.exists(), "nothing may be written to disk");
@@ -619,9 +643,11 @@ approved-commands = ["npm install"]
)
.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"),
+ approvals.is_command_approved(&"git.company.example/owner/repo".into(), "npm test")
+ );
+ assert!(
+ !approvals.is_command_approved(&"git.company.example/other/repo".into(), "npm test"),
"the pattern entry must not have absorbed the new approval"
);
}
@@ -642,15 +668,15 @@ approved-commands = ["npm test"]
approvals.save_to(&path).unwrap();
approvals
- .revoke_project("git.company.example/owner/repo", &path)
+ .revoke_project(&"git.company.example/owner/repo".into(), &path)
.unwrap();
assert!(
- !approvals.is_command_approved("git.company.example/owner/repo", "npm test"),
+ !approvals.is_command_approved(&"git.company.example/owner/repo".into(), "npm test"),
"the repository's own approval is gone"
);
assert!(
- approvals.is_command_approved("git.company.example/owner/repo", "npm install"),
+ approvals.is_command_approved(&"git.company.example/owner/repo".into(), "npm install"),
"the pattern entry other repositories share is untouched"
);
}
@@ -668,9 +694,9 @@ approved-commands = ["npm test"]
)
.unwrap();
- assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
- assert!(!approvals.is_command_approved("github.com/user/repo", "npm test"));
- assert!(!approvals.is_command_approved("github.com/other/repo", "npm install"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(!approvals.is_command_approved(&"github.com/user/repo".into(), "npm test"));
+ assert!(!approvals.is_command_approved(&"github.com/other/repo".into(), "npm install"));
}
#[test]
@@ -715,8 +741,8 @@ approved-commands = ["npm test"]
)
.unwrap();
- assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
- assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm test"));
}
#[test]
@@ -740,12 +766,55 @@ approved-commands = ["npm test"]
.unwrap();
approvals
- .revoke_project("github.com/user/repo1", &path)
+ .revoke_project(&"github.com/user/repo1".into(), &path)
.unwrap();
assert!(!approvals.projects.contains_key("github.com/user/repo1"));
assert!(approvals.projects.contains_key("github.com/user/repo2"));
}
+ /// A project's approvals saved under its v0.80.0 identifier count toward
+ /// it, show as stale, and go with it on revoke, so `wt config approvals
+ /// clear` leaves nothing of its own approving commands.
+ #[test]
+ fn test_revoke_project_includes_legacy_identifier() {
+ let (_temp_dir, path) = test_dir();
+ let project = ProjectId::with_legacy(
+ "github.com/user/repo".to_string(),
+ Some("GitHub.com/user/repo".to_string()),
+ );
+
+ let mut approvals = Approvals::default();
+ for (key, command) in [
+ ("GitHub.com/user/repo", "npm install"),
+ ("github.com/user/repo", "npm test"),
+ ("github.com/user/other", "cargo build"),
+ ] {
+ approvals
+ .approve_commands(key.to_string(), vec![command.to_string()], &path)
+ .unwrap();
+ }
+ assert!(approvals.is_command_approved(&project, "npm install"));
+ assert_eq!(approvals.exact_approval_count(&project), 2);
+ assert_eq!(
+ approvals.stale_approvals(&project, &["npm test"]),
+ ["npm install"]
+ );
+
+ let removed = approvals
+ .revoke_stale(&project, &["npm test"], &path)
+ .unwrap();
+ assert_eq!(removed, ["npm install"]);
+ assert!(!approvals.projects.contains_key("GitHub.com/user/repo"));
+ assert!(approvals.is_command_approved(&project, "npm test"));
+
+ approvals.revoke_project(&project, &path).unwrap();
+ assert!(!approvals.is_command_approved(&project, "npm test"));
+ assert_eq!(
+ approvals.projects.keys().collect::<Vec<_>>(),
+ ["github.com/user/other"]
+ );
+ }
+
#[test]
fn test_clear_all() {
let (_temp_dir, path) = test_dir();
@@ -785,8 +854,8 @@ approved-commands = ["npm test"]
// Load from disk
let loaded = load_from_path(&path).unwrap();
- assert!(loaded.is_command_approved("github.com/user/repo", "npm install"));
- assert!(loaded.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(loaded.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(loaded.is_command_approved(&"github.com/user/repo".into(), "npm test"));
}
/// Failure to create the approvals directory must leave the blocking file
@@ -853,8 +922,8 @@ approved-commands = ["npm test"]
assert_eq!(std::fs::read_to_string(&path).unwrap(), original_content);
let loaded = Approvals::load_from_file(&path).unwrap();
- assert!(loaded.is_command_approved("github.com/user/repo", "npm install"));
- assert!(!loaded.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(loaded.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(!loaded.is_command_approved(&"github.com/user/repo".into(), "npm test"));
}
#[test]
@@ -895,7 +964,7 @@ approved-commands = ["npm test"]
.unwrap();
// Should match with canonical variable name
- assert!(approvals.is_command_approved("project", "echo {{ repo_path }}"));
+ assert!(approvals.is_command_approved(&"project".into(), "echo {{ repo_path }}"));
}
#[test]
@@ -911,7 +980,7 @@ approved-commands = ["npm test"]
)
.unwrap();
- assert!(!approvals.is_command_approved("project", "echo repo_path"));
+ assert!(!approvals.is_command_approved(&"project".into(), "echo repo_path"));
}
#[test]
@@ -975,9 +1044,9 @@ approved-commands = ["cargo build"]
.unwrap();
let approvals = Approvals::load_from_config_file(&config_path).unwrap();
- assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
- assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
- assert!(approvals.is_command_approved("github.com/other/repo", "cargo build"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm test"));
+ assert!(approvals.is_command_approved(&"github.com/other/repo".into(), "cargo build"));
}
/// When `approvals.toml` doesn't exist but `config.toml` is a sibling with
@@ -1010,8 +1079,8 @@ approved-commands = ["npm install"]
.unwrap();
// Both the fallback command and the new one should be present
- assert!(approvals.is_command_approved("github.com/user/repo", "npm install"));
- assert!(approvals.is_command_approved("github.com/user/repo", "npm test"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm install"));
+ assert!(approvals.is_command_approved(&"github.com/user/repo".into(), "npm test"));
// approvals.toml should now exist with both commands
let content = std::fs::read_to_string(&approvals_path).unwrap();
@@ -1101,8 +1170,10 @@ approved-command = ["npm test"]
.approve_commands("project-a".to_string(), vec!["cmd1".to_string()], &path)
.unwrap();
// Revoke a project that doesn't exist — should be a no-op
- approvals.revoke_project("nonexistent", &path).unwrap();
- assert!(approvals.is_command_approved("project-a", "cmd1"));
+ approvals
+ .revoke_project(&"nonexistent".into(), &path)
+ .unwrap();
+ assert!(approvals.is_command_approved(&"project-a".into(), "cmd1"));
}
#[test]
@@ -1156,7 +1227,9 @@ approved-command = ["npm test"]
// Write this state to disk
approvals.save_to(&path).unwrap();
// Now revoke_project should find the project but see empty commands → no-op
- approvals.revoke_project("project-a", &path).unwrap();
+ approvals
+ .revoke_project(&"project-a".into(), &path)
+ .unwrap();
}
/// Stale = approved but matching no config template, with the same
@@ -1179,11 +1252,12 @@ approved-command = ["npm test"]
)
.unwrap();
- let stale = approvals.stale_approvals("project", &["npm test", "echo {{ repo_path }}"]);
+ let stale =
+ approvals.stale_approvals(&"project".into(), &["npm test", "echo {{ repo_path }}"]);
assert_eq!(stale, vec!["removed command"]);
assert!(
approvals
- .stale_approvals("other-project", &["npm test"])
+ .stale_approvals(&"other-project".into(), &["npm test"])
.is_empty()
);
}
@@ -1210,20 +1284,22 @@ approved-command = ["npm test"]
let templates = ["npm test", "echo {{ repo_path }}"];
let removed = approvals
- .revoke_stale("project", &templates, &path)
+ .revoke_stale(&"project".into(), &templates, &path)
.unwrap();
assert_eq!(removed, vec!["removed command"]);
- assert!(approvals.is_command_approved("project", "npm test"));
- assert!(approvals.is_command_approved("project", "echo {{ repo_root }}"));
+ assert!(approvals.is_command_approved(&"project".into(), "npm test"));
+ assert!(approvals.is_command_approved(&"project".into(), "echo {{ repo_root }}"));
// Nothing stale left — a second call is a no-op.
let removed = approvals
- .revoke_stale("project", &templates, &path)
+ .revoke_stale(&"project".into(), &templates, &path)
.unwrap();
assert!(removed.is_empty());
// Every remaining approval stale — the project entry disappears.
- let removed = approvals.revoke_stale("project", &[], &path).unwrap();
+ let removed = approvals
+ .revoke_stale(&"project".into(), &[], &path)
+ .unwrap();
assert_eq!(removed.len(), 2);
assert!(!approvals.projects.contains_key("project"));
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index e827fd791..376cc76b9 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -228,6 +228,7 @@ pub use unknown_tree::{
UnknownTree, UnknownWarning, collect_unknown_warnings, compute_unknown_tree,
};
pub use user::LoadError;
+pub use user::project_match::ProjectId;
pub(crate) use user::project_match::matching_keys as matching_project_keys;
pub use user::{
CommitConfig, CommitGenerationConfig, CopyIgnoredConfig, ListColumnConfig, ListConfig,
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index cbe569ef6..aaed4fddd 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -8,9 +8,9 @@ use std::path::PathBuf;
use normalize_path::NormalizePath;
-use crate::config::HooksConfig;
use crate::config::commands::CommandConfig;
use crate::config::expansion::expand_template;
+use crate::config::{HooksConfig, ProjectId};
use crate::path::format_path_for_display;
use crate::shell_exec::ShellEscapeMode;
@@ -36,7 +36,7 @@ impl UserConfig {
/// and ordering rules.
fn project_overrides(
&self,
- project: Option<&str>,
+ project: Option<&ProjectId>,
) -> Vec<&super::sections::UserProjectOverrides> {
project.map_or_else(Vec::new, |p| {
super::project_match::matching_keys(&self.projects, p)
@@ -45,7 +45,7 @@ impl UserConfig {
fn merged_project_config<T: Merge + Clone>(
&self,
- project: Option<&str>,
+ project: Option<&ProjectId>,
global: &T,
project_config: impl Fn(&super::sections::UserProjectOverrides) -> &T,
) -> T {
@@ -60,7 +60,7 @@ impl UserConfig {
/// so the most specific entry that sets it wins.
fn project_field<'a, T>(
&'a self,
- project: Option<&str>,
+ project: Option<&ProjectId>,
field: impl Fn(&'a super::sections::UserProjectOverrides) -> Option<T>,
) -> Option<T> {
self.project_overrides(project)
@@ -82,7 +82,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 {
+ pub fn has_project_worktree_path(&self, project: &ProjectId) -> bool {
self.project_field(Some(project), |p| p.worktree_path.as_ref())
.is_some()
}
@@ -91,7 +91,7 @@ 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 {
+ pub fn worktree_path_for_project(&self, project: &ProjectId) -> String {
self.project_field(Some(project), |p| p.worktree_path.clone())
.unwrap_or_else(|| self.worktree_path())
}
@@ -103,7 +103,7 @@ impl UserConfig {
/// 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> {
+ pub fn forge_platform(&self, project: Option<&ProjectId>) -> Option<&str> {
self.project_field(project, |p| p.forge.platform.as_deref())
}
@@ -112,7 +112,7 @@ impl UserConfig {
/// 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> {
+ pub fn forge_hostname(&self, project: Option<&ProjectId>) -> Option<&str> {
self.project_field(project, |p| p.forge.hostname.as_deref())
}
@@ -122,7 +122,7 @@ impl UserConfig {
/// settings take precedence for fields that are set. Deprecated
/// `[commit-generation]` sections are normalized into `[commit.generation]`
/// during config loading.
- pub fn commit_generation(&self, project: Option<&str>) -> CommitGenerationConfig {
+ pub fn commit_generation(&self, project: Option<&ProjectId>) -> CommitGenerationConfig {
self.project_overrides(project)
.into_iter()
.filter_map(|config| config.commit.generation.as_ref())
@@ -136,7 +136,7 @@ impl UserConfig {
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn list(&self, project: Option<&str>) -> ListConfig {
+ pub fn list(&self, project: Option<&ProjectId>) -> ListConfig {
self.merged_project_config(project, &self.list, |config| &config.list)
}
@@ -144,7 +144,7 @@ impl UserConfig {
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn commit(&self, project: Option<&str>) -> CommitConfig {
+ pub fn commit(&self, project: Option<&ProjectId>) -> CommitConfig {
self.merged_project_config(project, &self.commit, |config| &config.commit)
}
@@ -152,7 +152,7 @@ impl UserConfig {
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn merge(&self, project: Option<&str>) -> MergeConfig {
+ pub fn merge(&self, project: Option<&ProjectId>) -> MergeConfig {
self.merged_project_config(project, &self.merge, |config| &config.merge)
}
@@ -160,7 +160,7 @@ impl UserConfig {
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn remove(&self, project: Option<&str>) -> RemoveConfig {
+ pub fn remove(&self, project: Option<&ProjectId>) -> RemoveConfig {
self.merged_project_config(project, &self.remove, |config| &config.remove)
}
@@ -168,17 +168,17 @@ impl UserConfig {
///
/// Merges project-specific settings with global settings, where project
/// settings take precedence for fields that are set.
- pub fn switch(&self, project: Option<&str>) -> SwitchConfig {
+ pub fn switch(&self, project: Option<&ProjectId>) -> SwitchConfig {
self.merged_project_config(project, &self.switch, |config| &config.switch)
}
/// Returns the `wt step` config for a specific project.
- pub fn step(&self, project: Option<&str>) -> StepConfig {
+ pub fn step(&self, project: Option<&ProjectId>) -> StepConfig {
self.merged_project_config(project, &self.step, |config| &config.step)
}
/// Returns the `wt step copy-ignored` config for a specific project.
- pub fn copy_ignored(&self, project: Option<&str>) -> CopyIgnoredConfig {
+ pub fn copy_ignored(&self, project: Option<&ProjectId>) -> CopyIgnoredConfig {
self.step(project).copy_ignored.unwrap_or_default()
}
@@ -187,7 +187,7 @@ impl UserConfig {
/// Merges project-specific settings with global settings, where project
/// 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 {
+ pub fn switch_picker(&self, project: Option<&ProjectId>) -> SwitchPickerConfig {
self.project_overrides(project)
.into_iter()
.filter_map(|config| config.switch.picker.as_ref())
@@ -201,7 +201,7 @@ 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 {
+ pub fn hooks(&self, project: Option<&ProjectId>) -> HooksConfig {
self.project_overrides(project)
.into_iter()
.fold(self.hooks.clone(), |merged, config| {
@@ -213,7 +213,7 @@ impl UserConfig {
///
/// Merges global user aliases with per-project user aliases using append
/// semantics: both run on name collision (global first, then per-project).
- pub fn aliases(&self, project: Option<&str>) -> BTreeMap<String, CommandConfig> {
+ pub fn aliases(&self, project: Option<&ProjectId>) -> BTreeMap<String, CommandConfig> {
let mut result = self.aliases.clone();
for proj in self.project_overrides(project) {
crate::config::commands::append_aliases(&mut result, &proj.aliases);
@@ -226,7 +226,7 @@ impl UserConfig {
/// Returns all resolved config with defaults applied.
///
/// Merges global and per-project settings, applying defaults for any unset fields.
- pub fn resolved(&self, project: Option<&str>) -> super::resolved::ResolvedConfig {
+ pub fn resolved(&self, project: Option<&ProjectId>) -> super::resolved::ResolvedConfig {
super::resolved::ResolvedConfig::for_project(self, project)
}
@@ -249,7 +249,7 @@ impl UserConfig {
main_worktree: &str,
branch: &str,
repo: &crate::git::Repository,
- project: Option<&str>,
+ project: Option<&ProjectId>,
) -> anyhow::Result<String> {
let template = match project {
Some(p) => self.worktree_path_for_project(p),
@@ -314,7 +314,7 @@ impl UserConfig {
})?;
let project = repo.project_identifier().ok();
- let expanded_path = self.format_path(repo_name, branch, repo, project.as_deref())?;
+ let expanded_path = self.format_path(repo_name, branch, repo, project.as_ref())?;
Ok(repo_root.join(expanded_path).normalize())
}
diff --git a/src/config/user/project_match.rs b/src/config/user/project_match.rs
index c518fe856..6ad74ec0d 100644
--- a/src/config/user/project_match.rs
+++ b/src/config/user/project_match.rs
@@ -30,6 +30,23 @@
//! the exact key must still win. Equal-specificity patterns fall back to
//! lexicographic order so the result never depends on map iteration luck.
//!
+//! # Identifiers from v0.80.0 and earlier
+//!
+//! The release after v0.80.0 changed the identifier of some remotes: a
+//! non-default SSH port joined the host, hosts were lowercased, and
+//! `git+ssh://` URLs began to parse. So that keys saved under the old
+//! identifier keep applying, a [`ProjectId`] carries it too where it differs
+//! (see [`legacy_project_identifier`]). Keys matching it count as least
+//! specific: [`matching_keys`] returns them before every key matching the
+//! current identifier, ordered among themselves by the usual rules. Settings
+//! under a current key override settings under a legacy key, and approvals
+//! under either key apply, so approving a new command (recorded under the
+//! current identifier) keeps the earlier approvals in force. The per-project
+//! `wt config approvals` operations (`list`'s stale approvals, `clear`, `clear
+//! --stale`) treat the legacy exact key like the current one.
+//!
+//! [`legacy_project_identifier`]: crate::git::legacy_project_identifier
+//!
//! # Where patterns do not apply
//!
//! Writes are always keyed by the exact identifier: `wt config approvals add`
@@ -43,6 +60,71 @@
use std::collections::BTreeMap;
+/// A repository's project identifier, the key for `approvals.toml` and
+/// `[projects."…"]` settings, as [`Repository::project_identifier`] computes
+/// it.
+///
+/// Dereferences to the current identifier, which is what is shown and
+/// written. Lookups that take a `ProjectId` also read keys saved under the
+/// identifier v0.80.0 computed for the same remote; see the module docs.
+///
+/// [`Repository::project_identifier`]: crate::git::Repository::project_identifier
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ProjectId {
+ current: String,
+ legacy: Option<String>,
+}
+
+impl ProjectId {
+ /// An identifier with a v0.80.0 spelling, kept only where it differs from
+ /// the current one.
+ pub(crate) fn with_legacy(current: String, legacy: Option<String>) -> Self {
+ let legacy = legacy.filter(|legacy| *legacy != current);
+ Self { current, legacy }
+ }
+
+ /// The identifier v0.80.0 computed for this repository's remote, when it
+ /// differs from the current one.
+ pub fn legacy(&self) -> Option<&str> {
+ self.legacy.as_deref()
+ }
+
+ /// The exact keys this project's entries can be saved under: the current
+ /// identifier, then the legacy one.
+ pub fn exact_keys(&self) -> impl Iterator<Item = &str> {
+ std::iter::once(self.current.as_str()).chain(self.legacy())
+ }
+}
+
+impl From<&str> for ProjectId {
+ fn from(current: &str) -> Self {
+ Self {
+ current: current.to_string(),
+ legacy: None,
+ }
+ }
+}
+
+impl std::ops::Deref for ProjectId {
+ type Target = str;
+
+ fn deref(&self) -> &str {
+ &self.current
+ }
+}
+
+impl PartialEq<&str> for ProjectId {
+ fn eq(&self, other: &&str) -> bool {
+ self.current == *other
+ }
+}
+
+impl std::fmt::Display for ProjectId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.current)
+ }
+}
+
/// Whether `pattern` matches `identifier`, treating `*` as any run of
/// characters and every other character as a literal.
///
@@ -85,29 +167,48 @@ fn literal_len(pattern: &str) -> usize {
pattern.chars().filter(|c| *c != '*').count()
}
-/// Every key of `projects` matching `identifier`, least- to most-specific.
+/// Every key of `projects` matching `project`, least- to most-specific.
///
/// A literal key sorts last, so a caller folding the results applies it over
-/// any pattern that also matched.
+/// any pattern that also matched. Keys matching only the legacy identifier
+/// come first of all.
pub(crate) fn matching_keys<'a, T>(
projects: &'a BTreeMap<String, T>,
- identifier: &str,
+ project: &ProjectId,
) -> Vec<&'a T> {
+ let current = ranked_keys(projects, project);
+ let mut matched = match project.legacy() {
+ Some(legacy) => ranked_keys(projects, legacy)
+ .into_iter()
+ .filter(|key| !current.contains(key))
+ .collect(),
+ None => Vec::new(),
+ };
+ matched.extend(current);
+ matched.into_iter().map(|key| &projects[key]).collect()
+}
+
+/// The keys of `projects` matching `identifier`, least- to most-specific.
+fn ranked_keys<'a, T>(projects: &'a BTreeMap<String, T>, identifier: &str) -> Vec<&'a str> {
// 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();
+ return projects
+ .get_key_value(identifier)
+ .map(|(key, _)| key.as_str())
+ .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))
+ let mut matched: Vec<(usize, bool, &str)> = projects
+ .keys()
+ .filter(|key| matches(key, identifier))
+ .map(|key| (literal_len(key), !key.contains('*'), key.as_str()))
.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()
+ matched.sort();
+ matched.into_iter().map(|(_, _, key)| key).collect()
}
#[cfg(test)]
@@ -156,7 +257,7 @@ mod tests {
("github.com/*".to_string(), "other-host"),
]);
assert_eq!(
- matching_keys(&projects, "git.company.example/team/repo"),
+ matching_keys(&projects, &"git.company.example/team/repo".into()),
vec![&"all", &"host", &"team", &"exact"]
);
}
@@ -168,10 +269,30 @@ mod tests {
("github.com/owner/other".to_string(), "theirs"),
]);
assert_eq!(
- matching_keys(&projects, "github.com/owner/repo"),
+ matching_keys(&projects, &"github.com/owner/repo".into()),
vec![&"mine"]
);
- assert!(matching_keys(&projects, "github.com/owner/absent").is_empty());
+ assert!(matching_keys(&projects, &"github.com/owner/absent".into()).is_empty());
+ }
+
+ #[test]
+ fn test_legacy_identifier_keys_rank_below_current_ones() {
+ let projects = BTreeMap::from([
+ ("*".to_string(), "all"),
+ ("git.example/*".to_string(), "legacy-host"),
+ ("git.example/owner/repo".to_string(), "legacy-exact"),
+ ("git.example:2222/*".to_string(), "host"),
+ ("git.example:2222/owner/repo".to_string(), "exact"),
+ ]);
+ let project = ProjectId::with_legacy(
+ "git.example:2222/owner/repo".to_string(),
+ Some("git.example/owner/repo".to_string()),
+ );
+ // `*` matches both identifiers and ranks with the current ones.
+ assert_eq!(
+ matching_keys(&projects, &project),
+ vec![&"legacy-host", &"legacy-exact", &"all", &"host", &"exact"]
+ );
}
#[test]
@@ -268,7 +389,7 @@ mod tests {
("github.com/owner/repo*".to_string(), "pattern"),
]);
assert_eq!(
- matching_keys(&projects, "github.com/owner/repo"),
+ matching_keys(&projects, &"github.com/owner/repo".into()),
vec![&"pattern", &"exact"]
);
}
@@ -283,7 +404,7 @@ mod tests {
("*/b/c*".to_string(), "star-slash"),
]);
assert_eq!(
- matching_keys(&projects, "a/b/c"),
+ matching_keys(&projects, &"a/b/c".into()),
vec![&"star-slash", &"star-a"]
);
}
diff --git a/src/config/user/resolved.rs b/src/config/user/resolved.rs
index 98e9075eb..1754bc157 100644
--- a/src/config/user/resolved.rs
+++ b/src/config/user/resolved.rs
@@ -9,6 +9,7 @@ use super::sections::{
CommitConfig, CommitGenerationConfig, ListConfig, MergeConfig, RemoveConfig, StepConfig,
SwitchConfig, SwitchPickerConfig,
};
+use crate::config::ProjectId;
/// All resolved configuration for a specific project context.
///
@@ -46,7 +47,7 @@ pub struct ResolvedConfig {
impl ResolvedConfig {
/// Resolve all configuration for a project.
- pub fn for_project(config: &UserConfig, project: Option<&str>) -> Self {
+ pub fn for_project(config: &UserConfig, project: Option<&ProjectId>) -> Self {
Self {
list: config.list(project),
merge: config.merge(project),
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 13d8da976..75d0ed21e 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -1,6 +1,6 @@
use super::*;
-use crate::config::HooksConfig;
use crate::config::commands::CommandConfig;
+use crate::config::{HooksConfig, ProjectId};
use crate::git::HookType;
use crate::testing::TestRepo;
@@ -201,7 +201,7 @@ fn test_worktree_path_for_project_uses_project_specific() {
// Project-specific path should be used
assert_eq!(
- config.worktree_path_for_project("github.com/user/repo"),
+ config.worktree_path_for_project(&ProjectId::from("github.com/user/repo")),
".worktrees/{{ branch | sanitize }}"
);
}
@@ -223,7 +223,7 @@ fn test_worktree_path_for_project_falls_back_to_global() {
// Should fall back to global worktree-path
assert_eq!(
- config.worktree_path_for_project("github.com/user/repo"),
+ config.worktree_path_for_project(&ProjectId::from("github.com/user/repo")),
"../{{ repo }}-{{ branch | sanitize }}"
);
}
@@ -234,7 +234,7 @@ fn test_worktree_path_for_project_falls_back_to_default() {
// Unknown project should fall back to default template
assert_eq!(
- config.worktree_path_for_project("github.com/unknown/project"),
+ config.worktree_path_for_project(&ProjectId::from("github.com/unknown/project")),
"{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"
);
}
@@ -260,7 +260,7 @@ fn test_format_path_with_project_override() {
"myrepo",
"feature/branch",
&test.repo,
- Some("github.com/user/repo"),
+ Some(&ProjectId::from("github.com/user/repo")),
)
.unwrap();
assert_eq!(path, ".worktrees/feature-branch");
@@ -549,7 +549,11 @@ delete-branch = false
// Global default is preserved
assert!(parsed.remove(None).delete_branch());
// Project override wins
- assert!(!parsed.remove(Some("github.com/user/repo")).delete_branch());
+ assert!(
+ !parsed
+ .remove(Some(&ProjectId::from("github.com/user/repo")))
+ .delete_branch()
+ );
}
#[test]
@@ -632,7 +636,7 @@ fn test_set_project_worktree_path() {
.unwrap();
assert_eq!(
- config.worktree_path_for_project("github.com/user/repo"),
+ config.worktree_path_for_project(&ProjectId::from("github.com/user/repo")),
"../{{ branch | sanitize }}"
);
@@ -930,14 +934,14 @@ fn test_effective_commit_generation_with_project_override() {
);
// With project identifier, should merge project config
- let effective = config.commit_generation(Some("github.com/user/repo"));
+ let effective = config.commit_generation(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(effective.command, Some("project-llm".to_string()));
// Without project or unknown project, should use global
let effective = config.commit_generation(None);
assert_eq!(effective.command, Some("global-llm".to_string()));
- let effective = config.commit_generation(Some("github.com/other/repo"));
+ let effective = config.commit_generation(Some(&ProjectId::from("github.com/other/repo")));
assert_eq!(effective.command, Some("global-llm".to_string()));
}
@@ -970,7 +974,7 @@ fn test_effective_merge_with_partial_override() {
},
);
- let effective = config.merge(Some("github.com/user/repo"));
+ let effective = config.merge(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(effective.squash, Some(false)); // From project
assert_eq!(effective.commit, Some(true)); // From global
assert_eq!(effective.rebase, Some(true)); // From global
@@ -993,13 +997,13 @@ fn test_effective_list_project_only() {
},
);
- let effective = config.list(Some("github.com/user/repo"));
+ let effective = config.list(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(effective.full, Some(true));
assert!(effective.branches.is_none());
// No global, no matching project falls back to default
assert_eq!(
- config.list(Some("github.com/other/repo")),
+ config.list(Some(&ProjectId::from("github.com/other/repo"))),
ListConfig::default()
);
}
@@ -1015,7 +1019,7 @@ fn test_effective_commit_global_only() {
..Default::default()
};
- let effective = config.commit(Some("github.com/any/project"));
+ let effective = config.commit(Some(&ProjectId::from("github.com/any/project")));
assert_eq!(effective.stage, Some(StageMode::Tracked));
}
@@ -1353,7 +1357,7 @@ fn test_switch_picker_project_override() {
},
);
- let picker = config.switch_picker(Some("github.com/user/repo"));
+ let picker = config.switch_picker(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(picker.pager.as_deref(), Some("bat")); // From project
}
@@ -1370,7 +1374,7 @@ pager = "bat"
)
.unwrap();
- let picker = config.switch_picker(Some("github.com/user/repo"));
+ let picker = config.switch_picker(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(picker.pager.as_deref(), Some("bat"));
// [select] is migrated to [switch.picker] at the TOML level before parsing,
// so it ends up in the switch.picker field, not select
@@ -1519,13 +1523,13 @@ squash = false
assert_eq!(project.merge.squash, Some(false));
// Effective config for project
- let effective_cg = config.commit_generation(Some("github.com/user/repo"));
+ let effective_cg = config.commit_generation(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(
effective_cg.command,
Some("claude -p --model opus".to_string())
);
- let effective_merge = config.merge(Some("github.com/user/repo"));
+ let effective_merge = config.merge(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(effective_merge.squash, Some(false));
}
@@ -1552,12 +1556,14 @@ exclude = [".repo-local/", ".entire/"]
assert_eq!(config.copy_ignored(None).exclude, expected_global);
assert_eq!(
- config.copy_ignored(Some(project_id)).exclude,
+ config
+ .copy_ignored(Some(&ProjectId::from(project_id)))
+ .exclude,
expected_merged.clone()
);
assert_eq!(
config
- .resolved(Some(project_id))
+ .resolved(Some(&ProjectId::from(project_id)))
.step
.copy_ignored()
.exclude,
@@ -1598,7 +1604,7 @@ command = "claude -p --model opus"
Some("claude -p --model opus")
);
- let effective_cg = config.commit_generation(Some("github.com/user/repo"));
+ let effective_cg = config.commit_generation(Some(&ProjectId::from("github.com/user/repo")));
assert_eq!(
effective_cg.command,
Some("claude -p --model opus".to_string())
@@ -1711,7 +1717,7 @@ fn test_hooks_merge_append_semantics() {
},
);
- let effective = config.hooks(Some("github.com/user/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/user/repo")));
let post_create = effective.post_create.unwrap();
let commands: Vec<_> = post_create.commands().collect();
assert_eq!(commands.len(), 2);
@@ -1727,7 +1733,7 @@ fn test_hooks_no_project_override_uses_global() {
..Default::default()
};
- let effective = config.hooks(Some("github.com/other/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/other/repo")));
let post_create = effective.post_create.unwrap();
let commands: Vec<_> = post_create.commands().collect();
assert_eq!(commands.len(), 1);
@@ -1747,7 +1753,7 @@ fn test_hooks_project_only_no_global() {
},
);
- let effective = config.hooks(Some("github.com/user/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/user/repo")));
let post_create = effective.post_create.unwrap();
let commands: Vec<_> = post_create.commands().collect();
assert_eq!(commands.len(), 1);
@@ -1771,7 +1777,7 @@ fn test_hooks_different_hook_types_not_merged() {
},
);
- let effective = config.hooks(Some("github.com/user/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/user/repo")));
// post-start: only global
let post_create = effective.post_create.unwrap();
@@ -1907,7 +1913,7 @@ setup = "echo setup"
);
// Verify merge preserves order: global first, then project
- let effective = config.hooks(Some("github.com/user/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/user/repo")));
let commands: Vec<_> = effective.post_create.as_ref().unwrap().commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "npm install"); // Global first
@@ -1946,7 +1952,7 @@ test = "npm test"
);
// Both commands present, global first
- let effective = config.hooks(Some("github.com/user/repo"));
+ let effective = config.hooks(Some(&ProjectId::from("github.com/user/repo")));
let commands: Vec<_> = effective.post_create.as_ref().unwrap().commands().collect();
assert_eq!(commands.len(), 2);
assert_eq!(commands[0].template, "cargo test");
@@ -2130,7 +2136,7 @@ project-only = "only-project"
"#;
let config: UserConfig = toml::from_str(toml_str).unwrap();
- let aliases = config.aliases(Some("test-project"));
+ let aliases = config.aliases(Some(&ProjectId::from("test-project")));
// Non-colliding aliases are present
assert_eq!(aliases["global-only"].commands().count(), 1);
@@ -2432,7 +2438,7 @@ fn test_cli_layer_outranks_project_worktree_path() {
let (table, warnings) = apply_overrides(base, &["worktree-path = \"/from-cli\""]);
assert!(warnings.is_empty());
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-cli"
);
}
@@ -2452,7 +2458,7 @@ fn test_env_layer_outranks_project_worktree_path() {
assert!(warnings.is_empty());
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-env"
);
}
@@ -2498,7 +2504,7 @@ fn test_file_layer_outranks_lower_layer_project_entry() {
);
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-user-global"
);
}
@@ -2518,8 +2524,11 @@ branches = true
let (table, warnings) = apply_overrides(base, &["list.full = false"]);
assert!(warnings.is_empty());
let config = loaded(table);
- assert_eq!(config.worktree_path_for_project(PROJECT), "/from-project");
- let list = config.list(Some(PROJECT));
+ assert_eq!(
+ config.worktree_path_for_project(&ProjectId::from(PROJECT)),
+ "/from-project"
+ );
+ let list = config.list(Some(&ProjectId::from(PROJECT)));
assert_eq!(list.full, Some(false), "the higher layer wins");
assert_eq!(list.branches, Some(true), "sibling key survives");
}
@@ -2538,7 +2547,7 @@ fn test_layer_keeps_its_own_project_scoped_override() {
);
assert!(warnings.is_empty());
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-cli-project"
);
}
@@ -2553,7 +2562,7 @@ fn test_layer_applies_to_pattern_entries() {
let (table, warnings) = apply_overrides(base, &["worktree-path = \"/from-cli\""]);
assert!(warnings.is_empty());
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-cli"
);
}
@@ -2591,15 +2600,20 @@ exclude = ["project-pattern"]
.collect::<Vec<_>>()
};
assert_eq!(
- templates(&config.hooks(Some(PROJECT)).pre_merge.unwrap()),
+ templates(
+ &config
+ .hooks(Some(&ProjectId::from(PROJECT)))
+ .pre_merge
+ .unwrap()
+ ),
["cli-hook", "project-hook"]
);
assert_eq!(
- templates(&config.aliases(Some(PROJECT))["ship"]),
+ templates(&config.aliases(Some(&ProjectId::from(PROJECT)))["ship"]),
["cli-alias", "project-alias"]
);
assert_eq!(
- config.copy_ignored(Some(PROJECT)).exclude,
+ config.copy_ignored(Some(&ProjectId::from(PROJECT))).exclude,
["cli-pattern", "project-pattern"]
);
}
@@ -2622,7 +2636,10 @@ width = 30
&["list.custom-columns.Ticket.template = \"from-cli\""],
);
assert!(warnings.is_empty());
- let column = loaded(table).list(Some(PROJECT)).custom_columns["Ticket"].clone();
+ let column = loaded(table)
+ .list(Some(&ProjectId::from(PROJECT)))
+ .custom_columns["Ticket"]
+ .clone();
assert_eq!(column.template, "from-cli");
assert_eq!(column.width, None, "the column went as a unit");
@@ -2646,7 +2663,10 @@ width = 30
],
);
assert!(warnings.is_empty());
- let column = loaded(table).list(Some(PROJECT)).custom_columns["Ticket"].clone();
+ let column = loaded(table)
+ .list(Some(&ProjectId::from(PROJECT)))
+ .custom_columns["Ticket"]
+ .clone();
assert_eq!(column.template, "from-cli-project");
assert_eq!(column.width, None, "the column went as a unit here too");
}
@@ -2658,7 +2678,7 @@ fn test_layer_noop_without_overrides() {
let (table, warnings) = apply_overrides(base, &[]);
assert!(warnings.is_empty());
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-project"
);
}
@@ -2671,7 +2691,7 @@ fn test_dropped_layer_leaves_projects_intact() {
let (table, warnings) = apply_overrides(base, &["worktree-path = \"/from-cli\"", "garbage"]);
assert_eq!(warnings.len(), 1);
assert_eq!(
- loaded(table).worktree_path_for_project(PROJECT),
+ loaded(table).worktree_path_for_project(&ProjectId::from(PROJECT)),
"/from-project"
);
}
@@ -3173,19 +3193,25 @@ platform = "gitlab"
"git.company.example/group/team/repo",
] {
assert_eq!(
- config.worktree_path_for_project(project),
+ config.worktree_path_for_project(&ProjectId::from(project)),
".worktrees/{{ branch | sanitize }}"
);
- assert!(config.has_project_worktree_path(project));
- assert_eq!(config.forge_platform(Some(project)), Some("gitlab"));
+ assert!(config.has_project_worktree_path(&ProjectId::from(project)));
+ assert_eq!(
+ config.forge_platform(Some(&ProjectId::from(project))),
+ Some("gitlab")
+ );
}
// A repo on another host takes the global settings.
assert_eq!(
- config.worktree_path_for_project("github.com/owner/repo"),
+ config.worktree_path_for_project(&ProjectId::from("github.com/owner/repo")),
"../{{ repo }}.{{ branch | sanitize }}"
);
- assert_eq!(config.forge_platform(Some("github.com/owner/repo")), None);
+ assert_eq!(
+ config.forge_platform(Some(&ProjectId::from("github.com/owner/repo"))),
+ None
+ );
}
#[test]
@@ -3205,15 +3231,15 @@ worktree-path = "exact"
.unwrap();
assert_eq!(
- config.worktree_path_for_project("git.company.example/team/repo"),
+ config.worktree_path_for_project(&ProjectId::from("git.company.example/team/repo")),
"exact"
);
assert_eq!(
- config.worktree_path_for_project("git.company.example/team/other"),
+ config.worktree_path_for_project(&ProjectId::from("git.company.example/team/other")),
"team"
);
assert_eq!(
- config.worktree_path_for_project("git.company.example/ops/thing"),
+ config.worktree_path_for_project(&ProjectId::from("git.company.example/ops/thing")),
"host"
);
}
@@ -3234,7 +3260,7 @@ branches = false
)
.unwrap();
- let list = config.list(Some("git.company.example/owner/repo"));
+ let list = config.list(Some(&ProjectId::from("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");
}
@@ -3254,7 +3280,7 @@ post-switch = "repo-setup"
)
.unwrap();
- let hooks = config.hooks(Some("git.company.example/owner/repo"));
+ let hooks = config.hooks(Some(&ProjectId::from("git.company.example/owner/repo")));
let commands: Vec<&str> = hooks
.post_switch
.iter()
@@ -3276,11 +3302,11 @@ hostname = "github.company.example"
.unwrap();
assert_eq!(
- config.forge_platform(Some("work/owner/repo")),
+ config.forge_platform(Some(&ProjectId::from("work/owner/repo"))),
Some("github")
);
assert_eq!(
- config.forge_hostname(Some("work/owner/repo")),
+ config.forge_hostname(Some(&ProjectId::from("work/owner/repo"))),
Some("github.company.example")
);
assert_eq!(config.forge_hostname(None), None);
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 592257686..f3afc7aa0 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -151,7 +151,7 @@ pub use repository::{
};
pub use url::parse_owner_repo;
pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};
-pub(crate) use url::{canonical_url_path_segment, url_path_segments_eq};
+pub(crate) use url::{canonical_url_path_segment, legacy_project_identifier, url_path_segments_eq};
pub use version::{git_version, require_minimum_git};
/// Why branch content is considered integrated into the target branch.
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 05f1563ee..860bc8457 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -143,7 +143,7 @@ use once_cell::sync::OnceCell;
use anyhow::Context;
use dunce::canonicalize;
-use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
+use crate::config::{LoadError, ProjectConfig, ProjectId, ResolvedConfig, UserConfig};
// Import types from parent module
use super::{
@@ -258,7 +258,7 @@ pub(super) struct RepoCache {
/// [`Repository::branch_diff_spec`]. `None` when no default branch resolves.
pub(super) comparison_base: OnceCell<Option<integration::ComparisonBase>>,
/// Project identifier derived from remote URL
- pub(super) project_identifier: OnceCell<String>,
+ pub(super) project_identifier: OnceCell<ProjectId>,
/// Project config (loaded from .config/wt.toml in main worktree)
pub(super) project_config: OnceCell<Option<ProjectConfig>>,
/// CI platform from project config (`forge.platform` / `ci.platform`).
@@ -1308,7 +1308,7 @@ impl Repository {
pub fn config(&self) -> &ResolvedConfig {
self.cache.resolved_config.get_or_init(|| {
let project_id = self.project_identifier().ok();
- self.user_config().resolved(project_id.as_deref())
+ self.user_config().resolved(project_id.as_ref())
})
}
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index f78fe3f7d..6ea8c283d 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -63,8 +63,9 @@
use anyhow::Context;
use super::{GitRemoteUrl, GitRepoInfo, Repository};
+use crate::config::ProjectId;
use crate::git::error::RefType;
-use crate::git::url_path_segments_eq;
+use crate::git::{legacy_project_identifier, url_path_segments_eq};
impl Repository {
/// Get the primary remote name for this repository.
@@ -404,22 +405,26 @@ impl Repository {
/// Uses the git remote URL if available (e.g., "github.com/user/repo"),
/// otherwise falls back to the full canonical path of the repository.
///
- /// This identifier is used to track which commands have been approved
- /// for execution in this project.
+ /// This identifier keys approved commands and `[projects."…"]` settings.
+ /// For a remote whose identifier changed after v0.80.0, it also carries
+ /// the old one, so keys saved under it keep applying.
///
/// Result is cached in the repository's shared cache (same for all clones).
- pub fn project_identifier(&self) -> anyhow::Result<String> {
+ pub fn project_identifier(&self) -> anyhow::Result<ProjectId> {
self.cache
.project_identifier
.get_or_try_init(|| {
// Try to get the remote URL first (cached)
if let Some(url) = self.primary_remote_url() {
- if let Some(parsed) = GitRemoteUrl::parse(url.trim()) {
- return Ok(parsed.project_identifier());
- }
- // Fallback for URLs that don't fit host/owner/repo model
- let url = url.strip_suffix(".git").unwrap_or(url.as_str());
- return Ok(url.to_string());
+ let current = match GitRemoteUrl::parse(url.trim()) {
+ Some(parsed) => parsed.project_identifier(),
+ // Fallback for URLs that don't fit host/owner/repo model
+ None => url.strip_suffix(".git").unwrap_or(url.as_str()).to_string(),
+ };
+ return Ok(ProjectId::with_legacy(
+ current,
+ legacy_project_identifier(&url),
+ ));
}
// Fall back to full canonical path (use worktree base for consistency across all worktrees)
@@ -431,7 +436,7 @@ impl Repository {
.to_str()
.context("Repository path is not valid UTF-8")?;
- Ok(path_str.to_string())
+ Ok(ProjectId::from(path_str))
})
.cloned()
}
diff --git a/src/git/url.rs b/src/git/url.rs
index d17a7627d..936e061b8 100644
--- a/src/git/url.rs
+++ b/src/git/url.rs
@@ -458,6 +458,61 @@ impl GitRemoteUrl {
}
}
+/// The project identifier Worktrunk v0.80.0 and earlier derived from a remote
+/// URL, frozen so `approvals.toml` and `[projects."…"]` keys written under it
+/// keep applying (read by [`ProjectId`](crate::config::ProjectId)).
+///
+/// The release after v0.80.0 moved remote parsing to `gix-url`, which changed
+/// the identifier for three kinds of remote. Saved keys use the old spelling:
+///
+/// - `ssh://git@host:2222/o/r`: the port was dropped (`host/o/r`).
+/// - `[email protected]:o/r`: the host kept its case (`GitHub.com/o/r`).
+/// - `git+ssh://` and `ssh+git://`: these didn't parse, so the identifier was
+/// the raw URL minus `.git`, as for any other unparsed URL.
+///
+/// Returns `None` for an `ssh://` URL with an IPv6 host, which the old parser
+/// truncated at its first `:` (`[2001/o/r`). That identifier was shared by
+/// every IPv6 server with the same leading group, the collision the `gix-url`
+/// parser fixed. The SCP form kept the rest of the address in the path, so
+/// its identifier stayed distinct and still counts.
+pub(crate) fn legacy_project_identifier(url: &str) -> Option<String> {
+ let trimmed = url.trim();
+ let parse = || -> Option<(&str, String, String)> {
+ let (host, path) = if let Some(rest) = trimmed
+ .strip_prefix("https://")
+ .or_else(|| trimmed.strip_prefix("http://"))
+ .or_else(|| trimmed.strip_prefix("git://"))
+ {
+ let (authority, path) = rest.split_once('/')?;
+ (authority_host(authority)?, path)
+ } else if let Some(rest) = trimmed.strip_prefix("ssh://") {
+ let (authority, path) = rest.split_once('/')?;
+ let host = authority_host(authority)?;
+ (host.split(':').next().unwrap_or(host), path)
+ } else if let Some((authority, path)) = trimmed.split_once(':')
+ && !authority.contains('/')
+ {
+ let (user, host) = authority.rsplit_once('@')?;
+ if user.is_empty() {
+ return None;
+ }
+ (host, path)
+ } else {
+ return None;
+ };
+ if host.is_empty() {
+ return None;
+ }
+ let (namespace, repo) = split_namespace_repo(path)?;
+ Some((host, namespace, repo))
+ };
+ match parse() {
+ Some((host, _, _)) if trimmed.starts_with("ssh://") && host.starts_with('[') => None,
+ Some((host, namespace, repo)) => Some(format!("{host}/{namespace}/{repo}")),
+ None => Some(url.strip_suffix(".git").unwrap_or(url).to_string()),
+ }
+}
+
/// Extract owner and repository name from a git remote URL.
pub fn parse_owner_repo(url: &str) -> Option<(String, String)> {
GitRemoteUrl::parse(url).map(|u| (u.owner().to_string(), u.repo().to_string()))
@@ -832,6 +887,40 @@ mod tests {
}
}
+ /// The v0.80.0 identifier, for remotes whose identifier changed and for
+ /// ordinary ones where it didn't. Values are what the v0.80.0 binary's
+ /// `wt config show` printed, except the truncated `ssh://` IPv6 host
+ /// (`[2001/o/r`), which gets none.
+ #[test]
+ fn test_legacy_project_identifier() {
+ let cases = [
+ (
+ "ssh://[email protected]:2222/o/r.git",
+ Some("host.example/o/r"),
+ ),
+ ("[email protected]:o/r.git", Some("GitHub.com/o/r")),
+ ("https://GitHub.com/O/R.git", Some("GitHub.com/O/R")),
+ (
+ "git+ssh://[email protected]/o/r.git",
+ Some("git+ssh://[email protected]/o/r"),
+ ),
+ (
+ "https://host.example:8443/o/r",
+ Some("host.example:8443/o/r"),
+ ),
+ ("[email protected]:o/r.git", Some("github.com/o/r")),
+ ("ssh://git@[2001:db8::1]/o/r.git", None),
+ ("git@[2001:db8::1]:o/r.git", Some("[2001/db8::1]:o/r")),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(
+ legacy_project_identifier(input).as_deref(),
+ expected,
+ "input: {input}"
+ );
+ }
+ }
+
#[test]
fn test_is_github() {
// GitHub.com
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index 070330860..f3aeff99b 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -40,7 +40,7 @@ fn test_approval_saves_to_disk() {
"#);
// Verify approval is in memory
- assert!(approvals.is_command_approved("github.com/test/repo", "test command"));
+ assert!(approvals.is_command_approved(&"github.com/test/repo".into(), "test command"));
}
#[test]
@@ -107,10 +107,10 @@ fn test_multiple_project_approvals() {
.unwrap();
// Verify all approvals exist
- assert!(approvals.is_command_approved("github.com/user1/repo1", "npm install"));
- assert!(approvals.is_command_approved("github.com/user2/repo2", "cargo build"));
- assert!(approvals.is_command_approved("github.com/user1/repo1", "npm test"));
- assert!(!approvals.is_command_approved("github.com/user1/repo1", "cargo build"));
+ assert!(approvals.is_command_approved(&"github.com/user1/repo1".into(), "npm install"));
+ assert!(approvals.is_command_approved(&"github.com/user2/repo2".into(), "cargo build"));
+ assert!(approvals.is_command_approved(&"github.com/user1/repo1".into(), "npm test"));
+ assert!(!approvals.is_command_approved(&"github.com/user1/repo1".into(), "cargo build"));
// Verify file structure
let toml_content = fs::read_to_string(&approvals_path).unwrap();
@@ -426,7 +426,7 @@ fn test_concurrent_revoke_preserves_all_changes() {
// Process A: revokes the project
let mut approvals_a = Approvals::default();
approvals_a
- .revoke_project("github.com/user/repo", &approvals_path)
+ .revoke_project(&"github.com/user/repo".into(), &approvals_path)
.unwrap();
// Read the final state from disk
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index ac9b28dcd..f265180ba 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -99,7 +99,7 @@ fn test_config_show_rejects_invalid_approvals_file(repo: TestRepo) {
fn test_config_show_hides_fully_approved_commands(repo: TestRepo) {
repo.write_project_config("pre-start = \"npm install\"\n");
let project = repo.repo.project_identifier().unwrap();
- let project = toml::Value::String(project).to_string();
+ let project = toml::Value::String(project.to_string()).to_string();
fs::write(
repo.test_approvals_path(),
format!("[projects.{project}]\napproved-commands = [\"npm install\"]\n"),
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index fdb877a67..ad3ae6075 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -359,7 +359,7 @@ fn test_project_identifier_ssh_protocol_with_port() {
}
/// The project identifier of a repository whose `origin` is `url`.
-fn project_identifier_for_remote(url: &str) -> String {
+fn project_identifier_for_remote(url: &str) -> worktrunk::config::ProjectId {
let mut repo = TestRepo::with_initial_commit();
repo.setup_remote("main");
repo.git_command()
@@ -382,10 +382,10 @@ fn test_project_identifier_ipv6_hosts_are_distinct() {
assert_eq!(second, "[2001:db8::2]/owner/repo");
}
-/// The identifier selects both saved approvals and `[projects]` settings: an
-/// entry keyed on the port-less identifier an SSH port remote used to share
-/// does not carry over, while the ordinary SSH and HTTPS forms of one project
-/// still share one entry.
+/// The identifier selects both saved approvals and `[projects]` settings. The
+/// ordinary SSH and HTTPS forms of one project share one entry. A remote on a
+/// non-default SSH port has its own identifier, but entries keyed on the
+/// port-less identifier v0.80.0 gave it still apply, below its own.
#[test]
fn test_project_identifier_selects_approvals_and_project_settings() {
use worktrunk::config::{Approvals, UserConfig};
@@ -395,19 +395,26 @@ fn test_project_identifier_selects_approvals_and_project_settings() {
let default_port =
project_identifier_for_remote("ssh://[email protected]:22/team/project.git");
let https = project_identifier_for_remote("https://gitlab.example.com/team/project.git");
+ assert_eq!(ported, "gitlab.example.com:2222/team/project");
+ assert_eq!(ported.legacy(), Some("gitlab.example.com/team/project"));
assert_eq!(default_port, "gitlab.example.com/team/project");
+ assert_eq!(default_port.legacy(), None);
assert_eq!(https, default_port);
let approvals: Approvals = toml::from_str(
r#"
[projects."gitlab.example.com/team/project"]
approved-commands = ["npm install"]
+
+[projects."gitlab.example.com:2222/team/project"]
+approved-commands = ["npm test"]
"#,
)
.unwrap();
assert!(approvals.is_command_approved(&https, "npm install"));
- assert!(approvals.is_command_approved(&default_port, "npm install"));
- assert!(!approvals.is_command_approved(&ported, "npm install"));
+ assert!(!approvals.is_command_approved(&https, "npm test"));
+ assert!(approvals.is_command_approved(&ported, "npm install"));
+ assert!(approvals.is_command_approved(&ported, "npm test"));
let config: UserConfig = toml::from_str(
r#"
@@ -415,16 +422,69 @@ worktree-path = "global"
[projects."gitlab.example.com/team/project"]
worktree-path = "default-port"
+"#,
+ )
+ .unwrap();
+ assert_eq!(config.worktree_path_for_project(&https), "default-port");
+ assert_eq!(config.worktree_path_for_project(&ported), "default-port");
+
+ let config: UserConfig = toml::from_str(
+ r#"
+[projects."gitlab.example.com/team/project"]
+worktree-path = "default-port"
-[projects."gitlab.example.com:2222/team/project"]
+[projects."gitlab.example.com:2222/*"]
worktree-path = "port-2222"
"#,
)
.unwrap();
- assert_eq!(config.worktree_path_for_project(&https), "default-port");
assert_eq!(config.worktree_path_for_project(&ported), "port-2222");
}
+/// Approvals and `[projects]` settings saved under the identifier v0.80.0 gave
+/// a remote keep applying after its identifier changed: a non-interactive
+/// `wt switch --create` runs the approved hook, in the worktree path the
+/// legacy entry names.
+#[rstest::rstest]
+#[case::ssh_port(
+ "ssh://[email protected]:2222/team/app.git",
+ "gitlab.example.com/team/app"
+)]
+#[case::uppercase_host("[email protected]:team/app.git", "GitHub.com/team/app")]
+#[case::git_plus_ssh(
+ "git+ssh://[email protected]/team/app.git",
+ "git+ssh://[email protected]/team/app"
+)]
+fn test_switch_honors_entries_under_legacy_identifier(#[case] url: &str, #[case] legacy: &str) {
+ let mut repo = TestRepo::with_initial_commit();
+ repo.setup_remote("main");
+ repo.git_command()
+ .args(["remote", "set-url", "origin", url])
+ .run()
+ .unwrap();
+ repo.write_project_config(r#"pre-start = "echo ran > hook-ran.txt""#);
+ repo.commit("Add config");
+ repo.write_test_config(&format!(
+ "[projects.'{legacy}']\nworktree-path = \"{{{{ repo_path }}}}/../legacy.{{{{ branch }}}}\"\n"
+ ));
+ repo.write_test_approvals(&format!(
+ "[projects.'{legacy}']\napproved-commands = [\"echo ran > hook-ran.txt\"]\n"
+ ));
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "--create", "feature"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let worktree = repo.root_path().parent().unwrap().join("legacy.feature");
+ assert!(worktree.join("hook-ran.txt").exists());
+}
+
#[test]
fn test_project_identifier_no_remote_fallback() {
let repo = TestRepo::with_initial_commit();