Skip to main content

gitpoulpi_hosting/bitbucket/
dc.rs

1//! The Bitbucket Data Center client (slice S12).
2//!
3//! Verified 2026-10-08 against Atlassian's published OpenAPI document for
4//! Data Center 10.0 (`https://dac-static.atlassian.com/server/bitbucket/10.0.swagger.v3.json`,
5//! the machine-readable form of the REST reference at
6//! `https://developer.atlassian.com/server/bitbucket/rest/v1000/`):
7//!
8//! - `GET /rest/api/latest/projects/{key}/repos/{slug}/pull-requests` with
9//!   `state` (`OPEN|DECLINED|MERGED|ALL`), `at` (a fully-qualified ref),
10//!   `direction` (`INCOMING|OUTGOING`, relative to the repository), `order`,
11//!   `draft`, `start`, `limit` (default 25).
12//! - Paging: `values`, `isLastPage`, `nextPageStart`, `start`, `limit`, `size`.
13//! - Pull request: `id`, `title`, `state` (`DECLINED|MERGED|OPEN`), `draft`,
14//!   `updatedDate` (epoch milliseconds), `fromRef`/`toRef` (`id` =
15//!   `refs/heads/x`, `displayId`, `repository.slug`, `repository.project.key`),
16//!   `author` and `reviewers` (participants: `user.{name,slug,displayName}`,
17//!   `role` `AUTHOR|REVIEWER|PARTICIPANT`, `status`
18//!   `UNAPPROVED|NEEDS_WORK|APPROVED`).
19//! - Create: `POST` the same url with `{title, description, draft, fromRef,
20//!   toRef}` (refs carry `id` and `repository.{slug, project.key}`); 201 with
21//!   the new pull request.
22//! - `GET /rest/api/latest/repos` (all repositories the caller can read;
23//!   paged), repository `slug`, `name`, `description`, `public`,
24//!   `project.key`.
25//! - `GET /rest/api/latest/users/{userSlug}`: `name`, `slug`, `displayName`.
26//! - SSH keys of the current user live in another REST root:
27//!   `/rest/ssh/latest/keys` (GET paged, POST `{text, label}`, DELETE
28//!   `/keys/{id}`); the key has `id` (integer), `label`, `text`.
29//!   Without a `user` parameter they act on the authenticated user.
30//! - The pull request head ref `refs/pull-requests/{id}/from` is documented
31//!   by Atlassian's article "Pull request proficiency: fetching abilities
32//!   unlocked" (it calls these refs private and undocumented in the API).
33//!
34//! NOT verifiable in the OpenAPI document, taken from community answers and
35//! the plan (so covered only by canned tests):
36//!
37//! - HTTP access tokens as `Authorization: Bearer` (`crate::auth`).
38//! - The current user's name: the `X-AUSERNAME` response header (here read
39//!   from `GET /rest/api/latest/application-properties`).
40//! - The `links.self[0].href` web url of a pull request and the
41//!   `links.clone[]` (`{href, name: "http"|"ssh"}`) of a repository: the
42//!   schema declares `links` as an opaque object.
43//!
44//! Left out because nothing verifiable backs them: web url builders for new
45//! pull requests, branches and commits (`spec`), and parsing the
46//! `/scm/KEY/slug.git` clone path beyond stripping it here.
47//!
48//! There is no issue tracker: Data Center installs use Jira.
49
50use std::sync::Arc;
51
52use serde::de::DeserializeOwned;
53
54use crate::client::{
55    encode_component, CreatedIssue, CreatedPullRequest, HostingClient, NewIssue, NewPullRequest,
56    MAX_PAGES,
57};
58use crate::conversation::{
59    Comment, ConversationCaps, ItemKey, ItemKind, PageCursor, PostingIdentity, TimelineOpts,
60    TimelinePage,
61};
62use crate::http::{HttpRequest, HttpTransport};
63use crate::integration::Integration;
64use crate::model::{
65    best_pull_request, HostedUser, IssueFilter, IssueSummary, PrFilter, PullRequestState,
66    PullRequestSummary, StateFilter, TokenCheck,
67};
68use crate::project::{HostedProject, HostedSshKey};
69use crate::{Error, Result};
70
71const LIMIT: u32 = 100;
72
73/// Why `list_issues` / `create_issue` always fail.
74pub const NO_ISSUES: &str = "Bitbucket Data Center has no issue tracker; link a Jira project";
75
76mod account;
77mod conversation;
78mod protection;
79
80pub struct BitbucketDcClient {
81    integration: Integration,
82    token: String,
83    transport: Arc<dyn HttpTransport>,
84    pub(crate) scopes: crate::scope_handle::ScopeHandle,
85}
86
87#[derive(serde::Deserialize)]
88struct Page<T> {
89    #[serde(default = "Vec::new")]
90    values: Vec<T>,
91    #[serde(default, rename = "isLastPage")]
92    is_last_page: bool,
93    #[serde(default, rename = "nextPageStart")]
94    next_page_start: Option<u64>,
95}
96
97#[derive(serde::Deserialize, Default)]
98struct Link {
99    #[serde(default)]
100    href: Option<String>,
101    #[serde(default)]
102    name: Option<String>,
103}
104
105#[derive(serde::Deserialize, Default)]
106struct Links {
107    #[serde(default, rename = "self")]
108    self_: Vec<Link>,
109    #[serde(default)]
110    clone: Vec<Link>,
111}
112
113#[derive(serde::Deserialize, Default)]
114struct User {
115    #[serde(default)]
116    name: String,
117    #[serde(default, rename = "displayName")]
118    display_name: Option<String>,
119    #[serde(default)]
120    slug: String,
121    #[serde(default)]
122    id: Option<u64>,
123    #[serde(default)]
124    links: Links,
125}
126
127impl User {
128    fn shown(&self) -> String {
129        self.display_name
130            .clone()
131            .filter(|n| !n.is_empty())
132            .unwrap_or_else(|| self.name.clone())
133    }
134}
135
136#[derive(serde::Deserialize, Default)]
137struct ProjectRef {
138    #[serde(default)]
139    key: String,
140}
141
142#[derive(serde::Deserialize, Default)]
143struct Repo {
144    #[serde(default)]
145    slug: String,
146    #[serde(default)]
147    name: String,
148    #[serde(default)]
149    description: Option<String>,
150    #[serde(default)]
151    public: bool,
152    #[serde(default)]
153    project: ProjectRef,
154    #[serde(default)]
155    links: Links,
156}
157
158impl Repo {
159    fn full_name(&self) -> String {
160        format!("{}/{}", self.project.key, self.slug)
161    }
162
163    fn into_project(self, integration_id: &str) -> HostedProject {
164        let clone = |kinds: &[&str]| {
165            self.links
166                .clone
167                .iter()
168                .find(|l| l.name.as_deref().is_some_and(|n| kinds.contains(&n)))
169                .and_then(|l| l.href.clone())
170        };
171        HostedProject {
172            integration_id: integration_id.to_string(),
173            id: self.full_name(),
174            name: if self.name.is_empty() {
175                self.slug.clone()
176            } else {
177                self.name.clone()
178            },
179            full_name: self.full_name(),
180            description: self.description.clone().filter(|d| !d.is_empty()),
181            // Not part of the repository payload (`defaultBranch` is write
182            // only in the reference): unknown here.
183            default_branch: None,
184            ssh_url: clone(&["ssh"]),
185            https_url: clone(&["http", "https"]).map(|u| without_user(&u)),
186            web_url: self.links.self_.first().and_then(|l| l.href.clone()),
187            private: !self.public,
188        }
189    }
190}
191
192/// `https://user@host/scm/K/r.git` -> without the `user@` the API embeds.
193fn without_user(url: &str) -> String {
194    match url.split_once("://") {
195        Some((scheme, rest)) => match rest.split_once('@') {
196            Some((user, tail)) if !user.contains('/') => format!("{scheme}://{tail}"),
197            _ => url.to_string(),
198        },
199        None => url.to_string(),
200    }
201}
202
203#[derive(serde::Deserialize, Default)]
204struct RepoRef {
205    #[serde(default)]
206    slug: String,
207    #[serde(default)]
208    project: ProjectRef,
209    #[serde(default)]
210    links: Links,
211}
212
213#[derive(serde::Deserialize)]
214struct Ref {
215    #[serde(default, rename = "displayId")]
216    display_id: String,
217    #[serde(default)]
218    repository: RepoRef,
219}
220
221#[derive(serde::Deserialize, Default)]
222struct Participant {
223    #[serde(default)]
224    user: User,
225    #[serde(default)]
226    status: String,
227    #[serde(default)]
228    approved: bool,
229}
230
231#[derive(serde::Deserialize)]
232struct PullRequest {
233    id: u64,
234    #[serde(default)]
235    title: String,
236    #[serde(default)]
237    state: String,
238    #[serde(default)]
239    draft: bool,
240    #[serde(rename = "fromRef")]
241    from_ref: Ref,
242    #[serde(rename = "toRef")]
243    to_ref: Ref,
244    #[serde(default)]
245    author: Participant,
246    #[serde(default)]
247    reviewers: Vec<Participant>,
248    #[serde(default, rename = "updatedDate")]
249    updated_date: u64,
250    #[serde(default)]
251    links: Links,
252}
253
254impl PullRequest {
255    fn web_url(&self) -> String {
256        self.links
257            .self_
258            .first()
259            .and_then(|l| l.href.clone())
260            .unwrap_or_default()
261    }
262
263    fn is_open(&self) -> bool {
264        self.state == "OPEN"
265    }
266
267    fn is_mine(&self, me: &str) -> bool {
268        self.author.user.name.eq_ignore_ascii_case(me)
269    }
270
271    fn review_requested(&self, me: &str) -> bool {
272        self.is_open()
273            && self.reviewers.iter().any(|r| {
274                r.user.name.eq_ignore_ascii_case(me) && !r.approved && r.status != "APPROVED"
275            })
276    }
277
278    fn into_summary(self, project: &str, me: Option<&str>) -> PullRequestSummary {
279        let state = match self.state.as_str() {
280            "MERGED" => PullRequestState::Merged,
281            "DECLINED" => PullRequestState::Closed,
282            _ if self.draft => PullRequestState::Draft,
283            _ => PullRequestState::Open,
284        };
285        let fork = format!(
286            "{}/{}",
287            self.from_ref.repository.project.key, self.from_ref.repository.slug
288        );
289        let source_project = (!self.from_ref.repository.slug.is_empty()
290            && !fork.eq_ignore_ascii_case(project))
291        .then_some(fork);
292        let review_requested = me.is_some_and(|me| self.review_requested(me));
293        let number = self.id;
294        let web_url = self.web_url();
295        PullRequestSummary {
296            number,
297            iid_label: format!("#{number}"),
298            title: self.title,
299            state,
300            source_branch: self.from_ref.display_id,
301            target_branch: self.to_ref.display_id,
302            source_project,
303            author: self.author.user.shown(),
304            web_url,
305            updated_at: epoch_ms_to_iso(self.updated_date),
306            review_requested,
307            assignees: Vec::new(),
308            reviewers: self.reviewers.iter().map(|r| r.user.shown()).collect(),
309            checks: None,
310            has_conflicts: None,
311        }
312    }
313}
314
315/// `1760000000000` -> `2025-10-09T08:53:20Z`.
316fn epoch_ms_to_iso(ms: u64) -> String {
317    if ms == 0 {
318        return String::new();
319    }
320    let secs = ms / 1000;
321    let (days, rem) = (secs / 86_400, secs % 86_400);
322    // Howard Hinnant's civil_from_days.
323    let z = days as i64 + 719_468;
324    let era = z.div_euclid(146_097);
325    let doe = z.rem_euclid(146_097);
326    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
327    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
328    let mp = (5 * doy + 2) / 153;
329    let day = doy - (153 * mp + 2) / 5 + 1;
330    let month = if mp < 10 { mp + 3 } else { mp - 9 };
331    let year = yoe + era * 400 + i64::from(month <= 2);
332    format!(
333        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
334        rem / 3600,
335        rem % 3600 / 60,
336        rem % 60
337    )
338}
339
340#[derive(serde::Deserialize)]
341struct SshKey {
342    #[serde(default)]
343    id: u64,
344    #[serde(default)]
345    label: Option<String>,
346    #[serde(default)]
347    text: String,
348}
349
350impl SshKey {
351    fn into_key(self) -> HostedSshKey {
352        HostedSshKey {
353            id: self.id.to_string(),
354            title: self.label.unwrap_or_default(),
355            key: self.text,
356        }
357    }
358}
359
360/// `KEY/slug`, however the remote spelled it: the clone path is
361/// `/scm/KEY/slug`, the browse path `projects/KEY/repos/slug`.
362fn split_project(project: &str) -> Result<(String, String)> {
363    let p = project.trim_matches('/').trim_end_matches(".git");
364    let p = p.strip_prefix("scm/").unwrap_or(p);
365    let parts: Vec<&str> = p.split('/').collect();
366    match parts.as_slice() {
367        [key, slug] if !key.is_empty() && !slug.is_empty() => {
368            Ok((key.to_string(), slug.to_string()))
369        }
370        ["projects", key, "repos", slug, ..] => Ok((key.to_string(), slug.to_string())),
371        _ => Err(Error::Decode(format!(
372            "not a Bitbucket Data Center repository (want KEY/slug): {project}"
373        ))),
374    }
375}
376
377impl BitbucketDcClient {
378    pub(crate) fn new(
379        integration: Integration,
380        token: String,
381        transport: Arc<dyn HttpTransport>,
382    ) -> Self {
383        Self {
384            integration,
385            token,
386            transport,
387            scopes: Default::default(),
388        }
389    }
390
391    fn authed(&self, mut request: HttpRequest) -> HttpRequest {
392        for (name, value) in crate::auth::auth_headers(&self.integration, &self.token) {
393            request = request.header(name, value);
394        }
395        request
396    }
397
398    fn api(&self) -> String {
399        self.integration.api_base()
400    }
401
402    /// The SSH keys REST root sits beside `/rest/api/...`.
403    fn ssh_api(&self) -> String {
404        let api = self.api();
405        let root = api.strip_suffix("/api/1.0").unwrap_or(&api);
406        format!("{root}/ssh/latest")
407    }
408
409    /// Every page, following `nextPageStart` (never a host-supplied url),
410    /// capped at [`MAX_PAGES`]. `first` already holds its query string.
411    async fn fetch_all<T: DeserializeOwned>(&self, first: String, what: &str) -> Result<Vec<T>> {
412        let mut out = Vec::new();
413        let mut start: Option<u64> = None;
414        for _ in 0..MAX_PAGES {
415            let url = match start {
416                None => first.clone(),
417                Some(s) => format!("{first}&start={s}"),
418            };
419            let response = self
420                .transport
421                .send(self.authed(HttpRequest::get(url)))
422                .await?;
423            response.error_for_status(what)?;
424            let page: Page<T> = response.json()?;
425            out.extend(page.values);
426            match (page.is_last_page, page.next_page_start) {
427                (false, Some(next)) => start = Some(next),
428                _ => break,
429            }
430        }
431        Ok(out)
432    }
433
434    /// The authenticated user's name, from the `X-AUSERNAME` header.
435    async fn my_name(&self) -> Result<String> {
436        let response = self
437            .transport
438            .send(self.authed(HttpRequest::get(format!(
439                "{}/application-properties",
440                self.api()
441            ))))
442            .await?;
443        response.error_for_status("reading the Bitbucket Data Center account")?;
444        response
445            .headers
446            .iter()
447            .find(|(k, _)| k.eq_ignore_ascii_case("x-ausername"))
448            .map(|(_, v)| v.trim().to_string())
449            .filter(|v| !v.is_empty())
450            .ok_or_else(|| {
451                Error::Decode(
452                    "Bitbucket Data Center did not name the authenticated user (no X-AUSERNAME header)"
453                        .to_string(),
454                )
455            })
456    }
457
458    fn pr_url(&self, project: &str) -> Result<String> {
459        let (key, slug) = split_project(project)?;
460        Ok(format!(
461            "{}/projects/{}/repos/{}/pull-requests",
462            self.api(),
463            encode_component(&key),
464            encode_component(&slug)
465        ))
466    }
467
468    async fn pull_requests(
469        &self,
470        project: &str,
471        state: &str,
472        extra: &str,
473        what: &str,
474    ) -> Result<Vec<PullRequest>> {
475        let url = format!(
476            "{}?state={state}&order=NEWEST&limit={LIMIT}{extra}",
477            self.pr_url(project)?
478        );
479        self.fetch_all(url, what).await
480    }
481
482    fn ref_json(project: &str, branch: &str) -> Result<serde_json::Value> {
483        let (key, slug) = split_project(project)?;
484        Ok(serde_json::json!({
485            "id": format!("refs/heads/{branch}"),
486            "repository": { "slug": slug, "project": { "key": key } },
487        }))
488    }
489}
490
491#[async_trait::async_trait]
492impl HostingClient for BitbucketDcClient {
493    fn integration(&self) -> &Integration {
494        &self.integration
495    }
496
497    async fn list_projects(&self) -> Result<Vec<HostedProject>> {
498        let url = format!("{}/repos?limit={LIMIT}", self.api());
499        let rows: Vec<Repo> = self
500            .fetch_all(url, "listing Bitbucket repositories")
501            .await?;
502        Ok(rows
503            .into_iter()
504            .map(|r| r.into_project(&self.integration.id))
505            .collect())
506    }
507
508    async fn account_items(
509        &self,
510        query: &crate::account::AccountQuery,
511    ) -> Result<crate::account::AccountItems> {
512        account::fetch(self, query).await
513    }
514
515    async fn list_ssh_keys(&self) -> Result<Vec<HostedSshKey>> {
516        let url = format!("{}/keys?limit={LIMIT}", self.ssh_api());
517        let rows: Vec<SshKey> = self.fetch_all(url, "listing Bitbucket SSH keys").await?;
518        Ok(rows.into_iter().map(SshKey::into_key).collect())
519    }
520
521    async fn upload_ssh_key(&self, title: &str, public_key: &str) -> Result<HostedSshKey> {
522        let body = serde_json::json!({ "text": public_key.trim(), "label": title });
523        let response = self
524            .transport
525            .send(self.authed(HttpRequest::post_json(
526                format!("{}/keys", self.ssh_api()),
527                &body,
528            )))
529            .await?;
530        response.error_for_status("uploading an SSH key to Bitbucket")?;
531        Ok(response.json::<SshKey>()?.into_key())
532    }
533
534    async fn delete_ssh_key(&self, id: &str) -> Result<()> {
535        let url = format!("{}/keys/{}", self.ssh_api(), encode_component(id));
536        let response = self
537            .transport
538            .send(self.authed(HttpRequest::delete(url)))
539            .await?;
540        response.error_for_status("deleting a Bitbucket SSH key")
541    }
542
543    async fn create_pull_request(&self, req: &NewPullRequest) -> Result<CreatedPullRequest> {
544        let from_project = req.fork_source().unwrap_or(&req.project);
545        let body = serde_json::json!({
546            "title": req.title,
547            "description": req.body,
548            "draft": req.draft,
549            "fromRef": Self::ref_json(from_project, &req.source_branch)?,
550            "toRef": Self::ref_json(&req.project, &req.target_branch)?,
551        });
552        let response = self
553            .transport
554            .send(self.authed(HttpRequest::post_json(self.pr_url(&req.project)?, &body)))
555            .await?;
556        response.error_for_status("opening a Bitbucket pull request")?;
557        let created: PullRequest = response.json()?;
558        Ok(CreatedPullRequest {
559            number: created.id,
560            web_url: created.web_url(),
561            ..Default::default()
562        })
563    }
564
565    async fn protected_branches(
566        &self,
567        project: &str,
568    ) -> Result<crate::protection::ProtectedBranches> {
569        self.protection(project).await
570    }
571
572    async fn current_user(&self) -> Result<HostedUser> {
573        let name = self.my_name().await?;
574        let url = format!("{}/users/{}", self.api(), encode_component(&name));
575        let response = self
576            .transport
577            .send(self.authed(HttpRequest::get(url)))
578            .await?;
579        response.error_for_status("checking the Bitbucket token")?;
580        let user: User = response.json()?;
581        Ok(HostedUser {
582            login: if user.name.is_empty() {
583                name
584            } else {
585                user.name
586            },
587            name: user.display_name.unwrap_or_default(),
588            id: user.id.map(|i| i.to_string()).unwrap_or(user.slug),
589            web_url: user.links.self_.first().and_then(|l| l.href.clone()),
590        })
591    }
592
593    async fn check_token(&self) -> Result<TokenCheck> {
594        // An access token's permissions are not reported: unknown, never
595        // "missing".
596        Ok(TokenCheck {
597            user: self.current_user().await?,
598            scopes: None,
599            missing_scopes: Vec::new(),
600            expires_at: None,
601            ..Default::default()
602        })
603    }
604
605    async fn list_pull_requests(
606        &self,
607        project: &str,
608        filter: &PrFilter,
609    ) -> Result<Vec<PullRequestSummary>> {
610        let states: &[&str] = match filter.state {
611            StateFilter::Open => &["OPEN"],
612            // `state` takes one value: closed is two requests.
613            StateFilter::Closed => &["MERGED", "DECLINED"],
614            StateFilter::All => &["ALL"],
615        };
616        let me = if filter.mine || filter.review_requested {
617            Some(self.my_name().await?)
618        } else {
619            None
620        };
621        let mut rows = Vec::new();
622        for state in states {
623            rows.extend(
624                self.pull_requests(project, state, "", "listing Bitbucket pull requests")
625                    .await?,
626            );
627        }
628        rows.sort_by_key(|r| std::cmp::Reverse(r.updated_date));
629        Ok(rows
630            .into_iter()
631            .filter(|r| match (&me, filter.mine) {
632                (Some(me), true) => r.is_mine(me),
633                _ => true,
634            })
635            .map(|r| r.into_summary(project, me.as_deref()))
636            .filter(|s| !filter.review_requested || s.review_requested)
637            .collect())
638    }
639
640    async fn pull_request_for_branch(
641        &self,
642        project: &str,
643        branch: &str,
644    ) -> Result<Option<PullRequestSummary>> {
645        let extra = format!(
646            "&direction=OUTGOING&at={}",
647            encode_component(&format!("refs/heads/{branch}"))
648        );
649        let rows = self
650            .pull_requests(
651                project,
652                "ALL",
653                &extra,
654                "looking up the pull request for a branch",
655            )
656            .await?;
657        Ok(best_pull_request(
658            rows.into_iter()
659                .map(|r| r.into_summary(project, None))
660                .collect(),
661        ))
662    }
663
664    async fn list_issues(
665        &self,
666        _project: &str,
667        _filter: &IssueFilter,
668    ) -> Result<Vec<IssueSummary>> {
669        Err(Error::Unsupported(NO_ISSUES.to_string()))
670    }
671
672    async fn create_issue(&self, _req: &NewIssue) -> Result<CreatedIssue> {
673        Err(Error::Unsupported(NO_ISSUES.to_string()))
674    }
675
676    fn conversation_caps(&self, kind: ItemKind) -> ConversationCaps {
677        ConversationCaps::bitbucket(kind)
678    }
679
680    async fn posting_identity(&self, project: &str) -> Result<PostingIdentity> {
681        self.conv_identity(project).await
682    }
683
684    async fn item_timeline(
685        &self,
686        project: &str,
687        key: &ItemKey,
688        older: Option<&PageCursor>,
689        opts: &TimelineOpts,
690    ) -> Result<TimelinePage> {
691        self.conv_timeline(project, key, older, opts).await
692    }
693
694    async fn post_item_comment(
695        &self,
696        project: &str,
697        key: &ItemKey,
698        body: &str,
699        internal: bool,
700    ) -> Result<Comment> {
701        self.conv_post(project, key, body, internal).await
702    }
703
704    async fn reply_in_discussion(
705        &self,
706        project: &str,
707        key: &ItemKey,
708        discussion_id: &str,
709        body: &str,
710    ) -> Result<Comment> {
711        self.conv_reply(project, key, discussion_id, body).await
712    }
713
714    async fn edit_item_comment(
715        &self,
716        project: &str,
717        key: &ItemKey,
718        comment_id: &str,
719        body: &str,
720    ) -> Result<Comment> {
721        self.conv_edit(project, key, comment_id, body).await
722    }
723
724    async fn delete_item_comment(
725        &self,
726        project: &str,
727        key: &ItemKey,
728        comment_id: &str,
729    ) -> Result<()> {
730        self.conv_delete(project, key, comment_id).await
731    }
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use crate::client::client_for;
738    use crate::http::RecordedTransport;
739    use crate::spec::{spec_for, CheckoutSource};
740    use crate::IntegrationKind;
741    use gitpoulpi_config::ApiFamily;
742
743    fn block_on<F: std::future::Future>(f: F) -> F::Output {
744        tokio::runtime::Builder::new_current_thread()
745            .enable_all()
746            .build()
747            .unwrap()
748            .block_on(f)
749    }
750
751    fn profile() -> Integration {
752        let mut i = Integration::new(
753            "dc",
754            IntegrationKind::BitbucketDataCenter,
755            "https://git.example.com/",
756        );
757        i.account = String::new();
758        i
759    }
760
761    fn pr(id: u64, state: &str, draft: bool, author: &str, reviewer: &str, ms: u64) -> String {
762        format!(
763            r#"{{"id":{id},"title":"T{id}","state":"{state}","draft":{draft},"updatedDate":{ms},
764            "fromRef":{{"id":"refs/heads/feat","displayId":"feat","repository":{{"slug":"fork","project":{{"key":"~ANN"}}}}}},
765            "toRef":{{"id":"refs/heads/main","displayId":"main","repository":{{"slug":"repo","project":{{"key":"PRJ"}}}}}},
766            "author":{{"user":{{"name":"{author}","displayName":"Author {author}"}},"role":"AUTHOR"}},
767            "reviewers":[{{"user":{{"name":"{reviewer}","displayName":"Rev {reviewer}"}},"role":"REVIEWER","approved":false,"status":"UNAPPROVED"}}],
768            "links":{{"self":[{{"href":"https://git.example.com/projects/PRJ/repos/repo/pull-requests/{id}"}}]}}}}"#
769        )
770    }
771
772    fn page(rows: &[String], last: bool, next: u64) -> String {
773        format!(
774            r#"{{"size":{},"limit":100,"isLastPage":{last},"nextPageStart":{next},"values":[{}]}}"#,
775            rows.len(),
776            rows.join(",")
777        )
778    }
779
780    fn client(t: Arc<RecordedTransport>) -> Box<dyn HostingClient> {
781        client_for(
782            profile(),
783            "tok".into(),
784            t,
785            &crate::trust::TrustGate::for_tests(),
786        )
787        .unwrap()
788    }
789
790    #[test]
791    fn the_dc_kind_gets_the_dc_client_with_a_bearer_token() {
792        let t = Arc::new(RecordedTransport::new().on("/repos", 200, &page(&[], true, 0)));
793        let c = client(t.clone());
794        assert!(block_on(c.list_projects()).unwrap().is_empty());
795        let seen = t.requests();
796        assert_eq!(
797            seen[0].url,
798            "https://git.example.com/rest/api/1.0/repos?limit=100"
799        );
800        assert!(seen[0]
801            .headers
802            .iter()
803            .any(|(k, v)| k == "Authorization" && v == "Bearer tok"));
804    }
805
806    #[test]
807    fn repositories_page_with_next_page_start_and_map_clone_links() {
808        let repo = |slug: &str| {
809            format!(
810                r#"{{"slug":"{slug}","name":"{slug}","public":false,"project":{{"key":"PRJ"}},
811                "links":{{"clone":[{{"href":"https://me@git.example.com/scm/prj/{slug}.git","name":"http"}},
812                {{"href":"ssh://git@git.example.com:7999/prj/{slug}.git","name":"ssh"}}],
813                "self":[{{"href":"https://git.example.com/projects/PRJ/repos/{slug}/browse"}}]}}}}"#
814            )
815        };
816        let t = Arc::new(
817            RecordedTransport::new()
818                .on("start=1", 200, &page(&[repo("b")], true, 0))
819                .on("/repos", 200, &page(&[repo("a")], false, 1)),
820        );
821        let rows = block_on(client(t.clone()).list_projects()).unwrap();
822        assert_eq!(rows.len(), 2);
823        assert_eq!(rows[0].full_name, "PRJ/a");
824        assert_eq!(
825            rows[0].https_url.as_deref(),
826            Some("https://git.example.com/scm/prj/a.git")
827        );
828        assert_eq!(
829            rows[0].ssh_url.as_deref(),
830            Some("ssh://git@git.example.com:7999/prj/a.git")
831        );
832        assert!(rows[0].private);
833        assert_eq!(t.requests().len(), 2);
834        assert!(t.requests()[1].url.ends_with("limit=100&start=1"));
835    }
836
837    #[test]
838    fn current_user_reads_x_ausername_then_the_user_record() {
839        let t = Arc::new(
840            RecordedTransport::new()
841                .on_with_headers(
842                    "/application-properties",
843                    200,
844                    "{}",
845                    &[("X-AUSERNAME", "jdoe")],
846                )
847                .on(
848                    "/users/jdoe",
849                    200,
850                    r#"{"name":"jdoe","slug":"jdoe","id":7,"displayName":"Jane Doe",
851                    "links":{"self":[{"href":"https://git.example.com/users/jdoe"}]}}"#,
852                ),
853        );
854        let user = block_on(client(t.clone()).current_user()).unwrap();
855        assert_eq!(
856            (user.login.as_str(), user.name.as_str(), user.id.as_str()),
857            ("jdoe", "Jane Doe", "7")
858        );
859        assert_eq!(
860            user.web_url.as_deref(),
861            Some("https://git.example.com/users/jdoe")
862        );
863    }
864
865    #[test]
866    fn a_missing_x_ausername_is_a_clear_error() {
867        let t = Arc::new(RecordedTransport::new().on("/application-properties", 200, "{}"));
868        let err = block_on(client(t).current_user()).unwrap_err();
869        assert!(err.to_string().contains("X-AUSERNAME"), "{err}");
870    }
871
872    #[test]
873    fn pull_requests_map_state_draft_fork_and_milliseconds() {
874        let rows = [
875            pr(1, "OPEN", false, "ann", "jdoe", 1_760_000_000_000),
876            pr(2, "OPEN", true, "bob", "zed", 1_760_000_100_000),
877            pr(3, "MERGED", false, "ann", "zed", 1_760_000_200_000),
878            pr(4, "DECLINED", false, "ann", "zed", 1_760_000_300_000),
879        ];
880        let t = Arc::new(RecordedTransport::new().on("/pull-requests", 200, &page(&rows, true, 0)));
881        let got = block_on(client(t.clone()).list_pull_requests(
882            "PRJ/repo",
883            &PrFilter {
884                state: StateFilter::All,
885                ..PrFilter::default()
886            },
887        ))
888        .unwrap();
889        assert_eq!(
890            t.requests()[0].url,
891            "https://git.example.com/rest/api/1.0/projects/PRJ/repos/repo/pull-requests?state=ALL&order=NEWEST&limit=100"
892        );
893        // Newest first.
894        assert_eq!(
895            got.iter().map(|p| p.number).collect::<Vec<_>>(),
896            [4, 3, 2, 1]
897        );
898        let by = |n: u64| got.iter().find(|p| p.number == n).unwrap();
899        assert_eq!(by(1).state, PullRequestState::Open);
900        assert_eq!(by(2).state, PullRequestState::Draft);
901        assert_eq!(by(3).state, PullRequestState::Merged);
902        assert_eq!(by(4).state, PullRequestState::Closed);
903        assert_eq!(by(1).source_project.as_deref(), Some("~ANN/fork"));
904        assert_eq!(by(1).source_branch, "feat");
905        assert_eq!(by(1).target_branch, "main");
906        assert_eq!(by(1).updated_at, "2025-10-09T08:53:20Z");
907        assert_eq!(by(1).author, "Author ann");
908        assert_eq!(by(1).reviewers, ["Rev jdoe"]);
909        assert_eq!(
910            by(1).web_url,
911            "https://git.example.com/projects/PRJ/repos/repo/pull-requests/1"
912        );
913    }
914
915    #[test]
916    fn closed_is_two_requests_and_mine_and_review_requested_filter_locally() {
917        let open = [
918            pr(1, "OPEN", false, "ann", "jdoe", 1_000),
919            pr(2, "OPEN", false, "jdoe", "zed", 2_000),
920        ];
921        let t = Arc::new(
922            RecordedTransport::new()
923                .on_with_headers(
924                    "/application-properties",
925                    200,
926                    "{}",
927                    &[("x-ausername", "jdoe")],
928                )
929                .on("/pull-requests", 200, &page(&open, true, 0)),
930        );
931        let c = client(t.clone());
932        let mine = block_on(c.list_pull_requests(
933            "PRJ/repo",
934            &PrFilter {
935                mine: true,
936                ..PrFilter::default()
937            },
938        ))
939        .unwrap();
940        assert_eq!(mine.iter().map(|p| p.number).collect::<Vec<_>>(), [2]);
941        let review = block_on(c.list_pull_requests(
942            "PRJ/repo",
943            &PrFilter {
944                review_requested: true,
945                ..PrFilter::default()
946            },
947        ))
948        .unwrap();
949        assert_eq!(review.iter().map(|p| p.number).collect::<Vec<_>>(), [1]);
950
951        let closed =
952            Arc::new(RecordedTransport::new().on("/pull-requests", 200, &page(&[], true, 0)));
953        block_on(client(closed.clone()).list_pull_requests(
954            "PRJ/repo",
955            &PrFilter {
956                state: StateFilter::Closed,
957                ..PrFilter::default()
958            },
959        ))
960        .unwrap();
961        let urls: Vec<String> = closed.requests().into_iter().map(|r| r.url).collect();
962        assert!(urls[0].contains("state=MERGED") && urls[1].contains("state=DECLINED"));
963    }
964
965    #[test]
966    fn the_branch_lookup_asks_for_outgoing_requests_at_the_ref() {
967        let t = Arc::new(RecordedTransport::new().on(
968            "/pull-requests",
969            200,
970            &page(&[pr(9, "OPEN", false, "ann", "zed", 5)], true, 0),
971        ));
972        // A remote spelled with the clone path still resolves.
973        let found =
974            block_on(client(t.clone()).pull_request_for_branch("scm/PRJ/repo.git", "feat/x"))
975                .unwrap()
976                .unwrap();
977        assert_eq!(found.number, 9);
978        let url = &t.requests()[0].url;
979        assert!(
980            url.contains("/projects/PRJ/repos/repo/pull-requests?state=ALL"),
981            "{url}"
982        );
983        assert!(
984            url.contains("direction=OUTGOING&at=refs%2Fheads%2Ffeat%2Fx"),
985            "{url}"
986        );
987    }
988
989    #[test]
990    fn create_posts_refs_with_slug_and_project_key_and_reads_the_web_url() {
991        let t = Arc::new(RecordedTransport::new().on(
992            "/pull-requests",
993            201,
994            &pr(12, "OPEN", true, "ann", "zed", 5),
995        ));
996        let created = block_on(client(t.clone()).create_pull_request(&NewPullRequest {
997            project: "PRJ/repo".into(),
998            source_branch: "feat".into(),
999            target_branch: "main".into(),
1000            title: "Title".into(),
1001            body: "Body".into(),
1002            draft: true,
1003            source_project: Some("~ANN/fork".into()),
1004            ..Default::default()
1005        }))
1006        .unwrap();
1007        assert_eq!(created.number, 12);
1008        assert_eq!(
1009            created.web_url,
1010            "https://git.example.com/projects/PRJ/repos/repo/pull-requests/12"
1011        );
1012        let req = &t.requests()[0];
1013        assert_eq!(
1014            req.url,
1015            "https://git.example.com/rest/api/1.0/projects/PRJ/repos/repo/pull-requests"
1016        );
1017        let body: serde_json::Value = serde_json::from_str(req.body.as_deref().unwrap()).unwrap();
1018        assert_eq!(body["title"], "Title");
1019        assert_eq!(body["description"], "Body");
1020        assert_eq!(body["draft"], true);
1021        assert_eq!(body["fromRef"]["id"], "refs/heads/feat");
1022        assert_eq!(body["fromRef"]["repository"]["slug"], "fork");
1023        assert_eq!(body["fromRef"]["repository"]["project"]["key"], "~ANN");
1024        assert_eq!(body["toRef"]["id"], "refs/heads/main");
1025        assert_eq!(body["toRef"]["repository"]["project"]["key"], "PRJ");
1026    }
1027
1028    #[test]
1029    fn ssh_keys_use_the_ssh_rest_root() {
1030        let key = r#"{"id":5,"label":"laptop","text":"ssh-ed25519 AAAA me"}"#;
1031        let t = Arc::new(RecordedTransport::new().on("/keys/5", 204, "").on(
1032            "/ssh/latest/keys",
1033            200,
1034            &format!(r#"{{"isLastPage":true,"values":[{key}]}}"#),
1035        ));
1036        let c = client(t.clone());
1037        let keys = block_on(c.list_ssh_keys()).unwrap();
1038        assert_eq!(
1039            (keys[0].id.as_str(), keys[0].title.as_str()),
1040            ("5", "laptop")
1041        );
1042        assert_eq!(
1043            t.requests()[0].url,
1044            "https://git.example.com/rest/ssh/latest/keys?limit=100"
1045        );
1046        block_on(c.delete_ssh_key("5")).unwrap();
1047        assert_eq!(
1048            t.requests()[1].url,
1049            "https://git.example.com/rest/ssh/latest/keys/5"
1050        );
1051    }
1052
1053    #[test]
1054    fn issues_are_unsupported() {
1055        let c = client(Arc::new(RecordedTransport::new()));
1056        assert!(matches!(
1057            block_on(c.list_issues("PRJ/repo", &IssueFilter::default())),
1058            Err(Error::Unsupported(_))
1059        ));
1060    }
1061
1062    #[test]
1063    fn project_spellings_and_epoch_dates() {
1064        assert_eq!(
1065            split_project("PRJ/repo").unwrap(),
1066            ("PRJ".into(), "repo".into())
1067        );
1068        assert_eq!(
1069            split_project("scm/~ann/repo.git").unwrap(),
1070            ("~ann".into(), "repo".into())
1071        );
1072        assert_eq!(
1073            split_project("projects/PRJ/repos/repo/browse").unwrap(),
1074            ("PRJ".into(), "repo".into())
1075        );
1076        assert!(split_project("just-one").is_err());
1077        assert_eq!(epoch_ms_to_iso(0), "");
1078        assert_eq!(epoch_ms_to_iso(951_782_400_000), "2000-02-29T00:00:00Z");
1079    }
1080
1081    #[test]
1082    fn a_data_center_pull_request_is_fetched_from_its_head_ref() {
1083        let summary = block_on(async {
1084            let t = Arc::new(RecordedTransport::new().on(
1085                "/pull-requests",
1086                200,
1087                &page(&[pr(7, "OPEN", false, "ann", "zed", 5)], true, 0),
1088            ));
1089            client(t)
1090                .list_pull_requests("PRJ/repo", &PrFilter::default())
1091                .await
1092                .unwrap()
1093                .remove(0)
1094        });
1095        assert_eq!(
1096            (spec_for(ApiFamily::Bitbucket).checkout)(&summary),
1097            CheckoutSource::HeadRef {
1098                remote_ref: "refs/pull-requests/7/from".into(),
1099                local: "pr/7".into(),
1100            }
1101        );
1102    }
1103}