stax 0.50.2

Fast stacked Git branches and PRs
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
use crate::config::Config;
use crate::git::GitRepo;
use anyhow::{Context, Result};
use git2::{ConfigLevel, Repository};
use std::collections::HashSet;
use std::path::Path;
use std::process::Command;

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ForgeType {
    GitHub,
    GitLab,
    #[serde(alias = "forgejo")]
    Gitea,
}

impl std::fmt::Display for ForgeType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::GitHub => write!(f, "GitHub"),
            Self::GitLab => write!(f, "GitLab"),
            Self::Gitea => write!(f, "Gitea"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct RemoteInfo {
    pub name: String,
    pub forge: ForgeType,
    pub host: String,
    pub namespace: String,
    pub repo: String,
    pub base_url: String,
    pub api_base_url: Option<String>,
}

impl RemoteInfo {
    pub fn from_repo(repo: &GitRepo, config: &Config) -> Result<Self> {
        let name = config.remote_name().to_string();
        let url = get_remote_url(repo.workdir()?, &name)?;
        let (host, path) = parse_remote_url(&url)?;
        let forge = detect_forge(
            &host,
            config.remote_base_url(),
            config.remote_forge_override(),
        );
        let (namespace, repo_name) = split_namespace_repo(&path)?;

        let configured_base = config.remote_base_url().trim_end_matches('/');
        let base_url = if configured_base.is_empty()
            || (configured_base == "https://github.com" && host != "github.com")
            || (configured_base == "https://gitlab.com" && host != "gitlab.com")
            || (configured_base == "https://gitea.com" && host != "gitea.com")
        {
            format!("https://{}", host)
        } else {
            configured_base.to_string()
        };

        let api_base_url = if let Some(api) = &config.remote.api_base_url {
            Some(api.clone())
        } else {
            Some(default_api_base_url(forge, &base_url))
        };

        Ok(Self {
            name,
            forge,
            host,
            namespace,
            repo: repo_name,
            base_url,
            api_base_url,
        })
    }

    /// Returns the GitHub API owner (first path component only).
    /// For repos like `wayve/frontends/robot-android`, namespace is `wayve/frontends`
    /// but the GitHub API owner is just `wayve`.
    pub fn owner(&self) -> &str {
        self.namespace.split('/').next().unwrap_or(&self.namespace)
    }

    pub fn project_path(&self) -> String {
        format!("{}/{}", self.namespace, self.repo)
    }

    pub fn encoded_project_path(&self) -> String {
        self.project_path().replace('/', "%2F")
    }

    pub fn repo_url(&self) -> String {
        format!("{}/{}/{}", self.base_url, self.namespace, self.repo)
    }

    pub fn pr_url(&self, number: u64) -> String {
        match self.forge {
            ForgeType::GitHub => format!("{}/pull/{}", self.repo_url(), number),
            ForgeType::GitLab => format!("{}/-/merge_requests/{}", self.repo_url(), number),
            ForgeType::Gitea => format!("{}/pulls/{}", self.repo_url(), number),
        }
    }
}

fn detect_forge(
    host: &str,
    configured_base_url: &str,
    forge_override: Option<ForgeType>,
) -> ForgeType {
    if let Some(forge) = forge_override {
        return forge;
    }

    let host = host.to_ascii_lowercase();
    let configured_base_url = configured_base_url.to_ascii_lowercase();

    if host.contains("gitlab") || configured_base_url.contains("gitlab") {
        ForgeType::GitLab
    } else if host.contains("gitea")
        || host.contains("forgejo")
        || configured_base_url.contains("gitea")
        || configured_base_url.contains("forgejo")
    {
        ForgeType::Gitea
    } else {
        ForgeType::GitHub
    }
}

fn default_api_base_url(forge: ForgeType, base_url: &str) -> String {
    match forge {
        ForgeType::GitHub => {
            if base_url == "https://github.com" {
                "https://api.github.com".to_string()
            } else {
                format!("{}/api/v3", base_url)
            }
        }
        ForgeType::GitLab => format!("{}/api/v4", base_url),
        ForgeType::Gitea => format!("{}/api/v1", base_url),
    }
}

pub fn get_remote_url(workdir: &Path, remote: &str) -> Result<String> {
    if let Ok(repo) = Repository::discover(workdir) {
        if let Ok(config) = repo.config() {
            if let Ok(local) = config.open_level(ConfigLevel::Local) {
                if let Ok(url) = local.get_string(&format!("remote.{}.url", remote)) {
                    if !url.trim().is_empty() {
                        return Ok(url);
                    }
                }
            }
        }
    }

    let output = Command::new("git")
        .args(["remote", "get-url", remote])
        .current_dir(workdir)
        .output()
        .context("Failed to get remote URL")?;

    if !output.status.success() {
        anyhow::bail!(
            "No git remote '{}' found.\n\n\
             To fix this, add a remote:\n\n  \
             git remote add {} <url>",
            remote,
            remote
        );
    }

    let url = String::from_utf8(output.stdout)?.trim().to_string();

    if url.is_empty() {
        anyhow::bail!(
            "Git remote '{}' has no URL configured.\n\n\
             To fix this, set the remote URL:\n\n  \
             git remote set-url {} <url>",
            remote,
            remote
        );
    }

    Ok(url)
}

pub fn get_remote_branches(workdir: &Path, remote: &str) -> Result<Vec<String>> {
    let output = Command::new("git")
        .args(["branch", "-r", "--format=%(refname)"])
        .current_dir(workdir)
        .output()
        .context("Failed to list remote branches")?;

    let prefix = format!("refs/remotes/{}/", remote);
    let branches: Vec<String> = String::from_utf8(output.stdout)?
        .lines()
        .filter_map(|s| s.trim().strip_prefix(&prefix))
        .map(|s| s.to_string())
        .collect();

    Ok(branches)
}

/// Remote branch names from `git ls-remote --heads` (no object transfer).
pub fn ls_remote_heads(workdir: &Path, remote: &str) -> Result<HashSet<String>> {
    let output = Command::new("git")
        .args(["ls-remote", "--heads", remote])
        .current_dir(workdir)
        .output()
        .with_context(|| format!("Failed to run git ls-remote --heads {}", remote))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!(
            "git ls-remote --heads failed ({}): {}",
            output.status,
            stderr.trim()
        );
    }

    let prefix = "refs/heads/";
    let mut names = HashSet::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Some((_, refpart)) = line.split_once('\t') {
            if let Some(name) = refpart.strip_prefix(prefix) {
                names.insert(name.to_string());
            }
        }
    }
    Ok(names)
}

/// Fetch only the given branch tips from `remote` (plus any objects reachable from them).
pub fn fetch_remote_refs(workdir: &Path, remote: &str, branches: &[String]) -> Result<()> {
    if branches.is_empty() {
        anyhow::bail!("fetch_remote_refs: no refs to fetch");
    }

    let output = Command::new("git")
        .arg("fetch")
        .arg("--no-tags")
        .arg(remote)
        .args(branches.iter().map(|s| s.as_str()))
        .current_dir(workdir)
        .output()
        .context("Failed to run git fetch")?;

    if output.status.success() {
        return Ok(());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    anyhow::bail!(
        "Failed to fetch refs from {}.\n\ngit stdout:\n{}\n\ngit stderr:\n{}",
        remote,
        stdout.trim(),
        stderr.trim()
    );
}

fn parse_remote_url(url: &str) -> Result<(String, String)> {
    if let Some(stripped) = url.strip_prefix("git@") {
        let mut parts = stripped.splitn(2, ':');
        let host = parts.next().unwrap_or("").to_string();
        let path = parts
            .next()
            .context("Invalid SSH remote URL")?
            .trim_end_matches(".git")
            .to_string();
        return Ok((host, path));
    }

    if let Some(stripped) = url.strip_prefix("ssh://") {
        let without_scheme = stripped;
        let mut host_and_path = without_scheme.splitn(2, '/');
        let host_part = host_and_path.next().unwrap_or("");
        let path = host_and_path
            .next()
            .context("Invalid SSH remote URL")?
            .trim_end_matches(".git")
            .to_string();

        let host_with_user = host_part.split('@').nth(1).unwrap_or(host_part);
        // SSH listen port (e.g. :2222) is not the HTTPS/web port; omit it from host.
        let host = host_with_user
            .split(':')
            .next()
            .unwrap_or(host_with_user)
            .to_string();
        return Ok((host, path));
    }

    if let Some(stripped) = url.strip_prefix("https://") {
        return parse_http_remote(stripped);
    }

    if let Some(stripped) = url.strip_prefix("http://") {
        return parse_http_remote(stripped);
    }

    anyhow::bail!("Unsupported remote URL format: {}", url)
}

fn parse_http_remote(stripped: &str) -> Result<(String, String)> {
    let mut parts = stripped.splitn(2, '/');
    let host = parts.next().unwrap_or("").to_string();
    let path = parts
        .next()
        .context("Invalid HTTP remote URL")?
        .trim_end_matches(".git")
        .to_string();
    Ok((host, path))
}

fn split_namespace_repo(path: &str) -> Result<(String, String)> {
    let parts: Vec<&str> = path
        .trim_matches('/')
        .split('/')
        .filter(|p| !p.is_empty())
        .collect();

    if parts.len() < 2 {
        anyhow::bail!("Remote URL path '{}' is missing owner/repo", path);
    }

    let repo = parts.last().unwrap().to_string();
    let namespace = parts[..parts.len() - 1].join("/");

    Ok((namespace, repo))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::process::Command;
    use tempfile::TempDir;

    #[test]
    fn test_parse_ssh_git_url() {
        let (host, path) = parse_remote_url("git@github.com:owner/repo.git").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_ssh_git_url_without_extension() {
        let (host, path) = parse_remote_url("git@github.com:owner/repo").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_https_url() {
        let (host, path) = parse_remote_url("https://github.com/owner/repo.git").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_https_url_without_extension() {
        let (host, path) = parse_remote_url("https://github.com/owner/repo").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_http_url() {
        let (host, path) = parse_remote_url("http://github.com/owner/repo.git").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_ssh_scheme_url() {
        let (host, path) = parse_remote_url("ssh://git@github.com/owner/repo.git").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_ssh_scheme_url_with_explicit_port() {
        let (host, path) =
            parse_remote_url("ssh://git@gitlab.example.com:2222/org/project.git").unwrap();
        assert_eq!(host, "gitlab.example.com");
        assert_eq!(path, "org/project");
    }

    #[test]
    fn test_parse_github_enterprise_ssh() {
        let (host, path) = parse_remote_url("git@github.example.com:org/project.git").unwrap();
        assert_eq!(host, "github.example.com");
        assert_eq!(path, "org/project");
    }

    #[test]
    fn test_parse_github_enterprise_https() {
        let (host, path) = parse_remote_url("https://github.example.com/org/project.git").unwrap();
        assert_eq!(host, "github.example.com");
        assert_eq!(path, "org/project");
    }

    #[test]
    fn test_get_remote_url_ignores_insteadof_rewrite() {
        let dir = TempDir::new().expect("Failed to create temp dir");
        let path = dir.path();

        Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(path)
            .output()
            .expect("Failed to init git repo");

        Command::new("git")
            .args([
                "remote",
                "add",
                "origin",
                "https://github.com/test/repo.git",
            ])
            .current_dir(path)
            .output()
            .expect("Failed to add remote");

        let base = format!("file://{}/", path.display());
        Command::new("git")
            .args([
                "config",
                &format!("url.{}.insteadOf", base),
                "https://github.com/",
            ])
            .current_dir(path)
            .output()
            .expect("Failed to set insteadOf");

        let url = get_remote_url(path, "origin").unwrap();
        assert_eq!(url, "https://github.com/test/repo.git");
    }

    #[test]
    fn test_parse_nested_namespace() {
        let (host, path) =
            parse_remote_url("https://gitlab.com/group/subgroup/project.git").unwrap();
        assert_eq!(host, "gitlab.com");
        assert_eq!(path, "group/subgroup/project");
    }

    #[test]
    fn test_parse_unsupported_url_format() {
        let result = parse_remote_url("ftp://example.com/repo");
        assert!(result.is_err());
    }

    #[test]
    fn test_split_namespace_repo_simple() {
        let (namespace, repo) = split_namespace_repo("owner/repo").unwrap();
        assert_eq!(namespace, "owner");
        assert_eq!(repo, "repo");
    }

    #[test]
    fn test_split_namespace_repo_nested() {
        let (namespace, repo) = split_namespace_repo("org/team/project").unwrap();
        assert_eq!(namespace, "org/team");
        assert_eq!(repo, "project");
    }

    #[test]
    fn test_split_namespace_repo_with_slashes() {
        let (namespace, repo) = split_namespace_repo("/owner/repo/").unwrap();
        assert_eq!(namespace, "owner");
        assert_eq!(repo, "repo");
    }

    #[test]
    fn test_split_namespace_repo_missing_parts() {
        let result = split_namespace_repo("onlyrepo");
        assert!(result.is_err());
    }

    #[test]
    fn test_split_namespace_repo_empty() {
        let result = split_namespace_repo("");
        assert!(result.is_err());
    }

    #[test]
    fn test_remote_info_owner() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::GitHub,
            host: "github.com".to_string(),
            namespace: "myorg".to_string(),
            repo: "myrepo".to_string(),
            base_url: "https://github.com".to_string(),
            api_base_url: Some("https://api.github.com".to_string()),
        };
        assert_eq!(info.owner(), "myorg");
    }

    #[test]
    fn test_remote_info_repo_url() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::GitHub,
            host: "github.com".to_string(),
            namespace: "myorg".to_string(),
            repo: "myrepo".to_string(),
            base_url: "https://github.com".to_string(),
            api_base_url: Some("https://api.github.com".to_string()),
        };
        assert_eq!(info.repo_url(), "https://github.com/myorg/myrepo");
    }

    #[test]
    fn test_remote_info_pr_url() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::GitHub,
            host: "github.com".to_string(),
            namespace: "myorg".to_string(),
            repo: "myrepo".to_string(),
            base_url: "https://github.com".to_string(),
            api_base_url: Some("https://api.github.com".to_string()),
        };
        assert_eq!(info.pr_url(42), "https://github.com/myorg/myrepo/pull/42");
    }

    #[test]
    fn test_remote_info_nested_namespace() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::GitLab,
            host: "gitlab.com".to_string(),
            namespace: "org/team".to_string(),
            repo: "project".to_string(),
            base_url: "https://gitlab.com".to_string(),
            api_base_url: None,
        };
        assert_eq!(info.repo_url(), "https://gitlab.com/org/team/project");
    }

    #[test]
    fn test_remote_info_gitlab_pr_url() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::GitLab,
            host: "gitlab.com".to_string(),
            namespace: "org/team".to_string(),
            repo: "project".to_string(),
            base_url: "https://gitlab.com".to_string(),
            api_base_url: Some("https://gitlab.com/api/v4".to_string()),
        };
        assert_eq!(
            info.pr_url(42),
            "https://gitlab.com/org/team/project/-/merge_requests/42"
        );
    }

    #[test]
    fn test_remote_info_gitea_pr_url() {
        let info = RemoteInfo {
            name: "origin".to_string(),
            forge: ForgeType::Gitea,
            host: "gitea.example.com".to_string(),
            namespace: "org".to_string(),
            repo: "project".to_string(),
            base_url: "https://gitea.example.com".to_string(),
            api_base_url: Some("https://gitea.example.com/api/v1".to_string()),
        };
        assert_eq!(
            info.pr_url(42),
            "https://gitea.example.com/org/project/pulls/42"
        );
    }

    #[test]
    fn test_detect_forge_prefers_host() {
        assert_eq!(
            detect_forge("gitlab.com", "https://github.com", None),
            ForgeType::GitLab
        );
        assert_eq!(
            detect_forge("gitea.example.com", "https://github.com", None),
            ForgeType::Gitea
        );
        assert_eq!(
            detect_forge("github.example.com", "https://github.com", None),
            ForgeType::GitHub
        );
    }

    #[test]
    fn test_detect_forge_recognizes_forgejo() {
        assert_eq!(
            detect_forge("forgejo.example.com", "https://github.com", None),
            ForgeType::Gitea
        );
        assert_eq!(
            detect_forge("git.example.com", "https://forgejo.example.com", None),
            ForgeType::Gitea
        );
    }

    #[test]
    fn test_detect_forge_explicit_override() {
        // Override should win over hostname-based detection
        assert_eq!(
            detect_forge("github.com", "https://github.com", Some(ForgeType::GitLab)),
            ForgeType::GitLab
        );
        assert_eq!(
            detect_forge(
                "git.mycompany.com",
                "https://git.mycompany.com",
                Some(ForgeType::GitLab)
            ),
            ForgeType::GitLab
        );
        assert_eq!(
            detect_forge("gitlab.com", "https://gitlab.com", Some(ForgeType::GitHub)),
            ForgeType::GitHub
        );
        assert_eq!(
            detect_forge(
                "git.example.com",
                "https://git.example.com",
                Some(ForgeType::Gitea)
            ),
            ForgeType::Gitea
        );
    }

    #[test]
    fn test_forge_type_serde_roundtrip() {
        // Lowercase names deserialize correctly
        assert_eq!(
            serde_json::from_str::<ForgeType>(r#""github""#).unwrap(),
            ForgeType::GitHub
        );
        assert_eq!(
            serde_json::from_str::<ForgeType>(r#""gitlab""#).unwrap(),
            ForgeType::GitLab
        );
        assert_eq!(
            serde_json::from_str::<ForgeType>(r#""gitea""#).unwrap(),
            ForgeType::Gitea
        );
        // "forgejo" alias maps to Gitea
        assert_eq!(
            serde_json::from_str::<ForgeType>(r#""forgejo""#).unwrap(),
            ForgeType::Gitea
        );
    }

    #[test]
    fn test_parse_http_remote_simple() {
        let (host, path) = parse_http_remote("github.com/owner/repo").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }

    #[test]
    fn test_parse_http_remote_with_git_extension() {
        let (host, path) = parse_http_remote("github.com/owner/repo.git").unwrap();
        assert_eq!(host, "github.com");
        assert_eq!(path, "owner/repo");
    }
}