Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(list): add repo_url to JSON output (#2941)
Ben Druckerf41493478dfa
diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex be1ca792b..20b07a780 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -84,6 +84,12 @@ pub struct JsonItem {#[serde(skip_serializing_if = "Option::is_none")]pub ci: Option<JsonCi>,+ /// Repository web URL derived from the primary remote (absent when no parseable forge remote).+ /// This is the local checkout's repo; for the repo a PR/MR targets (e.g. the upstream of a+ /// fork), see `ci.repo_url`.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub repo_url: Option<String>,+/// Dev server URL from project config template#[serde(skip_serializing_if = "Option::is_none")]pub url: Option<String>,@@ -225,6 +231,12 @@ pub struct JsonCi {/// URL to the PR/MR (if available)#[serde(skip_serializing_if = "Option::is_none")]pub url: Option<String>,++ /// Web URL of the repository the PR/MR targets, derived from `url`. For a+ /// fork PR this is the upstream repo (not the local fork). Absent when `url`+ /// is absent or not a recognized PR/MR link.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub repo_url: Option<String>,}impl JsonItem {@@ -232,9 +244,13 @@ impl JsonItem {////// `all_vars` is pre-fetched vars data for all branches (from `repo.all_vars_entries()`),/// avoiding N+1 git process spawns. Entries are moved out via `.remove()` to avoid cloning.+ ///+ /// `repo_url` is the repository web URL (from `repo.repo_web_url()`). It is repo-wide, so+ /// the caller computes it once and passes the same value to every item.pub fn from_list_item(item: &ListItem,all_vars: &mut HashMap<String, BTreeMap<String, String>>,+ repo_url: Option<&str>,) -> Self {let (kind_str, worktree_data) = match &item.kind {ItemKind::Worktree(data) => ("worktree", Some(data.as_ref())),@@ -368,6 +384,7 @@ impl JsonItem {is_current,is_previous,ci,+ repo_url: repo_url.map(String::from),url: item.url.clone(),url_active: item.url_active,summary,@@ -431,6 +448,10 @@ impl From<&PrStatus> for JsonCi {status: pr.ci_status.into(),source: pr.source,stale: pr.is_stale,+ repo_url: pr+ .url+ .as_deref()+ .and_then(worktrunk::git::remote_ref::repo_url_from_ref_url),url: pr.url.clone(),}}@@ -495,9 +516,10 @@ fn format_raw_symbols(symbols: &super::model::StatusSymbols) -> String {/// Fetches all vars data in a single git call, then distributes per-branch.pub fn to_json_items(items: &[ListItem], repo: &Repository) -> Vec<JsonItem> {let mut all_vars = repo.all_vars_entries();+ let repo_url = repo.repo_web_url();items.iter()- .map(|item| JsonItem::from_list_item(item, &mut all_vars))+ .map(|item| JsonItem::from_list_item(item, &mut all_vars, repo_url.as_deref())).collect()}@@ -553,6 +575,11 @@ mod tests {passed.url,Some("https://github.com/org/repo/pull/123".to_string()));+ // repo_url is derived from the PR URL (the target repo).+ assert_eq!(+ passed.repo_url,+ Some("https://github.com/org/repo".to_string())+ );// Stale branch with no URLlet failed = JsonCi::from(&PrStatus {@@ -565,6 +592,8 @@ mod tests {assert_eq!(failed.source, CiSource::Branch);assert!(failed.stale);assert!(failed.url.is_none());+ // No PR URL means no derived repo_url.+ assert!(failed.repo_url.is_none());// All status string mappingslet status_mappings = [@@ -911,8 +940,18 @@ mod tests {let mut item = ListItem::new_branch("abc1234".into(), "feature".into());item.summary = Some(Some("Add login page".to_string()));- let json_item = JsonItem::from_list_item(&item, &mut all_vars);++ // repo_url is set when provided, absent (skipped) when None.+ let json_item = JsonItem::from_list_item(&item, &mut all_vars, None);assert_eq!(json_item.summary, Some("Add login page".to_string()));+ assert!(json_item.repo_url.is_none());++ let json_item =+ JsonItem::from_list_item(&item, &mut all_vars, Some("https://github.com/owner/repo"));+ assert_eq!(+ json_item.repo_url,+ Some("https://github.com/owner/repo".to_string())+ );}#[test]@@ -923,14 +962,14 @@ mod tests {let mut item = ListItem::new_branch("abc1234".into(), "feature".into());// Both "not collected" and "no summary" should be absent in JSONassert!(- JsonItem::from_list_item(&item, &mut all_vars)+ JsonItem::from_list_item(&item, &mut all_vars, None).summary.is_none());item.summary = Some(None);assert!(- JsonItem::from_list_item(&item, &mut all_vars)+ JsonItem::from_list_item(&item, &mut all_vars, None).summary.is_none());@@ -942,7 +981,8 @@ mod tests {status: "passed",source: CiSource::PullRequest,stale: false,- url: Some("https://example.com".to_string()),+ url: Some("https://github.com/org/repo/pull/7".to_string()),+ repo_url: Some("https://github.com/org/repo".to_string()),}).unwrap();assert_snapshot!(json, @r#"@@ -950,7 +990,8 @@ mod tests {"status": "passed","source": "pr","stale": false,- "url": "https://example.com"+ "url": "https://github.com/org/repo/pull/7",+ "repo_url": "https://github.com/org/repo"}"#);}diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex 5b5fbf0e5..b3393506c 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -714,7 +714,8 @@ fn run_json() -> Result<()> {all_vars.insert(branch.clone(), entries);}}- let json_item = json_output::JsonItem::from_list_item(&item, &mut all_vars);+ let json_item =+ json_output::JsonItem::from_list_item(&item, &mut all_vars, repo.repo_web_url().as_deref());// Output as JSON array (consistent with wt list --format=json)let output = serde_json::to_string_pretty(&[json_item])?;diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rsindex c3783b4b0..9e0b50028 100644--- a/src/git/remote_ref/mod.rs+++ b/src/git/remote_ref/mod.rs@@ -271,56 +271,117 @@ pub fn local_branch_name(info: &RemoteRefInfo) -> String {info.source_branch.clone()}-/// Parse a forge PR/MR web URL into the equivalent `pr:N` / `mr:N` shortcut-/// string.-///-/// Recognises the canonical PR/MR URLs across all four supported forges-/// (GitHub including Enterprise, GitLab, Gitea, Azure DevOps). Callers-/// substitute the returned shortcut for the original input, so URL handling-/// flows through the same `pr:` / `mr:` parsing path as a literal shortcut —-/// no duplicate dispatch.+/// A forge PR/MR web URL decomposed into its parts.////// Detection is shape-based, not host-based: the URL must use `http(s)://`/// and contain `/pull/N`, `/pulls/N`, `/-/merge_requests/N`, or/// `/pullrequest/N` in its path. Trailing path segments (e.g. `/files`,/// `/commits`), query strings, and fragments are ignored. Host is not-/// inspected so self-hosted GitHub Enterprise / Gitea / GitLab instances+/// inspected, so self-hosted GitHub Enterprise / Gitea / GitLab instances/// work without a hostname allow-list.-pub fn parse_ref_url(input: &str) -> Option<String> {+struct RefUrlParts<'a> {+ /// URL scheme: `"https"` or `"http"`.+ scheme: &'a str,+ /// Non-empty path segments after the scheme (host, owner, …, marker, N).+ segments: Vec<&'a str>,+ /// Index into `segments` of the marker segment (`pull` / `pulls` /+ /// `pullrequest` / `merge_requests`).+ marker_index: usize,+ /// `"pr"` for GitHub/Gitea/Azure, `"mr"` for GitLab.+ kind: &'static str,+ /// The PR/MR number.+ number: u32,+}++/// Shape-based parse of a forge PR/MR web URL across all four supported forges+/// (GitHub including Enterprise, GitLab, Gitea, Azure DevOps).+///+/// Shared by [`parse_ref_url`] (which formats the `pr:`/`mr:` shortcut) and+/// [`repo_url_from_ref_url`] (which keeps the path up to the marker).+fn parse_ref_url_parts(input: &str) -> Option<RefUrlParts<'_>> {let trimmed = input.trim();- let rest = trimmed- .strip_prefix("https://")- .or_else(|| trimmed.strip_prefix("http://"))?;+ let scheme_end = trimmed.find("://")?;+ let scheme = &trimmed[..scheme_end];+ if scheme != "https" && scheme != "http" {+ return None;+ }+ let rest = &trimmed[scheme_end + 3..];// Drop query/fragment so trailing `?foo=bar` / `#discussion_r...` don't// break the segment match.let path = rest.split(['?', '#']).next()?;let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();- // Minimum shape: host / owner / repo / kind / N (5 segments). This- // rejects "pull/123" as a literal branch name (no protocol prefix passes- // the strip above already, but the length check covers e.g.- // `https://example.com/pull/1` which is too shallow to be a real URL).+ // Minimum shape: host / owner / repo / kind / N (5 segments). Rejects e.g.+ // `https://example.com/pull/1`, too shallow to be a real PR URL.if segments.len() < 5 {return None;}- for pair in segments.windows(2) {+ for (marker_index, pair) in segments.windows(2).enumerate() {let Ok(number) = pair[1].parse::<u32>() else {continue;};- match pair[0] {+ let kind = match pair[0] {// GitHub `pull`, Gitea `pulls`, Azure DevOps `pullrequest`.- "pull" | "pulls" | "pullrequest" => return Some(format!("pr:{number}")),+ "pull" | "pulls" | "pullrequest" => "pr",// GitLab `merge_requests` (always preceded by `/-/`).- "merge_requests" => return Some(format!("mr:{number}")),- _ => {}- }+ "merge_requests" => "mr",+ _ => continue,+ };+ return Some(RefUrlParts {+ scheme,+ segments,+ marker_index,+ kind,+ number,+ });}None}+/// Parse a forge PR/MR web URL into the equivalent `pr:N` / `mr:N` shortcut+/// string.+///+/// Callers substitute the returned shortcut for the original input, so URL+/// handling flows through the same `pr:` / `mr:` parsing path as a literal+/// shortcut, with no duplicate dispatch. Detection is shape-based, not+/// host-based, so self-hosted instances work without an allow-list (see+/// `parse_ref_url_parts`).+pub fn parse_ref_url(input: &str) -> Option<String> {+ let parts = parse_ref_url_parts(input)?;+ Some(format!("{}:{}", parts.kind, parts.number))+}++/// Derive the repository web URL from a PR/MR URL.+///+/// Truncates the PR/MR path (`/pull/N`, `/pulls/N`, `/pullrequest/N`, or+/// `/-/merge_requests/N`) to leave the repository's web URL. The result names+/// the **target** repository: for a fork PR it is the upstream repo the PR was+/// opened against, not the contributor's fork. `wt list --format=json` uses+/// this to align `repo_url` with the PR/MR link in `ci.url`, since the primary+/// remote in a fork checkout points at the fork (the source).+///+/// Detection is shape-based and host-agnostic (see `parse_ref_url_parts`).+/// Returns `None` when the input isn't a recognized PR/MR link.+pub fn repo_url_from_ref_url(input: &str) -> Option<String> {+ let parts = parse_ref_url_parts(input)?;++ // The repository path is everything before the marker segment. GitLab+ // places a `/-/` separator before `merge_requests`; drop the trailing `-`+ // so the repo URL doesn't end in it.+ let mut repo_segments = &parts.segments[..parts.marker_index];+ if repo_segments.last() == Some(&"-") {+ repo_segments = &repo_segments[..repo_segments.len() - 1];+ }+ // Need host + at least owner/repo (Azure: org/project/_git/repo).+ if repo_segments.len() < 3 {+ return None;+ }+ Some(format!("{}://{}", parts.scheme, repo_segments.join("/")))+}+#[cfg(test)]mod tests {use super::*;@@ -423,4 +484,71 @@ mod tests {assert_eq!(parse_ref_url(""), None);assert_eq!(parse_ref_url(" "), None);}++ #[test]+ fn repo_url_from_ref_url_per_forge() {+ let cases = [+ // GitHub, including a fork PR (target repo = the upstream owner).+ (+ "https://github.com/upstream/repo/pull/123",+ "https://github.com/upstream/repo",+ ),+ // Trailing segments and fragments are ignored.+ (+ "https://github.com/owner/repo/pull/2895/files",+ "https://github.com/owner/repo",+ ),+ (+ "https://github.com/owner/repo/pull/77#discussion_r1",+ "https://github.com/owner/repo",+ ),+ // GitHub Enterprise host.+ (+ "https://github.acme.com/team/repo/pull/9",+ "https://github.acme.com/team/repo",+ ),+ // GitLab drops the `/-/` separator; nested subgroups preserved.+ (+ "https://gitlab.com/group/sub/repo/-/merge_requests/7/diffs",+ "https://gitlab.com/group/sub/repo",+ ),+ // Gitea / Codeberg `/pulls/N`.+ (+ "https://codeberg.org/owner/repo/pulls/55",+ "https://codeberg.org/owner/repo",+ ),+ // Azure DevOps keeps the `_git` segment.+ (+ "https://dev.azure.com/org/project/_git/repo/pullrequest/9",+ "https://dev.azure.com/org/project/_git/repo",+ ),+ // http:// is preserved.+ (+ "http://github.com/owner/repo/pull/1",+ "http://github.com/owner/repo",+ ),+ ];+ for (input, expected) in cases {+ assert_eq!(+ repo_url_from_ref_url(input).as_deref(),+ Some(expected),+ "input: {input}"+ );+ }+ }++ #[test]+ fn repo_url_from_ref_url_rejects_non_pr_urls() {+ // Not a PR/MR link.+ assert_eq!(repo_url_from_ref_url("https://github.com/owner/repo"), None);+ assert_eq!(+ repo_url_from_ref_url("https://github.com/o/r/issues/5"),+ None+ );+ // Too shallow.+ assert_eq!(repo_url_from_ref_url("https://example.com/pull/1"), None);+ // Not a URL.+ assert_eq!(repo_url_from_ref_url("pr:123"), None);+ assert_eq!(repo_url_from_ref_url(""), None);+ }}diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 56595366d..a195c5cc8 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -295,6 +295,18 @@ impl Repository {.and_then(GitRemoteUrl::parse)}+ /// Repository web URL derived from the primary remote.+ ///+ /// Local-only: built from the cached primary remote URL via+ /// [`GitRemoteUrl::web_url`], with no network access. Returns `None` when no+ /// remote is configured or the URL doesn't parse as a forge remote. In rare+ /// multi-remote mirror setups this may name a different forge than a+ /// branch's CI URL, since it always derives from the primary remote+ /// (matching [`project_identifier`](Self::project_identifier)).+ pub fn repo_web_url(&self) -> Option<String> {+ self.primary_remote_parsed_url().and_then(|u| u.web_url())+ }+/// Parsed URL of the remote that belongs to a particular forge.////// Prefers the primary remote when it matches `is_forge`, then the firstdiff --git a/src/git/url.rs b/src/git/url.rsindex b4a68793e..5b1c4daf1 100644--- a/src/git/url.rs+++ b/src/git/url.rs@@ -212,6 +212,54 @@ impl GitRemoteUrl {parts.first().copied()}}++ /// Build the repository web URL from the already-parsed components.+ ///+ /// Local-only: derives purely from the parsed remote, with no network+ /// access. This is the single place that knows the per-forge "web URL from+ /// a parsed remote" shape.+ ///+ /// - Standard forges (GitHub, GitLab incl. nested groups, Gitea, generic):+ /// `https://{host}/{owner}/{repo}`.+ /// - Azure DevOps: `https://dev.azure.com/{org}/{project}/_git/{repo}`, or+ /// `https://{host}/{project}/_git/{repo}` for legacy `*.visualstudio.com`+ /// (where the org is in the hostname). The naive `host/owner/repo` form is+ /// wrong for the SSH (`ssh.dev.azure.com:v3/...`) remote shape, so the+ /// [`azure_organization`](Self::azure_organization) /+ /// [`azure_project`](Self::azure_project) accessors feed the canonical+ /// [`fork_remote_url`](crate::git::remote_ref::azure::fork_remote_url)+ /// builder. The SSH `ssh.dev.azure.com` host is normalized to the+ /// `dev.azure.com` web host.+ ///+ /// Returns `None` only when an Azure DevOps URL is missing its org/project.+ pub fn web_url(&self) -> Option<String> {+ if self.is_azure_devops() {+ let organization = self.azure_organization()?;+ let project = self.azure_project()?;+ // `*.visualstudio.com` keeps the org in the hostname; every other+ // Azure remote shape (including `ssh.dev.azure.com`) maps to the+ // `dev.azure.com` web host.+ let host = if self+ .host+ .to_ascii_lowercase()+ .ends_with(".visualstudio.com")+ {+ self.host.as_str()+ } else {+ "dev.azure.com"+ };+ return Some(crate::git::remote_ref::azure::fork_remote_url(+ host,+ organization,+ project,+ &self.repo,+ ));+ }+ Some(format!(+ "https://{}/{}/{}",+ self.host, self.owner, self.repo+ ))+ }}/// Extract owner and repository name from a git remote URL.@@ -1082,4 +1130,55 @@ mod tests {assert_eq!(url.azure_organization(), None);assert_eq!(url.azure_project(), None);}++ #[test]+ fn test_web_url() {+ let web_url = |input: &str| GitRemoteUrl::parse(input).unwrap().web_url();++ // github.com: SSH input produces HTTPS output (the core value).+ assert_eq!(+ web_url("[email protected]:owner/repo.git"),+ Some("https://github.com/owner/repo".to_string())+ );+ assert_eq!(+ web_url("https://github.com/owner/repo.git"),+ Some("https://github.com/owner/repo".to_string())+ );++ // GitHub Enterprise host.+ assert_eq!(+ web_url("[email protected]:owner/repo.git"),+ Some("https://github.mycompany.com/owner/repo".to_string())+ );++ // GitLab nested group.+ assert_eq!(+ web_url("[email protected]:group/subgroup/repo.git"),+ Some("https://gitlab.com/group/subgroup/repo".to_string())+ );++ // Gitea.+ assert_eq!(+ web_url("[email protected]:owner/repo.git"),+ Some("https://gitea.example.com/owner/repo".to_string())+ );++ // Azure DevOps: HTTPS dev.azure.com.+ assert_eq!(+ web_url("https://dev.azure.com/myorg/myproject/_git/myrepo"),+ Some("https://dev.azure.com/myorg/myproject/_git/myrepo".to_string())+ );++ // Azure DevOps: SSH ssh.dev.azure.com normalizes to the dev.azure.com web host.+ assert_eq!(+ web_url("[email protected]:v3/myorg/myproject/myrepo"),+ Some("https://dev.azure.com/myorg/myproject/_git/myrepo".to_string())+ );++ // Azure DevOps: legacy *.visualstudio.com keeps the org in the hostname.+ assert_eq!(+ web_url("https://myorg.visualstudio.com/myproject/_git/myrepo"),+ Some("https://myorg.visualstudio.com/myproject/_git/myrepo".to_string())+ );+ }}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 1896738c3..8fd4f195a 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -227,6 +227,35 @@ fn test_list_json_with_metadata(mut repo: TestRepo) {});}+/// `repo_url` is derived locally from the primary remote, converting an SSH+/// remote to its HTTPS web URL without shelling out to a forge.+#[rstest]+fn test_list_json_repo_url_from_ssh_remote(repo: TestRepo) {+ // A real forge SSH remote. The local-path remote the fixture configures+ // doesn't parse as a forge, so `repo_url` would be absent for it.+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "[email protected]:owner/repo.git",+ ]);++ let output = repo+ .wt_command()+ .args(["list", "--format=json"])+ .output()+ .unwrap();+ assert!(output.status.success(), "wt list should succeed");++ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();+ let row = json.first().expect("at least one row");+ assert_eq!(+ row["repo_url"].as_str(),+ Some("https://github.com/owner/repo"),+ "SSH remote should derive the HTTPS web URL"+ );+}+/// This tests the merge commit scenario where content matches main even with different commit history.#[rstest]fn test_list_json_tree_matches_main_after_merge(mut repo: TestRepo) {