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        let response = reqwest::Client::new()
115            .get(self.url(&path))
116            .header("Authorization", self.auth_header())
117            .send()
118            .await?;
119
120        if response.status().is_success() {
121            Ok(response.text().await?)
122        } else {
123            anyhow::bail!("Failed to get step log: {}", response.status())
124        }
125    }
126
127    /// List pipelines whose target commit matches `commit_hash`, newest first.
128    ///
129    /// Bitbucket's pipelines endpoint does not expose a server-side filter on
130    /// `target.commit.hash` (both the `?target.commit.hash=` query param and
131    /// the BBQL `q=` filter are silently ignored as of the 2.0 API), so this
132    /// fetches the most recent pipelines and filters client-side. `scan_limit`
133    /// bounds how many of the repo's recent pipelines are scanned and is
134    /// capped at Bitbucket's pagelen ceiling of 100; on repos that churn more
135    /// than 100 pipelines between the commit landing and this call, matches
136    /// older than that window will be missed.
137    pub async fn list_pipelines_for_commit(
138        &self,
139        workspace: &str,
140        repo_slug: &str,
141        commit_hash: &str,
142        scan_limit: u32,
143    ) -> Result<Vec<Pipeline>> {
144        let pagelen = scan_limit.clamp(1, 100);
145        let pipelines = self
146            .list_pipelines(workspace, repo_slug, None, Some(pagelen))
147            .await?;
148        Ok(pipelines
149            .values
150            .into_iter()
151            .filter(|p| {
152                p.target
153                    .commit
154                    .as_ref()
155                    .is_some_and(|c| commit_hashes_match(&c.hash, commit_hash))
156            })
157            .collect())
158    }
159
160    /// Get pipeline by build number
161    pub async fn get_pipeline_by_build_number(
162        &self,
163        workspace: &str,
164        repo_slug: &str,
165        build_number: u64,
166    ) -> Result<Pipeline> {
167        // Search for the pipeline with the given build number
168        let pipelines = self
169            .list_pipelines(workspace, repo_slug, Some(1), Some(100))
170            .await?;
171
172        pipelines
173            .values
174            .into_iter()
175            .find(|p| p.build_number == build_number)
176            .ok_or_else(|| anyhow::anyhow!("Pipeline #{} not found", build_number))
177    }
178}
179
180/// Compare two git commit hashes that may differ in length.
181///
182/// Bitbucket's pull-request API returns a 12-char short hash while the
183/// pipelines API returns the full 40-char hash. Match by treating the
184/// shorter of the two as a prefix of the longer.
185fn commit_hashes_match(a: &str, b: &str) -> bool {
186    let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
187    !short.is_empty() && long.starts_with(short)
188}
189
190#[cfg(test)]
191mod tests {
192    use super::commit_hashes_match;
193
194    #[test]
195    fn exact_equality_matches() {
196        assert!(commit_hashes_match("abc123", "abc123"));
197    }
198
199    #[test]
200    fn short_pr_hash_matches_full_pipeline_hash() {
201        assert!(commit_hashes_match(
202            "975f24a99dab12345abc678def910ghi112233jk",
203            "975f24a99dab"
204        ));
205    }
206
207    #[test]
208    fn full_pr_hash_matches_short_pipeline_hash() {
209        assert!(commit_hashes_match(
210            "975f24a99dab",
211            "975f24a99dab12345abc678def910ghi112233jk"
212        ));
213    }
214
215    #[test]
216    fn different_commits_do_not_match() {
217        assert!(!commit_hashes_match("abc123def", "abc999def"));
218    }
219
220    #[test]
221    fn empty_hash_never_matches() {
222        // Guard against false positives if the API returns a missing hash
223        // that somehow deserializes to an empty string.
224        assert!(!commit_hashes_match("", "abc123"));
225        assert!(!commit_hashes_match("abc123", ""));
226        assert!(!commit_hashes_match("", ""));
227    }
228}