Skip to main content

gitpoulpi_config/
integration.rs

1//! `[[integrations]]`: one configured hosting / issue-tracker profile.
2//!
3//! **This shape is a contract**, consumed by `gitpoulpi-hosting` and the
4//! frontends. `token_ref` is a *key into `gitpoulpi-secrets`*, never the
5//! token: a personal access token in `config.toml` would be a plaintext
6//! credential in a file people paste into bug reports.
7//!
8//! ```toml
9//! [[integrations]]
10//! id = "corp"
11//! kind = "gitlab_self_managed"
12//! url = "https://gitlab.example.com"
13//! token_ref = "integration:corp"
14//! ```
15
16use serde::{Deserialize, Serialize};
17
18/// Which product a profile talks to. Spellings are `snake_case` and pinned
19/// by tests: they are written to disk.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum IntegrationKind {
23    #[default]
24    Github,
25    GithubEnterprise,
26    Gitlab,
27    GitlabSelfManaged,
28    Bitbucket,
29    BitbucketDataCenter,
30    AzureDevops,
31    AzureDevopsServer,
32    JiraCloud,
33    JiraDataCenter,
34    Trello,
35    Gitea,
36    Forgejo,
37    Linear,
38    /// YouTrack Cloud and Server (same REST API): `url` is the instance.
39    Youtrack,
40    /// Redmine (issues only): `url` is the instance, the token is the REST API key.
41    Redmine,
42    /// Gerrit Code Review (review only): HTTP basic, the user name in
43    /// [`Integration::account`] and the HTTP password as the token.
44    Gerrit,
45    /// A folder of Markdown notes (an Obsidian vault subfolder, `docs/issues`):
46    /// no token, no network. `url` holds the folder.
47    LocalMarkdown,
48}
49
50/// The wire protocol a kind speaks; what a client is chosen by.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
52pub enum ApiFamily {
53    Github,
54    Gitlab,
55    Bitbucket,
56    AzureDevops,
57    Jira,
58    Trello,
59    Gitea,
60    Linear,
61    YouTrack,
62    Redmine,
63    Gerrit,
64    LocalMarkdown,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum IntegrationCategory {
69    Hosting,
70    IssueTracker,
71}
72
73/// The non-secret identity a kind needs besides its token
74/// ([`Integration::account`]); decides the form's label and validation.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum AccountField {
77    /// The Atlassian account email (Jira Cloud, Bitbucket Cloud).
78    Email,
79    /// The Trello API key.
80    ApiKey,
81    /// The user name of an HTTP-basic profile (Gerrit).
82    Username,
83}
84
85/// What a kind can do, and whether GitPoulpi does it yet.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Capabilities {
88    pub repos: bool,
89    pub pull_requests: bool,
90    pub issues: bool,
91    pub ssh_keys: bool,
92    /// Always false: personal-token integrations only, no OAuth flow. The
93    /// field stays for config compatibility.
94    pub oauth: bool,
95    /// The user must type a host (self-managed / data-center products).
96    pub needs_host: bool,
97    /// A client exists: the kind is in [`IntegrationKind::IMPLEMENTED`].
98    pub implemented: bool,
99    /// The extra non-secret identity the profile asks for, if any.
100    pub account: Option<AccountField>,
101    /// The profile is scoped to an organization (Azure DevOps).
102    pub org: bool,
103    /// `url` is a folder on this machine: no token, no host, no network
104    /// (the local Markdown issue source).
105    pub local_folder: bool,
106}
107
108/// Where the user mints a token.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum TokenLink {
111    /// A path appended to the instance's web root.
112    Path(&'static str),
113    /// A fixed page on another host (Atlassian's API-token page).
114    Absolute(&'static str),
115    /// Trello's authorize page: built from the API key, so there is no link
116    /// until [`Integration::account`] is set.
117    Trello,
118}
119
120/// How to help the user mint a token: the scopes to tick and the page that
121/// pre-fills them.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct TokenHelp {
124    pub scopes: &'static [&'static str],
125    pub link: TokenLink,
126}
127
128impl IntegrationKind {
129    pub const ALL: &'static [IntegrationKind] = &[
130        IntegrationKind::Github,
131        IntegrationKind::GithubEnterprise,
132        IntegrationKind::Gitlab,
133        IntegrationKind::GitlabSelfManaged,
134        IntegrationKind::Bitbucket,
135        IntegrationKind::BitbucketDataCenter,
136        IntegrationKind::AzureDevops,
137        IntegrationKind::AzureDevopsServer,
138        IntegrationKind::Gitea,
139        IntegrationKind::Forgejo,
140        IntegrationKind::Gerrit,
141        IntegrationKind::JiraCloud,
142        IntegrationKind::JiraDataCenter,
143        IntegrationKind::Trello,
144        IntegrationKind::Linear,
145        IntegrationKind::Youtrack,
146        IntegrationKind::Redmine,
147        IntegrationKind::LocalMarkdown,
148    ];
149
150    /// The kinds a client exists for (what a picker should offer today).
151    pub const IMPLEMENTED: &'static [IntegrationKind] = &[
152        IntegrationKind::Github,
153        IntegrationKind::GithubEnterprise,
154        IntegrationKind::Gitlab,
155        IntegrationKind::GitlabSelfManaged,
156        IntegrationKind::Bitbucket,
157        IntegrationKind::BitbucketDataCenter,
158        IntegrationKind::AzureDevops,
159        IntegrationKind::AzureDevopsServer,
160        IntegrationKind::Gitea,
161        IntegrationKind::Forgejo,
162        IntegrationKind::Gerrit,
163        IntegrationKind::JiraCloud,
164        IntegrationKind::JiraDataCenter,
165        IntegrationKind::Trello,
166        IntegrationKind::Linear,
167        IntegrationKind::Youtrack,
168        IntegrationKind::Redmine,
169        IntegrationKind::LocalMarkdown,
170    ];
171
172    /// The on-disk spelling.
173    pub fn as_str(self) -> &'static str {
174        match self {
175            IntegrationKind::Github => "github",
176            IntegrationKind::GithubEnterprise => "github_enterprise",
177            IntegrationKind::Gitlab => "gitlab",
178            IntegrationKind::GitlabSelfManaged => "gitlab_self_managed",
179            IntegrationKind::Bitbucket => "bitbucket",
180            IntegrationKind::BitbucketDataCenter => "bitbucket_data_center",
181            IntegrationKind::AzureDevops => "azure_devops",
182            IntegrationKind::AzureDevopsServer => "azure_devops_server",
183            IntegrationKind::JiraCloud => "jira_cloud",
184            IntegrationKind::JiraDataCenter => "jira_data_center",
185            IntegrationKind::Trello => "trello",
186            IntegrationKind::Gitea => "gitea",
187            IntegrationKind::Forgejo => "forgejo",
188            IntegrationKind::Linear => "linear",
189            IntegrationKind::Youtrack => "youtrack",
190            IntegrationKind::Redmine => "redmine",
191            IntegrationKind::Gerrit => "gerrit",
192            IntegrationKind::LocalMarkdown => "local_markdown",
193        }
194    }
195
196    /// Human-readable name.
197    pub fn label(self) -> &'static str {
198        match self {
199            IntegrationKind::Github => "GitHub",
200            IntegrationKind::GithubEnterprise => "GitHub Enterprise",
201            IntegrationKind::Gitlab => "GitLab",
202            IntegrationKind::GitlabSelfManaged => "GitLab Self-Managed",
203            IntegrationKind::Bitbucket => "Bitbucket",
204            IntegrationKind::BitbucketDataCenter => "Bitbucket Data Center",
205            IntegrationKind::AzureDevops => "Azure DevOps",
206            IntegrationKind::AzureDevopsServer => "Azure DevOps Server",
207            IntegrationKind::JiraCloud => "Jira Cloud",
208            IntegrationKind::JiraDataCenter => "Jira Data Center",
209            IntegrationKind::Trello => "Trello",
210            IntegrationKind::Gitea => "Gitea",
211            IntegrationKind::Forgejo => "Forgejo",
212            IntegrationKind::Linear => "Linear",
213            IntegrationKind::Youtrack => "YouTrack",
214            IntegrationKind::Redmine => "Redmine",
215            IntegrationKind::Gerrit => "Gerrit",
216            IntegrationKind::LocalMarkdown => "Local Markdown",
217        }
218    }
219
220    /// The fixed public host, for kinds that have exactly one.
221    pub fn public_url(self) -> Option<&'static str> {
222        match self {
223            IntegrationKind::Github => Some("https://github.com"),
224            IntegrationKind::Gitlab => Some("https://gitlab.com"),
225            IntegrationKind::Bitbucket => Some("https://bitbucket.org"),
226            IntegrationKind::AzureDevops => Some("https://dev.azure.com"),
227            IntegrationKind::Trello => Some("https://trello.com"),
228            IntegrationKind::Linear => Some("https://linear.app"),
229            IntegrationKind::GithubEnterprise
230            | IntegrationKind::GitlabSelfManaged
231            | IntegrationKind::BitbucketDataCenter
232            | IntegrationKind::AzureDevopsServer
233            | IntegrationKind::JiraCloud
234            | IntegrationKind::JiraDataCenter
235            | IntegrationKind::Gitea
236            | IntegrationKind::Forgejo
237            | IntegrationKind::Youtrack
238            | IntegrationKind::Redmine
239            | IntegrationKind::Gerrit
240            | IntegrationKind::LocalMarkdown => None,
241        }
242    }
243
244    /// The host prefilled (and editable) for kinds that have a well-known
245    /// public instance but are not tied to it: Codeberg for Forgejo.
246    pub fn default_url(self) -> Option<&'static str> {
247        match self {
248            IntegrationKind::Forgejo => Some("https://codeberg.org"),
249            _ => self.public_url(),
250        }
251    }
252
253    pub fn family(self) -> ApiFamily {
254        match self {
255            IntegrationKind::Github | IntegrationKind::GithubEnterprise => ApiFamily::Github,
256            IntegrationKind::Gitlab | IntegrationKind::GitlabSelfManaged => ApiFamily::Gitlab,
257            IntegrationKind::Bitbucket | IntegrationKind::BitbucketDataCenter => {
258                ApiFamily::Bitbucket
259            }
260            IntegrationKind::AzureDevops | IntegrationKind::AzureDevopsServer => {
261                ApiFamily::AzureDevops
262            }
263            IntegrationKind::JiraCloud | IntegrationKind::JiraDataCenter => ApiFamily::Jira,
264            IntegrationKind::Trello => ApiFamily::Trello,
265            IntegrationKind::Gitea | IntegrationKind::Forgejo => ApiFamily::Gitea,
266            IntegrationKind::Linear => ApiFamily::Linear,
267            IntegrationKind::Youtrack => ApiFamily::YouTrack,
268            IntegrationKind::Redmine => ApiFamily::Redmine,
269            IntegrationKind::Gerrit => ApiFamily::Gerrit,
270            IntegrationKind::LocalMarkdown => ApiFamily::LocalMarkdown,
271        }
272    }
273
274    pub fn category(self) -> IntegrationCategory {
275        match self.family() {
276            ApiFamily::Jira
277            | ApiFamily::Trello
278            | ApiFamily::Linear
279            | ApiFamily::YouTrack
280            | ApiFamily::Redmine
281            | ApiFamily::LocalMarkdown => IntegrationCategory::IssueTracker,
282            _ => IntegrationCategory::Hosting,
283        }
284    }
285
286    pub fn capabilities(self) -> Capabilities {
287        let family = self.family();
288        let hosting = self.category() == IntegrationCategory::Hosting;
289        Capabilities {
290            repos: hosting,
291            pull_requests: hosting,
292            // Bitbucket retired its issue tracker (2026-08-20): link Jira.
293            issues: !matches!(family, ApiFamily::Bitbucket | ApiFamily::Gerrit),
294            // Account SSH keys: GitHub, GitLab, Gitea/Forgejo and Bitbucket Cloud.
295            ssh_keys: matches!(
296                self,
297                IntegrationKind::Github
298                    | IntegrationKind::GithubEnterprise
299                    | IntegrationKind::Gitlab
300                    | IntegrationKind::GitlabSelfManaged
301                    | IntegrationKind::Bitbucket
302                    | IntegrationKind::Gitea
303                    | IntegrationKind::Forgejo
304            ),
305            oauth: false,
306            needs_host: self.public_url().is_none() && self != IntegrationKind::LocalMarkdown,
307            implemented: Self::IMPLEMENTED.contains(&self),
308            account: match self {
309                IntegrationKind::JiraCloud | IntegrationKind::Bitbucket => {
310                    Some(AccountField::Email)
311                }
312                IntegrationKind::Trello => Some(AccountField::ApiKey),
313                IntegrationKind::Gerrit => Some(AccountField::Username),
314                _ => None,
315            },
316            org: self == IntegrationKind::AzureDevops,
317            local_folder: self == IntegrationKind::LocalMarkdown,
318        }
319    }
320
321    /// How to mint a token for this kind.
322    pub fn token_help(self) -> Option<TokenHelp> {
323        if self == IntegrationKind::LocalMarkdown {
324            return None;
325        }
326        const ATLASSIAN: TokenLink =
327            TokenLink::Absolute("https://id.atlassian.com/manage-profile/security/api-tokens");
328        Some(match self {
329            IntegrationKind::Github | IntegrationKind::GithubEnterprise => TokenHelp {
330                scopes: &["repo", "read:user", "admin:public_key"],
331                link: TokenLink::Path(
332                    "/settings/tokens/new?description=GitPoulpi&scopes=repo,read:user,admin:public_key",
333                ),
334            },
335            IntegrationKind::Gitlab | IntegrationKind::GitlabSelfManaged => TokenHelp {
336                scopes: &["api", "read_user"],
337                link: TokenLink::Path(
338                    "/-/user_settings/personal_access_tokens?name=GitPoulpi&scopes=api,read_user",
339                ),
340            },
341            IntegrationKind::AzureDevops | IntegrationKind::AzureDevopsServer => TokenHelp {
342                scopes: &["Code (Read & write)", "Work Items (Read & write)"],
343                link: TokenLink::Path("/_usersSettings/tokens"),
344            },
345            // Scope names verified against Atlassian's API-token scope page
346            // (2026-10-08).
347            IntegrationKind::Bitbucket => TokenHelp {
348                scopes: &[
349                    "read:user:bitbucket",
350                    "read:workspace:bitbucket",
351                    "read:repository:bitbucket",
352                    "write:repository:bitbucket",
353                    "read:pullrequest:bitbucket",
354                    "write:pullrequest:bitbucket",
355                    "read:ssh-key:bitbucket",
356                    "write:ssh-key:bitbucket",
357                    "delete:ssh-key:bitbucket",
358                ],
359                link: ATLASSIAN,
360            },
361            IntegrationKind::BitbucketDataCenter => TokenHelp {
362                scopes: &["Repository (Read & write)", "Projects (Read)"],
363                link: TokenLink::Path("/plugins/servlet/access-tokens/manage"),
364            },
365            IntegrationKind::JiraCloud => TokenHelp {
366                scopes: &["classic API token"],
367                link: ATLASSIAN,
368            },
369            IntegrationKind::JiraDataCenter => TokenHelp {
370                scopes: &["personal access token"],
371                link: TokenLink::Path(
372                    "/secure/ViewProfile.jspa?selectedTab=com.atlassian.pats.pats-plugin:jira-user-personal-access-tokens",
373                ),
374            },
375            IntegrationKind::Trello => TokenHelp {
376                scopes: &["read", "write"],
377                link: TokenLink::Trello,
378            },
379            // The token page pre-fills nothing (Gitea has no scope query
380            // string); the scopes are the ones to tick.
381            IntegrationKind::Gitea | IntegrationKind::Forgejo => TokenHelp {
382                scopes: &[
383                    "read:user",
384                    "write:repository",
385                    "write:issue",
386                    "write:user",
387                ],
388                link: TokenLink::Path("/user/settings/applications"),
389            },
390            // Linear: Settings > Account > Security & access > Personal API keys.
391            IntegrationKind::Linear => TokenHelp {
392                scopes: &["read", "write", "issues:create"],
393                link: TokenLink::Absolute("https://linear.app/settings/account/security"),
394            },
395            // YouTrack: profile > Account Security > New token (permanent token).
396            IntegrationKind::Youtrack => TokenHelp {
397                scopes: &["YouTrack"],
398                link: TokenLink::Path("/users/me?tab=account-security"),
399            },
400            // Redmine: My account > API access key (the REST API must be on).
401            IntegrationKind::Redmine => TokenHelp {
402                scopes: &["REST API key"],
403                link: TokenLink::Path("/my/account"),
404            },
405            // Gerrit: Settings > HTTP Credentials > Generate new password.
406            IntegrationKind::Gerrit => TokenHelp {
407                scopes: &["HTTP password"],
408                link: TokenLink::Path("/settings/#HTTPCredentials"),
409            },
410            IntegrationKind::LocalMarkdown => return None,
411        })
412    }
413}
414
415#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
416#[serde(rename_all = "snake_case")]
417pub enum AuthMethod {
418    #[default]
419    Pat,
420    Oauth,
421}
422
423/// Who the profile's token belongs to, cached after a successful check.
424#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
425pub struct ConnectedUser {
426    pub login: String,
427    #[serde(default, skip_serializing_if = "String::is_empty")]
428    pub name: String,
429    #[serde(default, skip_serializing_if = "String::is_empty")]
430    pub id: String,
431}
432
433#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(rename_all = "snake_case")]
435pub enum SshMode {
436    #[default]
437    Default,
438    Generated,
439    Custom,
440}
441
442/// Per-profile SSH key choice.
443#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
444pub struct IntegrationSsh {
445    #[serde(default)]
446    pub mode: SshMode,
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub private_key_path: Option<String>,
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub public_key_path: Option<String>,
451    #[serde(default, skip_serializing_if = "Option::is_none")]
452    pub title: Option<String>,
453    /// The provider-side key id, so it can be deleted there later.
454    #[serde(default, skip_serializing_if = "Option::is_none")]
455    pub remote_key_id: Option<String>,
456}
457
458fn default_true() -> bool {
459    true
460}
461
462fn is_true(v: &bool) -> bool {
463    *v
464}
465
466/// One configured profile. `token_ref` is a key into `gitpoulpi-secrets`,
467/// never a token.
468#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
469pub struct Integration {
470    pub id: String,
471    pub kind: IntegrationKind,
472    pub url: String,
473    pub token_ref: String,
474    /// Display name; empty means "use the id".
475    #[serde(default, skip_serializing_if = "String::is_empty")]
476    pub name: String,
477    #[serde(default)]
478    pub auth: AuthMethod,
479    /// The non-secret identity next to the token: the Atlassian email
480    /// (`jira_cloud`, `bitbucket`) or the Trello API key. Empty otherwise.
481    /// The token stays the only secret.
482    #[serde(default, skip_serializing_if = "String::is_empty")]
483    pub account: String,
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub user: Option<ConnectedUser>,
486    #[serde(default, skip_serializing_if = "Option::is_none")]
487    pub ssh: Option<IntegrationSsh>,
488    #[serde(default = "default_true", skip_serializing_if = "is_true")]
489    pub enabled: bool,
490    /// The settings of a `local_markdown` profile; absent means the defaults.
491    #[serde(default, skip_serializing_if = "Option::is_none")]
492    pub local: Option<LocalMarkdownSettings>,
493    /// `[integrations.radar]`: the account-wide lists the Radar and
494    /// `hosting radar` fetch for this profile. Absent means all off.
495    #[serde(default, skip_serializing_if = "Option::is_none")]
496    pub radar: Option<IntegrationRadar>,
497    /// The text format a Redmine server is configured with: what its
498    /// comments are read as and what is written back. Other kinds ignore it.
499    #[serde(default, skip_serializing_if = "RedmineMarkup::is_default")]
500    pub markup: RedmineMarkup,
501    /// "Use this account for git over HTTPS on its host": every repository
502    /// whose https remote is on this profile's host authenticates its git
503    /// transfers with this profile's token, unless the repository has its own
504    /// `repo-auth` HTTPS setting. Off by default; see [`git_https_check`].
505    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
506    pub git_https: bool,
507}
508
509/// How a Redmine server formats text (Administration > Settings >
510/// General > Text formatting). The API does not say, so the profile does.
511#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
512#[serde(rename_all = "snake_case")]
513pub enum RedmineMarkup {
514    /// Redmine's historical default.
515    #[default]
516    Textile,
517    Markdown,
518}
519
520impl RedmineMarkup {
521    pub const ALL: [RedmineMarkup; 2] = [Self::Textile, Self::Markdown];
522
523    pub fn as_str(self) -> &'static str {
524        match self {
525            Self::Textile => "textile",
526            Self::Markdown => "markdown",
527        }
528    }
529
530    pub fn is_default(&self) -> bool {
531        *self == Self::default()
532    }
533
534    /// The other one (what a cycling control does).
535    pub fn toggled(self) -> Self {
536        match self {
537            Self::Textile => Self::Markdown,
538            Self::Markdown => Self::Textile,
539        }
540    }
541}
542
543/// What to do with a request whose repository is not cloned.
544#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
545#[serde(rename_all = "snake_case")]
546pub enum RemoteReviewMode {
547    /// Ask each time.
548    #[default]
549    Ask,
550    /// Clone the repository, then review it there.
551    Clone,
552    /// Review through the host's API, without a clone.
553    Api,
554}
555
556impl RemoteReviewMode {
557    pub const ALL: [RemoteReviewMode; 3] = [Self::Ask, Self::Clone, Self::Api];
558
559    pub fn as_str(self) -> &'static str {
560        match self {
561            Self::Ask => "ask",
562            Self::Clone => "clone",
563            Self::Api => "api",
564        }
565    }
566
567    /// `ask`, `clone` or `api`, any case.
568    pub fn parse(text: &str) -> Option<Self> {
569        Self::ALL
570            .into_iter()
571            .find(|m| m.as_str().eq_ignore_ascii_case(text.trim()))
572    }
573}
574
575/// `[integrations.radar]` of a code-host profile: which account-wide lists
576/// (not tied to a cloned repository) the Radar shows, all off by default.
577///
578/// ```toml
579/// [integrations.radar]
580/// review_requests = true      # requests waiting for my review, every repository
581/// open_requests = false       # every open request of my namespaces
582/// include_drafts = false      # account rows: drafts too
583/// assigned_issues = true      # open issues assigned to me, every repository
584/// namespaces = ["acme"]       # empty = my own namespace plus every membership
585/// review_mode = "ask"         # ask | clone | api
586/// ```
587#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
588pub struct IntegrationRadar {
589    #[serde(default)]
590    pub review_requests: bool,
591    #[serde(default)]
592    pub open_requests: bool,
593    #[serde(default)]
594    pub include_drafts: bool,
595    #[serde(default)]
596    pub assigned_issues: bool,
597    /// Orgs / groups / workspaces / Azure projects / Gerrit project
598    /// prefixes; empty means the account's own namespace plus every one it
599    /// is a member of.
600    ///
601    /// One entry per line of the Settings field. An old file may hold one
602    /// comma-separated string instead of a list; both load.
603    #[serde(
604        default,
605        deserialize_with = "de_namespaces",
606        skip_serializing_if = "Vec::is_empty"
607    )]
608    pub namespaces: Vec<String>,
609    /// Read each `namespaces` entry as a regular expression matched against
610    /// the full repository path, instead of a path prefix.
611    #[serde(default, skip_serializing_if = "is_false")]
612    pub namespaces_regex: bool,
613    #[serde(default)]
614    pub review_mode: RemoteReviewMode,
615}
616
617fn is_false(v: &bool) -> bool {
618    !*v
619}
620
621/// Namespace entries: trimmed, empty ones dropped, repeats dropped.
622pub fn clean_namespaces<I, S>(entries: I) -> Vec<String>
623where
624    I: IntoIterator<Item = S>,
625    S: AsRef<str>,
626{
627    let mut out: Vec<String> = Vec::new();
628    for entry in entries {
629        let entry = entry.as_ref().trim();
630        if !entry.is_empty() && !out.iter().any(|o| o == entry) {
631            out.push(entry.to_string());
632        }
633    }
634    out
635}
636
637/// The text of the Namespaces field: one entry per line. In plain mode the
638/// old single-line form (`acme, tools`) is still read, commas separate
639/// entries; in regex mode a comma belongs to the expression.
640pub fn parse_namespace_text(text: &str, regex: bool) -> Vec<String> {
641    if regex {
642        clean_namespaces(text.lines())
643    } else {
644        clean_namespaces(text.split(['\n', ',']))
645    }
646}
647
648fn de_namespaces<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
649where
650    D: serde::Deserializer<'de>,
651{
652    #[derive(Deserialize)]
653    #[serde(untagged)]
654    enum Form {
655        One(String),
656        Many(Vec<String>),
657    }
658    Ok(match Form::deserialize(deserializer)? {
659        Form::One(text) => parse_namespace_text(&text, false),
660        Form::Many(list) => clean_namespaces(list),
661    })
662}
663
664impl IntegrationRadar {
665    /// Whether any account-wide list is on (the drafts switch and the
666    /// namespaces only refine them).
667    pub fn any_list(&self) -> bool {
668        self.review_requests || self.open_requests || self.assigned_issues
669    }
670}
671
672/// `[integrations.local]` of a `local_markdown` profile: how its notes'
673/// `status` values are ordered and which one means closed.
674///
675/// ```toml
676/// [integrations.local]
677/// statuses = ["todo", "doing", "review", "done"]
678/// done_status = "done"
679/// reference_prefix = "LOC"   # shows LOC-12 instead of #12
680/// me = "kai"                 # who "assigned to me" means
681/// ```
682#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
683pub struct LocalMarkdownSettings {
684    /// The board's column order; statuses used by notes but not listed
685    /// follow, in order of appearance. Empty: [`DEFAULT_STATUSES`].
686    #[serde(default, skip_serializing_if = "Vec::is_empty")]
687    pub statuses: Vec<String>,
688    /// The status that closes an issue. Empty: `done`.
689    #[serde(default, skip_serializing_if = "String::is_empty")]
690    pub done_status: String,
691    /// Shown before the number (`LOC-12`); empty: `#12`.
692    #[serde(default, skip_serializing_if = "String::is_empty")]
693    pub reference_prefix: String,
694    /// The login "assigned to me" matches; empty: the connected user, else
695    /// the profile name.
696    #[serde(default, skip_serializing_if = "String::is_empty")]
697    pub me: String,
698}
699
700/// The column order of a local issue folder with no `statuses` configured.
701pub const DEFAULT_STATUSES: [&str; 3] = ["todo", "doing", "done"];
702
703impl LocalMarkdownSettings {
704    /// The configured order, or the default one.
705    pub fn status_order(&self) -> Vec<String> {
706        if self.statuses.is_empty() {
707            DEFAULT_STATUSES.iter().map(|s| s.to_string()).collect()
708        } else {
709            self.statuses.clone()
710        }
711    }
712
713    /// The status that closes an issue.
714    pub fn done(&self) -> &str {
715        let d = self.done_status.trim();
716        if d.is_empty() {
717            "done"
718        } else {
719            d
720        }
721    }
722
723    /// The status a reopened issue returns to: the first one in the order
724    /// that is not the done status.
725    pub fn open_status(&self) -> String {
726        self.status_order()
727            .into_iter()
728            .find(|s| !s.eq_ignore_ascii_case(self.done()))
729            .unwrap_or_else(|| "todo".to_string())
730    }
731}
732
733impl Integration {
734    /// The profile's `[integrations.radar]`, or all-off defaults.
735    pub fn radar_options(&self) -> IntegrationRadar {
736        self.radar.clone().unwrap_or_default()
737    }
738
739    /// The canonical `token_ref` for an id.
740    pub fn token_ref_for(id: &str) -> String {
741        format!("integration:{id}")
742    }
743
744    pub fn new(id: impl Into<String>, kind: IntegrationKind, url: impl Into<String>) -> Self {
745        let id = id.into();
746        let token_ref = Self::token_ref_for(&id);
747        Self {
748            id,
749            kind,
750            url: url.into(),
751            token_ref,
752            name: String::new(),
753            auth: AuthMethod::Pat,
754            account: String::new(),
755            user: None,
756            ssh: None,
757            enabled: true,
758            local: None,
759            radar: None,
760            markup: RedmineMarkup::default(),
761            git_https: false,
762        }
763    }
764
765    /// A fresh id (`gitlab`, `gitlab-2`, ...) not used by `existing`.
766    pub fn new_id<'a>(
767        kind: IntegrationKind,
768        existing: impl IntoIterator<Item = &'a Integration>,
769    ) -> String {
770        let taken: Vec<&str> = existing.into_iter().map(|i| i.id.as_str()).collect();
771        let base = kind.as_str().replace('_', "-");
772        if !taken.contains(&base.as_str()) {
773            return base;
774        }
775        (2..)
776            .map(|n| format!("{base}-{n}"))
777            .find(|c| !taken.contains(&c.as_str()))
778            .expect("infinite range")
779    }
780
781    pub fn display_name(&self) -> &str {
782        if self.name.is_empty() {
783            &self.id
784        } else {
785            &self.name
786        }
787    }
788
789    /// `host[:port]` of `url`, the key credential helpers use.
790    pub fn host(&self) -> Option<String> {
791        host_of(&self.url)
792    }
793
794    /// The API root, derived from `url` (never configured separately).
795    ///
796    /// github.com uses `https://api.github.com`; GitHub Enterprise Server
797    /// uses `<url>/api/v3`; GitLab always `<url>/api/v4`. Other families
798    /// have no client yet and return the bare base URL.
799    pub fn api_base(&self) -> String {
800        let base = self.url.trim_end_matches('/');
801        match self.kind.family() {
802            ApiFamily::Github => {
803                if is_dot_com(base, "github.com") {
804                    "https://api.github.com".to_string()
805                } else {
806                    format!("{base}/api/v3")
807                }
808            }
809            ApiFamily::Gitlab => format!("{base}/api/v4"),
810            ApiFamily::AzureDevops => match self.kind {
811                IntegrationKind::AzureDevops => normalize_azure_url(base),
812                _ => base.to_string(),
813            },
814            ApiFamily::Bitbucket => match self.kind {
815                IntegrationKind::BitbucketDataCenter => format!("{base}/rest/api/1.0"),
816                _ if is_dot_com(base, "bitbucket.org") => {
817                    "https://api.bitbucket.org/2.0".to_string()
818                }
819                _ => format!("{base}/2.0"),
820            },
821            ApiFamily::Jira => match self.kind {
822                IntegrationKind::JiraCloud => format!("{base}/rest/api/3"),
823                _ => format!("{base}/rest/api/2"),
824            },
825            ApiFamily::Trello => {
826                if is_dot_com(base, "trello.com") {
827                    "https://api.trello.com/1".to_string()
828                } else {
829                    format!("{base}/1")
830                }
831            }
832            ApiFamily::Gitea => format!("{base}/api/v1"),
833            // The GraphQL endpoint is `<root>/graphql`.
834            ApiFamily::Linear => {
835                if is_dot_com(base, "linear.app") {
836                    "https://api.linear.app".to_string()
837                } else {
838                    base.to_string()
839                }
840            }
841            ApiFamily::YouTrack => format!("{base}/api"),
842            // The REST resources sit at the root (`/issues.json`).
843            ApiFamily::Redmine => base.to_string(),
844            // Authenticated calls live under `/a/`.
845            ApiFamily::Gerrit => format!("{base}/a"),
846            // A folder: there is no API.
847            ApiFamily::LocalMarkdown => base.to_string(),
848        }
849    }
850
851    /// Jira Cloud creates issues through `/rest/api/2` (plain-text
852    /// description) while reading through `/3`; `None` for other kinds.
853    pub fn api_base_v2(&self) -> Option<String> {
854        (self.kind == IntegrationKind::JiraCloud)
855            .then(|| format!("{}/rest/api/2", self.url.trim_end_matches('/')))
856    }
857
858    /// The Azure DevOps Services organization of a `dev.azure.com/{org}` or
859    /// `{org}.visualstudio.com` URL. `None` for other kinds, Server, or a
860    /// URL without an organization.
861    pub fn azure_org(&self) -> Option<String> {
862        if self.kind != IntegrationKind::AzureDevops {
863            return None;
864        }
865        let normalized = normalize_azure_url(&self.url);
866        let rest = normalized.strip_prefix("https://dev.azure.com/")?;
867        let org = rest.split('/').next().unwrap_or("");
868        (!org.is_empty()).then(|| org.to_string())
869    }
870
871    /// The page that mints this profile's token, given the instance's web
872    /// root (`https://github.com`, ...). `None` when the kind has no flow or
873    /// Trello's key is not typed yet.
874    pub fn token_link_url(&self, web_base: &str) -> Option<String> {
875        let help = self.kind.token_help()?;
876        match help.link {
877            TokenLink::Path(path) => Some(format!("{}{path}", web_base.trim_end_matches('/'))),
878            TokenLink::Absolute(url) => Some(url.to_string()),
879            TokenLink::Trello => {
880                let key = self.account.trim();
881                (!key.is_empty()).then(|| {
882                    format!(
883                        "https://trello.com/1/authorize?expiration=never&name=GitPoulpi&scope=read,write&response_type=token&key={key}"
884                    )
885                })
886            }
887        }
888    }
889
890    /// Applies the legacy-kind migration; see
891    /// [`crate::Config::normalize_integrations`].
892    pub(crate) fn normalize_kind(&mut self) {
893        if self.url.trim().is_empty() {
894            return;
895        }
896        match self.kind {
897            IntegrationKind::Github if !is_dot_com(&self.url, "github.com") => {
898                self.kind = IntegrationKind::GithubEnterprise;
899            }
900            IntegrationKind::Gitlab if !is_dot_com(&self.url, "gitlab.com") => {
901                self.kind = IntegrationKind::GitlabSelfManaged;
902            }
903            _ => {}
904        }
905    }
906}
907
908/// Rewrites `https://{org}.visualstudio.com[/...]` to
909/// `https://dev.azure.com/{org}`; anything else loses only a trailing slash.
910pub fn normalize_azure_url(url: &str) -> String {
911    let trimmed = url.trim().trim_end_matches('/');
912    if let Some(host) = host_of(trimmed) {
913        let lower = host.to_ascii_lowercase();
914        if let Some(org) = lower.strip_suffix(".visualstudio.com") {
915            if !org.is_empty() && !org.contains('.') {
916                return format!("https://dev.azure.com/{org}");
917            }
918        }
919    }
920    trimmed.to_string()
921}
922
923/// Why "use this account for git over HTTPS" cannot be turned on for a profile.
924#[derive(Debug, Clone, PartialEq, Eq)]
925pub enum GitHttpsRefusal {
926    /// An issue tracker or a local folder: no git remote lives there.
927    NotCodeHost,
928    /// The profile's address is not a usable `https://` one (the token is
929    /// never sent over plain http).
930    NotHttps,
931    /// Another profile with the same host already has it on (its id).
932    HostTaken(String),
933}
934
935impl std::fmt::Display for GitHttpsRefusal {
936    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
937        match self {
938            Self::NotCodeHost => f.write_str("only a code host has git remotes"),
939            Self::NotHttps => f.write_str(
940                "the profile's address is not an https:// one: its token is never used for git over plain http",
941            ),
942            Self::HostTaken(id) => write!(
943                f,
944                "the profile `{id}` already is the git over HTTPS account of this host: turn it off first"
945            ),
946        }
947    }
948}
949
950/// The lowercase `host[:port]` of an `https://` URL (userinfo dropped, the
951/// default port `:443` removed), `None` for any other scheme. What a remote's
952/// host is compared with the profile's by.
953pub fn https_authority(url: &str) -> Option<String> {
954    let (scheme, rest) = url.trim().split_once("://")?;
955    if !scheme.eq_ignore_ascii_case("https") {
956        return None;
957    }
958    let authority = rest.split(['/', '?', '#']).next()?;
959    let host = authority.rsplit('@').next()?.to_ascii_lowercase();
960    let host = host.strip_suffix(":443").unwrap_or(&host).to_string();
961    (!host.is_empty()).then_some(host)
962}
963
964impl Integration {
965    /// The `https` authority git remotes of this profile's host carry, `None`
966    /// when the profile is not on an `https://` address.
967    pub fn git_https_authority(&self) -> Option<String> {
968        https_authority(&self.url)
969    }
970}
971
972/// Whether profile `index` may have `git_https` turned on: the host it would
973/// serve (a code host on an `https://` address) when it may, else why not.
974/// Two profiles on one host are never both on: the second is refused here.
975/// (A hand-edited file that has both on is read as "the first in file order",
976/// see [`git_https_profiles`].)
977pub fn git_https_check(list: &[Integration], index: usize) -> Result<String, GitHttpsRefusal> {
978    let profile = &list[index];
979    if profile.kind.category() != IntegrationCategory::Hosting {
980        return Err(GitHttpsRefusal::NotCodeHost);
981    }
982    let host = profile
983        .git_https_authority()
984        .ok_or(GitHttpsRefusal::NotHttps)?;
985    if let Some(other) = list.iter().enumerate().find(|(i, o)| {
986        *i != index && o.git_https && o.git_https_authority().as_deref() == Some(host.as_str())
987    }) {
988        return Err(GitHttpsRefusal::HostTaken(other.1.id.clone()));
989    }
990    Ok(host)
991}
992
993/// The enabled profiles that have `git_https` on and serve `authority`, in
994/// file order. The first one is the one used; more than one only happens in a
995/// hand-edited file.
996pub fn git_https_profiles<'a>(list: &'a [Integration], authority: &str) -> Vec<&'a Integration> {
997    list.iter()
998        .filter(|i| {
999            i.git_https
1000                && i.enabled
1001                && i.kind.category() == IntegrationCategory::Hosting
1002                && i.git_https_authority().as_deref() == Some(authority)
1003        })
1004        .collect()
1005}
1006
1007fn host_of(url: &str) -> Option<String> {
1008    let rest = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
1009    let host = rest.split('/').next().unwrap_or("").trim();
1010    (!host.is_empty()).then(|| host.to_string())
1011}
1012
1013/// Whether `url` is the public `domain` (also `www.` and, for GitHub,
1014/// `api.`), ignoring scheme, case, a trailing slash and any path.
1015fn is_dot_com(url: &str, domain: &str) -> bool {
1016    let Some(host) = host_of(url) else {
1017        return false;
1018    };
1019    let host = host.to_ascii_lowercase();
1020    host == domain || host == format!("www.{domain}") || host == format!("api.{domain}")
1021}
1022
1023#[cfg(test)]
1024mod tests {
1025    use super::*;
1026    use crate::Config;
1027
1028    fn host_profile(id: &str, kind: IntegrationKind, url: &str, on: bool) -> Integration {
1029        let mut i = Integration::new(id, kind, url);
1030        i.git_https = on;
1031        i
1032    }
1033
1034    #[test]
1035    fn git_https_is_off_by_default_and_round_trips() {
1036        let i = Integration::new("a", IntegrationKind::GitlabSelfManaged, "https://g.example");
1037        assert!(!i.git_https);
1038        assert!(!toml::to_string(&i).unwrap().contains("git_https"));
1039        let mut on = i.clone();
1040        on.git_https = true;
1041        let text = toml::to_string(&on).unwrap();
1042        assert!(text.contains("git_https = true"), "{text}");
1043        assert!(toml::from_str::<Integration>(&text).unwrap().git_https);
1044    }
1045
1046    #[test]
1047    fn the_authority_of_an_https_url_is_normalised_and_other_schemes_have_none() {
1048        assert_eq!(
1049            https_authority("https://User@GitLab.Example:443/a/b.git").as_deref(),
1050            Some("gitlab.example")
1051        );
1052        assert_eq!(
1053            https_authority("https://gitlab.example:8443/x").as_deref(),
1054            Some("gitlab.example:8443")
1055        );
1056        assert_eq!(https_authority("http://gitlab.example/x"), None);
1057        assert_eq!(https_authority("git@gitlab.example:a/b.git"), None);
1058        assert_eq!(https_authority("https://"), None);
1059    }
1060
1061    #[test]
1062    fn turning_git_https_on_is_refused_for_the_wrong_kind_address_or_a_taken_host() {
1063        let gl = IntegrationKind::GitlabSelfManaged;
1064        let list = vec![
1065            host_profile("a", gl, "https://g.example", true),
1066            host_profile("b", gl, "https://G.example/base", false),
1067            host_profile("c", gl, "http://plain.example", false),
1068            host_profile("d", IntegrationKind::Redmine, "https://g.example", false),
1069            host_profile("e", gl, "https://other.example", false),
1070        ];
1071        assert_eq!(
1072            git_https_check(&list, 1),
1073            Err(GitHttpsRefusal::HostTaken("a".into()))
1074        );
1075        assert_eq!(git_https_check(&list, 2), Err(GitHttpsRefusal::NotHttps));
1076        assert_eq!(git_https_check(&list, 3), Err(GitHttpsRefusal::NotCodeHost));
1077        assert_eq!(git_https_check(&list, 4).as_deref(), Ok("other.example"));
1078        // The one that has it on is not refused by itself.
1079        assert_eq!(git_https_check(&list, 0).as_deref(), Ok("g.example"));
1080    }
1081
1082    #[test]
1083    fn the_profiles_serving_a_host_are_the_enabled_ones_that_have_it_on_in_file_order() {
1084        let gl = IntegrationKind::GitlabSelfManaged;
1085        let mut off = host_profile("off", gl, "https://g.example", false);
1086        off.enabled = true;
1087        let mut disabled = host_profile("disabled", gl, "https://g.example", true);
1088        disabled.enabled = false;
1089        let list = vec![
1090            off,
1091            disabled,
1092            host_profile("first", gl, "https://g.example", true),
1093            host_profile("second", gl, "https://g.example:443", true),
1094        ];
1095        let ids: Vec<&str> = git_https_profiles(&list, "g.example")
1096            .iter()
1097            .map(|i| i.id.as_str())
1098            .collect();
1099        assert_eq!(ids, ["first", "second"]);
1100        assert!(git_https_profiles(&list, "other.example").is_empty());
1101    }
1102
1103    fn migrated(kind: &str, url: &str) -> IntegrationKind {
1104        let raw = format!(
1105            "[[integrations]]\nid = \"x\"\nkind = \"{kind}\"\nurl = \"{url}\"\ntoken_ref = \"integration:x\"\n"
1106        );
1107        Config::from_toml_str(&raw).unwrap().0.integrations[0].kind
1108    }
1109
1110    #[test]
1111    fn an_integration_carries_a_reference_not_a_token() {
1112        let integration =
1113            Integration::new("my-gitlab", IntegrationKind::Gitlab, "https://g.example");
1114        assert_eq!(integration.token_ref, "integration:my-gitlab");
1115        let raw = toml::to_string(&integration).unwrap();
1116        assert!(raw.contains("token_ref"), "{raw}");
1117        assert!(!raw.contains("token ="), "{raw}");
1118    }
1119
1120    #[test]
1121    fn serde_spellings_are_pinned() {
1122        let expected = [
1123            (IntegrationKind::Github, "github"),
1124            (IntegrationKind::GithubEnterprise, "github_enterprise"),
1125            (IntegrationKind::Gitlab, "gitlab"),
1126            (IntegrationKind::GitlabSelfManaged, "gitlab_self_managed"),
1127            (IntegrationKind::Bitbucket, "bitbucket"),
1128            (
1129                IntegrationKind::BitbucketDataCenter,
1130                "bitbucket_data_center",
1131            ),
1132            (IntegrationKind::AzureDevops, "azure_devops"),
1133            (IntegrationKind::AzureDevopsServer, "azure_devops_server"),
1134            (IntegrationKind::JiraCloud, "jira_cloud"),
1135            (IntegrationKind::JiraDataCenter, "jira_data_center"),
1136            (IntegrationKind::Trello, "trello"),
1137            (IntegrationKind::Gitea, "gitea"),
1138            (IntegrationKind::Forgejo, "forgejo"),
1139            (IntegrationKind::Linear, "linear"),
1140            (IntegrationKind::Youtrack, "youtrack"),
1141            (IntegrationKind::Redmine, "redmine"),
1142            (IntegrationKind::Gerrit, "gerrit"),
1143            (IntegrationKind::LocalMarkdown, "local_markdown"),
1144        ];
1145        assert_eq!(expected.len(), IntegrationKind::ALL.len());
1146        for (kind, spelling) in expected {
1147            assert_eq!(kind.as_str(), spelling);
1148            let raw = toml::to_string(&Integration::new("x", kind, "u")).unwrap();
1149            assert!(raw.contains(&format!("kind = \"{spelling}\"")), "{raw}");
1150        }
1151    }
1152
1153    #[test]
1154    fn old_toml_migrates_and_round_trips_stably() {
1155        let raw = r#"
1156[[integrations]]
1157id = "gh"
1158kind = "github"
1159url = "https://github.com"
1160token_ref = "integration:gh"
1161
1162[[integrations]]
1163id = "ghe"
1164kind = "github"
1165url = "https://ghe.example.com"
1166token_ref = "integration:ghe"
1167
1168[[integrations]]
1169id = "gl"
1170kind = "gitlab"
1171url = "https://gitlab.com/"
1172token_ref = "integration:gl"
1173
1174[[integrations]]
1175id = "corp"
1176kind = "gitlab"
1177url = "https://gitlab.example.com"
1178token_ref = "integration:corp"
1179"#;
1180        let (config, _) = Config::from_toml_str(raw).unwrap();
1181        let kinds: Vec<_> = config.integrations.iter().map(|i| i.kind).collect();
1182        assert_eq!(
1183            kinds,
1184            [
1185                IntegrationKind::Github,
1186                IntegrationKind::GithubEnterprise,
1187                IntegrationKind::Gitlab,
1188                IntegrationKind::GitlabSelfManaged
1189            ]
1190        );
1191        assert!(config.integrations.iter().all(|i| i.enabled));
1192        // Stable: write it out and read it back, nothing moves.
1193        let written = toml::to_string_pretty(&config).unwrap();
1194        let (again, _) = Config::from_toml_str(&written).unwrap();
1195        assert_eq!(again.integrations, config.integrations);
1196        let mut twice = again.clone();
1197        twice.normalize_integrations();
1198        assert_eq!(twice.integrations, config.integrations);
1199    }
1200
1201    #[test]
1202    fn migration_ignores_www_scheme_case_and_trailing_slash() {
1203        assert_eq!(
1204            migrated("github", "https://www.github.com"),
1205            IntegrationKind::Github
1206        );
1207        assert_eq!(
1208            migrated("github", "HTTPS://GitHub.com/"),
1209            IntegrationKind::Github
1210        );
1211        assert_eq!(
1212            migrated("gitlab", "https://www.gitlab.com/"),
1213            IntegrationKind::Gitlab
1214        );
1215        assert_eq!(
1216            migrated("github", "https://github.example.com/"),
1217            IntegrationKind::GithubEnterprise
1218        );
1219        // Never demoted, never touched when already specific.
1220        assert_eq!(
1221            migrated("github_enterprise", "https://github.com"),
1222            IntegrationKind::GithubEnterprise
1223        );
1224        assert_eq!(migrated("trello", "https://x"), IntegrationKind::Trello);
1225    }
1226
1227    #[test]
1228    fn all_and_implemented_list_hosting_before_issue_trackers() {
1229        for list in [IntegrationKind::ALL, IntegrationKind::IMPLEMENTED] {
1230            let first_tracker = list
1231                .iter()
1232                .position(|k| k.category() == IntegrationCategory::IssueTracker)
1233                .unwrap();
1234            assert!(list[first_tracker..]
1235                .iter()
1236                .all(|k| k.category() == IntegrationCategory::IssueTracker));
1237        }
1238    }
1239
1240    #[test]
1241    fn capabilities_and_implemented_agree() {
1242        for kind in IntegrationKind::ALL {
1243            let implemented = matches!(
1244                kind,
1245                IntegrationKind::Github
1246                    | IntegrationKind::GithubEnterprise
1247                    | IntegrationKind::Gitlab
1248                    | IntegrationKind::GitlabSelfManaged
1249                    | IntegrationKind::JiraCloud
1250                    | IntegrationKind::JiraDataCenter
1251                    | IntegrationKind::Trello
1252                    | IntegrationKind::Bitbucket
1253                    | IntegrationKind::BitbucketDataCenter
1254                    | IntegrationKind::AzureDevops
1255                    | IntegrationKind::AzureDevopsServer
1256                    | IntegrationKind::Gitea
1257                    | IntegrationKind::Forgejo
1258                    | IntegrationKind::Linear
1259                    | IntegrationKind::Youtrack
1260                    | IntegrationKind::Redmine
1261                    | IntegrationKind::Gerrit
1262                    | IntegrationKind::LocalMarkdown
1263            );
1264            assert_eq!(kind.capabilities().implemented, implemented, "{kind:?}");
1265            assert_eq!(IntegrationKind::IMPLEMENTED.contains(kind), implemented);
1266            assert_eq!(
1267                kind.token_help().is_some(),
1268                *kind != IntegrationKind::LocalMarkdown,
1269                "{kind:?}"
1270            );
1271            assert_eq!(
1272                kind.capabilities().needs_host,
1273                kind.public_url().is_none() && *kind != IntegrationKind::LocalMarkdown
1274            );
1275        }
1276        assert_eq!(
1277            IntegrationKind::JiraCloud.category(),
1278            IntegrationCategory::IssueTracker
1279        );
1280        assert_eq!(
1281            IntegrationKind::Github.category(),
1282            IntegrationCategory::Hosting
1283        );
1284    }
1285
1286    #[test]
1287    fn the_api_base_is_derived_per_kind() {
1288        for (kind, url, want) in [
1289            (
1290                IntegrationKind::Github,
1291                "https://github.com",
1292                "https://api.github.com",
1293            ),
1294            (
1295                IntegrationKind::Github,
1296                "https://github.com/",
1297                "https://api.github.com",
1298            ),
1299            (
1300                IntegrationKind::GithubEnterprise,
1301                "https://ghe.example.com",
1302                "https://ghe.example.com/api/v3",
1303            ),
1304            (
1305                IntegrationKind::Gitlab,
1306                "https://gitlab.com",
1307                "https://gitlab.com/api/v4",
1308            ),
1309            (
1310                IntegrationKind::GitlabSelfManaged,
1311                "https://gitlab.example.com/",
1312                "https://gitlab.example.com/api/v4",
1313            ),
1314        ] {
1315            assert_eq!(Integration::new("x", kind, url).api_base(), want, "{url}");
1316        }
1317    }
1318
1319    #[test]
1320    fn host_and_new_id() {
1321        let i = Integration::new(
1322            "a",
1323            IntegrationKind::Gitlab,
1324            "https://gitlab.example.com/sub",
1325        );
1326        assert_eq!(i.host().as_deref(), Some("gitlab.example.com"));
1327        assert_eq!(
1328            Integration::new("a", IntegrationKind::Gitlab, "").host(),
1329            None
1330        );
1331        let existing = vec![
1332            Integration::new("gitlab", IntegrationKind::Gitlab, "u"),
1333            Integration::new("gitlab-2", IntegrationKind::Gitlab, "u"),
1334        ];
1335        assert_eq!(
1336            Integration::new_id(IntegrationKind::Gitlab, &existing),
1337            "gitlab-3"
1338        );
1339        assert_eq!(
1340            Integration::new_id(IntegrationKind::GithubEnterprise, &existing),
1341            "github-enterprise"
1342        );
1343    }
1344    #[test]
1345    fn gitea_and_forgejo_share_a_family_and_forgejo_defaults_to_codeberg() {
1346        for kind in [IntegrationKind::Gitea, IntegrationKind::Forgejo] {
1347            assert_eq!(kind.family(), ApiFamily::Gitea);
1348            assert!(
1349                kind.capabilities().needs_host,
1350                "{kind:?}: the host stays editable"
1351            );
1352        }
1353        assert_eq!(
1354            IntegrationKind::Forgejo.default_url(),
1355            Some("https://codeberg.org")
1356        );
1357        assert_eq!(IntegrationKind::Gitea.default_url(), None);
1358        let i = Integration::new("c", IntegrationKind::Forgejo, "https://codeberg.org/");
1359        assert_eq!(i.api_base(), "https://codeberg.org/api/v1");
1360        let g = Integration::new("g", IntegrationKind::Gitea, "http://localhost:3000");
1361        assert_eq!(g.api_base(), "http://localhost:3000/api/v1");
1362    }
1363
1364    #[test]
1365    fn azure_devops_server_spelling_is_pinned() {
1366        assert_eq!(
1367            IntegrationKind::AzureDevopsServer.as_str(),
1368            "azure_devops_server"
1369        );
1370        assert!(IntegrationKind::ALL.contains(&IntegrationKind::AzureDevopsServer));
1371        assert_eq!(IntegrationKind::ALL.len(), 18);
1372        assert_eq!(
1373            IntegrationKind::AzureDevopsServer.family(),
1374            ApiFamily::AzureDevops
1375        );
1376        assert!(IntegrationKind::AzureDevopsServer.capabilities().needs_host);
1377    }
1378
1379    #[test]
1380    fn the_capability_table_covers_every_kind() {
1381        use AccountField::{ApiKey, Email, Username};
1382        // (kind, issues, pull_requests, ssh_keys, org, account)
1383        let table = [
1384            (IntegrationKind::Github, true, true, true, false, None),
1385            (
1386                IntegrationKind::GithubEnterprise,
1387                true,
1388                true,
1389                true,
1390                false,
1391                None,
1392            ),
1393            (IntegrationKind::Gitlab, true, true, true, false, None),
1394            (
1395                IntegrationKind::GitlabSelfManaged,
1396                true,
1397                true,
1398                true,
1399                false,
1400                None,
1401            ),
1402            (
1403                IntegrationKind::Bitbucket,
1404                false,
1405                true,
1406                true,
1407                false,
1408                Some(Email),
1409            ),
1410            (
1411                IntegrationKind::BitbucketDataCenter,
1412                false,
1413                true,
1414                false,
1415                false,
1416                None,
1417            ),
1418            (IntegrationKind::AzureDevops, true, true, false, true, None),
1419            (
1420                IntegrationKind::AzureDevopsServer,
1421                true,
1422                true,
1423                false,
1424                false,
1425                None,
1426            ),
1427            (
1428                IntegrationKind::JiraCloud,
1429                true,
1430                false,
1431                false,
1432                false,
1433                Some(Email),
1434            ),
1435            (
1436                IntegrationKind::JiraDataCenter,
1437                true,
1438                false,
1439                false,
1440                false,
1441                None,
1442            ),
1443            (
1444                IntegrationKind::Trello,
1445                true,
1446                false,
1447                false,
1448                false,
1449                Some(ApiKey),
1450            ),
1451            (IntegrationKind::Gitea, true, true, true, false, None),
1452            (IntegrationKind::Forgejo, true, true, true, false, None),
1453            (IntegrationKind::Linear, true, false, false, false, None),
1454            (IntegrationKind::Youtrack, true, false, false, false, None),
1455            (IntegrationKind::Redmine, true, false, false, false, None),
1456            (
1457                IntegrationKind::Gerrit,
1458                false,
1459                true,
1460                false,
1461                false,
1462                Some(Username),
1463            ),
1464            (
1465                IntegrationKind::LocalMarkdown,
1466                true,
1467                false,
1468                false,
1469                false,
1470                None,
1471            ),
1472        ];
1473        assert_eq!(table.len(), IntegrationKind::ALL.len());
1474        for (kind, issues, prs, ssh, org, account) in table {
1475            let c = kind.capabilities();
1476            assert_eq!(c.issues, issues, "{kind:?} issues");
1477            assert_eq!(c.pull_requests, prs, "{kind:?} pull_requests");
1478            assert_eq!(c.ssh_keys, ssh, "{kind:?} ssh_keys");
1479            assert_eq!(c.org, org, "{kind:?} org");
1480            assert_eq!(c.account, account, "{kind:?} account");
1481            assert!(!c.oauth, "{kind:?} oauth is off everywhere");
1482        }
1483    }
1484
1485    #[test]
1486    fn account_round_trips_and_is_skipped_when_empty() {
1487        let mut i = Integration::new(
1488            "jira",
1489            IntegrationKind::JiraCloud,
1490            "https://acme.atlassian.net",
1491        );
1492        assert!(!toml::to_string(&i).unwrap().contains("account"));
1493        i.account = "me@acme.com".into();
1494        let raw = toml::to_string(&i).unwrap();
1495        assert!(raw.contains("account = \"me@acme.com\""), "{raw}");
1496        assert_eq!(toml::from_str::<Integration>(&raw).unwrap(), i);
1497        // An old file without the field loads.
1498        let old = "id = \"x\"\nkind = \"jira_cloud\"\nurl = \"u\"\ntoken_ref = \"t\"\n";
1499        assert_eq!(toml::from_str::<Integration>(old).unwrap().account, "");
1500    }
1501
1502    #[test]
1503    fn radar_options_round_trip_and_an_old_file_has_none() {
1504        let mut i = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1505        assert!(!toml::to_string(&i).unwrap().contains("radar"));
1506        assert_eq!(i.radar_options(), IntegrationRadar::default());
1507        assert!(!i.radar_options().any_list());
1508        i.radar = Some(IntegrationRadar {
1509            review_requests: true,
1510            namespaces: vec!["acme".into(), "tools".into()],
1511            review_mode: RemoteReviewMode::Api,
1512            ..IntegrationRadar::default()
1513        });
1514        let raw = toml::to_string(&i).unwrap();
1515        assert!(raw.contains("[radar]"), "{raw}");
1516        assert!(raw.contains("review_mode = \"api\""), "{raw}");
1517        assert_eq!(toml::from_str::<Integration>(&raw).unwrap(), i);
1518        assert!(i.radar_options().any_list());
1519        // A table naming one key leaves the others off and the mode on ask.
1520        let old = "id = \"x\"\nkind = \"github\"\nurl = \"u\"\ntoken_ref = \"t\"\n[radar]\nassigned_issues = true\n";
1521        let radar = toml::from_str::<Integration>(old).unwrap().radar_options();
1522        assert!(radar.assigned_issues && !radar.review_requests && !radar.open_requests);
1523        assert_eq!(radar.review_mode, RemoteReviewMode::Ask);
1524        assert_eq!(
1525            RemoteReviewMode::parse(" API "),
1526            Some(RemoteReviewMode::Api)
1527        );
1528        assert_eq!(RemoteReviewMode::parse("nope"), None);
1529    }
1530
1531    #[test]
1532    fn namespaces_read_the_old_comma_string_and_save_as_a_list() {
1533        let head = "id = \"x\"\nkind = \"github\"\nurl = \"u\"\ntoken_ref = \"t\"\n[radar]\n";
1534        let load = |body: &str| {
1535            toml::from_str::<Integration>(&format!("{head}{body}"))
1536                .unwrap()
1537                .radar_options()
1538        };
1539        assert_eq!(
1540            load("namespaces = \"orbit, training\"\n").namespaces,
1541            ["orbit", "training"]
1542        );
1543        assert_eq!(load("namespaces = \"orbit\"\n").namespaces, ["orbit"]);
1544        assert_eq!(
1545            load("namespaces = [\"a\", \" b \", \"a\", \"\"]\n").namespaces,
1546            ["a", "b"]
1547        );
1548        assert!(!load("namespaces = [\"a\"]\n").namespaces_regex);
1549        assert!(load("namespaces = [\"a\"]\nnamespaces_regex = true\n").namespaces_regex);
1550        let mut i = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1551        i.radar = Some(load("namespaces = \"orbit, training\"\n"));
1552        let raw = toml::to_string(&i).unwrap();
1553        assert!(
1554            raw.contains("namespaces = [\"orbit\", \"training\"]"),
1555            "{raw}"
1556        );
1557        assert!(!raw.contains("namespaces_regex"), "{raw}");
1558    }
1559
1560    #[test]
1561    fn namespace_text_is_lines_and_commas_only_in_plain_mode() {
1562        assert_eq!(
1563            parse_namespace_text("a\n b ,c\n\na", false),
1564            ["a", "b", "c"]
1565        );
1566        assert_eq!(
1567            parse_namespace_text("^a{1,2}/\n  x  ", true),
1568            ["^a{1,2}/", "x"]
1569        );
1570    }
1571
1572    #[test]
1573    fn azure_org_parses_both_url_spellings() {
1574        let az = |url: &str| Integration::new("a", IntegrationKind::AzureDevops, url);
1575        assert_eq!(
1576            az("https://dev.azure.com/acme").azure_org().as_deref(),
1577            Some("acme")
1578        );
1579        assert_eq!(
1580            az("https://dev.azure.com/acme/").azure_org().as_deref(),
1581            Some("acme")
1582        );
1583        assert_eq!(
1584            az("https://acme.visualstudio.com").azure_org().as_deref(),
1585            Some("acme")
1586        );
1587        assert_eq!(az("https://dev.azure.com").azure_org(), None);
1588        let server = Integration::new(
1589            "s",
1590            IntegrationKind::AzureDevopsServer,
1591            "https://tfs.corp/tfs/Coll",
1592        );
1593        assert_eq!(server.azure_org(), None);
1594        let gh = Integration::new("g", IntegrationKind::Github, "https://dev.azure.com/acme");
1595        assert_eq!(gh.azure_org(), None);
1596        assert_eq!(
1597            normalize_azure_url("https://acme.visualstudio.com/"),
1598            "https://dev.azure.com/acme"
1599        );
1600        assert_eq!(
1601            normalize_azure_url("https://dev.azure.com/acme/"),
1602            "https://dev.azure.com/acme"
1603        );
1604    }
1605
1606    #[test]
1607    fn normalize_kind_leaves_the_new_kinds_alone() {
1608        for kind in [
1609            IntegrationKind::AzureDevopsServer,
1610            IntegrationKind::AzureDevops,
1611            IntegrationKind::Bitbucket,
1612            IntegrationKind::BitbucketDataCenter,
1613            IntegrationKind::JiraCloud,
1614            IntegrationKind::JiraDataCenter,
1615            IntegrationKind::Trello,
1616        ] {
1617            assert_eq!(migrated(kind.as_str(), "https://github.com"), kind);
1618            assert_eq!(migrated(kind.as_str(), "https://x.example.com"), kind);
1619        }
1620    }
1621
1622    #[test]
1623    fn the_api_base_of_the_new_kinds() {
1624        for (kind, url, want) in [
1625            (
1626                IntegrationKind::AzureDevops,
1627                "https://dev.azure.com/acme",
1628                "https://dev.azure.com/acme",
1629            ),
1630            (
1631                IntegrationKind::AzureDevops,
1632                "https://acme.visualstudio.com/",
1633                "https://dev.azure.com/acme",
1634            ),
1635            (
1636                IntegrationKind::AzureDevopsServer,
1637                "https://tfs.corp/tfs/DefaultCollection/",
1638                "https://tfs.corp/tfs/DefaultCollection",
1639            ),
1640            (
1641                IntegrationKind::Bitbucket,
1642                "https://bitbucket.org",
1643                "https://api.bitbucket.org/2.0",
1644            ),
1645            (
1646                IntegrationKind::Bitbucket,
1647                "http://127.0.0.1:9",
1648                "http://127.0.0.1:9/2.0",
1649            ),
1650            (
1651                IntegrationKind::BitbucketDataCenter,
1652                "https://bb.corp/",
1653                "https://bb.corp/rest/api/1.0",
1654            ),
1655            (
1656                IntegrationKind::JiraCloud,
1657                "https://acme.atlassian.net/",
1658                "https://acme.atlassian.net/rest/api/3",
1659            ),
1660            (
1661                IntegrationKind::JiraDataCenter,
1662                "https://jira.corp",
1663                "https://jira.corp/rest/api/2",
1664            ),
1665            (
1666                IntegrationKind::Trello,
1667                "https://trello.com",
1668                "https://api.trello.com/1",
1669            ),
1670            (
1671                IntegrationKind::Trello,
1672                "http://127.0.0.1:9",
1673                "http://127.0.0.1:9/1",
1674            ),
1675            (
1676                IntegrationKind::Linear,
1677                "https://linear.app",
1678                "https://api.linear.app",
1679            ),
1680            (
1681                IntegrationKind::Linear,
1682                "http://127.0.0.1:9",
1683                "http://127.0.0.1:9",
1684            ),
1685            (
1686                IntegrationKind::Youtrack,
1687                "https://acme.youtrack.cloud/",
1688                "https://acme.youtrack.cloud/api",
1689            ),
1690            (
1691                IntegrationKind::Redmine,
1692                "http://127.0.0.1:3002/",
1693                "http://127.0.0.1:3002",
1694            ),
1695            (
1696                IntegrationKind::Gerrit,
1697                "http://127.0.0.1:8081/",
1698                "http://127.0.0.1:8081/a",
1699            ),
1700        ] {
1701            assert_eq!(
1702                Integration::new("x", kind, url).api_base(),
1703                want,
1704                "{kind:?} {url}"
1705            );
1706        }
1707        let cloud = Integration::new(
1708            "j",
1709            IntegrationKind::JiraCloud,
1710            "https://acme.atlassian.net",
1711        );
1712        assert_eq!(
1713            cloud.api_base_v2().as_deref(),
1714            Some("https://acme.atlassian.net/rest/api/2")
1715        );
1716        let dc = Integration::new("j", IntegrationKind::JiraDataCenter, "https://jira.corp");
1717        assert_eq!(dc.api_base_v2(), None);
1718    }
1719
1720    #[test]
1721    fn the_token_link_per_kind() {
1722        let link = |kind: IntegrationKind| kind.token_help().expect("token help").link;
1723        assert!(
1724            matches!(link(IntegrationKind::Github), TokenLink::Path(p) if p.starts_with("/settings/tokens"))
1725        );
1726        assert!(matches!(
1727            link(IntegrationKind::AzureDevops),
1728            TokenLink::Path("/_usersSettings/tokens")
1729        ));
1730        assert!(
1731            matches!(link(IntegrationKind::JiraCloud), TokenLink::Absolute(u) if u.contains("id.atlassian.com"))
1732        );
1733        assert!(matches!(link(IntegrationKind::Trello), TokenLink::Trello));
1734        assert_eq!(
1735            IntegrationKind::Trello.token_help().unwrap().scopes,
1736            &["read", "write"]
1737        );
1738        // Trello has no link until the key is typed.
1739        let mut trello = Integration::new("t", IntegrationKind::Trello, "https://trello.com");
1740        assert_eq!(trello.token_link_url("https://trello.com"), None);
1741        trello.account = "KEY123".into();
1742        let url = trello.token_link_url("https://trello.com").unwrap();
1743        assert!(url.starts_with("https://trello.com/1/authorize?"), "{url}");
1744        assert!(
1745            url.contains("key=KEY123")
1746                && url.contains("scope=read,write")
1747                && url.contains("name=GitPoulpi"),
1748            "{url}"
1749        );
1750        let gl = Integration::new("g", IntegrationKind::Gitlab, "https://gitlab.com");
1751        assert!(gl
1752            .token_link_url("https://gitlab.com")
1753            .unwrap()
1754            .starts_with("https://gitlab.com/-/user_settings/personal_access_tokens"));
1755        let jira = Integration::new(
1756            "j",
1757            IntegrationKind::JiraCloud,
1758            "https://acme.atlassian.net",
1759        );
1760        assert_eq!(
1761            jira.token_link_url("https://acme.atlassian.net").as_deref(),
1762            Some("https://id.atlassian.com/manage-profile/security/api-tokens")
1763        );
1764    }
1765}