Skip to content

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

Simplify forge, shell integration, and removal internals (#3662)

Maximilian Roos1eded2794367
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.md
index 04049f3fc..48a784134 100644
--- a/.claude/skills/writing-user-outputs/SKILL.md
+++ b/.claude/skills/writing-user-outputs/SKILL.md
@@ -140,7 +140,7 @@ The split-trust design enforces two trust levels:
All directive env vars are removed from spawned subprocesses by default via
`shell_exec::scrub_directive_env_vars()`. `DirectivePassthrough::inherit_from_env()`
-re-adds only the CD file (and legacy compat file) for trusted contexts.
+re-adds only the CD file for trusted contexts.
## Windows Compatibility (Git Bash / MSYS2)
diff --git a/Cargo.lock b/Cargo.lock
index b3c2d67e2..77ad809af 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4463,7 +4463,6 @@ dependencies = [
"tracing",
"tracing-log",
"tracing-subscriber",
- "tree-sitter",
"tree-sitter-bash",
"tree-sitter-highlight",
"unicode-width 0.2.2",
diff --git a/Cargo.toml b/Cargo.toml
index d993486fd..91d5a71b6 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,9 +67,8 @@ consolidate-commits = true
[package.metadata.cargo-udeps.ignore]
# `which` is used only on Windows (#[cfg(windows)] in src/shell_exec.rs).
-# `petname-macros` is not referenced in code — it's pinned only to constrain
-# the transitive resolution of `petname`'s proc-macro (see the dependency
-# comment above).
+# `petname-macros` is not referenced in code — its exact pin keeps the proc
+# macro version aligned with `petname` (see the dependency comment below).
normal = ["which", "petname-macros"]
[features]
@@ -97,7 +96,7 @@ cli = [
"dep:tracing-log",
"dep:tracing-subscriber",
]
-syntax-highlighting = ["dep:tree-sitter", "dep:tree-sitter-bash", "dep:tree-sitter-highlight"]
+syntax-highlighting = ["dep:tree-sitter-bash", "dep:tree-sitter-highlight"]
# Enable shell/PTY integration tests (requires bash, zsh, fish installed on system)
# Includes: shell wrapper tests, PTY-based approval prompts, TUI select, progressive rendering
shell-integration-tests = []
@@ -202,11 +201,10 @@ synoptic = "2"
terminal_size = "0.4.3"
toml = { version = "1.0", features = ["preserve_order"] }
toml_edit = { version = "0.25", features = ["serde"] }
-# tree-sitter and tree-sitter-highlight should use matching versions.
-# tree-sitter-bash may lag behind (0.25.x works with tree-sitter 0.26.x).
+# tree-sitter-bash may lag behind tree-sitter-highlight (0.25.x works with
+# tree-sitter-highlight 0.26.x).
# These are optional dependencies controlled by the "syntax-highlighting" feature.
# To build without C compilation requirements, use: cargo install worktrunk --no-default-features --features cli
-tree-sitter = { version = "0.26", optional = true }
tree-sitter-bash = { version = "0.25.1", optional = true }
tree-sitter-highlight = { version = "0.26", optional = true }
unicode-width = "0.2.1"
@@ -248,17 +246,9 @@ sha2 = "0.11"
# `src/config/expansion.rs::codename`). We use only the static wordlists,
# not the random-name generator, so `default-rng` and `clap` stay off.
petname = { version = "=3.1.0", default-features = false, features = ["default-words"] }
-# PINNED EXACT to match the `petname` pin above. `petname` 3.0.1 declares a
-# caret range (`petname-macros = "3.0.0"` => `^3.0.0`), but petname-macros is
-# SemVer-incompatible with petname across the line in BOTH directions: macros
-# 3.1.0 emits `petnames!`-macro references (`::petname::lang::…`) that newer
-# petname has, but 3.0.x petname doesn't (E0433); macros 3.0.0 is missing the
-# `english` module that petname 3.0.1 re-exports (`petname_macros::english`),
-# so it too fails to compile (E0432). Only an exact match works. The committed
-# lockfile keeps 3.0.1, but the nightly `minimal-versions` job re-resolves with
-# `cargo update` (pulling 3.0.0) and a plain `cargo update` would pull 3.1.0 —
-# both broken. This direct `=3.0.1` requirement unifies the shared resolution
-# to 3.0.1. Bump in lockstep whenever `petname` itself is bumped.
+# PINNED EXACT to match `petname`: its caret dependency otherwise permits a
+# different proc-macro version, but the generated code and runtime re-exports
+# require an exact match. Keep both pins in lockstep.
petname-macros = "=3.1.0"
tempfile = "3.27"
diff --git a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
index 9e1e51031..d19dfdadb 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md
@@ -53,6 +53,15 @@ session.
When shell integration isn't working, `wt switch` shows warnings explaining why.
+### "shell wrapper is out of date"
+
+**Meaning**: The active shell still has a pre-split wrapper loaded. Current
+versions no longer write shell commands to that wrapper's single directive
+file, because it mixes trusted directory paths with arbitrary shell.
+
+**Fix**: Run `wt config shell install`, then restart the shell (or reload its
+config) to activate the current split-file wrapper.
+
### "shell integration not installed"
**Meaning**: The current shell's config file doesn't have the
@@ -150,6 +159,15 @@ wt() {
}
```
+### Directive trust boundary
+
+The CD file contains only a raw path, so Worktrunk can pass it through to
+alias and hook subprocesses. The EXEC file contains shell code that the parent
+wrapper sources, so Worktrunk removes it from project-defined aliases and
+hooks. User-config aliases are the intentional exception: because their
+commands are authored by the user, they retain the EXEC file and can run a
+nested `wt switch --execute`.
+
## Debugging Checklist
### 1. Check if wrapper is installed
diff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.md
index 9e1e51031..d19dfdadb 100644
--- a/skills/worktrunk/reference/shell-integration.md
+++ b/skills/worktrunk/reference/shell-integration.md
@@ -53,6 +53,15 @@ session.
When shell integration isn't working, `wt switch` shows warnings explaining why.
+### "shell wrapper is out of date"
+
+**Meaning**: The active shell still has a pre-split wrapper loaded. Current
+versions no longer write shell commands to that wrapper's single directive
+file, because it mixes trusted directory paths with arbitrary shell.
+
+**Fix**: Run `wt config shell install`, then restart the shell (or reload its
+config) to activate the current split-file wrapper.
+
### "shell integration not installed"
**Meaning**: The current shell's config file doesn't have the
@@ -150,6 +159,15 @@ wt() {
}
```
+### Directive trust boundary
+
+The CD file contains only a raw path, so Worktrunk can pass it through to
+alias and hook subprocesses. The EXEC file contains shell code that the parent
+wrapper sources, so Worktrunk removes it from project-defined aliases and
+hooks. User-config aliases are the intentional exception: because their
+commands are authored by the user, they retain the EXEC file and can run a
+nested `wt switch --execute`.
+
## Debugging Checklist
### 1. Check if wrapper is installed
diff --git a/src/commands/config/show.rs b/src/commands/config/show.rs
index 79600c0b4..a35f7911e 100644
--- a/src/commands/config/show.rs
+++ b/src/commands/config/show.rs
@@ -13,9 +13,11 @@ use worktrunk::config::{
ProjectConfig, UserConfig, default_system_config_path, require_config_path, system_config_path,
};
use worktrunk::git::remote_ref::azure::azure_devops_extension_installed;
-use worktrunk::git::{CiPlatform, ErrorExt, Repository};
+use worktrunk::git::{ErrorExt, ForgeKind, Repository};
use worktrunk::path::format_path_for_display;
-use worktrunk::shell::{FileDetectionResult, Shell, ZSH_PROBE_FLAGS, scan_for_detection_details};
+use worktrunk::shell::{
+ FileDetectionResult, Shell, ZshStartupScope, probe_zsh_compdef, scan_for_detection_details,
+};
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
FormattedMessage, error_message, format_bash_with_gutter, format_heading, format_toml,
@@ -24,6 +26,7 @@ use worktrunk::styling::{
use crate::cli::{SwitchFormat, version_str};
use crate::commands::configure_shell::{ConfigAction, ConfigureResult, scan_shell_configs};
+use crate::commands::legacy_forge_alias_diagnostic;
use crate::commands::list::ci_status::CiToolsStatus;
use crate::help_pager::show_help_in_pager;
use crate::llm::test_commit_generation;
@@ -260,75 +263,6 @@ pub(super) fn is_statusline_configured() -> bool {
})
}
-/// Get the git version string (e.g., "2.47.1")
-fn git_version() -> Option<String> {
- let output = Cmd::new("git").arg("--version").run().ok()?;
- if !output.status.success() {
- return None;
- }
-
- // Parse "git version 2.47.1" -> "2.47.1"
- let stdout = String::from_utf8_lossy(&output.stdout);
- stdout
- .trim()
- .strip_prefix("git version ")
- .map(|s| s.to_string())
-}
-
-/// Check if zsh has compinit enabled by spawning an interactive shell
-///
-/// Returns true if compinit is NOT enabled (i.e., user needs to add it).
-/// Returns false if compinit is enabled or we can't determine (fail-safe: don't warn).
-///
-// This remains separate from `shell::detect_zsh_compinit`: config show skips
-// global rcs, reads the exit status, and uses `Cmd`; shell setup sources global
-// rcs, reads marker output, and manages a raw `Command`.
-fn check_zsh_compinit_missing() -> bool {
- // Allow tests to bypass this check since zsh subprocess behavior varies across CI envs
- if std::env::var("WORKTRUNK_TEST_COMPINIT_CONFIGURED").is_ok() {
- return false; // Assume compinit is configured
- }
-
- // Force compinit to be missing (for tests that expect the warning)
- if std::env::var("WORKTRUNK_TEST_COMPINIT_MISSING").is_ok() {
- return true; // Force warning to appear
- }
-
- // Probe zsh to check if compdef function exists (indicates compinit has run)
- // Use --no-globalrcs to skip system files (like /etc/zshrc on macOS which enables compinit)
- // This ensures we're checking the USER's configuration, not system defaults
- // Suppress stderr to avoid noise like "can't change option: zle"
- // The (( ... )) arithmetic returns exit 0 if true (compdef exists), 1 if false
- // Suppress zsh's "insecure directories" warning from compinit.
- // See detailed rationale in shell::detect_zsh_compinit().
- //
- // Bound the probe with a timeout that kills the child on expiry — the same
- // hardening detect_zsh_compinit() relies on. An interactive `zsh -ic` whose
- // startup prompts on /dev/tty (compinit's insecure-directories prompt
- // bypasses both the stdin=null default and the stderr suppression above)
- // would otherwise hang `wt config show` indefinitely. On timeout run()
- // returns Err, so the `else` below declines to warn rather than misreport.
- // `+m` disables job control so this interactive probe doesn't grab wt's
- // controlling terminal. An interactive zsh with job control on `tcsetpgrp`s
- // to claim the terminal foreground; if the 2s timeout kills it before it
- // restores that, wt is left in a background process group and the pager
- // spawned moments later (config show always pages) raises SIGTTOU,
- // suspending the command (`suspended (tty output)`). See issue #3322.
- let Ok(output) = Cmd::new("zsh")
- .arg("--no-globalrcs")
- .args(ZSH_PROBE_FLAGS)
- .arg("(( $+functions[compdef] ))")
- .env("ZSH_DISABLE_COMPFIX", "true")
- .timeout(std::time::Duration::from_secs(2))
- .run()
- else {
- return false; // Can't determine, don't warn
- };
-
- // compdef NOT found = need to warn
- !output.status.success()
-}
-
// ==================== Render Functions ====================
/// Render CLAUDE CODE section (plugin and statusline status).
@@ -487,7 +421,7 @@ fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {
"{}",
info_message(cformat!("{cmd}: <bold>{version}</>"))
)?;
- if let Some(git_version) = git_version() {
+ if let Ok(git_version) = crate::diagnostic::git_version() {
writeln!(
out,
"{}",
@@ -519,7 +453,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
// Check the CI tool for this repo's platform (project config, else remote URL).
let repo = Repository::current()?;
match repo.ci_platform(None) {
- Some(CiPlatform::GitHub) => {
+ Some(ForgeKind::GitHub) => {
let ci_tools = CiToolsStatus::detect(None);
render_ci_tool_status(
out,
@@ -529,7 +463,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
ci_tools.gh_authenticated,
)?;
}
- Some(CiPlatform::GitLab) => {
+ Some(ForgeKind::GitLab) => {
let ci_tools = CiToolsStatus::detect(None);
render_ci_tool_status(
out,
@@ -539,7 +473,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
ci_tools.glab_authenticated,
)?;
}
- Some(CiPlatform::Gitea) => {
+ Some(ForgeKind::Gitea) => {
let ci_tools = CiToolsStatus::detect(None);
render_ci_tool_status(
out,
@@ -549,7 +483,7 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
ci_tools.tea_authenticated,
)?;
}
- Some(CiPlatform::AzureDevOps) => {
+ Some(ForgeKind::AzureDevOps) => {
let ci_tools = CiToolsStatus::detect(None);
render_ci_tool_status(
out,
@@ -572,11 +506,21 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {
}
}
None => {
- writeln!(
- out,
- "{}",
- hint_message("CI status requires GitHub, GitLab, Gitea, or Azure DevOps remote")
- )?;
+ if let Some(alias) = repo.legacy_forge_alias() {
+ writeln!(
+ out,
+ "{}",
+ warning_message(legacy_forge_alias_diagnostic(&alias))
+ )?;
+ } else {
+ writeln!(
+ out,
+ "{}",
+ hint_message(
+ "CI status requires GitHub, GitLab, Gitea, or Azure DevOps remote"
+ )
+ )?;
+ }
}
}
@@ -988,7 +932,7 @@ fn render_fish_legacy_migration(
/// Zsh-only: warn when compinit isn't enabled, since the integration
/// installs completions but they won't load without compinit.
fn render_zsh_compinit_warning(out: &mut String) -> anyhow::Result<()> {
- if !check_zsh_compinit_missing() {
+ if probe_zsh_compdef(ZshStartupScope::UserOnly) != Some(false) {
return Ok(());
}
writeln!(
@@ -1630,17 +1574,6 @@ fn is_newer_version(latest: &str, current: &str) -> bool {
mod tests {
use super::*;
- #[test]
- fn test_get_git_version_returns_version() {
- // In a normal environment with git installed, should return a version
- let version = git_version();
- assert!(version.is_some());
- let version = version.unwrap();
- // Version should look like a semver (e.g., "2.47.1")
- assert!(version.chars().next().unwrap().is_ascii_digit());
- assert!(version.contains('.'));
- }
-
#[test]
fn test_is_newer_version() {
// Newer versions
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index bde49546d..b5b28bf9c 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -451,10 +451,12 @@ pub fn handle_configure_shell(
&& (shell_filter == Some(Shell::Zsh)
|| (shell_filter.is_none() && shell::current_shell() == Some(Shell::Zsh)));
- // Probe user's zsh to check if compinit is enabled.
+ // Probe a normal interactive zsh (global + user startup files) to check if
+ // compinit is enabled in the session the freshly installed wrapper enters.
// Only flag if we positively detect it's missing (Some(false)).
// If detection fails (None), stay silent - we can't be sure.
- let zsh_needs_compinit = should_check_compinit && shell::detect_zsh_compinit() == Some(false);
+ let zsh_needs_compinit = should_check_compinit
+ && shell::probe_zsh_compdef(shell::ZshStartupScope::GlobalAndUser) == Some(false);
// Clean up legacy fish conf.d file if we just installed to functions/
// (issue #566), plus any nushell wrapper stranded at a legacy autoload
diff --git a/src/commands/custom.rs b/src/commands/custom.rs
index 0c6b02675..be7f5024d 100644
--- a/src/commands/custom.rs
+++ b/src/commands/custom.rs
@@ -30,6 +30,7 @@ use std::process::Command;
use anyhow::{Context, Result};
use worktrunk::git::WorktrunkError;
+use worktrunk::shell_exec::RETIRED_DIRECTIVE_FILE_ENV_VAR;
use worktrunk::trace::CommandTrace;
use crate::cli::build_command;
@@ -131,6 +132,9 @@ fn unrecognized_subcommand_error(name: &str) -> clap::Error {
fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Result<()> {
let mut cmd = Command::new(path);
cmd.args(args);
+ // Explicitly invoked extensions remain trusted with split CD/EXEC; only
+ // the retired sourceable single-file capability is forbidden.
+ cmd.env_remove(RETIRED_DIRECTIVE_FILE_ENV_VAR);
if let Some(dir) = working_dir {
cmd.current_dir(dir);
}
diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rs
index 49286f1e7..17829c997 100644
--- a/src/commands/list/ci_status/platform.rs
+++ b/src/commands/list/ci_status/platform.rs
@@ -1,12 +1,12 @@
//! Forge dispatch for CI status detection.
//!
-//! Given a [`CiPlatform`] (resolved by [`Repository::ci_platform`]), routes to
+//! Given a [`ForgeKind`] (resolved by [`Repository::ci_platform`]), routes to
//! the GitHub (`gh`), GitLab (`glab`), Gitea (`tea`), or Azure DevOps (`az`)
//! backend and checks whether that CLI is installed.
use std::sync::OnceLock;
-use worktrunk::git::{CiPlatform, Repository};
+use worktrunk::git::{ForgeKind, Repository};
use super::{CiBranchName, PrStatus, azure, gitea, github, gitlab, tool_available};
@@ -34,45 +34,45 @@ impl CiToolsAvailable {
}
/// Whether the CLI tool for this platform is installed (cached).
-fn is_tool_available(platform: CiPlatform) -> bool {
+fn is_tool_available(platform: ForgeKind) -> bool {
match platform {
- CiPlatform::GitHub => CiToolsAvailable::get().gh,
- CiPlatform::GitLab => CiToolsAvailable::get().glab,
- CiPlatform::Gitea => CiToolsAvailable::get().tea,
- CiPlatform::AzureDevOps => CiToolsAvailable::get().az,
+ ForgeKind::GitHub => CiToolsAvailable::get().gh,
+ ForgeKind::GitLab => CiToolsAvailable::get().glab,
+ ForgeKind::Gitea => CiToolsAvailable::get().tea,
+ ForgeKind::AzureDevOps => CiToolsAvailable::get().az,
}
}
/// Detect CI status from a PR/MR.
fn detect_pr_mr(
- platform: CiPlatform,
+ platform: ForgeKind,
repo: &Repository,
branch: &CiBranchName,
local_head: &str,
) -> Option<PrStatus> {
match platform {
- CiPlatform::GitHub => github::detect_github(repo, branch, local_head),
- CiPlatform::GitLab => gitlab::detect_gitlab(repo, branch, local_head),
- CiPlatform::Gitea => gitea::detect_gitea_pr(repo, branch, local_head),
- CiPlatform::AzureDevOps => azure::detect_azure_pr(repo, branch, local_head),
+ ForgeKind::GitHub => github::detect_github(repo, branch, local_head),
+ ForgeKind::GitLab => gitlab::detect_gitlab(repo, branch, local_head),
+ ForgeKind::Gitea => gitea::detect_gitea_pr(repo, branch, local_head),
+ ForgeKind::AzureDevOps => azure::detect_azure_pr(repo, branch, local_head),
}
}
/// Detect CI status from a branch workflow/pipeline (fallback when no PR/MR).
fn detect_branch(
- platform: CiPlatform,
+ platform: ForgeKind,
repo: &Repository,
branch: &CiBranchName,
local_head: &str,
) -> Option<PrStatus> {
match platform {
- CiPlatform::GitHub => github::detect_github_commit_checks(repo, branch, local_head),
+ ForgeKind::GitHub => github::detect_github_commit_checks(repo, branch, local_head),
// GitLab pipelines use the bare branch name (not "origin/feature").
- CiPlatform::GitLab => gitlab::detect_gitlab_pipeline(repo, &branch.name, local_head),
+ ForgeKind::GitLab => gitlab::detect_gitlab_pipeline(repo, &branch.name, local_head),
// Gitea queries the combined commit status by SHA, but owner/repo come
// from the branch's own remote (so remote-only rows hit the right repo).
- CiPlatform::Gitea => gitea::detect_gitea_commit_status(repo, branch, local_head),
- CiPlatform::AzureDevOps => azure::detect_azure_pipeline(repo, branch, local_head),
+ ForgeKind::Gitea => gitea::detect_gitea_commit_status(repo, branch, local_head),
+ ForgeKind::AzureDevOps => azure::detect_azure_pipeline(repo, branch, local_head),
}
}
@@ -80,7 +80,7 @@ fn detect_branch(
///
/// Returns `None` if the CLI tool isn't installed or no CI status is found.
pub(super) fn detect_ci(
- platform: CiPlatform,
+ platform: ForgeKind,
repo: &Repository,
branch: &CiBranchName,
local_head: &str,
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 992e949ea..d5cda61cf 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -2018,6 +2018,21 @@ pub fn collect(
return Ok(None);
}
+ // The old substring classifier treated branded SSH aliases such as
+ // `github-personal` as forges. Keep provider dispatch on the safer exact
+ // boundary, but explain the migration once when this collection actually
+ // requested CI. Do this after final table rendering so resolving the
+ // effective URL cannot add a git subprocess to the skeleton's critical
+ // path. Picker collections route through the warning stash; the statusline
+ // uses `populate_item`, not this path, and remains silent.
+ if collected.ci
+ && let Some(alias) = repo.legacy_forge_alias()
+ {
+ emit_warning(
+ warning_message(crate::commands::legacy_forge_alias_diagnostic(&alias)).to_string(),
+ );
+ }
+
// Status symbols are now computed during data collection (both modes), no fallback needed
// Display collection errors/warnings (after table rendering)
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index e369e55e3..4d065b280 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -71,6 +71,7 @@ pub(crate) use worktree::{
pub(crate) use worktrunk::shell::Shell;
use color_print::cformat;
+use worktrunk::git::LegacyForgeAlias;
use worktrunk::styling::{eprintln, format_with_gutter};
pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
@@ -81,6 +82,16 @@ pub(crate) fn flag_pair(positive: bool, negative: bool) -> Option<bool> {
}
}
+/// Actionable compatibility diagnostic for branded SSH aliases that no longer
+/// cross the exact-label forge-classification boundary.
+pub(crate) fn legacy_forge_alias_diagnostic(alias: &LegacyForgeAlias) -> String {
+ let platform = alias.platform().to_string();
+ let host = alias.host();
+ cformat!(
+ "SSH host alias <bold>{host}</> is not auto-detected as a forge; enable CI status and <bold>wt switch --prs</> with <bold>forge.platform = \"{platform}\"</> @ <bold>.config/wt.toml</>"
+ )
+}
+
/// Format command execution label with optional command name.
///
/// Examples:
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 9441200fd..e7570f446 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -162,30 +162,23 @@ enum PickerAction {
Create,
}
-/// The alt-x removal target parsed back out of a row's `output()` token.
+/// Parse the canonical removal target from a row's `output()` token.
///
/// A worktree-backed row's token is `worktree-path:<path>` (paths are
/// unique — detached worktrees would otherwise collide on the shared
/// `(detached)` label); a branch-only row's token is the bare branch name.
-enum PickerRemovalTarget {
- WorktreePath(PathBuf),
- Branch(String),
-}
-
-impl PickerRemovalTarget {
- fn from_signal(signal: &str) -> Option<Self> {
- let signal = signal.trim();
- if signal.is_empty() {
+fn parse_removal_target(signal: &str) -> Option<RemoveTarget> {
+ let signal = signal.trim();
+ if signal.is_empty() {
+ return None;
+ }
+ if let Some(path) = signal.strip_prefix(WORKTREE_OUTPUT_PREFIX) {
+ if path.is_empty() {
return None;
}
- if let Some(path) = signal.strip_prefix(WORKTREE_OUTPUT_PREFIX) {
- if path.is_empty() {
- return None;
- }
- return Some(Self::WorktreePath(PathBuf::from(path)));
- }
- Some(Self::Branch(signal.to_string()))
+ return Some(RemoveTarget::WorktreePath(PathBuf::from(path)));
}
+ Some(RemoveTarget::BranchOnly(signal.to_string()))
}
/// Resolve the switch identifier for a selected picker row, decoded from its
@@ -202,8 +195,8 @@ impl PickerRemovalTarget {
/// downcast fail when the item originates on the reader thread.
fn picker_item_identifier(item: &dyn SkimItem) -> String {
let output = item.output().to_string();
- match PickerRemovalTarget::from_signal(&output) {
- Some(PickerRemovalTarget::WorktreePath(path)) => path.to_string_lossy().into_owned(),
+ match parse_removal_target(&output) {
+ Some(RemoveTarget::WorktreePath(path)) => path.to_string_lossy().into_owned(),
_ => output,
}
}
@@ -318,31 +311,21 @@ impl AltXRemover {
/// `target` carries the exact worktree path or branch name decoded from
/// the row's `output()` token — no `git worktree list` lookup, so a
/// detached row can't be confused with another detached row.
- fn prepare_removal(
- &self,
- target: &PickerRemovalTarget,
- ) -> anyhow::Result<(Repository, RemovalPlan)> {
+ fn prepare_removal(&self, target: RemoveTarget) -> anyhow::Result<(Repository, RemovalPlan)> {
let repo = Repository::at(self.repo.discovery_path())?;
// Validate removal before touching the list. prepare_worktree_removal
// runs a few git commands (~15-20ms) — acceptable on skim's event loop.
// Only remove the item and spawn background deletion if this succeeds.
- let caller_path = repo.current_worktree().root().ok();
-
- let result = {
- let remove_target = match target {
- PickerRemovalTarget::WorktreePath(path) => RemoveTarget::Path(path),
- PickerRemovalTarget::Branch(branch) => RemoveTarget::Branch(branch),
- };
- repo.prepare_worktree_removal(
- remove_target,
- BranchDeletionMode::SafeDelete,
- false,
- caller_path,
- None,
- None,
- )?
- };
+ let caller_path = repo.current_worktree().root()?;
+ let result = repo.prepare_worktree_removal(
+ target,
+ BranchDeletionMode::SafeDelete,
+ false,
+ &caller_path,
+ None,
+ None,
+ )?;
Ok((repo, result))
}
@@ -370,8 +353,8 @@ impl AltXRemover {
/// worktree is physically gone (rendering or spawning a
/// `post-remove`/`post-switch` hook can error during the announcer flush, which
/// runs after the dir is renamed into `.git/wt/trash/`), and a `BranchOnly`
- /// delete that raced from integrated to unmerged returns `Ok` with the branch
- /// surviving. Instead it
+ /// delete that became unmerged or gained a checkout after planning returns
+ /// `Ok` with the branch surviving. Instead it
/// observes whether the target still exists ([`removal_target_still_present`])
/// and restores the row via [`restore_failed_removal`] only when it does, so
/// the list never shows a removal that didn't happen. The `Result` is for
@@ -419,10 +402,12 @@ impl AltXRemover {
if let Err(e) =
execute_branch_deletion(repo, branch_name, target, deletion_mode.is_force())
{
- // A safe-delete refusal is `Ok(NotDeleted)`, not an error;
- // this is a genuine `git branch -D` failure. The row is
- // restored anyway because the branch still exists (see
- // `removal_target_still_present`) — surface the cause.
+ // Safe-delete retention (`NotDeleted`,
+ // `RetainedCheckedOut`, or `RetainedRaced`) is `Ok`, not
+ // an error; this is a genuine deletion-command failure.
+ // The row is restored anyway because the branch still
+ // exists (see `removal_target_still_present`) — surface
+ // the cause.
tracing::warn!(branch = %branch_name, error = %e, "picker: failed to delete branch '{branch_name}': {e:#}");
}
}
@@ -690,10 +675,10 @@ impl AltXRemover {
/// `prepare_removal` git work is the same cost the old `reload`-time dispatch
/// paid; the actual worktree/branch deletion is deferred to a background thread.
fn apply(&self, selected_output: String) -> RemovalEffect {
- let Some(removal_target) = PickerRemovalTarget::from_signal(&selected_output) else {
+ let Some(removal_target) = parse_removal_target(&selected_output) else {
return RemovalEffect::Kept;
};
- match self.prepare_removal(&removal_target) {
+ match self.prepare_removal(removal_target) {
Ok((planning_repo, result)) => {
if removal_targets_current_worktree(&result) {
self.keep_current_worktree_row();
@@ -1115,12 +1100,13 @@ fn worktree_removal_keeps_branch(repo: &Repository, result: &RemovalPlan) -> Opt
/// A `Result` is the wrong signal in two directions: a `Worktree` removal
/// can return `Err` *after* the worktree is already trashed (rendering or
/// spawning a `post-remove`/`post-switch` hook fails during the announcer flush),
-/// and a `BranchOnly` safe-delete that raced from integrated to unmerged returns
-/// `Ok` while leaving the branch in place. (The *predictable* unmerged case never
-/// reaches here — [`removal_will_remove_target`] keeps that row without dropping
-/// it.) Observing the target directly handles both: the worktree dir is gone once
-/// removed (renamed into `.git/wt/trash/`), and the branch ref is gone once
-/// deleted. The check runs on the background thread, off skim's event loop.
+/// and a `BranchOnly` safe-delete that became unmerged or gained a checkout after
+/// planning returns `Ok` while leaving the branch in place. (The *predictable*
+/// unmerged case never reaches here — [`removal_will_remove_target`] keeps that
+/// row without dropping it.) Observing the target directly handles both: the
+/// worktree dir is gone once removed (renamed into `.git/wt/trash/`), and the
+/// branch ref is gone once deleted. The check runs on the background thread, off
+/// skim's event loop.
///
/// `worktree_path.exists()` is the right signal here because the picker only ever
/// removes *non-current* worktrees — [`removal_targets_current_worktree`] keeps the
@@ -1188,9 +1174,10 @@ struct DroppedRow {
/// `invoke` drops a row optimistically once alt-x's validation passes, then
/// removes the target on a background thread. When the target unexpectedly
/// survives (data safety: a clean-check race against `ensure_clean`, a locked
-/// directory, a failing `pre-remove` hook, or a `BranchOnly` delete that raced
-/// from integrated to unmerged — see [`removal_target_still_present`]; the
-/// predictably-kept unmerged branch is filtered earlier by
+/// directory, a failing `pre-remove` hook, or a `BranchOnly` delete that became
+/// unmerged or gained a checkout after planning — see
+/// [`removal_target_still_present`]; the predictably-kept unmerged branch is
+/// filtered earlier by
/// [`removal_will_remove_target`]), the row must reappear. This re-inserts it into
/// `shared_items` at its original slot, flashes the `kept` reason in the header and
/// stashes the same line (drained to stderr once skim releases the terminal; the
@@ -2530,10 +2517,11 @@ fn switch_pipeline_repo(repo: &Repository, is_recovered: bool) -> anyhow::Result
pub mod tests {
use super::items::{LocalCheckout, LocalContent, PickerRow, worktree_output_token};
use super::{
- AltXRemover, PickerAction, PickerRemovalTarget, RemovalEffect, drain_stashed_warnings,
- install_preview_tab_keybindings, install_shortcut_keybindings, picker_item_identifier,
- resolve_identifier, resolve_shortcut_branch, resolve_shortcut_url,
- summary_command_and_hint, switch_pipeline_repo,
+ AltXRemover, PickerAction, RemovalEffect, RemoveTarget, drain_stashed_warnings,
+ install_preview_tab_keybindings, install_shortcut_keybindings, parse_removal_target,
+ picker_item_identifier, removal_target_still_present, resolve_identifier,
+ resolve_shortcut_branch, resolve_shortcut_url, summary_command_and_hint,
+ switch_pipeline_repo,
};
use crate::commands::list::model::{BranchScope, ItemKind, ListItem, WorktreeData};
use crate::commands::worktree::RemovalPlan;
@@ -2792,22 +2780,22 @@ pub mod tests {
);
}
- /// `from_signal` rejects tokens that carry no usable target: a blank or
+ /// The parser rejects tokens that carry no usable target: a blank or
/// whitespace-only signal, and a bare `worktree-path:` prefix with no path
/// after it. A non-empty branch token and a prefixed path both parse.
#[test]
- fn test_picker_removal_target_from_signal() {
- assert!(PickerRemovalTarget::from_signal("").is_none());
- assert!(PickerRemovalTarget::from_signal(" ").is_none());
- assert!(PickerRemovalTarget::from_signal("worktree-path:").is_none());
+ fn test_parse_removal_target() {
+ assert!(parse_removal_target("").is_none());
+ assert!(parse_removal_target(" ").is_none());
+ assert!(parse_removal_target("worktree-path:").is_none());
assert!(matches!(
- PickerRemovalTarget::from_signal("feature/foo"),
- Some(PickerRemovalTarget::Branch(branch)) if branch == "feature/foo"
+ parse_removal_target("feature/foo"),
+ Some(RemoveTarget::BranchOnly(branch)) if branch == "feature/foo"
));
assert!(matches!(
- PickerRemovalTarget::from_signal("worktree-path:/tmp/wt"),
- Some(PickerRemovalTarget::WorktreePath(path)) if path == std::path::Path::new("/tmp/wt")
+ parse_removal_target("worktree-path:/tmp/wt"),
+ Some(RemoveTarget::WorktreePath(path)) if path == std::path::Path::new("/tmp/wt")
));
}
@@ -2964,9 +2952,9 @@ pub mod tests {
assert!(!wt_path.exists(), "detached worktree should be removed");
}
- /// A branch-only row's signal carries the bare branch name, which
- /// `PickerRemovalTarget::from_signal` decodes to `Branch`; `prepare_removal`
- /// then resolves it to the branch-only disposition.
+ /// A branch-only row's signal carries the bare branch name, which the
+ /// parser decodes directly to the canonical `BranchOnly` target;
+ /// `prepare_removal` then resolves it to the branch-only disposition.
#[test]
fn test_prepare_removal_resolves_branch_only_item() {
let test = worktrunk::testing::TestRepo::with_initial_commit();
@@ -2978,34 +2966,41 @@ pub mod tests {
let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo);
- let target = PickerRemovalTarget::from_signal("branch-only-feature").unwrap();
- let (_planning_repo, result) = remover.prepare_removal(&target).unwrap();
+ let target = parse_removal_target("branch-only-feature").unwrap();
+ let (_planning_repo, result) = remover.prepare_removal(target).unwrap();
assert!(
matches!(&result, RemovalPlan::BranchOnly { branch_name, .. } if branch_name == "branch-only-feature"),
"a branch with no worktree should resolve to BranchOnly"
);
}
- /// `do_removal` on a branch-only plan deletes the branch through
- /// `execute_branch_deletion` — the same fresh-refs CAS path every planned
- /// deletion takes — with no worktree involved.
+ /// A branch-only row can gain a checkout after `prepare_removal` returns.
+ /// `do_removal` must retain it, and the picker's direct target observation
+ /// must see the surviving ref so the optimistically dropped row is restored
+ /// rather than reported as gone.
#[test]
- fn test_do_removal_deletes_branch_only_plan() {
+ fn test_do_removal_restores_branch_only_row_that_gained_checkout() {
let test = worktrunk::testing::TestRepo::with_initial_commit();
let repo = worktrunk::git::Repository::at(test.path()).unwrap();
-
- // Integrated (same commit as main), no worktree → safe to delete.
repo.run_command(&["branch", "row-branch"]).unwrap();
let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo.clone());
- let target = PickerRemovalTarget::from_signal("row-branch").unwrap();
- let (planning_repo, plan) = remover.prepare_removal(&target).unwrap();
+ let target = parse_removal_target("row-branch").unwrap();
+ let (planning_repo, plan) = remover.prepare_removal(target).unwrap();
+
+ let checkout = test.home_path().join("repo.row-branch-raced-checkout");
+ test.run_git(&["worktree", "add", checkout.to_str().unwrap(), "row-branch"]);
AltXRemover::do_removal(&planning_repo, &plan, &Approvals::default()).unwrap();
assert!(
- repo.run_command(&["rev-parse", "--verify", "refs/heads/row-branch"])
- .is_err(),
- "an integrated branch-only row should be deleted"
+ removal_target_still_present(&planning_repo, &plan),
+ "the picker must observe the retained branch and restore its row"
+ );
+ assert!(
+ repo.worktree_at(&checkout)
+ .run_command(&["rev-parse", "--verify", "HEAD"])
+ .is_ok(),
+ "the checkout added after planning must remain resolvable"
);
}
@@ -3021,9 +3016,9 @@ pub mod tests {
let remover = test_remover(Arc::new(Mutex::new(Vec::new())), repo);
- let target = PickerRemovalTarget::from_signal("feature").unwrap();
+ let target = parse_removal_target("feature").unwrap();
let err = remover
- .prepare_removal(&target)
+ .prepare_removal(target)
.map(|_| ())
.expect_err("a branch with a worktree should not delete as branch-only");
let rendered = err.to_string();
@@ -3049,9 +3044,9 @@ pub mod tests {
// `RemovalPlan` isn't `Debug`; drop the Ok payload so `unwrap_err`
// (which needs `T: Debug`) can report a failure cleanly.
- let target = PickerRemovalTarget::from_signal("no-such-branch").unwrap();
+ let target = parse_removal_target("no-such-branch").unwrap();
let err = remover
- .prepare_removal(&target)
+ .prepare_removal(target)
.map(|_| ())
.expect_err("unknown removal target should fail validation");
assert!(
@@ -4389,8 +4384,8 @@ pub mod tests {
let items = Arc::new(Mutex::new(vec![Arc::clone(&item)]));
let remover = test_remover(Arc::clone(&items), repo.clone());
- let target = PickerRemovalTarget::from_signal(&token).expect("worktree token parses");
- let (planning_repo, plan) = remover.prepare_removal(&target).unwrap();
+ let target = parse_removal_target(&token).expect("worktree token parses");
+ let (planning_repo, plan) = remover.prepare_removal(target).unwrap();
let RemovalPlan::Worktree {
worktree_path,
changed_directory,
diff --git a/src/commands/picker/progressive_handler.rs b/src/commands/picker/progressive_handler.rs
index 93331aeac..69724ee9a 100644
--- a/src/commands/picker/progressive_handler.rs
+++ b/src/commands/picker/progressive_handler.rs
@@ -639,7 +639,10 @@ impl PickerProgressHandler for PickerHandler {
}
fn stash_warning(&self, line: String) {
- self.stashed_warnings.lock().unwrap().push(line);
+ let mut warnings = self.stashed_warnings.lock().unwrap();
+ if !warnings.contains(&line) {
+ warnings.push(line);
+ }
}
fn provide_layout(&self, layout: &crate::commands::list::layout::LayoutConfig) {
@@ -1559,13 +1562,14 @@ mod tests {
assert!(!matches("!7", gitlab), "!7 inverse-excludes its own MR row");
}
- /// `stash_warning` accumulates lines in arrival order so the picker can
- /// drain them in one shot after skim releases the terminal.
+ /// `stash_warning` accumulates distinct lines in arrival order so refreshes
+ /// and concurrent producers cannot repeat a diagnostic after skim exits.
#[test]
fn stash_warning_preserves_order() {
let (handler, _test, _rx) = make_handler();
handler.stash_warning("first".into());
handler.stash_warning("second".into());
+ handler.stash_warning("first".into());
handler.stash_warning("third".into());
let stash = handler.stashed_warnings.lock().unwrap();
assert_eq!(stash.as_slice(), &["first", "second", "third"]);
diff --git a/src/commands/picker/prs.rs b/src/commands/picker/prs.rs
index 63101447d..b0ed48aea 100644
--- a/src/commands/picker/prs.rs
+++ b/src/commands/picker/prs.rs
@@ -47,9 +47,10 @@ use color_print::cformat;
use serde::Deserialize;
use skim::prelude::*;
use unicode_width::UnicodeWidthStr;
-use worktrunk::git::{CiPlatform, Repository};
+use worktrunk::git::{ForgeKind, RefType, Repository};
use worktrunk::styling::{HINT_SYMBOL, INFO_SYMBOL, StyledLine, WARNING_SYMBOL, warning_message};
+use super::super::legacy_forge_alias_diagnostic;
use super::super::list::ci_status::{
CiSource, CiStatus, GitHubComment, GitHubPrInfo, PrRef, PrStatus, ReviewState,
non_interactive_cmd, tool_available,
@@ -125,25 +126,8 @@ const MAX_PRS: u8 = 50;
/// 2-cell gutter column.
const PR_GUTTER_SIGIL: &str = "# ";
-/// Whether a listed ref is a GitHub PR or a GitLab MR. Drives the `output()`
-/// shortcut (`pr:`/`mr:`) and the row label.
-#[derive(Clone, Copy)]
-enum RefKind {
- Pr,
- Mr,
-}
-
-impl RefKind {
- /// Shortcut prefix understood by `wt switch` (`pr` / `mr`).
- fn shortcut(self) -> &'static str {
- match self {
- RefKind::Pr => "pr",
- RefKind::Mr => "mr",
- }
- }
-}
-
/// One open PR/MR, normalized across forges for the picker row.
+#[derive(Debug)]
struct PrEntry {
number: u32,
title: String,
@@ -157,7 +141,7 @@ struct PrEntry {
author: String,
is_draft: bool,
url: Option<String>,
- kind: RefKind,
+ kind: RefType,
/// PR/MR description (GitHub `body`, GitLab `description`), rendered as
/// markdown in the `pr` preview tab. Rides the one list call — empty when
/// the forge returns no body.
@@ -179,8 +163,8 @@ impl PrEntry {
/// the row and preview renderers so both pick the sigil from one place.
fn pr_ref(&self) -> PrRef {
match self.kind {
- RefKind::Pr => PrRef::pr(u64::from(self.number)),
- RefKind::Mr => PrRef::mr(u64::from(self.number)),
+ RefType::Pr => PrRef::pr(u64::from(self.number)),
+ RefType::Mr => PrRef::mr(u64::from(self.number)),
}
}
@@ -188,7 +172,7 @@ impl PrEntry {
/// `output()` and as the preview-cache key prefix — git forbids `:` in ref
/// names, so it can never collide with a worktree row's branch-name key.
fn output_token(&self) -> String {
- format!("{}:{}", self.kind.shortcut(), self.number)
+ format!("{}{}", self.kind.syntax(), self.number)
}
/// The `PrStatus` a listed `--prs` row feeds into the unified row's static
@@ -339,10 +323,11 @@ fn fetch_and_stream(
let entries = match fetch_open_prs(repo) {
Ok(entries) => entries,
Err(e) => {
- stashed_warnings
- .lock()
- .unwrap()
- .push(warning_message(format!("{e:#}")).to_string());
+ let warning = warning_message(format!("{e:#}")).to_string();
+ let mut warnings = stashed_warnings.lock().unwrap();
+ if !warnings.contains(&warning) {
+ warnings.push(warning);
+ }
return;
}
};
@@ -569,7 +554,7 @@ fn spawn_comments_fetch(
orchestrator: &PreviewOrchestrator,
spawn_gen: &SpawnGeneration,
key_token: String,
- kind: RefKind,
+ kind: RefType,
number: u32,
updated_at: Option<String>,
width: usize,
@@ -601,8 +586,7 @@ pub(super) fn spawn_worktree_comments_fetch(
width: usize,
) {
let kind = match orchestrator.repo().ci_platform(None) {
- Some(CiPlatform::GitHub) => RefKind::Pr,
- Some(CiPlatform::GitLab) => RefKind::Mr,
+ Some(forge @ (ForgeKind::GitHub | ForgeKind::GitLab)) => forge.ref_type(),
_ => {
orchestrator.fill_external(
spawn_gen,
@@ -638,7 +622,7 @@ fn comments_unsupported_forge_pane() -> String {
/// where there's no entry to read the kind from.
pub(super) fn forge_noun(repo: &Repository) -> &'static str {
match repo.ci_platform(None) {
- Some(CiPlatform::GitLab) => "MRs",
+ Some(ForgeKind::GitLab) => "MRs",
_ => "PRs",
}
}
@@ -651,12 +635,17 @@ fn fetch_open_prs(repo: &Repository) -> anyhow::Result<Vec<PrEntry>> {
.context("Failed to resolve worktree root for --prs")?;
match repo.ci_platform(None) {
- Some(CiPlatform::GitHub) => fetch_github(&repo_root),
- Some(CiPlatform::GitLab) => fetch_gitlab(&repo_root),
+ Some(ForgeKind::GitHub) => fetch_github(&repo_root),
+ Some(ForgeKind::GitLab) => fetch_gitlab(&repo_root),
Some(other) => {
anyhow::bail!("--prs supports GitHub and GitLab; this repository's forge is {other}")
}
- None => anyhow::bail!("--prs could not determine the forge from the remote URL"),
+ None => {
+ if let Some(alias) = repo.legacy_forge_alias() {
+ anyhow::bail!("{}", legacy_forge_alias_diagnostic(&alias));
+ }
+ anyhow::bail!("--prs could not determine the forge from the remote URL")
+ }
}
}
@@ -727,7 +716,7 @@ fn parse_github_prs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {
.unwrap_or_default(),
is_draft: pr.info.is_draft == Some(true),
url: pr.info.url.clone(),
- kind: RefKind::Pr,
+ kind: RefType::Pr,
body: pr.info.body.clone().unwrap_or_default(),
updated_at: pr.info.updated_at.clone(),
status: Some(pr.info.open_pr_status()),
@@ -813,7 +802,7 @@ fn parse_gitlab_mrs(stdout: &[u8]) -> anyhow::Result<Vec<PrEntry>> {
author: mr.author.username,
is_draft: mr.draft,
url: mr.web_url,
- kind: RefKind::Mr,
+ kind: RefType::Mr,
body: mr.description,
// GitLab's MR `updated_at` is throttled and delete-blind, so it
// can't key a comments cache — MR comments stay uncached.
@@ -919,14 +908,14 @@ fn pr_unavailable_pane(label: &str) -> String {
/// terminal [`pr_unavailable_pane`] (see [`spawn_pr_previews`]).
fn fetch_forge_json(
repo: &Repository,
- kind: RefKind,
+ kind: RefType,
gh_args: &[&str],
glab_args: &[&str],
) -> Option<Vec<u8>> {
let repo_root = repo.current_worktree().root().ok()?;
let (program, args) = match kind {
- RefKind::Pr => ("gh", gh_args),
- RefKind::Mr => ("glab", glab_args),
+ RefType::Pr => ("gh", gh_args),
+ RefType::Mr => ("glab", glab_args),
};
let output = non_interactive_cmd(program)
.args(args.iter().copied())
@@ -954,7 +943,7 @@ fn fetch_forge_json(
/// `gh`'s complete `--json` result.
fn compute_pr_log(
repo: &Repository,
- kind: RefKind,
+ kind: RefType,
number: u32,
head_oid: Option<&str>,
head_branch: &str,
@@ -976,8 +965,8 @@ fn compute_pr_log(
&["api", "--paginate", &endpoint],
)?;
match kind {
- RefKind::Pr => render_github_commits(&stdout, width),
- RefKind::Mr => render_gitlab_commits(&stdout, width),
+ RefType::Pr => render_github_commits(&stdout, width),
+ RefType::Mr => render_gitlab_commits(&stdout, width),
}
}
@@ -1096,7 +1085,7 @@ fn render_commit_lines(commits: &[(String, String)], width: usize) -> String {
/// path and writes nothing to disk. See [`super::preview_cache::read_comments`].
fn compute_pr_comments(
repo: &Repository,
- kind: RefKind,
+ kind: RefType,
number: u32,
updated_at: Option<&str>,
width: usize,
@@ -1127,8 +1116,8 @@ fn compute_pr_comments(
&["api", "--paginate", &endpoint],
)?;
let comments = match kind {
- RefKind::Pr => parse_github_comments(&stdout),
- RefKind::Mr => parse_gitlab_notes(&stdout),
+ RefType::Pr => parse_github_comments(&stdout),
+ RefType::Mr => parse_gitlab_notes(&stdout),
}?;
// Persist the raw thread for the next session, keyed by the content
@@ -1362,10 +1351,10 @@ mod tests {
row.rendered.lock().unwrap().clone()
}
- fn entry(kind: RefKind, number: u32, title: &str) -> PrEntry {
+ fn entry(kind: RefType, number: u32, title: &str) -> PrEntry {
let number_ref = match kind {
- RefKind::Pr => PrRef::pr(u64::from(number)),
- RefKind::Mr => PrRef::mr(u64::from(number)),
+ RefType::Pr => PrRef::pr(u64::from(number)),
+ RefType::Mr => PrRef::mr(u64::from(number)),
};
PrEntry {
number,
@@ -1400,7 +1389,7 @@ mod tests {
#[test]
fn additional_prs_drops_already_shown_branches() {
let pr = |number, head: &str| {
- let mut e = entry(RefKind::Pr, number, "t");
+ let mut e = entry(RefType::Pr, number, "t");
e.head_branch = head.to_string();
e
};
@@ -1431,16 +1420,16 @@ mod tests {
#[test]
fn output_token_is_the_switch_shortcut() {
- let pr = pr_item(entry(RefKind::Pr, 123, "Fix the flaky test"), 120, None);
+ let pr = pr_item(entry(RefType::Pr, 123, "Fix the flaky test"), 120, None);
assert_eq!(pr.output(), "pr:123");
- let mr = pr_item(entry(RefKind::Mr, 7, "Add caching"), 120, None);
+ let mr = pr_item(entry(RefType::Mr, 7, "Add caching"), 120, None);
assert_eq!(mr.output(), "mr:7");
}
#[test]
fn search_text_covers_number_title_branch_author() {
- let pr = pr_item(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);
+ let pr = pr_item(entry(RefType::Pr, 42, "Speed up startup"), 120, None);
let text = pr.text();
assert!(text.contains("42"));
assert!(text.contains("Speed up startup"));
@@ -1468,7 +1457,7 @@ mod tests {
.is_some()
};
- let pr = pr_item(entry(RefKind::Pr, 42, "Speed up startup"), 120, None);
+ let pr = pr_item(entry(RefType::Pr, 42, "Speed up startup"), 120, None);
assert!(matches(&pr), "# selects the PR row");
// A worktree-style row carries no `#` in its folded search_text.
assert!(
@@ -1482,7 +1471,7 @@ mod tests {
// No grid: the freeform fallback shows reference and branch. The title
// and author have no column, so they stay off the row — but the title
// still feeds `search_text`.
- let pr = pr_item(entry(RefKind::Pr, 1, "Retry the flaky test"), 80, None);
+ let pr = pr_item(entry(RefType::Pr, 1, "Retry the flaky test"), 80, None);
let row = plain(&rendered_of(&pr));
assert!(row.contains("feature/auth"), "branch on the row: {row:?}");
assert!(row.contains("#1"), "reference on the row: {row:?}");
@@ -1501,7 +1490,7 @@ mod tests {
fn freeform_row_truncates_a_long_branch_to_the_pane() {
// The branch absorbs the remaining width after the reference and
// truncates so the row stays inside the pane.
- let mut e = entry(RefKind::Pr, 1, "Title");
+ let mut e = entry(RefType::Pr, 1, "Title");
e.head_branch = "a-very-long-branch-name-that-would-otherwise-overflow".to_string();
let pr = pr_item(e, 40, None);
let row = plain(&rendered_of(&pr));
@@ -1515,7 +1504,7 @@ mod tests {
// The row carries no title or inline flag, so a draft shows in the pr
// pane (and, with a CI column, as the dimmed number — see
// `grid_row_with_ci_dims_drafts_instead_of_flagging_them`).
- let mut e = entry(RefKind::Pr, 9, "WIP refactor");
+ let mut e = entry(RefType::Pr, 9, "WIP refactor");
e.is_draft = true;
let pr = pr_item(e, 120, None);
assert!(pr.render_pr_pane_cached(120).contains("draft"));
@@ -1532,7 +1521,7 @@ mod tests {
// First build: PR #42 is a draft; rendering its `pr` tab memoizes the
// draft pane under (pr:42, Pr).
- let mut draft = entry(RefKind::Pr, 42, "WIP refactor");
+ let mut draft = entry(RefType::Pr, 42, "WIP refactor");
draft.is_draft = true;
let row = pr_item_with_cache(draft, 120, None, Arc::clone(&cache));
assert!(
@@ -1541,7 +1530,7 @@ mod tests {
);
// Reload: #42 is now marked ready. The rebuilt row shares the cache.
- let ready = entry(RefKind::Pr, 42, "WIP refactor");
+ let ready = entry(RefType::Pr, 42, "WIP refactor");
let row = pr_item_with_cache(ready, 120, None, Arc::clone(&cache));
assert!(
!row.render_pr_pane_cached(120).contains("draft"),
@@ -1590,7 +1579,7 @@ mod tests {
// Branch column (which ends at 22, so the reference lands at 24). The
// title and author stay off the row.
let pr = pr_item(
- entry(RefKind::Pr, 123, "Fix the flaky test"),
+ entry(RefType::Pr, 123, "Fix the flaky test"),
120,
Some(&grid()),
);
@@ -1612,7 +1601,7 @@ mod tests {
#[test]
fn grid_row_truncates_long_branch_to_its_column() {
- let mut e = entry(RefKind::Pr, 5, "Title");
+ let mut e = entry(RefType::Pr, 5, "Title");
e.head_branch = "a-very-long-branch-name-overflowing".to_string();
let pr = pr_item(e, 120, Some(&grid_with_ci()));
let text = plain(&rendered_of(&pr));
@@ -1627,7 +1616,7 @@ mod tests {
// (the CI column, `wt list`). The CI-column number, freeform row, and
// preview all derive the sigil from `PrEntry::pr_ref`.
let mr = pr_item(
- entry(RefKind::Mr, 42, "Add caching"),
+ entry(RefType::Mr, 42, "Add caching"),
120,
Some(&grid_with_ci()),
);
@@ -1642,7 +1631,7 @@ mod tests {
"preview uses ! for MRs"
);
- let mr_freeform = pr_item(entry(RefKind::Mr, 42, "Add caching"), 120, None);
+ let mr_freeform = pr_item(entry(RefType::Mr, 42, "Add caching"), 120, None);
assert!(
plain(&rendered_of(&mr_freeform)).contains("!42"),
"freeform row uses !"
@@ -1650,7 +1639,7 @@ mod tests {
// GitHub PRs keep `#N`.
let pr = pr_item(
- entry(RefKind::Pr, 42, "Add caching"),
+ entry(RefType::Pr, 42, "Add caching"),
120,
Some(&grid_with_ci()),
);
@@ -1671,7 +1660,7 @@ mod tests {
grid_col(ColumnKind::Branch, 2, 20),
],
};
- let mut e = entry(RefKind::Pr, 1, "Title");
+ let mut e = entry(RefType::Pr, 1, "Title");
e.head_branch = "a-very-long-branch-name-that-runs-past-the-edge".to_string();
let pr = pr_item(e, 60, Some(&no_flexible));
let text = plain(&rendered_of(&pr));
@@ -1685,7 +1674,7 @@ mod tests {
#[test]
fn grid_row_places_the_number_in_the_ci_column() {
let pr = pr_item(
- entry(RefKind::Pr, 123, "Fix the flaky test"),
+ entry(RefType::Pr, 123, "Fix the flaky test"),
120,
Some(&grid_with_ci()),
);
@@ -1711,7 +1700,7 @@ mod tests {
],
};
let pr = pr_item(
- entry(RefKind::Pr, 42, "Retry the flaky test"),
+ entry(RefType::Pr, 42, "Retry the flaky test"),
120,
Some(&grid),
);
@@ -1728,7 +1717,7 @@ mod tests {
fn grid_row_dims_drafts_via_the_ci_number() {
// A draft shows only as the dimmed number in the CI column (review
// state Draft) — never as a "draft" word on the row.
- let mut e = entry(RefKind::Pr, 9, "WIP");
+ let mut e = entry(RefType::Pr, 9, "WIP");
e.is_draft = true;
if let Some(status) = e.status.as_mut() {
status.review_state = Some(ReviewState::Draft);
@@ -1810,7 +1799,7 @@ mod tests {
);
assert_eq!(entries[0].author, "octocat");
assert!(!entries[0].is_draft);
- assert!(matches!(entries[0].kind, RefKind::Pr));
+ assert!(matches!(entries[0].kind, RefType::Pr));
assert_eq!(entries[0].body, "Bumps the CI image and re-pins actions.");
assert_eq!(entries[1].number, 2969);
@@ -1844,26 +1833,40 @@ mod tests {
// A repo with no remote can't be classified as GitHub or GitLab, so
// `--prs` reports that instead of shelling out to gh/glab.
let test = worktrunk::testing::TestRepo::with_initial_commit();
- let err = match fetch_open_prs(&test.repo) {
- Ok(_) => panic!("expected --prs to bail without a forge remote"),
- Err(e) => e,
- };
+ let err =
+ fetch_open_prs(&test.repo).expect_err("expected --prs to bail without a forge remote");
assert!(
err.to_string().contains("could not determine the forge"),
"unexpected error: {err:#}"
);
}
+ #[test]
+ fn fetch_open_prs_explains_legacy_forge_alias_configuration() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ test.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "git@github-personal:owner/repo.git",
+ ]);
+ let err = fetch_open_prs(&test.repo)
+ .expect_err("expected --prs to require explicit forge config");
+ let message = err.to_string();
+ assert!(
+ message.contains("github-personal") && message.contains("forge.platform = \"github\""),
+ "unexpected error: {err:#}"
+ );
+ }
+
#[test]
fn fetch_open_prs_bails_on_an_unsupported_forge() {
// A recognized-but-unsupported forge (here Gitea, by its host) reports
// the GitHub/GitLab limitation rather than shelling out.
let test = worktrunk::testing::TestRepo::with_initial_commit();
test.run_git(&["remote", "add", "origin", "https://gitea.com/o/r.git"]);
- let err = match fetch_open_prs(&test.repo) {
- Ok(_) => panic!("expected --prs to bail on an unsupported forge"),
- Err(e) => e,
- };
+ let err =
+ fetch_open_prs(&test.repo).expect_err("expected --prs to bail on an unsupported forge");
assert!(
err.to_string().contains("supports GitHub and GitLab"),
"unexpected error: {err:#}"
@@ -1930,7 +1933,7 @@ mod tests {
);
assert!(entries[1].head_oid.is_none());
assert_eq!(entries[0].author, "alice");
- assert!(matches!(entries[0].kind, RefKind::Mr));
+ assert!(matches!(entries[0].kind, RefType::Mr));
assert_eq!(entries[0].body, "Caches the dependency graph between jobs.");
// GitLab's `description` maps to the same `body` slot; absent → empty.
assert_eq!(entries[1].body, "");
@@ -1949,7 +1952,7 @@ mod tests {
#[test]
fn pr_pane_shows_description_only_when_present() {
- let mut with_body = entry(RefKind::Pr, 1, "t");
+ let mut with_body = entry(RefType::Pr, 1, "t");
with_body.body = "A short summary of the change.".to_string();
let pr = pr_item(with_body, 120, Some(&grid()));
let pane = pr.render_pr_pane_cached(120);
@@ -1966,7 +1969,7 @@ mod tests {
// The base fixture has an empty body — the description block is skipped,
// label and all.
- let plain_pr = pr_item(entry(RefKind::Pr, 2, "t"), 120, Some(&grid()));
+ let plain_pr = pr_item(entry(RefType::Pr, 2, "t"), 120, Some(&grid()));
let plain_pane = plain_pr.render_pr_pane_cached(120);
assert!(
!plain_pane.contains("\n\n\x1b[0m"),
@@ -1986,7 +1989,7 @@ mod tests {
// real `SkimItem::preview` (the `--prs` streaming path is too async to
// exercise it reliably under a PTY). `context.width` (80) is wide enough
// for the full tab bar, so the `pr` / `comments` tabs show their labels.
- let pr = pr_item(entry(RefKind::Pr, 7, "Title"), 120, Some(&grid()));
+ let pr = pr_item(entry(RefType::Pr, 7, "Title"), 120, Some(&grid()));
let ctx = PreviewContext {
query: "",
cmd_query: "",
@@ -2018,7 +2021,7 @@ mod tests {
// alt-2); once the background fetch lands a value under that key, the
// pane shows it.
let cache: PreviewCache = Arc::new(DashMap::new());
- let pr = pr_item_with_cache(entry(RefKind::Pr, 42, "t"), 120, None, Arc::clone(&cache));
+ let pr = pr_item_with_cache(entry(RefType::Pr, 42, "t"), 120, None, Arc::clone(&cache));
let miss = pr.cached_or_loading(PreviewMode::Log);
assert!(miss.contains("Loading commit log"), "miss: {miss:?}");
@@ -2128,7 +2131,7 @@ mod tests {
// `compute_pr_log` takes the local path for a present head without
// touching the forge.
- let via_compute = compute_pr_log(&repo, RefKind::Pr, 42, Some(&oid), "feature", 80, 24)
+ let via_compute = compute_pr_log(&repo, RefType::Pr, 42, Some(&oid), "feature", 80, 24)
.expect("compute_pr_log renders the local log");
assert!(plain(&via_compute).contains("Add the retry"));
}
@@ -2139,7 +2142,7 @@ mod tests {
// keyed by the row's output token, with a loading placeholder (pointing
// at alt-7) on a miss.
let cache: PreviewCache = Arc::new(DashMap::new());
- let pr = pr_item_with_cache(entry(RefKind::Mr, 7, "t"), 120, None, Arc::clone(&cache));
+ let pr = pr_item_with_cache(entry(RefType::Mr, 7, "t"), 120, None, Arc::clone(&cache));
let miss = pr.cached_or_loading(PreviewMode::Comments);
assert!(miss.contains("Loading comments"), "miss: {miss:?}");
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 4a10b6428..04b31d710 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -638,6 +638,13 @@ impl<'a> RelocationExecutor<'a> {
cwd_path,
);
crate::output::change_directory(cd_target)?;
+ if crate::output::retired_shell_wrapper_active() {
+ eprintln!(
+ "{}",
+ warning_message("Cannot change directory — shell wrapper is out of date")
+ );
+ crate::output::print_outdated_shell_wrapper_hint_once();
+ }
}
self.moved.insert(idx);
diff --git a/src/commands/remove.rs b/src/commands/remove.rs
index 5e2a91c4f..d5cc858c1 100644
--- a/src/commands/remove.rs
+++ b/src/commands/remove.rs
@@ -70,11 +70,20 @@ fn validate_remove_targets(
force_delete: bool,
force: bool,
) -> RemovePlans {
- let current_worktree = repo
- .current_worktree()
- .root()
- .ok()
- .and_then(|p| dunce::canonicalize(&p).ok());
+ let mut plans = RemovePlans {
+ others: Vec::new(),
+ branch_only: Vec::new(),
+ current: None,
+ errors: Vec::new(),
+ };
+
+ let current_worktree = match repo.current_worktree().root() {
+ Ok(path) => dunce::canonicalize(&path).unwrap_or(path),
+ Err(e) => {
+ plans.record_error(e);
+ return plans;
+ }
+ };
// Dedupe inputs to avoid redundant planning/execution
let branches: Vec<_> = {
@@ -94,15 +103,8 @@ fn validate_remove_targets(
// fall back to capturing internally when None.
let snapshot = repo.capture_refs().ok();
- let mut plans = RemovePlans {
- others: Vec::new(),
- branch_only: Vec::new(),
- current: None,
- errors: Vec::new(),
- };
-
- for branch_name in &branches {
- let resolved = match repo.resolve_worktree(branch_name) {
+ for branch_name in branches {
+ let resolved = match repo.resolve_worktree(&branch_name) {
Ok(r) => r,
Err(e) => {
plans.record_error(e);
@@ -110,26 +112,10 @@ fn validate_remove_targets(
}
};
- match resolved {
+ let target = match resolved {
ResolvedWorktree::Worktree { path, branch: _ } => {
// Use canonical paths to avoid symlink/normalization mismatches
let path_canonical = dunce::canonicalize(&path).unwrap_or(path);
- let is_current = current_worktree.as_ref() == Some(&path_canonical);
-
- if is_current {
- match repo.prepare_worktree_removal(
- RemoveTarget::Current,
- deletion_mode,
- force,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.current = Some(result),
- Err(e) => plans.record_error(e),
- }
- continue;
- }
// Remove exactly the resolved worktree by its path. Targeting by
// branch name would resolve an ambiguous branch (one checked out
@@ -138,32 +124,31 @@ fn validate_remove_targets(
// the path is unambiguous. `prepare_worktree_removal` still
// deletes the branch when it's the sole checkout, and retains it
// otherwise (see its shared-branch handling).
- let target = RemoveTarget::Path(&path_canonical);
- match repo.prepare_worktree_removal(
- target,
- deletion_mode,
- force,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.others.push(result),
- Err(e) => plans.record_error(e),
- }
- }
- ResolvedWorktree::BranchOnly { branch } => {
- match repo.prepare_worktree_removal(
- RemoveTarget::Branch(&branch),
- deletion_mode,
- force,
- None,
- worktrees,
- snapshot.as_ref(),
- ) {
- Ok(result) => plans.branch_only.push(result),
- Err(e) => plans.record_error(e),
- }
+ RemoveTarget::WorktreePath(path_canonical)
}
+ ResolvedWorktree::BranchOnly { branch } => RemoveTarget::BranchOnly(branch),
+ };
+
+ match repo.prepare_worktree_removal(
+ target,
+ deletion_mode,
+ force,
+ &current_worktree,
+ worktrees,
+ snapshot.as_ref(),
+ ) {
+ // Bucket the validated result, not the pre-validation resolution:
+ // a worktree whose directory disappeared degrades to BranchOnly
+ // during preparation and must run with the other branch-only plans.
+ Ok(result) => match &result {
+ RemovalPlan::Worktree {
+ changed_directory: true,
+ ..
+ } => plans.current = Some(result),
+ RemovalPlan::Worktree { .. } => plans.others.push(result),
+ RemovalPlan::BranchOnly { .. } => plans.branch_only.push(result),
+ },
+ Err(e) => plans.record_error(e),
}
}
@@ -340,12 +325,16 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
if branches.is_empty() {
// Single worktree removal: validate FIRST, then approve, then execute
+ let current_path = repo
+ .current_worktree()
+ .root()
+ .context("Failed to remove worktree")?;
let result = repo
.prepare_worktree_removal(
- RemoveTarget::Current,
+ RemoveTarget::WorktreePath(current_path.clone()),
BranchDeletionMode::from_flags(!delete_branch, args.force_delete),
args.force,
- None,
+ &current_path,
None,
None,
)
@@ -474,3 +463,41 @@ pub fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()>
}
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use worktrunk::testing::TestRepo;
+
+ /// Resolution sees a registered worktree, but preparation discovers its
+ /// directory is gone and degrades the result to BranchOnly. Ordered
+ /// execution must bucket that returned plan with other branch-only plans,
+ /// not preserve the stale pre-validation classification.
+ #[test]
+ fn validation_buckets_missing_worktree_by_returned_plan() {
+ let mut test = TestRepo::with_initial_commit();
+ let missing = test.add_worktree("missing-worktree");
+ test.create_branch("branch-only");
+ std::fs::remove_dir_all(&missing).unwrap();
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let plans = validate_remove_targets(
+ &repo,
+ vec!["missing-worktree".to_string(), "branch-only".to_string()],
+ false,
+ false,
+ false,
+ );
+
+ assert!(plans.errors.is_empty());
+ assert!(plans.others.is_empty());
+ assert!(plans.current.is_none());
+ assert_eq!(plans.branch_only.len(), 2);
+ assert!(
+ plans
+ .branch_only
+ .iter()
+ .all(|plan| matches!(plan, RemovalPlan::BranchOnly { .. }))
+ );
+ }
+}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 0d22504f4..6f68db18e 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -16,20 +16,20 @@ use worktrunk::styling::{
/// Target for worktree removal.
#[derive(Debug)]
-pub enum RemoveTarget<'a> {
+pub enum RemoveTarget {
/// Delete a branch that has no worktree.
///
/// A branch names a worktree only while it has exactly one: let it name
/// two, which `git worktree add --force` allows, and the lookup silently
/// picks git's first-listed checkout. So callers resolve first and pass
- /// [`Path`](Self::Path) for anything that has a worktree, and this variant
- /// carries only the branch-only case. One that has since acquired a
- /// worktree lost the race and errors rather than removing it unasked.
- Branch(&'a str),
- /// Remove the current worktree (supports detached HEAD)
- Current,
- /// Remove worktree by path (supports detached HEAD)
- Path(&'a std::path::Path),
+ /// [`WorktreePath`](Self::WorktreePath) for anything that has a worktree,
+ /// and this variant carries only the branch-only case. One that has since
+ /// acquired a worktree lost the race and errors rather than removing it
+ /// unasked.
+ BranchOnly(String),
+ /// Remove the exact worktree at this path (supports detached HEAD and
+ /// duplicate branch checkouts).
+ WorktreePath(PathBuf),
}
/// CLI-only helpers implemented on [`Repository`] via an extension trait so we can keep orphan
@@ -48,10 +48,9 @@ pub trait RepositoryCliExt {
/// callers may plan speculatively: on a `--dry-run` scan, before an
/// approval prompt, or on the picker's event loop.
///
- /// `current_path` overrides process-CWD discovery for determining which
- /// worktree is "current". Pass `None` for normal CLI usage (discovers from
- /// CWD). Pass `Some` when calling from a context where CWD may have changed
- /// (e.g., background threads in the picker).
+ /// `current_path` is the worktree the caller started in. Callers resolve it
+ /// once at their boundary so target preparation never depends on a later
+ /// process-CWD lookup (notably on picker and prune background paths).
///
/// `worktrees` provides a pre-fetched worktree list to avoid redundant
/// `git worktree list` calls. Pass `None` to fetch on demand.
@@ -66,7 +65,7 @@ pub trait RepositoryCliExt {
target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
- current_path: Option<PathBuf>,
+ current_path: &Path,
worktrees: Option<&[WorktreeInfo]>,
snapshot: Option<&RefSnapshot>,
) -> anyhow::Result<RemovalPlan>;
@@ -113,11 +112,10 @@ impl RepositoryCliExt for Repository {
target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
- current_path: Option<PathBuf>,
+ current_path: &Path,
worktrees: Option<&[WorktreeInfo]>,
snapshot: Option<&RefSnapshot>,
) -> anyhow::Result<RemovalPlan> {
- let current_path = current_path.map_or_else(|| self.current_worktree().root(), Ok)?;
let worktrees = match worktrees {
Some(wts) => wts,
None => self.list_worktrees()?,
@@ -158,7 +156,7 @@ impl RepositoryCliExt for Repository {
}
let resolved = match target {
- RemoveTarget::Branch(branch) => {
+ RemoveTarget::BranchOnly(branch) => {
// The caller established there was no worktree, so one here
// appeared in between. Falling through would remove it — the
// wrong operation, and on a worktree nobody named — so the
@@ -166,7 +164,7 @@ impl RepositoryCliExt for Repository {
// that does mean "remove that worktree".
if let Some(wt) = worktrees
.iter()
- .find(|wt| wt.branch.as_deref() == Some(branch))
+ .find(|wt| wt.branch.as_deref() == Some(branch.as_str()))
{
let path = format_path_for_display(&wt.path);
bail!(cformat!(
@@ -176,18 +174,18 @@ impl RepositoryCliExt for Repository {
}
// Check the branch exists locally, so a typo or a remote-only
// name reports itself rather than deleting nothing.
- let branch_handle = self.branch(branch);
+ let branch_handle = self.branch(&branch);
if !branch_handle.exists_locally()? {
let remotes = branch_handle.remotes()?;
if !remotes.is_empty() {
return Err(GitError::RemoteOnlyBranch {
- branch: branch.into(),
+ branch,
remote: remotes[0].clone(),
}
.into());
}
return Err(GitError::BranchNotFound {
- branch: branch.into(),
+ branch,
show_create_hint: false,
last_fetch_ago: None,
pr_mr_platform: None,
@@ -196,17 +194,13 @@ impl RepositoryCliExt for Repository {
}
Resolved::BranchOnly {
pruned_from: None,
- branch: branch.to_string(),
+ branch,
}
}
- RemoveTarget::Current | RemoveTarget::Path(_) => {
- let lookup_path = match target {
- RemoveTarget::Path(p) => p,
- _ => current_path.as_path(),
- };
+ RemoveTarget::WorktreePath(lookup_path) => {
let wt = worktrees
.iter()
- .find(|wt| worktrunk::path::paths_match(&wt.path, lookup_path))
+ .find(|wt| worktrunk::path::paths_match(&wt.path, &lookup_path))
.ok_or_else(|| {
anyhow::anyhow!("Worktree not found at {}", lookup_path.display())
})?;
@@ -251,7 +245,7 @@ impl RepositoryCliExt for Repository {
branch: branch.to_string(),
}
} else {
- let is_current = wt.path == current_path;
+ let is_current = worktrunk::path::paths_match(&wt.path, current_path);
Resolved::Worktree {
path: wt.path.clone(),
branch: wt.branch.clone(),
@@ -343,7 +337,7 @@ impl RepositoryCliExt for Repository {
// changed_directory: whether the user needs to cd away from cwd.
let changed_directory = is_current;
let main_path = if worktree_path == primary_path {
- current_path
+ current_path.to_path_buf()
} else {
primary_path
};
@@ -731,6 +725,85 @@ impl TargetWorktreeStash {
#[cfg(test)]
mod tests {
use super::*;
+ use worktrunk::git::{BranchDeletionOutcome, execute_branch_deletion};
+ use worktrunk::testing::TestRepo;
+
+ /// A branch-only plan is only a snapshot of topology. If another process
+ /// checks the branch out before execution, the final safe-delete guard must
+ /// retain the ref so the new worktree's HEAD stays resolvable.
+ #[test]
+ fn branch_only_execution_rechecks_worktree_topology() {
+ let test = TestRepo::with_initial_commit();
+ test.create_branch("feature");
+ let repo = Repository::at(test.root_path()).unwrap();
+ let current_path = test.root_path().to_path_buf();
+
+ let plan = repo
+ .prepare_worktree_removal(
+ RemoveTarget::BranchOnly("feature".to_string()),
+ BranchDeletionMode::SafeDelete,
+ false,
+ &current_path,
+ None,
+ None,
+ )
+ .unwrap();
+ assert!(matches!(plan, RemovalPlan::BranchOnly { .. }));
+
+ let checkout = test.home_path().join("repo.feature-raced-checkout");
+ test.run_git(&["worktree", "add", checkout.to_str().unwrap(), "feature"]);
+
+ let result = execute_branch_deletion(&repo, "feature", "main", false).unwrap();
+ let BranchDeletionOutcome::RetainedCheckedOut { path } = result.outcome else {
+ panic!("safe deletion must report the checkout added after planning");
+ };
+ assert!(
+ worktrunk::path::paths_match(&path, &checkout),
+ "retention should name the checkout: {} != {}",
+ path.display(),
+ checkout.display()
+ );
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
+ .is_ok(),
+ "the checked-out branch ref must survive"
+ );
+ assert!(
+ repo.worktree_at(&checkout)
+ .run_command(&["rev-parse", "--verify", "HEAD"])
+ .is_ok(),
+ "the new checkout must not be orphaned"
+ );
+ }
+
+ /// Duplicate checkout detection excludes the worktree being removed by
+ /// canonical path identity, not by its literal spelling, and still finds a
+ /// separate checkout of the same branch.
+ #[test]
+ fn duplicate_checkout_detection_compares_paths_canonically() {
+ let mut test = TestRepo::with_initial_commit();
+ let removed = test.add_worktree("feature");
+ let survivor = test.home_path().join("repo.feature-survivor");
+ test.run_git(&[
+ "worktree",
+ "add",
+ "--force",
+ survivor.to_str().unwrap(),
+ "feature",
+ ]);
+
+ let alias_anchor = removed.join("alias-anchor");
+ std::fs::create_dir(&alias_anchor).unwrap();
+ let removed_alias = alias_anchor.join("..");
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worktrees = repo.list_worktrees().unwrap();
+
+ let found = live_sibling_checkout(worktrees, "feature", &removed_alias).unwrap();
+ assert!(
+ worktrunk::path::paths_match(&found.path, &survivor),
+ "only the canonical target path may be excluded"
+ );
+ }
#[test]
fn test_parse_porcelain_z_modified_staged() {
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index fed1b7d70..b09614496 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -415,6 +415,7 @@ fn check_one(
snapshot: &RefSnapshot,
integration_target: &str,
worktrees: &[WorktreeInfo],
+ current_path: &Path,
min_age_duration: Duration,
now_secs: u64,
) -> anyhow::Result<CheckOutcome> {
@@ -442,10 +443,10 @@ fn check_one(
match &item.source {
CheckSource::Orphan => repo
.prepare_worktree_removal(
- RemoveTarget::Branch(&item.integration_ref),
+ RemoveTarget::BranchOnly(item.integration_ref.clone()),
BranchDeletionMode::SafeDelete,
false,
- None,
+ current_path,
Some(worktrees),
Some(snapshot),
)
@@ -457,12 +458,13 @@ fn check_one(
// by branch would re-resolve to git's first-listed
// checkout, which for a duplicated branch is a different
// worktree — and for a stale entry is the live one. A
- // `Path` target degrades to branch-only deletion when the
- // directory is gone, so a stale entry plans its prune.
- RemoveTarget::Path(&wt.path),
+ // `WorktreePath` target degrades to branch-only deletion
+ // when the directory is gone, so a stale entry plans its
+ // prune.
+ RemoveTarget::WorktreePath(wt.path.clone()),
BranchDeletionMode::SafeDelete,
false,
- None,
+ current_path,
Some(worktrees),
Some(snapshot),
)
@@ -902,6 +904,7 @@ pub fn step_prune(
let snapshot_ref = &snapshot;
let check_items_ref = &check_items;
let integration_target_ref = integration_target.as_str();
+ let current_path_ref = current_root.as_path();
let check_lock_ref = &check_lock;
s.spawn(move || {
check_items_ref
@@ -916,6 +919,7 @@ pub fn step_prune(
snapshot_ref,
integration_target_ref,
worktrees,
+ current_path_ref,
min_age_duration,
now_secs,
)
@@ -1075,6 +1079,7 @@ pub fn step_prune(
let snapshot_ref = &snapshot;
let check_items_ref = &check_items;
let integration_target_ref = integration_target.as_str();
+ let current_path_ref = current_root.as_path();
let check_lock_ref = &check_lock;
s.spawn(move || {
check_items_ref
@@ -1089,6 +1094,7 @@ pub fn step_prune(
snapshot_ref,
integration_target_ref,
worktrees,
+ current_path_ref,
min_age_duration,
now_secs,
)
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index f3cb4d01d..a54d35998 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -21,8 +21,7 @@ use worktrunk::git::remote_ref::{
RemoteRefProvider, parse_ref_url,
};
use worktrunk::git::{
- GitError, GitRemoteUrl, RefContext, RefType, Repository, SwitchSuggestionCtx,
- current_or_recover,
+ ForgeKind, GitError, GitRemoteUrl, RefType, Repository, SwitchSuggestionCtx, current_or_recover,
};
use worktrunk::shell_exec::{ShellEscapeMode, directive_shell_escape_mode, shell_escape_for};
use worktrunk::styling::{
@@ -54,6 +53,10 @@ struct ResolvedTarget {
method: CreationMethod,
}
+static GITHUB_PROVIDER: GitHubProvider = GitHubProvider;
+static GITEA_PROVIDER: GiteaProvider = GiteaProvider;
+static AZURE_DEVOPS_PROVIDER: AzureDevOpsProvider = AzureDevOpsProvider;
+
/// Format PR/MR context for gutter display after fetching.
///
/// Returns two lines for gutter formatting:
@@ -61,35 +64,30 @@ struct ResolvedTarget {
/// ┃ Fix authentication bug in login flow (#101)
/// ┃ by @alice · open · feature-auth · https://github.com/owner/repo/pull/101
/// ```
-fn format_ref_context(ctx: &impl RefContext) -> String {
- let mut status_parts = vec![format!("by @{}", ctx.author()), ctx.state().to_string()];
- if ctx.draft() {
+fn format_ref_context(info: &RemoteRefInfo) -> String {
+ let mut status_parts = vec![format!("by @{}", info.author), info.state.clone()];
+ if info.draft {
status_parts.push("draft".to_string());
}
- status_parts.push(ctx.source_ref());
+ status_parts.push(info.source_ref());
let status_line = status_parts.join(" · ");
cformat!(
"<bold>{}</> ({}{})\n{status_line} · <bright-black>{}</>",
- ctx.title(),
- ctx.ref_type().symbol(),
- ctx.number(),
- ctx.url()
+ info.title,
+ info.ref_type().symbol(),
+ info.number,
+ info.url
)
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum PrProviderChoice {
- GitHub,
- Gitea,
- AzureDevOps,
-}
-
/// Choose which provider should handle `pr:<number>` resolution.
///
/// Priority:
/// 1. `forge.platform` config (`github` / `gitea` / `azure-devops`)
-/// 2. Primary remote URL detection (host contains `github`/`gitea`/`dev.azure.com`)
+/// 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.
/// 3. CLI auth lookup — if `tea` has a login for this host but `gh` does
/// not, pick Gitea; otherwise default to GitHub
///
@@ -97,20 +95,19 @@ enum PrProviderChoice {
/// host (e.g. `git.example.com`) without `tea login add` will see a single
/// GitHub error (with hint to set `forge.platform = "gitea"`), instead of a
/// wrapped two-provider error.
-fn choose_pr_provider(repo: &Repository) -> anyhow::Result<PrProviderChoice> {
+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))
{
- let platform = platform_raw.to_ascii_lowercase();
- match platform.as_str() {
- "github" => return Ok(PrProviderChoice::GitHub),
- "gitea" => return Ok(PrProviderChoice::Gitea),
- "azure-devops" | "azuredevops" => return Ok(PrProviderChoice::AzureDevOps),
- "gitlab" => {
+ match platform_raw.to_ascii_lowercase().parse::<ForgeKind>() {
+ Ok(ForgeKind::GitHub) => return Ok(&GITHUB_PROVIDER),
+ Ok(ForgeKind::Gitea) => return Ok(&GITEA_PROVIDER),
+ Ok(ForgeKind::AzureDevOps) => return Ok(&AZURE_DEVOPS_PROVIDER),
+ Ok(ForgeKind::GitLab) => {
bail!("forge.platform is set to gitlab; use mr:<number> instead of pr:<number>")
}
- _ => bail!(
+ Err(_) => bail!(
"Invalid forge.platform value `{platform_raw}` in .config/wt.toml; \
expected one of: github, gitlab, gitea, azure-devops"
),
@@ -125,17 +122,18 @@ fn choose_pr_provider(repo: &Repository) -> anyhow::Result<PrProviderChoice> {
.into_iter()
.filter_map(|(_, url)| GitRemoteUrl::parse(&url))
.collect();
+ let has_forge = |forge| all_parsed.iter().any(|url| url.forge_kind() == Some(forge));
- if all_parsed.iter().any(|u| u.is_github()) {
- return Ok(PrProviderChoice::GitHub);
+ if has_forge(ForgeKind::GitHub) {
+ return Ok(&GITHUB_PROVIDER);
}
- if all_parsed.iter().any(|u| u.is_gitea()) {
- return Ok(PrProviderChoice::Gitea);
+ if has_forge(ForgeKind::Gitea) {
+ return Ok(&GITEA_PROVIDER);
}
- if all_parsed.iter().any(|u| u.is_azure_devops()) {
- return Ok(PrProviderChoice::AzureDevOps);
+ if has_forge(ForgeKind::AzureDevOps) {
+ return Ok(&AZURE_DEVOPS_PROVIDER);
}
- if all_parsed.iter().any(|u| u.is_gitlab()) {
+ if has_forge(ForgeKind::GitLab) {
bail!("Detected GitLab remote; use mr:<number> instead of pr:<number>")
}
@@ -151,13 +149,13 @@ fn choose_pr_provider(repo: &Repository) -> anyhow::Result<PrProviderChoice> {
.and_then(|url| GitRemoteUrl::parse(&url))
.map(|u| u.host().to_string())
else {
- return Ok(PrProviderChoice::GitHub);
+ return Ok(&GITHUB_PROVIDER);
};
if remote_ref::gitea::is_authed_for(&host) && !remote_ref::github::is_authed_for(&host) {
- Ok(PrProviderChoice::Gitea)
+ Ok(&GITEA_PROVIDER)
} else {
- Ok(PrProviderChoice::GitHub)
+ Ok(&GITHUB_PROVIDER)
}
}
@@ -175,26 +173,14 @@ fn resolve_pr_target(
.into());
}
- match choose_pr_provider(repo)? {
- PrProviderChoice::GitHub => resolve_remote_ref(repo, &GitHubProvider, number, create, base),
- PrProviderChoice::Gitea => resolve_remote_ref(repo, &GiteaProvider, number, create, base),
- PrProviderChoice::AzureDevOps => {
- resolve_remote_ref(repo, &AzureDevOpsProvider, number, create, base)
- }
- }
+ resolve_remote_ref(repo, choose_pr_provider(repo)?, number, create, base)
}
fn resolve_pr_base(
repo: &Repository,
number: u32,
) -> anyhow::Result<(String, Option<(String, String)>)> {
- match choose_pr_provider(repo)? {
- PrProviderChoice::GitHub => resolve_remote_ref_as_base(repo, &GitHubProvider, number),
- PrProviderChoice::Gitea => resolve_remote_ref_as_base(repo, &GiteaProvider, number),
- PrProviderChoice::AzureDevOps => {
- resolve_remote_ref_as_base(repo, &AzureDevOpsProvider, number)
- }
- }
+ resolve_remote_ref_as_base(repo, choose_pr_provider(repo)?, number)
}
/// Fetch PR/MR info while showing a "still waiting" status.
@@ -2181,8 +2167,8 @@ mod tests {
]);
assert_eq!(
- choose_pr_provider(&test.repo).unwrap(),
- PrProviderChoice::GitHub
+ choose_pr_provider(&test.repo).unwrap().forge_kind(),
+ ForgeKind::GitHub
);
}
@@ -2198,8 +2184,8 @@ mod tests {
]);
assert_eq!(
- choose_pr_provider(&test.repo).unwrap(),
- PrProviderChoice::AzureDevOps
+ choose_pr_provider(&test.repo).unwrap().forge_kind(),
+ ForgeKind::AzureDevOps
);
}
@@ -2209,8 +2195,8 @@ mod tests {
// preserving the existing error message from `gh`.
let test = TestRepo::with_initial_commit();
assert_eq!(
- choose_pr_provider(&test.repo).unwrap(),
- PrProviderChoice::GitHub
+ choose_pr_provider(&test.repo).unwrap().forge_kind(),
+ ForgeKind::GitHub
);
}
@@ -2232,8 +2218,8 @@ mod tests {
test.write_project_config("[forge]\nplatform = \"azure-devops\"\n");
assert_eq!(
- choose_pr_provider(&test.repo).unwrap(),
- PrProviderChoice::AzureDevOps
+ choose_pr_provider(&test.repo).unwrap().forge_kind(),
+ ForgeKind::AzureDevOps
);
}
@@ -2251,8 +2237,8 @@ mod tests {
test.write_project_config("[forge]\nplatform = \"github\"\n");
assert_eq!(
- choose_pr_provider(&test.repo).unwrap(),
- PrProviderChoice::GitHub
+ choose_pr_provider(&test.repo).unwrap().forge_kind(),
+ ForgeKind::GitHub
);
}
}
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index f912b8a00..ee4238c3b 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -189,8 +189,9 @@ pub enum BranchFate {
/// The deletion ran and the branch is gone.
Deleted,
/// The deletion ran and the branch survives: SafeDelete declined an
- /// unmerged branch, the CAS refused a moved ref, or the delete command
- /// itself failed (already narrated at the site that observed it).
+ /// unmerged branch, a final topology check found a checkout, the CAS refused
+ /// a moved ref, or the delete command itself failed (already narrated at
+ /// the site that observed it).
Retained,
/// The deletion was handed to a detached background process (the legacy
/// `git worktree remove` fallback) whose outcome this process never sees.
@@ -212,9 +213,9 @@ impl BranchFate {
BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {
Self::Deleted
}
- BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced => {
- Self::Retained
- }
+ BranchDeletionOutcome::NotDeleted
+ | BranchDeletionOutcome::RetainedCheckedOut { .. }
+ | BranchDeletionOutcome::RetainedRaced => Self::Retained,
},
Some(Err(_)) => Self::Retained,
}
@@ -233,8 +234,8 @@ impl BranchFate {
///
/// Produced by the planner, executed by `output::handle_remove_output`. The
/// deletion-relevant fields are intent, not fact: `deletion_mode` says what the
-/// executor should attempt, and the actual deletion re-decides against fresh
-/// refs (`delete_branch_if_safe`'s CAS).
+/// executor should attempt, and the actual safe deletion rechecks both worktree
+/// topology and fresh refs (`delete_branch_if_safe`'s guard + CAS).
pub enum RemovalPlan {
/// Remove a worktree, changing directory away from it first if it's current.
Worktree {
@@ -283,9 +284,8 @@ pub enum RemovalPlan {
/// `origin/main` when upstream is ahead) or the local default branch.
/// `None` when no default branch is configured.
target_branch: Option<String>,
- /// Pre-computed integration reason. Branch-only removal has no
- /// worktree-local `pre-remove` hook, so the integration decision can
- /// be made during preparation.
+ /// Integration reason computed during preparation for display. The
+ /// executor still rechecks topology and ref state before safe deletion.
integration_reason: Option<worktrunk::git::IntegrationReason>,
/// A surviving checkout of `branch_name`, when one exists. Only reachable
/// on a pruned removal — the target's directory was gone, but a sibling
@@ -308,8 +308,8 @@ impl RemovalPlan {
}
}
- /// Branch name of the removed worktree, if known. `None` for detached-HEAD
- /// worktrees and (structurally) for branch-only deletions.
+ /// Branch named by this plan. `None` only for a detached-HEAD worktree;
+ /// branch-only plans always return their branch.
///
/// Only the `--reap` label needs this, which is Unix-only; gated to avoid a
/// dead-code warning on Windows where nothing consumes it.
@@ -464,6 +464,12 @@ mod tests {
fate(BranchDeletionOutcome::NotDeleted),
BranchFate::Retained
);
+ assert_eq!(
+ fate(BranchDeletionOutcome::RetainedCheckedOut {
+ path: PathBuf::from("/tmp/feature"),
+ }),
+ BranchFate::Retained
+ );
assert_eq!(
fate(BranchDeletionOutcome::RetainedRaced),
BranchFate::Retained
diff --git a/src/completion.rs b/src/completion.rs
index dc6ab7b5d..bf653f5e9 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -754,6 +754,8 @@ fn try_forward_completion_to_custom(
// work at best, the parent's trace lost at worst (the child's stderr is
// discarded below, so it can't surface anything useful anyway).
cmd.env_remove(crate::logging::VERBOSE_ENV);
+ // The retired single-file protocol is never delegated to child processes.
+ cmd.env_remove(worktrunk::shell_exec::RETIRED_DIRECTIVE_FILE_ENV_VAR);
// Capture the custom binary's stdout — it carries the forwarded completion
// candidates. Uses `std::process::Command` rather than `shell_exec::Cmd`
diff --git a/src/diagnostic.rs b/src/diagnostic.rs
index 16ddbc274..037fe6dc5 100644
--- a/src/diagnostic.rs
+++ b/src/diagnostic.rs
@@ -425,21 +425,30 @@ fn truncate_log(content: &str) -> String {
format!("(log truncated to last ~50KB)\n{}", &content[start..])
}
-/// Get git version string.
-fn git_version() -> anyhow::Result<String> {
+/// Get the version reported by `git --version`.
+pub(crate) fn git_version() -> anyhow::Result<String> {
let output = Cmd::new("git")
.arg("--version")
.run()
.context("Failed to run git --version")?;
- let stdout = String::from_utf8_lossy(&output.stdout);
+ anyhow::ensure!(output.status.success(), "git --version failed");
+ parse_git_version(&output.stdout)
+}
+
+fn parse_git_version(stdout: &[u8]) -> anyhow::Result<String> {
+ let stdout = std::str::from_utf8(stdout)
+ .context("git --version returned invalid UTF-8")?
+ .trim();
let version = stdout
- .trim()
.strip_prefix("git version ")
- .unwrap_or(stdout.trim())
- .to_string();
+ .context("git --version returned an unexpected response")?;
+ anyhow::ensure!(
+ !version.is_empty() && !version.contains(['\r', '\n']),
+ "git --version returned an unexpected response"
+ );
- Ok(version)
+ Ok(version.to_string())
}
/// Render the curated environment variables ([`DIAGNOSTIC_ENV_VARS`]) plus git's
@@ -624,6 +633,27 @@ mod tests {
assert!(render_trace_profile("not a trace line\nanother line\n").is_none());
}
+ #[test]
+ fn test_parse_git_version_requires_standard_single_line_output() {
+ assert_eq!(
+ parse_git_version(b"git version 2.47.1\n").unwrap(),
+ "2.47.1"
+ );
+ assert_eq!(
+ parse_git_version(b"git version 2.39.5 (Apple Git-154)\n").unwrap(),
+ "2.39.5 (Apple Git-154)"
+ );
+
+ for malformed in [
+ b"2.47.1".as_slice(),
+ b"git version \n",
+ b"git version 2.47.1\nextra",
+ b"git version 2.\xff",
+ ] {
+ assert!(parse_git_version(malformed).is_err());
+ }
+ }
+
#[test]
fn test_truncate_log_small_content() {
let content = "small log content";
diff --git a/src/git/ci_platform.rs b/src/git/ci_platform.rs
index e66ed5cb2..28c444510 100644
--- a/src/git/ci_platform.rs
+++ b/src/git/ci_platform.rs
@@ -1,20 +1,21 @@
//! CI platform identification.
//!
-//! [`CiPlatform`] names the forge a repository's CI runs on (GitHub, GitLab,
+//! [`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`].
-use crate::git::{GitRemoteUrl, Repository};
+use crate::git::{GitRemoteUrl, RefType, Repository};
-/// The forge a repository's CI runs on.
+/// A known forge.
///
-/// Resolved by [`Repository::ci_platform`]: project config (`forge.platform`,
-/// or the deprecated `ci.platform`) takes precedence, falling back to the
-/// remote URL host.
+/// This is the canonical identity shared by configuration, remote-host
+/// classification, remote-ref providers, and CI dispatch. Unknown hosts stay
+/// outside the enum as `None`; callers that expose an explicit `unknown` value
+/// add it only at that output boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]
#[strum(serialize_all = "lowercase")]
-pub enum CiPlatform {
+pub enum ForgeKind {
GitHub,
GitLab,
/// Experimental — Gitea CI status via the `tea` CLI.
@@ -23,21 +24,128 @@ pub enum CiPlatform {
AzureDevOps,
}
+/// A branded SSH host alias that the former substring classifier recognized.
+///
+/// This is diagnostic-only: callers can explain the compatibility change and
+/// suggest `forge.platform`, but must not use it to select a forge provider.
+/// Dispatch remains on [`ForgeKind::from_host`]'s exact-label boundary.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LegacyForgeAlias {
+ host: String,
+ platform: ForgeKind,
+}
+
+impl LegacyForgeAlias {
+ pub fn host(&self) -> &str {
+ &self.host
+ }
+
+ pub fn platform(&self) -> ForgeKind {
+ self.platform
+ }
+
+ /// Recognize the common multi-account SSH alias form (`github-personal`).
+ ///
+ /// Only SSH URLs with a single-label, forge-prefixed host qualify. Dotted
+ /// hosts stay out even when they contain a forge name: those are exactly
+ /// the security-sensitive lookalikes the exact-label classifier rejects.
+ fn from_url(url: &str) -> Option<Self> {
+ let url = url.trim();
+ let is_ssh = url.starts_with("ssh://")
+ || url
+ .split_once(':')
+ .is_some_and(|(authority, _)| !authority.contains('/') && authority.contains('@'));
+ if !is_ssh {
+ return None;
+ }
+
+ let parsed = GitRemoteUrl::parse(url)?;
+ let host = normalized_hostname(parsed.host());
+ if host.contains('.') || ForgeKind::from_host(&host).is_some() {
+ return None;
+ }
+
+ let platform = [
+ ("github-", ForgeKind::GitHub),
+ ("gitlab-", ForgeKind::GitLab),
+ ("gitea-", ForgeKind::Gitea),
+ ]
+ .into_iter()
+ .find_map(|(prefix, platform)| {
+ host.strip_prefix(prefix)
+ .filter(|suffix| !suffix.is_empty())
+ .map(|_| platform)
+ })?;
+
+ Some(Self { host, platform })
+ }
+}
+
+impl ForgeKind {
+ /// Classify a forge from a remote hostname.
+ ///
+ /// GitHub, GitLab, and Gitea self-hosted instances commonly put the forge
+ /// name in its own DNS label. Azure DevOps has fixed service domains, so it
+ /// uses domain-suffix matching and takes precedence over branded labels
+ /// inside those domains. Both rules respect label boundaries:
+ /// `github-mirror.example` and `dev.azure.com.attacker.example` are not
+ /// recognized. A branded hostname can opt in through `[forge].platform`.
+ pub fn from_host(host: &str) -> Option<Self> {
+ let host = normalized_hostname(host);
+ if normalized_host_is_within(&host, "dev.azure.com")
+ || normalized_host_is_within(&host, "visualstudio.com")
+ {
+ Some(Self::AzureDevOps)
+ } else if host_has_label(&host, "github") {
+ Some(Self::GitHub)
+ } else if host_has_label(&host, "gitlab") {
+ Some(Self::GitLab)
+ } else if host_has_label(&host, "gitea") {
+ Some(Self::Gitea)
+ } else {
+ None
+ }
+ }
+
+ /// PR/MR vocabulary for change requests on this forge.
+ pub const fn ref_type(self) -> RefType {
+ match self {
+ Self::GitLab => RefType::Mr,
+ Self::GitHub | Self::Gitea | Self::AzureDevOps => RefType::Pr,
+ }
+ }
+}
+
+/// Lowercase a hostname and remove transport-only syntax before classifying it.
+///
+/// `GitRemoteUrl` already strips ports from `ssh://` URLs, while HTTP(S) keeps
+/// the authority intact. Treat a numeric suffix as a port so both transports
+/// classify identically. A trailing DNS root dot is likewise identity-neutral.
+pub(super) fn normalized_hostname(host: &str) -> String {
+ let host = host.trim();
+ let host = host
+ .rsplit_once(':')
+ .filter(|(_, port)| !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()))
+ .map_or(host, |(hostname, _)| hostname);
+ host.trim_end_matches('.').to_ascii_lowercase()
+}
+
+fn host_has_label(host: &str, label: &str) -> bool {
+ host.split('.').any(|candidate| candidate == label)
+}
+
+fn normalized_host_is_within(host: &str, domain: &str) -> bool {
+ host == domain || host.strip_suffix(domain).is_some_and(|p| p.ends_with('.'))
+}
+
+pub(super) fn host_is_within(host: &str, domain: &str) -> bool {
+ normalized_host_is_within(&normalized_hostname(host), domain)
+}
+
/// Identify the CI platform from a remote URL host ("github" / "gitlab" /
/// "gitea" / Azure DevOps).
-fn platform_from_url(url: &str) -> Option<CiPlatform> {
- let parsed = GitRemoteUrl::parse(url)?;
- if parsed.is_github() {
- Some(CiPlatform::GitHub)
- } else if parsed.is_gitlab() {
- Some(CiPlatform::GitLab)
- } else if parsed.is_gitea() {
- Some(CiPlatform::Gitea)
- } else if parsed.is_azure_devops() {
- Some(CiPlatform::AzureDevOps)
- } else {
- None
- }
+fn platform_from_url(url: &str) -> Option<ForgeKind> {
+ GitRemoteUrl::parse(url)?.forge_kind()
}
impl Repository {
@@ -51,7 +159,7 @@ impl Repository {
/// For a remote branch, pass its remote as `remote_hint` so the right
/// platform is picked in mixed-remote repos (e.g. GitHub + GitLab).
/// Effective URLs are used so `url.insteadOf` aliases resolve.
- pub fn ci_platform(&self, remote_hint: Option<&str>) -> Option<CiPlatform> {
+ pub fn ci_platform(&self, remote_hint: Option<&str>) -> Option<ForgeKind> {
if let Some(platform) = self.configured_ci_platform() {
return Some(platform);
}
@@ -75,12 +183,26 @@ impl Repository {
None
}
+ /// Return a diagnostic for a legacy branded SSH alias on the primary remote.
+ ///
+ /// A configured platform resolves the ambiguity and suppresses the
+ /// diagnostic. The returned value never participates in provider dispatch.
+ pub fn legacy_forge_alias(&self) -> Option<LegacyForgeAlias> {
+ if self.configured_ci_platform().is_some() {
+ return None;
+ }
+
+ let remote = self.primary_remote().ok()?;
+ let url = self.effective_remote_url(&remote)?;
+ LegacyForgeAlias::from_url(&url)
+ }
+
/// The CI platform set in project config (`forge.platform` / `ci.platform`).
///
/// `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<CiPlatform> {
+ fn configured_ci_platform(&self) -> Option<ForgeKind> {
*self.cache.configured_ci_platform.get_or_init(|| {
let raw = self
.project_config()
@@ -88,7 +210,7 @@ impl Repository {
.flatten()?
.forge_platform()
.map(str::to_string)?;
- match raw.parse::<CiPlatform>() {
+ match raw.parse::<ForgeKind>() {
Ok(platform) => {
tracing::debug!(platform = %platform, "Using CI platform from config: {platform}");
Some(platform)
@@ -111,31 +233,26 @@ mod tests {
#[test]
fn test_ci_platform_string_roundtrip() {
- assert_eq!(
- "github".parse::<CiPlatform>().ok(),
- Some(CiPlatform::GitHub)
- );
- assert_eq!(
- "gitlab".parse::<CiPlatform>().ok(),
- Some(CiPlatform::GitLab)
- );
- assert_eq!("gitea".parse::<CiPlatform>().ok(), Some(CiPlatform::Gitea));
+ for (forge, spelling) in [
+ (ForgeKind::GitHub, "github"),
+ (ForgeKind::GitLab, "gitlab"),
+ (ForgeKind::Gitea, "gitea"),
+ (ForgeKind::AzureDevOps, "azure-devops"),
+ ] {
+ assert_eq!(forge.to_string(), spelling);
+ assert_eq!(spelling.parse::<ForgeKind>().ok(), Some(forge));
+ }
+
// Azure DevOps accepts both spellings; `azure-devops` is canonical.
assert_eq!(
- "azure-devops".parse::<CiPlatform>().ok(),
- Some(CiPlatform::AzureDevOps)
+ "azuredevops".parse::<ForgeKind>().ok(),
+ Some(ForgeKind::AzureDevOps)
);
- assert_eq!(
- "azuredevops".parse::<CiPlatform>().ok(),
- Some(CiPlatform::AzureDevOps)
- );
- assert_eq!(CiPlatform::GitHub.to_string(), "github");
- assert_eq!(CiPlatform::GitLab.to_string(), "gitlab");
// Unrecognized values, including wrong case, must not parse.
- assert!("invalid".parse::<CiPlatform>().is_err());
- assert!("GITHUB".parse::<CiPlatform>().is_err());
- assert!("GitHub".parse::<CiPlatform>().is_err());
+ assert!("invalid".parse::<ForgeKind>().is_err());
+ assert!("GITHUB".parse::<ForgeKind>().is_err());
+ assert!("GitHub".parse::<ForgeKind>().is_err());
}
#[test]
@@ -149,7 +266,7 @@ mod tests {
"http://github.com/owner/repo.git",
"git://github.com/owner/repo.git",
] {
- assert_eq!(platform_from_url(url), Some(CiPlatform::GitHub), "{url}");
+ assert_eq!(platform_from_url(url), Some(ForgeKind::GitHub), "{url}");
}
// GitLab — various URL formats, plus self-hosted instances.
@@ -160,7 +277,7 @@ mod tests {
"http://gitlab.example.com/owner/repo.git",
"git://gitlab.mycompany.com/owner/repo.git",
] {
- assert_eq!(platform_from_url(url), Some(CiPlatform::GitLab), "{url}");
+ assert_eq!(platform_from_url(url), Some(ForgeKind::GitLab), "{url}");
}
// Gitea — gitea.com and self-hosted instances with "gitea" in the host.
@@ -168,7 +285,7 @@ mod tests {
"https://gitea.com/owner/repo.git",
"[email protected]:owner/repo.git",
] {
- assert_eq!(platform_from_url(url), Some(CiPlatform::Gitea), "{url}");
+ assert_eq!(platform_from_url(url), Some(ForgeKind::Gitea), "{url}");
}
// Azure DevOps — HTTPS, SSH, and the legacy visualstudio.com host.
@@ -179,7 +296,7 @@ mod tests {
] {
assert_eq!(
platform_from_url(url),
- Some(CiPlatform::AzureDevOps),
+ Some(ForgeKind::AzureDevOps),
"{url}"
);
}
@@ -195,4 +312,72 @@ mod tests {
None
);
}
+
+ #[test]
+ fn test_platform_from_url_uses_network_host_after_userinfo() {
+ for url in [
+ "https://[email protected]/owner/repo.git",
+ "http://[email protected]/owner/repo.git",
+ "git://[email protected]/owner/repo.git",
+ "ssh://[email protected]/owner/repo.git",
+ ] {
+ assert_eq!(platform_from_url(url), None, "{url}");
+ }
+ }
+
+ #[test]
+ fn test_fixed_azure_domains_take_precedence_over_forge_labels() {
+ for host in [
+ "github.dev.azure.com",
+ "gitlab.visualstudio.com",
+ "gitea.visualstudio.com:443",
+ "GITHUB.DEV.AZURE.COM.",
+ ] {
+ assert_eq!(
+ ForgeKind::from_host(host),
+ Some(ForgeKind::AzureDevOps),
+ "{host}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_legacy_forge_alias_is_diagnostic_only_for_branded_ssh_aliases() {
+ for (url, platform) in [
+ ("git@github-personal:owner/repo.git", ForgeKind::GitHub),
+ ("ssh://git@gitlab-work/owner/repo.git", ForgeKind::GitLab),
+ ("git@gitea-local:owner/repo.git", ForgeKind::Gitea),
+ ] {
+ let alias = LegacyForgeAlias::from_url(url).expect(url);
+ assert_eq!(alias.platform(), platform, "{url}");
+ assert_eq!(ForgeKind::from_host(alias.host()), None, "{url}");
+ }
+
+ for url in [
+ "[email protected]:owner/repo.git",
+ "git@work:owner/repo.git",
+ "git@notgithub-personal:owner/repo.git",
+ "[email protected]:owner/repo.git",
+ "[email protected]:owner/repo.git",
+ "https://github-personal/owner/repo.git",
+ ] {
+ assert_eq!(LegacyForgeAlias::from_url(url), None, "{url}");
+ }
+ }
+
+ #[test]
+ fn test_configured_platform_suppresses_legacy_alias_diagnostic() {
+ let test = crate::testing::TestRepo::new();
+ test.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "git@github-personal:owner/repo.git",
+ ]);
+ test.write_project_config("[forge]\nplatform = \"github\"\n");
+
+ let repo = Repository::at(test.root_path().to_path_buf()).unwrap();
+ assert_eq!(repo.ci_platform(None), Some(ForgeKind::GitHub));
+ assert_eq!(repo.legacy_forge_alias(), None);
+ }
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 8810d8028..2958ab1c8 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -36,12 +36,12 @@ use crate::styling::{
/// Platform-specific reference type (PR vs MR).
///
-/// Used to unify error handling for GitHub PRs and GitLab MRs.
+/// Used to unify error handling across supported forges.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefType {
- /// GitHub Pull Request
+ /// Pull request (GitHub, Gitea, or Azure DevOps)
Pr,
- /// GitLab Merge Request
+ /// GitLab merge request
Mr,
}
@@ -86,25 +86,6 @@ impl RefType {
}
}
-/// Common display fields for PR/MR context.
-///
-/// Implemented by both `PrInfo` and `MrInfo` to enable unified formatting.
-pub trait RefContext {
- fn ref_type(&self) -> RefType;
- fn number(&self) -> u32;
- fn title(&self) -> &str;
- fn author(&self) -> &str;
- fn state(&self) -> &str;
- fn draft(&self) -> bool;
- fn url(&self) -> &str;
-
- /// The source branch reference for display.
- ///
- /// For same-repo PRs/MRs: just the branch name (e.g., `feature-auth`)
- /// For fork PRs/MRs: `owner:branch` format (e.g., `contributor:feature-fix`)
- fn source_ref(&self) -> String;
-}
-
/// Multi-line styled rendering for terminal display.
///
/// See the module docstring for the contract: types implementing
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 0ef364cfe..d57d59b48 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -39,7 +39,7 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::ne
pub const NULL_OID: &str = "0000000000000000000000000000000000000000";
// Re-exports from submodules
-pub use ci_platform::CiPlatform;
+pub use ci_platform::{ForgeKind, LegacyForgeAlias};
pub(crate) use diff::DiffStats;
pub use diff::{LineDiff, parse_numstat_line};
pub use error::{
@@ -59,7 +59,6 @@ pub use error::{
// Special-handling error enum
HookErrorWithHint,
// Platform-specific reference type (PR vs MR)
- RefContext,
RefType,
// CLI context for enriching switch suggestions in error hints
SwitchSuggestionCtx,
diff --git a/src/git/remote_ref/azure.rs b/src/git/remote_ref/azure.rs
index 4d4ddb0aa..33abe4966 100644
--- a/src/git/remote_ref/azure.rs
+++ b/src/git/remote_ref/azure.rs
@@ -8,8 +8,9 @@ use serde::Deserialize;
use super::{CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error};
use crate::git::canonical_url_path_segment;
-use crate::git::url::GitRemoteUrl;
-use crate::git::{RefType, Repository};
+use crate::git::ci_platform::host_is_within;
+use crate::git::url::{GitRemoteUrl, authority_host};
+use crate::git::{ForgeKind, Repository};
use crate::shell_exec::Cmd;
/// Azure DevOps Pull Request provider.
@@ -17,12 +18,8 @@ use crate::shell_exec::Cmd;
pub struct AzureDevOpsProvider;
impl RemoteRefProvider for AzureDevOpsProvider {
- fn ref_type(&self) -> RefType {
- RefType::Pr
- }
-
- fn platform_label(&self) -> &'static str {
- "azure-devops"
+ fn forge_kind(&self) -> ForgeKind {
+ ForgeKind::AzureDevOps
}
fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
@@ -45,7 +42,7 @@ pub fn fork_remote_url(host: &str, organization: &str, project: &str, repo: &str
let organization = canonical_url_path_segment(organization);
let project = canonical_url_path_segment(project);
let repo = canonical_url_path_segment(repo);
- if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
+ if host_is_within(host, "visualstudio.com") {
format!("https://{}/{}/_git/{}", host, project, repo)
} else {
format!(
@@ -60,7 +57,7 @@ pub fn pr_web_url(host: &str, organization: &str, project: &str, repo: &str, pr:
let organization = canonical_url_path_segment(organization);
let project = canonical_url_path_segment(project);
let repo = canonical_url_path_segment(repo);
- if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
+ if host_is_within(host, "visualstudio.com") {
format!(
"https://{}/{}/_git/{}/pullrequest/{}",
host, project, repo, pr
@@ -77,7 +74,7 @@ pub fn pr_web_url(host: &str, organization: &str, project: &str, repo: &str, pr:
pub fn build_web_url(host: &str, organization: &str, project: &str, build_id: u32) -> String {
let organization = canonical_url_path_segment(organization);
let project = canonical_url_path_segment(project);
- if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
+ if host_is_within(host, "visualstudio.com") {
format!(
"https://{}/{}/_build/results?buildId={}",
host, project, build_id
@@ -169,8 +166,7 @@ fn detect_azure_target(repo: &Repository) -> Option<(String, String)> {
/// API host. Legacy `*.visualstudio.com` hosts keep their hostname (the API
/// accepts both forms).
pub fn az_org_url(host: &str, organization: &str) -> String {
- let lower = host.to_ascii_lowercase();
- if lower.ends_with(".visualstudio.com") {
+ if host_is_within(host, "visualstudio.com") {
format!("https://{}", host)
} else {
format!("https://dev.azure.com/{}", organization)
@@ -192,12 +188,12 @@ fn parse_web_url(web_url: Option<&str>) -> Option<(String, String)> {
let rest = url
.strip_prefix("https://")
.or_else(|| url.strip_prefix("http://"))?;
- let (host, path) = rest.split_once('/')?;
- let host_lower = host.to_ascii_lowercase();
- if host_lower == "dev.azure.com" {
+ let (authority, path) = rest.split_once('/')?;
+ let host = authority_host(authority)?;
+ if host_is_within(host, "dev.azure.com") {
let org = path.split('/').next().filter(|s| !s.is_empty())?;
Some((host.to_string(), org.to_string()))
- } else if host_lower.ends_with(".visualstudio.com") {
+ } else if host_is_within(host, "visualstudio.com") {
let org = host.split('.').next().filter(|s| !s.is_empty())?;
Some((host.to_string(), org.to_string()))
} else {
@@ -280,7 +276,7 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
// ("Please run 'az login' …") more reliably than a paraphrase keyed on
// a word that can occur anywhere in an org, project, or repo name.
return Err(cli_api_error(
- RefType::Pr,
+ ForgeKind::AzureDevOps.ref_type(),
format!("az repos pr show failed for PR #{}", pr_number),
&output,
));
@@ -340,7 +336,6 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
let pr_url = pr_web_url(&host, &organization, &project, &repo_name, pr_number);
Ok(RemoteRefInfo {
- ref_type: RefType::Pr,
number: pr_number,
title: response.title,
author: response.created_by.unique_name,
@@ -373,7 +368,7 @@ mod tests {
#[test]
fn test_ref_type() {
let provider = AzureDevOpsProvider;
- assert_eq!(provider.ref_type(), RefType::Pr);
+ assert_eq!(provider.ref_type(), crate::git::RefType::Pr);
}
#[test]
@@ -393,6 +388,12 @@ mod tests {
parsed,
Some(("myorg.visualstudio.com".to_string(), "myorg".to_string()))
);
+ assert_eq!(
+ parse_web_url(Some(
+ "https://user:[email protected]/myproject/_git/myrepo"
+ )),
+ Some(("myorg.visualstudio.com".to_string(), "myorg".to_string()))
+ );
}
#[test]
@@ -428,6 +429,32 @@ mod tests {
);
}
+ #[test]
+ fn legacy_url_builders_recognize_ports_and_trailing_root_dots() {
+ for host in ["myorg.visualstudio.com:443", "myorg.visualstudio.com."] {
+ assert_eq!(
+ fork_remote_url(host, "myorg", "myproject", "myrepo"),
+ format!("https://{host}/myproject/_git/myrepo"),
+ "{host}"
+ );
+ assert_eq!(
+ pr_web_url(host, "myorg", "myproject", "myrepo", 42),
+ format!("https://{host}/myproject/_git/myrepo/pullrequest/42"),
+ "{host}"
+ );
+ assert_eq!(
+ build_web_url(host, "myorg", "myproject", 7),
+ format!("https://{host}/myproject/_build/results?buildId=7"),
+ "{host}"
+ );
+ assert_eq!(
+ az_org_url(host, "myorg"),
+ format!("https://{host}"),
+ "{host}"
+ );
+ }
+ }
+
#[test]
fn test_az_org_url_format() {
assert_eq!(
diff --git a/src/git/remote_ref/gitea.rs b/src/git/remote_ref/gitea.rs
index 074def518..a80b696ec 100644
--- a/src/git/remote_ref/gitea.rs
+++ b/src/git/remote_ref/gitea.rs
@@ -7,9 +7,9 @@
//! `tea api <path>` does support `{owner}` and `{repo}` placeholders, but their
//! values come from `tea`'s own repo-context resolver, which depends on the
//! local git remote being a Gitea-accessible URL and on the user having set up
-//! `tea login add` first. We resolve owner/repo from the primary remote URL
-//! ourselves and pass an already-expanded path so the call works regardless of
-//! how `tea` resolves its own context.
+//! `tea login add` first. We resolve owner/repo from a matching Gitea remote
+//! and pass an already-expanded path so the call works regardless of how `tea`
+//! resolves its own context.
use anyhow::{Context, bail};
use serde::Deserialize;
@@ -18,19 +18,15 @@ use super::{
CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error,
extract_host_from_html_url, run_cli_api,
};
-use crate::git::{RefType, Repository};
+use crate::git::{ForgeKind, Repository};
/// Gitea Pull Request provider.
#[derive(Debug, Clone, Copy)]
pub struct GiteaProvider;
impl RemoteRefProvider for GiteaProvider {
- fn ref_type(&self) -> RefType {
- RefType::Pr
- }
-
- fn platform_label(&self) -> &'static str {
- "gitea"
+ fn forge_kind(&self) -> ForgeKind {
+ ForgeKind::Gitea
}
fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
@@ -124,7 +120,7 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
// stderr names which.
if !output.status.success() {
return Err(cli_api_error(
- RefType::Pr,
+ ForgeKind::Gitea.ref_type(),
format!("tea api failed for PR #{}", pr_number),
&output,
));
@@ -200,7 +196,6 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
is_cross_repo.then(|| fork_remote_url(&host, &head_repo.owner.login, &head_repo.name));
Ok(RemoteRefInfo {
- ref_type: RefType::Pr,
number: pr_number,
title: response.title,
author: response.user.login,
@@ -360,7 +355,7 @@ mod tests {
#[test]
fn test_ref_type() {
let provider = GiteaProvider;
- assert_eq!(provider.ref_type(), RefType::Pr);
+ assert_eq!(provider.ref_type(), crate::git::RefType::Pr);
}
#[test]
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rs
index 76ef20f44..6fa16bc71 100644
--- a/src/git/remote_ref/github.rs
+++ b/src/git/remote_ref/github.rs
@@ -11,7 +11,7 @@ use super::{
CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,
extract_host_from_html_url, run_cli_api,
};
-use crate::git::{RefType, Repository};
+use crate::git::{ForgeKind, Repository};
use crate::shell_exec::Cmd;
/// GitHub Pull Request provider.
@@ -19,12 +19,8 @@ use crate::shell_exec::Cmd;
pub struct GitHubProvider;
impl RemoteRefProvider for GitHubProvider {
- fn ref_type(&self) -> RefType {
- RefType::Pr
- }
-
- fn platform_label(&self) -> &'static str {
- "github"
+ fn forge_kind(&self) -> ForgeKind {
+ ForgeKind::GitHub
}
fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
@@ -168,14 +164,14 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
or configure a different primary remote."
};
return Err(cli_api_error(
- RefType::Pr,
+ ForgeKind::GitHub.ref_type(),
format!("PR #{pr_number} not found on {owner}/{repo_name} ({source}). {hint}"),
&output,
));
}
return Err(cli_api_error(
- RefType::Pr,
+ ForgeKind::GitHub.ref_type(),
format!("gh api failed for PR #{}", pr_number),
&output,
));
@@ -221,7 +217,6 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
is_cross_repo.then(|| fork_remote_url(&host, &head_repo.owner.login, &head_repo.name));
Ok(RemoteRefInfo {
- ref_type: RefType::Pr,
number: pr_number,
title: response.title,
author: response.user.login,
@@ -285,7 +280,7 @@ mod tests {
#[test]
fn test_ref_type() {
let provider = GitHubProvider;
- assert_eq!(provider.ref_type(), RefType::Pr);
+ assert_eq!(provider.ref_type(), crate::git::RefType::Pr);
}
#[test]
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rs
index 543b1f969..ae67a890a 100644
--- a/src/git/remote_ref/gitlab.rs
+++ b/src/git/remote_ref/gitlab.rs
@@ -30,19 +30,15 @@ use super::{
CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,
run_cli_api,
};
-use crate::git::{RefType, Repository};
+use crate::git::{ForgeKind, Repository};
/// GitLab Merge Request provider.
#[derive(Debug, Clone, Copy)]
pub struct GitLabProvider;
impl RemoteRefProvider for GitLabProvider {
- fn ref_type(&self) -> RefType {
- RefType::Mr
- }
-
- fn platform_label(&self) -> &'static str {
- "gitlab"
+ fn forge_kind(&self) -> ForgeKind {
+ ForgeKind::GitLab
}
fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
@@ -99,7 +95,7 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn
// matching prose — and there is nothing to say afterwards that glab's own
// line doesn't already: `glab: 401 Unauthorized (HTTP 401)`. Forward it.
return Err(cli_api_error(
- RefType::Mr,
+ ForgeKind::GitLab.ref_type(),
format!("glab api failed for MR !{}", mr_number),
&output,
));
@@ -137,7 +133,6 @@ fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefIn
// Use fetch_gitlab_project_urls() when URLs are actually needed.
Ok(RemoteRefInfo {
- ref_type: RefType::Mr,
number: mr_number,
title: response.title,
author: response.author.username,
@@ -278,7 +273,7 @@ mod tests {
#[test]
fn test_ref_type() {
let provider = GitLabProvider;
- assert_eq!(provider.ref_type(), RefType::Mr);
+ assert_eq!(provider.ref_type(), crate::git::RefType::Mr);
}
#[test]
@@ -302,7 +297,6 @@ mod tests {
#[test]
fn test_fetch_gitlab_project_urls_rejects_github_ref() {
let github_info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 123,
title: "Test PR".to_string(),
author: "user".to_string(),
diff --git a/src/git/remote_ref/info.rs b/src/git/remote_ref/info.rs
index f3c66b9d4..5b4e98f2a 100644
--- a/src/git/remote_ref/info.rs
+++ b/src/git/remote_ref/info.rs
@@ -2,7 +2,7 @@
//!
//! Provides unified types for PR/MR metadata across platforms.
-use crate::git::{RefContext, RefType};
+use crate::git::{ForgeKind, RefType};
/// Platform-specific data for a remote ref.
///
@@ -61,14 +61,24 @@ pub enum PlatformData {
},
}
+impl PlatformData {
+ /// The forge represented by this platform-specific payload.
+ pub const fn forge_kind(&self) -> ForgeKind {
+ match self {
+ Self::GitHub { .. } => ForgeKind::GitHub,
+ Self::Gitea { .. } => ForgeKind::Gitea,
+ Self::GitLab { .. } => ForgeKind::GitLab,
+ Self::AzureDevOps { .. } => ForgeKind::AzureDevOps,
+ }
+ }
+}
+
/// Unified information about a PR or MR.
///
/// This struct contains all the data needed to create a local branch
/// for a PR/MR, regardless of platform.
#[derive(Debug, Clone)]
pub struct RemoteRefInfo {
- /// The reference type (PR or MR).
- pub ref_type: RefType,
/// The PR/MR number.
pub number: u32,
/// The PR/MR title.
@@ -91,36 +101,14 @@ pub struct RemoteRefInfo {
pub platform_data: PlatformData,
}
-impl RefContext for RemoteRefInfo {
- fn ref_type(&self) -> RefType {
- self.ref_type
- }
-
- fn number(&self) -> u32 {
- self.number
- }
-
- fn title(&self) -> &str {
- &self.title
- }
-
- fn author(&self) -> &str {
- &self.author
- }
-
- fn state(&self) -> &str {
- &self.state
- }
-
- fn draft(&self) -> bool {
- self.draft
- }
-
- fn url(&self) -> &str {
- &self.url
+impl RemoteRefInfo {
+ /// Whether this forge calls the change request a PR or an MR.
+ pub const fn ref_type(&self) -> RefType {
+ self.platform_data.forge_kind().ref_type()
}
- fn source_ref(&self) -> String {
+ /// The source branch reference for display.
+ pub fn source_ref(&self) -> String {
if self.is_cross_repo {
// Try to extract owner for display
match &self.platform_data {
@@ -148,9 +136,7 @@ impl RefContext for RemoteRefInfo {
self.source_branch.clone()
}
}
-}
-impl RemoteRefInfo {
/// Generate a prefixed local branch name for when the unprefixed name conflicts.
///
/// Returns `<owner>/<branch>` (e.g., `contributor/main`).
@@ -207,7 +193,6 @@ mod tests {
#[test]
fn test_source_ref_same_repo() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 101,
title: "Fix bug".to_string(),
author: "alice".to_string(),
@@ -225,13 +210,13 @@ mod tests {
base_repo: "repo".to_string(),
},
};
+ assert_eq!(info.ref_type(), RefType::Pr);
assert_eq!(info.source_ref(), "feature-auth");
}
#[test]
fn test_source_ref_fork_gitea() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 42,
title: "Add feature".to_string(),
author: "contributor".to_string(),
@@ -249,13 +234,13 @@ mod tests {
base_repo: "repo".to_string(),
},
};
+ assert_eq!(info.ref_type(), RefType::Pr);
assert_eq!(info.source_ref(), "contributor:feature-fix");
}
#[test]
fn test_source_ref_fork_github() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 42,
title: "Add feature".to_string(),
author: "contributor".to_string(),
@@ -279,7 +264,6 @@ mod tests {
#[test]
fn test_source_ref_fork_gitlab() {
let info = RemoteRefInfo {
- ref_type: RefType::Mr,
number: 101,
title: "Fix bug".to_string(),
author: "contributor".to_string(),
@@ -297,13 +281,13 @@ mod tests {
target_project_id: 123,
},
};
+ assert_eq!(info.ref_type(), RefType::Mr);
assert_eq!(info.source_ref(), "contributor:feature-fix");
}
#[test]
fn test_prefixed_local_branch_name_github() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 101,
title: "Test".to_string(),
author: "contributor".to_string(),
@@ -330,7 +314,6 @@ mod tests {
#[test]
fn test_prefixed_local_branch_name_gitea() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 101,
title: "Test".to_string(),
author: "contributor".to_string(),
@@ -357,7 +340,6 @@ mod tests {
#[test]
fn test_prefixed_local_branch_name_gitlab() {
let info = RemoteRefInfo {
- ref_type: RefType::Mr,
number: 101,
title: "Test".to_string(),
author: "contributor".to_string(),
@@ -424,7 +406,6 @@ mod tests {
#[test]
fn test_source_ref_azure_same_repo() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 550,
title: "Add ACH mandate support".to_string(),
author: "crogers".to_string(),
@@ -447,7 +428,6 @@ mod tests {
#[test]
fn test_prefixed_local_branch_name_azure() {
let info = RemoteRefInfo {
- ref_type: RefType::Pr,
number: 550,
title: "Test".to_string(),
author: "crogers".to_string(),
diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rs
index 8280df61a..c307b5b76 100644
--- a/src/git/remote_ref/mod.rs
+++ b/src/git/remote_ref/mod.rs
@@ -71,7 +71,7 @@
//!
//! Uses `tea api repos/{owner}/{repo}/pulls/<number>`. Unlike `gh`, `tea`'s
//! `{owner}`/`{repo}` template expansion depends on local repo context, so the
-//! provider resolves owner/repo from the primary remote URL and passes a
+//! provider resolves owner/repo from a matching Gitea remote and passes a
//! pre-expanded path.
//!
//! ## Azure DevOps
@@ -98,8 +98,10 @@ use std::process::Output;
use anyhow::{Context, bail};
+use crate::git::ci_platform::{host_is_within, normalized_hostname};
use crate::git::error::GitError;
-use crate::git::{GitRepoInfo, GitRepoProvider, RefType, Repository};
+use crate::git::url::authority_host;
+use crate::git::{ForgeKind, GitRepoInfo, GitRepoProvider, RefType, Repository};
use crate::shell_exec::Cmd;
/// Provider trait for platform-specific PR/MR operations.
@@ -107,15 +109,13 @@ use crate::shell_exec::Cmd;
/// Each platform (GitHub, Gitea, GitLab, Azure DevOps) implements this trait to
/// provide unified access to PR/MR metadata and ref paths.
pub trait RemoteRefProvider {
- /// The reference type this provider handles.
- fn ref_type(&self) -> RefType;
+ /// The forge whose API and ref namespace this provider implements.
+ fn forge_kind(&self) -> ForgeKind;
- /// Short, stable identifier for the platform — `"github"`, `"gitea"`,
- /// `"gitlab"`, or `"azure-devops"`. Useful for diagnostic logging and for
- /// tests that need to verify which provider was selected (the other trait
- /// methods don't distinguish GitHub, Gitea, and Azure DevOps — all three
- /// use `RefType::Pr` and `pull/{N}/head`).
- fn platform_label(&self) -> &'static str;
+ /// The reference type this provider handles.
+ fn ref_type(&self) -> RefType {
+ self.forge_kind().ref_type()
+ }
/// Fetch ref information from the platform API.
///
@@ -194,28 +194,6 @@ pub(super) fn cli_api_error(ref_type: RefType, message: String, output: &Output)
.into()
}
-/// Whether `host` is `domain` itself or a subdomain of it.
-///
-/// Compared label-wise, so `dev.azure.com` matches `dev.azure.com` and
-/// `x.dev.azure.com` but not `dev.azure.com.attacker.example` or
-/// `notdev.azure.com` — a plain substring test accepts an attacker-chosen host
-/// that merely contains the domain.
-fn host_is_within(host: &str, domain: &str) -> bool {
- let host = host.to_ascii_lowercase();
- host == domain || host.strip_suffix(domain).is_some_and(|p| p.ends_with('.'))
-}
-
-/// Whether any dot-separated label of `host` is exactly `label`.
-///
-/// Recognizes both `github.com` and the usual self-hosted naming
-/// (`github.corp.example`) without matching a host that merely spells the name
-/// inside a longer label, such as a `github-mirror.example` running something
-/// else. A deployment this misses names its provider explicitly — see
-/// `provider_override`.
-fn host_has_label(host: &str, label: &str) -> bool {
- host.to_ascii_lowercase().split('.').any(|l| l == label)
-}
-
/// Extract the host (e.g. `github.com`) from a PR/MR `html_url` returned by
/// the forge API. Both GitHub and Gitea responses use the same `https://host/...`
/// shape, so we share the parser.
@@ -223,8 +201,8 @@ pub(super) fn extract_host_from_html_url(html_url: &str) -> anyhow::Result<Strin
html_url
.strip_prefix("https://")
.or_else(|| html_url.strip_prefix("http://"))
- .and_then(|s| s.split('/').next())
- .filter(|h| !h.is_empty())
+ .and_then(|rest| rest.split(['/', '?', '#']).next())
+ .and_then(authority_host)
.map(String::from)
.with_context(|| format!("Failed to parse host from PR URL: {html_url}"))
}
@@ -467,14 +445,20 @@ pub fn repo_info_from_ref_url_with_provider(
if repo_segments.len() < 3 {
return None;
}
- let url = format!("{}://{}", parts.scheme, repo_segments.join("/"));
- let host = repo_segments[0].to_string();
+ let host = authority_host(repo_segments[0])?.to_string();
+ let url = format!(
+ "{}://{}/{}",
+ parts.scheme,
+ host,
+ repo_segments[1..].join("/")
+ );
let marker = parts.segments[parts.marker_index];
- let provider_override = GitRepoProvider::from_platform(provider_override);
+ let provider_override = provider_override.and_then(|value| value.parse::<ForgeKind>().ok());
let provider = match marker {
"pull" => {
- if provider_override == Some(GitRepoProvider::GitHub) || host_has_label(&host, "github")
+ if provider_override == Some(ForgeKind::GitHub)
+ || ForgeKind::from_host(&host) == Some(ForgeKind::GitHub)
{
GitRepoProvider::GitHub
} else {
@@ -484,9 +468,8 @@ pub fn repo_info_from_ref_url_with_provider(
"pulls" => GitRepoProvider::Gitea,
"merge_requests" => GitRepoProvider::GitLab,
"pullrequest" => {
- if provider_override == Some(GitRepoProvider::AzureDevOps)
- || host_is_within(&host, "dev.azure.com")
- || host_is_within(&host, "visualstudio.com")
+ if provider_override == Some(ForgeKind::AzureDevOps)
+ || ForgeKind::from_host(&host) == Some(ForgeKind::AzureDevOps)
{
GitRepoProvider::AzureDevOps
} else {
@@ -497,7 +480,7 @@ pub fn repo_info_from_ref_url_with_provider(
};
if provider == GitRepoProvider::AzureDevOps {
- let allow_generic_host = provider_override == Some(GitRepoProvider::AzureDevOps);
+ let allow_generic_host = provider_override == Some(ForgeKind::AzureDevOps);
if let Some((owner, project, name)) =
azure_repo_segments(&host, &repo_segments[1..], allow_generic_host)
{
@@ -543,24 +526,24 @@ fn azure_repo_segments(
segments: &[&str],
allow_generic_host: bool,
) -> Option<(String, String, String)> {
- let host_lower = host.to_ascii_lowercase();
- if host_lower == "dev.azure.com" {
- if segments.len() >= 4 && segments.get(2) == Some(&"_git") {
+ let host_lower = normalized_hostname(host);
+ if host_lower == "ssh.dev.azure.com" {
+ if segments.len() >= 4 && segments.first() == Some(&"v3") {
return Some((
- segments[0].to_string(),
segments[1].to_string(),
+ segments[2].to_string(),
segments[3].to_string(),
));
}
- } else if host_lower == "ssh.dev.azure.com" {
- if segments.len() >= 4 && segments.first() == Some(&"v3") {
+ } else if host_is_within(&host_lower, "dev.azure.com") {
+ if segments.len() >= 4 && segments.get(2) == Some(&"_git") {
return Some((
+ segments[0].to_string(),
segments[1].to_string(),
- segments[2].to_string(),
segments[3].to_string(),
));
}
- } else if host_lower.ends_with(".visualstudio.com") {
+ } else if host_is_within(&host_lower, "visualstudio.com") {
if segments.len() >= 3 && segments.get(1) == Some(&"_git") {
let organization = host.split('.').next()?.to_string();
return Some((
@@ -584,28 +567,18 @@ mod tests {
use super::*;
#[test]
- fn test_host_matching_respects_label_boundaries() {
- // The domain itself and subdomains of it.
- assert!(host_is_within("dev.azure.com", "dev.azure.com"));
- assert!(host_is_within("DEV.AZURE.COM", "dev.azure.com"));
- assert!(host_is_within("myorg.visualstudio.com", "visualstudio.com"));
- // A host that only spells the domain inside a longer name. A substring
- // test takes each of these for Azure DevOps.
- assert!(!host_is_within(
- "dev.azure.com.attacker.example",
- "dev.azure.com"
- ));
- assert!(!host_is_within("notdev.azure.com", "dev.azure.com"));
- assert!(!host_is_within("evil-visualstudio.com", "visualstudio.com"));
-
- // github.com and the usual self-hosted naming.
- assert!(host_has_label("github.com", "github"));
- assert!(host_has_label("github.corp.example", "github"));
- assert!(host_has_label("git.github.corp.example", "github"));
- // Spelled inside a longer label: not GitHub.
- assert!(!host_has_label("github-mirror.example", "github"));
- assert!(!host_has_label("mygithubmirror.com", "github"));
- assert!(!host_has_label("notgithub.io", "github"));
+ fn api_url_host_uses_the_network_host_after_userinfo() {
+ assert_eq!(
+ extract_host_from_html_url("https://[email protected]/owner/repo/pull/1")
+ .unwrap(),
+ "attacker.example"
+ );
+ assert_eq!(
+ extract_host_from_html_url("http://user:[email protected]:8443/owner/repo/pull/1")
+ .unwrap(),
+ "github.com:8443"
+ );
+ assert!(extract_host_from_html_url("https://github.com@/owner/repo/pull/1").is_err());
}
#[test]
@@ -864,6 +837,46 @@ mod tests {
assert_eq!(info.project, None);
}
+ #[test]
+ fn repo_info_from_ref_url_respects_host_boundaries_and_ports() {
+ let github = repo_info_from_ref_url("https://github.com:8443/owner/repo/pull/1")
+ .expect("GitHub PR URL");
+ assert_eq!(github.provider, GitRepoProvider::GitHub);
+
+ let azure = repo_info_from_ref_url(
+ "https://dev.azure.com:8443/org/project/_git/repo/pullrequest/9",
+ )
+ .expect("Azure DevOps PR URL");
+ assert_eq!(azure.provider, GitRepoProvider::AzureDevOps);
+ assert_eq!(azure.owner, "org");
+ assert_eq!(azure.project.as_deref(), Some("project"));
+
+ let azure_with_forge_label = repo_info_from_ref_url(
+ "https://github.dev.azure.com/org/project/_git/repo/pullrequest/9",
+ )
+ .expect("Azure DevOps PR URL");
+ assert_eq!(
+ azure_with_forge_label.provider,
+ GitRepoProvider::AzureDevOps
+ );
+
+ let hostile_userinfo =
+ repo_info_from_ref_url("https://[email protected]/owner/repo/pull/1")
+ .expect("ref URL is structurally valid");
+ assert_eq!(hostile_userinfo.provider, GitRepoProvider::Unknown);
+ assert_eq!(hostile_userinfo.host, "attacker.example");
+ assert_eq!(hostile_userinfo.url, "https://attacker.example/owner/repo");
+
+ for input in [
+ "https://github-mirror.example/owner/repo/pull/1",
+ "https://dev.azure.com.attacker.example/org/project/_git/repo/pullrequest/9",
+ "https://evil-visualstudio.com/org/project/_git/repo/pullrequest/9",
+ ] {
+ let info = repo_info_from_ref_url(input).expect("ref URL is structurally valid");
+ assert_eq!(info.provider, GitRepoProvider::Unknown, "{input}");
+ }
+ }
+
#[test]
fn repo_info_from_ref_url_uses_configured_github_for_opaque_host() {
let input = "https://git.example.com/owner/repo/pull/1";
diff --git a/src/git/remove.rs b/src/git/remove.rs
index b659e9c18..d0ec9b55e 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -68,7 +68,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::git::repository::WorkingTree;
-use crate::git::{IntegrationReason, Repository};
+use crate::git::{IntegrationReason, Repository, WorktreeInfo};
use crate::shell_exec::Cmd;
use crate::utils::epoch_now;
@@ -229,6 +229,10 @@ impl BranchDeletionMode {
pub enum BranchDeletionOutcome {
/// Branch was not deleted — it was not integrated, and deletion was not forced.
NotDeleted,
+ /// Branch was integrated, but a fresh topology read found it checked out in
+ /// a worktree immediately before deletion. The ref is retained so that
+ /// worktree's HEAD remains resolvable.
+ RetainedCheckedOut { path: PathBuf },
/// Branch was integrated but the atomic compare-and-swap deletion was
/// rejected because the ref moved between the integration check and the
/// delete attempt — e.g. a hook or concurrent process advanced it. The
@@ -421,13 +425,14 @@ pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option
/// site that doesn't already hold a fresh snapshot (the background fast path,
/// prune's synchronous fallback, branch-only removal, a picker row). The
/// invariant it carries — no deletion ever runs against the planning-time
-/// snapshot, so the CAS in [`delete_branch_if_safe`] re-decides against the
-/// live ref — also holds on the two paths that don't call it: the foreground
-/// removal captures its own fresh snapshot just before
+/// snapshot, so the topology guard and CAS in [`delete_branch_if_safe`]
+/// re-decide against live state — also holds on the two paths that don't call
+/// it: the foreground removal captures its own fresh snapshot just before
/// [`remove_worktree_with_cleanup`], and the detached fallback can't call
-/// Rust, so it gets the guarantee from an `update-ref -d <ref> <sha>` shell
-/// tail instead. A hook or concurrent process that advanced the branch since
-/// planning surfaces as `RetainedRaced`, not a lost commit.
+/// Rust, so it gets the guarantee from a fresh porcelain topology read followed
+/// by an `update-ref -d <ref> <sha>` shell tail instead. A hook or concurrent
+/// process that checked out or advanced the branch since planning retains it,
+/// rather than orphaning a worktree or losing a commit.
pub fn execute_branch_deletion(
repo: &Repository,
branch_name: &str,
@@ -447,7 +452,8 @@ pub fn execute_branch_deletion(
///
/// Returns a [`BranchDeletionResult`] rather than raising an error for the
/// "not integrated" case — that's a normal outcome and the caller decides how
-/// to surface it. Only `git branch -D` failures propagate as `Err`.
+/// to surface it. Failures to read current topology or run the Git mutation
+/// propagate as `Err`.
pub fn delete_branch_if_safe(
repo: &Repository,
snapshot: &crate::git::RefSnapshot,
@@ -469,6 +475,24 @@ pub fn delete_branch_if_safe(
let outcome = match reason {
Some(r) => {
+ // `update-ref` deliberately bypasses `git branch`'s checked-out
+ // branch protection, so sample topology from a brand-new
+ // Repository immediately before the ref mutation. Never consult
+ // `repo.list_worktrees()` here: callers often used that planning
+ // cache before a pre-remove hook or another process had a chance to
+ // add a checkout.
+ //
+ // Git exposes no transaction spanning worktree registration and ref
+ // updates. Keeping this fresh read directly adjacent to the CAS
+ // minimizes that unavoidable TOCTOU window; either command failing
+ // leaves the branch intact.
+ if let Some(path) = fresh_branch_checkout(repo, branch_name)? {
+ return Ok(BranchDeletionResult {
+ outcome: BranchDeletionOutcome::RetainedCheckedOut { path },
+ integration_target: effective_target,
+ });
+ }
+
// Atomic compare-and-swap against the snapshotted SHA. If the ref
// moved between `integration_reason` and the delete (e.g. a hook
// advanced the branch), `git update-ref -d <ref> <expected>` fails
@@ -501,6 +525,36 @@ pub fn delete_branch_if_safe(
})
}
+/// Find a live checkout of `branch` using a new repository cache.
+///
+/// Removal planning intentionally caches `git worktree list`, but branch
+/// deletion happens after hooks and other concurrent actors may have changed
+/// topology. Constructing a new [`Repository`] is the cache boundary: its first
+/// `list_worktrees` call executes a fresh `git worktree list --porcelain`.
+///
+/// Git still lists stale registrations whose directories are gone, marking
+/// them `prunable`; those have no live checkout to orphan and must not strand
+/// the branch. Missing locked worktrees remain non-prunable, so their lock
+/// continues to retain the branch conservatively.
+fn fresh_branch_checkout(repo: &Repository, branch_name: &str) -> anyhow::Result<Option<PathBuf>> {
+ let fresh_repo = Repository::at(repo.discovery_path())?;
+ Ok(fresh_repo
+ .list_worktrees()?
+ .iter()
+ .find(|worktree| branch_checkout_requires_retention(worktree, branch_name))
+ .map(|worktree| worktree.path.clone()))
+}
+
+/// Whether deleting `branch` would risk orphaning this worktree record.
+///
+/// Git normally reports a missing locked worktree as `locked` but not
+/// `prunable`. Letting the lock win explicitly keeps the guard fail-closed if a
+/// Git version or synthetic porcelain record ever carries both fields.
+fn branch_checkout_requires_retention(worktree: &WorktreeInfo, branch_name: &str) -> bool {
+ worktree.branch.as_deref() == Some(branch_name)
+ && (!worktree.is_prunable() || worktree.locked.is_some())
+}
+
/// Atomically delete `refs/heads/<branch>` iff it currently points at
/// `expected_sha`, and translate the result into a [`BranchDeletionOutcome`].
///
@@ -666,6 +720,51 @@ mod tests {
);
}
+ /// ForceDelete remains a direct `git branch -D` operation. If topology
+ /// changes after planning, Git's own checked-out-branch protection rejects
+ /// it rather than the SafeDelete topology guard translating it into a
+ /// retained outcome.
+ #[test]
+ fn force_delete_uses_git_checkout_protection() {
+ let test = TestRepo::with_initial_commit();
+ test.create_branch("feature");
+ let repo = Repository::at(test.root_path()).unwrap();
+ let snapshot = repo.capture_refs().unwrap();
+
+ let checkout = test.home_path().join("repo.feature-force-race");
+ test.run_git(&["worktree", "add", checkout.to_str().unwrap(), "feature"]);
+
+ assert!(
+ delete_branch_if_safe(&repo, &snapshot, "feature", "main", true).is_err(),
+ "git branch -D must refuse a branch checked out after planning"
+ );
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
+ .is_ok(),
+ "Git's refusal must preserve the branch"
+ );
+ }
+
+ /// A lock is the user's explicit protection for a temporarily absent
+ /// worktree. It must win even over a synthetic record that is also marked
+ /// prunable; an ordinary unlocked prunable record remains stale.
+ #[test]
+ fn locked_prunable_checkout_still_requires_retention() {
+ let mut worktree = WorktreeInfo {
+ path: PathBuf::from("/missing/feature"),
+ head: "0123456789abcdef".to_string(),
+ branch: Some("feature".to_string()),
+ bare: false,
+ detached: false,
+ locked: Some("detachable media".to_string()),
+ prunable: Some("gitdir file points to non-existent location".to_string()),
+ };
+
+ assert!(branch_checkout_requires_retention(&worktree, "feature"));
+ worktree.locked = None;
+ assert!(!branch_checkout_requires_retention(&worktree, "feature"));
+ }
+
/// When the branch ref vanishes between snapshot capture and the CAS
/// delete, `git update-ref -d` fails *and* the ref is already absent, so
/// the outcome is a real error (propagated) — distinct from the
@@ -733,6 +832,12 @@ mod tests {
// Ensure the match patterns work correctly
let outcomes = [
(BranchDeletionOutcome::NotDeleted, false),
+ (
+ BranchDeletionOutcome::RetainedCheckedOut {
+ path: PathBuf::from("/tmp/feature"),
+ },
+ false,
+ ),
(BranchDeletionOutcome::RetainedRaced, false),
(BranchDeletionOutcome::ForceDeleted, true),
(
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 3358cbc20..05ede0aeb 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -139,7 +139,7 @@ use dunce::canonicalize;
use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};
// Import types from parent module
-use super::{CiPlatform, CommandError, DefaultBranchName, GitError, LineDiff, WorktreeInfo};
+use super::{CommandError, DefaultBranchName, ForgeKind, GitError, LineDiff, WorktreeInfo};
// Re-export types needed by submodules
pub(super) use super::{
@@ -252,7 +252,7 @@ pub(super) struct RepoCache {
/// `None` when unset or unrecognized; an unrecognized value warns once,
/// deduplicating the warning across the many branches `wt list` probes.
/// Resolved via [`Repository::ci_platform`].
- pub(super) configured_ci_platform: OnceCell<Option<CiPlatform>>,
+ pub(super) configured_ci_platform: OnceCell<Option<ForgeKind>>,
/// User config (raw, as loaded from disk).
/// Populated by [`Repository::at`] from the
/// [`WORKTRUNK_USER_CONFIG_PRELOAD`] preload when prewarm ran; otherwise
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index e46a1dea2..16dc25556 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -2,52 +2,34 @@
//!
//! # Forge detection
//!
-//! Worktrunk needs three pieces of information to talk to GitHub/GitLab:
+//! Forge-aware operations need three pieces of information:
//!
-//! 1. **Platform** — GitHub or GitLab (which CLI to invoke)
-//! 2. **Owner/repo** — the project path (for API calls)
-//! 3. **API hostname** — which server to talk to (only needed for GHE /
-//! self-hosted GitLab; `gh`/`glab` default to github.com/gitlab.com)
+//! 1. **Forge** — GitHub, GitLab, Gitea, or Azure DevOps
+//! 2. **Repository identity** — the owner/namespace and repository path
+//! 3. **API hostname** — needed when a CLI cannot infer a self-hosted server
//!
-//! ## Design principle
+//! [`ForgeKind::from_host`](crate::git::ForgeKind::from_host) is the canonical host
+//! classifier. Azure DevOps service domains use domain-suffix matching and
+//! take precedence over forge-like labels within those domains. GitHub, GitLab,
+//! and Gitea require the forge name as a complete DNS label. Matching ignores
+//! case, numeric ports, and a trailing DNS root dot.
//!
-//! Derive owner/repo from URL paths, not hostnames. SSH aliases only
-//! corrupt the host component — the path (`owner/repo`) is always real.
-//! Only use the hostname for platform detection (substring match), and
-//! let `gh`/`glab` default to the right API host unless overridden.
+//! Repository identity comes from the URL path. This keeps owner/repository
+//! extraction valid when an SSH alias replaces the hostname.
//!
-//! **Resolution order:**
+//! Remote selection depends on the operation:
//!
-//! 1. **Remote** — branch's remote (for remote branches) >
-//! [`primary_remote()`](Repository::primary_remote)
-//! 2. **Platform** — `forge.platform` config > hostname substring match
-//! ([`is_github()`](super::GitRemoteUrl::is_github) /
-//! [`is_gitlab()`](super::GitRemoteUrl::is_gitlab)) on effective URL
-//! 3. **Owner/repo** — parsed from the chosen remote's URL path (works
-//! regardless of hostname, including SSH aliases)
-//! 4. **API hostname** — `forge.hostname` config > omit (let CLI default)
-//!
-//! For `wt list`, steps 1-4 are sufficient — each branch uses its
-//! associated remote.
-//!
-//! For `wt switch pr:N`, the API call uses owner/repo from the primary
-//! remote's raw URL. The API response provides the base repo's identity,
-//! and `Repository::find_remote_for_repo` matches it back to a local remote by
-//! owner/repo (host is not required to match).
-//!
-//! ## Where each piece is used
-//!
-//! | Need | `wt switch pr:N` | `wt list` CI status |
-//! |------|------------------|---------------------|
-//! | Platform | Implicit (`pr:` = GitHub, `mr:` = GitLab) | `Repository::ci_platform` |
-//! | Owner/repo | `fetch_pr_info` builds API path | `github_owner_repo` for check-runs API |
-//! | API hostname | `forge.hostname` config, else omit | `forge.hostname` config, else omit |
-//! | Fetch remote | `Repository::find_remote_for_repo` by owner/repo | Not needed |
+//! - [`Repository::ci_platform`] uses `forge.platform`, then the hinted
+//! remote's effective URL, then the primary remote's effective URL.
+//! - `wt switch pr:N` honors `forge.platform`, then scans every raw remote
+//! using an explicit provider priority. Its provider owns the final fallback.
+//! - Forge API calls extract repository identity from a matching raw remote.
+//! API responses are matched back to local remotes by repository identity.
//!
//! ## Config: `[forge]` section
//!
-//! All fields are optional. For most repositories (single remote, hostname
-//! contains "github" or "gitlab"), no configuration is needed.
+//! All fields are optional. Standard service hosts and self-hosted names with
+//! an exact `github`, `gitlab`, or `gitea` label need no platform override.
//!
//! ```toml
//! [forge]
@@ -60,25 +42,14 @@
//! ## SSH host aliases
//!
//! Multi-account SSH setups use host aliases (`git@github-personal:owner/repo`)
-//! where SSH resolves `github-personal` → `github.com` via `~/.ssh/config`.
+//! where SSH resolves `github-personal` to `github.com` via `~/.ssh/config`.
//! Git operations work, but the literal hostname affects forge detection.
//!
-//! Owner/repo extraction is unaffected — aliases only change the host, not
-//! the path. The impact depends on the alias name:
-//!
-//! | Alias | Platform detection | API calls | Config needed |
-//! |-------|-------------------|-----------|---------------|
-//! | `github-personal` | Works ("github" in name) | Works (`gh` defaults to github.com) | None |
-//! | `work` (opaque) | Fails | Works (`gh` defaults to github.com) | `forge.platform` |
-//! | GHE alias | May work | Needs explicit host | `forge.hostname` (+ `forge.platform` if opaque) |
-//!
-//! ### `url.insteadOf` (alternative)
-//!
-//! Git's `url.insteadOf` rewrites URLs before any tool sees them, which
-//! solves all detection problems. Trade-off: it also affects SSH, which
-//! sees `github.com` instead of the alias and can't select the correct
-//! `IdentityFile`. Users must pair it with per-repo `core.sshCommand`.
-//! The `[forge]` config avoids this trade-off.
+//! Owner/repo extraction is unaffected because aliases only change the host.
+//! An alias with an exact forge label, such as `github.personal`, classifies
+//! automatically. Hyphenated and opaque aliases, such as `github-personal` or
+//! `work`, need `forge.platform`. A self-hosted alias also needs
+//! `forge.hostname` when the forge CLI cannot infer the API server.
//!
//! ## URL methods
//!
@@ -353,10 +324,10 @@ impl Repository {
.or_else(|| self.primary_remote_parsed_url())
}
- /// Detect the platform's reference type (PR for GitHub, MR for GitLab).
+ /// Detect the known forge's reference type (PR or MR).
///
- /// Hostname-matches the primary remote's effective URL (so `url.insteadOf`
- /// rewrites are respected). Returns `None` when the platform can't be
+ /// Classifies the primary remote's effective URL (so `url.insteadOf`
+ /// rewrites are respected). Returns `None` when the forge can't be
/// determined (no remote, opaque host).
///
/// Drives the numeric-branch hint in `BranchNotFound` only — `forge.platform`
@@ -369,13 +340,7 @@ impl Repository {
.ok()
.and_then(|remote| self.effective_remote_url(&remote))?;
let parsed = GitRemoteUrl::parse(&url)?;
- if parsed.is_github() {
- Some(RefType::Pr)
- } else if parsed.is_gitlab() {
- Some(RefType::Mr)
- } else {
- None
- }
+ parsed.forge_kind().map(|forge| forge.ref_type())
}
/// Get a project identifier for approval tracking.
diff --git a/src/git/url.rs b/src/git/url.rs
index ff0a193ef..e6b5746f4 100644
--- a/src/git/url.rs
+++ b/src/git/url.rs
@@ -6,7 +6,7 @@
use schemars::JsonSchema;
use serde::Serialize;
-use super::ci_platform::CiPlatform;
+use super::ci_platform::{ForgeKind, host_is_within, normalized_hostname};
/// Parsed, provider-neutral repository metadata.
///
@@ -51,37 +51,13 @@ pub enum GitRepoProvider {
Unknown,
}
-impl GitRepoProvider {
- /// Parse a configured `[forge].platform` value.
- ///
- /// Returns `None` for absent or unrecognized values so callers can fall
- /// back to URL host heuristics.
- pub fn from_platform(value: Option<&str>) -> Option<Self> {
- value?.parse::<CiPlatform>().ok().map(Into::into)
- }
-
- fn from_remote_host(url: &GitRemoteUrl) -> Option<Self> {
- if url.is_github() {
- Some(Self::GitHub)
- } else if url.is_gitlab() {
- Some(Self::GitLab)
- } else if url.is_gitea() {
- Some(Self::Gitea)
- } else if url.is_azure_devops() {
- Some(Self::AzureDevOps)
- } else {
- None
- }
- }
-}
-
-impl From<CiPlatform> for GitRepoProvider {
- fn from(platform: CiPlatform) -> Self {
+impl From<ForgeKind> for GitRepoProvider {
+ fn from(platform: ForgeKind) -> Self {
match platform {
- CiPlatform::GitHub => Self::GitHub,
- CiPlatform::GitLab => Self::GitLab,
- CiPlatform::Gitea => Self::Gitea,
- CiPlatform::AzureDevOps => Self::AzureDevOps,
+ ForgeKind::GitHub => Self::GitHub,
+ ForgeKind::GitLab => Self::GitLab,
+ ForgeKind::Gitea => Self::Gitea,
+ ForgeKind::AzureDevOps => Self::AzureDevOps,
}
}
}
@@ -155,6 +131,21 @@ pub(crate) fn url_path_segments_eq(left: &str, right: &str) -> bool {
canonical_url_path_segment(left).eq_ignore_ascii_case(&canonical_url_path_segment(right))
}
+/// Extract the network host (plus an HTTP(S)/git port, when present) from a URL
+/// authority, discarding userinfo at the final `@`.
+///
+/// The final separator matters for hostile or credential-bearing authorities:
+/// `[email protected]` connects to `attacker.example`, while
+/// `user:[email protected]:8443` connects to `github.com:8443`. Validation uses
+/// the same normalized hostname view as forge classification so an authority
+/// containing only userinfo and a port cannot produce an empty host.
+pub(crate) fn authority_host(authority: &str) -> Option<&str> {
+ let host = authority
+ .rsplit_once('@')
+ .map_or(authority, |(_, host)| host);
+ (!host.is_empty() && !normalized_hostname(host).is_empty()).then_some(host)
+}
+
impl GitRemoteUrl {
/// Parse a git remote URL into structured components.
///
@@ -165,20 +156,14 @@ impl GitRemoteUrl {
pub fn parse(url: &str) -> Option<Self> {
let url = url.trim();
- let (host, namespace, repo) = if let Some(rest) = url.strip_prefix("https://") {
- // https://github.com/owner/repo.git
- // https://gitlab.com/group/subgroup/repo.git
- let (host, path) = rest.split_once('/')?;
- let (namespace, repo) = split_namespace_repo(path)?;
- (host, namespace, repo)
- } else if let Some(rest) = url.strip_prefix("http://") {
- // http://github.com/owner/repo.git
- let (host, path) = rest.split_once('/')?;
- let (namespace, repo) = split_namespace_repo(path)?;
- (host, namespace, repo)
- } else if let Some(rest) = url.strip_prefix("git://") {
- // git://github.com/owner/repo.git
- let (host, path) = rest.split_once('/')?;
+ let (host, namespace, repo) = if let Some(rest) = url
+ .strip_prefix("https://")
+ .or_else(|| url.strip_prefix("http://"))
+ .or_else(|| url.strip_prefix("git://"))
+ {
+ // Scheme URL: [userinfo@]host[:port]/namespace/repo.git.
+ let (authority, path) = rest.split_once('/')?;
+ let host = authority_host(authority)?;
let (namespace, repo) = split_namespace_repo(path)?;
(host, namespace, repo)
} else if let Some(rest) = url.strip_prefix("ssh://") {
@@ -242,33 +227,37 @@ impl GitRemoteUrl {
format!("{}/{}/{}", self.host, self.owner, self.repo)
}
+ /// The known forge identified by this URL's hostname.
+ pub fn forge_kind(&self) -> Option<ForgeKind> {
+ ForgeKind::from_host(&self.host)
+ }
+
/// Check if this URL points to a GitHub host.
///
/// Matches github.com and GitHub Enterprise hosts (e.g., github.mycompany.com).
pub fn is_github(&self) -> bool {
- self.host.to_ascii_lowercase().contains("github")
+ self.forge_kind() == Some(ForgeKind::GitHub)
}
/// Check if this URL points to a GitLab host.
///
/// Matches gitlab.com and self-hosted GitLab instances (e.g., gitlab.example.com).
pub fn is_gitlab(&self) -> bool {
- self.host.to_ascii_lowercase().contains("gitlab")
+ self.forge_kind() == Some(ForgeKind::GitLab)
}
/// Check if this URL points to a Gitea host.
///
/// Matches gitea.com and self-hosted Gitea instances (e.g., gitea.example.com).
pub fn is_gitea(&self) -> bool {
- self.host.to_ascii_lowercase().contains("gitea")
+ self.forge_kind() == Some(ForgeKind::Gitea)
}
/// Check if this URL points to an Azure DevOps host.
///
/// Matches `dev.azure.com`, `ssh.dev.azure.com`, and legacy `*.visualstudio.com` hosts.
pub fn is_azure_devops(&self) -> bool {
- let host = self.host.to_ascii_lowercase();
- host.contains("dev.azure.com") || host.contains("visualstudio.com")
+ self.forge_kind() == Some(ForgeKind::AzureDevOps)
}
/// Extract the Azure DevOps organization from the URL.
@@ -282,10 +271,10 @@ impl GitRemoteUrl {
return None;
}
let parts: Vec<&str> = self.owner.split('/').collect();
- let host = self.host.to_ascii_lowercase();
- if host.contains("ssh.dev.azure.com") {
+ let host = normalized_hostname(&self.host);
+ if host == "ssh.dev.azure.com" {
parts.get(1).copied()
- } else if host.contains("dev.azure.com") {
+ } else if host_is_within(&host, "dev.azure.com") {
parts.first().copied()
} else {
self.host.split('.').next()
@@ -300,10 +289,10 @@ impl GitRemoteUrl {
return None;
}
let parts: Vec<&str> = self.owner.split('/').collect();
- let host = self.host.to_ascii_lowercase();
- if host.contains("ssh.dev.azure.com") {
+ let host = normalized_hostname(&self.host);
+ if host == "ssh.dev.azure.com" {
parts.get(2).copied()
- } else if host.contains("dev.azure.com") {
+ } else if host_is_within(&host, "dev.azure.com") {
parts.get(1).copied()
} else {
parts.first().copied()
@@ -336,11 +325,7 @@ impl GitRemoteUrl {
// `*.visualstudio.com` keeps the org in the hostname; every other
// Azure remote shape (including `ssh.dev.azure.com`) maps to the
// `dev.azure.com` web host.
- let host = if self
- .host
- .to_ascii_lowercase()
- .ends_with(".visualstudio.com")
- {
+ let host = if host_is_within(&self.host, "visualstudio.com") {
self.host.as_str()
} else {
"dev.azure.com"
@@ -365,10 +350,11 @@ impl GitRemoteUrl {
/// non-canonical hosts; an absent or unrecognized value falls back to host
/// heuristics, then [`GitRepoProvider::Unknown`].
pub fn repo_info(&self, provider_override: Option<&str>) -> Option<GitRepoInfo> {
- let provider_override = GitRepoProvider::from_platform(provider_override);
- let provider_from_host = GitRepoProvider::from_remote_host(self);
+ let provider_override = provider_override.and_then(|value| value.parse::<ForgeKind>().ok());
+ let provider_from_host = self.forge_kind();
let provider = provider_override
.or(provider_from_host)
+ .map(GitRepoProvider::from)
.unwrap_or(GitRepoProvider::Unknown);
if provider == GitRepoProvider::AzureDevOps {
@@ -389,8 +375,8 @@ impl GitRemoteUrl {
});
}
- if provider_override == Some(GitRepoProvider::AzureDevOps)
- && provider_from_host != Some(GitRepoProvider::AzureDevOps)
+ if provider_override == Some(ForgeKind::AzureDevOps)
+ && provider_from_host != Some(ForgeKind::AzureDevOps)
{
return Some(GitRepoInfo {
url: self.web_url()?,
@@ -419,11 +405,7 @@ impl GitRemoteUrl {
if let (Some(organization), Some(project)) =
(self.azure_organization(), self.azure_project())
{
- let host = if self
- .host
- .to_ascii_lowercase()
- .ends_with(".visualstudio.com")
- {
+ let host = if host_is_within(&self.host, "visualstudio.com") {
self.host.clone()
} else {
"dev.azure.com".to_string()
@@ -586,6 +568,93 @@ mod tests {
assert!(url.is_gitlab());
}
+ /// URL-scheme authorities use the final `@` as the userinfo boundary, so
+ /// forge-looking credentials cannot impersonate the network host. Ports
+ /// remain part of HTTP(S)/git authorities while SSH keeps its established
+ /// transport-only port stripping.
+ #[test]
+ fn scheme_authorities_use_the_network_host_after_userinfo() {
+ for (input, expected_host) in [
+ (
+ "https://[email protected]/owner/repo.git",
+ "attacker.example",
+ ),
+ (
+ "http://[email protected]:8443/owner/repo.git",
+ "attacker.example:8443",
+ ),
+ (
+ "git://[email protected]/owner/repo.git",
+ "attacker.example",
+ ),
+ (
+ "ssh://[email protected]/owner/repo.git",
+ "attacker.example",
+ ),
+ (
+ "[email protected]@attacker.example:owner/repo.git",
+ "attacker.example",
+ ),
+ ] {
+ let parsed = GitRemoteUrl::parse(input).expect("userinfo URL is structurally valid");
+ assert_eq!(parsed.host(), expected_host, "{input}");
+ assert_eq!(parsed.forge_kind(), None, "{input}");
+ assert_eq!(
+ parsed
+ .repo_info(None)
+ .expect("repository metadata")
+ .provider,
+ GitRepoProvider::Unknown,
+ "{input}"
+ );
+ }
+
+ for (input, expected_host, expected_forge) in [
+ (
+ "https://user:[email protected]:8443/owner/repo.git",
+ "github.com:8443",
+ ForgeKind::GitHub,
+ ),
+ (
+ "http://[email protected]/owner/repo.git",
+ "gitlab.example.com",
+ ForgeKind::GitLab,
+ ),
+ (
+ "git://[email protected]/owner/repo.git",
+ "gitea.example.com",
+ ForgeKind::Gitea,
+ ),
+ (
+ "ssh://[email protected]:2222/owner/repo.git",
+ "gitlab.example.com",
+ ForgeKind::GitLab,
+ ),
+ (
+ "[email protected]:owner/repo.git",
+ "gitlab.example.com",
+ ForgeKind::GitLab,
+ ),
+ ] {
+ let parsed = GitRemoteUrl::parse(input).expect("credentialed URL is supported");
+ assert_eq!(parsed.host(), expected_host, "{input}");
+ assert_eq!(parsed.forge_kind(), Some(expected_forge), "{input}");
+ }
+
+ for input in [
+ "https://github.com@/owner/repo.git",
+ "http://gitlab.com@/owner/repo.git",
+ "git://gitea.com@/owner/repo.git",
+ "ssh://github.com@/owner/repo.git",
+ "github.com@:owner/repo.git",
+ ] {
+ assert!(
+ GitRemoteUrl::parse(input).is_none(),
+ "empty network host must be rejected: {input}"
+ );
+ }
+ }
+
#[test]
fn test_malformed_urls() {
assert!(GitRemoteUrl::parse("").is_none());
@@ -735,6 +804,49 @@ mod tests {
);
}
+ #[test]
+ fn forge_detection_respects_host_boundaries_and_ports() {
+ let supported = [
+ ("https://github.com:8443/owner/repo.git", ForgeKind::GitHub),
+ (
+ "https://gitlab.example.com:8443/owner/repo.git",
+ ForgeKind::GitLab,
+ ),
+ (
+ "https://gitea.example.com:8443/owner/repo.git",
+ ForgeKind::Gitea,
+ ),
+ (
+ "https://dev.azure.com:8443/org/project/_git/repo",
+ ForgeKind::AzureDevOps,
+ ),
+ ];
+ for (input, expected) in supported {
+ let parsed = GitRemoteUrl::parse(input).expect("supported forge URL");
+ assert_eq!(parsed.forge_kind(), Some(expected), "{input}");
+ }
+
+ let lookalikes = [
+ "https://github-mirror.example/owner/repo.git",
+ "https://notgitlab.example/owner/repo.git",
+ "https://gitea-mirror.example/owner/repo.git",
+ "https://dev.azure.com.attacker.example/org/project/_git/repo",
+ "https://evil-visualstudio.com/org/project/_git/repo",
+ ];
+ for input in lookalikes {
+ let parsed = GitRemoteUrl::parse(input).expect("lookalike URL is structurally valid");
+ assert_eq!(parsed.forge_kind(), None, "{input}");
+ assert_eq!(
+ parsed
+ .repo_info(None)
+ .expect("repository metadata")
+ .provider,
+ GitRepoProvider::Unknown,
+ "{input}"
+ );
+ }
+ }
+
// Security-critical tests for nested GitLab groups.
//
// GitLab supports nested groups (subgroups) with arbitrary depth:
@@ -1456,10 +1568,11 @@ mod tests {
assert_eq!(info.owner, "owner");
assert_eq!(info.name, "repo");
- assert_eq!(
- GitRepoProvider::from_platform(Some("gitlab")),
- Some(GitRepoProvider::GitLab)
- );
+ let info = GitRemoteUrl::parse("https://git.example.com/owner/repo.git")
+ .unwrap()
+ .repo_info(Some("gitlab"))
+ .unwrap();
+ assert_eq!(info.provider, GitRepoProvider::GitLab);
}
#[test]
diff --git a/src/output/concurrent.rs b/src/output/concurrent.rs
index 3f64e5f4b..8be02acd3 100644
--- a/src/output/concurrent.rs
+++ b/src/output/concurrent.rs
@@ -46,8 +46,8 @@ use anyhow::Context;
use worktrunk::command_log::log_command;
use worktrunk::git::WorktrunkError;
use worktrunk::shell_exec::{
- DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR, ShellConfig,
- scrub_directive_env_vars, scrub_git_discovery_env_vars,
+ DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, ShellConfig, scrub_directive_env_vars,
+ scrub_git_discovery_env_vars,
};
#[cfg(unix)]
use worktrunk::signal_forwarder::ForegroundSignals;
@@ -310,9 +310,6 @@ fn spawn_child(
if let Some(path) = &cmd.directives.exec_file {
command.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);
}
- if let Some(path) = &cmd.directives.legacy_file {
- command.env(DIRECTIVE_FILE_ENV_VAR, path);
- }
#[cfg(unix)]
{
@@ -485,7 +482,7 @@ mod tests {
//! Unit tests that exercise the executor's option-bearing code paths which
//! aren't reachable through the alias integration tests today: every child
//! currently has `log_label=None` (aliases skip per-child logging) and the
- //! CD/legacy directive env vars are usually unset. Driving these branches
+ //! CD/EXEC directive env vars are usually unset. Driving these branches
//! with a direct call proves they behave correctly when a future caller
//! (concurrent foreground hooks, once their deprecation completes) uses them.
use super::*;
@@ -526,9 +523,9 @@ mod tests {
// passing a log_label doesn't panic and the command still runs.
}
- /// `DirectivePassthrough` with `cd_file`, `exec_file`, and `legacy_file`
- /// set must propagate all three env vars to the child. The child script
- /// echoes each env var; we assert every value is delivered.
+ /// `DirectivePassthrough` with `cd_file` and `exec_file` set must propagate
+ /// both env vars to the child. The child script writes to each named file;
+ /// we assert both values are delivered.
///
/// Unix-only: the script uses POSIX `sh` redirect syntax and relies on
/// native temp paths that don't need escaping. Git Bash on Windows would
@@ -539,29 +536,24 @@ mod tests {
use tempfile::NamedTempFile;
let cd = NamedTempFile::new().unwrap();
let exec = NamedTempFile::new().unwrap();
- let legacy = NamedTempFile::new().unwrap();
let directives = DirectivePassthrough {
cd_file: Some(cd.path().to_path_buf()),
exec_file: Some(exec.path().to_path_buf()),
- legacy_file: Some(legacy.path().to_path_buf()),
};
// Write each env var's value to its matching temp file. If the child
// didn't receive the env var, the redirect would fail or write an
// empty file.
let script = format!(
- "printf CD > {} && printf EXEC > {} && printf LEGACY > {}",
+ "printf CD > {} && printf EXEC > {}",
cd.path().display(),
exec.path().display(),
- legacy.path().display(),
);
let outcomes = run_one_with_directives("job", &script, None, &directives);
assert!(outcomes[0].is_ok(), "child should exit 0");
let cd_contents = std::fs::read_to_string(cd.path()).unwrap();
let exec_contents = std::fs::read_to_string(exec.path()).unwrap();
- let legacy_contents = std::fs::read_to_string(legacy.path()).unwrap();
assert_eq!(cd_contents, "CD");
assert_eq!(exec_contents, "EXEC");
- assert_eq!(legacy_contents, "LEGACY");
}
/// An empty `cmds` slice must return an empty outcomes vec without
diff --git a/src/output/global.rs b/src/output/global.rs
index cbfc7e8a2..d5e190dd4 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -36,17 +36,9 @@
//! <https://github.com/max-sixty/worktrunk/issues/2101> so users can report
//! whether to relax the restriction further.
//!
-//! # Legacy compat
-//!
-//! Users who upgrade wt without restarting their shell still run the previous
-//! release's shell wrapper, which only sets `WORKTRUNK_DIRECTIVE_FILE`. When
-//! only that variable is set, wt falls back to the pre-split protocol (shell
-//! commands written to the single file) and emits a one-shot deprecation
-//! warning hinting at `wt config shell install`. For bash, zsh, fish, and
-//! PowerShell a shell restart picks up the new wrapper automatically; nushell
-//! is the only shell where users have to rerun `wt config shell install`
-//! because its wrapper is a static file. Remove the legacy path in the next
-//! breaking release.
+//! The retired single-file protocol is never written. If an old wrapper still
+//! sets only `WORKTRUNK_DIRECTIVE_FILE`, switch output diagnoses the outdated
+//! wrapper and tells the user to reinstall shell integration.
use std::fs::OpenOptions;
use std::io::{self, Write};
@@ -70,8 +62,7 @@ use worktrunk::shell_exec::ShellConfig;
#[cfg(unix)]
use worktrunk::shell_exec::scrub_git_discovery_env_vars;
use worktrunk::shell_exec::{
- DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR,
- ShellEscapeMode, directive_shell_escape_mode,
+ DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,
};
use worktrunk::styling::{hint_message, warning_message};
@@ -96,11 +87,12 @@ pub use worktrunk::styling::set_verbosity;
/// unreachable - the lock is only held for trivial Option assignments that cannot panic.
static OUTPUT_STATE: OnceLock<Mutex<OutputState>> = OnceLock::new();
+/// Ensures output shows the retired wrapper's reinstall action at most once.
+static RETIRED_REPAIR_HINT_SHOWN: OnceLock<()> = OnceLock::new();
+
/// Selects which directive files wt writes to based on environment.
///
/// Computed once during `state()` initialization from the process environment.
-/// Legacy mode only activates when no new-protocol vars are set — a fresh
-/// wrapper always wins over any leftover legacy var.
#[derive(Debug, Clone, Default)]
enum DirectiveMode {
/// Shell integration not active. `execute()` runs commands directly;
@@ -108,16 +100,18 @@ enum DirectiveMode {
/// dir used by `execute()`.
#[default]
Interactive,
- /// New split protocol. `cd_file` is always a real path; `exec_file` is
+ /// Split protocol. `cd_file` is always a real path; `exec_file` is
/// `None` when the EXEC var was scrubbed from this process (we're
/// running inside an alias/hook shell body). `--execute` in the scrubbed
/// case warns and drops the command.
- NewProtocol {
+ Split {
cd_file: PathBuf,
exec_file: Option<PathBuf>,
},
- /// Legacy single-file protocol. Pre-split wrapper is still active.
- Legacy { file: PathBuf },
+ /// A retired pre-split wrapper is active. This state is diagnostic-only:
+ /// wt never reads or writes the retired directive file, and `--execute`
+ /// is refused rather than run directly.
+ Retired,
}
#[derive(Default)]
@@ -265,50 +259,59 @@ fn read_env_path(var: &str) -> Option<PathBuf> {
.map(PathBuf::from)
}
+/// Whether this invocation came through a retired pre-split shell wrapper.
+///
+/// A split-protocol CD file always wins over a leftover single-file variable.
+/// The old variable is recognized only to produce a targeted repair message;
+/// wt never writes to it.
+pub(crate) fn retired_shell_wrapper_active() -> bool {
+ matches!(
+ state().lock().expect("OUTPUT_STATE lock poisoned").mode,
+ DirectiveMode::Retired
+ )
+}
+
fn compute_directive_mode() -> DirectiveMode {
let cd = read_env_path(DIRECTIVE_CD_FILE_ENV_VAR);
let exec = read_env_path(DIRECTIVE_EXEC_FILE_ENV_VAR);
- let legacy = read_env_path(DIRECTIVE_FILE_ENV_VAR);
+ let retired = read_env_path(RETIRED_DIRECTIVE_FILE_ENV_VAR);
match cd {
- Some(cd_file) => DirectiveMode::NewProtocol {
+ Some(cd_file) => DirectiveMode::Split {
cd_file,
exec_file: exec,
},
- None => match legacy {
- // Hitting this branch means the active shell wrapper still sets
- // only `WORKTRUNK_DIRECTIVE_FILE` (pre-split protocol). bash, zsh,
- // fish, and PowerShell wrappers self-update on shell restart, so
- // any wt invocation still landing here is using an outdated
- // wrapper — most often nushell, where the wrapper is a static
- // file the user must reinstall via `wt config shell install`.
- // Warn once per process so the user is prompted to refresh it
- // before the legacy fallback is removed in a future release.
- Some(file) => {
- warn_legacy_directive();
- DirectiveMode::Legacy { file }
- }
- None => DirectiveMode::Interactive,
- },
+ None if retired.is_some() => DirectiveMode::Retired,
+ None => DirectiveMode::Interactive,
+ }
+}
+
+/// Print the canonical repair action for the retired pre-split wrapper once.
+pub(crate) fn print_outdated_shell_wrapper_hint_once() {
+ if RETIRED_REPAIR_HINT_SHOWN.set(()).is_ok() {
+ eprintln!(
+ "{}",
+ hint_message(cformat!(
+ "To update the shell wrapper, run <underline>wt config shell install</>"
+ ))
+ );
}
}
-/// Warn that the active shell wrapper is using the pre-split directive-file
-/// protocol. The caller (`compute_directive_mode`) runs once per process from
-/// `OUTPUT_STATE.get_or_init`, so this naturally fires at most once.
-fn warn_legacy_directive() {
+/// Refuse `--execute` from a retired wrapper. Fires at most once per process,
+/// and supplies the reinstall action when no earlier directory warning did.
+fn warn_retired_exec_once(command: &str) {
+ static WARNED: OnceLock<()> = OnceLock::new();
+ if WARNED.set(()).is_err() {
+ return;
+ }
eprintln!(
"{}",
warning_message(cformat!(
- "Shell wrapper uses the legacy directive-file protocol; it will be removed in a future release"
- ))
- );
- eprintln!(
- "{}",
- hint_message(cformat!(
- "To update, run <underline>wt config shell install</>"
+ "<bold>--execute</> disabled because the shell wrapper is out of date; skipping <bold>{command}</>"
))
);
+ print_outdated_shell_wrapper_hint_once();
}
/// Warn that `--execute` was refused because we're running inside an alias or
@@ -381,35 +384,11 @@ fn write_cd_path_io(file: &Path, path: &Path) -> io::Result<()> {
f.flush()
}
-/// Escape a path as a single-quoted `cd` command for the active directive
-/// shell. Only used in legacy mode where we still emit shell commands.
-///
-/// Always wraps the path in `'…'` (even when the path has no metacharacters),
-/// unlike the POSIX `--execute` payload escaper which omits quotes around safe
-/// values — a constant `cd '…'` shape keeps the legacy directive predictable.
-/// The per-shell decision comes from the shared [`directive_shell_escape_mode`],
-/// so the path body is escaped for POSIX (`'\''`), PowerShell (`''`), or fish
-/// (`\\` and `\'`) consistently with the rest of the directive payload.
-fn escape_legacy_cd(path: &Path) -> String {
- let path_str = path.to_string_lossy();
- let escaped = match directive_shell_escape_mode() {
- ShellEscapeMode::PowerShell => path_str.replace('\'', "''"),
- // fish treats `\` as an escape inside `'…'`, so the path body must
- // double `\` (before escaping `'`) — POSIX `'\''` would corrupt it.
- ShellEscapeMode::Fish => path_str.replace('\\', r"\\").replace('\'', r"\'"),
- // Literal is unreachable here (directive_shell_escape_mode yields only
- // Posix/PowerShell/Fish); grouped with Posix as the safe default.
- ShellEscapeMode::Literal | ShellEscapeMode::Posix => path_str.replace('\'', r"'\''"),
- };
- format!("cd '{}'", escaped)
-}
-
/// Request directory change (for shell integration).
///
-/// Writes the target path to the CD directive file (new protocol) or emits
-/// a shell `cd '...'` command to the legacy file (legacy compat). In
-/// interactive mode (no wrapper), just buffers the target so that a later
-/// `execute()` can use it as the child's working directory.
+/// Writes the target path to the CD directive file. In interactive mode (no
+/// current wrapper), just buffers the target so that a later `execute()` can
+/// use it as the child's working directory.
///
/// A write failure names the file it couldn't write — see [`append_line`].
pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
@@ -421,14 +400,8 @@ pub fn change_directory(path: impl AsRef<Path>) -> anyhow::Result<()> {
};
match mode {
- DirectiveMode::Interactive => Ok(()),
- DirectiveMode::NewProtocol { cd_file, .. } => {
- write_cd_path(&cd_file, &to_logical_path(path))
- }
- DirectiveMode::Legacy { file } => {
- let directive = escape_legacy_cd(&to_logical_path(path));
- append_line(&file, &directive, "the cd command")
- }
+ DirectiveMode::Interactive | DirectiveMode::Retired => Ok(()),
+ DirectiveMode::Split { cd_file, .. } => write_cd_path(&cd_file, &to_logical_path(path)),
}
}
@@ -456,13 +429,13 @@ pub fn was_cwd_removed() -> bool {
///
/// Dispatches by directive mode:
/// - Interactive: runs the command directly (replacing this process on Unix).
-/// - New protocol with EXEC file: appends the command to the EXEC file; the
+/// - Split protocol with EXEC file: appends the command to the EXEC file; the
/// wrapper sources it after wt exits, so it runs in the user's interactive
/// shell.
-/// - New protocol without EXEC file: refuses the command with a warning. We
+/// - Split protocol without EXEC file: refuses the command with a warning. We
/// land here when running inside an alias or hook body, where `Cmd` scrubbed
/// the EXEC var to keep arbitrary shell from reaching the parent session.
-/// - Legacy: appends the command to the single legacy directive file.
+/// - Retired wrapper: refuses the command and points to the reinstall action.
///
/// A failed append names the file it couldn't write — see [`append_line`].
pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
@@ -475,31 +448,35 @@ pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
match mode {
DirectiveMode::Interactive => execute_command(command, target_dir.as_deref()),
- DirectiveMode::NewProtocol {
+ DirectiveMode::Split {
exec_file: Some(file),
..
} => append_line(&file, &command, "the command"),
- DirectiveMode::NewProtocol {
+ DirectiveMode::Split {
exec_file: None, ..
} => {
warn_exec_scrubbed_once(&command);
Ok(())
}
- DirectiveMode::Legacy { file } => append_line(&file, &command, "the command"),
+ DirectiveMode::Retired => {
+ warn_retired_exec_once(&command);
+ Ok(())
+ }
}
}
/// Whether a call to `execute()` with a non-empty command would be refused
-/// by the conservative scrub. Callers can use this to suppress pre-exec
-/// output (e.g. "Executing (--execute):" headers) so the warning stands alone.
+/// by the conservative scrub or a retired wrapper. Callers can use this to
+/// suppress pre-exec output (e.g. "Executing (--execute):" headers) so the
+/// warning stands alone.
pub fn exec_would_be_refused() -> bool {
let guard = state().lock().expect("OUTPUT_STATE lock poisoned");
matches!(
guard.mode,
- DirectiveMode::NewProtocol {
+ DirectiveMode::Split {
exec_file: None,
..
- }
+ } | DirectiveMode::Retired
)
}
@@ -578,14 +555,11 @@ pub fn terminate_output() -> io::Result<()> {
stderr.flush()
}
-/// Check if we're in shell integration mode (any directive-file protocol active).
-///
-/// Useful for handlers that need to know whether shell integration is in effect,
-/// regardless of which protocol (new or legacy) is being used.
+/// Check whether the split directive-file protocol is active.
pub fn is_shell_integration_active() -> bool {
- !matches!(
+ matches!(
state().lock().expect("OUTPUT_STATE lock poisoned").mode,
- DirectiveMode::Interactive
+ DirectiveMode::Split { .. }
)
}
@@ -791,30 +765,6 @@ mod tests {
rx.recv().unwrap();
}
- // Shell escaping tests (escape_legacy_cd)
-
- #[test]
- fn test_escape_legacy_cd_simple_path() {
- let result = escape_legacy_cd(Path::new("/test/path"));
- assert_eq!(result, "cd '/test/path'");
- }
-
- #[test]
- fn test_escape_legacy_cd_single_quotes() {
- let result = escape_legacy_cd(Path::new("/test/it's/path"));
- assert_eq!(result, r"cd '/test/it'\''s/path'");
- }
-
- #[test]
- fn test_escape_legacy_cd_spaces() {
- let result = escape_legacy_cd(Path::new("/test/my path/here"));
- assert_eq!(result, "cd '/test/my path/here'");
- }
-
- // PowerShell branch of escape_legacy_cd is exercised via integration
- // test `test_switch_legacy_directive_file_powershell` which sets
- // WORKTRUNK_SHELL=powershell on the subprocess.
-
/// Test that anstyle formatting is preserved
#[test]
fn test_success_preserves_anstyle() {
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index ad0847ae6..3682a25a7 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -133,6 +133,30 @@ enum BackgroundRemovalPlan {
CompletedSynchronously,
}
+/// Print `live` when a complete porcelain record names the requested branch
+/// and is either non-prunable or locked.
+///
+/// The caller checks both this script's exit status and its exact output:
+/// an empty successful result means no live checkout, `live` means retain, and
+/// any tool failure or unexpected output fails closed. Paragraph mode (`RS =
+/// ""`) keeps each worktree's `branch`, `prunable`, and `locked` fields
+/// associated. A lock wins if a record ever carries both status fields.
+const LIVE_BRANCH_WORKTREE_AWK: &str = r#"BEGIN { RS = ""; FS = "\n" }
+{
+ has_branch = 0
+ prunable = 0
+ locked = 0
+ for (i = 1; i <= NF; i++) {
+ if ($i == worktrunk_wanted_branch) has_branch = 1
+ if ($i == "prunable" || index($i, "prunable ") == 1) prunable = 1
+ if ($i == "locked" || index($i, "locked ") == 1) locked = 1
+ }
+ if (has_branch && (!prunable || locked)) {
+ print "live"
+ exit
+ }
+}"#;
+
/// Spawn background worktree removal: clean-check, stop fsmonitor,
/// rename-then-prune, spawn detached rm.
///
@@ -363,6 +387,9 @@ fn delete_branch_in_synchronous_fallback(
/// tip moved between integration check and delete (a hook, a concurrent
/// push). Always surface — the unmerged commits would otherwise vanish
/// silently from the user's view.
+/// - `Ok(RetainedCheckedOut)`: the final topology read found the branch in a
+/// worktree. Always surface the path; neither the moved-ref nor unmerged
+/// wording describes this outcome.
/// - `Ok(NotDeleted)`: integration check declined the branch. Warn only
/// when the planner predicted deletion (a `pre-remove` hook commit, or
/// similar race) — otherwise `print_hints` has explained the case and a
@@ -377,30 +404,37 @@ fn warn_if_branch_retained(
planner_expected_retention: bool,
) {
match result {
- Ok(r) if matches!(r.outcome, BranchDeletionOutcome::RetainedRaced) => {
- // The branch tip moved between the integration check and the
- // atomic delete (a hook commit, a concurrent push). The
- // compare-and-swap refused — fail-closed — so the unmerged
- // commits are preserved. Always surface, regardless of planner
- // prediction.
- eprintln!("{}", retained_raced_branch_message(branch, true));
- }
- Ok(r)
- if matches!(r.outcome, BranchDeletionOutcome::NotDeleted)
- && !planner_expected_retention =>
- {
- let cmd = suggest_command("remove", &[branch], &["-D"]);
- eprintln!(
- "{}",
- warning_message(cformat!(
- "Removed worktree but kept branch <bold>{branch}</> (not integrated); to delete, run <bold>{cmd}</>"
- ))
- );
- }
+ Ok(result) => match &result.outcome {
+ BranchDeletionOutcome::RetainedCheckedOut { path } => {
+ eprintln!(
+ "{}",
+ retained_checked_out_branch_message(branch, path, true)
+ );
+ }
+ BranchDeletionOutcome::RetainedRaced => {
+ // The branch tip moved between the integration check and the
+ // atomic delete (a hook commit, a concurrent push). The
+ // compare-and-swap refused — fail-closed — so the unmerged
+ // commits are preserved. Always surface, regardless of planner
+ // prediction.
+ eprintln!("{}", retained_raced_branch_message(branch, true));
+ }
+ BranchDeletionOutcome::NotDeleted if !planner_expected_retention => {
+ let cmd = suggest_command("remove", &[branch], &["-D"]);
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Removed worktree but kept branch <bold>{branch}</> (not integrated); to delete, run <bold>{cmd}</>"
+ ))
+ );
+ }
+ BranchDeletionOutcome::NotDeleted
+ | BranchDeletionOutcome::ForceDeleted
+ | BranchDeletionOutcome::Integrated(_) => {}
+ },
Err(e) => {
tracing::warn!(branch = %branch, error = %e, "Failed to delete branch {branch} after removing worktree: {e}");
}
- Ok(_) => {}
}
}
@@ -408,11 +442,17 @@ fn warn_if_branch_retained(
/// fallback path.
///
/// Captures a fresh snapshot, runs the same `integration_reason` check the
-/// fast path uses, and — if the branch is integrated — returns an atomic
-/// `git update-ref -d refs/heads/<branch> <expected-sha>` that will be
-/// appended to the detached `git worktree remove` command. The CAS keeps the
-/// deletion safe against tip movement between this foreground check and the
-/// detached process executing it.
+/// fast path uses, and — if the branch is integrated — returns a fail-closed
+/// topology guard followed by atomic
+/// `git update-ref -d refs/heads/<branch> <expected-sha>`. The detached process
+/// re-reads `git worktree list --porcelain` after removing the original
+/// worktree and skips deletion if any non-prunable worktree now holds the
+/// branch; stale `prunable` records do not strand it. The tail is joined to
+/// `git worktree remove` with `&&`, so the exact target's registration is
+/// already gone before this guard runs; every same-branch record that remains
+/// belongs to a different worktree. The CAS then protects against tip movement.
+/// The detached executor provides POSIX `sh` on Unix and requires Git Bash on
+/// Windows, so the record-aware `awk` guard is available on both paths.
///
/// Returns `None` when the branch is not integrated, when the snapshot
/// doesn't carry the branch SHA, or when the snapshot/integration call
@@ -432,9 +472,13 @@ fn build_cas_branch_delete_tail(
let expected_sha = snapshot.local_branch(branch)?.commit_sha.clone();
let ref_name = format!("refs/heads/{branch}");
+ let branch_line = format!("branch {ref_name}");
+ let branch_line_escaped = escape(branch_line.as_str().into());
let ref_escaped = escape(ref_name.as_str().into());
let sha_escaped = escape(expected_sha.as_str().into());
- Some(format!("git update-ref -d {ref_escaped} {sha_escaped}"))
+ Some(format!(
+ "worktrunk_worktrees=$(git worktree list --porcelain) && {{ worktrunk_live_checkout=$(printf '%s\\n' \"$worktrunk_worktrees\" | awk -v worktrunk_wanted_branch={branch_line_escaped} '{LIVE_BRANCH_WORKTREE_AWK}') && {{ if [ \"$worktrunk_live_checkout\" = live ]; then :; elif [ -z \"$worktrunk_live_checkout\" ]; then git update-ref -d {ref_escaped} {sha_escaped}; else false; fi; }}; }}"
+ ))
}
/// Build the detached worktree-removal command, optionally appending a
@@ -565,6 +609,8 @@ fn build_switch_output_context(
fn print_switch_directory_hint(branch: &str, is_git_subcommand: bool) {
if is_git_subcommand {
eprintln!("{}", hint_message(git_subcommand_warning()));
+ } else if super::retired_shell_wrapper_active() {
+ super::print_outdated_shell_wrapper_hint_once();
} else if should_show_explicit_path_hint() {
eprintln!("{}", hint_message(explicit_path_hint(branch)));
}
@@ -745,11 +791,35 @@ fn retained_raced_branch_message(branch_name: &str, removed_worktree: bool) -> S
.to_string()
}
+/// The canonical message for a branch retained by the final topology read.
+///
+/// Unlike [`retained_raced_branch_message`], this is not a ref-tip race and
+/// does not suggest `-D`: Git refuses to delete a branch while the named
+/// worktree holds it. The path is the actionable explanation.
+fn retained_checked_out_branch_message(
+ branch_name: &str,
+ path: &Path,
+ removed_worktree: bool,
+) -> String {
+ let lead_in = if removed_worktree {
+ "Removed worktree but retained branch"
+ } else {
+ "Retained branch"
+ };
+ let path = format_path_for_display(path);
+ warning_message(cformat!(
+ "{lead_in} <bold>{branch_name}</>; checked out @ <bold>{path}</>"
+ ))
+ .to_string()
+}
+
/// Handle the result of a branch deletion attempt.
///
/// Converts a deletion attempt into structured display data:
/// - `NotDeleted`: We checked and chose not to delete (not integrated) — sets
/// `show_unmerged_hint`.
+/// - `RetainedCheckedOut`: the final fresh topology read found a checkout.
+/// Callers surface its path, not the unmerged hint.
/// - `RetainedRaced`: integration check passed but the atomic CAS delete was
/// refused because the ref moved (a hook or concurrent process advanced it).
/// Callers surface this with [`retained_raced_branch_message`], not the
@@ -836,9 +906,9 @@ fn flag_note(
}
match outcome {
- BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced => {
- FlagNote::empty()
- }
+ BranchDeletionOutcome::NotDeleted
+ | BranchDeletionOutcome::RetainedCheckedOut { .. }
+ | BranchDeletionOutcome::RetainedRaced => FlagNote::empty(),
BranchDeletionOutcome::ForceDeleted => FlagNote::text_only(" (--force-delete)"),
BranchDeletionOutcome::Integrated(reason) => {
let Some(target) = target_branch else {
@@ -908,7 +978,9 @@ fn print_switch_message_if_changed(
warning_message(cformat!("Cannot change directory — {reason}"))
);
// Show appropriate hint based on invocation mode
- if should_show_explicit_path_hint() {
+ if super::retired_shell_wrapper_active() {
+ super::print_outdated_shell_wrapper_hint_once();
+ } else if should_show_explicit_path_hint() {
eprintln!("{}", hint_message(explicit_path_hint(&dest_branch)));
} else {
print_shell_integration_hint(&repo);
@@ -1028,13 +1100,13 @@ pub fn handle_switch_output(
/// directory (shell integration not active). This helps users understand where
/// the command runs.
///
-/// When the conservative EXEC scrub is in effect (nested `wt` inside an alias
-/// or hook body), no `Executing` header is printed — `execute()` emits its own
+/// When execution will be refused (the conservative EXEC scrub or a retired
+/// wrapper), no `Executing` header is printed — `execute()` emits its own
/// warning explaining the skip, and a contradictory header would read as a
-/// broken promise. See `output::global::warn_exec_scrubbed_once`.
+/// broken promise.
pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyhow::Result<()> {
if super::exec_would_be_refused() {
- // execute() will emit the conservative-scrub warning and return Ok.
+ // execute() will emit the refusal warning and return Ok.
return super::execute(command);
}
@@ -1227,20 +1299,31 @@ fn handle_branch_only_output(
}
};
- if matches!(
- deletion.result.outcome,
- BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced
- ) {
- eprintln!("{}", info_message(&branch_info));
- if matches!(
- deletion.result.outcome,
- BranchDeletionOutcome::RetainedRaced
- ) {
+ let retained = match &deletion.result.outcome {
+ BranchDeletionOutcome::RetainedCheckedOut { path } => {
+ eprintln!("{}", info_message(&branch_info));
+ eprintln!(
+ "{}",
+ retained_checked_out_branch_message(branch_name, path, false)
+ );
+ true
+ }
+ BranchDeletionOutcome::RetainedRaced => {
+ eprintln!("{}", info_message(&branch_info));
eprintln!("{}", retained_raced_branch_message(branch_name, false));
- } else if deletion.show_unmerged_hint {
- print_retained_unmerged_branch(branch_name);
+ true
}
- } else {
+ BranchDeletionOutcome::NotDeleted => {
+ eprintln!("{}", info_message(&branch_info));
+ if deletion.show_unmerged_hint {
+ print_retained_unmerged_branch(branch_name);
+ }
+ true
+ }
+ BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => false,
+ };
+
+ if !retained {
let flag_note = flag_note(
deletion_mode,
&deletion.result.outcome,
@@ -1275,9 +1358,9 @@ fn handle_branch_only_output(
BranchDeletionOutcome::Integrated(_) | BranchDeletionOutcome::ForceDeleted => {
BranchFate::Deleted
}
- BranchDeletionOutcome::NotDeleted | BranchDeletionOutcome::RetainedRaced => {
- BranchFate::Retained
- }
+ BranchDeletionOutcome::NotDeleted
+ | BranchDeletionOutcome::RetainedCheckedOut { .. }
+ | BranchDeletionOutcome::RetainedRaced => BranchFate::Retained,
})
}
@@ -1364,7 +1447,7 @@ fn spawn_hooks_after_remove(
/// computed for background mode or actual for foreground mode) so that message
/// formatting can be shared between both modes.
struct RemovalDisplayInfo {
- /// The deletion outcome (NotDeleted, ForceDeleted, or Integrated)
+ /// The observed deletion outcome, including retained race cases.
outcome: BranchDeletionOutcome,
/// The target branch used for integration check (may be upstream if ahead of local)
integration_target: Option<String>,
@@ -1532,13 +1615,24 @@ impl RemovalDisplayInfo {
}
// A raced retention isn't "unmerged" — the branch was integrated but
- // its tip moved during the delete. Surface the dedicated message
- // (inspect commits, then force-delete if safe) rather than falling
- // through to the generic unmerged hint, whose bare `-D` would drop the
- // racing commits.
- if matches!(self.outcome, BranchDeletionOutcome::RetainedRaced) {
- eprintln!("{}", retained_raced_branch_message(branch_name, true));
- return Ok(());
+ // either gained a checkout or its tip moved during the delete. Surface
+ // the dedicated message rather than falling through to the generic
+ // unmerged hint, whose explanation would be false.
+ match &self.outcome {
+ BranchDeletionOutcome::RetainedCheckedOut { path } => {
+ eprintln!(
+ "{}",
+ retained_checked_out_branch_message(branch_name, path, true)
+ );
+ return Ok(());
+ }
+ BranchDeletionOutcome::RetainedRaced => {
+ eprintln!("{}", retained_raced_branch_message(branch_name, true));
+ return Ok(());
+ }
+ BranchDeletionOutcome::NotDeleted
+ | BranchDeletionOutcome::ForceDeleted
+ | BranchDeletionOutcome::Integrated(_) => {}
}
if deletion_mode.should_keep() {
@@ -1973,9 +2067,9 @@ fn remove_removed_worktree_silently(
///
/// - `DirectivePassthrough::default()` — scrubs all directive env vars from
/// the child. Used by background hooks (outlive the parent shell).
-/// - `DirectivePassthrough::inherit_from_env()` — re-adds CD (and the legacy
-/// compat var) but scrubs EXEC. Used by project aliases and foreground hooks,
-/// which may emit `cd` directives but must not be able to inject shell.
+/// - `DirectivePassthrough::inherit_from_env()` — re-adds CD but scrubs EXEC.
+/// Used by project aliases and foreground hooks, which may emit `cd`
+/// directives but must not be able to inject shell.
/// - `DirectivePassthrough::inherit_from_env_with_exec()` — also re-adds EXEC.
/// Used only for user-source aliases, where the alias body is already user-
/// authored just like a top-level `wt switch --execute` invocation.
@@ -2062,9 +2156,6 @@ pub fn execute_shell_command(
if let Some(path) = directives.exec_file {
cmd = cmd.directive_exec_file(path);
}
- if let Some(path) = directives.legacy_file {
- cmd = cmd.directive_legacy_file(path);
- }
cmd.stream()?;
@@ -2086,21 +2177,19 @@ pub fn execute_shell_command(
pub struct DirectivePassthrough {
pub cd_file: Option<std::path::PathBuf>,
pub exec_file: Option<std::path::PathBuf>,
- pub legacy_file: Option<std::path::PathBuf>,
}
impl DirectivePassthrough {
- /// Pass CD and legacy directive files through to the child, reading the
- /// current process environment. Used by project aliases and foreground
- /// hooks that may legitimately emit a `cd` directive. The EXEC file is
- /// deliberately omitted — a project-config body could otherwise inject
- /// arbitrary shell into the parent session.
+ /// Pass the CD directive file through to the child, reading the current
+ /// process environment. Used by project aliases and foreground hooks that
+ /// may legitimately emit a `cd` directive. The EXEC file is deliberately
+ /// omitted — a project-config body could otherwise inject arbitrary shell
+ /// into the parent session.
pub fn inherit_from_env() -> Self {
- use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR};
+ use worktrunk::shell_exec::DIRECTIVE_CD_FILE_ENV_VAR;
Self {
cd_file: read_directive_env(DIRECTIVE_CD_FILE_ENV_VAR),
exec_file: None,
- legacy_file: read_directive_env(DIRECTIVE_FILE_ENV_VAR),
}
}
@@ -2153,6 +2242,15 @@ mod tests {
warn_if_branch_retained("feature", &ok(BranchDeletionOutcome::RetainedRaced), false);
warn_if_branch_retained("feature", &ok(BranchDeletionOutcome::RetainedRaced), true);
+ // RetainedCheckedOut → surface the checkout path
+ warn_if_branch_retained(
+ "feature",
+ &ok(BranchDeletionOutcome::RetainedCheckedOut {
+ path: Path::new("/tmp/repo.feature-survivor").to_path_buf(),
+ }),
+ false,
+ );
+
// Success arms → silent
warn_if_branch_retained("feature", &ok(BranchDeletionOutcome::ForceDeleted), false);
warn_if_branch_retained(
@@ -2186,6 +2284,20 @@ mod tests {
assert!(branch_only.contains("wt remove -D feature"));
}
+ #[test]
+ fn retained_checked_out_branch_message_names_checkout() {
+ let path = Path::new("/tmp/repo.feature-survivor");
+ let removed = retained_checked_out_branch_message("feature", path, true);
+ assert!(removed.contains("Removed worktree but retained branch"));
+ assert!(removed.contains("/tmp/repo.feature-survivor"));
+ assert!(!removed.contains("moved during deletion"));
+ assert!(!removed.contains("not integrated"));
+
+ let branch_only = retained_checked_out_branch_message("feature", path, false);
+ assert!(branch_only.contains("Retained branch"));
+ assert!(!branch_only.contains("Removed worktree"));
+ }
+
#[test]
fn build_remove_command_with_tail_appends_only_when_present() {
let path = Path::new("/tmp/wt");
@@ -2205,6 +2317,130 @@ mod tests {
);
}
+ /// The detached safe-delete tail samples worktree topology immediately
+ /// before the ref CAS. A checkout created after the tail was planned must
+ /// make the tail succeed without deleting the branch.
+ #[test]
+ fn detached_cas_tail_retains_branch_checked_out_after_planning() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ test.create_branch("feature");
+ let repo = Repository::at(test.root_path()).unwrap();
+ let expected_sha = test.git_output(&["rev-parse", "feature"]);
+ let tail = build_cas_branch_delete_tail(&repo, "feature", Some("main")).unwrap();
+
+ let normalized_tail = tail.replace(&expected_sha, "<sha>");
+ assert!(
+ normalized_tail.contains("awk -v worktrunk_wanted_branch='branch refs/heads/feature'")
+ && normalized_tail.contains("git update-ref -d refs/heads/feature <sha>"),
+ "the guard must associate the exact branch record with the existing CAS: {normalized_tail}"
+ );
+
+ let checkout = test.home_path().join("repo.feature-detached-race");
+ test.run_git(&["worktree", "add", checkout.to_str().unwrap(), "feature"]);
+
+ let guarded = Cmd::new("sh")
+ .args(["-c", &tail])
+ .current_dir(test.root_path())
+ .run()
+ .unwrap();
+ assert!(
+ guarded.status.success(),
+ "a matching checkout is a clean skip"
+ );
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
+ .is_ok(),
+ "the detached guard must retain a newly checked-out branch"
+ );
+ assert!(
+ repo.worktree_at(&checkout)
+ .run_command(&["rev-parse", "--verify", "HEAD"])
+ .is_ok(),
+ "the guarded tail must not orphan the checkout"
+ );
+
+ let failing_awk = format!("awk() {{ return 2; }}; {tail}");
+ let failed_guard = Cmd::new("sh")
+ .args(["-c", &failing_awk])
+ .current_dir(test.root_path())
+ .run()
+ .unwrap();
+ assert!(
+ !failed_guard.status.success(),
+ "an awk/tool failure is not the no-match case"
+ );
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", "refs/heads/feature"])
+ .is_ok(),
+ "a topology-parser failure must fail closed"
+ );
+ }
+
+ /// A lock protects a temporarily absent worktree. The detached parser must
+ /// let it win even over a synthetic record that also says `prunable`.
+ #[test]
+ fn detached_topology_parser_retains_locked_prunable_record() {
+ let porcelain = "worktree /missing/feature
+HEAD 0123456789abcdef
+branch refs/heads/feature
+locked detachable media
+prunable gitdir file points to non-existent location
+
+";
+ let command = format!(
+ "awk -v worktrunk_wanted_branch='branch refs/heads/feature' '{LIVE_BRANCH_WORKTREE_AWK}'"
+ );
+ let output = Cmd::new("sh")
+ .args(["-c", &command])
+ .stdin_bytes(porcelain)
+ .run()
+ .unwrap();
+
+ assert!(output.status.success());
+ assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "live");
+ }
+
+ /// The exact porcelain branch line and ref argument are shell-escaped. A
+ /// prunable stale registration is not a live checkout, so that arm still
+ /// reaches the expected-SHA CAS without interpreting a valid but
+ /// shell-active branch name.
+ #[test]
+ fn detached_cas_tail_escapes_branch_and_deletes_when_not_checked_out() {
+ let test = worktrunk::testing::TestRepo::with_initial_commit();
+ let branch = "feature;touch${IFS}PWNED";
+ test.create_branch(branch);
+ let repo = Repository::at(test.root_path()).unwrap();
+ let tail = build_cas_branch_delete_tail(&repo, branch, Some("main")).unwrap();
+ assert!(
+ tail.contains("'branch refs/heads/feature;touch${IFS}PWNED'"),
+ "the complete porcelain line must be one escaped shell word: {tail}"
+ );
+ assert!(
+ tail.contains("'refs/heads/feature;touch${IFS}PWNED'"),
+ "the CAS ref must be escaped independently: {tail}"
+ );
+
+ let stale = test.home_path().join("repo.feature-stale");
+ test.run_git(&["worktree", "add", stale.to_str().unwrap(), branch]);
+ std::fs::remove_dir_all(&stale).unwrap();
+
+ let output = Cmd::new("sh")
+ .args(["-c", &tail])
+ .current_dir(test.root_path())
+ .run()
+ .unwrap();
+ assert!(output.status.success(), "no checkout should run the CAS");
+ assert!(
+ repo.run_command(&["rev-parse", "--verify", &format!("refs/heads/{branch}")])
+ .is_err(),
+ "the intended branch should be deleted"
+ );
+ assert!(
+ !test.root_path().join("PWNED").exists(),
+ "the branch name must never be interpreted by the shell"
+ );
+ }
+
#[test]
fn test_format_switch_message() {
let path = PathBuf::from("/tmp/test");
diff --git a/src/output/mod.rs b/src/output/mod.rs
index dacff348b..084ce73ae 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -22,10 +22,6 @@
//! - `WORKTRUNK_DIRECTIVE_CD_FILE` — raw path; the wrapper `cd`s to it.
//! - `WORKTRUNK_DIRECTIVE_EXEC_FILE` — arbitrary shell; the wrapper sources it.
//!
-//! The legacy single-file `WORKTRUNK_DIRECTIVE_FILE` env var is still honored
-//! for one release to bridge users who upgraded `wt` without restarting
-//! their shell. See `global` for the `DirectiveMode` selection logic.
-//!
//! When no directive env vars are set (direct binary call):
//! - Commands execute directly.
//! - Shell hints are shown for missing integration.
@@ -42,7 +38,8 @@ pub(crate) mod shell_integration;
// Re-export the public API
pub(crate) use global::{
change_directory, exec_would_be_refused, execute, is_shell_integration_active,
- mark_cwd_removed, post_hook_display_path, pre_hook_display_path, set_verbosity,
+ mark_cwd_removed, post_hook_display_path, pre_hook_display_path,
+ print_outdated_shell_wrapper_hint_once, retired_shell_wrapper_active, set_verbosity,
terminate_output, to_logical_path, was_cwd_removed,
};
// Re-export output handlers
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 50e2c5a5b..3269993a5 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -8,6 +8,7 @@
//!
//! | Condition | Warning | Hint |
//! |-----------|---------|------|
+//! | Outdated wrapper | `Worktree for X @ path, but cannot change directory — shell wrapper is out of date` | `To update the shell wrapper, run wt config shell install` |
//! | Not installed | `Worktree for X @ path, but cannot change directory — shell integration not installed` | `To enable automatic cd, run wt config shell install` |
//! | Installed, not active | `Worktree for X @ path, but cannot change directory — shell integration installed but not active` | `A shell restart usually activates shell integration; if it doesn't, ask an agent to debug with the docs @ https://worktrunk.dev/llms.txt` |
//! | Explicit path | `Worktree for X @ path, but cannot change directory — ran ./wt; shell integration wraps wt` | `To change directory, run wt switch X` |
@@ -20,6 +21,7 @@
//! | Condition | Success | Warning | Hint |
//! |-----------|---------|---------|------|
//! | Shell active | `Created new worktree for X from base @ path` | (none) | (none) |
+//! | Outdated wrapper | `Created new worktree for X from base @ path` | `Cannot change directory — shell wrapper is out of date` | `To update the shell wrapper, run wt config shell install` |
//! | Not installed | `Created new worktree for X from base @ path` | `Cannot change directory — shell integration not installed` | `To enable automatic cd, run wt config shell install` |
//! | Explicit path | `Created new worktree for X from base @ path` | `Cannot change directory — ran ./wt; shell integration wraps wt` | `To change directory, run wt switch X` |
//! | Git subcommand | `Created new worktree for X from base @ path` | `Cannot change directory — ran git wt; running through git prevents cd` | `For automatic cd, invoke directly (with the -): git-wt` |
@@ -29,6 +31,7 @@
//! | Condition | Warning | Hint |
//! |-----------|---------|------|
//! | Shell active | (info) `Switched to worktree for main @ path` | (none) |
+//! | Outdated wrapper | `Cannot change directory — shell wrapper is out of date` | `To update the shell wrapper, run wt config shell install` |
//! | Git subcommand | `Cannot change directory — ran git wt; running through git prevents cd` | `For automatic cd, invoke directly (with the -): git-wt` |
//! | Explicit path | `Cannot change directory — ran ./wt; shell integration wraps wt` | `To change directory, run wt switch main` |
//! | Other | `Cannot change directory — {reason}` | `To enable automatic cd, run wt config shell install` |
@@ -40,6 +43,7 @@
//! | Condition | Action |
//! |-----------|--------|
//! | Git subcommand | Return early (warning already shown) |
+//! | Outdated wrapper | Return early (targeted reinstall hint already shown) |
//! | Unsupported shell | Hint: `Shell integration not yet supported for <shell>` |
//! | No shell detected | Hint: `To enable automatic cd, run wt config shell install` |
//! | Current shell already installed | Hint: `A shell restart usually activates shell integration; …` |
@@ -52,6 +56,7 @@
//!
//! | Reason | Meaning |
//! |--------|---------|
+//! | `shell wrapper is out of date` | Only the retired single-file directive env var is set |
//! | `shell integration not installed` | Shell config doesn't have the `eval` line |
//! | `shell integration installed but not active` | Shell config has `eval` line but wrapper not active |
//! | `ran X; shell integration wraps Y` | Invoked with explicit path (e.g., `./target/debug/wt`) |
@@ -165,6 +170,10 @@ pub(crate) fn should_show_explicit_path_hint() -> bool {
/// any shell. This prevents misleading "restart" advice when e.g. bash has
/// integration but the user is running fish.
pub(crate) fn compute_shell_warning_reason() -> String {
+ if super::retired_shell_wrapper_active() {
+ return "shell wrapper is out of date".to_string();
+ }
+
// Check if the CURRENT shell has integration configured, not just ANY shell
let is_configured = current_shell()
.and_then(|shell| shell.is_shell_configured(&crate::binary_name()).ok())
@@ -412,6 +421,11 @@ pub fn prompt_shell_integration(
if crate::is_git_subcommand() {
return Ok(false);
}
+ // The caller already showed the targeted outdated-wrapper warning and
+ // reinstall hint. Do not follow it with the generic first-run prompt.
+ if super::retired_shell_wrapper_active() {
+ return Ok(false);
+ }
let is_tty = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
diff --git a/src/shell/mod.rs b/src/shell/mod.rs
index e58989593..ba8870593 100644
--- a/src/shell/mod.rs
+++ b/src/shell/mod.rs
@@ -23,8 +23,8 @@ pub use paths::{
line_based_config_paths, nushell_autoload_candidates,
};
pub use utils::{
- AncestorShell, ZSH_PROBE_FLAGS, ancestor_shell, current_shell, current_shell_name,
- detect_zsh_compinit, extract_filename_from_path,
+ AncestorShell, ZshStartupScope, ancestor_shell, current_shell, current_shell_name,
+ extract_filename_from_path, probe_zsh_compdef,
};
/// Validate a command name before embedding it in shell syntax or shell-owned paths.
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
index 6abf074b1..8bc428e34 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
@@ -34,7 +34,7 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
try {
# Run wt with split directive env vars
- # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping (legacy compat)
+ # WORKTRUNK_SHELL selects PowerShell escaping for the EXEC directive payload
$env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
$env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
$env:WORKTRUNK_SHELL = "powershell"
diff --git a/src/shell/utils.rs b/src/shell/utils.rs
index 8794b6856..5425bda4e 100644
--- a/src/shell/utils.rs
+++ b/src/shell/utils.rs
@@ -3,11 +3,6 @@
//! This module provides utilities for detecting the current shell, extracting
//! shell names from paths, and probing shell configuration state.
-use std::process::{Command, Stdio};
-use std::time::Duration;
-
-use wait_timeout::ChildExt;
-
use super::Shell;
/// Extract executable name from a path, stripping `.exe` on Windows.
@@ -303,19 +298,36 @@ fn process_name_and_ppid(_pid: u32) -> Option<(String, u32)> {
None
}
-/// Leading flags for the interactive zsh compinit probe.
-///
-/// `+m` (disable job control) is load-bearing — see the call site and issue
-/// #3322. It must precede `-ic` so zsh parses it as an option, not a command
-/// argument.
-pub const ZSH_PROBE_FLAGS: [&str; 2] = ["+m", "-ic"];
+const ZSH_COMPDEF_PROBE: &str = "(( $+functions[compdef] ))";
+const ZSH_USER_ONLY_PROBE_ARGS: [&str; 4] = ["--no-globalrcs", "+m", "-ic", ZSH_COMPDEF_PROBE];
+const ZSH_GLOBAL_AND_USER_PROBE_ARGS: [&str; 3] = ["+m", "-ic", ZSH_COMPDEF_PROBE];
+
+/// Which startup files an interactive zsh probe should source.
+#[derive(Debug, Clone, Copy)]
+pub enum ZshStartupScope {
+ /// Source the user's startup files while excluding global rc files after
+ /// the always-read `/etc/zshenv`.
+ UserOnly,
+ /// Source both global and user startup files, as a normal interactive zsh
+ /// session does.
+ GlobalAndUser,
+}
-/// Detect if user's zsh has compinit enabled by probing for the compdef function.
+impl ZshStartupScope {
+ fn probe_args(self) -> &'static [&'static str] {
+ match self {
+ Self::UserOnly => &ZSH_USER_ONLY_PROBE_ARGS,
+ Self::GlobalAndUser => &ZSH_GLOBAL_AND_USER_PROBE_ARGS,
+ }
+ }
+}
+
+/// Probe whether an interactive zsh defines the `compdef` function.
///
/// Zsh's completion system (compinit) must be explicitly enabled - it's not on by default.
/// When compinit runs, it defines the `compdef` function. We probe for this function
-/// by spawning an interactive zsh that sources the user's config, then checking if
-/// compdef exists.
+/// by spawning an interactive zsh with the requested startup scope, then checking
+/// the command's exit status.
///
/// This approach matches what other CLI tools (hugo, podman, dvc) recommend: detect
/// the state and advise users, rather than trying to auto-enable compinit.
@@ -324,11 +336,7 @@ pub const ZSH_PROBE_FLAGS: [&str; 2] = ["+m", "-ic"];
/// - `Some(true)` if compinit is enabled (compdef function exists)
/// - `Some(false)` if compinit is NOT enabled
/// - `None` if detection failed (zsh not installed, timeout, error)
-///
-// Config show skips global rcs, reads the exit status, and uses `Cmd`; this
-// probe sources global rcs, reads marker output, and manages a raw `Command`.
-// Only the load-bearing zsh flags are shared.
-pub fn detect_zsh_compinit() -> Option<bool> {
+pub fn probe_zsh_compdef(startup_scope: ZshStartupScope) -> Option<bool> {
// Allow tests to bypass this check since zsh subprocess behavior varies across CI envs
if std::env::var("WORKTRUNK_TEST_COMPINIT_CONFIGURED").is_ok() {
return Some(true); // Assume compinit is configured
@@ -339,26 +347,17 @@ pub fn detect_zsh_compinit() -> Option<bool> {
return Some(false); // Force warning to appear
}
- // Probe command: check if compdef function exists (proof compinit ran).
- // We use unique markers (__WT_COMPINIT_*) to avoid false matches from any
- // output the user's zshrc might produce during startup.
- let probe_cmd =
- r#"(( $+functions[compdef] )) && echo __WT_COMPINIT_YES__ || echo __WT_COMPINIT_NO__"#;
-
- tracing::debug!(command = %probe_cmd, "$ zsh +m -ic '{}' (probe)", probe_cmd);
-
- let mut cmd = Command::new("zsh");
// `+m` disables job control so the interactive probe doesn't grab wt's
// controlling terminal. An interactive zsh with job control on `tcsetpgrp`s
// to claim the terminal foreground; if the 2s timeout kills it before it
// restores that, wt is left in a background process group and the next
// terminal write raises SIGTTOU. See issue #3322. `+m` must precede `-ic`
// so it's parsed as an option rather than a command argument.
- cmd.args(ZSH_PROBE_FLAGS)
- .arg(probe_cmd)
- .stdin(Stdio::null()) // Prevent compinit from prompting interactively
- .stdout(Stdio::piped())
- .stderr(Stdio::null()) // Suppress user's zsh startup messages
+ //
+ // `Cmd::run` supplies null stdin and captures stdout/stderr, preventing
+ // startup prompts and messages from reaching the terminal.
+ let output = crate::shell_exec::Cmd::new("zsh")
+ .args(startup_scope.probe_args().iter().copied())
// Suppress zsh's "insecure directories" warning from compinit.
//
// When fpath contains directories with insecure permissions, compinit prompts:
@@ -376,47 +375,36 @@ pub fn detect_zsh_compinit() -> Option<bool> {
//
// Safe to suppress because we're only probing shell state, not doing anything
// security-sensitive, and this only affects our subprocess.
- .env("ZSH_DISABLE_COMPFIX", "true");
- crate::shell_exec::scrub_directive_env_vars(&mut cmd);
- let mut child = cmd.spawn().ok()?;
-
- let timeout = Duration::from_secs(2);
-
- match child.wait_timeout(timeout) {
- Ok(Some(_status)) => {
- // Child exited: pipe write ends are closed, safe to read sequentially.
- use std::io::Read;
- let mut buf = Vec::new();
- child.stdout.as_mut()?.read_to_end(&mut buf).ok()?;
- let stdout = String::from_utf8_lossy(&buf);
- Some(stdout.contains("__WT_COMPINIT_YES__"))
- }
- Ok(None) => {
- // Timed out - kill and clean up
- let _ = child.kill();
- let _ = child.wait();
- None
- }
- Err(_) => None,
- }
+ .env("ZSH_DISABLE_COMPFIX", "true")
+ .timeout(std::time::Duration::from_secs(2))
+ .run()
+ .ok()?;
+
+ Some(output.status.success())
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
+ #[cfg(unix)]
+ use std::process::{Command, Stdio};
+ #[cfg(unix)]
+ use std::time::Duration;
- /// Regression guard for #3322: the interactive zsh compinit probe must
- /// disable job control (`+m`) so it can't grab wt's controlling terminal —
- /// otherwise a timeout-kill leaves the parent in a background process group
- /// and the next terminal write raises SIGTTOU.
+ /// The two callers intentionally observe different startup scopes. Both
+ /// disable job control before `-ic` so a timeout cannot strand wt in a
+ /// background process group (#3322).
#[test]
- fn test_zsh_probe_disables_job_control() {
+ fn test_zsh_probe_startup_scopes() {
+ assert_eq!(
+ ZshStartupScope::UserOnly.probe_args(),
+ ["--no-globalrcs", "+m", "-ic", "(( $+functions[compdef] ))"]
+ );
assert_eq!(
- ZSH_PROBE_FLAGS[0], "+m",
- "job control must be disabled before -ic (#3322)"
+ ZshStartupScope::GlobalAndUser.probe_args(),
+ ["+m", "-ic", "(( $+functions[compdef] ))"]
);
- assert!(ZSH_PROBE_FLAGS.contains(&"-ic"));
}
// ==========================================================================
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index d2149f364..77d1ce105 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -507,12 +507,12 @@ pub const DIRECTIVE_CD_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_CD_FILE";
/// since the body is user-authored just like a top-level `wt --execute`.
pub const DIRECTIVE_EXEC_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_EXEC_FILE";
-/// Legacy pre-split directive file env var. Honored for one release so users
-/// who upgraded `wt` without restarting their shell still get shell integration
-/// from their current session's old wrapper. When only this is set (no new
-/// vars), wt writes shell-format directives to it. Remove in the next breaking
-/// release.
-pub const DIRECTIVE_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_FILE";
+/// Retired pre-split directive file env var.
+///
+/// wt never writes to or passes this file through, but still removes the
+/// variable from child environments so an old wrapper cannot expose a file
+/// that its parent shell will source.
+pub const RETIRED_DIRECTIVE_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_FILE";
/// Scrub all directive file env vars from a `std::process::Command`.
///
@@ -522,7 +522,7 @@ pub const DIRECTIVE_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_FILE";
pub fn scrub_directive_env_vars(cmd: &mut std::process::Command) {
cmd.env_remove(DIRECTIVE_CD_FILE_ENV_VAR);
cmd.env_remove(DIRECTIVE_EXEC_FILE_ENV_VAR);
- cmd.env_remove(DIRECTIVE_FILE_ENV_VAR);
+ cmd.env_remove(RETIRED_DIRECTIVE_FILE_ENV_VAR);
}
/// Scrub the git-discovery path vars ([`INHERITED_GIT_PATH_VARS`]) from a child
@@ -664,8 +664,8 @@ pub enum ShellEscapeMode {
/// Escape mode for a payload the *active directive shell* will parse.
///
/// Reads [`WORKTRUNK_SHELL_ENV_VAR`] — the single source of truth for the
-/// per-shell escaping decision shared by `escape_legacy_cd`, the `--execute`
-/// command template, and its trailing args. `powershell` ⇒
+/// per-shell escaping decision shared by the `--execute` command template and
+/// its trailing args. `powershell` ⇒
/// [`ShellEscapeMode::PowerShell`], `fish` ⇒ [`ShellEscapeMode::Fish`], any
/// other value or absent ⇒ [`ShellEscapeMode::Posix`].
pub fn directive_shell_escape_mode() -> ShellEscapeMode {
@@ -1052,10 +1052,6 @@ pub struct Cmd {
/// user typing it at the top level. Project aliases and hooks must NEVER
/// set this — they could inject arbitrary shell into the parent session.
directive_exec_file: Option<std::path::PathBuf>,
- /// When set, re-adds the legacy `WORKTRUNK_DIRECTIVE_FILE` env var. Used in
- /// legacy-wrapper compat mode to preserve pre-split behavior for alias/hook
- /// bodies running under an old shell wrapper.
- directive_legacy_file: Option<std::path::PathBuf>,
}
struct ExternalCommandLog {
@@ -1197,7 +1193,6 @@ impl Cmd {
external_label: None,
directive_cd_file: None,
directive_exec_file: None,
- directive_legacy_file: None,
}
}
@@ -1277,9 +1272,9 @@ impl Cmd {
// Prevent subprocesses from writing shell directives (security).
// Applied last so it can't be re-added by user-provided envs.
- // `stream()` selectively re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` (and
- // the legacy var, in compat mode) for trusted contexts — but never
- // `WORKTRUNK_DIRECTIVE_EXEC_FILE`, which carries arbitrary shell.
+ // `stream()` selectively re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` for
+ // trusted contexts, and `WORKTRUNK_DIRECTIVE_EXEC_FILE` only for
+ // trusted user-source aliases.
scrub_directive_env_vars(cmd);
}
@@ -1488,17 +1483,6 @@ impl Cmd {
self
}
- /// Pass the legacy (pre-split) directive file through to the child process.
- ///
- /// Used only in legacy-wrapper compat mode. Preserves pre-split behavior
- /// for alias/hook bodies running under an old shell wrapper that still
- /// sets `WORKTRUNK_DIRECTIVE_FILE`. Remove together with the legacy env
- /// var in the next breaking release.
- pub fn directive_legacy_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
- self.directive_legacy_file = Some(path.into());
- self
- }
-
/// Execute the command and return its output.
///
/// Captures stdout/stderr and returns them in `Output`. For interactive
@@ -1515,9 +1499,7 @@ impl Cmd {
"Cmd::shell() commands must use .stream(), not .run()"
);
debug_assert!(
- self.directive_cd_file.is_none()
- && self.directive_exec_file.is_none()
- && self.directive_legacy_file.is_none(),
+ self.directive_cd_file.is_none() && self.directive_exec_file.is_none(),
"directive_*_file is only applied by .stream(), not .run()"
);
@@ -1656,10 +1638,8 @@ impl Cmd {
debug_assert!(
self.directive_cd_file.is_none()
&& self.directive_exec_file.is_none()
- && self.directive_legacy_file.is_none()
&& next.directive_cd_file.is_none()
- && next.directive_exec_file.is_none()
- && next.directive_legacy_file.is_none(),
+ && next.directive_exec_file.is_none(),
"directive_*_file is only applied by .stream(), not pipe_into"
);
@@ -1879,9 +1859,6 @@ impl Cmd {
if let Some(ref path) = self.directive_exec_file {
cmd.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);
}
- if let Some(ref path) = self.directive_legacy_file {
- cmd.env(DIRECTIVE_FILE_ENV_VAR, path);
- }
if let Err(e) = self.check_spawn_preconditions() {
// Nothing spawned yet — emit a one-shot failed record (the trace
@@ -2087,8 +2064,7 @@ impl Cmd {
&& self.timeout.is_none()
&& self.external_label.is_none()
&& self.directive_cd_file.is_none()
- && self.directive_exec_file.is_none()
- && self.directive_legacy_file.is_none(),
+ && self.directive_exec_file.is_none(),
"delayed_stream does not support stdin/timeout/external/directive options"
);
@@ -2250,6 +2226,34 @@ pub fn forward_signal_with_escalation(pgid: i32, sig: i32) {
mod tests {
use super::*;
+ #[test]
+ fn test_scrub_directive_env_vars_includes_retired_variable() {
+ assert_eq!(RETIRED_DIRECTIVE_FILE_ENV_VAR, "WORKTRUNK_DIRECTIVE_FILE");
+
+ let mut cmd = std::process::Command::new("child");
+ for var in [
+ DIRECTIVE_CD_FILE_ENV_VAR,
+ DIRECTIVE_EXEC_FILE_ENV_VAR,
+ RETIRED_DIRECTIVE_FILE_ENV_VAR,
+ ] {
+ cmd.env(var, "directive");
+ }
+
+ scrub_directive_env_vars(&mut cmd);
+
+ for var in [
+ DIRECTIVE_CD_FILE_ENV_VAR,
+ DIRECTIVE_EXEC_FILE_ENV_VAR,
+ RETIRED_DIRECTIVE_FILE_ENV_VAR,
+ ] {
+ assert!(
+ cmd.get_envs()
+ .any(|(key, value)| { key == std::ffi::OsStr::new(var) && value.is_none() }),
+ "{var} should be removed from the child environment"
+ );
+ }
+ }
+
/// The only test allowed to set `FOREGROUND_THREAD` (a process-wide
/// set-once): with it unset, `is_foreground_thread()` is false everywhere,
/// which is the state every other test runs under.
diff --git a/src/testing/mock_commands.rs b/src/testing/mock_commands.rs
index 0d5dcb70e..e17a4a15a 100644
--- a/src/testing/mock_commands.rs
+++ b/src/testing/mock_commands.rs
@@ -326,81 +326,6 @@ API authentication.
.write(bin_dir);
}
-/// Create a mock uv command for dependency sync and dev server.
-pub fn create_mock_uv_sync(bin_dir: &Path) {
- MockConfig::new("uv")
- .command(
- "sync",
- MockResponse::output(
- "
- Resolved 24 packages in 145ms
- Installed 24 packages in 1.2s
-",
- ),
- )
- .command(
- "run",
- MockResponse::output(
- "
- Starting dev server on http://localhost:3000...
-",
- ),
- )
- .write(bin_dir);
-}
-
-/// Create mock uv that delegates to pytest/ruff commands.
-///
-/// Note: This mock doesn't actually delegate - it provides fixed output.
-/// For tests needing real delegation, set up both commands separately.
-pub fn create_mock_uv_pytest_ruff(bin_dir: &Path) {
- MockConfig::new("uv")
- .command(
- "run",
- MockResponse::output(
- "
-============================= test session starts ==============================
-collected 3 items
-
-tests/test_auth.py::test_login_success PASSED [ 33%]
-tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
-tests/test_auth.py::test_token_validation PASSED [100%]
-
-============================== 3 passed in 0.8s ===============================
-",
- ),
- )
- .write(bin_dir);
-}
-
-/// Create a mock pytest command with test output.
-pub fn create_mock_pytest(bin_dir: &Path) {
- MockConfig::new("pytest")
- .command(
- "_default",
- MockResponse::output(
- "
-============================= test session starts ==============================
-collected 3 items
-
-tests/test_auth.py::test_login_success PASSED [ 33%]
-tests/test_auth.py::test_login_invalid_password PASSED [ 66%]
-tests/test_auth.py::test_token_validation PASSED [100%]
-
-============================== 3 passed in 0.8s ===============================
-",
- ),
- )
- .write(bin_dir);
-}
-
-/// Create a mock ruff command.
-pub fn create_mock_ruff(bin_dir: &Path) {
- MockConfig::new("ruff")
- .command("check", MockResponse::output("\nAll checks passed!\n\n"))
- .write(bin_dir);
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/testing/mod.rs b/src/testing/mod.rs
index fd48e60f6..a991ff482 100644
--- a/src/testing/mod.rs
+++ b/src/testing/mod.rs
@@ -1108,25 +1108,6 @@ pub fn configure_directive_cd_only(cmd: &mut Command, cd_path: &Path) {
cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", cd_path);
}
-/// Create a temporary file for legacy single-file directive output, in a
-/// directory of its own (see `directive_temp_dir` for why).
-///
-/// Used to test the legacy fallback path where an old shell wrapper sets
-/// `WORKTRUNK_DIRECTIVE_FILE`. Returns `(path, guard)`.
-pub fn legacy_directive_file() -> (PathBuf, TempDir) {
- let dir = directive_temp_dir();
- let path = create_empty(dir.path().join("directive"));
- (path, dir)
-}
-
-/// Configure a Command to use the legacy single-file directive protocol.
-///
-/// Sets `WORKTRUNK_DIRECTIVE_FILE` env var (no new vars) to simulate an
-/// outdated shell wrapper that hasn't been updated to the split protocol.
-pub fn configure_legacy_directive_file(cmd: &mut Command, path: &Path) {
- cmd.env("WORKTRUNK_DIRECTIVE_FILE", path);
-}
-
/// Set home environment variables for commands that rely on isolated temp homes.
///
/// Sets both Unix (`HOME`, `XDG_CONFIG_HOME`) and Windows (`USERPROFILE`) variables
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index 53f86d277..6117465f5 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -30,7 +30,7 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
try {
# Run wt with split directive env vars
- # WORKTRUNK_SHELL tells the binary to use PowerShell-compatible escaping (legacy compat)
+ # WORKTRUNK_SHELL selects PowerShell escaping for the EXEC directive payload
$env:WORKTRUNK_DIRECTIVE_CD_FILE = $cdFile
$env:WORKTRUNK_DIRECTIVE_EXEC_FILE = $execFile
$env:WORKTRUNK_SHELL = "powershell"
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index 50bd7b883..fdd35fead 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -2174,16 +2174,25 @@ fn test_complete_custom_subcommand_listed(repo: TestRepo) {
#[rstest]
fn test_complete_custom_subcommand_forwards(repo: TestRepo) {
use std::os::unix::fs::PermissionsExt;
+ use worktrunk::shell_exec::RETIRED_DIRECTIVE_FILE_ENV_VAR;
+
repo.commit("initial");
// Create a real shell script that outputs completions (not mock-stub, which
// needs WORKTRUNK_TEST_MOCK_CONFIG_DIR and doesn't know about COMPLETE env
// var).
let ext_dir = tempfile::tempdir().unwrap();
+ let retired_file = ext_dir.path().join("retired");
+ std::fs::write(&retired_file, "").unwrap();
let script = ext_dir.path().join("wt-testext");
std::fs::write(
&script,
- "#!/bin/sh\nprintf '%s\\n%s' '--custom-flag' '--another'\n",
+ r#"#!/bin/sh
+if [ -n "${WORKTRUNK_DIRECTIVE_FILE+x}" ]; then
+ printf 'retired write\n' >> "$WORKTRUNK_DIRECTIVE_FILE"
+fi
+printf '%s\n%s\n%s' '--custom-flag' '--another' "retired:${WORKTRUNK_DIRECTIVE_FILE-unset}"
+"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
@@ -2191,6 +2200,7 @@ fn test_complete_custom_subcommand_forwards(repo: TestRepo) {
// Complete "wt testext --" — should forward to wt-testext and show its output
let mut cmd = repo.completion_cmd(&["wt", "testext", "--"]);
prepend_path(&mut cmd, ext_dir.path());
+ cmd.env(RETIRED_DIRECTIVE_FILE_ENV_VAR, &retired_file);
let output = cmd.output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -2199,4 +2209,13 @@ fn test_complete_custom_subcommand_forwards(repo: TestRepo) {
stdout.contains("--custom-flag"),
"Forwarded completion output missing '--custom-flag': {stdout}"
);
+ assert!(
+ stdout.contains("retired:unset"),
+ "Forwarded completion received the retired directive variable: {stdout}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(&retired_file).unwrap(),
+ "",
+ "the retired directive file must remain untouched"
+ );
}
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index adaa6aea5..9de60b266 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -3,6 +3,7 @@ use crate::common::{
setup_home_snapshot_settings, setup_snapshot_settings, setup_snapshot_settings_with_home,
temp_home, wt_command,
};
+use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::fs;
@@ -1342,6 +1343,48 @@ fn test_config_show_full_not_configured(mut repo: TestRepo, temp_home: TempDir)
});
}
+#[rstest]
+fn test_config_show_full_legacy_forge_alias(mut repo: TestRepo, temp_home: TempDir) {
+ repo.setup_mock_ci_tools_unauthenticated();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "git@github-personal:owner/repo.git",
+ ]);
+
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(
+ global_config_dir.join("config.toml"),
+ "worktree-path = \"../{{ repo }}.{{ branch }}\"",
+ )
+ .unwrap();
+
+ let mut cmd = repo.wt_command();
+ cmd.env("WORKTRUNK_TEST_LATEST_VERSION", env!("CARGO_PKG_VERSION"));
+ cmd.arg("config")
+ .arg("show")
+ .arg("--full")
+ .current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ set_xdg_config_path(&mut cmd, temp_home.path());
+
+ let output = cmd.output().unwrap();
+ assert!(
+ output.status.success(),
+ "config show should succeed:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let alias_lines = stdout
+ .lines()
+ .filter(|line| line.contains("SSH host alias"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert_snapshot!(alias_lines, @r#"▲ SSH host alias github-personal is not auto-detected as a forge; enable CI status and wt switch --prs with forge.platform = "github" @ .config/wt.toml"#);
+}
+
#[rstest]
fn test_config_show_full_command_not_found(mut repo: TestRepo, temp_home: TempDir) {
// Setup mock gh/glab for deterministic BINARIES output
@@ -2000,16 +2043,17 @@ fn test_config_show_shell_integration_active(mut repo: TestRepo, temp_home: Temp
cmd.arg("config").arg("show").current_dir(repo.root_path());
set_temp_home_env(&mut cmd, temp_home.path());
set_xdg_config_path(&mut cmd, temp_home.path());
- // Set WORKTRUNK_DIRECTIVE_FILE to simulate shell integration being active
+ // Set the cd directive file to simulate shell integration being active.
cmd.env("WORKTRUNK_DIRECTIVE_CD_FILE", &directive_file);
assert_cmd_snapshot!(cmd);
});
}
-/// When shell integration is active at runtime (WORKTRUNK_DIRECTIVE_FILE set) but the
-/// init line is NOT in the scanned config file (e.g., sourced from another file), config
-/// show should report "Configured ... (not found in ...)" instead of "Not configured".
+/// When shell integration is active at runtime (`WORKTRUNK_DIRECTIVE_CD_FILE` set) but
+/// the init line is NOT in the scanned config file (e.g., sourced from another file),
+/// config show should report "Configured ... (not found in ...)" instead of
+/// "Not configured".
/// Regression test for https://github.com/max-sixty/worktrunk/issues/1306
#[rstest]
fn test_config_show_shell_active_but_not_in_config_file(mut repo: TestRepo, temp_home: TempDir) {
diff --git a/tests/integration_tests/custom.rs b/tests/integration_tests/custom.rs
index 756902880..4aec835db 100644
--- a/tests/integration_tests/custom.rs
+++ b/tests/integration_tests/custom.rs
@@ -82,6 +82,65 @@ fn custom_subcommand_accepts_non_utf8_forwarded_arg() {
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "custom ran");
}
+#[cfg(unix)]
+#[test]
+fn custom_subcommand_scrubs_retired_directive_and_preserves_split_files() {
+ use std::os::unix::fs::PermissionsExt;
+ use worktrunk::shell_exec::{
+ DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, RETIRED_DIRECTIVE_FILE_ENV_VAR,
+ };
+
+ let dir = TempDir::new().unwrap();
+ let retired_file = dir.path().join("retired");
+ let cd_file = dir.path().join("cd");
+ let exec_file = dir.path().join("exec");
+ std::fs::write(&retired_file, "").unwrap();
+ std::fs::write(&cd_file, "").unwrap();
+ std::fs::write(&exec_file, "").unwrap();
+
+ let script = dir.path().join("wt-wt-test-extcmd-directives");
+ std::fs::write(
+ &script,
+ r#"#!/bin/sh
+if [ -n "${WORKTRUNK_DIRECTIVE_FILE+x}" ]; then
+ printf 'retired write\n' >> "$WORKTRUNK_DIRECTIVE_FILE"
+fi
+printf 'retired=%s\ncd=%s\nexec=%s\n' "${WORKTRUNK_DIRECTIVE_FILE-unset}" "${WORKTRUNK_DIRECTIVE_CD_FILE-unset}" "${WORKTRUNK_DIRECTIVE_EXEC_FILE-unset}"
+"#,
+ )
+ .unwrap();
+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
+
+ let mut cmd = wt_command();
+ prepend_path(&mut cmd, dir.path());
+ cmd.env(RETIRED_DIRECTIVE_FILE_ENV_VAR, &retired_file)
+ .env(DIRECTIVE_CD_FILE_ENV_VAR, &cd_file)
+ .env(DIRECTIVE_EXEC_FILE_ENV_VAR, &exec_file)
+ .arg("wt-test-extcmd-directives");
+
+ let output = cmd.output().expect("failed to run wt");
+ assert!(
+ output.status.success(),
+ "expected success, stderr: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(stdout.contains("retired=unset"), "{stdout}");
+ assert!(
+ stdout.contains(&format!("cd={}", cd_file.display())),
+ "{stdout}"
+ );
+ assert!(
+ stdout.contains(&format!("exec={}", exec_file.display())),
+ "{stdout}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(&retired_file).unwrap(),
+ "",
+ "the retired directive file must remain untouched"
+ );
+}
+
#[test]
fn custom_subcommand_not_found_prints_clap_error() {
let mut cmd = wt_command();
diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rs
index 0084093ad..105ec9208 100644
--- a/tests/integration_tests/directives.rs
+++ b/tests/integration_tests/directives.rs
@@ -1,6 +1,5 @@
use crate::common::{
- TestRepo, configure_directive_cd_only, configure_directive_files,
- configure_legacy_directive_file, directive_files, legacy_directive_file, repo,
+ TestRepo, configure_directive_cd_only, configure_directive_files, directive_files, repo,
repo_with_feature_worktree, repo_with_remote, repo_with_remote_and_feature,
setup_snapshot_settings, wt_command,
};
@@ -20,132 +19,120 @@ use std::path::Path;
// - WORKTRUNK_DIRECTIVE_EXEC_FILE: wt writes arbitrary shell (e.g. from --execute).
// The shell wrapper sources the file.
-// ============================================================================
-// Legacy Directive File Tests (single WORKTRUNK_DIRECTIVE_FILE)
-// ============================================================================
-// These tests verify the legacy single-file protocol still works for users
-// who haven't restarted their shell after upgrading.
-
#[rstest]
-fn test_switch_legacy_directive_file(#[from(repo_with_remote)] mut repo: TestRepo) {
- let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = legacy_directive_file();
-
- let mut settings = setup_snapshot_settings(&repo);
- // Normalize the directive file cd path
- settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- configure_legacy_directive_file(&mut cmd, &directive_path);
- cmd.arg("switch")
- .arg("feature")
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!(cmd);
-
- // Verify directive file contains cd command (legacy format)
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
- assert!(
- directives.contains("cd '"),
- "Legacy directive file should contain cd command, got: {}",
- directives
- );
- });
-}
-
-/// Legacy directive file in PowerShell mode: single quotes are doubled
-/// instead of using POSIX escaping.
-#[rstest]
-fn test_switch_legacy_directive_file_powershell(#[from(repo_with_remote)] mut repo: TestRepo) {
- let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = legacy_directive_file();
+fn test_switch_retired_directive_file_refuses_execute_after_switch(
+ #[from(repo_with_remote)] mut repo: TestRepo,
+) {
+ let feature_wt = repo.add_worktree("feature");
+ let directive_dir = tempfile::TempDir::new().unwrap();
+ let directive_path = directive_dir.path().join("directive");
+ let execute_marker = feature_wt.join("retired-execute-ran");
+ fs::write(&directive_path, "").unwrap();
let settings = setup_snapshot_settings(&repo);
-
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_legacy_directive_file(&mut cmd, &directive_path);
- cmd.env("WORKTRUNK_SHELL", "powershell");
+ cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_path);
cmd.arg("switch")
.arg("feature")
+ .arg("--execute")
+ .arg("echo spawned > retired-execute-ran")
.current_dir(repo.root_path());
assert_cmd_snapshot!(cmd);
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Legacy directive file should contain cd command, got: {directives}",
+ !execute_marker.exists(),
+ "wt must never spawn an --execute payload from the retired wrapper"
+ );
+ assert_eq!(
+ fs::read_to_string(&directive_path).unwrap(),
+ "",
+ "wt must never write to the retired directive file"
);
});
}
-/// Legacy directive file in fish mode: the `cd` path is fish-escaped (`\`
-/// doubled, `'` backslash-escaped) instead of using the POSIX `'\''` idiom,
-/// which the fish wrapper's `eval` would mis-parse.
#[rstest]
-fn test_switch_legacy_directive_file_fish(#[from(repo_with_remote)] mut repo: TestRepo) {
- let _feature_wt = repo.add_worktree("feature");
- let (directive_path, _guard) = legacy_directive_file();
+fn test_switch_retired_directive_file_refuses_execute_when_already_at(
+ #[from(repo_with_remote)] mut repo: TestRepo,
+) {
+ let feature_wt = repo.add_worktree("feature");
+ let directive_dir = tempfile::TempDir::new().unwrap();
+ let directive_path = directive_dir.path().join("directive");
+ let execute_marker = feature_wt.join("retired-execute-ran");
+ fs::write(&directive_path, "").unwrap();
let settings = setup_snapshot_settings(&repo);
-
settings.bind(|| {
let mut cmd = wt_command();
repo.configure_wt_cmd(&mut cmd);
- configure_legacy_directive_file(&mut cmd, &directive_path);
- cmd.env("WORKTRUNK_SHELL", "fish");
+ cmd.env("WORKTRUNK_DIRECTIVE_FILE", &directive_path);
cmd.arg("switch")
.arg("feature")
- .current_dir(repo.root_path());
+ .arg("--execute")
+ .arg("echo spawned > retired-execute-ran")
+ .current_dir(&feature_wt);
assert_cmd_snapshot!(cmd);
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
assert!(
- directives.contains("cd '"),
- "Legacy directive file should contain cd command, got: {directives}",
+ !execute_marker.exists(),
+ "wt must never spawn an --execute payload from the retired wrapper"
+ );
+ assert_eq!(
+ fs::read_to_string(&directive_path).unwrap(),
+ "",
+ "wt must never write to the retired directive file"
);
});
}
-/// Legacy directive file with --execute: both cd and execute commands
-/// should be written to the single file.
+/// A current split wrapper may inherit the retired variable from an older
+/// parent shell. The split files still take precedence: both directives land
+/// in their dedicated files, and the retired file remains untouched.
#[rstest]
-fn test_switch_legacy_directive_file_with_execute(#[from(repo_with_remote)] repo: TestRepo) {
- let (directive_path, _guard) = legacy_directive_file();
-
- let mut settings = setup_snapshot_settings(&repo);
- settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.configure_wt_cmd(&mut cmd);
- configure_legacy_directive_file(&mut cmd, &directive_path);
- cmd.args([
- "switch",
- "--create",
- "exec-legacy",
- "--execute",
- "echo hello",
- ])
- .current_dir(repo.root_path());
+fn test_split_directive_files_win_over_retired_variable(
+ #[from(repo_with_remote)] mut repo: TestRepo,
+) {
+ let _feature_wt = repo.add_worktree("feature");
+ let (cd_path, exec_path, _guard) = directive_files();
+ let retired_dir = tempfile::TempDir::new().unwrap();
+ let retired_path = retired_dir.path().join("directive");
+ fs::write(&retired_path, "").unwrap();
- assert_cmd_snapshot!(cmd);
+ let mut cmd = repo.wt_command();
+ configure_directive_files(&mut cmd, &cd_path, &exec_path);
+ let output = cmd
+ .env("WORKTRUNK_DIRECTIVE_FILE", &retired_path)
+ .args(["switch", "feature", "--execute", "echo through-split"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
- let directives = std::fs::read_to_string(&directive_path).unwrap_or_default();
- assert!(
- directives.contains("cd '"),
- "Legacy directive file should contain cd command, got: {directives}",
- );
- assert!(
- directives.contains("echo hello"),
- "Legacy directive file should contain execute command, got: {directives}",
- );
- });
+ assert!(
+ output.status.success(),
+ "split directives must remain active when the retired variable is also set.\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ !fs::read_to_string(&cd_path)
+ .unwrap_or_default()
+ .trim()
+ .is_empty(),
+ "the split CD file must receive the target path"
+ );
+ assert_eq!(
+ fs::read_to_string(&exec_path).unwrap(),
+ "echo through-split\n",
+ "the split EXEC file must receive the command"
+ );
+ assert_eq!(
+ fs::read_to_string(&retired_path).unwrap(),
+ "",
+ "wt must never write to the retired directive file"
+ );
}
/// When only the CD file is set (EXEC scrubbed — running inside an alias/hook),
@@ -680,7 +667,7 @@ cd = false
}
// ============================================================================
-// Non-Directive Mode Tests (no WORKTRUNK_DIRECTIVE_FILE)
+// Non-Directive Mode Tests (no split directive env vars)
// ============================================================================
#[rstest]
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 870d6313f..7c53897f8 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -2,6 +2,7 @@ use crate::common::{
DAY, HOUR, MINUTE, TestRepo, list_snapshots, make_snapshot_cmd, repo, repo_with_remote,
setup_snapshot_settings_for_paths, wt_command,
};
+use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -442,6 +443,51 @@ fn test_list_json_repo_url_from_ssh_remote(repo: TestRepo) {
);
}
+/// CI collection reports the intentional exact-label compatibility break once,
+/// while an explicit forge platform resolves and suppresses the diagnostic.
+/// The statusline takes its separate silent collection path.
+#[rstest]
+fn test_list_ci_legacy_forge_alias_diagnostic(mut repo: TestRepo) {
+ repo.setup_mock_gh();
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "git@github-personal:owner/repo.git",
+ ]);
+
+ let output = repo.wt_command().args(["list", "--full"]).output().unwrap();
+ assert!(output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let alias_lines = stderr
+ .lines()
+ .filter(|line| line.contains("SSH host alias"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert_snapshot!(alias_lines, @r#"▲ SSH host alias github-personal is not auto-detected as a forge; enable CI status and wt switch --prs with forge.platform = "github" @ .config/wt.toml"#);
+
+ let statusline = repo
+ .wt_command()
+ .args(["list", "statusline", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(statusline.status.success());
+ let statusline_stderr = String::from_utf8_lossy(&statusline.stderr);
+ assert!(
+ statusline_stderr.is_empty(),
+ "statusline must remain silent:\n{statusline_stderr}"
+ );
+
+ repo.write_project_config("[forge]\nplatform = \"github\"\n");
+ let configured = repo.wt_command().args(["list", "--full"]).output().unwrap();
+ assert!(configured.status.success());
+ let configured_stderr = String::from_utf8_lossy(&configured.stderr);
+ assert!(
+ !configured_stderr.contains("SSH host alias"),
+ "explicit forge config should suppress the diagnostic:\n{configured_stderr}"
+ );
+}
+
#[rstest]
fn test_list_json_configured_azure_generic_remote_is_unknown(repo: TestRepo) {
repo.run_git(&[
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index ab1f6f407..822945e48 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -207,7 +207,7 @@ fn test_remove_locked_detached_worktree(mut repo: TestRepo) {
repo.lock_worktree("locked-detached", Some("Detached and locked"));
// Try to remove from within the locked detached worktree - should fail
- // This exercises the RemoveTarget::Current path for locked worktrees
+ // This exercises exact-path removal of the current locked worktree.
assert_cmd_snapshot!(make_snapshot_cmd(
&repo,
"remove",
@@ -4257,6 +4257,47 @@ fn test_remove_last_live_checkout_deletes_branch(mut repo: TestRepo) {
);
}
+/// Planning sees one checkout, then an approved `pre-remove` hook creates a
+/// duplicate. The final topology guard must retain the branch and report the
+/// actual checkout race, not mislabel it as ref movement or failed integration.
+#[rstest]
+fn test_pre_remove_hook_new_checkout_retains_branch(mut repo: TestRepo) {
+ let survivor = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.feature-hook-survivor");
+ let hook = "git worktree add --force ../repo.feature-hook-survivor feature-hook-checkout";
+ repo.write_project_config(&format!("pre-remove = {hook:?}"));
+ repo.commit("Add config");
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
+approved-commands = [{hook:?}]
+"#
+ ));
+ let removed = repo.add_worktree("feature-hook-checkout");
+
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ assert_cmd_snapshot!(
+ "remove_pre_remove_hook_new_checkout_retains_branch",
+ make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["--foreground", "feature-hook-checkout"],
+ None,
+ )
+ );
+ });
+
+ assert!(
+ !removed.exists(),
+ "the originally planned worktree is removed"
+ );
+ assert_branch_exists(&repo, "feature-hook-checkout", true, "snapshot above");
+ assert_not_orphaned(&repo, &survivor, "snapshot above");
+}
+
/// Assert git still tracks `branch`'s worktree — that its `.git/worktrees/<id>`
/// admin dir survived a neighbouring removal.
fn assert_still_registered(repo: &TestRepo, branch: &str) {
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 1cafb4a28..c9181c438 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -651,6 +651,17 @@ fn test_detect_ref_type() {
let r = Repository::at(gitlab.root_path().to_path_buf()).unwrap();
assert_eq!(r.detect_ref_type(), Some(RefType::Mr));
+ // Other known PR forges use the same canonical mapping.
+ for url in [
+ "https://gitea.example.com/owner/repo.git",
+ "https://dev.azure.com/org/project/_git/repo",
+ ] {
+ let repo = TestRepo::new();
+ repo.run_git(&["remote", "add", "origin", url]);
+ let r = Repository::at(repo.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.detect_ref_type(), Some(RefType::Pr), "{url}");
+ }
+
// Unknown host → None
let other = TestRepo::new();
other.run_git(&[
diff --git a/tests/integration_tests/security.rs b/tests/integration_tests/security.rs
index ccd04de0d..fdab61e9d 100644
--- a/tests/integration_tests/security.rs
+++ b/tests/integration_tests/security.rs
@@ -29,10 +29,6 @@
//! 4. **Filesystem layer**: OS enforces valid path characters (NUL is
//! universally invalid in paths).
//!
-//! 5. **Legacy escaping** (compat path only): When the pre-split legacy
-//! wrapper is active, paths use POSIX single-quote escaping (`'\''`),
-//! which handles `$`, `` ` ``, `;`, `&`, `|`, spaces, etc.
-//!
//! ## What These Tests Verify
//!
//! The CD file holds a raw path, so path-based shell injection is structurally
diff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rs
index e98621d5e..f58130dc3 100644
--- a/tests/integration_tests/shell_integration_prompt.rs
+++ b/tests/integration_tests/shell_integration_prompt.rs
@@ -347,12 +347,6 @@ mod pty_tests {
fs::write(&bashrc, format!("{config_line}\n")).unwrap();
let mut env_vars = repo.test_env_vars();
- // Remove directive env vars (ensure shell integration not active)
- env_vars.retain(|(k, _)| {
- k != "WORKTRUNK_DIRECTIVE_CD_FILE"
- && k != "WORKTRUNK_DIRECTIVE_EXEC_FILE"
- && k != "WORKTRUNK_DIRECTIVE_FILE"
- });
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
@@ -397,7 +391,6 @@ mod pty_tests {
fs::write(&bashrc, "# empty bashrc\n").unwrap();
let mut env_vars = repo.test_env_vars();
- env_vars.retain(|(k, _)| k != "WORKTRUNK_DIRECTIVE_FILE");
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
@@ -453,7 +446,6 @@ mod pty_tests {
fs::write(&bashrc, "# empty bashrc\n").unwrap();
let mut env_vars = repo.test_env_vars();
- env_vars.retain(|(k, _)| k != "WORKTRUNK_DIRECTIVE_FILE");
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
@@ -510,7 +502,6 @@ mod pty_tests {
fs::write(&bashrc, "# empty bashrc\n").unwrap();
let mut env_vars = repo.test_env_vars();
- env_vars.retain(|(k, _)| k != "WORKTRUNK_DIRECTIVE_FILE");
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
@@ -566,7 +557,6 @@ mod pty_tests {
fs::write(&bashrc, "# empty bashrc\n").unwrap();
let mut env_vars = repo.test_env_vars();
- env_vars.retain(|(k, _)| k != "WORKTRUNK_DIRECTIVE_FILE");
// Set SHELL to bash since we're testing with .bashrc
env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));
diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rs
index 26df1a253..6266e3822 100644
--- a/tests/integration_tests/step_relocate.rs
+++ b/tests/integration_tests/step_relocate.rs
@@ -1372,6 +1372,66 @@ fn test_relocate_preserves_subdir(repo: TestRepo) {
);
}
+/// A shell started before the split directive protocol cannot follow a
+/// relocated current worktree. The relocation still succeeds, but it must
+/// explain that the wrapper is stale and how to repair it rather than silently
+/// leaving the shell in the renamed-away directory.
+///
+/// Ignored on Windows for the same reason as the adjacent subdirectory test:
+/// relocating a worktree while this process holds its cwd there fails with a
+/// sharing violation before the directive-warning path is reachable.
+#[rstest]
+#[cfg_attr(windows, ignore)]
+fn test_relocate_current_with_retired_wrapper_warns(repo: TestRepo) {
+ let parent = worktree_parent(&repo);
+ let wrong_path = parent.join("wrong-location");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "-b",
+ "feature",
+ wrong_path.to_str().unwrap(),
+ ]);
+
+ let directive_dir = tempfile::TempDir::new().unwrap();
+ let retired_path = directive_dir.path().join("directive");
+ fs::write(&retired_path, "").unwrap();
+
+ let output = repo
+ .wt_command()
+ .env("WORKTRUNK_DIRECTIVE_FILE", &retired_path)
+ .args(["step", "relocate"])
+ .current_dir(&wrong_path)
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "relocation should still succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(!wrong_path.exists(), "the old worktree path should be gone");
+ assert!(
+ parent.join("repo.feature").exists(),
+ "the worktree should reach its expected path"
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("shell wrapper is out of date"),
+ "the stale wrapper must not fail silently:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("wt config shell install"),
+ "the warning must include the repair action:\n{stderr}"
+ );
+ assert_eq!(
+ fs::read_to_string(&retired_path).unwrap(),
+ "",
+ "wt must never write to the retired directive file"
+ );
+}
+
/// An argument naming no worktree is an error. Matching it against branch names
/// alone left a typo filtering everything out, and the empty result rendered as
/// "All worktrees are at expected paths" — a success message for a no-op.
diff --git a/tests/integration_tests/switch_picker_dry_run.rs b/tests/integration_tests/switch_picker_dry_run.rs
index eff6e1803..9bd8a3ac9 100644
--- a/tests/integration_tests/switch_picker_dry_run.rs
+++ b/tests/integration_tests/switch_picker_dry_run.rs
@@ -11,6 +11,7 @@
use crate::common::mock_commands::{MockConfig, MockResponse, mock_calls};
use crate::common::{TEST_EPOCH, TestRepo, repo};
+use insta::assert_snapshot;
use rstest::rstest;
#[rstest::fixture]
@@ -336,6 +337,34 @@ fn test_picker_dry_run_drains_stashed_warnings(mut repo: TestRepo) {
);
}
+/// The collect and `--prs` threads discover the same legacy alias
+/// independently. Their shared stash emits the actionable migration warning
+/// once after the picker releases the terminal.
+#[rstest]
+fn test_picker_dry_run_deduplicates_legacy_forge_alias_warning(repo: TestRepo) {
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "git@github-personal:owner/repo.git",
+ ]);
+
+ let output = repo
+ .wt_command()
+ .args(["switch", "--prs"])
+ .env("WORKTRUNK_PICKER_DRY_RUN", "1")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "dry-run should exit 0; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_snapshot!(stderr.as_ref(), @r#"▲ SSH host alias github-personal is not auto-detected as a forge; enable CI status and wt switch --prs with forge.platform = "github" @ .config/wt.toml"#);
+}
+
/// Same as above but with `list.summary=true` and a strict fake LLM command,
/// proving the configured generator runs before its result reaches mode 5.
#[rstest]
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap b/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap
deleted file mode 100644
index 20efc5a2f..000000000
--- a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_powershell.snap
+++ /dev/null
@@ -1,54 +0,0 @@
----
-source: tests/integration_tests/directives.rs
-info:
- program: wt
- args:
- - switch
- - feature
- env:
- APPDATA: "[TEST_CONFIG_HOME]"
- CLICOLOR_FORCE: "1"
- COLUMNS: "500"
- GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
- GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
- GIT_CONFIG_SYSTEM: /dev/null
- 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_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
- WORKTRUNK_SHELL: powershell
- 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_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 -----
-▲ Shell wrapper uses the legacy directive-file protocol; it will be removed in a future release
-↳ To update, run wt config shell install
-○ Switched to worktree for feature @ _REPO_.feature
-
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap
similarity index 60%
rename from tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap
rename to tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap
index 4041844b2..b8e13eba6 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_fish.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_after_switch.snap
@@ -5,10 +5,14 @@ info:
args:
- switch
- feature
+ - "--execute"
+ - echo spawned > retired-execute-ran
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_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -25,7 +29,6 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
- WORKTRUNK_SHELL: fish
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -37,6 +40,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"
@@ -48,7 +52,8 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ Shell wrapper uses the legacy directive-file protocol; it will be removed in a future release
-↳ To update, run wt config shell install
-○ Switched to worktree for feature @ _REPO_.feature
-
+▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
+↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo spawned > retired-execute-ran'
+▲ Worktree for feature @ _REPO_.feature, but cannot change directory — shell wrapper is out of date
+↳ To update the shell wrapper, run wt config shell install
+▲ --execute disabled because the shell wrapper is out of date; skipping echo spawned > retired-execute-ran
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap
similarity index 75%
rename from tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap
rename to tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap
index c9c7dbf3f..f0be7ff69 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file_with_execute.snap
+++ b/tests/snapshots/integration__integration_tests__directives__switch_retired_directive_file_refuses_execute_when_already_at.snap
@@ -4,14 +4,15 @@ info:
program: wt
args:
- switch
- - "--create"
- - exec-legacy
+ - feature
- "--execute"
- - echo hello
+ - echo spawned > retired-execute-ran
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_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -39,6 +40,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"
@@ -51,11 +53,7 @@ exit_code: 0
----- stderr -----
▲ --execute will change in a future release: it will run a single program, with arguments after --, not a shell command line
-↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo hello'
-▲ Shell wrapper uses the legacy directive-file protocol; it will be removed in a future release
-↳ To update, run wt config shell install
-✓ Created branch exec-legacy from main and worktree @ _REPO_.exec-legacy
-↳ To customize worktree locations, run wt config create
-◎ Executing (--execute):
-  echo hello
-
+↳ Comment at https://github.com/max-sixty/worktrunk/issues/2860 if the new single-program form would make a workflow worse; to run this command line unchanged, pass it to a shell: --execute sh -- -c 'echo spawned > retired-execute-ran'
+○ Already on worktree for feature @ _REPO_.feature
+▲ --execute disabled because the shell wrapper is out of date; skipping echo spawned > retired-execute-ran
+↳ To update the shell wrapper, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap b/tests/snapshots/integration__integration_tests__remove__remove_pre_remove_hook_new_checkout_retains_branch.snap
similarity index 60%
rename from tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap
rename to tests/snapshots/integration__integration_tests__remove__remove_pre_remove_hook_new_checkout_retains_branch.snap
index 024e456a5..f2934dbdb 100644
--- a/tests/snapshots/integration__integration_tests__directives__switch_legacy_directive_file.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_pre_remove_hook_new_checkout_retains_branch.snap
@@ -1,14 +1,17 @@
---
-source: tests/integration_tests/directives.rs
+source: tests/integration_tests/remove.rs
info:
program: wt
args:
- - switch
- - feature
+ - remove
+ - "--foreground"
+ - feature-hook-checkout
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_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -24,7 +27,6 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
- WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
@@ -36,6 +38,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"
@@ -47,7 +50,10 @@ exit_code: 0
----- stdout -----
----- stderr -----
-▲ Shell wrapper uses the legacy directive-file protocol; it will be removed in a future release
-↳ To update, run wt config shell install
-○ Switched to worktree for feature @ _REPO_.feature
-
+◎ Running pre-remove project hook @ _REPO_.feature-hook-checkout
+  git worktree add --force ../repo.feature-hook-survivor feature-hook-checkout
+Preparing worktree (checking out 'feature-hook-checkout')
+HEAD is now at 2caa7f2 Add config
+◎ Removing feature-hook-checkout worktree...
+✓ Removed feature-hook-checkout worktree (4 files · [BYTES] B)
+▲ Removed worktree but retained branch feature-hook-checkout; checked out @ _REPO_.feature-hook-survivor