Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor color detection and add error snapshots
Maximilian Roos4873e3806942
diff --git a/benches/list.rs b/benches/list.rsindex 2d3a735ab..3c621fea2 100644--- a/benches/list.rs+++ b/benches/list.rs@@ -128,7 +128,7 @@ fn add_worktree_with_divergence(// Get current HEAD to diverge fromlet head_output = Command::new("git")- .args(&["rev-parse", "HEAD"])+ .args(["rev-parse", "HEAD"]).current_dir(repo_path).output().unwrap();@@ -191,7 +191,7 @@ fn bench_list_by_worktree_count(c: &mut Criterion) {// Build release binary oncelet build_output = Command::new("cargo")- .args(&["build", "--release"])+ .args(["build", "--release"]).output().unwrap();assert!(@@ -292,7 +292,7 @@ fn bench_sequential_vs_parallel(c: &mut Criterion) {// Build release binary oncelet build_output = Command::new("cargo")- .args(&["build", "--release"])+ .args(["build", "--release"]).output().unwrap();assert!(diff --git a/src/config.rs b/src/config.rsindex 629487a39..59dc32892 100644--- a/src/config.rs+++ b/src/config.rs@@ -89,7 +89,7 @@ fn validate_worktree_path(template: &str) -> Result<(), ConfigError> {pub fn format_worktree_path(template: &str, repo: &str, branch: &str) -> String {// Sanitize branch name by replacing path separators to prevent directory traversal- let safe_branch = branch.replace('/', "-").replace('\\', "-");+ let safe_branch = branch.replace(['/', '\\'], "-");template.replace("{repo}", repo).replace("{branch}", &safe_branch)diff --git a/src/error_format.rs b/src/error_format.rsindex 48d57a83e..8cb0ac209 100644--- a/src/error_format.rs+++ b/src/error_format.rs@@ -1,20 +1,24 @@use anstyle::{AnsiColor, Color, Style};use std::io::IsTerminal;-/// Determines if colored output should be used-fn should_use_color() -> bool {- // Check for force color environment variables (for testing)- if std::env::var("CLICOLOR_FORCE").is_ok() || std::env::var("FORCE_COLOR").is_ok() {+/// Determines if colored output should be used based on environment+fn should_use_color_with_env(no_color: bool, force_color: bool, is_terminal: bool) -> bool {+ if force_color {return true;}-- // Check if NO_COLOR is set (universal way to disable colors)- if std::env::var("NO_COLOR").is_ok() {+ if no_color {return false;}+ is_terminal+}- // Otherwise use TTY detection- std::io::stderr().is_terminal()+/// Determines if colored output should be used+fn should_use_color() -> bool {+ should_use_color_with_env(+ std::env::var("NO_COLOR").is_ok(),+ std::env::var("CLICOLOR_FORCE").is_ok() || std::env::var("FORCE_COLOR").is_ok(),+ std::io::stderr().is_terminal(),+ )}/// Format an error message with red color and ❌ emoji@@ -77,16 +81,6 @@ pub fn bold(text: &str) -> String {}}-/// Format text with a specific color-pub fn colored(text: &str, color: AnsiColor) -> String {- if should_use_color() {- let style = Style::new().fg_color(Some(Color::Ansi(color)));- format!("{}{}{}", style.render(), text, style.render_reset())- } else {- text.to_string()- }-}-/// Format an error message with bold emphasis on specific parts////// Example: `format_error_with_bold("Branch '", "feature-x", "' already exists")`@@ -116,63 +110,20 @@ mod tests {use super::*;#[test]- fn test_format_error_no_color() {- // Ensure NO_COLOR disables formatting- unsafe {- std::env::set_var("NO_COLOR", "1");- }- let result = format_error("Test error");- assert_eq!(result, "❌ Test error");- unsafe {- std::env::remove_var("NO_COLOR");- }- }-- #[test]- fn test_format_error_with_bold_no_color() {- unsafe {- std::env::set_var("NO_COLOR", "1");- }- let result = format_error_with_bold("Branch '", "main", "' already exists");- assert_eq!(result, "❌ Branch 'main' already exists");- unsafe {- std::env::remove_var("NO_COLOR");- }- }-- #[test]- fn test_format_warning() {- unsafe {- std::env::set_var("NO_COLOR", "1");- }- let result = format_warning("Test warning");- assert_eq!(result, "🟡 Test warning");- unsafe {- std::env::remove_var("NO_COLOR");- }+ fn test_should_use_color_force_color() {+ assert!(should_use_color_with_env(false, true, false));+ assert!(should_use_color_with_env(true, true, false));}#[test]- fn test_format_hint() {- unsafe {- std::env::set_var("NO_COLOR", "1");- }- let result = format_hint("Test hint");- assert_eq!(result, "💡 Test hint");- unsafe {- std::env::remove_var("NO_COLOR");- }+ fn test_should_use_color_no_color() {+ assert!(!should_use_color_with_env(true, false, true));+ assert!(!should_use_color_with_env(true, false, false));}#[test]- fn test_bold() {- unsafe {- std::env::set_var("NO_COLOR", "1");- }- let result = bold("important");- assert_eq!(result, "important");- unsafe {- std::env::remove_var("NO_COLOR");- }+ fn test_should_use_color_terminal() {+ assert!(should_use_color_with_env(false, false, true));+ assert!(!should_use_color_with_env(false, false, false));}}diff --git a/src/main.rs b/src/main.rsindex 8e9fdef99..0d54f76c9 100644--- a/src/main.rs+++ b/src/main.rs@@ -5,7 +5,7 @@ use rayon::prelude::*;use std::io;use std::process;use worktrunk::config::{format_worktree_path, load_config};-use worktrunk::error_format::{format_error_with_bold, format_hint, format_warning};+use worktrunk::error_format::{format_error, format_error_with_bold, format_hint, format_warning};use worktrunk::git::{GitError, Worktree, branch_exists, count_commits, get_ahead_behind_in, get_all_branches,get_available_branches, get_branch_diff_stats_in, get_changed_files, get_commit_timestamp_in,@@ -608,7 +608,6 @@ fn handle_switch(fn handle_remove(internal: bool) -> Result<(), GitError> {// Check for uncommitted changesif is_dirty()? {- use worktrunk::error_format::format_error;return Err(GitError::CommandFailed(format_error("Working tree has uncommitted changes. Commit or stash them first.",)));@@ -704,7 +703,6 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi// Check for merge commits unless allowedif !allow_merge_commits && has_merge_commits(&target_branch, "HEAD")? {- use worktrunk::error_format::format_error;return Err(GitError::CommandFailed(format_error("Found merge commits in push range. Use --allow-merge-commits to push non-linear history.",)));@@ -757,7 +755,6 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gi.collect();if !overlapping.is_empty() {- use worktrunk::error_format::format_error;eprintln!("{}",format_error("Cannot push: conflicting uncommitted changes in:")@@ -811,7 +808,6 @@ fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<(), Gifn handle_merge(target: Option<&str>, keep: bool) -> Result<(), GitError> {// Get current branch- use worktrunk::error_format::format_error;let current_branch = get_current_branch()?.ok_or_else(|| GitError::CommandFailed(format_error("Not on a branch (detached HEAD)")))?;@@ -829,7 +825,6 @@ fn handle_merge(target: Option<&str>, keep: bool) -> Result<(), GitError> {// Check for uncommitted changesif is_dirty()? {- use worktrunk::error_format::format_error;return Err(GitError::CommandFailed(format_error("Working tree has uncommitted changes. Commit or stash them first.",)));diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex c0a69a522..aa36715bf 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -212,3 +212,20 @@ fn test_merge_to_default_branch() {// Merge without specifying target (should use default branch)snapshot_merge("merge_to_default", &repo, &[], Some(&feature_wt));}++#[test]+fn test_merge_error_detached_head() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Detach HEAD in the repo+ repo.detach_head();++ // Try to merge (should fail - detached HEAD)+ snapshot_merge(+ "merge_error_detached_head",+ &repo,+ &["main"],+ Some(repo.root_path()),+ );+}diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rsindex bcf22dc6e..af21fbaa9 100644--- a/tests/integration_tests/push.rs+++ b/tests/integration_tests/push.rs@@ -161,3 +161,136 @@ fn test_push_with_dirty_target() {// Try to push (should fail due to conflicting changes)snapshot_push("push_dirty_target", &repo, &["main"], Some(&feature_wt));}++#[test]+fn test_push_error_not_fast_forward() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create feature branch from initial commit+ let feature_wt = repo.add_worktree("feature", "feature");++ // Make a commit in the main worktree (repo root) and push it+ std::fs::write(repo.root_path().join("main-file.txt"), "main content")+ .expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "main-file.txt"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Main commit"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to commit");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["push", "origin", "main"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to push");++ // Make a commit in feature (which doesn't have main's commit)+ std::fs::write(feature_wt.join("feature.txt"), "feature content")+ .expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "feature.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Feature commit"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Try to push feature to main (should fail - main has commits not in feature)+ snapshot_push(+ "push_error_not_fast_forward",+ &repo,+ &["main"],+ Some(&feature_wt),+ );+}++#[test]+fn test_push_error_with_merge_commits() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create feature branch+ let feature_wt = repo.add_worktree("feature", "feature");+ std::fs::write(feature_wt.join("file1.txt"), "content1").expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "file1.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Commit 1"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Create another branch for merging+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["checkout", "-b", "temp"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to create temp branch");++ std::fs::write(feature_wt.join("file2.txt"), "content2").expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "file2.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Commit 2"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Switch back to feature and merge temp (creating merge commit)+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["checkout", "feature"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to checkout feature");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["merge", "temp", "--no-ff", "-m", "Merge temp"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to merge");++ // Try to push to main (should fail - has merge commits)+ snapshot_push(+ "push_error_with_merge_commits",+ &repo,+ &["main"],+ Some(&feature_wt),+ );+}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 3998cbf13..e041ade53 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -95,3 +95,18 @@ fn test_switch_existing_worktree_internal() {&["--internal", "existing-wt"],);}++#[test]+fn test_switch_error_missing_worktree_directory() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a worktree+ let wt_path = repo.add_worktree("missing-wt", "missing-wt");++ // Remove the worktree directory (but leave it registered in git)+ std::fs::remove_dir_all(&wt_path).expect("Failed to remove worktree directory");++ // Try to switch to the missing worktree (should fail)+ snapshot_switch("switch_error_missing_directory", &repo, &["missing-wt"]);+}diff --git a/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap b/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snapnew file mode 100644index 000000000..b7983b32c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_error_detached_head.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m❌ Not on a branch (detached HEAD)[0mdiff --git a/tests/snapshots/integration__integration_tests__push__push_error_not_fast_forward.snap b/tests/snapshots/integration__integration_tests__push__push_error_not_fast_forward.snapnew file mode 100644index 000000000..8b8092ef7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__push__push_error_not_fast_forward.snap@@ -0,0 +1,25 @@+---+source: tests/integration_tests/push.rs+info:+ program: wt+ args:+ - push+ - main+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m❌ Not a fast-forward from '[1m[31mmain[31m' to HEAD[0m+[2m💡 The target branch has commits not in your current branch. Consider 'git pull' or 'git rebase'[0mdiff --git a/tests/snapshots/integration__integration_tests__push__push_error_with_merge_commits.snap b/tests/snapshots/integration__integration_tests__push__push_error_with_merge_commits.snapnew file mode 100644index 000000000..4b4e0214c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__push__push_error_with_merge_commits.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/push.rs+info:+ program: wt+ args:+ - push+ - main+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m❌ Found merge commits in push range. Use --allow-merge-commits to push non-linear history.[0mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snapnew file mode 100644index 000000000..70ecc784e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_missing_directory.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - missing-wt+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m❌ Worktree directory missing for '[1m[31mmissing-wt[31m'. Run 'git worktree prune' to clean up.[0m