Skip to content

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

refactor: move inline imports to module top (batch 2/4) (#819)

Maximilian Roosc752399e033d
diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rs
index 25aa2bab9..be9bd150b 100644
--- a/src/git/repository/branch.rs
+++ b/src/git/repository/branch.rs
@@ -1,5 +1,7 @@
//! Branch - a handle for branch-specific git operations.
+use crate::git::GitRemoteUrl;
+
use super::Repository;
/// A handle for running git commands on a specific branch.
@@ -175,7 +177,6 @@ impl<'a> Branch<'a> {
/// Returns the push remote URL if configured and pointing to GitHub,
/// otherwise returns `None`.
pub fn github_push_url(&self) -> Option<String> {
- use crate::git::GitRemoteUrl;
let url = self.push_remote_url()?;
let parsed = GitRemoteUrl::parse(&url)?;
parsed.is_github().then_some(url)
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index fac758e7e..069513bae 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -3,7 +3,7 @@
//! For single-branch operations, see [`super::Branch`].
//! This module contains multi-branch operations (listing, filtering, etc.).
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use super::{BranchCategory, CompletionBranch, Repository};
@@ -195,7 +195,6 @@ impl Repository {
// Group by branch name, collecting all remotes that have each branch.
// Uses HashMap for grouping, then sorts by timestamp to preserve recency order.
- use std::collections::HashMap;
let mut branch_remotes: HashMap<String, (Vec<String>, i64)> = HashMap::new();
for line in remote_output.lines() {
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index 4b7c45f16..5066fdaab 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -2,7 +2,7 @@
use std::collections::HashMap;
-use anyhow::Context;
+use anyhow::{Context, bail};
use super::{DiffStats, LineDiff, Repository};
@@ -147,8 +147,6 @@ impl Repository {
/// when multiple tasks need the same merge-base (e.g., parallel `wt list` tasks).
/// The cache key is normalized (sorted) since merge-base(A, B) == merge-base(B, A).
pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<Option<String>> {
- use anyhow::bail;
-
// Normalize key order since merge-base is symmetric: merge-base(A, B) == merge-base(B, A)
let key = if commit1 <= commit2 {
(commit1.to_string(), commit2.to_string())
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 55ccf7c6f..9a666521f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -16,9 +16,15 @@
//! - `config.rs` - Git config, hints, markers, and default branch detection
//! - `integration.rs` - Integration detection (same commit, ancestor, trees match)
-use crate::shell_exec::Cmd;
+use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, OnceLock};
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Mutex, OnceLock};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use crate::shell_exec::Cmd;
use dashmap::DashMap;
use once_cell::sync::OnceCell;
@@ -564,13 +570,6 @@ impl Repository {
delay_ms: i64,
progress_message: Option<String>,
) -> anyhow::Result<()> {
- use std::io::{BufRead, BufReader, Write};
- use std::process::Stdio;
- use std::sync::Mutex;
- use std::sync::atomic::{AtomicBool, Ordering};
- use std::thread;
- use std::time::{Duration, Instant};
-
// Allow tests to override delay threshold (-1 to disable, 0 for immediate)
let delay_ms = std::env::var("WT_TEST_DELAYED_STREAM_MS")
.ok()
diff --git a/src/output/global.rs b/src/output/global.rs
index 8811db998..c6650d6e4 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -19,11 +19,16 @@
use std::fs::OpenOptions;
use std::io::{self, Write};
-use std::path::Path;
-use std::path::PathBuf;
#[cfg(unix)]
+use std::os::unix::process::CommandExt;
+use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::sync::{Mutex, OnceLock};
+
+#[cfg(not(unix))]
+use worktrunk::git::WorktrunkError;
+#[cfg(not(unix))]
+use worktrunk::shell_exec::Cmd;
use worktrunk::shell_exec::DIRECTIVE_FILE_ENV_VAR;
#[cfg(unix)]
use worktrunk::shell_exec::ShellConfig;
@@ -156,8 +161,6 @@ pub fn execute(command: impl Into<String>) -> anyhow::Result<()> {
/// Execute a command in the given directory (Unix: exec, non-Unix: spawn)
#[cfg(unix)]
fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
- use std::os::unix::process::CommandExt;
-
let exec_dir = target_dir.unwrap_or_else(|| Path::new("."));
let shell = ShellConfig::get();
@@ -184,9 +187,6 @@ fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result
/// Execute a command in the given directory (non-Unix: spawn and wait)
#[cfg(not(unix))]
fn execute_command(command: String, target_dir: Option<&Path>) -> anyhow::Result<()> {
- use std::process::Stdio;
- use worktrunk::git::WorktrunkError;
- use worktrunk::shell_exec::Cmd;
let mut cmd = Cmd::shell(&command).stdin(Stdio::inherit());
if let Some(dir) = target_dir {
cmd = cmd.current_dir(dir);
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 4a20d1bab..a71f68729 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1,9 +1,12 @@
//! Output handlers for worktree operations using the global output context
-use color_print::cformat;
use std::io::Write;
use std::path::{Path, PathBuf};
-use worktrunk::styling::stderr;
+use std::process::Stdio;
+
+use color_print::cformat;
+use worktrunk::shell_exec::Cmd;
+use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};
use crate::commands::branch_deletion::{
BranchDeletionOutcome, BranchDeletionResult, delete_branch_if_safe,
@@ -467,8 +470,6 @@ pub fn handle_switch_output(
/// `display_path` is shown when the user's shell won't be in the worktree directory
/// (shell integration not active). This helps users understand where the command runs.
pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyhow::Result<()> {
- use worktrunk::styling::format_bash_with_gutter;
-
// Show what command is being executed (section header + gutter content)
// Include path when user's shell won't be there (shell integration not active)
let header = match display_path {
@@ -1077,10 +1078,6 @@ pub fn execute_command_in_worktree(
command: &str,
stdin_content: Option<&str>,
) -> anyhow::Result<()> {
- use std::io::Write;
- use worktrunk::shell_exec::Cmd;
- use worktrunk::styling::{eprint, stderr};
-
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
stderr().flush()?;
@@ -1092,7 +1089,6 @@ pub fn execute_command_in_worktree(
stderr().flush().ok(); // Ignore flush errors - reset is best-effort, command execution should proceed
// Execute with stdout→stderr redirect for deterministic ordering
- use std::process::Stdio;
let mut cmd = Cmd::shell(command)
.current_dir(worktree_path)
.stdout(Stdio::from(std::io::stderr()))
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 0fbf58041..a6b44e152 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -58,12 +58,19 @@
//!
//! Note: The git subcommand case (`ran git wt; ...`) is handled separately via [`crate::is_git_subcommand`].
-use color_print::cformat;
+use std::io::IsTerminal;
+use color_print::cformat;
use worktrunk::config::UserConfig;
use worktrunk::path::format_path_for_display;
use worktrunk::shell::{Shell, current_shell, extract_filename_from_path};
-use worktrunk::styling::{eprintln, hint_message};
+use worktrunk::styling::{
+ eprintln, format_bash_with_gutter, hint_message, info_message, success_message, warning_message,
+};
+
+use crate::commands::configure_shell::{
+ ConfigAction, handle_configure_shell, prompt_for_install, scan_shell_configs,
+};
/// Shell integration install hint message.
// TODO(hints-count): After showing this hint 5+ times, suggest `wt config show` for diagnostics.
@@ -206,11 +213,6 @@ pub fn print_skipped_shells(
pub fn print_shell_install_result(
scan_result: &crate::commands::configure_shell::ScanResult,
) -> anyhow::Result<()> {
- use crate::commands::configure_shell::ConfigAction;
- use worktrunk::styling::{
- format_bash_with_gutter, info_message, success_message, warning_message,
- };
-
// Count shells that became (more) configured
let shells_configured_count = scan_result
.configured
@@ -362,12 +364,6 @@ pub fn prompt_shell_integration(
binary_name: &str,
skip_prompt: bool,
) -> anyhow::Result<bool> {
- use crate::commands::configure_shell::{
- ConfigAction, handle_configure_shell, prompt_for_install, scan_shell_configs,
- };
- use std::io::IsTerminal;
- use worktrunk::shell::current_shell;
-
// Skip when running as git subcommand - shell integration can't help there
// (running through git prevents cd, so the shell wrapper won't intercept)
// The git subcommand warning is already shown by the caller
diff --git a/src/shell/detection.rs b/src/shell/detection.rs
index 2561a1b8f..9a34fddad 100644
--- a/src/shell/detection.rs
+++ b/src/shell/detection.rs
@@ -4,6 +4,9 @@
//! shell config files (`.bashrc`, `.zshrc`, etc.) for eval/source lines
//! that invoke `wt config shell init`.
+use std::collections::HashSet;
+use std::fs;
+use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use super::paths::{home_dir_required, powershell_profile_paths};
@@ -262,9 +265,6 @@ pub struct BypassAlias {
/// Scan a single file for shell integration lines and potential false negatives.
fn scan_file(path: &std::path::Path, cmd: &str) -> Option<FileDetectionResult> {
- use std::fs;
- use std::io::{BufRead, BufReader};
-
let file = fs::File::open(path).ok()?;
let reader = BufReader::new(file);
let mut matched_lines = Vec::new();
@@ -394,8 +394,6 @@ fn detect_bypass_alias(line: &str, cmd: &str, line_number: usize) -> Option<Bypa
///
/// Used by `wt config show` to provide debugging output.
pub fn scan_for_detection_details(cmd: &str) -> Result<Vec<FileDetectionResult>, std::io::Error> {
- use std::collections::HashSet;
-
let home = home_dir_required()?;
let mut results = Vec::new();
diff --git a/src/shell/mod.rs b/src/shell/mod.rs
index 44da014ea..0a18a49cf 100644
--- a/src/shell/mod.rs
+++ b/src/shell/mod.rs
@@ -9,6 +9,8 @@ mod detection;
mod paths;
mod utils;
+use std::io::{BufRead, BufReader};
+
use askama::Template;
// Re-export public types and functions
@@ -124,8 +126,6 @@ impl Shell {
/// Check if a file contains shell integration lines for the given command.
fn file_has_integration(path: &std::path::Path, cmd: &str) -> Result<bool, std::io::Error> {
- use std::io::{BufRead, BufReader};
-
let file = std::fs::File::open(path)?;
for line in BufReader::new(file).lines() {
if is_shell_integration_line(&line?, cmd) {
diff --git a/src/shell/utils.rs b/src/shell/utils.rs
index 32772f902..270de9458 100644
--- a/src/shell/utils.rs
+++ b/src/shell/utils.rs
@@ -3,6 +3,9 @@
//! This module provides utilities for detecting the current shell, extracting
//! shell names from paths, and probing shell configuration state.
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
use super::Shell;
/// Extract executable name from a path, stripping `.exe` on Windows.
@@ -81,9 +84,6 @@ pub fn current_shell() -> Option<Shell> {
/// - `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