worktrunk 0.59.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Azure DevOps PR provider.
//!
//! Implements `RemoteRefProvider` for Azure DevOps Pull Requests using the `az` CLI.
//! Requires the `azure-devops` extension (`az extension add --name azure-devops`).

use anyhow::{Context, bail};
use serde::Deserialize;

use super::{CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error};
use crate::git::url::GitRemoteUrl;
use crate::git::{RefType, Repository};

/// Azure DevOps Pull Request provider.
#[derive(Debug, Clone, Copy)]
pub struct AzureDevOpsProvider;

impl RemoteRefProvider for AzureDevOpsProvider {
    fn ref_type(&self) -> RefType {
        RefType::Pr
    }

    fn platform_label(&self) -> &'static str {
        "azure-devops"
    }

    fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
        fetch_pr_info(number, repo)
    }

    fn ref_path(&self, number: u32) -> String {
        format!("pull/{}/head", number)
    }
}

/// Construct an Azure DevOps remote URL for a repo.
///
/// Emits `https://{host}/{org}/{project}/_git/{repo}` for `dev.azure.com` and
/// `https://{host}/{project}/_git/{repo}` for legacy `*.visualstudio.com` hosts
/// (where the org is in the hostname). Azure DevOps SSH URLs require per-org
/// public keys, so HTTPS — which works with both PAT and Azure CLI auth — is
/// the safe default.
pub fn fork_remote_url(host: &str, organization: &str, project: &str, repo: &str) -> String {
    if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
        format!("https://{}/{}/_git/{}", host, project, repo)
    } else {
        format!(
            "https://{}/{}/{}/_git/{}",
            host, organization, project, repo
        )
    }
}

/// Construct the PR web URL for the user's actual host (handles `*.visualstudio.com`).
pub fn pr_web_url(host: &str, organization: &str, project: &str, repo: &str, pr: u32) -> String {
    if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
        format!(
            "https://{}/{}/_git/{}/pullrequest/{}",
            host, project, repo, pr
        )
    } else {
        format!(
            "https://dev.azure.com/{}/{}/_git/{}/pullrequest/{}",
            organization, project, repo, pr
        )
    }
}

/// Construct the build-results web URL for the user's actual host.
pub fn build_web_url(host: &str, organization: &str, project: &str, build_id: u32) -> String {
    if host.to_ascii_lowercase().ends_with(".visualstudio.com") {
        format!(
            "https://{}/{}/_build/results?buildId={}",
            host, project, build_id
        )
    } else {
        format!(
            "https://dev.azure.com/{}/{}/_build/results?buildId={}",
            organization, project, build_id
        )
    }
}

/// Raw JSON response from `az repos pr show --id <N>`.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AzPrResponse {
    title: String,
    created_by: AzIdentity,
    status: String,
    #[serde(default)]
    is_draft: bool,
    source_ref_name: String,
    repository: AzRepository,
    #[serde(default)]
    fork_source: Option<AzForkRef>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AzIdentity {
    unique_name: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AzRepository {
    name: String,
    project: AzProject,
    #[serde(default)]
    web_url: Option<String>,
}

#[derive(Debug, Deserialize)]
struct AzProject {
    name: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AzForkRef {
    repository: AzForkRepository,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct AzForkRepository {
    #[serde(default)]
    remote_url: Option<String>,
    #[serde(default)]
    ssh_url: Option<String>,
}

/// Detect the Azure DevOps `(host, organization)` to use for API calls.
///
/// Prefers the primary remote (typically `origin` or whatever the user pushed
/// with) so fork workflows hit the right tenant. Falls back to the first
/// Azure remote found if the primary isn't Azure DevOps.
fn detect_azure_target(repo: &Repository) -> Option<(String, String)> {
    if let Ok(remote) = repo.primary_remote()
        && let Some(url) = repo.effective_remote_url(&remote)
        && let Some(parsed) = GitRemoteUrl::parse(&url)
        && let Some(org) = parsed.azure_organization()
    {
        return Some((parsed.host().to_string(), org.to_string()));
    }
    for (_, url) in repo.all_remote_urls() {
        if let Some(parsed) = GitRemoteUrl::parse(&url)
            && let Some(org) = parsed.azure_organization()
        {
            return Some((parsed.host().to_string(), org.to_string()));
        }
    }
    None
}

/// Build the `--org` URL for the `az` CLI from a host and organization.
///
/// `dev.azure.com` and `ssh.dev.azure.com` both map to the cloud `dev.azure.com`
/// API host. Legacy `*.visualstudio.com` hosts keep their hostname (the API
/// accepts both forms).
pub fn az_org_url(host: &str, organization: &str) -> String {
    let lower = host.to_ascii_lowercase();
    if lower.ends_with(".visualstudio.com") {
        format!("https://{}", host)
    } else {
        format!("https://dev.azure.com/{}", organization)
    }
}

/// Parse `(host, organization)` out of an Azure DevOps web URL.
///
/// Returns `None` if the URL is missing or unrecognised; callers fall back to
/// the org detected from local remotes. We refuse to invent values here — the
/// previous version's `unwrap_or(project_name)` produced wrong but plausible
/// identifiers that propagated into the constructed PR URL.
///
/// Two shapes are recognised:
/// - `https://dev.azure.com/{org}/{project}/_git/{repo}` → `("dev.azure.com", org)`
/// - `https://{org}.visualstudio.com/{project}/_git/{repo}` → `("{org}.visualstudio.com", org)`
fn parse_web_url(web_url: Option<&str>) -> Option<(String, String)> {
    let url = web_url?;
    let rest = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    let (host, path) = rest.split_once('/')?;
    let host_lower = host.to_ascii_lowercase();
    if host_lower == "dev.azure.com" {
        let org = path.split('/').next().filter(|s| !s.is_empty())?;
        Some((host.to_string(), org.to_string()))
    } else if host_lower.ends_with(".visualstudio.com") {
        let org = host.split('.').next().filter(|s| !s.is_empty())?;
        Some((host.to_string(), org.to_string()))
    } else {
        None
    }
}

fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
    let repo_root = repo.repo_path()?;
    let pr_id = pr_number.to_string();

    let mut args = vec![
        "repos",
        "pr",
        "show",
        "--id",
        pr_id.as_str(),
        "--output",
        "json",
    ];

    // Auto-detect organization from the primary Azure DevOps remote so
    // contributors don't have to pass `--org` explicitly.
    let target = detect_azure_target(repo);
    let org_url = target.as_ref().map(|(host, org)| az_org_url(host, org));
    if let Some(org_url) = &org_url {
        args.extend(["--org", org_url]);
    }

    let output = super::run_cli_api(CliApiRequest {
        tool: "az",
        args: &args,
        repo_root,
        prompt_env: ("AZURE_CORE_NO_COLOR", "true"),
        install_hint: "Azure CLI (az) not installed; install from https://aka.ms/installazurecli",
        run_context: "Failed to run az repos pr show",
    })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
        let stdout_str = String::from_utf8_lossy(&output.stdout).trim().to_string();

        if stderr.contains("does not exist") || stdout_str.contains("does not exist") {
            bail!("Azure DevOps PR #{} not found", pr_number);
        }
        if stderr.contains("login") || stderr.contains("authenticate") {
            bail!("Azure CLI not authenticated; run az login");
        }
        if stderr.contains("azure-devops") && stderr.contains("extension") {
            bail!(
                "Azure DevOps CLI extension not installed; \
                 run: az extension add --name azure-devops"
            );
        }

        return Err(cli_api_error(
            RefType::Pr,
            format!("az repos pr show failed for PR #{}", pr_number),
            &output,
        ));
    }

    let response: AzPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {
        format!(
            "Failed to parse Azure DevOps API response for PR #{}. \
             This may indicate an az CLI version issue.",
            pr_number
        )
    })?;

    // Strip refs/heads/ prefix from branch names
    let source_branch = response
        .source_ref_name
        .strip_prefix("refs/heads/")
        .unwrap_or(&response.source_ref_name)
        .to_string();

    // Validate at the provider boundary — same as the GitHub/GitLab/Gitea
    // providers — so an empty or `refs/heads/`-only sourceRefName produces a
    // clear diagnostic rather than confusing downstream git/path errors.
    if source_branch.is_empty() {
        bail!(
            "Azure DevOps PR #{} has empty branch name; the PR may be in an invalid state",
            pr_number
        );
    }

    let is_cross_repo = response.fork_source.is_some();

    let fork_push_url = response.fork_source.as_ref().and_then(|fork| {
        fork.repository
            .ssh_url
            .clone()
            .or_else(|| fork.repository.remote_url.clone())
    });

    let project = response.repository.project.name.clone();
    let repo_name = response.repository.name.clone();

    // Prefer the API response's web_url; fall back to whatever we detected from
    // local remotes. Never invent the org from the project name — Azure orgs
    // and projects share a namespace, so a collision produces a URL that 404s
    // in a hard-to-debug way.
    let (host, organization) = parse_web_url(response.repository.web_url.as_deref())
        .or_else(|| target.clone())
        .with_context(|| {
            format!(
                "Could not determine Azure DevOps org/host for PR #{}: \
                 response had no web_url and no local Azure remote is configured.",
                pr_number
            )
        })?;

    let pr_url = pr_web_url(&host, &organization, &project, &repo_name, pr_number);

    Ok(RemoteRefInfo {
        ref_type: RefType::Pr,
        number: pr_number,
        title: response.title,
        author: response.created_by.unique_name,
        state: response.status,
        draft: response.is_draft,
        source_branch,
        is_cross_repo,
        url: pr_url,
        fork_push_url,
        platform_data: PlatformData::AzureDevOps {
            host,
            organization,
            project,
            repo_name,
        },
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ref_path() {
        let provider = AzureDevOpsProvider;
        assert_eq!(provider.ref_path(550), "pull/550/head");
        assert_eq!(provider.tracking_ref(550), "refs/pull/550/head");
    }

    #[test]
    fn test_ref_type() {
        let provider = AzureDevOpsProvider;
        assert_eq!(provider.ref_type(), RefType::Pr);
    }

    #[test]
    fn test_parse_web_url_dev_azure() {
        let parsed = parse_web_url(Some("https://dev.azure.com/myorg/myproject/_git/myrepo"));
        assert_eq!(
            parsed,
            Some(("dev.azure.com".to_string(), "myorg".to_string()))
        );
    }

    #[test]
    fn test_parse_web_url_visualstudio() {
        // Legacy *.visualstudio.com URLs encode the org in the hostname.
        let parsed = parse_web_url(Some("https://myorg.visualstudio.com/myproject/_git/myrepo"));
        assert_eq!(
            parsed,
            Some(("myorg.visualstudio.com".to_string(), "myorg".to_string()))
        );
    }

    #[test]
    fn test_parse_web_url_missing_or_unknown() {
        assert_eq!(parse_web_url(None), None);
        assert_eq!(parse_web_url(Some("https://github.com/owner/repo")), None);
        assert_eq!(parse_web_url(Some("not-a-url")), None);
    }

    #[test]
    fn test_fork_remote_url_format() {
        // dev.azure.com gets the canonical {host}/{org}/{project}/_git/{repo} layout.
        assert_eq!(
            fork_remote_url("dev.azure.com", "myorg", "myproject", "myrepo"),
            "https://dev.azure.com/myorg/myproject/_git/myrepo"
        );
        // *.visualstudio.com URLs omit the org (it's already in the hostname).
        assert_eq!(
            fork_remote_url("myorg.visualstudio.com", "myorg", "myproject", "myrepo"),
            "https://myorg.visualstudio.com/myproject/_git/myrepo"
        );
    }

    #[test]
    fn test_pr_web_url_format() {
        assert_eq!(
            pr_web_url("dev.azure.com", "myorg", "myproject", "myrepo", 42),
            "https://dev.azure.com/myorg/myproject/_git/myrepo/pullrequest/42"
        );
        assert_eq!(
            pr_web_url("myorg.visualstudio.com", "myorg", "myproject", "myrepo", 42),
            "https://myorg.visualstudio.com/myproject/_git/myrepo/pullrequest/42"
        );
    }

    #[test]
    fn test_az_org_url_format() {
        assert_eq!(
            az_org_url("dev.azure.com", "myorg"),
            "https://dev.azure.com/myorg"
        );
        assert_eq!(
            az_org_url("myorg.visualstudio.com", "myorg"),
            "https://myorg.visualstudio.com"
        );
        // ssh.dev.azure.com is the API's cloud host — still routes through dev.azure.com.
        assert_eq!(
            az_org_url("ssh.dev.azure.com", "myorg"),
            "https://dev.azure.com/myorg"
        );
    }
}