zlayer-builder 0.11.12

Dockerfile parsing and buildah-based container image building
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
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
//! Runtime templates for `ZLayer` builder
//!
//! This module provides pre-built Dockerfile templates for common runtimes,
//! allowing users to build container images without writing Dockerfiles.
//!
//! # Usage
//!
//! Templates can be used via the `zlayer build` command:
//!
//! ```bash
//! # Use a specific runtime template
//! zlayer build --runtime node20
//!
//! # Auto-detect runtime from project files
//! zlayer build --detect-runtime
//! ```
//!
//! # Available Runtimes
//!
//! - **Node.js 20** (`node20`): Production-ready Node.js 20 with Alpine base
//! - **Node.js 22** (`node22`): Production-ready Node.js 22 with Alpine base
//! - **Python 3.12** (`python312`): Python 3.12 slim with pip packages
//! - **Python 3.13** (`python313`): Python 3.13 slim with pip packages
//! - **Rust** (`rust`): Static binary build with musl
//! - **Go** (`go`): Static binary build with Alpine
//! - **Deno** (`deno`): Official Deno runtime
//! - **Bun** (`bun`): Official Bun runtime
//! - **Windows Nanoserver** (`windows-nanoserver`): Minimal Windows base for
//!   self-contained binaries; no package managers / no `PowerShell`
//! - **Windows Server Core** (`windows-servercore`): Larger Windows base with
//!   `PowerShell` bundled; required for chocolatey / winget / full .NET SDK
//!
//! # Auto-Detection
//!
//! The [`detect_runtime`] function can automatically detect the appropriate
//! runtime based on files present in the project directory:
//!
//! - `package.json` -> Node.js (unless Bun or Deno indicators present)
//! - `bun.lockb` -> Bun
//! - `deno.json` or `deno.jsonc` -> Deno
//! - `Cargo.toml` -> Rust
//! - `requirements.txt`, `pyproject.toml`, `setup.py` -> Python
//! - `go.mod` -> Go
//! - `*.sln` / `*.csproj` / `*.vcxproj` / `project.json` -> Windows Server Core
//! - `*.exe` (with no Linux indicators) -> Windows Nanoserver
//!
//! Auto-detection is a *hint*. Explicit overrides (`os:` field, `--platform`
//! CLI flag) always win — see `resolve_runtime`.

mod detect;

use std::fmt;
use std::path::Path;
use std::str::FromStr;

pub use detect::{detect_runtime, detect_runtime_with_version};

/// Supported runtime environments
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Runtime {
    /// Node.js 20 (LTS)
    Node20,
    /// Node.js 22 (Current)
    Node22,
    /// Python 3.12
    Python312,
    /// Python 3.13
    Python313,
    /// Rust (latest stable)
    Rust,
    /// Go (latest stable)
    Go,
    /// Deno (latest)
    Deno,
    /// Bun (latest)
    Bun,
    /// Windows Nanoserver (`mcr.microsoft.com/windows/nanoserver:ltsc2022`).
    ///
    /// Minimal Windows base image for self-contained binaries. No `PowerShell`,
    /// no chocolatey, no winget.
    WindowsNanoserver,
    /// Windows Server Core (`mcr.microsoft.com/windows/servercore:ltsc2022`).
    ///
    /// Larger Windows base that bundles `PowerShell` and is compatible with
    /// chocolatey / winget / full .NET SDK workloads.
    WindowsServerCore,
    /// `WebAssembly` (delegates to `wasm:` build mode).
    ///
    /// The associated [`WasmTargetHint`] is a best-effort indicator of whether
    /// the project builds a raw WASI module or a WASI component. Downstream
    /// build logic treats this as guidance only; the actual target is still
    /// driven by the `ZImagefile` `wasm:` section (or its defaults).
    Wasm(WasmTargetHint),
}

/// Hint for the kind of `WebAssembly` artifact a project produces.
///
/// This is populated by [`Runtime::detect_from_path`] (via the `detect` module)
/// and carried through `Runtime::Wasm(hint)` so callers can pick reasonable
/// defaults when delegating to the `wasm:` build mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum WasmTargetHint {
    /// WASI preview1 / preview2 raw module (no component wrapper).
    Module,
    /// WASI component (cargo-component, jco, componentize-py, ...).
    Component,
    /// Unknown / let the builder pick its own default (currently preview2).
    #[default]
    Auto,
}

impl WasmTargetHint {
    /// Short lowercase name used in diagnostics and YAML emission.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Module => "module",
            Self::Component => "component",
            Self::Auto => "auto",
        }
    }
}

impl Runtime {
    /// Get all available runtimes
    #[must_use]
    pub fn all() -> &'static [RuntimeInfo] {
        &[
            RuntimeInfo {
                runtime: Runtime::Node20,
                name: "node20",
                description: "Node.js 20 (LTS) - Alpine-based, production optimized",
                detect_files: &["package.json"],
            },
            RuntimeInfo {
                runtime: Runtime::Node22,
                name: "node22",
                description: "Node.js 22 (Current) - Alpine-based, production optimized",
                detect_files: &["package.json"],
            },
            RuntimeInfo {
                runtime: Runtime::Python312,
                name: "python312",
                description: "Python 3.12 - Slim Debian-based with pip",
                detect_files: &["requirements.txt", "pyproject.toml", "setup.py"],
            },
            RuntimeInfo {
                runtime: Runtime::Python313,
                name: "python313",
                description: "Python 3.13 - Slim Debian-based with pip",
                detect_files: &["requirements.txt", "pyproject.toml", "setup.py"],
            },
            RuntimeInfo {
                runtime: Runtime::Rust,
                name: "rust",
                description: "Rust - Static musl binary, minimal Alpine runtime",
                detect_files: &["Cargo.toml"],
            },
            RuntimeInfo {
                runtime: Runtime::Go,
                name: "go",
                description: "Go - Static binary, minimal Alpine runtime",
                detect_files: &["go.mod"],
            },
            RuntimeInfo {
                runtime: Runtime::Deno,
                name: "deno",
                description: "Deno - Official runtime with TypeScript support",
                detect_files: &["deno.json", "deno.jsonc"],
            },
            RuntimeInfo {
                runtime: Runtime::Bun,
                name: "bun",
                description: "Bun - Fast JavaScript runtime and bundler",
                detect_files: &["bun.lockb"],
            },
            RuntimeInfo {
                runtime: Runtime::WindowsNanoserver,
                name: "windows-nanoserver",
                description:
                    "Windows Nanoserver - Minimal Windows base (no package managers, no `PowerShell`)",
                // Any .exe file at the context root suggests a self-contained
                // Windows binary workload.
                detect_files: &["*.exe"],
            },
            RuntimeInfo {
                runtime: Runtime::WindowsServerCore,
                name: "windows-servercore",
                description:
                    "Windows Server Core - Windows base with `PowerShell`, chocolatey/winget compatible",
                detect_files: &["*.sln", "*.csproj", "*.vcxproj", "project.json"],
            },
            RuntimeInfo {
                runtime: Runtime::Wasm(WasmTargetHint::Auto),
                name: "wasm",
                description: "WebAssembly - Delegates to wasm: build mode (auto-detects target)",
                detect_files: &["cargo-component.toml", "componentize-py.config"],
            },
        ]
    }

    /// Parse a runtime from its name
    #[must_use]
    pub fn from_name(name: &str) -> Option<Runtime> {
        let name_lower = name.to_lowercase();
        match name_lower.as_str() {
            "node20" | "node-20" | "nodejs20" | "node" => Some(Runtime::Node20),
            "node22" | "node-22" | "nodejs22" => Some(Runtime::Node22),
            "python312" | "python-312" | "python3.12" | "python" => Some(Runtime::Python312),
            "python313" | "python-313" | "python3.13" => Some(Runtime::Python313),
            "rust" | "rs" => Some(Runtime::Rust),
            "go" | "golang" => Some(Runtime::Go),
            "deno" => Some(Runtime::Deno),
            "bun" => Some(Runtime::Bun),
            "windows-nanoserver" | "nanoserver" | "windows_nanoserver" => {
                Some(Runtime::WindowsNanoserver)
            }
            "windows-servercore" | "windows-server-core" | "servercore" | "windows_servercore" => {
                Some(Runtime::WindowsServerCore)
            }
            "wasm" | "webassembly" => Some(Runtime::Wasm(WasmTargetHint::Auto)),
            "wasm-module" | "wasm-preview1" | "wasm-preview2" => {
                Some(Runtime::Wasm(WasmTargetHint::Module))
            }
            "wasm-component" | "wasi-component" => Some(Runtime::Wasm(WasmTargetHint::Component)),
            _ => None,
        }
    }

    /// Get information about this runtime
    ///
    /// # Panics
    ///
    /// Panics if the runtime variant is missing from the static info table (internal invariant).
    #[must_use]
    pub fn info(&self) -> &'static RuntimeInfo {
        // WASM variants all share a single info entry regardless of the
        // [`WasmTargetHint`] payload, so we collapse to the `Auto` hint for
        // lookup.
        let lookup = match self {
            Runtime::Wasm(_) => Runtime::Wasm(WasmTargetHint::Auto),
            other => *other,
        };
        Runtime::all()
            .iter()
            .find(|info| info.runtime == lookup)
            .expect("All runtimes must have info")
    }

    /// Get the Dockerfile template for this runtime
    ///
    /// # Note on `Runtime::Wasm`
    ///
    /// The WASM variant does not produce a Dockerfile — it is a sentinel that
    /// tells the builder to delegate to the `wasm:` build mode. The returned
    /// string is a `ZImagefile` YAML snippet (see [`Runtime::wasm_zimagefile`])
    /// so callers that feed `template()` output through the `ZImagefile` parser
    /// will cleanly route into the WASM build path. Callers that feed it
    /// through the Dockerfile parser must special-case `Runtime::Wasm(_)`.
    #[must_use]
    pub fn template(&self) -> &'static str {
        match self {
            Runtime::Node20 => include_str!("dockerfiles/node20.Dockerfile"),
            Runtime::Node22 => include_str!("dockerfiles/node22.Dockerfile"),
            Runtime::Python312 => include_str!("dockerfiles/python312.Dockerfile"),
            Runtime::Python313 => include_str!("dockerfiles/python313.Dockerfile"),
            Runtime::Rust => include_str!("dockerfiles/rust.Dockerfile"),
            Runtime::Go => include_str!("dockerfiles/go.Dockerfile"),
            Runtime::Deno => include_str!("dockerfiles/deno.Dockerfile"),
            Runtime::Bun => include_str!("dockerfiles/bun.Dockerfile"),
            Runtime::WindowsNanoserver => {
                include_str!("dockerfiles/windows-nanoserver.Dockerfile")
            }
            Runtime::WindowsServerCore => {
                include_str!("dockerfiles/windows-servercore.Dockerfile")
            }
            Runtime::Wasm(hint) => Self::wasm_zimagefile(*hint),
        }
    }

    /// Return a minimal `ZImagefile` YAML snippet for the WASM runtime.
    ///
    /// The snippet sets `wasm:` mode with defaults appropriate for the given
    /// [`WasmTargetHint`]. The parser's `validate_wasm` accepts these defaults,
    /// and the builder's WASM path will auto-detect the source language when
    /// `language` is omitted.
    fn wasm_zimagefile(hint: WasmTargetHint) -> &'static str {
        match hint {
            // Components default to preview2 (WASI component model).
            WasmTargetHint::Component => "wasm:\n  target: preview2\n",
            // Raw modules default to preview1, which is what a bare
            // `wasm32-wasip1` Cargo build produces.
            WasmTargetHint::Module => "wasm:\n  target: preview1\n",
            // Unknown — pick the modern default and let the builder decide.
            WasmTargetHint::Auto => "wasm: {}\n",
        }
    }

    /// Get the canonical name for this runtime
    #[must_use]
    pub fn name(&self) -> &'static str {
        self.info().name
    }
}

impl fmt::Display for Runtime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl FromStr for Runtime {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Runtime::from_name(s).ok_or_else(|| format!("Unknown runtime: {s}"))
    }
}

/// Information about a runtime template
#[derive(Debug, Clone, Copy)]
pub struct RuntimeInfo {
    /// The runtime enum value
    pub runtime: Runtime,
    /// Short name used in CLI (e.g., "node20")
    pub name: &'static str,
    /// Human-readable description
    pub description: &'static str,
    /// Files that indicate this runtime should be used
    pub detect_files: &'static [&'static str],
}

/// List all available templates
#[must_use]
pub fn list_templates() -> Vec<&'static RuntimeInfo> {
    Runtime::all().iter().collect()
}

/// Get template content for a runtime
#[must_use]
pub fn get_template(runtime: Runtime) -> &'static str {
    runtime.template()
}

/// Get template content by runtime name
#[must_use]
pub fn get_template_by_name(name: &str) -> Option<&'static str> {
    Runtime::from_name(name).map(|r| r.template())
}

/// Resolve runtime from either explicit name or auto-detection
pub fn resolve_runtime(
    runtime_name: Option<&str>,
    context_path: impl AsRef<Path>,
    use_version_hints: bool,
) -> Option<Runtime> {
    // If explicitly specified, use that
    if let Some(name) = runtime_name {
        return Runtime::from_name(name);
    }

    // Otherwise, auto-detect
    if use_version_hints {
        detect_runtime_with_version(context_path)
    } else {
        detect_runtime(context_path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Dockerfile;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_runtime_from_name() {
        assert_eq!(Runtime::from_name("node20"), Some(Runtime::Node20));
        assert_eq!(Runtime::from_name("Node20"), Some(Runtime::Node20));
        assert_eq!(Runtime::from_name("node"), Some(Runtime::Node20));
        assert_eq!(Runtime::from_name("python"), Some(Runtime::Python312));
        assert_eq!(Runtime::from_name("rust"), Some(Runtime::Rust));
        assert_eq!(Runtime::from_name("go"), Some(Runtime::Go));
        assert_eq!(Runtime::from_name("golang"), Some(Runtime::Go));
        assert_eq!(Runtime::from_name("deno"), Some(Runtime::Deno));
        assert_eq!(Runtime::from_name("bun"), Some(Runtime::Bun));
        assert_eq!(Runtime::from_name("unknown"), None);
    }

    #[test]
    fn test_runtime_info() {
        let info = Runtime::Node20.info();
        assert_eq!(info.name, "node20");
        assert!(info.description.contains("Node.js"));
        assert!(info.detect_files.contains(&"package.json"));
    }

    #[test]
    fn test_all_templates_parse_correctly() {
        for info in Runtime::all() {
            // The WASM runtime emits a ZImagefile YAML snippet (routed to the
            // `wasm:` build mode), not a Dockerfile — skip the Dockerfile
            // parser for that variant.
            if matches!(info.runtime, Runtime::Wasm(_)) {
                continue;
            }

            let template = info.runtime.template();
            let result = Dockerfile::parse(template);
            assert!(
                result.is_ok(),
                "Template {} failed to parse: {:?}",
                info.name,
                result.err()
            );

            let dockerfile = result.unwrap();
            assert!(
                !dockerfile.stages.is_empty(),
                "Template {} has no stages",
                info.name
            );
        }
    }

    #[test]
    fn test_runtime_wasm_from_name() {
        assert_eq!(
            Runtime::from_name("wasm"),
            Some(Runtime::Wasm(WasmTargetHint::Auto))
        );
        assert_eq!(
            Runtime::from_name("WASM"),
            Some(Runtime::Wasm(WasmTargetHint::Auto))
        );
        assert_eq!(
            Runtime::from_name("webassembly"),
            Some(Runtime::Wasm(WasmTargetHint::Auto))
        );
        assert_eq!(
            Runtime::from_name("wasm-component"),
            Some(Runtime::Wasm(WasmTargetHint::Component))
        );
        assert_eq!(
            Runtime::from_name("wasm-module"),
            Some(Runtime::Wasm(WasmTargetHint::Module))
        );
    }

    #[test]
    fn test_runtime_wasm_template_is_zimagefile_yaml() {
        let t = Runtime::Wasm(WasmTargetHint::Auto).template();
        assert!(t.contains("wasm:"), "template should set wasm mode: {t}");

        let component = Runtime::Wasm(WasmTargetHint::Component).template();
        assert!(component.contains("preview2"), "component → preview2");

        let module = Runtime::Wasm(WasmTargetHint::Module).template();
        assert!(module.contains("preview1"), "module → preview1");
    }

    #[test]
    fn test_runtime_wasm_info_lookup() {
        // All WasmTargetHint variants must resolve through info() without
        // panicking.
        let auto = Runtime::Wasm(WasmTargetHint::Auto).info();
        let module = Runtime::Wasm(WasmTargetHint::Module).info();
        let component = Runtime::Wasm(WasmTargetHint::Component).info();
        assert_eq!(auto.name, "wasm");
        assert_eq!(module.name, "wasm");
        assert_eq!(component.name, "wasm");
    }

    #[test]
    fn test_node20_template_structure() {
        let template = Runtime::Node20.template();
        let dockerfile = Dockerfile::parse(template).expect("Should parse");

        // Should be multi-stage
        assert_eq!(dockerfile.stages.len(), 2);

        // First stage is builder
        assert_eq!(dockerfile.stages[0].name, Some("builder".to_string()));

        // Final stage should have USER instruction for security
        let final_stage = dockerfile.final_stage().unwrap();
        let has_user = final_stage
            .instructions
            .iter()
            .any(|i| matches!(i, crate::Instruction::User(_)));
        assert!(has_user, "Node template should run as non-root user");
    }

    #[test]
    fn test_rust_template_structure() {
        let template = Runtime::Rust.template();
        let dockerfile = Dockerfile::parse(template).expect("Should parse");

        // Should be multi-stage
        assert_eq!(dockerfile.stages.len(), 2);

        // First stage is builder
        assert_eq!(dockerfile.stages[0].name, Some("builder".to_string()));
    }

    #[test]
    fn test_windows_nanoserver_from_name() {
        assert_eq!(
            Runtime::from_name("windows-nanoserver"),
            Some(Runtime::WindowsNanoserver)
        );
        assert_eq!(
            Runtime::from_name("nanoserver"),
            Some(Runtime::WindowsNanoserver)
        );
        assert_eq!(
            Runtime::from_name("Windows-Nanoserver"),
            Some(Runtime::WindowsNanoserver)
        );
    }

    #[test]
    fn test_windows_servercore_from_name() {
        assert_eq!(
            Runtime::from_name("windows-servercore"),
            Some(Runtime::WindowsServerCore)
        );
        assert_eq!(
            Runtime::from_name("windows-server-core"),
            Some(Runtime::WindowsServerCore)
        );
        assert_eq!(
            Runtime::from_name("servercore"),
            Some(Runtime::WindowsServerCore)
        );
    }

    #[test]
    fn test_windows_nanoserver_template_structure() {
        let template = Runtime::WindowsNanoserver.template();
        let dockerfile = Dockerfile::parse(template).expect("nanoserver template should parse");

        // Single-stage minimal template.
        assert_eq!(dockerfile.stages.len(), 1);

        let stage = &dockerfile.stages[0];
        let base = stage.base_image.to_string();
        assert!(
            base.contains("nanoserver"),
            "nanoserver template must FROM an mcr nanoserver image, got {base}"
        );

        // Must set USER to ContainerAdministrator (the parser preserves the
        // argument verbatim, so trim before comparing).
        let has_user = stage.instructions.iter().any(
            |i| matches!(i, crate::Instruction::User(u) if u.trim() == "ContainerAdministrator"),
        );
        assert!(
            has_user,
            "nanoserver template must set USER ContainerAdministrator"
        );

        // Must set a Windows-style WORKDIR.
        let has_windows_workdir = stage
            .instructions
            .iter()
            .any(|i| matches!(i, crate::Instruction::Workdir(w) if w.trim().starts_with("C:")));
        assert!(
            has_windows_workdir,
            "nanoserver template must set a Windows WORKDIR (C:\\...)"
        );

        // Must have a CMD.
        let has_cmd = stage
            .instructions
            .iter()
            .any(|i| matches!(i, crate::Instruction::Cmd(_)));
        assert!(has_cmd, "nanoserver template must define a CMD");
    }

    #[test]
    fn test_windows_servercore_template_structure() {
        let template = Runtime::WindowsServerCore.template();
        let dockerfile = Dockerfile::parse(template).expect("servercore template should parse");

        assert_eq!(dockerfile.stages.len(), 1);

        let stage = &dockerfile.stages[0];
        let base = stage.base_image.to_string();
        assert!(
            base.contains("servercore"),
            "servercore template must FROM an mcr servercore image, got {base}"
        );

        // Servercore bundles `PowerShell` — template must SHELL into it so
        // subsequent RUNs accept `PowerShell` syntax.
        let has_powershell_shell = stage.instructions.iter().any(|i| {
            matches!(
                i,
                crate::Instruction::Shell(argv)
                    if argv.first().map(String::as_str) == Some("powershell")
            )
        });
        assert!(
            has_powershell_shell,
            "servercore template must switch SHELL to powershell"
        );

        // USER + WORKDIR sanity checks (same skeleton as nanoserver); parser
        // preserves the raw argument so we trim before comparing.
        let has_user = stage.instructions.iter().any(
            |i| matches!(i, crate::Instruction::User(u) if u.trim() == "ContainerAdministrator"),
        );
        assert!(
            has_user,
            "servercore template must set USER ContainerAdministrator"
        );

        let has_windows_workdir = stage
            .instructions
            .iter()
            .any(|i| matches!(i, crate::Instruction::Workdir(w) if w.trim().starts_with("C:")));
        assert!(
            has_windows_workdir,
            "servercore template must set a Windows WORKDIR (C:\\...)"
        );
    }

    #[test]
    fn test_windows_templates_listed_in_all() {
        let names: Vec<&str> = Runtime::all().iter().map(|info| info.name).collect();
        assert!(
            names.contains(&"windows-nanoserver"),
            "windows-nanoserver missing from Runtime::all()"
        );
        assert!(
            names.contains(&"windows-servercore"),
            "windows-servercore missing from Runtime::all()"
        );
    }

    #[test]
    fn test_get_windows_templates_by_name() {
        let nano = get_template_by_name("windows-nanoserver");
        assert!(nano.is_some(), "windows-nanoserver template must resolve");
        assert!(nano.unwrap().contains("nanoserver"));

        let sc = get_template_by_name("windows-servercore");
        assert!(sc.is_some(), "windows-servercore template must resolve");
        assert!(sc.unwrap().contains("servercore"));
    }

    #[test]
    fn test_list_templates() {
        let templates = list_templates();
        assert!(!templates.is_empty());
        assert!(templates.iter().any(|t| t.name == "node20"));
        assert!(templates.iter().any(|t| t.name == "rust"));
        assert!(templates.iter().any(|t| t.name == "go"));
    }

    #[test]
    fn test_get_template_by_name() {
        let template = get_template_by_name("node20");
        assert!(template.is_some());
        assert!(template.unwrap().contains("node:20"));

        let template = get_template_by_name("unknown");
        assert!(template.is_none());
    }

    #[test]
    fn test_resolve_runtime_explicit() {
        let dir = TempDir::new().unwrap();

        // Explicit name takes precedence
        let runtime = resolve_runtime(Some("rust"), dir.path(), false);
        assert_eq!(runtime, Some(Runtime::Rust));
    }

    #[test]
    fn test_resolve_runtime_detect() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("Cargo.toml"), "[package]").unwrap();

        // Auto-detect when no name given
        let runtime = resolve_runtime(None, dir.path(), false);
        assert_eq!(runtime, Some(Runtime::Rust));
    }

    #[test]
    fn test_runtime_display() {
        assert_eq!(format!("{}", Runtime::Node20), "node20");
        assert_eq!(format!("{}", Runtime::Rust), "rust");
    }

    #[test]
    fn test_runtime_from_str() {
        let runtime: Result<Runtime, _> = "node20".parse();
        assert_eq!(runtime, Ok(Runtime::Node20));

        let runtime: Result<Runtime, _> = "unknown".parse();
        assert!(runtime.is_err());
    }
}