1#![cfg_attr(
10 not(any(
11 feature = "github",
12 feature = "gitlab",
13 feature = "jira",
14 feature = "bitbucket",
15 feature = "azure-devops",
16 feature = "trello",
17 feature = "gitea",
18 feature = "linear",
19 feature = "youtrack",
20 feature = "redmine",
21 feature = "gerrit"
22 )),
23 allow(dead_code, unused_variables)
24)]
25
26use std::sync::Arc;
27
28#[cfg(any(feature = "github", feature = "gitlab"))]
29use serde::de::DeserializeOwned;
30
31#[cfg(feature = "bitbucket")]
32use crate::bitbucket::BitbucketClient;
33use crate::conversation::{
34 Comment, ConversationCaps, ItemKey, PageCursor, PostingIdentity, TimelineOpts, TimelinePage,
35};
36#[cfg(feature = "github")]
37use crate::github::GitHubClient;
38#[cfg(feature = "gitlab")]
39use crate::gitlab::GitLabClient;
40use crate::http::HttpTransport;
41#[cfg(any(feature = "github", feature = "gitlab"))]
42use crate::http::{HttpRequest, HttpResponse};
43use crate::integration::Integration;
44use crate::issue_flow::{CreatedBranch, IssueLinks, NewIssueBranch};
45use crate::metadata::{HostedLabel, HostedMilestone, IssueEdit, ItemMeta, MetaKind, PrEdit};
46use crate::model::{
47 HostedUser, IssueCreateOptions, IssueFilter, IssueSummary, PrFilter, PullRequestSummary,
48 TokenCheck,
49};
50use crate::project::{HostedProject, HostedSshKey};
51use crate::review::{
52 PullRequestDetail, ReviewCapabilities, ReviewComment, ReviewFile, ReviewOutcome,
53 ReviewSubmission, ReviewThread,
54};
55use crate::spec::{spec_for, CheckoutSource};
56use crate::{Error, Result};
57#[cfg(any(
58 feature = "github",
59 feature = "gitlab",
60 feature = "jira",
61 feature = "bitbucket",
62 feature = "azure-devops",
63 feature = "trello",
64 feature = "gitea",
65 feature = "linear",
66 feature = "youtrack",
67 feature = "redmine",
68 feature = "gerrit",
69 feature = "local-issues"
70))]
71use gitpoulpi_config::ApiFamily;
72
73#[cfg(any(feature = "github", feature = "gitlab", feature = "azure-devops"))]
77pub(crate) const PAGE_SIZE: u32 = 100;
78
79#[cfg(any(
83 feature = "github",
84 feature = "gitlab",
85 feature = "jira",
86 feature = "bitbucket",
87 feature = "azure-devops",
88 feature = "gitea",
89 feature = "linear",
90 feature = "youtrack",
91 feature = "redmine",
92 feature = "gerrit"
93))]
94pub(crate) const MAX_PAGES: u32 = 50;
95
96#[derive(Debug, Clone, Default, PartialEq, Eq)]
102pub struct NewPullRequest {
103 pub project: String,
104 pub source_branch: String,
105 pub target_branch: String,
106 pub title: String,
107 pub body: String,
108 pub draft: bool,
109 pub source_project: Option<String>,
112 pub assignees: Vec<String>,
114 pub reviewers: Vec<String>,
116 pub labels: Vec<String>,
118 pub milestone: Option<u64>,
120}
121
122impl NewPullRequest {
123 pub fn fork_source(&self) -> Option<&str> {
125 self.source_project
126 .as_deref()
127 .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case(&self.project))
128 }
129}
130
131#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
133pub struct CreatedPullRequest {
134 pub number: u64,
137 pub web_url: String,
138 #[serde(skip_serializing_if = "Option::is_none")]
141 pub warning: Option<String>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Default)]
146pub struct NewIssue {
147 pub project: String,
149 pub title: String,
150 pub body: String,
151 pub labels: Vec<String>,
152 pub issue_type: Option<String>,
154 pub list_id: Option<String>,
156 pub assignees: Vec<String>,
158 pub milestone: Option<u64>,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
164pub struct CreatedIssue {
165 pub number: u64,
167 pub web_url: String,
168 pub reference: String,
170}
171
172#[async_trait::async_trait]
173pub trait HostingClient: Send + Sync {
174 fn integration(&self) -> &Integration;
175
176 fn unsupported(&self, what: &str) -> Error {
180 Error::Unsupported(what.to_string())
181 }
182
183 async fn list_projects(&self) -> Result<Vec<HostedProject>>;
186
187 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>>;
191
192 async fn upload_ssh_key(&self, title: &str, public_key: &str) -> Result<HostedSshKey>;
195
196 async fn create_pull_request(&self, req: &NewPullRequest) -> Result<CreatedPullRequest>;
199
200 async fn current_user(&self) -> Result<HostedUser> {
202 Err(self.unsupported("current_user"))
203 }
204
205 async fn protected_branches(
210 &self,
211 _project: &str,
212 ) -> Result<crate::protection::ProtectedBranches> {
213 Err(self.unsupported("protected_branches"))
214 }
215
216 async fn check_token(&self) -> Result<TokenCheck> {
218 Err(self.unsupported("check_token"))
219 }
220
221 async fn list_pull_requests(
223 &self,
224 _project: &str,
225 _filter: &PrFilter,
226 ) -> Result<Vec<PullRequestSummary>> {
227 Err(self.unsupported("list_pull_requests"))
228 }
229
230 async fn pull_request_for_branch(
233 &self,
234 _project: &str,
235 _branch: &str,
236 ) -> Result<Option<PullRequestSummary>> {
237 Err(self.unsupported("pull_request_for_branch"))
238 }
239
240 async fn list_issues(
241 &self,
242 _project: &str,
243 _filter: &IssueFilter,
244 ) -> Result<Vec<IssueSummary>> {
245 Err(self.unsupported("list_issues"))
246 }
247
248 async fn create_issue(&self, _req: &NewIssue) -> Result<CreatedIssue> {
250 Err(self.unsupported("create_issue"))
251 }
252
253 async fn issue_create_options(&self, _project: &str) -> Result<IssueCreateOptions> {
256 Ok(IssueCreateOptions::default())
257 }
258
259 async fn delete_ssh_key(&self, _id: &str) -> Result<()> {
261 Err(self.unsupported("delete_ssh_key"))
262 }
263
264 fn review_capabilities(&self) -> ReviewCapabilities {
270 ReviewCapabilities::default()
271 }
272
273 async fn pull_request_detail(&self, _project: &str, _number: u64) -> Result<PullRequestDetail> {
276 Err(self.unsupported("pull_request_detail"))
277 }
278
279 async fn pull_request_detail_at(
282 &self,
283 project: &str,
284 number: u64,
285 _patch_set: Option<u32>,
286 ) -> Result<PullRequestDetail> {
287 self.pull_request_detail(project, number).await
288 }
289
290 async fn pull_request_files_at(
292 &self,
293 project: &str,
294 number: u64,
295 _patch_set: Option<u32>,
296 ) -> Result<Vec<ReviewFile>> {
297 self.pull_request_files(project, number).await
298 }
299
300 async fn pull_request_files_against(
304 &self,
305 project: &str,
306 number: u64,
307 patch_set: Option<u32>,
308 _base_patch_set: Option<u32>,
309 ) -> Result<Vec<ReviewFile>> {
310 self.pull_request_files_at(project, number, patch_set).await
311 }
312
313 async fn submit_change(&self, _project: &str, _number: u64) -> Result<()> {
316 Err(self.unsupported("submit_change"))
317 }
318
319 async fn abandon_change(
322 &self,
323 _project: &str,
324 _number: u64,
325 _message: Option<&str>,
326 ) -> Result<()> {
327 Err(self.unsupported("abandon_change"))
328 }
329
330 async fn pull_request_threads_at(
333 &self,
334 project: &str,
335 number: u64,
336 _patch_set: Option<u32>,
337 ) -> Result<Vec<ReviewThread>> {
338 self.pull_request_threads(project, number).await
339 }
340
341 async fn pull_request_files(&self, _project: &str, _number: u64) -> Result<Vec<ReviewFile>> {
343 Err(self.unsupported("pull_request_files"))
344 }
345
346 async fn pull_request_threads(
348 &self,
349 _project: &str,
350 _number: u64,
351 ) -> Result<Vec<ReviewThread>> {
352 Err(self.unsupported("pull_request_threads"))
353 }
354
355 async fn pull_request_conversation(
357 &self,
358 _project: &str,
359 _number: u64,
360 ) -> Result<Vec<ReviewComment>> {
361 Err(self.unsupported("pull_request_conversation"))
362 }
363
364 async fn pull_request_reviews(
367 &self,
368 _project: &str,
369 _number: u64,
370 ) -> Result<Vec<crate::review::SubmittedReview>> {
371 Err(self.unsupported("pull_request_reviews"))
372 }
373
374 async fn add_comment(
376 &self,
377 _project: &str,
378 _number: u64,
379 _body: &str,
380 ) -> Result<ReviewComment> {
381 Err(self.unsupported("add_comment"))
382 }
383
384 async fn reply_to_thread(
386 &self,
387 _project: &str,
388 _number: u64,
389 _thread_id: &str,
390 _body: &str,
391 ) -> Result<ReviewComment> {
392 Err(self.unsupported("reply_to_thread"))
393 }
394
395 async fn resolve_thread(
397 &self,
398 _project: &str,
399 _number: u64,
400 _thread_id: &str,
401 _resolved: bool,
402 ) -> Result<()> {
403 Err(self.unsupported("resolve_thread"))
404 }
405
406 async fn submit_review(
410 &self,
411 _project: &str,
412 _number: u64,
413 _review: &ReviewSubmission,
414 ) -> Result<ReviewOutcome> {
415 Err(self.unsupported("submit_review"))
416 }
417
418 fn conversation_caps(&self, _kind: crate::conversation::ItemKind) -> ConversationCaps {
423 ConversationCaps::NONE
424 }
425
426 async fn posting_identity(&self, _project: &str) -> Result<PostingIdentity> {
429 Err(self.unsupported("posting_identity"))
430 }
431
432 async fn item_timeline(
436 &self,
437 _project: &str,
438 _key: &ItemKey,
439 _older: Option<&PageCursor>,
440 _opts: &TimelineOpts,
441 ) -> Result<TimelinePage> {
442 Err(self.unsupported("item_timeline"))
443 }
444
445 async fn post_item_comment(
448 &self,
449 _project: &str,
450 _key: &ItemKey,
451 _body: &str,
452 _internal: bool,
453 ) -> Result<Comment> {
454 Err(self.unsupported("post_item_comment"))
455 }
456
457 async fn reply_in_discussion(
459 &self,
460 _project: &str,
461 _key: &ItemKey,
462 _discussion_id: &str,
463 _body: &str,
464 ) -> Result<Comment> {
465 Err(self.unsupported("reply_in_discussion"))
466 }
467
468 async fn edit_item_comment(
470 &self,
471 _project: &str,
472 _key: &ItemKey,
473 _comment_id: &str,
474 _body: &str,
475 ) -> Result<Comment> {
476 Err(self.unsupported("edit_item_comment"))
477 }
478
479 async fn delete_item_comment(
481 &self,
482 _project: &str,
483 _key: &ItemKey,
484 _comment_id: &str,
485 ) -> Result<()> {
486 Err(self.unsupported("delete_item_comment"))
487 }
488
489 async fn create_issue_branch(&self, _req: &NewIssueBranch) -> Result<CreatedBranch> {
495 Err(self.unsupported("create_issue_branch"))
496 }
497
498 async fn issue_links(&self, _project: &str, _number: u64) -> Result<IssueLinks> {
500 Err(self.unsupported("issue_links"))
501 }
502
503 async fn branch_names(&self, _project: &str, _search: &str) -> Result<Vec<String>> {
506 Err(self.unsupported("branch_names"))
507 }
508
509 async fn project_members(&self, _project: &str, _query: &str) -> Result<Vec<HostedUser>> {
514 Err(self.unsupported("project_members"))
515 }
516
517 async fn project_labels(&self, _project: &str) -> Result<Vec<HostedLabel>> {
519 Err(self.unsupported("project_labels"))
520 }
521
522 async fn project_milestones(&self, _project: &str) -> Result<Vec<HostedMilestone>> {
524 Err(self.unsupported("project_milestones"))
525 }
526
527 async fn item_meta(&self, _project: &str, _number: u64, _kind: MetaKind) -> Result<ItemMeta> {
529 Err(self.unsupported("item_meta"))
530 }
531
532 async fn update_issue(&self, _project: &str, _number: u64, _edit: &IssueEdit) -> Result<()> {
534 Err(self.unsupported("update_issue"))
535 }
536
537 async fn issue_statuses(&self, _project: &str) -> Result<Vec<String>> {
542 Ok(Vec::new())
543 }
544
545 async fn set_issue_status(&self, _project: &str, _number: u64, _status: &str) -> Result<()> {
547 Err(self.unsupported("set_issue_status"))
548 }
549
550 async fn set_issue_state(&self, _project: &str, _number: u64, _closed: bool) -> Result<()> {
554 Err(self.unsupported("set_issue_state"))
555 }
556
557 fn board_source(&self) -> crate::board::BoardSource {
563 crate::board::BoardSource::OpenClosed
564 }
565
566 async fn move_issue(
571 &self,
572 project: &str,
573 issue: &IssueSummary,
574 spec: &crate::board::BoardSpec,
575 to: &crate::board::BoardColumn,
576 ) -> Result<()> {
577 let plan = crate::board::plan_move(spec, issue, to)?;
578 if let Some(_list) = &plan.list {
579 return Err(self.unsupported("move_issue"));
580 }
581 if let Some(status) = &plan.status {
582 self.set_issue_status(project, issue.number, status).await?;
583 }
584 if let Some(labels) = &plan.labels {
585 let edit = IssueEdit {
586 labels: Some(labels.clone()),
587 ..IssueEdit::default()
588 };
589 self.update_issue(project, issue.number, &edit).await?;
590 }
591 if let Some(closed) = plan.closed {
592 self.set_issue_state(project, issue.number, closed).await?;
593 }
594 Ok(())
595 }
596
597 async fn merge_pull_request(
600 &self,
601 _project: &str,
602 _number: u64,
603 _method: crate::request_actions::MergeMethod,
604 ) -> Result<()> {
605 Err(self.unsupported("merge_pull_request"))
606 }
607
608 async fn mark_pull_request_ready(&self, _project: &str, _number: u64) -> Result<()> {
610 Err(self.unsupported("mark_pull_request_ready"))
611 }
612
613 async fn close_pull_request(&self, _project: &str, _number: u64) -> Result<()> {
615 Err(self.unsupported("close_pull_request"))
616 }
617
618 async fn update_pull_request(
621 &self,
622 _project: &str,
623 _number: u64,
624 _edit: &PrEdit,
625 ) -> Result<()> {
626 Err(self.unsupported("update_pull_request"))
627 }
628
629 async fn pull_request_diff(
635 &self,
636 _project: &str,
637 _number: u64,
638 _patch_set: Option<u32>,
639 _compare: Option<u32>,
640 ) -> Result<Vec<crate::review::ApiFileDiff>> {
641 Err(self.unsupported("pull_request_diff"))
642 }
643
644 async fn pull_request_commits(
646 &self,
647 _project: &str,
648 _number: u64,
649 ) -> Result<Vec<crate::review::ApiCommit>> {
650 Err(self.unsupported("pull_request_commits"))
651 }
652
653 async fn commit_diff(
655 &self,
656 _project: &str,
657 _sha: &str,
658 ) -> Result<Vec<crate::review::ApiFileDiff>> {
659 Err(self.unsupported("commit_diff"))
660 }
661
662 async fn file_content(
666 &self,
667 _project: &str,
668 _path: &str,
669 _rev: Option<&str>,
670 ) -> Result<Option<Vec<u8>>> {
671 Err(self.unsupported("file_content"))
672 }
673
674 async fn account_items(
679 &self,
680 _query: &crate::account::AccountQuery,
681 ) -> Result<crate::account::AccountItems> {
682 Err(self.unsupported("account_items"))
683 }
684}
685
686pub fn client_for(
698 integration: Integration,
699 token: String,
700 transport: Arc<dyn HttpTransport>,
701 gate: &crate::trust::TrustGate,
702) -> Result<Box<dyn HostingClient>> {
703 let transport = if integration.kind.capabilities().local_folder {
704 transport
705 } else {
706 let admitted = gate.admit(&integration)?;
707 let guarded = Arc::new(crate::trust::GuardedTransport::new(
708 transport,
709 admitted.subject,
710 admitted.record.origin.clone(),
711 admitted.origins,
712 admitted.record.tls.clone(),
713 )) as Arc<dyn HttpTransport>;
714 #[cfg(feature = "github")]
717 let guarded = if integration.kind.family() == ApiFamily::Github {
718 Arc::new(crate::scoped_transport::ScopedTransport::new(
719 guarded,
720 integration.id.clone(),
721 )) as Arc<dyn HttpTransport>
722 } else {
723 guarded
724 };
725 guarded
726 };
727 Ok(crate::assignment_guard::AssignmentGuard::wrap(
728 build_client(integration, token, transport),
729 ))
730}
731
732fn build_client(
733 integration: Integration,
734 token: String,
735 transport: Arc<dyn HttpTransport>,
736) -> Box<dyn HostingClient> {
737 match integration.kind.family() {
738 #[cfg(feature = "github")]
739 ApiFamily::Github => Box::new(GitHubClient::new(integration, token, transport)),
740 #[cfg(feature = "gitlab")]
741 ApiFamily::Gitlab => Box::new(GitLabClient::new(integration, token, transport)),
742 #[cfg(feature = "jira")]
743 ApiFamily::Jira => Box::new(crate::jira::JiraClient::new(integration, token, transport)),
744 #[cfg(feature = "bitbucket")]
745 ApiFamily::Bitbucket if integration.kind == crate::IntegrationKind::Bitbucket => {
746 Box::new(BitbucketClient::new(integration, token, transport))
747 }
748 #[cfg(feature = "bitbucket")]
749 ApiFamily::Bitbucket => Box::new(crate::bitbucket::dc::BitbucketDcClient::new(
750 integration,
751 token,
752 transport,
753 )),
754 #[cfg(feature = "azure-devops")]
755 ApiFamily::AzureDevops => Box::new(crate::azure_devops::AzureDevopsClient::new(
756 integration,
757 token,
758 transport,
759 )),
760 #[cfg(feature = "trello")]
761 ApiFamily::Trello => Box::new(crate::trello::TrelloClient::new(
762 integration,
763 token,
764 transport,
765 )),
766 #[cfg(feature = "gitea")]
767 ApiFamily::Gitea => Box::new(crate::gitea::GiteaClient::new(
768 integration,
769 token,
770 transport,
771 )),
772 #[cfg(feature = "linear")]
773 ApiFamily::Linear => Box::new(crate::linear::LinearClient::new(
774 integration,
775 token,
776 transport,
777 )),
778 #[cfg(feature = "youtrack")]
779 ApiFamily::YouTrack => Box::new(crate::youtrack::YouTrackClient::new(
780 integration,
781 token,
782 transport,
783 )),
784 #[cfg(feature = "redmine")]
785 ApiFamily::Redmine => Box::new(crate::redmine::RedmineClient::new(
786 integration,
787 token,
788 transport,
789 )),
790 #[cfg(feature = "gerrit")]
791 ApiFamily::Gerrit => Box::new(crate::gerrit::GerritClient::new(
792 integration,
793 token,
794 transport,
795 )),
796 #[cfg(feature = "local-issues")]
797 ApiFamily::LocalMarkdown => {
798 Box::new(crate::local_markdown::LocalMarkdownClient::new(integration))
799 }
800 #[allow(unreachable_patterns)]
802 _ => Box::new(UnsupportedClient { integration }),
803 }
804}
805
806pub struct UnsupportedClient {
809 integration: Integration,
810}
811
812#[async_trait::async_trait]
813impl HostingClient for UnsupportedClient {
814 fn integration(&self) -> &Integration {
815 &self.integration
816 }
817 fn unsupported(&self, _what: &str) -> Error {
818 Error::NotImplemented(self.integration.kind.label().to_string())
819 }
820 async fn list_projects(&self) -> Result<Vec<HostedProject>> {
821 Err(self.unsupported("list_projects"))
822 }
823 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
824 Err(self.unsupported("list_ssh_keys"))
825 }
826 async fn upload_ssh_key(&self, _title: &str, _public_key: &str) -> Result<HostedSshKey> {
827 Err(self.unsupported("upload_ssh_key"))
828 }
829 async fn create_pull_request(&self, _req: &NewPullRequest) -> Result<CreatedPullRequest> {
830 Err(self.unsupported("create_pull_request"))
831 }
832}
833
834#[cfg(any(feature = "github", feature = "gitlab"))]
840pub(crate) async fn fetch_pages<T: DeserializeOwned>(
841 transport: &dyn HttpTransport,
842 request: impl Fn(String) -> HttpRequest,
843 base_url: &str,
844 what: &str,
845) -> Result<Vec<T>> {
846 fetch_pages_with(transport, request, base_url, what, |r| r.json()).await
847}
848
849#[cfg(any(feature = "github", feature = "gitlab"))]
852pub(crate) async fn fetch_pages_with<T>(
853 transport: &dyn HttpTransport,
854 request: impl Fn(String) -> HttpRequest,
855 base_url: &str,
856 what: &str,
857 rows: impl Fn(&HttpResponse) -> Result<Vec<T>>,
858) -> Result<Vec<T>> {
859 let mut out = Vec::new();
860 for page in 1..=MAX_PAGES {
861 let url = format!("{base_url}&per_page={PAGE_SIZE}&page={page}");
862 let response = transport.send(request(url)).await?;
863 response.error_for_status(what)?;
864 let page_rows = rows(&response)?;
865 let count = page_rows.len();
866 out.extend(page_rows);
867 if count < PAGE_SIZE as usize {
868 break;
869 }
870 }
871 Ok(out)
872}
873
874#[cfg_attr(
878 not(any(
879 feature = "github",
880 feature = "gitlab",
881 feature = "jira",
882 feature = "bitbucket",
883 feature = "azure-devops",
884 feature = "trello",
885 feature = "gitea",
886 feature = "youtrack",
887 feature = "redmine",
888 feature = "gerrit",
889 feature = "local-issues"
890 )),
891 allow(dead_code)
892)]
893pub(crate) fn encode_component(text: &str) -> String {
894 let mut out = String::with_capacity(text.len());
895 for b in text.bytes() {
896 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
897 out.push(b as char);
898 } else {
899 out.push_str(&format!("%{b:02X}"));
900 }
901 }
902 out
903}
904
905pub use crate::spec::web_base;
906
907pub fn pull_request_web_url(
909 integration: &Integration,
910 project: &str,
911 number: u64,
912) -> Option<String> {
913 let base = web_base(integration)?;
914 (spec_for(integration.kind.family()).pr_web_url)(&base, project, number)
915}
916
917pub fn pull_request_head_ref(
923 kind: crate::IntegrationKind,
924 number: u64,
925) -> Option<(String, String)> {
926 let probe = PullRequestSummary {
927 number,
928 iid_label: String::new(),
929 title: String::new(),
930 state: crate::model::PullRequestState::Open,
931 source_branch: String::new(),
932 target_branch: String::new(),
933 source_project: None,
934 author: String::new(),
935 web_url: String::new(),
936 updated_at: String::new(),
937 review_requested: false,
938 assignees: vec![],
939 reviewers: vec![],
940 checks: None,
941 has_conflicts: None,
942 };
943 match (spec_for(kind.family()).checkout)(&probe) {
944 CheckoutSource::HeadRef { remote_ref, local } => Some((remote_ref, local)),
945 CheckoutSource::Branch { .. } => None,
946 }
947}
948
949pub fn pull_request_edit_url(kind: Option<crate::IntegrationKind>, web_url: &str) -> String {
953 match kind {
954 Some(kind) => (spec_for(kind.family()).pr_edit_url)(web_url),
955 None => web_url.to_string(),
956 }
957}
958
959pub fn issue_web_url(integration: &Integration, project: &str, number: u64) -> Option<String> {
961 let base = web_base(integration)?;
962 (spec_for(integration.kind.family()).issue_web_url)(&base, project, &number.to_string())
963}
964
965pub fn token_create_url(integration: &Integration) -> Option<String> {
969 let base = web_base(integration)?;
970 integration.token_link_url(&base)
971}
972
973#[cfg(all(test, feature = "github", feature = "gitlab"))]
974mod tests {
975 use super::*;
976 use crate::http::RecordedTransport;
977 use crate::integration::IntegrationKind;
978 use std::sync::Arc;
979
980 fn integration(kind: IntegrationKind, url: &str) -> Integration {
981 Integration::new("h", kind, url)
982 }
983
984 fn block_on<F: std::future::Future>(f: F) -> F::Output {
985 tokio::runtime::Builder::new_current_thread()
986 .enable_all()
987 .build()
988 .unwrap()
989 .block_on(f)
990 }
991
992 fn header<'a>(request: &'a HttpRequest, name: &str) -> Option<&'a str> {
993 request
994 .headers
995 .iter()
996 .find(|(k, _)| k.eq_ignore_ascii_case(name))
997 .map(|(_, v)| v.as_str())
998 }
999
1000 const GITHUB_PAGE: &str = r#"[
1001 {"full_name":"me/one","name":"one","description":"first",
1002 "default_branch":"main","ssh_url":"git@github.com:me/one.git",
1003 "clone_url":"https://github.com/me/one.git",
1004 "html_url":"https://github.com/me/one","private":true}
1005 ]"#;
1006
1007 const GITHUB_ORGS_PAGE: &str = r#"[
1008 {"full_name":"me/secret","name":"secret","private":true,
1009 "clone_url":"https://github.com/me/secret.git"},
1010 {"full_name":"acme/site","name":"site","private":false,
1011 "clone_url":"https://github.com/acme/site.git"},
1012 {"full_name":"acme/internal","name":"internal","private":true,
1013 "clone_url":"https://github.com/acme/internal.git"}
1014 ]"#;
1015
1016 const GITLAB_GROUPS_PAGE: &str = r#"[
1017 {"id":1,"name":"mine","path_with_namespace":"kai/mine","visibility":"private"},
1018 {"id":2,"name":"open","path_with_namespace":"corp/tools/open","visibility":"public"},
1019 {"id":3,"name":"shared","path_with_namespace":"corp/tools/shared","visibility":"internal"}
1020 ]"#;
1021
1022 const GITLAB_PAGE: &str = r#"[
1023 {"id":42,"name":"one","path_with_namespace":"group/sub/one",
1024 "description":"first","default_branch":"main",
1025 "ssh_url_to_repo":"git@gitlab.example.com:group/sub/one.git",
1026 "http_url_to_repo":"https://gitlab.example.com/group/sub/one.git",
1027 "web_url":"https://gitlab.example.com/group/sub/one",
1028 "visibility":"private"}
1029 ]"#;
1030
1031 #[test]
1032 fn the_default_issue_create_options_are_empty_and_new_issue_has_no_type() {
1033 let transport = std::sync::Arc::new(RecordedTransport::new());
1034 let gh = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1035 let client = client_for(
1036 gh,
1037 "tok".into(),
1038 transport,
1039 &crate::trust::TrustGate::for_tests(),
1040 )
1041 .unwrap();
1042 let options = block_on(client.issue_create_options("me/thing")).unwrap();
1043 assert_eq!(options, IssueCreateOptions::default());
1044 let new = NewIssue::default();
1045 assert!(new.issue_type.is_none() && new.list_id.is_none());
1046 }
1047
1048 #[test]
1049 fn github_repositories_normalise_into_hosted_projects() {
1050 let transport = Arc::new(RecordedTransport::new().on("/user/repos", 200, GITHUB_PAGE));
1051 let client = client_for(
1052 integration(IntegrationKind::Github, "https://github.com"),
1053 "tok".into(),
1054 transport.clone(),
1055 &crate::trust::TrustGate::for_tests(),
1056 )
1057 .unwrap();
1058
1059 let projects = block_on(client.list_projects()).unwrap();
1060 assert_eq!(projects.len(), 1);
1061 assert_eq!(projects[0].full_name, "me/one");
1062 assert_eq!(projects[0].id, "me/one");
1063 assert_eq!(projects[0].integration_id, "h");
1064 assert!(projects[0].private);
1065 assert_eq!(
1066 projects[0].clone_url(true),
1067 Some("git@github.com:me/one.git")
1068 );
1069
1070 let request = &transport.requests()[0];
1071 assert!(request.url.starts_with("https://api.github.com/user/repos"));
1072 assert_eq!(header(request, "Authorization"), Some("Bearer tok"));
1073 assert!(
1074 request.url.contains("affiliation="),
1075 "the token's own repositories, not a public user listing: {}",
1076 request.url
1077 );
1078 }
1079
1080 #[test]
1081 fn gitlab_projects_normalise_into_hosted_projects() {
1082 let transport = Arc::new(RecordedTransport::new().on("/projects?", 200, GITLAB_PAGE));
1083 let client = client_for(
1084 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1085 "tok".into(),
1086 transport.clone(),
1087 &crate::trust::TrustGate::for_tests(),
1088 )
1089 .unwrap();
1090
1091 let projects = block_on(client.list_projects()).unwrap();
1092 assert_eq!(projects[0].full_name, "group/sub/one");
1093 assert_eq!(projects[0].id, "42");
1094 assert!(projects[0].private);
1095
1096 let request = &transport.requests()[0];
1097 assert!(
1098 request
1099 .url
1100 .starts_with("https://gitlab.example.com/api/v4/projects"),
1101 "a self-managed instance's api lives under its own url: {}",
1102 request.url
1103 );
1104 assert_eq!(header(request, "PRIVATE-TOKEN"), Some("tok"));
1105 assert!(
1106 request.url.contains("membership=true"),
1107 "without membership=true this lists every public project on the instance: {}",
1108 request.url
1109 );
1110 }
1111
1112 #[test]
1113 fn github_listing_carries_owner_and_private_flag_for_user_and_org_repos() {
1114 let transport = Arc::new(RecordedTransport::new().on("/user/repos", 200, GITHUB_ORGS_PAGE));
1115 let client = client_for(
1116 integration(IntegrationKind::Github, "https://github.com"),
1117 "tok".into(),
1118 transport.clone(),
1119 &crate::trust::TrustGate::for_tests(),
1120 )
1121 .unwrap();
1122 let projects = block_on(client.list_projects()).unwrap();
1123 let seen: Vec<(&str, bool)> = projects.iter().map(|p| (p.owner(), p.private)).collect();
1124 assert_eq!(seen, vec![("me", true), ("acme", false), ("acme", true)]);
1125 assert!(
1126 transport.requests()[0]
1127 .url
1128 .contains("affiliation=owner,collaborator,organization_member"),
1129 "organisation repositories are part of the listing"
1130 );
1131 }
1132
1133 #[test]
1134 fn gitlab_listing_carries_the_group_path_and_visibility() {
1135 let transport =
1136 Arc::new(RecordedTransport::new().on("/projects?", 200, GITLAB_GROUPS_PAGE));
1137 let client = client_for(
1138 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1139 "tok".into(),
1140 transport,
1141 &crate::trust::TrustGate::for_tests(),
1142 )
1143 .unwrap();
1144 let projects = block_on(client.list_projects()).unwrap();
1145 let seen: Vec<(&str, bool)> = projects.iter().map(|p| (p.owner(), p.private)).collect();
1146 assert_eq!(
1147 seen,
1148 vec![("kai", true), ("corp/tools", false), ("corp/tools", true)]
1149 );
1150 }
1151
1152 #[test]
1155 fn a_full_page_is_followed_by_another_request() {
1156 let full: String = format!(
1157 "[{}]",
1158 (0..PAGE_SIZE)
1159 .map(|n| format!(
1160 r#"{{"id":{n},"name":"p{n}","path_with_namespace":"g/p{n}","visibility":"public"}}"#
1161 ))
1162 .collect::<Vec<_>>()
1163 .join(",")
1164 );
1165 let transport = Arc::new(RecordedTransport::new().on("&page=1", 200, &full).on(
1166 "&page=2",
1167 200,
1168 GITLAB_PAGE,
1169 ));
1170 let client = client_for(
1171 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1172 "tok".into(),
1173 transport.clone(),
1174 &crate::trust::TrustGate::for_tests(),
1175 )
1176 .unwrap();
1177
1178 let projects = block_on(client.list_projects()).unwrap();
1179 assert_eq!(projects.len(), PAGE_SIZE as usize + 1);
1180 assert_eq!(transport.requests().len(), 2, "must stop on a short page");
1181 }
1182
1183 #[test]
1187 fn a_rejected_token_is_an_unauthorized_error_not_an_empty_list() {
1188 let transport = Arc::new(RecordedTransport::new().on(
1189 "/user/repos",
1190 401,
1191 r#"{"message":"Bad credentials"}"#,
1192 ));
1193 let client = client_for(
1194 integration(IntegrationKind::Github, "https://github.com"),
1195 "stale".into(),
1196 transport,
1197 &crate::trust::TrustGate::for_tests(),
1198 )
1199 .unwrap();
1200
1201 let err = block_on(client.list_projects()).unwrap_err();
1202 assert!(matches!(err, crate::Error::Unauthorized { .. }));
1203 assert!(err.to_string().contains("Bad credentials"));
1204 }
1205
1206 #[test]
1207 fn uploading_a_key_sends_the_hosts_own_field_names() {
1208 for (kind, url, fragment) in [
1209 (
1210 IntegrationKind::Github,
1211 "https://github.com",
1212 "api.github.com",
1213 ),
1214 (
1215 IntegrationKind::Gitlab,
1216 "https://gitlab.example.com",
1217 "gitlab.example.com/api/v4",
1218 ),
1219 ] {
1220 let transport = Arc::new(RecordedTransport::new().on(
1221 "/user/keys",
1222 201,
1223 r#"{"id":7,"title":"laptop","key":"ssh-ed25519 AAAA laptop"}"#,
1224 ));
1225 let client = client_for(
1226 integration(kind, url),
1227 "tok".into(),
1228 transport.clone(),
1229 &crate::trust::TrustGate::for_tests(),
1230 )
1231 .unwrap();
1232
1233 let key =
1234 block_on(client.upload_ssh_key("laptop", "ssh-ed25519 AAAA laptop\n")).unwrap();
1235 assert_eq!(key.id, "7");
1236 assert_eq!(key.title, "laptop");
1237
1238 let request = &transport.requests()[0];
1239 assert!(request.url.contains(fragment), "{}", request.url);
1240 let body: serde_json::Value =
1241 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1242 assert_eq!(body["title"], "laptop");
1243 assert_eq!(
1244 body["key"], "ssh-ed25519 AAAA laptop",
1245 "the trailing newline must be trimmed - both hosts reject it"
1246 );
1247 }
1248 }
1249
1250 fn new_pr(project: &str) -> NewPullRequest {
1251 NewPullRequest {
1252 project: project.into(),
1253 source_branch: "feature".into(),
1254 target_branch: "main".into(),
1255 title: "Add feature".into(),
1256 body: "does the thing".into(),
1257 draft: false,
1258 source_project: None,
1259 ..Default::default()
1260 }
1261 }
1262
1263 #[test]
1264 fn github_pull_request_sends_head_base_and_returns_html_url() {
1265 let transport = Arc::new(RecordedTransport::new().on(
1266 "/pulls",
1267 201,
1268 r#"{"number":42,"html_url":"https://github.com/me/thing/pull/42"}"#,
1269 ));
1270 let client = client_for(
1271 integration(IntegrationKind::Github, "https://github.com"),
1272 "tok".into(),
1273 transport.clone(),
1274 &crate::trust::TrustGate::for_tests(),
1275 )
1276 .unwrap();
1277
1278 let created = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap();
1279 assert_eq!(created.number, 42);
1280 assert_eq!(created.web_url, "https://github.com/me/thing/pull/42");
1281
1282 let request = &transport.requests()[0];
1283 assert!(
1284 request.url.ends_with("/repos/me/thing/pulls"),
1285 "{}",
1286 request.url
1287 );
1288 let body: serde_json::Value =
1289 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1290 assert_eq!(body["head"], "feature");
1291 assert_eq!(body["base"], "main");
1292 assert_eq!(body["title"], "Add feature");
1293 assert_eq!(body["draft"], false);
1294 }
1295
1296 #[test]
1297 fn gitlab_merge_request_url_encodes_the_project_path() {
1298 let transport = Arc::new(RecordedTransport::new().on(
1299 "/merge_requests",
1300 201,
1301 r#"{"iid":7,"web_url":"https://gitlab.example.com/group/sub/proj/-/merge_requests/7"}"#,
1302 ));
1303 let client = client_for(
1304 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1305 "tok".into(),
1306 transport.clone(),
1307 &crate::trust::TrustGate::for_tests(),
1308 )
1309 .unwrap();
1310
1311 let mut req = new_pr("group/sub/proj");
1312 req.draft = true;
1313 let created = block_on(client.create_pull_request(&req)).unwrap();
1314 assert_eq!(created.number, 7);
1315 assert_eq!(
1316 created.web_url,
1317 "https://gitlab.example.com/group/sub/proj/-/merge_requests/7"
1318 );
1319
1320 let request = &transport.requests()[0];
1321 assert!(
1322 request
1323 .url
1324 .contains("/projects/group%2Fsub%2Fproj/merge_requests"),
1325 "{}",
1326 request.url
1327 );
1328 let body: serde_json::Value =
1329 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1330 assert_eq!(body["source_branch"], "feature");
1331 assert_eq!(body["target_branch"], "main");
1332 assert_eq!(
1333 body["title"], "Draft: Add feature",
1334 "GitLab marks drafts by title prefix"
1335 );
1336 }
1337
1338 #[test]
1339 fn a_fork_pull_request_names_the_fork_owner_on_github() {
1340 let transport = Arc::new(RecordedTransport::new().on(
1341 "/pulls",
1342 201,
1343 r#"{"number":3,"html_url":"https://github.com/up/thing/pull/3"}"#,
1344 ));
1345 let client = client_for(
1346 integration(IntegrationKind::Github, "https://github.com"),
1347 "tok".into(),
1348 transport.clone(),
1349 &crate::trust::TrustGate::for_tests(),
1350 )
1351 .unwrap();
1352 let mut req = new_pr("up/thing");
1353 req.source_project = Some("me/thing".into());
1354 block_on(client.create_pull_request(&req)).unwrap();
1355 let request = &transport.requests()[0];
1356 assert!(
1357 request.url.ends_with("/repos/up/thing/pulls"),
1358 "{}",
1359 request.url
1360 );
1361 let body: serde_json::Value =
1362 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1363 assert_eq!(body["head"], "me:feature");
1364 let mut same = new_pr("up/thing");
1366 same.source_project = Some("UP/thing".into());
1367 assert_eq!(same.fork_source(), None);
1368 }
1369
1370 #[test]
1371 fn a_fork_merge_request_is_posted_from_the_source_project_with_the_target_id() {
1372 let transport = Arc::new(
1373 RecordedTransport::new()
1374 .on(
1375 "/merge_requests",
1376 201,
1377 r#"{"iid":9,"web_url":"https://g.example.com/up/thing/-/merge_requests/9"}"#,
1378 )
1379 .on("/projects/up%2Fthing", 200, r#"{"id":77}"#),
1380 );
1381 let client = client_for(
1382 integration(IntegrationKind::Gitlab, "https://g.example.com"),
1383 "tok".into(),
1384 transport.clone(),
1385 &crate::trust::TrustGate::for_tests(),
1386 )
1387 .unwrap();
1388 let mut req = new_pr("up/thing");
1389 req.source_project = Some("me/thing".into());
1390 let created = block_on(client.create_pull_request(&req)).unwrap();
1391 assert_eq!(created.number, 9);
1392 let requests = transport.requests();
1393 let post = requests.last().unwrap();
1394 assert!(
1395 post.url.contains("/projects/me%2Fthing/merge_requests"),
1396 "{}",
1397 post.url
1398 );
1399 let body: serde_json::Value = serde_json::from_str(post.body.as_deref().unwrap()).unwrap();
1400 assert_eq!(body["target_project_id"], 77);
1401 }
1402
1403 #[test]
1407 fn an_existing_pull_request_surfaces_the_hosts_message() {
1408 let transport = Arc::new(RecordedTransport::new().on(
1409 "/pulls",
1410 422,
1411 r#"{"message":"Validation Failed","errors":[{"message":"A pull request already exists for me:feature."}]}"#,
1412 ));
1413 let client = client_for(
1414 integration(IntegrationKind::Github, "https://github.com"),
1415 "tok".into(),
1416 transport,
1417 &crate::trust::TrustGate::for_tests(),
1418 )
1419 .unwrap();
1420
1421 let err = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap_err();
1422 assert!(matches!(err, crate::Error::Api { status: 422, .. }));
1423 assert!(err.to_string().contains("Validation Failed"), "{err}");
1424 }
1425
1426 #[test]
1430 fn create_pull_request_401_and_403_map_to_the_existing_errors() {
1431 for (status, want_unauthorized) in [(401, true), (403, false)] {
1432 let transport =
1433 Arc::new(RecordedTransport::new().on("/pulls", status, r#"{"message":"nope"}"#));
1434 let client = client_for(
1435 integration(IntegrationKind::Github, "https://github.com"),
1436 "tok".into(),
1437 transport,
1438 &crate::trust::TrustGate::for_tests(),
1439 )
1440 .unwrap();
1441 let err = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap_err();
1442 if want_unauthorized {
1443 assert!(matches!(err, crate::Error::Unauthorized { .. }));
1444 } else {
1445 assert!(matches!(err, crate::Error::Forbidden { .. }));
1446 }
1447 }
1448 }
1449
1450 #[test]
1451 fn existing_keys_can_be_listed_so_a_duplicate_upload_is_avoidable() {
1452 let transport = Arc::new(RecordedTransport::new().on(
1453 "/user/keys",
1454 200,
1455 r#"[{"id":7,"title":"laptop","key":"ssh-ed25519 AAAA laptop"}]"#,
1456 ));
1457 let client = client_for(
1458 integration(IntegrationKind::Github, "https://github.com"),
1459 "tok".into(),
1460 transport,
1461 &crate::trust::TrustGate::for_tests(),
1462 )
1463 .unwrap();
1464 let keys = block_on(client.list_ssh_keys()).unwrap();
1465 assert_eq!(keys[0].title, "laptop");
1466 }
1467
1468 #[test]
1471 fn new_operations_default_to_unsupported() {
1472 struct Old(Integration);
1473 #[async_trait::async_trait]
1474 impl HostingClient for Old {
1475 fn integration(&self) -> &Integration {
1476 &self.0
1477 }
1478 async fn list_projects(&self) -> Result<Vec<HostedProject>> {
1479 Ok(vec![])
1480 }
1481 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
1482 Ok(vec![])
1483 }
1484 async fn upload_ssh_key(&self, _: &str, _: &str) -> Result<HostedSshKey> {
1485 unreachable!()
1486 }
1487 async fn create_pull_request(&self, _: &NewPullRequest) -> Result<CreatedPullRequest> {
1488 unreachable!()
1489 }
1490 }
1491 let old = Old(integration(IntegrationKind::Github, "https://github.com"));
1492 assert!(matches!(
1493 block_on(old.current_user()).unwrap_err(),
1494 Error::Unsupported(_)
1495 ));
1496 assert!(matches!(
1497 block_on(old.delete_ssh_key("1")).unwrap_err(),
1498 Error::Unsupported(_)
1499 ));
1500 assert!(matches!(
1501 block_on(old.pull_request_for_branch("a/b", "x")).unwrap_err(),
1502 Error::Unsupported(_)
1503 ));
1504 }
1505
1506 #[test]
1507 fn pull_request_heads_live_in_the_hosts_special_refs() {
1508 assert_eq!(
1509 pull_request_head_ref(IntegrationKind::Github, 7),
1510 Some(("refs/pull/7/head".into(), "pr/7".into()))
1511 );
1512 assert_eq!(
1513 pull_request_head_ref(IntegrationKind::GitlabSelfManaged, 7),
1514 Some(("refs/merge-requests/7/head".into(), "mr/7".into()))
1515 );
1516 }
1517
1518 #[test]
1519 fn web_url_helpers_per_family() {
1520 let gh = integration(IntegrationKind::Github, "https://github.com/");
1521 assert_eq!(
1522 pull_request_web_url(&gh, "me/thing", 12).as_deref(),
1523 Some("https://github.com/me/thing/pull/12")
1524 );
1525 assert_eq!(
1526 issue_web_url(&gh, "me/thing", 3).as_deref(),
1527 Some("https://github.com/me/thing/issues/3")
1528 );
1529 let ghe = integration(IntegrationKind::GithubEnterprise, "https://ghe.example.com");
1530 assert_eq!(
1531 pull_request_web_url(&ghe, "o/r", 1).as_deref(),
1532 Some("https://ghe.example.com/o/r/pull/1")
1533 );
1534 let gl = integration(
1535 IntegrationKind::GitlabSelfManaged,
1536 "https://gitlab.example.com",
1537 );
1538 assert_eq!(
1539 pull_request_web_url(&gl, "g/sub/p", 53).as_deref(),
1540 Some("https://gitlab.example.com/g/sub/p/-/merge_requests/53")
1541 );
1542 assert_eq!(
1543 issue_web_url(&gl, "g/sub/p", 12).as_deref(),
1544 Some("https://gitlab.example.com/g/sub/p/-/issues/12")
1545 );
1546 let jira = integration(IntegrationKind::JiraCloud, "https://x.atlassian.net");
1547 assert_eq!(pull_request_web_url(&jira, "p", 1), None);
1548 }
1549
1550 #[test]
1551 fn the_token_create_url_needs_a_host_and_a_token_flow() {
1552 assert_eq!(
1553 token_create_url(&integration(IntegrationKind::Github, "")).as_deref(),
1554 Some("https://github.com/settings/tokens/new?description=GitPoulpi&scopes=repo,read:user,admin:public_key")
1555 );
1556 assert_eq!(
1557 token_create_url(&integration(
1558 IntegrationKind::GitlabSelfManaged,
1559 "https://gitlab.example.com/"
1560 ))
1561 .as_deref(),
1562 Some("https://gitlab.example.com/-/user_settings/personal_access_tokens?name=GitPoulpi&scopes=api,read_user")
1563 );
1564 assert_eq!(
1565 token_create_url(&integration(IntegrationKind::GitlabSelfManaged, "")),
1566 None
1567 );
1568 assert_eq!(
1569 token_create_url(&integration(IntegrationKind::Trello, "")),
1570 None
1571 );
1572 }
1573}