Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: move inline imports to module top level (batch 3) (#820)
Maximilian Roos3cf0f41cf64e
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex a437fdf8f..bf2e8262f 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -17,8 +17,9 @@//! This ensures approval happens exactly once at the command entry point,//! eliminating the need to thread `auto_trust` through execution layers.-use super::hook_filter::{HookSource, ParsedFilter};-use super::project_config::{HookCommand, collect_commands_for_hooks};+use std::io::{self, IsTerminal, Write};+use std::path::Path;+use anyhow::Context;use color_print::cformat;use worktrunk::config::UserConfig;@@ -28,6 +29,9 @@ use worktrunk::styling::{hint_message, stderr, warning_message,};+use super::hook_filter::{HookSource, ParsedFilter};+use super::project_config::{HookCommand, collect_commands_for_hooks};+/// Batch approval helper used when multiple commands are queued for execution./// Returns `Ok(true)` when execution may continue, `Ok(false)` when the user/// declined, and `Err` if config reload/save fails.@@ -104,9 +108,6 @@ pub fn approve_command_batch(}fn prompt_for_batch_approval(commands: &[&HookCommand], project_id: &str) -> anyhow::Result<bool> {- use std::io::{self, IsTerminal, Write};- use std::path::Path;-// Extract just the directory name for displaylet project_name = Path::new(project_id).file_name()diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 3ddef9c70..5ee639129 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -1,6 +1,9 @@+use std::collections::HashSet;use std::fs::{self, OpenOptions};use std::io::{self, BufRead, BufReader, Write};use std::path::{Path, PathBuf};++use anstyle::Style;use worktrunk::path::format_path_for_display;use worktrunk::shell::{self, Shell};use worktrunk::styling::{@@ -590,8 +593,6 @@ pub fn show_install_preview(completion_results: &[CompletionResult],cmd: &str,) {- use anstyle::Style;-let bold = Style::new().bold();// Show shell extension changes@@ -663,8 +664,6 @@ pub fn show_uninstall_preview(results: &[UninstallResult],completion_results: &[CompletionUninstallResult],) {- use anstyle::Style;-let bold = Style::new().bold();for result in results {@@ -751,7 +750,6 @@ pub fn prompt_for_install(/// Prompt user for yes/no confirmation (simple [y/N] prompt)fn prompt_yes_no() -> Result<bool, String> {- use anstyle::Style;use worktrunk::styling::eprint;let bold = Style::new().bold();@@ -1080,8 +1078,7 @@ fn uninstall_from_file(// Remove matching lines and any immediately preceding blank line// (install adds "\n{line}\n", so we remove both the blank and the integration line)- let mut indices_to_remove: std::collections::HashSet<usize> =- integration_lines.iter().map(|(i, _)| *i).collect();+ let mut indices_to_remove: HashSet<usize> = integration_lines.iter().map(|(i, _)| *i).collect();for &(i, _) in &integration_lines {if i > 0 && lines[i - 1].trim().is_empty() {indices_to_remove.insert(i - 1);@@ -1117,8 +1114,6 @@ fn prompt_for_uninstall_confirmation(results: &[UninstallResult],completion_results: &[CompletionUninstallResult],) -> Result<bool, String> {- use anstyle::Style;-for result in results {let bold = Style::new().bold();let shell = result.shell;diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 844f0a15e..001b360dc 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -6,9 +6,11 @@//! - `clear_approvals` - Clear approved commands//! - `handle_hook_show` - Display configured hooks+use std::collections::HashMap;+use std::fmt::Write as _;+use anyhow::Context;use color_print::cformat;-use std::fmt::Write as _;use strum::IntoEnumIterator;use worktrunk::HookType;use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};@@ -19,6 +21,9 @@ use worktrunk::styling::{info_message, success_message,};+use super::command_approval::approve_hooks_filtered;+use super::command_executor::build_hook_context;+use super::command_executor::CommandContext;use super::context::CommandEnv;use super::hooks::{@@ -52,8 +57,6 @@ pub fn run_hook(name_filter: Option<&str>,custom_vars: &[(String, String)],) -> anyhow::Result<()> {- use super::command_approval::approve_hooks_filtered;-// Derive context from current environment (branch-optional for CI compatibility)let env = CommandEnv::for_action_branchless()?;let repo = &env.repo;@@ -657,8 +660,6 @@ fn render_hook_commands(/// Expand a command template with context variablesfn expand_command_template(template: &str, ctx: &CommandContext, hook_type: HookType) -> String {- use super::command_executor::build_hook_context;-// Build extra vars based on hook type (same logic as run_hook approval)let default_branch = ctx.repo.default_branch();let extra_vars: Vec<(&str, &str)> = match hook_type {@@ -677,7 +678,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook_ => Vec::new(),};let template_ctx = build_hook_context(ctx, &extra_vars);- let vars: std::collections::HashMap<&str, &str> = template_ctx+ let vars: HashMap<&str, &str> = template_ctx.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 9e5ff9353..768824920 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -49,14 +49,15 @@ pub(crate) use worktree::{// Re-export Shell from the canonical locationpub(crate) use worktrunk::shell::Shell;+use color_print::cformat;+use worktrunk::styling::{eprintln, format_with_gutter};+/// Format command execution label with optional command name.////// Examples:/// - `format_command_label("post-create", Some("install"))` → `"Running post-create install"` (with bold)/// - `format_command_label("post-create", None)` → `"Running post-create"`pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> String {- use color_print::cformat;-match name {Some(name) => cformat!("Running {command_type} <bold>{name}</>"),None => format!("Running {command_type}"),@@ -72,8 +73,6 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St/// * `repo` - The repository to query/// * `range` - The commit range to diff (e.g., "HEAD~1..HEAD" or "main..HEAD")pub(crate) fn show_diffstat(repo: &worktrunk::git::Repository, range: &str) -> anyhow::Result<()> {- use worktrunk::styling::{eprintln, format_with_gutter};-let term_width = crate::display::get_terminal_width();let stat_width = term_width.saturating_sub(worktrunk::styling::GUTTER_OVERHEAD);let diff_stat = repodiff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex e7216c00b..b680a5f5e 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -6,12 +6,14 @@//! This command reuses the data collection infrastructure from `wt list`,//! avoiding duplication of git operations.-use anyhow::{Context, Result};use std::env;-use std::io::{self, Read};-use std::path::Path;+use std::io::{self, IsTerminal, Read};+use std::path::{Component, Path};++use ansi_str::AnsiStr;+use anyhow::{Context, Result};use worktrunk::git::Repository;-use worktrunk::styling::{get_terminal_width, truncate_visible};+use worktrunk::styling::{fix_dim_after_color_reset, get_terminal_width, truncate_visible};use super::list::{self, CollectOptions, StatuslineSegment};@@ -65,8 +67,6 @@ impl ClaudeCodeContext {/// Try to read and parse Claude Code context from stdin./// Returns None if stdin is a terminal or not valid JSON.fn from_stdin() -> Option<Self> {- use std::io::IsTerminal;-if io::stdin().is_terminal() {return None;}@@ -84,8 +84,6 @@ impl ClaudeCodeContext {/// - `/home/user` -> `~`/// - `/tmp/test` -> `/t/test`fn format_directory_fish_style(path: &Path) -> String {- use std::path::Component;-// Replace home directory prefix with ~let (suffix, tilde_prefix) = worktrunk::path::home_dir().and_then(|home| path.strip_prefix(&home).ok().map(|s| (s, true)))@@ -203,7 +201,6 @@ pub fn run(claude_code: bool) -> Result<()> {// Join and apply final truncation as fallbacklet output = StatuslineSegment::join(&fitted_segments);- use worktrunk::styling::fix_dim_after_color_reset;let reset = anstyle::Reset;let output = fix_dim_after_color_reset(&output);let output = truncate_visible(&format!("{reset} {output}"), max_width);@@ -216,7 +213,6 @@ pub fn run(claude_code: bool) -> Result<()> {/// Filter out branch segment if directory already shows it via worktrunk template.fn filter_redundant_branch(segments: Vec<StatuslineSegment>, dir: &str) -> Vec<StatuslineSegment> {use super::list::columns::ColumnKind;- use ansi_str::AnsiStr;// Find the branch segment by its column kind (not priority, which could be shared)if let Some(branch_seg) = segments.iter().find(|s| s.kind == Some(ColumnKind::Branch)) {@@ -445,7 +441,6 @@ mod tests {#[test]fn test_statusline_truncation() {use color_print::cformat;- use worktrunk::styling::truncate_visible;// Simulate a long statusline with styled contentlet long_line =diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 3bce27170..bded8e3dd 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -7,10 +7,13 @@//! - `handle_rebase` - Rebase onto target branch//! - `step_copy_ignored` - Copy gitignored files matching .worktreeinclude+use std::fs;+use std::io::ErrorKind;use std::path::{Path, PathBuf};use anyhow::Context;use color_print::cformat;+use ignore::gitignore::GitignoreBuilder;use worktrunk::HookType;use worktrunk::config::UserConfig;use worktrunk::git::Repository;@@ -18,10 +21,12 @@ use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,};-use super::commit::{CommitGenerator, CommitOptions};+use super::command_approval::approve_hooks;+use super::commit::{CommitGenerator, CommitOptions, StageMode};use super::context::CommandEnv;use super::hooks::{HookFailureStrategy, run_hook_with_filter};use super::repository_ext::RepositoryCliExt;+use worktrunk::shell_exec::Cmd;/// Handle `wt step commit` command///@@ -29,11 +34,9 @@ use super::repository_ext::RepositoryCliExt;pub fn step_commit(yes: bool,no_verify: bool,- stage: Option<super::commit::StageMode>,+ stage: Option<StageMode>,show_prompt: bool,) -> anyhow::Result<()> {- use super::command_approval::approve_hooks;-// Handle --show-prompt early: just build and output the promptif show_prompt {let repo = worktrunk::git::Repository::current()?;@@ -75,7 +78,7 @@ pub fn step_commit(options.stage_mode = stage_mode;options.show_no_squash_note = false;// Only warn about untracked if we're staging all- options.warn_about_untracked = stage_mode == super::commit::StageMode::All;+ options.warn_about_untracked = stage_mode == StageMode::All;options.commit()}@@ -102,10 +105,8 @@ pub fn handle_squash(target: Option<&str>,yes: bool,skip_pre_commit: bool,- stage: Option<super::commit::StageMode>,+ stage: Option<StageMode>,) -> anyhow::Result<SquashResult> {- use super::commit::StageMode;-let env = CommandEnv::for_action("squash")?;let repo = &env.repo;// Squash requires being on a branch (can't squash in detached HEAD)@@ -220,7 +221,7 @@ pub fn handle_squash(let with_changes = if has_staged {match stage_mode {- super::commit::StageMode::Tracked => " & tracked changes",+ StageMode::Tracked => " & tracked changes",_ => " & working tree changes",}} else {@@ -457,9 +458,6 @@ pub fn step_copy_ignored(to: Option<&str>,dry_run: bool,) -> anyhow::Result<()> {- use ignore::gitignore::GitignoreBuilder;- use std::fs;-let repo = Repository::current()?;// Resolve source and destination worktree paths@@ -628,8 +626,6 @@ fn list_ignored_entries(worktree_path: &Path,context: &str,) -> anyhow::Result<Vec<(std::path::PathBuf, bool)>> {- use worktrunk::shell_exec::Cmd;-let output = Cmd::new("git").args(["ls-files",@@ -690,9 +686,6 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> anyhow::Result<()> {////// Used as fallback when atomic directory clone isn't available or fails.fn copy_dir_recursive_fallback(src: &Path, dest: &Path) -> anyhow::Result<()> {- use std::fs;- use std::io::ErrorKind;-fs::create_dir_all(dest)?;for entry in fs::read_dir(src)? {diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex a5019c937..4db63554e 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -5,6 +5,7 @@use std::path::{Path, PathBuf};use color_print::cformat;+use dunce::canonicalize;use normalize_path::NormalizePath;use worktrunk::config::UserConfig;use worktrunk::git::{GitError, Repository, ResolvedWorktree};@@ -131,7 +132,6 @@ pub fn is_worktree_at_expected_path(////// 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