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};
14
15const KEY_DISPLAY_CHARS: usize = 40;
17
18#[derive(Subcommand)]
20pub enum DeployKeyCommands {
21 List {
23 repo: String,
25 },
26
27 Add {
29 repo: String,
31
32 #[arg(
34 long,
35 conflicts_with = "key_file",
36 required_unless_present = "key_file"
37 )]
38 key: Option<String>,
39
40 #[arg(long, value_name = "PATH", required_unless_present = "key")]
42 key_file: Option<PathBuf>,
43
44 #[arg(long)]
46 label: String,
47 },
48
49 Delete {
51 repo: String,
53
54 id: u64,
56
57 #[arg(short, long)]
59 yes: bool,
60 },
61}
62
63#[derive(Subcommand)]
65pub enum EnvironmentCommands {
66 List {
68 repo: String,
70 },
71
72 Create {
74 repo: String,
76
77 name: String,
79
80 #[arg(
82 long = "type",
83 value_name = "TYPE",
84 value_enum,
85 ignore_case = true,
86 default_value = "test"
87 )]
88 environment_type: EnvironmentTypeArg,
89 },
90
91 Delete {
93 repo: String,
95
96 uuid: String,
98
99 #[arg(short, long)]
101 yes: bool,
102 },
103}
104
105#[derive(Subcommand)]
107pub enum DeploymentCommands {
108 List {
110 repo: String,
112
113 #[arg(short, long, default_value = "25")]
115 limit: u32,
116 },
117
118 View {
120 repo: String,
122
123 uuid: String,
125 },
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
130pub enum EnvironmentTypeArg {
131 Test,
132 Staging,
133 Production,
134}
135
136impl EnvironmentTypeArg {
137 fn api_name(self) -> &'static str {
139 match self {
140 EnvironmentTypeArg::Test => "Test",
141 EnvironmentTypeArg::Staging => "Staging",
142 EnvironmentTypeArg::Production => "Production",
143 }
144 }
145}
146
147#[derive(Tabled)]
148struct DeployKeyRow {
149 #[tabled(rename = "ID")]
150 id: String,
151 #[tabled(rename = "LABEL")]
152 label: String,
153 #[tabled(rename = "KEY")]
154 key: String,
155}
156
157impl DeployKeyCommands {
158 pub async fn run(self) -> Result<()> {
160 match self {
161 DeployKeyCommands::List { repo } => {
162 let (workspace, repo_slug) = parse_repo(&repo)?;
163 let client = BitbucketClient::from_stored().await?;
164 let keys = client.list_deploy_keys(&workspace, &repo_slug).await?;
165
166 if output_json() {
167 return print_json(&keys.values);
168 }
169
170 if keys.values.is_empty() {
171 println!("No deploy keys found in {}", repo);
172 return Ok(());
173 }
174
175 let rows: Vec<DeployKeyRow> = keys
176 .values
177 .iter()
178 .map(|k| DeployKeyRow {
179 id: k.id.map(|id| id.to_string()).unwrap_or_else(|| "-".into()),
180 label: k.label.clone().unwrap_or_default(),
181 key: truncate_chars(k.key.as_deref().unwrap_or("-"), KEY_DISPLAY_CHARS),
182 })
183 .collect();
184
185 println!("{}", Table::new(rows));
186
187 Ok(())
188 }
189
190 DeployKeyCommands::Add {
191 repo,
192 key,
193 key_file,
194 label,
195 } => {
196 let (workspace, repo_slug) = parse_repo(&repo)?;
197
198 let material = match (key, key_file) {
201 (Some(key), None) => key,
202 (None, Some(path)) => std::fs::read_to_string(&path)
203 .with_context(|| format!("Failed to read key file '{}'", path.display()))?,
204 (Some(_), Some(_)) => {
205 anyhow::bail!("Pass either --key or --key-file, not both")
206 }
207 (None, None) => anyhow::bail!("Pass one of --key or --key-file"),
208 };
209 let key = normalize_key(&material)?;
210
211 let request = AddDeployKeyRequest { key, label };
212
213 let client = BitbucketClient::from_stored().await?;
214 let added = client
215 .add_deploy_key(&workspace, &repo_slug, &request)
216 .await?;
217
218 if output_json() {
219 return print_json(&added);
220 }
221
222 println!(
223 "{} Added deploy key {} to {}",
224 "✓".green(),
225 added.label.as_deref().unwrap_or(&request.label).cyan(),
226 repo.cyan()
227 );
228
229 if let Some(id) = added.id {
230 println!("{} {}", "ID:".dimmed(), id);
231 }
232
233 Ok(())
234 }
235
236 DeployKeyCommands::Delete { repo, id, yes } => {
237 let (workspace, repo_slug) = parse_repo(&repo)?;
238
239 if !yes
240 && !confirm_or_abort(format!(
241 "Delete deploy key {} from {}?",
242 id.to_string().red(),
243 repo
244 ))?
245 {
246 return Ok(());
247 }
248
249 let client = BitbucketClient::from_stored().await?;
250 client.delete_deploy_key(&workspace, &repo_slug, id).await?;
251
252 if output_json() {
253 return print_json(&serde_json::json!({ "ok": true }));
254 }
255
256 println!("{} Deleted deploy key {}", "✓".green(), id);
257
258 Ok(())
259 }
260 }
261 }
262}
263
264#[derive(Tabled)]
265struct EnvironmentRow {
266 #[tabled(rename = "NAME")]
267 name: String,
268 #[tabled(rename = "TYPE")]
269 environment_type: String,
270 #[tabled(rename = "UUID")]
271 uuid: String,
272}
273
274impl EnvironmentCommands {
275 pub async fn run(self) -> Result<()> {
277 match self {
278 EnvironmentCommands::List { repo } => {
279 let (workspace, repo_slug) = parse_repo(&repo)?;
280 let client = BitbucketClient::from_stored().await?;
281 let environments = client.list_environments(&workspace, &repo_slug).await?;
282
283 if output_json() {
284 return print_json(&environments.values);
285 }
286
287 if environments.values.is_empty() {
288 println!("No environments found in {}", repo);
289 return Ok(());
290 }
291
292 let rows: Vec<EnvironmentRow> = environments
293 .values
294 .iter()
295 .map(|e| EnvironmentRow {
296 name: e.name.clone().unwrap_or_default(),
297 environment_type: e
298 .environment_type
299 .as_ref()
300 .and_then(|t| t.name.clone())
301 .unwrap_or_else(|| "-".into()),
302 uuid: e.uuid.clone().unwrap_or_else(|| "-".into()),
303 })
304 .collect();
305
306 println!("{}", Table::new(rows));
307
308 Ok(())
309 }
310
311 EnvironmentCommands::Create {
312 repo,
313 name,
314 environment_type,
315 } => {
316 let (workspace, repo_slug) = parse_repo(&repo)?;
317
318 let request = CreateEnvironmentRequest {
319 name,
320 environment_type: EnvironmentType {
321 name: Some(environment_type.api_name().to_string()),
322 },
323 };
324
325 let client = BitbucketClient::from_stored().await?;
326 let created = client
327 .create_environment(&workspace, &repo_slug, &request)
328 .await?;
329
330 if output_json() {
331 return print_json(&created);
332 }
333
334 println!(
335 "{} Created {} environment {}",
336 "✓".green(),
337 environment_type.api_name(),
338 created.name.as_deref().unwrap_or(&request.name).cyan()
339 );
340
341 if let Some(uuid) = &created.uuid {
342 println!("{} {}", "UUID:".dimmed(), uuid);
343 }
344
345 Ok(())
346 }
347
348 EnvironmentCommands::Delete { repo, uuid, yes } => {
349 let (workspace, repo_slug) = parse_repo(&repo)?;
350 let uuid = ensure_braced(&uuid);
351
352 if !yes
353 && !confirm_or_abort(format!(
354 "Delete environment {} from {}?",
355 uuid.red(),
356 repo
357 ))?
358 {
359 return Ok(());
360 }
361
362 let client = BitbucketClient::from_stored().await?;
363 client
364 .delete_environment(&workspace, &repo_slug, &uuid)
365 .await?;
366
367 if output_json() {
368 return print_json(&serde_json::json!({ "ok": true }));
369 }
370
371 println!("{} Deleted environment {}", "✓".green(), uuid);
372
373 Ok(())
374 }
375 }
376 }
377}
378
379#[derive(Tabled)]
380struct DeploymentRow {
381 #[tabled(rename = "UUID")]
382 uuid: String,
383 #[tabled(rename = "STATUS")]
384 status: String,
385 #[tabled(rename = "ENVIRONMENT")]
386 environment: String,
387}
388
389impl DeploymentCommands {
390 pub async fn run(self) -> Result<()> {
392 match self {
393 DeploymentCommands::List { repo, limit } => {
394 let (workspace, repo_slug) = parse_repo(&repo)?;
395
396 let capped = capped_limit(limit);
397 if capped != limit && !output_json() {
398 println!(
399 "{} Limit capped at {} (the Bitbucket API maximum)",
400 "ℹ".blue(),
401 MAX_LIMIT
402 );
403 }
404
405 let client = BitbucketClient::from_stored().await?;
406 let deployments = client
407 .list_deployments(&workspace, &repo_slug, Some(capped))
408 .await?;
409
410 if output_json() {
411 return print_json(&deployments.values);
412 }
413
414 if deployments.values.is_empty() {
415 println!("No deployments found in {}", repo);
416 return Ok(());
417 }
418
419 let rows: Vec<DeploymentRow> = deployments
420 .values
421 .iter()
422 .map(|d| DeploymentRow {
423 uuid: d.uuid.clone().unwrap_or_else(|| "-".into()),
424 status: color_status(&deployment_status(d)),
425 environment: environment_label(d.environment.as_ref()),
426 })
427 .collect();
428
429 println!("{}", Table::new(rows));
430
431 if deployments.next.is_some() {
432 println!(
433 "\n{} More deployments available. Use --limit to see more.",
434 "ℹ".blue()
435 );
436 }
437
438 Ok(())
439 }
440
441 DeploymentCommands::View { repo, uuid } => {
442 let (workspace, repo_slug) = parse_repo(&repo)?;
443 let uuid = ensure_braced(&uuid);
444
445 let client = BitbucketClient::from_stored().await?;
446 let deployment = client.get_deployment(&workspace, &repo_slug, &uuid).await?;
447
448 if output_json() {
449 return print_json(&deployment);
450 }
451
452 println!(
453 "{}",
454 format!("Deployment {}", deployment.uuid.as_deref().unwrap_or(&uuid)).bold()
455 );
456 println!("{}", "─".repeat(60));
457
458 println!(
459 "{} {}",
460 "Status:".dimmed(),
461 color_status(&deployment_status(&deployment))
462 );
463 println!(
464 "{} {}",
465 "Environment:".dimmed(),
466 environment_label(deployment.environment.as_ref())
467 );
468
469 if let Some(summary) = deployment.release.as_ref().and_then(release_summary) {
470 println!("{} {}", "Release:".dimmed(), summary);
471 }
472
473 Ok(())
474 }
475 }
476 }
477}
478
479fn normalize_key(material: &str) -> Result<String> {
482 let key = material.trim();
483 if key.is_empty() {
484 anyhow::bail!("The provided SSH key is empty");
485 }
486 Ok(key.to_string())
487}
488
489fn truncate_chars(s: &str, max: usize) -> String {
492 let mut out: String = s.chars().take(max).collect();
493 if s.chars().count() > max {
494 out.push('…');
495 }
496 out
497}
498
499fn ensure_braced(uuid: &str) -> String {
502 let uuid = uuid.trim();
503 if uuid.starts_with('{') && uuid.ends_with('}') && uuid.len() >= 2 {
504 uuid.to_string()
505 } else {
506 format!("{{{}}}", uuid)
507 }
508}
509
510fn deployment_status(deployment: &Deployment) -> String {
513 deployment
514 .state
515 .as_ref()
516 .and_then(|state| {
517 state
518 .status
519 .as_ref()
520 .and_then(|status| status.get("name"))
521 .and_then(|name| name.as_str())
522 .map(str::to_string)
523 .or_else(|| state.name.clone())
524 })
525 .unwrap_or_else(|| "-".to_string())
526}
527
528fn environment_label(environment: Option<&Environment>) -> String {
531 environment
532 .and_then(|e| e.name.clone().or_else(|| e.uuid.clone()))
533 .unwrap_or_else(|| "-".to_string())
534}
535
536fn release_summary(release: &serde_json::Value) -> Option<String> {
539 let name = release.get("name").and_then(|v| v.as_str());
540 let commit = release
541 .get("commit")
542 .and_then(|c| c.get("hash"))
543 .and_then(|h| h.as_str())
544 .map(|h| h.chars().take(12).collect::<String>());
545
546 match (name, commit) {
547 (Some(name), Some(commit)) => Some(format!("{} ({})", name, commit)),
548 (Some(name), None) => Some(name.to_string()),
549 (None, Some(commit)) => Some(commit),
550 (None, None) => None,
551 }
552}
553
554fn color_status(status: &str) -> String {
556 match status {
557 "COMPLETED" | "SUCCESSFUL" => status.green().to_string(),
558 "FAILED" | "ERROR" | "STOPPED" => status.red().to_string(),
559 "IN_PROGRESS" => status.blue().to_string(),
560 "PENDING" | "UNDEPLOYED" => status.dimmed().to_string(),
561 _ => status.normal().to_string(),
562 }
563}
564
565#[cfg(test)]
566mod tests {
567 use serde_json::json;
568
569 use super::*;
570 use crate::models::DeploymentState;
571
572 #[test]
573 fn normalize_key_trims_surrounding_whitespace() {
574 let key = normalize_key(" ssh-ed25519 AAAA host\n").unwrap();
575 assert_eq!(key, "ssh-ed25519 AAAA host");
576 }
577
578 #[test]
579 fn normalize_key_rejects_empty_input() {
580 assert!(normalize_key("").is_err());
581 assert!(normalize_key(" \n\t ").is_err());
582 }
583
584 #[test]
585 fn truncate_chars_leaves_short_strings_alone() {
586 assert_eq!(truncate_chars("short", 40), "short");
587 assert_eq!(truncate_chars("1234567890", 10), "1234567890");
588 }
589
590 #[test]
591 fn truncate_chars_cuts_long_strings_with_ellipsis() {
592 assert_eq!(truncate_chars("abcdef", 3), "abc…");
593 }
594
595 #[test]
596 fn truncate_chars_counts_characters_not_bytes() {
597 assert_eq!(truncate_chars("ééééé", 3), "ééé…");
598 }
599
600 #[test]
601 fn ensure_braced_wraps_bare_uuids() {
602 assert_eq!(ensure_braced("abc-123"), "{abc-123}");
603 }
604
605 #[test]
606 fn ensure_braced_keeps_existing_braces() {
607 assert_eq!(ensure_braced("{abc-123}"), "{abc-123}");
608 }
609
610 #[test]
611 fn ensure_braced_trims_whitespace() {
612 assert_eq!(ensure_braced(" abc "), "{abc}");
613 assert_eq!(ensure_braced(" {abc} "), "{abc}");
614 }
615
616 #[test]
617 fn environment_type_arg_maps_to_api_names() {
618 assert_eq!(EnvironmentTypeArg::Test.api_name(), "Test");
619 assert_eq!(EnvironmentTypeArg::Staging.api_name(), "Staging");
620 assert_eq!(EnvironmentTypeArg::Production.api_name(), "Production");
621 }
622
623 fn deployment_with_state(state: Option<DeploymentState>) -> Deployment {
624 Deployment {
625 uuid: None,
626 state,
627 environment: None,
628 release: None,
629 }
630 }
631
632 #[test]
633 fn deployment_status_prefers_nested_status_name() {
634 let deployment = deployment_with_state(Some(DeploymentState {
635 name: Some("COMPLETED".into()),
636 status: Some(json!({ "name": "SUCCESSFUL" })),
637 }));
638 assert_eq!(deployment_status(&deployment), "SUCCESSFUL");
639 }
640
641 #[test]
642 fn deployment_status_falls_back_to_state_name() {
643 let deployment = deployment_with_state(Some(DeploymentState {
644 name: Some("IN_PROGRESS".into()),
645 status: None,
646 }));
647 assert_eq!(deployment_status(&deployment), "IN_PROGRESS");
648 }
649
650 #[test]
651 fn deployment_status_defaults_to_dash() {
652 assert_eq!(deployment_status(&deployment_with_state(None)), "-");
653 }
654
655 #[test]
656 fn environment_label_prefers_name_over_uuid() {
657 let environment = Environment {
658 uuid: Some("{u}".into()),
659 name: Some("Production".into()),
660 environment_type: None,
661 };
662 assert_eq!(environment_label(Some(&environment)), "Production");
663
664 let unnamed = Environment {
665 uuid: Some("{u}".into()),
666 name: None,
667 environment_type: None,
668 };
669 assert_eq!(environment_label(Some(&unnamed)), "{u}");
670
671 assert_eq!(environment_label(None), "-");
672 }
673
674 #[test]
675 fn release_summary_combines_name_and_short_hash() {
676 let release = json!({
677 "name": "v1.2.3",
678 "commit": { "hash": "0123456789abcdef0123" }
679 });
680 assert_eq!(release_summary(&release).unwrap(), "v1.2.3 (0123456789ab)");
681 }
682
683 #[test]
684 fn release_summary_handles_partial_data() {
685 assert_eq!(release_summary(&json!({ "name": "v1" })).unwrap(), "v1");
686 assert_eq!(
687 release_summary(&json!({ "commit": { "hash": "abc123" } })).unwrap(),
688 "abc123"
689 );
690 assert!(release_summary(&json!({})).is_none());
691 }
692}