Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: split large files into focused modules (#688)
Maximilian Roos51c65bd4263d
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 53a221922..24f80defd 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -57,7 +57,7 @@ repos:entry: '\\x1b\['# format.rs strips ANSI codes injected by wrap_ansi crate# select.rs tests verify ANSI dimming behavior- exclude: '^(tests/|.*_test\.rs$|src/styling/(mod|format)\.rs$|src/commands/select\.rs$)'+ exclude: '^(tests/|.*_test\.rs$|src/styling/(mod|format)\.rs$|src/commands/select/)'- id: no-std-canonicalize-in-testsname: no-std-canonicalize-in-testsdescription: Use dunce::canonicalize in tests to avoid Windows \\?\ prefix issues@@ -74,7 +74,7 @@ repos:# select.rs: skim API's selected.output() is not Command::output()# tests/benches: test utilities run commands directly# src/config/{test,expansion,mod,user}.rs: TestRepo test fixtures use git init directly- exclude: '^(src/shell_exec\.rs|src/commands/select\.rs|src/config/(test|expansion|mod|user)\.rs|tests/|benches/)'+ exclude: '^(src/shell_exec\.rs|src/commands/select/|src/config/(test|expansion|mod|user)\.rs|tests/|benches/)'ci:# pre-commit.ci doesn't have Rust toolchain, so skip Rust-specific hooks.diff --git a/src/commands/config.rs b/src/commands/config.rsdeleted file mode 100644index db61aea51..000000000--- a/src/commands/config.rs+++ /dev/null@@ -1,1904 +0,0 @@-use anyhow::Context;-use color_print::cformat;-use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};-use std::fmt::Write as _;-use std::path::PathBuf;-use worktrunk::config::{- ProjectConfig, WorktrunkConfig, find_unknown_project_keys, find_unknown_user_keys,-};-use worktrunk::git::Repository;-use worktrunk::path::format_path_for_display;-use worktrunk::shell::{Shell, scan_for_detection_details};-use worktrunk::styling::{- error_message, format_bash_with_gutter, format_heading, format_toml, format_with_gutter,- hint_message, info_message, success_message, warning_message,-};-use worktrunk::utils::get_now;--use super::configure_shell::{ConfigAction, scan_shell_configs};-use super::list::ci_status::CachedCiStatus;-use crate::cli::version_str;-use crate::display::format_relative_time_short;-use crate::help_pager::show_help_in_pager;-use crate::llm::test_commit_generation;-use crate::output;--/// Example user configuration file content (displayed in help with values uncommented)-const USER_CONFIG_EXAMPLE: &str = include_str!("../../dev/config.example.toml");--/// Example project configuration file content-const PROJECT_CONFIG_EXAMPLE: &str = include_str!("../../dev/wt.example.toml");--/// Comment out all non-comment, non-empty lines for writing to disk-fn comment_out_config(content: &str) -> String {- let has_trailing_newline = content.ends_with('\n');- let result = content- .lines()- .map(|line| {- // Comment out non-empty lines that aren't already comments- if !line.is_empty() && !line.starts_with('#') {- format!("# {}", line)- } else {- line.to_string()- }- })- .collect::<Vec<_>>()- .join("\n");-- if has_trailing_newline {- format!("{}\n", result)- } else {- result- }-}--/// Handle the config create command-pub fn handle_config_create(project: bool) -> anyhow::Result<()> {- if project {- let repo = Repository::current()?;- let config_path = repo.current_worktree().root()?.join(".config/wt.toml");- let user_config_exists = require_user_config_path()- .map(|p| p.exists())- .unwrap_or(false);- create_config_file(- config_path,- PROJECT_CONFIG_EXAMPLE,- "Project config",- &[- "Edit this file to configure hooks for this repository",- "See https://worktrunk.dev/hook/ for hook documentation",- ],- user_config_exists,- true, // is_project- )- } else {- let project_config_exists = Repository::current()- .and_then(|repo| repo.current_worktree().root())- .map(|root| root.join(".config/wt.toml").exists())- .unwrap_or(false);- create_config_file(- require_user_config_path()?,- USER_CONFIG_EXAMPLE,- "User config",- &["Edit this file to customize worktree paths and LLM settings"],- project_config_exists,- false, // is_project- )- }-}--/// Create a config file at the specified path with the given content-fn create_config_file(- path: PathBuf,- content: &str,- config_type: &str,- success_hints: &[&str],- other_config_exists: bool,- is_project: bool,-) -> anyhow::Result<()> {- // Check if file already exists- if path.exists() {- output::print(info_message(cformat!(- "{config_type} already exists: <bold>{}</>",- format_path_for_display(&path)- )))?;-- // Build hint message based on whether the other config exists- let hint = if other_config_exists {- // Both configs exist- cformat!("To view both user and project configs, run <bright-black>wt config show</>")- } else if is_project {- // Project config exists, no user config- cformat!(- "To view, run <bright-black>wt config show</>. To create a user config, run <bright-black>wt config create</>"- )- } else {- // User config exists, no project config- cformat!(- "To view, run <bright-black>wt config show</>. To create a project config, run <bright-black>wt config create --project</>"- )- };- output::print(hint_message(hint))?;- return Ok(());- }-- // Create parent directory if it doesn't exist- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent).context("Failed to create config directory")?;- }-- // Write the example config with all values commented out- let commented_config = comment_out_config(content);- std::fs::write(&path, commented_config).context("Failed to write config file")?;-- // Success message- output::print(success_message(cformat!(- "Created {}: <bold>{}</>",- config_type.to_lowercase(),- format_path_for_display(&path)- )))?;- output::blank()?;- for hint in success_hints {- output::print(hint_message(*hint))?;- }-- Ok(())-}--/// Handle the config show command-pub fn handle_config_show(full: bool) -> anyhow::Result<()> {- // Build the complete output as a string- let mut show_output = String::new();-- // Render user config- render_user_config(&mut show_output)?;- show_output.push('\n');-- // Render project config if in a git repository- render_project_config(&mut show_output)?;- show_output.push('\n');-- // Render shell integration status- render_shell_status(&mut show_output)?;-- // Run full diagnostic checks if requested (includes slow network calls)- if full {- show_output.push('\n');- render_diagnostics(&mut show_output)?;- }-- // Render runtime info at the bottom (version, binary name, shell integration status)- show_output.push('\n');- render_runtime_info(&mut show_output)?;-- // Display through pager (config show is always long-form output)- if let Err(e) = show_help_in_pager(&show_output, true) {- log::debug!("Pager invocation failed: {}", e);- // Fall back to direct output via eprintln (matches help behavior)- worktrunk::styling::eprintln!("{}", show_output);- }-- Ok(())-}--/// Check if Claude Code CLI is available-fn is_claude_available() -> bool {- use worktrunk::shell_exec::Cmd;-- Cmd::new("claude")- .arg("--version")- .run()- .map(|o| o.status.success())- .unwrap_or(false)-}--/// Check if the worktrunk plugin is installed in Claude Code-fn is_plugin_installed() -> bool {- // Try HOME/USERPROFILE env vars first (for tests and explicit overrides), then fall back to dirs- let home = std::env::var("HOME")- .or_else(|_| std::env::var("USERPROFILE"))- .ok()- .map(PathBuf::from)- .or_else(dirs::home_dir);-- let Some(home) = home else {- return false;- };-- let plugins_file = home.join(".claude/plugins/installed_plugins.json");- let Ok(content) = std::fs::read_to_string(&plugins_file) else {- return false;- };-- // Look for "worktrunk@worktrunk" in the plugins object- content.contains("\"worktrunk@worktrunk\"")-}--/// Get the git version string (e.g., "2.47.1")-fn get_git_version() -> Option<String> {- use worktrunk::shell_exec::Cmd;-- 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())-}--/// Render OTHER section (version, Claude plugin, hyperlinks)-fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {- let cmd = crate::binary_name();- let version = version_str();-- writeln!(out, "{}", format_heading("OTHER", None))?;-- // Version info- writeln!(- out,- "{}",- info_message(cformat!("{cmd}: <bold>{version}</>"))- )?;- if let Some(git_version) = get_git_version() {- writeln!(- out,- "{}",- info_message(cformat!("git: <bold>{git_version}</>"))- )?;- }-- // Claude Code plugin status- let plugin_installed = is_plugin_installed();- let claude_available = is_claude_available();-- if plugin_installed {- writeln!(out, "{}", success_message("Claude Code plugin installed"))?;- } else if claude_available {- writeln!(- out,- "{}",- hint_message("Claude Code plugin not installed. To install, run:")- )?;- let install_commands = "claude plugin marketplace add max-sixty/worktrunk\nclaude plugin install worktrunk@worktrunk";- writeln!(out, "{}", format_bash_with_gutter(install_commands))?;- } else {- writeln!(- out,- "{}",- hint_message(cformat!(- "Claude Code plugin not installed (<bold>claude</> not found)"- ))- )?;- }-- // Show hyperlink support status- let hyperlinks_supported =- worktrunk::styling::supports_hyperlinks(worktrunk::styling::Stream::Stderr);- let status = if hyperlinks_supported {- "active"- } else {- "inactive"- };- writeln!(- out,- "{}",- info_message(cformat!("Hyperlinks: <bold>{status}</>"))- )?;-- Ok(())-}--/// Run full diagnostic checks (CI tools, commit generation) and render to buffer-fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {- use super::list::ci_status::{CiPlatform, CiToolsStatus, get_platform_for_repo};-- writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;-- // Check CI tool based on detected platform (with config override support)- let repo = Repository::current()?;- let project_config = repo.load_project_config().ok().flatten();- let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());- let platform = get_platform_for_repo(&repo, platform_override);-- match platform {- Some(CiPlatform::GitHub) => {- let ci_tools = CiToolsStatus::detect(None);- render_ci_tool_status(- out,- "gh",- "GitHub",- ci_tools.gh_installed,- ci_tools.gh_authenticated,- )?;- }- Some(CiPlatform::GitLab) => {- let ci_tools = CiToolsStatus::detect(None);- render_ci_tool_status(- out,- "glab",- "GitLab",- ci_tools.glab_installed,- ci_tools.glab_authenticated,- )?;- }- None => {- writeln!(- out,- "{}",- hint_message("CI status requires GitHub or GitLab remote")- )?;- }- }-- // Test commit generation- let config = WorktrunkConfig::load()?;- let commit_config = &config.commit_generation;-- if !commit_config.is_configured() {- writeln!(out, "{}", hint_message("Commit generation not configured"))?;- return Ok(());- }-- let command_display = format!(- "{}{}",- commit_config.command.as_ref().unwrap(),- if commit_config.args.is_empty() {- String::new()- } else {- format!(" {}", commit_config.args.join(" "))- }- );-- match test_commit_generation(commit_config) {- Ok(message) => {- writeln!(- out,- "{}",- success_message(cformat!(- "Commit generation working (<bold>{command_display}</>)"- ))- )?;- writeln!(out, "{}", format_with_gutter(&message, None))?;- }- Err(e) => {- writeln!(- out,- "{}",- error_message(cformat!(- "Commit generation failed (<bold>{command_display}</>)"- ))- )?;- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;- }- }-- Ok(())-}--fn render_user_config(out: &mut String) -> anyhow::Result<()> {- let config_path = require_user_config_path()?;-- writeln!(- out,- "{}",- format_heading("USER CONFIG", Some(&format_path_for_display(&config_path)))- )?;-- // Check if file exists- if !config_path.exists() {- writeln!(- out,- "{}",- hint_message(cformat!(- "Not found; to create one, run <bright-black>wt config create</>"- ))- )?;- return Ok(());- }-- // Read and display the file contents- let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;-- if contents.trim().is_empty() {- writeln!(out, "{}", hint_message("Empty file (using defaults)"))?;- return Ok(());- }-- // Validate config (syntax + schema) and warn if invalid- if let Err(e) = toml::from_str::<WorktrunkConfig>(&contents) {- // Use gutter for error details to avoid markup interpretation of user content- writeln!(out, "{}", error_message("Invalid config"))?;- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;- } else {- // Only check for unknown keys if config is valid- warn_unknown_keys(out, &find_unknown_user_keys(&contents))?;- }-- // Display TOML with syntax highlighting (gutter at column 0)- write!(out, "{}", format_toml(&contents))?;-- Ok(())-}--/// Write warnings for any unknown config keys-fn warn_unknown_keys(out: &mut String, unknown_keys: &[String]) -> anyhow::Result<()> {- for key in unknown_keys {- writeln!(- out,- "{}",- warning_message(cformat!("Unknown key <bold>{key}</> will be ignored"))- )?;- }- Ok(())-}--fn render_project_config(out: &mut String) -> anyhow::Result<()> {- // Try to get current repository root- let repo_root = match Repository::current().and_then(|repo| repo.current_worktree().root()) {- Ok(root) => root,- Err(_) => {- writeln!(- out,- "{}",- cformat!(- "<dim>{}</>",- format_heading("PROJECT CONFIG", Some("Not in a git repository"))- )- )?;- return Ok(());- }- };- let config_path = repo_root.join(".config").join("wt.toml");-- writeln!(- out,- "{}",- format_heading(- "PROJECT CONFIG",- Some(&format_path_for_display(&config_path))- )- )?;-- // Check if file exists- if !config_path.exists() {- writeln!(out, "{}", hint_message("Not found"))?;- return Ok(());- }-- // Read and display the file contents- let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;-- if contents.trim().is_empty() {- writeln!(out, "{}", hint_message("Empty file"))?;- return Ok(());- }-- // Validate config (syntax + schema) and warn if invalid- if let Err(e) = toml::from_str::<ProjectConfig>(&contents) {- // Use gutter for error details to avoid markup interpretation of user content- writeln!(out, "{}", error_message("Invalid config"))?;- writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;- } else {- // Only check for unknown keys if config is valid- warn_unknown_keys(out, &find_unknown_project_keys(&contents))?;- }-- // Display TOML with syntax highlighting (gutter at column 0)- write!(out, "{}", format_toml(&contents))?;-- Ok(())-}--fn render_shell_status(out: &mut String) -> anyhow::Result<()> {- writeln!(out, "{}", format_heading("SHELL INTEGRATION", None))?;-- // Shell integration runtime status (moved from RUNTIME section)- let shell_active = output::is_shell_integration_active();- if shell_active {- writeln!(out, "{}", info_message("Shell integration active"))?;- } else {- writeln!(out, "{}", warning_message("Shell integration not active"))?;- // Show invocation details to help diagnose- let invocation = crate::invocation_path();- let is_git_subcommand = crate::is_git_subcommand();- let mut debug_lines = vec![cformat!("Invoked as: <bold>{invocation}</>")];-- // Show actual binary path if different from invocation (helps detect wrong wt in PATH)- if let Ok(exe_path) = std::env::current_exe() {- let exe_display = format_path_for_display(&exe_path);- // Only show if meaningfully different (not just ./ prefix differences)- let invocation_canonical = std::fs::canonicalize(&invocation).ok();- let exe_canonical = std::fs::canonicalize(&exe_path).ok();- if invocation_canonical != exe_canonical {- debug_lines.push(cformat!("Running from: <bold>{exe_display}</>"));- }- }-- // Show $SHELL to help diagnose rc file sourcing issues- if let Ok(shell_env) = std::env::var("SHELL") {- debug_lines.push(cformat!("$SHELL: <bold>{shell_env}</>"));- }-- if is_git_subcommand {- debug_lines.push("Git subcommand: yes (GIT_EXEC_PATH set)".to_string());- }- writeln!(out, "{}", format_with_gutter(&debug_lines.join("\n"), None))?;- }- writeln!(out)?;-- // Use the same detection logic as `wt config shell install`- let cmd = crate::binary_name();- let scan_result = match scan_shell_configs(None, true, &cmd) {- Ok(r) => r,- Err(e) => {- writeln!(- out,- "{}",- hint_message(format!("Could not determine shell status: {e}"))- )?;- return Ok(());- }- };-- // Get detection details to show matched lines inline- let detection_results = scan_for_detection_details(&cmd).unwrap_or_default();-- // Check for legacy fish conf.d path (deprecated location from before #566)- // We need this early to handle the case where fish shows "Not configured" at the- // new location but has valid integration at the legacy location.- let legacy_fish_conf_d = Shell::legacy_fish_conf_d_path(&cmd).ok();- let legacy_fish_has_integration = legacy_fish_conf_d.as_ref().is_some_and(|legacy_path| {- detection_results- .iter()- .any(|d| d.path == *legacy_path && !d.matched_lines.is_empty())- });-- let mut any_not_configured = false;- let mut has_any_unmatched = false;-- // Show configured and not-configured shells (matching `config shell install` format exactly)- // Bash/Zsh: inline completions, show "shell extension & completions"- // Fish: separate completion file, show "shell extension" for functions/ and "completions" for completions/- for result in &scan_result.configured {- let shell = result.shell;- let path = format_path_for_display(&result.path);- // Fish has separate completion file; bash/zsh have inline completions- let what = if matches!(shell, Shell::Fish) {- "shell extension"- } else {- "shell extension & completions"- };-- match result.action {- ConfigAction::AlreadyExists => {- // Show the matched lines directly under this status- let detection = detection_results- .iter()- .find(|d| d.path == result.path && !d.matched_lines.is_empty());-- // Build file:line location (clickable in terminals - use first line only)- let location = if let Some(det) = detection {- if let Some(first_line) = det.matched_lines.first() {- format!("{}:{}", path, first_line.line_number)- } else {- path.to_string()- }- } else {- path.to_string()- };-- writeln!(- out,- "{}",- info_message(cformat!(- "Already configured {what} for <bold>{shell}</> @ {location}"- ))- )?;-- if let Some(det) = detection {- for detected in &det.matched_lines {- writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;- }-- // Check if any matched lines use .exe suffix and warn about function name- let uses_exe = det.matched_lines.iter().any(|m| m.content.contains(".exe"));- if uses_exe {- writeln!(- out,- "{}",- hint_message(cformat!(- "Creates shell function <bold>{cmd}</>. Aliases should use <bright-black>{cmd}</>, not <bright-black>{cmd}.exe</>"- ))- )?;- }- }-- // Check if zsh has compinit enabled (required for completions)- if matches!(shell, Shell::Zsh) && check_zsh_compinit_missing() {- writeln!(- out,- "{}",- warning_message(- "Completions won't work; add to ~/.zshrc before the wt line:"- )- )?;- writeln!(- out,- "{}",- format_with_gutter("autoload -Uz compinit && compinit", None)- )?;- }-- // For fish, check completions file separately- if matches!(shell, Shell::Fish)- && let Ok(completion_path) = shell.completion_path(&cmd)- {- let completion_display = format_path_for_display(&completion_path);- if completion_path.exists() {- writeln!(- out,- "{}",- info_message(cformat!(- "Already configured completions for <bold>{shell}</> @ {completion_display}"- ))- )?;- } else {- any_not_configured = true;- writeln!(- out,- "{}",- hint_message(format!("Not configured completions for {shell}"))- )?;- }- }- }- ConfigAction::WouldAdd | ConfigAction::WouldCreate => {- // For fish, check if we have valid integration at the legacy conf.d location- if matches!(shell, Shell::Fish) && legacy_fish_has_integration {- // Show migration hint instead of "Not configured"- let legacy_path = legacy_fish_conf_d- .as_ref()- .map(|p| format_path_for_display(p))- .unwrap_or_default();- writeln!(- out,- "{}",- info_message(cformat!(- "Fish integration found in deprecated location @ <bold>{legacy_path}</>"- ))- )?;- // Get canonical path for the migration hint- let canonical_path = Shell::Fish- .config_paths(&cmd)- .ok()- .and_then(|p| p.into_iter().next())- .map(|p| format_path_for_display(&p))- .unwrap_or_else(|| "~/.config/fish/functions/".to_string());- writeln!(- out,- "{}",- hint_message(cformat!(- "To migrate to <bright-black>{canonical_path}</>, run <bright-black>{cmd} config shell install fish</>"- ))- )?;- } else {- any_not_configured = true;- writeln!(- out,- "{}",- hint_message(format!("Not configured {what} for {shell}"))- )?;- }- }- _ => {} // Added/Created won't appear in dry_run mode- }- }-- // Show skipped (not installed) shells- // For fish with legacy integration, show migration hint instead of "skipped"- for (shell, path) in &scan_result.skipped {- if matches!(shell, Shell::Fish) && legacy_fish_has_integration {- // Show migration hint for legacy fish location- let legacy_path = legacy_fish_conf_d- .as_ref()- .map(|p| format_path_for_display(p))- .unwrap_or_default();- let canonical_path = Shell::Fish- .config_paths(&cmd)- .ok()- .and_then(|p| p.into_iter().next())- .map(|p| format_path_for_display(&p))- .unwrap_or_else(|| "~/.config/fish/functions/".to_string());- writeln!(- out,- "{}",- info_message(cformat!(- "Fish integration found in deprecated location @ <bold>{legacy_path}</>"- ))- )?;- writeln!(- out,- "{}",- hint_message(cformat!(- "To migrate to <bright-black>{canonical_path}</>, run <bright-black>{cmd} config shell install fish</>"- ))- )?;- continue;- }- let path = format_path_for_display(path);- writeln!(- out,- "{}",- info_message(cformat!("<dim>Skipped {shell}; {path} not found</>"))- )?;- }-- // Summary hint when shells need configuration- if any_not_configured {- writeln!(out)?;- writeln!(- out,- "{}",- hint_message(cformat!(- "To configure, run <bright-black>{cmd} config shell install</>"- ))- )?;- }-- // Show potential false negatives (lines containing cmd but not detected)- // Skip files that have valid integration detected (matched_lines) - those are fine,- // and the other lines containing cmd are just part of the integration script.- for detection in &detection_results {- if !detection.unmatched_candidates.is_empty() && detection.matched_lines.is_empty() {- has_any_unmatched = true;- let path = format_path_for_display(&detection.path);-- // Build file:line location (clickable in terminals - use first line only)- let location = if let Some(first) = detection.unmatched_candidates.first() {- format!("{}:{}", path, first.line_number)- } else {- path.to_string()- };- writeln!(- out,- "{}",- warning_message(cformat!(- "Found <bold>{cmd}</> in <bold>{location}</> but not detected as integration:"- ))- )?;- for detected in &detection.unmatched_candidates {- writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;- }-- // If any unmatched lines contain .exe, explain the function name issue- let uses_exe = detection- .unmatched_candidates- .iter()- .any(|m| m.content.contains(".exe"));- if uses_exe {- writeln!(- out,- "{}",- hint_message(cformat!(- "Note: <bold>{cmd}.exe</> creates shell function <bold>{cmd}</>. \- Aliases should use <bright-black>{cmd}</>, not <bright-black>{cmd}.exe</>"- ))- )?;- }- }- }-- // Show aliases that bypass shell integration (Issue #348)- for detection in &detection_results {- for alias in &detection.bypass_aliases {- let path = format_path_for_display(&detection.path);- let location = format!("{}:{}", path, alias.line_number);- writeln!(- out,- "{}",- warning_message(cformat!(- "Alias <bold>{}</> bypasses shell integration — won't auto-cd",- alias.alias_name- ))- )?;- writeln!(out, "{}", format_bash_with_gutter(alias.content.trim()))?;- writeln!(- out,- "{}",- hint_message(cformat!(- "Change to <bright-black>alias {}=\"{cmd}\"</> @ {location}",- alias.alias_name- ))- )?;- }- }-- // Check if any shell has config already (eval line present)- let has_any_configured = scan_result- .configured- .iter()- .any(|r| matches!(r.action, ConfigAction::AlreadyExists));-- // If we have unmatched candidates but no configured shells, suggest raising an issue- if has_any_unmatched && !has_any_configured {- let unmatched_summary: Vec<_> = detection_results- .iter()- .filter(|r| !r.unmatched_candidates.is_empty())- .flat_map(|r| {- r.unmatched_candidates- .iter()- .map(|d| d.content.trim().to_string())- })- .collect();- let body = format!(- "Shell integration not detected despite config containing `{cmd}`.\n\n\- **Unmatched lines:**\n```\n{}\n```\n\n\- **Expected behavior:** These lines should be detected as shell integration.",- unmatched_summary.join("\n")- );- let issue_url = format!(- "https://github.com/max-sixty/worktrunk/issues/new?title={}&body={}",- urlencoding::encode("Shell integration detection false negative"),- urlencoding::encode(&body)- );-- // Quote a short version of the unmatched content in the hint- let quoted = if unmatched_summary.len() == 1 {- format!("`{}`", unmatched_summary[0])- } else {- format!(- "`{}` (and {} more)",- unmatched_summary[0],- unmatched_summary.len() - 1- )- };- writeln!(- out,- "{}",- hint_message(format!(- "If {quoted} is shell integration, report a false negative: {issue_url}"- ))- )?;- }-- Ok(())-}--fn render_ci_tool_status(- out: &mut String,- tool: &str,- platform: &str,- installed: bool,- authenticated: bool,-) -> anyhow::Result<()> {- if installed {- if authenticated {- writeln!(- out,- "{}",- success_message(cformat!("<bold>{tool}</> installed & authenticated"))- )?;- } else {- writeln!(- out,- "{}",- warning_message(cformat!(- "<bold>{tool}</> installed but not authenticated; run <bold>{tool} auth login</>"- ))- )?;- }- } else {- writeln!(- out,- "{}",- hint_message(cformat!(- "<bold>{tool}</> not found ({platform} CI status unavailable)"- ))- )?;- }- Ok(())-}--/// 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).-fn check_zsh_compinit_missing() -> bool {- use worktrunk::shell_exec::Cmd;-- // 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().- let Ok(output) = Cmd::new("zsh")- .args(["--no-globalrcs", "-ic", "(( $+functions[compdef] ))"])- .env("ZSH_DISABLE_COMPFIX", "true")- .run()- else {- return false; // Can't determine, don't warn- };-- // compdef NOT found = need to warn- !output.status.success()-}--/// Core logic for determining user config path from env var values-fn resolve_user_config_path(xdg_config_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {- // Respect XDG_CONFIG_HOME environment variable (Linux)- if let Some(xdg_config) = xdg_config_home {- let config_path = PathBuf::from(xdg_config);- return Some(config_path.join("worktrunk").join("config.toml"));- }-- // Respect HOME environment variable (fallback)- if let Some(home) = home {- let home_path = PathBuf::from(home);- return Some(- home_path- .join(".config")- .join("worktrunk")- .join("config.toml"),- );- }-- None-}--fn get_user_config_path() -> Option<PathBuf> {- // Try env vars first, then fall back to etcetera- resolve_user_config_path(- std::env::var("XDG_CONFIG_HOME").ok().as_deref(),- std::env::var("HOME").ok().as_deref(),- )- .or_else(|| {- let strategy = choose_base_strategy().ok()?;- Some(strategy.config_dir().join("worktrunk").join("config.toml"))- })-}--fn require_user_config_path() -> anyhow::Result<PathBuf> {- get_user_config_path().ok_or_else(|| {- anyhow::anyhow!(- "Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME environment variable"- )- })-}--/// Clear all log files from the wt-logs directory-fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {- let log_dir = repo.wt_logs_dir();-- if !log_dir.exists() {- return Ok(0);- }-- let mut cleared = 0;- for entry in std::fs::read_dir(&log_dir)? {- let entry = entry?;- let path = entry.path();- if path.is_file() && path.extension().is_some_and(|ext| ext == "log") {- std::fs::remove_file(&path)?;- cleared += 1;- }- }-- // Remove the directory if empty- if std::fs::read_dir(&log_dir)?.next().is_none() {- let _ = std::fs::remove_dir(&log_dir);- }-- Ok(cleared)-}--/// Render the LOG FILES section (heading + table or "(none)") into the output buffer-fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {- let log_dir = repo.wt_logs_dir();- let log_dir_display = format_path_for_display(&log_dir);-- writeln!(- out,- "{}",- format_heading("LOG FILES", Some(&format!("@ {log_dir_display}")))- )?;-- if !log_dir.exists() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- return Ok(());- }-- let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?- .filter_map(|e| e.ok())- .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))- .collect();-- if entries.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- return Ok(());- }-- // Sort by modification time (newest first), then by name for stability- entries.sort_by(|a, b| {- let a_time = a.metadata().and_then(|m| m.modified()).ok();- let b_time = b.metadata().and_then(|m| m.modified()).ok();- b_time- .cmp(&a_time)- .then_with(|| a.file_name().cmp(&b.file_name()))- });-- // Build table- let mut table = String::from("| File | Size | Age |\n");- table.push_str("|------|------|-----|\n");-- for entry in entries {- let path = entry.path();- let name = path.file_name().unwrap_or_default().to_string_lossy();- let meta = entry.metadata().ok();-- let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);- let size_str = if size < 1024 {- format!("{size}B")- } else {- format!("{}K", size / 1024)- };-- let age = meta- .and_then(|m| m.modified().ok())- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())- .map(|d| format_relative_time_short(d.as_secs() as i64))- .unwrap_or_else(|| "?".to_string());-- table.push_str(&format!("| {name} | {size_str} | {age} |\n"));- }-- let rendered = crate::md_help::render_markdown_table(&table);- write!(out, "{}", rendered.trim_end())?;-- Ok(())-}--/// Handle the state get command-pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {- use super::list::ci_status::PrStatus;-- let repo = Repository::current()?;-- match key {- "default-branch" => {- let branch_name = repo.default_branch().ok_or_else(|| {- anyhow::anyhow!(cformat!(- "Cannot determine default branch. To configure, run <bold>wt config state default-branch set BRANCH</>"- ))- })?;- crate::output::stdout(branch_name)?;- }- "previous-branch" => match repo.get_switch_previous() {- Some(prev) => crate::output::stdout(prev)?,- None => crate::output::stdout("")?,- },- "marker" => {- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("get marker for current branch")?,- };- match repo.branch_keyed_marker(&branch_name) {- Some(marker) => crate::output::stdout(marker)?,- None => crate::output::stdout("")?,- }- }- "ci-status" => {- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("get ci-status for current branch")?,- };-- // Get the HEAD commit for this branch- let head = repo- .run_command(&["rev-parse", &branch_name])- .map(|s| s.trim().to_string())- .unwrap_or_default();-- if head.is_empty() {- return Err(worktrunk::git::GitError::InvalidReference {- reference: branch_name,- }- .into());- }-- let has_upstream = repo.upstream_branch(&branch_name).ok().flatten().is_some();- let ci_status = PrStatus::detect(&repo, &branch_name, &head, has_upstream)- .map_or(super::list::ci_status::CiStatus::NoCI, |s| s.ci_status);- let status_str: &'static str = ci_status.into();- crate::output::stdout(status_str)?;- }- // TODO: Consider simplifying to just print the path and let users run `ls -al` themselves- "logs" => {- let mut out = String::new();- render_log_files(&mut out, &repo)?;-- // Display through pager (fall back to stderr if pager unavailable)- if show_help_in_pager(&out, true).is_err() {- worktrunk::styling::eprintln!("{}", out);- }- }- _ => {- anyhow::bail!(- "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"- )- }- }-- Ok(())-}--/// Handle the state set command-pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anyhow::Result<()> {- let repo = Repository::current()?;-- match key {- "default-branch" => {- // Warn if the branch doesn't exist locally- if !repo.local_branch_exists(&value)? {- crate::output::print(warning_message(cformat!(- "Branch <bold>{value}</> does not exist locally"- )))?;- }- repo.set_default_branch(&value)?;- crate::output::print(success_message(cformat!(- "Set default branch to <bold>{value}</>"- )))?;- }- "previous-branch" => {- repo.record_switch_previous(Some(&value))?;- crate::output::print(success_message(cformat!(- "Set previous branch to <bold>{value}</>"- )))?;- }- "marker" => {- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("set marker for current branch")?,- };-- // Store as JSON with timestamp- let now = get_now();- let json = serde_json::json!({- "marker": value,- "set_at": now- });-- let config_key = format!("worktrunk.state.{branch_name}.marker");- repo.run_command(&["config", &config_key, &json.to_string()])?;-- crate::output::print(success_message(cformat!(- "Set marker for <bold>{branch_name}</> to <bold>{value}</>"- )))?;- }- _ => {- anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, previous-branch, marker")- }- }-- Ok(())-}--/// Handle the state clear command-pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhow::Result<()> {- let repo = Repository::current()?;-- match key {- "default-branch" => {- if repo.clear_default_branch_cache()? {- crate::output::print(success_message("Cleared default branch cache"))?;- } else {- crate::output::print(info_message("No default branch cache to clear"))?;- }- }- "previous-branch" => {- if repo- .run_command(&["config", "--unset", "worktrunk.history"])- .is_ok()- {- crate::output::print(success_message("Cleared previous branch"))?;- } else {- crate::output::print(info_message("No previous branch to clear"))?;- }- }- "ci-status" => {- if all {- let cleared = CachedCiStatus::clear_all(&repo);- if cleared == 0 {- crate::output::print(info_message("No CI cache entries to clear"))?;- } else {- crate::output::print(success_message(cformat!(- "Cleared <bold>{cleared}</> CI cache entr{}",- if cleared == 1 { "y" } else { "ies" }- )))?;- }- } else {- // Clear CI status for specific branch- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("clear ci-status for current branch")?,- };- let config_key = format!("worktrunk.state.{branch_name}.ci-status");- if repo- .run_command(&["config", "--unset", &config_key])- .is_ok()- {- crate::output::print(success_message(cformat!(- "Cleared CI cache for <bold>{branch_name}</>"- )))?;- } else {- crate::output::print(info_message(cformat!(- "No CI cache for <bold>{branch_name}</>"- )))?;- }- }- }- "marker" => {- if all {- let output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])- .unwrap_or_default();-- let mut cleared_count = 0;- for line in output.lines() {- if let Some(config_key) = line.split_whitespace().next() {- repo.run_command(&["config", "--unset", config_key])?;- cleared_count += 1;- }- }-- if cleared_count == 0 {- crate::output::print(info_message("No markers to clear"))?;- } else {- crate::output::print(success_message(cformat!(- "Cleared <bold>{cleared_count}</> marker{}",- if cleared_count == 1 { "" } else { "s" }- )))?;- }- } else {- let branch_name = match branch {- Some(b) => b,- None => repo.require_current_branch("clear marker for current branch")?,- };-- let config_key = format!("worktrunk.state.{branch_name}.marker");- if repo- .run_command(&["config", "--unset", &config_key])- .is_ok()- {- crate::output::print(success_message(cformat!(- "Cleared marker for <bold>{branch_name}</>"- )))?;- } else {- crate::output::print(info_message(cformat!(- "No marker set for <bold>{branch_name}</>"- )))?;- }- }- }- "logs" => {- let cleared = clear_logs(&repo)?;- if cleared == 0 {- crate::output::print(info_message("No logs to clear"))?;- } else {- crate::output::print(success_message(cformat!(- "Cleared <bold>{cleared}</> log file{}",- if cleared == 1 { "" } else { "s" }- )))?;- }- }- _ => {- anyhow::bail!(- "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"- )- }- }-- Ok(())-}--/// Handle the state clear all command-pub fn handle_state_clear_all() -> anyhow::Result<()> {- let repo = Repository::current()?;- let mut cleared_any = false;-- // Clear default branch cache- if matches!(repo.clear_default_branch_cache(), Ok(true)) {- cleared_any = true;- }-- // Clear previous branch- if repo- .run_command(&["config", "--unset", "worktrunk.history"])- .is_ok()- {- cleared_any = true;- }-- // Clear all markers- let markers_output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])- .unwrap_or_default();- for line in markers_output.lines() {- if let Some(config_key) = line.split_whitespace().next() {- let _ = repo.run_command(&["config", "--unset", config_key]);- cleared_any = true;- }- }-- // Clear all CI status cache- let ci_cleared = CachedCiStatus::clear_all(&repo);- if ci_cleared > 0 {- cleared_any = true;- }-- // Clear all logs- let logs_cleared = clear_logs(&repo)?;- if logs_cleared > 0 {- cleared_any = true;- }-- // Clear all hints- let hints_cleared = repo.clear_all_hints()?;- if hints_cleared > 0 {- cleared_any = true;- }-- if cleared_any {- crate::output::print(success_message("Cleared all stored state"))?;- } else {- crate::output::print(info_message("No stored state to clear"))?;- }-- Ok(())-}--/// Handle the hints get command (list shown hints)-pub fn handle_hints_get() -> anyhow::Result<()> {- let repo = Repository::current()?;- let hints = repo.list_shown_hints();-- if hints.is_empty() {- crate::output::print(info_message("No hints have been shown"))?;- } else {- for hint in hints {- crate::output::stdout(&hint)?;- }- }-- Ok(())-}--/// Handle the hints clear command-pub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {- let repo = Repository::current()?;-- match name {- Some(hint_name) => {- let msg = if repo.clear_hint(&hint_name)? {- success_message(cformat!("Cleared hint <bold>{hint_name}</>"))- } else {- info_message(cformat!("Hint <bold>{hint_name}</> was not set"))- };- crate::output::print(msg)?;- }- None => {- let cleared = repo.clear_all_hints()?;- let msg = if cleared == 0 {- info_message("No hints to clear")- } else {- let suffix = if cleared == 1 { "" } else { "s" };- success_message(cformat!("Cleared <bold>{cleared}</> hint{suffix}"))- };- crate::output::print(msg)?;- }- }-- Ok(())-}--/// Handle the state get command (shows all state)-pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()> {- use crate::cli::OutputFormat;-- let repo = Repository::current()?;-- match format {- OutputFormat::Json => handle_state_show_json(&repo),- OutputFormat::Table => handle_state_show_table(&repo),- }-}--/// Output state as JSON-fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {- // Get default branch- let default_branch = repo.default_branch();-- // Get previous branch- let previous_branch = repo.get_switch_previous();-- // Get markers- let markers: Vec<serde_json::Value> = get_all_markers(repo)- .into_iter()- .map(|m| {- serde_json::json!({- "branch": m.branch,- "marker": m.marker,- "set_at": if m.set_at > 0 { Some(m.set_at) } else { None }- })- })- .collect();-- // Get CI status cache- let mut ci_entries = CachedCiStatus::list_all(repo);- ci_entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });- let ci_status: Vec<serde_json::Value> = ci_entries- .into_iter()- .map(|(branch, cached)| {- let status = cached- .status- .as_ref()- .map(|s| -> &'static str { s.ci_status.into() });- serde_json::json!({- "branch": branch,- "status": status,- "checked_at": cached.checked_at,- "head": cached.head- })- })- .collect();-- // Get log files- let log_dir = repo.wt_logs_dir();- let logs: Vec<serde_json::Value> = if log_dir.exists() {- let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?- .filter_map(|e| e.ok())- .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))- .collect();-- entries.sort_by(|a, b| {- let a_time = a.metadata().and_then(|m| m.modified()).ok();- let b_time = b.metadata().and_then(|m| m.modified()).ok();- b_time.cmp(&a_time)- });-- entries- .into_iter()- .map(|entry| {- let path = entry.path();- let name = path- .file_name()- .unwrap_or_default()- .to_string_lossy()- .to_string();- let meta = entry.metadata().ok();- let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);- let modified = meta- .and_then(|m| m.modified().ok())- .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())- .map(|d| d.as_secs());-- serde_json::json!({- "file": name,- "size": size,- "modified_at": modified- })- })- .collect()- } else {- vec![]- };-- // Get hints- let hints = repo.list_shown_hints();-- let output = serde_json::json!({- "default_branch": default_branch,- "previous_branch": previous_branch,- "markers": markers,- "ci_status": ci_status,- "logs": logs,- "hints": hints- });-- crate::output::stdout(serde_json::to_string_pretty(&output)?)?;- Ok(())-}--/// Output state as human-readable table-fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {- // Build complete output as a string- let mut out = String::new();-- // Show default branch cache- writeln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;- match repo.default_branch() {- Some(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,- None => writeln!(out, "{}", format_with_gutter("(not available)", None))?,- }- writeln!(out)?;-- // Show previous branch (for `wt switch -`)- writeln!(out, "{}", format_heading("PREVIOUS BRANCH", None))?;- match repo.get_switch_previous() {- Some(prev) => writeln!(out, "{}", format_with_gutter(&prev, None))?,- None => writeln!(out, "{}", format_with_gutter("(none)", None))?,- }- writeln!(out)?;-- // Show branch markers- writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;- let markers = get_all_markers(repo);- if markers.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- let mut table = String::from("| Branch | Marker | Age |\n");- table.push_str("|--------|--------|-----|\n");- for entry in markers {- let age = format_relative_time_short(entry.set_at as i64);- table.push_str(&format!(- "| {} | {} | {} |\n",- entry.branch, entry.marker, age- ));- }- let rendered = crate::md_help::render_markdown_table(&table);- writeln!(out, "{}", rendered.trim_end())?;- }- writeln!(out)?;-- // Show CI status cache- writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;- let mut entries = CachedCiStatus::list_all(repo);- // Sort by age (most recent first), then by branch name for ties- entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });- if entries.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- // Build markdown table- let mut table = String::from("| Branch | Status | Age | Head |\n");- table.push_str("|--------|--------|-----|------|\n");- for (branch, cached) in entries {- let status = match &cached.status {- Some(pr_status) => {- let status: &'static str = pr_status.ci_status.into();- status.to_string()- }- None => "none".to_string(),- };- let age = format_relative_time_short(cached.checked_at as i64);- let head: String = cached.head.chars().take(8).collect();-- table.push_str(&format!("| {branch} | {status} | {age} | {head} |\n"));- }-- let rendered = crate::md_help::render_markdown_table(&table);- writeln!(out, "{}", rendered.trim_end())?;- }- writeln!(out)?;-- // Show hints- writeln!(out, "{}", format_heading("HINTS", None))?;- let hints = repo.list_shown_hints();- if hints.is_empty() {- writeln!(out, "{}", format_with_gutter("(none)", None))?;- } else {- for hint in hints {- writeln!(out, "{}", format_with_gutter(&hint, None))?;- }- }- writeln!(out)?;-- // Show log files- render_log_files(&mut out, repo)?;-- // Display through pager (fall back to stderr if pager unavailable)- if let Err(e) = show_help_in_pager(&out, true) {- log::debug!("Pager invocation failed: {}", e);- // Fall back to direct output via eprintln (matches help behavior)- worktrunk::styling::eprintln!("{}", out);- }-- Ok(())-}--/// Marker entry with branch, text, and timestamp-struct MarkerEntry {- branch: String,- marker: String,- set_at: u64,-}--/// Get all branch markers from git config with timestamps-fn get_all_markers(repo: &Repository) -> Vec<MarkerEntry> {- let output = repo- .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])- .unwrap_or_default();-- let mut markers = Vec::new();- for line in output.lines() {- // Format: "worktrunk.state.<branch>.marker json_value"- let Some((key, value)) = line.split_once(' ') else {- continue;- };- let Some(branch) = key- .strip_prefix("worktrunk.state.")- .and_then(|s| s.strip_suffix(".marker"))- else {- continue;- };- let Ok(parsed) = serde_json::from_str::<serde_json::Value>(value) else {- continue; // Skip invalid JSON- };- let Some(marker) = parsed.get("marker").and_then(|v| v.as_str()) else {- continue; // Skip if "marker" field is missing- };- let set_at = parsed.get("set_at").and_then(|v| v.as_u64()).unwrap_or(0);- markers.push(MarkerEntry {- branch: branch.to_string(),- marker: marker.to_string(),- set_at,- });- }-- // Sort by age (most recent first), then by branch name for ties- markers.sort_by(|a, b| {- b.set_at- .cmp(&a.set_at)- .then_with(|| a.branch.cmp(&b.branch))- });- markers-}--#[cfg(test)]-mod tests {- use super::*;-- // ==================== comment_out_config tests ====================-- #[test]- fn test_comment_out_config_basic() {- let input = "key = \"value\"\n";- let expected = "# key = \"value\"\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_preserves_existing_comments() {- let input = "# This is a comment\nkey = \"value\"\n";- let expected = "# This is a comment\n# key = \"value\"\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_preserves_empty_lines() {- let input = "key1 = \"value\"\n\nkey2 = \"value\"\n";- let expected = "# key1 = \"value\"\n\n# key2 = \"value\"\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_preserves_trailing_newline() {- let with_newline = "key = \"value\"\n";- let without_newline = "key = \"value\"";-- assert!(comment_out_config(with_newline).ends_with('\n'));- assert!(!comment_out_config(without_newline).ends_with('\n'));- }-- #[test]- fn test_comment_out_config_section_headers() {- let input = "[hooks]\ncommand = \"npm test\"\n";- let expected = "# [hooks]\n# command = \"npm test\"\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_empty_input() {- assert_eq!(comment_out_config(""), "");- }-- #[test]- fn test_comment_out_config_only_empty_lines() {- let input = "\n\n\n";- let expected = "\n\n\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_only_comments() {- let input = "# comment 1\n# comment 2\n";- let expected = "# comment 1\n# comment 2\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_mixed_content() {- let input =- "# Header comment\n\n[section]\nkey = \"value\"\n\n# Another comment\nkey2 = true\n";- let expected = "# Header comment\n\n# [section]\n# key = \"value\"\n\n# Another comment\n# key2 = true\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_inline_table() {- let input = "point = { x = 1, y = 2 }\n";- let expected = "# point = { x = 1, y = 2 }\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_multiline_array() {- let input = "args = [\n \"--flag\",\n \"value\"\n]\n";- let expected = "# args = [\n# \"--flag\",\n# \"value\"\n# ]\n";- assert_eq!(comment_out_config(input), expected);- }-- #[test]- fn test_comment_out_config_whitespace_only_line() {- // Lines with only whitespace are not empty - they should NOT be commented- // Actually, let's check what the current behavior is:- // The function checks `!line.is_empty()` - a line with spaces is not empty- let input = "key = 1\n \nkey2 = 2\n";- let expected = "# key = 1\n# \n# key2 = 2\n";- assert_eq!(comment_out_config(input), expected);- }-- // ==================== warn_unknown_keys tests ====================-- #[test]- fn test_warn_unknown_keys_empty() {- let mut out = String::new();- warn_unknown_keys(&mut out, &[]).unwrap();- assert!(out.is_empty());- }-- #[test]- fn test_warn_unknown_keys_single() {- let mut out = String::new();- warn_unknown_keys(&mut out, &["unknown-key".to_string()]).unwrap();- assert!(out.contains("unknown-key"));- assert!(out.contains("Unknown key"));- }-- #[test]- fn test_warn_unknown_keys_multiple() {- let mut out = String::new();- warn_unknown_keys(&mut out, &["key1".to_string(), "key2".to_string()]).unwrap();- assert!(out.contains("key1"));- assert!(out.contains("key2"));- // Should have two separate warning lines- assert_eq!(out.matches("Unknown key").count(), 2);- }-- // ==================== render_ci_tool_status tests ====================-- #[test]- fn test_render_ci_tool_status_installed_authenticated() {- let mut out = String::new();- render_ci_tool_status(&mut out, "gh", "GitHub", true, true).unwrap();- assert!(out.contains("gh"));- assert!(out.contains("installed"));- assert!(out.contains("authenticated"));- }-- #[test]- fn test_render_ci_tool_status_installed_not_authenticated() {- let mut out = String::new();- render_ci_tool_status(&mut out, "gh", "GitHub", true, false).unwrap();- assert!(out.contains("gh"));- assert!(out.contains("installed"));- assert!(out.contains("not authenticated"));- assert!(out.contains("gh auth login"));- }-- #[test]- fn test_render_ci_tool_status_not_installed() {- let mut out = String::new();- render_ci_tool_status(&mut out, "glab", "GitLab", false, false).unwrap();- assert!(out.contains("glab"));- assert!(out.contains("not found"));- assert!(out.contains("GitLab"));- assert!(out.contains("CI status unavailable"));- }-- #[test]- fn test_render_ci_tool_status_glab() {- let mut out = String::new();- render_ci_tool_status(&mut out, "glab", "GitLab", true, true).unwrap();- assert!(out.contains("glab"));- assert!(out.contains("installed"));- assert!(out.contains("authenticated"));- }-- // ==================== resolve_user_config_path tests ====================-- #[test]- fn test_resolve_user_config_path_xdg_takes_priority() {- let path = resolve_user_config_path(Some("/custom/xdg"), Some("/home/user"));- assert_eq!(- path,- Some(PathBuf::from("/custom/xdg/worktrunk/config.toml"))- );- }-- #[test]- fn test_resolve_user_config_path_home_fallback() {- let path = resolve_user_config_path(None, Some("/home/testuser"));- assert_eq!(- path,- Some(PathBuf::from(- "/home/testuser/.config/worktrunk/config.toml"- ))- );- }-- #[test]- fn test_resolve_user_config_path_none_when_no_env() {- let path = resolve_user_config_path(None, None);- assert_eq!(path, None);- }-- // ==================== get_user_config_path tests ====================-- #[test]- fn test_get_user_config_path_returns_some() {- // In a normal environment, get_user_config_path should return Some- // (either from env vars or etcetera fallback)- let path = get_user_config_path();- assert!(path.is_some());- let path = path.unwrap();- assert!(path.ends_with("worktrunk/config.toml"));- }-- // ==================== require_user_config_path tests ====================-- #[test]- fn test_require_user_config_path_returns_ok() {- // In a normal environment, require_user_config_path should succeed- let result = require_user_config_path();- assert!(result.is_ok());- let path = result.unwrap();- assert!(path.ends_with("worktrunk/config.toml"));- }-- // ==================== get_git_version tests ====================-- #[test]- fn test_get_git_version_returns_version() {- // In a normal environment with git installed, should return a version- let version = get_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('.'));- }-}diff --git a/src/commands/config/create.rs b/src/commands/config/create.rsnew file mode 100644index 000000000..ccb194d1e--- /dev/null+++ b/src/commands/config/create.rs@@ -0,0 +1,135 @@+//! Config file creation.+//!+//! Commands for creating user and project configuration files.++use anyhow::Context;+use color_print::cformat;+use std::path::PathBuf;+use worktrunk::git::Repository;+use worktrunk::path::format_path_for_display;+use worktrunk::styling::{hint_message, info_message, success_message};++use super::state::require_user_config_path;+use crate::output;++/// Example user configuration file content (displayed in help with values uncommented)+const USER_CONFIG_EXAMPLE: &str = include_str!("../../../dev/config.example.toml");++/// Example project configuration file content+const PROJECT_CONFIG_EXAMPLE: &str = include_str!("../../../dev/wt.example.toml");++/// Comment out all non-comment, non-empty lines for writing to disk+pub(super) fn comment_out_config(content: &str) -> String {+ let has_trailing_newline = content.ends_with('\n');+ let result = content+ .lines()+ .map(|line| {+ // Comment out non-empty lines that aren't already comments+ if !line.is_empty() && !line.starts_with('#') {+ format!("# {}", line)+ } else {+ line.to_string()+ }+ })+ .collect::<Vec<_>>()+ .join("\n");++ if has_trailing_newline {+ format!("{}\n", result)+ } else {+ result+ }+}++/// Handle the config create command+pub fn handle_config_create(project: bool) -> anyhow::Result<()> {+ if project {+ let repo = Repository::current()?;+ let config_path = repo.current_worktree().root()?.join(".config/wt.toml");+ let user_config_exists = require_user_config_path()+ .map(|p| p.exists())+ .unwrap_or(false);+ create_config_file(+ config_path,+ PROJECT_CONFIG_EXAMPLE,+ "Project config",+ &[+ "Edit this file to configure hooks for this repository",+ "See https://worktrunk.dev/hook/ for hook documentation",+ ],+ user_config_exists,+ true, // is_project+ )+ } else {+ let project_config_exists = Repository::current()+ .and_then(|repo| repo.current_worktree().root())+ .map(|root| root.join(".config/wt.toml").exists())+ .unwrap_or(false);+ create_config_file(+ require_user_config_path()?,+ USER_CONFIG_EXAMPLE,+ "User config",+ &["Edit this file to customize worktree paths and LLM settings"],+ project_config_exists,+ false, // is_project+ )+ }+}++/// Create a config file at the specified path with the given content+fn create_config_file(+ path: PathBuf,+ content: &str,+ config_type: &str,+ success_hints: &[&str],+ other_config_exists: bool,+ is_project: bool,+) -> anyhow::Result<()> {+ // Check if file already exists+ if path.exists() {+ output::print(info_message(cformat!(+ "{config_type} already exists: <bold>{}</>",+ format_path_for_display(&path)+ )))?;++ // Build hint message based on whether the other config exists+ let hint = if other_config_exists {+ // Both configs exist+ cformat!("To view both user and project configs, run <bright-black>wt config show</>")+ } else if is_project {+ // Project config exists, no user config+ cformat!(+ "To view, run <bright-black>wt config show</>. To create a user config, run <bright-black>wt config create</>"+ )+ } else {+ // User config exists, no project config+ cformat!(+ "To view, run <bright-black>wt config show</>. To create a project config, run <bright-black>wt config create --project</>"+ )+ };+ output::print(hint_message(hint))?;+ return Ok(());+ }++ // Create parent directory if it doesn't exist+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent).context("Failed to create config directory")?;+ }++ // Write the example config with all values commented out+ let commented_config = comment_out_config(content);+ std::fs::write(&path, commented_config).context("Failed to write config file")?;++ // Success message+ output::print(success_message(cformat!(+ "Created {}: <bold>{}</>",+ config_type.to_lowercase(),+ format_path_for_display(&path)+ )))?;+ output::blank()?;+ for hint in success_hints {+ output::print(hint_message(*hint))?;+ }++ Ok(())+}diff --git a/src/commands/config/hints.rs b/src/commands/config/hints.rsnew file mode 100644index 000000000..bf4436e55--- /dev/null+++ b/src/commands/config/hints.rs@@ -0,0 +1,53 @@+//! Hint management commands.+//!+//! Commands for viewing and clearing shown hints.++use color_print::cformat;+use worktrunk::git::Repository;+use worktrunk::styling::{info_message, success_message};++use crate::output;++/// Handle the hints get command (list shown hints)+pub fn handle_hints_get() -> anyhow::Result<()> {+ let repo = Repository::current()?;+ let hints = repo.list_shown_hints();++ if hints.is_empty() {+ output::print(info_message("No hints have been shown"))?;+ } else {+ for hint in hints {+ output::stdout(&hint)?;+ }+ }++ Ok(())+}++/// Handle the hints clear command+pub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {+ let repo = Repository::current()?;++ match name {+ Some(hint_name) => {+ let msg = if repo.clear_hint(&hint_name)? {+ success_message(cformat!("Cleared hint <bold>{hint_name}</>"))+ } else {+ info_message(cformat!("Hint <bold>{hint_name}</> was not set"))+ };+ output::print(msg)?;+ }+ None => {+ let cleared = repo.clear_all_hints()?;+ let msg = if cleared == 0 {+ info_message("No hints to clear")+ } else {+ let suffix = if cleared == 1 { "" } else { "s" };+ success_message(cformat!("Cleared <bold>{cleared}</> hint{suffix}"))+ };+ output::print(msg)?;+ }+ }++ Ok(())+}diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rsnew file mode 100644index 000000000..afefc4ed0--- /dev/null+++ b/src/commands/config/mod.rs@@ -0,0 +1,234 @@+//! Configuration commands.+//!+//! Commands for managing user config, project config, state, and hints.++mod create;+mod hints;+mod show;+mod state;++// Re-export public functions+pub use create::handle_config_create;+pub use hints::{handle_hints_clear, handle_hints_get};+pub use show::handle_config_show;+pub use state::{+ handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,+ handle_state_show,+};++#[cfg(test)]+mod tests {+ use std::path::PathBuf;++ use super::create::comment_out_config;+ use super::show::{render_ci_tool_status, warn_unknown_keys};+ use super::state::{get_user_config_path, require_user_config_path, resolve_user_config_path};++ // ==================== comment_out_config tests ====================++ #[test]+ fn test_comment_out_config_basic() {+ let input = "key = \"value\"\n";+ let expected = "# key = \"value\"\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_preserves_existing_comments() {+ let input = "# This is a comment\nkey = \"value\"\n";+ let expected = "# This is a comment\n# key = \"value\"\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_preserves_empty_lines() {+ let input = "key1 = \"value\"\n\nkey2 = \"value\"\n";+ let expected = "# key1 = \"value\"\n\n# key2 = \"value\"\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_preserves_trailing_newline() {+ let with_newline = "key = \"value\"\n";+ let without_newline = "key = \"value\"";++ assert!(comment_out_config(with_newline).ends_with('\n'));+ assert!(!comment_out_config(without_newline).ends_with('\n'));+ }++ #[test]+ fn test_comment_out_config_section_headers() {+ let input = "[hooks]\ncommand = \"npm test\"\n";+ let expected = "# [hooks]\n# command = \"npm test\"\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_empty_input() {+ assert_eq!(comment_out_config(""), "");+ }++ #[test]+ fn test_comment_out_config_only_empty_lines() {+ let input = "\n\n\n";+ let expected = "\n\n\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_only_comments() {+ let input = "# comment 1\n# comment 2\n";+ let expected = "# comment 1\n# comment 2\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_mixed_content() {+ let input =+ "# Header comment\n\n[section]\nkey = \"value\"\n\n# Another comment\nkey2 = true\n";+ let expected = "# Header comment\n\n# [section]\n# key = \"value\"\n\n# Another comment\n# key2 = true\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_inline_table() {+ let input = "point = { x = 1, y = 2 }\n";+ let expected = "# point = { x = 1, y = 2 }\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_multiline_array() {+ let input = "args = [\n \"--flag\",\n \"value\"\n]\n";+ let expected = "# args = [\n# \"--flag\",\n# \"value\"\n# ]\n";+ assert_eq!(comment_out_config(input), expected);+ }++ #[test]+ fn test_comment_out_config_whitespace_only_line() {+ // Lines with only whitespace are not empty - they should NOT be commented+ // Actually, let's check what the current behavior is:+ // The function checks `!line.is_empty()` - a line with spaces is not empty+ let input = "key = 1\n \nkey2 = 2\n";+ let expected = "# key = 1\n# \n# key2 = 2\n";+ assert_eq!(comment_out_config(input), expected);+ }++ // ==================== warn_unknown_keys tests ====================++ #[test]+ fn test_warn_unknown_keys_empty() {+ let mut out = String::new();+ warn_unknown_keys(&mut out, &[]).unwrap();+ assert!(out.is_empty());+ }++ #[test]+ fn test_warn_unknown_keys_single() {+ let mut out = String::new();+ warn_unknown_keys(&mut out, &["unknown-key".to_string()]).unwrap();+ assert!(out.contains("unknown-key"));+ assert!(out.contains("Unknown key"));+ }++ #[test]+ fn test_warn_unknown_keys_multiple() {+ let mut out = String::new();+ warn_unknown_keys(&mut out, &["key1".to_string(), "key2".to_string()]).unwrap();+ assert!(out.contains("key1"));+ assert!(out.contains("key2"));+ // Should have two separate warning lines+ assert_eq!(out.matches("Unknown key").count(), 2);+ }++ // ==================== render_ci_tool_status tests ====================++ #[test]+ fn test_render_ci_tool_status_installed_authenticated() {+ let mut out = String::new();+ render_ci_tool_status(&mut out, "gh", "GitHub", true, true).unwrap();+ assert!(out.contains("gh"));+ assert!(out.contains("installed"));+ assert!(out.contains("authenticated"));+ }++ #[test]+ fn test_render_ci_tool_status_installed_not_authenticated() {+ let mut out = String::new();+ render_ci_tool_status(&mut out, "gh", "GitHub", true, false).unwrap();+ assert!(out.contains("gh"));+ assert!(out.contains("installed"));+ assert!(out.contains("not authenticated"));+ assert!(out.contains("gh auth login"));+ }++ #[test]+ fn test_render_ci_tool_status_not_installed() {+ let mut out = String::new();+ render_ci_tool_status(&mut out, "glab", "GitLab", false, false).unwrap();+ assert!(out.contains("glab"));+ assert!(out.contains("not found"));+ assert!(out.contains("GitLab"));+ assert!(out.contains("CI status unavailable"));+ }++ #[test]+ fn test_render_ci_tool_status_glab() {+ let mut out = String::new();+ render_ci_tool_status(&mut out, "glab", "GitLab", true, true).unwrap();+ assert!(out.contains("glab"));+ assert!(out.contains("installed"));+ assert!(out.contains("authenticated"));+ }++ // ==================== resolve_user_config_path tests ====================++ #[test]+ fn test_resolve_user_config_path_xdg_takes_priority() {+ let path = resolve_user_config_path(Some("/custom/xdg"), Some("/home/user"));+ assert_eq!(+ path,+ Some(PathBuf::from("/custom/xdg/worktrunk/config.toml"))+ );+ }++ #[test]+ fn test_resolve_user_config_path_home_fallback() {+ let path = resolve_user_config_path(None, Some("/home/testuser"));+ assert_eq!(+ path,+ Some(PathBuf::from(+ "/home/testuser/.config/worktrunk/config.toml"+ ))+ );+ }++ #[test]+ fn test_resolve_user_config_path_none_when_no_env() {+ let path = resolve_user_config_path(None, None);+ assert_eq!(path, None);+ }++ // ==================== get_user_config_path tests ====================++ #[test]+ fn test_get_user_config_path_returns_some() {+ // In a normal environment, get_user_config_path should return Some+ // (either from env vars or etcetera fallback)+ let path = get_user_config_path();+ assert!(path.is_some());+ let path = path.unwrap();+ assert!(path.ends_with("worktrunk/config.toml"));+ }++ // ==================== require_user_config_path tests ====================++ #[test]+ fn test_require_user_config_path_returns_ok() {+ // In a normal environment, require_user_config_path should succeed+ let result = require_user_config_path();+ assert!(result.is_ok());+ let path = result.unwrap();+ assert!(path.ends_with("worktrunk/config.toml"));+ }+}diff --git a/src/commands/config/show.rs b/src/commands/config/show.rsnew file mode 100644index 000000000..c1da0e0b8--- /dev/null+++ b/src/commands/config/show.rs@@ -0,0 +1,842 @@+//! Config show command and rendering.+//!+//! Functions for displaying user config, project config, shell status,+//! diagnostics, and runtime info.++use std::fmt::Write as _;+use std::path::PathBuf;++use anyhow::Context;+use color_print::cformat;+use worktrunk::config::{+ ProjectConfig, WorktrunkConfig, find_unknown_project_keys, find_unknown_user_keys,+};+use worktrunk::git::Repository;+use worktrunk::path::format_path_for_display;+use worktrunk::shell::{Shell, scan_for_detection_details};+use worktrunk::styling::{+ error_message, format_bash_with_gutter, format_heading, format_toml, format_with_gutter,+ hint_message, info_message, success_message, warning_message,+};++use super::state::require_user_config_path;+use crate::cli::version_str;+use crate::commands::configure_shell::{ConfigAction, scan_shell_configs};+use crate::help_pager::show_help_in_pager;+use crate::llm::test_commit_generation;+use crate::output;++/// Handle the config show command+pub fn handle_config_show(full: bool) -> anyhow::Result<()> {+ // Build the complete output as a string+ let mut show_output = String::new();++ // Render user config+ render_user_config(&mut show_output)?;+ show_output.push('\n');++ // Render project config if in a git repository+ render_project_config(&mut show_output)?;+ show_output.push('\n');++ // Render shell integration status+ render_shell_status(&mut show_output)?;++ // Run full diagnostic checks if requested (includes slow network calls)+ if full {+ show_output.push('\n');+ render_diagnostics(&mut show_output)?;+ }++ // Render runtime info at the bottom (version, binary name, shell integration status)+ show_output.push('\n');+ render_runtime_info(&mut show_output)?;++ // Display through pager (config show is always long-form output)+ if let Err(e) = show_help_in_pager(&show_output, true) {+ log::debug!("Pager invocation failed: {}", e);+ // Fall back to direct output via eprintln (matches help behavior)+ worktrunk::styling::eprintln!("{}", show_output);+ }++ Ok(())+}++// ==================== Helper Functions ====================++/// Check if Claude Code CLI is available+fn is_claude_available() -> bool {+ use worktrunk::shell_exec::Cmd;++ Cmd::new("claude")+ .arg("--version")+ .run()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++/// Check if the worktrunk plugin is installed in Claude Code+fn is_plugin_installed() -> bool {+ // Try HOME/USERPROFILE env vars first (for tests and explicit overrides), then fall back to dirs+ let home = std::env::var("HOME")+ .or_else(|_| std::env::var("USERPROFILE"))+ .ok()+ .map(PathBuf::from)+ .or_else(dirs::home_dir);++ let Some(home) = home else {+ return false;+ };++ let plugins_file = home.join(".claude/plugins/installed_plugins.json");+ let Ok(content) = std::fs::read_to_string(&plugins_file) else {+ return false;+ };++ // Look for "worktrunk@worktrunk" in the plugins object+ content.contains("\"worktrunk@worktrunk\"")+}++/// Get the git version string (e.g., "2.47.1")+fn get_git_version() -> Option<String> {+ use worktrunk::shell_exec::Cmd;++ 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).+fn check_zsh_compinit_missing() -> bool {+ use worktrunk::shell_exec::Cmd;++ // 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().+ let Ok(output) = Cmd::new("zsh")+ .args(["--no-globalrcs", "-ic", "(( $+functions[compdef] ))"])+ .env("ZSH_DISABLE_COMPFIX", "true")+ .run()+ else {+ return false; // Can't determine, don't warn+ };++ // compdef NOT found = need to warn+ !output.status.success()+}++// ==================== Render Functions ====================++/// Render OTHER section (version, Claude plugin, hyperlinks)+fn render_runtime_info(out: &mut String) -> anyhow::Result<()> {+ let cmd = crate::binary_name();+ let version = version_str();++ writeln!(out, "{}", format_heading("OTHER", None))?;++ // Version info+ writeln!(+ out,+ "{}",+ info_message(cformat!("{cmd}: <bold>{version}</>"))+ )?;+ if let Some(git_version) = get_git_version() {+ writeln!(+ out,+ "{}",+ info_message(cformat!("git: <bold>{git_version}</>"))+ )?;+ }++ // Claude Code plugin status+ let plugin_installed = is_plugin_installed();+ let claude_available = is_claude_available();++ if plugin_installed {+ writeln!(out, "{}", success_message("Claude Code plugin installed"))?;+ } else if claude_available {+ writeln!(+ out,+ "{}",+ hint_message("Claude Code plugin not installed. To install, run:")+ )?;+ let install_commands = "claude plugin marketplace add max-sixty/worktrunk\nclaude plugin install worktrunk@worktrunk";+ writeln!(out, "{}", format_bash_with_gutter(install_commands))?;+ } else {+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Claude Code plugin not installed (<bold>claude</> not found)"+ ))+ )?;+ }++ // Show hyperlink support status+ let hyperlinks_supported =+ worktrunk::styling::supports_hyperlinks(worktrunk::styling::Stream::Stderr);+ let status = if hyperlinks_supported {+ "active"+ } else {+ "inactive"+ };+ writeln!(+ out,+ "{}",+ info_message(cformat!("Hyperlinks: <bold>{status}</>"))+ )?;++ Ok(())+}++/// Run full diagnostic checks (CI tools, commit generation) and render to buffer+fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {+ use crate::commands::list::ci_status::{CiPlatform, CiToolsStatus, get_platform_for_repo};++ writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;++ // Check CI tool based on detected platform (with config override support)+ let repo = Repository::current()?;+ let project_config = repo.load_project_config().ok().flatten();+ let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());+ let platform = get_platform_for_repo(&repo, platform_override);++ match platform {+ Some(CiPlatform::GitHub) => {+ let ci_tools = CiToolsStatus::detect(None);+ render_ci_tool_status(+ out,+ "gh",+ "GitHub",+ ci_tools.gh_installed,+ ci_tools.gh_authenticated,+ )?;+ }+ Some(CiPlatform::GitLab) => {+ let ci_tools = CiToolsStatus::detect(None);+ render_ci_tool_status(+ out,+ "glab",+ "GitLab",+ ci_tools.glab_installed,+ ci_tools.glab_authenticated,+ )?;+ }+ None => {+ writeln!(+ out,+ "{}",+ hint_message("CI status requires GitHub or GitLab remote")+ )?;+ }+ }++ // Test commit generation+ let config = WorktrunkConfig::load()?;+ let commit_config = &config.commit_generation;++ if !commit_config.is_configured() {+ writeln!(out, "{}", hint_message("Commit generation not configured"))?;+ return Ok(());+ }++ let command_display = format!(+ "{}{}",+ commit_config.command.as_ref().unwrap(),+ if commit_config.args.is_empty() {+ String::new()+ } else {+ format!(" {}", commit_config.args.join(" "))+ }+ );++ match test_commit_generation(commit_config) {+ Ok(message) => {+ writeln!(+ out,+ "{}",+ success_message(cformat!(+ "Commit generation working (<bold>{command_display}</>)"+ ))+ )?;+ writeln!(out, "{}", format_with_gutter(&message, None))?;+ }+ Err(e) => {+ writeln!(+ out,+ "{}",+ error_message(cformat!(+ "Commit generation failed (<bold>{command_display}</>)"+ ))+ )?;+ writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;+ }+ }++ Ok(())+}++fn render_user_config(out: &mut String) -> anyhow::Result<()> {+ let config_path = require_user_config_path()?;++ writeln!(+ out,+ "{}",+ format_heading("USER CONFIG", Some(&format_path_for_display(&config_path)))+ )?;++ // Check if file exists+ if !config_path.exists() {+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Not found; to create one, run <bright-black>wt config create</>"+ ))+ )?;+ return Ok(());+ }++ // Read and display the file contents+ let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;++ if contents.trim().is_empty() {+ writeln!(out, "{}", hint_message("Empty file (using defaults)"))?;+ return Ok(());+ }++ // Validate config (syntax + schema) and warn if invalid+ if let Err(e) = toml::from_str::<WorktrunkConfig>(&contents) {+ // Use gutter for error details to avoid markup interpretation of user content+ writeln!(out, "{}", error_message("Invalid config"))?;+ writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;+ } else {+ // Only check for unknown keys if config is valid+ warn_unknown_keys(out, &find_unknown_user_keys(&contents))?;+ }++ // Display TOML with syntax highlighting (gutter at column 0)+ write!(out, "{}", format_toml(&contents))?;++ Ok(())+}++/// Write warnings for any unknown config keys+pub(super) fn warn_unknown_keys(out: &mut String, unknown_keys: &[String]) -> anyhow::Result<()> {+ for key in unknown_keys {+ writeln!(+ out,+ "{}",+ warning_message(cformat!("Unknown key <bold>{key}</> will be ignored"))+ )?;+ }+ Ok(())+}++fn render_project_config(out: &mut String) -> anyhow::Result<()> {+ // Try to get current repository root+ let repo_root = match Repository::current().and_then(|repo| repo.current_worktree().root()) {+ Ok(root) => root,+ Err(_) => {+ writeln!(+ out,+ "{}",+ cformat!(+ "<dim>{}</>",+ format_heading("PROJECT CONFIG", Some("Not in a git repository"))+ )+ )?;+ return Ok(());+ }+ };+ let config_path = repo_root.join(".config").join("wt.toml");++ writeln!(+ out,+ "{}",+ format_heading(+ "PROJECT CONFIG",+ Some(&format_path_for_display(&config_path))+ )+ )?;++ // Check if file exists+ if !config_path.exists() {+ writeln!(out, "{}", hint_message("Not found"))?;+ return Ok(());+ }++ // Read and display the file contents+ let contents = std::fs::read_to_string(&config_path).context("Failed to read config file")?;++ if contents.trim().is_empty() {+ writeln!(out, "{}", hint_message("Empty file"))?;+ return Ok(());+ }++ // Validate config (syntax + schema) and warn if invalid+ if let Err(e) = toml::from_str::<ProjectConfig>(&contents) {+ // Use gutter for error details to avoid markup interpretation of user content+ writeln!(out, "{}", error_message("Invalid config"))?;+ writeln!(out, "{}", format_with_gutter(&e.to_string(), None))?;+ } else {+ // Only check for unknown keys if config is valid+ warn_unknown_keys(out, &find_unknown_project_keys(&contents))?;+ }++ // Display TOML with syntax highlighting (gutter at column 0)+ write!(out, "{}", format_toml(&contents))?;++ Ok(())+}++fn render_shell_status(out: &mut String) -> anyhow::Result<()> {+ writeln!(out, "{}", format_heading("SHELL INTEGRATION", None))?;++ // Shell integration runtime status (moved from RUNTIME section)+ let shell_active = output::is_shell_integration_active();+ if shell_active {+ writeln!(out, "{}", info_message("Shell integration active"))?;+ } else {+ writeln!(out, "{}", warning_message("Shell integration not active"))?;+ // Show invocation details to help diagnose+ let invocation = crate::invocation_path();+ let is_git_subcommand = crate::is_git_subcommand();+ let mut debug_lines = vec![cformat!("Invoked as: <bold>{invocation}</>")];++ // Show actual binary path if different from invocation (helps detect wrong wt in PATH)+ if let Ok(exe_path) = std::env::current_exe() {+ let exe_display = format_path_for_display(&exe_path);+ // Only show if meaningfully different (not just ./ prefix differences)+ let invocation_canonical = std::fs::canonicalize(&invocation).ok();+ let exe_canonical = std::fs::canonicalize(&exe_path).ok();+ if invocation_canonical != exe_canonical {+ debug_lines.push(cformat!("Running from: <bold>{exe_display}</>"));+ }+ }++ // Show $SHELL to help diagnose rc file sourcing issues+ if let Ok(shell_env) = std::env::var("SHELL") {+ debug_lines.push(cformat!("$SHELL: <bold>{shell_env}</>"));+ }++ if is_git_subcommand {+ debug_lines.push("Git subcommand: yes (GIT_EXEC_PATH set)".to_string());+ }+ writeln!(out, "{}", format_with_gutter(&debug_lines.join("\n"), None))?;+ }+ writeln!(out)?;++ // Use the same detection logic as `wt config shell install`+ let cmd = crate::binary_name();+ let scan_result = match scan_shell_configs(None, true, &cmd) {+ Ok(r) => r,+ Err(e) => {+ writeln!(+ out,+ "{}",+ hint_message(format!("Could not determine shell status: {e}"))+ )?;+ return Ok(());+ }+ };++ // Get detection details to show matched lines inline+ let detection_results = scan_for_detection_details(&cmd).unwrap_or_default();++ // Check for legacy fish conf.d path (deprecated location from before #566)+ // We need this early to handle the case where fish shows "Not configured" at the+ // new location but has valid integration at the legacy location.+ let legacy_fish_conf_d = Shell::legacy_fish_conf_d_path(&cmd).ok();+ let legacy_fish_has_integration = legacy_fish_conf_d.as_ref().is_some_and(|legacy_path| {+ detection_results+ .iter()+ .any(|d| d.path == *legacy_path && !d.matched_lines.is_empty())+ });++ let mut any_not_configured = false;+ let mut has_any_unmatched = false;++ // Show configured and not-configured shells (matching `config shell install` format exactly)+ // Bash/Zsh: inline completions, show "shell extension & completions"+ // Fish: separate completion file, show "shell extension" for functions/ and "completions" for completions/+ for result in &scan_result.configured {+ let shell = result.shell;+ let path = format_path_for_display(&result.path);+ // Fish has separate completion file; bash/zsh have inline completions+ let what = if matches!(shell, Shell::Fish) {+ "shell extension"+ } else {+ "shell extension & completions"+ };++ match result.action {+ ConfigAction::AlreadyExists => {+ // Show the matched lines directly under this status+ let detection = detection_results+ .iter()+ .find(|d| d.path == result.path && !d.matched_lines.is_empty());++ // Build file:line location (clickable in terminals - use first line only)+ let location = if let Some(det) = detection {+ if let Some(first_line) = det.matched_lines.first() {+ format!("{}:{}", path, first_line.line_number)+ } else {+ path.to_string()+ }+ } else {+ path.to_string()+ };++ writeln!(+ out,+ "{}",+ info_message(cformat!(+ "Already configured {what} for <bold>{shell}</> @ {location}"+ ))+ )?;++ if let Some(det) = detection {+ for detected in &det.matched_lines {+ writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;+ }++ // Check if any matched lines use .exe suffix and warn about function name+ let uses_exe = det.matched_lines.iter().any(|m| m.content.contains(".exe"));+ if uses_exe {+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Creates shell function <bold>{cmd}</>. Aliases should use <bright-black>{cmd}</>, not <bright-black>{cmd}.exe</>"+ ))+ )?;+ }+ }++ // Check if zsh has compinit enabled (required for completions)+ if matches!(shell, Shell::Zsh) && check_zsh_compinit_missing() {+ writeln!(+ out,+ "{}",+ warning_message(+ "Completions won't work; add to ~/.zshrc before the wt line:"+ )+ )?;+ writeln!(+ out,+ "{}",+ format_with_gutter("autoload -Uz compinit && compinit", None)+ )?;+ }++ // For fish, check completions file separately+ if matches!(shell, Shell::Fish)+ && let Ok(completion_path) = shell.completion_path(&cmd)+ {+ let completion_display = format_path_for_display(&completion_path);+ if completion_path.exists() {+ writeln!(+ out,+ "{}",+ info_message(cformat!(+ "Already configured completions for <bold>{shell}</> @ {completion_display}"+ ))+ )?;+ } else {+ any_not_configured = true;+ writeln!(+ out,+ "{}",+ hint_message(format!("Not configured completions for {shell}"))+ )?;+ }+ }+ }+ ConfigAction::WouldAdd | ConfigAction::WouldCreate => {+ // For fish, check if we have valid integration at the legacy conf.d location+ if matches!(shell, Shell::Fish) && legacy_fish_has_integration {+ // Show migration hint instead of "Not configured"+ let legacy_path = legacy_fish_conf_d+ .as_ref()+ .map(|p| format_path_for_display(p))+ .unwrap_or_default();+ writeln!(+ out,+ "{}",+ info_message(cformat!(+ "Fish integration found in deprecated location @ <bold>{legacy_path}</>"+ ))+ )?;+ // Get canonical path for the migration hint+ let canonical_path = Shell::Fish+ .config_paths(&cmd)+ .ok()+ .and_then(|p| p.into_iter().next())+ .map(|p| format_path_for_display(&p))+ .unwrap_or_else(|| "~/.config/fish/functions/".to_string());+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "To migrate to <bright-black>{canonical_path}</>, run <bright-black>{cmd} config shell install fish</>"+ ))+ )?;+ } else {+ any_not_configured = true;+ writeln!(+ out,+ "{}",+ hint_message(format!("Not configured {what} for {shell}"))+ )?;+ }+ }+ _ => {} // Added/Created won't appear in dry_run mode+ }+ }++ // Show skipped (not installed) shells+ // For fish with legacy integration, show migration hint instead of "skipped"+ for (shell, path) in &scan_result.skipped {+ if matches!(shell, Shell::Fish) && legacy_fish_has_integration {+ // Show migration hint for legacy fish location+ let legacy_path = legacy_fish_conf_d+ .as_ref()+ .map(|p| format_path_for_display(p))+ .unwrap_or_default();+ let canonical_path = Shell::Fish+ .config_paths(&cmd)+ .ok()+ .and_then(|p| p.into_iter().next())+ .map(|p| format_path_for_display(&p))+ .unwrap_or_else(|| "~/.config/fish/functions/".to_string());+ writeln!(+ out,+ "{}",+ info_message(cformat!(+ "Fish integration found in deprecated location @ <bold>{legacy_path}</>"+ ))+ )?;+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "To migrate to <bright-black>{canonical_path}</>, run <bright-black>{cmd} config shell install fish</>"+ ))+ )?;+ continue;+ }+ let path = format_path_for_display(path);+ writeln!(+ out,+ "{}",+ info_message(cformat!("<dim>Skipped {shell}; {path} not found</>"))+ )?;+ }++ // Summary hint when shells need configuration+ if any_not_configured {+ writeln!(out)?;+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "To configure, run <bright-black>{cmd} config shell install</>"+ ))+ )?;+ }++ // Show potential false negatives (lines containing cmd but not detected)+ // Skip files that have valid integration detected (matched_lines) - those are fine,+ // and the other lines containing cmd are just part of the integration script.+ for detection in &detection_results {+ if !detection.unmatched_candidates.is_empty() && detection.matched_lines.is_empty() {+ has_any_unmatched = true;+ let path = format_path_for_display(&detection.path);++ // Build file:line location (clickable in terminals - use first line only)+ let location = if let Some(first) = detection.unmatched_candidates.first() {+ format!("{}:{}", path, first.line_number)+ } else {+ path.to_string()+ };+ writeln!(+ out,+ "{}",+ warning_message(cformat!(+ "Found <bold>{cmd}</> in <bold>{location}</> but not detected as integration:"+ ))+ )?;+ for detected in &detection.unmatched_candidates {+ writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;+ }++ // If any unmatched lines contain .exe, explain the function name issue+ let uses_exe = detection+ .unmatched_candidates+ .iter()+ .any(|m| m.content.contains(".exe"));+ if uses_exe {+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Note: <bold>{cmd}.exe</> creates shell function <bold>{cmd}</>. \+ Aliases should use <bright-black>{cmd}</>, not <bright-black>{cmd}.exe</>"+ ))+ )?;+ }+ }+ }++ // Show aliases that bypass shell integration (Issue #348)+ for detection in &detection_results {+ for alias in &detection.bypass_aliases {+ let path = format_path_for_display(&detection.path);+ let location = format!("{}:{}", path, alias.line_number);+ writeln!(+ out,+ "{}",+ warning_message(cformat!(+ "Alias <bold>{}</> bypasses shell integration — won't auto-cd",+ alias.alias_name+ ))+ )?;+ writeln!(out, "{}", format_bash_with_gutter(alias.content.trim()))?;+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "Change to <bright-black>alias {}=\"{cmd}\"</> @ {location}",+ alias.alias_name+ ))+ )?;+ }+ }++ // Check if any shell has config already (eval line present)+ let has_any_configured = scan_result+ .configured+ .iter()+ .any(|r| matches!(r.action, ConfigAction::AlreadyExists));++ // If we have unmatched candidates but no configured shells, suggest raising an issue+ if has_any_unmatched && !has_any_configured {+ let unmatched_summary: Vec<_> = detection_results+ .iter()+ .filter(|r| !r.unmatched_candidates.is_empty())+ .flat_map(|r| {+ r.unmatched_candidates+ .iter()+ .map(|d| d.content.trim().to_string())+ })+ .collect();+ let body = format!(+ "Shell integration not detected despite config containing `{cmd}`.\n\n\+ **Unmatched lines:**\n```\n{}\n```\n\n\+ **Expected behavior:** These lines should be detected as shell integration.",+ unmatched_summary.join("\n")+ );+ let issue_url = format!(+ "https://github.com/max-sixty/worktrunk/issues/new?title={}&body={}",+ urlencoding::encode("Shell integration detection false negative"),+ urlencoding::encode(&body)+ );++ // Quote a short version of the unmatched content in the hint+ let quoted = if unmatched_summary.len() == 1 {+ format!("`{}`", unmatched_summary[0])+ } else {+ format!(+ "`{}` (and {} more)",+ unmatched_summary[0],+ unmatched_summary.len() - 1+ )+ };+ writeln!(+ out,+ "{}",+ hint_message(format!(+ "If {quoted} is shell integration, report a false negative: {issue_url}"+ ))+ )?;+ }++ Ok(())+}++pub(super) fn render_ci_tool_status(+ out: &mut String,+ tool: &str,+ platform: &str,+ installed: bool,+ authenticated: bool,+) -> anyhow::Result<()> {+ if installed {+ if authenticated {+ writeln!(+ out,+ "{}",+ success_message(cformat!("<bold>{tool}</> installed & authenticated"))+ )?;+ } else {+ writeln!(+ out,+ "{}",+ warning_message(cformat!(+ "<bold>{tool}</> installed but not authenticated; run <bold>{tool} auth login</>"+ ))+ )?;+ }+ } else {+ writeln!(+ out,+ "{}",+ hint_message(cformat!(+ "<bold>{tool}</> not found ({platform} CI status unavailable)"+ ))+ )?;+ }+ Ok(())+}++#[cfg(test)]+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 = get_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('.'));+ }+}diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsnew file mode 100644index 000000000..8eb08a0c6--- /dev/null+++ b/src/commands/config/state.rs@@ -0,0 +1,729 @@+//! State management commands.+//!+//! Commands for getting, setting, and clearing stored state like default branch,+//! previous branch, CI status, markers, and logs.++use std::fmt::Write as _;+use std::path::PathBuf;++use color_print::cformat;+use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};+use worktrunk::git::Repository;+use worktrunk::path::format_path_for_display;+use worktrunk::styling::{+ format_heading, format_with_gutter, info_message, success_message, warning_message,+};+use worktrunk::utils::get_now;++use super::super::list::ci_status::CachedCiStatus;+use crate::display::format_relative_time_short;+use crate::help_pager::show_help_in_pager;+use crate::output;++// ==================== Path Helpers ====================++/// Core logic for determining user config path from env var values+pub(super) fn resolve_user_config_path(+ xdg_config_home: Option<&str>,+ home: Option<&str>,+) -> Option<PathBuf> {+ // Respect XDG_CONFIG_HOME environment variable (Linux)+ if let Some(xdg_config) = xdg_config_home {+ let config_path = PathBuf::from(xdg_config);+ return Some(config_path.join("worktrunk").join("config.toml"));+ }++ // Respect HOME environment variable (fallback)+ if let Some(home) = home {+ let home_path = PathBuf::from(home);+ return Some(+ home_path+ .join(".config")+ .join("worktrunk")+ .join("config.toml"),+ );+ }++ None+}++pub(super) fn get_user_config_path() -> Option<PathBuf> {+ // Try env vars first, then fall back to etcetera+ resolve_user_config_path(+ std::env::var("XDG_CONFIG_HOME").ok().as_deref(),+ std::env::var("HOME").ok().as_deref(),+ )+ .or_else(|| {+ let strategy = choose_base_strategy().ok()?;+ Some(strategy.config_dir().join("worktrunk").join("config.toml"))+ })+}++pub fn require_user_config_path() -> anyhow::Result<PathBuf> {+ get_user_config_path().ok_or_else(|| {+ anyhow::anyhow!(+ "Cannot determine config directory. Set $HOME or $XDG_CONFIG_HOME environment variable"+ )+ })+}++// ==================== Log Management ====================++/// Clear all log files from the wt-logs directory+fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {+ let log_dir = repo.wt_logs_dir();++ if !log_dir.exists() {+ return Ok(0);+ }++ let mut cleared = 0;+ for entry in std::fs::read_dir(&log_dir)? {+ let entry = entry?;+ let path = entry.path();+ if path.is_file() && path.extension().is_some_and(|ext| ext == "log") {+ std::fs::remove_file(&path)?;+ cleared += 1;+ }+ }++ // Remove the directory if empty+ if std::fs::read_dir(&log_dir)?.next().is_none() {+ let _ = std::fs::remove_dir(&log_dir);+ }++ Ok(cleared)+}++/// Render the LOG FILES section (heading + table or "(none)") into the output buffer+pub(super) fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {+ let log_dir = repo.wt_logs_dir();+ let log_dir_display = format_path_for_display(&log_dir);++ writeln!(+ out,+ "{}",+ format_heading("LOG FILES", Some(&format!("@ {log_dir_display}")))+ )?;++ if !log_dir.exists() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ return Ok(());+ }++ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?+ .filter_map(|e| e.ok())+ .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))+ .collect();++ if entries.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ return Ok(());+ }++ // Sort by modification time (newest first), then by name for stability+ entries.sort_by(|a, b| {+ let a_time = a.metadata().and_then(|m| m.modified()).ok();+ let b_time = b.metadata().and_then(|m| m.modified()).ok();+ b_time+ .cmp(&a_time)+ .then_with(|| a.file_name().cmp(&b.file_name()))+ });++ // Build table+ let mut table = String::from("| File | Size | Age |\n");+ table.push_str("|------|------|-----|\n");++ for entry in entries {+ let path = entry.path();+ let name = path.file_name().unwrap_or_default().to_string_lossy();+ let meta = entry.metadata().ok();++ let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);+ let size_str = if size < 1024 {+ format!("{size}B")+ } else {+ format!("{}K", size / 1024)+ };++ let age = meta+ .and_then(|m| m.modified().ok())+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| format_relative_time_short(d.as_secs() as i64))+ .unwrap_or_else(|| "?".to_string());++ table.push_str(&format!("| {name} | {size_str} | {age} |\n"));+ }++ let rendered = crate::md_help::render_markdown_table(&table);+ write!(out, "{}", rendered.trim_end())?;++ Ok(())+}++// ==================== State Get/Set/Clear Commands ====================++/// Handle the state get command+pub fn handle_state_get(key: &str, branch: Option<String>) -> anyhow::Result<()> {+ use super::super::list::ci_status::PrStatus;++ let repo = Repository::current()?;++ match key {+ "default-branch" => {+ let branch_name = repo.default_branch().ok_or_else(|| {+ anyhow::anyhow!(cformat!(+ "Cannot determine default branch. To configure, run <bold>wt config state default-branch set BRANCH</>"+ ))+ })?;+ output::stdout(branch_name)?;+ }+ "previous-branch" => match repo.get_switch_previous() {+ Some(prev) => output::stdout(prev)?,+ None => output::stdout("")?,+ },+ "marker" => {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("get marker for current branch")?,+ };+ match repo.branch_keyed_marker(&branch_name) {+ Some(marker) => output::stdout(marker)?,+ None => output::stdout("")?,+ }+ }+ "ci-status" => {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("get ci-status for current branch")?,+ };++ // Get the HEAD commit for this branch+ let head = repo+ .run_command(&["rev-parse", &branch_name])+ .map(|s| s.trim().to_string())+ .unwrap_or_default();++ if head.is_empty() {+ return Err(worktrunk::git::GitError::InvalidReference {+ reference: branch_name,+ }+ .into());+ }++ let has_upstream = repo.upstream_branch(&branch_name).ok().flatten().is_some();+ let ci_status = PrStatus::detect(&repo, &branch_name, &head, has_upstream)+ .map_or(super::super::list::ci_status::CiStatus::NoCI, |s| {+ s.ci_status+ });+ let status_str: &'static str = ci_status.into();+ output::stdout(status_str)?;+ }+ // TODO: Consider simplifying to just print the path and let users run `ls -al` themselves+ "logs" => {+ let mut out = String::new();+ render_log_files(&mut out, &repo)?;++ // Display through pager (fall back to stderr if pager unavailable)+ if show_help_in_pager(&out, true).is_err() {+ worktrunk::styling::eprintln!("{}", out);+ }+ }+ _ => {+ anyhow::bail!(+ "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"+ )+ }+ }++ Ok(())+}++/// Handle the state set command+pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anyhow::Result<()> {+ let repo = Repository::current()?;++ match key {+ "default-branch" => {+ // Warn if the branch doesn't exist locally+ if !repo.local_branch_exists(&value)? {+ output::print(warning_message(cformat!(+ "Branch <bold>{value}</> does not exist locally"+ )))?;+ }+ repo.set_default_branch(&value)?;+ output::print(success_message(cformat!(+ "Set default branch to <bold>{value}</>"+ )))?;+ }+ "previous-branch" => {+ repo.record_switch_previous(Some(&value))?;+ output::print(success_message(cformat!(+ "Set previous branch to <bold>{value}</>"+ )))?;+ }+ "marker" => {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("set marker for current branch")?,+ };++ // Store as JSON with timestamp+ let now = get_now();+ let json = serde_json::json!({+ "marker": value,+ "set_at": now+ });++ let config_key = format!("worktrunk.state.{branch_name}.marker");+ repo.run_command(&["config", &config_key, &json.to_string()])?;++ output::print(success_message(cformat!(+ "Set marker for <bold>{branch_name}</> to <bold>{value}</>"+ )))?;+ }+ _ => {+ anyhow::bail!("Unknown key: {key}. Valid keys: default-branch, previous-branch, marker")+ }+ }++ Ok(())+}++/// Handle the state clear command+pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhow::Result<()> {+ let repo = Repository::current()?;++ match key {+ "default-branch" => {+ if repo.clear_default_branch_cache()? {+ output::print(success_message("Cleared default branch cache"))?;+ } else {+ output::print(info_message("No default branch cache to clear"))?;+ }+ }+ "previous-branch" => {+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {+ output::print(success_message("Cleared previous branch"))?;+ } else {+ output::print(info_message("No previous branch to clear"))?;+ }+ }+ "ci-status" => {+ if all {+ let cleared = CachedCiStatus::clear_all(&repo);+ if cleared == 0 {+ output::print(info_message("No CI cache entries to clear"))?;+ } else {+ output::print(success_message(cformat!(+ "Cleared <bold>{cleared}</> CI cache entr{}",+ if cleared == 1 { "y" } else { "ies" }+ )))?;+ }+ } else {+ // Clear CI status for specific branch+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("clear ci-status for current branch")?,+ };+ let config_key = format!("worktrunk.state.{branch_name}.ci-status");+ if repo+ .run_command(&["config", "--unset", &config_key])+ .is_ok()+ {+ output::print(success_message(cformat!(+ "Cleared CI cache for <bold>{branch_name}</>"+ )))?;+ } else {+ output::print(info_message(cformat!(+ "No CI cache for <bold>{branch_name}</>"+ )))?;+ }+ }+ }+ "marker" => {+ if all {+ let output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])+ .unwrap_or_default();++ let mut cleared_count = 0;+ for line in output.lines() {+ if let Some(config_key) = line.split_whitespace().next() {+ repo.run_command(&["config", "--unset", config_key])?;+ cleared_count += 1;+ }+ }++ if cleared_count == 0 {+ output::print(info_message("No markers to clear"))?;+ } else {+ output::print(success_message(cformat!(+ "Cleared <bold>{cleared_count}</> marker{}",+ if cleared_count == 1 { "" } else { "s" }+ )))?;+ }+ } else {+ let branch_name = match branch {+ Some(b) => b,+ None => repo.require_current_branch("clear marker for current branch")?,+ };++ let config_key = format!("worktrunk.state.{branch_name}.marker");+ if repo+ .run_command(&["config", "--unset", &config_key])+ .is_ok()+ {+ output::print(success_message(cformat!(+ "Cleared marker for <bold>{branch_name}</>"+ )))?;+ } else {+ output::print(info_message(cformat!(+ "No marker set for <bold>{branch_name}</>"+ )))?;+ }+ }+ }+ "logs" => {+ let cleared = clear_logs(&repo)?;+ if cleared == 0 {+ output::print(info_message("No logs to clear"))?;+ } else {+ output::print(success_message(cformat!(+ "Cleared <bold>{cleared}</> log file{}",+ if cleared == 1 { "" } else { "s" }+ )))?;+ }+ }+ _ => {+ anyhow::bail!(+ "Unknown key: {key}. Valid keys: default-branch, previous-branch, ci-status, marker, logs"+ )+ }+ }++ Ok(())+}++/// Handle the state clear all command+pub fn handle_state_clear_all() -> anyhow::Result<()> {+ let repo = Repository::current()?;+ let mut cleared_any = false;++ // Clear default branch cache+ if matches!(repo.clear_default_branch_cache(), Ok(true)) {+ cleared_any = true;+ }++ // Clear previous branch+ if repo+ .run_command(&["config", "--unset", "worktrunk.history"])+ .is_ok()+ {+ cleared_any = true;+ }++ // Clear all markers+ let markers_output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])+ .unwrap_or_default();+ for line in markers_output.lines() {+ if let Some(config_key) = line.split_whitespace().next() {+ let _ = repo.run_command(&["config", "--unset", config_key]);+ cleared_any = true;+ }+ }++ // Clear all CI status cache+ let ci_cleared = CachedCiStatus::clear_all(&repo);+ if ci_cleared > 0 {+ cleared_any = true;+ }++ // Clear all logs+ let logs_cleared = clear_logs(&repo)?;+ if logs_cleared > 0 {+ cleared_any = true;+ }++ // Clear all hints+ let hints_cleared = repo.clear_all_hints()?;+ if hints_cleared > 0 {+ cleared_any = true;+ }++ if cleared_any {+ output::print(success_message("Cleared all stored state"))?;+ } else {+ output::print(info_message("No stored state to clear"))?;+ }++ Ok(())+}++// ==================== State Show Commands ====================++/// Handle the state get command (shows all state)+pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()> {+ use crate::cli::OutputFormat;++ let repo = Repository::current()?;++ match format {+ OutputFormat::Json => handle_state_show_json(&repo),+ OutputFormat::Table => handle_state_show_table(&repo),+ }+}++/// Output state as JSON+fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {+ // Get default branch+ let default_branch = repo.default_branch();++ // Get previous branch+ let previous_branch = repo.get_switch_previous();++ // Get markers+ let markers: Vec<serde_json::Value> = get_all_markers(repo)+ .into_iter()+ .map(|m| {+ serde_json::json!({+ "branch": m.branch,+ "marker": m.marker,+ "set_at": if m.set_at > 0 { Some(m.set_at) } else { None }+ })+ })+ .collect();++ // Get CI status cache+ let mut ci_entries = CachedCiStatus::list_all(repo);+ ci_entries.sort_by(|a, b| {+ b.1.checked_at+ .cmp(&a.1.checked_at)+ .then_with(|| a.0.cmp(&b.0))+ });+ let ci_status: Vec<serde_json::Value> = ci_entries+ .into_iter()+ .map(|(branch, cached)| {+ let status = cached+ .status+ .as_ref()+ .map(|s| -> &'static str { s.ci_status.into() });+ serde_json::json!({+ "branch": branch,+ "status": status,+ "checked_at": cached.checked_at,+ "head": cached.head+ })+ })+ .collect();++ // Get log files+ let log_dir = repo.wt_logs_dir();+ let logs: Vec<serde_json::Value> = if log_dir.exists() {+ let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?+ .filter_map(|e| e.ok())+ .filter(|e| e.path().is_file() && e.path().extension().is_some_and(|ext| ext == "log"))+ .collect();++ entries.sort_by(|a, b| {+ let a_time = a.metadata().and_then(|m| m.modified()).ok();+ let b_time = b.metadata().and_then(|m| m.modified()).ok();+ b_time.cmp(&a_time)+ });++ entries+ .into_iter()+ .map(|entry| {+ let path = entry.path();+ let name = path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .to_string();+ let meta = entry.metadata().ok();+ let size = meta.as_ref().map(|m| m.len()).unwrap_or(0);+ let modified = meta+ .and_then(|m| m.modified().ok())+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_secs());++ serde_json::json!({+ "file": name,+ "size": size,+ "modified_at": modified+ })+ })+ .collect()+ } else {+ vec![]+ };++ // Get hints+ let hints = repo.list_shown_hints();++ let output = serde_json::json!({+ "default_branch": default_branch,+ "previous_branch": previous_branch,+ "markers": markers,+ "ci_status": ci_status,+ "logs": logs,+ "hints": hints+ });++ output::stdout(serde_json::to_string_pretty(&output)?)?;+ Ok(())+}++/// Output state as human-readable table+fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {+ // Build complete output as a string+ let mut out = String::new();++ // Show default branch cache+ writeln!(out, "{}", format_heading("DEFAULT BRANCH", None))?;+ match repo.default_branch() {+ Some(branch) => writeln!(out, "{}", format_with_gutter(&branch, None))?,+ None => writeln!(out, "{}", format_with_gutter("(not available)", None))?,+ }+ writeln!(out)?;++ // Show previous branch (for `wt switch -`)+ writeln!(out, "{}", format_heading("PREVIOUS BRANCH", None))?;+ match repo.get_switch_previous() {+ Some(prev) => writeln!(out, "{}", format_with_gutter(&prev, None))?,+ None => writeln!(out, "{}", format_with_gutter("(none)", None))?,+ }+ writeln!(out)?;++ // Show branch markers+ writeln!(out, "{}", format_heading("BRANCH MARKERS", None))?;+ let markers = get_all_markers(repo);+ if markers.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ let mut table = String::from("| Branch | Marker | Age |\n");+ table.push_str("|--------|--------|-----|\n");+ for entry in markers {+ let age = format_relative_time_short(entry.set_at as i64);+ table.push_str(&format!(+ "| {} | {} | {} |\n",+ entry.branch, entry.marker, age+ ));+ }+ let rendered = crate::md_help::render_markdown_table(&table);+ writeln!(out, "{}", rendered.trim_end())?;+ }+ writeln!(out)?;++ // Show CI status cache+ writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;+ let mut entries = CachedCiStatus::list_all(repo);+ // Sort by age (most recent first), then by branch name for ties+ entries.sort_by(|a, b| {+ b.1.checked_at+ .cmp(&a.1.checked_at)+ .then_with(|| a.0.cmp(&b.0))+ });+ if entries.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ // Build markdown table+ let mut table = String::from("| Branch | Status | Age | Head |\n");+ table.push_str("|--------|--------|-----|------|\n");+ for (branch, cached) in entries {+ let status = match &cached.status {+ Some(pr_status) => {+ let status: &'static str = pr_status.ci_status.into();+ status.to_string()+ }+ None => "none".to_string(),+ };+ let age = format_relative_time_short(cached.checked_at as i64);+ let head: String = cached.head.chars().take(8).collect();++ table.push_str(&format!("| {branch} | {status} | {age} | {head} |\n"));+ }++ let rendered = crate::md_help::render_markdown_table(&table);+ writeln!(out, "{}", rendered.trim_end())?;+ }+ writeln!(out)?;++ // Show hints+ writeln!(out, "{}", format_heading("HINTS", None))?;+ let hints = repo.list_shown_hints();+ if hints.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ for hint in hints {+ writeln!(out, "{}", format_with_gutter(&hint, None))?;+ }+ }+ writeln!(out)?;++ // Show log files+ render_log_files(&mut out, repo)?;++ // Display through pager (fall back to stderr if pager unavailable)+ if let Err(e) = show_help_in_pager(&out, true) {+ log::debug!("Pager invocation failed: {}", e);+ // Fall back to direct output via eprintln (matches help behavior)+ worktrunk::styling::eprintln!("{}", out);+ }++ Ok(())+}++// ==================== Marker Helpers ====================++/// Marker entry with branch, text, and timestamp+pub(super) struct MarkerEntry {+ pub branch: String,+ pub marker: String,+ pub set_at: u64,+}++/// Get all branch markers from git config with timestamps+pub(super) fn get_all_markers(repo: &Repository) -> Vec<MarkerEntry> {+ let output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.state\..+\.marker$"])+ .unwrap_or_default();++ let mut markers = Vec::new();+ for line in output.lines() {+ // Format: "worktrunk.state.<branch>.marker json_value"+ let Some((key, value)) = line.split_once(' ') else {+ continue;+ };+ let Some(branch) = key+ .strip_prefix("worktrunk.state.")+ .and_then(|s| s.strip_suffix(".marker"))+ else {+ continue;+ };+ let Ok(parsed) = serde_json::from_str::<serde_json::Value>(value) else {+ continue; // Skip invalid JSON+ };+ let Some(marker) = parsed.get("marker").and_then(|v| v.as_str()) else {+ continue; // Skip if "marker" field is missing+ };+ let set_at = parsed.get("set_at").and_then(|v| v.as_u64()).unwrap_or(0);+ markers.push(MarkerEntry {+ branch: branch.to_string(),+ marker: marker.to_string(),+ set_at,+ });+ }++ // Sort by age (most recent first), then by branch name for ties+ markers.sort_by(|a, b| {+ b.set_at+ .cmp(&a.set_at)+ .then_with(|| a.branch.cmp(&b.branch))+ });+ markers+}diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsdeleted file mode 100644index 3a74e9cc2..000000000--- a/src/commands/list/ci_status.rs+++ /dev/null@@ -1,1710 +0,0 @@-use serde::{Deserialize, Serialize, de::DeserializeOwned};-use std::fs;-use std::path::{Path, PathBuf};-use worktrunk::git::{Repository, parse_owner_repo, parse_remote_owner};-use worktrunk::path::sanitize_for_filename;-use worktrunk::shell_exec::Cmd;-use worktrunk::utils::get_now;--/// CI platform detected from project config override or remote URL.-///-/// Platform is determined by:-/// 1. Project config `[ci] platform = "github" | "gitlab"` (takes precedence)-/// 2. Remote URL detection (searches for "github" or "gitlab" in URL)-#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]-#[strum(serialize_all = "lowercase")]-pub enum CiPlatform {- GitHub,- GitLab,-}--/// Detect the CI platform from a remote URL by searching for "github" or "gitlab".-fn detect_platform_from_url(url: &str) -> Option<CiPlatform> {- let url_lower = url.to_ascii_lowercase();- if url_lower.contains("github") {- Some(CiPlatform::GitHub)- } else if url_lower.contains("gitlab") {- Some(CiPlatform::GitLab)- } else {- None- }-}--/// Get the CI platform for a repository.-///-/// If `platform_override` is provided (from project config `[ci] platform`),-/// uses that value directly. Otherwise, detects platform from the primary-/// remote URL.-pub fn get_platform_for_repo(- repo: &Repository,- platform_override: Option<&str>,-) -> Option<CiPlatform> {- // Config override takes precedence- if let Some(platform_str) = platform_override {- if let Ok(platform) = platform_str.parse::<CiPlatform>() {- log::debug!("Using CI platform from config override: {}", platform);- return Some(platform);- }- log::warn!(- "Invalid CI platform in config: '{}'. Expected 'github' or 'gitlab'.",- platform_str- );- }-- // Fall back to URL detection- let url = repo.primary_remote_url()?;- detect_platform_from_url(&url)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_detect_platform_from_url() {- // GitHub - various URL formats- assert_eq!(- detect_platform_from_url("https://github.com/owner/repo.git"),- Some(CiPlatform::GitHub)- );- assert_eq!(- detect_platform_from_url("[email protected]:owner/repo.git"),- Some(CiPlatform::GitHub)- );- assert_eq!(- detect_platform_from_url("ssh://[email protected]/owner/repo.git"),- Some(CiPlatform::GitHub)- );-- // GitHub Enterprise- assert_eq!(- detect_platform_from_url("https://github.mycompany.com/owner/repo.git"),- Some(CiPlatform::GitHub)- );-- // GitLab - various URL formats- assert_eq!(- detect_platform_from_url("https://gitlab.com/owner/repo.git"),- Some(CiPlatform::GitLab)- );- assert_eq!(- detect_platform_from_url("[email protected]:owner/repo.git"),- Some(CiPlatform::GitLab)- );-- // Self-hosted GitLab- assert_eq!(- detect_platform_from_url("https://gitlab.example.com/owner/repo.git"),- Some(CiPlatform::GitLab)- );-- // Legacy schemes (http://, git://) - common on self-hosted installations- assert_eq!(- detect_platform_from_url("http://github.com/owner/repo.git"),- Some(CiPlatform::GitHub)- );- assert_eq!(- detect_platform_from_url("git://github.com/owner/repo.git"),- Some(CiPlatform::GitHub)- );- assert_eq!(- detect_platform_from_url("http://gitlab.example.com/owner/repo.git"),- Some(CiPlatform::GitLab)- );- assert_eq!(- detect_platform_from_url("git://gitlab.mycompany.com/owner/repo.git"),- Some(CiPlatform::GitLab)- );-- // Unknown platforms- assert_eq!(- detect_platform_from_url("https://bitbucket.org/owner/repo.git"),- None- );- assert_eq!(- detect_platform_from_url("https://codeberg.org/owner/repo.git"),- None- );- }-- #[test]- fn test_platform_override_github() {- // Config override should take precedence over URL detection- assert_eq!(- "github".parse::<CiPlatform>().ok(),- Some(CiPlatform::GitHub)- );- }-- #[test]- fn test_platform_override_gitlab() {- // Config override should take precedence over URL detection- assert_eq!(- "gitlab".parse::<CiPlatform>().ok(),- Some(CiPlatform::GitLab)- );- }-- #[test]- fn test_platform_override_invalid() {- // Invalid platform strings should not parse- assert!("invalid".parse::<CiPlatform>().is_err());- assert!("GITHUB".parse::<CiPlatform>().is_err()); // Case-sensitive- assert!("GitHub".parse::<CiPlatform>().is_err()); // Case-sensitive- }-- #[test]- fn test_ttl_jitter_range_and_determinism() {- use std::path::Path;-- // Check range: TTL should be in [30, 60)- let paths = [- "/tmp/repo1",- "/tmp/repo2",- "/workspace/project",- "/home/user/code",- ];- for path in paths {- let ttl = CachedCiStatus::ttl_for_repo(Path::new(path));- assert!(- (30..60).contains(&ttl),- "TTL {} for path {} should be in [30, 60)",- ttl,- path- );- }-- // Check determinism: same path should always produce same TTL- let path = Path::new("/some/consistent/path");- let ttl1 = CachedCiStatus::ttl_for_repo(path);- let ttl2 = CachedCiStatus::ttl_for_repo(path);- assert_eq!(ttl1, ttl2, "Same path should produce same TTL");-- // Check diversity: different paths should likely produce different TTLs- let diverse_paths: Vec<_> = (0..20).map(|i| format!("/repo/path{}", i)).collect();- let ttls: std::collections::HashSet<_> = diverse_paths- .iter()- .map(|p| CachedCiStatus::ttl_for_repo(Path::new(p)))- .collect();- // With 20 paths mapping to 30 possible values, we expect good diversity- assert!(- ttls.len() >= 10,- "Expected diverse TTLs across paths, got {} unique values",- ttls.len()- );- }-- #[test]- fn test_is_retriable_error() {- // Rate limit errors- assert!(is_retriable_error("API rate limit exceeded"));- assert!(is_retriable_error("rate limit exceeded for requests"));- assert!(is_retriable_error("Error 403: forbidden"));- assert!(is_retriable_error("HTTP 429 Too Many Requests"));-- // Network errors- assert!(is_retriable_error("connection timed out"));- assert!(is_retriable_error("network error"));- assert!(is_retriable_error("timeout waiting for response"));-- // Case insensitivity- assert!(is_retriable_error("RATE LIMIT"));- assert!(is_retriable_error("Connection Reset"));-- // Non-retriable errors- assert!(!is_retriable_error("branch not found"));- assert!(!is_retriable_error("invalid credentials"));- assert!(!is_retriable_error("permission denied"));- assert!(!is_retriable_error(""));- }-- #[test]- fn test_ci_status_color() {- use anstyle::AnsiColor;-- assert_eq!(CiStatus::Passed.color(), AnsiColor::Green);- assert_eq!(CiStatus::Running.color(), AnsiColor::Blue);- assert_eq!(CiStatus::Failed.color(), AnsiColor::Red);- assert_eq!(CiStatus::Conflicts.color(), AnsiColor::Yellow);- assert_eq!(CiStatus::Error.color(), AnsiColor::Yellow);- assert_eq!(CiStatus::NoCI.color(), AnsiColor::BrightBlack);- }-- #[test]- fn test_pr_status_indicator() {- let pr_passed = PrStatus {- ci_status: CiStatus::Passed,- source: CiSource::PullRequest,- is_stale: false,- url: None,- };- assert_eq!(pr_passed.indicator(), "●");-- let branch_running = PrStatus {- ci_status: CiStatus::Running,- source: CiSource::Branch,- is_stale: false,- url: None,- };- assert_eq!(branch_running.indicator(), "●");-- let error_status = PrStatus {- ci_status: CiStatus::Error,- source: CiSource::PullRequest,- is_stale: false,- url: None,- };- assert_eq!(error_status.indicator(), "⚠");- }-- #[test]- fn test_format_indicator_with_url() {- let pr_with_url = PrStatus {- ci_status: CiStatus::Passed,- source: CiSource::PullRequest,- is_stale: false,- url: Some("https://github.com/owner/repo/pull/123".to_string()),- };-- // Call format_indicator(true) directly- let formatted = pr_with_url.format_indicator(true);- // Should contain OSC 8 hyperlink escape sequences- assert!(formatted.contains("\x1b]8;;"));- assert!(formatted.contains("https://github.com/owner/repo/pull/123"));- assert!(formatted.contains("●"));- }-- #[test]- fn test_format_indicator_without_url() {- let pr_no_url = PrStatus {- ci_status: CiStatus::Passed,- source: CiSource::PullRequest,- is_stale: false,- url: None,- };-- // Call format_indicator(true) directly- let formatted = pr_no_url.format_indicator(true);- // Should NOT contain OSC 8 hyperlink- assert!(- !formatted.contains("\x1b]8;;"),- "Should not contain OSC 8 sequences"- );- assert!(formatted.contains("●"));- }-- #[test]- fn test_format_indicator_skips_link() {- // When include_link=false, should not include OSC 8 even when URL is present- let pr_with_url = PrStatus {- ci_status: CiStatus::Passed,- source: CiSource::PullRequest,- is_stale: false,- url: Some("https://github.com/owner/repo/pull/123".to_string()),- };-- let with_link = pr_with_url.format_indicator(true);- let without_link = pr_with_url.format_indicator(false);-- // With link should contain OSC 8- assert!(- with_link.contains("\x1b]8;;"),- "include_link=true should contain OSC 8"- );-- // Without link should NOT contain OSC 8- assert!(- !without_link.contains("\x1b]8;;"),- "include_link=false should not contain OSC 8"- );-- // Both should contain the indicator- assert!(with_link.contains("●"), "Should contain indicator");- assert!(without_link.contains("●"), "Should contain indicator");- }-- #[test]- fn test_pr_status_error_constructor() {- let error = PrStatus::error();- assert_eq!(error.ci_status, CiStatus::Error);- assert_eq!(error.source, CiSource::Branch);- assert!(!error.is_stale);- assert!(error.url.is_none());- }-- #[test]- fn test_github_pr_info_ci_status() {- // No checks = NoCI- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: None,- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::NoCI);-- // Empty checks = NoCI- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::NoCI);-- // CheckRun pending states- for status in ["IN_PROGRESS", "QUEUED", "PENDING", "EXPECTED"] {- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![GitHubCheck {- status: Some(status.into()),- conclusion: None,- state: None,- }]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::Running, "status={status}");- }-- // StatusContext pending- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![GitHubCheck {- status: None,- conclusion: None,- state: Some("PENDING".into()),- }]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::Running);-- // CheckRun failures- for conclusion in ["FAILURE", "ERROR", "CANCELLED"] {- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![GitHubCheck {- status: Some("COMPLETED".into()),- conclusion: Some(conclusion.into()),- state: None,- }]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::Failed, "conclusion={conclusion}");- }-- // StatusContext failures- for state in ["FAILURE", "ERROR"] {- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![GitHubCheck {- status: None,- conclusion: None,- state: Some(state.into()),- }]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::Failed, "state={state}");- }-- // Success- let pr = GitHubPrInfo {- head_ref_oid: None,- merge_state_status: None,- status_check_rollup: Some(vec![GitHubCheck {- status: Some("COMPLETED".into()),- conclusion: Some("SUCCESS".into()),- state: None,- }]),- url: None,- head_repository_owner: None,- };- assert_eq!(pr.ci_status(), CiStatus::Passed);- }-- #[test]- fn test_aggregate_github_checks() {- // Helper to create a check without state field (like check-runs API)- fn check(status: &str, conclusion: Option<&str>) -> GitHubCheck {- GitHubCheck {- status: Some(status.into()),- conclusion: conclusion.map(|c| c.into()),- state: None,- }- }-- // Empty checks = NoCI- assert_eq!(aggregate_github_checks(&[]), CiStatus::NoCI);-- // All skipped = NoCI (skipped doesn't count as success)- let checks = vec![- check("completed", Some("skipped")),- check("completed", Some("neutral")),- ];- assert_eq!(aggregate_github_checks(&checks), CiStatus::NoCI);-- // Any running = Running- for status in ["in_progress", "queued", "pending"] {- let checks = vec![check("completed", Some("success")), check(status, None)];- assert_eq!(- aggregate_github_checks(&checks),- CiStatus::Running,- "status={status}"- );- }-- // Any failure among completed checks = Failed- for conclusion in ["failure", "cancelled", "timed_out", "action_required"] {- let checks = vec![- check("completed", Some("success")),- check("completed", Some(conclusion)),- ];- assert_eq!(- aggregate_github_checks(&checks),- CiStatus::Failed,- "conclusion={conclusion}"- );- }-- // Running takes priority over failure (build might still succeed)- let checks = vec![- check("in_progress", None),- check("completed", Some("failure")),- ];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);-- // All success = Passed- let checks = vec![- check("completed", Some("success")),- check("completed", Some("success")),- ];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);-- // Mix of success and skipped = Passed (skipped doesn't block)- let checks = vec![- check("completed", Some("success")),- check("completed", Some("skipped")),- ];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);-- // Case insensitivity (handles both PR uppercase and API lowercase)- let checks = vec![check("COMPLETED", Some("FAILURE"))];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);-- // StatusContext via state field (used by external CI like pre-commit.ci)- let checks = vec![GitHubCheck {- status: None,- conclusion: None,- state: Some("PENDING".into()),- }];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);-- let checks = vec![GitHubCheck {- status: None,- conclusion: None,- state: Some("failure".into()),- }];- assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);- }-- #[test]- fn test_parse_gitlab_status() {- // Running states- for status in [- "running",- "pending",- "preparing",- "waiting_for_resource",- "created",- "scheduled",- ] {- assert_eq!(- parse_gitlab_status(Some(status)),- CiStatus::Running,- "status={status}"- );- }-- // Failed states- for status in ["failed", "canceled", "manual"] {- assert_eq!(- parse_gitlab_status(Some(status)),- CiStatus::Failed,- "status={status}"- );- }-- // Success- assert_eq!(parse_gitlab_status(Some("success")), CiStatus::Passed);-- // NoCI states- assert_eq!(parse_gitlab_status(Some("skipped")), CiStatus::NoCI);- assert_eq!(parse_gitlab_status(None), CiStatus::NoCI);- assert_eq!(parse_gitlab_status(Some("unknown")), CiStatus::NoCI);- }-- #[test]- fn test_gitlab_mr_info_ci_status() {- // No pipeline = NoCI- let mr = GitLabMrInfo {- sha: "abc".into(),- has_conflicts: false,- detailed_merge_status: None,- head_pipeline: None,- pipeline: None,- source_project_id: None,- web_url: None,- };- assert_eq!(mr.ci_status(), CiStatus::NoCI);-- // head_pipeline takes precedence- let mr = GitLabMrInfo {- sha: "abc".into(),- has_conflicts: false,- detailed_merge_status: None,- head_pipeline: Some(GitLabPipeline {- status: Some("success".into()),- sha: None,- web_url: None,- }),- pipeline: Some(GitLabPipeline {- status: Some("failed".into()),- sha: None,- web_url: None,- }),- source_project_id: None,- web_url: None,- };- assert_eq!(mr.ci_status(), CiStatus::Passed);-- // Falls back to pipeline if no head_pipeline- let mr = GitLabMrInfo {- sha: "abc".into(),- has_conflicts: false,- detailed_merge_status: None,- head_pipeline: None,- pipeline: Some(GitLabPipeline {- status: Some("running".into()),- sha: None,- web_url: None,- }),- source_project_id: None,- web_url: None,- };- assert_eq!(mr.ci_status(), CiStatus::Running);- }-- #[test]- fn test_pr_status_style_and_format() {- let status = PrStatus {- ci_status: CiStatus::Passed,- source: CiSource::PullRequest,- is_stale: false,- url: None,- };- // Call format_indicator directly- let formatted = status.format_indicator(false);- assert!(formatted.contains("●"));-- // Stale status gets dimmed- let stale = PrStatus {- ci_status: CiStatus::Running,- source: CiSource::Branch,- is_stale: true,- url: None,- };- let style = stale.style();- // Just verify it doesn't panic and returns a style- let _ = format!("{style}test{style:#}");- }-}--/// Maximum number of PRs/MRs to fetch when filtering by source repository.-///-/// We fetch multiple results because the same branch name may exist in-/// multiple forks. 20 should be sufficient for most cases.-///-/// # Limitation-///-/// If more than 20 PRs/MRs exist for the same branch name, we only search the-/// first page. This means in extremely busy repos with many forks, our PR/MR-/// could be on page 2+ and not be found. This is a trade-off: pagination would-/// require multiple API calls and slow down status detection. In practice, 20-/// is sufficient for most workflows.-const MAX_PRS_TO_FETCH: u8 = 20;--/// Get the owner of the origin remote (for GitHub fork detection).-///-/// Used for client-side filtering of PRs by source repository.-/// See [`parse_remote_owner`] for details on why this is necessary.-fn get_origin_owner(repo: &Repository) -> Option<String> {- let url = repo.primary_remote_url()?;- parse_remote_owner(&url)-}--/// Get the owner and repo name from the primary remote.-///-/// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths.-fn get_owner_repo(repo: &Repository) -> Option<(String, String)> {- let url = repo.primary_remote_url()?;- parse_owner_repo(&url)-}--/// Get the GitLab project ID for a repository.-///-/// Used for client-side filtering of MRs by source project.-/// This is the GitLab equivalent of [`get_origin_owner`] for GitHub.-///-/// Returns None if glab is not available or not configured for this repo.-///-/// # Performance Note-///-/// This function is called during GitLab detection regardless of whether-/// the repo is actually GitLab-hosted. If glab is installed but the repo-/// is GitHub, this adds an unnecessary CLI call. A future optimization-/// could check the remote URL first and skip for non-GitLab remotes.-fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {- let repo_root = repo.current_worktree().root().ok()?;-- // Use glab repo view to get the project info as JSON- // Disable color/pager to avoid ANSI noise in JSON output- let output = non_interactive_cmd("glab")- .args(["repo", "view", "--output", "json"])- .current_dir(&repo_root)- .env("PAGER", "cat")- .run()- .ok()?;-- if !output.status.success() {- return None;- }-- // Parse the JSON to extract the project ID- #[derive(Deserialize)]- struct RepoInfo {- id: u64,- }-- serde_json::from_slice::<RepoInfo>(&output.stdout)- .ok()- .map(|info| info.id)-}--/// Create a Cmd configured for non-interactive batch execution.-///-/// This prevents tools like `gh` and `glab` from:-/// - Prompting for user input-/// - Using TTY-specific output formatting-/// - Opening browsers for authentication-fn non_interactive_cmd(program: &str) -> Cmd {- Cmd::new(program)- .env_remove("CLICOLOR_FORCE")- .env_remove("GH_FORCE_TTY")- .env("NO_COLOR", "1")- .env("CLICOLOR", "0")- .env("GH_PROMPT_DISABLED", "1")-}--/// Check if a CLI tool is available-///-/// On Windows, CreateProcessW (via Cmd) searches PATH for .exe files.-/// We provide .exe mocks in tests via mock-stub, so this works consistently.-fn tool_available(tool: &str, args: &[&str]) -> bool {- Cmd::new(tool)- .args(args.iter().copied())- .run()- .map(|o| o.status.success())- .unwrap_or(false)-}--/// Status of CI tools availability-#[derive(Debug, Clone, Copy)]-pub struct CiToolsStatus {- /// gh is installed (can run --version)- pub gh_installed: bool,- /// gh is installed and authenticated- pub gh_authenticated: bool,- /// glab is installed (can run --version)- pub glab_installed: bool,- /// glab is installed and authenticated- pub glab_authenticated: bool,-}--impl CiToolsStatus {- /// Check which CI tools are available- ///- /// If `gitlab_host` is provided, checks glab auth status against that specific- /// host instead of the default. This is important for self-hosted GitLab instances- /// where the default host (gitlab.com) may be unreachable.- pub fn detect(gitlab_host: Option<&str>) -> Self {- let gh_installed = tool_available("gh", &["--version"]);- let gh_authenticated = gh_installed && tool_available("gh", &["auth", "status"]);- let glab_installed = tool_available("glab", &["--version"]);- let glab_authenticated = glab_installed- && if let Some(host) = gitlab_host {- tool_available("glab", &["auth", "status", "--hostname", host])- } else {- tool_available("glab", &["auth", "status"])- };- Self {- gh_installed,- gh_authenticated,- glab_installed,- glab_authenticated,- }- }-}--/// Parse JSON output from CLI tools-fn parse_json<T: DeserializeOwned>(stdout: &[u8], command: &str, branch: &str) -> Option<T> {- serde_json::from_slice(stdout)- .map_err(|e| log::warn!("Failed to parse {} JSON for {}: {}", command, branch, e))- .ok()-}--/// Check if stderr indicates a retriable error (rate limit, network issues)-fn is_retriable_error(stderr: &str) -> bool {- let lower = stderr.to_ascii_lowercase();- [- "rate limit",- "api rate",- "403",- "429",- "timeout",- "connection",- "network",- ]- .iter()- .any(|p| lower.contains(p))-}--/// CI status from GitHub/GitLab checks-/// Matches the statusline.sh color scheme:-/// - Passed: Green (all checks passed)-/// - Running: Blue (checks in progress)-/// - Failed: Red (checks failed)-/// - Conflicts: Yellow (merge conflicts)-/// - NoCI: Gray (no PR/checks)-/// - Error: Yellow (CI fetch failed, e.g., rate limit)-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]-#[serde(rename_all = "kebab-case")]-#[strum(serialize_all = "kebab-case")]-pub enum CiStatus {- Passed,- Running,- Failed,- Conflicts,- NoCI,- /// CI status could not be fetched (rate limit, network error, etc.)- Error,-}--/// Source of CI status-///-/// Visual distinction: Currently both PR and branch CI use ● (filled circle).-/// The internal distinction (CiSource::PullRequest vs CiSource::Branch) is preserved-/// for potential future visual differentiation. We tried ◒ (half circle) for branch CI-/// but it renders narrower than ● in many terminal fonts, causing misalignment.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]-#[strum(serialize_all = "kebab-case")]-pub enum CiSource {- /// Pull request or merge request- #[serde(rename = "pr", alias = "pull-request")]- PullRequest,- /// Branch workflow/pipeline (no PR/MR)- #[serde(rename = "branch")]- Branch,-}--/// CI status from PR/MR or branch workflow-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct PrStatus {- pub ci_status: CiStatus,- /// Source of the CI status (PR/MR or branch workflow)- pub source: CiSource,- /// True if local HEAD differs from remote HEAD (unpushed changes)- pub is_stale: bool,- /// URL to the PR/MR (if available)- #[serde(skip_serializing_if = "Option::is_none")]- pub url: Option<String>,-}--/// Cached CI status stored in `.git/wt-cache/ci-status/<branch>.json`-///-/// Uses file-based caching instead of git config to avoid file locking issues.-/// On Windows, concurrent `git config` writes can temporarily lock `.git/config`,-/// causing other git operations to fail with "Permission denied".-#[derive(Debug, Clone, Serialize, Deserialize)]-pub(crate) struct CachedCiStatus {- /// The cached CI status (None means no CI found for this branch)- pub status: Option<PrStatus>,- /// Unix timestamp when the status was fetched- pub checked_at: u64,- /// The HEAD commit SHA when the status was fetched- pub head: String,-}--impl CachedCiStatus {- /// Base cache TTL in seconds.- const TTL_BASE_SECS: u64 = 30;-- /// Maximum jitter added to TTL in seconds.- /// Actual TTL will be BASE + (0..JITTER) based on repo path hash.- const TTL_JITTER_SECS: u64 = 30;-- /// Compute TTL with jitter based on repo path.- ///- /// Different directories get different TTLs [30, 60) seconds, which spreads- /// out cache expirations when multiple statuslines run concurrently.- pub(crate) fn ttl_for_repo(repo_root: &Path) -> u64 {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};-- let mut hasher = DefaultHasher::new();- // Hash the path bytes directly for consistent TTL across string representations- repo_root.as_os_str().hash(&mut hasher);- let hash = hasher.finish();-- // Map hash to jitter range [0, TTL_JITTER_SECS)- let jitter = hash % Self::TTL_JITTER_SECS;- Self::TTL_BASE_SECS + jitter- }-- /// Check if the cache is still valid- fn is_valid(&self, current_head: &str, now_secs: u64, repo_root: &Path) -> bool {- // Cache is valid if:- // 1. HEAD hasn't changed (same commit)- // 2. TTL hasn't expired (with deterministic jitter based on repo path)- let ttl = Self::ttl_for_repo(repo_root);- self.head == current_head && now_secs.saturating_sub(self.checked_at) < ttl- }-- /// Get the cache directory path: `.git/wt-cache/ci-status/`- fn cache_dir(repo: &Repository) -> PathBuf {- repo.git_common_dir().join("wt-cache").join("ci-status")- }-- /// Get the cache file path for a branch.- fn cache_file(repo: &Repository, branch: &str) -> PathBuf {- let dir = Self::cache_dir(repo);- let safe_branch = sanitize_for_filename(branch);- dir.join(format!("{safe_branch}.json"))- }-- /// Read cached CI status from file.- fn read(repo: &Repository, branch: &str) -> Option<Self> {- let path = Self::cache_file(repo, branch);- let json = fs::read_to_string(&path).ok()?;- serde_json::from_str(&json).ok()- }-- /// Write CI status to cache file.- ///- /// Uses atomic write (write to temp file, then rename) to avoid corruption- /// and minimize lock contention on Windows.- fn write(&self, repo: &Repository, branch: &str) {- let path = Self::cache_file(repo, branch);-- // Create cache directory if needed- if let Some(parent) = path.parent()- && let Err(e) = fs::create_dir_all(parent)- {- log::debug!("Failed to create cache dir for {}: {}", branch, e);- return;- }-- let Ok(json) = serde_json::to_string(self) else {- log::debug!("Failed to serialize CI cache for {}", branch);- return;- };-- // Write to temp file first, then rename for atomic update- let temp_path = path.with_extension("json.tmp");- if let Err(e) = fs::write(&temp_path, &json) {- log::debug!("Failed to write CI cache temp file for {}: {}", branch, e);- return;- }-- if let Err(e) = fs::rename(&temp_path, &path) {- log::debug!("Failed to rename CI cache file for {}: {}", branch, e);- // Clean up temp file on failure- let _ = fs::remove_file(&temp_path);- }- }-- /// List all cached CI statuses as (branch_name, cached_status) pairs.- pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {- let cache_dir = Self::cache_dir(repo);-- let entries = match fs::read_dir(&cache_dir) {- Ok(entries) => entries,- Err(_) => return Vec::new(),- };-- entries- .filter_map(|entry| {- let entry = entry.ok()?;- let path = entry.path();-- // Only process .json files (skip .json.tmp)- if path.extension()?.to_str()? != "json" {- return None;- }-- let branch = path.file_stem()?.to_str()?.to_string();- let json = fs::read_to_string(&path).ok()?;- let cached: Self = serde_json::from_str(&json).ok()?;- Some((branch, cached))- })- .collect()- }-- /// Clear all cached CI statuses, returns count cleared.- pub(crate) fn clear_all(repo: &Repository) -> usize {- let cache_dir = Self::cache_dir(repo);-- let entries = match fs::read_dir(&cache_dir) {- Ok(entries) => entries,- Err(_) => return 0,- };-- let mut cleared = 0;- for entry in entries.flatten() {- let path = entry.path();- // Only remove .json files- if path.extension().is_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {- cleared += 1;- }- }- cleared- }-}--impl CiStatus {- /// Get the ANSI color for this CI status.- ///- /// - Passed: Green- /// - Running: Blue- /// - Failed: Red- /// - Conflicts: Yellow- /// - NoCI: BrightBlack (dimmed)- /// - Error: Yellow (warning color)- pub fn color(&self) -> anstyle::AnsiColor {- use anstyle::AnsiColor;- match self {- Self::Passed => AnsiColor::Green,- Self::Running => AnsiColor::Blue,- Self::Failed => AnsiColor::Red,- Self::Conflicts | Self::Error => AnsiColor::Yellow,- Self::NoCI => AnsiColor::BrightBlack,- }- }-}--impl PrStatus {- /// Get the style for this PR status (color + optional dimming for stale)- pub fn style(&self) -> anstyle::Style {- use anstyle::{Color, Style};- let style = Style::new().fg_color(Some(Color::Ansi(self.ci_status.color())));- if self.is_stale { style.dimmed() } else { style }- }-- /// Get the indicator symbol for this status- ///- /// - Error: ⚠ (overrides source indicator)- /// - PullRequest: ● (filled circle)- /// - Branch: ● (filled circle) — same as PR for now, see CiSource doc comment- pub fn indicator(&self) -> &'static str {- match self.ci_status {- CiStatus::Error => "⚠",- _ => match self.source {- CiSource::PullRequest => "●",- // Using same indicator as PR for now due to font rendering issues.- // See CiSource doc comment for details.- CiSource::Branch => "●",- },- }- }-- /// Format CI status with control over link inclusion.- ///- /// When `include_link` is false, the indicator is colored but not clickable.- /// Used for environments that don't support OSC 8 hyperlinks (e.g., Claude Code).- pub fn format_indicator(&self, include_link: bool) -> String {- let indicator = self.indicator();- if include_link && self.url.is_some() {- let url = self.url.as_ref().unwrap();- let style = self.style().underline();- format!(- "{}{}{}{}{}",- style,- osc8::Hyperlink::new(url),- indicator,- osc8::Hyperlink::END,- style.render_reset()- )- } else {- let style = self.style();- format!("{style}{indicator}{style:#}")- }- }-- /// Create an error status for retriable failures (rate limit, network errors)- fn error() -> Self {- Self {- ci_status: CiStatus::Error,- source: CiSource::Branch,- is_stale: false,- url: None,- }- }-- /// Detect CI status for a branch using gh/glab CLI- /// First tries to find PR/MR status, then falls back to workflow/pipeline runs- /// Returns None if no CI found or CLI tools unavailable- ///- /// # Caching- /// Results (including None) are cached in `.git/wt-cache/ci-status/<branch>.json`- /// for 30-60 seconds to avoid hitting GitHub API rate limits. TTL uses deterministic jitter- /// based on repo path to spread cache expirations across concurrent statuslines. Invalidated- /// when HEAD changes.- ///- /// # Fork Support- /// Runs gh commands from the repository directory to enable auto-detection of- /// upstream repositories for forks. This ensures PRs opened against upstream- /// repos are properly detected.- ///- /// # Arguments- /// * `has_upstream` - Whether the branch has upstream tracking configured.- /// PR/MR detection always runs. Workflow/pipeline fallback only runs if true.- pub fn detect(- repo: &Repository,- branch: &str,- local_head: &str,- has_upstream: bool,- ) -> Option<Self> {- let repo_path = repo.current_worktree().root().ok()?;-- // Check cache first to avoid hitting API rate limits- let now_secs = get_now();-- if let Some(cached) = CachedCiStatus::read(repo, branch) {- if cached.is_valid(local_head, now_secs, &repo_path) {- log::debug!(- "Using cached CI status for {} (age={}s, ttl={}s, status={:?})",- branch,- now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(&repo_path),- cached.status.as_ref().map(|s| &s.ci_status)- );- return cached.status;- }- log::debug!(- "Cache expired for {} (age={}s, ttl={}s, head_match={})",- branch,- now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(&repo_path),- cached.head == local_head- );- }-- // Cache miss or expired - fetch fresh status- let status = Self::detect_uncached(repo, branch, local_head, has_upstream);-- // Cache the result (including None - means no CI found for this branch)- let cached = CachedCiStatus {- status: status.clone(),- checked_at: now_secs,- head: local_head.to_string(),- };- cached.write(repo, branch);-- status- }-- /// Detect CI status without caching (internal implementation)- ///- /// Platform is determined by project config override or remote URL detection.- /// For unknown platforms (e.g., GitHub Enterprise with custom domains), falls back- /// to trying both platforms.- /// PR/MR detection always runs. Workflow/pipeline fallback only runs if `has_upstream`.- fn detect_uncached(- repo: &Repository,- branch: &str,- local_head: &str,- has_upstream: bool,- ) -> Option<Self> {- // Load project config for platform override (cached in Repository)- let project_config = repo.load_project_config().ok().flatten();- let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());-- // Determine platform (config override or URL detection)- let platform = get_platform_for_repo(repo, platform_override);-- match platform {- Some(CiPlatform::GitHub) => {- Self::detect_github_ci(repo, branch, local_head, has_upstream)- }- Some(CiPlatform::GitLab) => {- Self::detect_gitlab_ci(repo, branch, local_head, has_upstream)- }- None => {- // Unknown platform (e.g., GitHub Enterprise, self-hosted GitLab with custom domain)- // Fall back to trying both platforms- log::debug!("Could not determine CI platform, trying both");- Self::detect_github_ci(repo, branch, local_head, has_upstream)- .or_else(|| Self::detect_gitlab_ci(repo, branch, local_head, has_upstream))- }- }- }-- /// Detect GitHub CI status (PR first, then workflow if has_upstream)- fn detect_github_ci(- repo: &Repository,- branch: &str,- local_head: &str,- has_upstream: bool,- ) -> Option<Self> {- if let Some(status) = Self::detect_github(repo, branch, local_head) {- return Some(status);- }- if has_upstream {- return Self::detect_github_commit_checks(repo, local_head);- }- None- }-- /// Detect GitLab CI status (MR first, then pipeline if has_upstream)- fn detect_gitlab_ci(- repo: &Repository,- branch: &str,- local_head: &str,- has_upstream: bool,- ) -> Option<Self> {- if let Some(status) = Self::detect_gitlab(repo, branch, local_head) {- return Some(status);- }- if has_upstream {- return Self::detect_gitlab_pipeline(branch, local_head);- }- None- }-- /// Detect GitHub PR CI status for a branch.- ///- /// # Filtering Strategy- ///- /// We need to find PRs where the head branch comes from *our* fork, not just- /// PRs we authored. The `--author` flag filters by PR creator, but we want- /// to filter by source repository.- ///- /// Since `gh pr list --head` doesn't support `owner:branch` format, we:- /// 1. Fetch all open PRs with matching branch name (up to 20)- /// 2. Include `headRepositoryOwner` in the JSON output- /// 3. Filter client-side by comparing `headRepositoryOwner.login` to our origin owner- ///- /// This correctly handles:- /// - Fork workflows (PRs from your fork to upstream)- /// - Organization repos (PRs from org branches)- /// - Multiple users with same branch name- fn detect_github(repo: &Repository, branch: &str, local_head: &str) -> Option<Self> {- let repo_root = repo.current_worktree().root().ok()?;-- // Get origin owner for filtering (see parse_remote_owner docs for why)- let origin_owner = get_origin_owner(repo);- if origin_owner.is_none() {- log::debug!("Could not determine origin owner for {}", branch);- }-- // Use `gh pr list --head` instead of `gh pr view` to handle numeric branch names correctly.- // When branch name is all digits (e.g., "4315"), `gh pr view` interprets it as a PR number,- // but `gh pr list --head` correctly treats it as a branch name.- //- // We fetch up to MAX_PRS_TO_FETCH PRs to handle branch name collisions, then filter- // client-side by headRepositoryOwner to find PRs from our fork.- let output = match non_interactive_cmd("gh")- .args([- "pr",- "list",- "--head",- branch,- "--state",- "open",- "--limit",- &MAX_PRS_TO_FETCH.to_string(),- "--json",- "headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner",- ])- .current_dir(&repo_root)- .run()- {- Ok(output) => output,- Err(e) => {- log::warn!("gh pr list failed to execute for branch {}: {}", branch, e);- return None;- }- };-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- if is_retriable_error(&stderr) {- return Some(Self::error());- }- return None;- }-- // gh pr list returns an array - find the first PR from our origin- let pr_list: Vec<GitHubPrInfo> = parse_json(&output.stdout, "gh pr list", branch)?;-- // Filter to PRs from our origin (case-insensitive comparison for GitHub usernames).- // If headRepositoryOwner is missing (older GH CLI, Enterprise, or permissions),- // treat it as a potential match to avoid false negatives.- let pr_info = if let Some(ref owner) = origin_owner {- let matched = pr_list.iter().find(|pr| {- pr.head_repository_owner- .as_ref()- .map(|h| h.login.eq_ignore_ascii_case(owner))- .unwrap_or(true) // Missing owner field = potential match- });- if matched.is_none() && !pr_list.is_empty() {- log::debug!(- "Found {} PRs for branch {} but none from origin owner {}",- pr_list.len(),- branch,- owner- );- }- matched- } else {- // If we can't determine origin owner, fall back to first open PR- // This is less accurate but better than nothing- log::debug!(- "No origin owner for {}, using first open PR for branch {}",- repo_root.display(),- branch- );- pr_list.first()- }?;-- // Determine CI status using priority: conflicts > running > failed > passed > no_ci- let ci_status = if pr_info.merge_state_status.as_deref() == Some("DIRTY") {- CiStatus::Conflicts- } else {- pr_info.ci_status()- };-- let is_stale = pr_info- .head_ref_oid- .as_ref()- .map(|pr_head| pr_head != local_head)- .unwrap_or(false);-- Some(PrStatus {- ci_status,- source: CiSource::PullRequest,- is_stale,- url: pr_info.url.clone(),- })- }-- /// Detect GitLab MR CI status for a branch.- ///- /// # Filtering Strategy- ///- /// Similar to GitHub (see `detect_github`), we need to find MRs where the- /// source branch comes from *our* project, not just MRs we authored.- ///- /// Since `glab mr list` doesn't support filtering by source project, we:- /// 1. Get the current project ID via `glab repo view`- /// 2. Fetch all open MRs with matching branch name (up to 20)- /// 3. Filter client-side by comparing `source_project_id` to our project ID- fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -> Option<Self> {- if !tool_available("glab", &["--version"]) {- return None;- }-- let repo_root = repo.current_worktree().root().ok()?;-- // Get current project ID for filtering- let project_id = get_gitlab_project_id(repo);- if project_id.is_none() {- log::debug!("Could not determine GitLab project ID");- }-- // Fetch MRs with matching source branch.- // We filter client-side by source_project_id (numeric project ID comparison).- let output = match Cmd::new("glab")- .args([- "mr",- "list",- "--source-branch",- branch,- "--state=opened",- &format!("--per-page={}", MAX_PRS_TO_FETCH),- "--output",- "json",- ])- .current_dir(&repo_root)- .run()- {- Ok(output) => output,- Err(e) => {- log::warn!(- "glab mr list failed to execute for branch {}: {}",- branch,- e- );- return None;- }- };-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- // Return error status for retriable failures (rate limit, network) so they- // surface as warnings instead of being cached as "no CI"- if is_retriable_error(&stderr) {- return Some(Self::error());- }- return None;- }-- // glab mr list returns an array - find the first MR from our project- let mr_list: Vec<GitLabMrInfo> = parse_json(&output.stdout, "glab mr list", branch)?;-- // Filter to MRs from our project (numeric project ID comparison)- let mr_info = if let Some(proj_id) = project_id {- let matched = mr_list- .iter()- .find(|mr| mr.source_project_id == Some(proj_id));- if matched.is_none() && !mr_list.is_empty() {- log::debug!(- "Found {} MRs for branch {} but none from project ID {}",- mr_list.len(),- branch,- proj_id- );- }- matched- } else {- // If we can't determine project ID, fall back to first MR- log::debug!(- "No project ID for {}, using first MR for branch {}",- repo_root.display(),- branch- );- mr_list.first()- }?;-- // Determine CI status using priority: conflicts > running > failed > passed > no_ci- let ci_status = if mr_info.has_conflicts- || mr_info.detailed_merge_status.as_deref() == Some("conflict")- {- CiStatus::Conflicts- } else if mr_info.detailed_merge_status.as_deref() == Some("ci_still_running") {- CiStatus::Running- } else if mr_info.detailed_merge_status.as_deref() == Some("ci_must_pass") {- CiStatus::Failed- } else {- mr_info.ci_status()- };-- let is_stale = mr_info.sha != local_head;-- Some(PrStatus {- ci_status,- source: CiSource::PullRequest,- is_stale,- url: mr_info.web_url.clone(),- })- }-- /// Detect CI status for a commit using GitHub's check-runs API.- ///- /// This queries all check runs for the commit SHA, giving us the same data- /// that `statusCheckRollup` provides for PRs. This correctly aggregates- /// status across multiple workflows (e.g., `ci` and `publish-docs`).- fn detect_github_commit_checks(repo: &Repository, local_head: &str) -> Option<Self> {- let repo_root = repo.current_worktree().root().ok()?;- let (owner, repo_name) = get_owner_repo(repo)?;-- // Use GitHub's check-runs API to get all checks for this commit- let output = match non_interactive_cmd("gh")- .args([- "api",- &format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs"),- "--jq",- ".check_runs | map({status, conclusion})",- ])- .current_dir(&repo_root)- .run()- {- Ok(output) => output,- Err(e) => {- log::warn!(- "gh api check-runs failed to execute for {}: {}",- local_head,- e- );- return None;- }- };-- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- if is_retriable_error(&stderr) {- return Some(Self::error());- }- return None;- }-- let checks: Vec<GitHubCheck> = parse_json(&output.stdout, "gh api check-runs", local_head)?;-- if checks.is_empty() {- return None;- }-- // Aggregate status: any failed → Failed, any running → Running, else Passed- let ci_status = aggregate_github_checks(&checks);-- Some(PrStatus {- ci_status,- source: CiSource::Branch,- is_stale: false, // We're querying by SHA, so always current- url: None,- })- }-- fn detect_gitlab_pipeline(branch: &str, local_head: &str) -> Option<Self> {- if !tool_available("glab", &["--version"]) {- return None;- }-- // Get most recent pipeline for the branch using JSON output- let output = match Cmd::new("glab")- .args(["ci", "list", "--per-page", "1", "--output", "json"])- .env("BRANCH", branch) // glab ci list uses BRANCH env var- .run()- {- Ok(output) => output,- Err(e) => {- log::warn!(- "glab ci list failed to execute for branch {}: {}",- branch,- e- );- return None;- }- };-- if !output.status.success() {- return None;- }-- let pipelines: Vec<GitLabPipeline> = parse_json(&output.stdout, "glab ci list", branch)?;- let pipeline = pipelines.first()?;-- // Check if the pipeline matches our local HEAD commit- let is_stale = pipeline- .sha- .as_ref()- .map(|pipeline_sha| pipeline_sha != local_head)- .unwrap_or(true); // If no SHA, consider it stale-- let ci_status = pipeline.ci_status();-- Some(PrStatus {- ci_status,- source: CiSource::Branch,- is_stale,- url: pipeline.web_url.clone(),- })- }-}--/// GitHub PR info from `gh pr list --json ...`-///-/// Note: We include `headRepositoryOwner` for client-side filtering by source fork.-/// See [`parse_remote_owner`] for why this is necessary.-///-/// Note: We don't include `state` because we already filter with `--state open`.-#[derive(Debug, Deserialize)]-struct GitHubPrInfo {- #[serde(rename = "headRefOid")]- head_ref_oid: Option<String>,- #[serde(rename = "mergeStateStatus")]- merge_state_status: Option<String>,- #[serde(rename = "statusCheckRollup")]- status_check_rollup: Option<Vec<GitHubCheck>>,- url: Option<String>,- /// The owner of the repository the PR's head branch comes from.- /// Used to filter PRs by source fork (see [`parse_remote_owner`]).- #[serde(rename = "headRepositoryOwner")]- head_repository_owner: Option<HeadRepositoryOwner>,-}--/// Owner info for the head repository of a PR.-#[derive(Debug, Deserialize)]-struct HeadRepositoryOwner {- /// The login (username/org name) of the repository owner.- login: String,-}--/// A single check from `statusCheckRollup`.-///-/// This is a union of two GitHub API types with different field structures:-/// - `CheckRun` (GitHub Actions): has `status` ("COMPLETED", "IN_PROGRESS") and-/// `conclusion` ("SUCCESS", "FAILURE", "CANCELLED", "SKIPPED")-/// - `StatusContext` (external CI like pre-commit.ci): has `state` only-/// ("SUCCESS", "FAILURE", "PENDING", "ERROR")-///-/// We parse all three fields and check whichever is present. An alternative approach would be-/// `gh pr checks <number> --json state` which returns a flat array with unified `state` field,-/// but that requires a separate API call after finding the PR number. Since we also need-/// `gh run list` for branch-based CI (branches without PRs), keeping the single-call approach-/// here is simpler overall.-#[derive(Debug, Deserialize)]-struct GitHubCheck {- /// CheckRun only: "COMPLETED", "IN_PROGRESS", "QUEUED", etc.- status: Option<String>,- /// CheckRun only: "SUCCESS", "FAILURE", "CANCELLED", "SKIPPED", etc.- conclusion: Option<String>,- /// StatusContext only: "SUCCESS", "FAILURE", "PENDING", "ERROR"- state: Option<String>,-}--/// Aggregate CI status from multiple GitHub checks (case-insensitive).-///-/// Priority: running > failed > passed > no-ci.-/// Handles both `statusCheckRollup` (uppercase) and check-runs API (lowercase).-/// Skipped/neutral checks don't contribute to pass/fail.-fn aggregate_github_checks(checks: &[GitHubCheck]) -> CiStatus {- let mut has_running = false;- let mut has_failure = false;- let mut has_success = false;-- for check in checks {- // CheckRun: status field indicates in-progress states- if let Some(status) = &check.status {- let s = status.to_ascii_lowercase();- if matches!(- s.as_str(),- "in_progress" | "queued" | "pending" | "expected"- ) {- has_running = true;- }- }-- // StatusContext: state field indicates pending- if let Some(state) = &check.state {- let s = state.to_ascii_lowercase();- if s == "pending" {- has_running = true;- } else if matches!(s.as_str(), "failure" | "error") {- has_failure = true;- } else if s == "success" {- has_success = true;- }- }-- // CheckRun: conclusion field indicates final result- if let Some(conclusion) = &check.conclusion {- let c = conclusion.to_ascii_lowercase();- match c.as_str() {- "failure" | "error" | "cancelled" | "timed_out" | "action_required" => {- has_failure = true;- }- "success" => {- has_success = true;- }- // "skipped", "neutral" - ignored- _ => {}- }- }- }-- if has_running {- CiStatus::Running- } else if has_failure {- CiStatus::Failed- } else if has_success {- CiStatus::Passed- } else {- CiStatus::NoCI- }-}--impl GitHubPrInfo {- fn ci_status(&self) -> CiStatus {- match &self.status_check_rollup {- None => CiStatus::NoCI,- Some(checks) if checks.is_empty() => CiStatus::NoCI,- Some(checks) => aggregate_github_checks(checks),- }- }-}--/// GitLab MR info from `glab mr list --output json`-///-/// Note: We include `source_project_id` for client-side filtering by source project.-/// See [`parse_remote_owner`] for why we filter by source, not by author.-#[derive(Debug, Deserialize)]-struct GitLabMrInfo {- sha: String,- has_conflicts: bool,- detailed_merge_status: Option<String>,- head_pipeline: Option<GitLabPipeline>,- pipeline: Option<GitLabPipeline>,- /// The source project ID (the project the MR's branch comes from).- /// Used to filter MRs by source project.- source_project_id: Option<u64>,- /// URL to the MR page for clickable links- web_url: Option<String>,-}--impl GitLabMrInfo {- fn ci_status(&self) -> CiStatus {- self.head_pipeline- .as_ref()- .or(self.pipeline.as_ref())- .map(GitLabPipeline::ci_status)- .unwrap_or(CiStatus::NoCI)- }-}--#[derive(Debug, Deserialize)]-struct GitLabPipeline {- status: Option<String>,- /// Only present in `glab ci list` output, not in MR view embedded pipeline- #[serde(default)]- sha: Option<String>,- /// URL to the pipeline page for clickable links- #[serde(default)]- web_url: Option<String>,-}--fn parse_gitlab_status(status: Option<&str>) -> CiStatus {- match status {- Some(- "running" | "pending" | "preparing" | "waiting_for_resource" | "created" | "scheduled",- ) => CiStatus::Running,- Some("failed" | "canceled" | "manual") => CiStatus::Failed,- Some("success") => CiStatus::Passed,- Some("skipped") | None => CiStatus::NoCI,- _ => CiStatus::NoCI,- }-}--impl GitLabPipeline {- fn ci_status(&self) -> CiStatus {- parse_gitlab_status(self.status.as_deref())- }-}diff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rsnew file mode 100644index 000000000..1e4554d93--- /dev/null+++ b/src/commands/list/ci_status/cache.rs@@ -0,0 +1,207 @@+//! CI status caching.+//!+//! Caches CI status in `.git/wt-cache/ci-status/<branch>.json` to avoid+//! hitting API rate limits.++use serde::{Deserialize, Serialize};+use std::fs;+use std::path::{Path, PathBuf};+use worktrunk::git::Repository;+use worktrunk::path::sanitize_for_filename;++use super::PrStatus;++/// Cached CI status stored in `.git/wt-cache/ci-status/<branch>.json`+///+/// Uses file-based caching instead of git config to avoid file locking issues.+/// On Windows, concurrent `git config` writes can temporarily lock `.git/config`,+/// causing other git operations to fail with "Permission denied".+#[derive(Debug, Clone, Serialize, Deserialize)]+pub(crate) struct CachedCiStatus {+ /// The cached CI status (None means no CI found for this branch)+ pub status: Option<PrStatus>,+ /// Unix timestamp when the status was fetched+ pub checked_at: u64,+ /// The HEAD commit SHA when the status was fetched+ pub head: String,+}++impl CachedCiStatus {+ /// Base cache TTL in seconds.+ const TTL_BASE_SECS: u64 = 30;++ /// Maximum jitter added to TTL in seconds.+ /// Actual TTL will be BASE + (0..JITTER) based on repo path hash.+ const TTL_JITTER_SECS: u64 = 30;++ /// Compute TTL with jitter based on repo path.+ ///+ /// Different directories get different TTLs [30, 60) seconds, which spreads+ /// out cache expirations when multiple statuslines run concurrently.+ pub(crate) fn ttl_for_repo(repo_root: &Path) -> u64 {+ use std::collections::hash_map::DefaultHasher;+ use std::hash::{Hash, Hasher};++ let mut hasher = DefaultHasher::new();+ // Hash the path bytes directly for consistent TTL across string representations+ repo_root.as_os_str().hash(&mut hasher);+ let hash = hasher.finish();++ // Map hash to jitter range [0, TTL_JITTER_SECS)+ let jitter = hash % Self::TTL_JITTER_SECS;+ Self::TTL_BASE_SECS + jitter+ }++ /// Check if the cache is still valid+ pub(super) fn is_valid(&self, current_head: &str, now_secs: u64, repo_root: &Path) -> bool {+ // Cache is valid if:+ // 1. HEAD hasn't changed (same commit)+ // 2. TTL hasn't expired (with deterministic jitter based on repo path)+ let ttl = Self::ttl_for_repo(repo_root);+ self.head == current_head && now_secs.saturating_sub(self.checked_at) < ttl+ }++ /// Get the cache directory path: `.git/wt-cache/ci-status/`+ fn cache_dir(repo: &Repository) -> PathBuf {+ repo.git_common_dir().join("wt-cache").join("ci-status")+ }++ /// Get the cache file path for a branch.+ fn cache_file(repo: &Repository, branch: &str) -> PathBuf {+ let dir = Self::cache_dir(repo);+ let safe_branch = sanitize_for_filename(branch);+ dir.join(format!("{safe_branch}.json"))+ }++ /// Read cached CI status from file.+ pub(super) fn read(repo: &Repository, branch: &str) -> Option<Self> {+ let path = Self::cache_file(repo, branch);+ let json = fs::read_to_string(&path).ok()?;+ serde_json::from_str(&json).ok()+ }++ /// Write CI status to cache file.+ ///+ /// Uses atomic write (write to temp file, then rename) to avoid corruption+ /// and minimize lock contention on Windows.+ pub(super) fn write(&self, repo: &Repository, branch: &str) {+ let path = Self::cache_file(repo, branch);++ // Create cache directory if needed+ if let Some(parent) = path.parent()+ && let Err(e) = fs::create_dir_all(parent)+ {+ log::debug!("Failed to create cache dir for {}: {}", branch, e);+ return;+ }++ let Ok(json) = serde_json::to_string(self) else {+ log::debug!("Failed to serialize CI cache for {}", branch);+ return;+ };++ // Write to temp file first, then rename for atomic update+ let temp_path = path.with_extension("json.tmp");+ if let Err(e) = fs::write(&temp_path, &json) {+ log::debug!("Failed to write CI cache temp file for {}: {}", branch, e);+ return;+ }++ if let Err(e) = fs::rename(&temp_path, &path) {+ log::debug!("Failed to rename CI cache file for {}: {}", branch, e);+ // Clean up temp file on failure+ let _ = fs::remove_file(&temp_path);+ }+ }++ /// List all cached CI statuses as (branch_name, cached_status) pairs.+ pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {+ let cache_dir = Self::cache_dir(repo);++ let entries = match fs::read_dir(&cache_dir) {+ Ok(entries) => entries,+ Err(_) => return Vec::new(),+ };++ entries+ .filter_map(|entry| {+ let entry = entry.ok()?;+ let path = entry.path();++ // Only process .json files (skip .json.tmp)+ if path.extension()?.to_str()? != "json" {+ return None;+ }++ let branch = path.file_stem()?.to_str()?.to_string();+ let json = fs::read_to_string(&path).ok()?;+ let cached: Self = serde_json::from_str(&json).ok()?;+ Some((branch, cached))+ })+ .collect()+ }++ /// Clear all cached CI statuses, returns count cleared.+ pub(crate) fn clear_all(repo: &Repository) -> usize {+ let cache_dir = Self::cache_dir(repo);++ let entries = match fs::read_dir(&cache_dir) {+ Ok(entries) => entries,+ Err(_) => return 0,+ };++ let mut cleared = 0;+ for entry in entries.flatten() {+ let path = entry.path();+ // Only remove .json files+ if path.extension().is_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {+ cleared += 1;+ }+ }+ cleared+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_ttl_jitter_range_and_determinism() {+ // Check range: TTL should be in [30, 60)+ let paths = [+ "/tmp/repo1",+ "/tmp/repo2",+ "/workspace/project",+ "/home/user/code",+ ];+ for path in paths {+ let ttl = CachedCiStatus::ttl_for_repo(Path::new(path));+ assert!(+ (30..60).contains(&ttl),+ "TTL {} for path {} should be in [30, 60)",+ ttl,+ path+ );+ }++ // Check determinism: same path should always produce same TTL+ let path = Path::new("/some/consistent/path");+ let ttl1 = CachedCiStatus::ttl_for_repo(path);+ let ttl2 = CachedCiStatus::ttl_for_repo(path);+ assert_eq!(ttl1, ttl2, "Same path should produce same TTL");++ // Check diversity: different paths should likely produce different TTLs+ let diverse_paths: Vec<_> = (0..20).map(|i| format!("/repo/path{}", i)).collect();+ let ttls: std::collections::HashSet<_> = diverse_paths+ .iter()+ .map(|p| CachedCiStatus::ttl_for_repo(Path::new(p)))+ .collect();+ // With 20 paths mapping to 30 possible values, we expect good diversity+ assert!(+ ttls.len() >= 10,+ "Expected diverse TTLs across paths, got {} unique values",+ ttls.len()+ );+ }+}diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsnew file mode 100644index 000000000..a9623e41d--- /dev/null+++ b/src/commands/list/ci_status/github.rs@@ -0,0 +1,512 @@+//! GitHub CI status detection.+//!+//! Detects CI status from GitHub PRs and workflow runs using the `gh` CLI.++use serde::Deserialize;+use worktrunk::git::{Repository, parse_owner_repo, parse_remote_owner};++use super::{+ CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error, non_interactive_cmd,+ parse_json,+};++/// Get the owner of the origin remote (for GitHub fork detection).+///+/// Used for client-side filtering of PRs by source repository.+/// See [`parse_remote_owner`] for details on why this is necessary.+fn get_origin_owner(repo: &Repository) -> Option<String> {+ let url = repo.primary_remote_url()?;+ parse_remote_owner(&url)+}++/// Get the owner and repo name from the primary remote.+///+/// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths.+fn get_owner_repo(repo: &Repository) -> Option<(String, String)> {+ let url = repo.primary_remote_url()?;+ parse_owner_repo(&url)+}++/// Detect GitHub PR CI status for a branch.+///+/// # Filtering Strategy+///+/// We need to find PRs where the head branch comes from *our* fork, not just+/// PRs we authored. The `--author` flag filters by PR creator, but we want+/// to filter by source repository.+///+/// Since `gh pr list --head` doesn't support `owner:branch` format, we:+/// 1. Fetch all open PRs with matching branch name (up to 20)+/// 2. Include `headRepositoryOwner` in the JSON output+/// 3. Filter client-side by comparing `headRepositoryOwner.login` to our origin owner+///+/// This correctly handles:+/// - Fork workflows (PRs from your fork to upstream)+/// - Organization repos (PRs from org branches)+/// - Multiple users with same branch name+pub(super) fn detect_github(repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+ let repo_root = repo.current_worktree().root().ok()?;++ // Get origin owner for filtering (see parse_remote_owner docs for why)+ let origin_owner = get_origin_owner(repo);+ if origin_owner.is_none() {+ log::debug!("Could not determine origin owner for {}", branch);+ }++ // Use `gh pr list --head` instead of `gh pr view` to handle numeric branch names correctly.+ // When branch name is all digits (e.g., "4315"), `gh pr view` interprets it as a PR number,+ // but `gh pr list --head` correctly treats it as a branch name.+ //+ // We fetch up to MAX_PRS_TO_FETCH PRs to handle branch name collisions, then filter+ // client-side by headRepositoryOwner to find PRs from our fork.+ let output = match non_interactive_cmd("gh")+ .args([+ "pr",+ "list",+ "--head",+ branch,+ "--state",+ "open",+ "--limit",+ &MAX_PRS_TO_FETCH.to_string(),+ "--json",+ "headRefOid,mergeStateStatus,statusCheckRollup,url,headRepositoryOwner",+ ])+ .current_dir(&repo_root)+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ log::warn!("gh pr list failed to execute for branch {}: {}", branch, e);+ return None;+ }+ };++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ if is_retriable_error(&stderr) {+ return Some(PrStatus::error());+ }+ return None;+ }++ // gh pr list returns an array - find the first PR from our origin+ let pr_list: Vec<GitHubPrInfo> = parse_json(&output.stdout, "gh pr list", branch)?;++ // Filter to PRs from our origin (case-insensitive comparison for GitHub usernames).+ // If headRepositoryOwner is missing (older GH CLI, Enterprise, or permissions),+ // treat it as a potential match to avoid false negatives.+ let pr_info = if let Some(ref owner) = origin_owner {+ let matched = pr_list.iter().find(|pr| {+ pr.head_repository_owner+ .as_ref()+ .map(|h| h.login.eq_ignore_ascii_case(owner))+ .unwrap_or(true) // Missing owner field = potential match+ });+ if matched.is_none() && !pr_list.is_empty() {+ log::debug!(+ "Found {} PRs for branch {} but none from origin owner {}",+ pr_list.len(),+ branch,+ owner+ );+ }+ matched+ } else {+ // If we can't determine origin owner, fall back to first open PR+ // This is less accurate but better than nothing+ log::debug!(+ "No origin owner for {}, using first open PR for branch {}",+ repo_root.display(),+ branch+ );+ pr_list.first()+ }?;++ // Determine CI status using priority: conflicts > running > failed > passed > no_ci+ let ci_status = if pr_info.merge_state_status.as_deref() == Some("DIRTY") {+ CiStatus::Conflicts+ } else {+ pr_info.ci_status()+ };++ let is_stale = pr_info+ .head_ref_oid+ .as_ref()+ .map(|pr_head| pr_head != local_head)+ .unwrap_or(false);++ Some(PrStatus {+ ci_status,+ source: CiSource::PullRequest,+ is_stale,+ url: pr_info.url.clone(),+ })+}++/// Detect CI status for a commit using GitHub's check-runs API.+///+/// This queries all check runs for the commit SHA, giving us the same data+/// that `statusCheckRollup` provides for PRs. This correctly aggregates+/// status across multiple workflows (e.g., `ci` and `publish-docs`).+pub(super) fn detect_github_commit_checks(repo: &Repository, local_head: &str) -> Option<PrStatus> {+ let repo_root = repo.current_worktree().root().ok()?;+ let (owner, repo_name) = get_owner_repo(repo)?;++ // Use GitHub's check-runs API to get all checks for this commit+ let output = match non_interactive_cmd("gh")+ .args([+ "api",+ &format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs"),+ "--jq",+ ".check_runs | map({status, conclusion})",+ ])+ .current_dir(&repo_root)+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ log::warn!(+ "gh api check-runs failed to execute for {}: {}",+ local_head,+ e+ );+ return None;+ }+ };++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ if is_retriable_error(&stderr) {+ return Some(PrStatus::error());+ }+ return None;+ }++ let checks: Vec<GitHubCheck> = parse_json(&output.stdout, "gh api check-runs", local_head)?;++ if checks.is_empty() {+ return None;+ }++ // Aggregate status: any failed → Failed, any running → Running, else Passed+ let ci_status = aggregate_github_checks(&checks);++ Some(PrStatus {+ ci_status,+ source: CiSource::Branch,+ is_stale: false, // We're querying by SHA, so always current+ url: None,+ })+}++/// GitHub PR info from `gh pr list --json ...`+///+/// Note: We include `headRepositoryOwner` for client-side filtering by source fork.+/// See [`parse_remote_owner`] for why this is necessary.+///+/// Note: We don't include `state` because we already filter with `--state open`.+#[derive(Debug, Deserialize)]+pub(super) struct GitHubPrInfo {+ #[serde(rename = "headRefOid")]+ pub head_ref_oid: Option<String>,+ #[serde(rename = "mergeStateStatus")]+ pub merge_state_status: Option<String>,+ #[serde(rename = "statusCheckRollup")]+ pub status_check_rollup: Option<Vec<GitHubCheck>>,+ pub url: Option<String>,+ /// The owner of the repository the PR's head branch comes from.+ /// Used to filter PRs by source fork (see [`parse_remote_owner`]).+ #[serde(rename = "headRepositoryOwner")]+ pub head_repository_owner: Option<HeadRepositoryOwner>,+}++/// Owner info for the head repository of a PR.+#[derive(Debug, Deserialize)]+pub(super) struct HeadRepositoryOwner {+ /// The login (username/org name) of the repository owner.+ pub login: String,+}++/// A single check from `statusCheckRollup`.+///+/// This is a union of two GitHub API types with different field structures:+/// - `CheckRun` (GitHub Actions): has `status` ("COMPLETED", "IN_PROGRESS") and+/// `conclusion` ("SUCCESS", "FAILURE", "CANCELLED", "SKIPPED")+/// - `StatusContext` (external CI like pre-commit.ci): has `state` only+/// ("SUCCESS", "FAILURE", "PENDING", "ERROR")+///+/// We parse all three fields and check whichever is present. An alternative approach would be+/// `gh pr checks <number> --json state` which returns a flat array with unified `state` field,+/// but that requires a separate API call after finding the PR number. Since we also need+/// `gh run list` for branch-based CI (branches without PRs), keeping the single-call approach+/// here is simpler overall.+#[derive(Debug, Deserialize)]+pub(super) struct GitHubCheck {+ /// CheckRun only: "COMPLETED", "IN_PROGRESS", "QUEUED", etc.+ pub status: Option<String>,+ /// CheckRun only: "SUCCESS", "FAILURE", "CANCELLED", "SKIPPED", etc.+ pub conclusion: Option<String>,+ /// StatusContext only: "SUCCESS", "FAILURE", "PENDING", "ERROR"+ pub state: Option<String>,+}++impl GitHubPrInfo {+ pub fn ci_status(&self) -> CiStatus {+ match &self.status_check_rollup {+ None => CiStatus::NoCI,+ Some(checks) if checks.is_empty() => CiStatus::NoCI,+ Some(checks) => aggregate_github_checks(checks),+ }+ }+}++/// Aggregate CI status from multiple GitHub checks (case-insensitive).+///+/// Priority: running > failed > passed > no-ci.+/// Handles both `statusCheckRollup` (uppercase) and check-runs API (lowercase).+/// Skipped/neutral checks don't contribute to pass/fail.+pub(super) fn aggregate_github_checks(checks: &[GitHubCheck]) -> CiStatus {+ let mut has_running = false;+ let mut has_failure = false;+ let mut has_success = false;++ for check in checks {+ // CheckRun: status field indicates in-progress states+ if let Some(status) = &check.status {+ let s = status.to_ascii_lowercase();+ if matches!(+ s.as_str(),+ "in_progress" | "queued" | "pending" | "expected"+ ) {+ has_running = true;+ }+ }++ // StatusContext: state field indicates pending+ if let Some(state) = &check.state {+ let s = state.to_ascii_lowercase();+ if s == "pending" {+ has_running = true;+ } else if matches!(s.as_str(), "failure" | "error") {+ has_failure = true;+ } else if s == "success" {+ has_success = true;+ }+ }++ // CheckRun: conclusion field indicates final result+ if let Some(conclusion) = &check.conclusion {+ let c = conclusion.to_ascii_lowercase();+ match c.as_str() {+ "failure" | "error" | "cancelled" | "timed_out" | "action_required" => {+ has_failure = true;+ }+ "success" => {+ has_success = true;+ }+ // "skipped", "neutral" - ignored+ _ => {}+ }+ }+ }++ if has_running {+ CiStatus::Running+ } else if has_failure {+ CiStatus::Failed+ } else if has_success {+ CiStatus::Passed+ } else {+ CiStatus::NoCI+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_github_pr_info_ci_status() {+ // No checks = NoCI+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: None,+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::NoCI);++ // Empty checks = NoCI+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::NoCI);++ // CheckRun pending states+ for status in ["IN_PROGRESS", "QUEUED", "PENDING", "EXPECTED"] {+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![GitHubCheck {+ status: Some(status.into()),+ conclusion: None,+ state: None,+ }]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::Running, "status={status}");+ }++ // StatusContext pending+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![GitHubCheck {+ status: None,+ conclusion: None,+ state: Some("PENDING".into()),+ }]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::Running);++ // CheckRun failures+ for conclusion in ["FAILURE", "ERROR", "CANCELLED"] {+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![GitHubCheck {+ status: Some("COMPLETED".into()),+ conclusion: Some(conclusion.into()),+ state: None,+ }]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::Failed, "conclusion={conclusion}");+ }++ // StatusContext failures+ for state in ["FAILURE", "ERROR"] {+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![GitHubCheck {+ status: None,+ conclusion: None,+ state: Some(state.into()),+ }]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::Failed, "state={state}");+ }++ // Success+ let pr = GitHubPrInfo {+ head_ref_oid: None,+ merge_state_status: None,+ status_check_rollup: Some(vec![GitHubCheck {+ status: Some("COMPLETED".into()),+ conclusion: Some("SUCCESS".into()),+ state: None,+ }]),+ url: None,+ head_repository_owner: None,+ };+ assert_eq!(pr.ci_status(), CiStatus::Passed);+ }++ #[test]+ fn test_aggregate_github_checks() {+ // Helper to create a check without state field (like check-runs API)+ fn check(status: &str, conclusion: Option<&str>) -> GitHubCheck {+ GitHubCheck {+ status: Some(status.into()),+ conclusion: conclusion.map(|c| c.into()),+ state: None,+ }+ }++ // Empty checks = NoCI+ assert_eq!(aggregate_github_checks(&[]), CiStatus::NoCI);++ // All skipped = NoCI (skipped doesn't count as success)+ let checks = vec![+ check("completed", Some("skipped")),+ check("completed", Some("neutral")),+ ];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::NoCI);++ // Any running = Running+ for status in ["in_progress", "queued", "pending"] {+ let checks = vec![check("completed", Some("success")), check(status, None)];+ assert_eq!(+ aggregate_github_checks(&checks),+ CiStatus::Running,+ "status={status}"+ );+ }++ // Any failure among completed checks = Failed+ for conclusion in ["failure", "cancelled", "timed_out", "action_required"] {+ let checks = vec![+ check("completed", Some("success")),+ check("completed", Some(conclusion)),+ ];+ assert_eq!(+ aggregate_github_checks(&checks),+ CiStatus::Failed,+ "conclusion={conclusion}"+ );+ }++ // Running takes priority over failure (build might still succeed)+ let checks = vec![+ check("in_progress", None),+ check("completed", Some("failure")),+ ];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);++ // All success = Passed+ let checks = vec![+ check("completed", Some("success")),+ check("completed", Some("success")),+ ];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);++ // Mix of success and skipped = Passed (skipped doesn't block)+ let checks = vec![+ check("completed", Some("success")),+ check("completed", Some("skipped")),+ ];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Passed);++ // Case insensitivity (handles both PR uppercase and API lowercase)+ let checks = vec![check("COMPLETED", Some("FAILURE"))];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);++ // StatusContext via state field (used by external CI like pre-commit.ci)+ let checks = vec![GitHubCheck {+ status: None,+ conclusion: None,+ state: Some("PENDING".into()),+ }];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Running);++ let checks = vec![GitHubCheck {+ status: None,+ conclusion: None,+ state: Some("failure".into()),+ }];+ assert_eq!(aggregate_github_checks(&checks), CiStatus::Failed);+ }+}diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rsnew file mode 100644index 000000000..4947cf8ee--- /dev/null+++ b/src/commands/list/ci_status/gitlab.rs@@ -0,0 +1,358 @@+//! GitLab CI status detection.+//!+//! Detects CI status from GitLab MRs and pipelines using the `glab` CLI.++use serde::Deserialize;+use worktrunk::git::Repository;+use worktrunk::shell_exec::Cmd;++use super::{+ CiSource, CiStatus, MAX_PRS_TO_FETCH, PrStatus, is_retriable_error, non_interactive_cmd,+ parse_json, tool_available,+};++/// Get the GitLab project ID for a repository.+///+/// Used for client-side filtering of MRs by source project.+/// This is the GitLab equivalent of `get_origin_owner` for GitHub.+///+/// Returns None if glab is not available or not configured for this repo.+///+/// # Performance Note+///+/// This function is called during GitLab detection regardless of whether+/// the repo is actually GitLab-hosted. If glab is installed but the repo+/// is GitHub, this adds an unnecessary CLI call. A future optimization+/// could check the remote URL first and skip for non-GitLab remotes.+fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {+ let repo_root = repo.current_worktree().root().ok()?;++ // Use glab repo view to get the project info as JSON+ // Disable color/pager to avoid ANSI noise in JSON output+ let output = non_interactive_cmd("glab")+ .args(["repo", "view", "--output", "json"])+ .current_dir(&repo_root)+ .env("PAGER", "cat")+ .run()+ .ok()?;++ if !output.status.success() {+ return None;+ }++ // Parse the JSON to extract the project ID+ #[derive(Deserialize)]+ struct RepoInfo {+ id: u64,+ }++ serde_json::from_slice::<RepoInfo>(&output.stdout)+ .ok()+ .map(|info| info.id)+}++/// Detect GitLab MR CI status for a branch.+///+/// # Filtering Strategy+///+/// Similar to GitHub (see `detect_github`), we need to find MRs where the+/// source branch comes from *our* project, not just MRs we authored.+///+/// Since `glab mr list` doesn't support filtering by source project, we:+/// 1. Get the current project ID via `glab repo view`+/// 2. Fetch all open MRs with matching branch name (up to 20)+/// 3. Filter client-side by comparing `source_project_id` to our project ID+pub(super) fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -> Option<PrStatus> {+ if !tool_available("glab", &["--version"]) {+ return None;+ }++ let repo_root = repo.current_worktree().root().ok()?;++ // Get current project ID for filtering+ let project_id = get_gitlab_project_id(repo);+ if project_id.is_none() {+ log::debug!("Could not determine GitLab project ID");+ }++ // Fetch MRs with matching source branch.+ // We filter client-side by source_project_id (numeric project ID comparison).+ let output = match Cmd::new("glab")+ .args([+ "mr",+ "list",+ "--source-branch",+ branch,+ "--state=opened",+ &format!("--per-page={}", MAX_PRS_TO_FETCH),+ "--output",+ "json",+ ])+ .current_dir(&repo_root)+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ log::warn!(+ "glab mr list failed to execute for branch {}: {}",+ branch,+ e+ );+ return None;+ }+ };++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ // Return error status for retriable failures (rate limit, network) so they+ // surface as warnings instead of being cached as "no CI"+ if is_retriable_error(&stderr) {+ return Some(PrStatus::error());+ }+ return None;+ }++ // glab mr list returns an array - find the first MR from our project+ let mr_list: Vec<GitLabMrInfo> = parse_json(&output.stdout, "glab mr list", branch)?;++ // Filter to MRs from our project (numeric project ID comparison)+ let mr_info = if let Some(proj_id) = project_id {+ let matched = mr_list+ .iter()+ .find(|mr| mr.source_project_id == Some(proj_id));+ if matched.is_none() && !mr_list.is_empty() {+ log::debug!(+ "Found {} MRs for branch {} but none from project ID {}",+ mr_list.len(),+ branch,+ proj_id+ );+ }+ matched+ } else {+ // If we can't determine project ID, fall back to first MR+ log::debug!(+ "No project ID for {}, using first MR for branch {}",+ repo_root.display(),+ branch+ );+ mr_list.first()+ }?;++ // Determine CI status using priority: conflicts > running > failed > passed > no_ci+ let ci_status =+ if mr_info.has_conflicts || mr_info.detailed_merge_status.as_deref() == Some("conflict") {+ CiStatus::Conflicts+ } else if mr_info.detailed_merge_status.as_deref() == Some("ci_still_running") {+ CiStatus::Running+ } else if mr_info.detailed_merge_status.as_deref() == Some("ci_must_pass") {+ CiStatus::Failed+ } else {+ mr_info.ci_status()+ };++ let is_stale = mr_info.sha != local_head;++ Some(PrStatus {+ ci_status,+ source: CiSource::PullRequest,+ is_stale,+ url: mr_info.web_url.clone(),+ })+}++/// Detect GitLab pipeline status for a branch (when no MR exists).+pub(super) fn detect_gitlab_pipeline(branch: &str, local_head: &str) -> Option<PrStatus> {+ if !tool_available("glab", &["--version"]) {+ return None;+ }++ // Get most recent pipeline for the branch using JSON output+ let output = match Cmd::new("glab")+ .args(["ci", "list", "--per-page", "1", "--output", "json"])+ .env("BRANCH", branch) // glab ci list uses BRANCH env var+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ log::warn!(+ "glab ci list failed to execute for branch {}: {}",+ branch,+ e+ );+ return None;+ }+ };++ if !output.status.success() {+ return None;+ }++ let pipelines: Vec<GitLabPipeline> = parse_json(&output.stdout, "glab ci list", branch)?;+ let pipeline = pipelines.first()?;++ // Check if the pipeline matches our local HEAD commit+ let is_stale = pipeline+ .sha+ .as_ref()+ .map(|pipeline_sha| pipeline_sha != local_head)+ .unwrap_or(true); // If no SHA, consider it stale++ let ci_status = pipeline.ci_status();++ Some(PrStatus {+ ci_status,+ source: CiSource::Branch,+ is_stale,+ url: pipeline.web_url.clone(),+ })+}++/// GitLab MR info from `glab mr list --output json`+///+/// Note: We include `source_project_id` for client-side filtering by source project.+/// See [`worktrunk::git::parse_remote_owner`] for why we filter by source, not by author.+#[derive(Debug, Deserialize)]+pub(super) struct GitLabMrInfo {+ pub sha: String,+ pub has_conflicts: bool,+ pub detailed_merge_status: Option<String>,+ pub head_pipeline: Option<GitLabPipeline>,+ pub pipeline: Option<GitLabPipeline>,+ /// The source project ID (the project the MR's branch comes from).+ /// Used to filter MRs by source project.+ pub source_project_id: Option<u64>,+ /// URL to the MR page for clickable links+ pub web_url: Option<String>,+}++impl GitLabMrInfo {+ pub fn ci_status(&self) -> CiStatus {+ self.head_pipeline+ .as_ref()+ .or(self.pipeline.as_ref())+ .map(GitLabPipeline::ci_status)+ .unwrap_or(CiStatus::NoCI)+ }+}++#[derive(Debug, Deserialize)]+pub(super) struct GitLabPipeline {+ pub status: Option<String>,+ /// Only present in `glab ci list` output, not in MR view embedded pipeline+ #[serde(default)]+ pub sha: Option<String>,+ /// URL to the pipeline page for clickable links+ #[serde(default)]+ pub web_url: Option<String>,+}++fn parse_gitlab_status(status: Option<&str>) -> CiStatus {+ match status {+ Some(+ "running" | "pending" | "preparing" | "waiting_for_resource" | "created" | "scheduled",+ ) => CiStatus::Running,+ Some("failed" | "canceled" | "manual") => CiStatus::Failed,+ Some("success") => CiStatus::Passed,+ Some("skipped") | None => CiStatus::NoCI,+ _ => CiStatus::NoCI,+ }+}++impl GitLabPipeline {+ pub fn ci_status(&self) -> CiStatus {+ parse_gitlab_status(self.status.as_deref())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_parse_gitlab_status() {+ // Running states+ for status in [+ "running",+ "pending",+ "preparing",+ "waiting_for_resource",+ "created",+ "scheduled",+ ] {+ assert_eq!(+ parse_gitlab_status(Some(status)),+ CiStatus::Running,+ "status={status}"+ );+ }++ // Failed states+ for status in ["failed", "canceled", "manual"] {+ assert_eq!(+ parse_gitlab_status(Some(status)),+ CiStatus::Failed,+ "status={status}"+ );+ }++ // Success+ assert_eq!(parse_gitlab_status(Some("success")), CiStatus::Passed);++ // NoCI states+ assert_eq!(parse_gitlab_status(Some("skipped")), CiStatus::NoCI);+ assert_eq!(parse_gitlab_status(None), CiStatus::NoCI);+ assert_eq!(parse_gitlab_status(Some("unknown")), CiStatus::NoCI);+ }++ #[test]+ fn test_gitlab_mr_info_ci_status() {+ // No pipeline = NoCI+ let mr = GitLabMrInfo {+ sha: "abc".into(),+ has_conflicts: false,+ detailed_merge_status: None,+ head_pipeline: None,+ pipeline: None,+ source_project_id: None,+ web_url: None,+ };+ assert_eq!(mr.ci_status(), CiStatus::NoCI);++ // head_pipeline takes precedence+ let mr = GitLabMrInfo {+ sha: "abc".into(),+ has_conflicts: false,+ detailed_merge_status: None,+ head_pipeline: Some(GitLabPipeline {+ status: Some("success".into()),+ sha: None,+ web_url: None,+ }),+ pipeline: Some(GitLabPipeline {+ status: Some("failed".into()),+ sha: None,+ web_url: None,+ }),+ source_project_id: None,+ web_url: None,+ };+ assert_eq!(mr.ci_status(), CiStatus::Passed);++ // Falls back to pipeline if no head_pipeline+ let mr = GitLabMrInfo {+ sha: "abc".into(),+ has_conflicts: false,+ detailed_merge_status: None,+ head_pipeline: None,+ pipeline: Some(GitLabPipeline {+ status: Some("running".into()),+ sha: None,+ web_url: None,+ }),+ source_project_id: None,+ web_url: None,+ };+ assert_eq!(mr.ci_status(), CiStatus::Running);+ }+}diff --git a/src/commands/list/ci_status/mod.rs b/src/commands/list/ci_status/mod.rsnew file mode 100644index 000000000..29aab8455--- /dev/null+++ b/src/commands/list/ci_status/mod.rs@@ -0,0 +1,549 @@+//! CI status detection for GitHub and GitLab.+//!+//! This module provides CI status detection by querying GitHub PRs/workflows+//! and GitLab MRs/pipelines using their respective CLI tools (`gh` and `glab`).++mod cache;+mod github;+mod gitlab;+mod platform;++use serde::{Deserialize, Serialize, de::DeserializeOwned};+use worktrunk::git::Repository;+use worktrunk::shell_exec::Cmd;+use worktrunk::utils::get_now;++// Re-export public types+pub(crate) use cache::CachedCiStatus;+pub use platform::{CiPlatform, get_platform_for_repo};++/// Maximum number of PRs/MRs to fetch when filtering by source repository.+///+/// We fetch multiple results because the same branch name may exist in+/// multiple forks. 20 should be sufficient for most cases.+///+/// # Limitation+///+/// If more than 20 PRs/MRs exist for the same branch name, we only search the+/// first page. This means in extremely busy repos with many forks, our PR/MR+/// could be on page 2+ and not be found. This is a trade-off: pagination would+/// require multiple API calls and slow down status detection. In practice, 20+/// is sufficient for most workflows.+const MAX_PRS_TO_FETCH: u8 = 20;++/// Create a Cmd configured for non-interactive batch execution.+///+/// This prevents tools like `gh` and `glab` from:+/// - Prompting for user input+/// - Using TTY-specific output formatting+/// - Opening browsers for authentication+fn non_interactive_cmd(program: &str) -> Cmd {+ Cmd::new(program)+ .env_remove("CLICOLOR_FORCE")+ .env_remove("GH_FORCE_TTY")+ .env("NO_COLOR", "1")+ .env("CLICOLOR", "0")+ .env("GH_PROMPT_DISABLED", "1")+}++/// Check if a CLI tool is available+///+/// On Windows, CreateProcessW (via Cmd) searches PATH for .exe files.+/// We provide .exe mocks in tests via mock-stub, so this works consistently.+fn tool_available(tool: &str, args: &[&str]) -> bool {+ Cmd::new(tool)+ .args(args.iter().copied())+ .run()+ .map(|o| o.status.success())+ .unwrap_or(false)+}++/// Parse JSON output from CLI tools+fn parse_json<T: DeserializeOwned>(stdout: &[u8], command: &str, branch: &str) -> Option<T> {+ serde_json::from_slice(stdout)+ .map_err(|e| log::warn!("Failed to parse {} JSON for {}: {}", command, branch, e))+ .ok()+}++/// Check if stderr indicates a retriable error (rate limit, network issues)+fn is_retriable_error(stderr: &str) -> bool {+ let lower = stderr.to_ascii_lowercase();+ [+ "rate limit",+ "api rate",+ "403",+ "429",+ "timeout",+ "connection",+ "network",+ ]+ .iter()+ .any(|p| lower.contains(p))+}++/// Status of CI tools availability+#[derive(Debug, Clone, Copy)]+pub struct CiToolsStatus {+ /// gh is installed (can run --version)+ pub gh_installed: bool,+ /// gh is installed and authenticated+ pub gh_authenticated: bool,+ /// glab is installed (can run --version)+ pub glab_installed: bool,+ /// glab is installed and authenticated+ pub glab_authenticated: bool,+}++impl CiToolsStatus {+ /// Check which CI tools are available+ ///+ /// If `gitlab_host` is provided, checks glab auth status against that specific+ /// host instead of the default. This is important for self-hosted GitLab instances+ /// where the default host (gitlab.com) may be unreachable.+ pub fn detect(gitlab_host: Option<&str>) -> Self {+ let gh_installed = tool_available("gh", &["--version"]);+ let gh_authenticated = gh_installed && tool_available("gh", &["auth", "status"]);+ let glab_installed = tool_available("glab", &["--version"]);+ let glab_authenticated = glab_installed+ && if let Some(host) = gitlab_host {+ tool_available("glab", &["auth", "status", "--hostname", host])+ } else {+ tool_available("glab", &["auth", "status"])+ };+ Self {+ gh_installed,+ gh_authenticated,+ glab_installed,+ glab_authenticated,+ }+ }+}++/// CI status from GitHub/GitLab checks+/// Matches the statusline.sh color scheme:+/// - Passed: Green (all checks passed)+/// - Running: Blue (checks in progress)+/// - Failed: Red (checks failed)+/// - Conflicts: Yellow (merge conflicts)+/// - NoCI: Gray (no PR/checks)+/// - Error: Yellow (CI fetch failed, e.g., rate limit)+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]+#[serde(rename_all = "kebab-case")]+#[strum(serialize_all = "kebab-case")]+pub enum CiStatus {+ Passed,+ Running,+ Failed,+ Conflicts,+ NoCI,+ /// CI status could not be fetched (rate limit, network error, etc.)+ Error,+}++/// Source of CI status+///+/// Visual distinction: Currently both PR and branch CI use ● (filled circle).+/// The internal distinction (CiSource::PullRequest vs CiSource::Branch) is preserved+/// for potential future visual differentiation. We tried ◒ (half circle) for branch CI+/// but it renders narrower than ● in many terminal fonts, causing misalignment.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, strum::IntoStaticStr)]+#[strum(serialize_all = "kebab-case")]+pub enum CiSource {+ /// Pull request or merge request+ #[serde(rename = "pr", alias = "pull-request")]+ PullRequest,+ /// Branch workflow/pipeline (no PR/MR)+ #[serde(rename = "branch")]+ Branch,+}++/// CI status from PR/MR or branch workflow+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PrStatus {+ pub ci_status: CiStatus,+ /// Source of the CI status (PR/MR or branch workflow)+ pub source: CiSource,+ /// True if local HEAD differs from remote HEAD (unpushed changes)+ pub is_stale: bool,+ /// URL to the PR/MR (if available)+ #[serde(skip_serializing_if = "Option::is_none")]+ pub url: Option<String>,+}++impl CiStatus {+ /// Get the ANSI color for this CI status.+ ///+ /// - Passed: Green+ /// - Running: Blue+ /// - Failed: Red+ /// - Conflicts: Yellow+ /// - NoCI: BrightBlack (dimmed)+ /// - Error: Yellow (warning color)+ pub fn color(&self) -> anstyle::AnsiColor {+ use anstyle::AnsiColor;+ match self {+ Self::Passed => AnsiColor::Green,+ Self::Running => AnsiColor::Blue,+ Self::Failed => AnsiColor::Red,+ Self::Conflicts | Self::Error => AnsiColor::Yellow,+ Self::NoCI => AnsiColor::BrightBlack,+ }+ }+}++impl PrStatus {+ /// Get the style for this PR status (color + optional dimming for stale)+ pub fn style(&self) -> anstyle::Style {+ use anstyle::{Color, Style};+ let style = Style::new().fg_color(Some(Color::Ansi(self.ci_status.color())));+ if self.is_stale { style.dimmed() } else { style }+ }++ /// Get the indicator symbol for this status+ ///+ /// - Error: ⚠ (overrides source indicator)+ /// - PullRequest: ● (filled circle)+ /// - Branch: ● (filled circle) — same as PR for now, see CiSource doc comment+ pub fn indicator(&self) -> &'static str {+ match self.ci_status {+ CiStatus::Error => "⚠",+ _ => match self.source {+ CiSource::PullRequest => "●",+ // Using same indicator as PR for now due to font rendering issues.+ // See CiSource doc comment for details.+ CiSource::Branch => "●",+ },+ }+ }++ /// Format CI status with control over link inclusion.+ ///+ /// When `include_link` is false, the indicator is colored but not clickable.+ /// Used for environments that don't support OSC 8 hyperlinks (e.g., Claude Code).+ pub fn format_indicator(&self, include_link: bool) -> String {+ let indicator = self.indicator();+ if include_link && self.url.is_some() {+ let url = self.url.as_ref().unwrap();+ let style = self.style().underline();+ format!(+ "{}{}{}{}{}",+ style,+ osc8::Hyperlink::new(url),+ indicator,+ osc8::Hyperlink::END,+ style.render_reset()+ )+ } else {+ let style = self.style();+ format!("{style}{indicator}{style:#}")+ }+ }++ /// Create an error status for retriable failures (rate limit, network errors)+ fn error() -> Self {+ Self {+ ci_status: CiStatus::Error,+ source: CiSource::Branch,+ is_stale: false,+ url: None,+ }+ }++ /// Detect CI status for a branch using gh/glab CLI+ /// First tries to find PR/MR status, then falls back to workflow/pipeline runs+ /// Returns None if no CI found or CLI tools unavailable+ ///+ /// # Caching+ /// Results (including None) are cached in `.git/wt-cache/ci-status/<branch>.json`+ /// for 30-60 seconds to avoid hitting GitHub API rate limits. TTL uses deterministic jitter+ /// based on repo path to spread cache expirations across concurrent statuslines. Invalidated+ /// when HEAD changes.+ ///+ /// # Fork Support+ /// Runs gh commands from the repository directory to enable auto-detection of+ /// upstream repositories for forks. This ensures PRs opened against upstream+ /// repos are properly detected.+ ///+ /// # Arguments+ /// * `has_upstream` - Whether the branch has upstream tracking configured.+ /// PR/MR detection always runs. Workflow/pipeline fallback only runs if true.+ pub fn detect(+ repo: &Repository,+ branch: &str,+ local_head: &str,+ has_upstream: bool,+ ) -> Option<Self> {+ let repo_path = repo.current_worktree().root().ok()?;++ // Check cache first to avoid hitting API rate limits+ let now_secs = get_now();++ if let Some(cached) = CachedCiStatus::read(repo, branch) {+ if cached.is_valid(local_head, now_secs, &repo_path) {+ log::debug!(+ "Using cached CI status for {} (age={}s, ttl={}s, status={:?})",+ branch,+ now_secs - cached.checked_at,+ CachedCiStatus::ttl_for_repo(&repo_path),+ cached.status.as_ref().map(|s| &s.ci_status)+ );+ return cached.status;+ }+ log::debug!(+ "Cache expired for {} (age={}s, ttl={}s, head_match={})",+ branch,+ now_secs - cached.checked_at,+ CachedCiStatus::ttl_for_repo(&repo_path),+ cached.head == local_head+ );+ }++ // Cache miss or expired - fetch fresh status+ let status = Self::detect_uncached(repo, branch, local_head, has_upstream);++ // Cache the result (including None - means no CI found for this branch)+ let cached = CachedCiStatus {+ status: status.clone(),+ checked_at: now_secs,+ head: local_head.to_string(),+ };+ cached.write(repo, branch);++ status+ }++ /// Detect CI status without caching (internal implementation)+ ///+ /// Platform is determined by project config override or remote URL detection.+ /// For unknown platforms (e.g., GitHub Enterprise with custom domains), falls back+ /// to trying both platforms.+ /// PR/MR detection always runs. Workflow/pipeline fallback only runs if `has_upstream`.+ fn detect_uncached(+ repo: &Repository,+ branch: &str,+ local_head: &str,+ has_upstream: bool,+ ) -> Option<Self> {+ // Load project config for platform override (cached in Repository)+ let project_config = repo.load_project_config().ok().flatten();+ let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());++ // Determine platform (config override or URL detection)+ let platform = get_platform_for_repo(repo, platform_override);++ match platform {+ Some(CiPlatform::GitHub) => {+ Self::detect_github_ci(repo, branch, local_head, has_upstream)+ }+ Some(CiPlatform::GitLab) => {+ Self::detect_gitlab_ci(repo, branch, local_head, has_upstream)+ }+ None => {+ // Unknown platform (e.g., GitHub Enterprise, self-hosted GitLab with custom domain)+ // Fall back to trying both platforms+ log::debug!("Could not determine CI platform, trying both");+ Self::detect_github_ci(repo, branch, local_head, has_upstream)+ .or_else(|| Self::detect_gitlab_ci(repo, branch, local_head, has_upstream))+ }+ }+ }++ /// Detect GitHub CI status (PR first, then workflow if has_upstream)+ fn detect_github_ci(+ repo: &Repository,+ branch: &str,+ local_head: &str,+ has_upstream: bool,+ ) -> Option<Self> {+ if let Some(status) = github::detect_github(repo, branch, local_head) {+ return Some(status);+ }+ if has_upstream {+ return github::detect_github_commit_checks(repo, local_head);+ }+ None+ }++ /// Detect GitLab CI status (MR first, then pipeline if has_upstream)+ fn detect_gitlab_ci(+ repo: &Repository,+ branch: &str,+ local_head: &str,+ has_upstream: bool,+ ) -> Option<Self> {+ if let Some(status) = gitlab::detect_gitlab(repo, branch, local_head) {+ return Some(status);+ }+ if has_upstream {+ return gitlab::detect_gitlab_pipeline(branch, local_head);+ }+ None+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_is_retriable_error() {+ // Rate limit errors+ assert!(is_retriable_error("API rate limit exceeded"));+ assert!(is_retriable_error("rate limit exceeded for requests"));+ assert!(is_retriable_error("Error 403: forbidden"));+ assert!(is_retriable_error("HTTP 429 Too Many Requests"));++ // Network errors+ assert!(is_retriable_error("connection timed out"));+ assert!(is_retriable_error("network error"));+ assert!(is_retriable_error("timeout waiting for response"));++ // Case insensitivity+ assert!(is_retriable_error("RATE LIMIT"));+ assert!(is_retriable_error("Connection Reset"));++ // Non-retriable errors+ assert!(!is_retriable_error("branch not found"));+ assert!(!is_retriable_error("invalid credentials"));+ assert!(!is_retriable_error("permission denied"));+ assert!(!is_retriable_error(""));+ }++ #[test]+ fn test_ci_status_color() {+ use anstyle::AnsiColor;++ assert_eq!(CiStatus::Passed.color(), AnsiColor::Green);+ assert_eq!(CiStatus::Running.color(), AnsiColor::Blue);+ assert_eq!(CiStatus::Failed.color(), AnsiColor::Red);+ assert_eq!(CiStatus::Conflicts.color(), AnsiColor::Yellow);+ assert_eq!(CiStatus::Error.color(), AnsiColor::Yellow);+ assert_eq!(CiStatus::NoCI.color(), AnsiColor::BrightBlack);+ }++ #[test]+ fn test_pr_status_indicator() {+ let pr_passed = PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: None,+ };+ assert_eq!(pr_passed.indicator(), "●");++ let branch_running = PrStatus {+ ci_status: CiStatus::Running,+ source: CiSource::Branch,+ is_stale: false,+ url: None,+ };+ assert_eq!(branch_running.indicator(), "●");++ let error_status = PrStatus {+ ci_status: CiStatus::Error,+ source: CiSource::PullRequest,+ is_stale: false,+ url: None,+ };+ assert_eq!(error_status.indicator(), "⚠");+ }++ #[test]+ fn test_format_indicator_with_url() {+ let pr_with_url = PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: Some("https://github.com/owner/repo/pull/123".to_string()),+ };++ // Call format_indicator(true) directly+ let formatted = pr_with_url.format_indicator(true);+ // Should contain OSC 8 hyperlink escape sequences+ assert!(formatted.contains("\x1b]8;;"));+ assert!(formatted.contains("https://github.com/owner/repo/pull/123"));+ assert!(formatted.contains("●"));+ }++ #[test]+ fn test_format_indicator_without_url() {+ let pr_no_url = PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: None,+ };++ // Call format_indicator(true) directly+ let formatted = pr_no_url.format_indicator(true);+ // Should NOT contain OSC 8 hyperlink+ assert!(+ !formatted.contains("\x1b]8;;"),+ "Should not contain OSC 8 sequences"+ );+ assert!(formatted.contains("●"));+ }++ #[test]+ fn test_format_indicator_skips_link() {+ // When include_link=false, should not include OSC 8 even when URL is present+ let pr_with_url = PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: Some("https://github.com/owner/repo/pull/123".to_string()),+ };++ let with_link = pr_with_url.format_indicator(true);+ let without_link = pr_with_url.format_indicator(false);++ // With link should contain OSC 8+ assert!(+ with_link.contains("\x1b]8;;"),+ "include_link=true should contain OSC 8"+ );++ // Without link should NOT contain OSC 8+ assert!(+ !without_link.contains("\x1b]8;;"),+ "include_link=false should not contain OSC 8"+ );++ // Both should contain the indicator+ assert!(with_link.contains("●"), "Should contain indicator");+ assert!(without_link.contains("●"), "Should contain indicator");+ }++ #[test]+ fn test_pr_status_error_constructor() {+ let error = PrStatus::error();+ assert_eq!(error.ci_status, CiStatus::Error);+ assert_eq!(error.source, CiSource::Branch);+ assert!(!error.is_stale);+ assert!(error.url.is_none());+ }++ #[test]+ fn test_pr_status_style_and_format() {+ let status = PrStatus {+ ci_status: CiStatus::Passed,+ source: CiSource::PullRequest,+ is_stale: false,+ url: None,+ };+ // Call format_indicator directly+ let formatted = status.format_indicator(false);+ assert!(formatted.contains("●"));++ // Stale status gets dimmed+ let stale = PrStatus {+ ci_status: CiStatus::Running,+ source: CiSource::Branch,+ is_stale: true,+ url: None,+ };+ let style = stale.style();+ // Just verify it doesn't panic and returns a style+ let _ = format!("{style}test{style:#}");+ }+}diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rsnew file mode 100644index 000000000..6f0f140e1--- /dev/null+++ b/src/commands/list/ci_status/platform.rs@@ -0,0 +1,154 @@+//! CI platform detection.+//!+//! Determines whether a repository uses GitHub or GitLab based on+//! project config override or remote URL detection.++use worktrunk::git::Repository;++/// CI platform detected from project config override or remote URL.+///+/// Platform is determined by:+/// 1. Project config `[ci] platform = "github" | "gitlab"` (takes precedence)+/// 2. Remote URL detection (searches for "github" or "gitlab" in URL)+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]+#[strum(serialize_all = "lowercase")]+pub enum CiPlatform {+ GitHub,+ GitLab,+}++/// Detect the CI platform from a remote URL by searching for "github" or "gitlab".+pub fn detect_platform_from_url(url: &str) -> Option<CiPlatform> {+ let url_lower = url.to_ascii_lowercase();+ if url_lower.contains("github") {+ Some(CiPlatform::GitHub)+ } else if url_lower.contains("gitlab") {+ Some(CiPlatform::GitLab)+ } else {+ None+ }+}++/// Get the CI platform for a repository.+///+/// If `platform_override` is provided (from project config `[ci] platform`),+/// uses that value directly. Otherwise, detects platform from the primary+/// remote URL.+pub fn get_platform_for_repo(+ repo: &Repository,+ platform_override: Option<&str>,+) -> Option<CiPlatform> {+ // Config override takes precedence+ if let Some(platform_str) = platform_override {+ if let Ok(platform) = platform_str.parse::<CiPlatform>() {+ log::debug!("Using CI platform from config override: {}", platform);+ return Some(platform);+ }+ log::warn!(+ "Invalid CI platform in config: '{}'. Expected 'github' or 'gitlab'.",+ platform_str+ );+ }++ // Fall back to URL detection+ let url = repo.primary_remote_url()?;+ detect_platform_from_url(&url)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_detect_platform_from_url() {+ // GitHub - various URL formats+ assert_eq!(+ detect_platform_from_url("https://github.com/owner/repo.git"),+ Some(CiPlatform::GitHub)+ );+ assert_eq!(+ detect_platform_from_url("[email protected]:owner/repo.git"),+ Some(CiPlatform::GitHub)+ );+ assert_eq!(+ detect_platform_from_url("ssh://[email protected]/owner/repo.git"),+ Some(CiPlatform::GitHub)+ );++ // GitHub Enterprise+ assert_eq!(+ detect_platform_from_url("https://github.mycompany.com/owner/repo.git"),+ Some(CiPlatform::GitHub)+ );++ // GitLab - various URL formats+ assert_eq!(+ detect_platform_from_url("https://gitlab.com/owner/repo.git"),+ Some(CiPlatform::GitLab)+ );+ assert_eq!(+ detect_platform_from_url("[email protected]:owner/repo.git"),+ Some(CiPlatform::GitLab)+ );++ // Self-hosted GitLab+ assert_eq!(+ detect_platform_from_url("https://gitlab.example.com/owner/repo.git"),+ Some(CiPlatform::GitLab)+ );++ // Legacy schemes (http://, git://) - common on self-hosted installations+ assert_eq!(+ detect_platform_from_url("http://github.com/owner/repo.git"),+ Some(CiPlatform::GitHub)+ );+ assert_eq!(+ detect_platform_from_url("git://github.com/owner/repo.git"),+ Some(CiPlatform::GitHub)+ );+ assert_eq!(+ detect_platform_from_url("http://gitlab.example.com/owner/repo.git"),+ Some(CiPlatform::GitLab)+ );+ assert_eq!(+ detect_platform_from_url("git://gitlab.mycompany.com/owner/repo.git"),+ Some(CiPlatform::GitLab)+ );++ // Unknown platforms+ assert_eq!(+ detect_platform_from_url("https://bitbucket.org/owner/repo.git"),+ None+ );+ assert_eq!(+ detect_platform_from_url("https://codeberg.org/owner/repo.git"),+ None+ );+ }++ #[test]+ fn test_platform_override_github() {+ // Config override should take precedence over URL detection+ assert_eq!(+ "github".parse::<CiPlatform>().ok(),+ Some(CiPlatform::GitHub)+ );+ }++ #[test]+ fn test_platform_override_gitlab() {+ // Config override should take precedence over URL detection+ assert_eq!(+ "gitlab".parse::<CiPlatform>().ok(),+ Some(CiPlatform::GitLab)+ );+ }++ #[test]+ fn test_platform_override_invalid() {+ // Invalid platform strings should not parse+ assert!("invalid".parse::<CiPlatform>().is_err());+ assert!("GITHUB".parse::<CiPlatform>().is_err()); // Case-sensitive+ assert!("GitHub".parse::<CiPlatform>().is_err()); // Case-sensitive+ }+}diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsdeleted file mode 100644index f188dc801..000000000--- a/src/commands/list/collect.rs+++ /dev/null@@ -1,2639 +0,0 @@-//! Worktree data collection with parallelized git operations.-//!-//! This module provides an efficient approach to collecting worktree data:-//! - All tasks flattened into a single Rayon work queue-//! - Network tasks (CI, URL) sorted to run last-//! - Progressive updates via channels (update UI as each task completes)-//!-//! ## Skeleton Performance-//!-//! The skeleton (placeholder table with loading indicators) must render as fast as possible-//! to give users immediate feedback. Every git command before skeleton adds latency.-//!-//! ### Fixed Command Count (O(1), not O(N))-//!-//! Pre-skeleton runs a **fixed number of git commands** regardless of worktree count.-//! This is achieved through:-//! - **Batching** — timestamp fetch passes all SHAs to one `git show` command-//! - **Parallelization** — independent commands run concurrently via `join!` macro-//!-//! **Steady-state (5-7 commands):**-//!-//! | Command | Purpose | Parallel |-//! |---------|---------|----------|-//! | `git worktree list --porcelain` | Enumerate worktrees | Sequential (required first) |-//! | `git config worktrunk.default-branch` | Cached default branch | ✓ |-//! | `git config --bool core.bare` | Bare repo check for expected-path logic | ✓ |-//! | `git rev-parse --show-toplevel` | Worktree root for project config | ✓ |-//! | `git for-each-ref refs/heads` | Only with `--branches` flag | ✓ |-//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag | ✓ |-//! | `git show -s --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |-//!-//! **Non-git operations (negligible latency):**-//! - Path canonicalization — detect current worktree-//! - Project config file read — check if URL column needed (no template expansion)-//!-//! ### First-Run Behavior-//!-//! When `worktrunk.default-branch` is not cached, `default_branch()` runs additional-//! commands to detect it:-//! 1. Query primary remote (origin/HEAD or `git ls-remote`)-//! 2. Fall back to local inference (check init.defaultBranch, common names)-//! 3. Cache result to `git config worktrunk.default-branch`-//!-//! Subsequent runs use the cached value — only one `git config` call.-//!-//! ### Post-Skeleton Operations-//!-//! After the skeleton renders, remaining setup runs before spawning the worker thread.-//! These operations are parallelized using `rayon::scope` with single-level parallelism:-//!-//! ```text-//! Skeleton render-//! ├─ is_builtin_fsmonitor_enabled() (5ms, sequential - gate)-//! ├─ rayon::scope(-//! │ ├─ get_switch_previous() (5ms)-//! │ ├─ integration_target() (10ms)-//! │ ├─ start_fsmonitor_daemon × N worktrees (6ms each, all parallel)-//! │ ) // ~10ms total (max of all spawns)-//! Worker thread spawns-//! ```-//!-//! **Why fsmonitor check is sequential:** It gates whether daemon starts are needed.-//! The check is fast (~5ms) and must complete before we know which spawns to add.-//!-//! **Why fsmonitor starts are in the parallel scope:** The `git fsmonitor--daemon start`-//! command returns quickly after signaling the daemon. By the time the worker thread-//! starts executing `git status` commands, daemons have had time to initialize.-//!-//! **Invalid default branch warning:** `invalid_default_branch_config()` reads the value-//! cached by `default_branch()` during pre-skeleton. It's a pure cache read.-//!-//! When adding new features, ask: "Can this be computed after skeleton?" If yes, defer it.-//! The skeleton shows `·` placeholder for gutter symbols, filled in when data loads.-//!-//! ## Unified Collection Architecture-//!-//! Progressive and buffered modes use the same collection and rendering code.-//! The only difference is whether intermediate updates are shown during collection:-//! - Progressive: renders a skeleton table and updates rows/footer as data arrives (TTY),-//! or renders once at the end (non-TTY)-//! - Buffered: collects silently, then renders the final table-//!-//! Both modes render the final table in `collect()`, ensuring a single canonical rendering path.-//!-//! **Flat parallelism**: All tasks (for all worktrees and branches) are collected into a single-//! work queue and processed via Rayon's thread pool. This avoids nested parallelism and keeps-//! utilization high regardless of worktree count (pool size is set at startup; default is 2x CPU-//! cores unless `RAYON_NUM_THREADS` is set).-//!-//! **Task ordering**: Work items are sorted so local git operations run first, network tasks-//! (CI status, URL health checks) run last. This ensures the table fills in quickly with local-//! data while slower network requests complete in the background.-use anyhow::Context;-use color_print::cformat;-use crossbeam_channel as chan;-use dunce::canonicalize;-use once_cell::sync::OnceCell;-use rayon::prelude::*;-use std::sync::Arc;-use worktrunk::git::{BranchRef, LineDiff, Repository, WorktreeInfo};-use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, warning_message};--use crate::commands::is_worktree_at_expected_path;--use super::ci_status::PrStatus;-use super::model::{- AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields, GitOperationState, ItemKind,- ListItem, UpstreamStatus, WorktreeData,-};--use super::model::WorkingTreeStatus;--/// Context for status symbol computation during result processing-#[derive(Clone, Default)]-struct StatusContext {- has_merge_tree_conflicts: bool,- /// Working tree conflict check result (--full only, worktrees only).- /// None = use commit check (task didn't run or working tree clean)- /// Some(b) = dirty working tree, b is conflict result- // TODO: If we need to distinguish "task didn't run" from "clean working tree",- // expand to an enum. Currently both cases fall back to commit-based check.- has_working_tree_conflicts: Option<bool>,- user_marker: Option<String>,- working_tree_status: Option<WorkingTreeStatus>,- has_conflicts: bool,-}--impl StatusContext {- fn apply_to(&self, item: &mut ListItem, target: &str) {- // Main worktree case is handled inside check_integration_state()- //- // Prefer working tree conflicts (--full) when available.- // None means task didn't run or working tree was clean - use commit check.- let has_conflicts = self- .has_working_tree_conflicts- .unwrap_or(self.has_merge_tree_conflicts);-- item.compute_status_symbols(- Some(target),- has_conflicts,- self.user_marker.clone(),- self.working_tree_status,- self.has_conflicts,- );- }-}--/// Task results sent as each git operation completes.-/// These enable progressive rendering - update UI as data arrives.-///-/// Each spawned task produces exactly one TaskResult. Multiple results-/// may feed into a single table column, and one result may feed multiple-/// columns. See `drain_results()` for how results map to ListItem fields.-///-/// The `EnumDiscriminants` derive generates a companion `TaskKind` enum-/// with the same variants but no payloads, used for type-safe tracking-/// of expected vs received results.-#[derive(Debug, Clone, strum::EnumDiscriminants)]-#[strum_discriminants(- name(TaskKind),- vis(pub),- derive(Hash, Ord, PartialOrd, strum::IntoStaticStr),- strum(serialize_all = "kebab-case")-)]-pub(crate) enum TaskResult {- /// Commit timestamp and message- CommitDetails {- item_idx: usize,- commit: CommitDetails,- },- /// Ahead/behind counts vs default branch- AheadBehind {- item_idx: usize,- counts: AheadBehind,- /// True if this is an orphan branch (no common ancestor with default branch)- is_orphan: bool,- },- /// Whether HEAD's tree SHA matches integration target's tree SHA (committed content identical)- CommittedTreesMatch {- item_idx: usize,- committed_trees_match: bool,- },- /// Whether branch has file changes beyond the merge-base with integration target (three-dot diff)- HasFileChanges {- item_idx: usize,- has_file_changes: bool,- },- /// Whether merging branch into integration target would add changes (merge simulation)- WouldMergeAdd {- item_idx: usize,- would_merge_add: bool,- },- /// Whether branch HEAD is ancestor of integration target (same commit or already merged)- IsAncestor { item_idx: usize, is_ancestor: bool },- /// Line diff vs default branch- BranchDiff {- item_idx: usize,- branch_diff: BranchDiffTotals,- },- /// Working tree diff and status- WorkingTreeDiff {- item_idx: usize,- working_tree_diff: LineDiff,- /// Working tree change flags- working_tree_status: WorkingTreeStatus,- has_conflicts: bool,- },- /// Potential merge conflicts with default branch (merge-tree simulation on committed HEAD)- MergeTreeConflicts {- item_idx: usize,- has_merge_tree_conflicts: bool,- },- /// Potential merge conflicts including working tree changes (--full only)- ///- /// For dirty worktrees, uses `git stash create` to get a tree object that- /// includes uncommitted changes, then runs merge-tree against that.- /// Returns None if working tree is clean (fall back to MergeTreeConflicts).- WorkingTreeConflicts {- item_idx: usize,- /// None = working tree clean (use MergeTreeConflicts result)- /// Some(true) = dirty working tree would conflict- /// Some(false) = dirty working tree would not conflict- has_working_tree_conflicts: Option<bool>,- },- /// Git operation in progress (rebase/merge)- GitOperation {- item_idx: usize,- git_operation: GitOperationState,- },- /// User-defined status from git config- UserMarker {- item_idx: usize,- user_marker: Option<String>,- },- /// Upstream tracking status- Upstream {- item_idx: usize,- upstream: UpstreamStatus,- },- /// CI/PR status (slow operation)- CiStatus {- item_idx: usize,- pr_status: Option<PrStatus>,- },- /// URL status (expanded URL and health check result)- UrlStatus {- item_idx: usize,- /// Expanded URL from template (None if no template or no branch)- url: Option<String>,- /// Whether the port is listening (None if no URL or couldn't parse port)- active: Option<bool>,- },-}--impl TaskResult {- /// Get the item index for this result- fn item_idx(&self) -> usize {- match self {- TaskResult::CommitDetails { item_idx, .. }- | TaskResult::AheadBehind { item_idx, .. }- | TaskResult::CommittedTreesMatch { item_idx, .. }- | TaskResult::HasFileChanges { item_idx, .. }- | TaskResult::WouldMergeAdd { item_idx, .. }- | TaskResult::IsAncestor { item_idx, .. }- | TaskResult::BranchDiff { item_idx, .. }- | TaskResult::WorkingTreeDiff { item_idx, .. }- | TaskResult::MergeTreeConflicts { item_idx, .. }- | TaskResult::WorkingTreeConflicts { item_idx, .. }- | TaskResult::GitOperation { item_idx, .. }- | TaskResult::UserMarker { item_idx, .. }- | TaskResult::Upstream { item_idx, .. }- | TaskResult::CiStatus { item_idx, .. }- | TaskResult::UrlStatus { item_idx, .. } => *item_idx,- }- }-}--impl TaskKind {- /// Whether this task requires network access.- ///- /// Network tasks are sorted to run last to avoid blocking local tasks.- pub fn is_network(self) -> bool {- matches!(self, TaskKind::CiStatus | TaskKind::UrlStatus)- }-}--/// Detect if a worktree is in the middle of a git operation (rebase/merge).-pub(crate) fn detect_git_operation(wt: &worktrunk::git::WorkingTree<'_>) -> GitOperationState {- if wt.is_rebasing().unwrap_or(false) {- GitOperationState::Rebase- } else if wt.is_merging().unwrap_or(false) {- GitOperationState::Merge- } else {- GitOperationState::None- }-}--/// Result of draining task results - indicates whether all results were received-/// or if a timeout occurred.-#[derive(Debug)]-enum DrainOutcome {- /// All results received (channel closed normally)- Complete,- /// Timeout occurred - contains diagnostic info about what was received- TimedOut {- /// Number of task results received before timeout- received_count: usize,- /// Items with missing results- items_with_missing: Vec<MissingResult>,- },-}--/// Item with missing task results (for timeout diagnostics)-#[derive(Debug)]-struct MissingResult {- item_idx: usize,- name: String,- missing_kinds: Vec<TaskKind>,-}--/// Cause of a task error.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum ErrorCause {- /// Command exceeded the configured timeout.- Timeout,- /// Any other error (permission denied, git error, etc.).- Other,-}--/// Error during task execution.-///-/// Tasks return this instead of swallowing errors. The drain layer-/// applies defaults and collects errors for display after rendering.-#[derive(Debug, Clone)]-pub struct TaskError {- pub item_idx: usize,- pub kind: TaskKind,- pub message: String,- /// What caused this error. Use `is_timeout()` to check.- cause: ErrorCause,-}--impl TaskError {- pub fn new(- item_idx: usize,- kind: TaskKind,- message: impl Into<String>,- cause: ErrorCause,- ) -> Self {- Self {- item_idx,- kind,- message: message.into(),- cause,- }- }-- /// Whether this error was caused by a timeout.- pub fn is_timeout(&self) -> bool {- self.cause == ErrorCause::Timeout- }-}--/// Tracks expected result types per item for timeout diagnostics.-///-/// Populated at spawn time so we know exactly which results to expect,-/// without hardcoding result lists that could drift from the spawn functions.-#[derive(Default)]-pub(crate) struct ExpectedResults {- inner: std::sync::Mutex<Vec<Vec<TaskKind>>>,-}--impl ExpectedResults {- /// Record that we expect a result of the given kind for the given item.- /// Called internally by `TaskSpawner::spawn()`.- pub fn expect(&self, item_idx: usize, kind: TaskKind) {- let mut inner = self.inner.lock().unwrap();- if inner.len() <= item_idx {- inner.resize_with(item_idx + 1, Vec::new);- }- inner[item_idx].push(kind);- }-- /// Total number of expected results (for progress display).- pub fn count(&self) -> usize {- self.inner.lock().unwrap().iter().map(|v| v.len()).sum()- }-- /// Expected results for a specific item.- fn results_for(&self, item_idx: usize) -> Vec<TaskKind> {- self.inner- .lock()- .unwrap()- .get(item_idx)- .cloned()- .unwrap_or_default()- }-}--// ============================================================================-// Task Framework (merged from collect_progressive_impl.rs)-// ============================================================================--// ============================================================================-// Options and Context-// ============================================================================--/// Options for controlling what data to collect.-///-/// This is operation parameters for a single `wt list` invocation, not a cache.-/// For cached repo data, see Repository's global cache.-#[derive(Clone, Default)]-pub struct CollectOptions {- /// Tasks to skip (not compute). Empty set means compute everything.- ///- /// This controls both:- /// - Work item generation (in `work_items_for_worktree`/`work_items_for_branch`)- /// - Column visibility (layout filters columns via `ColumnSpec::requires_task`)- pub skip_tasks: std::collections::HashSet<TaskKind>,-- /// URL template from project config (e.g., "http://localhost:{{ branch | hash_port }}").- /// Expanded per-item in task spawning (post-skeleton) to minimize time-to-skeleton.- pub url_template: Option<String>,-- /// Branches to skip expensive tasks for (behind > threshold).- ///- /// Presence in set = skip expensive tasks for this branch (HasFileChanges,- /// IsAncestor, WouldMergeAdd, BranchDiff, MergeTreeConflicts).- ///- /// ## Why "commits behind" as the heuristic- ///- /// The expensive operations (`git merge-tree`, `git diff`) scale with:- /// - **Files changed on both sides** — each needs 3-way merge or diff- /// - **Size of those files** — content loading and merge algorithm- ///- /// Commit count isn't directly in the algorithm, but "commits behind" is a- /// cheap proxy: more commits on main since divergence → more files main has- /// touched → more potential overlap with the branch's changes.- ///- /// We use "behind" rather than "ahead" because feature branches typically- /// have small ahead counts, so behind dominates. A more accurate heuristic- /// would be `min(files_changed_on_main, files_changed_on_branch)`, but- /// computing that requires per-branch git commands, defeating the optimization.- ///- /// The batch `git for-each-ref --format='%(ahead-behind:...)'` gives us all- /// counts in a single command, making this heuristic essentially free.- ///- /// ## Implementation- ///- /// Built by filtering `batch_ahead_behind()` results on local branches only.- /// Remote-only branches are never in this set (they use individual git commands).- /// The threshold (default 50) is applied at construction time. Ahead/behind- /// counts are cached in Repository and looked up by AheadBehindTask.- ///- /// **Display implications:** When tasks are skipped:- /// - BranchDiff column shows `…` instead of diff stats- /// - Status symbols (conflict `✗`, integrated `⊂`) may be missing or incorrect- /// since they depend on skipped tasks- ///- /// Note: `wt select` doesn't show the BranchDiff column, so `…` isn't visible there.- /// This is similar to how `✗` conflict only shows with `--full` even in `wt list`.- ///- /// TODO: Consider adding a visible indicator in Status column when integration- /// checks are skipped, so users know the `⊂` symbol may be incomplete.- pub stale_branches: std::collections::HashSet<String>,-}--/// Context for task computation. Cloned and moved into spawned threads.-///-/// Contains all data needed by any task. The `repo` field shares its cache-/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from-/// cached merge-base results, ahead/behind counts, default branch, and-/// integration target.-#[derive(Clone)]-pub struct TaskContext {- /// Shared repository handle. All clones share the same cache via Arc.- pub repo: Repository,- /// The branch this task operates on. Contains branch name, commit SHA,- /// and optional worktree path.- ///- /// For worktree-specific operations, use `self.worktree()` which returns- /// `Some(WorkingTree)` only when this ref has a worktree path.- pub branch_ref: BranchRef,- pub item_idx: usize,- /// Expanded URL for this item (from project config template).- /// UrlStatusTask uses this to check if the port is listening.- pub item_url: Option<String>,-}--impl TaskContext {- fn error(&self, kind: TaskKind, err: &anyhow::Error) -> TaskError {- // Check if any error in the chain is a timeout- let is_timeout = err.chain().any(|e| {- e.downcast_ref::<std::io::Error>()- .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::TimedOut)- });-- let cause = if is_timeout {- let kind_str: &'static str = kind.into();- let sha = &self.branch_ref.commit_sha;- let short_sha = &sha[..sha.len().min(8)];- let branch = self.branch_ref.branch.as_deref().unwrap_or(short_sha);- log::debug!("Task {} timed out for {}", kind_str, branch);- ErrorCause::Timeout- } else {- ErrorCause::Other- };- TaskError::new(self.item_idx, kind, err.to_string(), cause)- }-- /// Get the default branch (cached in Repository).- ///- /// Used for informational stats (ahead/behind, branch diff).- /// Returns None if default branch cannot be determined.- fn default_branch(&self) -> Option<String> {- self.repo.default_branch()- }-- /// Get the integration target (cached in Repository).- ///- /// Used for integration checks (status symbols, safe deletion).- /// Returns None if default branch cannot be determined.- fn integration_target(&self) -> Option<String> {- self.repo.integration_target()- }-}--// ============================================================================-// Task Trait and Spawner-// ============================================================================--/// A task that computes a single `TaskResult`.-///-/// Each task type has a compile-time `KIND` that determines which `TaskResult`-/// variant it produces. The `compute()` function receives a cloned context and-/// returns a Result - either the successful result or an error.-///-/// Tasks should propagate errors via `?` rather than swallowing them.-/// The drain layer handles defaults and collects errors for display.-pub trait Task: Send + Sync + 'static {- /// The kind of result this task produces (compile-time constant).- const KIND: TaskKind;-- /// Compute the task result. Called in a spawned thread.- /// Returns Ok(result) on success, Err(TaskError) on failure.- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError>;-}--// ============================================================================-// Work Item Dispatch (for flat parallelism)-// ============================================================================--/// A unit of work for the thread pool.-///-/// Each work item represents a single task to be executed. Work items are-/// collected upfront and then processed in parallel via Rayon's thread pool,-/// avoiding nested parallelism (Rayon par_iter → thread::scope).-#[derive(Clone)]-pub struct WorkItem {- pub ctx: TaskContext,- pub kind: TaskKind,-}--impl WorkItem {- /// Execute this work item, returning the task result.- pub fn execute(self) -> Result<TaskResult, TaskError> {- let result = dispatch_task(self.kind, self.ctx);- if let Ok(ref task_result) = result {- debug_assert_eq!(TaskKind::from(task_result), self.kind);- }- result- }-}--/// Dispatch a task by kind, calling the appropriate Task::compute().-fn dispatch_task(kind: TaskKind, ctx: TaskContext) -> Result<TaskResult, TaskError> {- match kind {- TaskKind::CommitDetails => CommitDetailsTask::compute(ctx),- TaskKind::AheadBehind => AheadBehindTask::compute(ctx),- TaskKind::CommittedTreesMatch => CommittedTreesMatchTask::compute(ctx),- TaskKind::HasFileChanges => HasFileChangesTask::compute(ctx),- TaskKind::WouldMergeAdd => WouldMergeAddTask::compute(ctx),- TaskKind::IsAncestor => IsAncestorTask::compute(ctx),- TaskKind::BranchDiff => BranchDiffTask::compute(ctx),- TaskKind::WorkingTreeDiff => WorkingTreeDiffTask::compute(ctx),- TaskKind::MergeTreeConflicts => MergeTreeConflictsTask::compute(ctx),- TaskKind::WorkingTreeConflicts => WorkingTreeConflictsTask::compute(ctx),- TaskKind::GitOperation => GitOperationTask::compute(ctx),- TaskKind::UserMarker => UserMarkerTask::compute(ctx),- TaskKind::Upstream => UpstreamTask::compute(ctx),- TaskKind::CiStatus => CiStatusTask::compute(ctx),- TaskKind::UrlStatus => UrlStatusTask::compute(ctx),- }-}--// Tasks that are expensive because they require merge-base computation or merge simulation.-// These are skipped for branches that are far behind the default branch (in wt select).-// AheadBehind is NOT here - we use batch data for it instead of skipping.-// CommittedTreesMatch is NOT here - it's a cheap tree comparison that aids integration detection.-const EXPENSIVE_TASKS: &[TaskKind] = &[- TaskKind::HasFileChanges, // git diff with three-dot range- TaskKind::IsAncestor, // git merge-base --is-ancestor- TaskKind::WouldMergeAdd, // git merge-tree simulation- TaskKind::BranchDiff, // git diff with three-dot range- TaskKind::MergeTreeConflicts, // git merge-tree simulation-];--/// Generate work items for a worktree.-///-/// Returns a list of work items representing all tasks that should run for this-/// worktree. Expected results are registered internally as each work item is added.-/// The caller is responsible for executing the work items.-///-/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.-pub fn work_items_for_worktree(- repo: &Repository,- wt: &WorktreeInfo,- item_idx: usize,- options: &CollectOptions,- expected_results: &Arc<ExpectedResults>,- tx: &chan::Sender<Result<TaskResult, TaskError>>,-) -> Vec<WorkItem> {- // Skip git operations for prunable worktrees (directory missing).- if wt.is_prunable() {- return vec![];- }-- let skip = &options.skip_tasks;-- // Expand URL template for this item- let item_url = options.url_template.as_ref().and_then(|template| {- wt.branch.as_ref().and_then(|branch| {- let mut vars = std::collections::HashMap::new();- vars.insert("branch", branch.as_str());- worktrunk::config::expand_template(template, &vars, false, repo).ok()- })- });-- // Send URL immediately (before health check) so it appears right away.- // The UrlStatusTask will later update with active status.- if let Some(ref url) = item_url {- expected_results.expect(item_idx, TaskKind::UrlStatus);- let _ = tx.send(Ok(TaskResult::UrlStatus {- item_idx,- url: Some(url.clone()),- active: None,- }));- }-- let ctx = TaskContext {- repo: repo.clone(),- branch_ref: BranchRef::from(wt),- item_idx,- item_url,- };-- // Check if this branch is stale and should skip expensive tasks.- let is_stale = wt- .branch- .as_deref()- .is_some_and(|b| options.stale_branches.contains(b));-- let mut items = Vec::with_capacity(15);-- // Helper to add a work item and register the expected result- let mut add_item = |kind: TaskKind| {- expected_results.expect(item_idx, kind);- items.push(WorkItem {- ctx: ctx.clone(),- kind,- });- };-- for kind in [- TaskKind::CommitDetails,- TaskKind::AheadBehind,- TaskKind::CommittedTreesMatch,- TaskKind::HasFileChanges,- TaskKind::IsAncestor,- TaskKind::Upstream,- TaskKind::WorkingTreeDiff,- TaskKind::GitOperation,- TaskKind::UserMarker,- TaskKind::WorkingTreeConflicts,- TaskKind::BranchDiff,- TaskKind::MergeTreeConflicts,- TaskKind::CiStatus,- TaskKind::WouldMergeAdd,- ] {- if skip.contains(&kind) {- continue;- }- // Skip expensive tasks for stale branches (far behind default branch)- if is_stale && EXPENSIVE_TASKS.contains(&kind) {- continue;- }- add_item(kind);- }- // URL status health check task (if we have a URL).- // Note: We already registered and sent an immediate UrlStatus above with url + active=None.- // This work item will send a second UrlStatus with active=Some(bool) after health check.- // Both results must be registered and expected.- if !skip.contains(&TaskKind::UrlStatus) && ctx.item_url.is_some() {- expected_results.expect(item_idx, TaskKind::UrlStatus);- items.push(WorkItem {- ctx: ctx.clone(),- kind: TaskKind::UrlStatus,- });- }-- items-}--/// Generate work items for a branch (no worktree).-///-/// Returns a list of work items representing all tasks that should run for this-/// branch. Branches have fewer tasks than worktrees (no working tree operations).-///-/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.-pub fn work_items_for_branch(- repo: &Repository,- branch_name: &str,- commit_sha: &str,- item_idx: usize,- options: &CollectOptions,- expected_results: &Arc<ExpectedResults>,-) -> Vec<WorkItem> {- let skip = &options.skip_tasks;-- let ctx = TaskContext {- repo: repo.clone(),- branch_ref: BranchRef::branch_only(branch_name, commit_sha),- item_idx,- item_url: None, // Branches without worktrees don't have URLs- };-- // Check if this branch is stale and should skip expensive tasks.- let is_stale = options.stale_branches.contains(branch_name);-- let mut items = Vec::with_capacity(11);-- // Helper to add a work item and register the expected result- let mut add_item = |kind: TaskKind| {- expected_results.expect(item_idx, kind);- items.push(WorkItem {- ctx: ctx.clone(),- kind,- });- };-- for kind in [- TaskKind::CommitDetails,- TaskKind::AheadBehind,- TaskKind::CommittedTreesMatch,- TaskKind::HasFileChanges,- TaskKind::IsAncestor,- TaskKind::Upstream,- TaskKind::BranchDiff,- TaskKind::MergeTreeConflicts,- TaskKind::CiStatus,- TaskKind::WouldMergeAdd,- ] {- if skip.contains(&kind) {- continue;- }- // Skip expensive tasks for stale branches (far behind default branch)- if is_stale && EXPENSIVE_TASKS.contains(&kind) {- continue;- }- add_item(kind);- }-- items-}--// ============================================================================-// Task Implementations-// ============================================================================--/// Task 1: Commit details (timestamp, message)-pub struct CommitDetailsTask;--impl Task for CommitDetailsTask {- const KIND: TaskKind = TaskKind::CommitDetails;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;- let (timestamp, commit_message) = repo- .commit_details(&ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::CommitDetails {- item_idx: ctx.item_idx,- commit: CommitDetails {- timestamp,- commit_message,- },- })- }-}--/// Task 2: Ahead/behind counts vs local default branch (informational stats)-pub struct AheadBehindTask;--impl Task for AheadBehindTask {- const KIND: TaskKind = TaskKind::AheadBehind;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return zero counts (cells show empty)- let Some(base) = ctx.default_branch() else {- return Ok(TaskResult::AheadBehind {- item_idx: ctx.item_idx,- counts: AheadBehind::default(),- is_orphan: false,- });- };- let repo = &ctx.repo;-- // Check for orphan branch (no common ancestor with default branch).- // merge_base() is cached, so this is cheap after first call.- let is_orphan = repo- .merge_base(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?- .is_none();-- if is_orphan {- return Ok(TaskResult::AheadBehind {- item_idx: ctx.item_idx,- counts: AheadBehind::default(),- is_orphan: true,- });- }-- // Check cache first (populated by batch_ahead_behind if it ran).- // Cache lookup has minor overhead (rev-parse for cache key + allocations),- // but saves the expensive ahead_behind computation on cache hit.- let (ahead, behind) = if let Some(branch) = ctx.branch_ref.branch.as_deref() {- if let Some(counts) = repo.get_cached_ahead_behind(&base, branch) {- counts- } else {- repo.ahead_behind(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?- }- } else {- repo.ahead_behind(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?- };-- Ok(TaskResult::AheadBehind {- item_idx: ctx.item_idx,- counts: AheadBehind { ahead, behind },- is_orphan: false,- })- }-}--/// Task 3: Tree identity check (does the item's commit tree match integration target's tree?)-///-/// Uses target for integration detection (squash merge, rebase).-pub struct CommittedTreesMatchTask;--impl Task for CommittedTreesMatchTask {- const KIND: TaskKind = TaskKind::CommittedTreesMatch;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When integration_target is None, return false (conservative: don't mark as integrated)- let Some(base) = ctx.integration_target() else {- return Ok(TaskResult::CommittedTreesMatch {- item_idx: ctx.item_idx,- committed_trees_match: false,- });- };- let repo = &ctx.repo;- // Use the item's commit instead of HEAD, since for branches without- // worktrees, HEAD is the main worktree's HEAD.- let committed_trees_match = repo- .trees_match(&ctx.branch_ref.commit_sha, &base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::CommittedTreesMatch {- item_idx: ctx.item_idx,- committed_trees_match,- })- }-}--/// Task 3b: File changes check (does branch have file changes beyond merge-base?)-///-/// Uses three-dot diff (`target...branch`) to detect if the branch has any file-/// changes relative to the merge-base with target. Returns false when the diff-/// is empty, indicating the branch content is already integrated.-///-/// This catches branches where commits exist (ahead > 0) but those commits-/// don't add any file changes - e.g., squash-merged branches, merge commits-/// that pulled in main, or commits whose changes were reverted.-///-/// Uses target for integration detection.-pub struct HasFileChangesTask;--impl Task for HasFileChangesTask {- const KIND: TaskKind = TaskKind::HasFileChanges;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // No branch name (detached HEAD) - return conservative default (assume has changes)- let Some(branch) = ctx.branch_ref.branch.as_deref() else {- return Ok(TaskResult::HasFileChanges {- item_idx: ctx.item_idx,- has_file_changes: true,- });- };- // When integration_target is None, return true (conservative: assume has changes)- let Some(target) = ctx.integration_target() else {- return Ok(TaskResult::HasFileChanges {- item_idx: ctx.item_idx,- has_file_changes: true,- });- };- let repo = &ctx.repo;- let has_file_changes = repo- .has_added_changes(branch, &target)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::HasFileChanges {- item_idx: ctx.item_idx,- has_file_changes,- })- }-}--/// Task 3b: Merge simulation-///-/// Checks if merging the branch into target would add any changes by simulating-/// the merge with `git merge-tree --write-tree`. Returns false when the merge-/// result equals target's tree, indicating the branch is already integrated.-///-/// This catches branches where target has advanced past the squash-merge point --/// the three-dot diff might show changes, but those changes are already in target-/// via the squash merge.-///-/// Uses target for integration detection.-pub struct WouldMergeAddTask;--impl Task for WouldMergeAddTask {- const KIND: TaskKind = TaskKind::WouldMergeAdd;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // No branch name (detached HEAD) - return conservative default (assume would add)- let Some(branch) = ctx.branch_ref.branch.as_deref() else {- return Ok(TaskResult::WouldMergeAdd {- item_idx: ctx.item_idx,- would_merge_add: true,- });- };- // When integration_target is None, return true (conservative: assume would add)- let Some(base) = ctx.integration_target() else {- return Ok(TaskResult::WouldMergeAdd {- item_idx: ctx.item_idx,- would_merge_add: true,- });- };- let repo = &ctx.repo;- let would_merge_add = repo- .would_merge_add_to_target(branch, &base)- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::WouldMergeAdd {- item_idx: ctx.item_idx,- would_merge_add,- })- }-}--/// Task 3c: Ancestor check (is branch HEAD an ancestor of integration target?)-///-/// Checks if branch is an ancestor of target - runs `git merge-base --is-ancestor`.-/// Returns true when the branch HEAD is in target's history (merged via fast-forward-/// or rebase).-///-/// Uses target (target) for the Ancestor integration reason in `⊂`.-/// The `_` symbol uses ahead/behind counts (vs default_branch) instead.-pub struct IsAncestorTask;--impl Task for IsAncestorTask {- const KIND: TaskKind = TaskKind::IsAncestor;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When integration_target is None, return false (conservative: don't mark as ancestor)- let Some(base) = ctx.integration_target() else {- return Ok(TaskResult::IsAncestor {- item_idx: ctx.item_idx,- is_ancestor: false,- });- };- let repo = &ctx.repo;- let is_ancestor = repo- .is_ancestor(&ctx.branch_ref.commit_sha, &base)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::IsAncestor {- item_idx: ctx.item_idx,- is_ancestor,- })- }-}--/// Task 4: Branch diff stats vs local default branch (informational stats)-pub struct BranchDiffTask;--impl Task for BranchDiffTask {- const KIND: TaskKind = TaskKind::BranchDiff;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return empty diff (cells show empty)- let Some(base) = ctx.default_branch() else {- return Ok(TaskResult::BranchDiff {- item_idx: ctx.item_idx,- branch_diff: BranchDiffTotals::default(),- });- };- let repo = &ctx.repo;- let diff = repo- .branch_diff_stats(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::BranchDiff {- item_idx: ctx.item_idx,- branch_diff: BranchDiffTotals { diff },- })- }-}--/// Task 5 (worktree only): Working tree diff + status flags-///-/// Runs `git status --porcelain` to get working tree status and computes diff stats.-pub struct WorkingTreeDiffTask;--impl Task for WorkingTreeDiffTask {- const KIND: TaskKind = TaskKind::WorkingTreeDiff;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .expect("WorkingTreeDiffTask requires a worktree");-- // Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's- // `git stash create` which needs the index lock.- let status_output = wt- .run_command(&["--no-optional-locks", "status", "--porcelain"])- .map_err(|e| ctx.error(Self::KIND, &e))?;-- let (working_tree_status, is_dirty, has_conflicts) =- parse_working_tree_status(&status_output);-- let working_tree_diff = if is_dirty {- wt.working_tree_diff_stats()- .map_err(|e| ctx.error(Self::KIND, &e))?- } else {- LineDiff::default()- };-- Ok(TaskResult::WorkingTreeDiff {- item_idx: ctx.item_idx,- working_tree_diff,- working_tree_status,- has_conflicts,- })- }-}--/// Task 6: Potential merge conflicts check (merge-tree vs local main)-///-/// Uses default_branch (local main) for consistency with other Main subcolumn symbols.-/// Shows whether merging to your local main would conflict.-pub struct MergeTreeConflictsTask;--impl Task for MergeTreeConflictsTask {- const KIND: TaskKind = TaskKind::MergeTreeConflicts;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return false (no conflicts can be detected)- let Some(base) = ctx.default_branch() else {- return Ok(TaskResult::MergeTreeConflicts {- item_idx: ctx.item_idx,- has_merge_tree_conflicts: false,- });- };- let repo = &ctx.repo;- let has_merge_tree_conflicts = repo- .has_merge_conflicts(&base, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;- Ok(TaskResult::MergeTreeConflicts {- item_idx: ctx.item_idx,- has_merge_tree_conflicts,- })- }-}--/// Task 6b (worktree only, --full only): Working tree conflict check-///-/// For dirty worktrees, uses `git stash create` to get a tree object that-/// includes uncommitted changes, then runs merge-tree against that.-/// Returns None if working tree is clean (caller should fall back to MergeTreeConflicts).-pub struct WorkingTreeConflictsTask;--impl Task for WorkingTreeConflictsTask {- const KIND: TaskKind = TaskKind::WorkingTreeConflicts;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return None (skip conflict check)- let Some(base) = ctx.default_branch() else {- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- };- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .expect("WorkingTreeConflictsTask requires a worktree");-- // Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.- // Both tasks run in parallel, and `git stash create` below needs the index lock.- let status_output = wt- .run_command(&["--no-optional-locks", "status", "--porcelain"])- .map_err(|e| ctx.error(Self::KIND, &e))?;-- let is_dirty = !status_output.trim().is_empty();-- if !is_dirty {- // Clean working tree - return None to signal "use commit-based check"- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }-- // Dirty working tree - create a temporary tree object via stash create- // `git stash create` returns a commit SHA without modifying refs- //- // Note: stash create fails when there are unmerged files (merge conflict in progress).- // In that case, fall back to the commit-based check.- let stash_result = wt.run_command(&["stash", "create"]);-- let stash_sha = match stash_result {- Ok(sha) => sha,- Err(_) => {- // Stash create failed (likely unmerged files during rebase/merge)- // Fall back to commit-based check- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }- };-- let stash_sha = stash_sha.trim();-- // If stash create returns empty, working tree is clean (shouldn't happen but handle it)- if stash_sha.is_empty() {- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }-- // Run merge-tree with the stash commit (repo-wide operation, doesn't need worktree)- let has_conflicts = ctx- .repo- .has_merge_conflicts(&base, stash_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: Some(has_conflicts),- })- }-}--/// Task 7 (worktree only): Git operation state detection (rebase/merge)-pub struct GitOperationTask;--impl Task for GitOperationTask {- const KIND: TaskKind = TaskKind::GitOperation;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // This task is only spawned for worktree items, so worktree path is always present.- let wt = ctx- .branch_ref- .working_tree(&ctx.repo)- .expect("GitOperationTask requires a worktree");- let git_operation = detect_git_operation(&wt);- Ok(TaskResult::GitOperation {- item_idx: ctx.item_idx,- git_operation,- })- }-}--/// Task 8 (worktree only): User-defined status from git config-pub struct UserMarkerTask;--impl Task for UserMarkerTask {- const KIND: TaskKind = TaskKind::UserMarker;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;- let user_marker = repo.user_marker(ctx.branch_ref.branch.as_deref());- Ok(TaskResult::UserMarker {- item_idx: ctx.item_idx,- user_marker,- })- }-}--/// Task 9: Upstream tracking status-pub struct UpstreamTask;--impl Task for UpstreamTask {- const KIND: TaskKind = TaskKind::Upstream;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;-- // No branch means no upstream- let Some(branch) = ctx.branch_ref.branch.as_deref() else {- return Ok(TaskResult::Upstream {- item_idx: ctx.item_idx,- upstream: UpstreamStatus::default(),- });- };-- // Get upstream branch (None is valid - just means no upstream configured)- let upstream_branch = repo- .upstream_branch(branch)- .map_err(|e| ctx.error(Self::KIND, &e))?;- let Some(upstream_branch) = upstream_branch else {- return Ok(TaskResult::Upstream {- item_idx: ctx.item_idx,- upstream: UpstreamStatus::default(),- });- };-- let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());- let (ahead, behind) = repo- .ahead_behind(&upstream_branch, &ctx.branch_ref.commit_sha)- .map_err(|e| ctx.error(Self::KIND, &e))?;-- Ok(TaskResult::Upstream {- item_idx: ctx.item_idx,- upstream: UpstreamStatus {- remote,- ahead,- behind,- },- })- }-}--/// Task 10: CI/PR status-///-/// Always checks for open PRs/MRs regardless of upstream tracking.-/// For branch workflow/pipeline fallback (no PR), requires upstream tracking-/// to prevent false matches from similarly-named branches on the remote.-pub struct CiStatusTask;--impl Task for CiStatusTask {- const KIND: TaskKind = TaskKind::CiStatus;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = &ctx.repo;- let pr_status = ctx.branch_ref.branch.as_deref().and_then(|branch| {- let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();- PrStatus::detect(repo, branch, &ctx.branch_ref.commit_sha, has_upstream)- });-- Ok(TaskResult::CiStatus {- item_idx: ctx.item_idx,- pr_status,- })- }-}--/// Task 13: URL health check (port availability).-///-/// The URL itself is sent immediately after template expansion (in spawning code)-/// so it appears in normal styling right away. This task only checks if the port-/// is listening, and if not, the URL dims.-pub struct UrlStatusTask;--impl Task for UrlStatusTask {- const KIND: TaskKind = TaskKind::UrlStatus;-- fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- use std::net::{SocketAddr, TcpStream};- use std::time::Duration;-- // URL already sent in spawning code; this task only checks port availability- let Some(ref url) = ctx.item_url else {- return Ok(TaskResult::UrlStatus {- item_idx: ctx.item_idx,- url: None,- active: None,- });- };-- // Parse port from URL and check if it's listening- // Skip health check in tests to avoid flaky results from random local processes- let active = if std::env::var("WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK").is_ok() {- Some(false)- } else {- parse_port_from_url(url).map(|port| {- // Quick TCP connect check with 50ms timeout- let addr = SocketAddr::from(([127, 0, 0, 1], port));- TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()- })- };-- // Return only active status (url=None to avoid overwriting the already-sent URL)- Ok(TaskResult::UrlStatus {- item_idx: ctx.item_idx,- url: None,- active,- })- }-}--/// Parse port number from a URL string (e.g., "http://localhost:12345" -> 12345)-pub(crate) fn parse_port_from_url(url: &str) -> Option<u16> {- // Strip scheme- let url = url- .strip_prefix("http://")- .or_else(|| url.strip_prefix("https://"))?;- // Extract host:port (before path, query, or fragment)- let host_port = url.split(&['/', '?', '#'][..]).next()?;- let (_host, port_str) = host_port.rsplit_once(':')?;- port_str.parse().ok()-}--// ============================================================================-// Helper Functions-// ============================================================================--/// Parse git status output to extract working tree status and conflict state.-/// Returns (WorkingTreeStatus, is_dirty, has_conflicts).-fn parse_working_tree_status(status_output: &str) -> (WorkingTreeStatus, bool, bool) {- let mut has_untracked = false;- let mut has_modified = false;- let mut has_staged = false;- let mut has_renamed = false;- let mut has_deleted = false;- let mut has_conflicts = false;-- for line in status_output.lines() {- if line.len() < 2 {- continue;- }-- let bytes = line.as_bytes();- let index_status = bytes[0] as char;- let worktree_status = bytes[1] as char;-- if index_status == '?' && worktree_status == '?' {- has_untracked = true;- }-- // Worktree changes: M = modified, A = intent-to-add (git add -N), T = type change (file↔symlink)- if matches!(worktree_status, 'M' | 'A' | 'T') {- has_modified = true;- }-- // Index changes: A = added, M = modified, C = copied, T = type change (file↔symlink)- if matches!(index_status, 'A' | 'M' | 'C' | 'T') {- has_staged = true;- }-- if index_status == 'R' {- has_renamed = true;- }-- if index_status == 'D' || worktree_status == 'D' {- has_deleted = true;- }-- // Detect unmerged/conflicting paths (porcelain v1 two-letter codes)- // Only U codes and AA/DD indicate actual merge conflicts.- // AD/DA are normal staging states (staged then deleted, or deleted then restored).- let is_unmerged_pair = matches!(- (index_status, worktree_status),- ('U', _) | (_, 'U') | ('A', 'A') | ('D', 'D')- );- if is_unmerged_pair {- has_conflicts = true;- }- }-- let working_tree_status = WorkingTreeStatus::new(- has_staged,- has_modified,- has_untracked,- has_renamed,- has_deleted,- );-- let is_dirty = working_tree_status.is_dirty();-- (working_tree_status, is_dirty, has_conflicts)-}--/// Apply default values for a failed task.-///-/// When a task fails, we still need to populate the item fields with sensible-/// defaults so the UI can render. This centralizes all default logic in one place.-fn apply_default(items: &mut [ListItem], status_contexts: &mut [StatusContext], error: &TaskError) {- let idx = error.item_idx;- match error.kind {- TaskKind::CommitDetails => {- items[idx].commit = Some(CommitDetails::default());- }- TaskKind::AheadBehind => {- // Leave as None — UI shows `⋯` for not-loaded tasks- // Conservative: don't claim orphan if we couldn't check- items[idx].is_orphan = Some(false);- }- TaskKind::CommittedTreesMatch => {- // Conservative: don't claim integrated if we couldn't check- items[idx].committed_trees_match = Some(false);- }- TaskKind::HasFileChanges => {- // Conservative: assume has changes if we couldn't check- items[idx].has_file_changes = Some(true);- }- TaskKind::WouldMergeAdd => {- // Conservative: assume would add changes if we couldn't check- items[idx].would_merge_add = Some(true);- }- TaskKind::IsAncestor => {- // Conservative: don't claim merged if we couldn't check- items[idx].is_ancestor = Some(false);- }- TaskKind::BranchDiff => {- // Leave as None — UI shows `…` for skipped/failed tasks- }- TaskKind::WorkingTreeDiff => {- if let ItemKind::Worktree(data) = &mut items[idx].kind {- data.working_tree_diff = Some(LineDiff::default());- } else {- debug_assert!(false, "WorkingTreeDiff task spawned for non-worktree item");- }- status_contexts[idx].working_tree_status = Some(WorkingTreeStatus::default());- status_contexts[idx].has_conflicts = false;- }- TaskKind::MergeTreeConflicts => {- // Don't show conflict symbol if we couldn't check- status_contexts[idx].has_merge_tree_conflicts = false;- }- TaskKind::WorkingTreeConflicts => {- // Fall back to commit-based check on failure- status_contexts[idx].has_working_tree_conflicts = None;- }- TaskKind::GitOperation => {- // Already defaults to GitOperationState::None in WorktreeData- }- TaskKind::UserMarker => {- // Already defaults to None- status_contexts[idx].user_marker = None;- }- TaskKind::Upstream => {- items[idx].upstream = Some(UpstreamStatus::default());- }- TaskKind::CiStatus => {- // Leave as None (not fetched) on error. This allows the hint path- // in mod.rs to run and show "install gh/glab" when CI tools fail.- // Some(None) means "CI tool ran successfully but found no PR".- }- TaskKind::UrlStatus => {- // URL is set at item creation, only default url_active- items[idx].url_active = None;- }- }-}--/// Drain task results from the channel and apply them to items.-///-/// This is the shared logic between progressive and buffered collection modes.-/// The `on_result` callback is called after each result is processed with the-/// item index and a reference to the updated item, allowing progressive mode-/// to update the live table while buffered mode does nothing.-///-/// Uses a 30-second deadline to prevent infinite hangs if git commands stall.-/// When timeout occurs, returns `DrainOutcome::TimedOut` with diagnostic info.-///-/// Errors are collected in the `errors` vec for display after rendering.-/// Default values are applied for failed tasks so the UI can still render.-///-/// Callers decide how to handle timeout:-/// - `collect()`: Shows user-facing diagnostic (interactive command)-/// - `populate_item()`: Logs silently (used by statusline)-fn drain_results(- rx: chan::Receiver<Result<TaskResult, TaskError>>,- items: &mut [ListItem],- errors: &mut Vec<TaskError>,- expected_results: &ExpectedResults,- mut on_result: impl FnMut(usize, &mut ListItem, &StatusContext),-) -> DrainOutcome {- use std::time::{Duration, Instant};-- // Deadline for the entire drain operation (30 seconds should be more than enough)- let deadline = Instant::now() + Duration::from_secs(30);-- // Track which result kinds we've received per item (for timeout diagnostics)- let mut received_by_item: Vec<Vec<TaskKind>> = vec![Vec::new(); items.len()];-- // Temporary storage for data needed by status_symbols computation- let mut status_contexts = vec![StatusContext::default(); items.len()];-- // Process task results as they arrive (with deadline)- loop {- let remaining = deadline.saturating_duration_since(Instant::now());- if remaining.is_zero() {- // Deadline exceeded - build diagnostic info showing MISSING results- let received_count: usize = received_by_item.iter().map(|v| v.len()).sum();-- // Find items with missing results by comparing received vs expected- let mut items_with_missing: Vec<MissingResult> = Vec::new();-- for (item_idx, item) in items.iter().enumerate() {- // Get expected results for this item (populated at spawn time)- let expected = expected_results.results_for(item_idx);-- // Get received results for this item (empty vec if none received)- let received = received_by_item[item_idx].as_slice();-- // Find missing results- let missing_kinds: Vec<TaskKind> = expected- .iter()- .filter(|kind| !received.contains(kind))- .copied()- .collect();-- if !missing_kinds.is_empty() {- let name = item- .branch- .clone()- .unwrap_or_else(|| item.head[..8.min(item.head.len())].to_string());- items_with_missing.push(MissingResult {- item_idx,- name,- missing_kinds,- });- }- }-- // Sort by item index and limit to first 5- items_with_missing.sort_by_key(|result| result.item_idx);- items_with_missing.truncate(5);-- return DrainOutcome::TimedOut {- received_count,- items_with_missing,- };- }-- let outcome = match rx.recv_timeout(remaining) {- Ok(outcome) => outcome,- Err(chan::RecvTimeoutError::Timeout) => continue, // Check deadline in next iteration- Err(chan::RecvTimeoutError::Disconnected) => break, // All senders dropped - done- };-- // Handle success or error- let (item_idx, kind) = match outcome {- Ok(ref result) => (result.item_idx(), TaskKind::from(result)),- Err(ref error) => (error.item_idx, error.kind),- };-- // Track this result for diagnostics (both success and error count as "received")- received_by_item[item_idx].push(kind);-- // Handle error case: apply defaults and collect error- if let Err(error) = outcome {- apply_default(items, &mut status_contexts, &error);- errors.push(error);- let item = &mut items[item_idx];- let status_ctx = &status_contexts[item_idx];- on_result(item_idx, item, status_ctx);- continue;- }-- // Handle success case- let result = outcome.unwrap();- let item = &mut items[item_idx];- let status_ctx = &mut status_contexts[item_idx];-- match result {- TaskResult::CommitDetails { commit, .. } => {- item.commit = Some(commit);- }- TaskResult::AheadBehind {- counts, is_orphan, ..- } => {- item.counts = Some(counts);- item.is_orphan = Some(is_orphan);- }- TaskResult::CommittedTreesMatch {- committed_trees_match,- ..- } => {- item.committed_trees_match = Some(committed_trees_match);- }- TaskResult::HasFileChanges {- has_file_changes, ..- } => {- item.has_file_changes = Some(has_file_changes);- }- TaskResult::WouldMergeAdd {- would_merge_add, ..- } => {- item.would_merge_add = Some(would_merge_add);- }- TaskResult::IsAncestor { is_ancestor, .. } => {- item.is_ancestor = Some(is_ancestor);- }- TaskResult::BranchDiff { branch_diff, .. } => {- item.branch_diff = Some(branch_diff);- }- TaskResult::WorkingTreeDiff {- working_tree_diff,- working_tree_status,- has_conflicts,- ..- } => {- if let ItemKind::Worktree(data) = &mut item.kind {- data.working_tree_diff = Some(working_tree_diff);- } else {- debug_assert!(false, "WorkingTreeDiff result for non-worktree item");- }- // Store for status_symbols computation- status_ctx.working_tree_status = Some(working_tree_status);- status_ctx.has_conflicts = has_conflicts;- }- TaskResult::MergeTreeConflicts {- has_merge_tree_conflicts,- ..- } => {- // Store for status_symbols computation- status_ctx.has_merge_tree_conflicts = has_merge_tree_conflicts;- }- TaskResult::WorkingTreeConflicts {- has_working_tree_conflicts,- ..- } => {- // Store for status_symbols computation (takes precedence over commit check)- status_ctx.has_working_tree_conflicts = has_working_tree_conflicts;- }- TaskResult::GitOperation { git_operation, .. } => {- if let ItemKind::Worktree(data) = &mut item.kind {- data.git_operation = git_operation;- } else {- debug_assert!(false, "GitOperation result for non-worktree item");- }- }- TaskResult::UserMarker { user_marker, .. } => {- // Store for status_symbols computation- status_ctx.user_marker = user_marker;- }- TaskResult::Upstream { upstream, .. } => {- item.upstream = Some(upstream);- }- TaskResult::CiStatus { pr_status, .. } => {- // Wrap in Some() to indicate "loaded" (Some(None) = no CI, Some(Some(status)) = has CI)- item.pr_status = Some(pr_status);- }- TaskResult::UrlStatus { url, active, .. } => {- // Two-phase URL rendering:- // 1. First result (from spawning code): url=Some, active=None → URL appears in normal styling- // 2. Second result (from health check): url=None, active=Some → dims if inactive- // Only update non-None fields to preserve values from earlier results.- if url.is_some() {- item.url = url;- }- if active.is_some() {- item.url_active = active;- }- }- }-- // Invoke callback (progressive mode re-renders rows, buffered mode does nothing)- on_result(item_idx, item, status_ctx);- }-- DrainOutcome::Complete-}--fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> std::collections::HashSet<&str> {- worktrees- .iter()- .filter_map(|wt| wt.branch.as_deref())- .collect()-}--/// Collect worktree data with optional progressive rendering.-///-/// When `show_progress` is true, renders a skeleton immediately and updates as data arrives.-/// When false, behavior depends on `render_table`:-/// - If `render_table` is true: renders final table (buffered mode)-/// - If `render_table` is false: returns data without rendering (JSON mode)-///-/// The `command_timeout` parameter, if set, limits how long individual git commands can run.-/// This is useful for `wt select` to show the TUI faster by skipping slow operations.-///-/// TODO: Now that we skip expensive tasks for stale branches (see `skip_expensive_for_stale`),-/// the timeout may be unnecessary. Consider removing it if it doesn't provide value.-///-/// The `skip_expensive_for_stale` parameter enables batch-fetching ahead/behind counts and-/// skipping expensive merge-base operations for branches far behind the default branch.-/// This dramatically improves performance for repos with many stale branches.-#[allow(clippy::too_many_arguments)]-pub fn collect(- repo: &Repository,- show_branches: bool,- show_remotes: bool,- skip_tasks: &std::collections::HashSet<TaskKind>,- show_progress: bool,- render_table: bool,- config: &worktrunk::config::WorktrunkConfig,- command_timeout: Option<std::time::Duration>,- skip_expensive_for_stale: bool,-) -> anyhow::Result<Option<super::model::ListData>> {- use super::progressive_table::ProgressiveTable;- worktrunk::shell_exec::trace_instant("List collect started");-- // Phase 1: Parallel fetch of ALL independent git data- //- // Key insight: most operations don't depend on each other. By running them all- // in parallel via rayon::scope, we minimize wall-clock time. Dependencies:- //- // - worktree list: independent (needed for filtering and SHAs)- // - default_branch: independent (git config + verify)- // - is_bare: independent (git config, cached for later use)- // - url_template: independent (loads project config via show-toplevel)- // - local_branches: independent (for-each-ref, but filtering needs worktrees)- // - remote_branches: independent (for-each-ref)- //- // After this scope completes, we have all raw data and can do CPU-only work.- let worktrees_cell: OnceCell<anyhow::Result<Vec<WorktreeInfo>>> = OnceCell::new();- let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();- let url_template_cell: OnceCell<Option<String>> = OnceCell::new();- let local_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();- let remote_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();-- rayon::scope(|s| {- s.spawn(|_| {- let _ = worktrees_cell.set(repo.list_worktrees());- });- s.spawn(|_| {- let _ = default_branch_cell.set(repo.default_branch());- });- s.spawn(|_| {- // Populate is_bare cache (value used later via repo_path)- let _ = repo.is_bare();- });- s.spawn(|_| {- let _ = url_template_cell.set(repo.url_template());- });- s.spawn(|_| {- if show_branches {- let _ = local_branches_cell.set(repo.list_local_branches());- }- });- s.spawn(|_| {- if show_remotes {- let _ = remote_branches_cell.set(repo.list_untracked_remote_branches());- }- });- });-- // Extract results- let worktrees = worktrees_cell- .into_inner()- .unwrap()- .context("Failed to list worktrees")?;- if worktrees.is_empty() {- return Ok(None);- }- let default_branch = default_branch_cell.into_inner().unwrap();- let url_template = url_template_cell.into_inner().unwrap();-- // Filter local branches to those without worktrees (CPU-only, no git commands)- let branches_without_worktrees = if show_branches {- let all_local = local_branches_cell.into_inner().unwrap()?;- let worktree_branches = worktree_branch_set(&worktrees);- all_local- .into_iter()- .filter(|(name, _)| !worktree_branches.contains(name.as_str()))- .collect()- } else {- Vec::new()- };- let remote_branches = if show_remotes {- remote_branches_cell.into_inner().unwrap()?- } else {- Vec::new()- };-- // Detect current worktree by checking if repo path is inside any worktree.- // This avoids a git command - we just compare canonicalized paths.- let repo_path_canonical = canonicalize(repo.discovery_path()).ok();- let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {- worktrees.iter().find_map(|wt| {- canonicalize(&wt.path)- .ok()- .filter(|wt_path| repo_path.starts_with(wt_path))- })- });- // Show warning if user configured a default branch that doesn't exist locally- if let Some(configured) = repo.invalid_default_branch_config() {- let msg =- cformat!("Configured default branch <bold>{configured}</> does not exist locally");- crate::output::print(warning_message(msg))?;- let hint = cformat!("To reset, run <bright-black>wt config state default-branch clear</>");- crate::output::print(worktrunk::styling::hint_message(hint))?;- }-- // Main worktree is the worktree on the default branch (if exists), else first non-prunable worktree.- // find_home returns None if all worktrees are prunable or the list is empty.- // TODO: show ellipsis or indicator when default_branch is None and columns are empty- let main_worktree =- WorktreeInfo::find_home(&worktrees, default_branch.as_deref().unwrap_or(""))- .cloned()- .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;-- // Defer previous_branch lookup until after skeleton - set is_previous later- // (skeleton shows placeholder gutter, actual symbols appear when data loads)-- // Phase 3: Batch fetch timestamps (needs all SHAs from worktrees + branches)- let all_shas: Vec<&str> = worktrees- .iter()- .map(|wt| wt.head.as_str())- .chain(- branches_without_worktrees- .iter()- .map(|(_, sha)| sha.as_str()),- )- .chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))- .collect();- let timestamps = repo.commit_timestamps(&all_shas).unwrap_or_default();-- // Sort worktrees: current first, main second, then by timestamp descending- let sorted_worktrees = sort_worktrees_with_cache(- worktrees.clone(),- &main_worktree,- current_worktree_path.as_ref(),- ×tamps,- );-- // Sort branches by timestamp (most recent first)- let branches_without_worktrees =- sort_by_timestamp_desc_with_cache(branches_without_worktrees, ×tamps, |(_, sha)| {- sha.as_str()- });- let remote_branches =- sort_by_timestamp_desc_with_cache(remote_branches, ×tamps, |(_, sha)| sha.as_str());-- // Pre-canonicalize main_worktree.path for is_main comparison- // (paths from git worktree list may differ based on symlinks or working directory)- let main_worktree_canonical = canonicalize(&main_worktree.path).ok();-- // URL template already fetched in parallel join (layout needs to know if column is needed)- // Initialize worktree items with identity fields and None for computed fields- let mut all_items: Vec<ListItem> = sorted_worktrees- .iter()- .map(|wt| {- // Canonicalize paths for comparison - git worktree list may return different- // path representations depending on symlinks or which directory you run from- let wt_canonical = canonicalize(&wt.path).ok();- let is_main = match (&wt_canonical, &main_worktree_canonical) {- (Some(wt_c), Some(main_c)) => wt_c == main_c,- // Fallback to direct comparison if canonicalization fails- _ => wt.path == main_worktree.path,- };- let is_current = current_worktree_path- .as_ref()- .is_some_and(|cp| wt_canonical.as_ref() == Some(cp));- // is_previous set to false initially - computed after skeleton- let is_previous = false;-- // Check if worktree is at its expected path based on config template- let branch_worktree_mismatch = !is_worktree_at_expected_path(wt, repo, config);-- let mut worktree_data =- WorktreeData::from_worktree(wt, is_main, is_current, is_previous);- worktree_data.branch_worktree_mismatch = branch_worktree_mismatch;-- // URL expanded post-skeleton to minimize time-to-skeleton- ListItem {- head: wt.head.clone(),- branch: wt.branch.clone(),- commit: None,- counts: None,- branch_diff: None,- committed_trees_match: None,- has_file_changes: None,- would_merge_add: None,- is_ancestor: None,- is_orphan: None,- upstream: None,- pr_status: None,- url: None,- url_active: None,- status_symbols: None,- display: DisplayFields::default(),- kind: ItemKind::Worktree(Box::new(worktree_data)),- }- })- .collect();-- // Initialize branch items (local and remote) - URLs expanded post-skeleton- let branch_start_idx = all_items.len();- all_items.extend(- branches_without_worktrees- .iter()- .map(|(name, sha)| ListItem::new_branch(sha.clone(), name.clone())),- );-- let remote_start_idx = all_items.len();- all_items.extend(- remote_branches- .iter()- .map(|(name, sha)| ListItem::new_branch(sha.clone(), name.clone())),- );-- // If no URL template configured, add UrlStatus to skip_tasks- let mut effective_skip_tasks = skip_tasks.clone();- if url_template.is_none() {- effective_skip_tasks.insert(TaskKind::UrlStatus);- }-- // Calculate layout from items (worktrees, local branches, and remote branches)- let layout = super::layout::calculate_layout_from_basics(- &all_items,- &effective_skip_tasks,- &main_worktree.path,- url_template.as_deref(),- );-- // Single-line invariant: use safe width to prevent line wrapping- let max_width = crate::display::get_terminal_width();-- // Create collection options from skip set- let mut options = CollectOptions {- skip_tasks: effective_skip_tasks,- url_template: url_template.clone(),- ..Default::default()- };-- // Track expected results per item - populated as spawns are queued- let expected_results = std::sync::Arc::new(ExpectedResults::default());- let num_worktrees = all_items- .iter()- .filter(|item| item.worktree_data().is_some())- .count();- let num_local_branches = branches_without_worktrees.len();- let num_remote_branches = remote_branches.len();-- let footer_base =- if (show_branches && num_local_branches > 0) || (show_remotes && num_remote_branches > 0) {- let mut parts = vec![format!("{} worktrees", num_worktrees)];- if show_branches && num_local_branches > 0 {- parts.push(format!("{} branches", num_local_branches));- }- if show_remotes && num_remote_branches > 0 {- parts.push(format!("{} remote branches", num_remote_branches));- }- format!("Showing {}", parts.join(", "))- } else {- let plural = if num_worktrees == 1 { "" } else { "s" };- format!("Showing {} worktree{}", num_worktrees, plural)- };-- // Create progressive table if showing progress- let mut progressive_table = if show_progress {- use anstyle::Style;- let dim = Style::new().dimmed();-- // Build skeleton rows for both worktrees and branches- // All items need skeleton rendering since computed data (timestamp, ahead/behind, etc.)- // hasn't been loaded yet. Using format_list_item_line would show default values like "55y".- let skeletons: Vec<String> = all_items- .iter()- .map(|item| layout.render_skeleton_row(item).render())- .collect();-- let initial_footer = format!("{INFO_SYMBOL} {dim}{footer_base} (loading...){dim:#}");-- let mut table = ProgressiveTable::new(- layout.format_header_line(),- skeletons,- initial_footer,- max_width,- );- table.render_skeleton()?;- worktrunk::shell_exec::trace_instant("Skeleton rendered");- Some(table)- } else {- None- };-- // Early exit for benchmarking skeleton render time- if std::env::var("WORKTRUNK_SKELETON_ONLY").is_ok() {- return Ok(None);- }-- // === Post-skeleton computations (deferred to minimize time-to-skeleton) ===- //- // These operations run in parallel using rayon::scope with single-level parallelism.- // See module docs for the timing diagram.-- // Collect worktree paths for fsmonitor starts (macOS only, fast, no git commands).- // Git's builtin fsmonitor has race conditions under parallel load - pre-starting- // daemons before parallel operations avoids hangs.- #[cfg(target_os = "macos")]- let fsmonitor_worktrees: Vec<_> = if repo.is_builtin_fsmonitor_enabled() {- sorted_worktrees- .iter()- .filter(|wt| !wt.is_prunable())- .collect()- } else {- vec![]- };- #[cfg(not(target_os = "macos"))]- let fsmonitor_worktrees: Vec<&WorktreeInfo> = vec![];-- // Single-level parallelism: all spawns in one rayon::scope.- // See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's fsmonitor workaround)- // See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same fsmonitor issue)- let previous_branch_cell: OnceCell<Option<String>> = OnceCell::new();- let integration_target_cell: OnceCell<Option<String>> = OnceCell::new();-- rayon::scope(|s| {- // Previous branch lookup (for gutter symbol)- s.spawn(|_| {- let _ = previous_branch_cell.set(repo.get_switch_previous());- });-- // Integration target (upstream if ahead of local, else local)- s.spawn(|_| {- let _ = integration_target_cell.set(repo.integration_target());- });-- // Fsmonitor daemon starts (one spawn per worktree)- for wt in &fsmonitor_worktrees {- s.spawn(|_| {- repo.start_fsmonitor_daemon_at(&wt.path);- });- }- });-- // Extract results from cells- let previous_branch = previous_branch_cell.into_inner().flatten();- let integration_target = integration_target_cell.into_inner().flatten();-- // Update is_previous on items- if let Some(prev) = previous_branch.as_deref() {- for item in &mut all_items {- if item.branch.as_deref() == Some(prev)- && let Some(wt_data) = item.worktree_data_mut()- {- wt_data.is_previous = true;- }- }- }-- // Batch-fetch ahead/behind counts to identify branches that are far behind.- // This allows skipping expensive merge-base operations for diverged branches, dramatically- // improving performance on repos with many stale branches (e.g., wt select).- //- // Uses `git for-each-ref --format='%(ahead-behind:...)'` (git 2.36+) which gets all- // counts in a single command. On older git versions, returns empty and all tasks run.- // Skip if default_branch is unknown.- if skip_expensive_for_stale && let Some(ref db) = default_branch {- // Branches more than 50 commits behind skip expensive operations.- // 50 is low enough to catch truly stale branches while keeping info for- // recently-diverged ones.- //- // "Behind" is a proxy for the actual cost driver: files changed on both- // sides since the merge-base. More commits on main → more files touched →- // more overlap with the branch. See `CollectOptions::stale_branches` for- // detailed rationale.- let threshold: usize = std::env::var("WORKTRUNK_TEST_SKIP_EXPENSIVE_THRESHOLD")- .ok()- .and_then(|s| s.parse().ok())- .unwrap_or(50);- // batch_ahead_behind populates the Repository cache with all counts- let ahead_behind = repo.batch_ahead_behind(db);- // Filter to stale branches (behind > threshold). The set indicates which- // branches should skip expensive tasks; counts come from the cache.- options.stale_branches = ahead_behind- .into_iter()- .filter_map(|(branch, (_, behind))| (behind > threshold).then_some(branch))- .collect();- }-- // Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive- // and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.-- // Cache last rendered (unclamped) message per row to avoid redundant updates.- let mut last_rendered_lines: Vec<String> = vec![String::new(); all_items.len()];-- // Create channel for task results- let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();-- // Collect errors for display after rendering- let mut errors: Vec<TaskError> = Vec::new();-- // Collect all work items upfront, then execute in a single Rayon pool.- // This avoids nested parallelism (Rayon par_iter → thread::scope per worktree)- // which could create 100+ threads. Instead, we have one pool with the configured- // thread count (default 2x CPU cores unless overridden by RAYON_NUM_THREADS).- let sorted_worktrees_clone = sorted_worktrees.clone();- let tx_worker = tx.clone();- let expected_results_clone = expected_results.clone();-- // Clone repo for the worker thread (shares cache via Arc)- let repo_clone = repo.clone();-- // Prepare branch data if needed (before moving into closure)- let branch_data: Vec<(usize, String, String)> = if show_branches || show_remotes {- let mut all_branches = Vec::new();- if show_branches {- all_branches.extend(- branches_without_worktrees- .iter()- .enumerate()- .map(|(idx, (name, sha))| (branch_start_idx + idx, name.clone(), sha.clone())),- );- }- if show_remotes {- all_branches.extend(- remote_branches- .iter()- .enumerate()- .map(|(idx, (name, sha))| (remote_start_idx + idx, name.clone(), sha.clone())),- );- }- all_branches- } else {- Vec::new()- };-- worktrunk::shell_exec::trace_instant("Spawning worker thread");- std::thread::spawn(move || {- // Phase 1: Generate all work items (sequential, fast)- // Work items are collected upfront so we can process them all in a single par_iter.- let mut all_work_items = Vec::new();-- // Worktree work items- for (idx, wt) in sorted_worktrees_clone.iter().enumerate() {- all_work_items.extend(work_items_for_worktree(- &repo_clone,- wt,- idx,- &options,- &expected_results_clone,- &tx_worker,- ));- }-- // Branch work items (local + remote)- for (item_idx, branch_name, commit_sha) in &branch_data {- all_work_items.extend(work_items_for_branch(- &repo_clone,- branch_name,- commit_sha,- *item_idx,- &options,- &expected_results_clone,- ));- }-- // Sort work items: network tasks last to avoid blocking local operations- all_work_items.sort_by_key(|item| item.kind.is_network());-- // Phase 2: Execute all work items in parallel- worktrunk::shell_exec::trace_instant("Parallel execution started");- all_work_items.into_par_iter().for_each(|item| {- worktrunk::shell_exec::set_command_timeout(command_timeout);- let result = item.execute();- let _ = tx_worker.send(result);- });- });-- // Drop the original sender so drain_results knows when all spawned threads are done- drop(tx);-- // Track completed results for footer progress- let mut completed_results = 0;- let mut progress_overflow = false;- let mut first_result_traced = false;-- // Drain task results with conditional progressive rendering- let drain_outcome = drain_results(- rx,- &mut all_items,- &mut errors,- &expected_results,- |item_idx, item, ctx| {- // Trace first result arrival- if !first_result_traced {- first_result_traced = true;- worktrunk::shell_exec::trace_instant("First result received");- }-- // Compute/recompute status symbols as data arrives (both modes).- // This is idempotent and updates status as new data (like upstream) arrives.- if let Some(ref target) = integration_target {- ctx.apply_to(item, target.as_str());- }-- // Progressive mode only: update UI- if let Some(ref mut table) = progressive_table {- use anstyle::Style;- let dim = Style::new().dimmed();-- completed_results += 1;- let total_results = expected_results.count();-- // Catch counting bugs: completed should never exceed expected- debug_assert!(- completed_results <= total_results,- "completed ({completed_results}) > expected ({total_results}): \- task result sent without registering expectation"- );- if completed_results > total_results {- progress_overflow = true;- }-- // Update footer progress- let footer_msg = format!(- "{INFO_SYMBOL} {dim}{footer_base} ({completed_results}/{total_results} loaded){dim:#}"- );- table.update_footer(footer_msg);-- // Re-render the row with caching (now includes status if computed)- let rendered = layout.format_list_item_line(item);-- // Compare using full line so changes beyond the clamp (e.g., CI) still refresh.- if rendered != last_rendered_lines[item_idx] {- last_rendered_lines[item_idx] = rendered.clone();- table.update_row(item_idx, rendered);- }-- // Flush updates to terminal- if let Err(e) = table.flush() {- log::debug!("Progressive table flush failed: {}", e);- }- }- },- );- worktrunk::shell_exec::trace_instant("All results drained");-- // Handle timeout if it occurred- if let DrainOutcome::TimedOut {- received_count,- items_with_missing,- } = drain_outcome- {- // Build diagnostic message showing what's MISSING (more useful for debugging)- let mut diag = format!("wt list timed out after 30s ({received_count} results received)");-- if !items_with_missing.is_empty() {- diag.push_str("\nMissing results:");- let missing_lines: Vec<String> = items_with_missing- .iter()- .map(|result| {- let missing_names: Vec<&str> =- result.missing_kinds.iter().map(|k| k.into()).collect();- cformat!("<bold>{}</>: {}", result.name, missing_names.join(", "))- })- .collect();- diag.push_str(&format!(- "\n{}",- format_with_gutter(&missing_lines.join("\n"), None)- ));- }-- diag.push_str(- "\n\nThis likely indicates a git command hung. Run with -v for details, -vv to create a diagnostic file.",- );-- crate::output::print(warning_message(&diag))?;-- // Show issue reporting hint (free function - doesn't collect diagnostic data)- crate::output::print(worktrunk::styling::hint_message(- crate::diagnostic::issue_hint(),- ))?;- }-- // Compute status symbols for prunable worktrees (skipped during task spawning).- // They didn't receive any task results, so status_symbols is still None.- for item in &mut all_items {- if item.status_symbols.is_none()- && let Some(data) = item.worktree_data()- && data.is_prunable()- {- // Use default context - no tasks ran, so no conflict/status info- let ctx = StatusContext::default();- if let Some(ref target) = integration_target {- ctx.apply_to(item, target.as_str());- }- }- }-- // Count errors for summary- let error_count = errors.len();- let timed_out_count = errors.iter().filter(|e| e.is_timeout()).count();-- // Finalize progressive table or render buffered output- if let Some(mut table) = progressive_table {- // Build final summary string- let final_msg = super::format_summary_message(- &all_items,- show_branches || show_remotes,- layout.hidden_column_count,- error_count,- timed_out_count,- );-- if table.is_tty() {- // Interactive: do final render pass and update footer to summary- for (item_idx, item) in all_items.iter().enumerate() {- let rendered = layout.format_list_item_line(item);- table.update_row(item_idx, rendered);- }- table.finalize(final_msg)?;- } else {- // Non-TTY: output to stdout (same as buffered mode)- // Progressive skeleton was suppressed; now output the final table- crate::output::stdout(layout.format_header_line())?;- for item in &all_items {- crate::output::stdout(layout.format_list_item_line(item))?;- }- crate::output::stdout("")?;- crate::output::stdout(final_msg)?;- }- } else if render_table {- // Buffered mode: render final table- let final_msg = super::format_summary_message(- &all_items,- show_branches || show_remotes,- layout.hidden_column_count,- error_count,- timed_out_count,- );-- crate::output::stdout(layout.format_header_line())?;- for item in &all_items {- crate::output::stdout(layout.format_list_item_line(item))?;- }- crate::output::stdout("")?;- crate::output::stdout(final_msg)?;- }-- // Status symbols are now computed during data collection (both modes), no fallback needed-- // Display collection errors/warnings (after table rendering)- // Filter out timeout errors - they're shown in the summary footer- let non_timeout_errors: Vec<_> = errors.iter().filter(|e| !e.is_timeout()).collect();-- if !non_timeout_errors.is_empty() || progress_overflow {- let mut warning_parts = Vec::new();-- if !non_timeout_errors.is_empty() {- // Sort for deterministic output (tasks complete in arbitrary order)- let mut sorted_errors = non_timeout_errors;- sorted_errors.sort_by_key(|e| (e.item_idx, e.kind));- let error_lines: Vec<String> = sorted_errors- .iter()- .map(|error| {- let name = all_items[error.item_idx].branch_name();- let kind_str: &'static str = error.kind.into();- // Take first line only - git errors can be multi-line with usage hints- let msg = error.message.lines().next().unwrap_or(&error.message);- cformat!("<bold>{}</>: {} ({})", name, kind_str, msg)- })- .collect();- warning_parts.push(format!(- "Some git operations failed:\n{}",- format_with_gutter(&error_lines.join("\n"), None)- ));- }-- if progress_overflow {- // Defensive: should never trigger now that immediate URL sends register expectations,- // but kept to detect future counting bugs- warning_parts.push("Progress counter overflow (completed > expected)".to_string());- }-- let warning = warning_parts.join("\n");- crate::output::print(warning_message(&warning))?;-- // Show issue reporting hint (free function - doesn't collect diagnostic data)- crate::output::print(worktrunk::styling::hint_message(- crate::diagnostic::issue_hint(),- ))?;- }-- // Populate display fields for all items (used by JSON output and statusline)- for item in &mut all_items {- item.finalize_display();- }-- // all_items now contains both worktrees and branches (if requested)- let items = all_items;-- // Table rendering complete (when render_table=true):- // - Progressive + TTY: rows morphed in place, footer became summary- // - Progressive + Non-TTY: rendered final table (no intermediate output)- // - Buffered: rendered final table- // JSON mode (render_table=false): no rendering, data returned for serialization- worktrunk::shell_exec::trace_instant("List collect complete");-- Ok(Some(super::model::ListData {- items,- main_worktree_path: main_worktree.path.clone(),- }))-}--/// Sort items by timestamp descending using pre-fetched timestamps.-fn sort_by_timestamp_desc_with_cache<T, F>(- items: Vec<T>,- timestamps: &std::collections::HashMap<String, i64>,- get_sha: F,-) -> Vec<T>-where- F: Fn(&T) -> &str,-{- // Embed timestamp in tuple to avoid parallel Vec and index lookups- let mut with_ts: Vec<_> = items- .into_iter()- .map(|item| {- let ts = *timestamps.get(get_sha(&item)).unwrap_or(&0);- (item, ts)- })- .collect();- with_ts.sort_by_key(|(_, ts)| std::cmp::Reverse(*ts));- with_ts.into_iter().map(|(item, _)| item).collect()-}--/// Sort worktrees: current first, main second, then by timestamp descending.-/// Uses pre-fetched timestamps for efficiency.-fn sort_worktrees_with_cache(- worktrees: Vec<WorktreeInfo>,- main_worktree: &WorktreeInfo,- current_path: Option<&std::path::PathBuf>,- timestamps: &std::collections::HashMap<String, i64>,-) -> Vec<WorktreeInfo> {- // Embed timestamp and priority in tuple to avoid parallel Vec and index lookups- let mut with_sort_key: Vec<_> = worktrees- .into_iter()- .map(|wt| {- let priority = if current_path.is_some_and(|cp| &wt.path == cp) {- 0 // Current first- } else if wt.path == main_worktree.path {- 1 // Main second- } else {- 2 // Rest by timestamp- };- let ts = *timestamps.get(&wt.head).unwrap_or(&0);- (wt, priority, ts)- })- .collect();-- with_sort_key.sort_by_key(|(_, priority, ts)| (*priority, std::cmp::Reverse(*ts)));- with_sort_key.into_iter().map(|(wt, _, _)| wt).collect()-}--// ============================================================================-// Public API for single-worktree collection (used by statusline)-// ============================================================================--/// Build a ListItem for a single worktree with identity fields only.-///-/// Computed fields (counts, diffs, CI) are left as None. Use `populate_item()`-/// to fill them in.-pub fn build_worktree_item(- wt: &WorktreeInfo,- is_main: bool,- is_current: bool,- is_previous: bool,-) -> ListItem {- ListItem {- head: wt.head.clone(),- branch: wt.branch.clone(),- commit: None,- counts: None,- branch_diff: None,- committed_trees_match: None,- has_file_changes: None,- would_merge_add: None,- is_ancestor: None,- is_orphan: None,- upstream: None,- pr_status: None,- url: None,- url_active: None,- status_symbols: None,- display: DisplayFields::default(),- kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(- wt,- is_main,- is_current,- is_previous,- ))),- }-}--/// Populate computed fields for items in parallel (blocking).-///-/// Spawns parallel git operations and collects results. Modifies items in place-/// with: commit details, ahead/behind, diffs, upstream, CI, etc.-///-/// # Parameters-/// - `repo`: Repository handle (cloned into background thread, shares cache via Arc)-///-/// This is the blocking version used by statusline. For progressive rendering-/// with callbacks, see the `collect()` function.-pub fn populate_item(- repo: &Repository,- item: &mut ListItem,- options: CollectOptions,-) -> anyhow::Result<()> {- use std::sync::Arc;-- // Extract worktree data (skip if not a worktree item)- let Some(data) = item.worktree_data() else {- return Ok(());- };-- // Get integration target for status symbol computation (cached in repo)- // None if default branch cannot be determined - status symbols will be skipped- let target = repo.integration_target();-- // Create channel for task results- let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();-- // Track expected results (populated at spawn time)- let expected_results = Arc::new(ExpectedResults::default());-- // Collect errors (logged silently for statusline)- let mut errors: Vec<TaskError> = Vec::new();-- // Extract data for background thread (can't send borrows across threads)- let wt = WorktreeInfo {- path: data.path.clone(),- head: item.head.clone(),- branch: item.branch.clone(),- bare: false,- detached: false,- locked: None,- prunable: None,- };- let repo_clone = repo.clone();- let expected_results_clone = expected_results.clone();-- // Spawn collection in background thread- std::thread::spawn(move || {- // Generate work items for this single worktree- let mut work_items = work_items_for_worktree(- &repo_clone,- &wt,- 0, // Single item, always index 0- &options,- &expected_results_clone,- &tx,- );-- // Sort: network tasks last- work_items.sort_by_key(|item| item.kind.is_network());-- // Execute all tasks in parallel- work_items.into_par_iter().for_each(|item| {- let result = item.execute();- let _ = tx.send(result);- });- });-- // Drain task results (blocking until complete)- let drain_outcome = drain_results(- rx,- std::slice::from_mut(item),- &mut errors,- &expected_results,- |_item_idx, item, ctx| {- if let Some(ref t) = target {- ctx.apply_to(item, t);- }- },- );-- // Handle timeout (silent for statusline - just log it)- if let DrainOutcome::TimedOut { received_count, .. } = drain_outcome {- log::warn!("populate_item timed out after 30s ({received_count} results received)");- }-- // Log errors silently (statusline shouldn't spam warnings)- if !errors.is_empty() {- log::warn!("populate_item had {} task errors", errors.len());- for error in &errors {- let kind_str: &'static str = error.kind.into();- log::debug!(- " - item {}: {} ({})",- error.item_idx,- kind_str,- error.message- );- }- }-- // Populate display fields (including status_line for statusline command)- item.finalize_display();-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_task_error_other_is_not_timeout() {- let error = TaskError::new(0, TaskKind::AheadBehind, "test error", ErrorCause::Other);- assert!(!error.is_timeout());- }-- #[test]- fn test_task_error_timeout_is_timeout() {- let error = TaskError::new(0, TaskKind::AheadBehind, "timed out", ErrorCause::Timeout);- assert!(error.is_timeout());- }-}diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsnew file mode 100644index 000000000..c743bd1ac--- /dev/null+++ b/src/commands/list/collect/execution.rs@@ -0,0 +1,292 @@+//! Work item generation and execution.+//!+//! Contains the flat parallelism infrastructure:+//! - `WorkItem` - unit of work for the thread pool+//! - `dispatch_task()` - route TaskKind to the correct Task implementation+//! - `work_items_for_worktree()` / `work_items_for_branch()` - generate work items+//! - `ExpectedResults` - track expected results for timeout diagnostics++use std::sync::Arc;++use crossbeam_channel as chan;+use worktrunk::git::{BranchRef, Repository, WorktreeInfo};++use super::CollectOptions;+use super::tasks::{+ AheadBehindTask, BranchDiffTask, CiStatusTask, CommitDetailsTask, CommittedTreesMatchTask,+ GitOperationTask, HasFileChangesTask, IsAncestorTask, MergeTreeConflictsTask, Task,+ TaskContext, UpstreamTask, UrlStatusTask, UserMarkerTask, WorkingTreeConflictsTask,+ WorkingTreeDiffTask, WouldMergeAddTask,+};+use super::types::{TaskError, TaskKind, TaskResult};++// Tasks that are expensive because they require merge-base computation or merge simulation.+// These are skipped for branches that are far behind the default branch (in wt select).+// AheadBehind is NOT here - we use batch data for it instead of skipping.+// CommittedTreesMatch is NOT here - it's a cheap tree comparison that aids integration detection.+const EXPENSIVE_TASKS: &[TaskKind] = &[+ TaskKind::HasFileChanges, // git diff with three-dot range+ TaskKind::IsAncestor, // git merge-base --is-ancestor+ TaskKind::WouldMergeAdd, // git merge-tree simulation+ TaskKind::BranchDiff, // git diff with three-dot range+ TaskKind::MergeTreeConflicts, // git merge-tree simulation+];++// ============================================================================+// Work Item Dispatch (for flat parallelism)+// ============================================================================++/// A unit of work for the thread pool.+///+/// Each work item represents a single task to be executed. Work items are+/// collected upfront and then processed in parallel via Rayon's thread pool,+/// avoiding nested parallelism (Rayon par_iter → thread::scope).+#[derive(Clone)]+pub struct WorkItem {+ pub ctx: TaskContext,+ pub kind: TaskKind,+}++impl WorkItem {+ /// Execute this work item, returning the task result.+ pub fn execute(self) -> Result<TaskResult, TaskError> {+ let result = dispatch_task(self.kind, self.ctx);+ if let Ok(ref task_result) = result {+ debug_assert_eq!(TaskKind::from(task_result), self.kind);+ }+ result+ }+}++/// Dispatch a task by kind, calling the appropriate Task::compute().+fn dispatch_task(kind: TaskKind, ctx: TaskContext) -> Result<TaskResult, TaskError> {+ match kind {+ TaskKind::CommitDetails => CommitDetailsTask::compute(ctx),+ TaskKind::AheadBehind => AheadBehindTask::compute(ctx),+ TaskKind::CommittedTreesMatch => CommittedTreesMatchTask::compute(ctx),+ TaskKind::HasFileChanges => HasFileChangesTask::compute(ctx),+ TaskKind::WouldMergeAdd => WouldMergeAddTask::compute(ctx),+ TaskKind::IsAncestor => IsAncestorTask::compute(ctx),+ TaskKind::BranchDiff => BranchDiffTask::compute(ctx),+ TaskKind::WorkingTreeDiff => WorkingTreeDiffTask::compute(ctx),+ TaskKind::MergeTreeConflicts => MergeTreeConflictsTask::compute(ctx),+ TaskKind::WorkingTreeConflicts => WorkingTreeConflictsTask::compute(ctx),+ TaskKind::GitOperation => GitOperationTask::compute(ctx),+ TaskKind::UserMarker => UserMarkerTask::compute(ctx),+ TaskKind::Upstream => UpstreamTask::compute(ctx),+ TaskKind::CiStatus => CiStatusTask::compute(ctx),+ TaskKind::UrlStatus => UrlStatusTask::compute(ctx),+ }+}++// ============================================================================+// Expected Results Tracking+// ============================================================================++/// Tracks expected result types per item for timeout diagnostics.+///+/// Populated at spawn time so we know exactly which results to expect,+/// without hardcoding result lists that could drift from the spawn functions.+#[derive(Default)]+pub(crate) struct ExpectedResults {+ inner: std::sync::Mutex<Vec<Vec<TaskKind>>>,+}++impl ExpectedResults {+ /// Record that we expect a result of the given kind for the given item.+ /// Called internally by `TaskSpawner::spawn()`.+ pub fn expect(&self, item_idx: usize, kind: TaskKind) {+ let mut inner = self.inner.lock().unwrap();+ if inner.len() <= item_idx {+ inner.resize_with(item_idx + 1, Vec::new);+ }+ inner[item_idx].push(kind);+ }++ /// Total number of expected results (for progress display).+ pub fn count(&self) -> usize {+ self.inner.lock().unwrap().iter().map(|v| v.len()).sum()+ }++ /// Expected results for a specific item.+ pub fn results_for(&self, item_idx: usize) -> Vec<TaskKind> {+ self.inner+ .lock()+ .unwrap()+ .get(item_idx)+ .cloned()+ .unwrap_or_default()+ }+}++// ============================================================================+// Work Item Generation+// ============================================================================++/// Generate work items for a worktree.+///+/// Returns a list of work items representing all tasks that should run for this+/// worktree. Expected results are registered internally as each work item is added.+/// The caller is responsible for executing the work items.+///+/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.+pub fn work_items_for_worktree(+ repo: &Repository,+ wt: &WorktreeInfo,+ item_idx: usize,+ options: &CollectOptions,+ expected_results: &Arc<ExpectedResults>,+ tx: &chan::Sender<Result<TaskResult, TaskError>>,+) -> Vec<WorkItem> {+ // Skip git operations for prunable worktrees (directory missing).+ if wt.is_prunable() {+ return vec![];+ }++ let skip = &options.skip_tasks;++ // Expand URL template for this item+ let item_url = options.url_template.as_ref().and_then(|template| {+ wt.branch.as_ref().and_then(|branch| {+ let mut vars = std::collections::HashMap::new();+ vars.insert("branch", branch.as_str());+ worktrunk::config::expand_template(template, &vars, false, repo).ok()+ })+ });++ // Send URL immediately (before health check) so it appears right away.+ // The UrlStatusTask will later update with active status.+ if let Some(ref url) = item_url {+ expected_results.expect(item_idx, TaskKind::UrlStatus);+ let _ = tx.send(Ok(TaskResult::UrlStatus {+ item_idx,+ url: Some(url.clone()),+ active: None,+ }));+ }++ let ctx = TaskContext {+ repo: repo.clone(),+ branch_ref: BranchRef::from(wt),+ item_idx,+ item_url,+ };++ // Check if this branch is stale and should skip expensive tasks.+ let is_stale = wt+ .branch+ .as_deref()+ .is_some_and(|b| options.stale_branches.contains(b));++ let mut items = Vec::with_capacity(15);++ // Helper to add a work item and register the expected result+ let mut add_item = |kind: TaskKind| {+ expected_results.expect(item_idx, kind);+ items.push(WorkItem {+ ctx: ctx.clone(),+ kind,+ });+ };++ for kind in [+ TaskKind::CommitDetails,+ TaskKind::AheadBehind,+ TaskKind::CommittedTreesMatch,+ TaskKind::HasFileChanges,+ TaskKind::IsAncestor,+ TaskKind::Upstream,+ TaskKind::WorkingTreeDiff,+ TaskKind::GitOperation,+ TaskKind::UserMarker,+ TaskKind::WorkingTreeConflicts,+ TaskKind::BranchDiff,+ TaskKind::MergeTreeConflicts,+ TaskKind::CiStatus,+ TaskKind::WouldMergeAdd,+ ] {+ if skip.contains(&kind) {+ continue;+ }+ // Skip expensive tasks for stale branches (far behind default branch)+ if is_stale && EXPENSIVE_TASKS.contains(&kind) {+ continue;+ }+ add_item(kind);+ }+ // URL status health check task (if we have a URL).+ // Note: We already registered and sent an immediate UrlStatus above with url + active=None.+ // This work item will send a second UrlStatus with active=Some(bool) after health check.+ // Both results must be registered and expected.+ if !skip.contains(&TaskKind::UrlStatus) && ctx.item_url.is_some() {+ expected_results.expect(item_idx, TaskKind::UrlStatus);+ items.push(WorkItem {+ ctx: ctx.clone(),+ kind: TaskKind::UrlStatus,+ });+ }++ items+}++/// Generate work items for a branch (no worktree).+///+/// Returns a list of work items representing all tasks that should run for this+/// branch. Branches have fewer tasks than worktrees (no working tree operations).+///+/// The `repo` parameter is cloned into each TaskContext, sharing its cache via Arc.+pub fn work_items_for_branch(+ repo: &Repository,+ branch_name: &str,+ commit_sha: &str,+ item_idx: usize,+ options: &CollectOptions,+ expected_results: &Arc<ExpectedResults>,+) -> Vec<WorkItem> {+ let skip = &options.skip_tasks;++ let ctx = TaskContext {+ repo: repo.clone(),+ branch_ref: BranchRef::branch_only(branch_name, commit_sha),+ item_idx,+ item_url: None, // Branches without worktrees don't have URLs+ };++ // Check if this branch is stale and should skip expensive tasks.+ let is_stale = options.stale_branches.contains(branch_name);++ let mut items = Vec::with_capacity(11);++ // Helper to add a work item and register the expected result+ let mut add_item = |kind: TaskKind| {+ expected_results.expect(item_idx, kind);+ items.push(WorkItem {+ ctx: ctx.clone(),+ kind,+ });+ };++ for kind in [+ TaskKind::CommitDetails,+ TaskKind::AheadBehind,+ TaskKind::CommittedTreesMatch,+ TaskKind::HasFileChanges,+ TaskKind::IsAncestor,+ TaskKind::Upstream,+ TaskKind::BranchDiff,+ TaskKind::MergeTreeConflicts,+ TaskKind::CiStatus,+ TaskKind::WouldMergeAdd,+ ] {+ if skip.contains(&kind) {+ continue;+ }+ // Skip expensive tasks for stale branches (far behind default branch)+ if is_stale && EXPENSIVE_TASKS.contains(&kind) {+ continue;+ }+ add_item(kind);+ }++ items+}diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsnew file mode 100644index 000000000..fb05d842a--- /dev/null+++ b/src/commands/list/collect/mod.rs@@ -0,0 +1,1111 @@+//! Worktree data collection with parallelized git operations.+//!+//! This module provides an efficient approach to collecting worktree data:+//! - All tasks flattened into a single Rayon work queue+//! - Network tasks (CI, URL) sorted to run last+//! - Progressive updates via channels (update UI as each task completes)+//!+//! ## Skeleton Performance+//!+//! The skeleton (placeholder table with loading indicators) must render as fast as possible+//! to give users immediate feedback. Every git command before skeleton adds latency.+//!+//! ### Fixed Command Count (O(1), not O(N))+//!+//! Pre-skeleton runs a **fixed number of git commands** regardless of worktree count.+//! This is achieved through:+//! - **Batching** — timestamp fetch passes all SHAs to one `git show` command+//! - **Parallelization** — independent commands run concurrently via `join!` macro+//!+//! **Steady-state (5-7 commands):**+//!+//! | Command | Purpose | Parallel |+//! |---------|---------|----------|+//! | `git worktree list --porcelain` | Enumerate worktrees | Sequential (required first) |+//! | `git config worktrunk.default-branch` | Cached default branch | ✓ |+//! | `git config --bool core.bare` | Bare repo check for expected-path logic | ✓ |+//! | `git rev-parse --show-toplevel` | Worktree root for project config | ✓ |+//! | `git for-each-ref refs/heads` | Only with `--branches` flag | ✓ |+//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag | ✓ |+//! | `git show -s --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |+//!+//! **Non-git operations (negligible latency):**+//! - Path canonicalization — detect current worktree+//! - Project config file read — check if URL column needed (no template expansion)+//!+//! ### First-Run Behavior+//!+//! When `worktrunk.default-branch` is not cached, `default_branch()` runs additional+//! commands to detect it:+//! 1. Query primary remote (origin/HEAD or `git ls-remote`)+//! 2. Fall back to local inference (check init.defaultBranch, common names)+//! 3. Cache result to `git config worktrunk.default-branch`+//!+//! Subsequent runs use the cached value — only one `git config` call.+//!+//! ### Post-Skeleton Operations+//!+//! After the skeleton renders, remaining setup runs before spawning the worker thread.+//! These operations are parallelized using `rayon::scope` with single-level parallelism:+//!+//! ```text+//! Skeleton render+//! ├─ is_builtin_fsmonitor_enabled() (5ms, sequential - gate)+//! ├─ rayon::scope(+//! │ ├─ get_switch_previous() (5ms)+//! │ ├─ integration_target() (10ms)+//! │ ├─ start_fsmonitor_daemon × N worktrees (6ms each, all parallel)+//! │ ) // ~10ms total (max of all spawns)+//! Worker thread spawns+//! ```+//!+//! **Why fsmonitor check is sequential:** It gates whether daemon starts are needed.+//! The check is fast (~5ms) and must complete before we know which spawns to add.+//!+//! **Why fsmonitor starts are in the parallel scope:** The `git fsmonitor--daemon start`+//! command returns quickly after signaling the daemon. By the time the worker thread+//! starts executing `git status` commands, daemons have had time to initialize.+//!+//! **Invalid default branch warning:** `invalid_default_branch_config()` reads the value+//! cached by `default_branch()` during pre-skeleton. It's a pure cache read.+//!+//! When adding new features, ask: "Can this be computed after skeleton?" If yes, defer it.+//! The skeleton shows `·` placeholder for gutter symbols, filled in when data loads.+//!+//! ## Unified Collection Architecture+//!+//! Progressive and buffered modes use the same collection and rendering code.+//! The only difference is whether intermediate updates are shown during collection:+//! - Progressive: renders a skeleton table and updates rows/footer as data arrives (TTY),+//! or renders once at the end (non-TTY)+//! - Buffered: collects silently, then renders the final table+//!+//! Both modes render the final table in `collect()`, ensuring a single canonical rendering path.+//!+//! **Flat parallelism**: All tasks (for all worktrees and branches) are collected into a single+//! work queue and processed via Rayon's thread pool. This avoids nested parallelism and keeps+//! utilization high regardless of worktree count (pool size is set at startup; default is 2x CPU+//! cores unless `RAYON_NUM_THREADS` is set).+//!+//! **Task ordering**: Work items are sorted so local git operations run first, network tasks+//! (CI status, URL health checks) run last. This ensures the table fills in quickly with local+//! data while slower network requests complete in the background.++mod execution;+mod results;+mod tasks;+mod types;++use anyhow::Context;+use color_print::cformat;+use crossbeam_channel as chan;+use dunce::canonicalize;+use once_cell::sync::OnceCell;+use rayon::prelude::*;+use std::sync::Arc;+use worktrunk::git::{Repository, WorktreeInfo};+use worktrunk::styling::{INFO_SYMBOL, format_with_gutter, hint_message, warning_message};++use crate::commands::is_worktree_at_expected_path;++use super::model::{DisplayFields, ItemKind, ListItem, WorktreeData};++// Re-exports for sibling modules (columns.rs, render.rs, layout.rs)+pub(crate) use tasks::parse_port_from_url;+pub(crate) use types::TaskKind;++// Internal imports+pub(crate) use execution::ExpectedResults;+use execution::{work_items_for_branch, work_items_for_worktree};+use results::drain_results;+use types::{DrainOutcome, StatusContext};+use types::{TaskError, TaskResult};++/// Options for controlling what data to collect.+///+/// This is operation parameters for a single `wt list` invocation, not a cache.+/// For cached repo data, see Repository's global cache.+#[derive(Clone, Default)]+pub struct CollectOptions {+ /// Tasks to skip (not compute). Empty set means compute everything.+ ///+ /// This controls both:+ /// - Work item generation (in `work_items_for_worktree`/`work_items_for_branch`)+ /// - Column visibility (layout filters columns via `ColumnSpec::requires_task`)+ pub skip_tasks: std::collections::HashSet<TaskKind>,++ /// URL template from project config (e.g., "http://localhost:{{ branch | hash_port }}").+ /// Expanded per-item in task spawning (post-skeleton) to minimize time-to-skeleton.+ pub url_template: Option<String>,++ /// Branches to skip expensive tasks for (behind > threshold).+ ///+ /// Presence in set = skip expensive tasks for this branch (HasFileChanges,+ /// IsAncestor, WouldMergeAdd, BranchDiff, MergeTreeConflicts).+ ///+ /// ## Why "commits behind" as the heuristic+ ///+ /// The expensive operations (`git merge-tree`, `git diff`) scale with:+ /// - **Files changed on both sides** — each needs 3-way merge or diff+ /// - **Size of those files** — content loading and merge algorithm+ ///+ /// Commit count isn't directly in the algorithm, but "commits behind" is a+ /// cheap proxy: more commits on main since divergence → more files main has+ /// touched → more potential overlap with the branch's changes.+ ///+ /// We use "behind" rather than "ahead" because feature branches typically+ /// have small ahead counts, so behind dominates. A more accurate heuristic+ /// would be `min(files_changed_on_main, files_changed_on_branch)`, but+ /// computing that requires per-branch git commands, defeating the optimization.+ ///+ /// The batch `git for-each-ref --format='%(ahead-behind:...)'` gives us all+ /// counts in a single command, making this heuristic essentially free.+ ///+ /// ## Implementation+ ///+ /// Built by filtering `batch_ahead_behind()` results on local branches only.+ /// Remote-only branches are never in this set (they use individual git commands).+ /// The threshold (default 50) is applied at construction time. Ahead/behind+ /// counts are cached in Repository and looked up by AheadBehindTask.+ ///+ /// **Display implications:** When tasks are skipped:+ /// - BranchDiff column shows `…` instead of diff stats+ /// - Status symbols (conflict `✗`, integrated `⊂`) may be missing or incorrect+ /// since they depend on skipped tasks+ ///+ /// Note: `wt select` doesn't show the BranchDiff column, so `…` isn't visible there.+ /// This is similar to how `✗` conflict only shows with `--full` even in `wt list`.+ ///+ /// TODO: Consider adding a visible indicator in Status column when integration+ /// checks are skipped, so users know the `⊂` symbol may be incomplete.+ pub stale_branches: std::collections::HashSet<String>,+}++fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> std::collections::HashSet<&str> {+ worktrees+ .iter()+ .filter_map(|wt| wt.branch.as_deref())+ .collect()+}++/// Collect worktree data with optional progressive rendering.+///+/// When `show_progress` is true, renders a skeleton immediately and updates as data arrives.+/// When false, behavior depends on `render_table`:+/// - If `render_table` is true: renders final table (buffered mode)+/// - If `render_table` is false: returns data without rendering (JSON mode)+///+/// The `command_timeout` parameter, if set, limits how long individual git commands can run.+/// This is useful for `wt select` to show the TUI faster by skipping slow operations.+///+/// TODO: Now that we skip expensive tasks for stale branches (see `skip_expensive_for_stale`),+/// the timeout may be unnecessary. Consider removing it if it doesn't provide value.+///+/// The `skip_expensive_for_stale` parameter enables batch-fetching ahead/behind counts and+/// skipping expensive merge-base operations for branches far behind the default branch.+/// This dramatically improves performance for repos with many stale branches.+#[allow(clippy::too_many_arguments)]+pub fn collect(+ repo: &Repository,+ show_branches: bool,+ show_remotes: bool,+ skip_tasks: &std::collections::HashSet<TaskKind>,+ show_progress: bool,+ render_table: bool,+ config: &worktrunk::config::WorktrunkConfig,+ command_timeout: Option<std::time::Duration>,+ skip_expensive_for_stale: bool,+) -> anyhow::Result<Option<super::model::ListData>> {+ use super::progressive_table::ProgressiveTable;+ worktrunk::shell_exec::trace_instant("List collect started");++ // Phase 1: Parallel fetch of ALL independent git data+ //+ // Key insight: most operations don't depend on each other. By running them all+ // in parallel via rayon::scope, we minimize wall-clock time. Dependencies:+ //+ // - worktree list: independent (needed for filtering and SHAs)+ // - default_branch: independent (git config + verify)+ // - is_bare: independent (git config, cached for later use)+ // - url_template: independent (loads project config via show-toplevel)+ // - local_branches: independent (for-each-ref, but filtering needs worktrees)+ // - remote_branches: independent (for-each-ref)+ //+ // After this scope completes, we have all raw data and can do CPU-only work.+ let worktrees_cell: OnceCell<anyhow::Result<Vec<WorktreeInfo>>> = OnceCell::new();+ let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();+ let url_template_cell: OnceCell<Option<String>> = OnceCell::new();+ let local_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();+ let remote_branches_cell: OnceCell<anyhow::Result<Vec<(String, String)>>> = OnceCell::new();++ rayon::scope(|s| {+ s.spawn(|_| {+ let _ = worktrees_cell.set(repo.list_worktrees());+ });+ s.spawn(|_| {+ let _ = default_branch_cell.set(repo.default_branch());+ });+ s.spawn(|_| {+ // Populate is_bare cache (value used later via repo_path)+ let _ = repo.is_bare();+ });+ s.spawn(|_| {+ let _ = url_template_cell.set(repo.url_template());+ });+ s.spawn(|_| {+ if show_branches {+ let _ = local_branches_cell.set(repo.list_local_branches());+ }+ });+ s.spawn(|_| {+ if show_remotes {+ let _ = remote_branches_cell.set(repo.list_untracked_remote_branches());+ }+ });+ });++ // Extract results+ let worktrees = worktrees_cell+ .into_inner()+ .unwrap()+ .context("Failed to list worktrees")?;+ if worktrees.is_empty() {+ return Ok(None);+ }+ let default_branch = default_branch_cell.into_inner().unwrap();+ let url_template = url_template_cell.into_inner().unwrap();++ // Filter local branches to those without worktrees (CPU-only, no git commands)+ let branches_without_worktrees = if show_branches {+ let all_local = local_branches_cell.into_inner().unwrap()?;+ let worktree_branches = worktree_branch_set(&worktrees);+ all_local+ .into_iter()+ .filter(|(name, _)| !worktree_branches.contains(name.as_str()))+ .collect()+ } else {+ Vec::new()+ };+ let remote_branches = if show_remotes {+ remote_branches_cell.into_inner().unwrap()?+ } else {+ Vec::new()+ };++ // Detect current worktree by checking if repo path is inside any worktree.+ // This avoids a git command - we just compare canonicalized paths.+ let repo_path_canonical = canonicalize(repo.discovery_path()).ok();+ let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {+ worktrees.iter().find_map(|wt| {+ canonicalize(&wt.path)+ .ok()+ .filter(|wt_path| repo_path.starts_with(wt_path))+ })+ });+ // Show warning if user configured a default branch that doesn't exist locally+ if let Some(configured) = repo.invalid_default_branch_config() {+ let msg =+ cformat!("Configured default branch <bold>{configured}</> does not exist locally");+ crate::output::print(warning_message(msg))?;+ let hint = cformat!("To reset, run <bright-black>wt config state default-branch clear</>");+ crate::output::print(hint_message(hint))?;+ }++ // Main worktree is the worktree on the default branch (if exists), else first non-prunable worktree.+ // find_home returns None if all worktrees are prunable or the list is empty.+ // TODO: show ellipsis or indicator when default_branch is None and columns are empty+ let main_worktree =+ WorktreeInfo::find_home(&worktrees, default_branch.as_deref().unwrap_or(""))+ .cloned()+ .ok_or_else(|| anyhow::anyhow!("No worktrees found"))?;++ // Defer previous_branch lookup until after skeleton - set is_previous later+ // (skeleton shows placeholder gutter, actual symbols appear when data loads)++ // Phase 3: Batch fetch timestamps (needs all SHAs from worktrees + branches)+ let all_shas: Vec<&str> = worktrees+ .iter()+ .map(|wt| wt.head.as_str())+ .chain(+ branches_without_worktrees+ .iter()+ .map(|(_, sha)| sha.as_str()),+ )+ .chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))+ .collect();+ let timestamps = repo.commit_timestamps(&all_shas).unwrap_or_default();++ // Sort worktrees: current first, main second, then by timestamp descending+ let sorted_worktrees = sort_worktrees_with_cache(+ worktrees.clone(),+ &main_worktree,+ current_worktree_path.as_ref(),+ ×tamps,+ );++ // Sort branches by timestamp (most recent first)+ let branches_without_worktrees =+ sort_by_timestamp_desc_with_cache(branches_without_worktrees, ×tamps, |(_, sha)| {+ sha.as_str()+ });+ let remote_branches =+ sort_by_timestamp_desc_with_cache(remote_branches, ×tamps, |(_, sha)| sha.as_str());++ // Pre-canonicalize main_worktree.path for is_main comparison+ // (paths from git worktree list may differ based on symlinks or working directory)+ let main_worktree_canonical = canonicalize(&main_worktree.path).ok();++ // URL template already fetched in parallel join (layout needs to know if column is needed)+ // Initialize worktree items with identity fields and None for computed fields+ let mut all_items: Vec<ListItem> = sorted_worktrees+ .iter()+ .map(|wt| {+ // Canonicalize paths for comparison - git worktree list may return different+ // path representations depending on symlinks or which directory you run from+ let wt_canonical = canonicalize(&wt.path).ok();+ let is_main = match (&wt_canonical, &main_worktree_canonical) {+ (Some(wt_c), Some(main_c)) => wt_c == main_c,+ // Fallback to direct comparison if canonicalization fails+ _ => wt.path == main_worktree.path,+ };+ let is_current = current_worktree_path+ .as_ref()+ .is_some_and(|cp| wt_canonical.as_ref() == Some(cp));+ // is_previous set to false initially - computed after skeleton+ let is_previous = false;++ // Check if worktree is at its expected path based on config template+ let branch_worktree_mismatch = !is_worktree_at_expected_path(wt, repo, config);++ let mut worktree_data =+ WorktreeData::from_worktree(wt, is_main, is_current, is_previous);+ worktree_data.branch_worktree_mismatch = branch_worktree_mismatch;++ // URL expanded post-skeleton to minimize time-to-skeleton+ ListItem {+ head: wt.head.clone(),+ branch: wt.branch.clone(),+ commit: None,+ counts: None,+ branch_diff: None,+ committed_trees_match: None,+ has_file_changes: None,+ would_merge_add: None,+ is_ancestor: None,+ is_orphan: None,+ upstream: None,+ pr_status: None,+ url: None,+ url_active: None,+ status_symbols: None,+ display: DisplayFields::default(),+ kind: ItemKind::Worktree(Box::new(worktree_data)),+ }+ })+ .collect();++ // Initialize branch items (local and remote) - URLs expanded post-skeleton+ let branch_start_idx = all_items.len();+ all_items.extend(+ branches_without_worktrees+ .iter()+ .map(|(name, sha)| ListItem::new_branch(sha.clone(), name.clone())),+ );++ let remote_start_idx = all_items.len();+ all_items.extend(+ remote_branches+ .iter()+ .map(|(name, sha)| ListItem::new_branch(sha.clone(), name.clone())),+ );++ // If no URL template configured, add UrlStatus to skip_tasks+ let mut effective_skip_tasks = skip_tasks.clone();+ if url_template.is_none() {+ effective_skip_tasks.insert(TaskKind::UrlStatus);+ }++ // Calculate layout from items (worktrees, local branches, and remote branches)+ let layout = super::layout::calculate_layout_from_basics(+ &all_items,+ &effective_skip_tasks,+ &main_worktree.path,+ url_template.as_deref(),+ );++ // Single-line invariant: use safe width to prevent line wrapping+ let max_width = crate::display::get_terminal_width();++ // Create collection options from skip set+ let mut options = CollectOptions {+ skip_tasks: effective_skip_tasks,+ url_template: url_template.clone(),+ ..Default::default()+ };++ // Track expected results per item - populated as spawns are queued+ let expected_results = std::sync::Arc::new(ExpectedResults::default());+ let num_worktrees = all_items+ .iter()+ .filter(|item| item.worktree_data().is_some())+ .count();+ let num_local_branches = branches_without_worktrees.len();+ let num_remote_branches = remote_branches.len();++ let footer_base =+ if (show_branches && num_local_branches > 0) || (show_remotes && num_remote_branches > 0) {+ let mut parts = vec![format!("{} worktrees", num_worktrees)];+ if show_branches && num_local_branches > 0 {+ parts.push(format!("{} branches", num_local_branches));+ }+ if show_remotes && num_remote_branches > 0 {+ parts.push(format!("{} remote branches", num_remote_branches));+ }+ format!("Showing {}", parts.join(", "))+ } else {+ let plural = if num_worktrees == 1 { "" } else { "s" };+ format!("Showing {} worktree{}", num_worktrees, plural)+ };++ // Create progressive table if showing progress+ let mut progressive_table = if show_progress {+ use anstyle::Style;+ let dim = Style::new().dimmed();++ // Build skeleton rows for both worktrees and branches+ // All items need skeleton rendering since computed data (timestamp, ahead/behind, etc.)+ // hasn't been loaded yet. Using format_list_item_line would show default values like "55y".+ let skeletons: Vec<String> = all_items+ .iter()+ .map(|item| layout.render_skeleton_row(item).render())+ .collect();++ let initial_footer = format!("{INFO_SYMBOL} {dim}{footer_base} (loading...){dim:#}");++ let mut table = ProgressiveTable::new(+ layout.format_header_line(),+ skeletons,+ initial_footer,+ max_width,+ );+ table.render_skeleton()?;+ worktrunk::shell_exec::trace_instant("Skeleton rendered");+ Some(table)+ } else {+ None+ };++ // Early exit for benchmarking skeleton render time+ if std::env::var("WORKTRUNK_SKELETON_ONLY").is_ok() {+ return Ok(None);+ }++ // === Post-skeleton computations (deferred to minimize time-to-skeleton) ===+ //+ // These operations run in parallel using rayon::scope with single-level parallelism.+ // See module docs for the timing diagram.++ // Collect worktree paths for fsmonitor starts (macOS only, fast, no git commands).+ // Git's builtin fsmonitor has race conditions under parallel load - pre-starting+ // daemons before parallel operations avoids hangs.+ #[cfg(target_os = "macos")]+ let fsmonitor_worktrees: Vec<_> = if repo.is_builtin_fsmonitor_enabled() {+ sorted_worktrees+ .iter()+ .filter(|wt| !wt.is_prunable())+ .collect()+ } else {+ vec![]+ };+ #[cfg(not(target_os = "macos"))]+ let fsmonitor_worktrees: Vec<&WorktreeInfo> = vec![];++ // Single-level parallelism: all spawns in one rayon::scope.+ // See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's fsmonitor workaround)+ // See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same fsmonitor issue)+ let previous_branch_cell: OnceCell<Option<String>> = OnceCell::new();+ let integration_target_cell: OnceCell<Option<String>> = OnceCell::new();++ rayon::scope(|s| {+ // Previous branch lookup (for gutter symbol)+ s.spawn(|_| {+ let _ = previous_branch_cell.set(repo.get_switch_previous());+ });++ // Integration target (upstream if ahead of local, else local)+ s.spawn(|_| {+ let _ = integration_target_cell.set(repo.integration_target());+ });++ // Fsmonitor daemon starts (one spawn per worktree)+ for wt in &fsmonitor_worktrees {+ s.spawn(|_| {+ repo.start_fsmonitor_daemon_at(&wt.path);+ });+ }+ });++ // Extract results from cells+ let previous_branch = previous_branch_cell.into_inner().flatten();+ let integration_target = integration_target_cell.into_inner().flatten();++ // Update is_previous on items+ if let Some(prev) = previous_branch.as_deref() {+ for item in &mut all_items {+ if item.branch.as_deref() == Some(prev)+ && let Some(wt_data) = item.worktree_data_mut()+ {+ wt_data.is_previous = true;+ }+ }+ }++ // Batch-fetch ahead/behind counts to identify branches that are far behind.+ // This allows skipping expensive merge-base operations for diverged branches, dramatically+ // improving performance on repos with many stale branches (e.g., wt select).+ //+ // Uses `git for-each-ref --format='%(ahead-behind:...)'` (git 2.36+) which gets all+ // counts in a single command. On older git versions, returns empty and all tasks run.+ // Skip if default_branch is unknown.+ if skip_expensive_for_stale && let Some(ref db) = default_branch {+ // Branches more than 50 commits behind skip expensive operations.+ // 50 is low enough to catch truly stale branches while keeping info for+ // recently-diverged ones.+ //+ // "Behind" is a proxy for the actual cost driver: files changed on both+ // sides since the merge-base. More commits on main → more files touched →+ // more overlap with the branch. See `CollectOptions::stale_branches` for+ // detailed rationale.+ let threshold: usize = std::env::var("WORKTRUNK_TEST_SKIP_EXPENSIVE_THRESHOLD")+ .ok()+ .and_then(|s| s.parse().ok())+ .unwrap_or(50);+ // batch_ahead_behind populates the Repository cache with all counts+ let ahead_behind = repo.batch_ahead_behind(db);+ // Filter to stale branches (behind > threshold). The set indicates which+ // branches should skip expensive tasks; counts come from the cache.+ options.stale_branches = ahead_behind+ .into_iter()+ .filter_map(|(branch, (_, behind))| (behind > threshold).then_some(branch))+ .collect();+ }++ // Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive+ // and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.++ // Cache last rendered (unclamped) message per row to avoid redundant updates.+ let mut last_rendered_lines: Vec<String> = vec![String::new(); all_items.len()];++ // Create channel for task results+ let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();++ // Collect errors for display after rendering+ let mut errors: Vec<TaskError> = Vec::new();++ // Collect all work items upfront, then execute in a single Rayon pool.+ // This avoids nested parallelism (Rayon par_iter → thread::scope per worktree)+ // which could create 100+ threads. Instead, we have one pool with the configured+ // thread count (default 2x CPU cores unless overridden by RAYON_NUM_THREADS).+ let sorted_worktrees_clone = sorted_worktrees.clone();+ let tx_worker = tx.clone();+ let expected_results_clone = expected_results.clone();++ // Clone repo for the worker thread (shares cache via Arc)+ let repo_clone = repo.clone();++ // Prepare branch data if needed (before moving into closure)+ let branch_data: Vec<(usize, String, String)> = if show_branches || show_remotes {+ let mut all_branches = Vec::new();+ if show_branches {+ all_branches.extend(+ branches_without_worktrees+ .iter()+ .enumerate()+ .map(|(idx, (name, sha))| (branch_start_idx + idx, name.clone(), sha.clone())),+ );+ }+ if show_remotes {+ all_branches.extend(+ remote_branches+ .iter()+ .enumerate()+ .map(|(idx, (name, sha))| (remote_start_idx + idx, name.clone(), sha.clone())),+ );+ }+ all_branches+ } else {+ Vec::new()+ };++ worktrunk::shell_exec::trace_instant("Spawning worker thread");+ std::thread::spawn(move || {+ // Phase 1: Generate all work items (sequential, fast)+ // Work items are collected upfront so we can process them all in a single par_iter.+ let mut all_work_items = Vec::new();++ // Worktree work items+ for (idx, wt) in sorted_worktrees_clone.iter().enumerate() {+ all_work_items.extend(work_items_for_worktree(+ &repo_clone,+ wt,+ idx,+ &options,+ &expected_results_clone,+ &tx_worker,+ ));+ }++ // Branch work items (local + remote)+ for (item_idx, branch_name, commit_sha) in &branch_data {+ all_work_items.extend(work_items_for_branch(+ &repo_clone,+ branch_name,+ commit_sha,+ *item_idx,+ &options,+ &expected_results_clone,+ ));+ }++ // Sort work items: network tasks last to avoid blocking local operations+ all_work_items.sort_by_key(|item| item.kind.is_network());++ // Phase 2: Execute all work items in parallel+ worktrunk::shell_exec::trace_instant("Parallel execution started");+ all_work_items.into_par_iter().for_each(|item| {+ worktrunk::shell_exec::set_command_timeout(command_timeout);+ let result = item.execute();+ let _ = tx_worker.send(result);+ });+ });++ // Drop the original sender so drain_results knows when all spawned threads are done+ drop(tx);++ // Track completed results for footer progress+ let mut completed_results = 0;+ let mut progress_overflow = false;+ let mut first_result_traced = false;++ // Drain task results with conditional progressive rendering+ let drain_outcome = drain_results(+ rx,+ &mut all_items,+ &mut errors,+ &expected_results,+ |item_idx, item, ctx| {+ // Trace first result arrival+ if !first_result_traced {+ first_result_traced = true;+ worktrunk::shell_exec::trace_instant("First result received");+ }++ // Compute/recompute status symbols as data arrives (both modes).+ // This is idempotent and updates status as new data (like upstream) arrives.+ if let Some(ref target) = integration_target {+ ctx.apply_to(item, target.as_str());+ }++ // Progressive mode only: update UI+ if let Some(ref mut table) = progressive_table {+ use anstyle::Style;+ let dim = Style::new().dimmed();++ completed_results += 1;+ let total_results = expected_results.count();++ // Catch counting bugs: completed should never exceed expected+ debug_assert!(+ completed_results <= total_results,+ "completed ({completed_results}) > expected ({total_results}): \+ task result sent without registering expectation"+ );+ if completed_results > total_results {+ progress_overflow = true;+ }++ // Update footer progress+ let footer_msg = format!(+ "{INFO_SYMBOL} {dim}{footer_base} ({completed_results}/{total_results} loaded){dim:#}"+ );+ table.update_footer(footer_msg);++ // Re-render the row with caching (now includes status if computed)+ let rendered = layout.format_list_item_line(item);++ // Compare using full line so changes beyond the clamp (e.g., CI) still refresh.+ if rendered != last_rendered_lines[item_idx] {+ last_rendered_lines[item_idx] = rendered.clone();+ table.update_row(item_idx, rendered);+ }++ // Flush updates to terminal+ if let Err(e) = table.flush() {+ log::debug!("Progressive table flush failed: {}", e);+ }+ }+ },+ );+ worktrunk::shell_exec::trace_instant("All results drained");++ // Handle timeout if it occurred+ if let DrainOutcome::TimedOut {+ received_count,+ items_with_missing,+ } = drain_outcome+ {+ // Build diagnostic message showing what's MISSING (more useful for debugging)+ let mut diag = format!("wt list timed out after 30s ({received_count} results received)");++ if !items_with_missing.is_empty() {+ diag.push_str("\nMissing results:");+ let missing_lines: Vec<String> = items_with_missing+ .iter()+ .map(|result| {+ let missing_names: Vec<&str> =+ result.missing_kinds.iter().map(|k| k.into()).collect();+ cformat!("<bold>{}</>: {}", result.name, missing_names.join(", "))+ })+ .collect();+ diag.push_str(&format!(+ "\n{}",+ format_with_gutter(&missing_lines.join("\n"), None)+ ));+ }++ diag.push_str(+ "\n\nThis likely indicates a git command hung. Run with -v for details, -vv to create a diagnostic file.",+ );++ crate::output::print(warning_message(&diag))?;++ // Show issue reporting hint (free function - doesn't collect diagnostic data)+ crate::output::print(hint_message(crate::diagnostic::issue_hint()))?;+ }++ // Compute status symbols for prunable worktrees (skipped during task spawning).+ // They didn't receive any task results, so status_symbols is still None.+ for item in &mut all_items {+ if item.status_symbols.is_none()+ && let Some(data) = item.worktree_data()+ && data.is_prunable()+ {+ // Use default context - no tasks ran, so no conflict/status info+ let ctx = StatusContext::default();+ if let Some(ref target) = integration_target {+ ctx.apply_to(item, target.as_str());+ }+ }+ }++ // Count errors for summary+ let error_count = errors.len();+ let timed_out_count = errors.iter().filter(|e| e.is_timeout()).count();++ // Finalize progressive table or render buffered output+ if let Some(mut table) = progressive_table {+ // Build final summary string+ let final_msg = super::format_summary_message(+ &all_items,+ show_branches || show_remotes,+ layout.hidden_column_count,+ error_count,+ timed_out_count,+ );++ if table.is_tty() {+ // Interactive: do final render pass and update footer to summary+ for (item_idx, item) in all_items.iter().enumerate() {+ let rendered = layout.format_list_item_line(item);+ table.update_row(item_idx, rendered);+ }+ table.finalize(final_msg)?;+ } else {+ // Non-TTY: output to stdout (same as buffered mode)+ // Progressive skeleton was suppressed; now output the final table+ crate::output::stdout(layout.format_header_line())?;+ for item in &all_items {+ crate::output::stdout(layout.format_list_item_line(item))?;+ }+ crate::output::stdout("")?;+ crate::output::stdout(final_msg)?;+ }+ } else if render_table {+ // Buffered mode: render final table+ let final_msg = super::format_summary_message(+ &all_items,+ show_branches || show_remotes,+ layout.hidden_column_count,+ error_count,+ timed_out_count,+ );++ crate::output::stdout(layout.format_header_line())?;+ for item in &all_items {+ crate::output::stdout(layout.format_list_item_line(item))?;+ }+ crate::output::stdout("")?;+ crate::output::stdout(final_msg)?;+ }++ // Status symbols are now computed during data collection (both modes), no fallback needed++ // Display collection errors/warnings (after table rendering)+ // Filter out timeout errors - they're shown in the summary footer+ let non_timeout_errors: Vec<_> = errors.iter().filter(|e| !e.is_timeout()).collect();++ if !non_timeout_errors.is_empty() || progress_overflow {+ let mut warning_parts = Vec::new();++ if !non_timeout_errors.is_empty() {+ // Sort for deterministic output (tasks complete in arbitrary order)+ let mut sorted_errors = non_timeout_errors;+ sorted_errors.sort_by_key(|e| (e.item_idx, e.kind));+ let error_lines: Vec<String> = sorted_errors+ .iter()+ .map(|error| {+ let name = all_items[error.item_idx].branch_name();+ let kind_str: &'static str = error.kind.into();+ // Take first line only - git errors can be multi-line with usage hints+ let msg = error.message.lines().next().unwrap_or(&error.message);+ cformat!("<bold>{}</>: {} ({})", name, kind_str, msg)+ })+ .collect();+ warning_parts.push(format!(+ "Some git operations failed:\n{}",+ format_with_gutter(&error_lines.join("\n"), None)+ ));+ }++ if progress_overflow {+ // Defensive: should never trigger now that immediate URL sends register expectations,+ // but kept to detect future counting bugs+ warning_parts.push("Progress counter overflow (completed > expected)".to_string());+ }++ let warning = warning_parts.join("\n");+ crate::output::print(warning_message(&warning))?;++ // Show issue reporting hint (free function - doesn't collect diagnostic data)+ crate::output::print(hint_message(crate::diagnostic::issue_hint()))?;+ }++ // Populate display fields for all items (used by JSON output and statusline)+ for item in &mut all_items {+ item.finalize_display();+ }++ // all_items now contains both worktrees and branches (if requested)+ let items = all_items;++ // Table rendering complete (when render_table=true):+ // - Progressive + TTY: rows morphed in place, footer became summary+ // - Progressive + Non-TTY: rendered final table (no intermediate output)+ // - Buffered: rendered final table+ // JSON mode (render_table=false): no rendering, data returned for serialization+ worktrunk::shell_exec::trace_instant("List collect complete");++ Ok(Some(super::model::ListData {+ items,+ main_worktree_path: main_worktree.path.clone(),+ }))+}++// ============================================================================+// Sorting Helpers+// ============================================================================++/// Sort items by timestamp descending using pre-fetched timestamps.+fn sort_by_timestamp_desc_with_cache<T, F>(+ items: Vec<T>,+ timestamps: &std::collections::HashMap<String, i64>,+ get_sha: F,+) -> Vec<T>+where+ F: Fn(&T) -> &str,+{+ // Embed timestamp in tuple to avoid parallel Vec and index lookups+ let mut with_ts: Vec<_> = items+ .into_iter()+ .map(|item| {+ let ts = *timestamps.get(get_sha(&item)).unwrap_or(&0);+ (item, ts)+ })+ .collect();+ with_ts.sort_by_key(|(_, ts)| std::cmp::Reverse(*ts));+ with_ts.into_iter().map(|(item, _)| item).collect()+}++/// Sort worktrees: current first, main second, then by timestamp descending.+/// Uses pre-fetched timestamps for efficiency.+fn sort_worktrees_with_cache(+ worktrees: Vec<WorktreeInfo>,+ main_worktree: &WorktreeInfo,+ current_path: Option<&std::path::PathBuf>,+ timestamps: &std::collections::HashMap<String, i64>,+) -> Vec<WorktreeInfo> {+ // Embed timestamp and priority in tuple to avoid parallel Vec and index lookups+ let mut with_sort_key: Vec<_> = worktrees+ .into_iter()+ .map(|wt| {+ let priority = if current_path.is_some_and(|cp| &wt.path == cp) {+ 0 // Current first+ } else if wt.path == main_worktree.path {+ 1 // Main second+ } else {+ 2 // Rest by timestamp+ };+ let ts = *timestamps.get(&wt.head).unwrap_or(&0);+ (wt, priority, ts)+ })+ .collect();++ with_sort_key.sort_by_key(|(_, priority, ts)| (*priority, std::cmp::Reverse(*ts)));+ with_sort_key.into_iter().map(|(wt, _, _)| wt).collect()+}++// ============================================================================+// Public API for single-worktree collection (used by statusline)+// ============================================================================++/// Build a ListItem for a single worktree with identity fields only.+///+/// Computed fields (counts, diffs, CI) are left as None. Use `populate_item()`+/// to fill them in.+pub fn build_worktree_item(+ wt: &WorktreeInfo,+ is_main: bool,+ is_current: bool,+ is_previous: bool,+) -> ListItem {+ ListItem {+ head: wt.head.clone(),+ branch: wt.branch.clone(),+ commit: None,+ counts: None,+ branch_diff: None,+ committed_trees_match: None,+ has_file_changes: None,+ would_merge_add: None,+ is_ancestor: None,+ is_orphan: None,+ upstream: None,+ pr_status: None,+ url: None,+ url_active: None,+ status_symbols: None,+ display: DisplayFields::default(),+ kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(+ wt,+ is_main,+ is_current,+ is_previous,+ ))),+ }+}++/// Populate computed fields for items in parallel (blocking).+///+/// Spawns parallel git operations and collects results. Modifies items in place+/// with: commit details, ahead/behind, diffs, upstream, CI, etc.+///+/// # Parameters+/// - `repo`: Repository handle (cloned into background thread, shares cache via Arc)+///+/// This is the blocking version used by statusline. For progressive rendering+/// with callbacks, see the `collect()` function.+pub fn populate_item(+ repo: &Repository,+ item: &mut ListItem,+ options: CollectOptions,+) -> anyhow::Result<()> {+ // Extract worktree data (skip if not a worktree item)+ let Some(data) = item.worktree_data() else {+ return Ok(());+ };++ // Get integration target for status symbol computation (cached in repo)+ // None if default branch cannot be determined - status symbols will be skipped+ let target = repo.integration_target();++ // Create channel for task results+ let (tx, rx) = chan::unbounded::<Result<TaskResult, TaskError>>();++ // Track expected results (populated at spawn time)+ let expected_results = Arc::new(ExpectedResults::default());++ // Collect errors (logged silently for statusline)+ let mut errors: Vec<TaskError> = Vec::new();++ // Extract data for background thread (can't send borrows across threads)+ let wt = WorktreeInfo {+ path: data.path.clone(),+ head: item.head.clone(),+ branch: item.branch.clone(),+ bare: false,+ detached: false,+ locked: None,+ prunable: None,+ };+ let repo_clone = repo.clone();+ let expected_results_clone = expected_results.clone();++ // Spawn collection in background thread+ std::thread::spawn(move || {+ // Generate work items for this single worktree+ let mut work_items = work_items_for_worktree(+ &repo_clone,+ &wt,+ 0, // Single item, always index 0+ &options,+ &expected_results_clone,+ &tx,+ );++ // Sort: network tasks last+ work_items.sort_by_key(|item| item.kind.is_network());++ // Execute all tasks in parallel+ work_items.into_par_iter().for_each(|item| {+ let result = item.execute();+ let _ = tx.send(result);+ });+ });++ // Drain task results (blocking until complete)+ let drain_outcome = drain_results(+ rx,+ std::slice::from_mut(item),+ &mut errors,+ &expected_results,+ |_item_idx, item, ctx| {+ if let Some(ref t) = target {+ ctx.apply_to(item, t);+ }+ },+ );++ // Handle timeout (silent for statusline - just log it)+ if let DrainOutcome::TimedOut { received_count, .. } = drain_outcome {+ log::warn!("populate_item timed out after 30s ({received_count} results received)");+ }++ // Log errors silently (statusline shouldn't spam warnings)+ if !errors.is_empty() {+ log::warn!("populate_item had {} task errors", errors.len());+ for error in &errors {+ let kind_str: &'static str = error.kind.into();+ log::debug!(+ " - item {}: {} ({})",+ error.item_idx,+ kind_str,+ error.message+ );+ }+ }++ // Populate display fields (including status_line for statusline command)+ item.finalize_display();++ Ok(())+}diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rsnew file mode 100644index 000000000..50d7d49b0--- /dev/null+++ b/src/commands/list/collect/results.rs@@ -0,0 +1,300 @@+//! Result processing and draining.+//!+//! Contains the logic for processing task results:+//! - `drain_results()` - drain channel and apply results to items+//! - `apply_default()` - apply defaults for failed tasks++use crossbeam_channel as chan;+use worktrunk::git::LineDiff;++use super::super::model::{CommitDetails, ItemKind, ListItem, UpstreamStatus, WorkingTreeStatus};+use super::execution::ExpectedResults;+use super::types::{DrainOutcome, MissingResult, StatusContext, TaskError, TaskKind, TaskResult};++/// Apply default values for a failed task.+///+/// When a task fails, we still need to populate the item fields with sensible+/// defaults so the UI can render. This centralizes all default logic in one place.+pub(super) fn apply_default(+ items: &mut [ListItem],+ status_contexts: &mut [StatusContext],+ error: &TaskError,+) {+ let idx = error.item_idx;+ match error.kind {+ TaskKind::CommitDetails => {+ items[idx].commit = Some(CommitDetails::default());+ }+ TaskKind::AheadBehind => {+ // Leave as None — UI shows `⋯` for not-loaded tasks+ // Conservative: don't claim orphan if we couldn't check+ items[idx].is_orphan = Some(false);+ }+ TaskKind::CommittedTreesMatch => {+ // Conservative: don't claim integrated if we couldn't check+ items[idx].committed_trees_match = Some(false);+ }+ TaskKind::HasFileChanges => {+ // Conservative: assume has changes if we couldn't check+ items[idx].has_file_changes = Some(true);+ }+ TaskKind::WouldMergeAdd => {+ // Conservative: assume would add changes if we couldn't check+ items[idx].would_merge_add = Some(true);+ }+ TaskKind::IsAncestor => {+ // Conservative: don't claim merged if we couldn't check+ items[idx].is_ancestor = Some(false);+ }+ TaskKind::BranchDiff => {+ // Leave as None — UI shows `…` for skipped/failed tasks+ }+ TaskKind::WorkingTreeDiff => {+ if let ItemKind::Worktree(data) = &mut items[idx].kind {+ data.working_tree_diff = Some(LineDiff::default());+ } else {+ debug_assert!(false, "WorkingTreeDiff task spawned for non-worktree item");+ }+ status_contexts[idx].working_tree_status = Some(WorkingTreeStatus::default());+ status_contexts[idx].has_conflicts = false;+ }+ TaskKind::MergeTreeConflicts => {+ // Don't show conflict symbol if we couldn't check+ status_contexts[idx].has_merge_tree_conflicts = false;+ }+ TaskKind::WorkingTreeConflicts => {+ // Fall back to commit-based check on failure+ status_contexts[idx].has_working_tree_conflicts = None;+ }+ TaskKind::GitOperation => {+ // Already defaults to GitOperationState::None in WorktreeData+ }+ TaskKind::UserMarker => {+ // Already defaults to None+ status_contexts[idx].user_marker = None;+ }+ TaskKind::Upstream => {+ items[idx].upstream = Some(UpstreamStatus::default());+ }+ TaskKind::CiStatus => {+ // Leave as None (not fetched) on error. This allows the hint path+ // in mod.rs to run and show "install gh/glab" when CI tools fail.+ // Some(None) means "CI tool ran successfully but found no PR".+ }+ TaskKind::UrlStatus => {+ // URL is set at item creation, only default url_active+ items[idx].url_active = None;+ }+ }+}++/// Drain task results from the channel and apply them to items.+///+/// This is the shared logic between progressive and buffered collection modes.+/// The `on_result` callback is called after each result is processed with the+/// item index and a reference to the updated item, allowing progressive mode+/// to update the live table while buffered mode does nothing.+///+/// Uses a 30-second deadline to prevent infinite hangs if git commands stall.+/// When timeout occurs, returns `DrainOutcome::TimedOut` with diagnostic info.+///+/// Errors are collected in the `errors` vec for display after rendering.+/// Default values are applied for failed tasks so the UI can still render.+///+/// Callers decide how to handle timeout:+/// - `collect()`: Shows user-facing diagnostic (interactive command)+/// - `populate_item()`: Logs silently (used by statusline)+pub(super) fn drain_results(+ rx: chan::Receiver<Result<TaskResult, TaskError>>,+ items: &mut [ListItem],+ errors: &mut Vec<TaskError>,+ expected_results: &ExpectedResults,+ mut on_result: impl FnMut(usize, &mut ListItem, &StatusContext),+) -> DrainOutcome {+ use std::time::{Duration, Instant};++ // Deadline for the entire drain operation (30 seconds should be more than enough)+ let deadline = Instant::now() + Duration::from_secs(30);++ // Track which result kinds we've received per item (for timeout diagnostics)+ let mut received_by_item: Vec<Vec<TaskKind>> = vec![Vec::new(); items.len()];++ // Temporary storage for data needed by status_symbols computation+ let mut status_contexts = vec![StatusContext::default(); items.len()];++ // Process task results as they arrive (with deadline)+ loop {+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ // Deadline exceeded - build diagnostic info showing MISSING results+ let received_count: usize = received_by_item.iter().map(|v| v.len()).sum();++ // Find items with missing results by comparing received vs expected+ let mut items_with_missing: Vec<MissingResult> = Vec::new();++ for (item_idx, item) in items.iter().enumerate() {+ // Get expected results for this item (populated at spawn time)+ let expected = expected_results.results_for(item_idx);++ // Get received results for this item (empty vec if none received)+ let received = received_by_item[item_idx].as_slice();++ // Find missing results+ let missing_kinds: Vec<TaskKind> = expected+ .iter()+ .filter(|kind| !received.contains(kind))+ .copied()+ .collect();++ if !missing_kinds.is_empty() {+ let name = item+ .branch+ .clone()+ .unwrap_or_else(|| item.head[..8.min(item.head.len())].to_string());+ items_with_missing.push(MissingResult {+ item_idx,+ name,+ missing_kinds,+ });+ }+ }++ // Sort by item index and limit to first 5+ items_with_missing.sort_by_key(|result| result.item_idx);+ items_with_missing.truncate(5);++ return DrainOutcome::TimedOut {+ received_count,+ items_with_missing,+ };+ }++ let outcome = match rx.recv_timeout(remaining) {+ Ok(outcome) => outcome,+ Err(chan::RecvTimeoutError::Timeout) => continue, // Check deadline in next iteration+ Err(chan::RecvTimeoutError::Disconnected) => break, // All senders dropped - done+ };++ // Handle success or error+ let (item_idx, kind) = match outcome {+ Ok(ref result) => (result.item_idx(), TaskKind::from(result)),+ Err(ref error) => (error.item_idx, error.kind),+ };++ // Track this result for diagnostics (both success and error count as "received")+ received_by_item[item_idx].push(kind);++ // Handle error case: apply defaults and collect error+ if let Err(error) = outcome {+ apply_default(items, &mut status_contexts, &error);+ errors.push(error);+ let item = &mut items[item_idx];+ let status_ctx = &status_contexts[item_idx];+ on_result(item_idx, item, status_ctx);+ continue;+ }++ // Handle success case+ let result = outcome.unwrap();+ let item = &mut items[item_idx];+ let status_ctx = &mut status_contexts[item_idx];++ match result {+ TaskResult::CommitDetails { commit, .. } => {+ item.commit = Some(commit);+ }+ TaskResult::AheadBehind {+ counts, is_orphan, ..+ } => {+ item.counts = Some(counts);+ item.is_orphan = Some(is_orphan);+ }+ TaskResult::CommittedTreesMatch {+ committed_trees_match,+ ..+ } => {+ item.committed_trees_match = Some(committed_trees_match);+ }+ TaskResult::HasFileChanges {+ has_file_changes, ..+ } => {+ item.has_file_changes = Some(has_file_changes);+ }+ TaskResult::WouldMergeAdd {+ would_merge_add, ..+ } => {+ item.would_merge_add = Some(would_merge_add);+ }+ TaskResult::IsAncestor { is_ancestor, .. } => {+ item.is_ancestor = Some(is_ancestor);+ }+ TaskResult::BranchDiff { branch_diff, .. } => {+ item.branch_diff = Some(branch_diff);+ }+ TaskResult::WorkingTreeDiff {+ working_tree_diff,+ working_tree_status,+ has_conflicts,+ ..+ } => {+ if let ItemKind::Worktree(data) = &mut item.kind {+ data.working_tree_diff = Some(working_tree_diff);+ } else {+ debug_assert!(false, "WorkingTreeDiff result for non-worktree item");+ }+ // Store for status_symbols computation+ status_ctx.working_tree_status = Some(working_tree_status);+ status_ctx.has_conflicts = has_conflicts;+ }+ TaskResult::MergeTreeConflicts {+ has_merge_tree_conflicts,+ ..+ } => {+ // Store for status_symbols computation+ status_ctx.has_merge_tree_conflicts = has_merge_tree_conflicts;+ }+ TaskResult::WorkingTreeConflicts {+ has_working_tree_conflicts,+ ..+ } => {+ // Store for status_symbols computation (takes precedence over commit check)+ status_ctx.has_working_tree_conflicts = has_working_tree_conflicts;+ }+ TaskResult::GitOperation { git_operation, .. } => {+ if let ItemKind::Worktree(data) = &mut item.kind {+ data.git_operation = git_operation;+ } else {+ debug_assert!(false, "GitOperation result for non-worktree item");+ }+ }+ TaskResult::UserMarker { user_marker, .. } => {+ // Store for status_symbols computation+ status_ctx.user_marker = user_marker;+ }+ TaskResult::Upstream { upstream, .. } => {+ item.upstream = Some(upstream);+ }+ TaskResult::CiStatus { pr_status, .. } => {+ // Wrap in Some() to indicate "loaded" (Some(None) = no CI, Some(Some(status)) = has CI)+ item.pr_status = Some(pr_status);+ }+ TaskResult::UrlStatus { url, active, .. } => {+ // Two-phase URL rendering:+ // 1. First result (from spawning code): url=Some, active=None → URL appears in normal styling+ // 2. Second result (from health check): url=None, active=Some → dims if inactive+ // Only update non-None fields to preserve values from earlier results.+ if url.is_some() {+ item.url = url;+ }+ if active.is_some() {+ item.url_active = active;+ }+ }+ }++ // Invoke callback (progressive mode re-renders rows, buffered mode does nothing)+ on_result(item_idx, item, status_ctx);+ }++ DrainOutcome::Complete+}diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsnew file mode 100644index 000000000..815573db9--- /dev/null+++ b/src/commands/list/collect/tasks.rs@@ -0,0 +1,742 @@+//! Task trait and implementations.+//!+//! Contains the `Task` trait interface and all 15 task implementations that+//! compute various git operations for worktrees and branches.++use worktrunk::git::{LineDiff, Repository};++use super::super::ci_status::PrStatus;+use super::super::model::{+ AheadBehind, BranchDiffTotals, CommitDetails, GitOperationState, UpstreamStatus,+ WorkingTreeStatus,+};+use super::types::{ErrorCause, TaskError, TaskKind, TaskResult};++// ============================================================================+// Task Context+// ============================================================================++/// Context for task computation. Cloned and moved into spawned threads.+///+/// Contains all data needed by any task. The `repo` field shares its cache+/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from+/// cached merge-base results, ahead/behind counts, default branch, and+/// integration target.+#[derive(Clone)]+pub struct TaskContext {+ /// Shared repository handle. All clones share the same cache via Arc.+ pub repo: Repository,+ /// The branch this task operates on. Contains branch name, commit SHA,+ /// and optional worktree path.+ ///+ /// For worktree-specific operations, use `self.worktree()` which returns+ /// `Some(WorkingTree)` only when this ref has a worktree path.+ pub branch_ref: worktrunk::git::BranchRef,+ pub item_idx: usize,+ /// Expanded URL for this item (from project config template).+ /// UrlStatusTask uses this to check if the port is listening.+ pub item_url: Option<String>,+}++impl TaskContext {+ pub(super) fn error(&self, kind: TaskKind, err: &anyhow::Error) -> TaskError {+ // Check if any error in the chain is a timeout+ let is_timeout = err.chain().any(|e| {+ e.downcast_ref::<std::io::Error>()+ .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::TimedOut)+ });++ let cause = if is_timeout {+ let kind_str: &'static str = kind.into();+ let sha = &self.branch_ref.commit_sha;+ let short_sha = &sha[..sha.len().min(8)];+ let branch = self.branch_ref.branch.as_deref().unwrap_or(short_sha);+ log::debug!("Task {} timed out for {}", kind_str, branch);+ ErrorCause::Timeout+ } else {+ ErrorCause::Other+ };+ TaskError::new(self.item_idx, kind, err.to_string(), cause)+ }++ /// Get the default branch (cached in Repository).+ ///+ /// Used for informational stats (ahead/behind, branch diff).+ /// Returns None if default branch cannot be determined.+ pub(super) fn default_branch(&self) -> Option<String> {+ self.repo.default_branch()+ }++ /// Get the integration target (cached in Repository).+ ///+ /// Used for integration checks (status symbols, safe deletion).+ /// Returns None if default branch cannot be determined.+ pub(super) fn integration_target(&self) -> Option<String> {+ self.repo.integration_target()+ }+}++// ============================================================================+// Task Trait+// ============================================================================++/// A task that computes a single `TaskResult`.+///+/// Each task type has a compile-time `KIND` that determines which `TaskResult`+/// variant it produces. The `compute()` function receives a cloned context and+/// returns a Result - either the successful result or an error.+///+/// Tasks should propagate errors via `?` rather than swallowing them.+/// The drain layer handles defaults and collects errors for display.+pub trait Task: Send + Sync + 'static {+ /// The kind of result this task produces (compile-time constant).+ const KIND: TaskKind;++ /// Compute the task result. Called in a spawned thread.+ /// Returns Ok(result) on success, Err(TaskError) on failure.+ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError>;+}++// ============================================================================+// Task Implementations+// ============================================================================++/// Task 1: Commit details (timestamp, message)+pub struct CommitDetailsTask;++impl Task for CommitDetailsTask {+ const KIND: TaskKind = TaskKind::CommitDetails;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ let repo = &ctx.repo;+ let (timestamp, commit_message) = repo+ .commit_details(&ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ Ok(TaskResult::CommitDetails {+ item_idx: ctx.item_idx,+ commit: CommitDetails {+ timestamp,+ commit_message,+ },+ })+ }+}++/// Task 2: Ahead/behind counts vs local default branch (informational stats)+pub struct AheadBehindTask;++impl Task for AheadBehindTask {+ const KIND: TaskKind = TaskKind::AheadBehind;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When default_branch is None, return zero counts (cells show empty)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::AheadBehind {+ item_idx: ctx.item_idx,+ counts: AheadBehind::default(),+ is_orphan: false,+ });+ };+ let repo = &ctx.repo;++ // Check for orphan branch (no common ancestor with default branch).+ // merge_base() is cached, so this is cheap after first call.+ let is_orphan = repo+ .merge_base(&base, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?+ .is_none();++ if is_orphan {+ return Ok(TaskResult::AheadBehind {+ item_idx: ctx.item_idx,+ counts: AheadBehind::default(),+ is_orphan: true,+ });+ }++ // Check cache first (populated by batch_ahead_behind if it ran).+ // Cache lookup has minor overhead (rev-parse for cache key + allocations),+ // but saves the expensive ahead_behind computation on cache hit.+ let (ahead, behind) = if let Some(branch) = ctx.branch_ref.branch.as_deref() {+ if let Some(counts) = repo.get_cached_ahead_behind(&base, branch) {+ counts+ } else {+ repo.ahead_behind(&base, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?+ }+ } else {+ repo.ahead_behind(&base, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?+ };++ Ok(TaskResult::AheadBehind {+ item_idx: ctx.item_idx,+ counts: AheadBehind { ahead, behind },+ is_orphan: false,+ })+ }+}++/// Task 3: Tree identity check (does the item's commit tree match integration target's tree?)+///+/// Uses target for integration detection (squash merge, rebase).+pub struct CommittedTreesMatchTask;++impl Task for CommittedTreesMatchTask {+ const KIND: TaskKind = TaskKind::CommittedTreesMatch;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When integration_target is None, return false (conservative: don't mark as integrated)+ let Some(base) = ctx.integration_target() else {+ return Ok(TaskResult::CommittedTreesMatch {+ item_idx: ctx.item_idx,+ committed_trees_match: false,+ });+ };+ let repo = &ctx.repo;+ // Use the item's commit instead of HEAD, since for branches without+ // worktrees, HEAD is the main worktree's HEAD.+ let committed_trees_match = repo+ .trees_match(&ctx.branch_ref.commit_sha, &base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ Ok(TaskResult::CommittedTreesMatch {+ item_idx: ctx.item_idx,+ committed_trees_match,+ })+ }+}++/// Task 3b: File changes check (does branch have file changes beyond merge-base?)+///+/// Uses three-dot diff (`target...branch`) to detect if the branch has any file+/// changes relative to the merge-base with target. Returns false when the diff+/// is empty, indicating the branch content is already integrated.+///+/// This catches branches where commits exist (ahead > 0) but those commits+/// don't add any file changes - e.g., squash-merged branches, merge commits+/// that pulled in main, or commits whose changes were reverted.+///+/// Uses target for integration detection.+pub struct HasFileChangesTask;++impl Task for HasFileChangesTask {+ const KIND: TaskKind = TaskKind::HasFileChanges;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // No branch name (detached HEAD) - return conservative default (assume has changes)+ let Some(branch) = ctx.branch_ref.branch.as_deref() else {+ return Ok(TaskResult::HasFileChanges {+ item_idx: ctx.item_idx,+ has_file_changes: true,+ });+ };+ // When integration_target is None, return true (conservative: assume has changes)+ let Some(target) = ctx.integration_target() else {+ return Ok(TaskResult::HasFileChanges {+ item_idx: ctx.item_idx,+ has_file_changes: true,+ });+ };+ let repo = &ctx.repo;+ let has_file_changes = repo+ .has_added_changes(branch, &target)+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ Ok(TaskResult::HasFileChanges {+ item_idx: ctx.item_idx,+ has_file_changes,+ })+ }+}++/// Task 3b: Merge simulation+///+/// Checks if merging the branch into target would add any changes by simulating+/// the merge with `git merge-tree --write-tree`. Returns false when the merge+/// result equals target's tree, indicating the branch is already integrated.+///+/// This catches branches where target has advanced past the squash-merge point -+/// the three-dot diff might show changes, but those changes are already in target+/// via the squash merge.+///+/// Uses target for integration detection.+pub struct WouldMergeAddTask;++impl Task for WouldMergeAddTask {+ const KIND: TaskKind = TaskKind::WouldMergeAdd;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // No branch name (detached HEAD) - return conservative default (assume would add)+ let Some(branch) = ctx.branch_ref.branch.as_deref() else {+ return Ok(TaskResult::WouldMergeAdd {+ item_idx: ctx.item_idx,+ would_merge_add: true,+ });+ };+ // When integration_target is None, return true (conservative: assume would add)+ let Some(base) = ctx.integration_target() else {+ return Ok(TaskResult::WouldMergeAdd {+ item_idx: ctx.item_idx,+ would_merge_add: true,+ });+ };+ let repo = &ctx.repo;+ let would_merge_add = repo+ .would_merge_add_to_target(branch, &base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ Ok(TaskResult::WouldMergeAdd {+ item_idx: ctx.item_idx,+ would_merge_add,+ })+ }+}++/// Task 3c: Ancestor check (is branch HEAD an ancestor of integration target?)+///+/// Checks if branch is an ancestor of target - runs `git merge-base --is-ancestor`.+/// Returns true when the branch HEAD is in target's history (merged via fast-forward+/// or rebase).+///+/// Uses target (target) for the Ancestor integration reason in `⊂`.+/// The `_` symbol uses ahead/behind counts (vs default_branch) instead.+pub struct IsAncestorTask;++impl Task for IsAncestorTask {+ const KIND: TaskKind = TaskKind::IsAncestor;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When integration_target is None, return false (conservative: don't mark as ancestor)+ let Some(base) = ctx.integration_target() else {+ return Ok(TaskResult::IsAncestor {+ item_idx: ctx.item_idx,+ is_ancestor: false,+ });+ };+ let repo = &ctx.repo;+ let is_ancestor = repo+ .is_ancestor(&ctx.branch_ref.commit_sha, &base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ Ok(TaskResult::IsAncestor {+ item_idx: ctx.item_idx,+ is_ancestor,+ })+ }+}++/// Task 4: Branch diff stats vs local default branch (informational stats)+pub struct BranchDiffTask;++impl Task for BranchDiffTask {+ const KIND: TaskKind = TaskKind::BranchDiff;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When default_branch is None, return empty diff (cells show empty)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::BranchDiff {+ item_idx: ctx.item_idx,+ branch_diff: BranchDiffTotals::default(),+ });+ };+ let repo = &ctx.repo;+ let diff = repo+ .branch_diff_stats(&base, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ Ok(TaskResult::BranchDiff {+ item_idx: ctx.item_idx,+ branch_diff: BranchDiffTotals { diff },+ })+ }+}++/// Task 5 (worktree only): Working tree diff + status flags+///+/// Runs `git status --porcelain` to get working tree status and computes diff stats.+pub struct WorkingTreeDiffTask;++impl Task for WorkingTreeDiffTask {+ const KIND: TaskKind = TaskKind::WorkingTreeDiff;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .expect("WorkingTreeDiffTask requires a worktree");++ // Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's+ // `git stash create` which needs the index lock.+ let status_output = wt+ .run_command(&["--no-optional-locks", "status", "--porcelain"])+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ let (working_tree_status, is_dirty, has_conflicts) =+ parse_working_tree_status(&status_output);++ let working_tree_diff = if is_dirty {+ wt.working_tree_diff_stats()+ .map_err(|e| ctx.error(Self::KIND, &e))?+ } else {+ LineDiff::default()+ };++ Ok(TaskResult::WorkingTreeDiff {+ item_idx: ctx.item_idx,+ working_tree_diff,+ working_tree_status,+ has_conflicts,+ })+ }+}++/// Task 6: Potential merge conflicts check (merge-tree vs local main)+///+/// Uses default_branch (local main) for consistency with other Main subcolumn symbols.+/// Shows whether merging to your local main would conflict.+pub struct MergeTreeConflictsTask;++impl Task for MergeTreeConflictsTask {+ const KIND: TaskKind = TaskKind::MergeTreeConflicts;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When default_branch is None, return false (no conflicts can be detected)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::MergeTreeConflicts {+ item_idx: ctx.item_idx,+ has_merge_tree_conflicts: false,+ });+ };+ let repo = &ctx.repo;+ let has_merge_tree_conflicts = repo+ .has_merge_conflicts(&base, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ Ok(TaskResult::MergeTreeConflicts {+ item_idx: ctx.item_idx,+ has_merge_tree_conflicts,+ })+ }+}++/// Task 6b (worktree only, --full only): Working tree conflict check+///+/// For dirty worktrees, uses `git stash create` to get a tree object that+/// includes uncommitted changes, then runs merge-tree against that.+/// Returns None if working tree is clean (caller should fall back to MergeTreeConflicts).+pub struct WorkingTreeConflictsTask;++impl Task for WorkingTreeConflictsTask {+ const KIND: TaskKind = TaskKind::WorkingTreeConflicts;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // When default_branch is None, return None (skip conflict check)+ let Some(base) = ctx.default_branch() else {+ return Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: None,+ });+ };+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .expect("WorkingTreeConflictsTask requires a worktree");++ // Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.+ // Both tasks run in parallel, and `git stash create` below needs the index lock.+ let status_output = wt+ .run_command(&["--no-optional-locks", "status", "--porcelain"])+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ let is_dirty = !status_output.trim().is_empty();++ if !is_dirty {+ // Clean working tree - return None to signal "use commit-based check"+ return Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: None,+ });+ }++ // Dirty working tree - create a temporary tree object via stash create+ // `git stash create` returns a commit SHA without modifying refs+ //+ // Note: stash create fails when there are unmerged files (merge conflict in progress).+ // In that case, fall back to the commit-based check.+ let stash_result = wt.run_command(&["stash", "create"]);++ let stash_sha = match stash_result {+ Ok(sha) => sha,+ Err(_) => {+ // Stash create failed (likely unmerged files during rebase/merge)+ // Fall back to commit-based check+ return Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: None,+ });+ }+ };++ let stash_sha = stash_sha.trim();++ // If stash create returns empty, working tree is clean (shouldn't happen but handle it)+ if stash_sha.is_empty() {+ return Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: None,+ });+ }++ // Run merge-tree with the stash commit (repo-wide operation, doesn't need worktree)+ let has_conflicts = ctx+ .repo+ .has_merge_conflicts(&base, stash_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ Ok(TaskResult::WorkingTreeConflicts {+ item_idx: ctx.item_idx,+ has_working_tree_conflicts: Some(has_conflicts),+ })+ }+}++/// Task 7 (worktree only): Git operation state detection (rebase/merge)+pub struct GitOperationTask;++impl Task for GitOperationTask {+ const KIND: TaskKind = TaskKind::GitOperation;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ // This task is only spawned for worktree items, so worktree path is always present.+ let wt = ctx+ .branch_ref+ .working_tree(&ctx.repo)+ .expect("GitOperationTask requires a worktree");+ let git_operation = detect_git_operation(&wt);+ Ok(TaskResult::GitOperation {+ item_idx: ctx.item_idx,+ git_operation,+ })+ }+}++/// Task 8 (worktree only): User-defined status from git config+pub struct UserMarkerTask;++impl Task for UserMarkerTask {+ const KIND: TaskKind = TaskKind::UserMarker;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ let repo = &ctx.repo;+ let user_marker = repo.user_marker(ctx.branch_ref.branch.as_deref());+ Ok(TaskResult::UserMarker {+ item_idx: ctx.item_idx,+ user_marker,+ })+ }+}++/// Task 9: Upstream tracking status+pub struct UpstreamTask;++impl Task for UpstreamTask {+ const KIND: TaskKind = TaskKind::Upstream;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ let repo = &ctx.repo;++ // No branch means no upstream+ let Some(branch) = ctx.branch_ref.branch.as_deref() else {+ return Ok(TaskResult::Upstream {+ item_idx: ctx.item_idx,+ upstream: UpstreamStatus::default(),+ });+ };++ // Get upstream branch (None is valid - just means no upstream configured)+ let upstream_branch = repo+ .upstream_branch(branch)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let Some(upstream_branch) = upstream_branch else {+ return Ok(TaskResult::Upstream {+ item_idx: ctx.item_idx,+ upstream: UpstreamStatus::default(),+ });+ };++ let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());+ let (ahead, behind) = repo+ .ahead_behind(&upstream_branch, &ctx.branch_ref.commit_sha)+ .map_err(|e| ctx.error(Self::KIND, &e))?;++ Ok(TaskResult::Upstream {+ item_idx: ctx.item_idx,+ upstream: UpstreamStatus {+ remote,+ ahead,+ behind,+ },+ })+ }+}++/// Task 10: CI/PR status+///+/// Always checks for open PRs/MRs regardless of upstream tracking.+/// For branch workflow/pipeline fallback (no PR), requires upstream tracking+/// to prevent false matches from similarly-named branches on the remote.+pub struct CiStatusTask;++impl Task for CiStatusTask {+ const KIND: TaskKind = TaskKind::CiStatus;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ let repo = &ctx.repo;+ let pr_status = ctx.branch_ref.branch.as_deref().and_then(|branch| {+ let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();+ PrStatus::detect(repo, branch, &ctx.branch_ref.commit_sha, has_upstream)+ });++ Ok(TaskResult::CiStatus {+ item_idx: ctx.item_idx,+ pr_status,+ })+ }+}++/// Task 13: URL health check (port availability).+///+/// The URL itself is sent immediately after template expansion (in spawning code)+/// so it appears in normal styling right away. This task only checks if the port+/// is listening, and if not, the URL dims.+pub struct UrlStatusTask;++impl Task for UrlStatusTask {+ const KIND: TaskKind = TaskKind::UrlStatus;++ fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {+ use std::net::{SocketAddr, TcpStream};+ use std::time::Duration;++ // URL already sent in spawning code; this task only checks port availability+ let Some(ref url) = ctx.item_url else {+ return Ok(TaskResult::UrlStatus {+ item_idx: ctx.item_idx,+ url: None,+ active: None,+ });+ };++ // Parse port from URL and check if it's listening+ // Skip health check in tests to avoid flaky results from random local processes+ let active = if std::env::var("WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK").is_ok() {+ Some(false)+ } else {+ parse_port_from_url(url).map(|port| {+ // Quick TCP connect check with 50ms timeout+ let addr = SocketAddr::from(([127, 0, 0, 1], port));+ TcpStream::connect_timeout(&addr, Duration::from_millis(50)).is_ok()+ })+ };++ // Return only active status (url=None to avoid overwriting the already-sent URL)+ Ok(TaskResult::UrlStatus {+ item_idx: ctx.item_idx,+ url: None,+ active,+ })+ }+}++// ============================================================================+// Helper Functions+// ============================================================================++/// Detect if a worktree is in the middle of a git operation (rebase/merge).+pub(crate) fn detect_git_operation(wt: &worktrunk::git::WorkingTree<'_>) -> GitOperationState {+ if wt.is_rebasing().unwrap_or(false) {+ GitOperationState::Rebase+ } else if wt.is_merging().unwrap_or(false) {+ GitOperationState::Merge+ } else {+ GitOperationState::None+ }+}++/// Parse port number from a URL string (e.g., "http://localhost:12345" -> 12345)+pub(crate) fn parse_port_from_url(url: &str) -> Option<u16> {+ // Strip scheme+ let url = url+ .strip_prefix("http://")+ .or_else(|| url.strip_prefix("https://"))?;+ // Extract host:port (before path, query, or fragment)+ let host_port = url.split(&['/', '?', '#'][..]).next()?;+ let (_host, port_str) = host_port.rsplit_once(':')?;+ port_str.parse().ok()+}++/// Parse git status output to extract working tree status and conflict state.+/// Returns (WorkingTreeStatus, is_dirty, has_conflicts).+pub(super) fn parse_working_tree_status(status_output: &str) -> (WorkingTreeStatus, bool, bool) {+ let mut has_untracked = false;+ let mut has_modified = false;+ let mut has_staged = false;+ let mut has_renamed = false;+ let mut has_deleted = false;+ let mut has_conflicts = false;++ for line in status_output.lines() {+ if line.len() < 2 {+ continue;+ }++ let bytes = line.as_bytes();+ let index_status = bytes[0] as char;+ let worktree_status = bytes[1] as char;++ if index_status == '?' && worktree_status == '?' {+ has_untracked = true;+ }++ // Worktree changes: M = modified, A = intent-to-add (git add -N), T = type change (file↔symlink)+ if matches!(worktree_status, 'M' | 'A' | 'T') {+ has_modified = true;+ }++ // Index changes: A = added, M = modified, C = copied, T = type change (file↔symlink)+ if matches!(index_status, 'A' | 'M' | 'C' | 'T') {+ has_staged = true;+ }++ if index_status == 'R' {+ has_renamed = true;+ }++ if index_status == 'D' || worktree_status == 'D' {+ has_deleted = true;+ }++ // Detect unmerged/conflicting paths (porcelain v1 two-letter codes)+ // Only U codes and AA/DD indicate actual merge conflicts.+ // AD/DA are normal staging states (staged then deleted, or deleted then restored).+ let is_unmerged_pair = matches!(+ (index_status, worktree_status),+ ('U', _) | (_, 'U') | ('A', 'A') | ('D', 'D')+ );+ if is_unmerged_pair {+ has_conflicts = true;+ }+ }++ let working_tree_status = WorkingTreeStatus::new(+ has_staged,+ has_modified,+ has_untracked,+ has_renamed,+ has_deleted,+ );++ let is_dirty = working_tree_status.is_dirty();++ (working_tree_status, is_dirty, has_conflicts)+}diff --git a/src/commands/list/collect/types.rs b/src/commands/list/collect/types.rsnew file mode 100644index 000000000..918428b2b--- /dev/null+++ b/src/commands/list/collect/types.rs@@ -0,0 +1,272 @@+//! Task result types and context structures.+//!+//! Contains all the type definitions used by the collection system:+//! - `TaskResult` and `TaskKind` - result variants from task computations+//! - `TaskError` and `ErrorCause` - error handling for failed tasks+//! - `StatusContext` - context for status symbol computation+//! - `DrainOutcome` and `MissingResult` - timeout diagnostic info++use worktrunk::git::LineDiff;++use super::super::ci_status::PrStatus;+use super::super::model::{+ AheadBehind, BranchDiffTotals, CommitDetails, GitOperationState, ListItem, UpstreamStatus,+ WorkingTreeStatus,+};++/// Context for status symbol computation during result processing+#[derive(Clone, Default)]+pub(super) struct StatusContext {+ pub has_merge_tree_conflicts: bool,+ /// Working tree conflict check result (--full only, worktrees only).+ /// None = use commit check (task didn't run or working tree clean)+ /// Some(b) = dirty working tree, b is conflict result+ // TODO: If we need to distinguish "task didn't run" from "clean working tree",+ // expand to an enum. Currently both cases fall back to commit-based check.+ pub has_working_tree_conflicts: Option<bool>,+ pub user_marker: Option<String>,+ pub working_tree_status: Option<WorkingTreeStatus>,+ pub has_conflicts: bool,+}++impl StatusContext {+ pub fn apply_to(&self, item: &mut ListItem, target: &str) {+ // Main worktree case is handled inside check_integration_state()+ //+ // Prefer working tree conflicts (--full) when available.+ // None means task didn't run or working tree was clean - use commit check.+ let has_conflicts = self+ .has_working_tree_conflicts+ .unwrap_or(self.has_merge_tree_conflicts);++ item.compute_status_symbols(+ Some(target),+ has_conflicts,+ self.user_marker.clone(),+ self.working_tree_status,+ self.has_conflicts,+ );+ }+}++/// Task results sent as each git operation completes.+/// These enable progressive rendering - update UI as data arrives.+///+/// Each spawned task produces exactly one TaskResult. Multiple results+/// may feed into a single table column, and one result may feed multiple+/// columns. See `drain_results()` for how results map to ListItem fields.+///+/// The `EnumDiscriminants` derive generates a companion `TaskKind` enum+/// with the same variants but no payloads, used for type-safe tracking+/// of expected vs received results.+#[derive(Debug, Clone, strum::EnumDiscriminants)]+#[strum_discriminants(+ name(TaskKind),+ vis(pub),+ derive(Hash, Ord, PartialOrd, strum::IntoStaticStr),+ strum(serialize_all = "kebab-case")+)]+pub(crate) enum TaskResult {+ /// Commit timestamp and message+ CommitDetails {+ item_idx: usize,+ commit: CommitDetails,+ },+ /// Ahead/behind counts vs default branch+ AheadBehind {+ item_idx: usize,+ counts: AheadBehind,+ /// True if this is an orphan branch (no common ancestor with default branch)+ is_orphan: bool,+ },+ /// Whether HEAD's tree SHA matches integration target's tree SHA (committed content identical)+ CommittedTreesMatch {+ item_idx: usize,+ committed_trees_match: bool,+ },+ /// Whether branch has file changes beyond the merge-base with integration target (three-dot diff)+ HasFileChanges {+ item_idx: usize,+ has_file_changes: bool,+ },+ /// Whether merging branch into integration target would add changes (merge simulation)+ WouldMergeAdd {+ item_idx: usize,+ would_merge_add: bool,+ },+ /// Whether branch HEAD is ancestor of integration target (same commit or already merged)+ IsAncestor { item_idx: usize, is_ancestor: bool },+ /// Line diff vs default branch+ BranchDiff {+ item_idx: usize,+ branch_diff: BranchDiffTotals,+ },+ /// Working tree diff and status+ WorkingTreeDiff {+ item_idx: usize,+ working_tree_diff: LineDiff,+ /// Working tree change flags+ working_tree_status: WorkingTreeStatus,+ has_conflicts: bool,+ },+ /// Potential merge conflicts with default branch (merge-tree simulation on committed HEAD)+ MergeTreeConflicts {+ item_idx: usize,+ has_merge_tree_conflicts: bool,+ },+ /// Potential merge conflicts including working tree changes (--full only)+ ///+ /// For dirty worktrees, uses `git stash create` to get a tree object that+ /// includes uncommitted changes, then runs merge-tree against that.+ /// Returns None if working tree is clean (fall back to MergeTreeConflicts).+ WorkingTreeConflicts {+ item_idx: usize,+ /// None = working tree clean (use MergeTreeConflicts result)+ /// Some(true) = dirty working tree would conflict+ /// Some(false) = dirty working tree would not conflict+ has_working_tree_conflicts: Option<bool>,+ },+ /// Git operation in progress (rebase/merge)+ GitOperation {+ item_idx: usize,+ git_operation: GitOperationState,+ },+ /// User-defined status from git config+ UserMarker {+ item_idx: usize,+ user_marker: Option<String>,+ },+ /// Upstream tracking status+ Upstream {+ item_idx: usize,+ upstream: UpstreamStatus,+ },+ /// CI/PR status (slow operation)+ CiStatus {+ item_idx: usize,+ pr_status: Option<PrStatus>,+ },+ /// URL status (expanded URL and health check result)+ UrlStatus {+ item_idx: usize,+ /// Expanded URL from template (None if no template or no branch)+ url: Option<String>,+ /// Whether the port is listening (None if no URL or couldn't parse port)+ active: Option<bool>,+ },+}++impl TaskResult {+ /// Get the item index for this result+ pub fn item_idx(&self) -> usize {+ match self {+ TaskResult::CommitDetails { item_idx, .. }+ | TaskResult::AheadBehind { item_idx, .. }+ | TaskResult::CommittedTreesMatch { item_idx, .. }+ | TaskResult::HasFileChanges { item_idx, .. }+ | TaskResult::WouldMergeAdd { item_idx, .. }+ | TaskResult::IsAncestor { item_idx, .. }+ | TaskResult::BranchDiff { item_idx, .. }+ | TaskResult::WorkingTreeDiff { item_idx, .. }+ | TaskResult::MergeTreeConflicts { item_idx, .. }+ | TaskResult::WorkingTreeConflicts { item_idx, .. }+ | TaskResult::GitOperation { item_idx, .. }+ | TaskResult::UserMarker { item_idx, .. }+ | TaskResult::Upstream { item_idx, .. }+ | TaskResult::CiStatus { item_idx, .. }+ | TaskResult::UrlStatus { item_idx, .. } => *item_idx,+ }+ }+}++impl TaskKind {+ /// Whether this task requires network access.+ ///+ /// Network tasks are sorted to run last to avoid blocking local tasks.+ pub fn is_network(self) -> bool {+ matches!(self, TaskKind::CiStatus | TaskKind::UrlStatus)+ }+}++/// Result of draining task results - indicates whether all results were received+/// or if a timeout occurred.+#[derive(Debug)]+pub(super) enum DrainOutcome {+ /// All results received (channel closed normally)+ Complete,+ /// Timeout occurred - contains diagnostic info about what was received+ TimedOut {+ /// Number of task results received before timeout+ received_count: usize,+ /// Items with missing results+ items_with_missing: Vec<MissingResult>,+ },+}++/// Item with missing task results (for timeout diagnostics)+#[derive(Debug)]+pub(super) struct MissingResult {+ pub item_idx: usize,+ pub name: String,+ pub missing_kinds: Vec<TaskKind>,+}++/// Cause of a task error.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ErrorCause {+ /// Command exceeded the configured timeout.+ Timeout,+ /// Any other error (permission denied, git error, etc.).+ Other,+}++/// Error during task execution.+///+/// Tasks return this instead of swallowing errors. The drain layer+/// applies defaults and collects errors for display after rendering.+#[derive(Debug, Clone)]+pub struct TaskError {+ pub item_idx: usize,+ pub kind: TaskKind,+ pub message: String,+ /// What caused this error. Use `is_timeout()` to check.+ cause: ErrorCause,+}++impl TaskError {+ pub fn new(+ item_idx: usize,+ kind: TaskKind,+ message: impl Into<String>,+ cause: ErrorCause,+ ) -> Self {+ Self {+ item_idx,+ kind,+ message: message.into(),+ cause,+ }+ }++ /// Whether this error was caused by a timeout.+ pub fn is_timeout(&self) -> bool {+ self.cause == ErrorCause::Timeout+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_task_error_other_is_not_timeout() {+ let error = TaskError::new(0, TaskKind::AheadBehind, "test error", ErrorCause::Other);+ assert!(!error.is_timeout());+ }++ #[test]+ fn test_task_error_timeout_is_timeout() {+ let error = TaskError::new(0, TaskKind::AheadBehind, "timed out", ErrorCause::Timeout);+ assert!(error.is_timeout());+ }+}diff --git a/src/commands/select.rs b/src/commands/select.rsdeleted file mode 100644index fea6c90e0..000000000--- a/src/commands/select.rs+++ /dev/null@@ -1,1850 +0,0 @@-use anyhow::Context;-use color_print::cformat;-use skim::prelude::*;-use std::borrow::Cow;-use std::collections::{HashMap, HashSet};-use std::fs;-use std::path::PathBuf;-use std::process::{Command, Stdio};-use std::sync::{Arc, OnceLock};-use std::time::{Duration, Instant};-use worktrunk::config::WorktrunkConfig;-use worktrunk::git::{Repository, parse_numstat_line};-use worktrunk::shell::extract_filename_from_path;-use worktrunk::shell_exec::Cmd;--use super::list::collect;-use super::list::layout::{DiffDisplayConfig, DiffVariant};-use super::list::model::ListItem;-use super::worktree::{execute_switch, plan_switch};-use crate::output::handle_switch_output;-use crate::pager::{git_config_pager, parse_pager_value};--/// Cached pager command, detected once at startup.-///-/// None means no pager should be used (empty config or "cat").-/// We cache this to avoid running `git config` on every preview render.-static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();--/// Get the cached pager command, initializing if needed.-///-/// Precedence (highest to lowest):-/// 1. `[select] pager` in user config (explicit override, used as-is)-/// 2. `GIT_PAGER` environment variable (with auto-detection applied)-/// 3. `core.pager` git config (with auto-detection applied)-fn get_diff_pager() -> Option<&'static String> {- CACHED_PAGER- .get_or_init(|| {- // Check user config first for explicit pager override- // When set, use exactly as specified (no auto-detection)- if let Ok(config) = WorktrunkConfig::load()- && let Some(select_config) = config.select- && let Some(pager) = select_config.pager- && !pager.trim().is_empty()- {- return Some(pager);- }-- // GIT_PAGER takes precedence over core.pager- if let Ok(pager) = std::env::var("GIT_PAGER") {- return parse_pager_value(&pager);- }-- // Fall back to core.pager config- git_config_pager()- })- .as_ref()-}--/// Check if the pager spawns its own internal pager (e.g., less).-///-/// Some pagers like delta and bat spawn `less` by default, which hangs in-/// non-TTY contexts like skim's preview panel. These need `--paging=never`.-///-/// Used only when user hasn't set `[select] pager` config explicitly.-/// When config is set, that value is used as-is without modification.-fn pager_needs_paging_disabled(pager_cmd: &str) -> bool {- // Split on whitespace to get the command name, then extract basename- // Uses extract_filename_from_path for consistent handling of Windows paths and .exe- pager_cmd- .split_whitespace()- .next()- .and_then(extract_filename_from_path)- // bat is called "batcat" on Debian/Ubuntu- // Case-insensitive for Windows where commands might be Delta.exe, BAT.EXE, etc.- .is_some_and(|basename| {- basename.eq_ignore_ascii_case("delta")- || basename.eq_ignore_ascii_case("bat")- || basename.eq_ignore_ascii_case("batcat")- })-}--/// Check if user has explicitly configured a select-specific pager.-fn has_explicit_pager_config() -> bool {- WorktrunkConfig::load()- .ok()- .and_then(|config| config.select)- .and_then(|select| select.pager)- .is_some_and(|p| !p.trim().is_empty())-}--/// Maximum time to wait for pager to complete.-///-/// Pager blocking can freeze skim's event loop, making the UI unresponsive.-/// If the pager takes longer than this, kill it and fall back to raw diff.-const PAGER_TIMEOUT: Duration = Duration::from_millis(2000);--/// Skim uses this percentage of terminal height.-const SKIM_HEIGHT_PERCENT: usize = 90;--/// Maximum number of list items visible in down layout before scrolling.-const MAX_VISIBLE_ITEMS: usize = 12;--/// Lines reserved for skim chrome (header + prompt/margins).-const LIST_CHROME_LINES: usize = 4;--/// Minimum preview lines to keep usable even with many items.-const MIN_PREVIEW_LINES: usize = 5;--/// Run git diff piped directly through the pager as a streaming pipeline.-///-/// Runs `git <args> | pager` as a single shell command, avoiding intermediate-/// buffering. Returns None if pipeline fails or times out (caller should fall back to raw diff).-///-/// When `[select] pager` is not configured, automatically appends `--paging=never` for-/// delta/bat/batcat pagers to prevent hangs. To override this behavior, set an explicit-/// pager command in config: `[select] pager = "delta"` (or with custom flags).-fn run_git_diff_with_pager(git_args: &[&str], pager_cmd: &str) -> Option<String> {- // Note: pager_cmd is expected to be valid shell code (like git's core.pager).- // Users with paths containing special chars must quote them in their config.-- // Apply auto-detection only when user hasn't set explicit config- // If config is set, use the value as-is (user has full control)- let pager_with_args = if !has_explicit_pager_config() && pager_needs_paging_disabled(pager_cmd)- {- format!("{} --paging=never", pager_cmd)- } else {- pager_cmd.to_string()- };-- // Build shell pipeline: git <args> | pager- // Shell-escape args to handle paths with spaces- let escaped_args: Vec<String> = git_args- .iter()- .map(|arg| shlex::try_quote(arg).unwrap_or((*arg).into()).into_owned())- .collect();- let pipeline = format!("git {} | {}", escaped_args.join(" "), pager_with_args);-- log::debug!("Running pager pipeline: {}", pipeline);-- // Spawn pipeline- let mut child = match Command::new("sh")- .arg("-c")- .arg(&pipeline)- .stdout(Stdio::piped())- .stderr(Stdio::null())- // Prevent subprocesses from writing to the directive file- .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)- .spawn()- {- Ok(child) => child,- Err(e) => {- log::debug!("Failed to spawn pager pipeline: {}", e);- return None;- }- };-- // Read output in a thread to avoid blocking- let stdout = child.stdout.take()?;- let reader_thread = std::thread::spawn(move || {- use std::io::Read;- let mut stdout = stdout;- let mut output = Vec::new();- let _ = stdout.read_to_end(&mut output);- output- });-- // Wait for pipeline with timeout- let start = Instant::now();- loop {- match child.try_wait() {- Ok(Some(status)) => {- let output = reader_thread.join().ok()?;- if status.success() {- return String::from_utf8(output).ok();- } else {- log::debug!("Pager pipeline exited with status: {}", status);- return None;- }- }- Ok(None) => {- if start.elapsed() > PAGER_TIMEOUT {- log::debug!("Pager pipeline timed out after {:?}", PAGER_TIMEOUT);- let _ = child.kill();- return None;- }- std::thread::sleep(Duration::from_millis(10));- }- Err(e) => {- log::debug!("Failed to wait for pager pipeline: {}", e);- let _ = child.kill();- return None;- }- }- }-}--/// Preview modes for the interactive selector-///-/// Each mode shows a different aspect of the worktree:-/// 1. WorkingTree: Uncommitted changes (git diff HEAD --stat)-/// 2. Log: Commit history since diverging from the default branch (git log with merge-base)-/// 3. BranchDiff: Line diffs since the merge-base with the default branch (git diff --stat DEFAULT…)-/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)-///-/// Loosely aligned with `wt list` columns, though not a perfect match:-/// - Tab 1 corresponds to "HEAD±" column-/// - Tab 2 shows commits (related to "main↕" counts)-/// - Tab 3 corresponds to "main…± (--full)" column-/// - Tab 4 corresponds to "Remote⇅" column-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum PreviewMode {- WorkingTree = 1,- Log = 2,- BranchDiff = 3,- UpstreamDiff = 4,-}--/// Typical terminal character aspect ratio (width/height).-///-/// Terminal characters are taller than wide - typically around 0.5 (twice as tall as wide).-/// This varies by font, but 0.5 is a reasonable default for monospace fonts.-const CHAR_ASPECT_RATIO: f64 = 0.5;--/// Preview layout orientation for the interactive selector-///-/// Preview window position (auto-detected at startup based on terminal dimensions)-///-/// - Right: Preview on the right side (50% width) - better for wide terminals-/// - Down: Preview below the list - better for tall/vertical monitors-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]-enum PreviewLayout {- #[default]- Right,- Down,-}--impl PreviewLayout {- /// Auto-detect layout based on terminal dimensions.- ///- /// Terminal dimensions are in characters, not pixels. Since characters are- /// typically twice as tall as wide (~0.5 aspect ratio), we correct for this- /// when calculating the effective aspect ratio.- ///- /// Example: 180 cols × 136 rows- /// - Raw ratio: 180/136 = 1.32 (appears landscape)- /// - Effective: 1.32 × 0.5 = 0.66 (actually portrait!)- ///- /// Returns Down for portrait (effective ratio < 1.0), Right for landscape.- fn auto_detect() -> Self {- let (cols, rows) = terminal_size::terminal_size()- .map(|(terminal_size::Width(w), terminal_size::Height(h))| (w as f64, h as f64))- .unwrap_or((80.0, 24.0));-- // Effective aspect ratio accounting for character shape- let effective_ratio = (cols / rows) * CHAR_ASPECT_RATIO;-- if effective_ratio < 1.0 {- Self::Down- } else {- Self::Right- }- }-}--impl PreviewLayout {- /// Calculate the preview window spec for skim- ///- /// For Right layout: always 50%- /// For Down layout: dynamically sized based on item count - list gets- /// up to MAX_VISIBLE_ITEMS lines, preview gets the rest (min 5 lines)- fn to_preview_window_spec(self, num_items: usize) -> String {- match self {- Self::Right => "right:50%".to_string(),- Self::Down => {- let height = terminal_size::terminal_size()- .map(|(_, terminal_size::Height(h))| h as usize)- .unwrap_or(24);-- let available = height * SKIM_HEIGHT_PERCENT / 100;- let list_lines = LIST_CHROME_LINES + num_items.min(MAX_VISIBLE_ITEMS);- // Ensure preview doesn't exceed available space while trying to maintain minimum- let remaining = available.saturating_sub(list_lines);- let preview_lines = remaining.max(MIN_PREVIEW_LINES).min(available);-- format!("down:{}", preview_lines)- }- }- }-}--impl PreviewMode {- fn from_u8(n: u8) -> Self {- match n {- 2 => Self::Log,- 3 => Self::BranchDiff,- 4 => Self::UpstreamDiff,- _ => Self::WorkingTree,- }- }-}--/// Preview state persistence (mode only, layout auto-detected)-///-/// State file format: Single digit representing preview mode (1-4)-struct PreviewStateData;--impl PreviewStateData {- fn state_path() -> PathBuf {- // Use per-process temp file to avoid race conditions when running multiple instances- std::env::temp_dir().join(format!("wt-select-state-{}", std::process::id()))- }-- /// Read current preview mode from state file- fn read_mode() -> PreviewMode {- let state_path = Self::state_path();- fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree)- }-- fn write_mode(mode: PreviewMode) {- let state_path = Self::state_path();- let _ = fs::write(&state_path, format!("{}", mode as u8));- }-}--/// RAII wrapper for preview state file lifecycle management-struct PreviewState {- path: PathBuf,- initial_layout: PreviewLayout,-}--impl PreviewState {- fn new() -> Self {- let path = PreviewStateData::state_path();- PreviewStateData::write_mode(PreviewMode::WorkingTree);- Self {- path,- initial_layout: PreviewLayout::auto_detect(),- }- }-}--impl Drop for PreviewState {- fn drop(&mut self) {- let _ = fs::remove_file(&self.path);- }-}--/// Header item for column names (non-selectable)-struct HeaderSkimItem {- display_text: String,- display_text_with_ansi: String,-}--impl SkimItem for HeaderSkimItem {- fn text(&self) -> Cow<'_, str> {- Cow::Borrowed(&self.display_text)- }-- fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {- skim::AnsiString::parse(&self.display_text_with_ansi)- }-- fn output(&self) -> Cow<'_, str> {- Cow::Borrowed("") // Headers produce no output if selected- }-}--/// Wrapper to implement SkimItem for ListItem-struct WorktreeSkimItem {- display_text: String,- display_text_with_ansi: String,- branch_name: String,- item: Arc<ListItem>,-}--impl SkimItem for WorktreeSkimItem {- fn text(&self) -> Cow<'_, str> {- Cow::Borrowed(&self.display_text)- }-- fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {- skim::AnsiString::parse(&self.display_text_with_ansi)- }-- fn output(&self) -> Cow<'_, str> {- Cow::Borrowed(&self.branch_name)- }-- fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {- let mode = PreviewStateData::read_mode();-- // Build preview: tabs header + content- let mut result = Self::render_preview_tabs(mode);- result.push_str(&self.preview_for_mode(mode, context.width, context.height));-- ItemPreview::AnsiText(result)- }-}--impl WorktreeSkimItem {- /// Render the tab header for the preview window- ///- /// Shows all preview modes as tabs, with the current mode bolded- /// and unselected modes dimmed. Controls shown below in normal text- /// for visual distinction from inactive tabs.- fn render_preview_tabs(mode: PreviewMode) -> String {- /// Format a tab label with bold (active) or dimmed (inactive) styling- fn format_tab(label: &str, is_active: bool) -> String {- if is_active {- cformat!("<bold>{}</>", label)- } else {- cformat!("<dim>{}</>", label)- }- }-- let tab1 = format_tab("1: HEAD±", mode == PreviewMode::WorkingTree);- let tab2 = format_tab("2: log", mode == PreviewMode::Log);- let tab3 = format_tab("3: main…±", mode == PreviewMode::BranchDiff);- let tab4 = format_tab("4: remote⇅", mode == PreviewMode::UpstreamDiff);-- // Controls use dim yellow to distinguish from dimmed (white) tabs- let controls = cformat!(- "<dim,yellow>Enter: switch | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"- );-- format!(- "{} | {} | {} | {}\n{}\n\n",- tab1, tab2, tab3, tab4, controls- )- }-- /// Render preview for the given mode with specified dimensions- fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {- match mode {- PreviewMode::WorkingTree => self.render_working_tree_preview(width),- PreviewMode::Log => self.render_log_preview(width, height),- PreviewMode::BranchDiff => self.render_branch_diff_preview(width),- PreviewMode::UpstreamDiff => self.render_upstream_diff_preview(width),- }- }-- /// Common diff rendering pattern: check stat, show stat + full diff if non-empty- fn render_diff_preview(&self, args: &[&str], no_changes_msg: &str, width: usize) -> String {- let mut output = String::new();- let Ok(repo) = Repository::current() else {- return no_changes_msg.to_string();- };-- // Check stat output first- let mut stat_args = args.to_vec();- stat_args.push("--stat");- stat_args.push("--color=always");- let stat_width_arg = format!("--stat-width={}", width);- stat_args.push(&stat_width_arg);-- if let Ok(stat) = repo.run_command(&stat_args)- && !stat.trim().is_empty()- {- output.push_str(&stat);-- // Build diff args with color- let mut diff_args = args.to_vec();- diff_args.push("--color=always");-- // Try streaming through pager first (git diff | pager), fall back to plain diff- let diff = get_diff_pager()- .and_then(|pager| run_git_diff_with_pager(&diff_args, pager))- .or_else(|| repo.run_command(&diff_args).ok());-- if let Some(diff) = diff {- output.push_str(&diff);- }- } else {- output.push_str(no_changes_msg);- output.push('\n');- }-- output- }-- /// Render Tab 1: Working tree preview (uncommitted changes vs HEAD)- /// Matches `wt list` "HEAD±" column- fn render_working_tree_preview(&self, width: usize) -> String {- use worktrunk::styling::INFO_SYMBOL;-- let Some(wt_info) = self.item.worktree_data() else {- // Branch without worktree - selecting will create one- let branch = self.item.branch_name();- return format!(- "{INFO_SYMBOL} {branch} is branch only — press Enter to create worktree\n"- );- };-- let branch = self.item.branch_name();- let path = wt_info.path.display().to_string();- self.render_diff_preview(- &["-C", &path, "diff", "HEAD"],- &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no uncommitted changes"),- width,- )- }-- /// Render Tab 3: Branch diff preview (line diffs in commits ahead of default branch)- /// Matches `wt list` "main…± (--full)" column- fn render_branch_diff_preview(&self, width: usize) -> String {- use worktrunk::styling::INFO_SYMBOL;-- let branch = self.item.branch_name();- let Ok(repo) = Repository::current() else {- return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");- };- let Some(default_branch) = repo.default_branch() else {- return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");- };- if self.item.counts.is_some_and(|c| c.ahead == 0) {- return cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of <bold>{default_branch}</>\n"- );- }-- let merge_base = format!("{}...{}", default_branch, self.item.head());- self.render_diff_preview(- &["diff", &merge_base],- &cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has no file changes vs <bold>{default_branch}</>"- ),- width,- )- }-- /// Render Tab 4: Upstream diff preview (ahead/behind vs tracking branch)- /// Matches `wt list` "Remote⇅" column- fn render_upstream_diff_preview(&self, width: usize) -> String {- use worktrunk::styling::INFO_SYMBOL;-- let branch = self.item.branch_name();-- // Check if this branch has an upstream tracking branch- // Use as_ref() to avoid cloning UpstreamStatus on every preview render- let Some(active) = self.item.upstream.as_ref().and_then(|u| u.active()) else {- return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no upstream tracking branch\n");- };-- // Use @{u} syntax for performance (avoids extra git command to resolve upstream ref)- // Format: branch@{u} resolves to the upstream tracking branch- let upstream_ref = format!("{}@{{u}}", branch);-- if active.ahead == 0 && active.behind == 0 {- return cformat!("{INFO_SYMBOL} <bold>{branch}</> is up to date with upstream\n");- }-- // Handle different states: ahead only, behind only, or diverged- // Use ⇡/⇣ symbols to match wt list's Remote⇅ column- if active.ahead > 0 && active.behind > 0 {- // Diverged: show local changes (what would be pushed)- // Use three-dot diff to show changes unique to local branch- let range = format!("{}...{}", upstream_ref, self.item.head());- self.render_diff_preview(- &["diff", &range],- &cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has diverged (⇡{} ⇣{}) but no unique file changes",- active.ahead,- active.behind- ),- width,- )- } else if active.ahead > 0 {- // Ahead only: show unpushed commits- let range = format!("{}...{}", upstream_ref, self.item.head());- self.render_diff_preview(- &["diff", &range],- &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no unpushed file changes"),- width,- )- } else {- // Behind only: show what upstream has that we don't- let range = format!("{}...{}", self.item.head(), upstream_ref);- self.render_diff_preview(- &["diff", &range],- &cformat!(- "{INFO_SYMBOL} <bold>{branch}</> is behind upstream (⇣{}) but no file changes",- active.behind- ),- width,- )- }- }-- /// Render Tab 2: Log preview- fn render_log_preview(&self, width: usize, height: usize) -> String {- use worktrunk::styling::INFO_SYMBOL;- // Minimum preview width to show timestamps (adds ~7 chars: space + 4-char time + space)- // Note: preview is typically 50% of terminal width, so 50 = 100-col terminal- const TIMESTAMP_WIDTH_THRESHOLD: usize = 50;- // Tab header takes 3 lines (tabs + controls + blank)- const HEADER_LINES: usize = 3;-- let mut output = String::new();- let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;- // Calculate how many log lines fit in preview (height minus header)- let log_limit = height.saturating_sub(HEADER_LINES).max(1);- let head = self.item.head();- let branch = self.item.branch_name();- let Ok(repo) = Repository::current() else {- output.push_str(&cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"- ));- return output;- };- let Some(default_branch) = repo.default_branch() else {- output.push_str(&cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"- ));- return output;- };-- // Get merge-base with default branch- //- // Note on error handling: This code runs in an interactive preview pane that updates- // on every keystroke. We intentionally use silent fallbacks rather than propagating- // errors to avoid disruptive error messages during navigation. The preview is- // supplementary - users can still select worktrees even if preview fails.- //- // Alternative: Check specific conditions (default branch exists, valid HEAD, etc.) before- // running git commands. This would provide better diagnostics but adds latency to- // every preview render. Trade-off: simplicity + speed vs. detailed error messages.- let Ok(merge_base_output) = repo.run_command(&["merge-base", &default_branch, head]) else {- output.push_str(&cformat!(- "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"- ));- return output;- };-- let merge_base = merge_base_output.trim();- let is_default_branch = branch == default_branch;-- // Format strings for git log- // Without timestamps: hash (colored/dimmed), then message- // Format includes full hash (for matching) between SOH and NUL delimiters.- // Display content uses \x1f to separate fields for timestamp parsing.- // Format: SOH full_hash NUL short_hash \x1f timestamp \x1f decorations+message- // Using delimiters allows parsing without assuming fixed hash length (SHA-256 safe)- // Note: Use %x01/%x00 (git's hex escapes) to avoid embedding control chars in argv- let timestamp_format = format!(- "--format=%x01%H%x00%C(auto)%h{}%ct{}%C(auto)%d%C(reset) %s",- FIELD_DELIM, FIELD_DELIM- );- let no_timestamp_format = "--format=%x01%H%x00%C(auto)%h%C(auto)%d%C(reset) %s";-- let log_limit_str = log_limit.to_string();-- // Get commits after merge-base (for dimming logic)- // These are commits reachable from HEAD but not from merge-base, shown bright.- // Commits before merge-base (shared with default branch) are shown dimmed.- // Bounded to log_limit since we only need to check displayed commits.- let unique_commits: Option<HashSet<String>> = if is_default_branch {- // On default branch: no dimming (None means show everything bright)- None- } else {- // On feature branch: get commits unique to this branch- // rev-list A...B --right-only gives commits reachable from B but not A- let range = format!("{}...{}", merge_base, head);- let commits = repo- .run_command(&["rev-list", &range, "--right-only", "-n", &log_limit_str])- .map(|out| out.lines().map(String::from).collect())- .unwrap_or_default();- Some(commits) // Some(empty) means dim everything- };-- // Get graph output (no --numstat to avoid blank continuation lines)- let format: &str = if show_timestamps {- ×tamp_format- } else {- no_timestamp_format- };- let args = vec![- "log",- "--graph",- format,- "--color=always",- "-n",- &log_limit_str,- head,- ];-- if let Ok(log_output) = repo.run_command(&args) {- let (processed, hashes) =- process_log_with_dimming(&log_output, unique_commits.as_ref());- if show_timestamps {- // Batch fetch stats for all commits- let stats = batch_fetch_stats(&repo, &hashes);- output.push_str(&format_log_output(&processed, &stats));- } else {- // Strip hash markers (SOH...NUL) since we're not using format_log_output- output.push_str(&strip_hash_markers(&processed));- }- }-- output- }-}--/// Batch fetch diffstats for multiple commits using git diff-tree --stdin.-/// Returns a map of full_hash -> (insertions, deletions).-///-/// Failures are silent (preview context).-fn batch_fetch_stats(repo: &Repository, hashes: &[String]) -> HashMap<String, (usize, usize)> {- if hashes.is_empty() {- return HashMap::new();- }-- // --root: include stats for root commits (no parent to diff against)- // Each hash needs a trailing newline for git to process it- let stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();- let Ok(output) = Cmd::new("git")- .args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])- .current_dir(repo.repo_path().unwrap_or_else(|_| ".".into()))- .stdin_bytes(stdin_data)- .run()- else {- return HashMap::new();- };-- // Parse output: hash line followed by numstat lines- let mut stats: HashMap<String, (usize, usize)> = HashMap::new();- let mut current_hash: Option<String> = None;- let mut current_stats = (0usize, 0usize);-- for line in String::from_utf8_lossy(&output.stdout).lines() {- // Hash line (40 or 64 hex chars)- if line.chars().all(|c| c.is_ascii_hexdigit()) && (line.len() == 40 || line.len() == 64) {- // Save previous hash's stats- if let Some(hash) = current_hash.take() {- stats.insert(hash, current_stats);- }- current_hash = Some(line.to_string());- current_stats = (0, 0);- } else if let Some((ins, del)) = parse_numstat_line(line) {- current_stats.0 += ins;- current_stats.1 += del;- }- }-- // Don't forget the last hash- if let Some(hash) = current_hash {- stats.insert(hash, current_stats);- }-- stats-}--/// Field delimiter for git log format with timestamps-const FIELD_DELIM: char = '\x1f';--/// Start delimiter for full hash (SOH - Start of Heading)-const HASH_START: char = '\x01';--/// End delimiter for full hash (NUL)-const HASH_END: char = '\x00';--/// Timestamp column width ("12mo" is the longest)-const TIMESTAMP_WIDTH: usize = 4;--/// Process git log output: strip hash prefix and dim non-unique commits.-///-/// - `unique_commits = None`: show everything bright (default branch)-/// - `unique_commits = Some(set)`: bright if in set, dim otherwise-/// - Graph-only lines pass through unchanged-///-/// Returns (processed_output, list_of_full_hashes) for batch stats lookup.-fn process_log_with_dimming(- log_output: &str,- unique_commits: Option<&HashSet<String>>,-) -> (String, Vec<String>) {- use ansi_str::AnsiStr;- use std::fmt::Write;-- let dim = anstyle::Style::new().dimmed();- let reset = anstyle::Reset;-- let mut result = String::with_capacity(log_output.len());- let mut hashes = Vec::new();-- for (i, line) in log_output.lines().enumerate() {- if i > 0 {- result.push('\n');- }-- // Parse commit line: graph_prefix + SOH + full_hash + NUL + display- if let Some(hash_start) = line.find(HASH_START)- && let Some(hash_end_offset) = line[hash_start + 1..].find(HASH_END)- {- let hash_end = hash_start + 1 + hash_end_offset;- let graph_prefix = &line[..hash_start];- let full_hash = &line[hash_start + 1..hash_end];- let display = &line[hash_end + 1..];-- // Collect hash for stats lookup- hashes.push(full_hash.to_string());-- // Bright if: no dimming (None) OR commit is in unique set- let is_bright = match unique_commits {- None => true, // Default branch: all bright- Some(set) => set.contains(full_hash), // Feature branch: bright if unique- };-- // Keep SOH hash NUL markers for format_log_output to extract hash for stats lookup- if is_bright {- result.push_str(graph_prefix);- result.push(HASH_START);- result.push_str(full_hash);- result.push(HASH_END);- result.push_str(display);- } else {- // Dim: strip colors and wrap in dim style, but keep hash markers- let _ = write!(- result,- "{}{HASH_START}{full_hash}{HASH_END}{dim}{}{reset}",- graph_prefix,- display.ansi_strip()- );- }- continue;- }- // Graph-only lines: pass through unchanged- result.push_str(line);- }- (result, hashes)-}--/// Format git log output with timestamps and diffstats.-///-/// Takes pre-processed log output (graph + commits) and a stats map.-/// Each commit line has format: `graph_prefix short_hash \x1f timestamp \x1f decoration message`-///-/// The full hash for stats lookup is embedded as: `SOH full_hash NUL` before the short hash,-/// but this was already stripped by process_log_with_dimming. We need the hash in the line-/// to look up stats - so we keep the full hash in a different delimiter for this function.-fn format_log_output(log_output: &str, stats: &HashMap<String, (usize, usize)>) -> String {- use crate::display::format_relative_time_short;- format_log_output_with_formatter(log_output, stats, format_relative_time_short)-}--/// Format git log output with a custom time formatter.-///-/// This variant allows dependency injection for testing with deterministic timestamps.-fn format_log_output_with_formatter<F>(- log_output: &str,- stats: &HashMap<String, (usize, usize)>,- format_time: F,-) -> String-where- F: Fn(i64) -> String,-{- use ansi_str::AnsiStr;- use unicode_width::UnicodeWidthStr;-- // First pass: find max display width of graph+hash prefix for alignment- let max_prefix_width = log_output- .lines()- .filter(|line| line.contains(FIELD_DELIM))- .filter_map(|line| {- let first_delim = line.find(FIELD_DELIM)?;- let graph_hash_raw = &line[..first_delim];- let graph_hash = strip_hash_markers(graph_hash_raw);- // Calculate display width (strip ANSI, measure unicode width)- Some(graph_hash.ansi_strip().width())- })- .max()- .unwrap_or(0);-- // Second pass: format with alignment- let mut result = Vec::new();- for line in log_output.lines() {- if line.contains(FIELD_DELIM) {- // Commit line - look up stats by hash extracted from line- let commit_stats = extract_hash_from_line(line)- .and_then(|h| stats.get(h))- .copied()- .unwrap_or((0, 0));- result.push(format_commit_line(- line,- commit_stats,- max_prefix_width,- &format_time,- ));- } else {- // Graph-only line - pass through- result.push(line.to_string());- }- }-- result.join("\n")-}--/// Extract the full hash from a commit line that still has SOH/NUL markers.-/// Returns None if not found (line already processed or malformed).-fn extract_hash_from_line(line: &str) -> Option<&str> {- let hash_start = line.find(HASH_START)?;- let hash_end_offset = line[hash_start + 1..].find(HASH_END)?;- Some(&line[hash_start + 1..hash_start + 1 + hash_end_offset])-}--/// Strip SOH...NUL hash markers from output (used when not formatting with timestamps).-fn strip_hash_markers(s: &str) -> String {- let mut result = String::with_capacity(s.len());- let mut chars = s.chars().peekable();-- while let Some(c) = chars.next() {- if c == HASH_START {- // Skip until NUL- while let Some(&next) = chars.peek() {- chars.next();- if next == HASH_END {- break;- }- }- } else {- result.push(c);- }- }- result-}--/// Format a single commit line with stats, padding the prefix to target_width for alignment-fn format_commit_line<F>(- commit_line: &str,- (insertions, deletions): (usize, usize),- target_width: usize,- format_time: &F,-) -> String-where- F: Fn(i64) -> String,-{- use ansi_str::AnsiStr;- use unicode_width::UnicodeWidthStr;- use worktrunk::styling::{ADDITION, DELETION};-- let dim_style = anstyle::Style::new().dimmed();- let reset = anstyle::Reset;-- if let Some(first_delim) = commit_line.find(FIELD_DELIM)- && let Some(second_delim) = commit_line[first_delim + 1..].find(FIELD_DELIM)- {- let graph_hash_raw = &commit_line[..first_delim];- // Strip SOH...NUL hash markers from graph_hash portion- let graph_hash = strip_hash_markers(graph_hash_raw);- let timestamp_str = &commit_line[first_delim + 1..first_delim + 1 + second_delim];- let rest = &commit_line[first_delim + 1 + second_delim + 1..];-- let time = timestamp_str- .parse::<i64>()- .map(format_time)- .unwrap_or_default();-- // Use the same diff formatting as wt list (aligned columns)- let diff_config = DiffDisplayConfig {- variant: DiffVariant::Signs,- positive_style: ADDITION,- negative_style: DELETION,- always_show_zeros: false,- };- let stat_str = format!(" {}", diff_config.format_aligned(insertions, deletions));-- // Pad graph_hash to target_width for column alignment- let current_width = graph_hash.ansi_strip().width();- let padding = " ".repeat(target_width.saturating_sub(current_width));-- format!(- "{}{}{} {dim_style}{:>width$}{reset}{}",- graph_hash,- padding,- stat_str,- time,- rest,- width = TIMESTAMP_WIDTH- )- } else {- commit_line.to_string()- }-}--pub fn handle_select(- show_branches: bool,- show_remotes: bool,- config: &WorktrunkConfig,-) -> anyhow::Result<()> {- use std::io::IsTerminal;-- // Select requires an interactive terminal for the TUI- if !std::io::stdin().is_terminal() {- anyhow::bail!("wt select requires an interactive terminal");- }-- let repo = Repository::current()?;-- // Initialize preview mode state file (auto-cleanup on drop)- let state = PreviewState::new();-- // Gather list data using simplified collection (buffered mode)- // Skip expensive operations not needed for select UI- let skip_tasks = [- collect::TaskKind::BranchDiff,- collect::TaskKind::CiStatus,- collect::TaskKind::MergeTreeConflicts,- ]- .into_iter()- .collect();-- // Use 500ms timeout for git commands to show TUI faster on large repos.- // Typical slow operations: merge-tree ~400-1800ms, rev-list ~200-600ms.- // 500ms allows most operations to complete while cutting off tail latency.- // Operations that timeout fail silently (data not shown), but TUI stays responsive.- let command_timeout = Some(std::time::Duration::from_millis(500));-- let Some(list_data) = collect::collect(- &repo,- show_branches,- show_remotes,- &skip_tasks,- false, // show_progress (no progress bars)- false, // render_table (select renders its own UI)- config,- command_timeout,- true, // skip_expensive_for_stale (faster for repos with many stale branches)- )?- else {- return Ok(());- };-- // Use the same layout system as `wt list` for proper column alignment- // List width depends on preview position:- // - Right layout: skim splits ~50% for list, ~50% for preview- // - Down layout: list gets full width, preview is below- let terminal_width = crate::display::get_terminal_width();- let skim_list_width = match state.initial_layout {- PreviewLayout::Right => terminal_width / 2,- PreviewLayout::Down => terminal_width,- };- let layout = super::list::layout::calculate_layout_with_width(- &list_data.items,- &skip_tasks,- skim_list_width,- &list_data.main_worktree_path,- None, // URL column not shown in select- );-- // Render header using layout system (need both plain and styled text for skim)- let header_line = layout.render_header_line();- let header_display_text = header_line.render();- let header_plain_text = header_line.plain_text();-- // Convert to skim items using the layout system for rendering- let mut items: Vec<Arc<dyn SkimItem>> = list_data- .items- .into_iter()- .map(|item| {- let branch_name = item.branch_name().to_string();-- // Use layout system to render the line - this handles all column alignment- let rendered_line = layout.render_list_item_line(&item);- let display_text_with_ansi = rendered_line.render();- let display_text = rendered_line.plain_text();-- Arc::new(WorktreeSkimItem {- display_text,- display_text_with_ansi,- branch_name,- item: Arc::new(item),- }) as Arc<dyn SkimItem>- })- .collect();-- // Insert header row at the beginning (will be non-selectable via header_lines option)- items.insert(- 0,- Arc::new(HeaderSkimItem {- display_text: header_plain_text,- display_text_with_ansi: header_display_text,- }) as Arc<dyn SkimItem>,- );-- // Get state path for key bindings (shell-escaped for safety)- let state_path_display = state.path.display().to_string();- let state_path_str = shlex::try_quote(&state_path_display)- .map(|s| s.into_owned())- .unwrap_or(state_path_display);-- // Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%- let half_page = terminal_size::terminal_size()- .map(|(_, terminal_size::Height(h))| (h as usize * 45 / 100).max(5))- .unwrap_or(10);-- // Calculate preview window spec based on auto-detected layout- // items.len() - 1 because we added a header row- let num_items = items.len().saturating_sub(1);- let preview_window_spec = state.initial_layout.to_preview_window_spec(num_items);-- // Configure skim options with Rust-based preview and mode switching keybindings- let options = SkimOptionsBuilder::default()- .height("90%".to_string())- .layout("reverse".to_string())- .header_lines(1) // Make first line (header) non-selectable- .multi(false)- .no_info(true) // Hide info line (matched/total counter)- .preview(Some("".to_string())) // Enable preview (empty string means use SkimItem::preview())- .preview_window(preview_window_spec)- // Color scheme using fzf's --color=light values: dark text (237) on light gray bg (251)- //- // Terminal color compatibility is tricky:- // - current_bg:254 (original): too bright on dark terminals, washes out text- // - current_bg:236 (fzf dark): too dark on light terminals, jarring contrast- // - current_bg:251 + current:-1: light bg works on both, but unstyled text- // becomes unreadable on dark terminals (light-on-light)- // - current_bg:251 + current:237: fzf's light theme, best compromise- //- // The light theme works universally because:- // - On dark terminals: light gray highlight stands out clearly- // - On light terminals: light gray is subtle but visible- // - Dark text (237) ensures readability regardless of terminal theme- .color(Some(- "fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108"- .to_string(),- ))- .bind(vec![- // Mode switching (1/2/3/4 keys change preview content)- format!(- "1:execute-silent(echo 1 > {0})+refresh-preview",- state_path_str- ),- format!(- "2:execute-silent(echo 2 > {0})+refresh-preview",- state_path_str- ),- format!(- "3:execute-silent(echo 3 > {0})+refresh-preview",- state_path_str- ),- format!(- "4:execute-silent(echo 4 > {0})+refresh-preview",- state_path_str- ),- // Preview toggle (alt-p shows/hides preview)- // Note: skim doesn't support change-preview-window like fzf, only toggle- "alt-p:toggle-preview".to_string(),- // Preview scrolling (half-page based on terminal height)- format!("ctrl-u:preview-up({half_page})"),- format!("ctrl-d:preview-down({half_page})"),- ])- // Legend/controls moved to preview window tabs (render_preview_tabs)- .no_clear(true) // Prevent skim from clearing screen, we'll do it manually- .build()- .map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;-- // Create item receiver- let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();- for item in items {- tx.send(item)- .map_err(|e| anyhow::anyhow!("Failed to send item to skim: {}", e))?;- }- drop(tx);-- // Run skim- let output = Skim::run_with(&options, Some(rx));-- // Handle selection- if let Some(out) = output- && !out.is_abort- && let Some(selected) = out.selected_items.first()- {- // Get branch name or worktree path from selected item- // (output() returns the worktree path for existing worktrees, branch name otherwise)- let identifier = selected.output().to_string();-- // Load config- let config = WorktrunkConfig::load().context("Failed to load config")?;- let repo = Repository::current().context("Failed to switch worktree")?;-- // Switch to the selected worktree (no creation, no approval prompts)- let plan = plan_switch(&repo, &identifier, false, None, false, &config)?;- let (result, branch_info) = execute_switch(&repo, plan, &config, false, true)?;-- // Clear the terminal screen after skim exits to prevent artifacts- // Use stderr for terminal control - stdout is reserved for data output- use crossterm::{execute, terminal};- use std::io::stderr;- execute!(stderr(), terminal::Clear(terminal::ClearType::All))?;- execute!(stderr(), crossterm::cursor::MoveTo(0, 0))?;-- // Show success message; emit cd directive if shell integration is active- handle_switch_output(&result, &branch_info, None)?;- }-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_preview_mode_from_u8() {- assert_eq!(PreviewMode::from_u8(1), PreviewMode::WorkingTree);- assert_eq!(PreviewMode::from_u8(2), PreviewMode::Log);- assert_eq!(PreviewMode::from_u8(3), PreviewMode::BranchDiff);- assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);- // Invalid values default to WorkingTree- assert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);- assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);- }-- #[test]- fn test_preview_layout_to_preview_window_spec() {- // Right is always 50%- assert_eq!(PreviewLayout::Right.to_preview_window_spec(10), "right:50%");-- // Down calculates based on item count- let spec = PreviewLayout::Down.to_preview_window_spec(5);- assert!(spec.starts_with("down:"));- }-- #[test]- fn test_preview_state_data_read_default() {- // Use unique path to avoid interference from parallel tests- let state_path = std::env::temp_dir().join("wt-test-read-default");- let _ = fs::remove_file(&state_path);-- // When state file doesn't exist, read returns default- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::WorkingTree);- }-- #[test]- fn test_preview_state_data_roundtrip() {- // Use unique path to avoid interference from parallel tests- let state_path = std::env::temp_dir().join("wt-test-roundtrip");-- // Write and read back various modes- let _ = fs::write(&state_path, "1");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::WorkingTree);-- let _ = fs::write(&state_path, "2");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::Log);-- let _ = fs::write(&state_path, "3");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::BranchDiff);-- let _ = fs::write(&state_path, "4");- let mode = fs::read_to_string(&state_path)- .ok()- .and_then(|s| s.trim().parse::<u8>().ok())- .map(PreviewMode::from_u8)- .unwrap_or(PreviewMode::WorkingTree);- assert_eq!(mode, PreviewMode::UpstreamDiff);-- // Cleanup- let _ = fs::remove_file(&state_path);- }-- #[test]- fn test_pager_needs_paging_disabled() {- // delta - plain command name- assert!(pager_needs_paging_disabled("delta"));- // delta - with arguments- assert!(pager_needs_paging_disabled("delta --side-by-side"));- assert!(pager_needs_paging_disabled("delta --paging=always"));- // delta - full path- assert!(pager_needs_paging_disabled("/usr/bin/delta"));- assert!(pager_needs_paging_disabled(- "/opt/homebrew/bin/delta --line-numbers"- ));- // bat - also spawns less by default- assert!(pager_needs_paging_disabled("bat"));- assert!(pager_needs_paging_disabled("/usr/bin/bat"));- assert!(pager_needs_paging_disabled("bat --style=plain"));- // Pagers that don't spawn sub-pagers- assert!(!pager_needs_paging_disabled("less"));- assert!(!pager_needs_paging_disabled("diff-so-fancy"));- assert!(!pager_needs_paging_disabled("colordiff"));- // Edge cases - similar names but not delta/bat- assert!(!pager_needs_paging_disabled("delta-preview"));- assert!(!pager_needs_paging_disabled("/path/to/delta-preview"));- assert!(pager_needs_paging_disabled("batcat")); // Debian's bat package name-- // Case-insensitive matching (Windows command names)- assert!(pager_needs_paging_disabled("Delta"));- assert!(pager_needs_paging_disabled("DELTA"));- assert!(pager_needs_paging_disabled("BAT"));- assert!(pager_needs_paging_disabled("Bat"));- assert!(pager_needs_paging_disabled("BatCat"));- assert!(pager_needs_paging_disabled("delta.exe"));- assert!(pager_needs_paging_disabled("Delta.EXE"));- }-- #[test]- fn test_has_explicit_pager_config() {- // This function loads real config, so we just test that it doesn't panic- // The behavior is covered by integration tests that set actual config- let _ = has_explicit_pager_config();- }-- #[test]- fn test_render_preview_tabs_working_tree_mode() {- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);- // Tab 1 should be bold (active), tabs 2/3/4 dimmed- assert!(output.contains("1: HEAD±"));- assert!(output.contains("2: log"));- assert!(output.contains("3: main…±"));- assert!(output.contains("4: remote⇅"));- assert!(output.contains("Enter: switch"));- // Verify structure: tabs on first line, controls on second- assert!(output.contains(" | "));- assert!(output.ends_with("\n\n"));- }-- #[test]- fn test_render_preview_tabs_log_mode() {- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::Log);- assert!(output.contains("1: HEAD±"));- assert!(output.contains("2: log"));- assert!(output.contains("3: main…±"));- assert!(output.contains("4: remote⇅"));- }-- #[test]- fn test_render_preview_tabs_branch_diff_mode() {- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::BranchDiff);- assert!(output.contains("1: HEAD±"));- assert!(output.contains("2: log"));- assert!(output.contains("3: main…±"));- assert!(output.contains("4: remote⇅"));- }-- #[test]- fn test_render_preview_tabs_upstream_diff_mode() {- let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::UpstreamDiff);- assert!(output.contains("1: HEAD±"));- assert!(output.contains("2: log"));- assert!(output.contains("3: main…±"));- assert!(output.contains("4: remote⇅"));- }-- // format_log_output tests use dependency injection for deterministic time formatting.- // The format_log_output_with_formatter function accepts a time formatter closure.-- /// Fixed time formatter for deterministic tests- fn fixed_time_formatter(_timestamp: i64) -> String {- "1h".to_string() // Return a fixed time for all timestamps- }-- /// Create a stats map with a single entry- fn stats_for(- hash: &str,- insertions: usize,- deletions: usize,- ) -> HashMap<String, (usize, usize)> {- let mut map = HashMap::new();- map.insert(hash.to_string(), (insertions, deletions));- map- }-- /// Create a stats map with multiple entries- fn multi_stats(entries: &[(&str, usize, usize)]) -> HashMap<String, (usize, usize)> {- entries- .iter()- .map(|(h, i, d)| (h.to_string(), (*i, *d)))- .collect()- }-- #[test]- fn test_format_log_output_single_commit() {- // Simulate git log output with SOH/NUL markers: * SOH full_hash NUL short_hash \x1f timestamp \x1f message- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Fix bug", full_hash);- let stats = stats_for(full_hash, 5, 2);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- // Should contain the hash and message- assert!(output.contains("abc1234"));- assert!(output.contains("Fix bug"));- // Should contain formatted time- assert!(output.contains("1h"));- // Should contain stats- assert!(output.contains("+5"), "expected +5 in output: {}", output);- }-- #[test]- fn test_format_log_output_with_stats() {- // Commit line with pre-computed stats- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Add feature",- full_hash- );- // Stats are pre-computed (accumulated from numstat lines)- let stats = stats_for(full_hash, 13, 5);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- // Should contain the hash and message- assert!(output.contains("abc1234"));- assert!(output.contains("Add feature"));- // Verify stats are present (green +13, red -5)- assert!(output.contains("+13"), "expected +13 in output: {}", output);- assert!(output.contains("-5"), "expected -5 in output: {}", output);- }-- #[test]- fn test_format_log_output_multiple_commits() {- // Two commits with pre-computed stats- let hash1 = "abc1234567890123456789012345678901234567ab";- let hash2 = "def5678901234567890123456789012345678901cd";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f First commit\n\- * \x01{}\x00def5678\x1f1699998000\x1f Second commit",- hash1, hash2- );- let stats = multi_stats(&[(hash1, 5, 2), (hash2, 10, 3)]);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- // Both commits should be in output- assert!(output.contains("abc1234"));- assert!(output.contains("def5678"));- assert!(output.contains("First commit"));- assert!(output.contains("Second commit"));-- // Output should be two lines (one per commit)- let lines: Vec<&str> = output.lines().collect();- assert_eq!(lines.len(), 2, "Expected 2 lines, got: {:?}", lines);- }-- #[test]- fn test_format_log_output_empty_input() {- let stats = HashMap::new();- let output = format_log_output_with_formatter("", &stats, fixed_time_formatter);- assert!(output.is_empty());- }-- #[test]- fn test_format_log_output_preserves_graph_lines() {- // Merge commit with graph continuation line between commits- let hash1 = "abc1234567890123456789012345678901234567ab";- let hash2 = "def5678901234567890123456789012345678901cd";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Merge branch\n\- |\\ \n\- | * \x01{}\x00def5678\x1f1699998000\x1f Feature commit",- hash1, hash2- );- let stats = multi_stats(&[(hash1, 0, 0), (hash2, 5, 2)]);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- // Graph line should be preserved between commits- assert!(output.contains("|\\"), "graph line should be preserved");- assert!(output.contains("abc1234"), "first commit should be present");- assert!(- output.contains("def5678"),- "second commit should be present"- );-- // Verify order: merge commit, graph line, feature commit- let lines: Vec<&str> = output.lines().collect();- assert_eq!(lines.len(), 3, "Expected 3 lines: {:?}", lines);- assert!(lines[0].contains("abc1234"));- assert!(lines[1].contains("\\"));- assert!(lines[2].contains("def5678"));- }-- #[test]- fn test_format_log_output_no_stats() {- // Commit without stats (not in stats map)- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Just a commit",- full_hash- );- let stats = HashMap::new(); // Empty stats - shows no diff- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- assert!(output.contains("abc1234"));- assert!(output.contains("Just a commit"));- }-- #[test]- fn test_format_log_output_with_graph_prefix() {- // Git graph output includes graph characters- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Commit with graph",- full_hash- );- let stats = stats_for(full_hash, 5, 2);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- assert!(output.contains("abc1234"));- assert!(output.contains("Commit with graph"));- // Verify stats are present- assert!(output.contains("+5"), "expected +5 in output: {}", output);- assert!(output.contains("-2"), "expected -2 in output: {}", output);- }-- #[test]- fn test_format_log_output_zero_stats() {- // Commit with zero stats (e.g., binary-only changes)- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Add image", full_hash);- let stats = stats_for(full_hash, 0, 0);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- assert!(output.contains("abc1234"));- assert!(output.contains("Add image"));- }-- #[test]- fn test_format_log_output_malformed_commit_line() {- // Line without proper field delimiters passes through- let input = "abc1234 regular commit line";- let stats = HashMap::new();- let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);-- // Lines without \x1f delimiter pass through unchanged- assert!(output.contains("abc1234"));- }-- #[test]- fn test_format_log_output_commit_line_missing_second_delimiter() {- // Only one delimiter - malformed- let input = "abc1234\x1f1699999000 Fix bug";- let stats = HashMap::new();- let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);-- // Should output the line as-is since it's malformed (only one \x1f)- assert!(output.contains("abc1234"));- }-- #[test]- fn test_format_log_output_stats_only_deletions() {- // Commit with only deletions (no insertions)- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Remove old code",- full_hash- );- let stats = stats_for(full_hash, 0, 50);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- assert!(output.contains("abc1234"));- assert!(output.contains("Remove old code"));- // Should show deletions- assert!(output.contains("-50"), "expected -50 in output: {}", output);- }-- #[test]- fn test_format_log_output_large_stats() {- // Commit with large stats (tests K notation)- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!(- "* \x01{}\x00abc1234\x1f1699999000\x1f Big refactor",- full_hash- );- let stats = stats_for(full_hash, 1500, 800);- let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);-- assert!(output.contains("abc1234"));- // Large numbers should use K notation- assert!(- output.contains("+1K") || output.contains("+1.5K"),- "expected K notation in output: {}",- output- );- }-- #[test]- fn test_format_commit_line_directly() {- // Test the format_commit_line function directly- let commit_line = "abc1234\x1f1699999000\x1f Test commit";- let stats = (10, 5);- let target_width = 7; // "abc1234" is 7 chars, no padding needed- let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);-- assert!(output.contains("abc1234"));- assert!(output.contains("Test commit"));- assert!(output.contains("+10"), "expected +10 in output: {}", output);- assert!(output.contains("-5"), "expected -5 in output: {}", output);- assert!(output.contains("1h"), "expected time in output: {}", output);- }-- #[test]- fn test_format_commit_line_with_padding() {- // Test that padding aligns shorter hashes to target width- let commit_line = "abc12\x1f1699999000\x1f Short hash";- let stats = (5, 2);- let target_width = 9; // Pad "abc12" (5 chars) to 9 chars- let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);-- // Should have 4 spaces of padding after hash before stats- assert!(output.contains("abc12 "), "expected padding: {}", output);- }-- // Tests for process_log_with_dimming- //- // Input format: graph_prefix + SOH (\x01) + full_hash + NUL (\x00) + display- // Example: "* \x01abc123...def456\x00abc1234 (HEAD) message"-- /// Parse output to determine which lines are dimmed vs bright.- /// Returns (is_dimmed, content) for each line.- fn parse_dimming_output(output: &str) -> Vec<(bool, String)> {- use ansi_str::AnsiStr;- output- .lines()- .map(|line| {- // Check if line contains dim escape sequence (\x1b[2m)- let is_dimmed = line.contains("\x1b[2m");- let content = line.ansi_strip().to_string();- (is_dimmed, content)- })- .collect()- }-- #[test]- fn test_process_log_with_dimming_parses_commit_line() {- // Simulates git log output with SOH/NUL delimiters around full hash- let hash = "abc123456789012345678901234567890123456789";- let input = format!("* \x01{}\x00abc1234 (HEAD) Fix bug", hash);-- let unique = HashSet::from([hash.to_string()]);- let (output, hashes) = process_log_with_dimming(&input, Some(&unique));-- // SOH/NUL markers are preserved for format_log_output to extract hashes- assert!(- output.contains('\x01'),- "SOH should be preserved for format_log_output"- );- assert!(- output.contains('\x00'),- "NUL should be preserved for format_log_output"- );- assert!(output.contains("abc1234"), "short hash preserved");- assert!(output.contains("Fix bug"), "message preserved");-- // Hashes should be collected for batch stats lookup- assert_eq!(hashes.len(), 1);- assert_eq!(hashes[0], hash);-- // Should be bright (in unique set)- let parsed = parse_dimming_output(&output);- assert_eq!(parsed.len(), 1);- assert!(!parsed[0].0, "commit in unique set should be bright");- }-- #[test]- fn test_process_log_with_dimming_dims_non_unique() {- let unique_hash = "abc123456789012345678901234567890123456789";- let other_hash = "def123456789012345678901234567890123456789";-- let input = format!(- "* \x01{}\x00abc1234 Unique commit\n\- * \x01{}\x00def1234 Not unique",- unique_hash, other_hash- );-- let unique = HashSet::from([unique_hash.to_string()]);- let (output, hashes) = process_log_with_dimming(&input, Some(&unique));-- // Both hashes should be collected- assert_eq!(hashes.len(), 2);-- let parsed = parse_dimming_output(&output);- assert_eq!(parsed.len(), 2);-- // First commit (unique) should be bright- assert!(!parsed[0].0, "unique commit should be bright");- assert!(parsed[0].1.contains("Unique commit"));-- // Second commit (not unique) should be dimmed- assert!(parsed[1].0, "non-unique commit should be dimmed");- assert!(parsed[1].1.contains("Not unique"));- }-- #[test]- fn test_process_log_with_dimming_none_means_all_bright() {- // None = default branch, show everything bright- let hash = "abc123456789012345678901234567890123456789";- let input = format!("* \x01{}\x00abc1234 Some commit", hash);-- let (output, hashes) = process_log_with_dimming(&input, None);-- assert_eq!(hashes.len(), 1);- let parsed = parse_dimming_output(&output);- assert_eq!(parsed.len(), 1);- assert!(!parsed[0].0, "None means default branch, all bright");- }-- #[test]- fn test_process_log_with_dimming_empty_set_means_all_dim() {- // Some(empty) = feature branch with no unique commits, dim everything- let hash = "abc123456789012345678901234567890123456789";- let input = format!("* \x01{}\x00abc1234 Some commit", hash);-- let empty: HashSet<String> = HashSet::new();- let (output, hashes) = process_log_with_dimming(&input, Some(&empty));-- assert_eq!(hashes.len(), 1);- let parsed = parse_dimming_output(&output);- assert_eq!(parsed.len(), 1);- assert!(- parsed[0].0,- "Some(empty) means feature branch with no unique commits, all dim"- );- }-- #[test]- fn test_process_log_with_dimming_preserves_graph_lines() {- let hash = "abc123456789012345678901234567890123456789";- // Git graph can have continuation lines between commits- let input = format!(- "* \x01{}\x00abc1234 First\n\- |\n\- * \x01{}\x00def1234 Second",- hash, "def123456789012345678901234567890123456789"- );-- let unique = HashSet::from([hash.to_string()]);- let (output, _hashes) = process_log_with_dimming(&input, Some(&unique));-- // Graph-only line should be preserved unchanged- assert!(output.contains("\n|\n"), "graph line should be preserved");- }-- #[test]- fn test_process_log_with_dimming_sha256_compatible() {- // SHA-256 hashes are 64 characters (not 40)- let sha256_hash = "abc1234567890123456789012345678901234567890123456789012345678901";- assert_eq!(sha256_hash.len(), 64);-- let input = format!("* \x01{}\x00abc1234 SHA-256 repo", sha256_hash);-- let unique = HashSet::from([sha256_hash.to_string()]);- let (output, hashes) = process_log_with_dimming(&input, Some(&unique));-- assert_eq!(hashes[0], sha256_hash);- let parsed = parse_dimming_output(&output);- assert!(!parsed[0].0, "SHA-256 hash should be matched correctly");- assert!(parsed[0].1.contains("SHA-256 repo"));- }-- #[test]- fn test_process_log_with_dimming_strips_ansi_when_dimming() {- let hash = "abc123456789012345678901234567890123456789";- // Simulate colored git output- let input = format!(- "* \x01{}\x00\x1b[33mabc1234\x1b[m\x1b[33m (HEAD)\x1b[m message",- hash- );-- // Use a different hash to trigger dimming- let other_unique = HashSet::from(["other".to_string()]);- let (output, _hashes) = process_log_with_dimming(&input, Some(&other_unique));-- // Dimmed output should have colors stripped- let parsed = parse_dimming_output(&output);- assert!(parsed[0].0, "should be dimmed");- // The ansi_strip should have removed the color codes- assert!(parsed[0].1.contains("abc1234"));- assert!(parsed[0].1.contains("(HEAD)"));- }-- // Tests for strip_hash_markers-- #[test]- fn test_strip_hash_markers_removes_soh_nul_block() {- let full_hash = "abc1234567890123456789012345678901234567ab";- let input = format!("* \x01{}\x00abc1234 message", full_hash);- let output = strip_hash_markers(&input);-- assert!(!output.contains('\x01'));- assert!(!output.contains('\x00'));- assert_eq!(output, "* abc1234 message");- }-- #[test]- fn test_strip_hash_markers_preserves_other_content() {- // No markers - content unchanged- let input = "* abc1234 (HEAD -> main) Initial commit";- let output = strip_hash_markers(input);- assert_eq!(output, input);- }-- #[test]- fn test_strip_hash_markers_handles_multiple_markers() {- let input = "line1 \x01hash1\x00 content1\nline2 \x01hash2\x00 content2";- let output = strip_hash_markers(input);- assert_eq!(output, "line1 content1\nline2 content2");- }-- // Tests for extract_hash_from_line-- #[test]- fn test_extract_hash_from_line_finds_hash() {- let full_hash = "abc1234567890123456789012345678901234567ab";- let line = format!("* \x01{}\x00abc1234 message", full_hash);- let extracted = extract_hash_from_line(&line);- assert_eq!(extracted, Some(full_hash));- }-- #[test]- fn test_extract_hash_from_line_sha256() {- let sha256_hash = "abc1234567890123456789012345678901234567890123456789012345678901";- let line = format!("* \x01{}\x00abc1234 message", sha256_hash);- let extracted = extract_hash_from_line(&line);- assert_eq!(extracted, Some(sha256_hash));- }-- #[test]- fn test_extract_hash_from_line_no_markers() {- let line = "* abc1234 message";- let extracted = extract_hash_from_line(line);- assert_eq!(extracted, None);- }-- #[test]- fn test_extract_hash_from_line_incomplete_markers() {- // Only SOH, no NUL- let line = "* \x01abc1234 message";- let extracted = extract_hash_from_line(line);- assert_eq!(extracted, None);- }-}diff --git a/src/commands/select/items.rs b/src/commands/select/items.rsnew file mode 100644index 000000000..159244f6e--- /dev/null+++ b/src/commands/select/items.rs@@ -0,0 +1,420 @@+//! Skim item implementations.+//!+//! Wrappers for ListItem and header row that implement SkimItem for the interactive selector.++use std::borrow::Cow;+use std::collections::HashSet;+use std::sync::Arc;++use color_print::cformat;+use skim::prelude::*;+use worktrunk::git::Repository;++use super::super::list::model::ListItem;+use super::log_formatter::{+ FIELD_DELIM, batch_fetch_stats, format_log_output, process_log_with_dimming, strip_hash_markers,+};+use super::pager::{get_diff_pager, run_git_diff_with_pager};+use super::preview::{PreviewMode, PreviewStateData};++/// Header item for column names (non-selectable)+pub(super) struct HeaderSkimItem {+ pub display_text: String,+ pub display_text_with_ansi: String,+}++impl SkimItem for HeaderSkimItem {+ fn text(&self) -> Cow<'_, str> {+ Cow::Borrowed(&self.display_text)+ }++ fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {+ skim::AnsiString::parse(&self.display_text_with_ansi)+ }++ fn output(&self) -> Cow<'_, str> {+ Cow::Borrowed("") // Headers produce no output if selected+ }+}++/// Wrapper to implement SkimItem for ListItem+pub(super) struct WorktreeSkimItem {+ pub display_text: String,+ pub display_text_with_ansi: String,+ pub branch_name: String,+ pub item: Arc<ListItem>,+}++impl SkimItem for WorktreeSkimItem {+ fn text(&self) -> Cow<'_, str> {+ Cow::Borrowed(&self.display_text)+ }++ fn display<'a>(&'a self, _context: skim::DisplayContext<'a>) -> skim::AnsiString<'a> {+ skim::AnsiString::parse(&self.display_text_with_ansi)+ }++ fn output(&self) -> Cow<'_, str> {+ Cow::Borrowed(&self.branch_name)+ }++ fn preview(&self, context: PreviewContext<'_>) -> ItemPreview {+ let mode = PreviewStateData::read_mode();++ // Build preview: tabs header + content+ let mut result = Self::render_preview_tabs(mode);+ result.push_str(&self.preview_for_mode(mode, context.width, context.height));++ ItemPreview::AnsiText(result)+ }+}++impl WorktreeSkimItem {+ /// Render the tab header for the preview window+ ///+ /// Shows all preview modes as tabs, with the current mode bolded+ /// and unselected modes dimmed. Controls shown below in normal text+ /// for visual distinction from inactive tabs.+ pub(super) fn render_preview_tabs(mode: PreviewMode) -> String {+ /// Format a tab label with bold (active) or dimmed (inactive) styling+ fn format_tab(label: &str, is_active: bool) -> String {+ if is_active {+ cformat!("<bold>{}</>", label)+ } else {+ cformat!("<dim>{}</>", label)+ }+ }++ let tab1 = format_tab("1: HEAD±", mode == PreviewMode::WorkingTree);+ let tab2 = format_tab("2: log", mode == PreviewMode::Log);+ let tab3 = format_tab("3: main…±", mode == PreviewMode::BranchDiff);+ let tab4 = format_tab("4: remote⇅", mode == PreviewMode::UpstreamDiff);++ // Controls use dim yellow to distinguish from dimmed (white) tabs+ let controls = cformat!(+ "<dim,yellow>Enter: switch | Esc: cancel | ctrl-u/d: scroll | alt-p: toggle</>"+ );++ format!(+ "{} | {} | {} | {}\n{}\n\n",+ tab1, tab2, tab3, tab4, controls+ )+ }++ /// Render preview for the given mode with specified dimensions+ fn preview_for_mode(&self, mode: PreviewMode, width: usize, height: usize) -> String {+ match mode {+ PreviewMode::WorkingTree => self.render_working_tree_preview(width),+ PreviewMode::Log => self.render_log_preview(width, height),+ PreviewMode::BranchDiff => self.render_branch_diff_preview(width),+ PreviewMode::UpstreamDiff => self.render_upstream_diff_preview(width),+ }+ }++ /// Common diff rendering pattern: check stat, show stat + full diff if non-empty+ fn render_diff_preview(&self, args: &[&str], no_changes_msg: &str, width: usize) -> String {+ let mut output = String::new();+ let Ok(repo) = Repository::current() else {+ return no_changes_msg.to_string();+ };++ // Check stat output first+ let mut stat_args = args.to_vec();+ stat_args.push("--stat");+ stat_args.push("--color=always");+ let stat_width_arg = format!("--stat-width={}", width);+ stat_args.push(&stat_width_arg);++ if let Ok(stat) = repo.run_command(&stat_args)+ && !stat.trim().is_empty()+ {+ output.push_str(&stat);++ // Build diff args with color+ let mut diff_args = args.to_vec();+ diff_args.push("--color=always");++ // Try streaming through pager first (git diff | pager), fall back to plain diff+ let diff = get_diff_pager()+ .and_then(|pager| run_git_diff_with_pager(&diff_args, pager))+ .or_else(|| repo.run_command(&diff_args).ok());++ if let Some(diff) = diff {+ output.push_str(&diff);+ }+ } else {+ output.push_str(no_changes_msg);+ output.push('\n');+ }++ output+ }++ /// Render Tab 1: Working tree preview (uncommitted changes vs HEAD)+ /// Matches `wt list` "HEAD±" column+ fn render_working_tree_preview(&self, width: usize) -> String {+ use worktrunk::styling::INFO_SYMBOL;++ let Some(wt_info) = self.item.worktree_data() else {+ // Branch without worktree - selecting will create one+ let branch = self.item.branch_name();+ return format!(+ "{INFO_SYMBOL} {branch} is branch only — press Enter to create worktree\n"+ );+ };++ let branch = self.item.branch_name();+ let path = wt_info.path.display().to_string();++ self.render_diff_preview(+ &["-C", &path, "diff", "HEAD"],+ &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no uncommitted changes"),+ width,+ )+ }++ /// Render Tab 3: Branch diff preview (line diffs in commits ahead of default branch)+ /// Matches `wt list` "main…± (--full)" column+ fn render_branch_diff_preview(&self, width: usize) -> String {+ use worktrunk::styling::INFO_SYMBOL;++ let branch = self.item.branch_name();+ let Ok(repo) = Repository::current() else {+ return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");+ };+ let Some(default_branch) = repo.default_branch() else {+ return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");+ };+ if self.item.counts.is_some_and(|c| c.ahead == 0) {+ return cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of <bold>{default_branch}</>\n"+ );+ }++ let merge_base = format!("{}...{}", default_branch, self.item.head());+ self.render_diff_preview(+ &["diff", &merge_base],+ &cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no file changes vs <bold>{default_branch}</>"+ ),+ width,+ )+ }++ /// Render Tab 4: Upstream diff preview (ahead/behind vs tracking branch)+ /// Matches `wt list` "Remote⇅" column+ fn render_upstream_diff_preview(&self, width: usize) -> String {+ use worktrunk::styling::INFO_SYMBOL;++ let branch = self.item.branch_name();++ // Check if this branch has an upstream tracking branch+ // Use as_ref() to avoid cloning UpstreamStatus on every preview render+ let Some(active) = self.item.upstream.as_ref().and_then(|u| u.active()) else {+ return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no upstream tracking branch\n");+ };++ // Use @{u} syntax for performance (avoids extra git command to resolve upstream ref)+ // Format: branch@{u} resolves to the upstream tracking branch+ let upstream_ref = format!("{}@{{u}}", branch);++ if active.ahead == 0 && active.behind == 0 {+ return cformat!("{INFO_SYMBOL} <bold>{branch}</> is up to date with upstream\n");+ }++ // Handle different states: ahead only, behind only, or diverged+ // Use ⇡/⇣ symbols to match wt list's Remote⇅ column+ if active.ahead > 0 && active.behind > 0 {+ // Diverged: show local changes (what would be pushed)+ // Use three-dot diff to show changes unique to local branch+ let range = format!("{}...{}", upstream_ref, self.item.head());+ self.render_diff_preview(+ &["diff", &range],+ &cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has diverged (⇡{} ⇣{}) but no unique file changes",+ active.ahead,+ active.behind+ ),+ width,+ )+ } else if active.ahead > 0 {+ // Ahead only: show unpushed commits+ let range = format!("{}...{}", upstream_ref, self.item.head());+ self.render_diff_preview(+ &["diff", &range],+ &cformat!("{INFO_SYMBOL} <bold>{branch}</> has no unpushed file changes"),+ width,+ )+ } else {+ // Behind only: show what upstream has that we don't+ let range = format!("{}...{}", self.item.head(), upstream_ref);+ self.render_diff_preview(+ &["diff", &range],+ &cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> is behind upstream (⇣{}) but no file changes",+ active.behind+ ),+ width,+ )+ }+ }++ /// Render Tab 2: Log preview+ fn render_log_preview(&self, width: usize, height: usize) -> String {+ use worktrunk::styling::INFO_SYMBOL;+ // Minimum preview width to show timestamps (adds ~7 chars: space + 4-char time + space)+ // Note: preview is typically 50% of terminal width, so 50 = 100-col terminal+ const TIMESTAMP_WIDTH_THRESHOLD: usize = 50;+ // Tab header takes 3 lines (tabs + controls + blank)+ const HEADER_LINES: usize = 3;++ let mut output = String::new();+ let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;+ // Calculate how many log lines fit in preview (height minus header)+ let log_limit = height.saturating_sub(HEADER_LINES).max(1);+ let head = self.item.head();+ let branch = self.item.branch_name();+ let Ok(repo) = Repository::current() else {+ output.push_str(&cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"+ ));+ return output;+ };+ let Some(default_branch) = repo.default_branch() else {+ output.push_str(&cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"+ ));+ return output;+ };++ // Get merge-base with default branch+ //+ // Note on error handling: This code runs in an interactive preview pane that updates+ // on every keystroke. We intentionally use silent fallbacks rather than propagating+ // errors to avoid disruptive error messages during navigation. The preview is+ // supplementary - users can still select worktrees even if preview fails.+ //+ // Alternative: Check specific conditions (default branch exists, valid HEAD, etc.) before+ // running git commands. This would provide better diagnostics but adds latency to+ // every preview render. Trade-off: simplicity + speed vs. detailed error messages.+ let Ok(merge_base_output) = repo.run_command(&["merge-base", &default_branch, head]) else {+ output.push_str(&cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"+ ));+ return output;+ };++ let merge_base = merge_base_output.trim();+ let is_default_branch = branch == default_branch;++ // Format strings for git log+ // Without timestamps: hash (colored/dimmed), then message+ // Format includes full hash (for matching) between SOH and NUL delimiters.+ // Display content uses \x1f to separate fields for timestamp parsing.+ // Format: SOH full_hash NUL short_hash \x1f timestamp \x1f decorations+message+ // Using delimiters allows parsing without assuming fixed hash length (SHA-256 safe)+ // Note: Use %x01/%x00 (git's hex escapes) to avoid embedding control chars in argv+ let timestamp_format = format!(+ "--format=%x01%H%x00%C(auto)%h{}%ct{}%C(auto)%d%C(reset) %s",+ FIELD_DELIM, FIELD_DELIM+ );+ let no_timestamp_format = "--format=%x01%H%x00%C(auto)%h%C(auto)%d%C(reset) %s";++ let log_limit_str = log_limit.to_string();++ // Get commits after merge-base (for dimming logic)+ // These are commits reachable from HEAD but not from merge-base, shown bright.+ // Commits before merge-base (shared with default branch) are shown dimmed.+ // Bounded to log_limit since we only need to check displayed commits.+ let unique_commits: Option<HashSet<String>> = if is_default_branch {+ // On default branch: no dimming (None means show everything bright)+ None+ } else {+ // On feature branch: get commits unique to this branch+ // rev-list A...B --right-only gives commits reachable from B but not A+ let range = format!("{}...{}", merge_base, head);+ let commits = repo+ .run_command(&["rev-list", &range, "--right-only", "-n", &log_limit_str])+ .map(|out| out.lines().map(String::from).collect())+ .unwrap_or_default();+ Some(commits) // Some(empty) means dim everything+ };++ // Get graph output (no --numstat to avoid blank continuation lines)+ let format: &str = if show_timestamps {+ ×tamp_format+ } else {+ no_timestamp_format+ };+ let args = vec![+ "log",+ "--graph",+ format,+ "--color=always",+ "-n",+ &log_limit_str,+ head,+ ];++ if let Ok(log_output) = repo.run_command(&args) {+ let (processed, hashes) =+ process_log_with_dimming(&log_output, unique_commits.as_ref());+ if show_timestamps {+ // Batch fetch stats for all commits+ let stats = batch_fetch_stats(&repo, &hashes);+ output.push_str(&format_log_output(&processed, &stats));+ } else {+ // Strip hash markers (SOH...NUL) since we're not using format_log_output+ output.push_str(&strip_hash_markers(&processed));+ }+ }++ output+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_render_preview_tabs_working_tree_mode() {+ let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::WorkingTree);+ // Tab 1 should be bold (active), tabs 2/3/4 dimmed+ assert!(output.contains("1: HEAD±"));+ assert!(output.contains("2: log"));+ assert!(output.contains("3: main…±"));+ assert!(output.contains("4: remote⇅"));+ assert!(output.contains("Enter: switch"));+ // Verify structure: tabs on first line, controls on second+ assert!(output.contains(" | "));+ assert!(output.ends_with("\n\n"));+ }++ #[test]+ fn test_render_preview_tabs_log_mode() {+ let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::Log);+ assert!(output.contains("1: HEAD±"));+ assert!(output.contains("2: log"));+ assert!(output.contains("3: main…±"));+ assert!(output.contains("4: remote⇅"));+ }++ #[test]+ fn test_render_preview_tabs_branch_diff_mode() {+ let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::BranchDiff);+ assert!(output.contains("1: HEAD±"));+ assert!(output.contains("2: log"));+ assert!(output.contains("3: main…±"));+ assert!(output.contains("4: remote⇅"));+ }++ #[test]+ fn test_render_preview_tabs_upstream_diff_mode() {+ let output = WorktreeSkimItem::render_preview_tabs(PreviewMode::UpstreamDiff);+ assert!(output.contains("1: HEAD±"));+ assert!(output.contains("2: log"));+ assert!(output.contains("3: main…±"));+ assert!(output.contains("4: remote⇅"));+ }+}diff --git a/src/commands/select/log_formatter.rs b/src/commands/select/log_formatter.rsnew file mode 100644index 000000000..0301f74d3--- /dev/null+++ b/src/commands/select/log_formatter.rs@@ -0,0 +1,786 @@+//! Git log output formatting.+//!+//! Functions for processing and formatting git log output with diffstats and dimming.++use std::collections::{HashMap, HashSet};++use worktrunk::git::{Repository, parse_numstat_line};+use worktrunk::shell_exec::Cmd;++use super::super::list::layout::{DiffDisplayConfig, DiffVariant};++/// Field delimiter for git log format with timestamps+pub(super) const FIELD_DELIM: char = '\x1f';++/// Start delimiter for full hash (SOH - Start of Heading)+pub(super) const HASH_START: char = '\x01';++/// End delimiter for full hash (NUL)+pub(super) const HASH_END: char = '\x00';++/// Timestamp column width ("12mo" is the longest)+pub(super) const TIMESTAMP_WIDTH: usize = 4;++/// Batch fetch diffstats for multiple commits using git diff-tree --stdin.+/// Returns a map of full_hash -> (insertions, deletions).+///+/// Failures are silent (preview context).+pub(super) fn batch_fetch_stats(+ repo: &Repository,+ hashes: &[String],+) -> HashMap<String, (usize, usize)> {+ if hashes.is_empty() {+ return HashMap::new();+ }++ // --root: include stats for root commits (no parent to diff against)+ // Each hash needs a trailing newline for git to process it+ let stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();+ let Ok(output) = Cmd::new("git")+ .args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])+ .current_dir(repo.repo_path().unwrap_or_else(|_| ".".into()))+ .stdin_bytes(stdin_data)+ .run()+ else {+ return HashMap::new();+ };++ // Parse output: hash line followed by numstat lines+ let mut stats: HashMap<String, (usize, usize)> = HashMap::new();+ let mut current_hash: Option<String> = None;+ let mut current_stats = (0usize, 0usize);++ for line in String::from_utf8_lossy(&output.stdout).lines() {+ // Hash line (40 or 64 hex chars)+ if line.chars().all(|c| c.is_ascii_hexdigit()) && (line.len() == 40 || line.len() == 64) {+ // Save previous hash's stats+ if let Some(hash) = current_hash.take() {+ stats.insert(hash, current_stats);+ }+ current_hash = Some(line.to_string());+ current_stats = (0, 0);+ } else if let Some((ins, del)) = parse_numstat_line(line) {+ current_stats.0 += ins;+ current_stats.1 += del;+ }+ }++ // Don't forget the last hash+ if let Some(hash) = current_hash {+ stats.insert(hash, current_stats);+ }++ stats+}++/// Process git log output: strip hash prefix and dim non-unique commits.+///+/// - `unique_commits = None`: show everything bright (default branch)+/// - `unique_commits = Some(set)`: bright if in set, dim otherwise+/// - Graph-only lines pass through unchanged+///+/// Returns (processed_output, list_of_full_hashes) for batch stats lookup.+pub(super) fn process_log_with_dimming(+ log_output: &str,+ unique_commits: Option<&HashSet<String>>,+) -> (String, Vec<String>) {+ use ansi_str::AnsiStr;+ use std::fmt::Write;++ let dim = anstyle::Style::new().dimmed();+ let reset = anstyle::Reset;++ let mut result = String::with_capacity(log_output.len());+ let mut hashes = Vec::new();++ for (i, line) in log_output.lines().enumerate() {+ if i > 0 {+ result.push('\n');+ }++ // Parse commit line: graph_prefix + SOH + full_hash + NUL + display+ if let Some(hash_start) = line.find(HASH_START)+ && let Some(hash_end_offset) = line[hash_start + 1..].find(HASH_END)+ {+ let hash_end = hash_start + 1 + hash_end_offset;+ let graph_prefix = &line[..hash_start];+ let full_hash = &line[hash_start + 1..hash_end];+ let display = &line[hash_end + 1..];++ // Collect hash for stats lookup+ hashes.push(full_hash.to_string());++ // Bright if: no dimming (None) OR commit is in unique set+ let is_bright = match unique_commits {+ None => true, // Default branch: all bright+ Some(set) => set.contains(full_hash), // Feature branch: bright if unique+ };++ // Keep SOH hash NUL markers for format_log_output to extract hash for stats lookup+ if is_bright {+ result.push_str(graph_prefix);+ result.push(HASH_START);+ result.push_str(full_hash);+ result.push(HASH_END);+ result.push_str(display);+ } else {+ // Dim: strip colors and wrap in dim style, but keep hash markers+ let _ = write!(+ result,+ "{}{HASH_START}{full_hash}{HASH_END}{dim}{}{reset}",+ graph_prefix,+ display.ansi_strip()+ );+ }+ continue;+ }+ // Graph-only lines: pass through unchanged+ result.push_str(line);+ }+ (result, hashes)+}++/// Format git log output with timestamps and diffstats.+///+/// Takes pre-processed log output (graph + commits) and a stats map.+/// Each commit line has format: `graph_prefix short_hash \x1f timestamp \x1f decoration message`+///+/// The full hash for stats lookup is embedded as: `SOH full_hash NUL` before the short hash,+/// but this was already stripped by process_log_with_dimming. We need the hash in the line+/// to look up stats - so we keep the full hash in a different delimiter for this function.+pub(super) fn format_log_output(+ log_output: &str,+ stats: &HashMap<String, (usize, usize)>,+) -> String {+ use crate::display::format_relative_time_short;+ format_log_output_with_formatter(log_output, stats, format_relative_time_short)+}++/// Format git log output with a custom time formatter.+///+/// This variant allows dependency injection for testing with deterministic timestamps.+pub(super) fn format_log_output_with_formatter<F>(+ log_output: &str,+ stats: &HashMap<String, (usize, usize)>,+ format_time: F,+) -> String+where+ F: Fn(i64) -> String,+{+ use ansi_str::AnsiStr;+ use unicode_width::UnicodeWidthStr;++ // First pass: find max display width of graph+hash prefix for alignment+ let max_prefix_width = log_output+ .lines()+ .filter(|line| line.contains(FIELD_DELIM))+ .filter_map(|line| {+ let first_delim = line.find(FIELD_DELIM)?;+ let graph_hash_raw = &line[..first_delim];+ let graph_hash = strip_hash_markers(graph_hash_raw);+ // Calculate display width (strip ANSI, measure unicode width)+ Some(graph_hash.ansi_strip().width())+ })+ .max()+ .unwrap_or(0);++ // Second pass: format with alignment+ let mut result = Vec::new();+ for line in log_output.lines() {+ if line.contains(FIELD_DELIM) {+ // Commit line - look up stats by hash extracted from line+ let commit_stats = extract_hash_from_line(line)+ .and_then(|h| stats.get(h))+ .copied()+ .unwrap_or((0, 0));+ result.push(format_commit_line(+ line,+ commit_stats,+ max_prefix_width,+ &format_time,+ ));+ } else {+ // Graph-only line - pass through+ result.push(line.to_string());+ }+ }++ result.join("\n")+}++/// Extract the full hash from a commit line that still has SOH/NUL markers.+/// Returns None if not found (line already processed or malformed).+pub(super) fn extract_hash_from_line(line: &str) -> Option<&str> {+ let hash_start = line.find(HASH_START)?;+ let hash_end_offset = line[hash_start + 1..].find(HASH_END)?;+ Some(&line[hash_start + 1..hash_start + 1 + hash_end_offset])+}++/// Strip SOH...NUL hash markers from output (used when not formatting with timestamps).+pub(super) fn strip_hash_markers(s: &str) -> String {+ let mut result = String::with_capacity(s.len());+ let mut chars = s.chars().peekable();++ while let Some(c) = chars.next() {+ if c == HASH_START {+ // Skip until NUL+ while let Some(&next) = chars.peek() {+ chars.next();+ if next == HASH_END {+ break;+ }+ }+ } else {+ result.push(c);+ }+ }+ result+}++/// Format a single commit line with stats, padding the prefix to target_width for alignment+pub(super) fn format_commit_line<F>(+ commit_line: &str,+ (insertions, deletions): (usize, usize),+ target_width: usize,+ format_time: &F,+) -> String+where+ F: Fn(i64) -> String,+{+ use ansi_str::AnsiStr;+ use unicode_width::UnicodeWidthStr;+ use worktrunk::styling::{ADDITION, DELETION};++ let dim_style = anstyle::Style::new().dimmed();+ let reset = anstyle::Reset;++ if let Some(first_delim) = commit_line.find(FIELD_DELIM)+ && let Some(second_delim) = commit_line[first_delim + 1..].find(FIELD_DELIM)+ {+ let graph_hash_raw = &commit_line[..first_delim];+ // Strip SOH...NUL hash markers from graph_hash portion+ let graph_hash = strip_hash_markers(graph_hash_raw);+ let timestamp_str = &commit_line[first_delim + 1..first_delim + 1 + second_delim];+ let rest = &commit_line[first_delim + 1 + second_delim + 1..];++ let time = timestamp_str+ .parse::<i64>()+ .map(format_time)+ .unwrap_or_default();++ // Use the same diff formatting as wt list (aligned columns)+ let diff_config = DiffDisplayConfig {+ variant: DiffVariant::Signs,+ positive_style: ADDITION,+ negative_style: DELETION,+ always_show_zeros: false,+ };+ let stat_str = format!(" {}", diff_config.format_aligned(insertions, deletions));++ // Pad graph_hash to target_width for column alignment+ let current_width = graph_hash.ansi_strip().width();+ let padding = " ".repeat(target_width.saturating_sub(current_width));++ format!(+ "{}{}{} {dim_style}{:>width$}{reset}{}",+ graph_hash,+ padding,+ stat_str,+ time,+ rest,+ width = TIMESTAMP_WIDTH+ )+ } else {+ commit_line.to_string()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ // format_log_output tests use dependency injection for deterministic time formatting.+ // The format_log_output_with_formatter function accepts a time formatter closure.++ /// Fixed time formatter for deterministic tests+ fn fixed_time_formatter(_timestamp: i64) -> String {+ "1h".to_string() // Return a fixed time for all timestamps+ }++ /// Create a stats map with a single entry+ fn stats_for(+ hash: &str,+ insertions: usize,+ deletions: usize,+ ) -> HashMap<String, (usize, usize)> {+ let mut map = HashMap::new();+ map.insert(hash.to_string(), (insertions, deletions));+ map+ }++ /// Create a stats map with multiple entries+ fn multi_stats(entries: &[(&str, usize, usize)]) -> HashMap<String, (usize, usize)> {+ entries+ .iter()+ .map(|(h, i, d)| (h.to_string(), (*i, *d)))+ .collect()+ }++ #[test]+ fn test_format_log_output_single_commit() {+ // Simulate git log output with SOH/NUL markers: * SOH full_hash NUL short_hash \x1f timestamp \x1f message+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Fix bug", full_hash);+ let stats = stats_for(full_hash, 5, 2);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ // Should contain the hash and message+ assert!(output.contains("abc1234"));+ assert!(output.contains("Fix bug"));+ // Should contain formatted time+ assert!(output.contains("1h"));+ // Should contain stats+ assert!(output.contains("+5"), "expected +5 in output: {}", output);+ }++ #[test]+ fn test_format_log_output_with_stats() {+ // Commit line with pre-computed stats+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Add feature",+ full_hash+ );+ // Stats are pre-computed (accumulated from numstat lines)+ let stats = stats_for(full_hash, 13, 5);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ // Should contain the hash and message+ assert!(output.contains("abc1234"));+ assert!(output.contains("Add feature"));+ // Verify stats are present (green +13, red -5)+ assert!(output.contains("+13"), "expected +13 in output: {}", output);+ assert!(output.contains("-5"), "expected -5 in output: {}", output);+ }++ #[test]+ fn test_format_log_output_multiple_commits() {+ // Two commits with pre-computed stats+ let hash1 = "abc1234567890123456789012345678901234567ab";+ let hash2 = "def5678901234567890123456789012345678901cd";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f First commit\n\+ * \x01{}\x00def5678\x1f1699998000\x1f Second commit",+ hash1, hash2+ );+ let stats = multi_stats(&[(hash1, 5, 2), (hash2, 10, 3)]);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ // Both commits should be in output+ assert!(output.contains("abc1234"));+ assert!(output.contains("def5678"));+ assert!(output.contains("First commit"));+ assert!(output.contains("Second commit"));++ // Output should be two lines (one per commit)+ let lines: Vec<&str> = output.lines().collect();+ assert_eq!(lines.len(), 2, "Expected 2 lines, got: {:?}", lines);+ }++ #[test]+ fn test_format_log_output_empty_input() {+ let stats = HashMap::new();+ let output = format_log_output_with_formatter("", &stats, fixed_time_formatter);+ assert!(output.is_empty());+ }++ #[test]+ fn test_format_log_output_preserves_graph_lines() {+ // Merge commit with graph continuation line between commits+ let hash1 = "abc1234567890123456789012345678901234567ab";+ let hash2 = "def5678901234567890123456789012345678901cd";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Merge branch\n\+ |\\ \n\+ | * \x01{}\x00def5678\x1f1699998000\x1f Feature commit",+ hash1, hash2+ );+ let stats = multi_stats(&[(hash1, 0, 0), (hash2, 5, 2)]);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ // Graph line should be preserved between commits+ assert!(output.contains("|\\"), "graph line should be preserved");+ assert!(output.contains("abc1234"), "first commit should be present");+ assert!(+ output.contains("def5678"),+ "second commit should be present"+ );++ // Verify order: merge commit, graph line, feature commit+ let lines: Vec<&str> = output.lines().collect();+ assert_eq!(lines.len(), 3, "Expected 3 lines: {:?}", lines);+ assert!(lines[0].contains("abc1234"));+ assert!(lines[1].contains("\\"));+ assert!(lines[2].contains("def5678"));+ }++ #[test]+ fn test_format_log_output_no_stats() {+ // Commit without stats (not in stats map)+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Just a commit",+ full_hash+ );+ let stats = HashMap::new(); // Empty stats - shows no diff+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ assert!(output.contains("abc1234"));+ assert!(output.contains("Just a commit"));+ }++ #[test]+ fn test_format_log_output_with_graph_prefix() {+ // Git graph output includes graph characters+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Commit with graph",+ full_hash+ );+ let stats = stats_for(full_hash, 5, 2);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ assert!(output.contains("abc1234"));+ assert!(output.contains("Commit with graph"));+ // Verify stats are present+ assert!(output.contains("+5"), "expected +5 in output: {}", output);+ assert!(output.contains("-2"), "expected -2 in output: {}", output);+ }++ #[test]+ fn test_format_log_output_zero_stats() {+ // Commit with zero stats (e.g., binary-only changes)+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!("* \x01{}\x00abc1234\x1f1699999000\x1f Add image", full_hash);+ let stats = stats_for(full_hash, 0, 0);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ assert!(output.contains("abc1234"));+ assert!(output.contains("Add image"));+ }++ #[test]+ fn test_format_log_output_malformed_commit_line() {+ // Line without proper field delimiters passes through+ let input = "abc1234 regular commit line";+ let stats = HashMap::new();+ let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);++ // Lines without \x1f delimiter pass through unchanged+ assert!(output.contains("abc1234"));+ }++ #[test]+ fn test_format_log_output_commit_line_missing_second_delimiter() {+ // Only one delimiter - malformed+ let input = "abc1234\x1f1699999000 Fix bug";+ let stats = HashMap::new();+ let output = format_log_output_with_formatter(input, &stats, fixed_time_formatter);++ // Should output the line as-is since it's malformed (only one \x1f)+ assert!(output.contains("abc1234"));+ }++ #[test]+ fn test_format_log_output_stats_only_deletions() {+ // Commit with only deletions (no insertions)+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Remove old code",+ full_hash+ );+ let stats = stats_for(full_hash, 0, 50);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ assert!(output.contains("abc1234"));+ assert!(output.contains("Remove old code"));+ // Should show deletions+ assert!(output.contains("-50"), "expected -50 in output: {}", output);+ }++ #[test]+ fn test_format_log_output_large_stats() {+ // Commit with large stats (tests K notation)+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!(+ "* \x01{}\x00abc1234\x1f1699999000\x1f Big refactor",+ full_hash+ );+ let stats = stats_for(full_hash, 1500, 800);+ let output = format_log_output_with_formatter(&input, &stats, fixed_time_formatter);++ assert!(output.contains("abc1234"));+ // Large numbers should use K notation+ assert!(+ output.contains("+1K") || output.contains("+1.5K"),+ "expected K notation in output: {}",+ output+ );+ }++ #[test]+ fn test_format_commit_line_directly() {+ // Test the format_commit_line function directly+ let commit_line = "abc1234\x1f1699999000\x1f Test commit";+ let stats = (10, 5);+ let target_width = 7; // "abc1234" is 7 chars, no padding needed+ let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);++ assert!(output.contains("abc1234"));+ assert!(output.contains("Test commit"));+ assert!(output.contains("+10"), "expected +10 in output: {}", output);+ assert!(output.contains("-5"), "expected -5 in output: {}", output);+ assert!(output.contains("1h"), "expected time in output: {}", output);+ }++ #[test]+ fn test_format_commit_line_with_padding() {+ // Test that padding aligns shorter hashes to target width+ let commit_line = "abc12\x1f1699999000\x1f Short hash";+ let stats = (5, 2);+ let target_width = 9; // Pad "abc12" (5 chars) to 9 chars+ let output = format_commit_line(commit_line, stats, target_width, &fixed_time_formatter);++ // Should have 4 spaces of padding after hash before stats+ assert!(output.contains("abc12 "), "expected padding: {}", output);+ }++ // Tests for process_log_with_dimming+ //+ // Input format: graph_prefix + SOH (\x01) + full_hash + NUL (\x00) + display+ // Example: "* \x01abc123...def456\x00abc1234 (HEAD) message"++ /// Parse output to determine which lines are dimmed vs bright.+ /// Returns (is_dimmed, content) for each line.+ fn parse_dimming_output(output: &str) -> Vec<(bool, String)> {+ use ansi_str::AnsiStr;+ output+ .lines()+ .map(|line| {+ // Check if line contains dim escape sequence (\x1b[2m)+ let is_dimmed = line.contains("\x1b[2m");+ let content = line.ansi_strip().to_string();+ (is_dimmed, content)+ })+ .collect()+ }++ #[test]+ fn test_process_log_with_dimming_parses_commit_line() {+ // Simulates git log output with SOH/NUL delimiters around full hash+ let hash = "abc123456789012345678901234567890123456789";+ let input = format!("* \x01{}\x00abc1234 (HEAD) Fix bug", hash);++ let unique = HashSet::from([hash.to_string()]);+ let (output, hashes) = process_log_with_dimming(&input, Some(&unique));++ // SOH/NUL markers are preserved for format_log_output to extract hashes+ assert!(+ output.contains('\x01'),+ "SOH should be preserved for format_log_output"+ );+ assert!(+ output.contains('\x00'),+ "NUL should be preserved for format_log_output"+ );+ assert!(output.contains("abc1234"), "short hash preserved");+ assert!(output.contains("Fix bug"), "message preserved");++ // Hashes should be collected for batch stats lookup+ assert_eq!(hashes.len(), 1);+ assert_eq!(hashes[0], hash);++ // Should be bright (in unique set)+ let parsed = parse_dimming_output(&output);+ assert_eq!(parsed.len(), 1);+ assert!(!parsed[0].0, "commit in unique set should be bright");+ }++ #[test]+ fn test_process_log_with_dimming_dims_non_unique() {+ let unique_hash = "abc123456789012345678901234567890123456789";+ let other_hash = "def123456789012345678901234567890123456789";++ let input = format!(+ "* \x01{}\x00abc1234 Unique commit\n\+ * \x01{}\x00def1234 Not unique",+ unique_hash, other_hash+ );++ let unique = HashSet::from([unique_hash.to_string()]);+ let (output, hashes) = process_log_with_dimming(&input, Some(&unique));++ // Both hashes should be collected+ assert_eq!(hashes.len(), 2);++ let parsed = parse_dimming_output(&output);+ assert_eq!(parsed.len(), 2);++ // First commit (unique) should be bright+ assert!(!parsed[0].0, "unique commit should be bright");+ assert!(parsed[0].1.contains("Unique commit"));++ // Second commit (not unique) should be dimmed+ assert!(parsed[1].0, "non-unique commit should be dimmed");+ assert!(parsed[1].1.contains("Not unique"));+ }++ #[test]+ fn test_process_log_with_dimming_none_means_all_bright() {+ // None = default branch, show everything bright+ let hash = "abc123456789012345678901234567890123456789";+ let input = format!("* \x01{}\x00abc1234 Some commit", hash);++ let (output, hashes) = process_log_with_dimming(&input, None);++ assert_eq!(hashes.len(), 1);+ let parsed = parse_dimming_output(&output);+ assert_eq!(parsed.len(), 1);+ assert!(!parsed[0].0, "None means default branch, all bright");+ }++ #[test]+ fn test_process_log_with_dimming_empty_set_means_all_dim() {+ // Some(empty) = feature branch with no unique commits, dim everything+ let hash = "abc123456789012345678901234567890123456789";+ let input = format!("* \x01{}\x00abc1234 Some commit", hash);++ let empty: HashSet<String> = HashSet::new();+ let (output, hashes) = process_log_with_dimming(&input, Some(&empty));++ assert_eq!(hashes.len(), 1);+ let parsed = parse_dimming_output(&output);+ assert_eq!(parsed.len(), 1);+ assert!(+ parsed[0].0,+ "Some(empty) means feature branch with no unique commits, all dim"+ );+ }++ #[test]+ fn test_process_log_with_dimming_preserves_graph_lines() {+ let hash = "abc123456789012345678901234567890123456789";+ // Git graph can have continuation lines between commits+ let input = format!(+ "* \x01{}\x00abc1234 First\n\+ |\n\+ * \x01{}\x00def1234 Second",+ hash, "def123456789012345678901234567890123456789"+ );++ let unique = HashSet::from([hash.to_string()]);+ let (output, _hashes) = process_log_with_dimming(&input, Some(&unique));++ // Graph-only line should be preserved unchanged+ assert!(output.contains("\n|\n"), "graph line should be preserved");+ }++ #[test]+ fn test_process_log_with_dimming_sha256_compatible() {+ // SHA-256 hashes are 64 characters (not 40)+ let sha256_hash = "abc1234567890123456789012345678901234567890123456789012345678901";+ assert_eq!(sha256_hash.len(), 64);++ let input = format!("* \x01{}\x00abc1234 SHA-256 repo", sha256_hash);++ let unique = HashSet::from([sha256_hash.to_string()]);+ let (output, hashes) = process_log_with_dimming(&input, Some(&unique));++ assert_eq!(hashes[0], sha256_hash);+ let parsed = parse_dimming_output(&output);+ assert!(!parsed[0].0, "SHA-256 hash should be matched correctly");+ assert!(parsed[0].1.contains("SHA-256 repo"));+ }++ #[test]+ fn test_process_log_with_dimming_strips_ansi_when_dimming() {+ let hash = "abc123456789012345678901234567890123456789";+ // Simulate colored git output+ let input = format!(+ "* \x01{}\x00\x1b[33mabc1234\x1b[m\x1b[33m (HEAD)\x1b[m message",+ hash+ );++ // Use a different hash to trigger dimming+ let other_unique = HashSet::from(["other".to_string()]);+ let (output, _hashes) = process_log_with_dimming(&input, Some(&other_unique));++ // Dimmed output should have colors stripped+ let parsed = parse_dimming_output(&output);+ assert!(parsed[0].0, "should be dimmed");+ // The ansi_strip should have removed the color codes+ assert!(parsed[0].1.contains("abc1234"));+ assert!(parsed[0].1.contains("(HEAD)"));+ }++ // Tests for strip_hash_markers++ #[test]+ fn test_strip_hash_markers_removes_soh_nul_block() {+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let input = format!("* \x01{}\x00abc1234 message", full_hash);+ let output = strip_hash_markers(&input);++ assert!(!output.contains('\x01'));+ assert!(!output.contains('\x00'));+ assert_eq!(output, "* abc1234 message");+ }++ #[test]+ fn test_strip_hash_markers_preserves_other_content() {+ // No markers - content unchanged+ let input = "* abc1234 (HEAD -> main) Initial commit";+ let output = strip_hash_markers(input);+ assert_eq!(output, input);+ }++ #[test]+ fn test_strip_hash_markers_handles_multiple_markers() {+ let input = "line1 \x01hash1\x00 content1\nline2 \x01hash2\x00 content2";+ let output = strip_hash_markers(input);+ assert_eq!(output, "line1 content1\nline2 content2");+ }++ // Tests for extract_hash_from_line++ #[test]+ fn test_extract_hash_from_line_finds_hash() {+ let full_hash = "abc1234567890123456789012345678901234567ab";+ let line = format!("* \x01{}\x00abc1234 message", full_hash);+ let extracted = extract_hash_from_line(&line);+ assert_eq!(extracted, Some(full_hash));+ }++ #[test]+ fn test_extract_hash_from_line_sha256() {+ let sha256_hash = "abc1234567890123456789012345678901234567890123456789012345678901";+ let line = format!("* \x01{}\x00abc1234 message", sha256_hash);+ let extracted = extract_hash_from_line(&line);+ assert_eq!(extracted, Some(sha256_hash));+ }++ #[test]+ fn test_extract_hash_from_line_no_markers() {+ let line = "* abc1234 message";+ let extracted = extract_hash_from_line(line);+ assert_eq!(extracted, None);+ }++ #[test]+ fn test_extract_hash_from_line_incomplete_markers() {+ // Only SOH, no NUL+ let line = "* \x01abc1234 message";+ let extracted = extract_hash_from_line(line);+ assert_eq!(extracted, None);+ }+}diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rsnew file mode 100644index 000000000..caf2e55c8--- /dev/null+++ b/src/commands/select/mod.rs@@ -0,0 +1,273 @@+//! Interactive branch/worktree selector.+//!+//! A skim-based TUI for selecting and switching between worktrees.++mod items;+mod log_formatter;+mod pager;+mod preview;++use std::sync::Arc;++use anyhow::Context;+use skim::prelude::*;+use worktrunk::config::WorktrunkConfig;+use worktrunk::git::Repository;++use super::list::collect;+use super::worktree::{execute_switch, plan_switch};+use crate::output::handle_switch_output;++use items::{HeaderSkimItem, WorktreeSkimItem};+use preview::{PreviewLayout, PreviewState};++pub fn handle_select(+ show_branches: bool,+ show_remotes: bool,+ config: &WorktrunkConfig,+) -> anyhow::Result<()> {+ use std::io::IsTerminal;++ // Select requires an interactive terminal for the TUI+ if !std::io::stdin().is_terminal() {+ anyhow::bail!("wt select requires an interactive terminal");+ }++ let repo = Repository::current()?;++ // Initialize preview mode state file (auto-cleanup on drop)+ let state = PreviewState::new();++ // Gather list data using simplified collection (buffered mode)+ // Skip expensive operations not needed for select UI+ let skip_tasks = [+ collect::TaskKind::BranchDiff,+ collect::TaskKind::CiStatus,+ collect::TaskKind::MergeTreeConflicts,+ ]+ .into_iter()+ .collect();++ // Use 500ms timeout for git commands to show TUI faster on large repos.+ // Typical slow operations: merge-tree ~400-1800ms, rev-list ~200-600ms.+ // 500ms allows most operations to complete while cutting off tail latency.+ // Operations that timeout fail silently (data not shown), but TUI stays responsive.+ let command_timeout = Some(std::time::Duration::from_millis(500));++ let Some(list_data) = collect::collect(+ &repo,+ show_branches,+ show_remotes,+ &skip_tasks,+ false, // show_progress (no progress bars)+ false, // render_table (select renders its own UI)+ config,+ command_timeout,+ true, // skip_expensive_for_stale (faster for repos with many stale branches)+ )?+ else {+ return Ok(());+ };++ // Use the same layout system as `wt list` for proper column alignment+ // List width depends on preview position:+ // - Right layout: skim splits ~50% for list, ~50% for preview+ // - Down layout: list gets full width, preview is below+ let terminal_width = crate::display::get_terminal_width();+ let skim_list_width = match state.initial_layout {+ PreviewLayout::Right => terminal_width / 2,+ PreviewLayout::Down => terminal_width,+ };+ let layout = super::list::layout::calculate_layout_with_width(+ &list_data.items,+ &skip_tasks,+ skim_list_width,+ &list_data.main_worktree_path,+ None, // URL column not shown in select+ );++ // Render header using layout system (need both plain and styled text for skim)+ let header_line = layout.render_header_line();+ let header_display_text = header_line.render();+ let header_plain_text = header_line.plain_text();++ // Convert to skim items using the layout system for rendering+ let mut items: Vec<Arc<dyn SkimItem>> = list_data+ .items+ .into_iter()+ .map(|item| {+ let branch_name = item.branch_name().to_string();++ // Use layout system to render the line - this handles all column alignment+ let rendered_line = layout.render_list_item_line(&item);+ let display_text_with_ansi = rendered_line.render();+ let display_text = rendered_line.plain_text();++ Arc::new(WorktreeSkimItem {+ display_text,+ display_text_with_ansi,+ branch_name,+ item: Arc::new(item),+ }) as Arc<dyn SkimItem>+ })+ .collect();++ // Insert header row at the beginning (will be non-selectable via header_lines option)+ items.insert(+ 0,+ Arc::new(HeaderSkimItem {+ display_text: header_plain_text,+ display_text_with_ansi: header_display_text,+ }) as Arc<dyn SkimItem>,+ );++ // Get state path for key bindings (shell-escaped for safety)+ let state_path_display = state.path.display().to_string();+ let state_path_str = shlex::try_quote(&state_path_display)+ .map(|s| s.into_owned())+ .unwrap_or(state_path_display);++ // Calculate half-page scroll: skim uses 90% of terminal height, half of that = 45%+ let half_page = terminal_size::terminal_size()+ .map(|(_, terminal_size::Height(h))| (h as usize * 45 / 100).max(5))+ .unwrap_or(10);++ // Calculate preview window spec based on auto-detected layout+ // items.len() - 1 because we added a header row+ let num_items = items.len().saturating_sub(1);+ let preview_window_spec = state.initial_layout.to_preview_window_spec(num_items);++ // Configure skim options with Rust-based preview and mode switching keybindings+ let options = SkimOptionsBuilder::default()+ .height("90%".to_string())+ .layout("reverse".to_string())+ .header_lines(1) // Make first line (header) non-selectable+ .multi(false)+ .no_info(true) // Hide info line (matched/total counter)+ .preview(Some("".to_string())) // Enable preview (empty string means use SkimItem::preview())+ .preview_window(preview_window_spec)+ // Color scheme using fzf's --color=light values: dark text (237) on light gray bg (251)+ //+ // Terminal color compatibility is tricky:+ // - current_bg:254 (original): too bright on dark terminals, washes out text+ // - current_bg:236 (fzf dark): too dark on light terminals, jarring contrast+ // - current_bg:251 + current:-1: light bg works on both, but unstyled text+ // becomes unreadable on dark terminals (light-on-light)+ // - current_bg:251 + current:237: fzf's light theme, best compromise+ //+ // The light theme works universally because:+ // - On dark terminals: light gray highlight stands out clearly+ // - On light terminals: light gray is subtle but visible+ // - Dark text (237) ensures readability regardless of terminal theme+ .color(Some(+ "fg:-1,bg:-1,header:-1,matched:108,current:237,current_bg:251,current_match:108"+ .to_string(),+ ))+ .bind(vec![+ // Mode switching (1/2/3/4 keys change preview content)+ format!(+ "1:execute-silent(echo 1 > {0})+refresh-preview",+ state_path_str+ ),+ format!(+ "2:execute-silent(echo 2 > {0})+refresh-preview",+ state_path_str+ ),+ format!(+ "3:execute-silent(echo 3 > {0})+refresh-preview",+ state_path_str+ ),+ format!(+ "4:execute-silent(echo 4 > {0})+refresh-preview",+ state_path_str+ ),+ // Preview toggle (alt-p shows/hides preview)+ // Note: skim doesn't support change-preview-window like fzf, only toggle+ "alt-p:toggle-preview".to_string(),+ // Preview scrolling (half-page based on terminal height)+ format!("ctrl-u:preview-up({half_page})"),+ format!("ctrl-d:preview-down({half_page})"),+ ])+ // Legend/controls moved to preview window tabs (render_preview_tabs)+ .no_clear(true) // Prevent skim from clearing screen, we'll do it manually+ .build()+ .map_err(|e| anyhow::anyhow!("Failed to build skim options: {}", e))?;++ // Create item receiver+ let (tx, rx): (SkimItemSender, SkimItemReceiver) = unbounded();+ for item in items {+ tx.send(item)+ .map_err(|e| anyhow::anyhow!("Failed to send item to skim: {}", e))?;+ }+ drop(tx);++ // Run skim+ let output = Skim::run_with(&options, Some(rx));++ // Handle selection+ if let Some(out) = output+ && !out.is_abort+ && let Some(selected) = out.selected_items.first()+ {+ // Get branch name or worktree path from selected item+ // (output() returns the worktree path for existing worktrees, branch name otherwise)+ let identifier = selected.output().to_string();++ // Load config+ let config = WorktrunkConfig::load().context("Failed to load config")?;+ let repo = Repository::current().context("Failed to switch worktree")?;++ // Switch to the selected worktree (no creation, no approval prompts)+ let plan = plan_switch(&repo, &identifier, false, None, false, &config)?;+ let (result, branch_info) = execute_switch(&repo, plan, &config, false, true)?;++ // Clear the terminal screen after skim exits to prevent artifacts+ // Use stderr for terminal control - stdout is reserved for data output+ use crossterm::{execute, terminal};+ use std::io::stderr;+ execute!(stderr(), terminal::Clear(terminal::ClearType::All))?;+ execute!(stderr(), crossterm::cursor::MoveTo(0, 0))?;++ // Show success message; emit cd directive if shell integration is active+ handle_switch_output(&result, &branch_info, None)?;+ }++ Ok(())+}++#[cfg(test)]+pub mod tests {+ use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};+ use std::fs;++ #[test]+ fn test_preview_state_data_roundtrip() {+ let state_path = PreviewStateData::state_path();++ // Write and read back various modes+ let _ = fs::write(&state_path, "1");+ assert_eq!(PreviewStateData::read_mode(), PreviewMode::WorkingTree);++ let _ = fs::write(&state_path, "2");+ assert_eq!(PreviewStateData::read_mode(), PreviewMode::Log);++ let _ = fs::write(&state_path, "3");+ assert_eq!(PreviewStateData::read_mode(), PreviewMode::BranchDiff);++ let _ = fs::write(&state_path, "4");+ assert_eq!(PreviewStateData::read_mode(), PreviewMode::UpstreamDiff);++ // Cleanup+ let _ = fs::remove_file(&state_path);+ }++ #[test]+ fn test_preview_layout() {+ // Right is always 50%+ assert_eq!(PreviewLayout::Right.to_preview_window_spec(10), "right:50%");++ // Down calculates based on item count+ let spec = PreviewLayout::Down.to_preview_window_spec(5);+ assert!(spec.starts_with("down:"));+ }+}diff --git a/src/commands/select/pager.rs b/src/commands/select/pager.rsnew file mode 100644index 000000000..d1ae86319--- /dev/null+++ b/src/commands/select/pager.rs@@ -0,0 +1,221 @@+//! Pager detection and execution.+//!+//! Handles detection and use of diff pagers (delta, bat, etc.) for preview windows.++use std::process::{Command, Stdio};+use std::sync::OnceLock;+use std::time::{Duration, Instant};++use worktrunk::config::WorktrunkConfig;+use worktrunk::shell::extract_filename_from_path;++use crate::pager::{git_config_pager, parse_pager_value};++/// Cached pager command, detected once at startup.+///+/// None means no pager should be used (empty config or "cat").+/// We cache this to avoid running `git config` on every preview render.+pub(super) static CACHED_PAGER: OnceLock<Option<String>> = OnceLock::new();++/// Maximum time to wait for pager to complete.+///+/// Pager blocking can freeze skim's event loop, making the UI unresponsive.+/// If the pager takes longer than this, kill it and fall back to raw diff.+pub(super) const PAGER_TIMEOUT: Duration = Duration::from_millis(2000);++/// Get the cached pager command, initializing if needed.+///+/// Precedence (highest to lowest):+/// 1. `[select] pager` in user config (explicit override, used as-is)+/// 2. `GIT_PAGER` environment variable (with auto-detection applied)+/// 3. `core.pager` git config (with auto-detection applied)+pub(super) fn get_diff_pager() -> Option<&'static String> {+ CACHED_PAGER+ .get_or_init(|| {+ // Check user config first for explicit pager override+ // When set, use exactly as specified (no auto-detection)+ if let Ok(config) = WorktrunkConfig::load()+ && let Some(select_config) = config.select+ && let Some(pager) = select_config.pager+ && !pager.trim().is_empty()+ {+ return Some(pager);+ }++ // GIT_PAGER takes precedence over core.pager+ if let Ok(pager) = std::env::var("GIT_PAGER") {+ return parse_pager_value(&pager);+ }++ // Fall back to core.pager config+ git_config_pager()+ })+ .as_ref()+}++/// Check if the pager spawns its own internal pager (e.g., less).+///+/// Some pagers like delta and bat spawn `less` by default, which hangs in+/// non-TTY contexts like skim's preview panel. These need `--paging=never`.+///+/// Used only when user hasn't set `[select] pager` config explicitly.+/// When config is set, that value is used as-is without modification.+pub(super) fn pager_needs_paging_disabled(pager_cmd: &str) -> bool {+ // Split on whitespace to get the command name, then extract basename+ // Uses extract_filename_from_path for consistent handling of Windows paths and .exe+ pager_cmd+ .split_whitespace()+ .next()+ .and_then(extract_filename_from_path)+ // bat is called "batcat" on Debian/Ubuntu+ // Case-insensitive for Windows where commands might be Delta.exe, BAT.EXE, etc.+ .is_some_and(|basename| {+ basename.eq_ignore_ascii_case("delta")+ || basename.eq_ignore_ascii_case("bat")+ || basename.eq_ignore_ascii_case("batcat")+ })+}++/// Check if user has explicitly configured a select-specific pager.+pub(super) fn has_explicit_pager_config() -> bool {+ WorktrunkConfig::load()+ .ok()+ .and_then(|config| config.select)+ .and_then(|select| select.pager)+ .is_some_and(|p| !p.trim().is_empty())+}++/// Run git diff piped directly through the pager as a streaming pipeline.+///+/// Runs `git <args> | pager` as a single shell command, avoiding intermediate+/// buffering. Returns None if pipeline fails or times out (caller should fall back to raw diff).+///+/// When `[select] pager` is not configured, automatically appends `--paging=never` for+/// delta/bat/batcat pagers to prevent hangs. To override this behavior, set an explicit+/// pager command in config: `[select] pager = "delta"` (or with custom flags).+pub(super) fn run_git_diff_with_pager(git_args: &[&str], pager_cmd: &str) -> Option<String> {+ // Note: pager_cmd is expected to be valid shell code (like git's core.pager).+ // Users with paths containing special chars must quote them in their config.++ // Apply auto-detection only when user hasn't set explicit config+ // If config is set, use the value as-is (user has full control)+ let pager_with_args = if !has_explicit_pager_config() && pager_needs_paging_disabled(pager_cmd)+ {+ format!("{} --paging=never", pager_cmd)+ } else {+ pager_cmd.to_string()+ };++ // Build shell pipeline: git <args> | pager+ // Shell-escape args to handle paths with spaces+ let escaped_args: Vec<String> = git_args+ .iter()+ .map(|arg| shlex::try_quote(arg).unwrap_or((*arg).into()).into_owned())+ .collect();+ let pipeline = format!("git {} | {}", escaped_args.join(" "), pager_with_args);++ log::debug!("Running pager pipeline: {}", pipeline);++ // Spawn pipeline+ let mut child = match Command::new("sh")+ .arg("-c")+ .arg(&pipeline)+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ // Prevent subprocesses from writing to the directive file+ .env_remove(worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR)+ .spawn()+ {+ Ok(child) => child,+ Err(e) => {+ log::debug!("Failed to spawn pager pipeline: {}", e);+ return None;+ }+ };++ // Read output in a thread to avoid blocking+ let stdout = child.stdout.take()?;+ let reader_thread = std::thread::spawn(move || {+ use std::io::Read;+ let mut stdout = stdout;+ let mut output = Vec::new();+ let _ = stdout.read_to_end(&mut output);+ output+ });++ // Wait for pipeline with timeout+ let start = Instant::now();+ loop {+ match child.try_wait() {+ Ok(Some(status)) => {+ let output = reader_thread.join().ok()?;+ if status.success() {+ return String::from_utf8(output).ok();+ } else {+ log::debug!("Pager pipeline exited with status: {}", status);+ return None;+ }+ }+ Ok(None) => {+ if start.elapsed() > PAGER_TIMEOUT {+ log::debug!("Pager pipeline timed out after {:?}", PAGER_TIMEOUT);+ let _ = child.kill();+ return None;+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ Err(e) => {+ log::debug!("Failed to wait for pager pipeline: {}", e);+ let _ = child.kill();+ return None;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_pager_needs_paging_disabled() {+ // delta - plain command name+ assert!(pager_needs_paging_disabled("delta"));+ // delta - with arguments+ assert!(pager_needs_paging_disabled("delta --side-by-side"));+ assert!(pager_needs_paging_disabled("delta --paging=always"));+ // delta - full path+ assert!(pager_needs_paging_disabled("/usr/bin/delta"));+ assert!(pager_needs_paging_disabled(+ "/opt/homebrew/bin/delta --line-numbers"+ ));+ // bat - also spawns less by default+ assert!(pager_needs_paging_disabled("bat"));+ assert!(pager_needs_paging_disabled("/usr/bin/bat"));+ assert!(pager_needs_paging_disabled("bat --style=plain"));+ // Pagers that don't spawn sub-pagers+ assert!(!pager_needs_paging_disabled("less"));+ assert!(!pager_needs_paging_disabled("diff-so-fancy"));+ assert!(!pager_needs_paging_disabled("colordiff"));+ // Edge cases - similar names but not delta/bat+ assert!(!pager_needs_paging_disabled("delta-preview"));+ assert!(!pager_needs_paging_disabled("/path/to/delta-preview"));+ assert!(pager_needs_paging_disabled("batcat")); // Debian's bat package name++ // Case-insensitive matching (Windows command names)+ assert!(pager_needs_paging_disabled("Delta"));+ assert!(pager_needs_paging_disabled("DELTA"));+ assert!(pager_needs_paging_disabled("BAT"));+ assert!(pager_needs_paging_disabled("Bat"));+ assert!(pager_needs_paging_disabled("BatCat"));+ assert!(pager_needs_paging_disabled("delta.exe"));+ assert!(pager_needs_paging_disabled("Delta.EXE"));+ }++ #[test]+ fn test_has_explicit_pager_config() {+ // This function loads real config, so we just test that it doesn't panic+ // The behavior is covered by integration tests that set actual config+ let _ = has_explicit_pager_config();+ }+}diff --git a/src/commands/select/preview.rs b/src/commands/select/preview.rsnew file mode 100644index 000000000..561a2b17d--- /dev/null+++ b/src/commands/select/preview.rs@@ -0,0 +1,254 @@+//! Preview mode and layout management.+//!+//! Handles preview state persistence and layout auto-detection for the interactive selector.++use std::fs;+use std::path::PathBuf;++/// Preview modes for the interactive selector+///+/// Each mode shows a different aspect of the worktree:+/// 1. WorkingTree: Uncommitted changes (git diff HEAD --stat)+/// 2. Log: Commit history since diverging from the default branch (git log with merge-base)+/// 3. BranchDiff: Line diffs since the merge-base with the default branch (git diff --stat DEFAULT…)+/// 4. UpstreamDiff: Diff vs upstream tracking branch (ahead/behind)+///+/// Loosely aligned with `wt list` columns, though not a perfect match:+/// - Tab 1 corresponds to "HEAD±" column+/// - Tab 2 shows commits (related to "main↕" counts)+/// - Tab 3 corresponds to "main…± (--full)" column+/// - Tab 4 corresponds to "Remote⇅" column+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum PreviewMode {+ WorkingTree = 1,+ Log = 2,+ BranchDiff = 3,+ UpstreamDiff = 4,+}++impl PreviewMode {+ pub(super) fn from_u8(n: u8) -> Self {+ match n {+ 2 => Self::Log,+ 3 => Self::BranchDiff,+ 4 => Self::UpstreamDiff,+ _ => Self::WorkingTree,+ }+ }+}++/// Typical terminal character aspect ratio (width/height).+///+/// Terminal characters are taller than wide - typically around 0.5 (twice as tall as wide).+/// This varies by font, but 0.5 is a reasonable default for monospace fonts.+const CHAR_ASPECT_RATIO: f64 = 0.5;++/// Skim uses this percentage of terminal height.+pub(super) const SKIM_HEIGHT_PERCENT: usize = 90;++/// Maximum number of list items visible in down layout before scrolling.+pub(super) const MAX_VISIBLE_ITEMS: usize = 12;++/// Lines reserved for skim chrome (header + prompt/margins).+pub(super) const LIST_CHROME_LINES: usize = 4;++/// Minimum preview lines to keep usable even with many items.+pub(super) const MIN_PREVIEW_LINES: usize = 5;++/// Preview layout orientation for the interactive selector+///+/// Preview window position (auto-detected at startup based on terminal dimensions)+///+/// - Right: Preview on the right side (50% width) - better for wide terminals+/// - Down: Preview below the list - better for tall/vertical monitors+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub(super) enum PreviewLayout {+ #[default]+ Right,+ Down,+}++impl PreviewLayout {+ /// Auto-detect layout based on terminal dimensions.+ ///+ /// Terminal dimensions are in characters, not pixels. Since characters are+ /// typically twice as tall as wide (~0.5 aspect ratio), we correct for this+ /// when calculating the effective aspect ratio.+ ///+ /// Example: 180 cols × 136 rows+ /// - Raw ratio: 180/136 = 1.32 (appears landscape)+ /// - Effective: 1.32 × 0.5 = 0.66 (actually portrait!)+ ///+ /// Returns Down for portrait (effective ratio < 1.0), Right for landscape.+ pub(super) fn auto_detect() -> Self {+ let (cols, rows) = terminal_size::terminal_size()+ .map(|(terminal_size::Width(w), terminal_size::Height(h))| (w as f64, h as f64))+ .unwrap_or((80.0, 24.0));++ // Effective aspect ratio accounting for character shape+ let effective_ratio = (cols / rows) * CHAR_ASPECT_RATIO;++ if effective_ratio < 1.0 {+ Self::Down+ } else {+ Self::Right+ }+ }++ /// Calculate the preview window spec for skim+ ///+ /// For Right layout: always 50%+ /// For Down layout: dynamically sized based on item count - list gets+ /// up to MAX_VISIBLE_ITEMS lines, preview gets the rest (min 5 lines)+ pub(super) fn to_preview_window_spec(self, num_items: usize) -> String {+ match self {+ Self::Right => "right:50%".to_string(),+ Self::Down => {+ let height = terminal_size::terminal_size()+ .map(|(_, terminal_size::Height(h))| h as usize)+ .unwrap_or(24);++ let available = height * SKIM_HEIGHT_PERCENT / 100;+ let list_lines = LIST_CHROME_LINES + num_items.min(MAX_VISIBLE_ITEMS);+ // Ensure preview doesn't exceed available space while trying to maintain minimum+ let remaining = available.saturating_sub(list_lines);+ let preview_lines = remaining.max(MIN_PREVIEW_LINES).min(available);++ format!("down:{}", preview_lines)+ }+ }+ }+}++/// Preview state persistence (mode only, layout auto-detected)+///+/// State file format: Single digit representing preview mode (1-4)+pub(super) struct PreviewStateData;++impl PreviewStateData {+ pub(super) fn state_path() -> PathBuf {+ // Use per-process temp file to avoid race conditions when running multiple instances+ std::env::temp_dir().join(format!("wt-select-state-{}", std::process::id()))+ }++ /// Read current preview mode from state file+ pub(super) fn read_mode() -> PreviewMode {+ let state_path = Self::state_path();+ fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree)+ }++ pub(super) fn write_mode(mode: PreviewMode) {+ let state_path = Self::state_path();+ let _ = fs::write(&state_path, format!("{}", mode as u8));+ }+}++/// RAII wrapper for preview state file lifecycle management+pub(super) struct PreviewState {+ pub(super) path: PathBuf,+ pub(super) initial_layout: PreviewLayout,+}++impl PreviewState {+ pub(super) fn new() -> Self {+ let path = PreviewStateData::state_path();+ PreviewStateData::write_mode(PreviewMode::WorkingTree);+ Self {+ path,+ initial_layout: PreviewLayout::auto_detect(),+ }+ }+}++impl Drop for PreviewState {+ fn drop(&mut self) {+ let _ = fs::remove_file(&self.path);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_preview_mode_from_u8() {+ assert_eq!(PreviewMode::from_u8(1), PreviewMode::WorkingTree);+ assert_eq!(PreviewMode::from_u8(2), PreviewMode::Log);+ assert_eq!(PreviewMode::from_u8(3), PreviewMode::BranchDiff);+ assert_eq!(PreviewMode::from_u8(4), PreviewMode::UpstreamDiff);+ // Invalid values default to WorkingTree+ assert_eq!(PreviewMode::from_u8(0), PreviewMode::WorkingTree);+ assert_eq!(PreviewMode::from_u8(99), PreviewMode::WorkingTree);+ }++ #[test]+ fn test_preview_layout_to_preview_window_spec() {+ // Right is always 50%+ assert_eq!(PreviewLayout::Right.to_preview_window_spec(10), "right:50%");++ // Down calculates based on item count+ let spec = PreviewLayout::Down.to_preview_window_spec(5);+ assert!(spec.starts_with("down:"));+ }++ #[test]+ fn test_preview_state_data_read_default() {+ // Use unique path to avoid interference from parallel tests+ let state_path = std::env::temp_dir().join("wt-test-read-default");+ let _ = fs::remove_file(&state_path);++ // When state file doesn't exist, read returns default+ let mode = fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree);+ assert_eq!(mode, PreviewMode::WorkingTree);+ }++ #[test]+ fn test_preview_state_data_roundtrip() {+ // Use unique path to avoid interference from parallel tests+ let state_path = std::env::temp_dir().join("wt-test-roundtrip");++ // Write and read back various modes+ let _ = fs::write(&state_path, "1");+ let mode = fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree);+ assert_eq!(mode, PreviewMode::WorkingTree);++ let _ = fs::write(&state_path, "2");+ let mode = fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree);+ assert_eq!(mode, PreviewMode::Log);++ let _ = fs::write(&state_path, "3");+ let mode = fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree);+ assert_eq!(mode, PreviewMode::BranchDiff);++ let _ = fs::write(&state_path, "4");+ let mode = fs::read_to_string(&state_path)+ .ok()+ .and_then(|s| s.trim().parse::<u8>().ok())+ .map(PreviewMode::from_u8)+ .unwrap_or(PreviewMode::WorkingTree);+ assert_eq!(mode, PreviewMode::UpstreamDiff);++ // Cleanup+ let _ = fs::remove_file(&state_path);+ }+}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsdeleted file mode 100644index ffba03e55..000000000--- a/src/commands/worktree.rs+++ /dev/null@@ -1,1632 +0,0 @@-//! Worktree operations with file-based shell integration.-//!-//! # The Directory Change Problem-//!-//! Worktree commands (`switch`, `remove`, `merge`) need to change the user's working directory,-//! but there's a fundamental Unix limitation: **child processes cannot change their parent's-//! working directory**. This is a security feature and core Unix design principle.-//!-//! When a user runs `wt switch my-feature`, the `wt` binary runs as a child process of the shell.-//! The binary can change *its own* working directory, but when it exits, the parent shell remains-//! in the original directory.-//!-//! # Solution: File-Based Directive Passing-//!-//! Shell wrappers create a temp file and set `WORKTRUNK_DIRECTIVE_FILE` to its path:-//!-//! 1. Shell wrapper creates temp file via `mktemp`-//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_FILE=/path/to/temp`-//! 3. wt binary writes commands like `cd '/path'` to that file-//! 4. Shell wrapper sources the file after wt exits-//!-//! ## Without Shell Integration (Direct Binary Call)-//!-//! ```bash-//! $ wt switch my-feature-//! Created new branch and worktree for 'my-feature' @ /path/to/worktree-//!-//! Run `wt config shell install` to enable automatic cd-//!-//! $ pwd-//! /original/directory # ← User is still here!-//! ```-//!-//! The binary performs git operations and prints user-friendly messages, but **cannot** change-//! the parent shell's directory. User must manually `cd` to the worktree.-//!-//! ## With Shell Integration-//!-//! ```bash-//! $ wt switch my-feature-//! Created new branch and worktree for 'my-feature' @ /path/to/worktree-//!-//! $ pwd-//! /path/to/worktree # ← Automatically changed!-//! ```-//!-//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell wrapper:-//!-//! 1. Creates a temp file and sets `WORKTRUNK_DIRECTIVE_FILE` to its path-//! 2. Runs the wt binary (which writes `cd '/path'` to the temp file)-//! 3. Sources the temp file after wt exits-//!-//! # Implementation Details-//!-//! Result types (`SwitchResult`, `RemoveResult`) are pure data structures that only contain-//! operation results. All presentation logic is handled by the `output` module:-//!-//! - `output::handle_switch_output()`: Formats and outputs switch operation results-//! - `output::handle_remove_output()`: Formats and outputs remove operation results-//!-//! The output handlers check `is_shell_integration_active()` to determine if hints should-//! be suppressed (when shell integration is already configured).-//!-//! ## Exit Code Semantics-//!-//! When using `-x` to execute commands after switching:-//!-//! - **If wt operation fails**: Returns wt's exit code (command never executes)-//! - **If wt succeeds but command fails**: Returns the command's exit code-//! - **Rationale**: Enables command chaining with proper error propagation-//!-//! Example:-//! ```bash-//! wt switch feature -x "cargo build" && cargo test-//! # If wt fails (e.g., worktree doesn't exist), cargo build never runs-//! # If cargo build fails, cargo test doesn't run (exit code propagates)-//! ```-//!-//! The shell wrapper is generated by `wt config shell init <shell>` from templates in `templates/`.--use anyhow::Context;-use color_print::cformat;-use dunce::canonicalize;-use normalize_path::NormalizePath;-use std::path::{Path, PathBuf};-use worktrunk::HookType;-use worktrunk::config::WorktrunkConfig;-use worktrunk::git::{GitError, Repository, ResolvedWorktree};-use worktrunk::styling::{- format_with_gutter, hint_message, info_message, progress_message, success_message,- suggest_command, warning_message,-};--use super::command_executor::CommandContext;-use super::hooks::{HookFailureStrategy, prepare_hook_commands, spawn_hook_commands_background};-use super::repository_ext::{RemoveTarget, RepositoryCliExt};--/// Generate a backup path for the given path with a timestamp suffix.-///-/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP`-/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP`-///-/// Returns an error for unusual paths without a file name (e.g., `/` or `..`).-fn generate_backup_path(path: &std::path::Path, suffix: &str) -> anyhow::Result<PathBuf> {- let file_name = path- .file_name()- .ok_or_else(|| anyhow::anyhow!("Cannot generate backup path for {}", path.display()))?;-- if path.extension().is_none() {- // Path has no extension (e.g., /repo/feature)- Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy())))- } else {- // Path has an extension (e.g., /repo.feature or /file.txt)- Ok(path.with_extension(format!(- "{}.bak.{suffix}",- path.extension()- .map(|e| e.to_string_lossy().to_string())- .unwrap_or_default()- )))- }-}--/// Compute the backup path for clobber operations.-///-/// Returns `Ok(None)` if path doesn't exist.-/// Returns `Ok(Some(backup_path))` if clobber is true and path exists.-/// Returns `Err(GitError::WorktreePathExists)` if clobber is false and path exists.-fn compute_clobber_backup(- path: &Path,- branch: &str,- clobber: bool,- create: bool,-) -> anyhow::Result<Option<PathBuf>> {- if !path.exists() {- return Ok(None);- }-- if clobber {- let timestamp = worktrunk::utils::get_now() as i64;- let datetime =- chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);- let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();- let backup_path = generate_backup_path(path, &suffix)?;-- if backup_path.exists() {- anyhow::bail!(- "Backup path already exists: {}",- worktrunk::path::format_path_for_display(&backup_path)- );- }- Ok(Some(backup_path))- } else {- Err(GitError::WorktreePathExists {- branch: branch.to_string(),- path: path.to_path_buf(),- create,- }- .into())- }-}--/// Context for worktree resolution - determines which checks are performed.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum ResolutionContext {- /// Creating or switching to a worktree - path occupation is an error- /// because we need to create a worktree at the expected path.- CreateOrSwitch,- /// Removing a worktree - we only care if the branch has a worktree,- /// path occupation is irrelevant since we're not creating anything.- Remove,-}--/// Resolve a worktree argument using branch-first lookup.-///-/// Resolution order:-/// 1. Special symbols ("@", "-", "^") are handled specially-/// 2. Resolve argument as branch name-/// 3. If branch has a worktree, return it-/// 4. Otherwise, return branch-only (no worktree)-///-/// For `CreateOrSwitch` context: If the branch has no worktree but expected-/// path is occupied by another branch's worktree, an error is raised.-///-/// For `Remove` context: Path occupation is ignored since we're not creating-/// a worktree - we just return `BranchOnly` if no worktree exists.-pub fn resolve_worktree_arg(- repo: &Repository,- name: &str,- config: &WorktrunkConfig,- context: ResolutionContext,-) -> anyhow::Result<ResolvedWorktree> {- // Special symbols - delegate to Repository for consistent error handling- match name {- "@" | "-" | "^" => {- return repo.resolve_worktree(name);- }- _ => {}- }-- // Resolve as branch name- let branch = repo.resolve_worktree_name(name)?;-- // Branch-first: check if branch has worktree anywhere- if let Some(path) = repo.worktree_for_branch(&branch)? {- return Ok(ResolvedWorktree::Worktree {- path,- branch: Some(branch),- });- }-- // No worktree for branch - check if expected path is occupied (only for create/switch)- if context == ResolutionContext::CreateOrSwitch {- let expected_path = compute_worktree_path(repo, name, config)?;- if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {- // Path is occupied by a different branch's worktree- return Err(GitError::WorktreePathOccupied {- branch,- path: expected_path,- occupant: occupant_branch,- }- .into());- }- }-- // No worktree for branch (and path not occupied, or we don't care about path)- Ok(ResolvedWorktree::BranchOnly { branch })-}--/// Compute the expected worktree path for a branch name.-///-/// For the default branch, returns the repo root (main worktree location).-/// For other branches, applies the `worktree-path` template from config.-///-/// Uses cached values from Repository for `default_branch` and `is_bare`.-pub fn compute_worktree_path(- repo: &Repository,- branch: &str,- config: &WorktrunkConfig,-) -> anyhow::Result<PathBuf> {- let repo_root = repo.repo_path()?;- let default_branch = repo.default_branch().unwrap_or_default();- let is_bare = repo.is_bare()?;-- // Default branch lives at repo root (main worktree), not a templated path.- // Exception: bare repos have no main worktree, so all branches use templated paths.- if !is_bare && branch == default_branch {- return Ok(repo_root);- }-- let repo_name = repo_root- .file_name()- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?- .to_str()- .ok_or_else(|| {- anyhow::anyhow!(- "Repository path contains invalid UTF-8: {}",- repo_root.display()- )- })?;-- let relative_path = config- .format_path(repo_name, branch, repo)- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;-- Ok(repo_root.join(relative_path).normalize())-}--/// Check if a worktree is at its expected path based on config template.-///-/// Returns true if the worktree's actual path matches what `compute_worktree_path`-/// would generate for its branch. Detached HEAD always returns false (no expected path).-///-/// Uses canonicalization to handle symlinks and relative paths correctly.-/// Uses cached values from Repository for `default_branch` and `is_bare`.-pub fn is_worktree_at_expected_path(- wt: &worktrunk::git::WorktreeInfo,- repo: &Repository,- config: &WorktrunkConfig,-) -> bool {- match &wt.branch {- Some(branch) => compute_worktree_path(repo, branch, config)- .map(|expected| paths_match(&wt.path, &expected))- .unwrap_or(false),- None => false,- }-}--/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.-///-/// Returns `true` if the paths resolve to the same location.-fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {- use dunce::canonicalize;- let a_canonical = canonicalize(a).unwrap_or_else(|_| a.to_path_buf());- let b_canonical = canonicalize(b).unwrap_or_else(|_| b.to_path_buf());- a_canonical == b_canonical-}--/// Returns the expected path if `actual_path` differs from the template-computed path.-///-/// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.-/// Used to show path mismatch warnings in `wt remove` and `wt merge`.-pub fn get_path_mismatch(- repo: &Repository,- branch: &str,- actual_path: &std::path::Path,- config: &WorktrunkConfig,-) -> Option<PathBuf> {- compute_worktree_path(repo, branch, config)- .ok()- .filter(|expected| !paths_match(actual_path, expected))-}--/// Compute a user-facing display name for a worktree.-///-/// Returns styled content with branch names bolded:-/// - If branch is consistent with worktree location: just the branch name (bolded)-/// - If branch differs from expected location: `dir_name (on **branch**)` (both bolded)-/// - If detached HEAD: `dir_name (detached)` (dir_name bolded)-///-/// "Consistent" means the worktree path matches `compute_worktree_path(branch)`,-/// which returns repo root for default branch and templated path for others.-pub fn worktree_display_name(- wt: &worktrunk::git::WorktreeInfo,- repo: &Repository,- config: &WorktrunkConfig,-) -> String {- let dir_name = wt.dir_name();-- match &wt.branch {- Some(branch) => {- if is_worktree_at_expected_path(wt, repo, config) {- cformat!("<bold>{branch}</>")- } else {- cformat!("<bold>{dir_name}</> (on <bold>{branch}</>)")- }- }- None => cformat!("<bold>{dir_name}</> (detached)"),- }-}--/// Flags indicating which merge operations occurred-#[derive(Debug, Clone, Copy)]-pub struct MergeOperations {- pub committed: bool,- pub squashed: bool,- pub rebased: bool,-}--/// Result of a worktree switch operation-pub enum SwitchResult {- /// Already at the target worktree (no action taken)- AlreadyAt(PathBuf),- /// Switched to existing worktree at the given path- Existing(PathBuf),- /// Created new worktree at the given path- Created {- path: PathBuf,- /// True if we used `-b` to create a new branch (--create flag)- created_branch: bool,- /// Base branch when creating new branch (e.g., "main")- base_branch: Option<String>,- /// Absolute path to base branch's worktree (POSIX format for shell compatibility)- base_worktree_path: Option<String>,- /// Remote tracking branch if created from remote (e.g., "origin/feature")- /// This is set when git's DWIM created a local branch from a remote- from_remote: Option<String>,- },-}--impl SwitchResult {- /// Get the worktree path- pub fn path(&self) -> &PathBuf {- match self {- SwitchResult::AlreadyAt(path) => path,- SwitchResult::Existing(path) => path,- SwitchResult::Created { path, .. } => path,- }- }-}--/// Branch state for a switch operation.-#[derive(Debug, Clone)]-pub struct SwitchBranchInfo {- /// The branch being switched to- pub branch: String,- /// Expected path when there's a branch-worktree mismatch (None = path matches template)- pub expected_path: Option<PathBuf>,-}--/// How the worktree will be created.-#[derive(Debug)]-pub enum CreationMethod {- /// Use `git worktree add` - handles existing branch, DWIM from remote, or -b for new- Regular {- /// True if using `-b` to create a new branch (--create flag)- create_branch: bool,- /// Base branch for creation (resolved, validated to exist)- base_branch: Option<String>,- },- /// Fork PR: fetch from refs/pull/N/head, create branch, configure pushRemote- ForkPr {- pr_number: u32,- fork_push_url: String,- pr_url: String,- },-}--/// Validated plan for a switch operation.-///-/// Created by `plan_switch()`, consumed by `execute_switch()`.-/// This separation allows validation to happen before approval prompts,-/// ensuring users aren't asked to approve hooks for operations that will fail.-#[derive(Debug)]-pub enum SwitchPlan {- /// Branch already has a worktree - just switch to it (no git commands needed)- Existing {- path: PathBuf,- branch: String,- /// Expected path for mismatch detection- expected_path: PathBuf,- /// Branch to record as "previous" for `wt switch -`- new_previous: Option<String>,- },- /// Need to create a new worktree- Create {- branch: String,- worktree_path: PathBuf,- /// How to create the worktree- method: CreationMethod,- /// If path exists and --clobber, this is the backup path to move it to- clobber_backup: Option<PathBuf>,- /// Branch to record as "previous" for `wt switch -`- new_previous: Option<String>,- },-}--impl SwitchPlan {- /// Get the worktree path for this plan.- pub fn worktree_path(&self) -> &Path {- match self {- SwitchPlan::Existing { path, .. } => path,- SwitchPlan::Create { worktree_path, .. } => worktree_path,- }- }-- /// Get the branch name for this plan.- pub fn branch(&self) -> &str {- match self {- SwitchPlan::Existing { branch, .. } | SwitchPlan::Create { branch, .. } => branch,- }- }-- /// Returns true if this plan will create a new worktree.- pub fn is_create(&self) -> bool {- matches!(self, SwitchPlan::Create { .. })- }-}--/// How the branch should be handled after worktree removal.-///-/// This enum replaces the previous `no_delete_branch: bool, force_delete: bool` pattern,-/// making the three valid states explicit and preventing invalid combinations.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum BranchDeletionMode {- /// Keep the branch regardless of merge status (--no-delete-branch flag).- Keep,- /// Delete the branch only if it's fully merged into the target branch (default).- SafeDelete,- /// Delete the branch even if it's not merged (-D flag).- ForceDelete,-}--impl BranchDeletionMode {- /// Create from CLI flags.- ///- /// `--no-delete-branch` takes precedence over `-D` (force delete).- pub fn from_flags(no_delete_branch: bool, force_delete: bool) -> Self {- if no_delete_branch {- Self::Keep- } else if force_delete {- Self::ForceDelete- } else {- Self::SafeDelete- }- }-- /// Whether the branch should be kept (not deleted).- pub fn should_keep(&self) -> bool {- matches!(self, Self::Keep)- }-- /// Whether to force delete even if not merged.- pub fn is_force(&self) -> bool {- matches!(self, Self::ForceDelete)- }-}--/// Result of a worktree remove operation-pub enum RemoveResult {- /// Removed worktree and returned to main (if needed)- RemovedWorktree {- main_path: PathBuf,- worktree_path: PathBuf,- changed_directory: bool,- /// Branch name, if known. None for detached HEAD state.- branch_name: Option<String>,- deletion_mode: BranchDeletionMode,- target_branch: Option<String>,- /// Pre-computed integration reason (if branch is integrated with target).- /// Computed upfront to avoid race conditions when removing multiple worktrees- /// in background mode (background git operations can hold locks that cause- /// subsequent integration checks to fail).- integration_reason: Option<worktrunk::git::IntegrationReason>,- /// Force git worktree removal even with untracked files.- force_worktree: bool,- /// Expected path based on config template. `Some` when actual path differs- /// from expected (path mismatch), `None` when path matches template.- expected_path: Option<PathBuf>,- },- /// Branch exists but has no worktree - attempt branch deletion only- BranchOnly {- branch_name: String,- deletion_mode: BranchDeletionMode,- },-}--/// Result of resolving the switch target.-struct ResolvedTarget {- /// The resolved branch name- branch: String,- /// How to create the worktree- method: CreationMethod,-}--/// Resolve the switch target, handling pr: syntax and --create/--base flags.-///-/// This is the first phase of planning: determine what branch we're switching to-/// and how we'll create the worktree. May involve network calls for PR resolution.-fn resolve_switch_target(- repo: &Repository,- branch: &str,- create: bool,- base: Option<&str>,-) -> anyhow::Result<ResolvedTarget> {- use worktrunk::git::pr_ref::{fetch_pr_info, fork_remote_url, local_branch_name};-- // Handle pr:<number> syntax- if let Some(pr_number) = worktrunk::git::pr_ref::parse_pr_ref(branch) {- // --create and --base are invalid with pr: syntax- if create {- return Err(GitError::PrCreateConflict { pr_number }.into());- }- if base.is_some() {- return Err(GitError::PrBaseConflict { pr_number }.into());- }-- // Fetch PR info (network call)- let remote = repo.primary_remote()?;- crate::output::print(progress_message(cformat!(- "Fetching PR #{pr_number} from <bold>{remote}</>..."- )))?;-- let repo_root = repo.repo_path()?;- let pr_info = fetch_pr_info(pr_number, &repo_root)?;-- if pr_info.is_cross_repository {- // Fork PR: use owner/branch naming, will need fetch + config- let local_branch = local_branch_name(&pr_info);-- // Check if branch already exists and is tracking this PR- // If so, we can reuse it without re-fetching or re-configuring- if let Some(tracks_this_pr) =- worktrunk::git::pr_ref::branch_tracks_pr(&repo_root, &local_branch, pr_number)- {- if tracks_this_pr {- // Branch exists and tracks this PR - just create worktree- crate::output::print(info_message(cformat!(- "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"- )))?;- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- } else {- // Branch exists but tracks something else- return Err(GitError::BranchTracksDifferentPr {- branch: local_branch,- pr_number,- }- .into());- }- }-- // Branch doesn't exist - need full fork PR setup- let remote_url = repo.primary_remote_url().unwrap_or_default();- let fork_push_url =- fork_remote_url(&pr_info.head_owner, &pr_info.head_repo, &remote_url);-- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::ForkPr {- pr_number,- fork_push_url,- pr_url: pr_info.url,- },- });- } else {- // Same-repo PR: just use the branch name, regular switch- return Ok(ResolvedTarget {- branch: pr_info.head_ref_name,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- }- }-- // Regular branch switch- let resolved_branch = repo- .resolve_worktree_name(branch)- .context("Failed to resolve branch name")?;-- // Resolve and validate base- let resolved_base = if let Some(base_str) = base {- let resolved = repo.resolve_worktree_name(base_str)?;- if !create {- crate::output::print(warning_message(- "--base flag is only used with --create, ignoring",- ))?;- None- } else if !repo.ref_exists(&resolved)? {- return Err(GitError::InvalidReference {- reference: resolved,- }- .into());- } else {- Some(resolved)- }- } else {- None- };-- // Validate --create constraints- if create {- if repo.local_branch_exists(&resolved_branch)? {- return Err(GitError::BranchAlreadyExists {- branch: resolved_branch,- }- .into());- }-- // Warn if --create would shadow a remote branch- let remotes = repo.remotes_with_branch(&resolved_branch)?;- if !remotes.is_empty() {- let remote_ref = format!("{}/{}", remotes[0], resolved_branch);- crate::output::print(warning_message(cformat!(- "Branch <bold>{resolved_branch}</> exists on remote ({remote_ref}); creating new branch from base instead"- )))?;- let remove_cmd = suggest_command("remove", &[&resolved_branch], &[]);- let switch_cmd = suggest_command("switch", &[&resolved_branch], &[]);- crate::output::print(hint_message(cformat!(- "To switch to the remote branch, delete this branch and run without <bright-black>--create</>: <bright-black>{remove_cmd} && {switch_cmd}</>"- )))?;- }- }-- // Compute base branch for creation- let base_branch = if create {- resolved_base.or_else(|| {- // Check for invalid configured default branch- if let Some(configured) = repo.invalid_default_branch_config() {- let _ = crate::output::print(warning_message(cformat!(- "Configured default branch <bold>{configured}</> does not exist locally"- )));- let _ = crate::output::print(hint_message(cformat!(- "To reset, run <bright-black>wt config state default-branch clear</>"- )));- }- repo.resolve_target_branch(None)- .ok()- .filter(|b| repo.local_branch_exists(b).unwrap_or(false))- })- } else {- None- };-- Ok(ResolvedTarget {- branch: resolved_branch,- method: CreationMethod::Regular {- create_branch: create,- base_branch,- },- })-}--/// Check if branch already has a worktree.-///-/// Returns `Some(Existing)` if worktree exists and is valid.-/// Returns error if worktree record exists but directory is missing.-/// Returns `None` if no worktree exists for this branch.-fn check_existing_worktree(- repo: &Repository,- branch: &str,- expected_path: &Path,- new_previous: Option<String>,-) -> anyhow::Result<Option<SwitchPlan>> {- match repo.worktree_for_branch(branch)? {- Some(existing_path) if existing_path.exists() => Ok(Some(SwitchPlan::Existing {- path: canonicalize(&existing_path).unwrap_or(existing_path),- branch: branch.to_string(),- expected_path: expected_path.to_path_buf(),- new_previous,- })),- Some(_) => Err(GitError::WorktreeMissing {- branch: branch.to_string(),- }- .into()),- None => Ok(None),- }-}--/// Validate that we can create a worktree at the given path.-///-/// Checks:-/// - Path not occupied by another worktree-/// - For regular switches (not --create), branch must exist-/// - Handles --clobber for stale directories-///-/// Note: Fork PR branch existence is checked earlier in resolve_switch_target()-/// where we can also check if it's tracking the correct PR.-fn validate_worktree_creation(- repo: &Repository,- branch: &str,- path: &Path,- clobber: bool,- method: &CreationMethod,-) -> anyhow::Result<Option<PathBuf>> {- // For regular switches without --create, validate branch exists- if let CreationMethod::Regular {- create_branch: false,- ..- } = method- && !repo.branch_exists(branch)?- {- return Err(GitError::InvalidReference {- reference: branch.to_string(),- }- .into());- }-- // Check if path is occupied by another worktree- if let Some((existing_path, occupant)) = repo.worktree_at_path(path)? {- if !existing_path.exists() {- let occupant_branch = occupant.unwrap_or_else(|| branch.to_string());- return Err(GitError::WorktreeMissing {- branch: occupant_branch,- }- .into());- }- return Err(GitError::WorktreePathOccupied {- branch: branch.to_string(),- path: path.to_path_buf(),- occupant,- }- .into());- }-- // Handle clobber for stale directories- let is_create = matches!(- method,- CreationMethod::Regular {- create_branch: true,- ..- }- );- compute_clobber_backup(path, branch, clobber, is_create)-}--/// Set up a local branch for a fork PR.-///-/// Creates the branch, configures tracking, and creates the worktree.-/// Returns an error if any step fails - caller is responsible for cleanup.-fn setup_fork_pr_branch(- repo: &Repository,- branch: &str,- remote: &str,- pr_ref: &str,- fork_push_url: &str,- worktree_path: &Path,- pr_number: u32,-) -> anyhow::Result<()> {- // Create local branch from FETCH_HEAD- repo.run_command(&["branch", branch, "FETCH_HEAD"])- .with_context(|| {- format!(- "Failed to create local branch '{}' from PR #{}",- branch, pr_number- )- })?;-- // Configure branch tracking for pull and push- let branch_remote_key = format!("branch.{}.remote", branch);- let branch_merge_key = format!("branch.{}.merge", branch);- let branch_push_remote_key = format!("branch.{}.pushRemote", branch);- let merge_ref = format!("refs/{}", pr_ref);-- repo.run_command(&["config", &branch_remote_key, remote])- .with_context(|| format!("Failed to configure branch.{}.remote", branch))?;- repo.run_command(&["config", &branch_merge_key, &merge_ref])- .with_context(|| format!("Failed to configure branch.{}.merge", branch))?;- repo.run_command(&["config", &branch_push_remote_key, fork_push_url])- .with_context(|| format!("Failed to configure branch.{}.pushRemote", branch))?;-- // Create worktree- let worktree_path_str = worktree_path.to_string_lossy();- repo.run_command(&["worktree", "add", worktree_path_str.as_ref(), branch])- .map_err(|e| GitError::WorktreeCreationFailed {- branch: branch.to_string(),- base_branch: None,- error: e.to_string(),- })?;-- Ok(())-}--/// Validate and plan a switch operation.-///-/// This performs all validation upfront, returning a `SwitchPlan` that can be-/// executed later. Call this BEFORE approval prompts to ensure users aren't-/// asked to approve hooks for operations that will fail.-///-/// Warnings (remote branch shadow, --base without --create, invalid default branch)-/// are printed during planning since they're informational, not blocking.-pub fn plan_switch(- repo: &Repository,- branch: &str,- create: bool,- base: Option<&str>,- clobber: bool,- config: &WorktrunkConfig,-) -> anyhow::Result<SwitchPlan> {- // Record current branch for `wt switch -` support- let new_previous = repo.current_worktree().branch().ok().flatten();-- // Phase 1: Resolve target (handles pr:, validates --create/--base, may do network)- let target = resolve_switch_target(repo, branch, create, base)?;-- // Phase 2: Compute expected path- let expected_path = compute_worktree_path(repo, &target.branch, config)?;-- // Phase 3: Check if worktree already exists for this branch- if let Some(existing) =- check_existing_worktree(repo, &target.branch, &expected_path, new_previous.clone())?- {- return Ok(existing);- }-- // Phase 4: Validate we can create at this path- let clobber_backup = validate_worktree_creation(- repo,- &target.branch,- &expected_path,- clobber,- &target.method,- )?;-- // Phase 5: Return the plan- Ok(SwitchPlan::Create {- branch: target.branch,- worktree_path: expected_path,- method: target.method,- clobber_backup,- new_previous,- })-}--/// Execute a validated switch plan.-///-/// Takes a `SwitchPlan` from `plan_switch()` and executes it.-/// For `SwitchPlan::Existing`, just records history.-/// For `SwitchPlan::Create`, creates the worktree and runs hooks.-pub fn execute_switch(- repo: &Repository,- plan: SwitchPlan,- config: &WorktrunkConfig,- force: bool,- no_verify: bool,-) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {- match plan {- SwitchPlan::Existing {- path,- branch,- expected_path,- new_previous,- } => {- let _ = repo.record_switch_previous(new_previous.as_deref());-- let current_dir = std::env::current_dir()- .ok()- .and_then(|p| canonicalize(&p).ok());- let already_at_worktree = current_dir- .as_ref()- .map(|cur| cur == &path)- .unwrap_or(false);-- let mismatch_path = if !paths_match(&path, &expected_path) {- Some(expected_path)- } else {- None- };-- let result = if already_at_worktree {- SwitchResult::AlreadyAt(path)- } else {- SwitchResult::Existing(path)- };-- Ok((- result,- SwitchBranchInfo {- branch,- expected_path: mismatch_path,- },- ))- }-- SwitchPlan::Create {- branch,- worktree_path,- method,- clobber_backup,- new_previous,- } => {- // Handle --clobber backup if needed (shared for all creation methods)- if let Some(backup_path) = &clobber_backup {- let path_display = worktrunk::path::format_path_for_display(&worktree_path);- let backup_display = worktrunk::path::format_path_for_display(backup_path);- crate::output::print(warning_message(cformat!(- "Moving <bold>{path_display}</> to <bold>{backup_display}</> (--clobber)"- )))?;-- std::fs::rename(&worktree_path, backup_path).with_context(|| {- format!("Failed to move {path_display} to {backup_display}")- })?;- }-- // Execute based on creation method- let (created_branch, base_branch, from_remote) = match &method {- CreationMethod::Regular {- create_branch,- base_branch,- } => {- // Check if local branch exists BEFORE git worktree add (for DWIM detection)- let local_branch_existed =- !create_branch && repo.local_branch_exists(&branch).unwrap_or(false);-- // Build git worktree add command- let worktree_path_str = worktree_path.to_string_lossy();- let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];-- if *create_branch {- args.push("-b");- args.push(&branch);- if let Some(base) = base_branch {- args.push(base);- }- } else {- args.push(&branch);- }-- if let Err(e) = repo.run_command(&args) {- return Err(GitError::WorktreeCreationFailed {- branch: branch.clone(),- base_branch: base_branch.clone(),- error: e.to_string(),- }- .into());- }-- // Report tracking info only if git's DWIM created the branch from a remote- let from_remote = if !create_branch && !local_branch_existed {- repo.upstream_branch(&branch)?- } else {- None- };-- (*create_branch, base_branch.clone(), from_remote)- }-- CreationMethod::ForkPr {- pr_number,- fork_push_url,- pr_url: _,- } => {- let pr_ref = format!("pull/{}/head", pr_number);- let remote = repo.primary_remote()?;-- // Fetch the PR head (progress already shown during planning)- repo.run_command(&["fetch", &remote, &pr_ref])- .with_context(|| {- format!("Failed to fetch PR #{} from {}", pr_number, remote)- })?;-- // Execute branch creation and configuration with cleanup on failure.- // If any step after branch creation fails, we must delete the branch- // to avoid leaving orphaned state that blocks future attempts.- let setup_result = setup_fork_pr_branch(- repo,- &branch,- &remote,- &pr_ref,- fork_push_url,- &worktree_path,- *pr_number,- );-- if let Err(e) = setup_result {- // Cleanup: try to delete the branch if it was created- // (ignore errors - branch may not exist if creation failed)- let _ = repo.run_command(&["branch", "-D", &branch]);- return Err(e);- }-- crate::output::print(info_message(cformat!(- "Push configured to fork: <bright-black>{fork_push_url}</>"- )))?;-- (false, None, Some(format!("PR #{}", pr_number)))- }- };-- // Compute base worktree path for hooks and result- let base_worktree_path = base_branch- .as_ref()- .and_then(|b| repo.worktree_for_branch(b).ok().flatten())- .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));-- // Execute post-create commands- if !no_verify {- let repo_root = repo.repo_path()?;- let ctx = CommandContext::new(- repo,- config,- Some(&branch),- &worktree_path,- &repo_root,- force,- );-- match &method {- CreationMethod::Regular { base_branch, .. } => {- let extra_vars: Vec<(&str, &str)> = [- base_branch.as_ref().map(|b| ("base", b.as_str())),- base_worktree_path- .as_ref()- .map(|p| ("base_worktree_path", p.as_str())),- ]- .into_iter()- .flatten()- .collect();- ctx.execute_post_create_commands(&extra_vars)?;- }- CreationMethod::ForkPr {- pr_number, pr_url, ..- } => {- let pr_num_str = pr_number.to_string();- let extra_vars: Vec<(&str, &str)> =- vec![("pr_number", &pr_num_str), ("pr_url", pr_url)];- ctx.execute_post_create_commands(&extra_vars)?;- }- }- }-- // Record successful switch in history- let _ = repo.record_switch_previous(new_previous.as_deref());-- Ok((- SwitchResult::Created {- path: worktree_path,- created_branch,- base_branch,- base_worktree_path,- from_remote,- },- SwitchBranchInfo {- branch,- expected_path: None,- },- ))- }- }-}--pub fn handle_remove(- worktree_name: &str,- no_delete_branch: bool,- force_delete: bool,- force_worktree: bool,- config: &WorktrunkConfig,-) -> anyhow::Result<RemoveResult> {- let repo = Repository::current()?;-- // Progress message is shown in handle_removed_worktree_output() after pre-remove hooks run- repo.prepare_worktree_removal(- RemoveTarget::Branch(worktree_name),- BranchDeletionMode::from_flags(no_delete_branch, force_delete),- force_worktree,- config,- )-}--/// Handle removing the current worktree (supports detached HEAD state).-///-/// This is the path-based removal that handles the "@" shorthand, including-/// when HEAD is detached.-pub fn handle_remove_current(- no_delete_branch: bool,- force_delete: bool,- force_worktree: bool,- config: &WorktrunkConfig,-) -> anyhow::Result<RemoveResult> {- let repo = Repository::current()?;-- // Progress message is shown in handle_removed_worktree_output() after pre-remove hooks run- repo.prepare_worktree_removal(- RemoveTarget::Current,- BranchDeletionMode::from_flags(no_delete_branch, force_delete),- force_worktree,- config,- )-}--impl<'a> CommandContext<'a> {- /// Execute post-create commands sequentially (blocking)- ///- /// Runs user hooks first, then project hooks.- /// Shows path in hook announcements when shell integration isn't active (user's shell- /// won't cd to the new worktree, so they need to know where hooks ran).- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- pub fn execute_post_create_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;- super::hooks::run_hook_with_filter(- self,- self.config.hooks.post_create.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_create.as_ref()),- HookType::PostCreate,- extra_vars,- HookFailureStrategy::Warn,- None,- crate::output::post_hook_display_path(self.worktree_path),- )- }-- /// Spawn post-start commands in parallel as background processes (non-blocking)- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when- /// the user's shell won't be in the worktree (shell integration not active).- pub fn spawn_post_start_commands(- &self,- extra_vars: &[(&str, &str)],- display_path: Option<&std::path::Path>,- ) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;-- let commands = prepare_hook_commands(- self,- self.config.hooks.post_start.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_start.as_ref()),- HookType::PostStart,- extra_vars,- None,- display_path,- )?;-- spawn_hook_commands_background(self, commands, HookType::PostStart)- }-- /// Spawn post-switch commands in parallel as background processes (non-blocking)- ///- /// Runs on every switch, including to existing worktrees and newly created ones.- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when- /// the user's shell won't be in the worktree (shell integration not active).- pub fn spawn_post_switch_commands(- &self,- extra_vars: &[(&str, &str)],- display_path: Option<&std::path::Path>,- ) -> anyhow::Result<()> {- let project_config = self.repo.load_project_config()?;-- let commands = prepare_hook_commands(- self,- self.config.hooks.post_switch.as_ref(),- project_config- .as_ref()- .and_then(|c| c.hooks.post_switch.as_ref()),- HookType::PostSwitch,- extra_vars,- None,- display_path,- )?;-- spawn_hook_commands_background(self, commands, HookType::PostSwitch)- }-}--/// Push changes to target branch-///-/// The `operations` parameter indicates which merge operations occurred (commit, squash, rebase).-/// Pass `None` for standalone push operations where these concepts don't apply.-///-/// During the push stage we temporarily `git stash` non-overlapping changes in the-/// target worktree (if present) so that concurrent edits there do not block the-/// fast-forward. The stash is restored afterward and we bail out early if any file-/// overlaps with the push range.-pub fn handle_push(- target: Option<&str>,- verb: &str,- operations: Option<MergeOperations>,-) -> anyhow::Result<()> {- let repo = Repository::current()?;-- // Get and validate target branch (must be a branch since we're updating it)- let target_branch = repo.require_target_branch(target)?;-- // A worktree for the target branch is optional for push:- // - If present, we use it to check for overlapping dirty files.- // - If absent, we skip that safety step but still allow the push (git itself is fine).- let target_worktree_path = repo.worktree_for_branch(&target_branch)?;-- // Check if it's a fast-forward- if !repo.is_ancestor(&target_branch, "HEAD")? {- // Get formatted commit log (commits in target that we don't have)- let commits_formatted = repo- .run_command(&[- "log",- "--color=always",- "--graph",- "--oneline",- &format!("HEAD..{}", target_branch),- ])?- .trim()- .to_string();-- return Err(GitError::NotFastForward {- target_branch: target_branch.clone(),- commits_formatted,- in_merge_context: operations.is_some(),- }- .into());- }-- // Check for conflicting changes in target worktree (auto-stash safe changes)- // The stash guard auto-restores on drop (error paths), or explicitly via restore_now()- let mut stash_guard =- repo.prepare_target_worktree(target_worktree_path.as_ref(), &target_branch)?;-- // Count commits and show what will be pushed- let commit_count = repo.count_commits(&target_branch, "HEAD")?;-- // Get diff statistics BEFORE push (will be needed for success message later)- let stats_summary = if commit_count > 0 {- repo.diff_stats_summary(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])- } else {- Vec::new()- };-- // Build and show consolidated message with squash/rebase info- if commit_count > 0 {- let commit_text = if commit_count == 1 {- "commit"- } else {- "commits"- };- let head_sha = repo.run_command(&["rev-parse", "--short", "HEAD"])?;- let head_sha = head_sha.trim();-- let verb_ing = if verb.starts_with("Merged") {- "Merging"- } else {- "Pushing"- };-- // Build parenthetical showing which operations didn't happen and flags used- let mut notes = Vec::new();-- // Skipped operations - only include if we're in merge workflow context- if let Some(ops) = operations {- let mut skipped_ops = Vec::new();- if !ops.committed && !ops.squashed {- // Neither commit nor squash happened - combine them- skipped_ops.push("commit/squash");- }- if !ops.rebased {- skipped_ops.push("rebase");- }- if !skipped_ops.is_empty() {- notes.push(format!("no {} needed", skipped_ops.join("/")));- }- }-- let operations_note = if notes.is_empty() {- String::new()- } else {- format!(" ({})", notes.join(", "))- };-- crate::output::print(progress_message(cformat!(- "{verb_ing} {commit_count} {commit_text} to <bold>{target_branch}</> @ <dim>{head_sha}</>{operations_note}"- )))?;-- // Show the commit graph with color- let log_output = repo.run_command(&[- "log",- "--color=always",- "--graph",- "--oneline",- &format!("{}..HEAD", target_branch),- ])?;- crate::output::print(format_with_gutter(&log_output, None))?;-- // Show diff statistics- super::show_diffstat(&repo, &format!("{}..HEAD", target_branch))?;- }-- // Get git common dir for the push- let git_common_dir = repo.git_common_dir();- let git_common_dir_str = git_common_dir.to_string_lossy();-- // Perform the push - stash guard will auto-restore on any exit path- // Use --receive-pack to pass config to the receiving end without permanently mutating repo config- let push_target = format!("HEAD:{}", target_branch);- repo.run_command(&[- "push",- "--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",- git_common_dir_str.as_ref(),- &push_target,- ])- .map_err(|e| {- // CommandFailed contains raw git output, wrap in PushFailed for proper formatting- GitError::PushFailed {- target_branch: target_branch.clone(),- error: e.to_string(),- }- })?;-- // Restore stash before success message (Drop handles error paths automatically)- if let Some(guard) = stash_guard.as_mut() {- guard.restore_now();- }-- // Show success message after push completes- if commit_count > 0 {- // Use the diff statistics captured earlier (before push)- let mut summary_parts = vec![format!(- "{} commit{}",- commit_count,- if commit_count == 1 { "" } else { "s" }- )];- summary_parts.extend(stats_summary);-- // Re-apply bright-black after stats (which end with a reset) so ) is also gray- let stats_str = summary_parts.join(", ");- let paren_close = cformat!("<bright-black>)</>"); // Separate to avoid cformat optimization- crate::output::print(success_message(cformat!(- "{verb} <bold>{target_branch}</> <bright-black>({stats_str}</>{}",- paren_close- )))?;- } else {- // For merge workflow context, explain why nothing was pushed- let context = if let Some(ops) = operations {- let mut notes = Vec::new();- if !ops.committed && !ops.squashed {- notes.push("no new commits");- }- if !ops.rebased {- notes.push("no rebase needed");- }- if notes.is_empty() {- String::new()- } else {- format!(" ({})", notes.join(", "))- }- } else {- String::new()- };-- // No action: nothing was pushed, just acknowledging state- crate::output::print(info_message(cformat!(- "Already up to date with <bold>{target_branch}</>{context}"- )))?;- }-- Ok(())-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_switch_result_path_already_at() {- let path = PathBuf::from("/test/path");- let result = SwitchResult::AlreadyAt(path.clone());- assert_eq!(result.path(), &path);- }-- #[test]- fn test_switch_result_path_existing() {- let path = PathBuf::from("/test/existing");- let result = SwitchResult::Existing(path.clone());- assert_eq!(result.path(), &path);- }-- #[test]- fn test_switch_result_path_created() {- let path = PathBuf::from("/test/created");- let result = SwitchResult::Created {- path: path.clone(),- created_branch: true,- base_branch: Some("main".to_string()),- base_worktree_path: Some("/test/main".to_string()),- from_remote: None,- };- assert_eq!(result.path(), &path);- }-- #[test]- fn test_switch_result_created_with_remote() {- let path = PathBuf::from("/test/remote");- let result = SwitchResult::Created {- path: path.clone(),- created_branch: false,- base_branch: None,- base_worktree_path: None,- from_remote: Some("origin/feature".to_string()),- };- assert_eq!(result.path(), &path);- }-- #[test]- fn test_merge_operations_struct() {- let ops = MergeOperations {- committed: true,- squashed: false,- rebased: true,- };- assert!(ops.committed);- assert!(!ops.squashed);- assert!(ops.rebased);- }-- #[test]- fn test_merge_operations_clone() {- let ops = MergeOperations {- committed: true,- squashed: true,- rebased: false,- };- // MergeOperations implements both Clone and Copy- // Use Clone explicitly to test the Clone impl- let cloned = Clone::clone(&ops);- assert_eq!(ops.committed, cloned.committed);- assert_eq!(ops.squashed, cloned.squashed);- assert_eq!(ops.rebased, cloned.rebased);- }-- #[test]- fn test_merge_operations_copy() {- let ops = MergeOperations {- committed: false,- squashed: false,- rebased: true,- };- let copied = ops; // Copy trait- assert_eq!(ops.committed, copied.committed);- assert_eq!(ops.squashed, copied.squashed);- assert_eq!(ops.rebased, copied.rebased);- }-- #[test]- fn test_merge_operations_debug() {- let ops = MergeOperations {- committed: true,- squashed: false,- rebased: true,- };- let debug = format!("{:?}", ops);- assert!(debug.contains("committed: true"));- assert!(debug.contains("squashed: false"));- assert!(debug.contains("rebased: true"));- }-- #[test]- fn test_remove_result_removed_worktree() {- let result = RemoveResult::RemovedWorktree {- main_path: PathBuf::from("/main"),- worktree_path: PathBuf::from("/worktree"),- changed_directory: true,- branch_name: Some("feature".to_string()),- deletion_mode: BranchDeletionMode::SafeDelete,- target_branch: Some("main".to_string()),- integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),- force_worktree: false,- expected_path: None,- };- match result {- RemoveResult::RemovedWorktree {- main_path,- worktree_path,- changed_directory,- branch_name,- deletion_mode,- target_branch,- integration_reason,- force_worktree,- expected_path,- } => {- assert_eq!(main_path.to_str().unwrap(), "/main");- assert_eq!(worktree_path.to_str().unwrap(), "/worktree");- assert!(changed_directory);- assert_eq!(branch_name.as_deref(), Some("feature"));- assert!(!deletion_mode.should_keep());- assert!(!deletion_mode.is_force());- assert_eq!(target_branch.as_deref(), Some("main"));- assert!(integration_reason.is_some());- assert!(!force_worktree);- assert!(expected_path.is_none());- }- _ => panic!("Expected RemovedWorktree variant"),- }- }-- #[test]- fn test_remove_result_branch_only() {- let result = RemoveResult::BranchOnly {- branch_name: "stale-branch".to_string(),- deletion_mode: BranchDeletionMode::Keep,- };- match result {- RemoveResult::BranchOnly {- branch_name,- deletion_mode,- } => {- assert_eq!(branch_name, "stale-branch");- assert!(deletion_mode.should_keep());- assert!(!deletion_mode.is_force());- }- _ => panic!("Expected BranchOnly variant"),- }- }-- #[test]- fn test_remove_result_with_force_delete() {- let result = RemoveResult::RemovedWorktree {- main_path: PathBuf::from("/main"),- worktree_path: PathBuf::from("/worktree"),- changed_directory: false,- branch_name: None, // Detached HEAD- deletion_mode: BranchDeletionMode::ForceDelete,- target_branch: None,- integration_reason: None, // Force delete skips integration check- force_worktree: true,- expected_path: None,- };- match result {- RemoveResult::RemovedWorktree {- branch_name,- deletion_mode,- force_worktree,- ..- } => {- assert!(branch_name.is_none());- assert!(deletion_mode.is_force());- assert!(force_worktree);- }- _ => panic!("Expected RemovedWorktree variant"),- }- }-- #[test]- fn test_generate_backup_path_with_extension() {- // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP- let path = PathBuf::from("/tmp/repo.feature");- let backup = super::generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(- backup,- PathBuf::from("/tmp/repo.feature.bak.20250101-000000")- );-- let path = PathBuf::from("/tmp/file.txt");- let backup = super::generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000"));- }-- #[test]- fn test_generate_backup_path_without_extension() {- // Paths without extensions: foo -> foo.bak.TIMESTAMP- let path = PathBuf::from("/tmp/repo/feature");- let backup = super::generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(- backup,- PathBuf::from("/tmp/repo/feature.bak.20250101-000000")- );-- let path = PathBuf::from("/tmp/mydir");- let backup = super::generate_backup_path(&path, "20250101-000000").unwrap();- assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000"));- }-- #[test]- fn test_generate_backup_path_unusual_paths() {- // Root path has no file name- let path = PathBuf::from("/");- assert!(super::generate_backup_path(&path, "20250101-000000").is_err());-- // Parent reference has no file name- let path = PathBuf::from("..");- assert!(super::generate_backup_path(&path, "20250101-000000").is_err());- }-}diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsnew file mode 100644index 000000000..50279cd29--- /dev/null+++ b/src/commands/worktree/hooks.rs@@ -0,0 +1,91 @@+//! Hook execution for worktree operations.+//!+//! CommandContext implementations for post-create, post-start, and post-switch hooks.++use worktrunk::HookType;++use crate::commands::command_executor::CommandContext;+use crate::commands::hooks::{+ HookFailureStrategy, prepare_hook_commands, spawn_hook_commands_background,+};++impl<'a> CommandContext<'a> {+ /// Execute post-create commands sequentially (blocking)+ ///+ /// Runs user hooks first, then project hooks.+ /// Shows path in hook announcements when shell integration isn't active (user's shell+ /// won't cd to the new worktree, so they need to know where hooks ran).+ ///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).+ pub fn execute_post_create_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {+ let project_config = self.repo.load_project_config()?;+ crate::commands::hooks::run_hook_with_filter(+ self,+ self.config.hooks.post_create.as_ref(),+ project_config+ .as_ref()+ .and_then(|c| c.hooks.post_create.as_ref()),+ HookType::PostCreate,+ extra_vars,+ HookFailureStrategy::Warn,+ None,+ crate::output::post_hook_display_path(self.worktree_path),+ )+ }++ /// Spawn post-start commands in parallel as background processes (non-blocking)+ ///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).+ /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when+ /// the user's shell won't be in the worktree (shell integration not active).+ pub fn spawn_post_start_commands(+ &self,+ extra_vars: &[(&str, &str)],+ display_path: Option<&std::path::Path>,+ ) -> anyhow::Result<()> {+ let project_config = self.repo.load_project_config()?;++ let commands = prepare_hook_commands(+ self,+ self.config.hooks.post_start.as_ref(),+ project_config+ .as_ref()+ .and_then(|c| c.hooks.post_start.as_ref()),+ HookType::PostStart,+ extra_vars,+ None,+ display_path,+ )?;++ spawn_hook_commands_background(self, commands, HookType::PostStart)+ }++ /// Spawn post-switch commands in parallel as background processes (non-blocking)+ ///+ /// Runs on every switch, including to existing worktrees and newly created ones.+ ///+ /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).+ /// `display_path`: When `Some`, shows the path in hook announcements. Pass this when+ /// the user's shell won't be in the worktree (shell integration not active).+ pub fn spawn_post_switch_commands(+ &self,+ extra_vars: &[(&str, &str)],+ display_path: Option<&std::path::Path>,+ ) -> anyhow::Result<()> {+ let project_config = self.repo.load_project_config()?;++ let commands = prepare_hook_commands(+ self,+ self.config.hooks.post_switch.as_ref(),+ project_config+ .as_ref()+ .and_then(|c| c.hooks.post_switch.as_ref()),+ HookType::PostSwitch,+ extra_vars,+ None,+ display_path,+ )?;++ spawn_hook_commands_background(self, commands, HookType::PostSwitch)+ }+}diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsnew file mode 100644index 000000000..c52f8aa51--- /dev/null+++ b/src/commands/worktree/mod.rs@@ -0,0 +1,98 @@+//! Worktree operations with file-based shell integration.+//!+//! # The Directory Change Problem+//!+//! Worktree commands (`switch`, `remove`, `merge`) need to change the user's working directory,+//! but there's a fundamental Unix limitation: **child processes cannot change their parent's+//! working directory**. This is a security feature and core Unix design principle.+//!+//! When a user runs `wt switch my-feature`, the `wt` binary runs as a child process of the shell.+//! The binary can change *its own* working directory, but when it exits, the parent shell remains+//! in the original directory.+//!+//! # Solution: File-Based Directive Passing+//!+//! Shell wrappers create a temp file and set `WORKTRUNK_DIRECTIVE_FILE` to its path:+//!+//! 1. Shell wrapper creates temp file via `mktemp`+//! 2. Shell wrapper sets `WORKTRUNK_DIRECTIVE_FILE=/path/to/temp`+//! 3. wt binary writes commands like `cd '/path'` to that file+//! 4. Shell wrapper sources the file after wt exits+//!+//! ## Without Shell Integration (Direct Binary Call)+//!+//! ```bash+//! $ wt switch my-feature+//! Created new branch and worktree for 'my-feature' @ /path/to/worktree+//!+//! Run `wt config shell install` to enable automatic cd+//!+//! $ pwd+//! /original/directory # ← User is still here!+//! ```+//!+//! The binary performs git operations and prints user-friendly messages, but **cannot** change+//! the parent shell's directory. User must manually `cd` to the worktree.+//!+//! ## With Shell Integration+//!+//! ```bash+//! $ wt switch my-feature+//! Created new branch and worktree for 'my-feature' @ /path/to/worktree+//!+//! $ pwd+//! /path/to/worktree # ← Automatically changed!+//! ```+//!+//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell wrapper:+//!+//! 1. Creates a temp file and sets `WORKTRUNK_DIRECTIVE_FILE` to its path+//! 2. Runs the wt binary (which writes `cd '/path'` to the temp file)+//! 3. Sources the temp file after wt exits+//!+//! # Implementation Details+//!+//! Result types (`SwitchResult`, `RemoveResult`) are pure data structures that only contain+//! operation results. All presentation logic is handled by the `output` module:+//!+//! - `output::handle_switch_output()`: Formats and outputs switch operation results+//! - `output::handle_remove_output()`: Formats and outputs remove operation results+//!+//! The output handlers check `is_shell_integration_active()` to determine if hints should+//! be suppressed (when shell integration is already configured).+//!+//! ## Exit Code Semantics+//!+//! When using `-x` to execute commands after switching:+//!+//! - **If wt operation fails**: Returns wt's exit code (command never executes)+//! - **If wt succeeds but command fails**: Returns the command's exit code+//! - **Rationale**: Enables command chaining with proper error propagation+//!+//! Example:+//! ```bash+//! wt switch feature -x "cargo build" && cargo test+//! # If wt fails (e.g., worktree doesn't exist), cargo build never runs+//! # If cargo build fails, cargo test doesn't run (exit code propagates)+//! ```+//!+//! The shell wrapper is generated by `wt config shell init <shell>` from templates in `templates/`.++mod hooks;+mod push;+mod remove;+mod resolve;+mod switch;+mod types;++// Re-export public types and functions+pub use push::handle_push;+pub use remove::{handle_remove, handle_remove_current};+pub use resolve::{+ get_path_mismatch, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,+};+pub use switch::{execute_switch, plan_switch};+pub use types::{+ BranchDeletionMode, MergeOperations, RemoveResult, ResolutionContext, SwitchBranchInfo,+ SwitchResult,+};diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsnew file mode 100644index 000000000..853e0f0df--- /dev/null+++ b/src/commands/worktree/push.rs@@ -0,0 +1,200 @@+//! Worktree push operations.+//!+//! Push changes to target branch with safety checks.++use color_print::cformat;+use worktrunk::git::{GitError, Repository};+use worktrunk::styling::{format_with_gutter, info_message, progress_message, success_message};++use super::types::MergeOperations;+use crate::commands::repository_ext::RepositoryCliExt;++/// Push changes to target branch+///+/// The `operations` parameter indicates which merge operations occurred (commit, squash, rebase).+/// Pass `None` for standalone push operations where these concepts don't apply.+///+/// During the push stage we temporarily `git stash` non-overlapping changes in the+/// target worktree (if present) so that concurrent edits there do not block the+/// fast-forward. The stash is restored afterward and we bail out early if any file+/// overlaps with the push range.+pub fn handle_push(+ target: Option<&str>,+ verb: &str,+ operations: Option<MergeOperations>,+) -> anyhow::Result<()> {+ let repo = Repository::current()?;++ // Get and validate target branch (must be a branch since we're updating it)+ let target_branch = repo.require_target_branch(target)?;++ // A worktree for the target branch is optional for push:+ // - If present, we use it to check for overlapping dirty files.+ // - If absent, we skip that safety step but still allow the push (git itself is fine).+ let target_worktree_path = repo.worktree_for_branch(&target_branch)?;++ // Check if it's a fast-forward+ if !repo.is_ancestor(&target_branch, "HEAD")? {+ // Get formatted commit log (commits in target that we don't have)+ let commits_formatted = repo+ .run_command(&[+ "log",+ "--color=always",+ "--graph",+ "--oneline",+ &format!("HEAD..{}", target_branch),+ ])?+ .trim()+ .to_string();++ return Err(GitError::NotFastForward {+ target_branch: target_branch.clone(),+ commits_formatted,+ in_merge_context: operations.is_some(),+ }+ .into());+ }++ // Check for conflicting changes in target worktree (auto-stash safe changes)+ // The stash guard auto-restores on drop (error paths), or explicitly via restore_now()+ let mut stash_guard =+ repo.prepare_target_worktree(target_worktree_path.as_ref(), &target_branch)?;++ // Count commits and show what will be pushed+ let commit_count = repo.count_commits(&target_branch, "HEAD")?;++ // Get diff statistics BEFORE push (will be needed for success message later)+ let stats_summary = if commit_count > 0 {+ repo.diff_stats_summary(&["diff", "--shortstat", &format!("{}..HEAD", target_branch)])+ } else {+ Vec::new()+ };++ // Build and show consolidated message with squash/rebase info+ if commit_count > 0 {+ let commit_text = if commit_count == 1 {+ "commit"+ } else {+ "commits"+ };+ let head_sha = repo.run_command(&["rev-parse", "--short", "HEAD"])?;+ let head_sha = head_sha.trim();++ let verb_ing = if verb.starts_with("Merged") {+ "Merging"+ } else {+ "Pushing"+ };++ // Build parenthetical showing which operations didn't happen and flags used+ let mut notes = Vec::new();++ // Skipped operations - only include if we're in merge workflow context+ if let Some(ops) = operations {+ let mut skipped_ops = Vec::new();+ if !ops.committed && !ops.squashed {+ // Neither commit nor squash happened - combine them+ skipped_ops.push("commit/squash");+ }+ if !ops.rebased {+ skipped_ops.push("rebase");+ }+ if !skipped_ops.is_empty() {+ notes.push(format!("no {} needed", skipped_ops.join("/")));+ }+ }++ let operations_note = if notes.is_empty() {+ String::new()+ } else {+ format!(" ({})", notes.join(", "))+ };++ crate::output::print(progress_message(cformat!(+ "{verb_ing} {commit_count} {commit_text} to <bold>{target_branch}</> @ <dim>{head_sha}</>{operations_note}"+ )))?;++ // Show the commit graph with color+ let log_output = repo.run_command(&[+ "log",+ "--color=always",+ "--graph",+ "--oneline",+ &format!("{}..HEAD", target_branch),+ ])?;+ crate::output::print(format_with_gutter(&log_output, None))?;++ // Show diff statistics+ crate::commands::show_diffstat(&repo, &format!("{}..HEAD", target_branch))?;+ }++ // Get git common dir for the push+ let git_common_dir = repo.git_common_dir();+ let git_common_dir_str = git_common_dir.to_string_lossy();++ // Perform the push - stash guard will auto-restore on any exit path+ // Use --receive-pack to pass config to the receiving end without permanently mutating repo config+ let push_target = format!("HEAD:{}", target_branch);+ repo.run_command(&[+ "push",+ "--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",+ git_common_dir_str.as_ref(),+ &push_target,+ ])+ .map_err(|e| {+ // CommandFailed contains raw git output, wrap in PushFailed for proper formatting+ GitError::PushFailed {+ target_branch: target_branch.clone(),+ error: e.to_string(),+ }+ })?;++ // Restore stash before success message (Drop handles error paths automatically)+ if let Some(guard) = stash_guard.as_mut() {+ guard.restore_now();+ }++ // Show success message after push completes+ if commit_count > 0 {+ // Use the diff statistics captured earlier (before push)+ let mut summary_parts = vec![format!(+ "{} commit{}",+ commit_count,+ if commit_count == 1 { "" } else { "s" }+ )];+ summary_parts.extend(stats_summary);++ // Re-apply bright-black after stats (which end with a reset) so ) is also gray+ let stats_str = summary_parts.join(", ");+ let paren_close = cformat!("<bright-black>)</>"); // Separate to avoid cformat optimization+ crate::output::print(success_message(cformat!(+ "{verb} <bold>{target_branch}</> <bright-black>({stats_str}</>{}",+ paren_close+ )))?;+ } else {+ // For merge workflow context, explain why nothing was pushed+ let context = if let Some(ops) = operations {+ let mut notes = Vec::new();+ if !ops.committed && !ops.squashed {+ notes.push("no new commits");+ }+ if !ops.rebased {+ notes.push("no rebase needed");+ }+ if notes.is_empty() {+ String::new()+ } else {+ format!(" ({})", notes.join(", "))+ }+ } else {+ String::new()+ };++ // No action: nothing was pushed, just acknowledging state+ crate::output::print(info_message(cformat!(+ "Already up to date with <bold>{target_branch}</>{context}"+ )))?;+ }++ Ok(())+}diff --git a/src/commands/worktree/remove.rs b/src/commands/worktree/remove.rsnew file mode 100644index 000000000..bb1c64d13--- /dev/null+++ b/src/commands/worktree/remove.rs@@ -0,0 +1,47 @@+//! Worktree remove operations.++use worktrunk::config::WorktrunkConfig;+use worktrunk::git::Repository;++use super::types::{BranchDeletionMode, RemoveResult};+use crate::commands::repository_ext::{RemoveTarget, RepositoryCliExt};++/// Remove a worktree by branch name.+pub fn handle_remove(+ worktree_name: &str,+ no_delete_branch: bool,+ force_delete: bool,+ force_worktree: bool,+ config: &WorktrunkConfig,+) -> anyhow::Result<RemoveResult> {+ let repo = Repository::current()?;++ // Progress message is shown in handle_removed_worktree_output() after pre-remove hooks run+ repo.prepare_worktree_removal(+ RemoveTarget::Branch(worktree_name),+ BranchDeletionMode::from_flags(no_delete_branch, force_delete),+ force_worktree,+ config,+ )+}++/// Handle removing the current worktree (supports detached HEAD state).+///+/// This is the path-based removal that handles the "@" shorthand, including+/// when HEAD is detached.+pub fn handle_remove_current(+ no_delete_branch: bool,+ force_delete: bool,+ force_worktree: bool,+ config: &WorktrunkConfig,+) -> anyhow::Result<RemoveResult> {+ let repo = Repository::current()?;++ // Progress message is shown in handle_removed_worktree_output() after pre-remove hooks run+ repo.prepare_worktree_removal(+ RemoveTarget::Current,+ BranchDeletionMode::from_flags(no_delete_branch, force_delete),+ force_worktree,+ config,+ )+}diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsnew file mode 100644index 000000000..54f3783e7--- /dev/null+++ b/src/commands/worktree/resolve.rs@@ -0,0 +1,293 @@+//! Worktree resolution and path computation.+//!+//! Functions for resolving worktree arguments and computing expected paths.++use std::path::{Path, PathBuf};++use color_print::cformat;+use normalize_path::NormalizePath;+use worktrunk::config::WorktrunkConfig;+use worktrunk::git::{GitError, Repository, ResolvedWorktree};++use super::types::ResolutionContext;++/// Resolve a worktree argument using branch-first lookup.+///+/// Resolution order:+/// 1. Special symbols ("@", "-", "^") are handled specially+/// 2. Resolve argument as branch name+/// 3. If branch has a worktree, return it+/// 4. Otherwise, return branch-only (no worktree)+///+/// For `CreateOrSwitch` context: If the branch has no worktree but expected+/// path is occupied by another branch's worktree, an error is raised.+///+/// For `Remove` context: Path occupation is ignored since we're not creating+/// a worktree - we just return `BranchOnly` if no worktree exists.+pub fn resolve_worktree_arg(+ repo: &Repository,+ name: &str,+ config: &WorktrunkConfig,+ context: ResolutionContext,+) -> anyhow::Result<ResolvedWorktree> {+ // Special symbols - delegate to Repository for consistent error handling+ match name {+ "@" | "-" | "^" => {+ return repo.resolve_worktree(name);+ }+ _ => {}+ }++ // Resolve as branch name+ let branch = repo.resolve_worktree_name(name)?;++ // Branch-first: check if branch has worktree anywhere+ if let Some(path) = repo.worktree_for_branch(&branch)? {+ return Ok(ResolvedWorktree::Worktree {+ path,+ branch: Some(branch),+ });+ }++ // No worktree for branch - check if expected path is occupied (only for create/switch)+ if context == ResolutionContext::CreateOrSwitch {+ let expected_path = compute_worktree_path(repo, name, config)?;+ if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {+ // Path is occupied by a different branch's worktree+ return Err(GitError::WorktreePathOccupied {+ branch,+ path: expected_path,+ occupant: occupant_branch,+ }+ .into());+ }+ }++ // No worktree for branch (and path not occupied, or we don't care about path)+ Ok(ResolvedWorktree::BranchOnly { branch })+}++/// Compute the expected worktree path for a branch name.+///+/// For the default branch, returns the repo root (main worktree location).+/// For other branches, applies the `worktree-path` template from config.+///+/// Uses cached values from Repository for `default_branch` and `is_bare`.+pub fn compute_worktree_path(+ repo: &Repository,+ branch: &str,+ config: &WorktrunkConfig,+) -> anyhow::Result<PathBuf> {+ let repo_root = repo.repo_path()?;+ let default_branch = repo.default_branch().unwrap_or_default();+ let is_bare = repo.is_bare()?;++ // Default branch lives at repo root (main worktree), not a templated path.+ // Exception: bare repos have no main worktree, so all branches use templated paths.+ if !is_bare && branch == default_branch {+ return Ok(repo_root);+ }++ let repo_name = repo_root+ .file_name()+ .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?+ .to_str()+ .ok_or_else(|| {+ anyhow::anyhow!(+ "Repository path contains invalid UTF-8: {}",+ repo_root.display()+ )+ })?;++ let relative_path = config+ .format_path(repo_name, branch, repo)+ .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;++ Ok(repo_root.join(relative_path).normalize())+}++/// Check if a worktree is at its expected path based on config template.+///+/// Returns true if the worktree's actual path matches what `compute_worktree_path`+/// would generate for its branch. Detached HEAD always returns false (no expected path).+///+/// Uses canonicalization to handle symlinks and relative paths correctly.+/// Uses cached values from Repository for `default_branch` and `is_bare`.+pub fn is_worktree_at_expected_path(+ wt: &worktrunk::git::WorktreeInfo,+ repo: &Repository,+ config: &WorktrunkConfig,+) -> bool {+ match &wt.branch {+ Some(branch) => compute_worktree_path(repo, branch, config)+ .map(|expected| paths_match(&wt.path, &expected))+ .unwrap_or(false),+ None => false,+ }+}++/// Compare two paths for equality, canonicalizing to handle symlinks and relative paths.+///+/// Returns `true` if the paths resolve to the same location.+pub(super) fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {+ use dunce::canonicalize;+ let a_canonical = canonicalize(a).unwrap_or_else(|_| a.to_path_buf());+ let b_canonical = canonicalize(b).unwrap_or_else(|_| b.to_path_buf());+ a_canonical == b_canonical+}++/// Returns the expected path if `actual_path` differs from the template-computed path.+///+/// Returns `Some(expected_path)` when there's a mismatch, `None` when paths match.+/// Used to show path mismatch warnings in `wt remove` and `wt merge`.+pub fn get_path_mismatch(+ repo: &Repository,+ branch: &str,+ actual_path: &std::path::Path,+ config: &WorktrunkConfig,+) -> Option<PathBuf> {+ compute_worktree_path(repo, branch, config)+ .ok()+ .filter(|expected| !paths_match(actual_path, expected))+}++/// Compute a user-facing display name for a worktree.+///+/// Returns styled content with branch names bolded:+/// - If branch is consistent with worktree location: just the branch name (bolded)+/// - If branch differs from expected location: `dir_name (on **branch**)` (both bolded)+/// - If detached HEAD: `dir_name (detached)` (dir_name bolded)+///+/// "Consistent" means the worktree path matches `compute_worktree_path(branch)`,+/// which returns repo root for default branch and templated path for others.+pub fn worktree_display_name(+ wt: &worktrunk::git::WorktreeInfo,+ repo: &Repository,+ config: &WorktrunkConfig,+) -> String {+ let dir_name = wt.dir_name();++ match &wt.branch {+ Some(branch) => {+ if is_worktree_at_expected_path(wt, repo, config) {+ cformat!("<bold>{branch}</>")+ } else {+ cformat!("<bold>{dir_name}</> (on <bold>{branch}</>)")+ }+ }+ None => cformat!("<bold>{dir_name}</> (detached)"),+ }+}++/// Generate a backup path for the given path with a timestamp suffix.+///+/// For paths with extensions: `file.txt` → `file.txt.bak.TIMESTAMP`+/// For paths without extensions: `foo` → `foo.bak.TIMESTAMP`+///+/// Returns an error for unusual paths without a file name (e.g., `/` or `..`).+pub(super) fn generate_backup_path(+ path: &std::path::Path,+ suffix: &str,+) -> anyhow::Result<PathBuf> {+ let file_name = path+ .file_name()+ .ok_or_else(|| anyhow::anyhow!("Cannot generate backup path for {}", path.display()))?;++ if path.extension().is_none() {+ // Path has no extension (e.g., /repo/feature)+ Ok(path.with_file_name(format!("{}.bak.{suffix}", file_name.to_string_lossy())))+ } else {+ // Path has an extension (e.g., /repo.feature or /file.txt)+ Ok(path.with_extension(format!(+ "{}.bak.{suffix}",+ path.extension()+ .map(|e| e.to_string_lossy().to_string())+ .unwrap_or_default()+ )))+ }+}++/// Compute the backup path for clobber operations.+///+/// Returns `Ok(None)` if path doesn't exist.+/// Returns `Ok(Some(backup_path))` if clobber is true and path exists.+/// Returns `Err(GitError::WorktreePathExists)` if clobber is false and path exists.+pub(super) fn compute_clobber_backup(+ path: &Path,+ branch: &str,+ clobber: bool,+ create: bool,+) -> anyhow::Result<Option<PathBuf>> {+ if !path.exists() {+ return Ok(None);+ }++ if clobber {+ let timestamp = worktrunk::utils::get_now() as i64;+ let datetime =+ chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);+ let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();+ let backup_path = generate_backup_path(path, &suffix)?;++ if backup_path.exists() {+ anyhow::bail!(+ "Backup path already exists: {}",+ worktrunk::path::format_path_for_display(&backup_path)+ );+ }+ Ok(Some(backup_path))+ } else {+ Err(GitError::WorktreePathExists {+ branch: branch.to_string(),+ path: path.to_path_buf(),+ create,+ }+ .into())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_generate_backup_path_with_extension() {+ // Paths with extensions: file.txt -> file.txt.bak.TIMESTAMP+ let path = PathBuf::from("/tmp/repo.feature");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(+ backup,+ PathBuf::from("/tmp/repo.feature.bak.20250101-000000")+ );++ let path = PathBuf::from("/tmp/file.txt");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(backup, PathBuf::from("/tmp/file.txt.bak.20250101-000000"));+ }++ #[test]+ fn test_generate_backup_path_without_extension() {+ // Paths without extensions: foo -> foo.bak.TIMESTAMP+ let path = PathBuf::from("/tmp/repo/feature");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(+ backup,+ PathBuf::from("/tmp/repo/feature.bak.20250101-000000")+ );++ let path = PathBuf::from("/tmp/mydir");+ let backup = generate_backup_path(&path, "20250101-000000").unwrap();+ assert_eq!(backup, PathBuf::from("/tmp/mydir.bak.20250101-000000"));+ }++ #[test]+ fn test_generate_backup_path_unusual_paths() {+ // Root path has no file name+ let path = PathBuf::from("/");+ assert!(generate_backup_path(&path, "20250101-000000").is_err());++ // Parent reference has no file name+ let path = PathBuf::from("..");+ assert!(generate_backup_path(&path, "20250101-000000").is_err());+ }+}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsnew file mode 100644index 000000000..d757c14ac--- /dev/null+++ b/src/commands/worktree/switch.rs@@ -0,0 +1,589 @@+//! Worktree switch operations.+//!+//! Functions for planning and executing worktree switches.++use std::path::Path;++use anyhow::Context;+use color_print::cformat;+use dunce::canonicalize;+use worktrunk::config::WorktrunkConfig;+use worktrunk::git::{GitError, Repository};+use worktrunk::styling::{+ hint_message, info_message, progress_message, suggest_command, warning_message,+};++use super::resolve::{compute_clobber_backup, compute_worktree_path, paths_match};+use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};+use crate::commands::command_executor::CommandContext;++/// Result of resolving the switch target.+struct ResolvedTarget {+ /// The resolved branch name+ branch: String,+ /// How to create the worktree+ method: CreationMethod,+}++/// Resolve the switch target, handling pr: syntax and --create/--base flags.+///+/// This is the first phase of planning: determine what branch we're switching to+/// and how we'll create the worktree. May involve network calls for PR resolution.+fn resolve_switch_target(+ repo: &Repository,+ branch: &str,+ create: bool,+ base: Option<&str>,+) -> anyhow::Result<ResolvedTarget> {+ use worktrunk::git::pr_ref::{fetch_pr_info, fork_remote_url, local_branch_name};++ // Handle pr:<number> syntax+ if let Some(pr_number) = worktrunk::git::pr_ref::parse_pr_ref(branch) {+ // --create and --base are invalid with pr: syntax+ if create {+ return Err(GitError::PrCreateConflict { pr_number }.into());+ }+ if base.is_some() {+ return Err(GitError::PrBaseConflict { pr_number }.into());+ }++ // Fetch PR info (network call)+ let remote = repo.primary_remote()?;+ crate::output::print(progress_message(cformat!(+ "Fetching PR #{pr_number} from <bold>{remote}</>..."+ )))?;++ let repo_root = repo.repo_path()?;+ let pr_info = fetch_pr_info(pr_number, &repo_root)?;++ if pr_info.is_cross_repository {+ // Fork PR: use owner/branch naming, will need fetch + config+ let local_branch = local_branch_name(&pr_info);++ // Check if branch already exists and is tracking this PR+ // If so, we can reuse it without re-fetching or re-configuring+ if let Some(tracks_this_pr) =+ worktrunk::git::pr_ref::branch_tracks_pr(&repo_root, &local_branch, pr_number)+ {+ if tracks_this_pr {+ // Branch exists and tracks this PR - just create worktree+ crate::output::print(info_message(cformat!(+ "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"+ )))?;+ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });+ } else {+ // Branch exists but tracks something else+ return Err(GitError::BranchTracksDifferentPr {+ branch: local_branch,+ pr_number,+ }+ .into());+ }+ }++ // Branch doesn't exist - need full fork PR setup+ let remote_url = repo.primary_remote_url().unwrap_or_default();+ let fork_push_url =+ fork_remote_url(&pr_info.head_owner, &pr_info.head_repo, &remote_url);++ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::ForkPr {+ pr_number,+ fork_push_url,+ pr_url: pr_info.url,+ },+ });+ } else {+ // Same-repo PR: just use the branch name, regular switch+ return Ok(ResolvedTarget {+ branch: pr_info.head_ref_name,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });+ }+ }++ // Regular branch switch+ let resolved_branch = repo+ .resolve_worktree_name(branch)+ .context("Failed to resolve branch name")?;++ // Resolve and validate base+ let resolved_base = if let Some(base_str) = base {+ let resolved = repo.resolve_worktree_name(base_str)?;+ if !create {+ crate::output::print(warning_message(+ "--base flag is only used with --create, ignoring",+ ))?;+ None+ } else if !repo.ref_exists(&resolved)? {+ return Err(GitError::InvalidReference {+ reference: resolved,+ }+ .into());+ } else {+ Some(resolved)+ }+ } else {+ None+ };++ // Validate --create constraints+ if create {+ if repo.local_branch_exists(&resolved_branch)? {+ return Err(GitError::BranchAlreadyExists {+ branch: resolved_branch,+ }+ .into());+ }++ // Warn if --create would shadow a remote branch+ let remotes = repo.remotes_with_branch(&resolved_branch)?;+ if !remotes.is_empty() {+ let remote_ref = format!("{}/{}", remotes[0], resolved_branch);+ crate::output::print(warning_message(cformat!(+ "Branch <bold>{resolved_branch}</> exists on remote ({remote_ref}); creating new branch from base instead"+ )))?;+ let remove_cmd = suggest_command("remove", &[&resolved_branch], &[]);+ let switch_cmd = suggest_command("switch", &[&resolved_branch], &[]);+ crate::output::print(hint_message(cformat!(+ "To switch to the remote branch, delete this branch and run without <bright-black>--create</>: <bright-black>{remove_cmd} && {switch_cmd}</>"+ )))?;+ }+ }++ // Compute base branch for creation+ let base_branch = if create {+ resolved_base.or_else(|| {+ // Check for invalid configured default branch+ if let Some(configured) = repo.invalid_default_branch_config() {+ let _ = crate::output::print(warning_message(cformat!(+ "Configured default branch <bold>{configured}</> does not exist locally"+ )));+ let _ = crate::output::print(hint_message(cformat!(+ "To reset, run <bright-black>wt config state default-branch clear</>"+ )));+ }+ repo.resolve_target_branch(None)+ .ok()+ .filter(|b| repo.local_branch_exists(b).unwrap_or(false))+ })+ } else {+ None+ };++ Ok(ResolvedTarget {+ branch: resolved_branch,+ method: CreationMethod::Regular {+ create_branch: create,+ base_branch,+ },+ })+}++/// Check if branch already has a worktree.+///+/// Returns `Some(Existing)` if worktree exists and is valid.+/// Returns error if worktree record exists but directory is missing.+/// Returns `None` if no worktree exists for this branch.+fn check_existing_worktree(+ repo: &Repository,+ branch: &str,+ expected_path: &Path,+ new_previous: Option<String>,+) -> anyhow::Result<Option<SwitchPlan>> {+ match repo.worktree_for_branch(branch)? {+ Some(existing_path) if existing_path.exists() => Ok(Some(SwitchPlan::Existing {+ path: canonicalize(&existing_path).unwrap_or(existing_path),+ branch: branch.to_string(),+ expected_path: expected_path.to_path_buf(),+ new_previous,+ })),+ Some(_) => Err(GitError::WorktreeMissing {+ branch: branch.to_string(),+ }+ .into()),+ None => Ok(None),+ }+}++/// Validate that we can create a worktree at the given path.+///+/// Checks:+/// - Path not occupied by another worktree+/// - For regular switches (not --create), branch must exist+/// - Handles --clobber for stale directories+///+/// Note: Fork PR branch existence is checked earlier in resolve_switch_target()+/// where we can also check if it's tracking the correct PR.+fn validate_worktree_creation(+ repo: &Repository,+ branch: &str,+ path: &Path,+ clobber: bool,+ method: &CreationMethod,+) -> anyhow::Result<Option<std::path::PathBuf>> {+ // For regular switches without --create, validate branch exists+ if let CreationMethod::Regular {+ create_branch: false,+ ..+ } = method+ && !repo.branch_exists(branch)?+ {+ return Err(GitError::InvalidReference {+ reference: branch.to_string(),+ }+ .into());+ }++ // Check if path is occupied by another worktree+ if let Some((existing_path, occupant)) = repo.worktree_at_path(path)? {+ if !existing_path.exists() {+ let occupant_branch = occupant.unwrap_or_else(|| branch.to_string());+ return Err(GitError::WorktreeMissing {+ branch: occupant_branch,+ }+ .into());+ }+ return Err(GitError::WorktreePathOccupied {+ branch: branch.to_string(),+ path: path.to_path_buf(),+ occupant,+ }+ .into());+ }++ // Handle clobber for stale directories+ let is_create = matches!(+ method,+ CreationMethod::Regular {+ create_branch: true,+ ..+ }+ );+ compute_clobber_backup(path, branch, clobber, is_create)+}++/// Set up a local branch for a fork PR.+///+/// Creates the branch, configures tracking, and creates the worktree.+/// Returns an error if any step fails - caller is responsible for cleanup.+fn setup_fork_pr_branch(+ repo: &Repository,+ branch: &str,+ remote: &str,+ pr_ref: &str,+ fork_push_url: &str,+ worktree_path: &Path,+ pr_number: u32,+) -> anyhow::Result<()> {+ // Create local branch from FETCH_HEAD+ repo.run_command(&["branch", branch, "FETCH_HEAD"])+ .with_context(|| {+ format!(+ "Failed to create local branch '{}' from PR #{}",+ branch, pr_number+ )+ })?;++ // Configure branch tracking for pull and push+ let branch_remote_key = format!("branch.{}.remote", branch);+ let branch_merge_key = format!("branch.{}.merge", branch);+ let branch_push_remote_key = format!("branch.{}.pushRemote", branch);+ let merge_ref = format!("refs/{}", pr_ref);++ repo.run_command(&["config", &branch_remote_key, remote])+ .with_context(|| format!("Failed to configure branch.{}.remote", branch))?;+ repo.run_command(&["config", &branch_merge_key, &merge_ref])+ .with_context(|| format!("Failed to configure branch.{}.merge", branch))?;+ repo.run_command(&["config", &branch_push_remote_key, fork_push_url])+ .with_context(|| format!("Failed to configure branch.{}.pushRemote", branch))?;++ // Create worktree+ let worktree_path_str = worktree_path.to_string_lossy();+ repo.run_command(&["worktree", "add", worktree_path_str.as_ref(), branch])+ .map_err(|e| GitError::WorktreeCreationFailed {+ branch: branch.to_string(),+ base_branch: None,+ error: e.to_string(),+ })?;++ Ok(())+}++/// Validate and plan a switch operation.+///+/// This performs all validation upfront, returning a `SwitchPlan` that can be+/// executed later. Call this BEFORE approval prompts to ensure users aren't+/// asked to approve hooks for operations that will fail.+///+/// Warnings (remote branch shadow, --base without --create, invalid default branch)+/// are printed during planning since they're informational, not blocking.+pub fn plan_switch(+ repo: &Repository,+ branch: &str,+ create: bool,+ base: Option<&str>,+ clobber: bool,+ config: &WorktrunkConfig,+) -> anyhow::Result<SwitchPlan> {+ // Record current branch for `wt switch -` support+ let new_previous = repo.current_worktree().branch().ok().flatten();++ // Phase 1: Resolve target (handles pr:, validates --create/--base, may do network)+ let target = resolve_switch_target(repo, branch, create, base)?;++ // Phase 2: Compute expected path+ let expected_path = compute_worktree_path(repo, &target.branch, config)?;++ // Phase 3: Check if worktree already exists for this branch+ if let Some(existing) =+ check_existing_worktree(repo, &target.branch, &expected_path, new_previous.clone())?+ {+ return Ok(existing);+ }++ // Phase 4: Validate we can create at this path+ let clobber_backup = validate_worktree_creation(+ repo,+ &target.branch,+ &expected_path,+ clobber,+ &target.method,+ )?;++ // Phase 5: Return the plan+ Ok(SwitchPlan::Create {+ branch: target.branch,+ worktree_path: expected_path,+ method: target.method,+ clobber_backup,+ new_previous,+ })+}++/// Execute a validated switch plan.+///+/// Takes a `SwitchPlan` from `plan_switch()` and executes it.+/// For `SwitchPlan::Existing`, just records history.+/// For `SwitchPlan::Create`, creates the worktree and runs hooks.+pub fn execute_switch(+ repo: &Repository,+ plan: SwitchPlan,+ config: &WorktrunkConfig,+ force: bool,+ no_verify: bool,+) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {+ match plan {+ SwitchPlan::Existing {+ path,+ branch,+ expected_path,+ new_previous,+ } => {+ let _ = repo.record_switch_previous(new_previous.as_deref());++ let current_dir = std::env::current_dir()+ .ok()+ .and_then(|p| canonicalize(&p).ok());+ let already_at_worktree = current_dir+ .as_ref()+ .map(|cur| cur == &path)+ .unwrap_or(false);++ let mismatch_path = if !paths_match(&path, &expected_path) {+ Some(expected_path)+ } else {+ None+ };++ let result = if already_at_worktree {+ SwitchResult::AlreadyAt(path)+ } else {+ SwitchResult::Existing(path)+ };++ Ok((+ result,+ SwitchBranchInfo {+ branch,+ expected_path: mismatch_path,+ },+ ))+ }++ SwitchPlan::Create {+ branch,+ worktree_path,+ method,+ clobber_backup,+ new_previous,+ } => {+ // Handle --clobber backup if needed (shared for all creation methods)+ if let Some(backup_path) = &clobber_backup {+ let path_display = worktrunk::path::format_path_for_display(&worktree_path);+ let backup_display = worktrunk::path::format_path_for_display(backup_path);+ crate::output::print(warning_message(cformat!(+ "Moving <bold>{path_display}</> to <bold>{backup_display}</> (--clobber)"+ )))?;++ std::fs::rename(&worktree_path, backup_path).with_context(|| {+ format!("Failed to move {path_display} to {backup_display}")+ })?;+ }++ // Execute based on creation method+ let (created_branch, base_branch, from_remote) = match &method {+ CreationMethod::Regular {+ create_branch,+ base_branch,+ } => {+ // Check if local branch exists BEFORE git worktree add (for DWIM detection)+ let local_branch_existed =+ !create_branch && repo.local_branch_exists(&branch).unwrap_or(false);++ // Build git worktree add command+ let worktree_path_str = worktree_path.to_string_lossy();+ let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];++ if *create_branch {+ args.push("-b");+ args.push(&branch);+ if let Some(base) = base_branch {+ args.push(base);+ }+ } else {+ args.push(&branch);+ }++ if let Err(e) = repo.run_command(&args) {+ return Err(GitError::WorktreeCreationFailed {+ branch: branch.clone(),+ base_branch: base_branch.clone(),+ error: e.to_string(),+ }+ .into());+ }++ // Report tracking info only if git's DWIM created the branch from a remote+ let from_remote = if !create_branch && !local_branch_existed {+ repo.upstream_branch(&branch)?+ } else {+ None+ };++ (*create_branch, base_branch.clone(), from_remote)+ }++ CreationMethod::ForkPr {+ pr_number,+ fork_push_url,+ pr_url: _,+ } => {+ let pr_ref = format!("pull/{}/head", pr_number);+ let remote = repo.primary_remote()?;++ // Fetch the PR head (progress already shown during planning)+ repo.run_command(&["fetch", &remote, &pr_ref])+ .with_context(|| {+ format!("Failed to fetch PR #{} from {}", pr_number, remote)+ })?;++ // Execute branch creation and configuration with cleanup on failure.+ // If any step after branch creation fails, we must delete the branch+ // to avoid leaving orphaned state that blocks future attempts.+ let setup_result = setup_fork_pr_branch(+ repo,+ &branch,+ &remote,+ &pr_ref,+ fork_push_url,+ &worktree_path,+ *pr_number,+ );++ if let Err(e) = setup_result {+ // Cleanup: try to delete the branch if it was created+ // (ignore errors - branch may not exist if creation failed)+ let _ = repo.run_command(&["branch", "-D", &branch]);+ return Err(e);+ }++ crate::output::print(info_message(cformat!(+ "Push configured to fork: <bright-black>{fork_push_url}</>"+ )))?;++ (false, None, Some(format!("PR #{}", pr_number)))+ }+ };++ // Compute base worktree path for hooks and result+ let base_worktree_path = base_branch+ .as_ref()+ .and_then(|b| repo.worktree_for_branch(b).ok().flatten())+ .map(|p| worktrunk::path::to_posix_path(&p.to_string_lossy()));++ // Execute post-create commands+ if !no_verify {+ let repo_root = repo.repo_path()?;+ let ctx = CommandContext::new(+ repo,+ config,+ Some(&branch),+ &worktree_path,+ &repo_root,+ force,+ );++ match &method {+ CreationMethod::Regular { base_branch, .. } => {+ let extra_vars: Vec<(&str, &str)> = [+ base_branch.as_ref().map(|b| ("base", b.as_str())),+ base_worktree_path+ .as_ref()+ .map(|p| ("base_worktree_path", p.as_str())),+ ]+ .into_iter()+ .flatten()+ .collect();+ ctx.execute_post_create_commands(&extra_vars)?;+ }+ CreationMethod::ForkPr {+ pr_number, pr_url, ..+ } => {+ let pr_num_str = pr_number.to_string();+ let extra_vars: Vec<(&str, &str)> =+ vec![("pr_number", &pr_num_str), ("pr_url", pr_url)];+ ctx.execute_post_create_commands(&extra_vars)?;+ }+ }+ }++ // Record successful switch in history+ let _ = repo.record_switch_previous(new_previous.as_deref());++ Ok((+ SwitchResult::Created {+ path: worktree_path,+ created_branch,+ base_branch,+ base_worktree_path,+ from_remote,+ },+ SwitchBranchInfo {+ branch,+ expected_path: None,+ },+ ))+ }+ }+}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsnew file mode 100644index 000000000..f5485e405--- /dev/null+++ b/src/commands/worktree/types.rs@@ -0,0 +1,387 @@+//! Types for worktree operations.+//!+//! Core data structures used by switch, remove, and push operations.++use std::path::{Path, PathBuf};++/// Flags indicating which merge operations occurred+#[derive(Debug, Clone, Copy)]+pub struct MergeOperations {+ pub committed: bool,+ pub squashed: bool,+ pub rebased: bool,+}++/// Result of a worktree switch operation+pub enum SwitchResult {+ /// Already at the target worktree (no action taken)+ AlreadyAt(PathBuf),+ /// Switched to existing worktree at the given path+ Existing(PathBuf),+ /// Created new worktree at the given path+ Created {+ path: PathBuf,+ /// True if we used `-b` to create a new branch (--create flag)+ created_branch: bool,+ /// Base branch when creating new branch (e.g., "main")+ base_branch: Option<String>,+ /// Absolute path to base branch's worktree (POSIX format for shell compatibility)+ base_worktree_path: Option<String>,+ /// Remote tracking branch if created from remote (e.g., "origin/feature")+ /// This is set when git's DWIM created a local branch from a remote+ from_remote: Option<String>,+ },+}++impl SwitchResult {+ /// Get the worktree path+ pub fn path(&self) -> &PathBuf {+ match self {+ SwitchResult::AlreadyAt(path) => path,+ SwitchResult::Existing(path) => path,+ SwitchResult::Created { path, .. } => path,+ }+ }+}++/// Branch state for a switch operation.+#[derive(Debug, Clone)]+pub struct SwitchBranchInfo {+ /// The branch being switched to+ pub branch: String,+ /// Expected path when there's a branch-worktree mismatch (None = path matches template)+ pub expected_path: Option<PathBuf>,+}++/// How the worktree will be created.+#[derive(Debug)]+pub enum CreationMethod {+ /// Use `git worktree add` - handles existing branch, DWIM from remote, or -b for new+ Regular {+ /// True if using `-b` to create a new branch (--create flag)+ create_branch: bool,+ /// Base branch for creation (resolved, validated to exist)+ base_branch: Option<String>,+ },+ /// Fork PR: fetch from refs/pull/N/head, create branch, configure pushRemote+ ForkPr {+ pr_number: u32,+ fork_push_url: String,+ pr_url: String,+ },+}++/// Validated plan for a switch operation.+///+/// Created by `plan_switch()`, consumed by `execute_switch()`.+/// This separation allows validation to happen before approval prompts,+/// ensuring users aren't asked to approve hooks for operations that will fail.+#[derive(Debug)]+pub enum SwitchPlan {+ /// Branch already has a worktree - just switch to it (no git commands needed)+ Existing {+ path: PathBuf,+ branch: String,+ /// Expected path for mismatch detection+ expected_path: PathBuf,+ /// Branch to record as "previous" for `wt switch -`+ new_previous: Option<String>,+ },+ /// Need to create a new worktree+ Create {+ branch: String,+ worktree_path: PathBuf,+ /// How to create the worktree+ method: CreationMethod,+ /// If path exists and --clobber, this is the backup path to move it to+ clobber_backup: Option<PathBuf>,+ /// Branch to record as "previous" for `wt switch -`+ new_previous: Option<String>,+ },+}++impl SwitchPlan {+ /// Get the worktree path for this plan.+ pub fn worktree_path(&self) -> &Path {+ match self {+ SwitchPlan::Existing { path, .. } => path,+ SwitchPlan::Create { worktree_path, .. } => worktree_path,+ }+ }++ /// Get the branch name for this plan.+ pub fn branch(&self) -> &str {+ match self {+ SwitchPlan::Existing { branch, .. } | SwitchPlan::Create { branch, .. } => branch,+ }+ }++ /// Returns true if this plan will create a new worktree.+ pub fn is_create(&self) -> bool {+ matches!(self, SwitchPlan::Create { .. })+ }+}++/// How the branch should be handled after worktree removal.+///+/// This enum replaces the previous `no_delete_branch: bool, force_delete: bool` pattern,+/// making the three valid states explicit and preventing invalid combinations.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum BranchDeletionMode {+ /// Keep the branch regardless of merge status (--no-delete-branch flag).+ Keep,+ /// Delete the branch only if it's fully merged into the target branch (default).+ SafeDelete,+ /// Delete the branch even if it's not merged (-D flag).+ ForceDelete,+}++impl BranchDeletionMode {+ /// Create from CLI flags.+ ///+ /// `--no-delete-branch` takes precedence over `-D` (force delete).+ pub fn from_flags(no_delete_branch: bool, force_delete: bool) -> Self {+ if no_delete_branch {+ Self::Keep+ } else if force_delete {+ Self::ForceDelete+ } else {+ Self::SafeDelete+ }+ }++ /// Whether the branch should be kept (not deleted).+ pub fn should_keep(&self) -> bool {+ matches!(self, Self::Keep)+ }++ /// Whether to force delete even if not merged.+ pub fn is_force(&self) -> bool {+ matches!(self, Self::ForceDelete)+ }+}++/// Result of a worktree remove operation+pub enum RemoveResult {+ /// Removed worktree and returned to main (if needed)+ RemovedWorktree {+ main_path: PathBuf,+ worktree_path: PathBuf,+ changed_directory: bool,+ /// Branch name, if known. None for detached HEAD state.+ branch_name: Option<String>,+ deletion_mode: BranchDeletionMode,+ target_branch: Option<String>,+ /// Pre-computed integration reason (if branch is integrated with target).+ /// Computed upfront to avoid race conditions when removing multiple worktrees+ /// in background mode (background git operations can hold locks that cause+ /// subsequent integration checks to fail).+ integration_reason: Option<worktrunk::git::IntegrationReason>,+ /// Force git worktree removal even with untracked files.+ force_worktree: bool,+ /// Expected path based on config template. `Some` when actual path differs+ /// from expected (path mismatch), `None` when path matches template.+ expected_path: Option<PathBuf>,+ },+ /// Branch exists but has no worktree - attempt branch deletion only+ BranchOnly {+ branch_name: String,+ deletion_mode: BranchDeletionMode,+ },+}++/// Context for worktree resolution - determines which checks are performed.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ResolutionContext {+ /// Creating or switching to a worktree - path occupation is an error+ /// because we need to create a worktree at the expected path.+ CreateOrSwitch,+ /// Removing a worktree - we only care if the branch has a worktree,+ /// path occupation is irrelevant since we're not creating anything.+ Remove,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_switch_result_path_already_at() {+ let path = PathBuf::from("/test/path");+ let result = SwitchResult::AlreadyAt(path.clone());+ assert_eq!(result.path(), &path);+ }++ #[test]+ fn test_switch_result_path_existing() {+ let path = PathBuf::from("/test/existing");+ let result = SwitchResult::Existing(path.clone());+ assert_eq!(result.path(), &path);+ }++ #[test]+ fn test_switch_result_path_created() {+ let path = PathBuf::from("/test/created");+ let result = SwitchResult::Created {+ path: path.clone(),+ created_branch: true,+ base_branch: Some("main".to_string()),+ base_worktree_path: Some("/test/main".to_string()),+ from_remote: None,+ };+ assert_eq!(result.path(), &path);+ }++ #[test]+ fn test_switch_result_created_with_remote() {+ let path = PathBuf::from("/test/remote");+ let result = SwitchResult::Created {+ path: path.clone(),+ created_branch: false,+ base_branch: None,+ base_worktree_path: None,+ from_remote: Some("origin/feature".to_string()),+ };+ assert_eq!(result.path(), &path);+ }++ #[test]+ fn test_merge_operations_struct() {+ let ops = MergeOperations {+ committed: true,+ squashed: false,+ rebased: true,+ };+ assert!(ops.committed);+ assert!(!ops.squashed);+ assert!(ops.rebased);+ }++ #[test]+ fn test_merge_operations_clone() {+ let ops = MergeOperations {+ committed: true,+ squashed: true,+ rebased: false,+ };+ // MergeOperations implements both Clone and Copy+ // Use Clone explicitly to test the Clone impl+ let cloned = Clone::clone(&ops);+ assert_eq!(ops.committed, cloned.committed);+ assert_eq!(ops.squashed, cloned.squashed);+ assert_eq!(ops.rebased, cloned.rebased);+ }++ #[test]+ fn test_merge_operations_copy() {+ let ops = MergeOperations {+ committed: false,+ squashed: false,+ rebased: true,+ };+ let copied = ops; // Copy trait+ assert_eq!(ops.committed, copied.committed);+ assert_eq!(ops.squashed, copied.squashed);+ assert_eq!(ops.rebased, copied.rebased);+ }++ #[test]+ fn test_merge_operations_debug() {+ let ops = MergeOperations {+ committed: true,+ squashed: false,+ rebased: true,+ };+ let debug = format!("{:?}", ops);+ assert!(debug.contains("committed: true"));+ assert!(debug.contains("squashed: false"));+ assert!(debug.contains("rebased: true"));+ }++ #[test]+ fn test_remove_result_removed_worktree() {+ let result = RemoveResult::RemovedWorktree {+ main_path: PathBuf::from("/main"),+ worktree_path: PathBuf::from("/worktree"),+ changed_directory: true,+ branch_name: Some("feature".to_string()),+ deletion_mode: BranchDeletionMode::SafeDelete,+ target_branch: Some("main".to_string()),+ integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),+ force_worktree: false,+ expected_path: None,+ };+ match result {+ RemoveResult::RemovedWorktree {+ main_path,+ worktree_path,+ changed_directory,+ branch_name,+ deletion_mode,+ target_branch,+ integration_reason,+ force_worktree,+ expected_path,+ } => {+ assert_eq!(main_path.to_str().unwrap(), "/main");+ assert_eq!(worktree_path.to_str().unwrap(), "/worktree");+ assert!(changed_directory);+ assert_eq!(branch_name.as_deref(), Some("feature"));+ assert!(!deletion_mode.should_keep());+ assert!(!deletion_mode.is_force());+ assert_eq!(target_branch.as_deref(), Some("main"));+ assert!(integration_reason.is_some());+ assert!(!force_worktree);+ assert!(expected_path.is_none());+ }+ _ => panic!("Expected RemovedWorktree variant"),+ }+ }++ #[test]+ fn test_remove_result_branch_only() {+ let result = RemoveResult::BranchOnly {+ branch_name: "stale-branch".to_string(),+ deletion_mode: BranchDeletionMode::Keep,+ };+ match result {+ RemoveResult::BranchOnly {+ branch_name,+ deletion_mode,+ } => {+ assert_eq!(branch_name, "stale-branch");+ assert!(deletion_mode.should_keep());+ assert!(!deletion_mode.is_force());+ }+ _ => panic!("Expected BranchOnly variant"),+ }+ }++ #[test]+ fn test_remove_result_with_force_delete() {+ let result = RemoveResult::RemovedWorktree {+ main_path: PathBuf::from("/main"),+ worktree_path: PathBuf::from("/worktree"),+ changed_directory: false,+ branch_name: None, // Detached HEAD+ deletion_mode: BranchDeletionMode::ForceDelete,+ target_branch: None,+ integration_reason: None, // Force delete skips integration check+ force_worktree: true,+ expected_path: None,+ };+ match result {+ RemoveResult::RemovedWorktree {+ branch_name,+ deletion_mode,+ force_worktree,+ ..+ } => {+ assert!(branch_name.is_none());+ assert!(deletion_mode.is_force());+ assert!(force_worktree);+ }+ _ => panic!("Expected RemovedWorktree variant"),+ }+ }+}diff --git a/src/shell.rs b/src/shell/detection.rssimilarity index 54%rename from src/shell.rsrename to src/shell/detection.rsindex e80d99d9a..a11ceca3b 100644--- a/src/shell.rs+++ b/src/shell/detection.rs@@ -1,45 +1,12 @@-use askama::Template;-use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};+//! Shell integration detection logic.+//!+//! This module detects whether shell integration is configured by scanning+//! shell config files (`.bashrc`, `.zshrc`, etc.) for eval/source lines+//! that invoke `wt config shell init`.+use std::path::PathBuf;-use crate::path::home_dir;--/// Get PowerShell profile paths in order of preference.-/// On Windows, returns both PowerShell Core (7+) and Windows PowerShell (5.1) paths.-/// On Unix, uses the conventional ~/.config/powershell location.-fn powershell_profile_paths(home: &std::path::Path) -> Vec<PathBuf> {- #[cfg(windows)]- {- // Use platform-specific Documents path (handles non-English Windows)- let docs = dirs::document_dir().unwrap_or_else(|| home.join("Documents"));- vec![- // PowerShell Core 6+ (pwsh.exe) - preferred- docs.join("PowerShell")- .join("Microsoft.PowerShell_profile.ps1"),- // Windows PowerShell 5.1 (powershell.exe) - legacy but still common- docs.join("WindowsPowerShell")- .join("Microsoft.PowerShell_profile.ps1"),- ]- }- #[cfg(not(windows))]- {- vec![- home.join(".config")- .join("powershell")- .join("Microsoft.PowerShell_profile.ps1"),- ]- }-}--/// Get the user's home directory or return an error-fn home_dir_required() -> Result<PathBuf, std::io::Error> {- home_dir().ok_or_else(|| {- std::io::Error::new(- std::io::ErrorKind::NotFound,- "Cannot determine home directory. Set $HOME (Unix) or $USERPROFILE (Windows)",- )- })-}+use super::paths::{home_dir_required, powershell_profile_paths};/// Detect if a line contains shell integration for a specific command.///@@ -469,679 +436,11 @@ pub fn scan_for_detection_details(cmd: &str) -> Result<Vec<FileDetectionResult>,Ok(results)}-/// Supported shells-///-/// Currently supported: bash, fish, zsh, powershell-///-/// On Windows, Git Bash users should use `bash` for shell integration.-/// PowerShell integration is available for native Windows users without Git Bash.-#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]-#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]-pub enum Shell {- Bash,- Fish,- Zsh,- #[strum(serialize = "powershell")]- #[clap(name = "powershell")]- PowerShell,-}--impl Shell {- /// Returns the config file paths for this shell.- ///- /// The `cmd` parameter affects the Fish functions filename (e.g., `wt.fish` or `git-wt.fish`).- /// Returns paths in order of preference. The first existing file should be used.- pub fn config_paths(&self, cmd: &str) -> Result<Vec<PathBuf>, std::io::Error> {- let home = home_dir_required()?;-- Ok(match self {- Self::Bash => {- // Use .bashrc - sourced by interactive shells (login shells should source .bashrc)- vec![home.join(".bashrc")]- }- Self::Zsh => {- let zdotdir = std::env::var("ZDOTDIR")- .map(PathBuf::from)- .unwrap_or_else(|_| home.clone());- vec![zdotdir.join(".zshrc")]- }- Self::Fish => {- // For fish, we write to functions/ which is autoloaded on first use.- // This ensures PATH is fully configured before our function loads,- // fixing the issue where Homebrew PATH setup in config.fish runs- // after conf.d/ files. See: https://github.com/max-sixty/worktrunk/issues/566- vec![- home.join(".config")- .join("fish")- .join("functions")- .join(format!("{}.fish", cmd)),- ]- }- Self::PowerShell => powershell_profile_paths(&home),- })- }-- /// Returns the legacy fish conf.d path for cleanup purposes.- ///- /// Previously, fish shell integration was installed to `~/.config/fish/conf.d/{cmd}.fish`.- /// This caused issues with Homebrew PATH setup (see issue #566). We now install to- /// `functions/{cmd}.fish` instead. This method returns the legacy path so install/uninstall- /// can clean it up.- pub fn legacy_fish_conf_d_path(cmd: &str) -> Result<PathBuf, std::io::Error> {- let home = home_dir_required()?;- Ok(home- .join(".config")- .join("fish")- .join("conf.d")- .join(format!("{}.fish", cmd)))- }-- /// Returns the path to the native completion directory for this shell.- ///- /// The `cmd` parameter affects the completion filename (e.g., `wt.fish` or `git-wt.fish`).- ///- /// Note: Bash and Zsh use inline lazy completions in the init script.- /// Only Fish uses a separate completion file at ~/.config/fish/completions/- /// (installed by `wt config shell install`) that uses $WORKTRUNK_BIN to bypass- /// the shell function wrapper.- pub fn completion_path(&self, cmd: &str) -> Result<PathBuf, std::io::Error> {- let home = home_dir_required()?;-- // Use etcetera for XDG-compliant paths when available- let strategy = choose_base_strategy().ok();-- Ok(match self {- Self::Bash => {- // XDG_DATA_HOME defaults to ~/.local/share- let data_home = strategy- .as_ref()- .map(|s| s.data_dir())- .unwrap_or_else(|| home.join(".local").join("share"));- data_home- .join("bash-completion")- .join("completions")- .join(cmd)- }- Self::Zsh => home.join(".zfunc").join(format!("_{}", cmd)),- Self::Fish => {- // XDG_CONFIG_HOME defaults to ~/.config- let config_home = strategy- .as_ref()- .map(|s| s.config_dir())- .unwrap_or_else(|| home.join(".config"));- config_home- .join("fish")- .join("completions")- .join(format!("{}.fish", cmd))- }- Self::PowerShell => {- // PowerShell doesn't use a separate completion file - completions are- // registered inline in the profile using Register-ArgumentCompleter- // Return a dummy path that won't be used- home.join(format!(".{}-powershell-completions", cmd))- }- })- }-- /// Returns the line to add to the config file for shell integration.- ///- /// The `cmd` parameter specifies the command name (e.g., `wt` or `git-wt`).- /// All shells use a conditional wrapper to avoid errors when the command doesn't exist.- ///- /// Note: The generated line does not include `--cmd` because `binary_name()` already- /// detects the command name from argv\[0\] at runtime.- pub fn config_line(&self, cmd: &str) -> String {- match self {- Self::Bash | Self::Zsh => {- format!(- "if command -v {cmd} >/dev/null 2>&1; then eval \"$(command {cmd} config shell init {})\"; fi",- self- )- }- Self::Fish => {- format!(- "if type -q {cmd}; command {cmd} config shell init {} | source; end",- self- )- }- Self::PowerShell => {- format!(- "if (Get-Command {cmd} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {cmd} config shell init powershell) }}",- )- }- }- }-- /// Check if shell integration is configured for the given command name.- ///- /// Returns the path to the first config file with integration if found.- /// This helps detect the "configured but not restarted shell" state.- ///- /// The `cmd` parameter specifies the command name to look for (e.g., "wt" or "git-wt").- /// This ensures we only consider integration "configured" if it uses the same binary- /// we're running as - prevents confusion when users have multiple installs.- pub fn is_integration_configured(cmd: &str) -> Result<Option<PathBuf>, std::io::Error> {- let results = scan_for_detection_details(cmd)?;- Ok(results- .into_iter()- .find(|r| !r.matched_lines.is_empty())- .map(|r| r.path))- }-}--/// Shell integration configuration-pub struct ShellInit {- pub shell: Shell,- pub cmd: String,-}--impl ShellInit {- pub fn with_prefix(shell: Shell, cmd: String) -> Self {- Self { shell, cmd }- }-- /// Generate shell integration code (for `wt config shell init`)- pub fn generate(&self) -> Result<String, askama::Error> {- match self.shell {- Shell::Bash => {- let template = BashTemplate {- shell_name: self.shell.to_string(),- cmd: &self.cmd,- };- template.render()- }- Shell::Zsh => {- let template = ZshTemplate { cmd: &self.cmd };- template.render()- }- Shell::Fish => {- let template = FishTemplate { cmd: &self.cmd };- template.render()- }- Shell::PowerShell => {- let template = PowerShellTemplate { cmd: &self.cmd };- template.render()- }- }- }-- /// Generate fish wrapper code (for `wt config shell install fish`)- ///- /// This generates a minimal wrapper that sources the full function from the binary.- /// The wrapper file itself is static, but it loads the init output at runtime,- /// so users get updated behavior without reinstalling.- pub fn generate_fish_wrapper(&self) -> Result<String, askama::Error> {- let template = FishWrapperTemplate { cmd: &self.cmd };- template.render()- }-}--/// Bash shell template-#[derive(Template)]-#[template(path = "bash.sh", escape = "none")]-struct BashTemplate<'a> {- shell_name: String,- cmd: &'a str,-}--/// Zsh shell template-#[derive(Template)]-#[template(path = "zsh.zsh", escape = "none")]-struct ZshTemplate<'a> {- cmd: &'a str,-}--/// Fish shell template (full function for `wt config shell init fish`)-#[derive(Template)]-#[template(path = "fish.fish", escape = "none")]-struct FishTemplate<'a> {- cmd: &'a str,-}--/// Fish wrapper template (minimal wrapper for `functions/wt.fish`)-///-/// This wrapper is autoloaded by fish and sources the full function from the binary.-/// Unlike the full FishTemplate, this allows updates to worktrunk to automatically-/// provide the latest wrapper logic without requiring `wt config shell install`.-#[derive(Template)]-#[template(path = "fish_wrapper.fish", escape = "none")]-struct FishWrapperTemplate<'a> {- cmd: &'a str,-}--/// PowerShell template-#[derive(Template)]-#[template(path = "powershell.ps1", escape = "none")]-struct PowerShellTemplate<'a> {- cmd: &'a str,-}--/// Detect if user's zsh has compinit enabled by probing for 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.-///-/// This approach matches what other CLI tools (hugo, podman, dvc) recommend: detect-/// the state and advise users, rather than trying to auto-enable compinit.-///-/// Returns:-/// - `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)-pub fn detect_zsh_compinit() -> Option<bool> {- use std::process::{Command, Stdio};- use std::time::{Duration, Instant};-- // 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- }-- // Force compinit to be missing (for tests that expect the warning)- if std::env::var("WORKTRUNK_TEST_COMPINIT_MISSING").is_ok() {- 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__"#;-- log::debug!("$ zsh -ic '{}' (probe)", probe_cmd);-- let mut child = Command::new("zsh")- .arg("-ic")- .arg(probe_cmd)- .stdin(Stdio::null()) // Prevent compinit from prompting interactively- .stdout(Stdio::piped())- .stderr(Stdio::null()) // Suppress user's zsh startup messages- // Suppress zsh's "insecure directories" warning from compinit.- //- // When fpath contains directories with insecure permissions, compinit prompts:- // "zsh compinit: insecure directories, run compaudit for list."- // "Ignore insecure directories and continue [y] or abort compinit [n]?"- //- // This prompt goes to /dev/tty (not stderr), bypassing our stderr redirect.- //- // Worktrunk does NOT cause this warning - our shell init script doesn't modify- // fpath or call compinit. It only registers completions with `compdef` if the- // user has already set up compinit themselves. The warning appears because:- // 1. This probe runs `zsh -ic` which sources global configs like /etc/zsh/zshrc- // 2. Some environments (notably Ubuntu CI) have global configs that call compinit- // 3. Those environments may have insecure fpath directories- //- // 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")- // Prevent subprocesses from writing to the directive file- .env_remove(crate::shell_exec::DIRECTIVE_FILE_ENV_VAR)- .spawn()- .ok()?;-- let start = Instant::now();- let timeout = Duration::from_secs(2);-- loop {- match child.try_wait() {- Ok(Some(_status)) => {- // Process finished (exit status is always 0 due to || fallback in probe)- // wait_with_output() collects remaining stdout even after try_wait() succeeds- let output = child.wait_with_output().ok()?;- let stdout = String::from_utf8_lossy(&output.stdout);- return Some(stdout.contains("__WT_COMPINIT_YES__"));- }- Ok(None) => {- // Still running - check timeout- if start.elapsed() > timeout {- let _ = child.kill();- let _ = child.wait(); // Reap zombie process- return None;- }- std::thread::sleep(Duration::from_millis(20));- }- Err(_) => return None,- }- }-}--/// Extract executable name from a path, stripping `.exe` on Windows.-///-/// Uses `std::path::Path` for platform-native path handling:-/// - Unix: `/usr/bin/bash` -> "bash"-/// - Windows: `C:\Program Files\Git\usr\bin\bash.exe` -> "bash"-///-/// Only strips `.exe` extension (not other extensions like `.9` in `zsh-5.9`).-pub fn extract_filename_from_path(path: &str) -> Option<&str> {- let filename = std::path::Path::new(path).file_name()?.to_str()?;-- // Strip .exe extension (case-insensitive for Windows)- // Don't use file_stem() because it would strip version numbers like ".9" from "zsh-5.9"- // Handle all case variants: .exe, .EXE, .Exe, .eXe, etc.- if filename.len() > 4 && filename[filename.len() - 4..].eq_ignore_ascii_case(".exe") {- Some(&filename[..filename.len() - 4])- } else {- Some(filename)- }-}--/// Determine Shell variant from a shell name (without path or extension).-///-/// Handles versioned/prefixed binaries like `zsh-5.9` or `bash5`-/// by checking if the name starts with a known shell.-fn shell_from_name(shell_name: &str) -> Option<Shell> {- // Try exact match first- if let Ok(shell) = shell_name.parse() {- return Some(shell);- }-- // Handle versioned/prefixed binaries (e.g., "zsh-5.9", "bash5")- // Check if shell name starts with a known shell- let name_lower = shell_name.to_lowercase();- if name_lower.starts_with("zsh") {- Some(Shell::Zsh)- } else if name_lower.starts_with("bash") {- Some(Shell::Bash)- } else if name_lower.starts_with("fish") {- Some(Shell::Fish)- } else if name_lower.starts_with("pwsh") || name_lower.starts_with("powershell") {- Some(Shell::PowerShell)- } else {- None- }-}--/// Get the current shell from `$SHELL` environment variable.-///-/// Returns `None` if `$SHELL` is not set or doesn't match a known shell.-/// Handles versioned/prefixed binaries like `/nix/store/.../zsh-5.9` or `bash5`-/// by checking if the name starts with a known shell.-///-/// Works on both Unix and Windows:-/// - Unix: `/usr/bin/bash` -> Bash-/// - Windows Git Bash: `C:\Program Files\Git\usr\bin\bash.exe` -> Bash-pub fn current_shell() -> Option<Shell> {- let shell_path = std::env::var("SHELL").ok()?;- let shell_name = extract_filename_from_path(&shell_path)?;- shell_from_name(shell_name)-}-#[cfg(test)]mod tests {use super::*;use rstest::rstest;- #[test]- fn test_shell_from_str() {- assert!(matches!("bash".parse::<Shell>(), Ok(Shell::Bash)));- assert!(matches!("BASH".parse::<Shell>(), Ok(Shell::Bash)));- assert!(matches!("fish".parse::<Shell>(), Ok(Shell::Fish)));- assert!(matches!("zsh".parse::<Shell>(), Ok(Shell::Zsh)));- assert!(matches!(- "powershell".parse::<Shell>(),- Ok(Shell::PowerShell)- ));- assert!(matches!(- "POWERSHELL".parse::<Shell>(),- Ok(Shell::PowerShell)- ));- assert!("invalid".parse::<Shell>().is_err());- }-- #[test]- fn test_shell_display() {- assert_eq!(Shell::Bash.to_string(), "bash");- assert_eq!(Shell::Fish.to_string(), "fish");- assert_eq!(Shell::Zsh.to_string(), "zsh");- assert_eq!(Shell::PowerShell.to_string(), "powershell");- }-- // ==========================================================================- // Path extraction tests (Issue #348)- // ==========================================================================-- #[rstest]- #[case::just_name("bash", Some("bash"))]- #[case::just_name_exe("bash.exe", Some("bash"))]- #[case::mixed_case_exe_title("bash.Exe", Some("bash"))]- #[case::mixed_case_exe_upper("bash.EXE", Some("bash"))]- #[case::mixed_case_exe_camel("bash.eXe", Some("bash"))]- #[case::empty("", None)]- fn test_extract_filename_from_path_common(#[case] path: &str, #[case] expected: Option<&str>) {- assert_eq!(extract_filename_from_path(path), expected);- }-- #[cfg(unix)]- #[rstest]- #[case::unix_bash("/usr/bin/bash", Some("bash"))]- #[case::unix_zsh("/bin/zsh", Some("zsh"))]- #[case::unix_fish("/usr/local/bin/fish", Some("fish"))]- #[case::nix_versioned("/nix/store/abc123/zsh-5.9", Some("zsh-5.9"))]- fn test_extract_filename_from_path_unix(#[case] path: &str, #[case] expected: Option<&str>) {- assert_eq!(extract_filename_from_path(path), expected);- }-- #[cfg(windows)]- #[rstest]- #[case::windows_git_bash(r"C:\Program Files\Git\usr\bin\bash.exe", Some("bash"))]- #[case::windows_powershell(- r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",- Some("powershell")- )]- #[case::windows_pwsh(r"C:\Program Files\PowerShell\7\pwsh.exe", Some("pwsh"))]- #[case::windows_zsh(r"C:\msys64\usr\bin\zsh.exe", Some("zsh"))]- #[case::uppercase_exe(r"C:\WINDOWS\SYSTEM32\BASH.EXE", Some("BASH"))]- fn test_extract_filename_from_path_windows(#[case] path: &str, #[case] expected: Option<&str>) {- assert_eq!(extract_filename_from_path(path), expected);- }-- /// Issue #348: Windows Git Bash shell detection- ///- /// Git Bash sets $SHELL to Windows-style paths like:- /// `C:\Program Files\Git\usr\bin\bash.exe`- ///- /// This test verifies the full path-to-shell detection flow works on Windows.- #[cfg(windows)]- #[rstest]- #[case::git_bash(r"C:\Program Files\Git\usr\bin\bash.exe", Shell::Bash)]- #[case::msys2_zsh(r"C:\msys64\usr\bin\zsh.exe", Shell::Zsh)]- #[case::powershell(- r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",- Shell::PowerShell- )]- #[case::pwsh(r"C:\Program Files\PowerShell\7\pwsh.exe", Shell::PowerShell)]- fn test_issue_348_windows_shell_detection(#[case] shell_path: &str, #[case] expected: Shell) {- // This is the exact flow that failed before the fix:- // 1. extract_filename_from_path() extracts "bash" from Windows path- // 2. shell_from_name() maps "bash" to Shell::Bash- let shell_name = extract_filename_from_path(shell_path)- .expect("should extract filename from Windows path");- let detected =- shell_from_name(shell_name).expect("should detect shell from extracted name");- assert_eq!(detected, expected);- }-- #[rstest]- #[case::bash("bash", Some(Shell::Bash))]- #[case::bash_versioned("bash5", Some(Shell::Bash))]- #[case::zsh("zsh", Some(Shell::Zsh))]- #[case::zsh_versioned("zsh-5.9", Some(Shell::Zsh))]- #[case::fish("fish", Some(Shell::Fish))]- #[case::powershell("powershell", Some(Shell::PowerShell))]- #[case::pwsh("pwsh", Some(Shell::PowerShell))]- #[case::pwsh_preview("pwsh-preview", Some(Shell::PowerShell))]- #[case::unknown("tcsh", None)]- #[case::unknown_csh("csh", None)]- fn test_shell_from_name(#[case] name: &str, #[case] expected: Option<Shell>) {- assert_eq!(shell_from_name(name), expected);- }-- #[test]- fn test_shell_config_line() {- insta::assert_snapshot!("config_line_bash", Shell::Bash.config_line("wt"));- insta::assert_snapshot!("config_line_zsh", Shell::Zsh.config_line("wt"));- insta::assert_snapshot!("config_line_fish", Shell::Fish.config_line("wt"));- insta::assert_snapshot!(- "config_line_powershell",- Shell::PowerShell.config_line("wt")- );- }-- #[test]- fn test_config_line_uses_custom_prefix() {- // When using a custom prefix, the generated shell config line must use that prefix- // throughout - both in the command check AND the command invocation.- // This prevents the bug where we check for `git-wt` but then call `wt`.- insta::assert_snapshot!("config_line_bash_custom", Shell::Bash.config_line("git-wt"));- insta::assert_snapshot!("config_line_zsh_custom", Shell::Zsh.config_line("git-wt"));- insta::assert_snapshot!("config_line_fish_custom", Shell::Fish.config_line("git-wt"));- insta::assert_snapshot!(- "config_line_powershell_custom",- Shell::PowerShell.config_line("git-wt")- );- }-- #[test]- fn test_shell_init_generate() {- for shell in [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell] {- let init = ShellInit::with_prefix(shell, "wt".to_string());- let output = init.generate().expect("Failed to generate");- insta::assert_snapshot!(format!("init_{shell}"), output);- }- }-- #[test]- fn test_shell_config_paths_returns_paths() {- // All shells should return at least one config path- let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];- for shell in shells {- let result = shell.config_paths("wt");- assert!(result.is_ok(), "Failed to get config paths for {:?}", shell);- let paths = result.unwrap();- assert!(- !paths.is_empty(),- "No config paths returned for {:?}",- shell- );- }- }-- #[test]- fn test_shell_completion_path_returns_path() {- // All shells should return a completion path- let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];- for shell in shells {- let result = shell.completion_path("wt");- assert!(- result.is_ok(),- "Failed to get completion path for {:?}",- shell- );- let path = result.unwrap();- assert!(- !path.as_os_str().is_empty(),- "Empty completion path for {:?}",- shell- );- }- }-- #[test]- fn test_shell_config_paths_with_custom_prefix() {- // Test that custom prefix affects the paths where appropriate- let prefix = "custom-wt";-- // Fish config path should include prefix in filename- let fish_paths = Shell::Fish.config_paths(prefix).unwrap();- assert!(- fish_paths[0]- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains("custom-wt.fish")),- "Fish config should include prefix in filename"- );-- // Bash and Zsh config paths are fixed (not affected by prefix)- let bash_paths = Shell::Bash.config_paths(prefix).unwrap();- assert!(- bash_paths[0]- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains(".bashrc")),- "Bash config should be .bashrc"- );-- let zsh_paths = Shell::Zsh.config_paths(prefix).unwrap();- assert!(- zsh_paths[0]- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains(".zshrc")),- "Zsh config should be .zshrc"- );- }-- #[test]- fn test_shell_completion_path_with_custom_prefix() {- let prefix = "my-prefix";-- // Bash completion should include prefix in path- let bash_path = Shell::Bash.completion_path(prefix).unwrap();- assert!(- bash_path- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains("my-prefix")),- "Bash completion should include prefix"- );-- // Fish completion should include prefix in filename- let fish_path = Shell::Fish.completion_path(prefix).unwrap();- assert!(- fish_path- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains("my-prefix.fish")),- "Fish completion should include prefix in filename"- );-- // Zsh completion should include prefix- let zsh_path = Shell::Zsh.completion_path(prefix).unwrap();- assert!(- zsh_path- .file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.contains("_my-prefix")),- "Zsh completion should include underscore prefix"- );- }-- #[test]- fn test_shell_init_with_custom_prefix() {- let init = ShellInit::with_prefix(Shell::Bash, "custom".to_string());- insta::assert_snapshot!(init.generate().expect("Should generate with custom prefix"));- }-- /// Verify that `config_line()` generates lines that- /// `is_shell_integration_line()` can detect.- ///- /// This prevents install and detection from drifting out of sync.- /// Note: .exe variants are not included because `binary_name()` strips- /// the .exe suffix on Windows (MSYS2/Git Bash handles the resolution).- #[rstest]- fn test_config_line_detected_by_is_shell_integration_line(- #[values(Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell)] shell: Shell,- #[values("wt", "git-wt")] prefix: &str,- ) {- let line = shell.config_line(prefix);- assert!(- is_shell_integration_line(&line, prefix),- "{shell} config_line({prefix:?}) not detected:\n {line}"- );- }-// ==========================================================================// Detection tests: eval/source lines// ==========================================================================@@ -1613,39 +912,6 @@ mod tests {assert_not_detects(line, "git-wt", "prefixed 'git wt' should NOT match git-wt");}- // ------------------------------------------------------------------------- // Summary of confirmed ACCEPTABLE FALSE NEGATIVES:- // (These are documented limitations, not bugs to fix)- //- // 1. `. <(cmd ...)` - POSIX dot command (rare, users can use `source`)- // 2. `. =(cmd ...)` - zsh =() substitution (rare)- // 3. `iex (cmd ...)` - PowerShell iex alias (would need to add `iex` check)- // 4. `/path/to/wt` - path-prefixed binary (would need path parsing)- // 5. `~/path/to/wt` - home-relative path (would need path parsing)- // 6. `$HOME/path/wt` - env var path (would need path parsing)- // 7. Line continuations (`\` or backtick) - architectural limitation- // 8. Heredoc context (`: <<'EOF'`) - architectural limitation- //- // Summary of ACCEPTABLE FALSE POSITIVE risks:- // 9. PowerShell block comments `<# #>` - rare in shell configs- // 10. Subshell `(eval ...)` - detected correctly but doesn't persist- //- // FIXED in this version (were bugs, now correct):- // 11. `my-git-wt` no longer matches `git-wt`- // 12. `agit wt` no longer matches `git wt`- //- // By design (not bugs):- // 13. `git wt` (double space) - only single space "git wt" is valid- //- // IMPACT OF FALSE NEGATIVES:- // Detection is ONLY used when shell wrapper is NOT active. Once the user- // restarts their shell, WORKTRUNK_DIRECTIVE_FILE is set and no detection- // is needed. False negatives only affect:- // - `wt config show` status display- // - Warning message before shell restart ("not installed" vs "restart to activate")- // - `wt config shell uninstall` (lines might not be found)- // -------------------------------------------------------------------------// ==========================================================================// ALIAS BYPASS DETECTION TESTS (Issue #348)// ==========================================================================diff --git a/src/shell/mod.rs b/src/shell/mod.rsnew file mode 100644index 000000000..959827960--- /dev/null+++ b/src/shell/mod.rs@@ -0,0 +1,398 @@+//! Shell integration for worktrunk.+//!+//! This module provides:+//! - Shell detection and configuration path discovery+//! - Shell integration line detection for config files+//! - Shell initialization code generation (bash, zsh, fish, powershell)++mod detection;+mod paths;+mod utils;++use askama::Template;++// Re-export public types and functions+pub use detection::{+ BypassAlias, DetectedLine, FileDetectionResult, is_shell_integration_line,+ scan_for_detection_details,+};+pub use paths::{completion_path, config_paths, legacy_fish_conf_d_path};+pub use utils::{current_shell, detect_zsh_compinit, extract_filename_from_path};++/// Supported shells+///+/// Currently supported: bash, fish, zsh, powershell+///+/// On Windows, Git Bash users should use `bash` for shell integration.+/// PowerShell integration is available for native Windows users without Git Bash.+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, strum::Display, strum::EnumString)]+#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]+pub enum Shell {+ Bash,+ Fish,+ Zsh,+ #[strum(serialize = "powershell")]+ #[clap(name = "powershell")]+ PowerShell,+}++impl Shell {+ /// Returns the config file paths for this shell.+ ///+ /// The `cmd` parameter affects the Fish functions filename (e.g., `wt.fish` or `git-wt.fish`).+ /// Returns paths in order of preference. The first existing file should be used.+ pub fn config_paths(&self, cmd: &str) -> Result<Vec<std::path::PathBuf>, std::io::Error> {+ paths::config_paths(*self, cmd)+ }++ /// Returns the legacy fish conf.d path for cleanup purposes.+ ///+ /// Previously, fish shell integration was installed to `~/.config/fish/conf.d/{cmd}.fish`.+ /// This caused issues with Homebrew PATH setup (see issue #566). We now install to+ /// `functions/{cmd}.fish` instead. This method returns the legacy path so install/uninstall+ /// can clean it up.+ pub fn legacy_fish_conf_d_path(cmd: &str) -> Result<std::path::PathBuf, std::io::Error> {+ paths::legacy_fish_conf_d_path(cmd)+ }++ /// Returns the path to the native completion directory for this shell.+ ///+ /// The `cmd` parameter affects the completion filename (e.g., `wt.fish` or `git-wt.fish`).+ ///+ /// Note: Bash and Zsh use inline lazy completions in the init script.+ /// Only Fish uses a separate completion file at ~/.config/fish/completions/+ /// (installed by `wt config shell install`) that uses $WORKTRUNK_BIN to bypass+ /// the shell function wrapper.+ pub fn completion_path(&self, cmd: &str) -> Result<std::path::PathBuf, std::io::Error> {+ paths::completion_path(*self, cmd)+ }++ /// Returns the line to add to the config file for shell integration.+ ///+ /// The `cmd` parameter specifies the command name (e.g., `wt` or `git-wt`).+ /// All shells use a conditional wrapper to avoid errors when the command doesn't exist.+ ///+ /// Note: The generated line does not include `--cmd` because `binary_name()` already+ /// detects the command name from argv\[0\] at runtime.+ pub fn config_line(&self, cmd: &str) -> String {+ match self {+ Self::Bash | Self::Zsh => {+ format!(+ "if command -v {cmd} >/dev/null 2>&1; then eval \"$(command {cmd} config shell init {})\"; fi",+ self+ )+ }+ Self::Fish => {+ format!(+ "if type -q {cmd}; command {cmd} config shell init {} | source; end",+ self+ )+ }+ Self::PowerShell => {+ format!(+ "if (Get-Command {cmd} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {cmd} config shell init powershell) }}",+ )+ }+ }+ }++ /// Check if shell integration is configured for the given command name.+ ///+ /// Returns the path to the first config file with integration if found.+ /// This helps detect the "configured but not restarted shell" state.+ ///+ /// The `cmd` parameter specifies the command name to look for (e.g., "wt" or "git-wt").+ /// This ensures we only consider integration "configured" if it uses the same binary+ /// we're running as - prevents confusion when users have multiple installs.+ pub fn is_integration_configured(+ cmd: &str,+ ) -> Result<Option<std::path::PathBuf>, std::io::Error> {+ let results = scan_for_detection_details(cmd)?;+ Ok(results+ .into_iter()+ .find(|r| !r.matched_lines.is_empty())+ .map(|r| r.path))+ }+}++/// Shell integration configuration+pub struct ShellInit {+ pub shell: Shell,+ pub cmd: String,+}++impl ShellInit {+ pub fn with_prefix(shell: Shell, cmd: String) -> Self {+ Self { shell, cmd }+ }++ /// Generate shell integration code (for `wt config shell init`)+ pub fn generate(&self) -> Result<String, askama::Error> {+ match self.shell {+ Shell::Bash => {+ let template = BashTemplate {+ shell_name: self.shell.to_string(),+ cmd: &self.cmd,+ };+ template.render()+ }+ Shell::Zsh => {+ let template = ZshTemplate { cmd: &self.cmd };+ template.render()+ }+ Shell::Fish => {+ let template = FishTemplate { cmd: &self.cmd };+ template.render()+ }+ Shell::PowerShell => {+ let template = PowerShellTemplate { cmd: &self.cmd };+ template.render()+ }+ }+ }++ /// Generate fish wrapper code (for `wt config shell install fish`)+ ///+ /// This generates a minimal wrapper that sources the full function from the binary.+ /// The wrapper file itself is static, but it loads the init output at runtime,+ /// so users get updated behavior without reinstalling.+ pub fn generate_fish_wrapper(&self) -> Result<String, askama::Error> {+ let template = FishWrapperTemplate { cmd: &self.cmd };+ template.render()+ }+}++/// Bash shell template+#[derive(Template)]+#[template(path = "bash.sh", escape = "none")]+struct BashTemplate<'a> {+ shell_name: String,+ cmd: &'a str,+}++/// Zsh shell template+#[derive(Template)]+#[template(path = "zsh.zsh", escape = "none")]+struct ZshTemplate<'a> {+ cmd: &'a str,+}++/// Fish shell template (full function for `wt config shell init fish`)+#[derive(Template)]+#[template(path = "fish.fish", escape = "none")]+struct FishTemplate<'a> {+ cmd: &'a str,+}++/// Fish wrapper template (minimal wrapper for `functions/wt.fish`)+///+/// This wrapper is autoloaded by fish and sources the full function from the binary.+/// Unlike the full FishTemplate, this allows updates to worktrunk to automatically+/// provide the latest wrapper logic without requiring `wt config shell install`.+#[derive(Template)]+#[template(path = "fish_wrapper.fish", escape = "none")]+struct FishWrapperTemplate<'a> {+ cmd: &'a str,+}++/// PowerShell template+#[derive(Template)]+#[template(path = "powershell.ps1", escape = "none")]+struct PowerShellTemplate<'a> {+ cmd: &'a str,+}++#[cfg(test)]+mod tests {+ use super::*;+ use rstest::rstest;++ #[test]+ fn test_shell_from_str() {+ assert!(matches!("bash".parse::<Shell>(), Ok(Shell::Bash)));+ assert!(matches!("BASH".parse::<Shell>(), Ok(Shell::Bash)));+ assert!(matches!("fish".parse::<Shell>(), Ok(Shell::Fish)));+ assert!(matches!("zsh".parse::<Shell>(), Ok(Shell::Zsh)));+ assert!(matches!(+ "powershell".parse::<Shell>(),+ Ok(Shell::PowerShell)+ ));+ assert!(matches!(+ "POWERSHELL".parse::<Shell>(),+ Ok(Shell::PowerShell)+ ));+ assert!("invalid".parse::<Shell>().is_err());+ }++ #[test]+ fn test_shell_display() {+ assert_eq!(Shell::Bash.to_string(), "bash");+ assert_eq!(Shell::Fish.to_string(), "fish");+ assert_eq!(Shell::Zsh.to_string(), "zsh");+ assert_eq!(Shell::PowerShell.to_string(), "powershell");+ }++ #[test]+ fn test_shell_config_line() {+ insta::assert_snapshot!("config_line_bash", Shell::Bash.config_line("wt"));+ insta::assert_snapshot!("config_line_zsh", Shell::Zsh.config_line("wt"));+ insta::assert_snapshot!("config_line_fish", Shell::Fish.config_line("wt"));+ insta::assert_snapshot!(+ "config_line_powershell",+ Shell::PowerShell.config_line("wt")+ );+ }++ #[test]+ fn test_config_line_uses_custom_prefix() {+ // When using a custom prefix, the generated shell config line must use that prefix+ // throughout - both in the command check AND the command invocation.+ // This prevents the bug where we check for `git-wt` but then call `wt`.+ insta::assert_snapshot!("config_line_bash_custom", Shell::Bash.config_line("git-wt"));+ insta::assert_snapshot!("config_line_zsh_custom", Shell::Zsh.config_line("git-wt"));+ insta::assert_snapshot!("config_line_fish_custom", Shell::Fish.config_line("git-wt"));+ insta::assert_snapshot!(+ "config_line_powershell_custom",+ Shell::PowerShell.config_line("git-wt")+ );+ }++ #[test]+ fn test_shell_init_generate() {+ for shell in [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell] {+ let init = ShellInit::with_prefix(shell, "wt".to_string());+ let output = init.generate().expect("Failed to generate");+ insta::assert_snapshot!(format!("init_{shell}"), output);+ }+ }++ #[test]+ fn test_shell_config_paths_returns_paths() {+ // All shells should return at least one config path+ let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];+ for shell in shells {+ let result = shell.config_paths("wt");+ assert!(result.is_ok(), "Failed to get config paths for {:?}", shell);+ let paths = result.unwrap();+ assert!(+ !paths.is_empty(),+ "No config paths returned for {:?}",+ shell+ );+ }+ }++ #[test]+ fn test_shell_completion_path_returns_path() {+ // All shells should return a completion path+ let shells = [Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];+ for shell in shells {+ let result = shell.completion_path("wt");+ assert!(+ result.is_ok(),+ "Failed to get completion path for {:?}",+ shell+ );+ let path = result.unwrap();+ assert!(+ !path.as_os_str().is_empty(),+ "Empty completion path for {:?}",+ shell+ );+ }+ }++ #[test]+ fn test_shell_config_paths_with_custom_prefix() {+ // Test that custom prefix affects the paths where appropriate+ let prefix = "custom-wt";++ // Fish config path should include prefix in filename+ let fish_paths = Shell::Fish.config_paths(prefix).unwrap();+ assert!(+ fish_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("custom-wt.fish")),+ "Fish config should include prefix in filename"+ );++ // Bash and Zsh config paths are fixed (not affected by prefix)+ let bash_paths = Shell::Bash.config_paths(prefix).unwrap();+ assert!(+ bash_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains(".bashrc")),+ "Bash config should be .bashrc"+ );++ let zsh_paths = Shell::Zsh.config_paths(prefix).unwrap();+ assert!(+ zsh_paths[0]+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains(".zshrc")),+ "Zsh config should be .zshrc"+ );+ }++ #[test]+ fn test_shell_completion_path_with_custom_prefix() {+ let prefix = "my-prefix";++ // Bash completion should include prefix in path+ let bash_path = Shell::Bash.completion_path(prefix).unwrap();+ assert!(+ bash_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("my-prefix")),+ "Bash completion should include prefix"+ );++ // Fish completion should include prefix in filename+ let fish_path = Shell::Fish.completion_path(prefix).unwrap();+ assert!(+ fish_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("my-prefix.fish")),+ "Fish completion should include prefix in filename"+ );++ // Zsh completion should include prefix+ let zsh_path = Shell::Zsh.completion_path(prefix).unwrap();+ assert!(+ zsh_path+ .file_name()+ .and_then(|n| n.to_str())+ .is_some_and(|n| n.contains("_my-prefix")),+ "Zsh completion should include underscore prefix"+ );+ }++ #[test]+ fn test_shell_init_with_custom_prefix() {+ let init = ShellInit::with_prefix(Shell::Bash, "custom".to_string());+ insta::assert_snapshot!(init.generate().expect("Should generate with custom prefix"));+ }++ /// Verify that `config_line()` generates lines that+ /// `is_shell_integration_line()` can detect.+ ///+ /// This prevents install and detection from drifting out of sync.+ /// Note: .exe variants are not included because `binary_name()` strips+ /// the .exe suffix on Windows (MSYS2/Git Bash handles the resolution).+ #[rstest]+ fn test_config_line_detected_by_is_shell_integration_line(+ #[values(Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell)] shell: Shell,+ #[values("wt", "git-wt")] prefix: &str,+ ) {+ let line = shell.config_line(prefix);+ assert!(+ is_shell_integration_line(&line, prefix),+ "{shell} config_line({prefix:?}) not detected:\n {line}"+ );+ }+}diff --git a/src/shell/paths.rs b/src/shell/paths.rsnew file mode 100644index 000000000..77e280827--- /dev/null+++ b/src/shell/paths.rs@@ -0,0 +1,142 @@+//! Shell configuration and completion paths.+//!+//! This module handles locating shell configuration files (e.g., `.bashrc`, `.zshrc`)+//! and completion directories for different shells.++use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};+use std::path::PathBuf;++use crate::path::home_dir;++/// Get the user's home directory or return an error.+pub fn home_dir_required() -> Result<PathBuf, std::io::Error> {+ home_dir().ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::NotFound,+ "Cannot determine home directory. Set $HOME (Unix) or $USERPROFILE (Windows)",+ )+ })+}++/// Get PowerShell profile paths in order of preference.+/// On Windows, returns both PowerShell Core (7+) and Windows PowerShell (5.1) paths.+/// On Unix, uses the conventional ~/.config/powershell location.+pub fn powershell_profile_paths(home: &std::path::Path) -> Vec<PathBuf> {+ #[cfg(windows)]+ {+ // Use platform-specific Documents path (handles non-English Windows)+ let docs = dirs::document_dir().unwrap_or_else(|| home.join("Documents"));+ vec![+ // PowerShell Core 6+ (pwsh.exe) - preferred+ docs.join("PowerShell")+ .join("Microsoft.PowerShell_profile.ps1"),+ // Windows PowerShell 5.1 (powershell.exe) - legacy but still common+ docs.join("WindowsPowerShell")+ .join("Microsoft.PowerShell_profile.ps1"),+ ]+ }+ #[cfg(not(windows))]+ {+ vec![+ home.join(".config")+ .join("powershell")+ .join("Microsoft.PowerShell_profile.ps1"),+ ]+ }+}++/// Returns the config file paths for a shell.+///+/// The `cmd` parameter affects the Fish functions filename (e.g., `wt.fish` or `git-wt.fish`).+/// Returns paths in order of preference. The first existing file should be used.+pub fn config_paths(shell: super::Shell, cmd: &str) -> Result<Vec<PathBuf>, std::io::Error> {+ let home = home_dir_required()?;++ Ok(match shell {+ super::Shell::Bash => {+ // Use .bashrc - sourced by interactive shells (login shells should source .bashrc)+ vec![home.join(".bashrc")]+ }+ super::Shell::Zsh => {+ let zdotdir = std::env::var("ZDOTDIR")+ .map(PathBuf::from)+ .unwrap_or_else(|_| home.clone());+ vec![zdotdir.join(".zshrc")]+ }+ super::Shell::Fish => {+ // For fish, we write to functions/ which is autoloaded on first use.+ // This ensures PATH is fully configured before our function loads,+ // fixing the issue where Homebrew PATH setup in config.fish runs+ // after conf.d/ files. See: https://github.com/max-sixty/worktrunk/issues/566+ vec![+ home.join(".config")+ .join("fish")+ .join("functions")+ .join(format!("{}.fish", cmd)),+ ]+ }+ super::Shell::PowerShell => powershell_profile_paths(&home),+ })+}++/// Returns the legacy fish conf.d path for cleanup purposes.+///+/// Previously, fish shell integration was installed to `~/.config/fish/conf.d/{cmd}.fish`.+/// This caused issues with Homebrew PATH setup (see issue #566). We now install to+/// `functions/{cmd}.fish` instead. This method returns the legacy path so install/uninstall+/// can clean it up.+pub fn legacy_fish_conf_d_path(cmd: &str) -> Result<PathBuf, std::io::Error> {+ let home = home_dir_required()?;+ Ok(home+ .join(".config")+ .join("fish")+ .join("conf.d")+ .join(format!("{}.fish", cmd)))+}++/// Returns the path to the native completion directory for a shell.+///+/// The `cmd` parameter affects the completion filename (e.g., `wt.fish` or `git-wt.fish`).+///+/// Note: Bash and Zsh use inline lazy completions in the init script.+/// Only Fish uses a separate completion file at ~/.config/fish/completions/+/// (installed by `wt config shell install`) that uses $WORKTRUNK_BIN to bypass+/// the shell function wrapper.+pub fn completion_path(shell: super::Shell, cmd: &str) -> Result<PathBuf, std::io::Error> {+ let home = home_dir_required()?;++ // Use etcetera for XDG-compliant paths when available+ let strategy = choose_base_strategy().ok();++ Ok(match shell {+ super::Shell::Bash => {+ // XDG_DATA_HOME defaults to ~/.local/share+ let data_home = strategy+ .as_ref()+ .map(|s| s.data_dir())+ .unwrap_or_else(|| home.join(".local").join("share"));+ data_home+ .join("bash-completion")+ .join("completions")+ .join(cmd)+ }+ super::Shell::Zsh => home.join(".zfunc").join(format!("_{}", cmd)),+ super::Shell::Fish => {+ // XDG_CONFIG_HOME defaults to ~/.config+ let config_home = strategy+ .as_ref()+ .map(|s| s.config_dir())+ .unwrap_or_else(|| home.join(".config"));+ config_home+ .join("fish")+ .join("completions")+ .join(format!("{}.fish", cmd))+ }+ super::Shell::PowerShell => {+ // PowerShell doesn't use a separate completion file - completions are+ // registered inline in the profile using Register-ArgumentCompleter+ // Return a dummy path that won't be used+ home.join(format!(".{}-powershell-completions", cmd))+ }+ })+}diff --git a/src/snapshots/worktrunk__shell__tests__config_line_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_bash.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_bash.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_bash.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_bash_custom.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_bash_custom.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_bash_custom.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_bash_custom.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_fish.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_fish.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_fish.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_fish_custom.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_fish_custom.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_fish_custom.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_fish_custom.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_powershell.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_powershell.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_powershell_custom.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_zsh.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_zsh.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_zsh.snapdiff --git a/src/snapshots/worktrunk__shell__tests__config_line_zsh_custom.snap b/src/shell/snapshots/worktrunk__shell__tests__config_line_zsh_custom.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__config_line_zsh_custom.snaprename to src/shell/snapshots/worktrunk__shell__tests__config_line_zsh_custom.snapdiff --git a/src/snapshots/worktrunk__shell__tests__init_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__init_bash.snaprename to src/shell/snapshots/worktrunk__shell__tests__init_bash.snapdiff --git a/src/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__init_fish.snaprename to src/shell/snapshots/worktrunk__shell__tests__init_fish.snapdiff --git a/src/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__init_powershell.snaprename to src/shell/snapshots/worktrunk__shell__tests__init_powershell.snapdiff --git a/src/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__init_zsh.snaprename to src/shell/snapshots/worktrunk__shell__tests__init_zsh.snapdiff --git a/src/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snapsimilarity index 100%rename from src/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snaprename to src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snapdiff --git a/src/shell/utils.rs b/src/shell/utils.rsnew file mode 100644index 000000000..32772f902--- /dev/null+++ b/src/shell/utils.rs@@ -0,0 +1,244 @@+//! Shell detection and utility functions.+//!+//! This module provides utilities for detecting the current shell, extracting+//! shell names from paths, and probing shell configuration state.++use super::Shell;++/// Extract executable name from a path, stripping `.exe` on Windows.+///+/// Uses `std::path::Path` for platform-native path handling:+/// - Unix: `/usr/bin/bash` -> "bash"+/// - Windows: `C:\Program Files\Git\usr\bin\bash.exe` -> "bash"+///+/// Only strips `.exe` extension (not other extensions like `.9` in `zsh-5.9`).+pub fn extract_filename_from_path(path: &str) -> Option<&str> {+ let filename = std::path::Path::new(path).file_name()?.to_str()?;++ // Strip .exe extension (case-insensitive for Windows)+ // Don't use file_stem() because it would strip version numbers like ".9" from "zsh-5.9"+ // Handle all case variants: .exe, .EXE, .Exe, .eXe, etc.+ if filename.len() > 4 && filename[filename.len() - 4..].eq_ignore_ascii_case(".exe") {+ Some(&filename[..filename.len() - 4])+ } else {+ Some(filename)+ }+}++/// Determine Shell variant from a shell name (without path or extension).+///+/// Handles versioned/prefixed binaries like `zsh-5.9` or `bash5`+/// by checking if the name starts with a known shell.+pub fn shell_from_name(shell_name: &str) -> Option<Shell> {+ // Try exact match first+ if let Ok(shell) = shell_name.parse() {+ return Some(shell);+ }++ // Handle versioned/prefixed binaries (e.g., "zsh-5.9", "bash5")+ // Check if shell name starts with a known shell+ let name_lower = shell_name.to_lowercase();+ if name_lower.starts_with("zsh") {+ Some(Shell::Zsh)+ } else if name_lower.starts_with("bash") {+ Some(Shell::Bash)+ } else if name_lower.starts_with("fish") {+ Some(Shell::Fish)+ } else if name_lower.starts_with("pwsh") || name_lower.starts_with("powershell") {+ Some(Shell::PowerShell)+ } else {+ None+ }+}++/// Get the current shell from `$SHELL` environment variable.+///+/// Returns `None` if `$SHELL` is not set or doesn't match a known shell.+/// Handles versioned/prefixed binaries like `/nix/store/.../zsh-5.9` or `bash5`+/// by checking if the name starts with a known shell.+///+/// Works on both Unix and Windows:+/// - Unix: `/usr/bin/bash` -> Bash+/// - Windows Git Bash: `C:\Program Files\Git\usr\bin\bash.exe` -> Bash+pub fn current_shell() -> Option<Shell> {+ let shell_path = std::env::var("SHELL").ok()?;+ let shell_name = extract_filename_from_path(&shell_path)?;+ shell_from_name(shell_name)+}++/// Detect if user's zsh has compinit enabled by probing for 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.+///+/// This approach matches what other CLI tools (hugo, podman, dvc) recommend: detect+/// the state and advise users, rather than trying to auto-enable compinit.+///+/// Returns:+/// - `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)+pub fn detect_zsh_compinit() -> Option<bool> {+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};++ // 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+ }++ // Force compinit to be missing (for tests that expect the warning)+ if std::env::var("WORKTRUNK_TEST_COMPINIT_MISSING").is_ok() {+ 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__"#;++ log::debug!("$ zsh -ic '{}' (probe)", probe_cmd);++ let mut child = Command::new("zsh")+ .arg("-ic")+ .arg(probe_cmd)+ .stdin(Stdio::null()) // Prevent compinit from prompting interactively+ .stdout(Stdio::piped())+ .stderr(Stdio::null()) // Suppress user's zsh startup messages+ // Suppress zsh's "insecure directories" warning from compinit.+ //+ // When fpath contains directories with insecure permissions, compinit prompts:+ // "zsh compinit: insecure directories, run compaudit for list."+ // "Ignore insecure directories and continue [y] or abort compinit [n]?"+ //+ // This prompt goes to /dev/tty (not stderr), bypassing our stderr redirect.+ //+ // Worktrunk does NOT cause this warning - our shell init script doesn't modify+ // fpath or call compinit. It only registers completions with `compdef` if the+ // user has already set up compinit themselves. The warning appears because:+ // 1. This probe runs `zsh -ic` which sources global configs like /etc/zsh/zshrc+ // 2. Some environments (notably Ubuntu CI) have global configs that call compinit+ // 3. Those environments may have insecure fpath directories+ //+ // 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")+ // Prevent subprocesses from writing to the directive file+ .env_remove(crate::shell_exec::DIRECTIVE_FILE_ENV_VAR)+ .spawn()+ .ok()?;++ let start = Instant::now();+ let timeout = Duration::from_secs(2);++ loop {+ match child.try_wait() {+ Ok(Some(_status)) => {+ // Process finished (exit status is always 0 due to || fallback in probe)+ // wait_with_output() collects remaining stdout even after try_wait() succeeds+ let output = child.wait_with_output().ok()?;+ let stdout = String::from_utf8_lossy(&output.stdout);+ return Some(stdout.contains("__WT_COMPINIT_YES__"));+ }+ Ok(None) => {+ // Still running - check timeout+ if start.elapsed() > timeout {+ let _ = child.kill();+ let _ = child.wait(); // Reap zombie process+ return None;+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ Err(_) => return None,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use rstest::rstest;++ // ==========================================================================+ // Path extraction tests (Issue #348)+ // ==========================================================================++ #[rstest]+ #[case::just_name("bash", Some("bash"))]+ #[case::just_name_exe("bash.exe", Some("bash"))]+ #[case::mixed_case_exe_title("bash.Exe", Some("bash"))]+ #[case::mixed_case_exe_upper("bash.EXE", Some("bash"))]+ #[case::mixed_case_exe_camel("bash.eXe", Some("bash"))]+ #[case::empty("", None)]+ fn test_extract_filename_from_path_common(#[case] path: &str, #[case] expected: Option<&str>) {+ assert_eq!(extract_filename_from_path(path), expected);+ }++ #[cfg(unix)]+ #[rstest]+ #[case::unix_bash("/usr/bin/bash", Some("bash"))]+ #[case::unix_zsh("/bin/zsh", Some("zsh"))]+ #[case::unix_fish("/usr/local/bin/fish", Some("fish"))]+ #[case::nix_versioned("/nix/store/abc123/zsh-5.9", Some("zsh-5.9"))]+ fn test_extract_filename_from_path_unix(#[case] path: &str, #[case] expected: Option<&str>) {+ assert_eq!(extract_filename_from_path(path), expected);+ }++ #[cfg(windows)]+ #[rstest]+ #[case::windows_git_bash(r"C:\Program Files\Git\usr\bin\bash.exe", Some("bash"))]+ #[case::windows_powershell(+ r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",+ Some("powershell")+ )]+ #[case::windows_pwsh(r"C:\Program Files\PowerShell\7\pwsh.exe", Some("pwsh"))]+ #[case::windows_zsh(r"C:\msys64\usr\bin\zsh.exe", Some("zsh"))]+ #[case::uppercase_exe(r"C:\WINDOWS\SYSTEM32\BASH.EXE", Some("BASH"))]+ fn test_extract_filename_from_path_windows(#[case] path: &str, #[case] expected: Option<&str>) {+ assert_eq!(extract_filename_from_path(path), expected);+ }++ /// Issue #348: Windows Git Bash shell detection+ ///+ /// Git Bash sets $SHELL to Windows-style paths like:+ /// `C:\Program Files\Git\usr\bin\bash.exe`+ ///+ /// This test verifies the full path-to-shell detection flow works on Windows.+ #[cfg(windows)]+ #[rstest]+ #[case::git_bash(r"C:\Program Files\Git\usr\bin\bash.exe", Shell::Bash)]+ #[case::msys2_zsh(r"C:\msys64\usr\bin\zsh.exe", Shell::Zsh)]+ #[case::powershell(+ r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe",+ Shell::PowerShell+ )]+ #[case::pwsh(r"C:\Program Files\PowerShell\7\pwsh.exe", Shell::PowerShell)]+ fn test_issue_348_windows_shell_detection(#[case] shell_path: &str, #[case] expected: Shell) {+ // This is the exact flow that failed before the fix:+ // 1. extract_filename_from_path() extracts "bash" from Windows path+ // 2. shell_from_name() maps "bash" to Shell::Bash+ let shell_name = extract_filename_from_path(shell_path)+ .expect("should extract filename from Windows path");+ let detected =+ shell_from_name(shell_name).expect("should detect shell from extracted name");+ assert_eq!(detected, expected);+ }++ #[rstest]+ #[case::bash("bash", Some(Shell::Bash))]+ #[case::bash_versioned("bash5", Some(Shell::Bash))]+ #[case::zsh("zsh", Some(Shell::Zsh))]+ #[case::zsh_versioned("zsh-5.9", Some(Shell::Zsh))]+ #[case::fish("fish", Some(Shell::Fish))]+ #[case::powershell("powershell", Some(Shell::PowerShell))]+ #[case::pwsh("pwsh", Some(Shell::PowerShell))]+ #[case::pwsh_preview("pwsh-preview", Some(Shell::PowerShell))]+ #[case::unknown("tcsh", None)]+ #[case::unknown_csh("csh", None)]+ fn test_shell_from_name(#[case] name: &str, #[case] expected: Option<Shell>) {+ assert_eq!(shell_from_name(name), expected);+ }+}