Skip to content

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

feat(switch): suggest pr:N or mr:N for numeric branch names (#2516)

Maximilian Rooscdb17cbd7c40
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rs
index b8e3dc035..37397db42 100644
--- a/src/commands/config/state.rs
+++ b/src/commands/config/state.rs
@@ -710,6 +710,7 @@ pub fn handle_state_get(
branch: branch_name,
show_create_hint: true,
last_fetch_ago: None,
+ pr_mr_platform: repo.detect_ref_type(),
}
.into());
}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 2ca8a7624..0fba0dcee 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -157,6 +157,7 @@ impl RepositoryCliExt for Repository {
branch: branch.into(),
show_create_hint: false,
last_fetch_ago: None,
+ pr_mr_platform: None,
}
.into());
}
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 8aee0aa85..b66394389 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -518,6 +518,7 @@ fn validate_worktree_creation(
branch: branch.to_string(),
show_create_hint: true,
last_fetch_ago: format_last_fetch_ago(repo),
+ pr_mr_platform: repo.detect_ref_type(),
}
.into());
}
diff --git a/src/git/error.rs b/src/git/error.rs
index 57e3915ba..97b3f7ea8 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -183,6 +183,10 @@ pub enum GitError {
/// Pre-formatted label for the last fetch time (e.g., "3h ago", "never").
/// When present, the list-branches hint includes the fetch age as a parenthetical.
last_fetch_ago: Option<String>,
+ /// Platform's reference type for the PR/MR hint when the branch name is
+ /// purely numeric. `None` means the platform is unknown — fall back to
+ /// suggesting both `pr:N` and `mr:N`.
+ pr_mr_platform: Option<RefType>,
},
/// Reference (branch, tag, commit) not found - used when any commit-ish is accepted
ReferenceNotFound {
@@ -415,18 +419,31 @@ impl GitError {
branch,
show_create_hint,
last_fetch_ago,
+ pr_mr_platform,
} => {
let list_cmd = suggest_command("list", &[], &["--branches", "--remotes"]);
+ let fetch_note = last_fetch_ago
+ .as_ref()
+ .map(|ago| cformat!(" ({ago})"))
+ .unwrap_or_default();
+ let list_hint =
+ cformat!("to list branches, run <underline>{list_cmd}</>{fetch_note}");
let hint = if *show_create_hint {
let mut create_cmd = suggest_command("switch", &[branch], &["--create"]);
if let Some(ctx) = ctx {
create_cmd = ctx.apply(create_cmd);
}
- let fetch_note = last_fetch_ago.as_ref().map(|ago| cformat!(" ({ago})"));
- cformat!(
- "To create a new branch, run <underline>{create_cmd}</>; to list branches, run <underline>{list_cmd}</>{note}",
- note = fetch_note.as_deref().unwrap_or("")
- )
+ let create_hint =
+ cformat!("to create a new branch, run <underline>{create_cmd}</>");
+ if let Ok(number) = branch.parse::<u32>() {
+ let pr_mr_hint = pr_mr_switch_hint(number, *pr_mr_platform, ctx);
+ cformat!("{pr_mr_hint}; {create_hint}; {list_hint}")
+ } else {
+ // Existing format: capitalize the leading "to".
+ cformat!(
+ "To create a new branch, run <underline>{create_cmd}</>; {list_hint}"
+ )
+ }
} else {
cformat!("To list branches, run <underline>{list_cmd}</>")
};
@@ -1118,6 +1135,45 @@ impl std::error::Error for HookErrorWithHint {
}
}
+/// Build the leading "To switch to PR/MR …" hint shown when a numeric branch
+/// name doesn't exist locally.
+///
+/// Returns a sentence-cased clause without trailing punctuation so callers can
+/// chain it with `; …` follow-ups. Capitalization matches the existing hint
+/// style ("To switch …", "to create …").
+///
+/// `number` is the same digits as the branch (the caller has already parsed
+/// the branch as `u32`); combined with the literal `pr:` / `mr:` prefix the
+/// result is shell-safe, so the command is formatted directly to avoid
+/// `shell_escape` quoting (`'pr:42'`).
+fn pr_mr_switch_hint(
+ number: u32,
+ platform: Option<RefType>,
+ ctx: Option<&SwitchSuggestionCtx>,
+) -> String {
+ let make_cmd = |ref_type: RefType| {
+ let cmd = format!("wt switch {}{number}", ref_type.syntax());
+ match ctx {
+ Some(ctx) => ctx.apply(cmd),
+ None => cmd,
+ }
+ };
+ match platform {
+ Some(ref_type) => {
+ let label = ref_type.display(number);
+ let cmd = make_cmd(ref_type);
+ cformat!("To switch to {label}, run <underline>{cmd}</>")
+ }
+ None => {
+ let pr_cmd = make_cmd(RefType::Pr);
+ let mr_cmd = make_cmd(RefType::Mr);
+ cformat!(
+ "To switch to PR #{number} or MR !{number}, run <underline>{pr_cmd}</> or <underline>{mr_cmd}</>"
+ )
+ }
+ }
+}
+
/// Format an error with header and gutter content
fn format_error_block(header: impl Into<String>, error: &str) -> String {
let header = header.into();
@@ -1746,6 +1802,7 @@ mod tests {
branch: "emails".into(),
show_create_hint: true,
last_fetch_ago: None,
+ pr_mr_platform: None,
}),
ctx: SwitchSuggestionCtx {
extra_flags: vec!["--execute=claude".into()],
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index fe910f0a4..a4a649efd 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -380,6 +380,7 @@ impl Repository {
branch,
show_create_hint: true,
last_fetch_ago: None,
+ pr_mr_platform: self.detect_ref_type(),
}
.into());
}
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index 658197024..d32dfdce7 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -92,6 +92,7 @@
use anyhow::Context;
use super::{GitRemoteUrl, Repository};
+use crate::git::error::RefType;
impl Repository {
/// Get the primary remote name for this repository.
@@ -265,6 +266,31 @@ impl Repository {
.and_then(GitRemoteUrl::parse)
}
+ /// Detect the platform's reference type (PR for GitHub, MR for GitLab).
+ ///
+ /// Hostname-matches the primary remote's effective URL (so `url.insteadOf`
+ /// rewrites are respected). Returns `None` when the platform can't be
+ /// determined (no remote, opaque host).
+ ///
+ /// Drives the numeric-branch hint in `BranchNotFound` only — `forge.platform`
+ /// is intentionally not consulted here. Honoring it would duplicate
+ /// `platform_for_repo`'s precedence rules; users with that override and an
+ /// opaque remote host fall through to the both-platforms hint.
+ pub fn detect_ref_type(&self) -> Option<RefType> {
+ let url = self
+ .primary_remote()
+ .ok()
+ .and_then(|remote| self.effective_remote_url(&remote))?;
+ let parsed = GitRemoteUrl::parse(&url)?;
+ if parsed.is_github() {
+ Some(RefType::Pr)
+ } else if parsed.is_gitlab() {
+ Some(RefType::Mr)
+ } else {
+ None
+ }
+ }
+
/// Get a project identifier for approval tracking.
///
/// Uses the git remote URL if available (e.g., "github.com/user/repo"),
diff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rs
index e31b6d675..de511935f 100644
--- a/tests/integration_tests/git_error_display.rs
+++ b/tests/integration_tests/git_error_display.rs
@@ -110,6 +110,7 @@ fn branch_not_found() {
branch: "nonexistent".into(),
show_create_hint: true,
last_fetch_ago: None,
+ pr_mr_platform: None,
};
assert_snapshot!("branch_not_found", err.to_string());
@@ -121,6 +122,7 @@ fn branch_not_found_with_fetch_time() {
branch: "nonexistent".into(),
show_create_hint: true,
last_fetch_ago: Some("last fetched 3h ago".into()),
+ pr_mr_platform: None,
};
assert_snapshot!("branch_not_found_with_fetch_time", err.to_string());
@@ -132,11 +134,51 @@ fn branch_not_found_no_create_hint() {
branch: "nonexistent".into(),
show_create_hint: false,
last_fetch_ago: None,
+ pr_mr_platform: None,
};
assert_snapshot!("branch_not_found_no_create_hint", err.to_string());
}
+#[test]
+fn branch_not_found_numeric_unknown_platform() {
+ // Purely numeric name with unknown platform: hint suggests both `pr:N` and `mr:N`.
+ let err = GitError::BranchNotFound {
+ branch: "2474".into(),
+ show_create_hint: true,
+ last_fetch_ago: None,
+ pr_mr_platform: None,
+ };
+
+ assert_snapshot!("branch_not_found_numeric_unknown_platform", err.to_string());
+}
+
+#[test]
+fn branch_not_found_numeric_github() {
+ use worktrunk::git::RefType;
+ let err = GitError::BranchNotFound {
+ branch: "2474".into(),
+ show_create_hint: true,
+ last_fetch_ago: Some("last fetched 9h ago".into()),
+ pr_mr_platform: Some(RefType::Pr),
+ };
+
+ assert_snapshot!("branch_not_found_numeric_github", err.to_string());
+}
+
+#[test]
+fn branch_not_found_numeric_gitlab() {
+ use worktrunk::git::RefType;
+ let err = GitError::BranchNotFound {
+ branch: "2474".into(),
+ show_create_hint: true,
+ last_fetch_ago: None,
+ pr_mr_platform: Some(RefType::Mr),
+ };
+
+ assert_snapshot!("branch_not_found_numeric_gitlab", err.to_string());
+}
+
#[test]
fn display_worktree_path_occupied() {
let err = GitError::WorktreePathOccupied {
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 8ef0f092b..478f182e4 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -2,7 +2,7 @@
use std::fs;
-use worktrunk::git::Repository;
+use worktrunk::git::{RefType, Repository};
use crate::common::{BareRepoTest, TestRepo};
@@ -584,6 +584,51 @@ fn test_primary_remote_url_composition() {
assert!(r2.primary_remote_parsed_url().is_none());
}
+/// `detect_ref_type` resolves the platform's PR/MR reference type from the
+/// primary remote URL. Drives the numeric branch hint in `BranchNotFound`
+/// ("To switch to PR #N, run wt switch pr:N"). The `forge.platform` override
+/// branch is exercised end-to-end via the `platform_for_repo` paths.
+#[test]
+fn test_detect_ref_type() {
+ // GitHub remote → PR
+ let github = TestRepo::new();
+ github.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://github.com/max-sixty/worktrunk.git",
+ ]);
+ let r = Repository::at(github.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.detect_ref_type(), Some(RefType::Pr));
+
+ // GitLab remote → MR
+ let gitlab = TestRepo::new();
+ gitlab.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://gitlab.com/owner/repo.git",
+ ]);
+ let r = Repository::at(gitlab.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.detect_ref_type(), Some(RefType::Mr));
+
+ // Unknown host → None
+ let other = TestRepo::new();
+ other.run_git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://example.com/owner/repo.git",
+ ]);
+ let r = Repository::at(other.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.detect_ref_type(), None);
+
+ // No remote → None
+ let empty = TestRepo::new();
+ let r = Repository::at(empty.root_path().to_path_buf()).unwrap();
+ assert_eq!(r.detect_ref_type(), None);
+}
+
/// `remote_url` for a configured remote round-trips; unknown remotes
/// return `None`. Covers the `.filter(|url| !url.is_empty())` branch
/// via the happy-path URL read.
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_github.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_github.snap
new file mode 100644
index 000000000..1ea8e008a
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_github.snap
@@ -0,0 +1,6 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ No branch named 2474
+↳ To switch to PR #2474, run wt switch pr:2474; to create a new branch, run wt switch --create 2474; to list branches, run wt list --branches --remotes (last fetched 9h ago)
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_gitlab.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_gitlab.snap
new file mode 100644
index 000000000..e05ca756f
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_gitlab.snap
@@ -0,0 +1,6 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ No branch named 2474
+↳ To switch to MR !2474, run wt switch mr:2474; to create a new branch, run wt switch --create 2474; to list branches, run wt list --branches --remotes
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_unknown_platform.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_unknown_platform.snap
new file mode 100644
index 000000000..c1dbd7a1d
--- /dev/null
+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__branch_not_found_numeric_unknown_platform.snap
@@ -0,0 +1,6 @@
+---
+source: tests/integration_tests/git_error_display.rs
+expression: err.to_string()
+---
+✗ No branch named 2474
+↳ To switch to PR #2474 or MR !2474, run wt switch pr:2474 or wt switch mr:2474; to create a new branch, run wt switch --create 2474; to list branches, run wt list --branches --remotes