Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Preserve command execution order from TOML and refine messaging functionality
Maximilian Roosdef1240b4272
diff --git a/Cargo.lock b/Cargo.lockindex 3c5f3cedb..670a65711 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -908,6 +908,8 @@ checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f"dependencies = ["equivalent","hashbrown 0.16.0",+ "serde",+ "serde_core",][[package]]@@ -2364,6 +2366,7 @@ dependencies = ["directories","env_logger","etcetera",+ "indexmap","insta","insta-cmd","log",diff --git a/Cargo.toml b/Cargo.tomlindex 900f5f889..40623c3a2 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -34,6 +34,7 @@ clap_complete = "4.5"config = "0.15"directories = "6.0"env_logger = "0.11"+indexmap = { version = "2.8", features = ["serde"] }etcetera = "0.11"log = "0.4"minijinja = "2.12"@@ -45,7 +46,7 @@ shellexpand = "3.1"strum = { version = "0.27", features = ["derive"] }synoptic = "2"terminal_size = "0.4"-toml = "0.9"+toml = { version = "0.9", features = ["preserve_order"] }tree-sitter = "0.25"tree-sitter-bash = "0.25"tree-sitter-highlight = "0.25"diff --git a/src/config.rs b/src/config.rsindex 38b252e05..c0432f6fa 100644--- a/src/config.rs+++ b/src/config.rs@@ -37,6 +37,7 @@//! "what commands run for this project".use config::{Config, ConfigError, File};+use indexmap::IndexMap;use serde::{Deserialize, Serialize};use std::path::PathBuf;use toml;@@ -204,6 +205,10 @@ pub struct ProjectConfig {/// - Array: `post-create-command = ["npm install", "npm test"]`/// - Named table: `[post-create-command]` followed by `install = "npm install"`///+/// **Order preservation:** Named commands preserve TOML insertion order (requires+/// `preserve_order` feature on toml crate and IndexMap for deserialization). This+/// allows users to control execution order explicitly.+////// This canonical form eliminates branching at call sites - code just iterates over commands.#[derive(Debug, Clone, PartialEq)]pub struct CommandConfig {@@ -228,7 +233,7 @@ impl<'de> Deserialize<'de> for CommandConfig {enum CommandConfigToml {Single(String),Multiple(Vec<String>),- Named(std::collections::HashMap<String, String>),+ Named(IndexMap<String, String>),}let toml = CommandConfigToml::deserialize(deserializer)?;@@ -240,9 +245,8 @@ impl<'de> Deserialize<'de> for CommandConfig {.map(|(i, cmd)| (Some((i + 1).to_string()), cmd)).collect(),CommandConfigToml::Named(map) => {- let mut pairs: Vec<_> = map.into_iter().collect();- pairs.sort_by(|a, b| a.0.cmp(&b.0));- pairs.into_iter().map(|(k, v)| (Some(k), v)).collect()+ // IndexMap preserves insertion order from TOML+ map.into_iter().map(|(k, v)| (Some(k), v)).collect()}};Ok(CommandConfig { commands })@@ -538,11 +542,14 @@ impl ProjectConfig {return Ok(None);}- let config = Config::builder()- .add_source(File::from(config_path))- .build()?;+ // Load directly with toml crate to preserve insertion order (with preserve_order feature)+ let contents = std::fs::read_to_string(&config_path)+ .map_err(|e| ConfigError::Message(format!("Failed to read config file: {}", e)))?;++ let config: ProjectConfig = toml::from_str(&contents)+ .map_err(|e| ConfigError::Message(format!("Failed to parse TOML: {}", e)))?;- Ok(Some(config.try_deserialize()?))+ Ok(Some(config))}}@@ -845,7 +852,7 @@ mod tests {let cmd_config = config.post_start_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 2);- // Names are sorted alphabetically+ // Preserves TOML insertion orderassert_eq!(commands[0],(Some("server".to_string()), "npm run dev".to_string())@@ -856,6 +863,63 @@ mod tests {);}+ #[test]+ fn test_command_config_named_preserves_toml_order() {+ // Test that named commands preserve TOML order (not alphabetical)+ let toml = r#"+ [pre-merge-command]+ insta = "cargo insta test"+ doc = "cargo doc"+ clippy = "cargo clippy"+ "#;+ let config: ProjectConfig = toml::from_str(toml).unwrap();+ let cmd_config = config.pre_merge_command.unwrap();+ let commands = cmd_config.commands();++ // Extract just the names for easier verification+ let names: Vec<_> = commands+ .iter()+ .map(|(n, _)| n.as_deref().unwrap())+ .collect();++ // Verify TOML insertion order is preserved+ assert_eq!(names, vec!["insta", "doc", "clippy"]);++ // Verify it's NOT alphabetical (which would be clippy, doc, insta)+ let mut alphabetical = names.clone();+ alphabetical.sort();+ assert_ne!(+ names, alphabetical,+ "Order should be TOML insertion order, not alphabetical"+ );+ }++ #[test]+ fn test_command_config_task_order() {+ // Test exact ordering as used in post_start tests+ let toml = r#"+[post-start-command]+task1 = "echo 'Task 1 running' > task1.txt"+task2 = "echo 'Task 2 running' > task2.txt"+"#;+ let config: ProjectConfig = toml::from_str(toml).unwrap();+ let cmd_config = config.post_start_command.unwrap();+ let commands = cmd_config.commands();++ assert_eq!(commands.len(), 2);+ // Should be in TOML order: task1, task2+ assert_eq!(+ commands[0].0.as_deref(),+ Some("task1"),+ "First command should be task1"+ );+ assert_eq!(+ commands[1].0.as_deref(),+ Some("task2"),+ "Second command should be task2"+ );+ }+#[test]fn test_project_config_both_commands() {let toml = r#"@@ -908,7 +972,7 @@ mod tests {let cmd_config = config.pre_merge_command.unwrap();let commands = cmd_config.commands();assert_eq!(commands.len(), 3);- // Names are sorted alphabetically+ // Preserves TOML insertion orderassert_eq!(commands[0],(diff --git a/src/git.rs b/src/git.rsindex 3481cd6d0..60687cb87 100644--- a/src/git.rs+++ b/src/git.rs@@ -1046,7 +1046,7 @@ fn finalize_worktree(mut wt: Worktree) -> Worktree {wt}-fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {+pub(crate) fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {let mut worktrees = Vec::new();let mut current: Option<Worktree> = None;@@ -1132,7 +1132,7 @@ fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {Ok(worktrees)}-fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {+pub(crate) fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitError> {let trimmed = output.trim();// Strip "remote/" prefix if present@@ -1149,7 +1149,7 @@ fn parse_local_default_branch(output: &str, remote: &str) -> Result<String, GitEOk(branch.to_string())}-fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {+pub(crate) fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {output.lines().find_map(|line| {@@ -1164,7 +1164,7 @@ fn parse_remote_default_branch(output: &str) -> Result<String, GitError> {})}-fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {+pub(crate) fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {let mut total_added = 0;let mut total_deleted = 0;@@ -1186,12 +1186,13 @@ fn parse_numstat(output: &str) -> Result<(usize, usize), GitError> {continue;}- let added: usize = added_str- .parse()- .map_err(|e| GitError::ParseError(format!("Failed to parse added lines: {}", e)))?;- let deleted: usize = deleted_str- .parse()- .map_err(|e| GitError::ParseError(format!("Failed to parse deleted lines: {}", e)))?;+ // 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;diff --git a/src/git_parse_test.rs b/src/git_parse_test.rsnew file mode 100644index 000000000..e89959462--- /dev/null+++ b/src/git_parse_test.rs@@ -0,0 +1,546 @@+//! Tests for git parsing functions+//!+//! 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::{+ GitError, parse_local_default_branch, parse_numstat, parse_remote_default_branch,+ parse_worktree_list,+};++#[test]+fn test_parse_worktree_list_empty_output() {+ // Bug hypothesis: Empty output might not be handled correctly+ let result = parse_worktree_list("");+ assert!(result.is_ok(), "Empty output should parse successfully");+ assert_eq!(result.unwrap().len(), 0, "Should return empty vector");+}++#[test]+fn test_parse_worktree_list_missing_head() {+ // Bug hypothesis: Worktree without HEAD field might have empty string for head+ // This could cause issues when the head field is used later+ let output = "worktree /path/to/repo\nbranch refs/heads/main\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok(), "Should parse even without HEAD field");+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);++ // This is the key assertion - what happens when HEAD is missing?+ // Current code initializes head as String::new() and only updates if HEAD line found+ assert_eq!(+ worktrees[0].head, "",+ "Missing HEAD should result in empty string (current behavior)"+ );+}++#[test]+fn test_parse_worktree_list_locked_with_empty_reason() {+ // Bug hypothesis: "locked" with no reason (just the key) might be handled incorrectly+ // Current code: `locked = Some(value.unwrap_or_default().to_string())`+ // This means locked with no value becomes Some("")+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);++ // What does locked become? Some("") or None?+ match &worktrees[0].locked {+ Some(reason) if reason.is_empty() => {+ // This is what the current code does+ println!("Locked is Some(\"\") - empty reason");+ }+ Some(reason) => {+ panic!("Expected empty reason, got: {}", reason);+ }+ None => {+ panic!("Expected Some(\"\"), got None");+ }+ }+}++#[test]+fn test_parse_worktree_list_locked_with_reason() {+ // Verify normal locked behavior works+ let output =+ "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked working on it\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);+ assert_eq!(worktrees[0].locked, Some("working on it".to_string()));+}++#[test]+fn test_parse_worktree_list_prunable_empty() {+ // Same issue as locked - prunable with no value+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);++ // Should be Some("") based on current code+ assert!(worktrees[0].prunable.is_some());+ assert_eq!(worktrees[0].prunable.as_ref().unwrap(), "");+}++#[test]+fn test_parse_worktree_list_fields_before_worktree() {+ // Bug hypothesis: If we get HEAD/branch lines before a worktree line,+ // they'll be silently ignored because current is None+ let output = "HEAD abc123\nbranch refs/heads/main\nworktree /path/to/repo\nHEAD def456\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);++ // The HEAD should be def456 (second one), not abc123 (first one that was ignored)+ assert_eq!(worktrees[0].head, "def456");+}++#[test]+fn test_parse_worktree_list_no_trailing_blank_line() {+ // Bug hypothesis: If output doesn't end with blank line,+ // the last worktree might not be added+ // Looking at the code (lines 1128-1130), this should be handled correctly+ let output = "worktree /path/to/repo1\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/repo2\nHEAD def456\nbranch refs/heads/dev";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();++ // Should have 2 worktrees - code handles this with "if let Some(wt) = current" at end+ assert_eq!(+ worktrees.len(),+ 2,+ "Should parse both worktrees even without trailing blank line"+ );+}++#[test]+fn test_parse_worktree_list_bare_repository() {+ let output = "worktree /path/to/repo\nbare\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);+ assert!(worktrees[0].bare, "Should parse bare flag");+}++#[test]+fn test_parse_worktree_list_detached_head() {+ let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);+ assert!(worktrees[0].detached, "Should parse detached flag");+}++#[test]+fn test_parse_worktree_list_branch_with_refs_prefix() {+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/feature/nested/branch\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);++ // Should strip refs/heads/ prefix+ assert_eq!(+ worktrees[0].branch,+ Some("feature/nested/branch".to_string()),+ "Should strip refs/heads/ prefix and preserve slashes in branch name"+ );+}++#[test]+fn test_parse_worktree_list_branch_without_refs_prefix() {+ // Bug hypothesis: What if git returns branch without refs/heads/ prefix?+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);+ assert_eq!(worktrees[0].branch, Some("main".to_string()));+}++#[test]+fn test_parse_worktree_list_unknown_attributes() {+ // Forward compatibility - unknown attributes should be ignored+ let output = "worktree /path/to/repo\nHEAD abc123\nfutureattr somevalue\n\n";+ let result = parse_worktree_list(output);++ assert!(+ result.is_ok(),+ "Unknown attributes should be ignored for forward compatibility"+ );+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 1);+}++#[test]+fn test_parse_worktree_list_multiple_worktrees() {+ let output = "worktree /path/to/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /path/to/feature\nHEAD def456\nbranch refs/heads/feature\ndetached\n\n";+ let result = parse_worktree_list(output);++ assert!(result.is_ok());+ let worktrees = result.unwrap();+ assert_eq!(worktrees.len(), 2);++ assert_eq!(worktrees[0].branch, Some("main".to_string()));+ assert!(!worktrees[0].detached);++ assert_eq!(worktrees[1].branch, Some("feature".to_string()));+ assert!(worktrees[1].detached);+}++#[test]+fn test_parse_worktree_list_worktree_missing_path() {+ // Bug hypothesis: "worktree" line with no path should error+ let output = "worktree\nHEAD abc123\n\n";+ let result = parse_worktree_list(output);++ // Current code: value.ok_or_else(|| GitError::ParseError("worktree line missing path"))+ assert!(result.is_err(), "Worktree without path should error");+ match result {+ Err(GitError::ParseError(msg)) => {+ assert!(+ msg.contains("missing path"),+ "Error should mention missing path"+ );+ }+ _ => panic!("Expected ParseError about missing path"),+ }+}++#[test]+fn test_parse_worktree_list_head_missing_sha() {+ // Bug hypothesis: "HEAD" line with no SHA should error+ let output = "worktree /path/to/repo\nHEAD\nbranch refs/heads/main\n\n";+ let result = parse_worktree_list(output);++ // Current code: value.ok_or_else(|| GitError::ParseError("HEAD line missing SHA"))+ assert!(result.is_err(), "HEAD without SHA should error");+ match result {+ Err(GitError::ParseError(msg)) => {+ assert!(+ msg.contains("missing SHA"),+ "Error should mention missing SHA"+ );+ }+ _ => panic!("Expected ParseError about missing SHA"),+ }+}++#[test]+fn test_parse_worktree_list_branch_missing_ref() {+ // Bug hypothesis: "branch" line with no ref should error+ let output = "worktree /path/to/repo\nHEAD abc123\nbranch\n\n";+ let result = parse_worktree_list(output);++ // Current code: value.ok_or_else(|| GitError::ParseError("branch line missing ref"))+ assert!(result.is_err(), "Branch without ref should error");+ match result {+ Err(GitError::ParseError(msg)) => {+ assert!(+ msg.contains("missing ref"),+ "Error should mention missing ref"+ );+ }+ _ => panic!("Expected ParseError about missing ref"),+ }+}++// Tests for parse_remote_default_branch++#[test]+fn test_parse_remote_default_branch_normal() {+ // Normal git ls-remote output for HEAD+ let output = "ref: refs/heads/main\tHEAD\n";+ let result = parse_remote_default_branch(output);++ assert!(result.is_ok());+ assert_eq!(result.unwrap(), "main");+}++#[test]+fn test_parse_remote_default_branch_with_feature_branch() {+ // Remote default is a feature branch with slashes+ let output = "ref: refs/heads/feature/nested/branch\tHEAD\n";+ let result = parse_remote_default_branch(output);++ assert!(result.is_ok());+ assert_eq!(result.unwrap(), "feature/nested/branch");+}++#[test]+fn test_parse_remote_default_branch_empty_output() {+ // Bug hypothesis: Empty output should error, not panic+ let output = "";+ let result = parse_remote_default_branch(output);++ assert!(result.is_err(), "Empty output should return an error");+ match result {+ Err(GitError::ParseError(msg)) => {+ assert!(+ msg.contains("symbolic ref"),+ "Error should mention symbolic ref"+ );+ }+ _ => panic!("Expected ParseError"),+ }+}++#[test]+fn test_parse_remote_default_branch_no_ref_prefix() {+ // Bug hypothesis: Line without "ref: " prefix should be ignored+ let output = "refs/heads/main\tHEAD\n";+ let result = parse_remote_default_branch(output);++ // Should error because no line matches the pattern+ assert!(result.is_err());+}++#[test]+fn test_parse_remote_default_branch_missing_tab() {+ // Bug hypothesis: What if there's no tab separator?+ // Looking at the code: line.split_once('\t') returns None, so line is ignored+ let output = "ref: refs/heads/main";+ let result = parse_remote_default_branch(output);++ // Should error because split_once returns None+ assert!(result.is_err(), "Missing tab should cause error");+}++#[test]+fn test_parse_remote_default_branch_multiple_lines() {+ // Bug hypothesis: Multiple matching lines - should use first match+ let output = "ref: refs/heads/main\tHEAD\nref: refs/heads/develop\tHEAD\n";+ let result = parse_remote_default_branch(output);++ assert!(result.is_ok());+ // find_map returns first match+ assert_eq!(result.unwrap(), "main");+}++#[test]+fn test_parse_remote_default_branch_missing_refs_heads_prefix() {+ // Bug hypothesis: What if the ref doesn't have refs/heads/ prefix?+ // Looking at the code: strip_prefix returns None, so line is ignored+ let output = "ref: main\tHEAD\n";+ let result = parse_remote_default_branch(output);++ // Should error because strip_prefix fails+ assert!(result.is_err());+}++// Tests for parse_local_default_branch++#[test]+fn test_parse_local_default_branch_normal() {+ let result = parse_local_default_branch("origin/main", "origin");++ assert!(result.is_ok());+ assert_eq!(result.unwrap(), "main");+}++#[test]+fn test_parse_local_default_branch_without_remote_prefix() {+ // Bug hypothesis: If output doesn't have remote prefix, just return it as-is+ let result = parse_local_default_branch("main", "origin");++ assert!(result.is_ok());+ // strip_prefix fails, so unwrap_or returns original+ assert_eq!(result.unwrap(), "main");+}++#[test]+fn test_parse_local_default_branch_with_nested_slashes() {+ // Bug hypothesis: Branch name like "feature/sub/branch" might break if we have+ // multiple slashes. Let's verify it works correctly.+ let result = parse_local_default_branch("origin/feature/sub/branch", "origin");++ assert!(result.is_ok());+ // Should strip only "origin/" prefix, leaving "feature/sub/branch"+ assert_eq!(result.unwrap(), "feature/sub/branch");+}++#[test]+fn test_parse_local_default_branch_empty_output() {+ // Bug hypothesis: Empty string after trimming should error+ let result = parse_local_default_branch("", "origin");++ assert!(result.is_err(), "Empty output should error");+ match result {+ Err(GitError::ParseError(msg)) => {+ assert!(+ msg.contains("Empty branch"),+ "Error should mention empty branch"+ );+ }+ _ => panic!("Expected ParseError about empty branch"),+ }+}++#[test]+fn test_parse_local_default_branch_whitespace_only() {+ // Bug hypothesis: Whitespace-only input should error after trim+ let result = parse_local_default_branch(" \n ", "origin");++ assert!(result.is_err(), "Whitespace-only should error");+}++#[test]+fn test_parse_local_default_branch_empty_remote() {+ // Bug hypothesis: What if remote name is empty?+ // This creates prefix = "/" which might match branch names starting with /+ let result = parse_local_default_branch("/weird/branch", "");++ assert!(result.is_ok());+ // Strips "/" prefix, leaving "weird/branch"+ assert_eq!(result.unwrap(), "weird/branch");+}++// Tests for parse_numstat++#[test]+fn test_parse_numstat_normal() {+ let output = "10\t5\tfile1.rs\n3\t2\tfile2.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 13, "Should sum added lines");+ assert_eq!(deleted, 7, "Should sum deleted lines");+}++#[test]+fn test_parse_numstat_empty_output() {+ // Bug hypothesis: Empty output should return (0, 0), not error+ let result = parse_numstat("");++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0);+ assert_eq!(deleted, 0);+}++#[test]+fn test_parse_numstat_binary_files() {+ // Binary files show "-" for added/deleted+ let output = "10\t5\tfile1.rs\n-\t-\timage.png\n3\t2\tfile2.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ // Should skip the binary file line+ assert_eq!(added, 13);+ assert_eq!(deleted, 7);+}++#[test]+fn test_parse_numstat_mixed_binary() {+ // Bug hypothesis: What if only one side is "-"?+ // Current code checks "if added_str == '-' || deleted_str == '-'"+ // So it skips the line if EITHER is "-"+ let output = "10\t-\tfile1.rs\n-\t5\tfile2.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ // Both lines should be skipped+ assert_eq!(added, 0);+ assert_eq!(deleted, 0);+}++#[test]+fn test_parse_numstat_empty_lines() {+ let output = "10\t5\tfile1.rs\n\n3\t2\tfile2.rs\n\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ // Empty lines should be skipped+ assert_eq!(added, 13);+ assert_eq!(deleted, 7);+}++#[test]+fn test_parse_numstat_malformed_missing_second_value() {+ // BUG FIXED: Line with only one tab used to try to parse filename as number+ // Input: "10\tfile.rs\n"+ // parts.next() -> Some("10") ✓+ // parts.next() -> Some("file.rs") ✓ (not None!)+ // Old behavior: tried to parse "file.rs" as usize -> ERROR+ // New behavior: skip malformed lines gracefully+ //+ // The real git numstat format is: <added>\t<deleted>\t<filename>+ let output = "10\tfile.rs\n";+ let result = parse_numstat(output);++ // Fixed: Malformed lines are now skipped instead of causing errors+ assert!(result.is_ok(), "Malformed lines should be skipped");+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0, "Malformed line should be skipped");+ assert_eq!(deleted, 0, "Malformed line should be skipped");+}++#[test]+fn test_parse_numstat_malformed_missing_first_value() {+ // Bug hypothesis: Line with no tabs+ // parts.next() returns the whole line, parts.next() again returns None+ let output = "file.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ // Line should be skipped+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0);+ assert_eq!(deleted, 0);+}++#[test]+fn test_parse_numstat_non_numeric_values() {+ // Non-numeric values should be skipped (after the fix)+ let output = "abc\t5\tfile.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok(), "Malformed lines should be skipped");+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0, "Non-numeric line should be skipped");+ assert_eq!(deleted, 0, "Non-numeric line should be skipped");+}++#[test]+fn test_parse_numstat_non_numeric_deleted() {+ // Non-numeric deleted value should be skipped+ let output = "5\txyz\tfile.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok(), "Malformed lines should be skipped");+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0, "Non-numeric line should be skipped");+ assert_eq!(deleted, 0, "Non-numeric line should be skipped");+}++#[test]+fn test_parse_numstat_zero_values() {+ let output = "0\t0\tfile.rs\n";+ let result = parse_numstat(output);++ assert!(result.is_ok());+ let (added, deleted) = result.unwrap();+ assert_eq!(added, 0);+ assert_eq!(deleted, 0);+}diff --git a/src/lib.rs b/src/lib.rsindex dd2c72946..74b5a1157 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -8,3 +8,6 @@ pub 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 git_parse_test;diff --git a/src/output/directive.rs b/src/output/directive.rsindex ab12c40a8..3b5e3a630 100644--- a/src/output/directive.rs+++ b/src/output/directive.rs@@ -164,4 +164,147 @@ mod tests {// Directive mode preserves styling for users viewing through shell wrapper// (We're not testing actual output here, just documenting the behavior)}++ #[test]+ fn test_path_with_special_characters() {+ // BUG HYPOTHESIS: Paths with newlines or NUL bytes could break directive parsing+ let mut buffer = Vec::new();++ // Path with newline (shouldn't normally happen, but let's test)+ let path = PathBuf::from("/test/path\nwith\nnewlines");+ write!(&mut buffer, "__WORKTRUNK_CD__{}\0", path.display()).unwrap();++ let output = String::from_utf8_lossy(&buffer);+ // The newlines are preserved - this could break parsing!+ assert!(output.contains('\n'), "Newlines in path are preserved");++ // Count NUL bytes - should only be at the end+ let nul_positions: Vec<_> = buffer+ .iter()+ .enumerate()+ .filter(|&(_, &b)| b == 0)+ .map(|(i, _)| i)+ .collect();+ assert_eq!(+ nul_positions.len(),+ 1,+ "Should have exactly 1 NUL terminator"+ );+ assert_eq!(+ nul_positions[0],+ buffer.len() - 1,+ "NUL should be at the end"+ );+ }++ #[test]+ fn test_command_with_nul_bytes() {+ // BUG HYPOTHESIS: Commands with embedded NUL bytes could break parsing+ let mut buffer = Vec::new();++ let command = "echo test\0extra";+ write!(&mut buffer, "__WORKTRUNK_EXEC__{}\0", command).unwrap();++ // Count NUL bytes+ let nul_count = buffer.iter().filter(|&&b| b == 0).count();+ // We have 2 NUL bytes: one embedded in command, one terminator+ assert_eq!(+ nul_count, 2,+ "Embedded NUL creates extra terminator - breaks parsing!"+ );+ }++ #[test]+ fn test_message_with_nul_bytes() {+ // What if success message contains NUL bytes?+ let mut buffer = Vec::new();++ let message = "Part1\0Part2";+ write!(&mut buffer, "{}\0", message).unwrap();++ let nul_count = buffer.iter().filter(|&&b| b == 0).count();+ // Embedded NUL plus terminator = 2 NUL bytes+ assert_eq!(nul_count, 2, "Embedded NUL creates parsing ambiguity!");+ }++ #[test]+ fn test_color_reset_on_empty_style() {+ // BUG HYPOTHESIS from CLAUDE.md (lines 154-177):+ // Using {:#} on Style::new() produces empty string, not reset code+ use anstyle::Style;++ let empty_style = Style::new();+ let output = format!("{:#}", empty_style);++ // This is the bug: {:#} on empty style produces empty string!+ assert_eq!(+ output, "",+ "BUG: Empty style reset produces empty string, not \\x1b[0m"+ );++ // This means colors can leak: "text in color{:#}" where # is on empty Style+ // doesn't actually reset, it just removes the style prefix!+ }++ #[test]+ fn test_proper_reset_with_anstyle_reset() {+ // The correct way to reset ALL styles is anstyle::Reset+ use anstyle::Reset;++ let output = format!("{}", Reset);++ // This should produce the actual reset escape code+ assert!(+ output.contains("\x1b[0m") || output == "\x1b[0m",+ "Reset should produce actual ANSI reset code"+ );+ }++ #[test]+ fn test_nested_style_resets_leak_color() {+ // BUG HYPOTHESIS from CLAUDE.md:+ // Nested style resets can leak colors+ use anstyle::{AnsiColor, Color, Style};++ let warning = Style::new().fg_color(Some(Color::Ansi(AnsiColor::Yellow)));+ let bold = Style::new().bold();++ // BAD pattern: nested reset+ let bad_output = format!("{warning}Text with {bold}nested{bold:#} styles{warning:#}");++ // When {bold:#} resets, it might also reset the warning color!+ // We can't easily test the actual ANSI codes here, but document the issue+ println!(+ "Nested reset output: {}",+ bad_output.replace('\x1b', "\\x1b")+ );++ // GOOD pattern: compose styles+ let warning_bold = warning.bold();+ let good_output =+ format!("{warning}Text with {warning_bold}composed{warning_bold:#} styles{warning:#}");+ println!("Composed output: {}", good_output.replace('\x1b', "\\x1b"));++ // The good pattern maintains color through the bold section+ }++ #[test]+ fn test_path_with_ansi_codes() {+ // BUG HYPOTHESIS: What if a path somehow contains ANSI codes?+ // (This could happen with crafted directory names)+ let mut buffer = Vec::new();++ let path = PathBuf::from("/test/\x1b[31mred\x1b[0m/path");+ write!(&mut buffer, "__WORKTRUNK_CD__{}\0", path.display()).unwrap();++ let output = String::from_utf8_lossy(&buffer);+ // ANSI codes are preserved in the directive!+ assert!(+ output.contains('\x1b'),+ "ANSI codes in path leak into directive"+ );++ // This could cause the shell to display colored output when parsing the directive+ // or interfere with directive parsing+ }}diff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snapindex 1d446449c..caccb541f 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snap@@ -17,7 +17,7 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpwsFyAO/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpilIeZf/test-config.toml---success: trueexit_code: 0@@ -32,12 +32,12 @@ exit_code: 0✅ [32mMerged to [1m[32mmain[0m[0m (1 commit, 1 file, [32m+1[0m)✅ [32mReturned to primary at [1m[32m[REPO][0m[0m🔄 [36mRemoving worktree & branch...[0m-🔄 [36mRunning post-merge: [1mdeploy[0m[0m-[40m [0m [1m[34mecho[0m [32m'Deploying branch feature'[0m [36m>[0m deploy.txt[0m-🔄 [36mRunning post-merge: [1mnotify[0m[0m[40m [0m [1m[34mecho[0m [32m'Merge to main complete'[0m [36m>[0m notify.txt[0m+🔄 [36mRunning post-merge: [1mdeploy[0m[0m+[40m [0m [1m[34mecho[0m [32m'Deploying branch feature'[0m [36m>[0m deploy.txt[0m+----- stderr -----[0m[0mdiff --git a/tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap b/tests/snapshots/integration__integration_tests__merge__readme_example_complex.snapindex ffc2b429a..978922697 100644--- a/tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap+++ b/tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap@@ -16,9 +16,9 @@ info:GIT_EDITOR: ""LANG: CLC_ALL: C- PATH: "/private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRAGvvU/test-repo/.bin:/Users/maximilian/.cargo/bin:/Users/maximilian/.local/bin:/Users/maximilian/.bun/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"+ PATH: "/private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpeH86uP/test-repo/.bin:/Users/maximilian/.cargo/bin:/Users/maximilian/.local/bin:/Users/maximilian/.bun/bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"SOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRAGvvU/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpeH86uP/test-config.toml---success: trueexit_code: 0@@ -36,12 +36,12 @@ exit_code: 0[40m [0m - Create test suite covering all authentication flows✅ [32mSquashed @ [2m[SHA][0m-🔄 [36mRunning pre-merge: [1mlint[0m[0m-[40m [0m [1m[34mcargo[0m clippy[0m-🔄 [36mRunning pre-merge: [1mtest[0m[0m[40m [0m [1m[34mcargo[0m test[0m+🔄 [36mRunning pre-merge: [1mlint[0m[0m+[40m [0m [1m[34mcargo[0m clippy[0m+🔄 [36mMerging 1 commit to [1m[36mmain[0m @ [2m[SHA][0m (no rebase needed)* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature-auth[m[33m)[m feat(auth): Implement JWT authentication system@@ -59,8 +59,6 @@ exit_code: 0----- stderr ------[0m Checking worktrunk v0.1.0- Finished dev [unoptimized + debuginfo] target(s) in 1.23s[0m Finished test [unoptimized + debuginfo] target(s) in 0.12sRunning unittests src/lib.rs (target/debug/deps/worktrunk-abc123)@@ -71,6 +69,8 @@ test auth::tests::test_token_refresh ... oktest auth::tests::test_token_validation ... oktest result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s+[0m Checking worktrunk v0.1.0+ Finished dev [unoptimized + debuginfo] target(s) in 1.23s[0m Installing worktrunk v0.1.0Compiling worktrunk v0.1.0Finished release [optimized] target(s) in 2.34sdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snapindex fb1babd21..2f80d2dd4 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__invalid_toml.snap@@ -8,23 +8,24 @@ info:- featureenv:CLICOLOR_FORCE: "1"+ COLUMNS: "150"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpucihzx/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpg4vWIx/test-config.toml---success: falseexit_code: 1----- stdout ---------- stderr ------Failed to load project config: TOML parse error at line 1, column 39+Failed to load project config: Failed to parse TOML: TOML parse error at line 1, column 39|1 | post-create-command = [invalid syntax| ^unclosed array, expected `]`- in .config/wt.toml