Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor: Process worktree operations and results
Maximilian Roos4617c85d755b
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 3ba7431c1..ebaa0019a 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -24,31 +24,34 @@ pub struct WorktreeInfo {impl WorktreeInfo {/// Create WorktreeInfo from a Worktree, enriching it with git metadata- fn from_worktree(wt: worktrunk::git::Worktree, primary: &worktrunk::git::Worktree) -> Self {+ fn from_worktree(+ wt: &worktrunk::git::Worktree,+ primary: &worktrunk::git::Worktree,+ ) -> Result<Self, GitError> {let wt_repo = Repository::at(&wt.path);let is_primary = wt.path == primary.path;// Get commit timestamp- let timestamp = wt_repo.commit_timestamp(&wt.head).unwrap_or(0);+ let timestamp = wt_repo.commit_timestamp(&wt.head)?;// Get commit message- let commit_message = wt_repo.commit_message(&wt.head).unwrap_or_default();+ let commit_message = wt_repo.commit_message(&wt.head)?;// Calculate ahead/behind relative to primary branch (only if primary has a branch)let (ahead, behind) = if is_primary {(0, 0)} else if let Some(pb) = primary.branch.as_deref() {- wt_repo.ahead_behind(pb, &wt.head).unwrap_or((0, 0))+ wt_repo.ahead_behind(pb, &wt.head)?} else {(0, 0)};- let working_tree_diff = wt_repo.working_tree_diff_stats().unwrap_or((0, 0));+ let working_tree_diff = wt_repo.working_tree_diff_stats()?;// Get branch diff stats (downstream of primary, only if primary has a branch)let branch_diff = if is_primary {(0, 0)} else if let Some(pb) = primary.branch.as_deref() {- wt_repo.branch_diff_stats(pb, &wt.head).unwrap_or((0, 0))+ wt_repo.branch_diff_stats(pb, &wt.head)?} else {(0, 0)};@@ -66,19 +69,17 @@ impl WorktreeInfo {.map(|(remote, _)| remote).unwrap_or("origin").to_string();- let (ahead, behind) = wt_repo- .ahead_behind(&upstream_branch, &wt.head)- .unwrap_or((0, 0));+ let (ahead, behind) = wt_repo.ahead_behind(&upstream_branch, &wt.head)?;(Some(remote), ahead, behind)}None => (None, 0, 0),};// Get worktree state (merge/rebase/etc)- let worktree_state = wt_repo.worktree_state().unwrap_or(None);+ let worktree_state = wt_repo.worktree_state()?;- WorktreeInfo {- worktree: wt,+ Ok(WorktreeInfo {+ worktree: wt.clone(),timestamp,commit_message,ahead,@@ -90,7 +91,7 @@ impl WorktreeInfo {upstream_ahead,upstream_behind,worktree_state,- }+ })}}@@ -123,15 +124,15 @@ pub fn handle_list() -> Result<(), GitError> {let mut infos: Vec<WorktreeInfo> = if std::env::var("WT_SEQUENTIAL").is_ok() {// Sequential iteration (for benchmarking)worktrees- .into_iter()+ .iter().map(|wt| WorktreeInfo::from_worktree(wt, &primary))- .collect()+ .collect::<Result<Vec<_>, _>>()?} else {// Parallel iteration (default)worktrees- .into_par_iter()+ .par_iter().map(|wt| WorktreeInfo::from_worktree(wt, &primary))- .collect()+ .collect::<Result<Vec<_>, _>>()?};// Sort by most recent commit (descending)diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 0efbb9638..cf445b6e7 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -48,7 +48,12 @@ pub fn handle_merge(target: Option<&str>, squash: bool, keep: bool) -> Result<()// Get primary worktree path before finishing (while we can still run git commands)let primary_worktree_dir = repo.repo_root()?;- handle_remove(false)?;+ let result = handle_remove()?;++ // Display user-facing output+ if let Some(output) = result.format_user_output() {+ println!("{}", output);+ }// Check if we need to switch to target branchlet primary_repo = Repository::at(&primary_worktree_dir);diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex e898c6819..5b4beacf8 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -1,15 +1,118 @@+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};+/// Result of a worktree switch operation+pub enum SwitchResult {+ /// Switched to existing worktree at the given path+ ExistingWorktree(PathBuf),+ /// Created new worktree at the given path+ CreatedWorktree { path: PathBuf, created_branch: bool },+}++impl SwitchResult {+ /// Format the result for display (non-internal mode)+ pub fn format_user_output(&self, branch: &str) -> Option<String> {+ match self {+ SwitchResult::ExistingWorktree(_) => None,+ SwitchResult::CreatedWorktree {+ path,+ created_branch,+ } => {+ let msg = if *created_branch {+ format!(+ "Created new branch and worktree for '{}' at {}",+ branch,+ path.display()+ )+ } else {+ format!(+ "Added worktree for existing branch '{}' at {}",+ branch,+ path.display()+ )+ };+ Some(format!(+ "{}\nNote: Use 'wt switch' (with shell integration) for automatic cd",+ msg+ ))+ }+ }+ }++ /// Format the result for shell integration (internal mode)+ pub fn format_internal_output(&self, branch: &str) -> Option<String> {+ match self {+ SwitchResult::ExistingWorktree(path) => {+ Some(format!("__WORKTRUNK_CD__{}", path.display()))+ }+ SwitchResult::CreatedWorktree {+ path,+ created_branch,+ } => {+ let msg = if *created_branch {+ format!("Created new branch and worktree for '{}'", branch)+ } else {+ format!("Added worktree for existing branch '{}'", branch)+ };+ Some(format!(+ "__WORKTRUNK_CD__{}\n{} at {}",+ path.display(),+ msg,+ path.display()+ ))+ }+ }+ }+}++/// Result of a worktree remove operation+pub enum RemoveResult {+ /// Already on default branch, no action taken+ AlreadyOnDefault(String),+ /// Removed worktree and returned to primary+ RemovedWorktree { primary_path: PathBuf },+ /// Switched to default branch in main repo+ SwitchedToDefault(String),+}++impl RemoveResult {+ /// Format the result for display (non-internal mode)+ pub fn format_user_output(&self) -> Option<String> {+ match self {+ RemoveResult::AlreadyOnDefault(branch) => {+ Some(format!("Already on default branch '{}'", branch))+ }+ RemoveResult::RemovedWorktree { primary_path } => Some(format!(+ "Moved to primary worktree and removed worktree\nPath: {}\nNote: Use 'wt remove' (with shell integration) for automatic cd",+ primary_path.display()+ )),+ RemoveResult::SwitchedToDefault(branch) => {+ Some(format!("Switched to default branch '{}'", branch))+ }+ }+ }++ /// Format the result for shell integration (internal mode)+ pub fn format_internal_output(&self) -> Option<String> {+ match self {+ RemoveResult::AlreadyOnDefault(_) => None,+ RemoveResult::RemovedWorktree { primary_path } => {+ Some(format!("__WORKTRUNK_CD__{}", primary_path.display()))+ }+ RemoveResult::SwitchedToDefault(_) => None,+ }+ }+}+pub fn handle_switch(branch: &str,create: bool,base: Option<&str>,- internal: bool,config: &WorktrunkConfig,-) -> Result<(), GitError> {+) -> Result<SwitchResult, GitError> {let repo = Repository::current();// Check for conflicting conditions@@ -32,10 +135,7 @@ pub fn handle_switch(// Check if worktree already exists for this branchmatch repo.worktree_for_branch(branch)? {Some(existing_path) if existing_path.exists() => {- if internal {- println!("__WORKTRUNK_CD__{}", existing_path.display());- }- return Ok(());+ return Ok(SwitchResult::ExistingWorktree(existing_path));}Some(_) => {return Err(GitError::CommandFailed(format_error_with_bold(@@ -74,27 +174,13 @@ pub fn handle_switch(repo.run_command(&args).map_err(|e| GitError::CommandFailed(format!("Failed to create worktree: {}", e)))?;- // Output success message- let success_msg = if create {- format!(- "Created new branch and worktree for '{}' at {}",- branch,- worktree_path.display()- )- } else {- format!(- "Added worktree for existing branch '{}' at {}",- branch,- worktree_path.display()- )- };-- output_with_cd(internal, &worktree_path, &success_msg, "switch");-- Ok(())+ Ok(SwitchResult::CreatedWorktree {+ path: worktree_path,+ created_branch: create,+ })}-pub fn handle_remove(internal: bool) -> Result<(), GitError> {+pub fn handle_remove() -> Result<RemoveResult, GitError> {let repo = Repository::current();// Check for uncommitted changes@@ -107,10 +193,7 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {// If we're on default branch and not in a worktree, nothing to doif !in_worktree && current_branch.as_deref() == Some(&default_branch) {- if !internal {- println!("Already on default branch '{}'", default_branch);- }- return Ok(());+ return Ok(RemoveResult::AlreadyOnDefault(default_branch));}if in_worktree {@@ -118,10 +201,6 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {let worktree_root = repo.worktree_root()?;let primary_worktree_dir = repo.repo_root()?;- if internal {- println!("__WORKTRUNK_CD__{}", primary_worktree_dir.display());- }-// 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()])@@ -137,10 +216,9 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {);}- if !internal {- println!("Moved to primary worktree and removed worktree");- print_worktree_info(&primary_worktree_dir, "remove");- }+ Ok(RemoveResult::RemovedWorktree {+ primary_path: primary_worktree_dir,+ })} else {// In main repo but not on default branch: switch to defaultrepo.run_command(&["switch", &default_branch])@@ -148,12 +226,8 @@ pub fn handle_remove(internal: bool) -> Result<(), GitError> {GitError::CommandFailed(format!("Failed to switch to '{}': {}", default_branch, e))})?;- if !internal {- println!("Switched to default branch '{}'", default_branch);- }+ Ok(RemoveResult::SwitchedToDefault(default_branch))}-- Ok(())}/// Check for conflicting uncommitted changes in target worktree@@ -282,31 +356,6 @@ pub fn handle_push(target: Option<&str>, allow_merge_commits: bool) -> Result<()Ok(())}-fn print_worktree_info(path: &std::path::Path, command: &str) {- println!("Path: {}", path.display());- println!(- "Note: Use 'wt {}' (with shell integration) for automatic cd",- command- );-}-fn format_warning(msg: &str) -> String {worktrunk::styling::format_warning(msg)}--/// Output message with optional CD directive for internal mode.-///-/// In internal mode: prints CD directive and message-/// In normal mode: prints message and shell integration note-fn output_with_cd(internal: bool, path: &std::path::Path, message: &str, command: &str) {- if internal {- println!("__WORKTRUNK_CD__{}", path.display());- println!("{}", message);- } else {- println!("{}", message);- println!(- "Note: Use 'wt {}' (with shell integration) for automatic cd",- command- );- }-}diff --git a/src/main.rs b/src/main.rsindex cae5b28f2..4d76b1c4a 100644--- a/src/main.rs+++ b/src/main.rs@@ -119,8 +119,30 @@ fn main() {internal,} => WorktrunkConfig::load().map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))- .and_then(|config| handle_switch(&branch, create, base.as_deref(), internal, &config)),- Commands::Remove { internal } => handle_remove(internal),+ .and_then(|config| {+ handle_switch(&branch, create, base.as_deref(), &config).map(|result| {+ if internal {+ if let Some(output) = result.format_internal_output(&branch) {+ println!("{}", output);+ }+ } else {+ if let Some(output) = result.format_user_output(&branch) {+ println!("{}", output);+ }+ }+ })+ }),+ Commands::Remove { internal } => handle_remove().map(|result| {+ if internal {+ if let Some(output) = result.format_internal_output() {+ println!("{}", output);+ }+ } else {+ if let Some(output) = result.format_user_output() {+ println!("{}", output);+ }+ }+ }),Commands::Push {target,allow_merge_commits,