Skip to main content

bitbucket_cli/api/
pipelines.rs

1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::models::{Paginated, Pipeline, PipelineStep, TriggerPipelineRequest};
5
6impl BitbucketClient {
7    /// List pipelines for a repository
8    pub async fn list_pipelines(
9        &self,
10        workspace: &str,
11        repo_slug: &str,
12        page: Option<u32>,
13        pagelen: Option<u32>,
14    ) -> Result<Paginated<Pipeline>> {
15        let mut query = Vec::new();
16
17        // Sort by created_on descending to get most recent first
18        query.push(("sort", "-created_on".to_string()));
19
20        if let Some(p) = page {
21            query.push(("page", p.to_string()));
22        }
23        if let Some(len) = pagelen {
24            query.push(("pagelen", len.to_string()));
25        }
26
27        let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
28
29        let path = format!("/repositories/{}/{}/pipelines", workspace, repo_slug);
30        self.get_with_query(&path, &query_refs).await
31    }
32
33    /// Get a specific pipeline
34    pub async fn get_pipeline(
35        &self,
36        workspace: &str,
37        repo_slug: &str,
38        pipeline_uuid: &str,
39    ) -> Result<Pipeline> {
40        let path = format!(
41            "/repositories/{}/{}/pipelines/{}",
42            workspace, repo_slug, pipeline_uuid
43        );
44        self.get(&path).await
45    }
46
47    /// Trigger a new pipeline
48    pub async fn trigger_pipeline(
49        &self,
50        workspace: &str,
51        repo_slug: &str,
52        request: &TriggerPipelineRequest,
53    ) -> Result<Pipeline> {
54        let path = format!("/repositories/{}/{}/pipelines", workspace, repo_slug);
55        self.post(&path, request).await
56    }
57
58    /// Stop a running pipeline
59    pub async fn stop_pipeline(
60        &self,
61        workspace: &str,
62        repo_slug: &str,
63        pipeline_uuid: &str,
64    ) -> Result<()> {
65        let path = format!(
66            "/repositories/{}/{}/pipelines/{}/stopPipeline",
67            workspace, repo_slug, pipeline_uuid
68        );
69        self.post_no_response(&path, &serde_json::json!({})).await
70    }
71
72    /// List steps for a pipeline
73    pub async fn list_pipeline_steps(
74        &self,
75        workspace: &str,
76        repo_slug: &str,
77        pipeline_uuid: &str,
78    ) -> Result<Paginated<PipelineStep>> {
79        let path = format!(
80            "/repositories/{}/{}/pipelines/{}/steps",
81            workspace, repo_slug, pipeline_uuid
82        );
83        self.get(&path).await
84    }
85
86    /// Get a specific pipeline step
87    pub async fn get_pipeline_step(
88        &self,
89        workspace: &str,
90        repo_slug: &str,
91        pipeline_uuid: &str,
92        step_uuid: &str,
93    ) -> Result<PipelineStep> {
94        let path = format!(
95            "/repositories/{}/{}/pipelines/{}/steps/{}",
96            workspace, repo_slug, pipeline_uuid, step_uuid
97        );
98        self.get(&path).await
99    }
100
101    /// Get pipeline step log
102    pub async fn get_step_log(
103        &self,
104        workspace: &str,
105        repo_slug: &str,
106        pipeline_uuid: &str,
107        step_uuid: &str,
108    ) -> Result<String> {
109        let path = format!(
110            "/repositories/{}/{}/pipelines/{}/steps/{}/log",
111            workspace, repo_slug, pipeline_uuid, step_uuid
112        );
113
114        self.get_text(&path, None).await
115    }
116
117    /// List pipelines whose target commit matches `commit_hash`, newest first.
118    ///
119    /// Bitbucket's pipelines endpoint does not expose a server-side filter on
120    /// `target.commit.hash` (both the `?target.commit.hash=` query param and
121    /// the BBQL `q=` filter are silently ignored as of the 2.0 API), so this
122    /// fetches the most recent pipelines and filters client-side. `scan_limit`
123    /// bounds how many of the repo's recent pipelines are scanned and is
124    /// capped at Bitbucket's pagelen ceiling of 100; on repos that churn more
125    /// than 100 pipelines between the commit landing and this call, matches
126    /// older than that window will be missed.
127    pub async fn list_pipelines_for_commit(
128        &self,
129        workspace: &str,
130        repo_slug: &str,
131        commit_hash: &str,
132        scan_limit: u32,
133    ) -> Result<Vec<Pipeline>> {
134        let pagelen = scan_limit.clamp(1, 100);
135        let pipelines = self
136            .list_pipelines(workspace, repo_slug, None, Some(pagelen))
137            .await?;
138        Ok(pipelines
139            .values
140            .into_iter()
141            .filter(|p| {
142                p.target
143                    .commit
144                    .as_ref()
145                    .is_some_and(|c| commit_hashes_match(&c.hash, commit_hash))
146            })
147            .collect())
148    }
149
150    /// Get pipeline by build number
151    pub async fn get_pipeline_by_build_number(
152        &self,
153        workspace: &str,
154        repo_slug: &str,
155        build_number: u64,
156    ) -> Result<Pipeline> {
157        // Search for the pipeline with the given build number, newest first,
158        // scanning at most 50 pages of 100 pipelines each.
159        find_pipeline_by_build_number(
160            |page| self.list_pipelines(workspace, repo_slug, Some(page), Some(100)),
161            build_number,
162            50,
163        )
164        .await
165    }
166}
167
168/// Walk pages of pipelines, newest first, looking for a matching build number.
169///
170/// Fetches pages `1..=max_pages` via `fetch_page` and returns as soon as a
171/// pipeline with `build_number` is found. Stops early when a page has no
172/// `next` link; errors if the page cap is reached without a match so a bogus
173/// build number can't trigger an unbounded page walk.
174async fn find_pipeline_by_build_number<F, Fut>(
175    mut fetch_page: F,
176    build_number: u64,
177    max_pages: u32,
178) -> Result<Pipeline>
179where
180    F: FnMut(u32) -> Fut,
181    Fut: std::future::Future<Output = Result<Paginated<Pipeline>>>,
182{
183    let mut pipelines_seen: usize = 0;
184
185    for page in 1..=max_pages {
186        let pipelines = fetch_page(page).await?;
187        let has_next = pipelines.next.is_some();
188        pipelines_seen += pipelines.values.len();
189
190        if let Some(pipeline) = pipelines
191            .values
192            .into_iter()
193            .find(|p| p.build_number == build_number)
194        {
195            return Ok(pipeline);
196        }
197
198        if !has_next {
199            return Err(anyhow::anyhow!("Pipeline #{} not found", build_number));
200        }
201    }
202
203    Err(anyhow::anyhow!(
204        "Pipeline #{} not found (searched the {} most recent pipelines)",
205        build_number,
206        pipelines_seen
207    ))
208}
209
210/// Compare two git commit hashes that may differ in length.
211///
212/// Bitbucket's pull-request API returns a 12-char short hash while the
213/// pipelines API returns the full 40-char hash. Match by treating the
214/// shorter of the two as a prefix of the longer.
215fn commit_hashes_match(a: &str, b: &str) -> bool {
216    let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
217    !short.is_empty() && long.starts_with(short)
218}
219
220#[cfg(test)]
221mod tests {
222    use std::cell::Cell;
223    use std::future::{Ready, ready};
224
225    use chrono::Utc;
226
227    use super::{commit_hashes_match, find_pipeline_by_build_number};
228    use crate::models::{Paginated, Pipeline, PipelineState, PipelineStateName, PipelineTarget};
229
230    fn pipeline(build_number: u64) -> Pipeline {
231        Pipeline {
232            uuid: format!("{{pipeline-{}}}", build_number),
233            build_number,
234            creator: None,
235            repository: None,
236            target: PipelineTarget {
237                target_type: "pipeline_ref_target".to_string(),
238                ref_type: None,
239                ref_name: None,
240                selector: None,
241                commit: None,
242            },
243            trigger: None,
244            state: PipelineState {
245                name: PipelineStateName::Completed,
246                state_type: "pipeline_state_completed".to_string(),
247                result: None,
248                stage: None,
249            },
250            created_on: Utc::now(),
251            completed_on: None,
252            build_seconds_used: None,
253            links: None,
254        }
255    }
256
257    fn page(values: Vec<Pipeline>, has_next: bool) -> Paginated<Pipeline> {
258        Paginated {
259            size: None,
260            page: None,
261            pagelen: None,
262            next: has_next.then(|| "https://api.bitbucket.org/next".to_string()),
263            previous: None,
264            values,
265        }
266    }
267
268    type PageFuture = Ready<anyhow::Result<Paginated<Pipeline>>>;
269
270    #[tokio::test]
271    async fn finds_pipeline_on_second_page_with_exactly_two_fetches() {
272        let calls = Cell::new(0u32);
273        let fetch = |page_number: u32| -> PageFuture {
274            calls.set(calls.get() + 1);
275            ready(Ok(match page_number {
276                1 => page(vec![pipeline(100), pipeline(99)], true),
277                2 => page(vec![pipeline(98), pipeline(42)], true),
278                other => panic!("unexpected page fetch: {}", other),
279            }))
280        };
281
282        let found = find_pipeline_by_build_number(fetch, 42, 50)
283            .await
284            .expect("pipeline should be found on page 2");
285
286        assert_eq!(found.build_number, 42);
287        assert_eq!(calls.get(), 2);
288    }
289
290    #[tokio::test]
291    async fn stops_after_one_fetch_when_pages_are_exhausted() {
292        let calls = Cell::new(0u32);
293        let fetch = |_page_number: u32| -> PageFuture {
294            calls.set(calls.get() + 1);
295            ready(Ok(page(vec![pipeline(100), pipeline(99)], false)))
296        };
297
298        let err = find_pipeline_by_build_number(fetch, 42, 50)
299            .await
300            .expect_err("pipeline should not be found");
301
302        assert_eq!(err.to_string(), "Pipeline #42 not found");
303        assert_eq!(calls.get(), 1);
304    }
305
306    #[tokio::test]
307    async fn enforces_page_cap_when_next_is_always_present() {
308        let calls = Cell::new(0u32);
309        let fetch = |_page_number: u32| -> PageFuture {
310            calls.set(calls.get() + 1);
311            ready(Ok(page(vec![pipeline(100), pipeline(99)], true)))
312        };
313
314        let err = find_pipeline_by_build_number(fetch, 42, 3)
315            .await
316            .expect_err("search should stop at the page cap");
317
318        assert_eq!(
319            err.to_string(),
320            "Pipeline #42 not found (searched the 6 most recent pipelines)"
321        );
322        assert_eq!(calls.get(), 3);
323    }
324
325    #[test]
326    fn exact_equality_matches() {
327        assert!(commit_hashes_match("abc123", "abc123"));
328    }
329
330    #[test]
331    fn short_pr_hash_matches_full_pipeline_hash() {
332        assert!(commit_hashes_match(
333            "975f24a99dab12345abc678def910ghi112233jk",
334            "975f24a99dab"
335        ));
336    }
337
338    #[test]
339    fn full_pr_hash_matches_short_pipeline_hash() {
340        assert!(commit_hashes_match(
341            "975f24a99dab",
342            "975f24a99dab12345abc678def910ghi112233jk"
343        ));
344    }
345
346    #[test]
347    fn different_commits_do_not_match() {
348        assert!(!commit_hashes_match("abc123def", "abc999def"));
349    }
350
351    #[test]
352    fn empty_hash_never_matches() {
353        // Guard against false positives if the API returns a missing hash
354        // that somehow deserializes to an empty string.
355        assert!(!commit_hashes_match("", "abc123"));
356        assert!(!commit_hashes_match("abc123", ""));
357        assert!(!commit_hashes_match("", ""));
358    }
359}