Skip to main content

jouet_github/pr/
target.rs

1//! Naming a PR: a number, a URL, `owner/repo#123` or a branch, and the
2//! repository a bare number or branch belongs to.
3//!
4//! A repository is on GitHub unless it names a host: `gitlab.com/group/sub/project`,
5//! `codeberg.org/owner/repo`, or the host of the checkout's remote. On
6//! GitLab the owner is a group path and can hold slashes, so a repository
7//! is split at its last `/`, never its first.
8
9use crate::forge::{self, Forge};
10use std::fmt;
11use std::process::Command;
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash)]
14pub struct Repo {
15    /// A user or organisation, or on GitLab a group path such as
16    /// `group/subgroup`.
17    pub owner: String,
18    pub name: String,
19    /// The host of a repository that is not on github.com, such as
20    /// `gitlab.com` or `codeberg.org`. `None` is GitHub.
21    pub host: Option<String>,
22}
23
24impl Repo {
25    /// Parses `OWNER/NAME`, a GitHub repository, or `HOST/OWNER/NAME`, where
26    /// a first part with a dot or a colon is the host.
27    pub fn parse(s: &str) -> Option<Self> {
28        let (first, rest) = s.split_once('/')?;
29        if first.contains(['.', ':'])
30            && let Some(repo) = Self::on(first, rest)
31        {
32            return Some(repo);
33        }
34        let (owner, name) = (first, rest);
35        (valid(owner) && valid(name)).then(|| Self {
36            owner: owner.into(),
37            name: name.into(),
38            host: None,
39        })
40    }
41
42    /// The repository at `path` on `host`. Only a GitLab path (or one on a
43    /// host jouet does not know yet) can have more than two parts.
44    pub fn on(host: &str, path: &str) -> Option<Self> {
45        let host = forge::normalize(host);
46        if host.is_empty() || host.contains(['/', '@', ' ', '#']) {
47            return None;
48        }
49        let path = path.trim_matches('/');
50        let path = path.strip_suffix(".git").unwrap_or(path);
51        let known = forge::of_host(&host);
52        if known == Some(Forge::Entire) {
53            return Self::on_entire(host, path);
54        }
55        let (owner, name) = path.rsplit_once('/')?;
56        let nested = owner.contains('/');
57        if (nested && matches!(known, Some(Forge::GitHub | Forge::Forgejo)))
58            || !owner.split('/').all(valid)
59            || !valid(name)
60        {
61            return None;
62        }
63        Some(Self {
64            owner: owner.into(),
65            name: name.into(),
66            host: (known != Some(Forge::GitHub)).then_some(host),
67        })
68    }
69
70    /// A path on Entire: `et/PROJECT/REPO` (or `PROJECT/REPO`, as
71    /// [`Repo::qualified`] writes it) is hosted on Entire, and
72    /// `gh/OWNER/REPO` is the GitHub repository Entire mirrors.
73    fn on_entire(host: String, path: &str) -> Option<Self> {
74        let parts: Vec<&str> = path.split('/').collect();
75        let (owner, name, host) = match parts.as_slice() {
76            ["gh", owner, name] => (*owner, *name, None),
77            ["et", owner, name] | [owner, name] => (*owner, *name, Some(host)),
78            _ => return None,
79        };
80        (valid(owner) && valid(name)).then(|| Self {
81            owner: owner.into(),
82            name: name.into(),
83            host,
84        })
85    }
86
87    /// The forge the repository is on; `None` for a host jouet does not
88    /// know.
89    pub fn forge(&self) -> Option<Forge> {
90        match &self.host {
91            None => Some(Forge::GitHub),
92            Some(host) => forge::of_host(host),
93        }
94    }
95
96    /// `HOST/OWNER/NAME`, or `OWNER/NAME` on GitHub: what [`Repo::parse`]
97    /// reads back.
98    pub fn qualified(&self) -> String {
99        match &self.host {
100            None => self.to_string(),
101            Some(host) => format!("{host}/{self}"),
102        }
103    }
104
105    /// A name for files kept about the repository: `OWNER-NAME` on GitHub,
106    /// `HOST-OWNER-NAME` elsewhere, with a group path's slashes as dashes.
107    pub fn slug(&self) -> String {
108        let slug = match &self.host {
109            None => format!("{}-{}", self.owner, self.name),
110            Some(host) => format!("{host}-{}-{}", self.owner, self.name),
111        };
112        slug.replace(['/', ':'], "-")
113    }
114}
115
116fn valid(part: &str) -> bool {
117    !part.is_empty() && !part.contains(['/', '#', '!', ' ', ':'])
118}
119
120impl fmt::Display for Repo {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        write!(f, "{}/{}", self.owner, self.name)
123    }
124}
125
126/// A PR argument as written, before a repository is chosen for it.
127#[derive(Debug, PartialEq, Eq)]
128pub enum Arg {
129    Number(u64),
130    Branch(String),
131    InRepo(Repo, u64),
132}
133
134impl Arg {
135    /// Reads `123`, `#123`, GitLab's `!123`, `REPO#123` (or `REPO!123`), a
136    /// PR or merge request URL, or else a branch.
137    pub fn parse(s: &str) -> Self {
138        let bare = s
139            .strip_prefix('#')
140            .or_else(|| s.strip_prefix('!'))
141            .unwrap_or(s);
142        if let Some(n) = number(bare) {
143            return Self::Number(n);
144        }
145        if !s.contains("://")
146            && let Some((repo, n)) = s.rsplit_once(['#', '!'])
147            && let (Some(repo), Some(n)) = (Repo::parse(repo), number(n))
148        {
149            return Self::InRepo(repo, n);
150        }
151        if let Some((_, rest)) = s.split_once("://")
152            && let Some((repo, n)) = pr_url(rest)
153        {
154            return Self::InRepo(repo, n);
155        }
156        Self::Branch(s.to_string())
157    }
158}
159
160/// The repository and number in a PR URL, after its scheme:
161/// `HOST/OWNER/NAME/pull/N` (GitHub), `HOST/OWNER/NAME/pulls/N` (Forgejo),
162/// `HOST/et/PROJECT/NAME/trails/N` (Entire) or
163/// `HOST/GROUP/.../NAME/-/merge_requests/N` (GitLab), each with anything
164/// after it.
165fn pr_url(rest: &str) -> Option<(Repo, u64)> {
166    let path = rest.split(['?', '#']).next()?;
167    let (host, path) = path.split_once('/')?;
168    let host = host.rsplit('@').next()?;
169    let parts: Vec<&str> = path.split('/').collect();
170    let (repo, n) = if let Some(dash) = parts.iter().position(|p| *p == "-") {
171        if parts.get(dash + 1) != Some(&"merge_requests") {
172            return None;
173        }
174        (parts[..dash].join("/"), parts.get(dash + 2)?)
175    } else {
176        match parts.as_slice() {
177            [owner, name, "pull" | "pulls", n, ..] => (format!("{owner}/{name}"), n),
178            // An Entire trail; a GitHub repository's trail is not its PR.
179            ["et", owner, name, "trails", n, ..] => (format!("et/{owner}/{name}"), n),
180            _ => return None,
181        }
182    };
183    Some((Repo::on(host, &repo)?, number(n)?))
184}
185
186/// A PR to look up, with its repository settled.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub enum Target {
189    Number(Repo, u64),
190    Branch(Repo, String),
191}
192
193impl Target {
194    pub fn repo(&self) -> &Repo {
195        match self {
196            Self::Number(repo, _) | Self::Branch(repo, _) => repo,
197        }
198    }
199}
200
201impl fmt::Display for Target {
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        match self {
204            Self::Number(repo, n) => write!(f, "{repo}#{n}"),
205            Self::Branch(repo, branch) => write!(f, "{repo}:{branch}"),
206        }
207    }
208}
209
210fn number(s: &str) -> Option<u64> {
211    (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
212        .then(|| s.parse().ok())
213        .flatten()
214        .filter(|&n| n > 0)
215}
216
217/// The repository of this checkout's remotes, on any forge jouet knows,
218/// chosen in the order gh uses: a remote marked by `gh repo set-default`,
219/// then `upstream`, `github`, `origin`, then the rest as git lists them,
220/// with GitHub remotes before those on other forges.
221pub fn repo_from_git() -> Option<Repo> {
222    let out = Command::new("git")
223        .args(["config", "--get-regexp", r"^remote\..*\.(url|gh-resolved)$"])
224        .output()
225        .ok()?;
226    pick_remote(&String::from_utf8_lossy(&out.stdout))
227}
228
229/// The repository named by `git config --get-regexp
230/// '^remote\..*\.(url|gh-resolved)$'` output, chosen as [`repo_from_git`]
231/// chooses, for a caller that ran git in another directory.
232pub fn pick_remote(config: &str) -> Option<Repo> {
233    let mut remotes: Vec<(String, Repo)> = Vec::new();
234    let mut default = None;
235    for line in config.lines() {
236        let Some((key, value)) = line.split_once(' ') else {
237            continue;
238        };
239        let Some(key) = key.strip_prefix("remote.") else {
240            continue;
241        };
242        if let Some(name) = key.strip_suffix(".url") {
243            if let Some(repo) = remote_repo(value) {
244                remotes.push((name.to_string(), repo));
245            }
246        } else if let Some(name) = key.strip_suffix(".gh-resolved") {
247            // `base` marks the remote itself; anything else names a repo.
248            default = Some(if value == "base" {
249                Err(name.to_string())
250            } else {
251                Ok(value.to_string())
252            });
253        }
254    }
255    match default {
256        Some(Ok(repo)) => {
257            if let Some(repo) = Repo::parse(&repo) {
258                return Some(repo);
259            }
260        }
261        Some(Err(name)) => {
262            if let Some((_, repo)) = remotes.iter().find(|(n, _)| *n == name) {
263                return Some(repo.clone());
264            }
265        }
266        None => {}
267    }
268    let rank = |name: &str| match name {
269        "upstream" => 0,
270        "github" => 1,
271        "origin" => 2,
272        _ => 3,
273    };
274    // GitHub first, so a checkout that also has a GitLab or Forgejo mirror
275    // keeps reading GitHub.
276    remotes.sort_by_key(|(name, repo)| (repo.host.is_some(), rank(name)));
277    remotes.into_iter().next().map(|(_, repo)| repo)
278}
279
280/// The repository a remote URL names, in any of git's forms, when its host
281/// runs a forge jouet knows.
282fn remote_repo(url: &str) -> Option<Repo> {
283    let (host, path) = if let Some((scheme, rest)) = url.split_once("://") {
284        // https://gitlab.com/g/s/r, ssh://git@github.com:22/o/r
285        let (authority, path) = rest.split_once('/')?;
286        let host = authority.rsplit('@').next()?;
287        // An HTTP port is the web server's; an SSH port says nothing of it.
288        let host = if scheme.starts_with("http") {
289            host
290        } else {
291            host.split(':').next()?
292        };
293        (host, path)
294    } else {
295        // git@github.com:o/r
296        let (host, path) = url.split_once(':')?;
297        (host.rsplit('@').next()?, path)
298    };
299    forge::of_host(host)?;
300    Repo::on(host, path.trim_end_matches('/'))
301}
302
303/// The branch checked out in this directory, if any.
304pub fn current_branch() -> Option<String> {
305    let out = Command::new("git")
306        .args(["symbolic-ref", "--quiet", "--short", "HEAD"])
307        .output()
308        .ok()?;
309    let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
310    (out.status.success() && !branch.is_empty()).then_some(branch)
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    fn repo(s: &str) -> Repo {
318        Repo::parse(s).unwrap()
319    }
320
321    #[test]
322    fn arguments() {
323        assert_eq!(Arg::parse("15002"), Arg::Number(15002));
324        assert_eq!(Arg::parse("#15002"), Arg::Number(15002));
325        assert_eq!(
326            Arg::parse("jdx/mise#15002"),
327            Arg::InRepo(repo("jdx/mise"), 15002)
328        );
329        for url in [
330            "https://github.com/jdx/mise/pull/15002",
331            "https://github.com/jdx/mise/pull/15002/",
332            "https://github.com/jdx/mise/pull/15002/files?w=1",
333            "https://github.com/jdx/mise/pull/15002#discussion_r1",
334        ] {
335            assert_eq!(
336                Arg::parse(url),
337                Arg::InRepo(repo("jdx/mise"), 15002),
338                "{url}"
339            );
340        }
341        assert_eq!(
342            Arg::parse("feat/pr-status"),
343            Arg::Branch("feat/pr-status".into())
344        );
345        assert_eq!(Arg::parse("0"), Arg::Branch("0".into()));
346        assert_eq!(
347            Arg::parse("https://github.com/jdx/mise/issues/1"),
348            Arg::Branch("https://github.com/jdx/mise/issues/1".into())
349        );
350    }
351
352    #[test]
353    fn repos() {
354        assert_eq!(repo("jdx/mise").to_string(), "jdx/mise");
355        for bad in ["jdx", "/mise", "jdx/", "jdx/mise/x", "jdx/mi se"] {
356            assert_eq!(Repo::parse(bad), None, "{bad}");
357        }
358    }
359
360    #[test]
361    fn remote_urls() {
362        for url in [
363            "git@github.com:jdx/mise.git",
364            "git@github.com:jdx/mise",
365            "https://github.com/jdx/mise.git",
366            "https://github.com/jdx/mise/",
367            "https://user@github.com/jdx/mise",
368            "ssh://git@github.com/jdx/mise.git",
369            "ssh://git@ssh.github.com:443/jdx/mise.git",
370        ] {
371            assert_eq!(remote_repo(url), Some(repo("jdx/mise")), "{url}");
372        }
373        assert_eq!(remote_repo("/home/me/src/mise"), None);
374        assert_eq!(remote_repo("git@git.example.com:jdx/mise.git"), None);
375    }
376
377    #[test]
378    fn gitlab_group_paths_split_at_the_last_slash() {
379        let nested = Repo::parse("gitlab.com/group/sub/project").unwrap();
380        assert_eq!(nested.owner, "group/sub");
381        assert_eq!(nested.name, "project");
382        assert_eq!(nested.host.as_deref(), Some("gitlab.com"));
383        assert_eq!(nested.to_string(), "group/sub/project");
384        assert_eq!(nested.qualified(), "gitlab.com/group/sub/project");
385        assert_eq!(nested.slug(), "gitlab.com-group-sub-project");
386        for url in [
387            "git@gitlab.com:group/sub/project.git",
388            "https://gitlab.com/group/sub/project",
389            "ssh://git@altssh.gitlab.com:443/group/sub/project.git",
390        ] {
391            assert_eq!(remote_repo(url).as_ref(), Some(&nested), "{url}");
392        }
393        for arg in [
394            "https://gitlab.com/group/sub/project/-/merge_requests/12",
395            "https://gitlab.com/group/sub/project/-/merge_requests/12/diffs?w=1",
396            "gitlab.com/group/sub/project!12",
397            "gitlab.com/group/sub/project#12",
398        ] {
399            assert_eq!(Arg::parse(arg), Arg::InRepo(nested.clone(), 12), "{arg}");
400        }
401        assert_eq!(Arg::parse("!12"), Arg::Number(12));
402        // Only GitLab nests groups.
403        assert_eq!(Repo::parse("codeberg.org/a/b/c"), None);
404        assert_eq!(Repo::parse("github.com/a/b/c"), None);
405    }
406
407    #[test]
408    fn forgejo_and_github_hosts() {
409        let forgejo = Repo::parse("codeberg.org/forgejo/forgejo").unwrap();
410        assert_eq!(forgejo.forge(), Some(Forge::Forgejo));
411        assert_eq!(
412            Arg::parse("https://codeberg.org/forgejo/forgejo/pulls/7/files"),
413            Arg::InRepo(forgejo.clone(), 7)
414        );
415        assert_eq!(
416            remote_repo("git@codeberg.org:forgejo/forgejo.git"),
417            Some(forgejo)
418        );
419        // github.com named as a host is the same GitHub repository.
420        assert_eq!(Repo::parse("github.com/jdx/mise"), Some(repo("jdx/mise")));
421        assert_eq!(repo("jdx/mise").slug(), "jdx-mise");
422        // A host jouet does not know parses, and has no forge.
423        let unknown = Repo::parse("git.example.com/a/b").unwrap();
424        assert_eq!(unknown.forge(), None);
425    }
426
427    #[test]
428    fn entire_hosted_repositories_and_mirrors() {
429        let native = Repo::parse("entire.com/jdx/jouet-entire-forge-test").unwrap();
430        assert_eq!(native.forge(), Some(Forge::Entire));
431        assert_eq!(native.owner, "jdx");
432        assert_eq!(native.qualified(), "entire.com/jdx/jouet-entire-forge-test");
433        for url in [
434            "entire://aws-us-east-2.entire.io/et/jdx/jouet-entire-forge-test",
435            "entire://aws-eu-central-1.entire.io/et/jdx/jouet-entire-forge-test.git",
436        ] {
437            assert_eq!(remote_repo(url).as_ref(), Some(&native), "{url}");
438        }
439        assert_eq!(
440            Arg::parse("https://entire.com/et/jdx/jouet-entire-forge-test/trails/3/changes"),
441            Arg::InRepo(native.clone(), 3)
442        );
443        assert_eq!(
444            Arg::parse("entire.com/jdx/jouet-entire-forge-test#3"),
445            Arg::InRepo(native, 3)
446        );
447        // A GitHub repository served through Entire is still GitHub's, and
448        // its trail numbers are not PR numbers.
449        assert_eq!(
450            remote_repo("entire://aws-us-east-2.entire.io/gh/jdx/mise"),
451            Some(repo("jdx/mise"))
452        );
453        assert!(matches!(
454            Arg::parse("https://entire.com/gh/jdx/mise/trails/424"),
455            Arg::Branch(_)
456        ));
457        assert_eq!(Repo::parse("entire.com/et/a/b/c"), None);
458    }
459
460    #[test]
461    fn remotes_on_other_forges_are_chosen_too() {
462        let config = "remote.origin.url git@gitlab.com:group/sub/project.git\n";
463        assert_eq!(
464            pick_remote(config),
465            Repo::parse("gitlab.com/group/sub/project")
466        );
467    }
468
469    #[test]
470    fn remotes_are_chosen_in_ghs_order() {
471        let config = "remote.fork.url git@github.com:me/mise.git\n\
472                      remote.origin.url git@github.com:jdx/mise.git\n\
473                      remote.upstream.url https://gitlab.com/jdx/mise\n";
474        // A GitHub `origin` beats a GitLab `upstream`, and `origin` beats `fork`.
475        assert_eq!(pick_remote(config), Some(repo("jdx/mise")));
476        let config = "remote.origin.url git@github.com:me/mise.git\n\
477                      remote.upstream.url git@github.com:jdx/mise.git\n";
478        assert_eq!(pick_remote(config), Some(repo("jdx/mise")));
479        let config = "remote.origin.url git@github.com:jdx/mise.git\n\
480                      remote.fork.url git@github.com:me/mise.git\n\
481                      remote.fork.gh-resolved base\n";
482        assert_eq!(pick_remote(config), Some(repo("me/mise")));
483        let config = "remote.origin.url git@github.com:me/mise.git\n\
484                      remote.origin.gh-resolved jdx/mise\n";
485        assert_eq!(pick_remote(config), Some(repo("jdx/mise")));
486        assert_eq!(pick_remote(""), None);
487    }
488}