Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: unify find_remote and add gitlab::fork_remote_url (#1822)
Maximilian Roosaf122c04a5ac
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex cf4910f4e..731d2a277 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -802,8 +802,8 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {if all_vars.is_empty() {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {- let mut table = String::from("| Branch | Key | Value |\n");- table.push_str("|--------|-----|-------|\n");+ let headers = &["Branch", "Key", "Value"];+ let mut rows: Vec<Vec<String>> = Vec::new();for (branch, entries) in &all_vars {for (key, value) in entries {// Truncate long values for display@@ -812,10 +812,10 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {} else {value.to_string()};- table.push_str(&format!("| {branch} | {key} | {display_value} |\n"));+ rows.push(vec![branch.to_string(), key.to_string(), display_value]);}}- let rendered = crate::md_help::render_markdown_table(&table);+ let rendered = crate::md_help::render_data_table(headers, &rows);writeln!(out, "{}", rendered.trim_end())?;}writeln!(out)?;diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex de08a7b51..2c89a2012 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -108,21 +108,12 @@ fn resolve_fork_ref(let ref_type = provider.ref_type();let repo_root = repo.repo_path()?;let local_branch = remote_ref::local_branch_name(info);- let expected_remote = match ref_type {- RefType::Pr => match find_github_remote(repo, info) {- Ok(remote) => Some(remote),- Err(e) => {- log::debug!("Could not resolve GitHub remote for PR: {e:#}");- None- }- },- RefType::Mr => match find_gitlab_remote(repo, info) {- Ok(remote) => Some(remote),- Err(e) => {- log::debug!("Could not resolve GitLab remote for MR: {e:#}");- None- }- },+ let expected_remote = match remote_ref::find_remote(repo, info) {+ Ok(remote) => Some(remote),+ Err(e) => {+ log::debug!("Could not resolve remote for {}: {e:#}", ref_type.name());+ None+ }};// Check if branch already exists and is tracking this ref@@ -186,7 +177,7 @@ fn resolve_fork_ref(// Use prefixed branch name; push won't work (None for fork_push_url)// This is GitHub-only (GitLab doesn't support prefixed names)- let remote = find_github_remote(repo, info)?;+ let remote = remote_ref::find_remote(repo, info)?;return Ok(ResolvedTarget {branch: prefixed,method: CreationMethod::ForkRef {@@ -214,7 +205,7 @@ fn resolve_fork_ref(let (fork_push_url, remote) = match ref_type {RefType::Pr => {// GitHub: URLs already in info, just find remote.- let remote = find_github_remote(repo, info)?;+ let remote = remote_ref::find_remote(repo, info)?;(info.fork_push_url.clone(), remote)}RefType::Mr => {@@ -263,97 +254,15 @@ fn resolve_fork_ref(})}-/// Find the remote for a GitHub PR (where PR refs live).-fn find_github_remote(repo: &Repository, info: &RemoteRefInfo) -> anyhow::Result<String> {- use worktrunk::git::remote_ref::PlatformData;-- let PlatformData::GitHub {- host,- base_owner,- base_repo,- ..- } = &info.platform_data- else {- anyhow::bail!("find_github_remote called on non-GitHub ref");- };-- repo.find_remote_for_repo(Some(host), base_owner, base_repo)- .ok_or_else(|| {- let suggested_url =- worktrunk::git::remote_ref::github::fork_remote_url(host, base_owner, base_repo);- GitError::NoRemoteForRepo {- owner: base_owner.clone(),- repo: base_repo.clone(),- suggested_url,- }- .into()- })-}--/// Find the remote for a GitLab MR (where MR refs live).-fn find_gitlab_remote(repo: &Repository, info: &RemoteRefInfo) -> anyhow::Result<String> {- use worktrunk::git::remote_ref::PlatformData;-- let PlatformData::GitLab {- host,- base_owner,- base_repo,- ..- } = &info.platform_data- else {- anyhow::bail!("find_gitlab_remote called on non-GitLab ref");- };-- repo.find_remote_for_repo(Some(host), base_owner, base_repo)- .ok_or_else(|| {- GitError::NoRemoteForRepo {- owner: base_owner.clone(),- repo: base_repo.clone(),- suggested_url: format!("https://{host}/{base_owner}/{base_repo}.git"),- }- .into()- })-}-/// Resolve a same-repo (non-fork) PR/MR.fn resolve_same_repo_ref(repo: &Repository,info: &RemoteRefInfo,) -> anyhow::Result<ResolvedTarget> {- use worktrunk::git::remote_ref::PlatformData;-// Find the remote for the same-repo PR/MR and fetch the branch with an// explicit refspec. This ensures the remote tracking branch is created even// in repos with limited fetch refspecs (single-branch clones, bare repos).- let remote = match &info.platform_data {- PlatformData::GitHub {- host,- base_owner,- base_repo,- ..- } => {- let suggested_url =- worktrunk::git::remote_ref::github::fork_remote_url(host, base_owner, base_repo);- repo.find_remote_for_repo(Some(host), base_owner, base_repo)- .ok_or_else(|| GitError::NoRemoteForRepo {- owner: base_owner.clone(),- repo: base_repo.clone(),- suggested_url,- })?- }- PlatformData::GitLab {- host,- base_owner,- base_repo,- ..- } => repo- .find_remote_for_repo(Some(host), base_owner, base_repo)- .ok_or_else(|| GitError::NoRemoteForRepo {- owner: base_owner.clone(),- repo: base_repo.clone(),- suggested_url: format!("https://{host}/{base_owner}/{base_repo}.git"),- })?,- };+ let remote = remote_ref::find_remote(repo, info)?;let branch = &info.source_branch;eprintln!(diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rsindex ff12cbcb0..220a2fa9b 100644--- a/src/git/remote_ref/gitlab.rs+++ b/src/git/remote_ref/gitlab.rs@@ -273,6 +273,15 @@ pub fn git_protocol() -> String {.unwrap_or_else(|| "https".to_string())}+/// Construct the remote URL for a GitLab project, respecting protocol preference.+pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {+ if git_protocol() == "ssh" {+ format!("git@{host}:{owner}/{repo}.git")+ } else {+ format!("https://{host}/{owner}/{repo}.git")+ }+}+#[cfg(test)]mod tests {use super::*;@@ -291,6 +300,24 @@ mod tests {assert_eq!(provider.ref_type(), RefType::Mr);}+ #[test]+ fn test_fork_remote_url_formats() {+ // Protocol depends on `glab config get git_protocol`, so just check format+ let url = fork_remote_url("gitlab.com", "contributor", "repo");+ let valid_urls = [+ "[email protected]:contributor/repo.git",+ "https://gitlab.com/contributor/repo.git",+ ];+ assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");++ let url = fork_remote_url("gitlab.example.com", "org", "project");+ let valid_urls = [+ "[email protected]:org/project.git",+ "https://gitlab.example.com/org/project.git",+ ];+ assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");+ }+#[test]fn test_fetch_gitlab_project_urls_rejects_github_ref() {let github_info = RemoteRefInfo {diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rsindex b5d2f5a3f..7cc9f37b6 100644--- a/src/git/remote_ref/mod.rs+++ b/src/git/remote_ref/mod.rs@@ -128,6 +128,51 @@ pub(super) fn cli_config_value(tool: &str, key: &str) -> Option<String> {.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())}+/// Find the local remote that points to the base (target) project for a PR/MR.+///+/// Dispatches on `PlatformData` to extract host/owner/repo, then searches+/// configured remotes. The suggested URL in the error respects each platform's+/// configured git protocol (SSH vs HTTPS).+pub fn find_remote(repo: &Repository, info: &RemoteRefInfo) -> Result<String, GitError> {+ let (host, owner, repo_name) = match &info.platform_data {+ PlatformData::GitHub {+ host,+ base_owner,+ base_repo,+ ..+ }+ | PlatformData::GitLab {+ host,+ base_owner,+ base_repo,+ ..+ } => (host.as_str(), base_owner.as_str(), base_repo.as_str()),+ };++ repo.find_remote_for_repo(Some(host), owner, repo_name)+ .ok_or_else(|| {+ let suggested_url = match &info.platform_data {+ PlatformData::GitHub {+ host,+ base_owner,+ base_repo,+ ..+ } => github::fork_remote_url(host, base_owner, base_repo),+ PlatformData::GitLab {+ host,+ base_owner,+ base_repo,+ ..+ } => gitlab::fork_remote_url(host, base_owner, base_repo),+ };+ GitError::NoRemoteForRepo {+ owner: owner.to_string(),+ repo: repo_name.to_string(),+ suggested_url,+ }+ })+}+/// Check if a local branch is tracking a specific remote ref.////// Returns `Some(true)` if the branch is configured to track the given ref.