Skip to main content

bitbucket_cli/cli/
pipeline.rs

1use anyhow::{Context, Result};
2use clap::Subcommand;
3use colored::{ColoredString, Colorize};
4use indicatif::{ProgressBar, ProgressStyle};
5use tabled::{Table, Tabled};
6
7use super::{confirm_or_abort, parse_repo, resolve_workspace};
8use crate::api::BitbucketClient;
9use crate::cli::pagination::effective_limit;
10use crate::models::{
11    Pipeline, PipelineResultName, PipelineStateName, PipelineStep, PipelineVariable,
12    PipelineVariableInput, TriggerPipelineRequest, TriggerPipelineSelector,
13};
14
15#[derive(Subcommand)]
16pub enum PipelineCommands {
17    /// List pipelines
18    List {
19        /// Repository in format workspace/repo-slug
20        repo: String,
21
22        /// Number of results (capped at 100)
23        #[arg(short, long, default_value = "25")]
24        limit: u32,
25
26        /// Filter by status (PENDING, IN_PROGRESS, COMPLETED, ...)
27        #[arg(long)]
28        status: Option<String>,
29
30        /// Filter by target branch name
31        #[arg(long)]
32        target_branch: Option<String>,
33
34        /// Sort order (default: -created_on, most recent first)
35        #[arg(long)]
36        sort: Option<String>,
37
38        /// Page number to fetch
39        #[arg(long)]
40        page: Option<u32>,
41    },
42
43    /// View pipeline details
44    View {
45        /// Repository in format workspace/repo-slug
46        repo: String,
47
48        /// Pipeline build number
49        #[arg(short, long)]
50        build: u64,
51
52        /// Show step logs
53        #[arg(short, long)]
54        logs: bool,
55
56        /// Show only one step: a 1-based index or a step UUID prefix
57        #[arg(long)]
58        step: Option<String>,
59
60        /// Print complete step logs instead of the first 50 lines (implies --logs)
61        #[arg(long)]
62        full_logs: bool,
63    },
64
65    /// Trigger a new pipeline
66    Trigger {
67        /// Repository in format workspace/repo-slug
68        repo: String,
69
70        /// Branch to run pipeline on
71        #[arg(short, long, default_value = "main")]
72        branch: String,
73
74        /// Commit hash to run the pipeline on (takes precedence over --branch)
75        #[arg(long)]
76        commit: Option<String>,
77
78        /// Custom pipeline name (from bitbucket-pipelines.yml)
79        #[arg(short, long)]
80        pipeline: Option<String>,
81
82        /// Pipeline variable as KEY=VALUE (repeatable)
83        #[arg(long, value_name = "KEY=VALUE")]
84        var: Vec<String>,
85
86        /// Secured pipeline variable as KEY=VALUE, masked in logs (repeatable)
87        #[arg(long, value_name = "KEY=VALUE")]
88        secured_var: Vec<String>,
89
90        /// Wait for pipeline to complete
91        #[arg(short, long)]
92        wait: bool,
93    },
94
95    /// Stop a running pipeline
96    Stop {
97        /// Repository in format workspace/repo-slug
98        repo: String,
99
100        /// Pipeline build number
101        #[arg(short, long, required_unless_present = "uuid")]
102        build: Option<u64>,
103
104        /// Pipeline UUID (skips the build-number lookup)
105        #[arg(long, conflicts_with = "build")]
106        uuid: Option<String>,
107    },
108
109    /// Re-run a pipeline by triggering an equivalent one
110    Rerun {
111        /// Repository in format workspace/repo-slug
112        repo: String,
113
114        /// Build number of the pipeline to re-run
115        #[arg(short, long)]
116        build: u64,
117    },
118
119    /// View or update the repository pipelines configuration
120    Config {
121        /// Repository in format workspace/repo-slug
122        repo: String,
123
124        /// Enable pipelines for the repository
125        #[arg(long, conflicts_with = "disable")]
126        enable: bool,
127
128        /// Disable pipelines for the repository
129        #[arg(long)]
130        disable: bool,
131
132        /// Set the next pipeline build number
133        #[arg(long)]
134        next_build_number: Option<u64>,
135    },
136
137    /// Manage repository pipeline variables
138    Variable {
139        #[command(subcommand)]
140        command: VariableCommands,
141    },
142
143    /// Manage workspace-level pipeline variables
144    WorkspaceVariable {
145        #[command(subcommand)]
146        command: WorkspaceVariableCommands,
147    },
148
149    /// Manage pipeline schedules
150    Schedule {
151        #[command(subcommand)]
152        command: ScheduleCommands,
153    },
154
155    /// Manage pipeline dependency caches
156    Cache {
157        #[command(subcommand)]
158        command: CacheCommands,
159    },
160}
161
162#[derive(Subcommand)]
163pub enum VariableCommands {
164    /// List pipeline variables
165    List {
166        /// Repository in format workspace/repo-slug
167        repo: String,
168    },
169
170    /// Create or update a pipeline variable
171    Set {
172        /// Repository in format workspace/repo-slug
173        repo: String,
174
175        /// Variable name
176        key: String,
177
178        /// Variable value
179        value: String,
180
181        /// Mask the value in logs and the UI
182        #[arg(long)]
183        secured: bool,
184    },
185
186    /// Delete a pipeline variable by key
187    Delete {
188        /// Repository in format workspace/repo-slug
189        repo: String,
190
191        /// Variable name
192        key: String,
193
194        /// Skip confirmation prompt
195        #[arg(short, long)]
196        yes: bool,
197    },
198}
199
200#[derive(Subcommand)]
201pub enum WorkspaceVariableCommands {
202    /// List workspace pipeline variables
203    List {
204        /// Workspace (defaults to --workspace or the configured default)
205        workspace: Option<String>,
206    },
207
208    /// Create or update a workspace pipeline variable
209    Set {
210        /// Variable name
211        key: String,
212
213        /// Variable value
214        value: String,
215
216        /// Workspace (defaults to --workspace or the configured default)
217        workspace: Option<String>,
218
219        /// Mask the value in logs and the UI
220        #[arg(long)]
221        secured: bool,
222    },
223
224    /// Delete a workspace pipeline variable by key
225    Delete {
226        /// Variable name
227        key: String,
228
229        /// Workspace (defaults to --workspace or the configured default)
230        workspace: Option<String>,
231
232        /// Skip confirmation prompt
233        #[arg(short, long)]
234        yes: bool,
235    },
236}
237
238#[derive(Subcommand)]
239pub enum ScheduleCommands {
240    /// List pipeline schedules
241    List {
242        /// Repository in format workspace/repo-slug
243        repo: String,
244    },
245
246    /// Create a pipeline schedule
247    Create {
248        /// Repository in format workspace/repo-slug
249        repo: String,
250
251        /// Branch to run the scheduled pipeline on
252        #[arg(long)]
253        branch: String,
254
255        /// Cron pattern (e.g. "0 0 12 * * ? *")
256        #[arg(long)]
257        cron: String,
258    },
259
260    /// Delete a pipeline schedule by UUID
261    Delete {
262        /// Repository in format workspace/repo-slug
263        repo: String,
264
265        /// Schedule UUID (with or without braces)
266        uuid: String,
267
268        /// Skip confirmation prompt
269        #[arg(short, long)]
270        yes: bool,
271    },
272}
273
274#[derive(Subcommand)]
275pub enum CacheCommands {
276    /// List pipeline dependency caches
277    List {
278        /// Repository in format workspace/repo-slug
279        repo: String,
280    },
281
282    /// Delete pipeline dependency caches by name
283    Delete {
284        /// Repository in format workspace/repo-slug
285        repo: String,
286
287        /// Cache name (as shown by 'cache list')
288        name: String,
289
290        /// Skip confirmation prompt
291        #[arg(short, long)]
292        yes: bool,
293    },
294}
295
296#[derive(Tabled)]
297struct PipelineRow {
298    #[tabled(rename = "#")]
299    build: u64,
300    #[tabled(rename = "STATUS")]
301    status: String,
302    #[tabled(rename = "BRANCH")]
303    branch: String,
304    #[tabled(rename = "TRIGGERED")]
305    triggered: String,
306    #[tabled(rename = "DURATION")]
307    duration: String,
308}
309
310#[derive(Tabled)]
311struct VariableRow {
312    #[tabled(rename = "KEY")]
313    key: String,
314    #[tabled(rename = "VALUE")]
315    value: String,
316    #[tabled(rename = "SECURED")]
317    secured: String,
318    #[tabled(rename = "UUID")]
319    uuid: String,
320}
321
322#[derive(Tabled)]
323struct ScheduleRow {
324    #[tabled(rename = "ENABLED")]
325    enabled: String,
326    #[tabled(rename = "CRON")]
327    cron: String,
328    #[tabled(rename = "BRANCH")]
329    branch: String,
330    #[tabled(rename = "UUID")]
331    uuid: String,
332}
333
334#[derive(Tabled)]
335struct CacheRow {
336    #[tabled(rename = "NAME")]
337    name: String,
338    #[tabled(rename = "PATH")]
339    path: String,
340    #[tabled(rename = "SIZE")]
341    size: String,
342    #[tabled(rename = "UUID")]
343    uuid: String,
344}
345
346impl PipelineCommands {
347    pub async fn run(self) -> Result<()> {
348        match self {
349            PipelineCommands::List {
350                repo,
351                limit,
352                status,
353                target_branch,
354                sort,
355                page,
356            } => {
357                let (workspace, repo_slug) = parse_repo(&repo)?;
358                let client = BitbucketClient::from_stored().await?;
359                let limit = effective_limit(limit);
360
361                let pipelines = client
362                    .list_pipelines_filtered(
363                        &workspace,
364                        &repo_slug,
365                        crate::api::pipelines::PipelineListFilters {
366                            page,
367                            pagelen: Some(limit),
368                            status: status.as_deref(),
369                            target_branch: target_branch.as_deref(),
370                            sort: sort.as_deref(),
371                        },
372                    )
373                    .await?;
374
375                if super::output_json() {
376                    return super::print_json(&pipelines.values);
377                }
378
379                if pipelines.values.is_empty() {
380                    println!("No pipelines found");
381                    return Ok(());
382                }
383
384                let rows: Vec<PipelineRow> = pipelines
385                    .values
386                    .iter()
387                    .map(|p| {
388                        let duration = if let Some(seconds) = p.build_seconds_used {
389                            format_duration(seconds)
390                        } else if p.state.name == PipelineStateName::InProgress {
391                            "running...".to_string()
392                        } else {
393                            "-".to_string()
394                        };
395
396                        PipelineRow {
397                            build: p.build_number,
398                            status: format_status(
399                                &p.state.name,
400                                p.state.result.as_ref().map(|r| &r.name),
401                            ),
402                            branch: p.target.ref_name.clone().unwrap_or_else(|| "-".to_string()),
403                            triggered: p.created_on.format("%Y-%m-%d %H:%M").to_string(),
404                            duration,
405                        }
406                    })
407                    .collect();
408
409                let table = Table::new(rows).to_string();
410                println!("{}", table);
411
412                Ok(())
413            }
414
415            PipelineCommands::View {
416                repo,
417                build,
418                logs,
419                step,
420                full_logs,
421            } => {
422                let (workspace, repo_slug) = parse_repo(&repo)?;
423                let client = BitbucketClient::from_stored().await?;
424                let show_logs = logs || full_logs;
425
426                let pipeline = client
427                    .get_pipeline_by_build_number(&workspace, &repo_slug, build)
428                    .await?;
429
430                if super::output_json() && !show_logs {
431                    let steps = client
432                        .list_pipeline_steps(&workspace, &repo_slug, &pipeline.uuid)
433                        .await?;
434
435                    let steps = match &step {
436                        Some(selector) => {
437                            let (index, by_uuid) = select_step(&steps.values, selector)?;
438                            let chosen = &steps.values[index];
439                            let detail = if by_uuid {
440                                client
441                                    .get_pipeline_step(
442                                        &workspace,
443                                        &repo_slug,
444                                        &pipeline.uuid,
445                                        &chosen.uuid,
446                                    )
447                                    .await?
448                            } else {
449                                chosen.clone()
450                            };
451                            vec![detail]
452                        }
453                        None => steps.values,
454                    };
455
456                    return super::print_json(&serde_json::json!({
457                        "pipeline": pipeline,
458                        "steps": steps,
459                    }));
460                }
461
462                println!(
463                    "{} Pipeline #{} - {}",
464                    format_status(
465                        &pipeline.state.name,
466                        pipeline.state.result.as_ref().map(|r| &r.name)
467                    ),
468                    pipeline.build_number,
469                    pipeline.target.ref_name.as_deref().unwrap_or("unknown")
470                );
471                println!("{}", "─".repeat(60));
472
473                if let Some(creator) = &pipeline.creator {
474                    println!("{} {}", "Triggered by:".dimmed(), creator.display_name);
475                }
476
477                if let Some(trigger) = &pipeline.trigger {
478                    println!("{} {}", "Trigger type:".dimmed(), trigger.trigger_type);
479                }
480
481                println!(
482                    "{} {}",
483                    "Started:".dimmed(),
484                    pipeline.created_on.format("%Y-%m-%d %H:%M:%S")
485                );
486
487                if let Some(completed) = pipeline.completed_on {
488                    println!(
489                        "{} {}",
490                        "Completed:".dimmed(),
491                        completed.format("%Y-%m-%d %H:%M:%S")
492                    );
493                }
494
495                if let Some(seconds) = pipeline.build_seconds_used {
496                    println!("{} {}", "Duration:".dimmed(), format_duration(seconds));
497                }
498
499                let steps = client
500                    .list_pipeline_steps(&workspace, &repo_slug, &pipeline.uuid)
501                    .await?;
502
503                if let Some(selector) = step {
504                    let (index, by_uuid) = select_step(&steps.values, &selector)?;
505                    let chosen = &steps.values[index];
506
507                    // A UUID selection points at one concrete step, so use the
508                    // dedicated step endpoint for the freshest detail.
509                    let detail = if by_uuid {
510                        client
511                            .get_pipeline_step(&workspace, &repo_slug, &pipeline.uuid, &chosen.uuid)
512                            .await?
513                    } else {
514                        chosen.clone()
515                    };
516
517                    print_step_detail(&detail);
518
519                    if show_logs {
520                        // A single step was explicitly requested, so a failed
521                        // log fetch is worth surfacing rather than swallowing.
522                        if let Err(e) = print_step_log(
523                            &client,
524                            &workspace,
525                            &repo_slug,
526                            &pipeline.uuid,
527                            &detail.uuid,
528                            full_logs,
529                        )
530                        .await
531                        {
532                            eprintln!(
533                                "{} could not fetch log for step {}: {}",
534                                "⚠".yellow(),
535                                detail.name.as_deref().unwrap_or(&detail.uuid),
536                                e
537                            );
538                        }
539                    }
540
541                    return Ok(());
542                }
543
544                if !steps.values.is_empty() {
545                    println!();
546                    println!("{}", "Steps:".bold());
547
548                    for step in &steps.values {
549                        let name = step.name.as_deref().unwrap_or("Step");
550                        println!("  {} {}", step_status_icon(step), name);
551
552                        if show_logs {
553                            // Iterating over every step: logs for pending or
554                            // in-progress steps may not exist yet, so ignore
555                            // fetch errors here.
556                            let _ = print_step_log(
557                                &client,
558                                &workspace,
559                                &repo_slug,
560                                &pipeline.uuid,
561                                &step.uuid,
562                                full_logs,
563                            )
564                            .await;
565                        }
566                    }
567                }
568
569                Ok(())
570            }
571
572            PipelineCommands::Trigger {
573                repo,
574                branch,
575                commit,
576                pipeline,
577                var,
578                secured_var,
579                wait,
580            } => {
581                let (workspace, repo_slug) = parse_repo(&repo)?;
582                let client = BitbucketClient::from_stored().await?;
583
584                let mut variables = Vec::with_capacity(var.len() + secured_var.len());
585                for spec in &var {
586                    let (key, value) = parse_var(spec)?;
587                    variables.push(PipelineVariableInput {
588                        key,
589                        value,
590                        secured: false,
591                    });
592                }
593                for spec in &secured_var {
594                    let (key, value) = parse_var(spec)?;
595                    variables.push(PipelineVariableInput {
596                        key,
597                        value,
598                        secured: true,
599                    });
600                }
601                let variable_count = variables.len();
602
603                let mut request = match &commit {
604                    Some(hash) => TriggerPipelineRequest::for_commit(hash),
605                    None => TriggerPipelineRequest::for_branch(&branch),
606                };
607                if let Some(pipeline_name) = &pipeline {
608                    request = request.with_pipeline(pipeline_name);
609                }
610                request = request.with_variables(variables);
611
612                let triggered = client
613                    .trigger_pipeline(&workspace, &repo_slug, &request)
614                    .await?;
615
616                if super::output_json() {
617                    if wait {
618                        let done = wait_for_pipeline_silently(
619                            &client,
620                            &workspace,
621                            &repo_slug,
622                            &triggered.uuid,
623                        )
624                        .await?;
625                        return super::print_json(&done);
626                    }
627                    return super::print_json(&triggered);
628                }
629
630                let target_desc = match &commit {
631                    Some(hash) => format!("commit {}", hash.cyan()),
632                    None => format!("branch {}", branch.cyan()),
633                };
634                let variable_note = if variable_count > 0 {
635                    format!(" with {} variable(s)", variable_count)
636                } else {
637                    String::new()
638                };
639                println!(
640                    "{} Triggered pipeline #{} on {}{}",
641                    "✓".green(),
642                    triggered.build_number,
643                    target_desc,
644                    variable_note
645                );
646
647                if wait {
648                    println!();
649                    wait_for_pipeline(&client, &workspace, &repo_slug, &triggered.uuid).await?;
650                }
651
652                Ok(())
653            }
654
655            PipelineCommands::Stop { repo, build, uuid } => {
656                let (workspace, repo_slug) = parse_repo(&repo)?;
657                let client = BitbucketClient::from_stored().await?;
658
659                if let Some(uuid) = uuid {
660                    let uuid = ensure_braced_uuid(&uuid);
661                    client.stop_pipeline(&workspace, &repo_slug, &uuid).await?;
662                    if super::output_json() {
663                        return super::print_json(&serde_json::json!({"ok": true}));
664                    }
665                    println!("{} Stopped pipeline {}", "✓".green(), uuid);
666                    return Ok(());
667                }
668
669                // clap guarantees --build when --uuid is absent.
670                let build = build.expect("clap enforces --build or --uuid");
671                let pipeline = client
672                    .get_pipeline_by_build_number(&workspace, &repo_slug, build)
673                    .await?;
674
675                client
676                    .stop_pipeline(&workspace, &repo_slug, &pipeline.uuid)
677                    .await?;
678
679                if super::output_json() {
680                    return super::print_json(&serde_json::json!({"ok": true}));
681                }
682
683                println!("{} Stopped pipeline #{}", "✓".green(), build);
684
685                Ok(())
686            }
687
688            PipelineCommands::Rerun { repo, build } => {
689                let (workspace, repo_slug) = parse_repo(&repo)?;
690                let client = BitbucketClient::from_stored().await?;
691
692                let original = client
693                    .get_pipeline_by_build_number(&workspace, &repo_slug, build)
694                    .await?;
695
696                // Bitbucket has no rerun endpoint, so re-trigger an equivalent
697                // pipeline from the original's target.
698                let Some(ref_name) = original.target.ref_name.clone() else {
699                    anyhow::bail!(
700                        "Pipeline #{} has no branch to re-run from (target type '{}'). \
701                         Bitbucket has no rerun API, so only pipelines that ran against \
702                         a branch can be re-triggered. Use 'pipeline trigger' instead.",
703                        build,
704                        original.target.target_type
705                    );
706                };
707
708                let mut request = TriggerPipelineRequest::for_branch(&ref_name);
709                if let Some(selector) = &original.target.selector {
710                    if let Some(pattern) = &selector.pattern {
711                        request.target.selector = Some(TriggerPipelineSelector {
712                            selector_type: selector.selector_type.clone(),
713                            pattern: pattern.clone(),
714                        });
715                    }
716                }
717
718                let new = client
719                    .trigger_pipeline(&workspace, &repo_slug, &request)
720                    .await?;
721
722                if super::output_json() {
723                    return super::print_json(&new);
724                }
725
726                println!(
727                    "{} Re-ran pipeline #{} as #{} on branch {}",
728                    "✓".green(),
729                    build,
730                    new.build_number,
731                    ref_name.cyan()
732                );
733
734                Ok(())
735            }
736
737            PipelineCommands::Config {
738                repo,
739                enable,
740                disable,
741                next_build_number,
742            } => {
743                let (workspace, repo_slug) = parse_repo(&repo)?;
744                let client = BitbucketClient::from_stored().await?;
745
746                if super::output_json() {
747                    let mut config = None;
748                    if enable || disable {
749                        config = Some(
750                            client
751                                .update_pipelines_config_enabled(&workspace, &repo_slug, enable)
752                                .await?,
753                        );
754                    }
755                    if let Some(next) = next_build_number {
756                        client
757                            .set_pipelines_config_build_number(&workspace, &repo_slug, next)
758                            .await?;
759                    }
760                    return match config {
761                        Some(config) => super::print_json(&config),
762                        None if next_build_number.is_some() => {
763                            super::print_json(&serde_json::json!({"ok": true}))
764                        }
765                        None => super::print_json(
766                            &client.get_pipelines_config(&workspace, &repo_slug).await?,
767                        ),
768                    };
769                }
770
771                let mut changed = false;
772
773                if enable || disable {
774                    let config = client
775                        .update_pipelines_config_enabled(&workspace, &repo_slug, enable)
776                        .await?;
777                    let state = if config.enabled.unwrap_or(enable) {
778                        "enabled".green()
779                    } else {
780                        "disabled".red()
781                    };
782                    println!("{} Pipelines {} for {}", "✓".green(), state, repo);
783                    changed = true;
784                }
785
786                if let Some(next) = next_build_number {
787                    client
788                        .set_pipelines_config_build_number(&workspace, &repo_slug, next)
789                        .await?;
790                    println!("{} Next build number set to {}", "✓".green(), next);
791                    changed = true;
792                }
793
794                if !changed {
795                    let config = client.get_pipelines_config(&workspace, &repo_slug).await?;
796                    match config.enabled {
797                        Some(true) => println!("Pipelines are {} for {}", "enabled".green(), repo),
798                        Some(false) => println!("Pipelines are {} for {}", "disabled".red(), repo),
799                        None => println!("Pipelines enabled state is unknown for {}", repo),
800                    }
801                }
802
803                Ok(())
804            }
805
806            PipelineCommands::Variable { command } => command.run().await,
807            PipelineCommands::WorkspaceVariable { command } => command.run().await,
808            PipelineCommands::Schedule { command } => command.run().await,
809            PipelineCommands::Cache { command } => command.run().await,
810        }
811    }
812}
813
814impl VariableCommands {
815    pub async fn run(self) -> Result<()> {
816        match self {
817            VariableCommands::List { repo } => {
818                let (workspace, repo_slug) = parse_repo(&repo)?;
819                let client = BitbucketClient::from_stored().await?;
820
821                let variables = client
822                    .list_pipeline_variables(&workspace, &repo_slug)
823                    .await?;
824
825                if super::output_json() {
826                    return super::print_json(&masked_variables(&variables));
827                }
828
829                if variables.is_empty() {
830                    println!("No pipeline variables found");
831                    return Ok(());
832                }
833
834                let table = Table::new(variable_rows(&variables)).to_string();
835                println!("{}", table);
836
837                Ok(())
838            }
839
840            VariableCommands::Set {
841                repo,
842                key,
843                value,
844                secured,
845            } => {
846                let (workspace, repo_slug) = parse_repo(&repo)?;
847                let client = BitbucketClient::from_stored().await?;
848
849                let input = PipelineVariableInput {
850                    key: key.clone(),
851                    value,
852                    secured,
853                };
854
855                let variables = client
856                    .list_pipeline_variables(&workspace, &repo_slug)
857                    .await?;
858                match find_variable_uuid(&variables, &key) {
859                    Some(uuid) => {
860                        let variable = client
861                            .update_pipeline_variable(&workspace, &repo_slug, &uuid, &input)
862                            .await
863                            .with_context(|| {
864                                format!(
865                                    "updating variable '{}' (it may have been deleted \
866                                     concurrently — re-run to create it)",
867                                    key
868                                )
869                            })?;
870                        if super::output_json() {
871                            return super::print_json(&variable);
872                        }
873                        println!("{} Updated pipeline variable {}", "✓".green(), key.cyan());
874                    }
875                    None => {
876                        let variable = client
877                            .create_pipeline_variable(&workspace, &repo_slug, &input)
878                            .await?;
879                        if super::output_json() {
880                            return super::print_json(&variable);
881                        }
882                        println!("{} Created pipeline variable {}", "✓".green(), key.cyan());
883                    }
884                }
885
886                Ok(())
887            }
888
889            VariableCommands::Delete { repo, key, yes } => {
890                let (workspace, repo_slug) = parse_repo(&repo)?;
891                let client = BitbucketClient::from_stored().await?;
892
893                let variables = client
894                    .list_pipeline_variables(&workspace, &repo_slug)
895                    .await?;
896                let uuid = find_variable_uuid(&variables, &key).ok_or_else(|| {
897                    anyhow::anyhow!("No pipeline variable named '{}' in {}", key, repo)
898                })?;
899
900                if !yes && !confirm_or_abort(format!("Delete pipeline variable {}?", key.red()))? {
901                    return Ok(());
902                }
903
904                client
905                    .delete_pipeline_variable(&workspace, &repo_slug, &uuid)
906                    .await?;
907
908                if super::output_json() {
909                    return super::print_json(&serde_json::json!({"ok": true}));
910                }
911
912                println!("{} Deleted pipeline variable {}", "✓".green(), key);
913
914                Ok(())
915            }
916        }
917    }
918}
919
920impl WorkspaceVariableCommands {
921    pub async fn run(self) -> Result<()> {
922        match self {
923            WorkspaceVariableCommands::List { workspace } => {
924                let workspace = resolve_workspace(workspace)?;
925                let client = BitbucketClient::from_stored().await?;
926
927                let variables = client.list_workspace_pipeline_variables(&workspace).await?;
928
929                if super::output_json() {
930                    return super::print_json(&masked_variables(&variables));
931                }
932
933                if variables.is_empty() {
934                    println!("No workspace pipeline variables found");
935                    return Ok(());
936                }
937
938                let table = Table::new(variable_rows(&variables)).to_string();
939                println!("{}", table);
940
941                Ok(())
942            }
943
944            WorkspaceVariableCommands::Set {
945                key,
946                value,
947                workspace,
948                secured,
949            } => {
950                let workspace = resolve_workspace(workspace)?;
951                let client = BitbucketClient::from_stored().await?;
952
953                let input = PipelineVariableInput {
954                    key: key.clone(),
955                    value,
956                    secured,
957                };
958
959                let variables = client.list_workspace_pipeline_variables(&workspace).await?;
960                match find_variable_uuid(&variables, &key) {
961                    Some(uuid) => {
962                        let variable = client
963                            .update_workspace_pipeline_variable(&workspace, &uuid, &input)
964                            .await
965                            .with_context(|| {
966                                format!(
967                                    "updating variable '{}' (it may have been deleted \
968                                     concurrently — re-run to create it)",
969                                    key
970                                )
971                            })?;
972                        if super::output_json() {
973                            return super::print_json(&variable);
974                        }
975                        println!(
976                            "{} Updated workspace pipeline variable {}",
977                            "✓".green(),
978                            key.cyan()
979                        );
980                    }
981                    None => {
982                        let variable = client
983                            .create_workspace_pipeline_variable(&workspace, &input)
984                            .await?;
985                        if super::output_json() {
986                            return super::print_json(&variable);
987                        }
988                        println!(
989                            "{} Created workspace pipeline variable {}",
990                            "✓".green(),
991                            key.cyan()
992                        );
993                    }
994                }
995
996                Ok(())
997            }
998
999            WorkspaceVariableCommands::Delete {
1000                key,
1001                workspace,
1002                yes,
1003            } => {
1004                let workspace = resolve_workspace(workspace)?;
1005                let client = BitbucketClient::from_stored().await?;
1006
1007                let variables = client.list_workspace_pipeline_variables(&workspace).await?;
1008                let uuid = find_variable_uuid(&variables, &key).ok_or_else(|| {
1009                    anyhow::anyhow!(
1010                        "No workspace pipeline variable named '{}' in {}",
1011                        key,
1012                        workspace
1013                    )
1014                })?;
1015
1016                if !yes
1017                    && !confirm_or_abort(format!(
1018                        "Delete workspace pipeline variable {}?",
1019                        key.red()
1020                    ))?
1021                {
1022                    return Ok(());
1023                }
1024
1025                client
1026                    .delete_workspace_pipeline_variable(&workspace, &uuid)
1027                    .await?;
1028
1029                if super::output_json() {
1030                    return super::print_json(&serde_json::json!({"ok": true}));
1031                }
1032
1033                println!(
1034                    "{} Deleted workspace pipeline variable {}",
1035                    "✓".green(),
1036                    key
1037                );
1038
1039                Ok(())
1040            }
1041        }
1042    }
1043}
1044
1045impl ScheduleCommands {
1046    pub async fn run(self) -> Result<()> {
1047        match self {
1048            ScheduleCommands::List { repo } => {
1049                let (workspace, repo_slug) = parse_repo(&repo)?;
1050                let client = BitbucketClient::from_stored().await?;
1051
1052                let schedules = client
1053                    .list_pipeline_schedules(&workspace, &repo_slug)
1054                    .await?;
1055
1056                if super::output_json() {
1057                    return super::print_json(&schedules);
1058                }
1059
1060                if schedules.is_empty() {
1061                    println!("No pipeline schedules found");
1062                    return Ok(());
1063                }
1064
1065                let rows: Vec<ScheduleRow> = schedules
1066                    .iter()
1067                    .map(|s| ScheduleRow {
1068                        enabled: if s.enabled.unwrap_or(false) {
1069                            "yes".to_string()
1070                        } else {
1071                            "no".to_string()
1072                        },
1073                        cron: s.cron_pattern.clone().unwrap_or_else(|| "-".to_string()),
1074                        branch: schedule_branch(s.target.as_ref()),
1075                        uuid: s.uuid.clone(),
1076                    })
1077                    .collect();
1078
1079                let table = Table::new(rows).to_string();
1080                println!("{}", table);
1081
1082                Ok(())
1083            }
1084
1085            ScheduleCommands::Create { repo, branch, cron } => {
1086                let (workspace, repo_slug) = parse_repo(&repo)?;
1087                let client = BitbucketClient::from_stored().await?;
1088
1089                let schedule = client
1090                    .create_pipeline_schedule(&workspace, &repo_slug, &branch, &cron)
1091                    .await?;
1092
1093                if super::output_json() {
1094                    return super::print_json(&schedule);
1095                }
1096
1097                println!(
1098                    "{} Created schedule {} on branch {} ({})",
1099                    "✓".green(),
1100                    schedule.uuid,
1101                    branch.cyan(),
1102                    schedule.cron_pattern.as_deref().unwrap_or(&cron)
1103                );
1104
1105                Ok(())
1106            }
1107
1108            ScheduleCommands::Delete { repo, uuid, yes } => {
1109                let (workspace, repo_slug) = parse_repo(&repo)?;
1110                let client = BitbucketClient::from_stored().await?;
1111                let uuid = ensure_braced_uuid(&uuid);
1112
1113                if !yes && !confirm_or_abort(format!("Delete pipeline schedule {}?", uuid.red()))? {
1114                    return Ok(());
1115                }
1116
1117                client
1118                    .delete_pipeline_schedule(&workspace, &repo_slug, &uuid)
1119                    .await?;
1120
1121                if super::output_json() {
1122                    return super::print_json(&serde_json::json!({"ok": true}));
1123                }
1124
1125                println!("{} Deleted pipeline schedule {}", "✓".green(), uuid);
1126
1127                Ok(())
1128            }
1129        }
1130    }
1131}
1132
1133impl CacheCommands {
1134    pub async fn run(self) -> Result<()> {
1135        match self {
1136            CacheCommands::List { repo } => {
1137                let (workspace, repo_slug) = parse_repo(&repo)?;
1138                let client = BitbucketClient::from_stored().await?;
1139
1140                let caches = client.list_pipeline_caches(&workspace, &repo_slug).await?;
1141
1142                if super::output_json() {
1143                    return super::print_json(&caches);
1144                }
1145
1146                if caches.is_empty() {
1147                    println!("No pipeline caches found");
1148                    return Ok(());
1149                }
1150
1151                let rows: Vec<CacheRow> = caches
1152                    .iter()
1153                    .map(|c| CacheRow {
1154                        name: c.name.clone().unwrap_or_else(|| "-".to_string()),
1155                        path: c.path.clone().unwrap_or_else(|| "-".to_string()),
1156                        size: c
1157                            .file_size_bytes
1158                            .map(format_bytes)
1159                            .unwrap_or_else(|| "-".to_string()),
1160                        uuid: c.uuid.clone(),
1161                    })
1162                    .collect();
1163
1164                let table = Table::new(rows).to_string();
1165                println!("{}", table);
1166
1167                Ok(())
1168            }
1169
1170            CacheCommands::Delete { repo, name, yes } => {
1171                let (workspace, repo_slug) = parse_repo(&repo)?;
1172                let client = BitbucketClient::from_stored().await?;
1173
1174                let caches = client.list_pipeline_caches(&workspace, &repo_slug).await?;
1175                let matches: Vec<_> = caches
1176                    .into_iter()
1177                    .filter(|c| c.name.as_deref() == Some(name.as_str()))
1178                    .collect();
1179
1180                if matches.is_empty() {
1181                    anyhow::bail!("No pipeline cache named '{}' in {}", name, repo);
1182                }
1183
1184                if !yes
1185                    && !confirm_or_abort(format!(
1186                        "Delete {} pipeline cache(s) named {}?",
1187                        matches.len(),
1188                        name.red()
1189                    ))?
1190                {
1191                    return Ok(());
1192                }
1193
1194                let total = matches.len();
1195                let json = super::output_json();
1196                let mut deleted = 0usize;
1197                let mut failures: Vec<(String, anyhow::Error)> = Vec::new();
1198
1199                // Delete every match rather than aborting on the first error, so
1200                // a single bad cache doesn't leave the rest stranded.
1201                for cache in &matches {
1202                    match client
1203                        .delete_pipeline_cache(&workspace, &repo_slug, &cache.uuid)
1204                        .await
1205                    {
1206                        Ok(()) => {
1207                            deleted += 1;
1208                            if !json {
1209                                println!("{} Deleted pipeline cache {}", "✓".green(), cache.uuid);
1210                            }
1211                        }
1212                        Err(e) => failures.push((cache.uuid.clone(), e)),
1213                    }
1214                }
1215
1216                let failed = failures.len();
1217
1218                if failed > 0 {
1219                    for (uuid, e) in &failures {
1220                        eprintln!(
1221                            "{} could not delete pipeline cache {}: {}",
1222                            "⚠".yellow(),
1223                            uuid,
1224                            e
1225                        );
1226                    }
1227                    anyhow::bail!(
1228                        "Deleted {} of {} pipeline cache(s) named '{}' ({} failed)",
1229                        deleted,
1230                        total,
1231                        name,
1232                        failed
1233                    );
1234                }
1235
1236                if json {
1237                    return super::print_json(&serde_json::json!({"ok": true, "deleted": deleted}));
1238                }
1239
1240                println!(
1241                    "{} Deleted {} of {} pipeline cache(s) named {}",
1242                    "✓".green(),
1243                    deleted,
1244                    total,
1245                    name
1246                );
1247
1248                Ok(())
1249            }
1250        }
1251    }
1252}
1253
1254/// Poll a pipeline every 5 seconds until it reaches a terminal state (same
1255/// states as [`wait_for_pipeline`]) without any terminal output, and return
1256/// the final pipeline for JSON rendering.
1257async fn wait_for_pipeline_silently(
1258    client: &BitbucketClient,
1259    workspace: &str,
1260    repo_slug: &str,
1261    pipeline_uuid: &str,
1262) -> Result<Pipeline> {
1263    loop {
1264        tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
1265
1266        let current = client
1267            .get_pipeline(workspace, repo_slug, pipeline_uuid)
1268            .await?;
1269
1270        match current.state.name {
1271            PipelineStateName::Completed
1272            | PipelineStateName::Halted
1273            | PipelineStateName::Paused => return Ok(current),
1274            _ => {}
1275        }
1276    }
1277}
1278
1279/// Poll a pipeline every 5 seconds until it reaches a state where waiting is
1280/// pointless: completed, halted, or paused (paused pipelines never progress
1281/// without a manual resume in the Bitbucket UI, so treat them as terminal).
1282async fn wait_for_pipeline(
1283    client: &BitbucketClient,
1284    workspace: &str,
1285    repo_slug: &str,
1286    pipeline_uuid: &str,
1287) -> Result<()> {
1288    let pb = ProgressBar::new_spinner();
1289    pb.set_style(
1290        ProgressStyle::default_spinner()
1291            .template("{spinner:.blue} {msg}")
1292            .unwrap(),
1293    );
1294    pb.set_message("Waiting for pipeline to complete...");
1295
1296    loop {
1297        tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
1298
1299        let current = client
1300            .get_pipeline(workspace, repo_slug, pipeline_uuid)
1301            .await?;
1302
1303        match current.state.name {
1304            PipelineStateName::Completed => {
1305                pb.finish_and_clear();
1306
1307                if let Some(result) = &current.state.result {
1308                    match result.name {
1309                        PipelineResultName::Successful => {
1310                            println!(
1311                                "{} Pipeline #{} completed successfully!",
1312                                "✓".green(),
1313                                current.build_number
1314                            );
1315                        }
1316                        PipelineResultName::Failed => {
1317                            println!("{} Pipeline #{} failed", "✗".red(), current.build_number);
1318                        }
1319                        _ => {
1320                            println!(
1321                                "Pipeline #{} completed with status: {:?}",
1322                                current.build_number, result.name
1323                            );
1324                        }
1325                    }
1326                }
1327                break;
1328            }
1329            PipelineStateName::Halted => {
1330                pb.finish_and_clear();
1331                println!(
1332                    "{} Pipeline #{} was halted",
1333                    "⚠".yellow(),
1334                    current.build_number
1335                );
1336                break;
1337            }
1338            PipelineStateName::Paused => {
1339                pb.finish_and_clear();
1340                println!(
1341                    "{} Pipeline #{} is PAUSED and requires manual resume",
1342                    "⚠".yellow(),
1343                    current.build_number
1344                );
1345                break;
1346            }
1347            _ => {
1348                pb.tick();
1349            }
1350        }
1351    }
1352
1353    Ok(())
1354}
1355
1356/// Fetch and print a step's log, indented and dimmed. Without `full`, output
1357/// is truncated to the first 50 lines.
1358///
1359/// Returns any fetch error to the caller instead of swallowing it. An empty
1360/// log is treated as success (logs may simply not exist yet for pending or
1361/// in-progress steps): callers iterating over every step ignore the error,
1362/// while a caller that explicitly asked for one step surfaces it.
1363async fn print_step_log(
1364    client: &BitbucketClient,
1365    workspace: &str,
1366    repo_slug: &str,
1367    pipeline_uuid: &str,
1368    step_uuid: &str,
1369    full: bool,
1370) -> Result<()> {
1371    let log = client
1372        .get_step_log(workspace, repo_slug, pipeline_uuid, step_uuid)
1373        .await?;
1374
1375    if log.is_empty() {
1376        return Ok(());
1377    }
1378
1379    println!();
1380    if full {
1381        for line in log.lines() {
1382            println!("    {}", line.dimmed());
1383        }
1384    } else {
1385        let (shown, truncated) = take_log_lines(&log, 50);
1386        for line in shown {
1387            println!("    {}", line.dimmed());
1388        }
1389        if truncated {
1390            println!(
1391                "    {}",
1392                "... (truncated; use --full-logs for the complete log)".dimmed()
1393            );
1394        }
1395    }
1396    println!();
1397
1398    Ok(())
1399}
1400
1401/// Print the detail block for a single pipeline step.
1402fn print_step_detail(step: &PipelineStep) {
1403    println!();
1404    println!("{}", "Step:".bold());
1405    println!(
1406        "  {} {}",
1407        step_status_icon(step),
1408        step.name.as_deref().unwrap_or("Step")
1409    );
1410    println!("    {} {}", "UUID:".dimmed(), step.uuid);
1411
1412    if let Some(state) = &step.state {
1413        let result = state
1414            .result
1415            .as_ref()
1416            .map(|r| format!(" ({})", r.name))
1417            .unwrap_or_default();
1418        println!("    {} {}{}", "State:".dimmed(), state.name, result);
1419    }
1420
1421    if let Some(started) = step.started_on {
1422        println!(
1423            "    {} {}",
1424            "Started:".dimmed(),
1425            started.format("%Y-%m-%d %H:%M:%S")
1426        );
1427    }
1428
1429    if let Some(completed) = step.completed_on {
1430        println!(
1431            "    {} {}",
1432            "Completed:".dimmed(),
1433            completed.format("%Y-%m-%d %H:%M:%S")
1434        );
1435    }
1436
1437    if let Some(image) = &step.image {
1438        println!("    {} {}", "Image:".dimmed(), image.name);
1439    }
1440
1441    if let Some(commands) = &step.script_commands {
1442        println!("    {} {}", "Script commands:".dimmed(), commands.len());
1443    }
1444}
1445
1446/// Status icon for a pipeline step based on its state and result.
1447fn step_status_icon(step: &PipelineStep) -> ColoredString {
1448    let status = step
1449        .state
1450        .as_ref()
1451        .map(|s| s.name.as_str())
1452        .unwrap_or("unknown");
1453
1454    match status {
1455        "COMPLETED" => {
1456            let result = step
1457                .state
1458                .as_ref()
1459                .and_then(|s| s.result.as_ref())
1460                .map(|r| r.name.as_str())
1461                .unwrap_or("");
1462            match result {
1463                "SUCCESSFUL" => "✓".green(),
1464                "FAILED" => "✗".red(),
1465                _ => "○".normal(),
1466            }
1467        }
1468        "IN_PROGRESS" => "◉".blue(),
1469        "PENDING" => "○".dimmed(),
1470        _ => "○".normal(),
1471    }
1472}
1473
1474pub(crate) fn format_status(
1475    state: &PipelineStateName,
1476    result: Option<&PipelineResultName>,
1477) -> String {
1478    match state {
1479        PipelineStateName::Pending => "PENDING".yellow().to_string(),
1480        PipelineStateName::InProgress => "RUNNING".blue().to_string(),
1481        PipelineStateName::Paused => "PAUSED".yellow().to_string(),
1482        PipelineStateName::Halted => "HALTED".red().to_string(),
1483        PipelineStateName::Completed => {
1484            if let Some(result) = result {
1485                match result {
1486                    PipelineResultName::Successful => "SUCCESS".green().to_string(),
1487                    PipelineResultName::Failed => "FAILED".red().to_string(),
1488                    PipelineResultName::Error => "ERROR".red().to_string(),
1489                    PipelineResultName::Stopped => "STOPPED".yellow().to_string(),
1490                    PipelineResultName::Expired => "EXPIRED".dimmed().to_string(),
1491                }
1492            } else {
1493                "COMPLETED".normal().to_string()
1494            }
1495        }
1496    }
1497}
1498
1499pub(crate) fn format_duration(seconds: u64) -> String {
1500    if seconds < 60 {
1501        format!("{}s", seconds)
1502    } else if seconds < 3600 {
1503        format!("{}m {}s", seconds / 60, seconds % 60)
1504    } else {
1505        format!("{}h {}m", seconds / 3600, (seconds % 3600) / 60)
1506    }
1507}
1508
1509/// Split a `KEY=VALUE` argument on the FIRST '=' so values may contain '='.
1510fn parse_var(spec: &str) -> Result<(String, String)> {
1511    let (key, value) = spec
1512        .split_once('=')
1513        .ok_or_else(|| anyhow::anyhow!("Invalid variable '{}': expected KEY=VALUE", spec))?;
1514
1515    if key.is_empty() {
1516        anyhow::bail!("Invalid variable '{}': key must not be empty", spec);
1517    }
1518
1519    Ok((key.to_string(), value.to_string()))
1520}
1521
1522/// Resolve a `--step` selector against a pipeline's steps.
1523///
1524/// A selector that parses as a number is a 1-based index; anything else is
1525/// matched as a case-insensitive UUID prefix (braces optional). Returns the
1526/// zero-based index of the step and whether it was selected by UUID.
1527fn select_step(steps: &[PipelineStep], selector: &str) -> Result<(usize, bool)> {
1528    if let Ok(index) = selector.parse::<usize>() {
1529        if index == 0 || index > steps.len() {
1530            anyhow::bail!(
1531                "Step index {} out of range (pipeline has {} step(s))",
1532                index,
1533                steps.len()
1534            );
1535        }
1536        return Ok((index - 1, false));
1537    }
1538
1539    let clean = |s: &str| {
1540        s.trim_start_matches('{')
1541            .trim_end_matches('}')
1542            .to_lowercase()
1543    };
1544    let needle = clean(selector);
1545    if needle.is_empty() {
1546        anyhow::bail!("--step must be a 1-based index or a step UUID prefix");
1547    }
1548
1549    let matches: Vec<usize> = steps
1550        .iter()
1551        .enumerate()
1552        .filter(|(_, s)| clean(&s.uuid).starts_with(&needle))
1553        .map(|(i, _)| i)
1554        .collect();
1555
1556    match matches.as_slice() {
1557        [] => anyhow::bail!("No step matches '{}'", selector),
1558        [only] => Ok((*only, true)),
1559        _ => anyhow::bail!(
1560            "Step UUID prefix '{}' is ambiguous ({} steps match)",
1561            selector,
1562            matches.len()
1563        ),
1564    }
1565}
1566
1567/// Wrap a UUID in braces if the user omitted them; Bitbucket API paths
1568/// require the braced form.
1569fn ensure_braced_uuid(uuid: &str) -> String {
1570    let uuid = uuid.trim();
1571    let trimmed = uuid.trim_start_matches('{').trim_end_matches('}');
1572    format!("{{{}}}", trimmed)
1573}
1574
1575/// Find the UUID of the variable whose key matches exactly.
1576fn find_variable_uuid(variables: &[PipelineVariable], key: &str) -> Option<String> {
1577    variables
1578        .iter()
1579        .find(|v| v.key.as_deref() == Some(key))
1580        .and_then(|v| v.uuid.clone())
1581}
1582
1583/// Return a copy of `variables` with secured values nulled out.
1584///
1585/// The API already omits `value` for secured variables, but this defends the
1586/// JSON path so a future/API quirk can't leak a secret that the table view
1587/// would have masked.
1588fn masked_variables(variables: &[PipelineVariable]) -> Vec<PipelineVariable> {
1589    variables
1590        .iter()
1591        .map(|v| {
1592            let mut masked = v.clone();
1593            if masked.secured == Some(true) {
1594                masked.value = None;
1595            }
1596            masked
1597        })
1598        .collect()
1599}
1600
1601/// Table rows for repository or workspace pipeline variables. Secured values
1602/// are never returned by the API, so they render masked.
1603fn variable_rows(variables: &[PipelineVariable]) -> Vec<VariableRow> {
1604    variables
1605        .iter()
1606        .map(|v| {
1607            let secured = v.secured.unwrap_or(false);
1608            VariableRow {
1609                key: v.key.clone().unwrap_or_else(|| "-".to_string()),
1610                value: if secured {
1611                    "••••••".to_string()
1612                } else {
1613                    v.value.clone().unwrap_or_else(|| "-".to_string())
1614                },
1615                secured: if secured {
1616                    "yes".to_string()
1617                } else {
1618                    "no".to_string()
1619                },
1620                uuid: v.uuid.clone().unwrap_or_else(|| "-".to_string()),
1621            }
1622        })
1623        .collect()
1624}
1625
1626/// Extract the branch name from a schedule's raw target object.
1627fn schedule_branch(target: Option<&serde_json::Value>) -> String {
1628    target
1629        .and_then(|t| t.get("ref_name"))
1630        .and_then(|v| v.as_str())
1631        .unwrap_or("-")
1632        .to_string()
1633}
1634
1635/// Human-readable byte size using binary units.
1636fn format_bytes(bytes: u64) -> String {
1637    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
1638    let mut value = bytes as f64;
1639    let mut unit = 0;
1640
1641    while value >= 1024.0 && unit < UNITS.len() - 1 {
1642        value /= 1024.0;
1643        unit += 1;
1644    }
1645
1646    if unit == 0 {
1647        format!("{} B", bytes)
1648    } else {
1649        format!("{:.1} {}", value, UNITS[unit])
1650    }
1651}
1652
1653/// Take at most `max` display lines from a log in a single pass, reporting
1654/// whether any lines were left out.
1655fn take_log_lines(log: &str, max: usize) -> (Vec<&str>, bool) {
1656    let mut lines = log.lines();
1657    let shown: Vec<&str> = lines.by_ref().take(max).collect();
1658    let truncated = lines.next().is_some();
1659    (shown, truncated)
1660}
1661
1662#[cfg(test)]
1663mod tests {
1664    use crate::models::{PipelineStep, PipelineStepResult, PipelineStepState, PipelineVariable};
1665
1666    use super::{
1667        ensure_braced_uuid, find_variable_uuid, format_bytes, parse_var, schedule_branch,
1668        select_step, step_status_icon, take_log_lines, variable_rows,
1669    };
1670
1671    fn log_with_lines(n: usize) -> String {
1672        (0..n).map(|i| format!("line {}\n", i)).collect()
1673    }
1674
1675    #[test]
1676    fn under_the_limit_is_not_truncated() {
1677        let log = log_with_lines(49);
1678        let (shown, truncated) = take_log_lines(&log, 50);
1679        assert_eq!(shown.len(), 49);
1680        assert!(!truncated);
1681    }
1682
1683    #[test]
1684    fn exactly_the_limit_is_not_truncated() {
1685        let log = log_with_lines(50);
1686        let (shown, truncated) = take_log_lines(&log, 50);
1687        assert_eq!(shown.len(), 50);
1688        assert!(!truncated);
1689    }
1690
1691    #[test]
1692    fn one_over_the_limit_is_truncated() {
1693        let log = log_with_lines(51);
1694        let (shown, truncated) = take_log_lines(&log, 50);
1695        assert_eq!(shown.len(), 50);
1696        assert!(truncated);
1697    }
1698
1699    #[test]
1700    fn parse_var_splits_on_first_equals() {
1701        let (key, value) = parse_var("KEY=a=b=c").unwrap();
1702        assert_eq!(key, "KEY");
1703        assert_eq!(value, "a=b=c");
1704    }
1705
1706    #[test]
1707    fn parse_var_accepts_empty_value() {
1708        let (key, value) = parse_var("KEY=").unwrap();
1709        assert_eq!(key, "KEY");
1710        assert_eq!(value, "");
1711    }
1712
1713    #[test]
1714    fn parse_var_rejects_missing_equals() {
1715        let err = parse_var("KEYVALUE").unwrap_err();
1716        assert!(err.to_string().contains("expected KEY=VALUE"));
1717    }
1718
1719    #[test]
1720    fn parse_var_rejects_empty_key() {
1721        let err = parse_var("=value").unwrap_err();
1722        assert!(err.to_string().contains("key must not be empty"));
1723    }
1724
1725    fn step(uuid: &str) -> PipelineStep {
1726        PipelineStep {
1727            uuid: uuid.to_string(),
1728            name: Some("Step".to_string()),
1729            started_on: None,
1730            completed_on: None,
1731            state: None,
1732            image: None,
1733            setup_commands: None,
1734            script_commands: None,
1735            links: None,
1736        }
1737    }
1738
1739    #[test]
1740    fn select_step_by_one_based_index() {
1741        let steps = [step("{aaa-111}"), step("{bbb-222}")];
1742        let (index, by_uuid) = select_step(&steps, "2").unwrap();
1743        assert_eq!(index, 1);
1744        assert!(!by_uuid);
1745    }
1746
1747    #[test]
1748    fn select_step_rejects_index_zero() {
1749        let steps = [step("{aaa-111}")];
1750        assert!(select_step(&steps, "0").is_err());
1751    }
1752
1753    #[test]
1754    fn select_step_rejects_index_out_of_range() {
1755        let steps = [step("{aaa-111}")];
1756        assert!(select_step(&steps, "2").is_err());
1757    }
1758
1759    #[test]
1760    fn select_step_by_uuid_prefix_without_braces() {
1761        let steps = [step("{aaa-111}"), step("{bbb-222}")];
1762        let (index, by_uuid) = select_step(&steps, "bbb").unwrap();
1763        assert_eq!(index, 1);
1764        assert!(by_uuid);
1765    }
1766
1767    #[test]
1768    fn select_step_by_full_braced_uuid() {
1769        let steps = [step("{aaa-111}"), step("{bbb-222}")];
1770        let (index, by_uuid) = select_step(&steps, "{bbb-222}").unwrap();
1771        assert_eq!(index, 1);
1772        assert!(by_uuid);
1773    }
1774
1775    #[test]
1776    fn select_step_uuid_prefix_is_case_insensitive() {
1777        let steps = [step("{ABC-123}")];
1778        let (index, _) = select_step(&steps, "abc").unwrap();
1779        assert_eq!(index, 0);
1780    }
1781
1782    #[test]
1783    fn select_step_rejects_ambiguous_prefix() {
1784        let steps = [step("{abc-111}"), step("{abc-222}")];
1785        let err = select_step(&steps, "abc").unwrap_err();
1786        assert!(err.to_string().contains("ambiguous"));
1787    }
1788
1789    #[test]
1790    fn select_step_rejects_unknown_prefix() {
1791        let steps = [step("{aaa-111}")];
1792        assert!(select_step(&steps, "zzz").is_err());
1793    }
1794
1795    #[test]
1796    fn ensure_braced_uuid_wraps_bare_uuids() {
1797        assert_eq!(ensure_braced_uuid("abc-123"), "{abc-123}");
1798    }
1799
1800    #[test]
1801    fn ensure_braced_uuid_keeps_braced_uuids() {
1802        assert_eq!(ensure_braced_uuid("{abc-123}"), "{abc-123}");
1803    }
1804
1805    #[test]
1806    fn find_variable_uuid_matches_key_exactly() {
1807        let variables = vec![
1808            crate::models::PipelineVariable {
1809                uuid: Some("{u1}".to_string()),
1810                key: Some("FOO".to_string()),
1811                value: None,
1812                secured: None,
1813            },
1814            crate::models::PipelineVariable {
1815                uuid: Some("{u2}".to_string()),
1816                key: Some("FOOBAR".to_string()),
1817                value: None,
1818                secured: None,
1819            },
1820        ];
1821
1822        assert_eq!(
1823            find_variable_uuid(&variables, "FOO").as_deref(),
1824            Some("{u1}")
1825        );
1826        assert_eq!(find_variable_uuid(&variables, "BAR"), None);
1827    }
1828
1829    #[test]
1830    fn schedule_branch_reads_ref_name_from_target() {
1831        let target = serde_json::json!({"type": "pipeline_ref_target", "ref_name": "main"});
1832        assert_eq!(schedule_branch(Some(&target)), "main");
1833    }
1834
1835    #[test]
1836    fn schedule_branch_falls_back_to_dash() {
1837        assert_eq!(schedule_branch(None), "-");
1838        let target = serde_json::json!({"type": "pipeline_ref_target"});
1839        assert_eq!(schedule_branch(Some(&target)), "-");
1840    }
1841
1842    #[test]
1843    fn format_bytes_uses_binary_units() {
1844        assert_eq!(format_bytes(512), "512 B");
1845        assert_eq!(format_bytes(2048), "2.0 KiB");
1846        assert_eq!(format_bytes(5 * 1024 * 1024), "5.0 MiB");
1847    }
1848
1849    fn step_with_state(state: &str, result: Option<&str>) -> PipelineStep {
1850        PipelineStep {
1851            uuid: "{step}".to_string(),
1852            name: Some("Step".to_string()),
1853            started_on: None,
1854            completed_on: None,
1855            state: Some(PipelineStepState {
1856                name: state.to_string(),
1857                state_type: "pipeline_step_state".to_string(),
1858                result: result.map(|r| PipelineStepResult {
1859                    name: r.to_string(),
1860                    result_type: "pipeline_step_result".to_string(),
1861                }),
1862            }),
1863            image: None,
1864            setup_commands: None,
1865            script_commands: None,
1866            links: None,
1867        }
1868    }
1869
1870    #[test]
1871    fn step_status_icon_per_state() {
1872        // Assert on the underlying glyph via `contains` so the result holds
1873        // whether or not ANSI colouring is active in the test environment.
1874        assert!(
1875            step_status_icon(&step_with_state("COMPLETED", Some("SUCCESSFUL")))
1876                .to_string()
1877                .contains('✓')
1878        );
1879        assert!(
1880            step_status_icon(&step_with_state("COMPLETED", Some("FAILED")))
1881                .to_string()
1882                .contains('✗')
1883        );
1884        assert!(
1885            step_status_icon(&step_with_state("COMPLETED", Some("STOPPED")))
1886                .to_string()
1887                .contains('○')
1888        );
1889        assert!(
1890            step_status_icon(&step_with_state("IN_PROGRESS", None))
1891                .to_string()
1892                .contains('◉')
1893        );
1894        assert!(
1895            step_status_icon(&step_with_state("PENDING", None))
1896                .to_string()
1897                .contains('○')
1898        );
1899
1900        // No state at all falls back to the neutral marker.
1901        let mut stateless = step_with_state("PENDING", None);
1902        stateless.state = None;
1903        assert!(step_status_icon(&stateless).to_string().contains('○'));
1904    }
1905
1906    fn variable(key: &str, value: Option<&str>, secured: Option<bool>) -> PipelineVariable {
1907        PipelineVariable {
1908            uuid: Some("{u}".to_string()),
1909            key: Some(key.to_string()),
1910            value: value.map(|v| v.to_string()),
1911            secured,
1912        }
1913    }
1914
1915    #[test]
1916    fn variable_rows_masks_secured_values() {
1917        let vars = vec![
1918            variable("PLAIN", Some("hello"), Some(false)),
1919            variable("SECRET", Some("shh"), Some(true)),
1920        ];
1921        let rows = variable_rows(&vars);
1922
1923        assert_eq!(rows[0].value, "hello");
1924        assert_eq!(rows[0].secured, "no");
1925
1926        assert_eq!(rows[1].value, "••••••");
1927        assert_eq!(rows[1].secured, "yes");
1928    }
1929}