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}
502
503/// How a Redmine server formats text (Administration > Settings >
504/// General > Text formatting). The API does not say, so the profile does.
505#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(rename_all = "snake_case")]
507pub enum RedmineMarkup {
508    /// Redmine's historical default.
509    #[default]
510    Textile,
511    Markdown,
512}
513
514impl RedmineMarkup {
515    pub const ALL: [RedmineMarkup; 2] = [Self::Textile, Self::Markdown];
516
517    pub fn as_str(self) -> &'static str {
518        match self {
519            Self::Textile => "textile",
520            Self::Markdown => "markdown",
521        }
522    }
523
524    pub fn is_default(&self) -> bool {
525        *self == Self::default()
526    }
527
528    /// The other one (what a cycling control does).
529    pub fn toggled(self) -> Self {
530        match self {
531            Self::Textile => Self::Markdown,
532            Self::Markdown => Self::Textile,
533        }
534    }
535}
536
537/// What to do with a request whose repository is not cloned.
538#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
539#[serde(rename_all = "snake_case")]
540pub enum RemoteReviewMode {
541    /// Ask each time.
542    #[default]
543    Ask,
544    /// Clone the repository, then review it there.
545    Clone,
546    /// Review through the host's API, without a clone.
547    Api,
548}
549
550impl RemoteReviewMode {
551    pub const ALL: [RemoteReviewMode; 3] = [Self::Ask, Self::Clone, Self::Api];
552
553    pub fn as_str(self) -> &'static str {
554        match self {
555            Self::Ask => "ask",
556            Self::Clone => "clone",
557            Self::Api => "api",
558        }
559    }
560
561    /// `ask`, `clone` or `api`, any case.
562    pub fn parse(text: &str) -> Option<Self> {
563        Self::ALL
564            .into_iter()
565            .find(|m| m.as_str().eq_ignore_ascii_case(text.trim()))
566    }
567}
568
569/// `[integrations.radar]` of a code-host profile: which account-wide lists
570/// (not tied to a cloned repository) the Radar shows, all off by default.
571///
572/// ```toml
573/// [integrations.radar]
574/// review_requests = true      # requests waiting for my review, every repository
575/// open_requests = false       # every open request of my namespaces
576/// include_drafts = false      # account rows: drafts too
577/// assigned_issues = true      # open issues assigned to me, every repository
578/// namespaces = ["acme"]       # empty = my own namespace plus every membership
579/// review_mode = "ask"         # ask | clone | api
580/// ```
581#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
582pub struct IntegrationRadar {
583    #[serde(default)]
584    pub review_requests: bool,
585    #[serde(default)]
586    pub open_requests: bool,
587    #[serde(default)]
588    pub include_drafts: bool,
589    #[serde(default)]
590    pub assigned_issues: bool,
591    /// Orgs / groups / workspaces / Azure projects / Gerrit project
592    /// prefixes; empty means the account's own namespace plus every one it
593    /// is a member of.
594    ///
595    /// One entry per line of the Settings field. An old file may hold one
596    /// comma-separated string instead of a list; both load.
597    #[serde(
598        default,
599        deserialize_with = "de_namespaces",
600        skip_serializing_if = "Vec::is_empty"
601    )]
602    pub namespaces: Vec<String>,
603    /// Read each `namespaces` entry as a regular expression matched against
604    /// the full repository path, instead of a path prefix.
605    #[serde(default, skip_serializing_if = "is_false")]
606    pub namespaces_regex: bool,
607    #[serde(default)]
608    pub review_mode: RemoteReviewMode,
609}
610
611fn is_false(v: &bool) -> bool {
612    !*v
613}
614
615/// Namespace entries: trimmed, empty ones dropped, repeats dropped.
616pub fn clean_namespaces<I, S>(entries: I) -> Vec<String>
617where
618    I: IntoIterator<Item = S>,
619    S: AsRef<str>,
620{
621    let mut out: Vec<String> = Vec::new();
622    for entry in entries {
623        let entry = entry.as_ref().trim();
624        if !entry.is_empty() && !out.iter().any(|o| o == entry) {
625            out.push(entry.to_string());
626        }
627    }
628    out
629}
630
631/// The text of the Namespaces field: one entry per line. In plain mode the
632/// old single-line form (`acme, tools`) is still read, commas separate
633/// entries; in regex mode a comma belongs to the expression.
634pub fn parse_namespace_text(text: &str, regex: bool) -> Vec<String> {
635    if regex {
636        clean_namespaces(text.lines())
637    } else {
638        clean_namespaces(text.split(['\n', ',']))
639    }
640}
641
642fn de_namespaces<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
643where
644    D: serde::Deserializer<'de>,
645{
646    #[derive(Deserialize)]
647    #[serde(untagged)]
648    enum Form {
649        One(String),
650        Many(Vec<String>),
651    }
652    Ok(match Form::deserialize(deserializer)? {
653        Form::One(text) => parse_namespace_text(&text, false),
654        Form::Many(list) => clean_namespaces(list),
655    })
656}
657
658impl IntegrationRadar {
659    /// Whether any account-wide list is on (the drafts switch and the
660    /// namespaces only refine them).
661    pub fn any_list(&self) -> bool {
662        self.review_requests || self.open_requests || self.assigned_issues
663    }
664}
665
666/// `[integrations.local]` of a `local_markdown` profile: how its notes'
667/// `status` values are ordered and which one means closed.
668///
669/// ```toml
670/// [integrations.local]
671/// statuses = ["todo", "doing", "review", "done"]
672/// done_status = "done"
673/// reference_prefix = "LOC"   # shows LOC-12 instead of #12
674/// me = "kai"                 # who "assigned to me" means
675/// ```
676#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
677pub struct LocalMarkdownSettings {
678    /// The board's column order; statuses used by notes but not listed
679    /// follow, in order of appearance. Empty: [`DEFAULT_STATUSES`].
680    #[serde(default, skip_serializing_if = "Vec::is_empty")]
681    pub statuses: Vec<String>,
682    /// The status that closes an issue. Empty: `done`.
683    #[serde(default, skip_serializing_if = "String::is_empty")]
684    pub done_status: String,
685    /// Shown before the number (`LOC-12`); empty: `#12`.
686    #[serde(default, skip_serializing_if = "String::is_empty")]
687    pub reference_prefix: String,
688    /// The login "assigned to me" matches; empty: the connected user, else
689    /// the profile name.
690    #[serde(default, skip_serializing_if = "String::is_empty")]
691    pub me: String,
692}
693
694/// The column order of a local issue folder with no `statuses` configured.
695pub const DEFAULT_STATUSES: [&str; 3] = ["todo", "doing", "done"];
696
697impl LocalMarkdownSettings {
698    /// The configured order, or the default one.
699    pub fn status_order(&self) -> Vec<String> {
700        if self.statuses.is_empty() {
701            DEFAULT_STATUSES.iter().map(|s| s.to_string()).collect()
702        } else {
703            self.statuses.clone()
704        }
705    }
706
707    /// The status that closes an issue.
708    pub fn done(&self) -> &str {
709        let d = self.done_status.trim();
710        if d.is_empty() {
711            "done"
712        } else {
713            d
714        }
715    }
716
717    /// The status a reopened issue returns to: the first one in the order
718    /// that is not the done status.
719    pub fn open_status(&self) -> String {
720        self.status_order()
721            .into_iter()
722            .find(|s| !s.eq_ignore_ascii_case(self.done()))
723            .unwrap_or_else(|| "todo".to_string())
724    }
725}
726
727impl Integration {
728    /// The profile's `[integrations.radar]`, or all-off defaults.
729    pub fn radar_options(&self) -> IntegrationRadar {
730        self.radar.clone().unwrap_or_default()
731    }
732
733    /// The canonical `token_ref` for an id.
734    pub fn token_ref_for(id: &str) -> String {
735        format!("integration:{id}")
736    }
737
738    pub fn new(id: impl Into<String>, kind: IntegrationKind, url: impl Into<String>) -> Self {
739        let id = id.into();
740        let token_ref = Self::token_ref_for(&id);
741        Self {
742            id,
743            kind,
744            url: url.into(),
745            token_ref,
746            name: String::new(),
747            auth: AuthMethod::Pat,
748            account: String::new(),
749            user: None,
750            ssh: None,
751            enabled: true,
752            local: None,
753            radar: None,
754            markup: RedmineMarkup::default(),
755        }
756    }
757
758    /// A fresh id (`gitlab`, `gitlab-2`, ...) not used by `existing`.
759    pub fn new_id<'a>(
760        kind: IntegrationKind,
761        existing: impl IntoIterator<Item = &'a Integration>,
762    ) -> String {
763        let taken: Vec<&str> = existing.into_iter().map(|i| i.id.as_str()).collect();
764        let base = kind.as_str().replace('_', "-");
765        if !taken.contains(&base.as_str()) {
766            return base;
767        }
768        (2..)
769            .map(|n| format!("{base}-{n}"))
770            .find(|c| !taken.contains(&c.as_str()))
771            .expect("infinite range")
772    }
773
774    pub fn display_name(&self) -> &str {
775        if self.name.is_empty() {
776            &self.id
777        } else {
778            &self.name
779        }
780    }
781
782    /// `host[:port]` of `url`, the key credential helpers use.
783    pub fn host(&self) -> Option<String> {
784        host_of(&self.url)
785    }
786
787    /// The API root, derived from `url` (never configured separately).
788    ///
789    /// github.com uses `https://api.github.com`; GitHub Enterprise Server
790    /// uses `<url>/api/v3`; GitLab always `<url>/api/v4`. Other families
791    /// have no client yet and return the bare base URL.
792    pub fn api_base(&self) -> String {
793        let base = self.url.trim_end_matches('/');
794        match self.kind.family() {
795            ApiFamily::Github => {
796                if is_dot_com(base, "github.com") {
797                    "https://api.github.com".to_string()
798                } else {
799                    format!("{base}/api/v3")
800                }
801            }
802            ApiFamily::Gitlab => format!("{base}/api/v4"),
803            ApiFamily::AzureDevops => match self.kind {
804                IntegrationKind::AzureDevops => normalize_azure_url(base),
805                _ => base.to_string(),
806            },
807            ApiFamily::Bitbucket => match self.kind {
808                IntegrationKind::BitbucketDataCenter => format!("{base}/rest/api/1.0"),
809                _ if is_dot_com(base, "bitbucket.org") => {
810                    "https://api.bitbucket.org/2.0".to_string()
811                }
812                _ => format!("{base}/2.0"),
813            },
814            ApiFamily::Jira => match self.kind {
815                IntegrationKind::JiraCloud => format!("{base}/rest/api/3"),
816                _ => format!("{base}/rest/api/2"),
817            },
818            ApiFamily::Trello => {
819                if is_dot_com(base, "trello.com") {
820                    "https://api.trello.com/1".to_string()
821                } else {
822                    format!("{base}/1")
823                }
824            }
825            ApiFamily::Gitea => format!("{base}/api/v1"),
826            // The GraphQL endpoint is `<root>/graphql`.
827            ApiFamily::Linear => {
828                if is_dot_com(base, "linear.app") {
829                    "https://api.linear.app".to_string()
830                } else {
831                    base.to_string()
832                }
833            }
834            ApiFamily::YouTrack => format!("{base}/api"),
835            // The REST resources sit at the root (`/issues.json`).
836            ApiFamily::Redmine => base.to_string(),
837            // Authenticated calls live under `/a/`.
838            ApiFamily::Gerrit => format!("{base}/a"),
839            // A folder: there is no API.
840            ApiFamily::LocalMarkdown => base.to_string(),
841        }
842    }
843
844    /// Jira Cloud creates issues through `/rest/api/2` (plain-text
845    /// description) while reading through `/3`; `None` for other kinds.
846    pub fn api_base_v2(&self) -> Option<String> {
847        (self.kind == IntegrationKind::JiraCloud)
848            .then(|| format!("{}/rest/api/2", self.url.trim_end_matches('/')))
849    }
850
851    /// The Azure DevOps Services organization of a `dev.azure.com/{org}` or
852    /// `{org}.visualstudio.com` URL. `None` for other kinds, Server, or a
853    /// URL without an organization.
854    pub fn azure_org(&self) -> Option<String> {
855        if self.kind != IntegrationKind::AzureDevops {
856            return None;
857        }
858        let normalized = normalize_azure_url(&self.url);
859        let rest = normalized.strip_prefix("https://dev.azure.com/")?;
860        let org = rest.split('/').next().unwrap_or("");
861        (!org.is_empty()).then(|| org.to_string())
862    }
863
864    /// The page that mints this profile's token, given the instance's web
865    /// root (`https://github.com`, ...). `None` when the kind has no flow or
866    /// Trello's key is not typed yet.
867    pub fn token_link_url(&self, web_base: &str) -> Option<String> {
868        let help = self.kind.token_help()?;
869        match help.link {
870            TokenLink::Path(path) => Some(format!("{}{path}", web_base.trim_end_matches('/'))),
871            TokenLink::Absolute(url) => Some(url.to_string()),
872            TokenLink::Trello => {
873                let key = self.account.trim();
874                (!key.is_empty()).then(|| {
875                    format!(
876                        "https://trello.com/1/authorize?expiration=never&name=GitPoulpi&scope=read,write&response_type=token&key={key}"
877                    )
878                })
879            }
880        }
881    }
882
883    /// Applies the legacy-kind migration; see
884    /// [`crate::Config::normalize_integrations`].
885    pub(crate) fn normalize_kind(&mut self) {
886        if self.url.trim().is_empty() {
887            return;
888        }
889        match self.kind {
890            IntegrationKind::Github if !is_dot_com(&self.url, "github.com") => {
891                self.kind = IntegrationKind::GithubEnterprise;
892            }
893            IntegrationKind::Gitlab if !is_dot_com(&self.url, "gitlab.com") => {
894                self.kind = IntegrationKind::GitlabSelfManaged;
895            }
896            _ => {}
897        }
898    }
899}
900
901/// Rewrites `https://{org}.visualstudio.com[/...]` to
902/// `https://dev.azure.com/{org}`; anything else loses only a trailing slash.
903pub fn normalize_azure_url(url: &str) -> String {
904    let trimmed = url.trim().trim_end_matches('/');
905    if let Some(host) = host_of(trimmed) {
906        let lower = host.to_ascii_lowercase();
907        if let Some(org) = lower.strip_suffix(".visualstudio.com") {
908            if !org.is_empty() && !org.contains('.') {
909                return format!("https://dev.azure.com/{org}");
910            }
911        }
912    }
913    trimmed.to_string()
914}
915
916fn host_of(url: &str) -> Option<String> {
917    let rest = url.split_once("://").map(|(_, rest)| rest).unwrap_or(url);
918    let host = rest.split('/').next().unwrap_or("").trim();
919    (!host.is_empty()).then(|| host.to_string())
920}
921
922/// Whether `url` is the public `domain` (also `www.` and, for GitHub,
923/// `api.`), ignoring scheme, case, a trailing slash and any path.
924fn is_dot_com(url: &str, domain: &str) -> bool {
925    let Some(host) = host_of(url) else {
926        return false;
927    };
928    let host = host.to_ascii_lowercase();
929    host == domain || host == format!("www.{domain}") || host == format!("api.{domain}")
930}
931
932#[cfg(test)]
933mod tests {
934    use super::*;
935    use crate::Config;
936
937    fn migrated(kind: &str, url: &str) -> IntegrationKind {
938        let raw = format!(
939            "[[integrations]]\nid = \"x\"\nkind = \"{kind}\"\nurl = \"{url}\"\ntoken_ref = \"integration:x\"\n"
940        );
941        Config::from_toml_str(&raw).unwrap().0.integrations[0].kind
942    }
943
944    #[test]
945    fn an_integration_carries_a_reference_not_a_token() {
946        let integration =
947            Integration::new("my-gitlab", IntegrationKind::Gitlab, "https://g.example");
948        assert_eq!(integration.token_ref, "integration:my-gitlab");
949        let raw = toml::to_string(&integration).unwrap();
950        assert!(raw.contains("token_ref"), "{raw}");
951        assert!(!raw.contains("token ="), "{raw}");
952    }
953
954    #[test]
955    fn serde_spellings_are_pinned() {
956        let expected = [
957            (IntegrationKind::Github, "github"),
958            (IntegrationKind::GithubEnterprise, "github_enterprise"),
959            (IntegrationKind::Gitlab, "gitlab"),
960            (IntegrationKind::GitlabSelfManaged, "gitlab_self_managed"),
961            (IntegrationKind::Bitbucket, "bitbucket"),
962            (
963                IntegrationKind::BitbucketDataCenter,
964                "bitbucket_data_center",
965            ),
966            (IntegrationKind::AzureDevops, "azure_devops"),
967            (IntegrationKind::AzureDevopsServer, "azure_devops_server"),
968            (IntegrationKind::JiraCloud, "jira_cloud"),
969            (IntegrationKind::JiraDataCenter, "jira_data_center"),
970            (IntegrationKind::Trello, "trello"),
971            (IntegrationKind::Gitea, "gitea"),
972            (IntegrationKind::Forgejo, "forgejo"),
973            (IntegrationKind::Linear, "linear"),
974            (IntegrationKind::Youtrack, "youtrack"),
975            (IntegrationKind::Redmine, "redmine"),
976            (IntegrationKind::Gerrit, "gerrit"),
977            (IntegrationKind::LocalMarkdown, "local_markdown"),
978        ];
979        assert_eq!(expected.len(), IntegrationKind::ALL.len());
980        for (kind, spelling) in expected {
981            assert_eq!(kind.as_str(), spelling);
982            let raw = toml::to_string(&Integration::new("x", kind, "u")).unwrap();
983            assert!(raw.contains(&format!("kind = \"{spelling}\"")), "{raw}");
984        }
985    }
986
987    #[test]
988    fn old_toml_migrates_and_round_trips_stably() {
989        let raw = r#"
990[[integrations]]
991id = "gh"
992kind = "github"
993url = "https://github.com"
994token_ref = "integration:gh"
995
996[[integrations]]
997id = "ghe"
998kind = "github"
999url = "https://ghe.example.com"
1000token_ref = "integration:ghe"
1001
1002[[integrations]]
1003id = "gl"
1004kind = "gitlab"
1005url = "https://gitlab.com/"
1006token_ref = "integration:gl"
1007
1008[[integrations]]
1009id = "corp"
1010kind = "gitlab"
1011url = "https://gitlab.example.com"
1012token_ref = "integration:corp"
1013"#;
1014        let (config, _) = Config::from_toml_str(raw).unwrap();
1015        let kinds: Vec<_> = config.integrations.iter().map(|i| i.kind).collect();
1016        assert_eq!(
1017            kinds,
1018            [
1019                IntegrationKind::Github,
1020                IntegrationKind::GithubEnterprise,
1021                IntegrationKind::Gitlab,
1022                IntegrationKind::GitlabSelfManaged
1023            ]
1024        );
1025        assert!(config.integrations.iter().all(|i| i.enabled));
1026        // Stable: write it out and read it back, nothing moves.
1027        let written = toml::to_string_pretty(&config).unwrap();
1028        let (again, _) = Config::from_toml_str(&written).unwrap();
1029        assert_eq!(again.integrations, config.integrations);
1030        let mut twice = again.clone();
1031        twice.normalize_integrations();
1032        assert_eq!(twice.integrations, config.integrations);
1033    }
1034
1035    #[test]
1036    fn migration_ignores_www_scheme_case_and_trailing_slash() {
1037        assert_eq!(
1038            migrated("github", "https://www.github.com"),
1039            IntegrationKind::Github
1040        );
1041        assert_eq!(
1042            migrated("github", "HTTPS://GitHub.com/"),
1043            IntegrationKind::Github
1044        );
1045        assert_eq!(
1046            migrated("gitlab", "https://www.gitlab.com/"),
1047            IntegrationKind::Gitlab
1048        );
1049        assert_eq!(
1050            migrated("github", "https://github.example.com/"),
1051            IntegrationKind::GithubEnterprise
1052        );
1053        // Never demoted, never touched when already specific.
1054        assert_eq!(
1055            migrated("github_enterprise", "https://github.com"),
1056            IntegrationKind::GithubEnterprise
1057        );
1058        assert_eq!(migrated("trello", "https://x"), IntegrationKind::Trello);
1059    }
1060
1061    #[test]
1062    fn all_and_implemented_list_hosting_before_issue_trackers() {
1063        for list in [IntegrationKind::ALL, IntegrationKind::IMPLEMENTED] {
1064            let first_tracker = list
1065                .iter()
1066                .position(|k| k.category() == IntegrationCategory::IssueTracker)
1067                .unwrap();
1068            assert!(list[first_tracker..]
1069                .iter()
1070                .all(|k| k.category() == IntegrationCategory::IssueTracker));
1071        }
1072    }
1073
1074    #[test]
1075    fn capabilities_and_implemented_agree() {
1076        for kind in IntegrationKind::ALL {
1077            let implemented = matches!(
1078                kind,
1079                IntegrationKind::Github
1080                    | IntegrationKind::GithubEnterprise
1081                    | IntegrationKind::Gitlab
1082                    | IntegrationKind::GitlabSelfManaged
1083                    | IntegrationKind::JiraCloud
1084                    | IntegrationKind::JiraDataCenter
1085                    | IntegrationKind::Trello
1086                    | IntegrationKind::Bitbucket
1087                    | IntegrationKind::BitbucketDataCenter
1088                    | IntegrationKind::AzureDevops
1089                    | IntegrationKind::AzureDevopsServer
1090                    | IntegrationKind::Gitea
1091                    | IntegrationKind::Forgejo
1092                    | IntegrationKind::Linear
1093                    | IntegrationKind::Youtrack
1094                    | IntegrationKind::Redmine
1095                    | IntegrationKind::Gerrit
1096                    | IntegrationKind::LocalMarkdown
1097            );
1098            assert_eq!(kind.capabilities().implemented, implemented, "{kind:?}");
1099            assert_eq!(IntegrationKind::IMPLEMENTED.contains(kind), implemented);
1100            assert_eq!(
1101                kind.token_help().is_some(),
1102                *kind != IntegrationKind::LocalMarkdown,
1103                "{kind:?}"
1104            );
1105            assert_eq!(
1106                kind.capabilities().needs_host,
1107                kind.public_url().is_none() && *kind != IntegrationKind::LocalMarkdown
1108            );
1109        }
1110        assert_eq!(
1111            IntegrationKind::JiraCloud.category(),
1112            IntegrationCategory::IssueTracker
1113        );
1114        assert_eq!(
1115            IntegrationKind::Github.category(),
1116            IntegrationCategory::Hosting
1117        );
1118    }
1119
1120    #[test]
1121    fn the_api_base_is_derived_per_kind() {
1122        for (kind, url, want) in [
1123            (
1124                IntegrationKind::Github,
1125                "https://github.com",
1126                "https://api.github.com",
1127            ),
1128            (
1129                IntegrationKind::Github,
1130                "https://github.com/",
1131                "https://api.github.com",
1132            ),
1133            (
1134                IntegrationKind::GithubEnterprise,
1135                "https://ghe.example.com",
1136                "https://ghe.example.com/api/v3",
1137            ),
1138            (
1139                IntegrationKind::Gitlab,
1140                "https://gitlab.com",
1141                "https://gitlab.com/api/v4",
1142            ),
1143            (
1144                IntegrationKind::GitlabSelfManaged,
1145                "https://gitlab.example.com/",
1146                "https://gitlab.example.com/api/v4",
1147            ),
1148        ] {
1149            assert_eq!(Integration::new("x", kind, url).api_base(), want, "{url}");
1150        }
1151    }
1152
1153    #[test]
1154    fn host_and_new_id() {
1155        let i = Integration::new(
1156            "a",
1157            IntegrationKind::Gitlab,
1158            "https://gitlab.example.com/sub",
1159        );
1160        assert_eq!(i.host().as_deref(), Some("gitlab.example.com"));
1161        assert_eq!(
1162            Integration::new("a", IntegrationKind::Gitlab, "").host(),
1163            None
1164        );
1165        let existing = vec![
1166            Integration::new("gitlab", IntegrationKind::Gitlab, "u"),
1167            Integration::new("gitlab-2", IntegrationKind::Gitlab, "u"),
1168        ];
1169        assert_eq!(
1170            Integration::new_id(IntegrationKind::Gitlab, &existing),
1171            "gitlab-3"
1172        );
1173        assert_eq!(
1174            Integration::new_id(IntegrationKind::GithubEnterprise, &existing),
1175            "github-enterprise"
1176        );
1177    }
1178    #[test]
1179    fn gitea_and_forgejo_share_a_family_and_forgejo_defaults_to_codeberg() {
1180        for kind in [IntegrationKind::Gitea, IntegrationKind::Forgejo] {
1181            assert_eq!(kind.family(), ApiFamily::Gitea);
1182            assert!(
1183                kind.capabilities().needs_host,
1184                "{kind:?}: the host stays editable"
1185            );
1186        }
1187        assert_eq!(
1188            IntegrationKind::Forgejo.default_url(),
1189            Some("https://codeberg.org")
1190        );
1191        assert_eq!(IntegrationKind::Gitea.default_url(), None);
1192        let i = Integration::new("c", IntegrationKind::Forgejo, "https://codeberg.org/");
1193        assert_eq!(i.api_base(), "https://codeberg.org/api/v1");
1194        let g = Integration::new("g", IntegrationKind::Gitea, "http://localhost:3000");
1195        assert_eq!(g.api_base(), "http://localhost:3000/api/v1");
1196    }
1197
1198    #[test]
1199    fn azure_devops_server_spelling_is_pinned() {
1200        assert_eq!(
1201            IntegrationKind::AzureDevopsServer.as_str(),
1202            "azure_devops_server"
1203        );
1204        assert!(IntegrationKind::ALL.contains(&IntegrationKind::AzureDevopsServer));
1205        assert_eq!(IntegrationKind::ALL.len(), 18);
1206        assert_eq!(
1207            IntegrationKind::AzureDevopsServer.family(),
1208            ApiFamily::AzureDevops
1209        );
1210        assert!(IntegrationKind::AzureDevopsServer.capabilities().needs_host);
1211    }
1212
1213    #[test]
1214    fn the_capability_table_covers_every_kind() {
1215        use AccountField::{ApiKey, Email, Username};
1216        // (kind, issues, pull_requests, ssh_keys, org, account)
1217        let table = [
1218            (IntegrationKind::Github, true, true, true, false, None),
1219            (
1220                IntegrationKind::GithubEnterprise,
1221                true,
1222                true,
1223                true,
1224                false,
1225                None,
1226            ),
1227            (IntegrationKind::Gitlab, true, true, true, false, None),
1228            (
1229                IntegrationKind::GitlabSelfManaged,
1230                true,
1231                true,
1232                true,
1233                false,
1234                None,
1235            ),
1236            (
1237                IntegrationKind::Bitbucket,
1238                false,
1239                true,
1240                true,
1241                false,
1242                Some(Email),
1243            ),
1244            (
1245                IntegrationKind::BitbucketDataCenter,
1246                false,
1247                true,
1248                false,
1249                false,
1250                None,
1251            ),
1252            (IntegrationKind::AzureDevops, true, true, false, true, None),
1253            (
1254                IntegrationKind::AzureDevopsServer,
1255                true,
1256                true,
1257                false,
1258                false,
1259                None,
1260            ),
1261            (
1262                IntegrationKind::JiraCloud,
1263                true,
1264                false,
1265                false,
1266                false,
1267                Some(Email),
1268            ),
1269            (
1270                IntegrationKind::JiraDataCenter,
1271                true,
1272                false,
1273                false,
1274                false,
1275                None,
1276            ),
1277            (
1278                IntegrationKind::Trello,
1279                true,
1280                false,
1281                false,
1282                false,
1283                Some(ApiKey),
1284            ),
1285            (IntegrationKind::Gitea, true, true, true, false, None),
1286            (IntegrationKind::Forgejo, true, true, true, false, None),
1287            (IntegrationKind::Linear, true, false, false, false, None),
1288            (IntegrationKind::Youtrack, true, false, false, false, None),
1289            (IntegrationKind::Redmine, true, false, false, false, None),
1290            (
1291                IntegrationKind::Gerrit,
1292                false,
1293                true,
1294                false,
1295                false,
1296                Some(Username),
1297            ),
1298            (
1299                IntegrationKind::LocalMarkdown,
1300                true,
1301                false,
1302                false,
1303                false,
1304                None,
1305            ),
1306        ];
1307        assert_eq!(table.len(), IntegrationKind::ALL.len());
1308        for (kind, issues, prs, ssh, org, account) in table {
1309            let c = kind.capabilities();
1310            assert_eq!(c.issues, issues, "{kind:?} issues");
1311            assert_eq!(c.pull_requests, prs, "{kind:?} pull_requests");
1312            assert_eq!(c.ssh_keys, ssh, "{kind:?} ssh_keys");
1313            assert_eq!(c.org, org, "{kind:?} org");
1314            assert_eq!(c.account, account, "{kind:?} account");
1315            assert!(!c.oauth, "{kind:?} oauth is off everywhere");
1316        }
1317    }
1318
1319    #[test]
1320    fn account_round_trips_and_is_skipped_when_empty() {
1321        let mut i = Integration::new(
1322            "jira",
1323            IntegrationKind::JiraCloud,
1324            "https://acme.atlassian.net",
1325        );
1326        assert!(!toml::to_string(&i).unwrap().contains("account"));
1327        i.account = "me@acme.com".into();
1328        let raw = toml::to_string(&i).unwrap();
1329        assert!(raw.contains("account = \"me@acme.com\""), "{raw}");
1330        assert_eq!(toml::from_str::<Integration>(&raw).unwrap(), i);
1331        // An old file without the field loads.
1332        let old = "id = \"x\"\nkind = \"jira_cloud\"\nurl = \"u\"\ntoken_ref = \"t\"\n";
1333        assert_eq!(toml::from_str::<Integration>(old).unwrap().account, "");
1334    }
1335
1336    #[test]
1337    fn radar_options_round_trip_and_an_old_file_has_none() {
1338        let mut i = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1339        assert!(!toml::to_string(&i).unwrap().contains("radar"));
1340        assert_eq!(i.radar_options(), IntegrationRadar::default());
1341        assert!(!i.radar_options().any_list());
1342        i.radar = Some(IntegrationRadar {
1343            review_requests: true,
1344            namespaces: vec!["acme".into(), "tools".into()],
1345            review_mode: RemoteReviewMode::Api,
1346            ..IntegrationRadar::default()
1347        });
1348        let raw = toml::to_string(&i).unwrap();
1349        assert!(raw.contains("[radar]"), "{raw}");
1350        assert!(raw.contains("review_mode = \"api\""), "{raw}");
1351        assert_eq!(toml::from_str::<Integration>(&raw).unwrap(), i);
1352        assert!(i.radar_options().any_list());
1353        // A table naming one key leaves the others off and the mode on ask.
1354        let old = "id = \"x\"\nkind = \"github\"\nurl = \"u\"\ntoken_ref = \"t\"\n[radar]\nassigned_issues = true\n";
1355        let radar = toml::from_str::<Integration>(old).unwrap().radar_options();
1356        assert!(radar.assigned_issues && !radar.review_requests && !radar.open_requests);
1357        assert_eq!(radar.review_mode, RemoteReviewMode::Ask);
1358        assert_eq!(
1359            RemoteReviewMode::parse(" API "),
1360            Some(RemoteReviewMode::Api)
1361        );
1362        assert_eq!(RemoteReviewMode::parse("nope"), None);
1363    }
1364
1365    #[test]
1366    fn namespaces_read_the_old_comma_string_and_save_as_a_list() {
1367        let head = "id = \"x\"\nkind = \"github\"\nurl = \"u\"\ntoken_ref = \"t\"\n[radar]\n";
1368        let load = |body: &str| {
1369            toml::from_str::<Integration>(&format!("{head}{body}"))
1370                .unwrap()
1371                .radar_options()
1372        };
1373        assert_eq!(
1374            load("namespaces = \"ptm, formation\"\n").namespaces,
1375            ["ptm", "formation"]
1376        );
1377        assert_eq!(load("namespaces = \"ptm\"\n").namespaces, ["ptm"]);
1378        assert_eq!(
1379            load("namespaces = [\"a\", \" b \", \"a\", \"\"]\n").namespaces,
1380            ["a", "b"]
1381        );
1382        assert!(!load("namespaces = [\"a\"]\n").namespaces_regex);
1383        assert!(load("namespaces = [\"a\"]\nnamespaces_regex = true\n").namespaces_regex);
1384        let mut i = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1385        i.radar = Some(load("namespaces = \"ptm, formation\"\n"));
1386        let raw = toml::to_string(&i).unwrap();
1387        assert!(
1388            raw.contains("namespaces = [\"ptm\", \"formation\"]"),
1389            "{raw}"
1390        );
1391        assert!(!raw.contains("namespaces_regex"), "{raw}");
1392    }
1393
1394    #[test]
1395    fn namespace_text_is_lines_and_commas_only_in_plain_mode() {
1396        assert_eq!(
1397            parse_namespace_text("a\n b ,c\n\na", false),
1398            ["a", "b", "c"]
1399        );
1400        assert_eq!(
1401            parse_namespace_text("^a{1,2}/\n  x  ", true),
1402            ["^a{1,2}/", "x"]
1403        );
1404    }
1405
1406    #[test]
1407    fn azure_org_parses_both_url_spellings() {
1408        let az = |url: &str| Integration::new("a", IntegrationKind::AzureDevops, url);
1409        assert_eq!(
1410            az("https://dev.azure.com/acme").azure_org().as_deref(),
1411            Some("acme")
1412        );
1413        assert_eq!(
1414            az("https://dev.azure.com/acme/").azure_org().as_deref(),
1415            Some("acme")
1416        );
1417        assert_eq!(
1418            az("https://acme.visualstudio.com").azure_org().as_deref(),
1419            Some("acme")
1420        );
1421        assert_eq!(az("https://dev.azure.com").azure_org(), None);
1422        let server = Integration::new(
1423            "s",
1424            IntegrationKind::AzureDevopsServer,
1425            "https://tfs.corp/tfs/Coll",
1426        );
1427        assert_eq!(server.azure_org(), None);
1428        let gh = Integration::new("g", IntegrationKind::Github, "https://dev.azure.com/acme");
1429        assert_eq!(gh.azure_org(), None);
1430        assert_eq!(
1431            normalize_azure_url("https://acme.visualstudio.com/"),
1432            "https://dev.azure.com/acme"
1433        );
1434        assert_eq!(
1435            normalize_azure_url("https://dev.azure.com/acme/"),
1436            "https://dev.azure.com/acme"
1437        );
1438    }
1439
1440    #[test]
1441    fn normalize_kind_leaves_the_new_kinds_alone() {
1442        for kind in [
1443            IntegrationKind::AzureDevopsServer,
1444            IntegrationKind::AzureDevops,
1445            IntegrationKind::Bitbucket,
1446            IntegrationKind::BitbucketDataCenter,
1447            IntegrationKind::JiraCloud,
1448            IntegrationKind::JiraDataCenter,
1449            IntegrationKind::Trello,
1450        ] {
1451            assert_eq!(migrated(kind.as_str(), "https://github.com"), kind);
1452            assert_eq!(migrated(kind.as_str(), "https://x.example.com"), kind);
1453        }
1454    }
1455
1456    #[test]
1457    fn the_api_base_of_the_new_kinds() {
1458        for (kind, url, want) in [
1459            (
1460                IntegrationKind::AzureDevops,
1461                "https://dev.azure.com/acme",
1462                "https://dev.azure.com/acme",
1463            ),
1464            (
1465                IntegrationKind::AzureDevops,
1466                "https://acme.visualstudio.com/",
1467                "https://dev.azure.com/acme",
1468            ),
1469            (
1470                IntegrationKind::AzureDevopsServer,
1471                "https://tfs.corp/tfs/DefaultCollection/",
1472                "https://tfs.corp/tfs/DefaultCollection",
1473            ),
1474            (
1475                IntegrationKind::Bitbucket,
1476                "https://bitbucket.org",
1477                "https://api.bitbucket.org/2.0",
1478            ),
1479            (
1480                IntegrationKind::Bitbucket,
1481                "http://127.0.0.1:9",
1482                "http://127.0.0.1:9/2.0",
1483            ),
1484            (
1485                IntegrationKind::BitbucketDataCenter,
1486                "https://bb.corp/",
1487                "https://bb.corp/rest/api/1.0",
1488            ),
1489            (
1490                IntegrationKind::JiraCloud,
1491                "https://acme.atlassian.net/",
1492                "https://acme.atlassian.net/rest/api/3",
1493            ),
1494            (
1495                IntegrationKind::JiraDataCenter,
1496                "https://jira.corp",
1497                "https://jira.corp/rest/api/2",
1498            ),
1499            (
1500                IntegrationKind::Trello,
1501                "https://trello.com",
1502                "https://api.trello.com/1",
1503            ),
1504            (
1505                IntegrationKind::Trello,
1506                "http://127.0.0.1:9",
1507                "http://127.0.0.1:9/1",
1508            ),
1509            (
1510                IntegrationKind::Linear,
1511                "https://linear.app",
1512                "https://api.linear.app",
1513            ),
1514            (
1515                IntegrationKind::Linear,
1516                "http://127.0.0.1:9",
1517                "http://127.0.0.1:9",
1518            ),
1519            (
1520                IntegrationKind::Youtrack,
1521                "https://acme.youtrack.cloud/",
1522                "https://acme.youtrack.cloud/api",
1523            ),
1524            (
1525                IntegrationKind::Redmine,
1526                "http://127.0.0.1:3002/",
1527                "http://127.0.0.1:3002",
1528            ),
1529            (
1530                IntegrationKind::Gerrit,
1531                "http://127.0.0.1:8081/",
1532                "http://127.0.0.1:8081/a",
1533            ),
1534        ] {
1535            assert_eq!(
1536                Integration::new("x", kind, url).api_base(),
1537                want,
1538                "{kind:?} {url}"
1539            );
1540        }
1541        let cloud = Integration::new(
1542            "j",
1543            IntegrationKind::JiraCloud,
1544            "https://acme.atlassian.net",
1545        );
1546        assert_eq!(
1547            cloud.api_base_v2().as_deref(),
1548            Some("https://acme.atlassian.net/rest/api/2")
1549        );
1550        let dc = Integration::new("j", IntegrationKind::JiraDataCenter, "https://jira.corp");
1551        assert_eq!(dc.api_base_v2(), None);
1552    }
1553
1554    #[test]
1555    fn the_token_link_per_kind() {
1556        let link = |kind: IntegrationKind| kind.token_help().expect("token help").link;
1557        assert!(
1558            matches!(link(IntegrationKind::Github), TokenLink::Path(p) if p.starts_with("/settings/tokens"))
1559        );
1560        assert!(matches!(
1561            link(IntegrationKind::AzureDevops),
1562            TokenLink::Path("/_usersSettings/tokens")
1563        ));
1564        assert!(
1565            matches!(link(IntegrationKind::JiraCloud), TokenLink::Absolute(u) if u.contains("id.atlassian.com"))
1566        );
1567        assert!(matches!(link(IntegrationKind::Trello), TokenLink::Trello));
1568        assert_eq!(
1569            IntegrationKind::Trello.token_help().unwrap().scopes,
1570            &["read", "write"]
1571        );
1572        // Trello has no link until the key is typed.
1573        let mut trello = Integration::new("t", IntegrationKind::Trello, "https://trello.com");
1574        assert_eq!(trello.token_link_url("https://trello.com"), None);
1575        trello.account = "KEY123".into();
1576        let url = trello.token_link_url("https://trello.com").unwrap();
1577        assert!(url.starts_with("https://trello.com/1/authorize?"), "{url}");
1578        assert!(
1579            url.contains("key=KEY123")
1580                && url.contains("scope=read,write")
1581                && url.contains("name=GitPoulpi"),
1582            "{url}"
1583        );
1584        let gl = Integration::new("g", IntegrationKind::Gitlab, "https://gitlab.com");
1585        assert!(gl
1586            .token_link_url("https://gitlab.com")
1587            .unwrap()
1588            .starts_with("https://gitlab.com/-/user_settings/personal_access_tokens"));
1589        let jira = Integration::new(
1590            "j",
1591            IntegrationKind::JiraCloud,
1592            "https://acme.atlassian.net",
1593        );
1594        assert_eq!(
1595            jira.token_link_url("https://acme.atlassian.net").as_deref(),
1596            Some("https://id.atlassian.com/manage-profile/security/api-tokens")
1597        );
1598    }
1599}