Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Enhance switch when creating branches from remote
Maximilian Roos0b4ddf03d8f4
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 7273d8d9e..13f79efe9 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -114,7 +114,8 @@ use worktrunk::HookType;use worktrunk::config::{CommandPhase, WorktrunkConfig};use worktrunk::git::{GitError, Repository, is_command_not_approved};use worktrunk::styling::{- AnstyleStyle, CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, WARNING, format_with_gutter,+ AnstyleStyle, CYAN, CYAN_BOLD, GREEN, GREEN_BOLD, HINT, WARNING, WARNING_BOLD,+ format_with_gutter,};use super::command_executor::CommandContext;@@ -138,8 +139,13 @@ pub enum SwitchResult {/// Created new worktree at the given pathCreated {path: PathBuf,+ /// True if we used `-b` to create a new branch (--create flag)created_branch: bool,+ /// Base branch when creating new branch (e.g., "main")base_branch: Option<String>,+ /// Remote tracking branch if created from remote (e.g., "origin/feature")+ /// This is set when git's DWIM created a local branch from a remote+ from_remote: Option<String>,},}@@ -224,6 +230,20 @@ pub fn handle_switch(.into());}+ // Warn if --create would shadow a remote branch+ if create {+ let remotes = repo.remotes_with_branch(&resolved_branch)?;+ if !remotes.is_empty() {+ let remote_ref = format!("{}/{}", remotes[0], resolved_branch);+ crate::output::warning(format!(+ "{WARNING}Branch {WARNING_BOLD}{resolved_branch}{WARNING_BOLD:#}{WARNING} exists on remote ({remote_ref}); creating new branch from base instead{WARNING:#}"+ ))?;+ crate::output::hint(format!(+ "{HINT}Use 'wt switch {resolved_branch}' (without --create) to switch to the remote branch{HINT:#}"+ ))?;+ }+ }+// Check if base flag was provided without create flagif resolved_base.is_some() && !create {crate::output::warning(format!(@@ -366,6 +386,16 @@ pub fn handle_switch(.canonicalize().context("Failed to canonicalize worktree path")?;+ // Check if git's DWIM created a tracking branch from a remote+ // This happens when we don't use --create and the branch exists on a remote+ let from_remote = if !create {+ // Query the new worktree for its upstream tracking branch+ let worktree_repo = Repository::at(&worktree_path);+ worktree_repo.upstream_branch(&resolved_branch)?+ } else {+ None+ };+// Execute post-create commands (sequential, blocking)// Note: If user declines, continue anyway - worktree already createdif !no_verify {@@ -400,6 +430,7 @@ pub fn handle_switch(path: worktree_path,created_branch: create,base_branch: base_for_creation,+ from_remote,},resolved_branch,))diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex e4b9f7c5d..052ede963 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -199,6 +199,33 @@ impl Repository {.is_ok())}+ /// Find which remotes have a branch with the given name.+ ///+ /// Returns a list of remote names that have this branch (e.g., `["origin"]`).+ /// Returns an empty list if no remotes have this branch.+ pub fn remotes_with_branch(&self, branch: &str) -> anyhow::Result<Vec<String>> {+ // Get all remote tracking branches matching this name+ // Format: refs/remotes/<remote>/<branch>+ let output = self.run_command(&[+ "for-each-ref",+ "--format=%(refname:strip=2)",+ &format!("refs/remotes/*/{}", branch),+ ])?;++ // Parse output: each line is "<remote>/<branch>"+ // Extract the remote name (everything before the last /<branch>)+ let remotes: Vec<String> = output+ .lines()+ .filter_map(|line| {+ let line = line.trim();+ // Strip the branch suffix to get the remote name+ line.strip_suffix(&format!("/{}", branch)).map(String::from)+ })+ .collect();++ Ok(remotes)+ }+/// Get the current branch name, or None if in detached HEAD state.pub fn current_branch(&self) -> anyhow::Result<Option<String>> {let stdout = self.run_command(&["branch", "--show-current"])?;diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 741b8f66d..916da22b0 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -175,7 +175,7 @@ pub fn handle_switch_output(if is_directive_mode || has_execute_command || is_configured {// Shell integration active, --execute provided, or configured - show successsuper::success(super::format_switch_success_message(- branch, path, false, None,+ branch, path, false, None, None,))?;} else {// Shell integration not configured - show warning and setup hint@@ -190,6 +190,7 @@ pub fn handle_switch_output(path,created_branch,base_branch,+ from_remote,} => {// Creation succeeded - show successsuper::success(super::format_switch_success_message(@@ -197,6 +198,7 @@ pub fn handle_switch_output(path,*created_branch,base_branch.as_deref(),+ from_remote.as_deref(),))?;// Show setup hint if shell integration not activeif !is_directive_mode && !has_execute_command {diff --git a/src/output/mod.rs b/src/output/mod.rsindex 7840e9a37..394a64ac9 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -85,19 +85,24 @@ pub(crate) fn format_switch_success_message(path: &Path,created_branch: bool,base_branch: Option<&str>,+ from_remote: Option<&str>,) -> String {use worktrunk::styling::{GREEN, GREEN_BOLD};- let action = if created_branch {- "Created new worktree for"+ // Determine action and source based on how the worktree was created+ // Priority: explicit --create > DWIM from remote > existing local branch+ let (action, source) = if created_branch {+ ("Created new worktree for", base_branch)+ } else if let Some(remote) = from_remote {+ ("Created worktree for", Some(remote))} else {- "Switched to worktree for"+ ("Switched to worktree for", None)};// Re-establish GREEN after each green_bold reset to prevent color leak- match base_branch {- Some(base) => format!(- "{GREEN}{action} {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN} from {GREEN_BOLD}{base}{GREEN_BOLD:#}{GREEN} at {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",+ match source {+ Some(src) => format!(+ "{GREEN}{action} {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN} from {GREEN_BOLD}{src}{GREEN_BOLD:#}{GREEN} at {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",format_path_for_display(path)),None => format!(diff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_remote_only.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_remote_only.snapindex 577609897..755accd9a 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_create_remote_only.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_remote_only.snap@@ -26,5 +26,7 @@ exit_code: 0----- stdout ---------- stderr -----+π‘ [33mBranch [1m[33mremote-feature[0m[33m exists on remote (origin/remote-feature); creating new branch from base instead[0m+π‘ [2mUse 'wt switch remote-feature' (without --create) to switch to the remote branch[0mβ [32mCreated new worktree for [1m[32mremote-feature[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].remote-feature[0m[0mπ‘ [2mRun `wt config shell install` to enable automatic cd[0m