jjpr 0.14.0

Manage stacked pull requests in Jujutsu repositories
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
use anyhow::Result;

use super::types::RepoInfo;
use super::ForgeKind;
use crate::jj::GitRemote;

/// Parse a GitHub remote URL into owner/repo.
///
/// Supports HTTPS (`https://github.com/owner/repo.git`),
/// SSH (`git@github.com:owner/repo.git`),
/// and GitHub Enterprise subdomains (`company.github.com`).
pub fn parse_github_url(url: &str) -> Option<RepoInfo> {
    parse_url_for_host(url, is_github_host)
}

/// Parse a GitLab remote URL into owner/repo.
///
/// Supports `gitlab.com` and GitLab self-hosted subdomains (`company.gitlab.com`).
/// For nested groups (`group/subgroup/repo`), `owner` contains the full namespace.
pub fn parse_gitlab_url(url: &str) -> Option<RepoInfo> {
    let (host, path) = extract_host_and_path(url)?;
    if !is_gitlab_host(host) {
        return None;
    }
    parse_gitlab_path(path)
}

/// Parse a Forgejo/Codeberg remote URL into owner/repo.
pub fn parse_forgejo_url(url: &str) -> Option<RepoInfo> {
    parse_url_for_host(url, is_forgejo_host)
}

/// Detect the forge type and extract repo info from a remote URL.
pub fn detect_forge(url: &str) -> Option<(ForgeKind, RepoInfo)> {
    if let Some(info) = parse_github_url(url) {
        return Some((ForgeKind::GitHub, info));
    }
    if let Some(info) = parse_gitlab_url(url) {
        return Some((ForgeKind::GitLab, info));
    }
    if let Some(info) = parse_forgejo_url(url) {
        return Some((ForgeKind::Forgejo, info));
    }
    None
}

/// Extract host from a remote URL.
pub fn extract_host(url: &str) -> Option<&str> {
    extract_host_and_path(url).map(|(host, _)| host)
}

fn extract_host_and_path(url: &str) -> Option<(&str, &str)> {
    // SSH: git@host:path
    if let Some(rest) = url.strip_prefix("git@") {
        return rest.split_once(':');
    }
    // SSH: ssh://git@host/path
    if let Some(rest) = url.strip_prefix("ssh://git@") {
        return rest.split_once('/');
    }
    // HTTPS/HTTP
    for prefix in &["https://", "http://"] {
        if let Some(rest) = url.strip_prefix(prefix) {
            return rest.split_once('/');
        }
    }
    None
}

fn parse_url_for_host(url: &str, host_check: fn(&str) -> bool) -> Option<RepoInfo> {
    let (host, path) = extract_host_and_path(url)?;
    if !host_check(host) {
        return None;
    }
    parse_owner_repo(path)
}

fn is_github_host(host: &str) -> bool {
    host == "github.com" || host.ends_with(".github.com")
}

fn is_gitlab_host(host: &str) -> bool {
    host == "gitlab.com" || host.ends_with(".gitlab.com")
}

fn is_forgejo_host(host: &str) -> bool {
    host == "codeberg.org"
}

fn parse_owner_repo(path: &str) -> Option<RepoInfo> {
    let path = path.strip_suffix(".git").unwrap_or(path);
    let (owner, repo) = path.split_once('/')?;
    let owner = owner.trim();
    let repo = repo.split('/').next()?.trim();
    if owner.is_empty() || repo.is_empty() {
        return None;
    }
    Some(RepoInfo {
        owner: owner.to_string(),
        repo: repo.to_string(),
    })
}

/// GitLab supports nested groups: `group/subgroup/repo`.
/// The last segment is the repo, everything before is the namespace.
fn parse_gitlab_path(path: &str) -> Option<RepoInfo> {
    let path = path.strip_suffix(".git").unwrap_or(path);
    let last_slash = path.rfind('/')?;
    let owner = path[..last_slash].trim();
    let repo = path[last_slash + 1..].trim();
    if owner.is_empty() || repo.is_empty() {
        return None;
    }
    Some(RepoInfo {
        owner: owner.to_string(),
        repo: repo.to_string(),
    })
}

/// Parse owner/repo from a URL for a specific forge kind, ignoring host detection.
/// Used when config explicitly sets the forge type.
pub fn parse_url_as(url: &str, kind: ForgeKind) -> Option<RepoInfo> {
    let (_, path) = extract_host_and_path(url)?;
    match kind {
        ForgeKind::GitLab => parse_gitlab_path(path),
        ForgeKind::GitHub | ForgeKind::Forgejo => parse_owner_repo(path),
    }
}

/// Filter a list of git remotes to supported forge remotes.
pub fn find_forge_remotes(remotes: &[GitRemote]) -> Vec<(String, ForgeKind, RepoInfo)> {
    remotes
        .iter()
        .filter_map(|r| {
            let (kind, info) = detect_forge(&r.url)?;
            Some((r.name.clone(), kind, info))
        })
        .collect()
}

/// Select the appropriate remote. If `preferred` is set, use that; otherwise
/// if there's exactly one supported forge remote, use it; otherwise return an error.
pub fn resolve_remote(
    remotes: &[GitRemote],
    preferred: Option<&str>,
) -> Result<(String, ForgeKind, RepoInfo)> {
    let forge_remotes = find_forge_remotes(remotes);

    if let Some(name) = preferred {
        return forge_remotes
            .into_iter()
            .find(|(n, _, _)| n == name)
            .ok_or_else(|| anyhow::anyhow!("remote '{}' is not a supported forge remote", name));
    }

    match forge_remotes.len() {
        0 => anyhow::bail!(
            "no supported forge remotes found. Either add a supported remote \
             (jj git remote add origin <URL>) or set forge = \"...\" in .jj/jjpr.toml"
        ),
        1 => Ok(forge_remotes.into_iter().next().expect("len checked")),
        _ => {
            let names: Vec<&str> = forge_remotes.iter().map(|(n, _, _)| n.as_str()).collect();
            anyhow::bail!(
                "multiple forge remotes found: {}. Use --remote to specify one.",
                names.join(", ")
            )
        }
    }
}

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

    #[test]
    fn test_parse_github_https_url() {
        let info = parse_github_url("https://github.com/owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_https_no_git_suffix() {
        let info = parse_github_url("https://github.com/owner/repo").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_ssh_url() {
        let info = parse_github_url("git@github.com:owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_ssh_no_git_suffix() {
        let info = parse_github_url("git@github.com:owner/repo").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_ssh_protocol_url() {
        let info = parse_github_url("ssh://git@github.com/owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_github_enterprise_subdomain() {
        let info = parse_github_url("https://company.github.com/owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_reject_non_github_https() {
        assert!(parse_github_url("https://gitlab.com/owner/repo.git").is_none());
    }

    #[test]
    fn test_reject_non_github_ssh() {
        assert!(parse_github_url("git@gitlab.com:owner/repo.git").is_none());
    }

    #[test]
    fn test_reject_empty_url() {
        assert!(parse_github_url("").is_none());
    }

    // GitLab tests
    #[test]
    fn test_parse_gitlab_https() {
        let info = parse_gitlab_url("https://gitlab.com/owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_gitlab_ssh() {
        let info = parse_gitlab_url("git@gitlab.com:owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_gitlab_nested_groups() {
        let info = parse_gitlab_url("https://gitlab.com/group/subgroup/repo.git").unwrap();
        assert_eq!(info.owner, "group/subgroup");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_gitlab_enterprise_subdomain() {
        let info = parse_gitlab_url("https://company.gitlab.com/team/repo.git").unwrap();
        assert_eq!(info.owner, "team");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_gitlab_rejects_github_url() {
        assert!(parse_gitlab_url("https://github.com/owner/repo.git").is_none());
    }

    // Forgejo/Codeberg tests
    #[test]
    fn test_parse_codeberg_https() {
        let info = parse_forgejo_url("https://codeberg.org/owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_codeberg_ssh() {
        let info = parse_forgejo_url("git@codeberg.org:owner/repo.git").unwrap();
        assert_eq!(info.owner, "owner");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_forgejo_rejects_github_url() {
        assert!(parse_forgejo_url("https://github.com/owner/repo.git").is_none());
    }

    // detect_forge tests
    #[test]
    fn test_detect_forge_github() {
        let (kind, info) = detect_forge("git@github.com:me/repo.git").unwrap();
        assert_eq!(kind, ForgeKind::GitHub);
        assert_eq!(info.owner, "me");
    }

    #[test]
    fn test_detect_forge_gitlab() {
        let (kind, info) = detect_forge("git@gitlab.com:me/repo.git").unwrap();
        assert_eq!(kind, ForgeKind::GitLab);
        assert_eq!(info.owner, "me");
    }

    #[test]
    fn test_detect_forge_codeberg() {
        let (kind, info) = detect_forge("https://codeberg.org/me/repo.git").unwrap();
        assert_eq!(kind, ForgeKind::Forgejo);
        assert_eq!(info.owner, "me");
    }

    #[test]
    fn test_detect_forge_unknown() {
        assert!(detect_forge("https://example.com/me/repo.git").is_none());
    }

    // find_forge_remotes tests
    #[test]
    fn test_find_forge_remotes_mixed() {
        let remotes = vec![
            GitRemote {
                name: "origin".to_string(),
                url: "git@github.com:me/myrepo.git".to_string(),
            },
            GitRemote {
                name: "upstream".to_string(),
                url: "https://gitlab.com/other/repo.git".to_string(),
            },
            GitRemote {
                name: "unknown".to_string(),
                url: "https://example.com/foo/bar.git".to_string(),
            },
        ];
        let found = find_forge_remotes(&remotes);
        assert_eq!(found.len(), 2);
        assert_eq!(found[0].0, "origin");
        assert_eq!(found[0].1, ForgeKind::GitHub);
        assert_eq!(found[1].0, "upstream");
        assert_eq!(found[1].1, ForgeKind::GitLab);
    }

    // resolve_remote tests
    #[test]
    fn test_resolve_remote_single() {
        let remotes = vec![GitRemote {
            name: "origin".to_string(),
            url: "git@github.com:me/repo.git".to_string(),
        }];
        let (name, kind, info) = resolve_remote(&remotes, None).unwrap();
        assert_eq!(name, "origin");
        assert_eq!(kind, ForgeKind::GitHub);
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_resolve_remote_preferred() {
        let remotes = vec![
            GitRemote {
                name: "origin".to_string(),
                url: "git@github.com:me/repo.git".to_string(),
            },
            GitRemote {
                name: "fork".to_string(),
                url: "git@github.com:other/repo.git".to_string(),
            },
        ];
        let (name, _, info) = resolve_remote(&remotes, Some("fork")).unwrap();
        assert_eq!(name, "fork");
        assert_eq!(info.owner, "other");
    }

    #[test]
    fn test_resolve_remote_no_forge() {
        let remotes = vec![GitRemote {
            name: "origin".to_string(),
            url: "https://example.com/me/repo.git".to_string(),
        }];
        let err = resolve_remote(&remotes, None).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("no supported forge remotes found"), "{msg}");
    }

    #[test]
    fn test_resolve_remote_multiple_no_preference() {
        let remotes = vec![
            GitRemote {
                name: "origin".to_string(),
                url: "git@github.com:me/repo.git".to_string(),
            },
            GitRemote {
                name: "gitlab".to_string(),
                url: "git@gitlab.com:me/repo.git".to_string(),
            },
        ];
        let err = resolve_remote(&remotes, None).unwrap_err();
        assert!(err.to_string().contains("multiple forge remotes"));
    }

    // parse_url_as tests — used when config explicitly sets forge type
    #[test]
    fn test_parse_url_as_github_from_any_host() {
        let info = parse_url_as("https://forgejo.example.com/me/repo.git", ForgeKind::GitHub).unwrap();
        assert_eq!(info.owner, "me");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_url_as_forgejo_from_any_host() {
        let info = parse_url_as("git@git.mycompany.com:team/project.git", ForgeKind::Forgejo).unwrap();
        assert_eq!(info.owner, "team");
        assert_eq!(info.repo, "project");
    }

    #[test]
    fn test_parse_url_as_gitlab_uses_nested_groups() {
        let info = parse_url_as("https://git.mycompany.com/group/sub/repo.git", ForgeKind::GitLab).unwrap();
        assert_eq!(info.owner, "group/sub");
        assert_eq!(info.repo, "repo");
    }

    #[test]
    fn test_parse_url_as_invalid_url() {
        assert!(parse_url_as("", ForgeKind::GitHub).is_none());
    }
}