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