Skip to main content

jouet_github/
forge.rs

1//! Which forge a host runs, where its API is, and which tokens it takes.
2//!
3//! github.com, gitlab.com, codeberg.org, gitea.com and Entire (entire.com,
4//! and the *.entire.io clusters its git is served from) are known. A
5//! self-hosted GitLab or Forgejo is named in jouet's config, which the
6//! binary hands over with [`configure`] and which is read only when a host
7//! jouet does not know comes up:
8//!
9//! ```toml
10//! [forges."git.example.com"]
11//! kind = "gitlab"                                  # or "forgejo" ("gitea" is the same API)
12//! api_url = "https://git.example.com/api/v4"       # optional
13//! ```
14//!
15//! `JOUET_GITLAB_API_URL` and `JOUET_FORGEJO_API_URL` point every host of
16//! that kind at one API root, as `JOUET_GITHUB_API_URL` does for GitHub, for
17//! a test's fake server.
18
19use std::sync::OnceLock;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum Forge {
23    GitHub,
24    GitLab,
25    /// Forgejo and Gitea, which share one API.
26    Forgejo,
27    /// Repositories hosted on Entire itself (`/et/PROJECT/REPO`), read
28    /// through the `entire` CLI.
29    Entire,
30}
31
32impl Forge {
33    /// Parses a config `kind`.
34    pub fn parse(kind: &str) -> Option<Self> {
35        match kind.to_ascii_lowercase().as_str() {
36            "github" => Some(Self::GitHub),
37            "gitlab" => Some(Self::GitLab),
38            "forgejo" | "gitea" => Some(Self::Forgejo),
39            _ => None,
40        }
41    }
42
43    /// The forge's name in messages.
44    pub fn name(self) -> &'static str {
45        match self {
46            Self::GitHub => "GitHub",
47            Self::GitLab => "GitLab",
48            Self::Forgejo => "Forgejo",
49            Self::Entire => "Entire",
50        }
51    }
52
53    /// Entire has no API URL of jouet's own: the `entire` CLI dials it.
54    fn api_url_var(self) -> Option<&'static str> {
55        match self {
56            Self::GitHub => Some("JOUET_GITHUB_API_URL"),
57            Self::GitLab => Some("JOUET_GITLAB_API_URL"),
58            Self::Forgejo => Some("JOUET_FORGEJO_API_URL"),
59            Self::Entire => None,
60        }
61    }
62}
63
64/// A host named in the config.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct Configured {
67    pub host: String,
68    pub forge: Forge,
69    pub api_url: Option<String>,
70    /// The environment variable holding this host's token.
71    pub token_env: Option<String>,
72}
73
74static LOADER: OnceLock<fn() -> Vec<Configured>> = OnceLock::new();
75static CONFIGURED: OnceLock<Vec<Configured>> = OnceLock::new();
76
77/// Sets what reads the hosts the config names. Called once, before any
78/// repository is read; a second call is ignored.
79pub fn configure(load: fn() -> Vec<Configured>) {
80    let _ = LOADER.set(load);
81}
82
83fn configured(host: &str) -> Option<&'static Configured> {
84    let hosts = CONFIGURED.get_or_init(|| {
85        let load = LOADER.get().map_or_else(Vec::new, |load| load());
86        load.into_iter()
87            .map(|mut h| {
88                h.host = normalize(&h.host);
89                h
90            })
91            .collect()
92    });
93    hosts.iter().find(|c| c.host == host)
94}
95
96/// A host as jouet keys it: lowercase, without `www.`.
97pub(crate) fn normalize(host: &str) -> String {
98    let host = host.trim().trim_end_matches('.').to_ascii_lowercase();
99    let host = host
100        .strip_prefix("www.")
101        .map_or(host.clone(), str::to_string);
102    // The SSH-over-443 hosts serve the same repositories.
103    match host.as_str() {
104        "ssh.github.com" => "github.com".into(),
105        "altssh.gitlab.com" => "gitlab.com".into(),
106        // Entire serves its web pages from entire.com and its git from a
107        // cluster such as aws-us-east-2.entire.io; all name one repository.
108        "entire.io" => "entire.com".into(),
109        h if h.ends_with(".entire.io") => "entire.com".into(),
110        _ => host,
111    }
112}
113
114/// The forge a host runs, if jouet knows it.
115pub fn of_host(host: &str) -> Option<Forge> {
116    let host = normalize(host);
117    match host.as_str() {
118        "github.com" => Some(Forge::GitHub),
119        "gitlab.com" => Some(Forge::GitLab),
120        "codeberg.org" | "gitea.com" => Some(Forge::Forgejo),
121        "entire.com" => Some(Forge::Entire),
122        _ => configured(&host).map(|c| c.forge),
123    }
124}
125
126/// The environment variables whose token may be sent to `host`, in order.
127/// Each belongs to one host, so a token meant for one server never reaches
128/// another of the same kind:
129///
130/// - `JOUET_GITLAB_TOKEN`, `GITLAB_TOKEN` and `GITLAB_ACCESS_TOKEN` go to
131///   the host in `GITLAB_HOST`, as glab reads it, else to gitlab.com;
132/// - `JOUET_FORGEJO_TOKEN` and `FORGEJO_TOKEN` go to codeberg.org, and
133///   `GITEA_TOKEN` to gitea.com;
134/// - a configured host's `token_env` goes to that host alone, first.
135pub(crate) fn token_vars(forge: Forge, host: &str) -> Vec<String> {
136    let host = normalize(host);
137    let mut vars: Vec<String> = configured(&host)
138        .and_then(|c| c.token_env.clone())
139        .into_iter()
140        .collect();
141    let gitlab_host = std::env::var("GITLAB_HOST")
142        .ok()
143        .map(|h| {
144            let h = h.split_once("://").map_or(h.as_str(), |(_, rest)| rest);
145            normalize(h.split('/').next().unwrap_or_default())
146        })
147        .filter(|h| !h.is_empty())
148        .unwrap_or_else(|| "gitlab.com".into());
149    let shared: &[(&str, &str)] = match forge {
150        Forge::GitLab => &[
151            ("JOUET_GITLAB_TOKEN", &gitlab_host),
152            ("GITLAB_TOKEN", &gitlab_host),
153            ("GITLAB_ACCESS_TOKEN", &gitlab_host),
154        ],
155        Forge::Forgejo => &[
156            ("JOUET_FORGEJO_TOKEN", "codeberg.org"),
157            ("FORGEJO_TOKEN", "codeberg.org"),
158            ("GITEA_TOKEN", "gitea.com"),
159        ],
160        Forge::GitHub | Forge::Entire => &[],
161    };
162    vars.extend(
163        shared
164            .iter()
165            .filter(|(_, owner)| *owner == host)
166            .map(|(var, _)| (*var).to_string()),
167    );
168    vars
169}
170
171/// Why a host cannot be used, for a host jouet does not know.
172pub fn unknown(host: &str) -> String {
173    format!(
174        "jouet does not know which forge {host} runs; name it in jouet's config: \
175         [forges.\"{host}\"] kind = \"gitlab\" (or \"forgejo\")"
176    )
177}
178
179/// The API root of a GitLab or Forgejo host: the forge's environment
180/// variable, else the config's `api_url`, else the forge's usual path.
181pub(crate) fn api_url(forge: Forge, host: &str) -> String {
182    if let Some(url) = forge
183        .api_url_var()
184        .and_then(|var| std::env::var(var).ok())
185        .filter(|u| !u.is_empty())
186    {
187        return url.trim_end_matches('/').to_string();
188    }
189    if let Some(url) = configured(host).and_then(|c| c.api_url.clone()) {
190        return url.trim_end_matches('/').to_string();
191    }
192    match forge {
193        Forge::GitHub => "https://api.github.com".into(),
194        Forge::GitLab => format!("https://{host}/api/v4"),
195        Forge::Forgejo => format!("https://{host}/api/v1"),
196        Forge::Entire => format!("https://{host}"),
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn known_hosts_need_no_config() {
206        assert_eq!(of_host("github.com"), Some(Forge::GitHub));
207        assert_eq!(of_host("GitLab.com"), Some(Forge::GitLab));
208        assert_eq!(of_host("www.codeberg.org"), Some(Forge::Forgejo));
209        assert_eq!(of_host("git.example.com"), None);
210        assert_eq!(of_host("entire.com"), Some(Forge::Entire));
211        assert_eq!(of_host("aws-us-east-2.entire.io"), Some(Forge::Entire));
212        assert_eq!(normalize("aws-eu-central-1.entire.io"), "entire.com");
213    }
214
215    #[test]
216    fn shared_token_variables_belong_to_one_host() {
217        assert_eq!(
218            token_vars(Forge::Forgejo, "codeberg.org"),
219            ["JOUET_FORGEJO_TOKEN", "FORGEJO_TOKEN"]
220        );
221        assert_eq!(token_vars(Forge::Forgejo, "gitea.com"), ["GITEA_TOKEN"]);
222        assert!(token_vars(Forge::Forgejo, "git.example.com").is_empty());
223    }
224
225    #[test]
226    fn kinds_parse_with_gitea_as_forgejo() {
227        assert_eq!(Forge::parse("GitLab"), Some(Forge::GitLab));
228        assert_eq!(Forge::parse("gitea"), Some(Forge::Forgejo));
229        assert_eq!(Forge::parse("bitbucket"), None);
230    }
231}