Skip to main content

bitbucket_cli/cli/
deploy.rs

1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use clap::{Subcommand, ValueEnum};
5use colored::Colorize;
6use tabled::{Table, Tabled};
7
8use super::{confirm_or_abort, output_json, parse_repo, print_json};
9use crate::api::BitbucketClient;
10use crate::cli::pagination::{MAX_LIMIT, effective_limit as capped_limit};
11use crate::models::{
12    AddDeployKeyRequest, CreateEnvironmentRequest, Deployment, Environment, EnvironmentType,
13    EnvironmentVariable, EnvironmentVariableInput,
14};
15
16/// How many characters of SSH key material to show in list tables.
17const KEY_DISPLAY_CHARS: usize = 40;
18
19/// Commands for managing repository deploy keys.
20#[derive(Subcommand)]
21pub enum DeployKeyCommands {
22    /// List deploy keys for a repository
23    List {
24        /// Repository in format workspace/repo-slug
25        repo: String,
26    },
27
28    /// Add a deploy key to a repository
29    Add {
30        /// Repository in format workspace/repo-slug
31        repo: String,
32
33        /// SSH public key material (e.g. "ssh-ed25519 AAAA... user@host")
34        #[arg(
35            long,
36            conflicts_with = "key_file",
37            required_unless_present = "key_file"
38        )]
39        key: Option<String>,
40
41        /// Read the SSH public key from a file
42        #[arg(long, value_name = "PATH", required_unless_present = "key")]
43        key_file: Option<PathBuf>,
44
45        /// Label for the deploy key
46        #[arg(long)]
47        label: String,
48    },
49
50    /// Delete a deploy key from a repository
51    Delete {
52        /// Repository in format workspace/repo-slug
53        repo: String,
54
55        /// Deploy key ID (see `deploy-key list`)
56        id: u64,
57
58        /// Skip confirmation prompt
59        #[arg(short, long)]
60        yes: bool,
61    },
62}
63
64/// Commands for managing deployment environments.
65#[derive(Subcommand)]
66pub enum EnvironmentCommands {
67    /// List deployment environments for a repository
68    List {
69        /// Repository in format workspace/repo-slug
70        repo: String,
71    },
72
73    /// Create a deployment environment
74    Create {
75        /// Repository in format workspace/repo-slug
76        repo: String,
77
78        /// Environment name
79        name: String,
80
81        /// Environment type
82        #[arg(
83            long = "type",
84            value_name = "TYPE",
85            value_enum,
86            ignore_case = true,
87            default_value = "test"
88        )]
89        environment_type: EnvironmentTypeArg,
90    },
91
92    /// Delete a deployment environment
93    Delete {
94        /// Repository in format workspace/repo-slug
95        repo: String,
96
97        /// Environment UUID (see `environment list`)
98        uuid: String,
99
100        /// Skip confirmation prompt
101        #[arg(short, long)]
102        yes: bool,
103    },
104
105    /// Manage variables scoped to a deployment environment
106    Variable {
107        #[command(subcommand)]
108        command: EnvironmentVariableCommands,
109    },
110}
111
112/// Commands for managing variables on a single deployment environment.
113///
114/// Unlike `pipeline variable` (repository-wide) and `pipeline
115/// workspace-variable` (workspace-wide), these are scoped to one environment,
116/// so the same key can carry a different value per environment — which is how
117/// a `deployment: staging` step and a `deployment: production` step see
118/// different `AWS_ROLE_ARN`, bucket, etc.
119#[derive(Subcommand)]
120pub enum EnvironmentVariableCommands {
121    /// List the variables on a deployment environment
122    List {
123        /// Repository in format workspace/repo-slug
124        repo: String,
125
126        /// Environment UUID (see `environment list`)
127        environment: String,
128    },
129
130    /// Create or update a variable on a deployment environment
131    Set {
132        /// Repository in format workspace/repo-slug
133        repo: String,
134
135        /// Environment UUID (see `environment list`)
136        environment: String,
137
138        /// Variable name
139        key: String,
140
141        /// Variable value
142        value: String,
143
144        /// Mask the value in logs and the UI
145        #[arg(long)]
146        secured: bool,
147    },
148
149    /// Delete a variable from a deployment environment by key
150    Delete {
151        /// Repository in format workspace/repo-slug
152        repo: String,
153
154        /// Environment UUID (see `environment list`)
155        environment: String,
156
157        /// Variable name
158        key: String,
159
160        /// Skip confirmation prompt
161        #[arg(short, long)]
162        yes: bool,
163    },
164}
165
166/// Commands for inspecting deployments.
167#[derive(Subcommand)]
168pub enum DeploymentCommands {
169    /// List deployments for a repository
170    List {
171        /// Repository in format workspace/repo-slug
172        repo: String,
173
174        /// Number of results (max 100)
175        #[arg(short, long, default_value = "25")]
176        limit: u32,
177    },
178
179    /// View deployment details
180    View {
181        /// Repository in format workspace/repo-slug
182        repo: String,
183
184        /// Deployment UUID
185        uuid: String,
186    },
187}
188
189/// Environment category accepted by `environment create --type`.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
191pub enum EnvironmentTypeArg {
192    Test,
193    Staging,
194    Production,
195}
196
197impl EnvironmentTypeArg {
198    /// The type name the Bitbucket API expects for this environment category.
199    fn api_name(self) -> &'static str {
200        match self {
201            EnvironmentTypeArg::Test => "Test",
202            EnvironmentTypeArg::Staging => "Staging",
203            EnvironmentTypeArg::Production => "Production",
204        }
205    }
206}
207
208#[derive(Tabled)]
209struct DeployKeyRow {
210    #[tabled(rename = "ID")]
211    id: String,
212    #[tabled(rename = "LABEL")]
213    label: String,
214    #[tabled(rename = "KEY")]
215    key: String,
216}
217
218impl DeployKeyCommands {
219    /// Execute the deploy-key subcommand.
220    pub async fn run(self) -> Result<()> {
221        match self {
222            DeployKeyCommands::List { repo } => {
223                let (workspace, repo_slug) = parse_repo(&repo)?;
224                let client = BitbucketClient::from_stored().await?;
225                let keys = client.list_deploy_keys(&workspace, &repo_slug).await?;
226
227                if output_json() {
228                    return print_json(&keys.values);
229                }
230
231                if keys.values.is_empty() {
232                    println!("No deploy keys found in {}", repo);
233                    return Ok(());
234                }
235
236                let rows: Vec<DeployKeyRow> = keys
237                    .values
238                    .iter()
239                    .map(|k| DeployKeyRow {
240                        id: k.id.map(|id| id.to_string()).unwrap_or_else(|| "-".into()),
241                        label: k.label.clone().unwrap_or_default(),
242                        key: truncate_chars(k.key.as_deref().unwrap_or("-"), KEY_DISPLAY_CHARS),
243                    })
244                    .collect();
245
246                println!("{}", Table::new(rows));
247
248                Ok(())
249            }
250
251            DeployKeyCommands::Add {
252                repo,
253                key,
254                key_file,
255                label,
256            } => {
257                let (workspace, repo_slug) = parse_repo(&repo)?;
258
259                // clap enforces exactly one key source; the bail arms are a
260                // safety net in case this is ever called programmatically.
261                let material = match (key, key_file) {
262                    (Some(key), None) => key,
263                    (None, Some(path)) => std::fs::read_to_string(&path)
264                        .with_context(|| format!("Failed to read key file '{}'", path.display()))?,
265                    (Some(_), Some(_)) => {
266                        anyhow::bail!("Pass either --key or --key-file, not both")
267                    }
268                    (None, None) => anyhow::bail!("Pass one of --key or --key-file"),
269                };
270                let key = normalize_key(&material)?;
271
272                let request = AddDeployKeyRequest { key, label };
273
274                let client = BitbucketClient::from_stored().await?;
275                let added = client
276                    .add_deploy_key(&workspace, &repo_slug, &request)
277                    .await?;
278
279                if output_json() {
280                    return print_json(&added);
281                }
282
283                println!(
284                    "{} Added deploy key {} to {}",
285                    "✓".green(),
286                    added.label.as_deref().unwrap_or(&request.label).cyan(),
287                    repo.cyan()
288                );
289
290                if let Some(id) = added.id {
291                    println!("{} {}", "ID:".dimmed(), id);
292                }
293
294                Ok(())
295            }
296
297            DeployKeyCommands::Delete { repo, id, yes } => {
298                let (workspace, repo_slug) = parse_repo(&repo)?;
299
300                if !yes
301                    && !confirm_or_abort(format!(
302                        "Delete deploy key {} from {}?",
303                        id.to_string().red(),
304                        repo
305                    ))?
306                {
307                    return Ok(());
308                }
309
310                let client = BitbucketClient::from_stored().await?;
311                client.delete_deploy_key(&workspace, &repo_slug, id).await?;
312
313                if output_json() {
314                    return print_json(&serde_json::json!({ "ok": true }));
315                }
316
317                println!("{} Deleted deploy key {}", "✓".green(), id);
318
319                Ok(())
320            }
321        }
322    }
323}
324
325#[derive(Tabled)]
326struct EnvironmentRow {
327    #[tabled(rename = "NAME")]
328    name: String,
329    #[tabled(rename = "TYPE")]
330    environment_type: String,
331    #[tabled(rename = "UUID")]
332    uuid: String,
333}
334
335impl EnvironmentCommands {
336    /// Execute the environment subcommand.
337    pub async fn run(self) -> Result<()> {
338        match self {
339            EnvironmentCommands::List { repo } => {
340                let (workspace, repo_slug) = parse_repo(&repo)?;
341                let client = BitbucketClient::from_stored().await?;
342                let environments = client.list_environments(&workspace, &repo_slug).await?;
343
344                if output_json() {
345                    return print_json(&environments.values);
346                }
347
348                if environments.values.is_empty() {
349                    println!("No environments found in {}", repo);
350                    return Ok(());
351                }
352
353                let rows: Vec<EnvironmentRow> = environments
354                    .values
355                    .iter()
356                    .map(|e| EnvironmentRow {
357                        name: e.name.clone().unwrap_or_default(),
358                        environment_type: e
359                            .environment_type
360                            .as_ref()
361                            .and_then(|t| t.name.clone())
362                            .unwrap_or_else(|| "-".into()),
363                        uuid: e.uuid.clone().unwrap_or_else(|| "-".into()),
364                    })
365                    .collect();
366
367                println!("{}", Table::new(rows));
368
369                Ok(())
370            }
371
372            EnvironmentCommands::Create {
373                repo,
374                name,
375                environment_type,
376            } => {
377                let (workspace, repo_slug) = parse_repo(&repo)?;
378
379                let request = CreateEnvironmentRequest {
380                    name,
381                    environment_type: EnvironmentType {
382                        name: Some(environment_type.api_name().to_string()),
383                    },
384                };
385
386                let client = BitbucketClient::from_stored().await?;
387                let created = client
388                    .create_environment(&workspace, &repo_slug, &request)
389                    .await?;
390
391                if output_json() {
392                    return print_json(&created);
393                }
394
395                println!(
396                    "{} Created {} environment {}",
397                    "✓".green(),
398                    environment_type.api_name(),
399                    created.name.as_deref().unwrap_or(&request.name).cyan()
400                );
401
402                if let Some(uuid) = &created.uuid {
403                    println!("{} {}", "UUID:".dimmed(), uuid);
404                }
405
406                Ok(())
407            }
408
409            EnvironmentCommands::Delete { repo, uuid, yes } => {
410                let (workspace, repo_slug) = parse_repo(&repo)?;
411                let uuid = ensure_braced(&uuid);
412
413                if !yes
414                    && !confirm_or_abort(format!(
415                        "Delete environment {} from {}?",
416                        uuid.red(),
417                        repo
418                    ))?
419                {
420                    return Ok(());
421                }
422
423                let client = BitbucketClient::from_stored().await?;
424                client
425                    .delete_environment(&workspace, &repo_slug, &uuid)
426                    .await?;
427
428                if output_json() {
429                    return print_json(&serde_json::json!({ "ok": true }));
430                }
431
432                println!("{} Deleted environment {}", "✓".green(), uuid);
433
434                Ok(())
435            }
436
437            EnvironmentCommands::Variable { command } => command.run().await,
438        }
439    }
440}
441
442/// Table row for `environment variable list`.
443#[derive(Tabled)]
444struct EnvironmentVariableRow {
445    #[tabled(rename = "KEY")]
446    key: String,
447    #[tabled(rename = "VALUE")]
448    value: String,
449    #[tabled(rename = "SECURED")]
450    secured: String,
451    #[tabled(rename = "UUID")]
452    uuid: String,
453}
454
455/// Find a variable's UUID by key (secured or not) within one environment.
456fn find_environment_variable_uuid(
457    variables: &[EnvironmentVariable],
458    key: &str,
459) -> Option<String> {
460    variables
461        .iter()
462        .find(|v| v.key.as_deref() == Some(key))
463        .and_then(|v| v.uuid.clone())
464}
465
466/// Blank out `value` on secured variables so a JSON dump never leaks a secret
467/// (the API already omits it, but a locally-constructed value could sneak in).
468fn masked_environment_variables(variables: &[EnvironmentVariable]) -> Vec<EnvironmentVariable> {
469    variables
470        .iter()
471        .map(|v| {
472            let mut v = v.clone();
473            if v.secured.unwrap_or(false) {
474                v.value = None;
475            }
476            v
477        })
478        .collect()
479}
480
481fn environment_variable_rows(variables: &[EnvironmentVariable]) -> Vec<EnvironmentVariableRow> {
482    variables
483        .iter()
484        .map(|v| {
485            let secured = v.secured.unwrap_or(false);
486            EnvironmentVariableRow {
487                key: v.key.clone().unwrap_or_default(),
488                value: if secured {
489                    "<secured>".into()
490                } else {
491                    v.value.clone().unwrap_or_default()
492                },
493                secured: if secured { "yes" } else { "no" }.into(),
494                uuid: v.uuid.clone().unwrap_or_else(|| "-".into()),
495            }
496        })
497        .collect()
498}
499
500impl EnvironmentVariableCommands {
501    /// Execute the environment-variable subcommand.
502    pub async fn run(self) -> Result<()> {
503        match self {
504            EnvironmentVariableCommands::List { repo, environment } => {
505                let (workspace, repo_slug) = parse_repo(&repo)?;
506                let environment = ensure_braced(&environment);
507                let client = BitbucketClient::from_stored().await?;
508
509                let variables = client
510                    .list_environment_variables(&workspace, &repo_slug, &environment)
511                    .await?;
512
513                if output_json() {
514                    return print_json(&masked_environment_variables(&variables));
515                }
516
517                if variables.is_empty() {
518                    println!("No variables on environment {}", environment);
519                    return Ok(());
520                }
521
522                println!("{}", Table::new(environment_variable_rows(&variables)));
523
524                Ok(())
525            }
526
527            EnvironmentVariableCommands::Set {
528                repo,
529                environment,
530                key,
531                value,
532                secured,
533            } => {
534                let (workspace, repo_slug) = parse_repo(&repo)?;
535                let environment = ensure_braced(&environment);
536                let client = BitbucketClient::from_stored().await?;
537
538                let input = EnvironmentVariableInput {
539                    key: key.clone(),
540                    value,
541                    secured,
542                };
543
544                let variables = client
545                    .list_environment_variables(&workspace, &repo_slug, &environment)
546                    .await?;
547
548                match find_environment_variable_uuid(&variables, &key) {
549                    Some(uuid) => {
550                        let variable = client
551                            .update_environment_variable(
552                                &workspace,
553                                &repo_slug,
554                                &environment,
555                                &uuid,
556                                &input,
557                            )
558                            .await
559                            .with_context(|| {
560                                format!(
561                                    "updating variable '{}' (it may have been deleted \
562                                     concurrently — re-run to create it)",
563                                    key
564                                )
565                            })?;
566                        if output_json() {
567                            return print_json(&variable);
568                        }
569                        println!(
570                            "{} Updated environment variable {}",
571                            "✓".green(),
572                            key.cyan()
573                        );
574                    }
575                    None => {
576                        let variable = client
577                            .create_environment_variable(
578                                &workspace,
579                                &repo_slug,
580                                &environment,
581                                &input,
582                            )
583                            .await?;
584                        if output_json() {
585                            return print_json(&variable);
586                        }
587                        println!(
588                            "{} Created environment variable {}",
589                            "✓".green(),
590                            key.cyan()
591                        );
592                    }
593                }
594
595                Ok(())
596            }
597
598            EnvironmentVariableCommands::Delete {
599                repo,
600                environment,
601                key,
602                yes,
603            } => {
604                let (workspace, repo_slug) = parse_repo(&repo)?;
605                let environment = ensure_braced(&environment);
606                let client = BitbucketClient::from_stored().await?;
607
608                let variables = client
609                    .list_environment_variables(&workspace, &repo_slug, &environment)
610                    .await?;
611                let uuid =
612                    find_environment_variable_uuid(&variables, &key).ok_or_else(|| {
613                        anyhow::anyhow!(
614                            "No variable named '{}' on environment {}",
615                            key,
616                            environment
617                        )
618                    })?;
619
620                if !yes
621                    && !confirm_or_abort(format!("Delete environment variable {}?", key.red()))?
622                {
623                    return Ok(());
624                }
625
626                client
627                    .delete_environment_variable(&workspace, &repo_slug, &environment, &uuid)
628                    .await?;
629
630                if output_json() {
631                    return print_json(&serde_json::json!({ "ok": true }));
632                }
633
634                println!("{} Deleted environment variable {}", "✓".green(), key);
635
636                Ok(())
637            }
638        }
639    }
640}
641
642#[derive(Tabled)]
643struct DeploymentRow {
644    #[tabled(rename = "UUID")]
645    uuid: String,
646    #[tabled(rename = "STATUS")]
647    status: String,
648    #[tabled(rename = "ENVIRONMENT")]
649    environment: String,
650}
651
652impl DeploymentCommands {
653    /// Execute the deployment subcommand.
654    pub async fn run(self) -> Result<()> {
655        match self {
656            DeploymentCommands::List { repo, limit } => {
657                let (workspace, repo_slug) = parse_repo(&repo)?;
658
659                let capped = capped_limit(limit);
660                if capped != limit && !output_json() {
661                    println!(
662                        "{} Limit capped at {} (the Bitbucket API maximum)",
663                        "ℹ".blue(),
664                        MAX_LIMIT
665                    );
666                }
667
668                let client = BitbucketClient::from_stored().await?;
669                let deployments = client
670                    .list_deployments(&workspace, &repo_slug, Some(capped))
671                    .await?;
672
673                if output_json() {
674                    return print_json(&deployments.values);
675                }
676
677                if deployments.values.is_empty() {
678                    println!("No deployments found in {}", repo);
679                    return Ok(());
680                }
681
682                let rows: Vec<DeploymentRow> = deployments
683                    .values
684                    .iter()
685                    .map(|d| DeploymentRow {
686                        uuid: d.uuid.clone().unwrap_or_else(|| "-".into()),
687                        status: color_status(&deployment_status(d)),
688                        environment: environment_label(d.environment.as_ref()),
689                    })
690                    .collect();
691
692                println!("{}", Table::new(rows));
693
694                if deployments.next.is_some() {
695                    println!(
696                        "\n{} More deployments available. Use --limit to see more.",
697                        "ℹ".blue()
698                    );
699                }
700
701                Ok(())
702            }
703
704            DeploymentCommands::View { repo, uuid } => {
705                let (workspace, repo_slug) = parse_repo(&repo)?;
706                let uuid = ensure_braced(&uuid);
707
708                let client = BitbucketClient::from_stored().await?;
709                let deployment = client.get_deployment(&workspace, &repo_slug, &uuid).await?;
710
711                if output_json() {
712                    return print_json(&deployment);
713                }
714
715                println!(
716                    "{}",
717                    format!("Deployment {}", deployment.uuid.as_deref().unwrap_or(&uuid)).bold()
718                );
719                println!("{}", "─".repeat(60));
720
721                println!(
722                    "{} {}",
723                    "Status:".dimmed(),
724                    color_status(&deployment_status(&deployment))
725                );
726                println!(
727                    "{} {}",
728                    "Environment:".dimmed(),
729                    environment_label(deployment.environment.as_ref())
730                );
731
732                if let Some(summary) = deployment.release.as_ref().and_then(release_summary) {
733                    println!("{} {}", "Release:".dimmed(), summary);
734                }
735
736                Ok(())
737            }
738        }
739    }
740}
741
742/// Trim surrounding whitespace from SSH key material (public keys are a
743/// single line; files usually end with a newline), rejecting empty input.
744fn normalize_key(material: &str) -> Result<String> {
745    let key = material.trim();
746    if key.is_empty() {
747        anyhow::bail!("The provided SSH key is empty");
748    }
749    Ok(key.to_string())
750}
751
752/// Truncate a string to at most `max` characters, appending an ellipsis when
753/// anything was cut off.
754fn truncate_chars(s: &str, max: usize) -> String {
755    let mut out: String = s.chars().take(max).collect();
756    if s.chars().count() > max {
757        out.push('…');
758    }
759    out
760}
761
762/// Wrap a UUID in the braces Bitbucket expects (`{...}`) unless it already
763/// has them, so users can paste UUIDs with or without braces.
764fn ensure_braced(uuid: &str) -> String {
765    let uuid = uuid.trim();
766    if uuid.starts_with('{') && uuid.ends_with('}') && uuid.len() >= 2 {
767        uuid.to_string()
768    } else {
769        format!("{{{}}}", uuid)
770    }
771}
772
773/// The most specific status string available for a deployment: the nested
774/// status name when present, then the state name, then "-".
775fn deployment_status(deployment: &Deployment) -> String {
776    deployment
777        .state
778        .as_ref()
779        .and_then(|state| {
780            state
781                .status
782                .as_ref()
783                .and_then(|status| status.get("name"))
784                .and_then(|name| name.as_str())
785                .map(str::to_string)
786                .or_else(|| state.name.clone())
787        })
788        .unwrap_or_else(|| "-".to_string())
789}
790
791/// Human-readable label for a deployment's environment: its name when known,
792/// falling back to the UUID, then "-".
793fn environment_label(environment: Option<&Environment>) -> String {
794    environment
795        .and_then(|e| e.name.clone().or_else(|| e.uuid.clone()))
796        .unwrap_or_else(|| "-".to_string())
797}
798
799/// Short summary of a deployment release: its name and, when present, the
800/// abbreviated commit hash it points at.
801fn release_summary(release: &serde_json::Value) -> Option<String> {
802    let name = release.get("name").and_then(|v| v.as_str());
803    let commit = release
804        .get("commit")
805        .and_then(|c| c.get("hash"))
806        .and_then(|h| h.as_str())
807        .map(|h| h.chars().take(12).collect::<String>());
808
809    match (name, commit) {
810        (Some(name), Some(commit)) => Some(format!("{} ({})", name, commit)),
811        (Some(name), None) => Some(name.to_string()),
812        (None, Some(commit)) => Some(commit),
813        (None, None) => None,
814    }
815}
816
817/// Colorize a deployment status string for terminal output.
818fn color_status(status: &str) -> String {
819    match status {
820        "COMPLETED" | "SUCCESSFUL" => status.green().to_string(),
821        "FAILED" | "ERROR" | "STOPPED" => status.red().to_string(),
822        "IN_PROGRESS" => status.blue().to_string(),
823        "PENDING" | "UNDEPLOYED" => status.dimmed().to_string(),
824        _ => status.normal().to_string(),
825    }
826}
827
828#[cfg(test)]
829mod tests {
830    use serde_json::json;
831
832    use super::*;
833    use crate::models::DeploymentState;
834
835    fn env_var(key: &str, value: Option<&str>, secured: bool, uuid: &str) -> EnvironmentVariable {
836        EnvironmentVariable {
837            uuid: Some(uuid.to_string()),
838            key: Some(key.to_string()),
839            value: value.map(|v| v.to_string()),
840            secured: Some(secured),
841        }
842    }
843
844    #[test]
845    fn find_environment_variable_uuid_matches_by_key() {
846        let vars = vec![
847            env_var("VITE_API_URL", Some("https://x"), false, "{aaa}"),
848            env_var("AWS_ROLE_ARN", Some("arn:..."), false, "{bbb}"),
849        ];
850        assert_eq!(
851            find_environment_variable_uuid(&vars, "AWS_ROLE_ARN"),
852            Some("{bbb}".to_string())
853        );
854        assert_eq!(find_environment_variable_uuid(&vars, "MISSING"), None);
855    }
856
857    #[test]
858    fn masked_environment_variables_blanks_secured_values() {
859        let vars = vec![
860            env_var("PLAIN", Some("visible"), false, "{a}"),
861            env_var("SECRET", Some("leak"), true, "{b}"),
862        ];
863        let masked = masked_environment_variables(&vars);
864        assert_eq!(masked[0].value.as_deref(), Some("visible"));
865        assert_eq!(masked[1].value, None);
866    }
867
868    #[test]
869    fn environment_variable_rows_shows_secured_placeholder() {
870        let vars = vec![
871            env_var("PLAIN", Some("v"), false, "{a}"),
872            env_var("SECRET", Some("v"), true, "{b}"),
873        ];
874        let rows = environment_variable_rows(&vars);
875        assert_eq!(rows[0].value, "v");
876        assert_eq!(rows[0].secured, "no");
877        assert_eq!(rows[1].value, "<secured>");
878        assert_eq!(rows[1].secured, "yes");
879    }
880
881    #[test]
882    fn normalize_key_trims_surrounding_whitespace() {
883        let key = normalize_key("  ssh-ed25519 AAAA host\n").unwrap();
884        assert_eq!(key, "ssh-ed25519 AAAA host");
885    }
886
887    #[test]
888    fn normalize_key_rejects_empty_input() {
889        assert!(normalize_key("").is_err());
890        assert!(normalize_key("  \n\t ").is_err());
891    }
892
893    #[test]
894    fn truncate_chars_leaves_short_strings_alone() {
895        assert_eq!(truncate_chars("short", 40), "short");
896        assert_eq!(truncate_chars("1234567890", 10), "1234567890");
897    }
898
899    #[test]
900    fn truncate_chars_cuts_long_strings_with_ellipsis() {
901        assert_eq!(truncate_chars("abcdef", 3), "abc…");
902    }
903
904    #[test]
905    fn truncate_chars_counts_characters_not_bytes() {
906        assert_eq!(truncate_chars("ééééé", 3), "ééé…");
907    }
908
909    #[test]
910    fn ensure_braced_wraps_bare_uuids() {
911        assert_eq!(ensure_braced("abc-123"), "{abc-123}");
912    }
913
914    #[test]
915    fn ensure_braced_keeps_existing_braces() {
916        assert_eq!(ensure_braced("{abc-123}"), "{abc-123}");
917    }
918
919    #[test]
920    fn ensure_braced_trims_whitespace() {
921        assert_eq!(ensure_braced(" abc "), "{abc}");
922        assert_eq!(ensure_braced(" {abc} "), "{abc}");
923    }
924
925    #[test]
926    fn environment_type_arg_maps_to_api_names() {
927        assert_eq!(EnvironmentTypeArg::Test.api_name(), "Test");
928        assert_eq!(EnvironmentTypeArg::Staging.api_name(), "Staging");
929        assert_eq!(EnvironmentTypeArg::Production.api_name(), "Production");
930    }
931
932    fn deployment_with_state(state: Option<DeploymentState>) -> Deployment {
933        Deployment {
934            uuid: None,
935            state,
936            environment: None,
937            release: None,
938        }
939    }
940
941    #[test]
942    fn deployment_status_prefers_nested_status_name() {
943        let deployment = deployment_with_state(Some(DeploymentState {
944            name: Some("COMPLETED".into()),
945            status: Some(json!({ "name": "SUCCESSFUL" })),
946        }));
947        assert_eq!(deployment_status(&deployment), "SUCCESSFUL");
948    }
949
950    #[test]
951    fn deployment_status_falls_back_to_state_name() {
952        let deployment = deployment_with_state(Some(DeploymentState {
953            name: Some("IN_PROGRESS".into()),
954            status: None,
955        }));
956        assert_eq!(deployment_status(&deployment), "IN_PROGRESS");
957    }
958
959    #[test]
960    fn deployment_status_defaults_to_dash() {
961        assert_eq!(deployment_status(&deployment_with_state(None)), "-");
962    }
963
964    #[test]
965    fn environment_label_prefers_name_over_uuid() {
966        let environment = Environment {
967            uuid: Some("{u}".into()),
968            name: Some("Production".into()),
969            environment_type: None,
970        };
971        assert_eq!(environment_label(Some(&environment)), "Production");
972
973        let unnamed = Environment {
974            uuid: Some("{u}".into()),
975            name: None,
976            environment_type: None,
977        };
978        assert_eq!(environment_label(Some(&unnamed)), "{u}");
979
980        assert_eq!(environment_label(None), "-");
981    }
982
983    #[test]
984    fn release_summary_combines_name_and_short_hash() {
985        let release = json!({
986            "name": "v1.2.3",
987            "commit": { "hash": "0123456789abcdef0123" }
988        });
989        assert_eq!(release_summary(&release).unwrap(), "v1.2.3 (0123456789ab)");
990    }
991
992    #[test]
993    fn release_summary_handles_partial_data() {
994        assert_eq!(release_summary(&json!({ "name": "v1" })).unwrap(), "v1");
995        assert_eq!(
996            release_summary(&json!({ "commit": { "hash": "abc123" } })).unwrap(),
997            "abc123"
998        );
999        assert!(release_summary(&json!({})).is_none());
1000    }
1001}