zlayer-builder 0.14.0

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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
//! Dockerfile IR → text rendering and shared variable expansion.
//!
//! This module provides two backend-agnostic operations over the parsed
//! [`Dockerfile`] IR:
//!
//! - [`expand_dockerfile`] performs Docker build-time variable substitution
//!   across an entire `Dockerfile`, returning a fully-substituted clone of the
//!   IR. It mirrors the per-instruction expansion the buildah CLI backend does
//!   inline (`backend::buildah::expand_instruction`) but operates on the whole
//!   document, maintaining the accumulating ARG/ENV binding map per stage with
//!   Docker semantics (per-stage ARG scope, pre-FROM global ARG defaults).
//! - [`render_dockerfile`] serializes an (already-substituted) `Dockerfile` IR
//!   back to canonical Dockerfile text.
//!
//! These are additive building blocks for unifying the build backends: a single
//! shared expansion + render pass that every backend can reuse instead of each
//! re-deriving the substitution rules.

use std::collections::HashMap;
use std::fmt::Write as _;

use super::instruction::{
    AddInstruction, CopyInstruction, EnvInstruction, ExposeProtocol, HealthcheckInstruction,
    Instruction, RunInstruction, RunMount, RunNetwork, RunSecurity, ShellOrExec,
};
use super::parser::{Dockerfile, Stage};
use super::variable::expand_variables;

/// Escape a string for embedding inside a JSON string literal (exec-form arrays).
///
/// Shared by the Dockerfile text renderer and the buildah command translator so
/// both produce byte-identical JSON escaping. Handles backslash, double-quote,
/// and the common control characters (`\n`, `\r`, `\t`).
#[must_use]
pub(crate) fn escape_json_string(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

/// Quote a shell token if it contains whitespace or characters that the shell
/// would otherwise interpret. Returns the token unchanged when no quoting is
/// required. Used for inlining per-step `RUN` env assignments and degraded
/// exec-form args into a shell-form `RUN` line.
fn shell_quote(s: &str) -> String {
    if s.is_empty() {
        return "\"\"".to_string();
    }
    let needs_quote = s.chars().any(|c| {
        c.is_whitespace()
            || matches!(
                c,
                '"' | '\''
                    | '\\'
                    | '$'
                    | '`'
                    | '&'
                    | '|'
                    | ';'
                    | '<'
                    | '>'
                    | '('
                    | ')'
                    | '*'
                    | '?'
                    | '['
                    | ']'
                    | '{'
                    | '}'
                    | '#'
                    | '~'
                    | '!'
            )
    });
    if !needs_quote {
        return s.to_string();
    }
    // Double-quote and escape the characters that remain special inside double
    // quotes: backslash, double-quote, dollar, and backtick.
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '"' | '\\' | '$' | '`' => {
                out.push('\\');
                out.push(c);
            }
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Render an exec-form argument vector as a JSON array: `["a","b"]`.
fn render_json_array(args: &[String]) -> String {
    let inner: Vec<String> = args
        .iter()
        .map(|a| format!("\"{}\"", escape_json_string(a)))
        .collect();
    format!("[{}]", inner.join(", "))
}

/// Render a `key=value` env list inline, sorted by key, shell-quoting values.
fn render_inline_env(env: &HashMap<String, String>) -> String {
    let mut keys: Vec<&String> = env.keys().collect();
    keys.sort();
    keys.iter()
        .map(|k| format!("{}={}", k, shell_quote(&env[*k])))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Merge the build's default cache mounts into every `RUN` instruction of a
/// [`Dockerfile`] IR, in place.
///
/// For each `RUN` instruction, every [`RunMount::Cache`] entry in
/// `options.default_cache_mounts` is appended to `run.mounts` unless a cache
/// mount with the same `target` is already present (step-level mounts win).
/// Non-cache entries in `default_cache_mounts` are ignored (the field only ever
/// carries cache mounts, but we filter defensively).
///
/// This lifts the auto-cache-mount injection that the buildah CLI backend used
/// to do inline per-RUN so it now materializes as real IR before rendering —
/// making the rendered Dockerfile carry the `--mount=type=cache` flags
/// identically for any backend that renders the IR to text.
///
/// A no-op when `options.default_cache_mounts` is empty (the common case).
pub fn merge_default_cache_mounts(df: &mut Dockerfile, options: &crate::builder::BuildOptions) {
    if options.default_cache_mounts.is_empty() {
        return;
    }
    for stage in &mut df.stages {
        for instruction in &mut stage.instructions {
            let Instruction::Run(run) = instruction else {
                continue;
            };
            for default_mount in &options.default_cache_mounts {
                let RunMount::Cache { target, .. } = default_mount else {
                    continue;
                };
                let already_has = run
                    .mounts
                    .iter()
                    .any(|m| matches!(m, RunMount::Cache { target: t, .. } if t == target));
                if !already_has {
                    run.mounts.push(default_mount.clone());
                }
            }
        }
    }
}

/// Expand Docker build-time variables across an entire [`Dockerfile`] IR.
///
/// Walks `global_args` first (pre-FROM ARG defaults), then each [`Stage`]'s
/// instructions, maintaining the accumulating ARG/ENV binding map exactly as the
/// buildah CLI loop does: ARG scope is per-stage (reset to `build_args` + global
/// ARG defaults at the start of each stage), and ARG/ENV instructions fold their
/// (expanded) values into the bindings so later instructions observe them.
///
/// Substituted fields match `backend::buildah::expand_instruction` — RUN command,
/// ENV values, COPY/ADD src+dest, WORKDIR, USER, LABEL values — PLUS each value
/// in `RunInstruction::env` (the per-step transient env), which the inline
/// translator historically failed to expand.
///
/// Returns a fully-substituted clone of the IR; the input is not modified.
#[must_use]
#[allow(clippy::implicit_hasher)]
pub fn expand_dockerfile(df: &Dockerfile, build_args: &HashMap<String, String>) -> Dockerfile {
    let mut out = df.clone();

    for stage in &mut out.stages {
        // Per-stage ARG scope (Docker semantics): start from the build args,
        // overlaid with global (pre-FROM) ARG defaults that the build did not
        // already provide.
        let mut arg_values: HashMap<String, String> = build_args.clone();
        for global_arg in &df.global_args {
            if !arg_values.contains_key(&global_arg.name) {
                if let Some(default) = &global_arg.default {
                    arg_values.insert(global_arg.name.clone(), default.clone());
                }
            }
        }
        let mut env_values: HashMap<String, String> = HashMap::new();

        for instruction in &mut stage.instructions {
            *instruction = expand_instruction(instruction, &mut arg_values, &mut env_values);
        }
    }

    out
}

/// Every build-arg NAME declared in the [`Dockerfile`] IR: the pre-FROM global
/// `ARG`s plus every per-stage `ARG` instruction. Duplicates across stages are
/// possible; callers that care about uniqueness should dedup.
fn declared_arg_names(df: &Dockerfile) -> Vec<String> {
    let mut names: Vec<String> = df.global_args.iter().map(|a| a.name.clone()).collect();
    for stage in &df.stages {
        for instruction in &stage.instructions {
            if let Instruction::Arg(arg) = instruction {
                names.push(arg.name.clone());
            }
        }
    }
    names
}

/// Forward declared-but-unset build-args from the process environment.
///
/// Docker's `--build-arg FOO` (no `=value`) takes `FOO`'s value from the
/// builder's environment. We extend that convenience to every build-arg that is
/// DECLARED in the Dockerfile IR (a pre-FROM global `ARG` or a per-stage `ARG`):
/// if such an arg has no effective value in `args` (absent, or an empty string)
/// and the process environment has a matching non-empty var, the env value is
/// forwarded into `args`. This is why a declared `FORGEJO_TOKEN` build-arg
/// populates from `$FORGEJO_TOKEN` with no explicit `--set`.
///
/// Guarantees:
/// - Never overrides an explicit non-empty value already in `args`.
/// - Only forwards names that are actually declared as build-args — the whole
///   environment is never dumped into the image.
/// - A no-op when the matching env var is unset or empty (identical to today).
///
/// Call this on the merged `effective_build_args` BEFORE deriving the expansion
/// map so both the `--build-arg` flags and in-Dockerfile `${VAR}` expansion see
/// the forwarded value.
#[allow(clippy::implicit_hasher)]
pub fn forward_build_arg_env(
    df: &Dockerfile,
    args: &mut std::collections::BTreeMap<String, String>,
) {
    for name in declared_arg_names(df) {
        // Only fall back when the declared arg has no effective value.
        if args.get(&name).is_some_and(|v| !v.is_empty()) {
            continue;
        }
        match std::env::var(&name) {
            Ok(value) if !value.is_empty() => {
                args.insert(name, value);
            }
            _ => {}
        }
    }
}

/// Expand a single instruction's build-time-expandable fields and fold ARG/ENV
/// bindings into the accumulators. This is the shared counterpart of the inline
/// `backend::buildah::expand_instruction`, with the BUG3 fix: `RunInstruction`'s
/// per-step `env` values are expanded too.
fn expand_instruction(
    instruction: &Instruction,
    arg_values: &mut HashMap<String, String>,
    env_values: &mut HashMap<String, String>,
) -> Instruction {
    match instruction {
        Instruction::Run(run) => {
            let mut run = run.clone();
            run.command = match &run.command {
                ShellOrExec::Shell(s) => {
                    ShellOrExec::Shell(expand_variables(s, arg_values, env_values))
                }
                ShellOrExec::Exec(args) => ShellOrExec::Exec(
                    args.iter()
                        .map(|a| expand_variables(a, arg_values, env_values))
                        .collect(),
                ),
            };
            // BUG3 fix: expand the per-step transient env values too. The old
            // inline translator expanded only `run.command`, so a per-step
            // `ENV TOKEN=${FORGEJO_TOKEN}` style assignment on a RUN reached the
            // runtime unexpanded.
            run.env = run
                .env
                .iter()
                .map(|(k, v)| (k.clone(), expand_variables(v, arg_values, env_values)))
                .collect();
            Instruction::Run(run)
        }
        Instruction::Env(env) => {
            let mut vars = HashMap::with_capacity(env.vars.len());
            for (key, value) in &env.vars {
                let expanded = expand_variables(value, arg_values, env_values);
                env_values.insert(key.clone(), expanded.clone());
                vars.insert(key.clone(), expanded);
            }
            Instruction::Env(EnvInstruction { vars })
        }
        Instruction::Copy(copy) => {
            let mut copy = copy.clone();
            copy.sources = copy
                .sources
                .iter()
                .map(|s| expand_variables(s, arg_values, env_values))
                .collect();
            copy.destination = expand_variables(&copy.destination, arg_values, env_values);
            Instruction::Copy(copy)
        }
        Instruction::Add(add) => {
            let mut add = add.clone();
            add.sources = add
                .sources
                .iter()
                .map(|s| expand_variables(s, arg_values, env_values))
                .collect();
            add.destination = expand_variables(&add.destination, arg_values, env_values);
            Instruction::Add(add)
        }
        Instruction::Workdir(dir) => {
            Instruction::Workdir(expand_variables(dir, arg_values, env_values))
        }
        Instruction::User(user) => {
            Instruction::User(expand_variables(user, arg_values, env_values))
        }
        Instruction::Label(labels) => {
            let expanded = labels
                .iter()
                .map(|(k, v)| (k.clone(), expand_variables(v, arg_values, env_values)))
                .collect();
            Instruction::Label(expanded)
        }
        Instruction::Arg(arg) => {
            // `ARG NAME=default` contributes its (expanded) default only when
            // the build did not already pass a value for it; a bare `ARG NAME`
            // leaves the variable unset (preserved as-is by `expand_variables`).
            if !arg_values.contains_key(&arg.name) {
                if let Some(default) = &arg.default {
                    let expanded = expand_variables(default, arg_values, env_values);
                    arg_values.insert(arg.name.clone(), expanded);
                }
            }
            instruction.clone()
        }
        other => other.clone(),
    }
}

/// Serialize a (presumably already variable-substituted) [`Dockerfile`] IR back
/// to canonical Dockerfile text.
///
/// Pure function: it does not perform variable expansion. Instruction order is
/// preserved exactly as it appears in the IR. The output round-trips through
/// [`Dockerfile::parse`] to a structurally-equivalent IR.
#[must_use]
pub fn render_dockerfile(df: &Dockerfile) -> String {
    let mut out = String::new();

    // Global ARGs (before the first FROM).
    for arg in &df.global_args {
        match &arg.default {
            Some(default) => {
                let _ = writeln!(out, "ARG {}={}", arg.name, default);
            }
            None => {
                let _ = writeln!(out, "ARG {}", arg.name);
            }
        }
    }

    for (idx, stage) in df.stages.iter().enumerate() {
        if idx > 0 || !df.global_args.is_empty() {
            out.push('\n');
        }
        render_stage(stage, &mut out);
    }

    out
}

/// Render a single stage (its `FROM` line plus instructions).
fn render_stage(stage: &Stage, out: &mut String) {
    out.push_str("FROM ");
    if let Some(platform) = &stage.platform {
        let _ = write!(out, "--platform={platform} ");
    }
    out.push_str(&stage.base_image.to_string());
    if let Some(name) = &stage.name {
        let _ = write!(out, " AS {name}");
    }
    out.push('\n');

    for instruction in &stage.instructions {
        out.push_str(&render_instruction(instruction));
        out.push('\n');
    }
}

/// Render a single instruction to one (possibly multi-token) Dockerfile line.
#[allow(clippy::too_many_lines)]
fn render_instruction(instruction: &Instruction) -> String {
    match instruction {
        Instruction::Run(run) => render_run(run),
        Instruction::Copy(copy) => render_copy(copy),
        Instruction::Add(add) => render_add(add),
        Instruction::Env(env) => {
            let mut keys: Vec<&String> = env.vars.keys().collect();
            keys.sort();
            let parts: Vec<String> = keys
                .iter()
                .map(|k| format!("{}={}", k, shell_quote(&env.vars[*k])))
                .collect();
            format!("ENV {}", parts.join(" "))
        }
        Instruction::Workdir(dir) => format!("WORKDIR {dir}"),
        Instruction::Expose(expose) => {
            let proto = match expose.protocol {
                ExposeProtocol::Tcp => "tcp",
                ExposeProtocol::Udp => "udp",
            };
            format!("EXPOSE {}/{proto}", expose.port)
        }
        Instruction::Label(labels) => {
            let mut keys: Vec<&String> = labels.keys().collect();
            keys.sort();
            let parts: Vec<String> = keys
                .iter()
                .map(|k| format!("{}=\"{}\"", k, escape_json_string(&labels[*k])))
                .collect();
            format!("LABEL {}", parts.join(" "))
        }
        Instruction::User(user) => format!("USER {user}"),
        Instruction::Entrypoint(cmd) => render_shell_or_exec("ENTRYPOINT", cmd),
        Instruction::Cmd(cmd) => render_shell_or_exec("CMD", cmd),
        Instruction::Volume(paths) => format!("VOLUME {}", render_json_array(paths)),
        Instruction::Shell(shell) => format!("SHELL {}", render_json_array(shell)),
        Instruction::Arg(arg) => match &arg.default {
            Some(default) => format!("ARG {}={}", arg.name, default),
            None => format!("ARG {}", arg.name),
        },
        Instruction::Stopsignal(signal) => format!("STOPSIGNAL {signal}"),
        Instruction::Healthcheck(health) => render_healthcheck(health),
        Instruction::Onbuild(inner) => format!("ONBUILD {}", render_instruction(inner)),
    }
}

/// Render an `ENTRYPOINT` / `CMD` instruction: exec form → JSON array, shell form
/// → bare command.
fn render_shell_or_exec(keyword: &str, cmd: &ShellOrExec) -> String {
    match cmd {
        ShellOrExec::Exec(args) => format!("{keyword} {}", render_json_array(args)),
        ShellOrExec::Shell(s) => format!("{keyword} {s}"),
    }
}

/// Render a `RUN` instruction, folding `--mount`, `--network`, `--security`
/// flags and the per-step env inline.
fn render_run(run: &RunInstruction) -> String {
    let mut flags = String::new();
    for mount in &run.mounts {
        let _ = write!(flags, "--mount={} ", mount.to_buildah_arg());
    }
    if let Some(network) = &run.network {
        let net = match network {
            RunNetwork::Default => "default",
            RunNetwork::None => "none",
            RunNetwork::Host => "host",
        };
        let _ = write!(flags, "--network={net} ");
    }
    if let Some(security) = &run.security {
        let sec = match security {
            RunSecurity::Sandbox => "sandbox",
            RunSecurity::Insecure => "insecure",
        };
        let _ = write!(flags, "--security={sec} ");
    }

    let env_prefix = if run.env.is_empty() {
        String::new()
    } else {
        format!("{} ", render_inline_env(&run.env))
    };

    match &run.command {
        ShellOrExec::Shell(s) => {
            format!("RUN {flags}{env_prefix}{s}")
        }
        ShellOrExec::Exec(args) => {
            if run.env.is_empty() {
                // Exec form with no env → JSON array form.
                format!("RUN {flags}{}", render_json_array(args))
            } else {
                // Exec form with env can't be expressed as a JSON array (env
                // assignments are a shell concept), so degrade to shell form
                // with the args joined and individually shell-quoted.
                let joined = args
                    .iter()
                    .map(|a| shell_quote(a))
                    .collect::<Vec<_>>()
                    .join(" ");
                format!("RUN {flags}{env_prefix}{joined}")
            }
        }
    }
}

/// Render a `COPY` instruction with its flags.
fn render_copy(copy: &CopyInstruction) -> String {
    let mut s = String::from("COPY ");
    if let Some(from) = &copy.from {
        let _ = write!(s, "--from={from} ");
    }
    if let Some(chown) = &copy.chown {
        let _ = write!(s, "--chown={chown} ");
    }
    if let Some(chmod) = &copy.chmod {
        let _ = write!(s, "--chmod={chmod} ");
    }
    if copy.link {
        s.push_str("--link ");
    }
    for exclude in &copy.exclude {
        let _ = write!(s, "--exclude={exclude} ");
    }
    s.push_str(&copy.sources.join(" "));
    s.push(' ');
    s.push_str(&copy.destination);
    s
}

/// Render an `ADD` instruction with its flags.
fn render_add(add: &AddInstruction) -> String {
    let mut s = String::from("ADD ");
    if let Some(chown) = &add.chown {
        let _ = write!(s, "--chown={chown} ");
    }
    if let Some(chmod) = &add.chmod {
        let _ = write!(s, "--chmod={chmod} ");
    }
    if add.link {
        s.push_str("--link ");
    }
    if let Some(checksum) = &add.checksum {
        let _ = write!(s, "--checksum={checksum} ");
    }
    s.push_str(&add.sources.join(" "));
    s.push(' ');
    s.push_str(&add.destination);
    s
}

/// Render a `HEALTHCHECK` instruction.
fn render_healthcheck(health: &HealthcheckInstruction) -> String {
    match health {
        HealthcheckInstruction::None => "HEALTHCHECK NONE".to_string(),
        HealthcheckInstruction::Check {
            command,
            interval,
            timeout,
            start_period,
            start_interval,
            retries,
        } => {
            let mut s = String::from("HEALTHCHECK");
            if let Some(d) = interval {
                let _ = write!(s, " --interval={}s", d.as_secs());
            }
            if let Some(d) = timeout {
                let _ = write!(s, " --timeout={}s", d.as_secs());
            }
            if let Some(d) = start_period {
                let _ = write!(s, " --start-period={}s", d.as_secs());
            }
            if let Some(d) = start_interval {
                let _ = write!(s, " --start-interval={}s", d.as_secs());
            }
            if let Some(r) = retries {
                let _ = write!(s, " --retries={r}");
            }
            match command {
                ShellOrExec::Exec(args) => {
                    let _ = write!(s, " CMD {}", render_json_array(args));
                }
                ShellOrExec::Shell(cmd) => {
                    let _ = write!(s, " CMD {cmd}");
                }
            }
            s
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dockerfile::{
        AddInstruction, ArgInstruction, CacheSharing, CopyInstruction, DockerfileFromTarget,
        EnvInstruction, ExposeInstruction, HealthcheckInstruction, Instruction, RunInstruction,
        RunMount, ShellOrExec, Stage,
    };
    use std::str::FromStr;
    use std::time::Duration;
    use zlayer_types::ImageReference;

    fn img(s: &str) -> DockerfileFromTarget {
        DockerfileFromTarget::Image(ImageReference::from_str(s).unwrap())
    }

    /// Normalize the `dockerfile_parser` "Misc" quirk where WORKDIR/USER/
    /// STOPSIGNAL arguments are captured with their leading whitespace included
    /// (e.g. `WORKDIR /src` parses to `Workdir(" /src")`). The renderer emits the
    /// canonical single-space form; trimming here lets the structural-equivalence
    /// check compare the meaningful payload rather than this parser artifact.
    fn normalize(inst: &Instruction) -> Instruction {
        match inst {
            Instruction::Workdir(s) => Instruction::Workdir(s.trim().to_string()),
            Instruction::User(s) => Instruction::User(s.trim().to_string()),
            Instruction::Stopsignal(s) => Instruction::Stopsignal(s.trim().to_string()),
            other => other.clone(),
        }
    }

    /// Compare two instruction vectors for structural equivalence, normalizing
    /// the parser's leading-whitespace quirk on Misc-derived instructions.
    fn assert_instructions_eq(expected: &[Instruction], actual: &[Instruction]) {
        assert_eq!(
            expected.len(),
            actual.len(),
            "instruction count mismatch\nexpected: {expected:#?}\nactual: {actual:#?}"
        );
        for (e, a) in expected.iter().zip(actual.iter()) {
            assert_eq!(normalize(e), normalize(a), "instruction mismatch");
        }
    }

    #[test]
    fn forward_build_arg_env_fills_only_declared_empty_args() {
        use std::collections::BTreeMap;

        // Unique names so we don't collide with the ambient environment.
        let declared_empty = "ZLAYER_TEST_FWD_DECLARED_EMPTY";
        let declared_explicit = "ZLAYER_TEST_FWD_DECLARED_EXPLICIT";
        let declared_noenv = "ZLAYER_TEST_FWD_DECLARED_NOENV";
        let undeclared = "ZLAYER_TEST_FWD_UNDECLARED";

        std::env::set_var(declared_empty, "from-env");
        std::env::set_var(declared_explicit, "from-env");
        std::env::set_var(undeclared, "from-env");
        std::env::remove_var(declared_noenv);

        // IR declares three args (two global, one per-stage); `undeclared` is NOT
        // declared anywhere.
        let df = Dockerfile {
            global_args: vec![
                ArgInstruction::new(declared_empty),
                ArgInstruction::new(declared_noenv),
            ],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine:3.18"),
                platform: None,
                instructions: vec![Instruction::Arg(ArgInstruction::new(declared_explicit))],
            }],
        };

        let mut args: BTreeMap<String, String> = BTreeMap::new();
        // Declared arg with an empty value -> takes the env value.
        args.insert(declared_empty.to_string(), String::new());
        // Declared arg with an explicit non-empty value -> preserved as-is.
        args.insert(declared_explicit.to_string(), "explicit".to_string());

        forward_build_arg_env(&df, &mut args);

        // Empty + env set -> resolves to the env value.
        assert_eq!(
            args.get(declared_empty).map(String::as_str),
            Some("from-env")
        );
        // Explicit non-empty + env set -> keeps the explicit value (never overridden).
        assert_eq!(
            args.get(declared_explicit).map(String::as_str),
            Some("explicit")
        );
        // Declared but env unset -> unchanged (still absent, current behavior).
        assert!(!args.contains_key(declared_noenv));
        // Undeclared env var -> never forwarded into the image.
        assert!(!args.contains_key(undeclared));

        std::env::remove_var(declared_empty);
        std::env::remove_var(declared_explicit);
        std::env::remove_var(undeclared);
    }

    #[test]
    fn round_trip_multistage_representative() {
        let stage0 = Stage {
            index: 0,
            name: Some("builder".to_string()),
            base_image: img("golang:1.21"),
            platform: None,
            instructions: vec![
                Instruction::Workdir("/src".to_string()),
                Instruction::Copy(CopyInstruction::new(vec![".".to_string()], ".".to_string())),
                Instruction::Run(RunInstruction::shell("go build -o /app")),
                Instruction::Run(RunInstruction::exec(vec![
                    "/bin/true".to_string(),
                    "arg with space".to_string(),
                ])),
                Instruction::Arg(ArgInstruction::with_default("VERSION", "1.0")),
                Instruction::Env(EnvInstruction::new("FOO", "bar baz")),
                Instruction::Expose(ExposeInstruction::tcp(8080)),
                Instruction::Stopsignal("SIGTERM".to_string()),
            ],
        };

        let mut label_map = std::collections::HashMap::new();
        label_map.insert(
            "org.opencontainers.image.title".to_string(),
            "my app".to_string(),
        );

        let stage1 = Stage {
            index: 1,
            name: None,
            base_image: img("alpine:3.18"),
            platform: None,
            instructions: vec![
                Instruction::Copy(
                    CopyInstruction::new(vec!["/app".to_string()], "/app".to_string())
                        .from_stage("builder")
                        .chown("1000:1000"),
                ),
                Instruction::User("appuser".to_string()),
                Instruction::Label(label_map),
                Instruction::Volume(vec!["/data".to_string(), "/cache".to_string()]),
                Instruction::Shell(vec!["/bin/sh".to_string(), "-c".to_string()]),
                Instruction::Entrypoint(ShellOrExec::Exec(vec!["/app".to_string()])),
                Instruction::Cmd(ShellOrExec::Shell("--serve".to_string())),
            ],
        };

        let df = Dockerfile {
            global_args: vec![ArgInstruction::with_default("BASE_TAG", "latest")],
            stages: vec![stage0, stage1],
        };

        let text = render_dockerfile(&df);
        let reparsed = Dockerfile::parse(&text)
            .unwrap_or_else(|e| panic!("re-parse failed: {e}\n---\n{text}\n---"));

        assert_eq!(
            reparsed.global_args.len(),
            df.global_args.len(),
            "global args mismatch\n{text}"
        );
        assert_eq!(
            reparsed.stages.len(),
            df.stages.len(),
            "stage count\n{text}"
        );

        for (orig, re) in df.stages.iter().zip(reparsed.stages.iter()) {
            assert_eq!(orig.name, re.name, "stage name\n{text}");
            assert_eq!(
                orig.base_image.to_string(),
                re.base_image.to_string(),
                "base image\n{text}"
            );
            assert_instructions_eq(&orig.instructions, &re.instructions);
        }
    }

    #[test]
    fn render_healthcheck_variants() {
        // NONE form.
        assert_eq!(
            render_instruction(&Instruction::Healthcheck(HealthcheckInstruction::None)),
            "HEALTHCHECK NONE"
        );

        // Full options + shell CMD. (Parser folds HEALTHCHECK flags into the
        // command string, so this is asserted on rendered text rather than via a
        // re-parse round-trip.)
        let hc = HealthcheckInstruction::Check {
            command: ShellOrExec::Shell("curl -f http://localhost/ || exit 1".to_string()),
            interval: Some(Duration::from_secs(30)),
            timeout: Some(Duration::from_secs(5)),
            start_period: Some(Duration::from_secs(10)),
            start_interval: Some(Duration::from_secs(2)),
            retries: Some(3),
        };
        assert_eq!(
            render_instruction(&Instruction::Healthcheck(hc)),
            "HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --start-interval=2s \
             --retries=3 CMD curl -f http://localhost/ || exit 1"
        );

        // Exec-form CMD renders as a JSON array.
        let hc_exec = HealthcheckInstruction::cmd(ShellOrExec::Exec(vec![
            "curl".to_string(),
            "-f".to_string(),
            "http://localhost/".to_string(),
        ]));
        assert_eq!(
            render_instruction(&Instruction::Healthcheck(hc_exec)),
            r#"HEALTHCHECK CMD ["curl", "-f", "http://localhost/"]"#
        );
    }

    #[test]
    fn render_run_with_cache_mount() {
        // `RUN --mount=type=cache` renders the BuildKit mount flag inline. (The
        // bundled `dockerfile_parser` folds `RUN` flags into the command string
        // rather than into typed mounts, so this is asserted on the rendered
        // text rather than via a re-parse round-trip.)
        let mut run = RunInstruction::shell("apt-get update");
        run.mounts = vec![RunMount::Cache {
            target: "/var/cache/apt".to_string(),
            id: Some("apt".to_string()),
            sharing: CacheSharing::Shared,
            readonly: false,
        }];

        let line = render_instruction(&Instruction::Run(run));
        assert_eq!(
            line,
            "RUN --mount=type=cache,target=/var/cache/apt,id=apt,sharing=shared apt-get update"
        );
    }

    #[test]
    fn round_trip_run_exec_no_env() {
        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![Instruction::Run(RunInstruction::exec(vec![
                    "echo".to_string(),
                    "hello world".to_string(),
                ]))],
            }],
        };

        let text = render_dockerfile(&df);
        assert!(
            text.contains(r#"RUN ["echo", "hello world"]"#),
            "got:\n{text}"
        );

        let reparsed = Dockerfile::parse(&text).unwrap();
        assert_instructions_eq(&df.stages[0].instructions, &reparsed.stages[0].instructions);
    }

    #[test]
    fn round_trip_run_with_per_step_env() {
        // Exec form with env degrades to shell form. We assert the rendered text
        // carries the env inline and the command tokens.
        let mut run = RunInstruction::shell("make build");
        run.env.insert("CC".to_string(), "clang".to_string());
        run.env.insert("FLAGS".to_string(), "-O2 -g".to_string());

        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![Instruction::Run(run)],
            }],
        };

        let text = render_dockerfile(&df);
        // Sorted keys, value with whitespace quoted.
        assert!(
            text.contains(r#"RUN CC=clang FLAGS="-O2 -g" make build"#),
            "got:\n{text}"
        );
        // The shell-form RUN re-parses to a shell command (env folds into the
        // command string since Dockerfile syntax has no per-step env concept).
        let reparsed = Dockerfile::parse(&text).unwrap();
        assert_eq!(reparsed.stages[0].instructions.len(), 1);
        assert!(matches!(
            &reparsed.stages[0].instructions[0],
            Instruction::Run(_)
        ));
    }

    #[test]
    fn round_trip_onbuild() {
        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![Instruction::Onbuild(Box::new(Instruction::Run(
                    RunInstruction::shell("echo onbuild"),
                )))],
            }],
        };

        let text = render_dockerfile(&df);
        assert!(text.contains("ONBUILD RUN echo onbuild"), "got:\n{text}");
        // The existing parser drops ONBUILD, but the renderer must PRESERVE it.
        // Assert via the rendered text rather than a re-parse round-trip.
    }

    #[test]
    fn render_add_with_checksum() {
        let mut add = AddInstruction::new(
            vec!["https://example.com/file.tar.gz".to_string()],
            "/opt/file.tar.gz".to_string(),
        );
        add.checksum = Some("sha256:abc".to_string());
        add.chown = Some("0:0".to_string());

        let line = render_instruction(&Instruction::Add(add));
        assert_eq!(
            line,
            "ADD --chown=0:0 --checksum=sha256:abc https://example.com/file.tar.gz /opt/file.tar.gz"
        );
    }

    #[test]
    fn expand_dockerfile_bug3_run_env_and_command() {
        // BUG3: a RUN with per-step env `TOKEN=${FORGEJO_TOKEN}` plus a command
        // referencing `${FORGEJO_TOKEN}` must expand BOTH.
        let mut run = RunInstruction::shell("auth --token ${FORGEJO_TOKEN}");
        run.env
            .insert("TOKEN".to_string(), "${FORGEJO_TOKEN}".to_string());

        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![Instruction::Run(run)],
            }],
        };

        let build_args: std::collections::HashMap<String, String> =
            [("FORGEJO_TOKEN".to_string(), "s3cr3t".to_string())]
                .into_iter()
                .collect();

        let expanded = expand_dockerfile(&df, &build_args);
        let Instruction::Run(run) = &expanded.stages[0].instructions[0] else {
            panic!("expected RUN");
        };

        assert_eq!(
            run.env.get("TOKEN"),
            Some(&"s3cr3t".to_string()),
            "BUG3: run.env value must be substituted"
        );
        match &run.command {
            ShellOrExec::Shell(s) => assert_eq!(s, "auth --token s3cr3t"),
            ShellOrExec::Exec(args) => panic!("expected shell command, got exec: {args:?}"),
        }
    }

    #[test]
    fn merge_default_cache_mounts_adds_and_dedups() {
        use crate::builder::BuildOptions;
        use crate::dockerfile::{CacheSharing, RunInstruction, RunMount};

        // RUN #0: no mounts → should receive the default cache mount.
        let run_bare = RunInstruction::shell("apt-get update");

        // RUN #1: already has a cache mount for the SAME target → the default
        // for that target must NOT be appended (step-level wins).
        let mut run_has_same = RunInstruction::shell("pip install foo");
        run_has_same.mounts.push(RunMount::Cache {
            target: "/var/cache/apt".to_string(),
            id: Some("step".to_string()),
            sharing: CacheSharing::Locked,
            readonly: false,
        });

        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![
                    Instruction::Run(run_bare),
                    Instruction::Run(run_has_same),
                    // A non-RUN instruction must be untouched.
                    Instruction::Workdir("/app".to_string()),
                ],
            }],
        };

        let mut ir = df;
        let options = BuildOptions {
            default_cache_mounts: vec![RunMount::Cache {
                target: "/var/cache/apt".to_string(),
                id: Some("auto".to_string()),
                sharing: CacheSharing::Shared,
                readonly: false,
            }],
            ..BuildOptions::default()
        };

        super::merge_default_cache_mounts(&mut ir, &options);

        let Instruction::Run(r0) = &ir.stages[0].instructions[0] else {
            panic!("expected RUN");
        };
        assert_eq!(r0.mounts.len(), 1, "bare RUN gains the default cache mount");
        assert!(matches!(
            &r0.mounts[0],
            RunMount::Cache { target, id, .. }
                if target == "/var/cache/apt" && id.as_deref() == Some("auto")
        ));

        let Instruction::Run(r1) = &ir.stages[0].instructions[1] else {
            panic!("expected RUN");
        };
        assert_eq!(
            r1.mounts.len(),
            1,
            "RUN with same-target cache mount is NOT duplicated"
        );
        assert!(matches!(
            &r1.mounts[0],
            RunMount::Cache { id, .. } if id.as_deref() == Some("step")
        ));

        assert!(matches!(
            &ir.stages[0].instructions[2],
            Instruction::Workdir(_)
        ));
    }

    #[test]
    fn merge_default_cache_mounts_noop_when_empty() {
        use crate::builder::BuildOptions;
        use crate::dockerfile::RunInstruction;

        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![Instruction::Run(RunInstruction::shell("echo hi"))],
            }],
        };
        let mut ir = df;
        super::merge_default_cache_mounts(&mut ir, &BuildOptions::default());
        let Instruction::Run(r) = &ir.stages[0].instructions[0] else {
            panic!("expected RUN");
        };
        assert!(r.mounts.is_empty());
    }

    #[test]
    fn expand_dockerfile_arg_and_env_accumulation() {
        // ARG default participates; ENV folds in and is visible to later RUN.
        let df = Dockerfile {
            global_args: vec![],
            stages: vec![Stage {
                index: 0,
                name: None,
                base_image: img("alpine"),
                platform: None,
                instructions: vec![
                    Instruction::Arg(ArgInstruction::with_default("GREETING", "hi")),
                    Instruction::Env(EnvInstruction::new("WHO", "${GREETING} world")),
                    Instruction::Run(RunInstruction::shell("echo ${WHO}")),
                ],
            }],
        };

        let expanded = expand_dockerfile(&df, &std::collections::HashMap::new());
        let Instruction::Env(env) = &expanded.stages[0].instructions[1] else {
            panic!("expected ENV");
        };
        assert_eq!(env.vars.get("WHO"), Some(&"hi world".to_string()));

        let Instruction::Run(run) = &expanded.stages[0].instructions[2] else {
            panic!("expected RUN");
        };
        match &run.command {
            ShellOrExec::Shell(s) => assert_eq!(s, "echo hi world"),
            ShellOrExec::Exec(args) => panic!("expected shell, got exec: {args:?}"),
        }
    }
}