amalgam 0.4.1

Type-safe configuration generator for Nickel from various schema sources
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
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},
    k8s_types::K8sTypesFetcher,
    openapi::OpenAPIParser,
    Parser as SchemaParser,
};

mod vendor;

#[derive(Parser)]
#[command(name = "amalgam")]
#[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: 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,
    },
}

#[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>,
    },

    /// 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>,
    },

    /// 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.31.0")]
        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>,
    },

    /// 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 {
        Commands::Import { source } => handle_import(source).await,
        Commands::Generate {
            input,
            output,
            target,
        } => handle_generate(input, output, &target),
        Commands::Convert {
            input,
            from,
            output,
            to,
        } => handle_convert(input, &from, output, &to),
        Commands::Vendor { command } => {
            let project_root = std::env::current_dir()?;
            let manager = vendor::VendorManager::new(project_root);
            manager.execute(command).await
        }
    }
}

async fn handle_import(source: ImportSource) -> Result<()> {
    match source {
        ImportSource::Url {
            url,
            output,
            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)?;
                        }
                    }
                }
            }

            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());
                }
            }

            Ok(())
        }

        ImportSource::Crd { file, output } => {
            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 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::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: _ } => {
            handle_k8s_core_import(&version, &output).await?;
            Ok(())
        }

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

fn apply_type_replacements(ty: &mut amalgam_core::types::Type, replacements: &std::collections::HashMap<String, String>) {
    use amalgam_core::types::Type;
    
    match ty {
        Type::Reference(name) => {
            if let Some(replacement) = replacements.get(name) {
                *name = replacement.clone();
            }
        }
        Type::Array(inner) => apply_type_replacements(inner, replacements),
        Type::Optional(inner) => apply_type_replacements(inner, replacements),
        Type::Map { value, .. } => apply_type_replacements(value, replacements),
        Type::Record { fields, .. } => {
            for field in fields.values_mut() {
                apply_type_replacements(&mut field.ty, replacements);
            }
        }
        Type::Union(types) => {
            for t in types {
                apply_type_replacements(t, replacements);
            }
        }
        Type::TaggedUnion { variants, .. } => {
            for t in variants.values_mut() {
                apply_type_replacements(t, replacements);
            }
        }
        Type::Contract { base, .. } => apply_type_replacements(base, replacements),
        _ => {}
    }
}

fn collect_type_references(ty: &amalgam_core::types::Type, refs: &mut std::collections::HashSet<String>) {
    use amalgam_core::types::Type;
    
    match ty {
        Type::Reference(name) => {
            refs.insert(name.clone());
        }
        Type::Array(inner) => collect_type_references(inner, refs),
        Type::Optional(inner) => collect_type_references(inner, refs),
        Type::Map { value, .. } => collect_type_references(value, refs),
        Type::Record { fields, .. } => {
            for field in fields.values() {
                collect_type_references(&field.ty, refs);
            }
        }
        Type::Union(types) => {
            for t in types {
                collect_type_references(t, refs);
            }
        }
        Type::TaggedUnion { variants, .. } => {
            for t in variants.values() {
                collect_type_references(t, refs);
            }
        }
        Type::Contract { base, .. } => collect_type_references(base, refs),
        _ => {}
    }
}

async fn handle_k8s_core_import(version: &str, output_dir: &PathBuf) -> Result<()> {
    info!("Fetching Kubernetes {} core types...", version);
    
    // Create fetcher
    let fetcher = K8sTypesFetcher::new();
    
    // Fetch the OpenAPI schema
    let openapi = fetcher.fetch_k8s_openapi(version).await?;
    
    // Extract core types
    let types = fetcher.extract_core_types(&openapi)?;
    
    let total_types = types.len();
    info!("Extracted {} core types", total_types);
    
    // Group types by version
    let mut types_by_version: std::collections::HashMap<String, Vec<(amalgam_parser::imports::TypeReference, amalgam_core::ir::TypeDefinition)>> = std::collections::HashMap::new();
    
    for (type_ref, type_def) in types {
        types_by_version
            .entry(type_ref.version.clone())
            .or_default()
            .push((type_ref, type_def));
    }
    
    // Generate files for each version
    for (version, version_types) in &types_by_version {
        let version_dir = output_dir.join(version);
        fs::create_dir_all(&version_dir)?;
        
        let mut mod_imports = Vec::new();
        
        // Generate each type in its own file
        for (type_ref, type_def) in version_types {
            // Check if this type references other types in the same version
            let mut imports = Vec::new();
            let mut type_replacements = std::collections::HashMap::new();
            
            // Collect any references to other types in the same module
            let mut referenced_types = std::collections::HashSet::new();
            collect_type_references(&type_def.ty, &mut referenced_types);
            
            // For each referenced type, check if it exists in the same version
            for referenced in &referenced_types {
                // Check if this is a simple type name (not a full path)
                if !referenced.contains('.') && referenced != &type_ref.kind {
                    // Check if this type exists in the same version
                    if version_types.iter().any(|(tr, _)| tr.kind == *referenced) {
                        // Add import for the type in the same directory
                        let alias = referenced.to_lowercase();
                        imports.push(amalgam_core::ir::Import {
                            path: format!("./{}.ncl", alias),
                            alias: Some(alias.clone()),
                            items: vec![referenced.clone()],
                        });
                        
                        // Store replacement: ManagedFieldsEntry -> managedfieldsentry.ManagedFieldsEntry
                        type_replacements.insert(referenced.clone(), format!("{}.{}", alias, referenced));
                    }
                }
            }
            
            // Apply type replacements to the type definition
            let mut updated_type_def = type_def.clone();
            apply_type_replacements(&mut updated_type_def.ty, &type_replacements);
            
            // Create a module with the type and its imports
            let module = amalgam_core::ir::Module {
                name: format!("k8s.io.{}.{}", type_ref.version, type_ref.kind.to_lowercase()),
                imports,
                types: vec![updated_type_def],
                constants: vec![],
                metadata: Default::default(),
            };
            
            // Create IR with the module
            let mut ir = amalgam_core::IR::new();
            ir.add_module(module);
            
            // Generate Nickel code
            let mut codegen = NickelCodegen::new();
            let code = codegen.generate(&ir)?;
            
            // Write to file
            let filename = format!("{}.ncl", type_ref.kind.to_lowercase());
            let file_path = version_dir.join(&filename);
            fs::write(&file_path, code)?;
            
            info!("Generated {:?}", file_path);
            
            // Add to module imports
            mod_imports.push(format!("  {} = (import \"./{}\").{},", 
                type_ref.kind, 
                filename,
                type_ref.kind
            ));
        }
        
        // Generate mod.ncl for this version
        let mod_content = format!(
            "# Kubernetes core {} types\n{{\n{}\n}}\n",
            version,
            mod_imports.join("\n")
        );
        fs::write(version_dir.join("mod.ncl"), mod_content)?;
    }
    
    // Generate top-level mod.ncl with all versions
    let mut version_imports = Vec::new();
    for version in types_by_version.keys() {
        version_imports.push(format!("  {} = import \"./{}/mod.ncl\",", version, version));
    }
    
    let root_mod_content = format!(
        "# Kubernetes core types\n{{\n{}\n}}\n",
        version_imports.join("\n")
    );
    fs::write(output_dir.join("mod.ncl"), root_mod_content)?;
    
    info!("Successfully generated {} k8s core types in {:?}", total_types, output_dir);
    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(())
}