davit 0.1.3

Kubernetes management utilities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
mod blueprint;
mod config;
mod dashboard;
mod git;
mod info;
mod registry;

use anyhow::{Context, Result};
use blueprint::Blueprint;
use chrono::Utc;
use clap::{Parser, Subcommand};
use config::{Config, Environment, ServiceSource};
use dashboard::Dashboard;
use git::Git;
use inquire::{Confirm, Select, Text};
use registry::{ImageMetadata, Registry};
use std::fs;
use std::process::Command;

#[derive(Parser)]
#[command(name = "davit")]
#[command(about = "A safe Kubernetes deployment wrapper & TUI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Deploy a service to an environment
    Deploy {
        /// Target environment (e.g., staging, production)
        #[arg(short, long)]
        env: Option<String>,

        /// Service name to deploy
        #[arg(short, long)]
        service: Option<String>,

        /// Image tag to deploy
        #[arg(short, long)]
        tag: Option<String>,

        /// Dry run: show commands without executing them
        #[arg(long)]
        dry_run: bool,
    },
    /// Show deployment information for a service
    Info {
        /// Target environment (e.g., staging, production)
        #[arg(short, long)]
        env: Option<String>,

        /// Kubernetes namespace filter
        #[arg(short, long)]
        namespace: Option<String>,

        /// Service name to inspect
        #[arg(short, long)]
        service: Option<String>,
    },
    /// Configuration management
    Config {
        #[command(subcommand)]
        command: ConfigCommands,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Show current configuration
    Show,
    /// Get path to configuration file
    Path,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();
    let config = Config::load().context("Failed to load configuration")?;

    match cli.command {
        Commands::Deploy {
            env,
            service,
            tag,
            dry_run,
        } => {
            let selected_env = resolve_environment(&config, env)?;

            // Phase 6.2 - Git Pull before deployment
            println!(
                "🔄 Checking for updates in {}...",
                selected_env.env_yaml_dir.display()
            );
            if let Err(e) = Git::pull(&selected_env.env_yaml_dir, dry_run) {
                println!("⚠️  Git pull failed: {}", e);
                if !Confirm::new("Do you want to continue with the deployment anyway?")
                    .with_default(false)
                    .prompt()?
                {
                    return Err(anyhow::anyhow!(
                        "Deployment aborted by user after git pull failure."
                    ));
                }
            }

            let selected_service = resolve_service(&selected_env, service)?;

            let selected_tag = if let Some(t) = tag {
                t
            } else {
                resolve_tag(&selected_env, &selected_service)?
            };

            // 6.3 Production Protection
            if selected_env.protected.unwrap_or(false) {
                println!(
                    "⚠️  WARNING: Deployment to {} is PROTECTED!",
                    selected_env.name
                );
                let confirmation = Text::new(&format!(
                    "Type the environment name '{}' to confirm:",
                    selected_env.name
                ))
                .prompt()
                .context("Production confirmation was cancelled")?;

                if confirmation != selected_env.name {
                    return Err(anyhow::anyhow!("Confirmation failed. Deployment aborted."));
                }
            }

            // Phase 4 - YAML modification & Visual Diff
            let yaml_path = selected_service.yaml_path.clone();

            let original_content = fs::read_to_string(&yaml_path)
                .with_context(|| format!("Failed to read YAML file at {}", yaml_path.display()))?;

            let base_image = selected_service
                .image_path
                .split([':', '@'])
                .next()
                .unwrap_or(&selected_service.image_path);

            let updated_content =
                Blueprint::update_image_tag(&original_content, base_image, &selected_tag)
                    .context("Failed to update image tag in YAML")?;

            let mut show_unified = true;
            let filename = yaml_path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("deployment.yaml");

            loop {
                Blueprint::show_diff(&original_content, &updated_content, filename, show_unified);

                let choices = if show_unified {
                    vec!["Apply", "Show full diff", "Dismiss"]
                } else {
                    vec!["Apply", "Show unified diff", "Dismiss"]
                };

                let selection = Select::new("Action:", choices).prompt()?;

                match selection {
                    "Apply" => {
                        if dry_run {
                            println!(
                                "Dry-run: would write updated YAML to {}",
                                yaml_path.display()
                            );
                        } else {
                            fs::write(&yaml_path, &updated_content).with_context(|| {
                                format!("Failed to write updated YAML to {}", yaml_path.display())
                            })?;
                        }
                        println!("Local YAML updated. Executing kubectl apply...");
                        break;
                    }
                    "Show full diff" => show_unified = false,
                    "Show unified diff" => show_unified = true,
                    _ => {
                        println!("Deployment cancelled. No changes made.");
                        return Ok(());
                    }
                }
            }

            if dry_run {
                println!(
                    "Dry-run: kubectl --context {} apply -f {}",
                    selected_env.kubectl_context,
                    yaml_path.display()
                );
            } else {
                let output = Command::new("kubectl")
                    .args([
                        "--context",
                        &selected_env.kubectl_context,
                        "apply",
                        "-f",
                        yaml_path.to_str().unwrap(),
                    ])
                    .output()
                    .context("Failed to execute kubectl apply")?;

                if !output.status.success() {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    println!("❌ kubectl apply failed: {}", stderr);
                    if Confirm::new("Revert local YAML changes?")
                        .with_default(true)
                        .prompt()?
                    {
                        fs::write(&yaml_path, &original_content)?;
                        println!("YAML reverted.");
                    }
                    return Err(anyhow::anyhow!("kubectl apply failed"));
                }
            }

            println!("Deployment applied. Starting dashboard...");

            let mut dashboard = Dashboard::new(
                selected_service.name.clone(),
                selected_env.name.clone(),
                selected_tag.clone(),
                selected_env.kubectl_context.clone(),
                selected_service.namespace.clone(),
                selected_service.selector.clone(),
                selected_service.container_name.clone(),
            );
            let res = dashboard.run().await;

            if let Err(e) = res {
                println!("❌ Dashboard error or aborted: {}", e);
                if Confirm::new("Revert local YAML changes?")
                    .with_default(true)
                    .prompt()?
                {
                    fs::write(&yaml_path, &original_content)?;
                    println!("YAML reverted.");
                }
                return Err(e);
            }

            // 6.1 Git Automation
            println!("\n🚀 Deployment successful. Preparing to commit changes...");
            let commit_msg = format!(
                "deploy({}): update {} to {}",
                selected_env.name, selected_service.name, selected_tag
            );

            println!("\n--- Commit Recap ---");
            println!("File to commit:   {}", yaml_path.display());
            println!("Commit message:   {}", commit_msg);
            Blueprint::show_diff(&original_content, &updated_content, filename, true);
            println!("--------------------\n");

            if Confirm::new("Do you want to commit and push these changes?")
                .with_default(true)
                .prompt()?
            {
                if let Err(e) = Git::commit_and_push(
                    &selected_env.env_yaml_dir,
                    &commit_msg,
                    &yaml_path,
                    dry_run,
                ) {
                    println!("⚠️  Failed to commit/push changes: {}", e);
                } else {
                    if !dry_run {
                        println!("✅ Changes committed and pushed to Git.");
                    }
                }
            } else {
                println!("Committing skipped by user.");
            }
        }
        Commands::Info {
            env,
            namespace,
            service,
        } => {
            let selected_env = resolve_environment(&config, env)?;
            let selected_service =
                resolve_service_with_ns_filter(&selected_env, service, namespace)?;
            info::show_info(&selected_env, &selected_service).await?;
        }
        Commands::Config { command } => match command {
            ConfigCommands::Show => {
                println!("{:#?}", config);
            }
            ConfigCommands::Path => {
                let path = Config::get_config_path()?;
                println!("{}", path.display());
            }
        },
    }

    Ok(())
}

fn resolve_environment(config: &Config, input: Option<String>) -> Result<Environment> {
    let env_names: Vec<String> = config.environments.iter().map(|e| e.name.clone()).collect();

    let name = match input {
        Some(val) => resolve_from_list("Environment", &env_names, val)?,
        None => Select::new("Select Environment:", env_names.clone())
            .prompt()
            .context("Environment selection was cancelled")?,
    };

    config
        .environments
        .iter()
        .find(|e| e.name == name)
        .cloned()
        .context("Environment not found in config")
}

fn get_service_display_name(
    s: &ServiceSource,
    all_services: &[ServiceSource],
    env_yaml_dir: &std::path::Path,
) -> String {
    let duplicates: Vec<&ServiceSource> = all_services
        .iter()
        .filter(|&other| other.name == s.name)
        .collect();

    if duplicates.len() <= 1 {
        return s.name.clone();
    }

    // Multiple services with same name, check namespace
    let same_namespace: Vec<&&ServiceSource> = duplicates
        .iter()
        .filter(|&other| other.namespace == s.namespace)
        .collect();

    if same_namespace.len() <= 1 {
        return format!(
            "{} ({})",
            s.name,
            s.namespace.as_deref().unwrap_or("no-namespace")
        );
    }

    // Multiple services with same name and same namespace, use relative path
    let relative_path =
        pathdiff::diff_paths(&s.yaml_path, env_yaml_dir).unwrap_or_else(|| s.yaml_path.clone());

    format!(
        "{} ({}) [{}]",
        s.name,
        s.namespace.as_deref().unwrap_or("no-namespace"),
        relative_path.display()
    )
}

fn resolve_service(env: &Environment, input: Option<String>) -> Result<ServiceSource> {
    let services = env
        .list_services()
        .context("Failed to list services in repo_root")?;
    resolve_service_from_list(services, env, input)
}

fn resolve_service_with_ns_filter(
    env: &Environment,
    input: Option<String>,
    namespace: Option<String>,
) -> Result<ServiceSource> {
    let all_services = env.list_services().context("Failed to list services")?;

    let services = match namespace {
        Some(ref ns) => {
            let filtered: Vec<ServiceSource> = all_services
                .into_iter()
                .filter(|s| s.namespace.as_deref() == Some(ns.as_str()))
                .collect();
            if filtered.is_empty() {
                return Err(anyhow::anyhow!("No services found in namespace '{}'", ns));
            }
            filtered
        }
        None => all_services,
    };

    resolve_service_from_list(services, env, input)
}

fn resolve_service_from_list(
    services: Vec<ServiceSource>,
    env: &Environment,
    input: Option<String>,
) -> Result<ServiceSource> {
    if services.is_empty() {
        return Err(anyhow::anyhow!(
            "No services found in {}",
            env.env_yaml_dir.display()
        ));
    }

    let service_map: Vec<(String, ServiceSource)> = services
        .iter()
        .cloned()
        .map(|s| {
            (
                get_service_display_name(&s, &services, &env.env_yaml_dir),
                s,
            )
        })
        .collect();

    let display_names: Vec<String> = service_map.iter().map(|(n, _)| n.clone()).collect();

    let selected_name = match input {
        Some(val) => resolve_from_list("Service", &display_names, val)?,
        None => Select::new("Select Service:", display_names.clone())
            .prompt()
            .context("Service selection was cancelled")?,
    };

    service_map
        .into_iter()
        .find(|(n, _)| n == &selected_name)
        .map(|(_, s)| s)
        .context("Resolved service not found in list")
}

fn resolve_tag(env: &Environment, service: &ServiceSource) -> Result<String> {
    let project = env.gcp_project.as_deref().unwrap_or("MOCK_PROJECT");

    println!(
        "Fetching images for {} using path {}...",
        service.name, service.image_path
    );

    let images = match Registry::fetch_images(&service.image_path) {
        Ok(imgs) => imgs,
        Err(e) => {
            if project == "MOCK_PROJECT" {
                mock_images()
            } else {
                return Err(e).context("Failed to fetch images from Artifact Registry");
            }
        }
    };

    if images.is_empty() {
        return Err(anyhow::anyhow!(
            "No images found for service {}",
            service.name
        ));
    }

    let options: Vec<String> = images
        .iter()
        .map(|img| {
            format!(
                "{:<15} ({}) [{}]",
                img.display_tag(),
                img.age_string(),
                img.short_hash()
            )
        })
        .collect();

    let selection = Select::new("Select Image Tag:", options)
        .prompt()
        .context("Image selection was cancelled")?;

    let tag = selection
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_end_matches(',')
        .to_string();
    Ok(tag)
}

fn mock_images() -> Vec<ImageMetadata> {
    use chrono::Duration;
    let now = Utc::now();
    vec![
        ImageMetadata {
            tags: vec!["v1.2.3".to_string(), "latest".to_string()],
            update_time: now - Duration::hours(2),
            name: "auth-service@sha256:abcdef123456789".to_string(),
        },
        ImageMetadata {
            tags: vec!["v1.2.2".to_string()],
            update_time: now - Duration::days(1),
            name: "auth-service@sha256:123456789abcdef".to_string(),
        },
        ImageMetadata {
            tags: vec!["v1.1.0".to_string()],
            update_time: now - Duration::days(5),
            name: "auth-service@sha256:987654321fedcba".to_string(),
        },
    ]
}

/// Generic disambiguation logic
fn resolve_from_list(label: &str, items: &[String], input: String) -> Result<String> {
    // 1. Exact match
    if items.contains(&input) {
        return Ok(input);
    }

    // 2. Partial matches
    let matches: Vec<&String> = items.iter().filter(|&i| i.contains(&input)).collect();

    match matches.len() {
        0 => {
            println!("No {} matches '{}'.", label.to_lowercase(), input);
            Select::new(&format!("Select {}:", label), items.to_vec())
                .prompt()
                .context(format!("{} selection was cancelled", label))
        }
        1 => {
            let suggest = matches[0];
            if Confirm::new(&format!("Did you mean '{}'?", suggest))
                .with_default(true)
                .prompt()?
            {
                Ok(suggest.clone())
            } else {
                Select::new(&format!("Select {}:", label), items.to_vec())
                    .prompt()
                    .context(format!("{} selection was cancelled", label))
            }
        }
        _ => Select::new(
            &format!(
                "Multiple matches for '{}'. Select {}:",
                input,
                label.to_lowercase()
            ),
            matches.into_iter().cloned().collect(),
        )
        .prompt()
        .context(format!("{} selection was cancelled", label)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_service_display_name_unique() {
        let s = ServiceSource {
            name: "service1".to_string(),
            kind: "Deployment".to_string(),
            image_path: "img1".to_string(),
            container_name: "c1".to_string(),
            yaml_path: PathBuf::from("/root/dir1/deploy.yaml"),
            namespace: Some("ns1".to_string()),
            selector: None,
        };
        let all = vec![s.clone()];
        let root = PathBuf::from("/root");
        assert_eq!(get_service_display_name(&s, &all, &root), "service1");
    }

    #[test]
    fn test_service_display_name_duplicate_name() {
        let s1 = ServiceSource {
            name: "service1".to_string(),
            kind: "Deployment".to_string(),
            image_path: "img1".to_string(),
            container_name: "c1".to_string(),
            yaml_path: PathBuf::from("/root/dir1/deploy.yaml"),
            namespace: Some("ns1".to_string()),
            selector: None,
        };
        let s2 = ServiceSource {
            name: "service1".to_string(),
            kind: "Deployment".to_string(),
            image_path: "img2".to_string(),
            container_name: "c2".to_string(),
            yaml_path: PathBuf::from("/root/dir2/deploy.yaml"),
            namespace: Some("ns2".to_string()),
            selector: None,
        };
        let all = vec![s1.clone(), s2.clone()];
        let root = PathBuf::from("/root");
        assert_eq!(get_service_display_name(&s1, &all, &root), "service1 (ns1)");
        assert_eq!(get_service_display_name(&s2, &all, &root), "service1 (ns2)");
    }

    #[test]
    fn test_service_display_name_duplicate_name_and_ns() {
        let s1 = ServiceSource {
            name: "service1".to_string(),
            kind: "Deployment".to_string(),
            image_path: "img1".to_string(),
            container_name: "c1".to_string(),
            yaml_path: PathBuf::from("/root/dir1/deploy.yaml"),
            namespace: Some("ns1".to_string()),
            selector: None,
        };
        let s2 = ServiceSource {
            name: "service1".to_string(),
            kind: "Deployment".to_string(),
            image_path: "img2".to_string(),
            container_name: "c2".to_string(),
            yaml_path: PathBuf::from("/root/dir2/deploy.yaml"),
            namespace: Some("ns1".to_string()),
            selector: None,
        };
        let all = vec![s1.clone(), s2.clone()];
        let root = PathBuf::from("/root");
        assert_eq!(
            get_service_display_name(&s1, &all, &root),
            "service1 (ns1) [dir1/deploy.yaml]"
        );
        assert_eq!(
            get_service_display_name(&s2, &all, &root),
            "service1 (ns1) [dir2/deploy.yaml]"
        );
    }
}