Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor git status parsing to use NUL-separated output
Maximilian Roos58fd1816223d
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex abf93f9a0..0b8847378 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -67,8 +67,9 @@ impl RepositoryCliExt for Repository {}fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()> {+ // Use -z for NUL-separated output to handle filenames with spaces/newlineslet status = self- .run_command(&["status", "--porcelain"])+ .run_command(&["status", "--porcelain", "-z"]).context("Failed to get status")?;AutoStageWarning::from_status(&status).emit()}@@ -325,12 +326,36 @@ struct AutoStageWarning {}impl AutoStageWarning {+ /// Parse `git status --porcelain -z` output for untracked files.+ ///+ /// Format: "XY path\0" where XY is the status code and path follows a space.+ /// Untracked files have status "??".fn from_status(status_output: &str) -> Self {- let files = status_output- .lines()- .filter_map(|line| line.strip_prefix("?? "))- .map(|filename| filename.to_string())- .collect();+ let mut files = Vec::new();+ let mut entries = status_output+ .split('\0')+ .filter(|s| !s.is_empty())+ .peekable();++ while let Some(entry) = entries.next() {+ // Format: "XY PATH" where XY is 2 status chars, space, then path+ if entry.len() < 3 {+ continue;+ }++ let status = &entry[0..2];+ let path = &entry[3..];++ // Only collect untracked files+ if status == "??" {+ files.push(path.to_string());+ }++ // Skip old path for renames/copies (we don't care about them here)+ if status.starts_with('R') || status.starts_with('C') {+ entries.next();+ }+ }Self { files }}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 48972ae11..2143733de 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -666,10 +666,34 @@ impl Repository {}/// Get files changed between base and head.+ ///+ /// For renames and copies, both old and new paths are included to ensure+ /// overlap detection works correctly (e.g., detecting conflicts when a file+ /// is renamed in one branch but has uncommitted changes under the old name).pub fn changed_files(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {let range = format!("{}..{}", base, head);- let stdout = self.run_command(&["diff", "--name-only", &range])?;- Ok(stdout.lines().map(String::from).collect())+ let stdout = self.run_command(&["diff", "--name-status", "-z", &range])?;++ // Format: STATUS\0PATH\0 or STATUS\0NEW_PATH\0OLD_PATH\0 for renames/copies+ let mut files = Vec::new();+ let mut parts = stdout.split('\0').filter(|s| !s.is_empty());++ while let Some(status) = parts.next() {+ let path = parts+ .next()+ .ok_or_else(|| anyhow::anyhow!("Malformed git diff output: status without path"))?;+ files.push(path.to_string());++ // For renames (R) and copies (C), the old path follows+ if status.starts_with('R') || status.starts_with('C') {+ let old_path = parts.next().ok_or_else(|| {+ anyhow::anyhow!("Malformed git diff output: rename/copy without old path")+ })?;+ files.push(old_path.to_string());+ }+ }++ Ok(files)}/// Get commit timestamp in seconds since epoch.diff --git a/src/llm.rs b/src/llm.rsindex 4e28389e8..51964ec67 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -446,11 +446,12 @@ pub fn generate_commit_message(// Fallback: generate a descriptive commit message based on changed fileslet repo = Repository::current();- let file_list = repo.run_command(&["diff", "--staged", "--name-only"])?;+ // Use -z for NUL-separated output to handle filenames with spaces/newlines+ let file_list = repo.run_command(&["diff", "--staged", "--name-only", "-z"])?;let staged_files = file_list- .lines()- .map(|line| line.trim())- .filter(|line| !line.is_empty())+ .split('\0')+ .map(|s| s.trim())+ .filter(|s| !s.is_empty()).map(|path| {Path::new(path).file_name()diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rsindex 8ef7e30d4..f5fa100cb 100644--- a/tests/integration_tests/push.rs+++ b/tests/integration_tests/push.rs@@ -129,6 +129,73 @@ fn test_push_dirty_target_autostash(mut repo: TestRepo) {);}+#[rstest]+fn test_push_dirty_target_overlap_renamed_file(mut repo: TestRepo) {+ // Regression test: overlap detection must detect conflicts when a file is renamed+ // in the source branch but has uncommitted changes under the old name in the target.+ //+ // Setup:+ // 1. main has file.txt (committed)+ // 2. main (target) has uncommitted modifications to file.txt+ // 3. feature renames file.txt -> renamed.txt (committed)+ // 4. Push from feature to main should FAIL (conflict on the same file)++ // Create initial file in main+ repo.commit_in_worktree(+ repo.root_path(),+ "file.txt",+ "original content",+ "Initial file",+ );++ // Create feature branch from main+ let feature_wt = repo.add_worktree("feature");++ // Make uncommitted changes to file.txt in main (target worktree)+ std::fs::write(repo.root_path().join("file.txt"), "modified in target").unwrap();++ // In feature worktree, rename file.txt to renamed.txt and commit+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["mv", "file.txt", "renamed.txt"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Rename file.txt to renamed.txt"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ // Try to push from feature to main (should fail due to conflicting changes)+ // The renamed file.txt (now renamed.txt) conflicts with uncommitted file.txt changes+ snapshot_push(+ "push_dirty_target_overlap_renamed_file",+ &repo,+ &["main"],+ Some(&feature_wt),+ );++ // Ensure target worktree still has the modified file.txt and no stash was created+ let main_contents = std::fs::read_to_string(repo.root_path().join("file.txt")).unwrap();+ assert_eq!(main_contents, "modified in target");++ let mut git_cmd = Command::new("git");+ repo.configure_git_cmd(&mut git_cmd);+ let stash_list = git_cmd+ .args(["stash", "list"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ assert!(+ String::from_utf8_lossy(&stash_list.stdout)+ .trim()+ .is_empty()+ );+}+#[rstest]fn test_push_error_not_fast_forward(mut repo: TestRepo) {// Create feature branch from initial commitdiff --git a/tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap_renamed_file.snap b/tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap_renamed_file.snapnew file mode 100644index 000000000..fcb7dd7e1--- /dev/null+++ b/tests/snapshots/integration__integration_tests__push__push_dirty_target_overlap_renamed_file.snap@@ -0,0 +1,36 @@+---+source: tests/integration_tests/push.rs+info:+ program: wt+ args:+ - step+ - push+ - main+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ SOURCE_DATE_EPOCH: "1735776000"+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+❌ [31mCannot push: conflicting uncommitted changes in:[39m++[107m [0m file.txt++💡 [2mCommit or stash these changes in [REPO] first[22m