Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Move per-worktree methods to WorkingTree (#686)
Maximilian Roos2728e128247f
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex be66adfe0..97bead5d5 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -81,9 +81,10 @@ impl<'a> CommitGenerator<'a> {stage_mode: StageMode,) -> anyhow::Result<()> {let repo = Repository::current()?;+ let wt = repo.current_worktree();// Fail early if nothing is staged (avoids confusing LLM prompt with empty diff)- if !repo.has_staged_changes()? {+ if !wt.has_staged_changes()? {anyhow::bail!("Nothing to commit");}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 5cd9780cc..4b56cff52 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -161,7 +161,8 @@ pub fn handle_squash(let commit_count = repo.count_commits(&merge_base, "HEAD")?;// Check if there are staged changes in addition to commits- let has_staged = repo.has_staged_changes()?;+ let wt = repo.current_worktree();+ let has_staged = wt.has_staged_changes()?;// Handle different scenariosif commit_count == 0 && !has_staged {@@ -224,7 +225,7 @@ pub fn handle_squash(// Create safety backup before potentially destructive reset if there are working tree changesif has_staged {let backup_message = format!("{} → {} (squash)", current_branch, target_branch);- let sha = repo.create_safety_backup(&backup_message)?;+ let sha = wt.create_safety_backup(&backup_message)?;crate::output::print(hint_message(format!("Backup created @ {sha}")))?;}@@ -261,7 +262,7 @@ pub fn handle_squash(.context("Failed to reset to merge base")?;// Check if there are actually any changes to commit- if !repo.has_staged_changes()? {+ if !wt.has_staged_changes()? {crate::output::print(info_message(format!("No changes after squashing {commit_count} {commit_text}")))?;diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 1d6f05928..4b7c45f16 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -327,71 +327,4 @@ impl Repository {.map(|output| DiffStats::from_numstat(&output).format_summary()).unwrap_or_default()}-- /// Determine whether there are staged changes in the index.- ///- /// Returns `Ok(true)` when staged changes are present, `Ok(false)` otherwise.- pub fn has_staged_changes(&self) -> anyhow::Result<bool> {- Ok(!self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?)- }-- /// Create a safety backup of current working tree state without affecting the working tree.- ///- /// This creates a backup commit containing all changes (staged, unstaged, and untracked files)- /// and stores it in a custom ref (`refs/wt-backup/<branch>`). This creates a reflog entry- /// for recovery without polluting the stash list. The working tree remains unchanged.- ///- /// Users can find safety backups with: `git reflog show refs/wt-backup/<branch>`- ///- /// Returns the short SHA of the backup commit.- ///- /// # Example- /// ```no_run- /// use worktrunk::git::Repository;- ///- /// let repo = Repository::current()?;- /// let sha = repo.create_safety_backup("feature → main (squash)")?;- /// println!("Backup created: {}", sha);- /// # Ok::<(), anyhow::Error>(())- /// ```- pub fn create_safety_backup(&self, message: &str) -> anyhow::Result<String> {- // Create a backup commit using git stash create (without storing it in the stash list)- let backup_sha = self- .run_command(&["stash", "create", "--include-untracked"])?- .trim()- .to_string();-- // Validate that we got a SHA back- if backup_sha.is_empty() {- return Err(super::super::GitError::Other {- message: "git stash create returned empty SHA - no changes to backup".into(),- }- .into());- }-- // Get current branch name to use in the ref name- let branch = self- .run_command(&["rev-parse", "--abbrev-ref", "HEAD"])?- .trim()- .to_string();-- // Sanitize branch name for use in ref path (replace / with -)- let safe_branch = branch.replace('/', "-");-- // Update a custom ref to point to this commit- // --create-reflog ensures the reflog is created for this custom ref- // This creates a reflog entry but doesn't add to the stash list- let ref_name = format!("refs/wt-backup/{}", safe_branch);- self.run_command(&[- "update-ref",- "--create-reflog",- "-m",- message,- &ref_name,- &backup_sha,- ])- .context("Failed to create backup ref")?;-- Ok(backup_sha[..7].to_string())- }}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 16b75d47d..3612862eb 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -209,4 +209,80 @@ impl<'a> WorkingTree<'a> {let stdout = self.run_command(&["diff", "--numstat", ref_name])?;LineDiff::from_numstat(&stdout)}++ /// Determine whether there are staged changes in the index.+ ///+ /// Returns `Ok(true)` when staged changes are present, `Ok(false)` otherwise.+ ///+ /// Note: The index is per-worktree in git, so this checks this specific+ /// worktree's staging area.+ pub fn has_staged_changes(&self) -> anyhow::Result<bool> {+ // Exit code 0 = no diff (no staged changes), exit code 1 = diff exists (has staged changes)+ // run_command returns Ok on exit 0, Err on non-zero+ // So: Err means has changes+ Ok(self+ .run_command(&["diff", "--cached", "--quiet", "--exit-code"])+ .is_err())+ }++ /// Create a safety backup of current working tree state without affecting the working tree.+ ///+ /// This creates a backup commit containing all changes (staged, unstaged, and untracked files)+ /// and stores it in a custom ref (`refs/wt-backup/<branch>`). This creates a reflog entry+ /// for recovery without polluting the stash list. The working tree remains unchanged.+ ///+ /// Users can find safety backups with: `git reflog show refs/wt-backup/<branch>`+ ///+ /// Returns the short SHA of the backup commit.+ ///+ /// # Example+ /// ```no_run+ /// use worktrunk::git::Repository;+ ///+ /// let repo = Repository::current()?;+ /// let wt = repo.current_worktree();+ /// let sha = wt.create_safety_backup("feature → main (squash)")?;+ /// println!("Backup created: {}", sha);+ /// # Ok::<(), anyhow::Error>(())+ /// ```+ pub fn create_safety_backup(&self, message: &str) -> anyhow::Result<String> {+ // Create a backup commit using git stash create (without storing it in the stash list)+ let backup_sha = self+ .run_command(&["stash", "create", "--include-untracked"])?+ .trim()+ .to_string();++ // Validate that we got a SHA back+ if backup_sha.is_empty() {+ return Err(GitError::Other {+ message: "git stash create returned empty SHA - no changes to backup".into(),+ }+ .into());+ }++ // Get current branch name to use in the ref name+ let branch = self+ .run_command(&["rev-parse", "--abbrev-ref", "HEAD"])?+ .trim()+ .to_string();++ // Sanitize branch name for use in ref path (replace / with -)+ let safe_branch = branch.replace('/', "-");++ // Update a custom ref to point to this commit+ // --create-reflog ensures the reflog is created for this custom ref+ // This creates a reflog entry but doesn't add to the stash list+ let ref_name = format!("refs/wt-backup/{}", safe_branch);+ self.run_command(&[+ "update-ref",+ "--create-reflog",+ "-m",+ message,+ &ref_name,+ &backup_sha,+ ])+ .context("Failed to create backup ref")?;++ Ok(backup_sha[..7].to_string())+ }}