1use serde::{Deserialize, Serialize};
17
18#[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,
40 Redmine,
42 Gerrit,
45 LocalMarkdown,
48}
49
50#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum AccountField {
77 Email,
79 ApiKey,
81 Username,
83}
84
85#[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 pub oauth: bool,
95 pub needs_host: bool,
97 pub implemented: bool,
99 pub account: Option<AccountField>,
101 pub org: bool,
103 pub local_folder: bool,
106}
107
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum TokenLink {
111 Path(&'static str),
113 Absolute(&'static str),
115 Trello,
118}
119
120#[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 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 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 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 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 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 issues: !matches!(family, ApiFamily::Bitbucket | ApiFamily::Gerrit),
294 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 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 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 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 IntegrationKind::Linear => TokenHelp {
392 scopes: &["read", "write", "issues:create"],
393 link: TokenLink::Absolute("https://linear.app/settings/account/security"),
394 },
395 IntegrationKind::Youtrack => TokenHelp {
397 scopes: &["YouTrack"],
398 link: TokenLink::Path("/users/me?tab=account-security"),
399 },
400 IntegrationKind::Redmine => TokenHelp {
402 scopes: &["REST API key"],
403 link: TokenLink::Path("/my/account"),
404 },
405 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#[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#[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 #[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#[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 #[serde(default, skip_serializing_if = "String::is_empty")]
476 pub name: String,
477 #[serde(default)]
478 pub auth: AuthMethod,
479 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
492 pub local: Option<LocalMarkdownSettings>,
493 #[serde(default, skip_serializing_if = "Option::is_none")]
496 pub radar: Option<IntegrationRadar>,
497 #[serde(default, skip_serializing_if = "RedmineMarkup::is_default")]
500 pub markup: RedmineMarkup,
501}
502
503#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(rename_all = "snake_case")]
507pub enum RedmineMarkup {
508 #[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 pub fn toggled(self) -> Self {
530 match self {
531 Self::Textile => Self::Markdown,
532 Self::Markdown => Self::Textile,
533 }
534 }
535}
536
537#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
539#[serde(rename_all = "snake_case")]
540pub enum RemoteReviewMode {
541 #[default]
543 Ask,
544 Clone,
546 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 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#[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 #[serde(
598 default,
599 deserialize_with = "de_namespaces",
600 skip_serializing_if = "Vec::is_empty"
601 )]
602 pub namespaces: Vec<String>,
603 #[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
615pub 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
631pub 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 pub fn any_list(&self) -> bool {
662 self.review_requests || self.open_requests || self.assigned_issues
663 }
664}
665
666#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
677pub struct LocalMarkdownSettings {
678 #[serde(default, skip_serializing_if = "Vec::is_empty")]
681 pub statuses: Vec<String>,
682 #[serde(default, skip_serializing_if = "String::is_empty")]
684 pub done_status: String,
685 #[serde(default, skip_serializing_if = "String::is_empty")]
687 pub reference_prefix: String,
688 #[serde(default, skip_serializing_if = "String::is_empty")]
691 pub me: String,
692}
693
694pub const DEFAULT_STATUSES: [&str; 3] = ["todo", "doing", "done"];
696
697impl LocalMarkdownSettings {
698 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 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 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 pub fn radar_options(&self) -> IntegrationRadar {
730 self.radar.clone().unwrap_or_default()
731 }
732
733 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 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 pub fn host(&self) -> Option<String> {
784 host_of(&self.url)
785 }
786
787 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 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 ApiFamily::Redmine => base.to_string(),
837 ApiFamily::Gerrit => format!("{base}/a"),
839 ApiFamily::LocalMarkdown => base.to_string(),
841 }
842 }
843
844 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 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 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 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
901pub 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
922fn 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 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 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 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 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 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 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}