nyl 0.4.1

Kubernetes manifest generator with Helm integration
Documentation
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
use chrono::Utc;
use clap::Args;
use kube::api::DynamicObject;
use std::collections::HashMap;

use colored::Colorize;

use crate::{
    cli::{
        commands::render::{run_render_preflight, ClusterClientRequirement, RenderOptions, RenderPreflightOptions},
        namespace_resolution::{adjust_duplicate_keys_for_namespace_resolution, resolve_manifest_namespaces},
    },
    kubernetes::{
        ApplyOutcome, KubeClient, KubeRsClient, KubernetesReleaseStorage, ReleaseState, ReleaseStatus, ReleaseStorage,
        ResourceKey, ResourceOrdering,
    },
    NylError, Result,
};

/// Apply rendered manifests to the cluster
#[derive(Args, Debug)]
pub struct ApplyArgs {
    #[command(flatten)]
    pub common: RenderOptions,

    /// Release name (required if no NylRelease in file)
    #[arg(long)]
    pub name: Option<String>,

    /// Release namespace (required if no NylRelease in file)
    #[arg(long)]
    pub namespace: Option<String>,

    /// Kubernetes context to use
    #[arg(long)]
    pub context: Option<String>,

    /// Append to previous release instead of replacing it.
    /// Merges current resources with previous release (union, current wins on duplicates).
    /// Skips pruning to preserve resources from previous releases.
    #[arg(long)]
    pub append_release: bool,

    /// Apply resources without creating release revisions or pruning.
    #[arg(long, conflicts_with_all = ["append_release", "name", "namespace"])]
    pub no_release: bool,
}

#[allow(clippy::too_many_lines)]
pub async fn execute(args: ApplyArgs) -> Result<()> {
    let preflight = run_render_preflight(RenderPreflightOptions {
        common: &args.common,
        offline: false,
        kube_version: None,
        kube_api_versions: &[],
        context_override: args.context.as_deref(),
        cluster_client_requirement: ClusterClientRequirement::Required,
        resolve_namespaces: false,
        release_namespace_hint: None,
        adjust_duplicate_keys: false,
    })
    .await?;

    let mut desired_manifests = preflight.manifests;
    let nyl_release = preflight.nyl_release;
    let mut duplicates = preflight.duplicates;
    let kube_client = preflight
        .kube_client
        .ok_or_else(|| NylError::Config("Kubernetes client unavailable in online mode".to_string()))?;
    let client = preflight
        .raw_client
        .ok_or_else(|| NylError::Config("Raw Kubernetes client unavailable in online mode".to_string()))?;

    if desired_manifests.is_empty() {
        tracing::info!("No manifests to apply");
        return Ok(());
    }

    let release_namespace_hint = nyl_release
        .as_ref()
        .map(|release| release.metadata.namespace.as_str())
        .or(args.namespace.as_deref());

    // Resolve missing namespaces for namespaced resources.
    resolve_manifest_namespaces(&kube_client, &mut desired_manifests, release_namespace_hint).await?;
    duplicates =
        adjust_duplicate_keys_for_namespace_resolution(&kube_client, &duplicates, release_namespace_hint).await?;

    // Display duplicate resources warning if any
    if !duplicates.is_empty() {
        print_duplicate_warning(&duplicates);
    }

    // 3. Sort resources by priority (Namespace → CRD → RBAC → Config → Workload)
    let mut sorted_manifests = desired_manifests.clone();
    ResourceOrdering::sort_by_priority(&mut sorted_manifests)?;

    // 4. Apply manifests
    let apply_result = apply_sorted_manifests(&kube_client, &sorted_manifests).await?;

    if args.no_release {
        print_apply_summary(&apply_result.outcomes, None, &duplicates, apply_result.failed_count);
        if apply_result.failed_count > 0 {
            return Err(NylError::Other(format!(
                "Apply completed with {} error(s)",
                apply_result.failed_count
            )));
        }
        return Ok(());
    }

    // 5. Determine release name and namespace
    let (release_name, release_namespace) = if let Some(ref release) = nyl_release {
        (release.metadata.name.clone(), release.metadata.namespace.clone())
    } else {
        // Require CLI flags if no NylRelease
        let name = args.name.ok_or_else(|| {
            NylError::Config("No NylRelease resource found. Specify --name and --namespace".to_string())
        })?;
        let namespace = args.namespace.ok_or_else(|| {
            NylError::Config("No NylRelease resource found. Specify --name and --namespace".to_string())
        })?;
        (name, namespace)
    };

    // 6. Initialize release storage
    let storage = KubernetesReleaseStorage::new(client);

    // 7. Determine next revision number
    let revisions = storage.list_revisions(&release_name, &release_namespace).await?;
    let next_revision = revisions.iter().max().map_or(1, |r| r + 1);

    // 8. Create initial release state
    let mut release = ReleaseState {
        release_name: release_name.clone(),
        release_namespace: release_namespace.clone(),
        revision: next_revision,
        resource_keys: apply_result.resource_keys.clone(),
        manifest: manifests_to_yaml(&desired_manifests)?,
        status: ReleaseStatus::Rendered,
        rendered_at: Utc::now(),
        applied_at: None,
        error: None,
    };

    // 9. Append-release mode: merge with previous release
    if args.append_release && next_revision > 1 {
        // Fetch previous release
        if let Ok(Some(previous_release)) = storage
            .get_release(&release_name, &release_namespace, next_revision - 1)
            .await
        {
            // Validate that previous release was successfully deployed
            // Only Deployed releases have complete resource sets safe to merge from
            if previous_release.status != ReleaseStatus::Deployed {
                return Err(NylError::Config(format!(
                    "Cannot use --append-release when previous release (revision {}) is in {:?} state. \
                     The previous release must be in Deployed state to safely merge resources.",
                    previous_release.revision, previous_release.status
                )));
            }

            // Use HashSet for deduplication
            let current_keys: std::collections::HashSet<_> = release.resource_keys.iter().cloned().collect();

            // Add previous resources not in current set
            let mut merged_keys = Vec::new();
            let mut added_from_previous = 0;
            for prev_key in &previous_release.resource_keys {
                if !current_keys.contains(prev_key) {
                    merged_keys.push(prev_key.clone());
                    added_from_previous += 1;
                }
            }

            // Add all current resources (current wins on duplicates)
            merged_keys.extend(release.resource_keys.clone());

            // Calculate overlap for better logging
            let overlap = previous_release.resource_keys.len() - added_from_previous;
            if overlap > 0 {
                tracing::info!(
                    "Append-release mode: merged {} from previous + {} current ({} overlap, {} total)",
                    added_from_previous,
                    release.resource_keys.len(),
                    overlap,
                    merged_keys.len()
                );
            } else {
                tracing::info!(
                    "Append-release mode: merged {} from previous + {} current ({} total)",
                    added_from_previous,
                    release.resource_keys.len(),
                    merged_keys.len()
                );
            }

            release.resource_keys = merged_keys;
        } else {
            tracing::warn!(
                "Append-release mode: no previous release found (revision {}), treating as initial apply",
                next_revision - 1
            );
        }
    }

    // 10. Update release status
    if apply_result.failed_count == 0 {
        release.status = ReleaseStatus::Deployed;
        release.applied_at = Some(Utc::now());
    } else {
        release.status = ReleaseStatus::Failed;
        release.error = Some(format!("{} resource(s) failed to apply", apply_result.failed_count));
    }

    // 11. Save release state
    // Ensure the release namespace exists before saving the release state
    ensure_namespace_exists(&kube_client, &release_namespace).await?;

    storage.save_release(&release).await?;

    // Mark previous revision as superseded (if successful)
    if release.status == ReleaseStatus::Deployed && next_revision > 1 {
        let prev_revision = next_revision - 1;
        storage
            .update_release_status(
                &release_name,
                &release_namespace,
                prev_revision,
                ReleaseStatus::Superseded,
                None,
            )
            .await
            .ok(); // Ignore errors if previous revision doesn't exist
    }

    // 12. Prune resources from previous release that are no longer desired
    if !args.append_release && release.status == ReleaseStatus::Deployed && next_revision > 1 {
        // Get previous release's resource keys
        if let Ok(Some(previous_release)) = storage
            .get_release(&release_name, &release_namespace, next_revision - 1)
            .await
        {
            // Find resources to prune (in previous but not in current)
            let current_keys: std::collections::HashSet<_> = release.resource_keys.iter().collect();
            let to_prune: Vec<_> = previous_release
                .resource_keys
                .iter()
                .filter(|k| !current_keys.contains(k))
                .collect();

            if !to_prune.is_empty() {
                println!("\nPruning {} resources...", to_prune.len());
                for key in to_prune {
                    match kube_client
                        .delete_resource(&key.gvk, key.namespace.as_deref(), &key.name)
                        .await
                    {
                        Ok(()) => {
                            println!("  ✓ Deleted {}", key);
                        }
                        Err(e) => {
                            println!("  ✗ Failed to delete {}: {}", key, e);
                        }
                    }
                }
                println!();
            }
        }
    }

    // 13. Print summary
    print_apply_summary(
        &apply_result.outcomes,
        Some(&release),
        &duplicates,
        apply_result.failed_count,
    );

    if apply_result.failed_count > 0 {
        return Err(NylError::Other(format!(
            "Apply completed with {} error(s)",
            apply_result.failed_count
        )));
    }

    Ok(())
}

struct ApplyExecutionResult {
    outcomes: Vec<ApplyOutcome>,
    failed_count: usize,
    resource_keys: Vec<ResourceKey>,
}

async fn apply_sorted_manifests(
    client: &KubeRsClient,
    manifests: &[serde_json::Value],
) -> Result<ApplyExecutionResult> {
    let mut outcomes = Vec::new();
    let mut failed_count = 0;
    let mut resource_keys = Vec::new();

    for manifest in manifests {
        let key = ResourceKey::from_json_value(manifest)?;
        match apply_manifest(client, manifest).await {
            Ok(outcome) => {
                outcomes.push(outcome);
                resource_keys.push(key);
            }
            Err(e) => {
                let error_msg = format!("(failed to apply resource: {})", e);
                println!("{} {} {}", "✗".red().bold(), key, error_msg.red());
                failed_count += 1;
            }
        }
    }

    Ok(ApplyExecutionResult {
        outcomes,
        failed_count,
        resource_keys,
    })
}

/// Convert manifests to YAML string
fn manifests_to_yaml(manifests: &[serde_json::Value]) -> Result<String> {
    let mut yaml_parts = Vec::new();

    for manifest in manifests {
        let yaml = crate::yaml::serialize_yaml_document(manifest).map_err(NylError::YamlEmit)?;
        yaml_parts.push(yaml);
    }

    Ok(yaml_parts.join("---\n"))
}

/// Apply a single manifest
async fn apply_manifest(client: &KubeRsClient, manifest: &serde_json::Value) -> Result<ApplyOutcome> {
    // Convert JSON to DynamicObject
    let resource: DynamicObject = serde_json::from_value(manifest.clone())?;

    // Apply using client
    client.apply_resource(&resource, "nyl", false).await
}

/// Print apply summary
#[allow(clippy::too_many_lines)]
fn print_apply_summary(
    outcomes: &[ApplyOutcome],
    release: Option<&ReleaseState>,
    duplicates: &HashMap<ResourceKey, usize>,
    failed_count: usize,
) {
    for outcome in outcomes {
        match outcome {
            ApplyOutcome::Created { resource_key } => {
                let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
                let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
                println!(
                    "{} {} {}{}",
                    "+".green().bold(),
                    outcome.kind(),
                    ns_name,
                    dup_annotation
                );
            }
            ApplyOutcome::Updated { resource_key } => {
                let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
                let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
                println!(
                    "{} {} {}{}",
                    "~".yellow().bold(),
                    outcome.kind(),
                    ns_name,
                    dup_annotation
                );
            }
            ApplyOutcome::Unchanged { resource_key } => {
                let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
                let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
                println!(
                    "{} {} {}{}",
                    "=".bright_black().bold(),
                    outcome.kind(),
                    ns_name,
                    dup_annotation
                );
            }
            ApplyOutcome::DryRun { would_be } => {
                // This shouldn't happen anymore since we removed --dry-run
                // But handle it anyway by unwrapping
                print_single_outcome(would_be, duplicates);
            }
        }
    }

    println!();

    // Print summary counts
    let mut created = 0;
    let mut updated = 0;
    let mut unchanged = 0;

    for outcome in outcomes {
        match outcome {
            ApplyOutcome::Created { .. } => created += 1,
            ApplyOutcome::Updated { .. } => updated += 1,
            ApplyOutcome::Unchanged { .. } => unchanged += 1,
            ApplyOutcome::DryRun { would_be } => match **would_be {
                ApplyOutcome::Created { .. } => created += 1,
                ApplyOutcome::Updated { .. } => updated += 1,
                ApplyOutcome::Unchanged { .. } => unchanged += 1,
                ApplyOutcome::DryRun { .. } => {} // shouldn't happen
            },
        }
    }

    let total_duplicates_ignored: usize = duplicates.values().map(|count| count - 1).sum();

    let mut parts = vec![
        format!("{} created", created.to_string().green()),
        format!("{} updated", updated.to_string().yellow()),
        format!("{} unchanged", unchanged),
    ];

    if total_duplicates_ignored > 0 {
        let plural = if total_duplicates_ignored == 1 {
            "duplicate"
        } else {
            "duplicates"
        };
        parts.push(format!(
            "{} {} ignored",
            total_duplicates_ignored.to_string().bright_black(),
            plural
        ));
    }

    if failed_count > 0 {
        parts.push(format!("{} failed", failed_count.to_string().red()));
    }

    println!("Summary: {}", parts.join(", "));

    if let Some(release) = release {
        println!();
        if release.status == ReleaseStatus::Deployed {
            println!(
                "Release: {} revision {} deployed successfully to namespace {}",
                release.release_name, release.revision, release.release_namespace
            );
        } else {
            println!("Release: {} revision {} failed", release.release_name, release.revision);
        }
    }
}

/// Print a single outcome
fn print_single_outcome(outcome: &ApplyOutcome, duplicates: &HashMap<ResourceKey, usize>) {
    match outcome {
        ApplyOutcome::Created { resource_key } => {
            let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
            let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
            println!(
                "{} {} {}{}",
                "+".green().bold(),
                outcome.kind(),
                ns_name,
                dup_annotation
            );
        }
        ApplyOutcome::Updated { resource_key } => {
            let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
            let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
            println!(
                "{} {} {}{}",
                "~".yellow().bold(),
                outcome.kind(),
                ns_name,
                dup_annotation
            );
        }
        ApplyOutcome::Unchanged { resource_key } => {
            let ns_name = format_namespace_name(outcome.namespace(), outcome.name());
            let dup_annotation = get_duplicate_annotation(resource_key, duplicates);
            println!(
                "{} {} {}{}",
                "=".bright_black().bold(),
                outcome.kind(),
                ns_name,
                dup_annotation
            );
        }
        ApplyOutcome::DryRun { would_be } => {
            print_single_outcome(would_be, duplicates);
        }
    }
}

/// Format namespace and name for display
fn format_namespace_name(namespace: Option<&str>, name: &str) -> String {
    if let Some(ns) = namespace {
        format!("{}/{}", ns, name)
    } else {
        name.to_string()
    }
}

/// Print a warning trace about duplicate resources
fn print_duplicate_warning(duplicates: &HashMap<ResourceKey, usize>) {
    if duplicates.is_empty() {
        return;
    }

    let total_unique = duplicates.len();
    let total_ignored: usize = duplicates.values().map(|count| count - 1).sum();

    tracing::warn!(
        "Found {} unique resources with duplicates ({} total duplicates ignored, keeping last occurrence)",
        total_unique,
        total_ignored
    );
}

/// Get duplicate annotation for a resource if it's a duplicate
fn get_duplicate_annotation(resource_key: &ResourceKey, duplicates: &HashMap<ResourceKey, usize>) -> String {
    // Use direct HashMap lookup with the full ResourceKey (including apiVersion/kind)
    // to avoid incorrectly matching resources with the same kind from different API versions
    if let Some(count) = duplicates.get(resource_key) {
        let ignored_count = count - 1;
        let plural = if ignored_count == 1 { "duplicate" } else { "duplicates" };
        return format!(" {}", format!("({} {} ignored)", ignored_count, plural).yellow());
    }
    String::new()
}

/// Ensure a namespace exists, creating it if necessary
async fn ensure_namespace_exists(client: &KubeRsClient, namespace: &str) -> Result<()> {
    use crate::kubernetes::GroupVersionKind;
    use kube::api::DynamicObject;
    use serde_json::json;

    // Build namespace GVK
    let ns_gvk = GroupVersionKind::from_api_version_kind("v1", "Namespace")?;

    // Check if namespace exists
    if let Some(_ns) = client.get_resource(&ns_gvk, None, namespace).await? {
        // Namespace exists, nothing to do
        Ok(())
    } else {
        // Namespace doesn't exist, create it
        tracing::warn!(
            "Namespace '{}' does not exist. Creating it to store release state.",
            namespace
        );

        // Create bare namespace resource
        let ns_resource: DynamicObject = serde_json::from_value(json!({
            "apiVersion": "v1",
            "kind": "Namespace",
            "metadata": {
                "name": namespace
            }
        }))?;

        // Apply the namespace
        client.apply_resource(&ns_resource, "nyl", false).await?;

        tracing::info!("Created namespace '{}'", namespace);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_manifests_to_yaml() {
        let manifests = vec![
            json!({
                "apiVersion": "v1",
                "kind": "ConfigMap",
                "metadata": {"name": "test1"}
            }),
            json!({
                "apiVersion": "v1",
                "kind": "ConfigMap",
                "metadata": {"name": "test2"}
            }),
        ];

        let yaml = manifests_to_yaml(&manifests).unwrap();
        assert!(yaml.contains("test1"));
        assert!(yaml.contains("test2"));
        assert!(yaml.contains("---"));
    }

    #[test]
    fn test_format_namespace_name_with_namespace() {
        assert_eq!(format_namespace_name(Some("default"), "myapp"), "default/myapp");
    }

    #[test]
    fn test_format_namespace_name_without_namespace() {
        assert_eq!(format_namespace_name(None, "mynamespace"), "mynamespace");
    }
}