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 update_pull_request(
600 &self,
601 _project: &str,
602 _number: u64,
603 _edit: &PrEdit,
604 ) -> Result<()> {
605 Err(self.unsupported("update_pull_request"))
606 }
607
608 async fn pull_request_diff(
614 &self,
615 _project: &str,
616 _number: u64,
617 _patch_set: Option<u32>,
618 _compare: Option<u32>,
619 ) -> Result<Vec<crate::review::ApiFileDiff>> {
620 Err(self.unsupported("pull_request_diff"))
621 }
622
623 async fn pull_request_commits(
625 &self,
626 _project: &str,
627 _number: u64,
628 ) -> Result<Vec<crate::review::ApiCommit>> {
629 Err(self.unsupported("pull_request_commits"))
630 }
631
632 async fn commit_diff(
634 &self,
635 _project: &str,
636 _sha: &str,
637 ) -> Result<Vec<crate::review::ApiFileDiff>> {
638 Err(self.unsupported("commit_diff"))
639 }
640
641 async fn file_content(
645 &self,
646 _project: &str,
647 _path: &str,
648 _rev: Option<&str>,
649 ) -> Result<Option<Vec<u8>>> {
650 Err(self.unsupported("file_content"))
651 }
652
653 async fn account_items(
658 &self,
659 _query: &crate::account::AccountQuery,
660 ) -> Result<crate::account::AccountItems> {
661 Err(self.unsupported("account_items"))
662 }
663}
664
665pub fn client_for(
677 integration: Integration,
678 token: String,
679 transport: Arc<dyn HttpTransport>,
680 gate: &crate::trust::TrustGate,
681) -> Result<Box<dyn HostingClient>> {
682 let transport = if integration.kind.capabilities().local_folder {
683 transport
684 } else {
685 let admitted = gate.admit(&integration)?;
686 let guarded = Arc::new(crate::trust::GuardedTransport::new(
687 transport,
688 admitted.subject,
689 admitted.record.origin.clone(),
690 admitted.origins,
691 admitted.record.tls.clone(),
692 )) as Arc<dyn HttpTransport>;
693 #[cfg(feature = "github")]
696 let guarded = if integration.kind.family() == ApiFamily::Github {
697 Arc::new(crate::scoped_transport::ScopedTransport::new(
698 guarded,
699 integration.id.clone(),
700 )) as Arc<dyn HttpTransport>
701 } else {
702 guarded
703 };
704 guarded
705 };
706 Ok(crate::assignment_guard::AssignmentGuard::wrap(
707 build_client(integration, token, transport),
708 ))
709}
710
711fn build_client(
712 integration: Integration,
713 token: String,
714 transport: Arc<dyn HttpTransport>,
715) -> Box<dyn HostingClient> {
716 match integration.kind.family() {
717 #[cfg(feature = "github")]
718 ApiFamily::Github => Box::new(GitHubClient::new(integration, token, transport)),
719 #[cfg(feature = "gitlab")]
720 ApiFamily::Gitlab => Box::new(GitLabClient::new(integration, token, transport)),
721 #[cfg(feature = "jira")]
722 ApiFamily::Jira => Box::new(crate::jira::JiraClient::new(integration, token, transport)),
723 #[cfg(feature = "bitbucket")]
724 ApiFamily::Bitbucket if integration.kind == crate::IntegrationKind::Bitbucket => {
725 Box::new(BitbucketClient::new(integration, token, transport))
726 }
727 #[cfg(feature = "bitbucket")]
728 ApiFamily::Bitbucket => Box::new(crate::bitbucket::dc::BitbucketDcClient::new(
729 integration,
730 token,
731 transport,
732 )),
733 #[cfg(feature = "azure-devops")]
734 ApiFamily::AzureDevops => Box::new(crate::azure_devops::AzureDevopsClient::new(
735 integration,
736 token,
737 transport,
738 )),
739 #[cfg(feature = "trello")]
740 ApiFamily::Trello => Box::new(crate::trello::TrelloClient::new(
741 integration,
742 token,
743 transport,
744 )),
745 #[cfg(feature = "gitea")]
746 ApiFamily::Gitea => Box::new(crate::gitea::GiteaClient::new(
747 integration,
748 token,
749 transport,
750 )),
751 #[cfg(feature = "linear")]
752 ApiFamily::Linear => Box::new(crate::linear::LinearClient::new(
753 integration,
754 token,
755 transport,
756 )),
757 #[cfg(feature = "youtrack")]
758 ApiFamily::YouTrack => Box::new(crate::youtrack::YouTrackClient::new(
759 integration,
760 token,
761 transport,
762 )),
763 #[cfg(feature = "redmine")]
764 ApiFamily::Redmine => Box::new(crate::redmine::RedmineClient::new(
765 integration,
766 token,
767 transport,
768 )),
769 #[cfg(feature = "gerrit")]
770 ApiFamily::Gerrit => Box::new(crate::gerrit::GerritClient::new(
771 integration,
772 token,
773 transport,
774 )),
775 #[cfg(feature = "local-issues")]
776 ApiFamily::LocalMarkdown => {
777 Box::new(crate::local_markdown::LocalMarkdownClient::new(integration))
778 }
779 #[allow(unreachable_patterns)]
781 _ => Box::new(UnsupportedClient { integration }),
782 }
783}
784
785pub struct UnsupportedClient {
788 integration: Integration,
789}
790
791#[async_trait::async_trait]
792impl HostingClient for UnsupportedClient {
793 fn integration(&self) -> &Integration {
794 &self.integration
795 }
796 fn unsupported(&self, _what: &str) -> Error {
797 Error::NotImplemented(self.integration.kind.label().to_string())
798 }
799 async fn list_projects(&self) -> Result<Vec<HostedProject>> {
800 Err(self.unsupported("list_projects"))
801 }
802 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
803 Err(self.unsupported("list_ssh_keys"))
804 }
805 async fn upload_ssh_key(&self, _title: &str, _public_key: &str) -> Result<HostedSshKey> {
806 Err(self.unsupported("upload_ssh_key"))
807 }
808 async fn create_pull_request(&self, _req: &NewPullRequest) -> Result<CreatedPullRequest> {
809 Err(self.unsupported("create_pull_request"))
810 }
811}
812
813#[cfg(any(feature = "github", feature = "gitlab"))]
819pub(crate) async fn fetch_pages<T: DeserializeOwned>(
820 transport: &dyn HttpTransport,
821 request: impl Fn(String) -> HttpRequest,
822 base_url: &str,
823 what: &str,
824) -> Result<Vec<T>> {
825 fetch_pages_with(transport, request, base_url, what, |r| r.json()).await
826}
827
828#[cfg(any(feature = "github", feature = "gitlab"))]
831pub(crate) async fn fetch_pages_with<T>(
832 transport: &dyn HttpTransport,
833 request: impl Fn(String) -> HttpRequest,
834 base_url: &str,
835 what: &str,
836 rows: impl Fn(&HttpResponse) -> Result<Vec<T>>,
837) -> Result<Vec<T>> {
838 let mut out = Vec::new();
839 for page in 1..=MAX_PAGES {
840 let url = format!("{base_url}&per_page={PAGE_SIZE}&page={page}");
841 let response = transport.send(request(url)).await?;
842 response.error_for_status(what)?;
843 let page_rows = rows(&response)?;
844 let count = page_rows.len();
845 out.extend(page_rows);
846 if count < PAGE_SIZE as usize {
847 break;
848 }
849 }
850 Ok(out)
851}
852
853#[cfg_attr(
857 not(any(
858 feature = "github",
859 feature = "gitlab",
860 feature = "jira",
861 feature = "bitbucket",
862 feature = "azure-devops",
863 feature = "trello",
864 feature = "gitea",
865 feature = "youtrack",
866 feature = "redmine",
867 feature = "gerrit",
868 feature = "local-issues"
869 )),
870 allow(dead_code)
871)]
872pub(crate) fn encode_component(text: &str) -> String {
873 let mut out = String::with_capacity(text.len());
874 for b in text.bytes() {
875 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
876 out.push(b as char);
877 } else {
878 out.push_str(&format!("%{b:02X}"));
879 }
880 }
881 out
882}
883
884pub use crate::spec::web_base;
885
886pub fn pull_request_web_url(
888 integration: &Integration,
889 project: &str,
890 number: u64,
891) -> Option<String> {
892 let base = web_base(integration)?;
893 (spec_for(integration.kind.family()).pr_web_url)(&base, project, number)
894}
895
896pub fn pull_request_head_ref(
902 kind: crate::IntegrationKind,
903 number: u64,
904) -> Option<(String, String)> {
905 let probe = PullRequestSummary {
906 number,
907 iid_label: String::new(),
908 title: String::new(),
909 state: crate::model::PullRequestState::Open,
910 source_branch: String::new(),
911 target_branch: String::new(),
912 source_project: None,
913 author: String::new(),
914 web_url: String::new(),
915 updated_at: String::new(),
916 review_requested: false,
917 assignees: vec![],
918 reviewers: vec![],
919 checks: None,
920 has_conflicts: None,
921 };
922 match (spec_for(kind.family()).checkout)(&probe) {
923 CheckoutSource::HeadRef { remote_ref, local } => Some((remote_ref, local)),
924 CheckoutSource::Branch { .. } => None,
925 }
926}
927
928pub fn pull_request_edit_url(kind: Option<crate::IntegrationKind>, web_url: &str) -> String {
932 match kind {
933 Some(kind) => (spec_for(kind.family()).pr_edit_url)(web_url),
934 None => web_url.to_string(),
935 }
936}
937
938pub fn issue_web_url(integration: &Integration, project: &str, number: u64) -> Option<String> {
940 let base = web_base(integration)?;
941 (spec_for(integration.kind.family()).issue_web_url)(&base, project, &number.to_string())
942}
943
944pub fn token_create_url(integration: &Integration) -> Option<String> {
948 let base = web_base(integration)?;
949 integration.token_link_url(&base)
950}
951
952#[cfg(all(test, feature = "github", feature = "gitlab"))]
953mod tests {
954 use super::*;
955 use crate::http::RecordedTransport;
956 use crate::integration::IntegrationKind;
957 use std::sync::Arc;
958
959 fn integration(kind: IntegrationKind, url: &str) -> Integration {
960 Integration::new("h", kind, url)
961 }
962
963 fn block_on<F: std::future::Future>(f: F) -> F::Output {
964 tokio::runtime::Builder::new_current_thread()
965 .enable_all()
966 .build()
967 .unwrap()
968 .block_on(f)
969 }
970
971 fn header<'a>(request: &'a HttpRequest, name: &str) -> Option<&'a str> {
972 request
973 .headers
974 .iter()
975 .find(|(k, _)| k.eq_ignore_ascii_case(name))
976 .map(|(_, v)| v.as_str())
977 }
978
979 const GITHUB_PAGE: &str = r#"[
980 {"full_name":"me/one","name":"one","description":"first",
981 "default_branch":"main","ssh_url":"git@github.com:me/one.git",
982 "clone_url":"https://github.com/me/one.git",
983 "html_url":"https://github.com/me/one","private":true}
984 ]"#;
985
986 const GITHUB_ORGS_PAGE: &str = r#"[
987 {"full_name":"me/secret","name":"secret","private":true,
988 "clone_url":"https://github.com/me/secret.git"},
989 {"full_name":"acme/site","name":"site","private":false,
990 "clone_url":"https://github.com/acme/site.git"},
991 {"full_name":"acme/internal","name":"internal","private":true,
992 "clone_url":"https://github.com/acme/internal.git"}
993 ]"#;
994
995 const GITLAB_GROUPS_PAGE: &str = r#"[
996 {"id":1,"name":"mine","path_with_namespace":"kai/mine","visibility":"private"},
997 {"id":2,"name":"open","path_with_namespace":"corp/tools/open","visibility":"public"},
998 {"id":3,"name":"shared","path_with_namespace":"corp/tools/shared","visibility":"internal"}
999 ]"#;
1000
1001 const GITLAB_PAGE: &str = r#"[
1002 {"id":42,"name":"one","path_with_namespace":"group/sub/one",
1003 "description":"first","default_branch":"main",
1004 "ssh_url_to_repo":"git@gitlab.example.com:group/sub/one.git",
1005 "http_url_to_repo":"https://gitlab.example.com/group/sub/one.git",
1006 "web_url":"https://gitlab.example.com/group/sub/one",
1007 "visibility":"private"}
1008 ]"#;
1009
1010 #[test]
1011 fn the_default_issue_create_options_are_empty_and_new_issue_has_no_type() {
1012 let transport = std::sync::Arc::new(RecordedTransport::new());
1013 let gh = Integration::new("gh", IntegrationKind::Github, "https://github.com");
1014 let client = client_for(
1015 gh,
1016 "tok".into(),
1017 transport,
1018 &crate::trust::TrustGate::for_tests(),
1019 )
1020 .unwrap();
1021 let options = block_on(client.issue_create_options("me/thing")).unwrap();
1022 assert_eq!(options, IssueCreateOptions::default());
1023 let new = NewIssue::default();
1024 assert!(new.issue_type.is_none() && new.list_id.is_none());
1025 }
1026
1027 #[test]
1028 fn github_repositories_normalise_into_hosted_projects() {
1029 let transport = Arc::new(RecordedTransport::new().on("/user/repos", 200, GITHUB_PAGE));
1030 let client = client_for(
1031 integration(IntegrationKind::Github, "https://github.com"),
1032 "tok".into(),
1033 transport.clone(),
1034 &crate::trust::TrustGate::for_tests(),
1035 )
1036 .unwrap();
1037
1038 let projects = block_on(client.list_projects()).unwrap();
1039 assert_eq!(projects.len(), 1);
1040 assert_eq!(projects[0].full_name, "me/one");
1041 assert_eq!(projects[0].id, "me/one");
1042 assert_eq!(projects[0].integration_id, "h");
1043 assert!(projects[0].private);
1044 assert_eq!(
1045 projects[0].clone_url(true),
1046 Some("git@github.com:me/one.git")
1047 );
1048
1049 let request = &transport.requests()[0];
1050 assert!(request.url.starts_with("https://api.github.com/user/repos"));
1051 assert_eq!(header(request, "Authorization"), Some("Bearer tok"));
1052 assert!(
1053 request.url.contains("affiliation="),
1054 "the token's own repositories, not a public user listing: {}",
1055 request.url
1056 );
1057 }
1058
1059 #[test]
1060 fn gitlab_projects_normalise_into_hosted_projects() {
1061 let transport = Arc::new(RecordedTransport::new().on("/projects?", 200, GITLAB_PAGE));
1062 let client = client_for(
1063 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1064 "tok".into(),
1065 transport.clone(),
1066 &crate::trust::TrustGate::for_tests(),
1067 )
1068 .unwrap();
1069
1070 let projects = block_on(client.list_projects()).unwrap();
1071 assert_eq!(projects[0].full_name, "group/sub/one");
1072 assert_eq!(projects[0].id, "42");
1073 assert!(projects[0].private);
1074
1075 let request = &transport.requests()[0];
1076 assert!(
1077 request
1078 .url
1079 .starts_with("https://gitlab.example.com/api/v4/projects"),
1080 "a self-managed instance's api lives under its own url: {}",
1081 request.url
1082 );
1083 assert_eq!(header(request, "PRIVATE-TOKEN"), Some("tok"));
1084 assert!(
1085 request.url.contains("membership=true"),
1086 "without membership=true this lists every public project on the instance: {}",
1087 request.url
1088 );
1089 }
1090
1091 #[test]
1092 fn github_listing_carries_owner_and_private_flag_for_user_and_org_repos() {
1093 let transport = Arc::new(RecordedTransport::new().on("/user/repos", 200, GITHUB_ORGS_PAGE));
1094 let client = client_for(
1095 integration(IntegrationKind::Github, "https://github.com"),
1096 "tok".into(),
1097 transport.clone(),
1098 &crate::trust::TrustGate::for_tests(),
1099 )
1100 .unwrap();
1101 let projects = block_on(client.list_projects()).unwrap();
1102 let seen: Vec<(&str, bool)> = projects.iter().map(|p| (p.owner(), p.private)).collect();
1103 assert_eq!(seen, vec![("me", true), ("acme", false), ("acme", true)]);
1104 assert!(
1105 transport.requests()[0]
1106 .url
1107 .contains("affiliation=owner,collaborator,organization_member"),
1108 "organisation repositories are part of the listing"
1109 );
1110 }
1111
1112 #[test]
1113 fn gitlab_listing_carries_the_group_path_and_visibility() {
1114 let transport =
1115 Arc::new(RecordedTransport::new().on("/projects?", 200, GITLAB_GROUPS_PAGE));
1116 let client = client_for(
1117 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1118 "tok".into(),
1119 transport,
1120 &crate::trust::TrustGate::for_tests(),
1121 )
1122 .unwrap();
1123 let projects = block_on(client.list_projects()).unwrap();
1124 let seen: Vec<(&str, bool)> = projects.iter().map(|p| (p.owner(), p.private)).collect();
1125 assert_eq!(
1126 seen,
1127 vec![("kai", true), ("corp/tools", false), ("corp/tools", true)]
1128 );
1129 }
1130
1131 #[test]
1134 fn a_full_page_is_followed_by_another_request() {
1135 let full: String = format!(
1136 "[{}]",
1137 (0..PAGE_SIZE)
1138 .map(|n| format!(
1139 r#"{{"id":{n},"name":"p{n}","path_with_namespace":"g/p{n}","visibility":"public"}}"#
1140 ))
1141 .collect::<Vec<_>>()
1142 .join(",")
1143 );
1144 let transport = Arc::new(RecordedTransport::new().on("&page=1", 200, &full).on(
1145 "&page=2",
1146 200,
1147 GITLAB_PAGE,
1148 ));
1149 let client = client_for(
1150 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1151 "tok".into(),
1152 transport.clone(),
1153 &crate::trust::TrustGate::for_tests(),
1154 )
1155 .unwrap();
1156
1157 let projects = block_on(client.list_projects()).unwrap();
1158 assert_eq!(projects.len(), PAGE_SIZE as usize + 1);
1159 assert_eq!(transport.requests().len(), 2, "must stop on a short page");
1160 }
1161
1162 #[test]
1166 fn a_rejected_token_is_an_unauthorized_error_not_an_empty_list() {
1167 let transport = Arc::new(RecordedTransport::new().on(
1168 "/user/repos",
1169 401,
1170 r#"{"message":"Bad credentials"}"#,
1171 ));
1172 let client = client_for(
1173 integration(IntegrationKind::Github, "https://github.com"),
1174 "stale".into(),
1175 transport,
1176 &crate::trust::TrustGate::for_tests(),
1177 )
1178 .unwrap();
1179
1180 let err = block_on(client.list_projects()).unwrap_err();
1181 assert!(matches!(err, crate::Error::Unauthorized { .. }));
1182 assert!(err.to_string().contains("Bad credentials"));
1183 }
1184
1185 #[test]
1186 fn uploading_a_key_sends_the_hosts_own_field_names() {
1187 for (kind, url, fragment) in [
1188 (
1189 IntegrationKind::Github,
1190 "https://github.com",
1191 "api.github.com",
1192 ),
1193 (
1194 IntegrationKind::Gitlab,
1195 "https://gitlab.example.com",
1196 "gitlab.example.com/api/v4",
1197 ),
1198 ] {
1199 let transport = Arc::new(RecordedTransport::new().on(
1200 "/user/keys",
1201 201,
1202 r#"{"id":7,"title":"laptop","key":"ssh-ed25519 AAAA laptop"}"#,
1203 ));
1204 let client = client_for(
1205 integration(kind, url),
1206 "tok".into(),
1207 transport.clone(),
1208 &crate::trust::TrustGate::for_tests(),
1209 )
1210 .unwrap();
1211
1212 let key =
1213 block_on(client.upload_ssh_key("laptop", "ssh-ed25519 AAAA laptop\n")).unwrap();
1214 assert_eq!(key.id, "7");
1215 assert_eq!(key.title, "laptop");
1216
1217 let request = &transport.requests()[0];
1218 assert!(request.url.contains(fragment), "{}", request.url);
1219 let body: serde_json::Value =
1220 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1221 assert_eq!(body["title"], "laptop");
1222 assert_eq!(
1223 body["key"], "ssh-ed25519 AAAA laptop",
1224 "the trailing newline must be trimmed - both hosts reject it"
1225 );
1226 }
1227 }
1228
1229 fn new_pr(project: &str) -> NewPullRequest {
1230 NewPullRequest {
1231 project: project.into(),
1232 source_branch: "feature".into(),
1233 target_branch: "main".into(),
1234 title: "Add feature".into(),
1235 body: "does the thing".into(),
1236 draft: false,
1237 source_project: None,
1238 ..Default::default()
1239 }
1240 }
1241
1242 #[test]
1243 fn github_pull_request_sends_head_base_and_returns_html_url() {
1244 let transport = Arc::new(RecordedTransport::new().on(
1245 "/pulls",
1246 201,
1247 r#"{"number":42,"html_url":"https://github.com/me/thing/pull/42"}"#,
1248 ));
1249 let client = client_for(
1250 integration(IntegrationKind::Github, "https://github.com"),
1251 "tok".into(),
1252 transport.clone(),
1253 &crate::trust::TrustGate::for_tests(),
1254 )
1255 .unwrap();
1256
1257 let created = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap();
1258 assert_eq!(created.number, 42);
1259 assert_eq!(created.web_url, "https://github.com/me/thing/pull/42");
1260
1261 let request = &transport.requests()[0];
1262 assert!(
1263 request.url.ends_with("/repos/me/thing/pulls"),
1264 "{}",
1265 request.url
1266 );
1267 let body: serde_json::Value =
1268 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1269 assert_eq!(body["head"], "feature");
1270 assert_eq!(body["base"], "main");
1271 assert_eq!(body["title"], "Add feature");
1272 assert_eq!(body["draft"], false);
1273 }
1274
1275 #[test]
1276 fn gitlab_merge_request_url_encodes_the_project_path() {
1277 let transport = Arc::new(RecordedTransport::new().on(
1278 "/merge_requests",
1279 201,
1280 r#"{"iid":7,"web_url":"https://gitlab.example.com/group/sub/proj/-/merge_requests/7"}"#,
1281 ));
1282 let client = client_for(
1283 integration(IntegrationKind::Gitlab, "https://gitlab.example.com"),
1284 "tok".into(),
1285 transport.clone(),
1286 &crate::trust::TrustGate::for_tests(),
1287 )
1288 .unwrap();
1289
1290 let mut req = new_pr("group/sub/proj");
1291 req.draft = true;
1292 let created = block_on(client.create_pull_request(&req)).unwrap();
1293 assert_eq!(created.number, 7);
1294 assert_eq!(
1295 created.web_url,
1296 "https://gitlab.example.com/group/sub/proj/-/merge_requests/7"
1297 );
1298
1299 let request = &transport.requests()[0];
1300 assert!(
1301 request
1302 .url
1303 .contains("/projects/group%2Fsub%2Fproj/merge_requests"),
1304 "{}",
1305 request.url
1306 );
1307 let body: serde_json::Value =
1308 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1309 assert_eq!(body["source_branch"], "feature");
1310 assert_eq!(body["target_branch"], "main");
1311 assert_eq!(
1312 body["title"], "Draft: Add feature",
1313 "GitLab marks drafts by title prefix"
1314 );
1315 }
1316
1317 #[test]
1318 fn a_fork_pull_request_names_the_fork_owner_on_github() {
1319 let transport = Arc::new(RecordedTransport::new().on(
1320 "/pulls",
1321 201,
1322 r#"{"number":3,"html_url":"https://github.com/up/thing/pull/3"}"#,
1323 ));
1324 let client = client_for(
1325 integration(IntegrationKind::Github, "https://github.com"),
1326 "tok".into(),
1327 transport.clone(),
1328 &crate::trust::TrustGate::for_tests(),
1329 )
1330 .unwrap();
1331 let mut req = new_pr("up/thing");
1332 req.source_project = Some("me/thing".into());
1333 block_on(client.create_pull_request(&req)).unwrap();
1334 let request = &transport.requests()[0];
1335 assert!(
1336 request.url.ends_with("/repos/up/thing/pulls"),
1337 "{}",
1338 request.url
1339 );
1340 let body: serde_json::Value =
1341 serde_json::from_str(request.body.as_deref().unwrap()).unwrap();
1342 assert_eq!(body["head"], "me:feature");
1343 let mut same = new_pr("up/thing");
1345 same.source_project = Some("UP/thing".into());
1346 assert_eq!(same.fork_source(), None);
1347 }
1348
1349 #[test]
1350 fn a_fork_merge_request_is_posted_from_the_source_project_with_the_target_id() {
1351 let transport = Arc::new(
1352 RecordedTransport::new()
1353 .on(
1354 "/merge_requests",
1355 201,
1356 r#"{"iid":9,"web_url":"https://g.example.com/up/thing/-/merge_requests/9"}"#,
1357 )
1358 .on("/projects/up%2Fthing", 200, r#"{"id":77}"#),
1359 );
1360 let client = client_for(
1361 integration(IntegrationKind::Gitlab, "https://g.example.com"),
1362 "tok".into(),
1363 transport.clone(),
1364 &crate::trust::TrustGate::for_tests(),
1365 )
1366 .unwrap();
1367 let mut req = new_pr("up/thing");
1368 req.source_project = Some("me/thing".into());
1369 let created = block_on(client.create_pull_request(&req)).unwrap();
1370 assert_eq!(created.number, 9);
1371 let requests = transport.requests();
1372 let post = requests.last().unwrap();
1373 assert!(
1374 post.url.contains("/projects/me%2Fthing/merge_requests"),
1375 "{}",
1376 post.url
1377 );
1378 let body: serde_json::Value = serde_json::from_str(post.body.as_deref().unwrap()).unwrap();
1379 assert_eq!(body["target_project_id"], 77);
1380 }
1381
1382 #[test]
1386 fn an_existing_pull_request_surfaces_the_hosts_message() {
1387 let transport = Arc::new(RecordedTransport::new().on(
1388 "/pulls",
1389 422,
1390 r#"{"message":"Validation Failed","errors":[{"message":"A pull request already exists for me:feature."}]}"#,
1391 ));
1392 let client = client_for(
1393 integration(IntegrationKind::Github, "https://github.com"),
1394 "tok".into(),
1395 transport,
1396 &crate::trust::TrustGate::for_tests(),
1397 )
1398 .unwrap();
1399
1400 let err = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap_err();
1401 assert!(matches!(err, crate::Error::Api { status: 422, .. }));
1402 assert!(err.to_string().contains("Validation Failed"), "{err}");
1403 }
1404
1405 #[test]
1409 fn create_pull_request_401_and_403_map_to_the_existing_errors() {
1410 for (status, want_unauthorized) in [(401, true), (403, false)] {
1411 let transport =
1412 Arc::new(RecordedTransport::new().on("/pulls", status, r#"{"message":"nope"}"#));
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 let err = block_on(client.create_pull_request(&new_pr("me/thing"))).unwrap_err();
1421 if want_unauthorized {
1422 assert!(matches!(err, crate::Error::Unauthorized { .. }));
1423 } else {
1424 assert!(matches!(err, crate::Error::Forbidden { .. }));
1425 }
1426 }
1427 }
1428
1429 #[test]
1430 fn existing_keys_can_be_listed_so_a_duplicate_upload_is_avoidable() {
1431 let transport = Arc::new(RecordedTransport::new().on(
1432 "/user/keys",
1433 200,
1434 r#"[{"id":7,"title":"laptop","key":"ssh-ed25519 AAAA laptop"}]"#,
1435 ));
1436 let client = client_for(
1437 integration(IntegrationKind::Github, "https://github.com"),
1438 "tok".into(),
1439 transport,
1440 &crate::trust::TrustGate::for_tests(),
1441 )
1442 .unwrap();
1443 let keys = block_on(client.list_ssh_keys()).unwrap();
1444 assert_eq!(keys[0].title, "laptop");
1445 }
1446
1447 #[test]
1450 fn new_operations_default_to_unsupported() {
1451 struct Old(Integration);
1452 #[async_trait::async_trait]
1453 impl HostingClient for Old {
1454 fn integration(&self) -> &Integration {
1455 &self.0
1456 }
1457 async fn list_projects(&self) -> Result<Vec<HostedProject>> {
1458 Ok(vec![])
1459 }
1460 async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
1461 Ok(vec![])
1462 }
1463 async fn upload_ssh_key(&self, _: &str, _: &str) -> Result<HostedSshKey> {
1464 unreachable!()
1465 }
1466 async fn create_pull_request(&self, _: &NewPullRequest) -> Result<CreatedPullRequest> {
1467 unreachable!()
1468 }
1469 }
1470 let old = Old(integration(IntegrationKind::Github, "https://github.com"));
1471 assert!(matches!(
1472 block_on(old.current_user()).unwrap_err(),
1473 Error::Unsupported(_)
1474 ));
1475 assert!(matches!(
1476 block_on(old.delete_ssh_key("1")).unwrap_err(),
1477 Error::Unsupported(_)
1478 ));
1479 assert!(matches!(
1480 block_on(old.pull_request_for_branch("a/b", "x")).unwrap_err(),
1481 Error::Unsupported(_)
1482 ));
1483 }
1484
1485 #[test]
1486 fn pull_request_heads_live_in_the_hosts_special_refs() {
1487 assert_eq!(
1488 pull_request_head_ref(IntegrationKind::Github, 7),
1489 Some(("refs/pull/7/head".into(), "pr/7".into()))
1490 );
1491 assert_eq!(
1492 pull_request_head_ref(IntegrationKind::GitlabSelfManaged, 7),
1493 Some(("refs/merge-requests/7/head".into(), "mr/7".into()))
1494 );
1495 }
1496
1497 #[test]
1498 fn web_url_helpers_per_family() {
1499 let gh = integration(IntegrationKind::Github, "https://github.com/");
1500 assert_eq!(
1501 pull_request_web_url(&gh, "me/thing", 12).as_deref(),
1502 Some("https://github.com/me/thing/pull/12")
1503 );
1504 assert_eq!(
1505 issue_web_url(&gh, "me/thing", 3).as_deref(),
1506 Some("https://github.com/me/thing/issues/3")
1507 );
1508 let ghe = integration(IntegrationKind::GithubEnterprise, "https://ghe.example.com");
1509 assert_eq!(
1510 pull_request_web_url(&ghe, "o/r", 1).as_deref(),
1511 Some("https://ghe.example.com/o/r/pull/1")
1512 );
1513 let gl = integration(
1514 IntegrationKind::GitlabSelfManaged,
1515 "https://gitlab.example.com",
1516 );
1517 assert_eq!(
1518 pull_request_web_url(&gl, "g/sub/p", 53).as_deref(),
1519 Some("https://gitlab.example.com/g/sub/p/-/merge_requests/53")
1520 );
1521 assert_eq!(
1522 issue_web_url(&gl, "g/sub/p", 12).as_deref(),
1523 Some("https://gitlab.example.com/g/sub/p/-/issues/12")
1524 );
1525 let jira = integration(IntegrationKind::JiraCloud, "https://x.atlassian.net");
1526 assert_eq!(pull_request_web_url(&jira, "p", 1), None);
1527 }
1528
1529 #[test]
1530 fn the_token_create_url_needs_a_host_and_a_token_flow() {
1531 assert_eq!(
1532 token_create_url(&integration(IntegrationKind::Github, "")).as_deref(),
1533 Some("https://github.com/settings/tokens/new?description=GitPoulpi&scopes=repo,read:user,admin:public_key")
1534 );
1535 assert_eq!(
1536 token_create_url(&integration(
1537 IntegrationKind::GitlabSelfManaged,
1538 "https://gitlab.example.com/"
1539 ))
1540 .as_deref(),
1541 Some("https://gitlab.example.com/-/user_settings/personal_access_tokens?name=GitPoulpi&scopes=api,read_user")
1542 );
1543 assert_eq!(
1544 token_create_url(&integration(IntegrationKind::GitlabSelfManaged, "")),
1545 None
1546 );
1547 assert_eq!(
1548 token_create_url(&integration(IntegrationKind::Trello, "")),
1549 None
1550 );
1551 }
1552}