Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: offer to fix worktree-path for bare repos with hidden directory names (#1656)
Maximilian Roosd989a3cd9361
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 403e6abed..37b53375c 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -13,7 +13,8 @@ use super::command_approval::approve_hooks;use super::command_executor::{CommandContext, build_hook_context};use super::hooks::{HookFailureStrategy, execute_hook};use super::worktree::{- SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, path_mismatch, plan_switch,+ SwitchBranchInfo, SwitchPlan, SwitchResult, execute_switch, offer_bare_repo_worktree_path_fix,+ path_mismatch, plan_switch,};use crate::output::{execute_user_command, handle_switch_output, is_shell_integration_active,@@ -244,6 +245,9 @@ pub fn handle_switch(run_pre_switch_hooks(&repo, config, branch, yes)?;}+ // Offer to fix worktree-path for bare repos with hidden directory names (.git, .bare).+ offer_bare_repo_worktree_path_fix(&repo, config)?;+// Validate and resolve the target branch.let plan = plan_switch(&repo, branch, create, base, clobber, config).map_err(|err| {match suggestion_ctx {diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 8b791d19a..36fbe99aa 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -22,7 +22,8 @@ use super::handle_switch::{};use super::list::collect;use super::worktree::{- SwitchBranchInfo, SwitchResult, execute_switch, handle_remove, path_mismatch, plan_switch,+ SwitchBranchInfo, SwitchResult, execute_switch, handle_remove,+ offer_bare_repo_worktree_path_fix, path_mismatch, plan_switch,};use crate::output::{handle_remove_output, handle_switch_output};@@ -372,25 +373,30 @@ pub fn handle_picker(} else {Repository::current().context("Failed to switch worktree")?};- let config = repo.user_config();+ // Load config, offering bare repo worktree-path fix if needed.+ // Reload from disk so mutations are picked up by plan_switch.+ let mut config =+ worktrunk::config::UserConfig::load().context("Failed to load config")?;+ offer_bare_repo_worktree_path_fix(&repo, &mut config)?;// Run pre-switch hooks before branch resolution or worktree creation.// {{ branch }} receives the raw user input (before resolution).// Skip when recovered — the source worktree is gone, nothing to run hooks against.if !is_recovered {- run_pre_switch_hooks(&repo, config, &identifier, true)?;+ run_pre_switch_hooks(&repo, &config, &identifier, true)?;}// Switch to existing worktree or create new one- let plan = plan_switch(&repo, &identifier, should_create, None, false, config)?;- let hooks_approved = approve_switch_hooks(&repo, config, &plan, false, true)?;+ let plan = plan_switch(&repo, &identifier, should_create, None, false, &config)?;+ let hooks_approved = approve_switch_hooks(&repo, &config, &plan, false, true)?;let (result, branch_info) =- execute_switch(&repo, plan, config, false, hooks_approved)?;+ execute_switch(&repo, plan, &config, false, hooks_approved)?;// Compute path mismatch lazily (deferred from plan_switch for existing worktrees)let branch_info = match &result {SwitchResult::Existing { path } | SwitchResult::AlreadyAt(path) => {- let expected_path = path_mismatch(&repo, &branch_info.branch, path, config);+ let expected_path =+ path_mismatch(&repo, &branch_info.branch, path, &config);SwitchBranchInfo {expected_path,..branch_info@@ -417,7 +423,7 @@ pub fn handle_picker(let extra_vars = switch_extra_vars(&result);spawn_switch_background_hooks(&repo,- config,+ &config,&result,&branch_info.branch,false,diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 6083105e2..dcfaf62e2 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -90,8 +90,8 @@ pub use push::{handle_no_ff_merge, handle_push};pub use remove::{handle_remove, handle_remove_current};pub(crate) use resolve::paths_match;pub use resolve::{- compute_worktree_path, is_worktree_at_expected_path, path_mismatch, resolve_worktree_arg,- worktree_display_name,+ compute_worktree_path, is_worktree_at_expected_path, offer_bare_repo_worktree_path_fix,+ path_mismatch, resolve_worktree_arg, worktree_display_name,};pub use switch::{execute_switch, plan_switch};pub use types::{diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex a8aa2a33d..68a7e73d8 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -2,6 +2,7 @@//!//! Functions for resolving worktree arguments and computing expected paths.+use std::io::IsTerminal;use std::path::{Path, PathBuf};use color_print::cformat;@@ -10,6 +11,11 @@ use normalize_path::NormalizePath;use worktrunk::config::UserConfig;use worktrunk::git::{GitError, Repository, ResolvedWorktree};use worktrunk::path::format_path_for_display;+use worktrunk::styling::{+ eprintln, format_toml, hint_message, info_message, success_message, warning_message,+};++use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};use super::types::OperationMode;@@ -297,6 +303,159 @@ pub(super) fn compute_clobber_backup(}}+/// Suggested worktree-path template for bare repos with hidden directory names.+///+/// Places worktrees as siblings of the bare repo directory inside the parent,+/// e.g., `myproject/.git` + branch `feature` → `myproject/feature`.+/// Uses an absolute path (`repo_path`/../) to avoid ambiguity with relative resolution.+const BARE_REPO_WORKTREE_PATH: &str = "{{ repo_path }}/../{{ branch | sanitize }}";++/// Check whether a template string references `{{ repo }}` or `{{ main_worktree }}`.+fn template_references_repo_name(template: &str) -> bool {+ let env = minijinja::Environment::new();+ let Ok(tmpl) = env.template_from_str(template) else {+ return false;+ };+ let vars = tmpl.undeclared_variables(false);+ vars.contains("repo") || vars.contains("main_worktree")+}++/// Offer to set a project-level `worktree-path` for bare repos with hidden directory names.+///+/// When a bare repo lives at a hidden path like `.git` or `.bare`, the `{{ repo }}`+/// template variable resolves to that directory name, producing broken worktree paths.+/// This function detects the situation and offers to set a project-level override.+///+/// Returns `true` if config was modified (caller should use the updated config).+pub fn offer_bare_repo_worktree_path_fix(+ repo: &Repository,+ config: &mut UserConfig,+) -> anyhow::Result<bool> {+ if !repo.is_bare()? {+ return Ok(false);+ }++ let repo_path = repo.repo_path()?;+ let repo_name = repo_path.file_name().and_then(|n| n.to_str()).unwrap_or("");+ if !repo_name.starts_with('.') {+ return Ok(false);+ }++ if repo+ .config_value("worktrunk.skip-bare-repo-prompt")+ .unwrap_or(None)+ .is_some()+ {+ return Ok(false);+ }++ let project_id = repo.project_identifier()?;+ let template = config.worktree_path_for_project(&project_id);+ if !template_references_repo_name(&template) {+ return Ok(false);+ }++ // Display names for messages+ let display_path = repo_path+ .parent()+ .map(|p| format_path_for_display(p).to_string())+ .unwrap_or_else(|| format_path_for_display(repo_path).to_string());+ let parent_name = repo_path+ .parent()+ .and_then(|p| p.file_name())+ .and_then(|n| n.to_str())+ .unwrap_or("project");++ // Example paths to show the user what changes+ let example_bad = format!("{parent_name}/{repo_name}.feature-auth");+ let example_good = format!("{parent_name}/feature-auth");++ let config_path_display = worktrunk::config::config_path()+ .map(|p| format_path_for_display(&p).to_string())+ .unwrap_or_else(|| "~/.config/worktrunk/config.toml".to_string());++ // Non-interactive: warn and show the config to add.+ if !std::io::stdin().is_terminal() {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Bare repo at <bold>{parent_name}/{repo_name}</> — worktrees will be at <bold>{example_bad}</>"+ ))+ );+ eprintln!(+ "{}",+ hint_message(cformat!(+ "To place worktrees at <underline>{example_good}</>, add to <underline>{config_path_display}</>:"+ ))+ );+ let config_snippet =+ format!("[projects.\"{project_id}\"]\nworktree-path = \"{BARE_REPO_WORKTREE_PATH}\"");+ eprintln!("{}", format_toml(&config_snippet));+ return Ok(false);+ }++ // Interactive: show diagnosis, then prompt+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Bare repo at <bold>{parent_name}/{repo_name}</> — worktrees will be at <bold>{example_bad}</>"+ ))+ );++ let config_path_for_preview = config_path_display.clone();+ let project_id_for_preview = project_id.clone();+ match prompt_yes_no_preview(+ &cformat!("Configure worktree-path to place worktrees at <bold>{example_good}</>?"),+ move || {+ eprintln!(+ "{}",+ info_message(cformat!("Would add to <bold>{config_path_for_preview}</>:"))+ );+ let preview = format!(+ "[projects.\"{project_id_for_preview}\"]\nworktree-path = \"{BARE_REPO_WORKTREE_PATH}\""+ );+ eprintln!("{}", format_toml(&preview));+ eprintln!();+ },+ )? {+ PromptResponse::Accepted => {+ config.set_project_worktree_path(+ &project_id,+ BARE_REPO_WORKTREE_PATH.to_string(),+ None,+ )?;+ print_accepted_message(&display_path, &config_path_display);+ Ok(true)+ }+ PromptResponse::Declined => {+ if let Err(e) = repo.set_config("worktrunk.skip-bare-repo-prompt", "true") {+ log::warn!("Failed to save skip-bare-repo-prompt to git config: {e}");+ }+ Ok(false)+ }+ }+}++fn print_accepted_message(display_path: &str, config_path: &str) {+ eprintln!(+ "{}",+ success_message(cformat!(+ "Set <bold>worktree-path</> for <bold>{display_path}</>:"+ ))+ );+ let global_config = format!("worktree-path = \"{BARE_REPO_WORKTREE_PATH}\"");+ eprintln!("{}", format_toml(&global_config));+ eprintln!(+ "{}",+ hint_message(cformat!(+ "To set globally, add to <underline>{config_path}</>"+ ))+ );++ // Blank line separates this setup phase from the main operation that follows+ eprintln!();+}+#[cfg(test)]mod tests {use super::*;@@ -436,4 +595,55 @@ mod tests {// Clean uplet _ = std::fs::remove_dir_all(&existing);}++ #[test]+ fn test_template_references_repo_name_default() {+ // Default template uses {{ repo }}+ assert!(template_references_repo_name(+ "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"+ ));+ }++ #[test]+ fn test_template_references_repo_name_with_filter() {+ assert!(template_references_repo_name("{{ repo | sanitize }}"));+ }++ #[test]+ fn test_template_references_repo_name_deprecated_alias() {+ assert!(template_references_repo_name(+ "{{ main_worktree }}.{{ branch }}"+ ));+ }++ #[test]+ fn test_template_references_repo_name_not_repo_path() {+ // {{ repo_path }} should NOT match+ assert!(!template_references_repo_name(+ "{{ repo_path }}/../{{ branch | sanitize }}"+ ));+ }++ #[test]+ fn test_template_references_repo_name_no_repo() {+ assert!(!template_references_repo_name("../{{ branch | sanitize }}"));+ }++ #[test]+ fn test_template_references_repo_name_no_spaces() {+ assert!(template_references_repo_name("{{repo}}.{{branch}}"));+ }++ #[test]+ fn test_template_references_repo_name_no_braces() {+ // "repo" outside template expressions should not match+ assert!(!template_references_repo_name("my-repo-path/{{ branch }}"));+ }++ #[test]+ fn test_template_references_repo_name_substring_prefix() {+ // "myrepo" should NOT match — "repo" is a suffix of a longer identifier+ assert!(!template_references_repo_name("{{ myrepo }}"));+ assert!(!template_references_repo_name("{{ norepo }}"));+ }}diff --git a/src/config/user/mutation.rs b/src/config/user/mutation.rsindex c6598d3f4..c70798a4c 100644--- a/src/config/user/mutation.rs+++ b/src/config/user/mutation.rs@@ -10,8 +10,7 @@ use crate::path::format_path_for_display;use super::UserConfig;use super::path;-use super::sections::CommitConfig;-use super::sections::CommitGenerationConfig;+use super::sections::{CommitConfig, CommitGenerationConfig};/// Acquire an exclusive lock on the config file for read-modify-write operations.///@@ -149,6 +148,26 @@ impl UserConfig {})}+ /// Set worktree-path for a specific project and save.+ ///+ /// Creates the project entry if it doesn't exist.+ /// Pass `None` for default config path, or `Some(path)` for testing.+ pub fn set_project_worktree_path(+ &mut self,+ project: &str,+ worktree_path: String,+ config_path: Option<&std::path::Path>,+ ) -> Result<(), ConfigError> {+ self.with_locked_mutation(config_path, |config| {+ let entry = config.projects.entry(project.to_string()).or_default();+ if entry.overrides.worktree_path.as_ref() == Some(&worktree_path) {+ return false;+ }+ entry.overrides.worktree_path = Some(worktree_path);+ true+ })+ }+/// Set commit generation command and save.////// Sets `[commit.generation] command = ...` in the user config.diff --git a/src/config/user/tests.rs b/src/config/user/tests.rsindex 68793ffb8..36950859b 100644--- a/src/config/user/tests.rs+++ b/src/config/user/tests.rs@@ -514,6 +514,32 @@ worktree-path = "../{{ main_worktree }}.{{ branch }}"assert!(!config.skip_shell_integration_prompt);}+#[test]+fn test_set_project_worktree_path() {+ let dir = tempfile::tempdir().unwrap();+ let config_path = dir.path().join("config.toml");+ std::fs::write(&config_path, "# empty config\n").unwrap();++ let mut config = UserConfig::default();+ config+ .set_project_worktree_path(+ "github.com/user/repo",+ "../{{ branch | sanitize }}".to_string(),+ Some(&config_path),+ )+ .unwrap();++ assert_eq!(+ config.worktree_path_for_project("github.com/user/repo"),+ "../{{ branch | sanitize }}"+ );++ // Verify it was saved to disk+ let content = std::fs::read_to_string(&config_path).unwrap();+ assert!(content.contains("[projects.\"github.com/user/repo\"]"));+ assert!(content.contains("worktree-path"));+}+// =========================================================================// Merge trait tests// =========================================================================diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 9939d3221..ebccd2974 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -573,7 +573,7 @@ const BG_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);////// NOTE: Path-dependent variables (HOME, WORKTRUNK_CONFIG_PATH, GIT_CONFIG_*)/// are NOT included here because they depend on the TestRepo instance.-const STATIC_TEST_ENV_VARS: &[(&str, &str)] = &[+pub const STATIC_TEST_ENV_VARS: &[(&str, &str)] = &[("CLICOLOR_FORCE", "1"),// Terminal width for PTY tests. configure_cli_command() overrides to 500 for longer paths.("COLUMNS", "150"),@@ -595,9 +595,9 @@ const STATIC_TEST_ENV_VARS: &[(&str, &str)] = &[/// Null device path, platform-appropriate./// Use this for GIT_CONFIG_SYSTEM to disable system config in tests.#[cfg(windows)]-const NULL_DEVICE: &str = "NUL";+pub const NULL_DEVICE: &str = "NUL";#[cfg(not(windows))]-const NULL_DEVICE: &str = "/dev/null";+pub const NULL_DEVICE: &str = "/dev/null";/// Create a `wt` CLI command with standardized test environment settings.///@@ -2909,9 +2909,32 @@ pub fn setup_temp_snapshot_settings(temp_path: &std::path::Path) -> insta::Settilet mut settings = insta::Settings::clone_current();settings.set_snapshot_path("../snapshots");- // Filter temp paths in output+ // Filter temp paths in output — multiple forms needed for cross-platform:+ // 1. Canonical path (macOS: /private/tmp needs the canonical /private form)+ // 2. Raw path as provided+ // 3. Regex matching the unique temp dir name with any prefix (Windows:+ // format_path_for_display replaces $HOME with ~, producing ~/AppData/...+ // which doesn't match the raw path. Match by unique dir name instead.)+ if let Ok(canonical) = dunce::canonicalize(temp_path) {+ let canonical_str = canonical.to_str().unwrap();+ let temp_str = temp_path.to_str().unwrap();+ if canonical_str != temp_str {+ settings.add_filter(®ex::escape(canonical_str), "[TEMP]");+ }+ }settings.add_filter(®ex::escape(temp_path.to_str().unwrap()), "[TEMP]");+ // Match the unique temp dir name with any path prefix (handles ~/AppData/... on Windows)+ if let Some(dir_name) = temp_path.file_name().and_then(|n| n.to_str()) {+ // Consume optional leading quote from shell_escape (format_path_for_display+ // wraps non-home paths in single quotes on Windows).+ let pattern = format!(r"'?[^\s]*{}", regex::escape(dir_name));+ settings.add_filter(&pattern, "[TEMP]");+ }settings.add_filter(r"\\", "/");+ // Clean up trailing shell-escape quote after [TEMP] replacement — the leading+ // quote is consumed by the dir-name regex, but the trailing one remains after+ // the file name (e.g., [TEMP]/test-config.toml' → [TEMP]/test-config.toml).+ settings.add_filter(r"(\[TEMP\]/[^\s]*)'", "$1");// Normalize Windows executable extension in help outputsettings.add_filter(r"wt\.exe", "wt");diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex 581afc5bc..31d7caeaa 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -645,6 +645,10 @@ impl NestedBareRepoTest {&self.bare_repo_path}+ fn config_path(&self) -> &Path {+ &self.test_config_path+ }+fn temp_path(&self) -> &Path {self.temp_dir.path()}@@ -656,6 +660,62 @@ impl NestedBareRepoTest {.env_remove("NO_COLOR").env_remove("CLICOLOR_FORCE");}++ /// Get test environment variables as a vector for PTY tests.+ #[cfg(all(unix, feature = "shell-integration-tests"))]+ fn test_env_vars(&self) -> Vec<(String, String)> {+ use crate::common::{NULL_DEVICE, STATIC_TEST_ENV_VARS, TEST_EPOCH};++ let mut vars: Vec<(String, String)> = STATIC_TEST_ENV_VARS+ .iter()+ .map(|&(k, v)| (k.to_string(), v.to_string()))+ .collect();++ // HOME and XDG_CONFIG_HOME are needed for config lookups in env_clear'd PTY+ let home = self.temp_dir.path().join("home");+ std::fs::create_dir_all(&home).ok();++ vars.extend([+ (+ "GIT_CONFIG_GLOBAL".to_string(),+ self.git_config_path.display().to_string(),+ ),+ ("GIT_CONFIG_SYSTEM".to_string(), NULL_DEVICE.to_string()),+ (+ "GIT_AUTHOR_DATE".to_string(),+ "2025-01-01T00:00:00Z".to_string(),+ ),+ (+ "GIT_COMMITTER_DATE".to_string(),+ "2025-01-01T00:00:00Z".to_string(),+ ),+ ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),+ ("HOME".to_string(), home.display().to_string()),+ (+ "XDG_CONFIG_HOME".to_string(),+ home.join(".config").display().to_string(),+ ),+ ("WORKTRUNK_TEST_EPOCH".to_string(), TEST_EPOCH.to_string()),+ (+ "WORKTRUNK_CONFIG_PATH".to_string(),+ self.test_config_path.display().to_string(),+ ),+ (+ "WORKTRUNK_SYSTEM_CONFIG_PATH".to_string(),+ "/etc/xdg/worktrunk/config.toml".to_string(),+ ),+ (+ "WORKTRUNK_APPROVALS_PATH".to_string(),+ self.temp_dir+ .path()+ .join("test-approvals.toml")+ .display()+ .to_string(),+ ),+ ]);++ vars+ }}impl TestRepoBase for NestedBareRepoTest {@@ -986,3 +1046,199 @@ fn test_bare_repo_merge_preserves_default_branch_worktree() {"Should show primary worktree preservation message.\nstderr: {stderr}");}++/// Helper: create a NestedBareRepoTest with no worktree-path configured and a main worktree.+///+/// Reuses NestedBareRepoTest's bare repo setup but clears the worktree-path config,+/// so the default template (which references `{{ repo }}`) triggers the bare repo prompt.+fn setup_unconfigured_nested_bare_repo() -> NestedBareRepoTest {+ let test = NestedBareRepoTest::new();++ // Temporarily set worktree-path so the main worktree lands at project/main+ // (without this, the default {{ repo }} template produces .git.main).+ fs::write(+ test.config_path(),+ "worktree-path = \"../{{ branch | sanitize }}\"\n",+ )+ .unwrap();++ // Create main worktree with a commit (needed as a starting point for switch)+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "main", "--yes"])+ .current_dir(test.bare_repo_path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "Failed to create main worktree:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );++ // Clear config so the default template applies — the test subject is the bare repo prompt.+ // Skip shell integration prompt so it doesn't interfere (especially in PTY tests).+ fs::write(test.config_path(), "skip-shell-integration-prompt = true\n").unwrap();++ test+}++/// Test that --yes does NOT auto-accept the bare repo config change — it shows+/// the warning and creates the worktree at the unconfigured (bad) path.+#[test]+fn test_bare_repo_worktree_path_prompt_auto_accept() {+ let test = setup_unconfigured_nested_bare_repo();+ let main_worktree = test.project_path().join("main");++ let settings = setup_temp_snapshot_settings(test.temp_path());+ settings.bind(|| {+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "feature", "--yes"])+ .current_dir(&main_worktree);++ assert_cmd_snapshot!(cmd);+ });++ // Config should NOT have worktree-path — --yes skips the config prompt+ let config_content = fs::read_to_string(test.config_path()).unwrap();+ assert!(+ !config_content.contains("worktree-path"),+ "Config should NOT contain worktree-path — --yes should not auto-configure.\nConfig: {config_content}"+ );++ // Worktree created at the unconfigured path (bad but expected without config)+ let bad_path = test.project_path().join(".git.feature");+ assert!(+ bad_path.exists(),+ "Worktree should be at {:?} (unconfigured default path)",+ bad_path+ );+}++/// Test that non-interactive (piped stdin) shows warning instead of prompt.+#[test]+fn test_bare_repo_worktree_path_prompt_non_interactive_warning() {+ let test = setup_unconfigured_nested_bare_repo();+ let main_worktree = test.project_path().join("main");++ let settings = setup_temp_snapshot_settings(test.temp_path());+ settings.bind(|| {+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ // No --yes, but stdin is piped (non-interactive) since assert_cmd_snapshot+ // doesn't attach a TTY+ cmd.args(["switch", "--create", "feature"])+ .current_dir(&main_worktree);++ assert_cmd_snapshot!(cmd);+ });+}++// =============================================================================+// PTY-based interactive prompt tests+// =============================================================================++#[cfg(all(unix, feature = "shell-integration-tests"))]+mod bare_repo_prompt_pty {+ use super::*;+ use crate::common::pty::{build_pty_command, exec_cmd_in_pty_prompted};+ use crate::common::{add_pty_binary_path_filters, add_pty_filters, wt_bin};+ use insta::assert_snapshot;++ fn prompt_pty_settings(temp_path: &Path) -> insta::Settings {+ let mut settings = setup_temp_snapshot_settings(temp_path);+ add_pty_filters(&mut settings);+ add_pty_binary_path_filters(&mut settings);+ settings+ }++ #[test]+ fn test_bare_repo_worktree_path_prompt_accept_pty() {+ let test = setup_unconfigured_nested_bare_repo();+ let main_worktree = test.project_path().join("main");+ let env_vars = test.test_env_vars();++ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["switch", "--create", "feature"],+ &main_worktree,+ &env_vars,+ None,+ );+ let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["y\n"], "[y/N");++ assert_eq!(exit_code, 0);+ prompt_pty_settings(test.temp_path()).bind(|| {+ assert_snapshot!("bare_repo_prompt_accept", &output);+ });++ // Verify config was written+ let config_content = fs::read_to_string(test.config_path()).unwrap();+ assert!(+ config_content.contains("worktree-path"),+ "Config should contain worktree-path override.\nConfig: {config_content}"+ );+ }++ #[test]+ fn test_bare_repo_worktree_path_prompt_decline_pty() {+ let test = setup_unconfigured_nested_bare_repo();+ let main_worktree = test.project_path().join("main");+ let env_vars = test.test_env_vars();++ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["switch", "--create", "feature"],+ &main_worktree,+ &env_vars,+ None,+ );+ let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["n\n"], "[y/N");++ assert_eq!(exit_code, 0);+ prompt_pty_settings(test.temp_path()).bind(|| {+ assert_snapshot!("bare_repo_prompt_decline", &output);+ });++ // Verify skip flag was saved in git config+ let git_config_output = Command::new("git")+ .args(["config", "worktrunk.skip-bare-repo-prompt"])+ .current_dir(&main_worktree)+ .env("GIT_CONFIG_GLOBAL", test.git_config_path())+ .output()+ .unwrap();+ let value = String::from_utf8_lossy(&git_config_output.stdout);+ assert_eq!(+ value.trim(),+ "true",+ "Skip flag should be saved in git config"+ );+ }++ #[test]+ fn test_bare_repo_worktree_path_prompt_preview_pty() {+ let test = setup_unconfigured_nested_bare_repo();+ let main_worktree = test.project_path().join("main");+ let env_vars = test.test_env_vars();++ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["switch", "--create", "feature"],+ &main_worktree,+ &env_vars,+ None,+ );+ // Send ? first to see preview, then n to decline+ let (output, exit_code) = exec_cmd_in_pty_prompted(cmd, &["?\n", "n\n"], "[y/N");++ assert_eq!(exit_code, 0);+ prompt_pty_settings(test.temp_path()).bind(|| {+ assert_snapshot!("bare_repo_prompt_preview", &output);+ });+ }+}diff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_accept.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_accept.snapnew file mode 100644index 000000000..cdc10fbe7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_accept.snap@@ -0,0 +1,15 @@+---+source: tests/integration_tests/bare_repository.rs+expression: "&output"+---+[33m▲[39m [33mBare repo at [1mproject/.git[22m — worktrees will be at [1mproject/.git.feature-auth[22m[39m++[36m❯[39m Configure worktree-path to place worktrees at [1mproject/feature-auth[22m? [1m[y/N/?][22m y+[32m✓[39m [32mSet [1mworktree-path[22m for [1m[TEMP]/project[22m:[39m+[107m [0m [2mworktree-path = [0m[2m[32m"{{ repo_path }}/../{{ branch | sanitize }}"[0m+[2m↳[22m [2mTo set globally, add to [4m[TEMP]/test-config.toml[24m[22m++[32m✓[39m [32mCreated branch [1mfeature[22m and worktree @ [1m[TEMP]/project/feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_decline.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_decline.snapnew file mode 100644index 000000000..16e620a59--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_decline.snap@@ -0,0 +1,11 @@+---+source: tests/integration_tests/bare_repository.rs+expression: "&output"+---+[33m▲[39m [33mBare repo at [1mproject/.git[22m — worktrees will be at [1mproject/.git.feature-auth[22m[39m++[36m❯[39m Configure worktree-path to place worktrees at [1mproject/feature-auth[22m? [1m[y/N/?][22m n+[32m✓[39m [32mCreated branch [1mfeature[22m and worktree @ [1m[TEMP]/project/.git.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_preview.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_preview.snapnew file mode 100644index 000000000..35ab245d2--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_prompt_pty__bare_repo_prompt_preview.snap@@ -0,0 +1,16 @@+---+source: tests/integration_tests/bare_repository.rs+expression: "&output"+---+[33m▲[39m [33mBare repo at [1mproject/.git[22m — worktrees will be at [1mproject/.git.feature-auth[22m[39m++[36m❯[39m Configure worktree-path to place worktrees at [1mproject/feature-auth[22m? [1m[y/N/?][22m ?+[2m○[22m Would add to [1m[TEMP]/test-config.toml[22m:+[107m [0m [2m[36m[projects."[TEMP]/project/.git"][0m+[107m [0m [2mworktree-path = [0m[2m[32m"{{ repo_path }}/../{{ branch | sanitize }}"[0m++[36m❯[39m Configure worktree-path to place worktrees at [1mproject/feature-auth[22m? [1m[y/N/?][22m n+[32m✓[39m [32mCreated branch [1mfeature[22m and worktree @ [1m[TEMP]/project/.git.feature[22m[39m+[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [4mwt config shell install[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snapnew file mode 100644index 000000000..612ae9f09--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_auto_accept.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/bare_repository.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ - "--yes"+ env:+ CLICOLOR_FORCE: ""+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+▲ Bare repo at project/.git — worktrees will be at project/.git.feature-auth+↳ To place worktrees at project/feature-auth, add to [TEMP]/test-config.toml:+ [projects."[TEMP]/project/.git"]+ worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"+✓ Created branch feature and worktree @ [TEMP]/project/.git.feature+↳ To customize worktree locations, run wt config create+[0mdiff --git a/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snapnew file mode 100644index 000000000..173f842ee--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__bare_repo_worktree_path_prompt_non_interactive_warning.snap@@ -0,0 +1,47 @@+---+source: tests/integration_tests/bare_repository.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature+ env:+ CLICOLOR_FORCE: ""+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_DIRECTIVE_FILE: "[DIRECTIVE_FILE]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+▲ Bare repo at project/.git — worktrees will be at project/.git.feature-auth+↳ To place worktrees at project/feature-auth, add to [TEMP]/test-config.toml:+ [projects."[TEMP]/project/.git"]+ worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"+✓ Created branch feature and worktree @ [TEMP]/project/.git.feature+↳ To customize worktree locations, run wt config create+[0m