Skip to main content

gitpoulpi_hosting/spec/
mod.rs

1//! The per-family descriptor table (plan `more-providers.md`, D1).
2//!
3//! What used to be a dozen free functions each doing
4//! `match family { Github, Gitlab, _ => None }` is one [`FamilySpec`] per
5//! [`ApiFamily`]. The old public functions (`pull_request_web_url`,
6//! `well_known_kind`, `new_pull_request_url`, ...) are one-line wrappers
7//! over [`spec_for`], so no caller changed. A provider slice fills in only
8//! its own `src/<provider>/spec.rs`.
9//!
10//! Pure on purpose: no I/O, and compiled whatever providers are built, so
11//! the URL helpers work in a no-network build.
12
13use gitpoulpi_config::{ApiFamily, Integration, IntegrationKind};
14
15use crate::PullRequestForm;
16
17mod github;
18mod gitlab;
19#[cfg(test)]
20mod tests;
21
22/// A git remote, read by a family's own parser.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct RemoteRef {
25    /// `https://host` (the instance's web root; never the API root).
26    pub web_base: String,
27    /// `group/sub/proj` (GitLab), `owner/name` (GitHub), ...
28    pub project: String,
29}
30
31/// How to get the code of a pull request onto a local branch.
32#[cfg(feature = "hosting")]
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum CheckoutSource {
35    /// The host keeps the head in a special ref of the target repository
36    /// (GitHub, GitLab, Bitbucket Data Center): fetch it, track `local`.
37    HeadRef { remote_ref: String, local: String },
38    /// The head is an ordinary branch, possibly of a fork (Azure DevOps,
39    /// Bitbucket Cloud).
40    Branch {
41        fork_url: Option<String>,
42        branch: String,
43        local: String,
44    },
45}
46
47/// Everything family-specific the app needs to know without a network call.
48pub struct FamilySpec {
49    pub family: ApiFamily,
50    /// Toolbar chip and list tag: `GH` `GL` `AZ` `BB` `JI` `TR` `GT` `LN` `YT` `RM` `GR`.
51    pub tag: &'static str,
52    /// The character before a pull request number: `#` or `!`.
53    pub pr_sigil: char,
54    /// Remote URL to instance root plus project path.
55    pub parse_remote: fn(&str) -> Option<RemoteRef>,
56    /// Does `integration` answer questions about `remote`? Default: same
57    /// hostname. Azure DevOps compares the organization root as well.
58    pub owns_remote: fn(&Integration, &RemoteRef) -> bool,
59    pub pr_web_url: fn(web_root: &str, project: &str, number: u64) -> Option<String>,
60    pub pr_edit_url: fn(pr_web_url: &str) -> String,
61    pub new_pr_url:
62        fn(web_root: &str, project: &str, source: &str, target: Option<&str>) -> Option<String>,
63    pub new_pr_form_url: fn(web_root: &str, form: &PullRequestForm<'_>) -> Option<String>,
64    pub issue_web_url: fn(web_root: &str, project: &str, reference: &str) -> Option<String>,
65    pub new_issue_url: fn(
66        web_root: &str,
67        project: &str,
68        title: &str,
69        body: &str,
70        labels: &[String],
71    ) -> Option<String>,
72    pub branch_url: fn(web_root: &str, project: &str, branch: &str) -> Option<String>,
73    pub commit_url: fn(web_root: &str, project: &str, sha: &str) -> Option<String>,
74    #[cfg(feature = "hosting")]
75    pub checkout: fn(&crate::model::PullRequestSummary) -> CheckoutSource,
76    /// The page that mints a token with the right scopes.
77    pub token_page: fn(&Integration) -> Option<String>,
78    /// The kind a lowercased web host identifies with no configuration.
79    pub well_known: fn(host: &str) -> Option<IntegrationKind>,
80}
81
82impl FamilySpec {
83    /// A spec with nothing filled in: every URL is `None`, remotes parse
84    /// and match by hostname, a pull request is fetched by branch.
85    pub const fn none(family: ApiFamily, tag: &'static str, pr_sigil: char) -> Self {
86        Self {
87            family,
88            tag,
89            pr_sigil,
90            parse_remote: default_parse_remote,
91            owns_remote: default_owns_remote,
92            pr_web_url: |_, _, _| None,
93            pr_edit_url: |url| url.to_string(),
94            new_pr_url: |_, _, _, _| None,
95            new_pr_form_url: |_, _| None,
96            issue_web_url: |_, _, _| None,
97            new_issue_url: |_, _, _, _, _| None,
98            branch_url: |_, _, _| None,
99            commit_url: |_, _, _| None,
100            #[cfg(feature = "hosting")]
101            checkout: default_checkout,
102            token_page: token_page_from_help,
103            well_known: |_| None,
104        }
105    }
106}
107
108/// The spec of `family`. Families whose provider is not built get the
109/// inert one, exactly as a family with no client yet.
110pub fn spec_for(family: ApiFamily) -> &'static FamilySpec {
111    match family {
112        ApiFamily::Github => &github::SPEC,
113        ApiFamily::Gitlab => &gitlab::SPEC,
114        #[cfg(feature = "azure-devops")]
115        ApiFamily::AzureDevops => &crate::azure_devops::spec::SPEC,
116        #[cfg(feature = "bitbucket")]
117        ApiFamily::Bitbucket => &crate::bitbucket::spec::SPEC,
118        #[cfg(feature = "jira")]
119        ApiFamily::Jira => &crate::jira::spec::SPEC,
120        #[cfg(feature = "trello")]
121        ApiFamily::Trello => &crate::trello::spec::SPEC,
122        #[cfg(feature = "gitea")]
123        ApiFamily::Gitea => &crate::gitea::spec::SPEC,
124        #[cfg(feature = "linear")]
125        ApiFamily::Linear => &crate::linear::spec::SPEC,
126        #[cfg(feature = "youtrack")]
127        ApiFamily::YouTrack => &crate::youtrack::spec::SPEC,
128        #[cfg(feature = "redmine")]
129        ApiFamily::Redmine => &crate::redmine::spec::SPEC,
130        #[cfg(feature = "gerrit")]
131        ApiFamily::Gerrit => &crate::gerrit::spec::SPEC,
132        #[cfg(feature = "local-issues")]
133        ApiFamily::LocalMarkdown => &crate::local_markdown::spec::SPEC,
134        #[allow(unreachable_patterns)]
135        other => inert(other),
136    }
137}
138
139/// The spec of a family whose provider module is compiled out.
140#[allow(dead_code)]
141fn inert(family: ApiFamily) -> &'static FamilySpec {
142    static AZ: FamilySpec = FamilySpec::none(ApiFamily::AzureDevops, "AZ", '!');
143    static BB: FamilySpec = FamilySpec::none(ApiFamily::Bitbucket, "BB", '#');
144    static JI: FamilySpec = FamilySpec::none(ApiFamily::Jira, "JI", '#');
145    static TR: FamilySpec = FamilySpec::none(ApiFamily::Trello, "TR", '#');
146    static GT: FamilySpec = FamilySpec::none(ApiFamily::Gitea, "GT", '#');
147    static LN: FamilySpec = FamilySpec::none(ApiFamily::Linear, "LN", '#');
148    static YT: FamilySpec = FamilySpec::none(ApiFamily::YouTrack, "YT", '#');
149    static RM: FamilySpec = FamilySpec::none(ApiFamily::Redmine, "RM", '#');
150    static GR: FamilySpec = FamilySpec::none(ApiFamily::Gerrit, "GR", '#');
151    static MD: FamilySpec = FamilySpec::none(ApiFamily::LocalMarkdown, "MD", '#');
152    match family {
153        ApiFamily::LocalMarkdown => &MD,
154        ApiFamily::AzureDevops => &AZ,
155        ApiFamily::Jira => &JI,
156        ApiFamily::Trello => &TR,
157        ApiFamily::Gitea => &GT,
158        ApiFamily::Linear => &LN,
159        ApiFamily::YouTrack => &YT,
160        ApiFamily::Redmine => &RM,
161        ApiFamily::Gerrit => &GR,
162        _ => &BB,
163    }
164}
165
166/// `remote_web_base`, as a [`RemoteRef`].
167pub fn default_parse_remote(remote_url: &str) -> Option<RemoteRef> {
168    let (web_base, project) = crate::remote_web_base(remote_url)?;
169    Some(RemoteRef { web_base, project })
170}
171
172/// Same hostname (port, `www.` and an `api.` prefix on a public host
173/// ignored).
174pub fn default_owns_remote(integration: &Integration, remote: &RemoteRef) -> bool {
175    integration_hostname(integration) == hostname(&remote.web_base).trim_start_matches("www.")
176}
177
178#[cfg(feature = "hosting")]
179fn default_checkout(pr: &crate::model::PullRequestSummary) -> CheckoutSource {
180    CheckoutSource::Branch {
181        fork_url: None,
182        branch: pr.source_branch.clone(),
183        local: format!("pr/{}", pr.number),
184    }
185}
186
187/// `host` of a web base (`https://host`), lowercased, port removed.
188pub(crate) fn hostname(web_base: &str) -> String {
189    let rest = web_base
190        .split_once("://")
191        .map(|(_, r)| r)
192        .unwrap_or(web_base);
193    let authority = rest.split('/').next().unwrap_or("");
194    let authority = authority
195        .rsplit_once('@')
196        .map(|(_, h)| h)
197        .unwrap_or(authority);
198    let host = match authority.rsplit_once(':') {
199        // Not an IPv6 literal's inner colon.
200        Some((h, port)) if port.chars().all(|c| c.is_ascii_digit()) => h,
201        _ => authority,
202    };
203    host.trim().to_ascii_lowercase()
204}
205
206pub(crate) fn integration_hostname(integration: &Integration) -> String {
207    let url = if integration.url.trim().is_empty() {
208        integration.kind.public_url().unwrap_or("")
209    } else {
210        integration.url.as_str()
211    };
212    // `api.github.com` style URLs identify the same instance as the web host.
213    let host = hostname(url);
214    host.strip_prefix("api.")
215        .filter(|_| integration.kind.public_url().is_some())
216        .map(str::to_string)
217        .unwrap_or(host)
218        .trim_start_matches("www.")
219        .to_string()
220}
221
222/// The instance's web root: the configured URL, or the kind's fixed public
223/// host when none is set.
224pub fn web_base(integration: &Integration) -> Option<String> {
225    let url = integration.url.trim().trim_end_matches('/');
226    if !url.is_empty() {
227        return Some(url.to_string());
228    }
229    integration.kind.public_url().map(str::to_string)
230}
231
232/// The token page, as the profile's kind defines it (S1's `token_link_url`).
233pub(crate) fn token_page_from_help(integration: &Integration) -> Option<String> {
234    let base = web_base(integration)?;
235    integration.token_link_url(&base)
236}