Skip to main content

release_kit/
detect.rs

1//! Forge, repository, and technology detection.
2//!
3//! One pass reads `git remote get-url origin`: the path is the project, the
4//! host chooses the forge. An unrecognized host is never defaulted — a wrong
5//! guess runs protection calls against the wrong API and fails partway
6//! through a setup — so callers refuse and name the override flags instead.
7//! The technology is read from the version file, exactly as the bindings
8//! define it.
9
10use std::path::Path;
11use std::process::Command;
12
13/// A supported forge.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Forge {
16    /// github.com, driven through `gh`.
17    Github,
18    /// gitlab.com or a self-hosted GitLab, driven through `glab`.
19    Gitlab,
20}
21
22impl Forge {
23    /// The wire and directory name.
24    #[must_use]
25    pub const fn as_str(self) -> &'static str {
26        match self {
27            Self::Github => "github",
28            Self::Gitlab => "gitlab",
29        }
30    }
31
32    /// Parse a `--forge` value.
33    #[must_use]
34    pub fn parse(name: &str) -> Option<Self> {
35        match name {
36            "github" => Some(Self::Github),
37            "gitlab" => Some(Self::Gitlab),
38            _ => None,
39        }
40    }
41
42    /// The forge CLI this forge is driven through.
43    #[must_use]
44    pub const fn cli(self) -> &'static str {
45        match self {
46            Self::Github => "gh",
47            Self::Gitlab => "glab",
48        }
49    }
50
51    /// The environment variable that substitutes this forge's CLI.
52    #[must_use]
53    pub const fn cli_override(self) -> &'static str {
54        match self {
55            Self::Github => "RK_GH_BIN",
56            Self::Gitlab => "RK_GLAB_BIN",
57        }
58    }
59
60    /// The lowest forge-CLI version this binary calls.
61    ///
62    /// `gh issue develop` was introduced in gh 2.19.0, so below that the
63    /// command does not exist and the floor is a fact rather than a
64    /// preference. The default naming this binary depends on is a property
65    /// of the GraphQL API — `CreateLinkedBranchInput.name` is optional and
66    /// documented to default to the issue number and title — so no higher
67    /// floor buys correctness.
68    ///
69    /// The `glab` floor is the version whose source this behavior was
70    /// written against. Only `glab api` is called, which is much older, so
71    /// the floor is stricter than the calls need.
72    #[must_use]
73    pub const fn cli_floor(self) -> (u32, u32, u32) {
74        match self {
75            Self::Github => (2, 19, 0),
76            Self::Gitlab => (1, 114, 0),
77        }
78    }
79
80    /// The command that raises a CLI below [`Self::cli_floor`].
81    #[must_use]
82    pub const fn cli_upgrade(self) -> &'static str {
83        match self {
84            Self::Github => "upgrade gh, or point RK_GH_BIN at a newer binary",
85            Self::Gitlab => "upgrade glab, or point RK_GLAB_BIN at a newer binary",
86        }
87    }
88
89    /// Every supported forge, in a stable order.
90    pub const ALL: [Self; 2] = [Self::Github, Self::Gitlab];
91}
92
93/// What one detection pass observed; every field is an observation, and
94/// refusing on what is absent is the caller's decision.
95#[derive(Debug, Default)]
96pub struct Detection {
97    /// The remote's host, where a remote exists and parses.
98    pub host: Option<String>,
99    /// The project path from the remote: no scheme, no `.git` suffix.
100    pub repo: Option<String>,
101    /// The forge the host maps to; `None` with a `host` present means the
102    /// host is unrecognized.
103    pub forge: Option<Forge>,
104}
105
106/// Read the `origin` remote of `dir` and map it, without judging.
107///
108/// The read answers for `dir` alone: the variables a running hook
109/// exports are scrubbed, so an inherited `GIT_DIR` cannot answer with
110/// another repository's remote. The child runs with `dir` as its working
111/// directory rather than through `-C`: where `dir` is the kernel's link
112/// to a held directory, the change of directory happens in the child
113/// before the exec closes the descriptor, so the child stands in the held
114/// directory itself, whatever the pathname has since become.
115#[must_use]
116pub fn detect(dir: &Path) -> Detection {
117    let mut command = Command::new(crate::probes::git_bin());
118    for var in crate::maintenance::GIT_HOOK_VARS {
119        command.env_remove(var);
120    }
121    let out = command
122        .current_dir(dir)
123        .args(["remote", "get-url", "origin"])
124        .output();
125    let url = match out {
126        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_owned(),
127        _ => return Detection::default(),
128    };
129    let Some((host, path)) = split_remote(&url) else {
130        return Detection::default();
131    };
132    let forge = forge_for_host(&host);
133    Detection {
134        host: Some(host),
135        repo: Some(path),
136        forge,
137    }
138}
139
140/// The forge a host maps to. `gitlab.com` and hosts that name gitlab map to
141/// GitLab; a self-hosted instance on a host name that says nothing needs
142/// `--forge`.
143#[must_use]
144pub fn forge_for_host(host: &str) -> Option<Forge> {
145    if host == "github.com" {
146        return Some(Forge::Github);
147    }
148    if host == "gitlab.com" || host.starts_with("gitlab.") {
149        return Some(Forge::Gitlab);
150    }
151    None
152}
153
154/// Host and project path from a git remote URL, for the URL and `scp`-like
155/// forms. The path drops a leading slash and a `.git` suffix.
156#[must_use]
157pub fn split_remote(url: &str) -> Option<(String, String)> {
158    let (host, raw_path) = if let Some((_, rest)) = url.split_once("://") {
159        let (authority, path) = rest.split_once('/')?;
160        let host = authority
161            .rsplit_once('@')
162            .map_or(authority, |(_, host)| host);
163        let host = host.split(':').next()?;
164        (host.to_owned(), path.to_owned())
165    } else {
166        let (authority, path) = url.split_once(':')?;
167        let host = authority
168            .rsplit_once('@')
169            .map_or(authority, |(_, host)| host);
170        (host.to_owned(), path.to_owned())
171    };
172    let path = raw_path
173        .trim_start_matches('/')
174        .trim_end_matches('/')
175        .trim_end_matches(".git")
176        .to_owned();
177    (!host.is_empty() && !path.is_empty()).then_some((host, path))
178}
179
180/// The technology of a repository, read from its version file: `Cargo.toml`
181/// means rust, `pyproject.toml` means python, a `VERSION` file means bash.
182#[must_use]
183pub fn tech_of(dir: &Path) -> Option<&'static str> {
184    if dir.join("Cargo.toml").is_file() {
185        Some("rust")
186    } else if dir.join("pyproject.toml").is_file() {
187        Some("python")
188    } else if dir.join("VERSION").is_file() {
189        Some("bash")
190    } else {
191        None
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::{Forge, forge_for_host, split_remote};
198
199    #[test]
200    fn a_remote_splits_into_host_and_path_in_both_forms() {
201        assert_eq!(
202            split_remote("https://github.com/owner/name.git"),
203            Some(("github.com".into(), "owner/name".into()))
204        );
205        assert_eq!(
206            split_remote("git@gitlab.com:group/sub/name.git"),
207            Some(("gitlab.com".into(), "group/sub/name".into()))
208        );
209        assert_eq!(
210            split_remote("ssh://git@github.com:22/owner/name.git"),
211            Some(("github.com".into(), "owner/name".into()))
212        );
213        assert_eq!(split_remote("not a url"), None);
214    }
215
216    #[test]
217    fn a_host_maps_to_its_forge_and_an_unknown_host_to_none() {
218        assert_eq!(forge_for_host("github.com"), Some(Forge::Github));
219        assert_eq!(forge_for_host("gitlab.com"), Some(Forge::Gitlab));
220        assert_eq!(forge_for_host("gitlab.example.org"), Some(Forge::Gitlab));
221        assert_eq!(forge_for_host("codeberg.org"), None);
222    }
223}