quadlet-lens 0.2.3

Source-aware Rust library for Podman Quadlet parsing, validation, generation, and rendering
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
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
//! Validated programmatic construction of deterministic Quadlet documents.
//!
//! This module owns native section and key spelling, repeated-entry rules, physical-line safety,
//! deterministic section order, and parse-back validation. Entry values remain exact authored
//! values: callers are responsible for key-specific semantic validity, while future focused value
//! encoders can provide stronger construction APIs without changing the document builder.

use std::{collections::BTreeSet, error::Error, fmt};

use crate::{
    diagnostic::Diagnostic,
    model::{
        ArtifactKey, BuildKey, ContainerKey, EntryKind, ImageKey, KubeKey, NetworkKey, PodKey, QuadletDocument,
        QuadletKey, QuadletParseResult, QuadletUnitType, SectionKind, SystemdUnitKey, TypedModelError, VolumeKey,
    },
    source::SourceId,
};

/// An exact, single-physical-line native Quadlet value.
///
/// The value is retained exactly. It may contain native systemd quoting and specifiers, but it may
/// not contain line endings or NUL bytes. This type enforces physical-line safety only; it does
/// not validate command arguments, environment assignments, lifecycle values, mount options, or
/// other key-specific semantics.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EntryValue(String);

impl EntryValue {
    /// Creates an exact native value that fits on one physical line.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::InvalidValue`] when the value contains a line ending or NUL byte.
    pub fn new(value: impl Into<String>) -> Result<Self, RenderError> {
        let value = value.into();
        if value.bytes().any(|byte| matches!(byte, 0 | b'\n' | b'\r')) {
            return Err(RenderError::InvalidValue);
        }
        Ok(Self(value))
    }

    /// Returns the exact native spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// One literal assignment for a container `Environment=` entry.
///
/// This focused construction boundary accepts one ASCII environment name and one literal
/// single-line Unicode value. It writes the whole assignment in systemd double quotes and escapes
/// only the quote and backslash characters required inside those quotes. It deliberately does not
/// decode authored environment entries, expand specifiers, split assignment lists, apply resets,
/// or interpret command arguments.
#[derive(Clone, Eq, PartialEq)]
pub struct EnvironmentAssignment {
    name: String,
    value: String,
    rendered: String,
}

impl fmt::Debug for EnvironmentAssignment {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EnvironmentAssignment")
            .field("name", &self.name)
            .field("value", &"<redacted environment value>")
            .field("rendered", &"<redacted environment assignment>")
            .finish()
    }
}

impl EnvironmentAssignment {
    /// Creates one literal `Environment=` assignment.
    ///
    /// The name must match ASCII `[A-Za-z_][A-Za-z0-9_]*`. The value may be empty, but rejects
    /// NUL, physical line endings, other control characters, and `%` until specifier semantics
    /// have focused evidence.
    ///
    /// # Errors
    ///
    /// Returns the category of invalid name or value in [`EnvironmentAssignmentError`].
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Result<Self, EnvironmentAssignmentError> {
        let name = name.into();
        if !is_environment_name(&name) {
            return Err(EnvironmentAssignmentError::InvalidName);
        }

        let value = value.into();
        for character in value.chars() {
            match character {
                '\0' => return Err(EnvironmentAssignmentError::Nul),
                '\r' => return Err(EnvironmentAssignmentError::CarriageReturn),
                '\n' => return Err(EnvironmentAssignmentError::LineFeed),
                '%' => return Err(EnvironmentAssignmentError::Specifier),
                _ if character.is_control() => return Err(EnvironmentAssignmentError::ControlCharacter),
                _ => {}
            }
        }

        let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
        let rendered = format!("\"{name}={escaped}\"");
        Ok(Self { name, value, rendered })
    }

    /// Returns the validated assignment name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the exact literal value before systemd quoting.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns the exact generated native `Environment=` value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.rendered
    }
}

impl From<EnvironmentAssignment> for EntryValue {
    fn from(assignment: EnvironmentAssignment) -> Self {
        Self(assignment.rendered)
    }
}

/// One non-empty group of validated container `Environment=` assignments.
///
/// The group accepts only existing [`EnvironmentAssignment`] values, so it neither reparses nor
/// revalidates names and literal values. It renders those already quoted whole assignments in
/// insertion order, separated by one ASCII space, for one physical `Environment=` entry.
#[derive(Clone, Eq, PartialEq)]
pub struct EnvironmentAssignments {
    assignments: Vec<EnvironmentAssignment>,
    rendered: String,
}

impl fmt::Debug for EnvironmentAssignments {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("EnvironmentAssignments")
            .field("assignment_count", &self.assignments.len())
            .field("rendered", &"<redacted environment assignments>")
            .finish()
    }
}

impl EnvironmentAssignments {
    /// Creates one non-empty group from validated assignments.
    ///
    /// # Errors
    ///
    /// Returns [`EnvironmentAssignmentsError::Empty`] when no assignment is supplied.
    pub fn new(
        assignments: impl IntoIterator<Item = EnvironmentAssignment>,
    ) -> Result<Self, EnvironmentAssignmentsError> {
        let assignments: Vec<_> = assignments.into_iter().collect();
        if assignments.is_empty() {
            return Err(EnvironmentAssignmentsError::Empty);
        }
        let rendered = assignments
            .iter()
            .map(EnvironmentAssignment::as_str)
            .collect::<Vec<_>>()
            .join(" ");
        Ok(Self { assignments, rendered })
    }

    /// Returns the validated assignments in their rendered order.
    #[must_use]
    pub fn assignments(&self) -> &[EnvironmentAssignment] {
        &self.assignments
    }

    /// Iterates over the validated assignments in their rendered order.
    #[must_use]
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &EnvironmentAssignment> {
        self.assignments.iter()
    }

    /// Returns the exact generated native `Environment=` value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.rendered
    }
}

impl From<EnvironmentAssignments> for EntryValue {
    fn from(assignments: EnvironmentAssignments) -> Self {
        Self(assignments.rendered)
    }
}

/// An explicit empty container `Environment=` directive.
///
/// This zero-sized marker emits one blank physical native value. It does not decode authored
/// values, apply the target's reset behavior, select effective variables, or inspect an
/// environment.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct EnvironmentReset {
    _private: (),
}

impl EnvironmentReset {
    /// Creates an explicit blank `Environment=` directive.
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }

    /// Returns the exact generated native value: an empty string.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        ""
    }
}

impl From<EnvironmentReset> for EntryValue {
    fn from(_: EnvironmentReset) -> Self {
        Self(String::new())
    }
}

/// One validated physical container `Environment=` directive in a generation plan.
#[derive(Clone, Eq, PartialEq)]
#[non_exhaustive]
pub enum ContainerEnvironmentDirective {
    /// One independently emitted literal assignment.
    Assignment(EnvironmentAssignment),
    /// One physical directive containing a non-empty ordered assignment group.
    Assignments(EnvironmentAssignments),
    /// One blank directive that resets the effective literal projection.
    Reset(EnvironmentReset),
}

impl fmt::Debug for ContainerEnvironmentDirective {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Assignment(_) => formatter.write_str("Assignment(<redacted environment assignment>)"),
            Self::Assignments(assignments) => formatter
                .debug_struct("Assignments")
                .field("assignment_count", &assignments.assignments.len())
                .field("values", &"<redacted environment assignments>")
                .finish(),
            Self::Reset(_) => formatter.write_str("Reset"),
        }
    }
}

/// Ordered, builder-owned container environment directives and their effective literal lookup.
///
/// The plan preserves every physical directive in insertion order. Its effective projection is
/// intentionally available only through explicit name lookup and opaque membership/count helpers:
/// groups apply left-to-right,
/// later names win, a reset clears earlier names, and an empty value remains `Some("")`.
/// Authored parsing, systemd specifier/continuation handling, manager expansion, environment-file
/// loading, secret lookup, and runtime behavior remain outside this construction API.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct ContainerEnvironmentPlan {
    directives: Vec<ContainerEnvironmentDirective>,
}

impl ContainerEnvironmentPlan {
    /// Creates an empty environment plan.
    #[must_use]
    pub const fn new() -> Self {
        Self { directives: Vec::new() }
    }

    /// Appends one independently emitted literal assignment.
    pub fn push_assignment(&mut self, assignment: EnvironmentAssignment) {
        self.directives
            .push(ContainerEnvironmentDirective::Assignment(assignment));
    }

    /// Appends one physical directive containing a non-empty ordered assignment group.
    pub fn push_assignments(&mut self, assignments: EnvironmentAssignments) {
        self.directives
            .push(ContainerEnvironmentDirective::Assignments(assignments));
    }

    /// Appends one blank reset directive.
    pub fn push_reset(&mut self) {
        self.directives
            .push(ContainerEnvironmentDirective::Reset(EnvironmentReset::new()));
    }

    /// Returns the original physical directives in insertion order.
    #[must_use]
    pub fn directives(&self) -> &[ContainerEnvironmentDirective] {
        &self.directives
    }

    /// Returns an opt-in deterministic plan ordered by assignment name within reset boundaries.
    ///
    /// Assignment groups are expanded to individual directives. Sorting is stable, so repeated
    /// assignments for the same name retain their original last-wins order. Explicit resets stay
    /// in their authored positions and divide independently sorted segments. The original plan is
    /// unchanged.
    ///
    /// Parsed and canonical source rendering never calls this method: source-owned repetition,
    /// grouping, quoting, and order remain lossless. This helper is only for caller-owned literal
    /// generation plans whose cross-name order has no authored significance.
    #[must_use]
    pub fn sorted_by_name(&self) -> Self {
        fn flush(assignments: &mut Vec<EnvironmentAssignment>, directives: &mut Vec<ContainerEnvironmentDirective>) {
            assignments.sort_by(|left, right| left.name().cmp(right.name()));
            directives.extend(assignments.drain(..).map(ContainerEnvironmentDirective::Assignment));
        }

        let mut directives = Vec::with_capacity(self.directives.len());
        let mut assignments = Vec::new();
        for directive in &self.directives {
            match directive {
                ContainerEnvironmentDirective::Assignment(assignment) => {
                    assignments.push(assignment.clone());
                }
                ContainerEnvironmentDirective::Assignments(group) => {
                    assignments.extend(group.iter().cloned());
                }
                ContainerEnvironmentDirective::Reset(reset) => {
                    flush(&mut assignments, &mut directives);
                    directives.push(ContainerEnvironmentDirective::Reset(*reset));
                }
            }
        }
        flush(&mut assignments, &mut directives);
        Self { directives }
    }

    /// Returns the effective literal value for one explicitly requested name.
    ///
    /// This projection does not expose map iteration order. It applies only the validated literal
    /// assignments owned by this plan and does not inspect authored directives or the environment.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        let mut effective = None;
        for directive in &self.directives {
            match directive {
                ContainerEnvironmentDirective::Assignment(assignment) => {
                    if assignment.name() == name {
                        effective = Some(assignment.value());
                    }
                }
                ContainerEnvironmentDirective::Assignments(assignments) => {
                    for assignment in assignments.iter() {
                        if assignment.name() == name {
                            effective = Some(assignment.value());
                        }
                    }
                }
                ContainerEnvironmentDirective::Reset(_) => effective = None,
            }
        }
        effective
    }

    /// Reports whether one explicitly requested name is present in the effective projection.
    #[must_use]
    pub fn contains(&self, name: &str) -> bool {
        self.get(name).is_some()
    }

    /// Returns the number of distinct names in the effective literal projection.
    ///
    /// This count exposes no name or iteration-order API. Use [`Self::directives`] when the number
    /// of physical directives is required.
    #[must_use]
    pub fn len(&self) -> usize {
        let mut names = BTreeSet::new();
        for directive in &self.directives {
            match directive {
                ContainerEnvironmentDirective::Assignment(assignment) => {
                    names.insert(assignment.name());
                }
                ContainerEnvironmentDirective::Assignments(assignments) => {
                    names.extend(assignments.iter().map(EnvironmentAssignment::name));
                }
                ContainerEnvironmentDirective::Reset(_) => names.clear(),
            }
        }
        names.len()
    }

    /// Reports whether the effective literal projection contains no names.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl fmt::Debug for ContainerEnvironmentPlan {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ContainerEnvironmentPlan")
            .field("directives", &self.directives)
            .finish()
    }
}

/// Invalid construction of [`EnvironmentAssignments`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum EnvironmentAssignmentsError {
    /// A grouped `Environment=` entry requires at least one assignment.
    Empty,
}

impl fmt::Display for EnvironmentAssignmentsError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("an environment assignment group must not be empty"),
        }
    }
}

impl Error for EnvironmentAssignmentsError {}

/// Invalid input to [`EnvironmentAssignment::new`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum EnvironmentAssignmentError {
    /// The assignment name does not match ASCII `[A-Za-z_][A-Za-z0-9_]*`.
    InvalidName,
    /// The literal value contains a NUL byte.
    Nul,
    /// The literal value contains a carriage return.
    CarriageReturn,
    /// The literal value contains a line feed.
    LineFeed,
    /// The literal value contains another Unicode control character.
    ControlCharacter,
    /// The literal value contains a systemd specifier introducer.
    Specifier,
}

impl fmt::Display for EnvironmentAssignmentError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidName => formatter.write_str("environment names must match ASCII [A-Za-z_][A-Za-z0-9_]*"),
            Self::Nul => formatter.write_str("environment values must not contain NUL bytes"),
            Self::CarriageReturn => formatter.write_str("environment values must not contain carriage returns"),
            Self::LineFeed => formatter.write_str("environment values must not contain line feeds"),
            Self::ControlCharacter => formatter.write_str("environment values must not contain control characters"),
            Self::Specifier => formatter.write_str("environment values must not contain systemd specifiers"),
        }
    }
}

impl Error for EnvironmentAssignmentError {}

fn is_environment_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    matches!(bytes.next(), Some(byte) if byte.is_ascii_alphabetic() || byte == b'_')
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}

/// Safely constructible process-ID limit for a container.
///
/// This helper covers only the documented unlimited spelling (`-1`) and positive finite values
/// written as nonzero ASCII decimal text. It deliberately does not parse the decimal into a Rust
/// integer, so large values and leading zeros retain their exact spelling without overflow.
/// Parsed and raw [`EntryValue`] inputs remain uninterpreted, so authored zero and noncanonical
/// values can still be preserved.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PidsLimit(String);

impl PidsLimit {
    /// Creates an unlimited process-ID limit rendered as `-1`.
    #[must_use]
    pub fn unlimited() -> Self {
        Self("-1".to_owned())
    }

    /// Creates a positive finite process-ID limit from exact ASCII decimal spelling.
    ///
    /// # Errors
    ///
    /// Returns [`PidsLimitError::Empty`] for empty text, [`PidsLimitError::NonDecimal`] for any
    /// non-ASCII-digit byte, and [`PidsLimitError::Zero`] when every digit is zero.
    pub fn finite(limit: impl Into<String>) -> Result<Self, PidsLimitError> {
        let limit = limit.into();
        if limit.is_empty() {
            return Err(PidsLimitError::Empty);
        }
        if !limit.bytes().all(|byte| byte.is_ascii_digit()) {
            return Err(PidsLimitError::NonDecimal);
        }
        if !limit.bytes().any(|byte| byte != b'0') {
            return Err(PidsLimitError::Zero);
        }
        Ok(Self(limit))
    }

    /// Returns the exact native spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<PidsLimit> for EntryValue {
    fn from(limit: PidsLimit) -> Self {
        Self(limit.0)
    }
}

/// Invalid input to [`PidsLimit::finite`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PidsLimitError {
    /// The finite decimal spelling is empty.
    Empty,
    /// The finite spelling contains a byte other than an ASCII decimal digit.
    NonDecimal,
    /// Zero is deliberately outside the typed construction contract.
    Zero,
}

impl fmt::Display for PidsLimitError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("a finite process-ID limit must not be empty"),
            Self::NonDecimal => formatter.write_str("a finite process-ID limit must contain only ASCII decimal digits"),
            Self::Zero => formatter.write_str("a finite process-ID limit must be positive"),
        }
    }
}

impl Error for PidsLimitError {}

/// Safely constructible native shared-memory size for a container or pod.
///
/// The exact spelling is retained without parsing into a machine integer. Accepted values contain
/// a non-negative ASCII-decimal amount followed by no unit or one lowercase native unit: `b`,
/// `k`, `m`, or `g`. Leading zeros and arbitrary-precision amounts remain unchanged. Parsed and
/// raw [`EntryValue`] inputs remain uninterpreted.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ShmSize(String);

impl ShmSize {
    /// Creates a shared-memory size from exact native spelling.
    ///
    /// # Errors
    ///
    /// Returns [`ShmSizeError::Empty`] for empty text and [`ShmSizeError::InvalidFormat`] unless
    /// the value is an ASCII-decimal amount with an optional lowercase `b`, `k`, `m`, or `g` unit.
    pub fn new(size: impl Into<String>) -> Result<Self, ShmSizeError> {
        let size = size.into();
        if size.is_empty() {
            return Err(ShmSizeError::Empty);
        }
        let amount = match size.as_bytes().last() {
            Some(b'b' | b'k' | b'm' | b'g') => &size[..size.len() - 1],
            _ => size.as_str(),
        };
        if amount.is_empty() || !amount.bytes().all(|byte| byte.is_ascii_digit()) {
            return Err(ShmSizeError::InvalidFormat);
        }
        Ok(Self(size))
    }

    /// Creates Podman's documented explicit unlimited shared-memory value, `0`.
    #[must_use]
    pub fn unlimited() -> Self {
        Self("0".to_owned())
    }

    /// Returns whether the exact spelling denotes a zero amount, Podman's documented unlimited value.
    #[must_use]
    pub fn is_unlimited(&self) -> bool {
        let amount = match self.0.as_bytes().last() {
            Some(b'b' | b'k' | b'm' | b'g') => &self.0[..self.0.len() - 1],
            _ => self.0.as_str(),
        };
        amount.bytes().all(|byte| byte == b'0')
    }

    /// Returns the exact native spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<ShmSize> for EntryValue {
    fn from(size: ShmSize) -> Self {
        Self(size.0)
    }
}

/// Invalid input to [`ShmSize::new`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ShmSizeError {
    /// The shared-memory size is empty.
    Empty,
    /// The value is not an ASCII-decimal amount with an optional supported lowercase unit.
    InvalidFormat,
}

impl fmt::Display for ShmSizeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("a shared-memory size must not be empty"),
            Self::InvalidFormat => formatter
                .write_str("a shared-memory size must be an ASCII decimal amount with optional unit b, k, m, or g"),
        }
    }
}

impl Error for ShmSizeError {}

/// Safely constructible native memory limit for a container.
///
/// The exact spelling is retained without parsing into a machine integer. Accepted values contain
/// a positive ASCII-decimal amount followed by no unit or one lowercase native unit: `b`, `k`,
/// `m`, or `g`. Leading zeros and arbitrary-precision amounts remain unchanged. Parsed and raw
/// [`EntryValue`] inputs remain uninterpreted.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Memory(String);

impl Memory {
    /// Creates a positive memory limit from exact native spelling.
    ///
    /// # Errors
    ///
    /// Returns [`MemoryError::Empty`] for empty text, [`MemoryError::InvalidFormat`] unless the
    /// value is an ASCII-decimal amount with an optional lowercase `b`, `k`, `m`, or `g` unit,
    /// and [`MemoryError::Zero`] when every amount digit is zero.
    pub fn new(memory: impl Into<String>) -> Result<Self, MemoryError> {
        let memory = memory.into();
        if memory.is_empty() {
            return Err(MemoryError::Empty);
        }
        let amount = match memory.as_bytes().last() {
            Some(b'b' | b'k' | b'm' | b'g') => &memory[..memory.len() - 1],
            _ => memory.as_str(),
        };
        if amount.is_empty() || !amount.bytes().all(|byte| byte.is_ascii_digit()) {
            return Err(MemoryError::InvalidFormat);
        }
        if !amount.bytes().any(|byte| byte != b'0') {
            return Err(MemoryError::Zero);
        }
        Ok(Self(memory))
    }

    /// Returns the exact native spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<Memory> for EntryValue {
    fn from(memory: Memory) -> Self {
        Self(memory.0)
    }
}

/// Invalid input to [`Memory::new`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum MemoryError {
    /// The memory-limit spelling is empty.
    Empty,
    /// The value is not an ASCII-decimal amount with an optional supported lowercase unit.
    InvalidFormat,
    /// A memory limit must be positive.
    Zero,
}

impl fmt::Display for MemoryError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("a memory limit must not be empty"),
            Self::InvalidFormat => {
                formatter.write_str("a memory limit must be an ASCII decimal amount with optional unit b, k, m, or g")
            }
            Self::Zero => formatter.write_str("a memory limit must be positive"),
        }
    }
}

impl Error for MemoryError {}

/// Generic systemd section supported in generated Quadlet files.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SystemdSection {
    /// The generic `[Unit]` section.
    Unit,
    /// The generic `[Service]` section.
    Service,
    /// The generic `[Install]` section.
    Install,
}

impl SystemdSection {
    const fn kind(self) -> SectionKind {
        match self {
            Self::Unit => SectionKind::Unit,
            Self::Service => SectionKind::Service,
            Self::Install => SectionKind::Install,
        }
    }
}

#[derive(Clone, Eq, PartialEq)]
struct GeneratedEntry {
    section: SectionKind,
    kind: EntryKind,
    key: String,
    value: EntryValue,
}

impl fmt::Debug for GeneratedEntry {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut debug = formatter.debug_struct("GeneratedEntry");
        debug
            .field("section", &self.section)
            .field("kind", &self.kind)
            .field("key", &self.key);
        if self.kind.has_sensitive_value() {
            debug.field("value", &"<redacted sensitive value>")
        } else {
            debug.field("value", &self.value)
        };
        debug.finish()
    }
}

/// Ordered builder for one supported Quadlet document.
///
/// Native entries use typed keys and must match the selected unit type. Repeated keys retain
/// insertion order; duplicate singleton native keys are rejected. Generated sections use the
/// deterministic order `[Unit]`, the selected native section, `[Service]`, and `[Install]`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QuadletDocumentBuilder {
    unit_type: QuadletUnitType,
    entries: Vec<GeneratedEntry>,
}

impl QuadletDocumentBuilder {
    /// Creates an empty document with the selected required native section.
    #[must_use]
    pub const fn new(unit_type: QuadletUnitType) -> Self {
        Self {
            unit_type,
            entries: Vec::new(),
        }
    }

    /// Returns the selected native unit type.
    #[must_use]
    pub const fn unit_type(&self) -> QuadletUnitType {
        self.unit_type
    }

    /// Appends a typed `[Container]` entry.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-container document and
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton key.
    pub fn push_container(&mut self, key: ContainerKey, value: EntryValue) -> Result<(), RenderError> {
        let attempted = container_key_name(key);
        if let Some(existing) = match key {
            ContainerKey::ReloadCmd => self.entries.iter().find_map(|entry| {
                (entry.kind == EntryKind::Container(ContainerKey::ReloadSignal)).then_some("ReloadSignal")
            }),
            ContainerKey::ReloadSignal => self
                .entries
                .iter()
                .find_map(|entry| (entry.kind == EntryKind::Container(ContainerKey::ReloadCmd)).then_some("ReloadCmd")),
            _ => None,
        } {
            return Err(RenderError::ConflictingSingletons {
                existing: existing.to_owned(),
                attempted: attempted.to_owned(),
            });
        }
        self.push_native(
            QuadletUnitType::Container,
            SectionKind::Container,
            EntryKind::Container(key),
            container_key_name(key),
            value,
        )
    }

    /// Appends one focused literal container `Environment=` assignment.
    ///
    /// This convenience method is equivalent to passing an [`EnvironmentAssignment`] converted
    /// into [`EntryValue`] to [`Self::push_container`]. Repetition remains native and ordered.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-container document.
    pub fn push_container_environment(&mut self, assignment: EnvironmentAssignment) -> Result<(), RenderError> {
        self.push_container(ContainerKey::Environment, assignment.into())
    }

    /// Appends one focused group of literal container `Environment=` assignments.
    ///
    /// One call emits one physical native entry. The group's validated assignments remain in
    /// order inside that entry; repeated calls remain native and ordered relative to single
    /// assignment calls and other container directives.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-container document.
    pub fn push_container_environment_assignments(
        &mut self,
        assignments: EnvironmentAssignments,
    ) -> Result<(), RenderError> {
        self.push_container(ContainerKey::Environment, assignments.into())
    }

    /// Appends one explicit blank container `Environment=` directive.
    ///
    /// The directive stays at this call position. This method does not apply reset behavior or
    /// inspect effective environment values.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-container document.
    pub fn push_container_environment_reset(&mut self) -> Result<(), RenderError> {
        self.push_container(ContainerKey::Environment, EnvironmentReset::new().into())
    }

    /// Appends every physical directive from a validated container environment plan.
    ///
    /// Assignment, group, and reset directives retain their original order and grouping. The
    /// builder does not emit the plan's effective projection or otherwise combine directives.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-container document. In that case no plan
    /// directive is appended.
    pub fn push_container_environment_plan(&mut self, plan: &ContainerEnvironmentPlan) -> Result<(), RenderError> {
        if self.unit_type != QuadletUnitType::Container {
            return Err(RenderError::WrongUnitType {
                document: self.unit_type,
                entry: QuadletUnitType::Container,
            });
        }
        for directive in plan.directives() {
            match directive {
                ContainerEnvironmentDirective::Assignment(assignment) => {
                    self.push_container_environment(assignment.clone())?;
                }
                ContainerEnvironmentDirective::Assignments(assignments) => {
                    self.push_container_environment_assignments(assignments.clone())?;
                }
                ContainerEnvironmentDirective::Reset(_) => self.push_container_environment_reset()?,
            }
        }
        Ok(())
    }

    /// Appends a typed `[Pod]` entry.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-pod document and
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton key.
    pub fn push_pod(&mut self, key: PodKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Pod,
            SectionKind::Pod,
            EntryKind::Pod(key),
            pod_key_name(key),
            value,
        )
    }

    /// Appends a typed `[Network]` entry.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-network document and
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton key.
    pub fn push_network(&mut self, key: NetworkKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Network,
            SectionKind::Network,
            EntryKind::Network(key),
            network_key_name(key),
            value,
        )
    }

    /// Appends a typed `[Volume]` entry.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-volume document and
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton key.
    pub fn push_volume(&mut self, key: VolumeKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Volume,
            SectionKind::Volume,
            EntryKind::Volume(key),
            volume_key_name(key),
            value,
        )
    }

    /// Appends a typed `[Build]` entry.
    ///
    /// `ImageTag`, `File`, `Network`, `Label`, `BuildArg`, `Secret`, `GroupAdd`, `DNS`, `DNSOption`, `DNSSearch`,
    /// `Annotation`, `Environment`, `ContainersConfModule`, `GlobalArgs`, `Volume`, and `PodmanArgs` entries remain repeatable and ordered; `SetWorkingDirectory`, `Target`, `Arch`, `Variant`,
    /// `Pull`, `Retry`, `RetryDelay`, `TLSVerify`, `ForceRM`, `AuthFile`, `IgnoreFile`, and `ServiceName` are singletons. Values are exact
    /// physical-line-safe native text and are not interpreted by the builder.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-build document and
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton Build key.
    pub fn push_build(&mut self, key: BuildKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Build,
            SectionKind::Build,
            EntryKind::Build(key),
            build_key_name(key),
            value,
        )
    }

    /// Appends a typed `[Image]` entry.
    ///
    /// `ContainersConfModule`, `GlobalArgs`, and `PodmanArgs` entries remain repeatable and ordered. All other Image keys, including `OS`, are
    /// singletons. `Creds` and `DecryptionKey` are debug-redacted after key assignment, while
    /// explicit rendering and raw-value access remain exact. Values are exact physical-line-safe
    /// native text and are not interpreted by the builder; it does not read paths or modules, parse configuration,
    /// validate a CLI, or model pull, runtime, graph, or conversion semantics.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-image document and
    /// [`RenderError::DuplicateSingleton`] only for a repeated singleton Image key.
    pub fn push_image(&mut self, key: ImageKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Image,
            SectionKind::Image,
            EntryKind::Image(key),
            image_key_name(key),
            value,
        )
    }

    /// Appends a typed `[Kube]` entry.
    ///
    /// `AutoUpdate`, `ConfigMap`, `ContainersConfModule`, `GlobalArgs`, `LogOpt`, `RemapGid`,
    /// `RemapUid`, `Network`,
    /// `PodmanArgs`, `PublishPort`, and required `Yaml` entries remain repeatable and ordered. All other Kube keys are
    /// singletons. Values are exact physical-line-safe native text; this builder neither reads
    /// files nor parses Kubernetes YAML, Podman arguments, ports, paths, or runtime behavior.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-Kube document,
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton Kube key, or
    /// [`RenderError::InvalidDocument`] when no nonblank required `Yaml=` source is present.
    pub fn push_kube(&mut self, key: KubeKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Kube,
            SectionKind::Kube,
            EntryKind::Kube(key),
            kube_key_name(key),
            value,
        )
    }

    /// Appends a typed experimental `[Artifact]` entry.
    ///
    /// `ContainersConfModule`, `GlobalArgs`, and `PodmanArgs` entries remain repeatable and
    /// ordered. The required `Artifact` source and every other Artifact key are singletons.
    /// `Creds` and `DecryptionKey` are redacted only from repository-owned debug output;
    /// rendering and explicit raw-value access remain exact. Values remain physical-line-safe
    /// opaque native text: this builder does not access a registry or filesystem, parse
    /// credentials, select retry defaults, or perform an artifact pull.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::WrongUnitType`] for a non-artifact document,
    /// [`RenderError::DuplicateSingleton`] for a repeated singleton key, or
    /// [`RenderError::InvalidDocument`] when the required final `Artifact=` source is absent or
    /// blank at build time.
    pub fn push_artifact(&mut self, key: ArtifactKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_native(
            QuadletUnitType::Artifact,
            SectionKind::Artifact,
            EntryKind::Artifact(key),
            artifact_key_name(key),
            value,
        )
    }

    /// Appends a shared `[Quadlet]` entry to any Quadlet unit type.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::DuplicateSingleton`] when `DefaultDependencies=` is repeated.
    pub fn push_quadlet(&mut self, key: QuadletKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_generated(
            SectionKind::Quadlet,
            EntryKind::Quadlet(key),
            quadlet_key_name(key),
            value,
        )
    }

    /// Appends an open-ended entry to a generic systemd section.
    ///
    /// Generic entries retain insertion order and may repeat because their reset and list behavior
    /// is directive-specific and intentionally not guessed by this builder.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::InvalidKey`] when the key is not an ASCII alphanumeric directive
    /// name.
    pub fn push_systemd(
        &mut self,
        section: SystemdSection,
        key: impl Into<String>,
        value: EntryValue,
    ) -> Result<(), RenderError> {
        let key = key.into();
        if key.is_empty() || !key.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
            return Err(RenderError::InvalidKey(key));
        }
        self.entries.push(GeneratedEntry {
            section: section.kind(),
            kind: EntryKind::GenericSystemd,
            key,
            value,
        });
        Ok(())
    }

    /// Appends an evidence-backed dependency or ordering directive to `[Unit]`.
    ///
    /// These entries remain repeatable and retain insertion order. The value is an exact systemd
    /// unit-list spelling; this method does not resolve unit names or infer relationships between
    /// Quadlet source files.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Self::push_systemd`].
    pub fn push_systemd_unit(&mut self, key: SystemdUnitKey, value: EntryValue) -> Result<(), RenderError> {
        self.push_generated(SectionKind::Unit, EntryKind::SystemdUnit(key), key.name(), value)
    }

    /// Renders, reparses, and validates the complete generated document.
    ///
    /// # Errors
    ///
    /// Returns [`RenderError::InvalidDocument`] when native shape validation fails, or
    /// [`RenderError::TypedModel`] for an internal source-span consistency failure.
    pub fn build(&self, source_id: SourceId) -> Result<GeneratedQuadletDocument, RenderError> {
        let text = self.render_text();
        let parsed = QuadletDocument::parse(self.unit_type, source_id, text).map_err(RenderError::TypedModel)?;
        if !parsed.is_valid() {
            let mut diagnostics = parsed.syntax().diagnostics().to_vec();
            diagnostics.extend_from_slice(parsed.model_diagnostics());
            return Err(RenderError::InvalidDocument(diagnostics));
        }
        Ok(GeneratedQuadletDocument { parsed })
    }

    fn push_native(
        &mut self,
        required: QuadletUnitType,
        section: SectionKind,
        kind: EntryKind,
        key: &'static str,
        value: EntryValue,
    ) -> Result<(), RenderError> {
        if self.unit_type != required {
            return Err(RenderError::WrongUnitType {
                document: self.unit_type,
                entry: required,
            });
        }
        self.push_generated(section, kind, key, value)
    }

    fn push_generated(
        &mut self,
        section: SectionKind,
        kind: EntryKind,
        key: &str,
        value: EntryValue,
    ) -> Result<(), RenderError> {
        if !kind.is_repeatable() && self.entries.iter().any(|entry| entry.kind == kind) {
            return Err(RenderError::DuplicateSingleton(key.to_owned()));
        }
        self.entries.push(GeneratedEntry {
            section,
            kind,
            key: key.to_owned(),
            value,
        });
        Ok(())
    }

    fn render_text(&self) -> String {
        let native = self.unit_type.native_section();
        let sections = [
            SectionKind::Unit,
            SectionKind::Quadlet,
            native,
            SectionKind::Service,
            SectionKind::Install,
        ];
        let mut output = String::new();
        let mut wrote_section = false;

        for section in sections {
            let entries: Vec<_> = self.entries.iter().filter(|entry| entry.section == section).collect();
            if entries.is_empty() && section != native {
                continue;
            }
            if wrote_section {
                output.push('\n');
            }
            wrote_section = true;
            output.push('[');
            output.push_str(section_name(section));
            output.push_str("]\n");
            for entry in entries {
                output.push_str(&entry.key);
                output.push('=');
                output.push_str(entry.value.as_str());
                output.push('\n');
            }
        }
        output
    }
}

/// Successfully generated and parse-back-validated Quadlet document.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeneratedQuadletDocument {
    parsed: QuadletParseResult,
}

impl GeneratedQuadletDocument {
    /// Returns the deterministic generated source text.
    #[must_use]
    pub fn text(&self) -> &str {
        self.parsed.syntax().document().render_preserved()
    }

    /// Returns the validated native typed document.
    #[must_use]
    pub const fn document(&self) -> &QuadletDocument {
        self.parsed.document()
    }

    /// Returns the complete syntax and model result.
    #[must_use]
    pub const fn parse_result(&self) -> &QuadletParseResult {
        &self.parsed
    }

    /// Decomposes the generated document into its complete parse result.
    #[must_use]
    pub fn into_parse_result(self) -> QuadletParseResult {
        self.parsed
    }
}

/// Failure while constructing or validating generated Quadlet source.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RenderError {
    /// A native value contained a line ending or NUL byte.
    InvalidValue,
    /// A generic systemd key was empty or contained non-alphanumeric bytes.
    InvalidKey(String),
    /// A native key did not belong to the builder's selected unit type.
    WrongUnitType {
        /// Unit type selected for the document.
        document: QuadletUnitType,
        /// Unit type required by the attempted entry.
        entry: QuadletUnitType,
    },
    /// A singleton native key was added more than once.
    DuplicateSingleton(String),
    /// Two mutually exclusive singleton native keys were added to one document.
    ConflictingSingletons {
        /// Existing native key.
        existing: String,
        /// Attempted native key.
        attempted: String,
    },
    /// Generated source failed syntax or native-model validation.
    InvalidDocument(Vec<Diagnostic>),
    /// Parser-owned spans could not be interpreted consistently.
    TypedModel(TypedModelError),
}

impl RenderError {
    /// Returns validation diagnostics for an invalid generated document.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        match self {
            Self::InvalidDocument(diagnostics) => diagnostics,
            _ => &[],
        }
    }
}

impl fmt::Display for RenderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidValue => formatter.write_str("generated Quadlet values must fit on one physical line"),
            Self::InvalidKey(key) => write!(formatter, "invalid generic systemd key `{key}`"),
            Self::WrongUnitType { document, entry } => {
                write!(formatter, "cannot add a {entry:?} entry to a {document:?} document")
            }
            Self::DuplicateSingleton(key) => write!(formatter, "singleton Quadlet key `{key}` is repeated"),
            Self::ConflictingSingletons { existing, attempted } => {
                write!(
                    formatter,
                    "singleton Quadlet keys `{existing}` and `{attempted}` conflict"
                )
            }
            Self::InvalidDocument(diagnostics) => {
                write!(
                    formatter,
                    "generated Quadlet document has {} diagnostic(s)",
                    diagnostics.len()
                )
            }
            Self::TypedModel(error) => write!(formatter, "generated Quadlet model is inconsistent: {error}"),
        }
    }
}

impl Error for RenderError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::TypedModel(error) => Some(error),
            _ => None,
        }
    }
}

const fn container_key_name(key: ContainerKey) -> &'static str {
    match key {
        ContainerKey::AddHost => "AddHost",
        ContainerKey::Image => "Image",
        ContainerKey::Exec => "Exec",
        ContainerKey::Environment => "Environment",
        ContainerKey::EnvironmentFile => "EnvironmentFile",
        ContainerKey::Label => "Label",
        ContainerKey::Secret => "Secret",
        ContainerKey::PublishPort => "PublishPort",
        ContainerKey::Volume => "Volume",
        ContainerKey::Network => "Network",
        ContainerKey::Pod => "Pod",
        ContainerKey::HealthCmd => "HealthCmd",
        ContainerKey::Notify => "Notify",
        ContainerKey::HealthInterval => "HealthInterval",
        ContainerKey::HealthRetries => "HealthRetries",
        ContainerKey::HealthStartPeriod => "HealthStartPeriod",
        ContainerKey::HealthTimeout => "HealthTimeout",
        ContainerKey::PodmanArgs => "PodmanArgs",
        ContainerKey::User => "User",
        ContainerKey::Group => "Group",
        ContainerKey::UserNS => "UserNS",
        ContainerKey::GroupAdd => "GroupAdd",
        ContainerKey::WorkingDir => "WorkingDir",
        ContainerKey::ReadOnly => "ReadOnly",
        ContainerKey::Rootfs => "Rootfs",
        ContainerKey::ContainerName => "ContainerName",
        ContainerKey::Entrypoint => "Entrypoint",
        ContainerKey::RunInit => "RunInit",
        ContainerKey::StopSignal => "StopSignal",
        ContainerKey::StopTimeout => "StopTimeout",
        ContainerKey::Pull => "Pull",
        ContainerKey::PidsLimit => "PidsLimit",
        ContainerKey::HostName => "HostName",
        ContainerKey::ShmSize => "ShmSize",
        ContainerKey::DropCapability => "DropCapability",
        ContainerKey::AddCapability => "AddCapability",
        ContainerKey::Tmpfs => "Tmpfs",
        ContainerKey::Sysctl => "Sysctl",
        ContainerKey::Ulimit => "Ulimit",
        ContainerKey::AddDevice => "AddDevice",
        ContainerKey::Memory => "Memory",
        ContainerKey::DNS => "DNS",
        ContainerKey::DNSOption => "DNSOption",
        ContainerKey::DNSSearch => "DNSSearch",
        ContainerKey::ExposeHostPort => "ExposeHostPort",
        ContainerKey::Annotation => "Annotation",
        ContainerKey::AppArmor => "AppArmor",
        ContainerKey::NoNewPrivileges => "NoNewPrivileges",
        ContainerKey::SeccompProfile => "SeccompProfile",
        ContainerKey::SecurityLabelDisable => "SecurityLabelDisable",
        ContainerKey::SecurityLabelFileType => "SecurityLabelFileType",
        ContainerKey::SecurityLabelLevel => "SecurityLabelLevel",
        ContainerKey::SecurityLabelNested => "SecurityLabelNested",
        ContainerKey::SecurityLabelType => "SecurityLabelType",
        ContainerKey::Mask => "Mask",
        ContainerKey::Unmask => "Unmask",
        ContainerKey::LogDriver => "LogDriver",
        ContainerKey::LogOpt => "LogOpt",
        ContainerKey::IP => "IP",
        ContainerKey::IP6 => "IP6",
        ContainerKey::NetworkAlias => "NetworkAlias",
        ContainerKey::ReloadCmd => "ReloadCmd",
        ContainerKey::ReloadSignal => "ReloadSignal",
        ContainerKey::AutoUpdate => "AutoUpdate",
        ContainerKey::CgroupsMode => "CgroupsMode",
        ContainerKey::EnvironmentHost => "EnvironmentHost",
        ContainerKey::GIDMap => "GIDMap",
        ContainerKey::HttpProxy => "HttpProxy",
        ContainerKey::Mount => "Mount",
        ContainerKey::ReadOnlyTmpfs => "ReadOnlyTmpfs",
        ContainerKey::Retry => "Retry",
        ContainerKey::RetryDelay => "RetryDelay",
        ContainerKey::StartWithPod => "StartWithPod",
        ContainerKey::SubGIDMap => "SubGIDMap",
        ContainerKey::SubUIDMap => "SubUIDMap",
        ContainerKey::Timezone => "Timezone",
        ContainerKey::UIDMap => "UIDMap",
        ContainerKey::HealthOnFailure => "HealthOnFailure",
        ContainerKey::ContainersConfModule => "ContainersConfModule",
        ContainerKey::GlobalArgs => "GlobalArgs",
        ContainerKey::HealthLogDestination => "HealthLogDestination",
        ContainerKey::HealthMaxLogCount => "HealthMaxLogCount",
        ContainerKey::HealthMaxLogSize => "HealthMaxLogSize",
        ContainerKey::HealthStartupCmd => "HealthStartupCmd",
        ContainerKey::HealthStartupInterval => "HealthStartupInterval",
        ContainerKey::HealthStartupRetries => "HealthStartupRetries",
        ContainerKey::HealthStartupSuccess => "HealthStartupSuccess",
        ContainerKey::HealthStartupTimeout => "HealthStartupTimeout",
        ContainerKey::ImageVolume => "ImageVolume",
        ContainerKey::ServiceName => "ServiceName",
    }
}

const fn build_key_name(key: BuildKey) -> &'static str {
    match key {
        BuildKey::ImageTag => "ImageTag",
        BuildKey::SetWorkingDirectory => "SetWorkingDirectory",
        BuildKey::File => "File",
        BuildKey::Target => "Target",
        BuildKey::Network => "Network",
        BuildKey::Label => "Label",
        BuildKey::BuildArg => "BuildArg",
        BuildKey::Secret => "Secret",
        BuildKey::Arch => "Arch",
        BuildKey::Variant => "Variant",
        BuildKey::Pull => "Pull",
        BuildKey::PodmanArgs => "PodmanArgs",
        BuildKey::Retry => "Retry",
        BuildKey::RetryDelay => "RetryDelay",
        BuildKey::TLSVerify => "TLSVerify",
        BuildKey::ForceRM => "ForceRM",
        BuildKey::GroupAdd => "GroupAdd",
        BuildKey::DNS => "DNS",
        BuildKey::DNSOption => "DNSOption",
        BuildKey::DNSSearch => "DNSSearch",
        BuildKey::AuthFile => "AuthFile",
        BuildKey::IgnoreFile => "IgnoreFile",
        BuildKey::Annotation => "Annotation",
        BuildKey::Environment => "Environment",
        BuildKey::ContainersConfModule => "ContainersConfModule",
        BuildKey::GlobalArgs => "GlobalArgs",
        BuildKey::ServiceName => "ServiceName",
        BuildKey::Volume => "Volume",
    }
}

const fn image_key_name(key: ImageKey) -> &'static str {
    match key {
        ImageKey::Image => "Image",
        ImageKey::ImageTag => "ImageTag",
        ImageKey::ServiceName => "ServiceName",
        ImageKey::AllTags => "AllTags",
        ImageKey::Arch => "Arch",
        ImageKey::AuthFile => "AuthFile",
        ImageKey::CertDir => "CertDir",
        ImageKey::ContainersConfModule => "ContainersConfModule",
        ImageKey::Creds => "Creds",
        ImageKey::DecryptionKey => "DecryptionKey",
        ImageKey::GlobalArgs => "GlobalArgs",
        ImageKey::OS => "OS",
        ImageKey::PodmanArgs => "PodmanArgs",
        ImageKey::Policy => "Policy",
        ImageKey::Retry => "Retry",
        ImageKey::RetryDelay => "RetryDelay",
        ImageKey::TLSVerify => "TLSVerify",
        ImageKey::Variant => "Variant",
    }
}

const fn kube_key_name(key: KubeKey) -> &'static str {
    match key {
        KubeKey::AutoUpdate => "AutoUpdate",
        KubeKey::ConfigMap => "ConfigMap",
        KubeKey::ContainersConfModule => "ContainersConfModule",
        KubeKey::ExitCodePropagation => "ExitCodePropagation",
        KubeKey::GlobalArgs => "GlobalArgs",
        KubeKey::KubeDownForce => "KubeDownForce",
        KubeKey::LogDriver => "LogDriver",
        KubeKey::Network => "Network",
        KubeKey::PodmanArgs => "PodmanArgs",
        KubeKey::PublishPort => "PublishPort",
        KubeKey::ServiceName => "ServiceName",
        KubeKey::SetWorkingDirectory => "SetWorkingDirectory",
        KubeKey::UserNS => "UserNS",
        KubeKey::Yaml => "Yaml",
        KubeKey::LogOpt => "LogOpt",
        KubeKey::RemapGid => "RemapGid",
        KubeKey::RemapUid => "RemapUid",
        KubeKey::RemapUidSize => "RemapUidSize",
        KubeKey::RemapUsers => "RemapUsers",
    }
}

const fn artifact_key_name(key: ArtifactKey) -> &'static str {
    match key {
        ArtifactKey::Artifact => "Artifact",
        ArtifactKey::AuthFile => "AuthFile",
        ArtifactKey::CertDir => "CertDir",
        ArtifactKey::Creds => "Creds",
        ArtifactKey::DecryptionKey => "DecryptionKey",
        ArtifactKey::Quiet => "Quiet",
        ArtifactKey::Retry => "Retry",
        ArtifactKey::RetryDelay => "RetryDelay",
        ArtifactKey::ServiceName => "ServiceName",
        ArtifactKey::TLSVerify => "TLSVerify",
        ArtifactKey::ContainersConfModule => "ContainersConfModule",
        ArtifactKey::GlobalArgs => "GlobalArgs",
        ArtifactKey::PodmanArgs => "PodmanArgs",
    }
}

const fn quadlet_key_name(key: QuadletKey) -> &'static str {
    match key {
        QuadletKey::DefaultDependencies => "DefaultDependencies",
    }
}

const fn pod_key_name(key: PodKey) -> &'static str {
    match key {
        PodKey::AddHost => "AddHost",
        PodKey::PodName => "PodName",
        PodKey::PublishPort => "PublishPort",
        PodKey::Network => "Network",
        PodKey::Volume => "Volume",
        PodKey::UserNS => "UserNS",
        PodKey::ShmSize => "ShmSize",
        PodKey::ExitPolicy => "ExitPolicy",
        PodKey::StopTimeout => "StopTimeout",
        PodKey::ServiceName => "ServiceName",
        PodKey::ContainersConfModule => "ContainersConfModule",
        PodKey::DNS => "DNS",
        PodKey::DNSOption => "DNSOption",
        PodKey::DNSSearch => "DNSSearch",
        PodKey::GIDMap => "GIDMap",
        PodKey::GlobalArgs => "GlobalArgs",
        PodKey::HostName => "HostName",
        PodKey::IP => "IP",
        PodKey::IP6 => "IP6",
        PodKey::Label => "Label",
        PodKey::NetworkAlias => "NetworkAlias",
        PodKey::PodmanArgs => "PodmanArgs",
        PodKey::SubGIDMap => "SubGIDMap",
        PodKey::SubUIDMap => "SubUIDMap",
        PodKey::UIDMap => "UIDMap",
    }
}

const fn network_key_name(key: NetworkKey) -> &'static str {
    match key {
        NetworkKey::NetworkName => "NetworkName",
        NetworkKey::Driver => "Driver",
        NetworkKey::Options => "Options",
        NetworkKey::Internal => "Internal",
        NetworkKey::IPv6 => "IPv6",
        NetworkKey::IPAMDriver => "IPAMDriver",
        NetworkKey::Subnet => "Subnet",
        NetworkKey::Gateway => "Gateway",
        NetworkKey::IPRange => "IPRange",
        NetworkKey::Label => "Label",
        NetworkKey::ContainersConfModule => "ContainersConfModule",
        NetworkKey::DisableDNS => "DisableDNS",
        NetworkKey::DNS => "DNS",
        NetworkKey::GlobalArgs => "GlobalArgs",
        NetworkKey::InterfaceName => "InterfaceName",
        NetworkKey::NetworkDeleteOnStop => "NetworkDeleteOnStop",
        NetworkKey::PodmanArgs => "PodmanArgs",
        NetworkKey::ServiceName => "ServiceName",
    }
}

const fn volume_key_name(key: VolumeKey) -> &'static str {
    match key {
        VolumeKey::VolumeName => "VolumeName",
        VolumeKey::Driver => "Driver",
        VolumeKey::Options => "Options",
        VolumeKey::Label => "Label",
        VolumeKey::Device => "Device",
        VolumeKey::Type => "Type",
        VolumeKey::Copy => "Copy",
        VolumeKey::ContainersConfModule => "ContainersConfModule",
        VolumeKey::GlobalArgs => "GlobalArgs",
        VolumeKey::PodmanArgs => "PodmanArgs",
        VolumeKey::User => "User",
        VolumeKey::Group => "Group",
        VolumeKey::UID => "UID",
        VolumeKey::GID => "GID",
        VolumeKey::ServiceName => "ServiceName",
        VolumeKey::Image => "Image",
    }
}

const fn section_name(section: SectionKind) -> &'static str {
    match section {
        SectionKind::Unit => "Unit",
        SectionKind::Container => "Container",
        SectionKind::Pod => "Pod",
        SectionKind::Network => "Network",
        SectionKind::Volume => "Volume",
        SectionKind::Build => "Build",
        SectionKind::Image => "Image",
        SectionKind::Kube => "Kube",
        SectionKind::Artifact => "Artifact",
        SectionKind::Quadlet => "Quadlet",
        SectionKind::Service => "Service",
        SectionKind::Install => "Install",
        SectionKind::Unknown => "Unknown",
    }
}