Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Refactor: Centralize git command execution in `Repository`

Maximilian Roos801dfe1c6f89
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 5b4beacf8..9ebf91b42 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -1,5 +1,4 @@
use std::path::PathBuf;
-use std::process;
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, Repository};
use worktrunk::styling::{format_error, format_error_with_bold, format_hint};
@@ -201,15 +200,9 @@ pub fn handle_remove() -> Result<RemoveResult, GitError> {
let worktree_root = repo.worktree_root()?;
let primary_worktree_dir = repo.repo_root()?;
- // Schedule worktree removal (synchronous for now, could be async later)
- let remove_result = process::Command::new("git")
- .args(["worktree", "remove", worktree_root.to_str().unwrap()])
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
- if !remove_result.status.success() {
- let stderr = String::from_utf8_lossy(&remove_result.stderr);
- eprintln!("Warning: Failed to remove worktree: {}", stderr);
+ // Remove the worktree
+ if let Err(e) = repo.remove_worktree(&worktree_root) {
+ eprintln!("Warning: Failed to remove worktree: {}", e);
eprintln!(
"You may need to run 'git worktree remove {}' manually",
worktree_root.display()
@@ -311,19 +304,9 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()
}
// Configure receive.denyCurrentBranch if needed
- // TODO: These git config commands don't use repo.run_command() because they don't check
- // status.success() and may rely on exit codes for missing keys. Should be refactored.
- let deny_config_output = process::Command::new("git")
- .args(["config", "receive.denyCurrentBranch"])
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
- let current_config = String::from_utf8_lossy(&deny_config_output.stdout);
- if current_config.trim() != "updateInstead" {
- process::Command::new("git")
- .args(["config", "receive.denyCurrentBranch", "updateInstead"])
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+ let current_config = repo.get_config("receive.denyCurrentBranch")?;
+ if current_config.as_deref() != Some("updateInstead") {
+ repo.set_config("receive.denyCurrentBranch", "updateInstead")?;
}
// Check for conflicting changes in target worktree
diff --git a/src/git.rs b/src/git.rs
index 9258633b4..4e4985e9f 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -205,13 +205,7 @@ impl Repository {
/// Check if base is an ancestor of head (i.e., would be a fast-forward).
pub fn is_ancestor(&self, base: &str, head: &str) -> Result<bool, GitError> {
- let output = std::process::Command::new("git")
- .args(["merge-base", "--is-ancestor", base, head])
- .current_dir(&self.path)
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
- Ok(output.status.success())
+ self.run_command_check(&["merge-base", "--is-ancestor", base, head])
}
/// Count commits between base and head.
@@ -365,14 +359,9 @@ impl Repository {
/// Check if there are staged changes.
pub fn has_staged_changes(&self) -> Result<bool, GitError> {
- let output = std::process::Command::new("git")
- .args(["diff", "--cached", "--quiet", "--exit-code"])
- .current_dir(&self.path)
- .output()
- .map_err(|e| GitError::CommandFailed(e.to_string()))?;
-
// exit code 0 = no changes, 1 = has changes
- Ok(!output.status.success())
+ let no_changes = self.run_command_check(&["diff", "--cached", "--quiet", "--exit-code"])?;
+ Ok(!no_changes)
}
/// List all worktrees for this repository.
@@ -407,6 +396,29 @@ impl Repository {
.collect())
}
+ /// Get a git config value. Returns None if the key doesn't exist.
+ pub fn get_config(&self, key: &str) -> Result<Option<String>, GitError> {
+ match self.run_command(&["config", key]) {
+ Ok(value) => Ok(Some(value.trim().to_string())),
+ Err(_) => Ok(None), // Config key doesn't exist
+ }
+ }
+
+ /// Set a git config value.
+ pub fn set_config(&self, key: &str, value: &str) -> Result<(), GitError> {
+ self.run_command(&["config", key, value])?;
+ Ok(())
+ }
+
+ /// Remove a worktree at the specified path.
+ pub fn remove_worktree(&self, path: &std::path::Path) -> Result<(), GitError> {
+ let path_str = path
+ .to_str()
+ .ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in worktree path".to_string()))?;
+ self.run_command(&["worktree", "remove", path_str])?;
+ Ok(())
+ }
+
// Private helper methods for default_branch()
fn get_local_default_branch(&self, remote: &str) -> Result<String, GitError> {
@@ -454,6 +466,31 @@ impl Repository {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}
+
+ /// Run a git command and return whether it succeeded (exit code 0).
+ ///
+ /// This is useful for commands that use exit codes for boolean results,
+ /// like `git merge-base --is-ancestor` or `git diff --quiet`.
+ ///
+ /// # Examples
+ /// ```no_run
+ /// use worktrunk::git::Repository;
+ ///
+ /// let repo = Repository::current();
+ /// let is_clean = repo.run_command_check(&["diff", "--quiet", "--exit-code"])?;
+ /// # Ok::<(), worktrunk::git::GitError>(())
+ /// ```
+ pub fn run_command_check(&self, args: &[&str]) -> Result<bool, GitError> {
+ let mut cmd = Command::new("git");
+ cmd.args(args);
+ cmd.current_dir(&self.path);
+
+ let output = cmd
+ .output()
+ .map_err(|e| GitError::CommandFailed(e.to_string()))?;
+
+ Ok(output.status.success())
+ }
}
fn parse_worktree_list(output: &str) -> Result<Vec<Worktree>, GitError> {
diff --git a/src/main.rs b/src/main.rs
index 4d76b1c4a..be98c9035 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -125,10 +125,8 @@ fn main() {
if let Some(output) = result.format_internal_output(&branch) {
println!("{}", output);
}
- } else {
- if let Some(output) = result.format_user_output(&branch) {
- println!("{}", output);
- }
+ } else if let Some(output) = result.format_user_output(&branch) {
+ println!("{}", output);
}
})
}),
@@ -137,10 +135,8 @@ fn main() {
if let Some(output) = result.format_internal_output() {
println!("{}", output);
}
- } else {
- if let Some(output) = result.format_user_output() {
- println!("{}", output);
- }
+ } else if let Some(output) = result.format_user_output() {
+ println!("{}", output);
}
}),
Commands::Push {