1use anyhow::Result;
2
3use super::BitbucketClient;
4use crate::models::{
5 Paginated, Pipeline, PipelineCache, PipelineSchedule, PipelineStep, PipelineVariable,
6 PipelineVariableInput, PipelinesConfig, TriggerPipelineRequest,
7};
8
9#[derive(Default)]
11pub(crate) struct PipelineListFilters<'a> {
12 pub page: Option<u32>,
13 pub pagelen: Option<u32>,
14 pub status: Option<&'a str>,
15 pub target_branch: Option<&'a str>,
16 pub sort: Option<&'a str>,
17}
18
19impl BitbucketClient {
20 pub async fn list_pipelines(
25 &self,
26 workspace: &str,
27 repo_slug: &str,
28 page: Option<u32>,
29 pagelen: Option<u32>,
30 ) -> Result<Paginated<Pipeline>> {
31 self.list_pipelines_filtered(
32 workspace,
33 repo_slug,
34 PipelineListFilters {
35 page,
36 pagelen,
37 ..Default::default()
38 },
39 )
40 .await
41 }
42
43 pub(crate) async fn list_pipelines_filtered(
49 &self,
50 workspace: &str,
51 repo_slug: &str,
52 filters: PipelineListFilters<'_>,
53 ) -> Result<Paginated<Pipeline>> {
54 let query = pipeline_list_params(&filters);
55 let query_refs: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
56
57 let path = format!("/repositories/{}/{}/pipelines", workspace, repo_slug);
58 self.get_with_query(&path, &query_refs).await
59 }
60
61 pub async fn get_pipeline(
63 &self,
64 workspace: &str,
65 repo_slug: &str,
66 pipeline_uuid: &str,
67 ) -> Result<Pipeline> {
68 let path = format!(
69 "/repositories/{}/{}/pipelines/{}",
70 workspace, repo_slug, pipeline_uuid
71 );
72 self.get(&path).await
73 }
74
75 pub async fn trigger_pipeline(
77 &self,
78 workspace: &str,
79 repo_slug: &str,
80 request: &TriggerPipelineRequest,
81 ) -> Result<Pipeline> {
82 let path = format!("/repositories/{}/{}/pipelines", workspace, repo_slug);
83 self.post(&path, request).await
84 }
85
86 pub async fn stop_pipeline(
88 &self,
89 workspace: &str,
90 repo_slug: &str,
91 pipeline_uuid: &str,
92 ) -> Result<()> {
93 let path = format!(
94 "/repositories/{}/{}/pipelines/{}/stopPipeline",
95 workspace, repo_slug, pipeline_uuid
96 );
97 self.post_no_response(&path, &serde_json::json!({})).await
98 }
99
100 pub async fn list_pipeline_steps(
102 &self,
103 workspace: &str,
104 repo_slug: &str,
105 pipeline_uuid: &str,
106 ) -> Result<Paginated<PipelineStep>> {
107 let path = format!(
108 "/repositories/{}/{}/pipelines/{}/steps",
109 workspace, repo_slug, pipeline_uuid
110 );
111 self.get(&path).await
112 }
113
114 pub async fn get_pipeline_step(
116 &self,
117 workspace: &str,
118 repo_slug: &str,
119 pipeline_uuid: &str,
120 step_uuid: &str,
121 ) -> Result<PipelineStep> {
122 let path = format!(
123 "/repositories/{}/{}/pipelines/{}/steps/{}",
124 workspace, repo_slug, pipeline_uuid, step_uuid
125 );
126 self.get(&path).await
127 }
128
129 pub async fn get_step_log(
131 &self,
132 workspace: &str,
133 repo_slug: &str,
134 pipeline_uuid: &str,
135 step_uuid: &str,
136 ) -> Result<String> {
137 let path = format!(
138 "/repositories/{}/{}/pipelines/{}/steps/{}/log",
139 workspace, repo_slug, pipeline_uuid, step_uuid
140 );
141
142 self.get_text(&path, None).await
143 }
144
145 pub async fn list_pipelines_for_commit(
156 &self,
157 workspace: &str,
158 repo_slug: &str,
159 commit_hash: &str,
160 scan_limit: u32,
161 ) -> Result<Vec<Pipeline>> {
162 let pagelen = scan_limit.clamp(1, 100);
163 let pipelines = self
164 .list_pipelines(workspace, repo_slug, None, Some(pagelen))
165 .await?;
166 Ok(pipelines
167 .values
168 .into_iter()
169 .filter(|p| {
170 p.target
171 .commit
172 .as_ref()
173 .is_some_and(|c| commit_hashes_match(&c.hash, commit_hash))
174 })
175 .collect())
176 }
177
178 pub async fn get_pipeline_by_build_number(
180 &self,
181 workspace: &str,
182 repo_slug: &str,
183 build_number: u64,
184 ) -> Result<Pipeline> {
185 find_pipeline_by_build_number(
188 |page| self.list_pipelines(workspace, repo_slug, Some(page), Some(100)),
189 build_number,
190 50,
191 )
192 .await
193 }
194
195 pub async fn list_pipeline_variables(
199 &self,
200 workspace: &str,
201 repo_slug: &str,
202 ) -> Result<Vec<PipelineVariable>> {
203 let path = format!(
204 "/repositories/{}/{}/pipelines_config/variables/",
205 workspace, repo_slug
206 );
207 self.get_all_pages(&path).await
208 }
209
210 pub async fn create_pipeline_variable(
212 &self,
213 workspace: &str,
214 repo_slug: &str,
215 variable: &PipelineVariableInput,
216 ) -> Result<PipelineVariable> {
217 let path = format!(
218 "/repositories/{}/{}/pipelines_config/variables/",
219 workspace, repo_slug
220 );
221 self.post(&path, variable).await
222 }
223
224 pub async fn update_pipeline_variable(
226 &self,
227 workspace: &str,
228 repo_slug: &str,
229 variable_uuid: &str,
230 variable: &PipelineVariableInput,
231 ) -> Result<PipelineVariable> {
232 let path = format!(
233 "/repositories/{}/{}/pipelines_config/variables/{}",
234 workspace, repo_slug, variable_uuid
235 );
236 self.put(&path, variable).await
237 }
238
239 pub async fn delete_pipeline_variable(
241 &self,
242 workspace: &str,
243 repo_slug: &str,
244 variable_uuid: &str,
245 ) -> Result<()> {
246 let path = format!(
247 "/repositories/{}/{}/pipelines_config/variables/{}",
248 workspace, repo_slug, variable_uuid
249 );
250 self.delete(&path).await
251 }
252
253 pub async fn list_workspace_pipeline_variables(
260 &self,
261 workspace: &str,
262 ) -> Result<Vec<PipelineVariable>> {
263 let path = format!("/workspaces/{}/pipelines-config/variables/", workspace);
264 self.get_all_pages(&path).await
265 }
266
267 pub async fn create_workspace_pipeline_variable(
269 &self,
270 workspace: &str,
271 variable: &PipelineVariableInput,
272 ) -> Result<PipelineVariable> {
273 let path = format!("/workspaces/{}/pipelines-config/variables/", workspace);
274 self.post(&path, variable).await
275 }
276
277 pub async fn update_workspace_pipeline_variable(
279 &self,
280 workspace: &str,
281 variable_uuid: &str,
282 variable: &PipelineVariableInput,
283 ) -> Result<PipelineVariable> {
284 let path = format!(
285 "/workspaces/{}/pipelines-config/variables/{}",
286 workspace, variable_uuid
287 );
288 self.put(&path, variable).await
289 }
290
291 pub async fn delete_workspace_pipeline_variable(
293 &self,
294 workspace: &str,
295 variable_uuid: &str,
296 ) -> Result<()> {
297 let path = format!(
298 "/workspaces/{}/pipelines-config/variables/{}",
299 workspace, variable_uuid
300 );
301 self.delete(&path).await
302 }
303
304 pub async fn list_pipeline_schedules(
308 &self,
309 workspace: &str,
310 repo_slug: &str,
311 ) -> Result<Vec<PipelineSchedule>> {
312 let path = format!(
313 "/repositories/{}/{}/pipelines_config/schedules/",
314 workspace, repo_slug
315 );
316 self.get_all_pages(&path).await
317 }
318
319 pub async fn create_pipeline_schedule(
321 &self,
322 workspace: &str,
323 repo_slug: &str,
324 branch: &str,
325 cron_pattern: &str,
326 ) -> Result<PipelineSchedule> {
327 let path = format!(
328 "/repositories/{}/{}/pipelines_config/schedules/",
329 workspace, repo_slug
330 );
331 let body = serde_json::json!({
332 "enabled": true,
333 "target": {
334 "type": "pipeline_ref_target",
335 "ref_type": "branch",
336 "ref_name": branch,
337 "selector": {
338 "type": "branches",
339 "pattern": branch,
340 },
341 },
342 "cron_pattern": cron_pattern,
343 });
344 self.post(&path, &body).await
345 }
346
347 pub async fn delete_pipeline_schedule(
349 &self,
350 workspace: &str,
351 repo_slug: &str,
352 schedule_uuid: &str,
353 ) -> Result<()> {
354 let path = format!(
355 "/repositories/{}/{}/pipelines_config/schedules/{}",
356 workspace, repo_slug, schedule_uuid
357 );
358 self.delete(&path).await
359 }
360
361 pub async fn list_pipeline_caches(
368 &self,
369 workspace: &str,
370 repo_slug: &str,
371 ) -> Result<Vec<PipelineCache>> {
372 let path = format!(
373 "/repositories/{}/{}/pipelines-config/caches/",
374 workspace, repo_slug
375 );
376 self.get_all_pages(&path).await
377 }
378
379 pub async fn delete_pipeline_cache(
381 &self,
382 workspace: &str,
383 repo_slug: &str,
384 cache_uuid: &str,
385 ) -> Result<()> {
386 let path = format!(
387 "/repositories/{}/{}/pipelines-config/caches/{}",
388 workspace, repo_slug, cache_uuid
389 );
390 self.delete(&path).await
391 }
392
393 pub async fn get_pipelines_config(
397 &self,
398 workspace: &str,
399 repo_slug: &str,
400 ) -> Result<PipelinesConfig> {
401 let path = format!("/repositories/{}/{}/pipelines_config", workspace, repo_slug);
402 self.get(&path).await
403 }
404
405 pub async fn update_pipelines_config_enabled(
407 &self,
408 workspace: &str,
409 repo_slug: &str,
410 enabled: bool,
411 ) -> Result<PipelinesConfig> {
412 let path = format!("/repositories/{}/{}/pipelines_config", workspace, repo_slug);
413 self.put(&path, &serde_json::json!({ "enabled": enabled }))
414 .await
415 }
416
417 pub async fn set_pipelines_config_build_number(
419 &self,
420 workspace: &str,
421 repo_slug: &str,
422 next: u64,
423 ) -> Result<()> {
424 let path = format!(
425 "/repositories/{}/{}/pipelines_config/build_number",
426 workspace, repo_slug
427 );
428 let _: serde_json::Value = self
429 .put(&path, &serde_json::json!({ "next": next }))
430 .await?;
431 Ok(())
432 }
433}
434
435fn pipeline_list_params(filters: &PipelineListFilters<'_>) -> Vec<(&'static str, String)> {
441 let mut query = Vec::new();
442
443 query.push(("sort", filters.sort.unwrap_or("-created_on").to_string()));
444
445 if let Some(status) = filters.status {
446 query.push(("status", status.to_uppercase()));
447 }
448 if let Some(branch) = filters.target_branch {
449 query.push(("target.branch", branch.to_string()));
450 }
451 if let Some(p) = filters.page {
452 query.push(("page", p.to_string()));
453 }
454 if let Some(len) = filters.pagelen {
455 query.push(("pagelen", len.to_string()));
456 }
457
458 query
459}
460
461async fn find_pipeline_by_build_number<F, Fut>(
468 mut fetch_page: F,
469 build_number: u64,
470 max_pages: u32,
471) -> Result<Pipeline>
472where
473 F: FnMut(u32) -> Fut,
474 Fut: std::future::Future<Output = Result<Paginated<Pipeline>>>,
475{
476 let mut pipelines_seen: usize = 0;
477
478 for page in 1..=max_pages {
479 let pipelines = fetch_page(page).await?;
480 let has_next = pipelines.next.is_some();
481 pipelines_seen += pipelines.values.len();
482
483 if let Some(pipeline) = pipelines
484 .values
485 .into_iter()
486 .find(|p| p.build_number == build_number)
487 {
488 return Ok(pipeline);
489 }
490
491 if !has_next {
492 return Err(anyhow::anyhow!("Pipeline #{} not found", build_number));
493 }
494 }
495
496 Err(anyhow::anyhow!(
497 "Pipeline #{} not found (searched the {} most recent pipelines)",
498 build_number,
499 pipelines_seen
500 ))
501}
502
503fn commit_hashes_match(a: &str, b: &str) -> bool {
509 let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
510 !short.is_empty() && long.starts_with(short)
511}
512
513#[cfg(test)]
514mod tests {
515 use std::cell::Cell;
516 use std::future::{Ready, ready};
517
518 use chrono::Utc;
519
520 use super::{
521 PipelineListFilters, commit_hashes_match, find_pipeline_by_build_number,
522 pipeline_list_params,
523 };
524 use crate::models::{Paginated, Pipeline, PipelineState, PipelineStateName, PipelineTarget};
525
526 fn param<'a>(params: &'a [(&'static str, String)], key: &str) -> Option<&'a str> {
527 params
528 .iter()
529 .find(|(k, _)| *k == key)
530 .map(|(_, v)| v.as_str())
531 }
532
533 #[test]
534 fn params_default_sort_is_created_on_descending() {
535 let params = pipeline_list_params(&PipelineListFilters::default());
536 assert_eq!(param(¶ms, "sort"), Some("-created_on"));
537 }
538
539 #[test]
540 fn params_sort_override_wins() {
541 let filters = PipelineListFilters {
542 sort: Some("created_on"),
543 ..Default::default()
544 };
545 assert_eq!(
546 param(&pipeline_list_params(&filters), "sort"),
547 Some("created_on")
548 );
549 }
550
551 #[test]
552 fn params_status_is_uppercased() {
553 let filters = PipelineListFilters {
554 status: Some("in_progress"),
555 ..Default::default()
556 };
557 assert_eq!(
558 param(&pipeline_list_params(&filters), "status"),
559 Some("IN_PROGRESS")
560 );
561 }
562
563 #[test]
564 fn params_target_branch_uses_dotted_key() {
565 let filters = PipelineListFilters {
566 target_branch: Some("main"),
567 ..Default::default()
568 };
569 let params = pipeline_list_params(&filters);
570 assert_eq!(param(¶ms, "target.branch"), Some("main"));
571 assert_eq!(
573 param(
574 &pipeline_list_params(&PipelineListFilters::default()),
575 "target.branch"
576 ),
577 None
578 );
579 }
580
581 fn pipeline(build_number: u64) -> Pipeline {
582 Pipeline {
583 uuid: format!("{{pipeline-{}}}", build_number),
584 build_number,
585 creator: None,
586 repository: None,
587 target: PipelineTarget {
588 target_type: "pipeline_ref_target".to_string(),
589 ref_type: None,
590 ref_name: None,
591 selector: None,
592 commit: None,
593 },
594 trigger: None,
595 state: PipelineState {
596 name: PipelineStateName::Completed,
597 state_type: "pipeline_state_completed".to_string(),
598 result: None,
599 stage: None,
600 },
601 created_on: Utc::now(),
602 completed_on: None,
603 build_seconds_used: None,
604 links: None,
605 }
606 }
607
608 fn page(values: Vec<Pipeline>, has_next: bool) -> Paginated<Pipeline> {
609 Paginated {
610 size: None,
611 page: None,
612 pagelen: None,
613 next: has_next.then(|| "https://api.bitbucket.org/next".to_string()),
614 previous: None,
615 values,
616 }
617 }
618
619 type PageFuture = Ready<anyhow::Result<Paginated<Pipeline>>>;
620
621 #[tokio::test]
622 async fn finds_pipeline_on_second_page_with_exactly_two_fetches() {
623 let calls = Cell::new(0u32);
624 let fetch = |page_number: u32| -> PageFuture {
625 calls.set(calls.get() + 1);
626 ready(Ok(match page_number {
627 1 => page(vec![pipeline(100), pipeline(99)], true),
628 2 => page(vec![pipeline(98), pipeline(42)], true),
629 other => panic!("unexpected page fetch: {}", other),
630 }))
631 };
632
633 let found = find_pipeline_by_build_number(fetch, 42, 50)
634 .await
635 .expect("pipeline should be found on page 2");
636
637 assert_eq!(found.build_number, 42);
638 assert_eq!(calls.get(), 2);
639 }
640
641 #[tokio::test]
642 async fn stops_after_one_fetch_when_pages_are_exhausted() {
643 let calls = Cell::new(0u32);
644 let fetch = |_page_number: u32| -> PageFuture {
645 calls.set(calls.get() + 1);
646 ready(Ok(page(vec![pipeline(100), pipeline(99)], false)))
647 };
648
649 let err = find_pipeline_by_build_number(fetch, 42, 50)
650 .await
651 .expect_err("pipeline should not be found");
652
653 assert_eq!(err.to_string(), "Pipeline #42 not found");
654 assert_eq!(calls.get(), 1);
655 }
656
657 #[tokio::test]
658 async fn enforces_page_cap_when_next_is_always_present() {
659 let calls = Cell::new(0u32);
660 let fetch = |_page_number: u32| -> PageFuture {
661 calls.set(calls.get() + 1);
662 ready(Ok(page(vec![pipeline(100), pipeline(99)], true)))
663 };
664
665 let err = find_pipeline_by_build_number(fetch, 42, 3)
666 .await
667 .expect_err("search should stop at the page cap");
668
669 assert_eq!(
670 err.to_string(),
671 "Pipeline #42 not found (searched the 6 most recent pipelines)"
672 );
673 assert_eq!(calls.get(), 3);
674 }
675
676 #[test]
677 fn exact_equality_matches() {
678 assert!(commit_hashes_match("abc123", "abc123"));
679 }
680
681 #[test]
682 fn short_pr_hash_matches_full_pipeline_hash() {
683 assert!(commit_hashes_match(
684 "975f24a99dab12345abc678def910ghi112233jk",
685 "975f24a99dab"
686 ));
687 }
688
689 #[test]
690 fn full_pr_hash_matches_short_pipeline_hash() {
691 assert!(commit_hashes_match(
692 "975f24a99dab",
693 "975f24a99dab12345abc678def910ghi112233jk"
694 ));
695 }
696
697 #[test]
698 fn different_commits_do_not_match() {
699 assert!(!commit_hashes_match("abc123def", "abc999def"));
700 }
701
702 #[test]
703 fn empty_hash_never_matches() {
704 assert!(!commit_hashes_match("", "abc123"));
707 assert!(!commit_hashes_match("abc123", ""));
708 assert!(!commit_hashes_match("", ""));
709 }
710}