Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: Split large files into focused modules and restore snapshot tests
Maximilian Roosbd636c78c844
diff --git a/src/config.rs b/src/config/mod.rssimilarity index 99%rename from src/config.rsrename to src/config/mod.rsindex eb547d5ed..bd4b05e84 100644--- a/src/config.rs+++ b/src/config/mod.rs@@ -45,6 +45,9 @@ use toml;#[cfg(not(test))]use etcetera::base_strategy::{BaseStrategy, choose_base_strategy};+#[cfg(test)]+mod test;+/// User-level configuration for worktree path formatting and LLM integration.////// This config is stored at `~/.config/worktrunk/config.toml` (or platform equivalent)diff --git a/src/snapshots/worktrunk__config_template_test__snapshot_complex_templates.snap b/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snapsimilarity index 92%rename from src/snapshots/worktrunk__config_template_test__snapshot_complex_templates.snaprename to src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snapindex 8a4e607d6..5c0bbaddb 100644--- a/src/snapshots/worktrunk__config_template_test__snapshot_complex_templates.snap+++ b/src/config/snapshots/worktrunk__config__test__snapshot_complex_templates.snap@@ -1,5 +1,5 @@----source: src/config_template_test.rs+source: src/config/test.rsexpression: results---- - cd_and_mergediff --git a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_paths.snap b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_paths.snapsimilarity index 92%rename from src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_paths.snaprename to src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_paths.snapindex 759f73646..f6c1ee5d8 100644--- a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_paths.snap+++ b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_paths.snap@@ -1,5 +1,5 @@----source: src/config_template_test.rs+source: src/config/test.rsexpression: results---- - spacesdiff --git a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_quotes.snap b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_quotes.snapsimilarity index 89%rename from src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_quotes.snaprename to src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_quotes.snapindex 58909cc79..55d2c98e6 100644--- a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_quotes.snap+++ b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_quotes.snap@@ -1,5 +1,5 @@----source: src/config_template_test.rs+source: src/config/test.rsexpression: results---- - single_quotediff --git a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_special_chars.snap b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snapsimilarity index 95%rename from src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_special_chars.snaprename to src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snapindex 7cf8bad0b..2ed4b046f 100644--- a/src/snapshots/worktrunk__config_template_test__snapshot_shell_escaping_special_chars.snap+++ b/src/config/snapshots/worktrunk__config__test__snapshot_shell_escaping_special_chars.snap@@ -1,5 +1,5 @@----source: src/config_template_test.rs+source: src/config/test.rsexpression: results---- - spacesdiff --git a/src/config_template_test.rs b/src/config/test.rssimilarity index 89%rename from src/config_template_test.rsrename to src/config/test.rsindex ccd2b6921..3537dccbd 100644--- a/src/config_template_test.rs+++ b/src/config/test.rs@@ -3,7 +3,7 @@//! These tests target potential shell injection vulnerabilities and//! edge cases in template variable substitution.-use crate::config::expand_template;+use super::expand_template;use std::collections::HashMap;#[test]@@ -30,78 +30,74 @@ fn test_expand_template_branch_with_slashes() {#[test]fn test_expand_template_branch_with_spaces() {- // FIXED: Branch names with spaces are now shell-escaped+ // Branch names with spaces are shell-escapedlet extras = HashMap::new();let result = expand_template("echo {branch}", "myrepo", "feature name", &extras);- // New behavior: shell-escaped with single quotes+ // Shell-escaped with single quotesassert_eq!(result, "echo 'feature name'");- // This correctly executes: echo 'feature name' (1 argument)}#[test]fn test_expand_template_branch_with_special_shell_chars() {- // FIXED: Special shell characters are now escaped+ // Special shell characters are escapedlet extras = HashMap::new();let result = expand_template("echo {branch}", "myrepo", "feature$(whoami)", &extras);- // New behavior: shell-escaped, prevents command substitution+ // Shell-escaped, prevents command substitutionassert_eq!(result, "echo 'feature$(whoami)'");// Shell executes: echo 'feature$(whoami)' (literal string, no command execution)}#[test]fn test_expand_template_branch_with_backticks() {- // FIXED: Backticks are now escaped+ // Backticks are escapedlet extras = HashMap::new();let result = expand_template("echo {branch}", "myrepo", "feature`id`", &extras);assert_eq!(result, "echo 'feature`id`'");- // Shell executes: echo 'feature`id`' (literal, no command execution)}#[test]fn test_expand_template_branch_with_quotes() {- // FIXED: Quotes in branch names are handled properly+ // Quotes are shell-escaped to prevent injectionlet extras = HashMap::new();let result = expand_template("echo '{branch}'", "myrepo", "feature'test", &extras);- // shell_escape uses single quotes, so single quotes inside are escaped+ // Shell escapes single quotes as '\''assert_eq!(result, "echo ''feature'\\''test''");- // This properly escapes the embedded single quotes}#[test]fn test_expand_template_extra_vars_with_spaces() {- // FIXED: Extra variables with spaces are now escaped+ // Extra variables with spaces are shell-escapedlet mut extras = HashMap::new();extras.insert("worktree", "/path with spaces/to/worktree");let result = expand_template("cd {worktree}", "myrepo", "main", &extras);assert_eq!(result, "cd '/path with spaces/to/worktree'");- // Shell correctly executes: cd '/path with spaces/to/worktree'}#[test]fn test_expand_template_extra_vars_with_dollar_sign() {- // FIXED: Dollar signs are now escaped+ // Dollar signs are shell-escaped to prevent variable expansionlet mut extras = HashMap::new();extras.insert("worktree", "/path/$USER/worktree");let result = expand_template("cd {worktree}", "myrepo", "main", &extras);assert_eq!(result, "cd '/path/$USER/worktree'");- // Shell executes literal path (no $USER expansion)+ // Shell-escaped, prevents $USER from being expanded}#[test]fn test_expand_template_extra_vars_with_command_substitution() {- // FIXED: Command injection is now prevented+ // Special shell characters are shell-escaped to prevent injectionlet mut extras = HashMap::new();extras.insert("target", "main; rm -rf /");let result = expand_template("git merge {target}", "myrepo", "feature", &extras);assert_eq!(result, "git merge 'main; rm -rf /'");- // Shell executes: git merge 'main; rm -rf /' (literal branch name, no command execution)+ // Shell-escaped, prevents semicolon from being executed as command separator}#[test]@@ -146,17 +142,17 @@ fn test_expand_template_empty_branch() {let extras = HashMap::new();let result = expand_template("echo {branch}", "myrepo", "", &extras);- // Empty string is escaped as ''+ // Empty string is shell-escaped to ''assert_eq!(result, "echo ''");}#[test]fn test_expand_template_unicode_in_branch() {- // Unicode characters in branch name+ // Unicode characters in branch name are shell-escapedlet extras = HashMap::new();let result = expand_template("echo {branch}", "myrepo", "feature-π", &extras);- // Unicode is preserved but quoted due to emoji+ // Unicode is preserved but quoted for shell safetyassert_eq!(result, "echo 'feature-π'");}diff --git a/src/git/error.rs b/src/git/error.rsnew file mode 100644index 000000000..43b9260c3--- /dev/null+++ b/src/git/error.rs@@ -0,0 +1,249 @@+//! Git error types and formatting++use std::path::PathBuf;++use super::HookType;++#[derive(Debug)]+pub enum GitError {+ /// Generic error with a message+ CommandFailed(String),+ /// Error for parsing failures+ ParseError(String),+ /// Repository is in detached HEAD state+ DetachedHead,+ /// Working tree has untracked files+ UntrackedFiles,+ /// Hook command failed+ HookCommandFailed {+ hook_type: HookType,+ command_name: Option<String>,+ error: String,+ },+ /// Working tree has uncommitted changes+ UncommittedChanges,+ /// Branch already exists (when trying to create)+ BranchAlreadyExists { branch: String },+ /// Worktree directory is missing+ WorktreeMissing { branch: String },+ /// No worktree found for branch+ NoWorktreeFound { branch: String },+ /// Cannot push due to conflicting uncommitted changes+ ConflictingChanges {+ files: Vec<String>,+ worktree_path: PathBuf,+ },+ /// Push is not a fast-forward+ NotFastForward {+ target_branch: String,+ commits_formatted: String,+ files_formatted: String,+ },+ /// Found merge commits in push range+ MergeCommitsFound,+ /// Command was not approved by user+ CommandNotApproved,+ /// Push operation failed+ PushFailed { error: String },+ /// Rebase resulted in a conflict or incomplete state+ RebaseConflict {+ state: String,+ target_branch: String,+ git_output: String,+ },+}++impl std::fmt::Display for GitError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ use crate::styling::{ERROR, ERROR_EMOJI, HINT, HINT_EMOJI};++ match self {+ // Plain message that will be displayed by main.rs+ GitError::CommandFailed(msg) => write!(f, "{}", msg),++ // ParseError messages need formatting+ GitError::ParseError(msg) => {+ write!(f, "{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")+ }++ // Detached HEAD error+ GitError::DetachedHead => {+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}\n\n{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}"+ )+ }++ // Untracked files error+ GitError::UntrackedFiles => {+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Working tree has untracked files{ERROR:#}\n\n{HINT_EMOJI} {HINT}Add them with 'git add' and try again{HINT:#}"+ )+ }++ // Hook command failed+ GitError::HookCommandFailed {+ hook_type,+ command_name,+ error,+ } => {+ let error_bold = ERROR.bold();+ match command_name {+ Some(name) => write!(+ f,+ "{ERROR_EMOJI} {ERROR}{hook_type} command failed: {error_bold}{name}{error_bold:#}{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip {hook_type} commands{HINT:#}"+ ),+ None => write!(+ f,+ "{ERROR_EMOJI} {ERROR}{hook_type} command failed{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip {hook_type} commands{HINT:#}"+ ),+ }+ }++ // Uncommitted changes+ GitError::UncommittedChanges => {+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"+ )+ }++ // Branch already exists+ GitError::BranchAlreadyExists { branch } => {+ let error_bold = ERROR.bold();+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Branch {error_bold}{branch}{error_bold:#}{ERROR} already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}"+ )+ }++ // Worktree missing+ GitError::WorktreeMissing { branch } => {+ let error_bold = ERROR.bold();+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Worktree directory missing for {error_bold}{branch}{error_bold:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}"+ )+ }++ // No worktree found+ GitError::NoWorktreeFound { branch } => {+ let error_bold = ERROR.bold();+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}No worktree found for branch {error_bold}{branch}{error_bold:#}{ERROR:#}"+ )+ }++ // Conflicting changes+ GitError::ConflictingChanges {+ files,+ worktree_path,+ } => {+ use crate::styling::AnstyleStyle;+ let dim = AnstyleStyle::new().dimmed();++ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"+ )?;+ for file in files {+ writeln!(f, "{dim}β’{dim:#} {file}")?;+ }+ write!(+ f,+ "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",+ worktree_path.display()+ )+ }++ // Not fast-forward+ GitError::NotFastForward {+ target_branch,+ commits_formatted,+ files_formatted,+ } => {+ let error_bold = ERROR.bold();++ writeln!(+ f,+ "{ERROR_EMOJI} {ERROR}Can't push to local {error_bold}{target_branch}{error_bold:#} branch: it has newer commits{ERROR:#}"+ )?;++ // Show the formatted commit log+ if !commits_formatted.is_empty() {+ writeln!(f)?;+ write!(f, "{}", commits_formatted)?;+ }++ // Show the formatted diff stat+ if !files_formatted.is_empty() {+ writeln!(f)?;+ write!(f, "{}", files_formatted)?;+ }++ write!(+ f,+ "\n{HINT_EMOJI} {HINT}Use 'wt merge' to rebase your changes onto {target_branch}{HINT:#}"+ )+ }++ // Merge commits found+ GitError::MergeCommitsFound => {+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Found merge commits in push range{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use --allow-merge-commits to push non-linear history{HINT:#}"+ )+ }++ // Command not approved+ GitError::CommandNotApproved => {+ Ok(()) // on_skip callback handles the printing+ }++ // Push failed+ GitError::PushFailed { error } => {+ write!(f, "{ERROR_EMOJI} {ERROR}Push failed: {error}{ERROR:#}")+ }++ // Rebase conflict+ GitError::RebaseConflict {+ state: _,+ target_branch,+ git_output,+ } => {+ use crate::styling::format_with_gutter;+ let error_bold = ERROR.bold();++ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Rebase onto {error_bold}{target_branch}{error_bold:#}{ERROR} incomplete{ERROR:#}"+ )?;++ if !git_output.is_empty() {+ writeln!(f)?;+ write!(f, "{}", format_with_gutter(git_output, "", None))?;+ } else {+ // Fallback hints if no git output (edge case)+ write!(+ f,+ "\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"+ )?;+ }++ Ok(())+ }+ }+ }+}++impl std::error::Error for GitError {}++// Automatic conversion from io::Error to GitError+// This eliminates the need for manual .map_err() on output functions+impl From<std::io::Error> for GitError {+ fn from(e: std::io::Error) -> Self {+ GitError::CommandFailed(e.to_string())+ }+}diff --git a/src/git/mod.rs b/src/git/mod.rsnew file mode 100644index 000000000..01aa7ce11--- /dev/null+++ b/src/git/mod.rs@@ -0,0 +1,90 @@+//! Git operations and repository management++use std::path::PathBuf;++// Submodules+mod error;+mod parse;+mod repository;++#[cfg(test)]+mod test;++// Re-exports from submodules+pub use error::GitError;+pub use repository::{GitResultExt, Repository};++// Re-export parsing functions for internal use+pub(crate) use parse::{+ parse_local_default_branch, parse_numstat, parse_remote_default_branch, parse_worktree_list,+};++// Note: HookType and Worktree are defined in this module and are already public.+// They're accessible as git::HookType and git::Worktree without needing re-export.++/// Hook types for git operations+#[derive(Debug, Clone, Copy, clap::ValueEnum, strum::Display)]+#[strum(serialize_all = "kebab-case")]+pub enum HookType {+ PostCreate,+ PostStart,+ PreCommit,+ PreMerge,+ PostMerge,+}++/// Worktree information+#[derive(Debug, Clone, PartialEq, serde::Serialize)]+pub struct Worktree {+ pub path: PathBuf,+ pub head: String,+ pub branch: Option<String>,+ pub bare: bool,+ pub detached: bool,+ pub locked: Option<String>,+ pub prunable: Option<String>,+}++// Helper functions for worktree parsing+//+// These live in mod.rs rather than parse.rs because they bridge multiple concerns:+// - read_rebase_branch() uses Repository (from repository.rs) to access git internals+// - finalize_worktree() operates on Worktree (defined here in mod.rs)+// - Both are tightly coupled to the Worktree type definition+//+// Placing them here avoids circular dependencies and keeps them close to Worktree.++/// Helper function to read rebase branch information+fn read_rebase_branch(worktree_path: &PathBuf) -> Option<String> {+ // Create a Repository instance to get the correct git directory+ let repo = Repository::at(worktree_path);+ let git_dir = repo.git_dir().ok()?;++ // Check both rebase-merge and rebase-apply+ for rebase_dir in ["rebase-merge", "rebase-apply"] {+ let head_name_path = git_dir.join(rebase_dir).join("head-name");+ if let Ok(content) = std::fs::read_to_string(head_name_path) {+ let branch_ref = content.trim();+ // Strip refs/heads/ prefix if present+ let branch = branch_ref+ .strip_prefix("refs/heads/")+ .unwrap_or(branch_ref)+ .to_string();+ return Some(branch);+ }+ }++ None+}++/// Finalize a worktree after parsing, filling in branch name from rebase state if needed.+pub(crate) fn finalize_worktree(mut wt: Worktree) -> Worktree {+ // If detached but no branch, check if we're rebasing+ if wt.detached+ && wt.branch.is_none()+ && let Some(branch) = read_rebase_branch(&wt.path)+ {+ wt.branch = Some(branch);+ }+ wt+}diff --git a/src/git/parse.rs b/src/git/parse.rsnew file mode 100644index 000000000..a43c3a6fa--- /dev/null+++ b/src/git/parse.rs@@ -0,0 +1,160 @@+//! Git output parsing functions++use std::path::PathBuf;++use super::{GitError, Worktree, finalize_worktree};++pub(crate) fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {+ let mut worktrees = Vec::new();+ let mut current: Option<Worktree> = None;++ for line in output.lines() {+ if line.is_empty() {+ if let Some(wt) = current.take() {+ worktrees.push(finalize_worktree(wt));+ }+ continue;+ }++ let (key, value) = match line.split_once(' ') {+ Some((k, v)) => (k, Some(v)),+ None => (line, None),+ };++ match key {+ "worktree" => {+ let path = value.ok_or_else(|| {+ GitError::ParseError("worktree line missing path".to_string())+ })?;+ current = Some(Worktree {+ path: PathBuf::from(path),+ head: String::new(),+ branch: None,+ bare: false,+ detached: false,+ locked: None,+ prunable: None,+ });+ }+ "HEAD" => {+ if let Some(ref mut wt) = current {+ wt.head = value+ .ok_or_else(|| GitError::ParseError("HEAD line missing SHA".to_string()))?+ .to_string();+ }+ }+ "branch" => {+ if let Some(ref mut wt) = current {+ // Strip refs/heads/ prefix if present+ let branch_ref = value.ok_or_else(|| {+ GitError::ParseError("branch line missing ref".to_string())+ })?;+ let branch = branch_ref+ .strip_prefix("refs/heads/")+ .unwrap_or(branch_ref)+ .to_string();+ wt.branch = Some(branch);+ }+ }+ "bare" => {+ if let Some(ref mut wt) = current {+ wt.bare = true;+ }+ }+ "detached" => {+ if let Some(ref mut wt) = current {+ wt.detached = true;+ }+ }+ "locked" => {+ if let Some(ref mut wt) = current {+ wt.locked = Some(value.unwrap_or_default().to_string());+ }+ }+ "prunable" => {+ if let Some(ref mut wt) = current {+ wt.prunable = Some(value.unwrap_or_default().to_string());+ }+ }+ _ => {+ // Ignore unknown attributes for forward compatibility+ }+ }+ }++ // Push the last worktree if the output doesn't end with a blank line+ if let Some(wt) = current {+ worktrees.push(finalize_worktree(wt));+ }++ Ok(worktrees)+}++pub(crate) fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {+ let trimmed = output.trim();++ // Strip "remote/" prefix if present+ let prefix = format!("{}/", remote);+ let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);++ if branch.is_empty() {+ return Err(GitError::ParseError(format!(+ "Empty branch name from {}/HEAD",+ remote+ )));+ }++ Ok(branch.to_string())+}++pub(crate) fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {+ output+ .lines()+ .find_map(|line| {+ line.strip_prefix("ref: ")+ .and_then(|symref| symref.split_once('\t'))+ .map(|(ref_path, _)| ref_path)+ .and_then(|ref_path| ref_path.strip_prefix("refs/heads/"))+ .map(|branch| branch.to_string())+ })+ .ok_or_else(|| {+ GitError::ParseError("Could not find symbolic ref in ls-remote output".to_string())+ })+}++pub(crate) fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {+ let mut total_added = 0;+ let mut total_deleted = 0;++ for line in output.lines() {+ if line.trim().is_empty() {+ continue;+ }++ let mut parts = line.split('\t');+ let Some(added_str) = parts.next() else {+ continue;+ };+ let Some(deleted_str) = parts.next() else {+ continue;+ };++ // Binary files show "-" for added/deleted+ if added_str == "-" || deleted_str == "-" {+ continue;+ }++ // Skip malformed lines (e.g., missing tabs) by treating parse errors as non-fatal+ let Ok(added) = added_str.parse::<usize>() else {+ continue;+ };+ let Ok(deleted) = deleted_str.parse::<usize>() else {+ continue;+ };++ total_added += added;+ total_deleted += deleted;+ }++ Ok((total_added, total_deleted))+}diff --git a/src/git.rs b/src/git/repository.rssimilarity index 70%rename from src/git.rsrename to src/git/repository.rsindex 60687cb87..61b30bdeb 100644--- a/src/git.rs+++ b/src/git/repository.rs@@ -1,270 +1,11 @@use std::path::PathBuf;use std::process::Command;-#[derive(Debug, Clone, Copy, clap::ValueEnum, strum::Display)]-#[strum(serialize_all = "kebab-case")]-pub enum HookType {- PostCreate,- PostStart,- PreCommit,- PreMerge,- PostMerge,-}--#[derive(Debug, Clone, PartialEq, serde::Serialize)]-pub struct Worktree {- pub path: PathBuf,- pub head: String,- pub branch: Option<String>,- pub bare: bool,- pub detached: bool,- pub locked: Option<String>,- pub prunable: Option<String>,-}--#[derive(Debug)]-pub enum GitError {- /// Generic error with a message- CommandFailed(String),- /// Error for parsing failures- ParseError(String),- /// Repository is in detached HEAD state- DetachedHead,- /// Working tree has untracked files- UntrackedFiles,- /// Hook command failed- HookCommandFailed {- hook_type: HookType,- command_name: Option<String>,- error: String,- },- /// Working tree has uncommitted changes- UncommittedChanges,- /// Branch already exists (when trying to create)- BranchAlreadyExists { branch: String },- /// Worktree directory is missing- WorktreeMissing { branch: String },- /// No worktree found for branch- NoWorktreeFound { branch: String },- /// Cannot push due to conflicting uncommitted changes- ConflictingChanges {- files: Vec<String>,- worktree_path: PathBuf,- },- /// Push is not a fast-forward- NotFastForward {- target_branch: String,- commits_formatted: String,- files_formatted: String,- },- /// Found merge commits in push range- MergeCommitsFound,- /// Command was not approved by user- CommandNotApproved,- /// Push operation failed- PushFailed { error: String },- /// Rebase resulted in a conflict or incomplete state- RebaseConflict {- state: String,- target_branch: String,- git_output: String,- },-}--impl std::fmt::Display for GitError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- use crate::styling::{ERROR, ERROR_EMOJI, HINT, HINT_EMOJI};-- match self {- // Plain message that will be displayed by main.rs- GitError::CommandFailed(msg) => write!(f, "{}", msg),-- // ParseError messages need formatting- GitError::ParseError(msg) => {- write!(f, "{ERROR_EMOJI} {ERROR}{msg}{ERROR:#}")- }-- // Detached HEAD error- GitError::DetachedHead => {- write!(- f,- "{ERROR_EMOJI} {ERROR}Not on a branch (detached HEAD){ERROR:#}\n\n{HINT_EMOJI} {HINT}You are in detached HEAD state{HINT:#}"- )- }-- // Untracked files error- GitError::UntrackedFiles => {- write!(- f,- "{ERROR_EMOJI} {ERROR}Working tree has untracked files{ERROR:#}\n\n{HINT_EMOJI} {HINT}Add them with 'git add' and try again{HINT:#}"- )- }-- // Hook command failed- GitError::HookCommandFailed {- hook_type,- command_name,- error,- } => {- let error_bold = ERROR.bold();- match command_name {- Some(name) => write!(- f,- "{ERROR_EMOJI} {ERROR}{hook_type} command failed: {error_bold}{name}{error_bold:#}{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip {hook_type} commands{HINT:#}"- ),- None => write!(- f,- "{ERROR_EMOJI} {ERROR}{hook_type} command failed{ERROR:#}\n\n{error}\n\n{HINT_EMOJI} {HINT}Use --no-hooks to skip {hook_type} commands{HINT:#}"- ),- }- }-- // Uncommitted changes- GitError::UncommittedChanges => {- write!(- f,- "{ERROR_EMOJI} {ERROR}Working tree has uncommitted changes{ERROR:#}\n\n{HINT_EMOJI} {HINT}Commit or stash them first{HINT:#}"- )- }-- // Branch already exists- GitError::BranchAlreadyExists { branch } => {- let error_bold = ERROR.bold();- write!(- f,- "{ERROR_EMOJI} {ERROR}Branch {error_bold}{branch}{error_bold:#}{ERROR} already exists{ERROR:#}\n\n{HINT_EMOJI} {HINT}Remove --create flag to switch to it{HINT:#}"- )- }-- // Worktree missing- GitError::WorktreeMissing { branch } => {- let error_bold = ERROR.bold();- write!(- f,- "{ERROR_EMOJI} {ERROR}Worktree directory missing for {error_bold}{branch}{error_bold:#}{ERROR:#}\n\n{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}"- )- }-- // No worktree found- GitError::NoWorktreeFound { branch } => {- let error_bold = ERROR.bold();- write!(- f,- "{ERROR_EMOJI} {ERROR}No worktree found for branch {error_bold}{branch}{error_bold:#}{ERROR:#}"- )- }-- // Conflicting changes- GitError::ConflictingChanges {- files,- worktree_path,- } => {- use crate::styling::AnstyleStyle;- let dim = AnstyleStyle::new().dimmed();-- write!(- f,- "{ERROR_EMOJI} {ERROR}Cannot push: conflicting uncommitted changes in:{ERROR:#}\n\n"- )?;- for file in files {- writeln!(f, "{dim}β’{dim:#} {file}")?;- }- write!(- f,- "\n{HINT_EMOJI} {HINT}Commit or stash these changes in {} first{HINT:#}",- worktree_path.display()- )- }-- // Not fast-forward- GitError::NotFastForward {- target_branch,- commits_formatted,- files_formatted,- } => {- let error_bold = ERROR.bold();-- writeln!(- f,- "{ERROR_EMOJI} {ERROR}Can't push to local {error_bold}{target_branch}{error_bold:#} branch: it has newer commits{ERROR:#}"- )?;-- // Show the formatted commit log- if !commits_formatted.is_empty() {- writeln!(f)?;- write!(f, "{}", commits_formatted)?;- }-- // Show the formatted diff stat- if !files_formatted.is_empty() {- writeln!(f)?;- write!(f, "{}", files_formatted)?;- }-- write!(- f,- "\n{HINT_EMOJI} {HINT}Use 'wt merge' to rebase your changes onto {target_branch}{HINT:#}"- )- }-- // Merge commits found- GitError::MergeCommitsFound => {- write!(- f,- "{ERROR_EMOJI} {ERROR}Found merge commits in push range{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use --allow-merge-commits to push non-linear history{HINT:#}"- )- }-- // Command not approved- GitError::CommandNotApproved => {- Ok(()) // on_skip callback handles the printing- }-- // Push failed- GitError::PushFailed { error } => {- write!(f, "{ERROR_EMOJI} {ERROR}Push failed: {error}{ERROR:#}")- }-- // Rebase conflict- GitError::RebaseConflict {- state: _,- target_branch,- git_output,- } => {- use crate::styling::format_with_gutter;- let error_bold = ERROR.bold();-- write!(- f,- "{ERROR_EMOJI} {ERROR}Rebase onto {error_bold}{target_branch}{error_bold:#}{ERROR} incomplete{ERROR:#}"- )?;-- if !git_output.is_empty() {- writeln!(f)?;- write!(f, "{}", format_with_gutter(git_output, "", None))?;- } else {- // Fallback hints if no git output (edge case)- write!(- f,- "\n\n{HINT_EMOJI} {HINT}Resolve conflicts and run 'git rebase --continue'{HINT:#}\n{HINT_EMOJI} {HINT}Or abort with 'git rebase --abort'{HINT:#}"- )?;- }-- Ok(())- }- }- }-}--impl std::error::Error for GitError {}--// Automatic conversion from io::Error to GitError-// This eliminates the need for manual .map_err() on output functions-impl From<std::io::Error> for GitError {- fn from(e: std::io::Error) -> Self {- GitError::CommandFailed(e.to_string())- }-}+// Import types and functions from parent module (mod.rs)+use super::{+ GitError, Worktree, parse_local_default_branch, parse_numstat, parse_remote_default_branch,+ parse_worktree_list,+};/// Extension trait for Result types to simplify GitError conversions///@@ -1011,198 +752,9 @@ impl Repository {}}-/// Read the branch name from rebase state files if a rebase is in progress.-fn read_rebase_branch(worktree_path: &PathBuf) -> Option<String> {- // Create a Repository instance to get the correct git directory- let repo = Repository::at(worktree_path);- let git_dir = repo.git_dir().ok()?;-- // Check both rebase-merge and rebase-apply- for rebase_dir in ["rebase-merge", "rebase-apply"] {- let head_name_path = git_dir.join(rebase_dir).join("head-name");- if let Ok(content) = std::fs::read_to_string(head_name_path) {- let branch_ref = content.trim();- // Strip refs/heads/ prefix if present- let branch = branch_ref- .strip_prefix("refs/heads/")- .unwrap_or(branch_ref)- .to_string();- return Some(branch);- }- }-- None-}--/// Finalize a worktree after parsing, filling in branch name from rebase state if needed.-fn finalize_worktree(mut wt: Worktree) -> Worktree {- // If detached but no branch, check if we're rebasing- if wt.detached- && wt.branch.is_none()- && let Some(branch) = read_rebase_branch(&wt.path)- {- wt.branch = Some(branch);- }- wt-}--pub(crate) fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {- let mut worktrees = Vec::new();- let mut current: Option<Worktree> = None;-- for line in output.lines() {- if line.is_empty() {- if let Some(wt) = current.take() {- worktrees.push(finalize_worktree(wt));- }- continue;- }-- let (key, value) = match line.split_once(' ') {- Some((k, v)) => (k, Some(v)),- None => (line, None),- };-- match key {- "worktree" => {- let path = value.ok_or_else(|| {- GitError::ParseError("worktree line missing path".to_string())- })?;- current = Some(Worktree {- path: PathBuf::from(path),- head: String::new(),- branch: None,- bare: false,- detached: false,- locked: None,- prunable: None,- });- }- "HEAD" => {- if let Some(ref mut wt) = current {- wt.head = value- .ok_or_else(|| GitError::ParseError("HEAD line missing SHA".to_string()))?- .to_string();- }- }- "branch" => {- if let Some(ref mut wt) = current {- // Strip refs/heads/ prefix if present- let branch_ref = value.ok_or_else(|| {- GitError::ParseError("branch line missing ref".to_string())- })?;- let branch = branch_ref- .strip_prefix("refs/heads/")- .unwrap_or(branch_ref)- .to_string();- wt.branch = Some(branch);- }- }- "bare" => {- if let Some(ref mut wt) = current {- wt.bare = true;- }- }- "detached" => {- if let Some(ref mut wt) = current {- wt.detached = true;- }- }- "locked" => {- if let Some(ref mut wt) = current {- wt.locked = Some(value.unwrap_or_default().to_string());- }- }- "prunable" => {- if let Some(ref mut wt) = current {- wt.prunable = Some(value.unwrap_or_default().to_string());- }- }- _ => {- // Ignore unknown attributes for forward compatibility- }- }- }-- // Push the last worktree if the output doesn't end with a blank line- if let Some(wt) = current {- worktrees.push(finalize_worktree(wt));- }-- Ok(worktrees)-}--pub(crate) fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {- let trimmed = output.trim();-- // Strip "remote/" prefix if present- let prefix = format!("{}/", remote);- let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);-- if branch.is_empty() {- return Err(GitError::ParseError(format!(- "Empty branch name from {}/HEAD",- remote- )));- }-- Ok(branch.to_string())-}--pub(crate) fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {- output- .lines()- .find_map(|line| {- line.strip_prefix("ref: ")- .and_then(|symref| symref.split_once('\t'))- .map(|(ref_path, _)| ref_path)- .and_then(|ref_path| ref_path.strip_prefix("refs/heads/"))- .map(|branch| branch.to_string())- })- .ok_or_else(|| {- GitError::ParseError("Could not find symbolic ref in ls-remote output".to_string())- })-}--pub(crate) fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {- let mut total_added = 0;- let mut total_deleted = 0;-- for line in output.lines() {- if line.trim().is_empty() {- continue;- }-- let mut parts = line.split('\t');- let Some(added_str) = parts.next() else {- continue;- };- let Some(deleted_str) = parts.next() else {- continue;- };-- // Binary files show "-" for added/deleted- if added_str == "-" || deleted_str == "-" {- continue;- }-- // Skip malformed lines (e.g., missing tabs) by treating parse errors as non-fatal- let Ok(added) = added_str.parse::<usize>() else {- continue;- };- let Ok(deleted) = deleted_str.parse::<usize>() else {- continue;- };-- total_added += added;- total_deleted += deleted;- }-- Ok((total_added, total_deleted))-}-#[cfg(test)]mod tests {+ use super::super::finalize_worktree;use super::*;#[test]diff --git a/src/git_parse_test.rs b/src/git/test.rssimilarity index 99%rename from src/git_parse_test.rsrename to src/git/test.rsindex e89959462..f564e7217 100644--- a/src/git_parse_test.rs+++ b/src/git/test.rs@@ -3,7 +3,7 @@//! These tests target edge cases and error conditions in git output parsing//! that are likely to reveal bugs in real-world usage.-use crate::git::{+use super::{GitError, parse_local_default_branch, parse_numstat, parse_remote_default_branch,parse_worktree_list,};diff --git a/src/lib.rs b/src/lib.rsindex 02e3ef785..6c3cdef36 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -5,12 +5,3 @@ pub mod styling;// Re-export HookType for conveniencepub use git::HookType;--// Note: display, commands, and llm modules are used by main.rs but not exposed as public API-// Test comment--#[cfg(test)]-mod config_template_test;--#[cfg(test)]-mod git_parse_test;