Skip to main content

gitpoulpi_hosting/
client.rs

1//! The provider-agnostic hosting port and its plumbing.
2//!
3//! The implementations live in [`crate::github`] and [`crate::gitlab`];
4//! kinds with no client yet (Bitbucket, Azure DevOps, Jira, Trello) get
5//! [`UnsupportedClient`], whose every call says so.
6
7// With `hosting` forced on but no provider built, the paging and encoding
8// helpers below have no caller and `client_for` ignores its inputs.
9#![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/// How many rows one page asks for: 100 is the maximum both hosts accept,
74/// and a larger ask is silently clamped, which would make the pagination
75/// loop's termination condition wrong on one host.
76#[cfg(any(feature = "github", feature = "gitlab", feature = "azure-devops"))]
77pub(crate) const PAGE_SIZE: u32 = 100;
78
79/// A safety rail on the pagination loop: a host that ignores the page
80/// parameter (a misconfigured proxy in front of a self-managed instance)
81/// returns page 1 forever. 50 pages is 5000 rows, past any real account.
82#[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/// What opening a pull/merge request needs, host-agnostic.
97///
98/// `project` is the `remote_web_base`-derived path (`group/sub/proj` for
99/// GitLab, `owner/name` for GitHub); each client encodes it as its API
100/// needs (GitLab URL-encodes it as one segment).
101#[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    /// The project the source branch lives in, when it is a fork of
110    /// `project` (`None`: same project). Path form, like `project`.
111    pub source_project: Option<String>,
112    /// Logins to assign (GitHub, GitLab).
113    pub assignees: Vec<String>,
114    /// Logins asked to review (GitHub, GitLab).
115    pub reviewers: Vec<String>,
116    /// Label names (GitHub, GitLab).
117    pub labels: Vec<String>,
118    /// `HostedMilestone::id` (GitHub, GitLab).
119    pub milestone: Option<u64>,
120}
121
122impl NewPullRequest {
123    /// `source_project`, only when it really differs from `project`.
124    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/// What the host answers with once the request exists.
132#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
133pub struct CreatedPullRequest {
134    /// The PR number (GitHub) or MR `iid` (GitLab) - the number the
135    /// host's own UI shows next to it, not its opaque database id.
136    pub number: u64,
137    pub web_url: String,
138    /// The request exists but part of its metadata could not be set
139    /// (GitHub applies it in a second call).
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub warning: Option<String>,
142}
143
144/// What opening an issue needs, host-agnostic (v1: title, body, labels).
145#[derive(Debug, Clone, PartialEq, Eq, Default)]
146pub struct NewIssue {
147    /// `owner/name` (GitHub) or `group/sub/proj` (GitLab).
148    pub project: String,
149    pub title: String,
150    pub body: String,
151    pub labels: Vec<String>,
152    /// Jira issue-type id, Azure work-item type name.
153    pub issue_type: Option<String>,
154    /// Trello list id.
155    pub list_id: Option<String>,
156    /// Logins to assign (GitHub, GitLab).
157    pub assignees: Vec<String>,
158    /// `HostedMilestone::id` (GitHub, GitLab).
159    pub milestone: Option<u64>,
160}
161
162/// What the host answers with once the issue exists.
163#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
164pub struct CreatedIssue {
165    /// The issue number (GitHub) or `iid` (GitLab).
166    pub number: u64,
167    pub web_url: String,
168    /// What a human types to reference it (`#12`, `ABC-123`).
169    pub reference: String,
170}
171
172#[async_trait::async_trait]
173pub trait HostingClient: Send + Sync {
174    fn integration(&self) -> &Integration;
175
176    /// The error for an operation this client does not offer. The optional
177    /// operations below return it by default, so one override changes the
178    /// answer for all of them.
179    fn unsupported(&self, what: &str) -> Error {
180        Error::Unsupported(what.to_string())
181    }
182
183    /// Every project the token can see, newest-activity first where the
184    /// host offers that ordering.
185    async fn list_projects(&self) -> Result<Vec<HostedProject>>;
186
187    /// The SSH public keys already on the account, so an *upload a key*
188    /// flow can say "you already have this one" instead of creating a
189    /// duplicate the user then has to find and delete.
190    async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>>;
191
192    /// Adds `public_key` (an `ssh-ed25519 AAAA... comment` line) to the
193    /// account under `title`.
194    async fn upload_ssh_key(&self, title: &str, public_key: &str) -> Result<HostedSshKey>;
195
196    /// Opens a pull request (GitHub) or merge request (GitLab) from
197    /// `req.source_branch` into `req.target_branch`.
198    async fn create_pull_request(&self, req: &NewPullRequest) -> Result<CreatedPullRequest>;
199
200    /// The account the token belongs to.
201    async fn current_user(&self) -> Result<HostedUser> {
202        Err(self.unsupported("current_user"))
203    }
204
205    /// The branches of `project` the host protects (names and `*`
206    /// patterns), for a history rewrite that must not force-push them
207    /// blindly. What the token cannot read is an error here; the caller
208    /// ([`crate::protection::lookup`]) turns it into "unknown".
209    async fn protected_branches(
210        &self,
211        _project: &str,
212    ) -> Result<crate::protection::ProtectedBranches> {
213        Err(self.unsupported("protected_branches"))
214    }
215
216    /// Validates the token and reports its user, scopes and expiry.
217    async fn check_token(&self) -> Result<TokenCheck> {
218        Err(self.unsupported("check_token"))
219    }
220
221    /// Pull/merge requests of `project` (`owner/name`, `group/sub/proj`).
222    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    /// The request that best represents `branch`: open, then draft, then
231    /// merged, then closed; newest first among equals.
232    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    /// Opens an issue on `req.project`.
249    async fn create_issue(&self, _req: &NewIssue) -> Result<CreatedIssue> {
250        Err(self.unsupported("create_issue"))
251    }
252
253    /// The types / lists the New-issue form offers for `project`. Empty
254    /// by default (GitHub and GitLab have neither).
255    async fn issue_create_options(&self, _project: &str) -> Result<IssueCreateOptions> {
256        Ok(IssueCreateOptions::default())
257    }
258
259    /// Removes the account SSH key with the host's own `id`.
260    async fn delete_ssh_key(&self, _id: &str) -> Result<()> {
261        Err(self.unsupported("delete_ssh_key"))
262    }
263
264    // -- in-app code review (see `crate::review`) --
265
266    /// What a review on this host may do, so a UI hides the rest instead
267    /// of offering a choice that fails (GitLab has no "request changes").
268    /// All-false by default.
269    fn review_capabilities(&self) -> ReviewCapabilities {
270        ReviewCapabilities::default()
271    }
272
273    /// One request, read for review: description, head and base commits,
274    /// merge state, checks.
275    async fn pull_request_detail(&self, _project: &str, _number: u64) -> Result<PullRequestDetail> {
276        Err(self.unsupported("pull_request_detail"))
277    }
278
279    /// [`Self::pull_request_detail`] at patch set `patch_set` (`None`: the
280    /// newest). Only Gerrit has patch sets; the others ignore it.
281    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    /// [`Self::pull_request_files`] at a patch set.
291    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    /// [`Self::pull_request_files_at`] as the difference from patch set
301    /// `base` instead of from the target branch (Gerrit's "compare with"; the
302    /// others have no patch sets and ignore it).
303    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    /// Submits (merges) a change on the host (Gerrit; `PullRequestDetail::
314    /// can_submit` says when the server allows it). Outward, not undoable.
315    async fn submit_change(&self, _project: &str, _number: u64) -> Result<()> {
316        Err(self.unsupported("submit_change"))
317    }
318
319    /// Abandons a change, with an optional message to the owner and
320    /// reviewers (Gerrit). Outward, not undoable from GitPoulpi.
321    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    /// [`Self::pull_request_threads`] judged against a patch set: threads
331    /// written on another one are outdated.
332    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    /// The files the request changes, for the file list.
342    async fn pull_request_files(&self, _project: &str, _number: u64) -> Result<Vec<ReviewFile>> {
343        Err(self.unsupported("pull_request_files"))
344    }
345
346    /// The code threads of the request, resolved ones included.
347    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    /// The comments that are not on code, oldest first.
356    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    /// The reviews already submitted (verdict and summary), oldest first.
365    /// Empty drafts are not listed.
366    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    /// Posts a conversation comment (not on code), immediately.
375    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    /// Answers a thread (`ReviewThread::id`), immediately.
385    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    /// Resolves (`true`) or reopens (`false`) a thread.
396    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    /// Submits a review: the collected line comments and the verdict in
407    /// one go. `Unsupported` for an event [`Self::review_capabilities`]
408    /// does not offer.
409    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    // -- conversations -------------------------------------------------------
419
420    /// What the conversation of an issue or request may do on this host.
421    /// [`ConversationCaps::NONE`] by default: no conversation at all.
422    fn conversation_caps(&self, _kind: crate::conversation::ItemKind) -> ConversationCaps {
423        ConversationCaps::NONE
424    }
425
426    /// Who a post to `project` is made as: always known (see
427    /// [`crate::conversation::identity`]). Hits the network at most once.
428    async fn posting_identity(&self, _project: &str) -> Result<PostingIdentity> {
429        Err(self.unsupported("posting_identity"))
430    }
431
432    /// The item's header and the newest window (at most
433    /// [`crate::conversation::WINDOW`] entries) of its conversation, or the
434    /// window before `older`.
435    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    /// Posts a comment on the item, immediately. Outward, not undoable.
446    /// `internal`: only members see it (GitLab).
447    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    /// Answers a discussion (a code thread, or a GitLab discussion).
458    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    /// Edits one of our own comments.
469    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    /// Deletes one of our own comments.
480    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    // -- host-driven flows (slice W4) ----------------------------------------
490
491    /// Creates a branch on the host for an issue (GitLab: the branches API,
492    /// GitHub: `createLinkedBranch`, Gitea / Forgejo: the branches API).
493    /// Outward, not undoable from GitPoulpi.
494    async fn create_issue_branch(&self, _req: &NewIssueBranch) -> Result<CreatedBranch> {
495        Err(self.unsupported("create_issue_branch"))
496    }
497
498    /// The branches and requests the host links to issue `number` itself.
499    async fn issue_links(&self, _project: &str, _number: u64) -> Result<IssueLinks> {
500        Err(self.unsupported("issue_links"))
501    }
502
503    /// Branch names of `project` that start with (GitHub) or contain
504    /// (GitLab, Gitea) `search`; the caller filters them exactly.
505    async fn branch_names(&self, _project: &str, _search: &str) -> Result<Vec<String>> {
506        Err(self.unsupported("branch_names"))
507    }
508
509    // -- metadata (slice M): GitHub and GitLab only ---------------------------
510
511    /// The people who can be assigned to or asked to review in `project`,
512    /// narrowed by `query` (empty: everyone, paged).
513    async fn project_members(&self, _project: &str, _query: &str) -> Result<Vec<HostedUser>> {
514        Err(self.unsupported("project_members"))
515    }
516
517    /// The labels of `project`.
518    async fn project_labels(&self, _project: &str) -> Result<Vec<HostedLabel>> {
519        Err(self.unsupported("project_labels"))
520    }
521
522    /// The open milestones of `project`.
523    async fn project_milestones(&self, _project: &str) -> Result<Vec<HostedMilestone>> {
524        Err(self.unsupported("project_milestones"))
525    }
526
527    /// What issue / request `number` carries now (the picker's checked rows).
528    async fn item_meta(&self, _project: &str, _number: u64, _kind: MetaKind) -> Result<ItemMeta> {
529        Err(self.unsupported("item_meta"))
530    }
531
532    /// Replaces the assignees / labels / milestone of an issue.
533    async fn update_issue(&self, _project: &str, _number: u64, _edit: &IssueEdit) -> Result<()> {
534        Err(self.unsupported("update_issue"))
535    }
536
537    // -- local issues (slice L1): status-based sources ----------------------
538
539    /// The statuses an issue can be in, board order (the local Markdown
540    /// source; the Kanban slice reads it too). Empty by default.
541    async fn issue_statuses(&self, _project: &str) -> Result<Vec<String>> {
542        Ok(Vec::new())
543    }
544
545    /// Moves an issue to `status` (local Markdown).
546    async fn set_issue_status(&self, _project: &str, _number: u64, _status: &str) -> Result<()> {
547        Err(self.unsupported("set_issue_status"))
548    }
549
550    /// Closes (`true`) or reopens (`false`) an issue (local Markdown: the
551    /// configured done status, or the first other one; GitHub, GitLab,
552    /// Gitea: the issue's state).
553    async fn set_issue_state(&self, _project: &str, _number: u64, _closed: bool) -> Result<()> {
554        Err(self.unsupported("set_issue_state"))
555    }
556
557    // -- the Kanban board (slice L2) -----------------------------------------
558
559    /// How this source forms the board's columns (`crate::board`). Open /
560    /// Closed by default; a provider with a workflow overrides it and, for
561    /// the status-like sources, `issue_statuses`.
562    fn board_source(&self) -> crate::board::BoardSource {
563        crate::board::BoardSource::OpenClosed
564    }
565
566    /// Moves `issue` to column `to` of the board `spec`. The default runs
567    /// the [`crate::board::plan_move`] plan through `set_issue_status`,
568    /// `update_issue` and `set_issue_state`, so a client gets a move by
569    /// implementing those (Unsupported otherwise: a read-only board).
570    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    /// Replaces the assignees / reviewers / labels / milestone of a pull /
598    /// merge request.
599    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    // -- the code of a request through the API, no clone (slice S3a) --
609
610    /// The diff of a request, file by file, with hunks, read from the host.
611    /// `patch_set` and `compare` are Gerrit's; the others ignore them. A
612    /// file whose patch the host left out carries `omitted`.
613    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    /// The commits of a request, oldest first.
624    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    /// What one commit changed (against its first parent), read from the host.
633    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    /// The bytes of `path` at `rev` (a branch, tag or commit; `None`: the
642    /// project's default branch). `Ok(None)` when the file does not exist
643    /// there.
644    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    /// The account-wide lists `query` asks for (requests waiting for my
654    /// review, every open request of my namespaces, issues assigned to me),
655    /// across every repository rather than one project. Every code host but
656    /// Bitbucket Cloud answers; the others say `Unsupported`.
657    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
665/// Builds the client for `integration`, over `transport`, once `gate` has
666/// admitted it.
667///
668/// The gate checks the address against the trust record **before** anything
669/// exists (see [`crate::trust`]), and the transport the client gets is
670/// wrapped so that no request leaves the integration's origins. A folder of
671/// local notes has no network and skips the gate.
672///
673/// Families without a client return an [`UnsupportedClient`] rather than
674/// failing here; callers that want to hide the feature altogether gate on
675/// `kind.capabilities().implemented`.
676pub 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        // A repository's token command can stand in for the personal token
694        // on its own calls (a GitHub App bot).
695        #[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        // A kind this binary was built without.
780        #[allow(unreachable_patterns)]
781        _ => Box::new(UnsupportedClient { integration }),
782    }
783}
784
785/// Stands in for a family with no client yet: every call fails with
786/// [`Error::NotImplemented`] naming the product.
787pub 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/// Fetches every page of a list endpoint (`base_url` already carries a
814/// `?`), stopping on the first short page or at [`MAX_PAGES`].
815///
816/// Counting rows rather than following `Link: rel="next"` keeps this
817/// working behind proxies that rewrite or drop that header.
818#[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/// [`fetch_pages`] for an endpoint whose rows sit inside a wrapper object
829/// (GitHub's search API): `rows` pulls one page's rows out of the response.
830#[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/// Percent-encodes everything but RFC 3986 unreserved characters, for a
854/// query-string value (`feature/x` becomes `feature%2Fx`).
855// Linear (GraphQL, a JSON body) is the one provider that never encodes a URL part.
856#[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
886/// The browser page of pull/merge request `number` in `project`.
887pub 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
896/// Where a host keeps the head of pull/merge request `number` - the ref
897/// a fork's commits are fetched from - and the local branch name to
898/// track it with: `("refs/pull/7/head", "pr/7")` on GitHub,
899/// `("refs/merge-requests/7/head", "mr/7")` on GitLab. `None` for hosts
900/// that fetch a pull request by branch instead ([`CheckoutSource::Branch`]).
901pub 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
928/// The page to edit a pull / merge request whose browser page is
929/// `web_url`: GitLab has a dedicated edit view (`.../merge_requests/53/edit`);
930/// GitHub edits the title and description in place on the request's page.
931pub 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
938/// The browser page of issue `number` in `project`.
939pub 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
944/// The page on the host that mints a token with the scopes the app
945/// needs, pre-filled. `None` for kinds without a token flow, or when no
946/// host is known yet (a self-managed profile still being typed).
947pub 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    /// The pagination loop has to ask for the next page while a page is
1132    /// full, and stop on the first short one.
1133    #[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    /// A rejected token must say so in words the user can act on, not
1163    /// as a bare status code - and must not be reported as an empty
1164    /// project list.
1165    #[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        // Same project spelled as the source is not a fork.
1344        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    /// A duplicate PR (git already has one open for this branch pair) is
1383    /// GitHub's classic 422; the host's own message must survive into the
1384    /// error, not a bare status code.
1385    #[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    /// 401/403 on create must map to the same `Unauthorized`/`Forbidden`
1406    /// errors every other call already uses - one vocabulary for a
1407    /// rejected or under-scoped token, not a special case per endpoint.
1408    #[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    /// A client that implements only the original four operations gets
1448    /// `Unsupported` for the new ones by default.
1449    #[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}