zlayer-builder 0.14.2

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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! Dockerfile parser
//!
//! This module provides functionality to parse Dockerfiles into a structured representation
//! using the `dockerfile-parser` crate as the parsing backend.

use std::collections::HashMap;
use std::path::Path;
use std::str::FromStr;

use dockerfile_parser::{Dockerfile as RawDockerfile, Instruction as RawInstruction};
use serde::{Deserialize, Serialize};
use zlayer_types::ImageReference;

use crate::error::{BuildError, Result};

use super::instruction::{
    AddInstruction, ArgInstruction, CopyInstruction, EnvInstruction, ExposeInstruction,
    ExposeProtocol, HealthcheckInstruction, Instruction, RunInstruction, ShellOrExec,
};

/// A Dockerfile `FROM` target.
///
/// `FROM` references can resolve to one of three things in a Dockerfile:
/// an OCI image (the common case), a previous stage in a multi-stage
/// build (e.g. `FROM builder AS final`), or the special `scratch`
/// pseudo-image. This enum captures all three. For non-Dockerfile call
/// sites (image registry lookups, toolchain detection, etc.) use
/// [`zlayer_types::ImageReference`] directly — the bare OCI ref type
/// without the Dockerfile-only variants.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum DockerfileFromTarget {
    /// An OCI image reference (canonical OCI grammar).
    Image(ImageReference),
    /// A reference to another stage in this multi-stage build.
    Stage(String),
    /// The special `scratch` pseudo-image.
    Scratch,
}

impl DockerfileFromTarget {
    /// Parse a raw `FROM` target string.
    ///
    /// Recognizes `scratch` (case-insensitive), then attempts an OCI
    /// reference parse via [`ImageReference::from_str`]. If parsing
    /// succeeds, the result is an [`Self::Image`]; otherwise the
    /// input is treated as a [`Self::Stage`] reference.
    ///
    /// Note that the OCI grammar accepts bare names like `alpine` as
    /// valid image references, so disambiguation between an image
    /// and a multi-stage stage reference must happen post-hoc at the
    /// call site by consulting the set of known stage names.
    #[must_use]
    pub fn parse(s: &str) -> Self {
        let s = s.trim();

        if s.eq_ignore_ascii_case("scratch") {
            return Self::Scratch;
        }

        match ImageReference::from_str(s) {
            Ok(r) => Self::Image(r),
            Err(_) => Self::Stage(s.to_string()),
        }
    }

    /// Returns true if this is a stage reference.
    #[must_use]
    pub fn is_stage(&self) -> bool {
        matches!(self, Self::Stage(_))
    }

    /// Returns true if this is the `scratch` pseudo-image.
    #[must_use]
    pub fn is_scratch(&self) -> bool {
        matches!(self, Self::Scratch)
    }
}

impl std::fmt::Display for DockerfileFromTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Image(r) => write!(f, "{r}"),
            Self::Stage(name) => f.write_str(name),
            Self::Scratch => f.write_str("scratch"),
        }
    }
}

/// A single stage in a multi-stage Dockerfile
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Stage {
    /// Stage index (0-based)
    pub index: usize,

    /// Optional stage name (from `AS name`)
    pub name: Option<String>,

    /// The base image for this stage
    pub base_image: DockerfileFromTarget,

    /// Optional platform specification (e.g., "linux/amd64")
    pub platform: Option<String>,

    /// Instructions in this stage (excluding the FROM)
    pub instructions: Vec<Instruction>,
}

impl Stage {
    /// Returns the stage identifier (name if present, otherwise index as string)
    #[must_use]
    pub fn identifier(&self) -> String {
        self.name.clone().unwrap_or_else(|| self.index.to_string())
    }

    /// Returns true if this stage matches the given name or index
    #[must_use]
    pub fn matches(&self, name_or_index: &str) -> bool {
        if let Some(ref name) = self.name {
            if name == name_or_index {
                return true;
            }
        }

        if let Ok(idx) = name_or_index.parse::<usize>() {
            return idx == self.index;
        }

        false
    }
}

/// Expand Docker build-arg references in a `FROM` target string.
///
/// Supports the forms Docker accepts in `FROM` lines: `${VAR}`,
/// `${VAR:-default}` (default when unset or empty), `${VAR:+alt}` (alt
/// when set and non-empty), and bare `$VAR`. Unknown variables expand to
/// the empty string, matching `docker build`.
fn expand_from_args(input: &str, vars: &HashMap<String, String>) -> String {
    let mut out = String::with_capacity(input.len());
    let mut chars = input.char_indices().peekable();
    while let Some((_, c)) = chars.next() {
        if c != '$' {
            out.push(c);
            continue;
        }
        match chars.peek() {
            Some(&(_, '{')) => {
                chars.next(); // consume '{'
                let mut body = String::new();
                let mut closed = false;
                for (_, bc) in chars.by_ref() {
                    if bc == '}' {
                        closed = true;
                        break;
                    }
                    body.push(bc);
                }
                if !closed {
                    // Unterminated `${...` — emit verbatim.
                    out.push_str("${");
                    out.push_str(&body);
                    continue;
                }
                if let Some((name, default)) = body.split_once(":-") {
                    match vars.get(name).filter(|v| !v.is_empty()) {
                        Some(v) => out.push_str(v),
                        None => out.push_str(default),
                    }
                } else if let Some((name, alt)) = body.split_once(":+") {
                    if vars.get(name).is_some_and(|v| !v.is_empty()) {
                        out.push_str(alt);
                    }
                } else {
                    out.push_str(vars.get(&body).map_or("", String::as_str));
                }
            }
            Some(&(_, next)) if next.is_ascii_alphabetic() || next == '_' => {
                let mut name = String::new();
                while let Some(&(_, nc)) = chars.peek() {
                    if nc.is_ascii_alphanumeric() || nc == '_' {
                        name.push(nc);
                        chars.next();
                    } else {
                        break;
                    }
                }
                out.push_str(vars.get(&name).map_or("", String::as_str));
            }
            // BuildKit escape: `$$` is a literal dollar sign.
            Some(&(_, '$')) => {
                chars.next();
                out.push('$');
            }
            _ => out.push('$'),
        }
    }
    out
}

/// Quote-tracking state while scanning an ARG/ENV instruction, carried
/// across line continuations (quoted values may span lines).
#[derive(Debug, Clone, Copy, Default)]
struct QuoteState {
    in_double: bool,
    in_single: bool,
}

impl QuoteState {
    fn in_quotes(self) -> bool {
        self.in_double || self.in_single
    }
}

/// Which multi-line construct the normalizer is currently inside.
enum LineState {
    /// Start of a fresh logical instruction.
    Top,
    /// Continuation of an ARG/ENV instruction (with carried quote state).
    ArgEnv(QuoteState),
    /// Continuation of any other instruction (e.g. RUN) — copied verbatim.
    Other,
}

/// True if `body` (a line without its terminator) ends in a Dockerfile
/// line continuation: a `\` followed only by spaces/tabs.
fn ends_with_continuation(body: &str) -> bool {
    body.trim_end_matches([' ', '\t']).ends_with('\\')
}

/// Rewrite unquoted-empty assignments (`KEY=` followed by whitespace or
/// end-of-line) on one line of an ARG/ENV instruction to the quoted-empty
/// spelling `KEY=""`, appending the result to `out`.
///
/// Returns `true` if the instruction continues on the next line (trailing
/// `\` outside quotes, an escaped newline inside a quoted string, or a
/// still-open quoted string).
fn rewrite_empty_assignments_in_line(
    body: &str,
    quotes: &mut QuoteState,
    out: &mut String,
    changed: &mut bool,
) -> bool {
    let mut continues = false;
    let mut prev_is_key_char = false;
    let mut chars = body.char_indices().peekable();

    while let Some((idx, c)) = chars.next() {
        if quotes.in_quotes() {
            match c {
                '\\' => {
                    out.push(c);
                    if let Some((_, esc)) = chars.next() {
                        out.push(esc);
                    } else {
                        // `\` at end of line inside a string: the grammar's
                        // `escape` rule consumes the newline, so the string
                        // (and the instruction) continues on the next line.
                        continues = true;
                    }
                }
                '"' if quotes.in_double => {
                    quotes.in_double = false;
                    out.push(c);
                }
                '\'' if quotes.in_single => {
                    quotes.in_single = false;
                    out.push(c);
                }
                _ => out.push(c),
            }
            prev_is_key_char = false;
            continue;
        }

        match c {
            '"' => {
                quotes.in_double = true;
                out.push(c);
                prev_is_key_char = false;
            }
            '\'' => {
                quotes.in_single = true;
                out.push(c);
                prev_is_key_char = false;
            }
            // Line continuation: `\` followed only by trailing whitespace.
            '\\' if body[idx + 1..].chars().all(|w| w == ' ' || w == '\t') => {
                continues = true;
                out.push_str(&body[idx..]);
                break;
            }
            '=' if prev_is_key_char => {
                out.push(c);
                // Empty value only when the `=` is followed by whitespace or
                // end-of-line. `KEY=\` (line continuation directly after the
                // `=`) is left alone: the value may continue on the next line.
                if matches!(chars.peek(), None | Some(&(_, ' ' | '\t'))) {
                    out.push_str("\"\"");
                    *changed = true;
                }
                prev_is_key_char = false;
            }
            _ => {
                out.push(c);
                prev_is_key_char = c.is_ascii_alphanumeric() || c == '_';
            }
        }
    }

    // An unterminated quoted string spans the raw newline in the upstream
    // grammar (`inner` matches ANY except `"`/`\`/two control chars), so the
    // instruction continues either way.
    continues || quotes.in_quotes()
}

/// Rewrite Docker-valid unquoted-empty assignments in ARG and ENV
/// instructions to their quoted-empty spelling before upstream parsing.
///
/// The `dockerfile-parser` pest grammar rejects `ARG NAME=` / `ENV NAME=` /
/// `ENV A= B=c`: its value rules (`arg_value` and `env_pair_value`, both
/// `any_whitespace`) require at least one character after `=`, while real
/// Docker (legacy builder and `BuildKit`) accepts an explicitly empty value —
/// `cross` 0.2.5 generates `ARG CROSS_DEB_ARCH=`. The grammar DOES accept
/// the quoted-empty form (`NAME=""`, parsed to an empty-string value), so
/// this pass rewrites `KEY=` → `KEY=""` inside ARG/ENV instructions only:
/// quoted regions are skipped, non-ARG/ENV instructions (and their
/// continuation lines) are copied verbatim, and line structure is preserved
/// so parse-error line numbers stay meaningful.
fn normalize_empty_assignments(content: &str) -> std::borrow::Cow<'_, str> {
    let mut out = String::with_capacity(content.len() + 8);
    let mut changed = false;
    let mut state = LineState::Top;

    for raw_line in content.split_inclusive('\n') {
        // Split the body from its terminator (`\n` or `\r\n`; the final line
        // may have none).
        let (body, terminator) = match raw_line.strip_suffix('\n') {
            Some(rest) => match rest.strip_suffix('\r') {
                Some(rest) => (rest, "\r\n"),
                None => (rest, "\n"),
            },
            None => (raw_line, ""),
        };

        state = match state {
            LineState::Top => {
                let trimmed = body.trim_start();
                let keyword_len = trimmed
                    .chars()
                    .take_while(char::is_ascii_alphabetic)
                    .count();
                let keyword = &trimmed[..keyword_len];
                let after_keyword = trimmed[keyword_len..].chars().next();
                let is_arg_env = (keyword.eq_ignore_ascii_case("arg")
                    || keyword.eq_ignore_ascii_case("env")
                    || keyword.eq_ignore_ascii_case("label"))
                    && matches!(after_keyword, Some(' ' | '\t' | '\\'));

                if is_arg_env {
                    let prefix_len = body.len() - trimmed.len() + keyword_len;
                    out.push_str(&body[..prefix_len]);
                    let mut quotes = QuoteState::default();
                    if rewrite_empty_assignments_in_line(
                        &trimmed[keyword_len..],
                        &mut quotes,
                        &mut out,
                        &mut changed,
                    ) {
                        LineState::ArgEnv(quotes)
                    } else {
                        LineState::Top
                    }
                } else {
                    out.push_str(body);
                    let is_blank_or_comment = trimmed.is_empty() || trimmed.starts_with('#');
                    if !is_blank_or_comment && ends_with_continuation(body) {
                        LineState::Other
                    } else {
                        LineState::Top
                    }
                }
            }
            LineState::ArgEnv(mut quotes) => {
                let trimmed = body.trim_start();
                if !quotes.in_quotes() && (trimmed.is_empty() || trimmed.starts_with('#')) {
                    // Comment and empty lines may follow a line continuation
                    // (grammar `arg_ws`); the instruction resumes after them.
                    out.push_str(body);
                    LineState::ArgEnv(quotes)
                } else if rewrite_empty_assignments_in_line(
                    body,
                    &mut quotes,
                    &mut out,
                    &mut changed,
                ) {
                    LineState::ArgEnv(quotes)
                } else {
                    LineState::Top
                }
            }
            LineState::Other => {
                out.push_str(body);
                let trimmed = body.trim_start();
                let is_blank_or_comment = trimmed.is_empty() || trimmed.starts_with('#');
                if is_blank_or_comment || ends_with_continuation(body) {
                    LineState::Other
                } else {
                    LineState::Top
                }
            }
        };

        out.push_str(terminator);
    }

    if changed {
        std::borrow::Cow::Owned(out)
    } else {
        std::borrow::Cow::Borrowed(content)
    }
}

/// A parsed Dockerfile
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dockerfile {
    /// Global ARG instructions that appear before the first FROM
    pub global_args: Vec<ArgInstruction>,

    /// Build stages
    pub stages: Vec<Stage>,
}

impl Dockerfile {
    /// Expand pre-FROM `ARG`s in every stage's `FROM` target.
    ///
    /// Docker semantics: only ARGs declared BEFORE the first `FROM`
    /// participate in `FROM`-line expansion (`FROM ${BASE_IMAGE}` /
    /// `FROM img:${TAG:-latest}`), with `--build-arg` values overriding
    /// their defaults. The parser can't do this (it has no build args), so
    /// targets containing `$` end up classified as [`DockerfileFromTarget::Stage`]
    /// — and struct-consuming backends then fail with `Stage '${BASE_IMAGE}'
    /// not found`. Call this with the effective build args before handing
    /// the Dockerfile to a backend.
    ///
    /// Expanded targets are re-classified: `scratch`, a previously declared
    /// stage name, an OCI image reference, or (still) a stage string. A
    /// target that expands to an empty string is left untouched so the
    /// eventual error names the unexpanded variable instead of a blank.
    pub fn resolve_from_args(&mut self, build_args: &HashMap<String, String>) {
        // Effective FROM-scope variables: declared global ARGs only,
        // defaults overridden by matching build args (an undeclared build
        // arg does NOT leak into FROM lines, per Docker).
        let mut vars: HashMap<String, String> = HashMap::new();
        for arg in &self.global_args {
            let value = build_args
                .get(&arg.name)
                .cloned()
                .or_else(|| arg.default.clone())
                .unwrap_or_default();
            vars.insert(arg.name.clone(), value);
        }

        let mut known_stage_names: std::collections::HashSet<String> =
            std::collections::HashSet::new();
        for stage in &mut self.stages {
            if let DockerfileFromTarget::Stage(raw) = &stage.base_image {
                if raw.contains('$') {
                    let expanded = expand_from_args(raw, &vars);
                    if !expanded.trim().is_empty() {
                        let mut target = DockerfileFromTarget::parse(&expanded);
                        // Same post-hoc stage promotion as `from_raw`: a bare
                        // name that matches an earlier stage alias is a stage
                        // reference even though it parses as an OCI ref.
                        if matches!(target, DockerfileFromTarget::Image(_))
                            && known_stage_names.contains(expanded.trim())
                        {
                            target = DockerfileFromTarget::Stage(expanded.trim().to_string());
                        }
                        stage.base_image = target;
                    }
                }
            }
            if let Some(name) = &stage.name {
                known_stage_names.insert(name.clone());
            }
        }
    }

    /// Parse a Dockerfile from a string
    ///
    /// # Errors
    ///
    /// Returns an error if the Dockerfile content is malformed or contains invalid instructions.
    pub fn parse(content: &str) -> Result<Self> {
        // The upstream grammar rejects Docker-valid unquoted-empty
        // assignments (`ARG NAME=` / `ENV NAME=`); rewrite them to the
        // quoted-empty spelling it accepts. See `normalize_empty_assignments`.
        let content = normalize_empty_assignments(content);
        let raw = RawDockerfile::parse(&content).map_err(|e| BuildError::DockerfileParse {
            message: e.to_string(),
            line: 1,
        })?;

        Self::from_raw(raw)
    }

    /// Parse a Dockerfile from a file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or the Dockerfile is malformed.
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let content =
            std::fs::read_to_string(path.as_ref()).map_err(|e| BuildError::ContextRead {
                path: path.as_ref().to_path_buf(),
                source: e,
            })?;

        Self::parse(&content)
    }

    /// Convert from the raw dockerfile-parser types to our internal representation
    fn from_raw(raw: RawDockerfile) -> Result<Self> {
        let mut global_args = Vec::new();
        let mut stages = Vec::new();
        let mut current_stage: Option<Stage> = None;
        let mut stage_index = 0;
        // Track stage names declared so far so subsequent FROM lines can
        // resolve `FROM <name>` to a stage reference even when the name
        // is also a syntactically-valid OCI reference (e.g. `FROM builder`).
        let mut known_stage_names: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        for instruction in raw.instructions {
            match &instruction {
                RawInstruction::From(from) => {
                    // Save previous stage if any
                    if let Some(stage) = current_stage.take() {
                        stages.push(stage);
                    }

                    // Parse base image
                    let raw_from = from.image.content.trim().to_string();
                    let mut base_image = DockerfileFromTarget::parse(&raw_from);

                    // Post-hoc stage promotion: `DockerfileFromTarget::parse`
                    // delegates to the OCI grammar, which accepts bare names
                    // like `builder` as valid image refs. If the raw FROM
                    // text matches a previously-declared stage name, swap
                    // the parsed `Image` for a `Stage` reference.
                    if matches!(base_image, DockerfileFromTarget::Image(_))
                        && known_stage_names.contains(&raw_from)
                    {
                        base_image = DockerfileFromTarget::Stage(raw_from.clone());
                    }

                    // Get alias (stage name) - the field is `alias` not `image_alias`
                    let name = from.alias.as_ref().map(|a| a.content.clone());

                    if let Some(ref n) = name {
                        known_stage_names.insert(n.clone());
                    }

                    // Get platform flag
                    let platform = from
                        .flags
                        .iter()
                        .find(|f| f.name.content.as_str() == "platform")
                        .map(|f| f.value.to_string());

                    current_stage = Some(Stage {
                        index: stage_index,
                        name,
                        base_image,
                        platform,
                        instructions: Vec::new(),
                    });

                    stage_index += 1;
                }

                RawInstruction::Arg(arg) => {
                    let arg_inst = ArgInstruction {
                        name: arg.name.to_string(),
                        default: arg.value.as_ref().map(std::string::ToString::to_string),
                    };

                    if current_stage.is_none() {
                        global_args.push(arg_inst);
                    } else if let Some(ref mut stage) = current_stage {
                        stage.instructions.push(Instruction::Arg(arg_inst));
                    }
                }

                _ => {
                    if let Some(ref mut stage) = current_stage {
                        if let Some(inst) = Self::convert_instruction(&instruction)? {
                            stage.instructions.push(inst);
                        }
                    }
                }
            }
        }

        // Don't forget the last stage
        if let Some(stage) = current_stage {
            stages.push(stage);
        }

        // Resolve stage references in COPY --from
        // (This is currently a no-op as stage references are already correct,
        // but kept for future validation/resolution logic)
        let _stage_names: HashMap<String, usize> = stages
            .iter()
            .filter_map(|s| s.name.as_ref().map(|n| (n.clone(), s.index)))
            .collect();
        let _num_stages = stages.len();

        Ok(Self {
            global_args,
            stages,
        })
    }

    /// Convert a raw instruction to our internal representation
    #[allow(clippy::too_many_lines)]
    fn convert_instruction(raw: &RawInstruction) -> Result<Option<Instruction>> {
        let instruction = match raw {
            RawInstruction::From(_) => {
                return Ok(None);
            }

            RawInstruction::Run(run) => {
                let command = match &run.expr {
                    dockerfile_parser::ShellOrExecExpr::Shell(s) => {
                        ShellOrExec::Shell(s.to_string())
                    }
                    dockerfile_parser::ShellOrExecExpr::Exec(args) => {
                        ShellOrExec::Exec(args.elements.iter().map(|s| s.content.clone()).collect())
                    }
                };

                Instruction::Run(RunInstruction {
                    command,
                    mounts: Vec::new(),
                    network: None,
                    security: None,
                    env: HashMap::new(),
                })
            }

            RawInstruction::Copy(copy) => {
                let from = copy
                    .flags
                    .iter()
                    .find(|f| f.name.content.as_str() == "from")
                    .map(|f| f.value.to_string());

                let chown = copy
                    .flags
                    .iter()
                    .find(|f| f.name.content.as_str() == "chown")
                    .map(|f| f.value.to_string());

                let chmod = copy
                    .flags
                    .iter()
                    .find(|f| f.name.content.as_str() == "chmod")
                    .map(|f| f.value.to_string());

                let link = copy.flags.iter().any(|f| f.name.content.as_str() == "link");

                // The external parser separates sources and destination already.
                let sources: Vec<String> = copy
                    .sources
                    .iter()
                    .map(std::string::ToString::to_string)
                    .collect();
                let destination = copy.destination.to_string();

                Instruction::Copy(CopyInstruction {
                    sources,
                    destination,
                    from,
                    chown,
                    chmod,
                    link,
                    exclude: Vec::new(),
                })
            }

            RawInstruction::Entrypoint(ep) => {
                let command = match &ep.expr {
                    dockerfile_parser::ShellOrExecExpr::Shell(s) => {
                        ShellOrExec::Shell(s.to_string())
                    }
                    dockerfile_parser::ShellOrExecExpr::Exec(args) => {
                        ShellOrExec::Exec(args.elements.iter().map(|s| s.content.clone()).collect())
                    }
                };
                Instruction::Entrypoint(command)
            }

            RawInstruction::Cmd(cmd) => {
                let command = match &cmd.expr {
                    dockerfile_parser::ShellOrExecExpr::Shell(s) => {
                        ShellOrExec::Shell(s.to_string())
                    }
                    dockerfile_parser::ShellOrExecExpr::Exec(args) => {
                        ShellOrExec::Exec(args.elements.iter().map(|s| s.content.clone()).collect())
                    }
                };
                Instruction::Cmd(command)
            }

            RawInstruction::Env(env) => {
                let mut vars = HashMap::new();
                for var in &env.vars {
                    vars.insert(var.key.to_string(), var.value.to_string());
                }
                Instruction::Env(EnvInstruction { vars })
            }

            RawInstruction::Label(label) => {
                let mut labels = HashMap::new();
                for l in &label.labels {
                    labels.insert(l.name.to_string(), l.value.to_string());
                }
                Instruction::Label(labels)
            }

            RawInstruction::Arg(arg) => Instruction::Arg(ArgInstruction {
                name: arg.name.to_string(),
                default: arg.value.as_ref().map(std::string::ToString::to_string),
            }),

            RawInstruction::Misc(misc) => {
                let instruction_upper = misc.instruction.content.to_uppercase();
                match instruction_upper.as_str() {
                    "WORKDIR" => Instruction::Workdir(misc.arguments.to_string()),

                    "USER" => Instruction::User(misc.arguments.to_string()),

                    "VOLUME" => {
                        let args = misc.arguments.to_string();
                        let volumes = if args.trim().starts_with('[') {
                            serde_json::from_str(&args).unwrap_or_else(|_| vec![args])
                        } else {
                            args.split_whitespace().map(String::from).collect()
                        };
                        Instruction::Volume(volumes)
                    }

                    "EXPOSE" => {
                        let args = misc.arguments.to_string();
                        let (port_str, protocol) = if let Some((p, proto)) = args.split_once('/') {
                            let proto = match proto.to_lowercase().as_str() {
                                "udp" => ExposeProtocol::Udp,
                                _ => ExposeProtocol::Tcp,
                            };
                            (p, proto)
                        } else {
                            (args.as_str(), ExposeProtocol::Tcp)
                        };

                        let port: u16 = port_str.trim().parse().map_err(|_| {
                            BuildError::InvalidInstruction {
                                instruction: "EXPOSE".to_string(),
                                reason: format!("Invalid port number: {port_str}"),
                            }
                        })?;

                        Instruction::Expose(ExposeInstruction { port, protocol })
                    }

                    "SHELL" => {
                        let args = misc.arguments.to_string();
                        let shell: Vec<String> = serde_json::from_str(&args).map_err(|_| {
                            BuildError::InvalidInstruction {
                                instruction: "SHELL".to_string(),
                                reason: "SHELL requires a JSON array".to_string(),
                            }
                        })?;
                        Instruction::Shell(shell)
                    }

                    "STOPSIGNAL" => Instruction::Stopsignal(misc.arguments.to_string()),

                    "HEALTHCHECK" => {
                        let args = misc.arguments.to_string().trim().to_string();
                        if args.eq_ignore_ascii_case("NONE") {
                            Instruction::Healthcheck(HealthcheckInstruction::None)
                        } else {
                            let command = if let Some(stripped) = args.strip_prefix("CMD ") {
                                ShellOrExec::Shell(stripped.to_string())
                            } else {
                                ShellOrExec::Shell(args)
                            };
                            Instruction::Healthcheck(HealthcheckInstruction::cmd(command))
                        }
                    }

                    "ONBUILD" => {
                        tracing::warn!("ONBUILD instruction parsing not fully implemented");
                        return Ok(None);
                    }

                    "MAINTAINER" => {
                        let mut labels = HashMap::new();
                        labels.insert("maintainer".to_string(), misc.arguments.to_string());
                        Instruction::Label(labels)
                    }

                    "ADD" => {
                        let args = misc.arguments.to_string();
                        let parts: Vec<String> =
                            args.split_whitespace().map(String::from).collect();

                        if parts.len() < 2 {
                            return Err(BuildError::InvalidInstruction {
                                instruction: "ADD".to_string(),
                                reason: "ADD requires at least one source and a destination"
                                    .to_string(),
                            });
                        }

                        let (sources, dest) = parts.split_at(parts.len() - 1);
                        let destination = dest.first().cloned().unwrap_or_default();

                        Instruction::Add(AddInstruction {
                            sources: sources.to_vec(),
                            destination,
                            chown: None,
                            chmod: None,
                            link: false,
                            checksum: None,
                            keep_git_dir: false,
                        })
                    }

                    other => {
                        tracing::warn!("Unknown Dockerfile instruction: {}", other);
                        return Ok(None);
                    }
                }
            }
        };

        Ok(Some(instruction))
    }

    /// Get a stage by name or index
    #[must_use]
    pub fn get_stage(&self, name_or_index: &str) -> Option<&Stage> {
        self.stages.iter().find(|s| s.matches(name_or_index))
    }

    /// Get the final stage (last one in the Dockerfile)
    #[must_use]
    pub fn final_stage(&self) -> Option<&Stage> {
        self.stages.last()
    }

    /// Get all stage names/identifiers
    #[must_use]
    pub fn stage_names(&self) -> Vec<String> {
        self.stages.iter().map(Stage::identifier).collect()
    }

    /// Check if a stage exists
    #[must_use]
    pub fn has_stage(&self, name_or_index: &str) -> bool {
        self.get_stage(name_or_index).is_some()
    }

    /// Returns the number of stages
    #[must_use]
    pub fn stage_count(&self) -> usize {
        self.stages.len()
    }
}

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

    #[test]
    fn test_parse_simple_dockerfile() {
        let content = r#"
FROM alpine:3.18
RUN apk add --no-cache curl
COPY . /app
WORKDIR /app
CMD ["./app"]
"#;

        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.stages.len(), 1);

        let stage = &dockerfile.stages[0];
        assert_eq!(stage.index, 0);
        assert!(stage.name.is_none());
        assert_eq!(stage.instructions.len(), 4);
    }

    #[test]
    fn test_parse_multistage_dockerfile() {
        let content = r#"
FROM golang:1.21 AS builder
WORKDIR /src
COPY . .
RUN go build -o /app

FROM alpine:3.18
COPY --from=builder /app /app
CMD ["/app"]
"#;

        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.stages.len(), 2);

        let builder = &dockerfile.stages[0];
        assert_eq!(builder.name, Some("builder".to_string()));

        let runtime = &dockerfile.stages[1];
        assert!(runtime.name.is_none());

        let copy = runtime
            .instructions
            .iter()
            .find(|i| matches!(i, Instruction::Copy(_)));
        assert!(copy.is_some());
        if let Some(Instruction::Copy(c)) = copy {
            assert_eq!(c.from, Some("builder".to_string()));
        }
    }

    #[test]
    fn test_parse_copy_from_external_image_reference() {
        // `COPY --from=<external-image>` must capture the full registry-
        // qualified reference in `CopyInstruction.from` so the buildah
        // backend can pull and forward it to `buildah copy --from=...`.
        let content = r"
FROM alpine:3.18
COPY --from=ghcr.io/astral-sh/uv:0.5.0 /uv /usr/local/bin/uv
RUN /usr/local/bin/uv --version
";

        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.stages.len(), 1);

        let copy = dockerfile.stages[0]
            .instructions
            .iter()
            .find_map(|i| {
                if let Instruction::Copy(c) = i {
                    Some(c)
                } else {
                    None
                }
            })
            .expect("COPY instruction present");

        assert_eq!(
            copy.from,
            Some("ghcr.io/astral-sh/uv:0.5.0".to_string()),
            "external image ref must be preserved verbatim in CopyInstruction.from",
        );
        assert_eq!(copy.sources, vec!["/uv".to_string()]);
        assert_eq!(copy.destination, "/usr/local/bin/uv".to_string());

        // The parser must NOT treat the external ref as a stage; only the
        // top-level `FROM alpine:3.18` should appear in the stage list.
        assert!(dockerfile.get_stage("ghcr.io/astral-sh/uv:0.5.0").is_none());
    }

    #[test]
    fn expand_from_args_all_forms() {
        let vars: HashMap<String, String> = [
            ("BASE".to_string(), "ghcr.io/org/img".to_string()),
            ("TAG".to_string(), "1.2".to_string()),
            ("EMPTY".to_string(), String::new()),
        ]
        .into_iter()
        .collect();

        assert_eq!(
            expand_from_args("${BASE}:${TAG}", &vars),
            "ghcr.io/org/img:1.2"
        );
        assert_eq!(expand_from_args("$BASE", &vars), "ghcr.io/org/img");
        assert_eq!(
            expand_from_args("img:${MISSING:-latest}", &vars),
            "img:latest"
        );
        assert_eq!(
            expand_from_args("img:${EMPTY:-fallback}", &vars),
            "img:fallback"
        );
        assert_eq!(expand_from_args("img:${TAG:+pinned}", &vars), "img:pinned");
        assert_eq!(expand_from_args("img:${MISSING:+pinned}", &vars), "img:");
        assert_eq!(expand_from_args("${MISSING}", &vars), "");
        // BuildKit `$$` escape yields a literal dollar; a trailing `$`
        // passes through.
        assert_eq!(expand_from_args("a$$b", &vars), "a$b");
        assert_eq!(expand_from_args("price$", &vars), "price$");
    }

    #[test]
    fn resolve_from_args_expands_from_lines() {
        let content = r"
ARG BASE_IMAGE=ghcr.io/org/alpine:latest
ARG BASE_TAG=latest
FROM ${BASE_IMAGE} AS builder
RUN echo hi
FROM ghcr.io/org/alpine:${BASE_TAG}
COPY --from=builder /x /x
";
        let mut dockerfile = Dockerfile::parse(content).unwrap();
        // Pre-resolution both FROM targets are (mis)classified as stages.
        assert!(dockerfile.stages[0].base_image.is_stage());
        assert!(dockerfile.stages[1].base_image.is_stage());

        let build_args: HashMap<String, String> = [("BASE_TAG".to_string(), "3.20".to_string())]
            .into_iter()
            .collect();
        dockerfile.resolve_from_args(&build_args);

        match &dockerfile.stages[0].base_image {
            DockerfileFromTarget::Image(r) => {
                assert_eq!(r.to_string(), "ghcr.io/org/alpine:latest");
            }
            other => panic!("stage 0 not resolved to an image: {other:?}"),
        }
        match &dockerfile.stages[1].base_image {
            DockerfileFromTarget::Image(r) => {
                // The build arg overrides the declared default.
                assert_eq!(r.to_string(), "ghcr.io/org/alpine:3.20");
            }
            other => panic!("stage 1 not resolved to an image: {other:?}"),
        }
    }

    #[test]
    fn resolve_from_args_keeps_stage_references() {
        let content = r"
ARG BASE=ghcr.io/org/alpine:latest
FROM ${BASE} AS builder
RUN echo hi
FROM builder
RUN echo again
";
        let mut dockerfile = Dockerfile::parse(content).unwrap();
        dockerfile.resolve_from_args(&HashMap::new());
        assert!(matches!(
            &dockerfile.stages[0].base_image,
            DockerfileFromTarget::Image(_)
        ));
        // `FROM builder` must stay a stage reference.
        assert_eq!(
            dockerfile.stages[1].base_image,
            DockerfileFromTarget::Stage("builder".to_string())
        );
    }

    #[test]
    fn test_parse_global_args() {
        let content = r#"
ARG BASE_IMAGE=alpine:3.18
FROM ${BASE_IMAGE}
RUN echo "hello"
"#;

        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.global_args.len(), 1);
        assert_eq!(dockerfile.global_args[0].name, "BASE_IMAGE");
        assert_eq!(
            dockerfile.global_args[0].default,
            Some("alpine:3.18".to_string())
        );
    }

    #[test]
    fn test_get_stage_by_name() {
        let content = r#"
FROM alpine:3.18 AS base
RUN echo "base"

FROM base AS builder
RUN echo "builder"
"#;

        let dockerfile = Dockerfile::parse(content).unwrap();

        let base = dockerfile.get_stage("base");
        assert!(base.is_some());
        assert_eq!(base.unwrap().index, 0);

        let builder = dockerfile.get_stage("builder");
        assert!(builder.is_some());
        assert_eq!(builder.unwrap().index, 1);

        let stage_0 = dockerfile.get_stage("0");
        assert!(stage_0.is_some());
        assert_eq!(stage_0.unwrap().name, Some("base".to_string()));
    }

    #[test]
    fn test_final_stage() {
        let content = r#"
FROM alpine:3.18 AS builder
RUN echo "builder"

FROM scratch
COPY --from=builder /app /app
"#;

        let dockerfile = Dockerfile::parse(content).unwrap();
        let final_stage = dockerfile.final_stage().unwrap();

        assert_eq!(final_stage.index, 1);
        assert!(matches!(
            final_stage.base_image,
            DockerfileFromTarget::Scratch
        ));
    }

    #[test]
    fn test_parse_env_instruction() {
        let content = r"
FROM alpine
ENV FOO=bar BAZ=qux
";

        let dockerfile = Dockerfile::parse(content).unwrap();
        let stage = &dockerfile.stages[0];

        let env = stage
            .instructions
            .iter()
            .find(|i| matches!(i, Instruction::Env(_)));
        assert!(env.is_some());

        if let Some(Instruction::Env(e)) = env {
            assert_eq!(e.vars.get("FOO"), Some(&"bar".to_string()));
            assert_eq!(e.vars.get("BAZ"), Some(&"qux".to_string()));
        }
    }

    /// Extract the ARG instructions of a stage as (name, default) pairs.
    fn stage_args(stage: &Stage) -> Vec<(String, Option<String>)> {
        stage
            .instructions
            .iter()
            .filter_map(|i| {
                if let Instruction::Arg(a) = i {
                    Some((a.name.clone(), a.default.clone()))
                } else {
                    None
                }
            })
            .collect()
    }

    #[test]
    fn arg_empty_unquoted_default_parses_as_defined_empty() {
        // `cross` 0.2.5 generates `ARG CROSS_DEB_ARCH=` — Docker-valid
        // (defined, empty default), distinct from `ARG NAME` (no default).
        let content = "FROM alpine:3.18\nARG CROSS_DEB_ARCH=\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(
            stage_args(&dockerfile.stages[0]),
            vec![("CROSS_DEB_ARCH".to_string(), Some(String::new()))],
        );
    }

    #[test]
    fn arg_empty_unquoted_default_parses_as_global_arg() {
        // Pre-FROM position: must land in `global_args` with a defined-empty
        // default so `resolve_from_args` sees "" rather than unset.
        let content = "ARG EMPTYDEFAULT=\nFROM alpine:3.18\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.global_args.len(), 1);
        assert_eq!(dockerfile.global_args[0].name, "EMPTYDEFAULT");
        assert_eq!(dockerfile.global_args[0].default, Some(String::new()));
    }

    #[test]
    fn label_empty_unquoted_value_parses() {
        // Same upstream-grammar defect class as ARG/ENV (`label_value` needs
        // ≥1 char after `=`); the normalizer rewrites `LABEL k=` → `LABEL k=""`.
        let content = "FROM alpine:3.18\nLABEL emptyone= other=\"x\"\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.stages.len(), 1);
    }

    #[test]
    fn arg_quoted_empty_default_parses_as_defined_empty() {
        let content = "FROM alpine:3.18\nARG NAME=\"\"\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(
            stage_args(&dockerfile.stages[0]),
            vec![("NAME".to_string(), Some(String::new()))],
        );
    }

    #[test]
    fn arg_no_default_and_plain_default_still_parse() {
        let content = "FROM alpine:3.18\nARG X\nARG Y=z\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(
            stage_args(&dockerfile.stages[0]),
            vec![
                ("X".to_string(), None),
                ("Y".to_string(), Some("z".to_string())),
            ],
        );
    }

    #[test]
    fn env_empty_values_parse() {
        // `ENV NAME=` and a trailing empty pair in a multi-pair ENV are both
        // Docker-valid (defined, empty).
        let content = "FROM alpine:3.18\nENV EMPTYONE=\nENV A= B=c\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        let stage = &dockerfile.stages[0];

        let envs: Vec<&EnvInstruction> = stage
            .instructions
            .iter()
            .filter_map(|i| {
                if let Instruction::Env(e) = i {
                    Some(e)
                } else {
                    None
                }
            })
            .collect();
        assert_eq!(envs.len(), 2);
        assert_eq!(envs[0].vars.get("EMPTYONE"), Some(&String::new()));
        assert_eq!(envs[1].vars.get("A"), Some(&String::new()));
        assert_eq!(envs[1].vars.get("B"), Some(&"c".to_string()));
    }

    #[test]
    fn env_quoted_value_containing_equals_is_untouched() {
        // The quoted `x= ` must not be rewritten by empty-assignment
        // normalization; only the trailing bare `B=` is.
        let content = "FROM alpine:3.18\nENV A=\"x= \" B=\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        let stage = &dockerfile.stages[0];
        if let Some(Instruction::Env(e)) = stage
            .instructions
            .iter()
            .find(|i| matches!(i, Instruction::Env(_)))
        {
            assert_eq!(e.vars.get("A"), Some(&"x= ".to_string()));
            assert_eq!(e.vars.get("B"), Some(&String::new()));
        } else {
            panic!("ENV instruction missing");
        }
    }

    #[test]
    fn run_shell_content_with_trailing_equals_is_untouched() {
        // A `KEY=` token inside RUN shell content (including on a
        // continuation line) is shell text — normalization must not
        // rewrite it into `KEY=""`.
        let content = "FROM alpine:3.18\nRUN export FOO= && \\\n    BAR= true\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        let stage = &dockerfile.stages[0];
        if let Some(Instruction::Run(run)) = stage
            .instructions
            .iter()
            .find(|i| matches!(i, Instruction::Run(_)))
        {
            let ShellOrExec::Shell(cmd) = &run.command else {
                panic!("expected shell-form RUN");
            };
            assert!(cmd.contains("FOO="), "cmd: {cmd}");
            assert!(!cmd.contains("FOO=\"\""), "cmd: {cmd}");
            assert!(cmd.contains("BAR="), "cmd: {cmd}");
            assert!(!cmd.contains("BAR=\"\""), "cmd: {cmd}");
        } else {
            panic!("RUN instruction missing");
        }
    }

    #[test]
    fn env_empty_value_on_continuation_line_parses() {
        let content = "FROM alpine:3.18\nENV A=1 \\\n    B=\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        let stage = &dockerfile.stages[0];
        if let Some(Instruction::Env(e)) = stage
            .instructions
            .iter()
            .find(|i| matches!(i, Instruction::Env(_)))
        {
            assert_eq!(e.vars.get("A"), Some(&"1".to_string()));
            assert_eq!(e.vars.get("B"), Some(&String::new()));
        } else {
            panic!("ENV instruction missing");
        }
    }

    #[test]
    fn normalize_empty_assignments_rewrites_only_arg_env() {
        // ARG / ENV empty assignments get the quoted-empty spelling.
        assert_eq!(normalize_empty_assignments("ARG A=\n"), "ARG A=\"\"\n");
        assert_eq!(
            normalize_empty_assignments("ENV A= B=c\n"),
            "ENV A=\"\" B=c\n"
        );
        // Quoted regions are skipped; only the bare trailing `B=` rewritten.
        assert_eq!(
            normalize_empty_assignments("ENV A=\"x= \" B=\n"),
            "ENV A=\"x= \" B=\"\"\n"
        );
        // Continuation lines of an ENV instruction are rewritten too.
        assert_eq!(
            normalize_empty_assignments("ENV A=1 \\\n    B=\n"),
            "ENV A=1 \\\n    B=\"\"\n"
        );
        // `KEY=\` (continuation directly after `=`) is left for the parser —
        // the value may continue on the next line.
        assert_eq!(
            normalize_empty_assignments("ARG A=\\\nx\n"),
            "ARG A=\\\nx\n"
        );
        // Non-ARG/ENV instructions and their continuation lines are verbatim.
        assert_eq!(
            normalize_empty_assignments("RUN export FOO= && \\\n    BAR= true\n"),
            "RUN export FOO= && \\\n    BAR= true\n"
        );
        // A keyword prefix is not enough — `ENVIRONMENT=` is not ENV.
        assert_eq!(
            normalize_empty_assignments("ENVIRONMENT= foo\n"),
            "ENVIRONMENT= foo\n"
        );
        // Untouched content comes back borrowed (no reallocation).
        assert!(matches!(
            normalize_empty_assignments("FROM alpine\nRUN echo hi\n"),
            std::borrow::Cow::Borrowed(_)
        ));
        // CRLF and a missing final newline are preserved.
        assert_eq!(
            normalize_empty_assignments("ARG A=\r\nARG B="),
            "ARG A=\"\"\r\nARG B=\"\""
        );
    }

    #[test]
    fn cross_generated_dockerfile_parses_end_to_end() {
        // Minimal mirror of the preamble `cross` 0.2.5 generates
        // (live failure: ZLayer build.yml run 19200 job 105756).
        let content = "FROM cross/x86_64-unknown-linux-musl:0.2.5\n\
                       ARG CROSS_DEB_ARCH=\n\
                       ARG CROSS_CMD\n\
                       RUN eval \"${CROSS_CMD}\"\n";
        let dockerfile = Dockerfile::parse(content).unwrap();
        assert_eq!(dockerfile.stages.len(), 1);

        let stage = &dockerfile.stages[0];
        assert_eq!(
            stage_args(stage),
            vec![
                ("CROSS_DEB_ARCH".to_string(), Some(String::new())),
                ("CROSS_CMD".to_string(), None),
            ],
        );
        assert!(stage
            .instructions
            .iter()
            .any(|i| matches!(i, Instruction::Run(_))));
    }
}