amalgam 0.6.4

Type-safe configuration generator for Nickel from various schema sources
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use std::fs;
use std::path::PathBuf;
use tracing::info;

use amalgam_codegen::{go::GoCodegen, nickel::NickelCodegen, Codegen};
use amalgam_parser::{
    crd::{CRDParser, CRD},
    openapi::OpenAPIParser,
    Parser as SchemaParser,
};

mod manifest;
mod validate;
mod vendor;

#[derive(Parser)]
#[command(name = "amalgam")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(about = "Generate type-safe Nickel configurations from any schema source", long_about = None)]
struct Cli {
    /// Enable verbose output
    #[arg(short, long)]
    verbose: bool,

    /// Enable debug output
    #[arg(short, long)]
    debug: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Import types from various sources
    Import {
        #[command(subcommand)]
        source: ImportSource,
    },

    /// Generate code from IR
    Generate {
        /// Input IR file (JSON format)
        #[arg(short, long)]
        input: PathBuf,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Target language
        #[arg(short, long, default_value = "nickel")]
        target: String,
    },

    /// Convert from one format to another
    Convert {
        /// Input file path
        #[arg(short, long)]
        input: PathBuf,

        /// Input format (crd, openapi, go)
        #[arg(short = 'f', long)]
        from: String,

        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Output format (nickel, go, ir)
        #[arg(short, long)]
        to: String,
    },

    /// Vendor package management
    Vendor {
        #[command(subcommand)]
        command: vendor::VendorCommand,
    },

    /// Validate a Nickel package
    Validate {
        /// Path to the Nickel package or file to validate
        #[arg(short, long)]
        path: PathBuf,

        /// Package path prefix for dependency resolution (e.g., examples/pkgs)
        #[arg(long)]
        package_path: Option<PathBuf>,

        /// Enable verbose output
        #[arg(short, long)]
        verbose: bool,
    },

    /// Generate packages from a manifest file
    GenerateFromManifest {
        /// Path to the manifest file (TOML format)
        #[arg(short, long, default_value = ".amalgam-manifest.toml")]
        manifest: PathBuf,

        /// Only generate specific packages (by name)
        #[arg(short, long)]
        packages: Vec<String>,

        /// Dry run - show what would be generated without doing it
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum ImportSource {
    /// Import from Kubernetes CRD
    Crd {
        /// CRD file path (YAML or JSON)
        #[arg(short, long)]
        file: PathBuf,

        /// Output file path
        #[arg(short, long)]
        output: Option<PathBuf>,

        /// Generate as submittable package (with package imports)
        #[arg(long)]
        package_mode: bool,
    },

    /// Import CRDs from URL (GitHub repo, directory, or direct file)
    Url {
        /// URL to fetch CRDs from
        #[arg(short, long)]
        url: String,

        /// Output directory for package
        #[arg(short, long)]
        output: PathBuf,

        /// Package name (defaults to last part of URL)
        #[arg(short, long)]
        package: Option<String>,

        /// Generate Nickel package manifest (experimental)
        #[arg(long)]
        nickel_package: bool,
    },

    /// Import from OpenAPI specification
    OpenApi {
        /// OpenAPI spec file path (YAML or JSON)
        #[arg(short, long)]
        file: PathBuf,

        /// Output file path
        #[arg(short, long)]
        output: Option<PathBuf>,
    },

    /// Import core Kubernetes types from upstream OpenAPI
    K8sCore {
        /// Kubernetes version (e.g., "v1.31.0", "master")
        #[arg(short, long, default_value = "v1.33.4")]
        version: String,

        /// Output directory for generated types
        #[arg(short, long, default_value = "k8s_io")]
        output: PathBuf,

        /// Specific types to import (if empty, imports common types)
        #[arg(short, long)]
        types: Vec<String>,

        /// Generate Nickel package manifest (experimental)
        #[arg(long)]
        nickel_package: bool,
    },

    /// Import from Kubernetes cluster (not implemented)
    K8s {
        /// Kubernetes context to use
        #[arg(short, long)]
        context: Option<String>,

        /// CRD group to import
        #[arg(short, long)]
        group: Option<String>,

        /// Output directory
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialize tracing
    let level = if cli.debug {
        tracing::Level::TRACE
    } else if cli.verbose {
        tracing::Level::DEBUG
    } else {
        tracing::Level::INFO
    };

    tracing_subscriber::fmt()
        .with_max_level(level)
        .with_target(cli.debug) // Show target module in debug mode
        .init();

    match cli.command {
        Some(Commands::Import { source }) => handle_import(source).await,
        Some(Commands::Generate {
            input,
            output,
            target,
        }) => handle_generate(input, output, &target),
        Some(Commands::Convert {
            input,
            from,
            output,
            to,
        }) => handle_convert(input, &from, output, &to),
        Some(Commands::Vendor { command }) => {
            let project_root = std::env::current_dir()?;
            let manager = vendor::VendorManager::new(project_root);
            manager.execute(command).await
        }
        Some(Commands::Validate {
            path,
            package_path,
            verbose: _,
        }) => validate::run_validation_with_package_path(&path, package_path.as_deref()),
        Some(Commands::GenerateFromManifest {
            manifest,
            packages,
            dry_run,
        }) => handle_manifest_generation(manifest, packages, dry_run).await,
        None => {
            // No command provided, show help
            use clap::CommandFactory;
            Cli::command().print_help()?;
            Ok(())
        }
    }
}

async fn handle_import(source: ImportSource) -> Result<()> {
    match source {
        ImportSource::Url {
            url,
            output,
            package,
            nickel_package,
        } => {
            info!("Fetching CRDs from URL: {}", url);

            // Determine package name
            let package_name = package.unwrap_or_else(|| {
                url.split('/')
                    .next_back()
                    .unwrap_or("generated")
                    .trim_end_matches(".yaml")
                    .trim_end_matches(".yml")
                    .to_string()
            });

            // Fetch CRDs
            let fetcher = amalgam_parser::fetch::CRDFetcher::new()?;
            let crds = fetcher.fetch_from_url(&url).await?;
            fetcher.finish(); // Clear progress bars when done

            info!("Found {} CRDs", crds.len());

            // Generate package structure
            let mut generator = amalgam_parser::package::PackageGenerator::new(
                package_name.clone(),
                output.clone(),
            );
            generator.add_crds(crds);

            let package_structure = generator.generate_package()?;

            // Create output directory structure
            fs::create_dir_all(&output)?;

            // Write main module file
            let main_module = package_structure.generate_main_module();
            fs::write(output.join("mod.ncl"), main_module)?;

            // Create group/version/kind structure
            for group in package_structure.groups() {
                let group_dir = output.join(&group);
                fs::create_dir_all(&group_dir)?;

                // Write group module
                if let Some(group_mod) = package_structure.generate_group_module(&group) {
                    fs::write(group_dir.join("mod.ncl"), group_mod)?;
                }

                // Create version directories
                for version in package_structure.versions(&group) {
                    let version_dir = group_dir.join(&version);
                    fs::create_dir_all(&version_dir)?;

                    // Write version module
                    if let Some(version_mod) =
                        package_structure.generate_version_module(&group, &version)
                    {
                        fs::write(version_dir.join("mod.ncl"), version_mod)?;
                    }

                    // Write individual kind files
                    for kind in package_structure.kinds(&group, &version) {
                        if let Some(kind_content) =
                            package_structure.generate_kind_file(&group, &version, &kind)
                        {
                            fs::write(version_dir.join(format!("{}.ncl", kind)), kind_content)?;
                        }
                    }
                }
            }

            // Generate Nickel package manifest if requested
            if nickel_package {
                info!("Generating Nickel package manifest (experimental)");
                let manifest = package_structure.generate_nickel_manifest(None);
                fs::write(output.join("Nickel-pkg.ncl"), manifest)?;
                info!("✓ Generated Nickel-pkg.ncl");
            }

            info!("Generated package '{}' in {:?}", package_name, output);
            info!("Package structure:");
            for group in package_structure.groups() {
                info!("  {}/", group);
                for version in package_structure.versions(&group) {
                    let kinds = package_structure.kinds(&group, &version);
                    info!("    {}/: {} types", version, kinds.len());
                }
            }
            if nickel_package {
                info!("  Nickel-pkg.ncl (package manifest)");
            }

            Ok(())
        }

        ImportSource::Crd {
            file,
            output,
            package_mode,
        } => {
            info!("Importing CRD from {:?}", file);

            let content = fs::read_to_string(&file)
                .with_context(|| format!("Failed to read CRD file: {:?}", file))?;

            let crd: CRD = if file.extension().is_some_and(|ext| ext == "json") {
                serde_json::from_str(&content)?
            } else {
                serde_yaml::from_str(&content)?
            };

            let parser = CRDParser::new();
            let mut ir = parser.parse(crd.clone())?;

            // Add imports for any k8s type references
            use amalgam_core::ir::Import;
            use amalgam_parser::imports::ImportResolver;

            // Analyze the IR for external references and add imports
            for module in &mut ir.modules {
                let mut import_resolver = ImportResolver::new();

                // Analyze all types in the module
                for type_def in &module.types {
                    import_resolver.analyze_type(&type_def.ty);
                }

                // Generate imports based on detected references
                for type_ref in import_resolver.references() {
                    // Get group and version from the CRD
                    let group = &crd.spec.group;
                    let version = crd
                        .spec
                        .versions
                        .first()
                        .map(|v| v.name.as_str())
                        .unwrap_or("v1");

                    // Convert TypeReference to Import
                    let import_path = type_ref.import_path(group, version);
                    let alias = Some(type_ref.module_alias());

                    tracing::debug!(
                        "Adding import for {:?} -> path: {}, alias: {:?}",
                        type_ref,
                        import_path,
                        alias
                    );

                    module.imports.push(Import {
                        path: import_path,
                        alias,
                        items: vec![], // Empty items means import the whole module
                    });
                }

                tracing::debug!(
                    "Module {} has {} imports",
                    module.name,
                    module.imports.len()
                );
            }

            // Generate Nickel code with package mode support
            let mut codegen = if package_mode {
                use amalgam_codegen::package_mode::PackageMode;
                use std::path::PathBuf;

                // Look for manifest in current directory first, then fallback locations
                let manifest_path = if PathBuf::from(".amalgam-manifest.toml").exists() {
                    PathBuf::from(".amalgam-manifest.toml")
                } else if PathBuf::from("amalgam-manifest.toml").exists() {
                    PathBuf::from("amalgam-manifest.toml")
                } else {
                    PathBuf::from("does-not-exist")
                };

                let manifest = if manifest_path.exists() {
                    Some(&manifest_path)
                } else {
                    None
                };

                // Create analyzer-based package mode
                let mut package_mode = PackageMode::new_with_analyzer(manifest);

                // Analyze the IR to detect dependencies automatically
                // Extract the package name from the CRD group
                let package_name = crd.spec.group.split('.').next().unwrap_or("unknown");
                let mut all_types: Vec<amalgam_core::types::Type> = Vec::new();
                for module in &ir.modules {
                    for type_def in &module.types {
                        all_types.push(type_def.ty.clone());
                    }
                }
                package_mode.analyze_and_update_dependencies(&all_types, package_name);

                NickelCodegen::new().with_package_mode(package_mode)
            } else {
                NickelCodegen::new()
            };
            let code = codegen.generate(&ir)?;

            if let Some(output_path) = output {
                fs::write(&output_path, code)
                    .with_context(|| format!("Failed to write output: {:?}", output_path))?;
                info!("Generated Nickel code written to {:?}", output_path);
            } else {
                println!("{}", code);
            }

            Ok(())
        }

        ImportSource::OpenApi { file, output } => {
            info!("Importing OpenAPI spec from {:?}", file);

            let content = fs::read_to_string(&file)
                .with_context(|| format!("Failed to read OpenAPI file: {:?}", file))?;

            let spec: openapiv3::OpenAPI = if file.extension().is_some_and(|ext| ext == "json") {
                serde_json::from_str(&content)?
            } else {
                serde_yaml::from_str(&content)?
            };

            let parser = OpenAPIParser::new();
            let mut ir = parser.parse(spec)?;

            // Add imports for any k8s type references
            use amalgam_core::ir::Import;
            use amalgam_parser::imports::ImportResolver;

            // Analyze the IR for external references and add imports
            for module in &mut ir.modules {
                let mut import_resolver = ImportResolver::new();

                // Analyze all types in the module
                for type_def in &module.types {
                    import_resolver.analyze_type(&type_def.ty);
                }

                // Generate imports based on detected references
                for type_ref in import_resolver.references() {
                    // For OpenAPI, use a default group/version or extract from the spec
                    let group = "api"; // Default group for OpenAPI specs
                    let version = "v1"; // Default version

                    // Convert TypeReference to Import
                    let import_path = type_ref.import_path(group, version);
                    let alias = Some(type_ref.module_alias());

                    tracing::debug!(
                        "Adding import for {:?} -> path: {}, alias: {:?}",
                        type_ref,
                        import_path,
                        alias
                    );

                    module.imports.push(Import {
                        path: import_path,
                        alias,
                        items: vec![], // Empty items means import the whole module
                    });
                }

                tracing::debug!(
                    "Module {} has {} imports",
                    module.name,
                    module.imports.len()
                );
            }

            // Generate Nickel code by default
            let mut codegen = NickelCodegen::new();
            let code = codegen.generate(&ir)?;

            if let Some(output_path) = output {
                fs::write(&output_path, code)
                    .with_context(|| format!("Failed to write output: {:?}", output_path))?;
                info!("Generated Nickel code written to {:?}", output_path);
            } else {
                println!("{}", code);
            }

            Ok(())
        }

        ImportSource::K8sCore {
            version,
            output,
            types: _,
            nickel_package,
        } => {
            handle_k8s_core_import(&version, &output, nickel_package).await?;
            Ok(())
        }

        ImportSource::K8s { .. } => {
            anyhow::bail!("Kubernetes import not yet implemented. Build with --features kubernetes to enable.")
        }
    }
}

// Moved to lib.rs to avoid duplication
use amalgam::handle_k8s_core_import;

async fn handle_manifest_generation(
    manifest_path: PathBuf,
    packages: Vec<String>,
    dry_run: bool,
) -> Result<()> {
    use crate::manifest::Manifest;

    info!("Loading manifest from {:?}", manifest_path);
    let mut manifest = Manifest::from_file(&manifest_path)?;

    // Filter packages if specific ones were requested
    if !packages.is_empty() {
        manifest.packages.retain(|p| packages.contains(&p.name));
        if manifest.packages.is_empty() {
            anyhow::bail!("No matching packages found for: {:?}", packages);
        }
    }

    if dry_run {
        info!("Dry run mode - showing what would be generated:");
        for package in &manifest.packages {
            if package.enabled {
                info!("  - {} -> {}", package.name, package.output);
            }
        }
        return Ok(());
    }

    // Generate all packages
    let report = manifest.generate_all().await?;
    report.print_summary();

    if !report.failed.is_empty() {
        anyhow::bail!("Some packages failed to generate");
    }

    Ok(())
}

fn handle_generate(input: PathBuf, output: PathBuf, target: &str) -> Result<()> {
    info!("Generating {} code from {:?}", target, input);

    let ir_content = fs::read_to_string(&input)
        .with_context(|| format!("Failed to read IR file: {:?}", input))?;

    let ir: amalgam_core::IR =
        serde_json::from_str(&ir_content).with_context(|| "Failed to parse IR JSON")?;

    let code = match target {
        "nickel" => {
            let mut codegen = NickelCodegen::new();
            codegen.generate(&ir)?
        }
        "go" => {
            let mut codegen = GoCodegen::new();
            codegen.generate(&ir)?
        }
        _ => {
            anyhow::bail!("Unsupported target language: {}", target);
        }
    };

    fs::write(&output, code).with_context(|| format!("Failed to write output: {:?}", output))?;

    info!("Generated code written to {:?}", output);
    Ok(())
}

fn handle_convert(input: PathBuf, from: &str, output: PathBuf, to: &str) -> Result<()> {
    info!("Converting from {} to {}", from, to);

    let content = fs::read_to_string(&input)
        .with_context(|| format!("Failed to read input file: {:?}", input))?;

    // Parse input to IR
    let ir = match from {
        "crd" => {
            let crd: CRD = if input.extension().is_some_and(|ext| ext == "json") {
                serde_json::from_str(&content)?
            } else {
                serde_yaml::from_str(&content)?
            };
            CRDParser::new().parse(crd)?
        }
        "openapi" => {
            let spec: openapiv3::OpenAPI = if input.extension().is_some_and(|ext| ext == "json") {
                serde_json::from_str(&content)?
            } else {
                serde_yaml::from_str(&content)?
            };
            OpenAPIParser::new().parse(spec)?
        }
        _ => {
            anyhow::bail!("Unsupported input format: {}", from);
        }
    };

    // Generate output
    let output_content = match to {
        "nickel" => {
            let mut codegen = NickelCodegen::new();
            codegen.generate(&ir)?
        }
        "go" => {
            let mut codegen = GoCodegen::new();
            codegen.generate(&ir)?
        }
        "ir" => serde_json::to_string_pretty(&ir)?,
        _ => {
            anyhow::bail!("Unsupported output format: {}", to);
        }
    };

    fs::write(&output, output_content)
        .with_context(|| format!("Failed to write output: {:?}", output))?;

    info!("Conversion complete. Output written to {:?}", output);
    Ok(())
}