onelf 0.6.1

Packer CLI for creating onelf single-binary packages
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
//! Declarative recipe file (`onelf.toml`) for reproducible packs.
//!
//! Example:
//!
//! ```toml
//! [package]
//! name = "myapp"
//! command = "bin/myapp"
//! working-dir = "package"
//!
//! [input]
//! binary = "../upstream/myapp"
//!
//! [[entrypoint]]
//! name = "myapp-cli"
//! path = "bin/myapp"
//! args = ["--no-gui"]
//!
//! [compression]
//! level = 19
//! dict = true
//!
//! [update]
//! url = "https://example.com/myapp.onelf"
//!
//! [bundle]
//! search-paths = ["${MUSL_LIBDRM}/lib"]
//! strict-libc = true
//! gl = true
//! rules = ["vendor-framework.toml"]
//! disable-rules = ["translations"]
//! ```

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use onelf_format::WorkingDir;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Recipe {
    pub package: Package,
    /// Files the build imports into the AppDir before assembly, from the
    /// `[input]` TOML table.
    #[serde(default)]
    pub input: Option<Input>,
    #[serde(default)]
    pub entrypoint: Vec<Entrypoint>,
    #[serde(default)]
    pub compression: Compression,
    pub update: Option<Update>,
    #[serde(default)]
    pub bundle: Bundle,
    /// Take the bundle's contents from a pinned sysroot instead of
    /// scanning the packer's machine.
    pub sysroot: Option<Sysroot>,
    /// Custom environment variables set before exec. Values support
    /// `${ONELF_DIR}` which expands to the package root at runtime.
    /// Deserialized from the `[env]` TOML table into a `BTreeMap` so the
    /// emitted `.onelf/env` order is deterministic (sorted by key) across
    /// runs. Order carries no runtime meaning: each `KEY=VALUE` is applied
    /// independently and values expand against the live environment.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Libraries dlopen'd on every exec by the bundled onelf-env
    /// constructor. Paths support `${ONELF_DIR}`. Survives sandboxed
    /// re-exec (DT_NEEDED + $ORIGIN RUNPATH), unlike `LD_PRELOAD`.
    #[serde(default)]
    pub preload: Vec<String>,
    /// Directories of the bundle made visible at the absolute paths an
    /// application compiled into itself. The key is the absolute path
    /// the application opens, the value is the directory in the bundle
    /// that should answer for it.
    #[serde(default)]
    pub paths: BTreeMap<String, String>,
}

/// The longest path an `[input]` names, in bytes.
const MAX_INPUT_PATH: usize = 4096;

/// `[input]`: files the build imports into the AppDir before assembly.
///
/// An imported binary is tracked by content hash like the rest of the
/// generated AppDir: a rebuild refreshes it from its source, and a
/// staged copy someone edited stops the build instead of being
/// silently overwritten.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Input {
    /// A bare executable the build copies to the package command's
    /// path before assembly, named relative to the recipe's directory.
    pub binary: Option<PathBuf>,
}

impl Input {
    /// Reject an `[input]` that cannot do anything, and path spellings
    /// the recipe-relative resolution rules refuse.
    pub fn validate(&self) -> std::io::Result<()> {
        let Some(binary) = &self.binary else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "[input] names no binary: there is nothing to import",
            ));
        };
        if binary.as_os_str().is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "[input] binary is empty",
            ));
        }
        if std::os::unix::ffi::OsStrExt::as_bytes(binary.as_os_str()).len() > MAX_INPUT_PATH {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("[input] binary is longer than the {MAX_INPUT_PATH} byte path limit"),
            ));
        }
        if binary.is_absolute() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "[input] binary must be relative to the recipe's directory",
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Package {
    pub name: Option<String>,
    pub command: String,
    pub output: Option<PathBuf>,
    #[serde(default)]
    pub working_dir: WorkingDirSpec,
    /// What the launch resolver may take from the host. `auto` (the
    /// default) decides from the bundle's contents.
    pub host_libs: Option<HostLibsSpec>,
    /// Let the runtime fall back to the persistent cache when no other
    /// execution mode works. Off by default, so a package leaves nothing
    /// on disk unless the publisher or the user asks for it.
    #[serde(default)]
    pub cache: bool,
    /// Run from the persistent cache before any other execution mode, for
    /// an app that records its own path in files that outlive it.
    /// Implies `cache`.
    #[serde(default)]
    pub prefer_cache: bool,
    /// Mark the default entrypoint memfd-eligible (overrides auto-detect).
    pub memfd: Option<bool>,
    /// The sets the package command selects, as written. An omitted list
    /// selects every declared set, an empty list selects none, and names
    /// select exactly those. Normalized against the recipe's
    /// `[sysroot]` declarations by [`SetSelections::normalize`].
    pub sets: Option<Vec<String>>,
    #[serde(default)]
    pub exclude: Vec<String>,
    /// Pin every entry's mtime to this Unix timestamp for reproducible
    /// output. Overrides filesystem mtimes and `SOURCE_DATE_EPOCH`.
    pub mtime: Option<u64>,
    pub version: Option<String>,
    pub description: Option<String>,
    pub license: Option<String>,
    pub homepage: Option<String>,
    /// Whether the app runs setuid binaries, such as an app that installs
    /// packages through `sudo` or `pkexec`.
    ///
    /// A setuid bit means nothing inside a user namespace the caller made
    /// itself: the owning uid is unmapped, so the file reads as `nobody` and
    /// the binary refuses. Saying so here keeps the app out of a namespace,
    /// at the cost of the modes that need one.
    #[serde(default)]
    pub needs_setuid: bool,
}

#[derive(Debug, Default, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WorkingDirSpec {
    #[default]
    Inherit,
    Package,
    Command,
}

impl From<WorkingDirSpec> for WorkingDir {
    fn from(s: WorkingDirSpec) -> Self {
        match s {
            WorkingDirSpec::Inherit => WorkingDir::Inherit,
            WorkingDirSpec::Package => WorkingDir::PackageRoot,
            WorkingDirSpec::Command => WorkingDir::EntrypointParent,
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Entrypoint {
    pub name: String,
    pub path: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub default: bool,
    /// The sets this entrypoint selects, as written. An omitted list
    /// selects every declared set, independently of the package
    /// command's list; an empty list selects none; names select exactly
    /// those.
    pub sets: Option<Vec<String>>,
}

/// Which of a recipe's declared sets one entrypoint selects.
///
/// An omitted `sets` list and a written one are deliberately distinct:
/// omission keeps the all-declared-set default every recipe without the
/// key has always had, while a written list, empty or not, says exactly
/// what applies.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum SetSelection {
    /// No `sets` list was written: every declared set applies.
    #[default]
    All,
    /// A `sets` list was written, in canonical (sorted) order: exactly
    /// these sets apply, possibly none.
    Names(Vec<String>),
}

impl SetSelection {
    /// Whether a `sets` list was written. An explicit selection makes
    /// the build nonlegacy, so it requires a runtime advertising the
    /// support carrying selection records needs.
    pub fn is_explicit(&self) -> bool {
        matches!(self, SetSelection::Names(_))
    }
}

/// The normalized primary and named set selections a recipe declares.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SetSelections {
    /// What the package command selects.
    pub primary: SetSelection,
    /// What each named entrypoint selects, by entrypoint name.
    pub named: BTreeMap<String, SetSelection>,
}

impl SetSelections {
    /// Normalize a recipe's `sets` lists into canonical form. Within one
    /// list, a repeated name and a name the recipe's `[sysroot]` does not
    /// declare are refused, naming the list they were written in, so a
    /// broken recipe fails at load and never reaches a build.
    ///
    /// A named entrypoint's omitted list stays omitted: it selects all
    /// declared sets and does not inherit the package command's list.
    /// A `[package]` list beside a default named entrypoint is refused:
    /// that entrypoint replaces the package command in the package's
    /// entrypoint table, so the list would select for nothing.
    pub fn normalize(recipe: &Recipe) -> std::io::Result<Self> {
        if recipe.package.sets.is_some()
            && let Some(default) = recipe.entrypoint.iter().find(|e| e.default)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "[package] sets has no entrypoint to apply to: entrypoint '{}' is the \
                     default and takes the package command's place. Write the list as \
                     that entrypoint's sets instead",
                    default.name
                ),
            ));
        }
        let declared: std::collections::BTreeSet<&str> = recipe
            .sysroot
            .as_ref()
            .map(|sr| sr.sets.keys().map(String::as_str).collect())
            .unwrap_or_default();
        let primary = normalize_list("[package]", recipe.package.sets.as_deref(), &declared)?;
        let mut named = BTreeMap::new();
        for entrypoint in &recipe.entrypoint {
            let what = format!("entrypoint '{}'", entrypoint.name);
            let selection = normalize_list(&what, entrypoint.sets.as_deref(), &declared)?;
            named.insert(entrypoint.name.clone(), selection);
        }
        Ok(Self { primary, named })
    }
}

/// Normalize one written `sets` list against the declared names: a
/// repeated name or a name nothing declares is refused naming the list
/// it was written in, and a written list is sorted into the canonical
/// order selection metadata uses.
fn normalize_list(
    what: &str,
    written: Option<&[String]>,
    declared: &std::collections::BTreeSet<&str>,
) -> std::io::Result<SetSelection> {
    let Some(names) = written else {
        return Ok(SetSelection::All);
    };
    let mut seen = std::collections::BTreeSet::new();
    for name in names {
        if !seen.insert(name.as_str()) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{what}: duplicate set name '{name}'"),
            ));
        }
        if !declared.contains(name.as_str()) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{what}: unknown set name '{name}': the recipe declares no such set"),
            ));
        }
    }
    let mut canonical: Vec<String> = names.to_vec();
    canonical.sort();
    Ok(SetSelection::Names(canonical))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Compression {
    #[serde(default = "default_level")]
    pub level: i32,
    /// Bytes per payload block, or the payload's default. See
    /// [`crate::pack::Payload::default_block_size`].
    pub block_size: Option<u64>,
    /// What the payload is made of. See [`crate::pack::Payload`].
    #[serde(default)]
    pub payload: PayloadSpec,
    #[serde(default)]
    pub dict: bool,
    /// Store the payload uncompressed (no zstd). Overrides `dict` and
    /// `level`. Larger file, zero decompression at runtime.
    #[serde(default)]
    pub store: bool,
    /// Startup profile recorded with `ONELF_PROFILE`, relative to the
    /// recipe. See [`crate::pack::read_profile`].
    pub prefetch: Option<PathBuf>,
}

impl Default for Compression {
    fn default() -> Self {
        Self {
            level: default_level(),
            block_size: None,
            payload: PayloadSpec::default(),
            dict: false,
            store: false,
            prefetch: None,
        }
    }
}

fn default_level() -> i32 {
    // 19 rather than 12: measured on a real bundle it is 6% smaller for
    // pack-time cost only, and 22 buys nothing further.
    19
}

/// Recipe spelling of the payload format.
#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PayloadSpec {
    #[default]
    Blocks,
    Stipple,
}

impl From<PayloadSpec> for crate::pack::Payload {
    fn from(v: PayloadSpec) -> Self {
        match v {
            PayloadSpec::Blocks => crate::pack::Payload::Blocks,
            PayloadSpec::Stipple => crate::pack::Payload::Stipple,
        }
    }
}

/// Recipe spelling of the host library policy.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HostLibsSpec {
    Auto,
    Always,
    Never,
}

impl From<HostLibsSpec> for crate::pack::HostLibs {
    fn from(v: HostLibsSpec) -> Self {
        match v {
            HostLibsSpec::Auto => crate::pack::HostLibs::Auto,
            HostLibsSpec::Always => crate::pack::HostLibs::Always,
            HostLibsSpec::Never => crate::pack::HostLibs::Never,
        }
    }
}

/// `[sysroot]`: a materialized rootfs whose package database decides the
/// bundle's contents. Paths are relative to the recipe.
///
/// With `path` the bundle is the closure of the entrypoint's package.
/// Without one there is no package database, so the AppDir stays exactly
/// as the author assembled it and only the sets (and an explicit GL
/// build pin) are recorded for the runtime to fetch at launch.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Sysroot {
    /// The materialized rootfs, when the bundle is taken from a package
    /// database. Absent leaves the AppDir alone and records only the
    /// sets.
    pub path: Option<PathBuf>,
    /// An archive to materialize into `path` when it does not exist yet:
    /// a path relative to the recipe, or an `https://` URL.
    pub archive: Option<PathBuf>,
    /// The archive's BLAKE3 hash. When set, an archive that does not
    /// match is not unpacked.
    pub hash: Option<String>,
    /// A label for this sysroot, recorded in the package's provenance.
    /// Defaults to the archive's file name, or the directory's name.
    pub platform: Option<String>,
    /// Optional dependencies to include, by package name.
    #[serde(default)]
    pub optional: Vec<String>,
    /// File of soname prefixes the host provides, one per line.
    pub platform_line: Option<PathBuf>,
    /// File of glob patterns that never ship, one per line.
    pub policy: Option<PathBuf>,
    /// File of paths a test run opened, one per line.
    pub trace: Option<PathBuf>,
    /// File of glob patterns the trace may not prune.
    pub keep: Option<PathBuf>,
    /// URL of the GL build for hosts without one, overriding what the
    /// sysroot's `etc/onelf/platform.toml` names.
    pub platform_url: Option<String>,
    /// BLAKE3 hash of that build, overriding the sysroot's.
    pub platform_hash: Option<String>,
    /// Dependency sets shared between packages: sysroot packages whose
    /// closure the bundle leaves out and a pinned build supplies.
    #[serde(default)]
    pub sets: BTreeMap<String, SharedSet>,
}

impl Sysroot {
    /// Reject a `[sysroot]` that cannot do anything, and sysroot-database
    /// keys used without the database they belong to.
    ///
    /// Without `path` there is no package database: no closure to take
    /// the bundle from, no archive to materialize, no owner to look up.
    /// The AppDir then stands as the author assembled it, and the only
    /// things left to record are the sets and an explicit GL build pin.
    pub fn validate(&self) -> std::io::Result<()> {
        if self.path.is_some() {
            return Ok(());
        }
        let database_keys: &[(&str, bool)] = &[
            ("archive", self.archive.is_some()),
            ("hash", self.hash.is_some()),
            ("platform", self.platform.is_some()),
            ("optional", !self.optional.is_empty()),
            ("platform-line", self.platform_line.is_some()),
            ("policy", self.policy.is_some()),
            ("trace", self.trace.is_some()),
            ("keep", self.keep.is_some()),
        ];
        for (name, present) in database_keys {
            if *present {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "[sysroot] {name} is a sysroot-database concept and needs path: \
                         without it there is no package database to apply it to"
                    ),
                ));
            }
        }
        if self.sets.is_empty() && self.platform_url.is_none() && self.platform_hash.is_none() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "[sysroot] names neither path nor sets: there is nothing to record",
            ));
        }
        Ok(())
    }
}

/// One shared dependency set: the sysroot packages it holds, made into a
/// build with `onelf sysroot pack-set`, and where that build is fetched
/// from, pinned by hash.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct SharedSet {
    pub packages: Vec<String>,
    pub url: String,
    pub blake3: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Update {
    pub url: String,
    /// Path to a file with the raw 32-byte Ed25519 public key used to
    /// verify signed self-updates.
    pub key: Option<PathBuf>,
    /// Release number stamped into the package as
    /// `.onelf/update-revision`. The runtime refuses downloads that are
    /// not strictly newer than the running revision.
    pub revision: Option<u64>,
    /// Accept unsigned self-updates: the package stores no signing key
    /// and its runtime installs whatever the update URL serves,
    /// warning on stderr every time. HTTPS is still required.
    #[serde(default)]
    pub unsigned: bool,
    /// Embed the update-capable runtime. Defaults to true. False records
    /// the URL and key but links the slim runtime, for packages updated
    /// by a package manager rather than by themselves.
    pub embed: Option<bool>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Bundle {
    /// If absent, defaults to ["auto"]. An empty list disables bundling.
    pub lib_dirs: Option<Vec<String>>,
    #[serde(default)]
    pub search_paths: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub gl: bool,
    #[serde(default)]
    pub dri: bool,
    #[serde(default)]
    pub vulkan: bool,
    #[serde(default)]
    pub wayland: bool,
    #[serde(default)]
    pub gtk: bool,
    /// Opt out of a framework even when auto-detection would enable it.
    #[serde(default)]
    pub no_gl: bool,
    #[serde(default)]
    pub no_dri: bool,
    #[serde(default)]
    pub no_vulkan: bool,
    #[serde(default)]
    pub no_wayland: bool,
    #[serde(default)]
    pub no_gtk: bool,
    #[serde(default)]
    pub strip: bool,
    #[serde(default)]
    pub strict_libc: bool,
    #[serde(default)]
    pub scan_dlopen: bool,
    /// Extra sonames added to the --scan-dlopen allow-list.
    #[serde(default)]
    pub dlopen: Vec<String>,
    /// Run the command and bundle every library it loaded at runtime.
    #[serde(default)]
    pub trace_run: bool,
    /// How long the traced run may go before it is stopped; 5 by default.
    #[serde(default)]
    pub trace_seconds: Option<u64>,
    /// Arguments for the traced run.
    #[serde(default)]
    pub trace_args: Vec<String>,
    /// Keep only what a trace observed in the directories inference
    /// collects: a data directory keeps the members the trace opened,
    /// the recipe's keep patterns name and the kept relative links'
    /// targets, a plugin directory keeps the members the trace loaded,
    /// their dependencies and the keep patterns. Needs a trace:
    /// `trace-run`, or `[sysroot] trace`. A traced run of a glibc
    /// target sees only the modules the loader maps, so there only
    /// plugin objects are trimmed and data is carried whole; runs of a
    /// musl target and sysroot traces record file opens.
    #[serde(default)]
    pub trim_inferred: bool,
    /// Skip running bundle-libs entirely (e.g. pre-bundled AppDir).
    #[serde(default)]
    pub skip: bool,
    /// Project-local framework descriptor files, relative to the recipe
    /// directory. Their identities extend the built-in catalog and may
    /// not repeat a built-in identity.
    #[serde(default)]
    pub rules: Vec<PathBuf>,
    /// Built-in or local rule identities that never activate and whose
    /// runtime mappings are not carried.
    #[serde(default)]
    pub disable_rules: Vec<String>,
}

/// Load a recipe from a file path. `${VAR}` references in string
/// values are expanded from environment variables after parsing, so
/// any string field can use them:
///
/// ```toml
/// [package]
/// version = "${PKG_VERSION}"
/// ```
///
/// A variable that is not set is kept as written, so the runtime can
/// still expand it (see [`expand_env`]). Returns an io::Error with a
/// descriptive message on failure (parse errors are converted via
/// `InvalidData`).
pub fn load(path: &Path) -> std::io::Result<Recipe> {
    let raw = std::fs::read_to_string(path).map_err(|e| match e.kind() {
        std::io::ErrorKind::InvalidData => std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "{}: not a valid recipe (expected a TOML file)",
                path.display()
            ),
        ),
        _ => std::io::Error::new(e.kind(), format!("{}: {e}", path.display())),
    })?;
    // Parse first, then expand `${VAR}` inside string *values* only. Doing
    // it after the structure is fixed means an expanded value containing a
    // quote or newline can never introduce new recipe keys.
    let mut value: toml::Value = toml::from_str(&raw).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("{}: {e}", path.display()),
        )
    })?;
    expand_value(&mut value);
    let recipe: Recipe = value.try_into().map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("{}: {e}", path.display()),
        )
    })?;
    if let Some(sr) = &recipe.sysroot {
        sr.validate().map_err(|e| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{}: {e}", path.display()),
            )
        })?;
    }
    if recipe.bundle.trim_inferred {
        let traced = match &recipe.sysroot {
            // A sysroot build trims by its recorded trace alone: the
            // traced host run cannot apply to it. A section without a
            // path pins sets on a host scan, so the traced host run
            // is the trace that applies.
            Some(sr) if sr.path.is_some() => sr.trace.is_some(),
            _ => recipe.bundle.trace_run,
        };
        if !traced {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "{}: [bundle] trim-inferred is set, but no trace applies to it: \
                     set [sysroot] trace on a sysroot build, or trace-run on a host scan",
                    path.display()
                ),
            ));
        }
    }
    if let Some(input) = &recipe.input {
        input.validate().map_err(|e| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("{}: {e}", path.display()),
            )
        })?;
    }
    SetSelections::normalize(&recipe).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("{}: {e}", path.display()),
        )
    })?;
    Ok(recipe)
}

/// Recursively expand `${VAR}` references in every string value of a parsed
/// TOML document. Keys are left untouched, so expansion can only ever change
/// values, never the document structure.
fn expand_value(value: &mut toml::Value) {
    match value {
        toml::Value::String(s) => *s = expand_env(s),
        toml::Value::Array(a) => a.iter_mut().for_each(expand_value),
        toml::Value::Table(t) => t.iter_mut().for_each(|(_, v)| expand_value(v)),
        _ => {}
    }
}

/// Resolve a recipe file from a user-supplied spec:
/// - If `spec` is a directory, use `<spec>/onelf.toml`.
/// - If `spec` is a file with a `.toml` extension, use it.
/// - Otherwise error, since the input is not something this tool can read.
pub fn resolve(spec: &Path) -> std::io::Result<PathBuf> {
    if spec.is_dir() {
        return Ok(spec.join("onelf.toml"));
    }
    if !spec.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("{}: no such file or directory", spec.display()),
        ));
    }
    if spec.extension().and_then(|s| s.to_str()) != Some("toml") {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            format!(
                "{}: expected a directory containing onelf.toml or a .toml file",
                spec.display()
            ),
        ));
    }
    Ok(spec.to_path_buf())
}

/// Expand `${VAR}` references in a string from the **packer's**
/// environment at recipe-load time. Variables not set are preserved
/// as-is (e.g. `${ONELF_DIR}` stays literal so the runtime can expand
/// it later).
///
/// `$$` is an escape for a literal `$`: it is emitted as a single `$`
/// and never triggers pack-time expansion. This lets a recipe defer a
/// reference to **runtime**, e.g. `PATH = "${ONELF_DIR}/bin:$${PATH}"`
/// reaches `.onelf/env` as `${ONELF_DIR}/bin:${PATH}` and the runtime
/// (onelf-rt / the onelf-env constructor) expands `${PATH}` against the
/// live process environment, so it prepends instead of replacing.
pub fn expand_env(s: &str) -> String {
    let bytes = s.as_bytes();
    // Accumulate raw bytes: the input is UTF-8 and every spliced fragment
    // (env values and preserved source slices) is UTF-8, so the result is
    // valid UTF-8. This avoids the `bytes[i] as char` path that mangled
    // multi-byte sequences into mojibake.
    let mut out: Vec<u8> = Vec::with_capacity(s.len());
    let mut i = 0;
    while i < bytes.len() {
        // `$$` -> literal `$` (escape; defers any following `{VAR}` to
        // runtime since the `${` pattern is no longer present).
        if bytes[i] == b'$' && i + 1 < bytes.len() && bytes[i + 1] == b'$' {
            out.push(b'$');
            i += 2;
            continue;
        }
        if bytes[i] == b'$'
            && i + 1 < bytes.len()
            && bytes[i + 1] == b'{'
            && let Some(end) = bytes[i + 2..].iter().position(|&b| b == b'}')
        {
            let name = std::str::from_utf8(&bytes[i + 2..i + 2 + end]).unwrap_or("");
            match std::env::var(name) {
                Ok(val) => out.extend_from_slice(val.as_bytes()),
                // Preserve unset variables for runtime expansion.
                Err(_) => out.extend_from_slice(&bytes[i..i + 3 + end]),
            }
            i += 3 + end;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

#[cfg(test)]
mod package_tests {
    use super::load;

    fn load_result(body: &str) -> std::io::Result<super::Recipe> {
        let dir = std::env::temp_dir().join(format!(
            "onelf-recipe-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("onelf.toml");
        std::fs::write(&path, body).unwrap();
        let recipe = load(&path);
        std::fs::remove_dir_all(&dir).unwrap();
        recipe
    }

    fn load_str(body: &str) -> super::Recipe {
        load_result(body).unwrap()
    }

    #[test]
    fn a_sysroot_section_parses_with_relative_paths() {
        let recipe = load_str(
            "[package]\ncommand = \"bin/app\"\n\n[sysroot]\npath = \"sysroot\"\narchive = \"root.tar.zst\"\noptional = [\"extra\"]\nplatform-line = \"platform.txt\"\npolicy = \"policy.txt\"\n",
        );
        let sr = recipe.sysroot.expect("section present");
        assert_eq!(sr.path, Some(std::path::PathBuf::from("sysroot")));
        assert_eq!(
            sr.archive.as_deref(),
            Some(std::path::Path::new("root.tar.zst"))
        );
        assert_eq!(sr.optional, ["extra"]);
        assert!(sr.trace.is_none());
        assert!(sr.platform.is_none());
        let recipe = load_str(
            "[package]\ncommand = \"bin/app\"\n\n[sysroot]\npath = \"sysroot\"\nplatform = \"platform-1\"\n",
        );
        let sr = recipe.sysroot.unwrap();
        assert_eq!(sr.platform.as_deref(), Some("platform-1"));
        assert!(sr.platform_url.is_none() && sr.platform_hash.is_none());
        let recipe = load_str(
            "[package]\ncommand = \"bin/app\"\n\n[sysroot]\npath = \"sysroot\"\nplatform-url = \"https://e/gl.onelf\"\nplatform-hash = \"abc\"\n",
        );
        let sr = recipe.sysroot.unwrap();
        assert_eq!(sr.platform_url.as_deref(), Some("https://e/gl.onelf"));
        assert_eq!(sr.platform_hash.as_deref(), Some("abc"));
        assert!(
            load_str("[package]\ncommand = \"bin/app\"\n")
                .sysroot
                .is_none()
        );
    }

    #[test]
    fn cache_defaults_off_and_parses_on() {
        let recipe = load_str("[package]\ncommand = \"bin/app\"\n");
        assert!(!recipe.package.cache);

        let recipe = load_str("[package]\ncommand = \"bin/app\"\ncache = true\n");
        assert!(recipe.package.cache);
        assert!(!recipe.package.prefer_cache);

        let recipe = load_str("[package]\ncommand = \"bin/app\"\nprefer-cache = true\n");
        assert!(recipe.package.prefer_cache);
    }

    const HASH: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

    /// A `[sysroot]` with only sets has no package database: the AppDir
    /// is the author's own, and the sets are recorded for the runtime.
    #[test]
    fn a_sysroot_with_only_sets_parses() {
        let recipe = load_str(&format!(
            "[package]\ncommand = \"bin/app\"\n\n[sysroot.sets.gtk]\npackages = [\"gtk3\"]\nurl = \"https://e/gtk.onelf\"\nblake3 = \"{HASH}\"\n"
        ));
        let sr = recipe.sysroot.expect("section present");
        assert!(sr.path.is_none());
        assert_eq!(sr.sets["gtk"].packages, ["gtk3"]);
        assert_eq!(sr.sets["gtk"].url, "https://e/gtk.onelf");
        assert_eq!(sr.sets["gtk"].blake3, HASH);
    }

    #[test]
    fn a_sysroot_with_neither_path_nor_sets_is_refused() {
        let err = load_result("[package]\ncommand = \"bin/app\"\n\n[sysroot]\n").unwrap_err();
        assert!(err.to_string().contains("neither path nor sets"), "{err}");
    }

    /// Every key that names a package-database concept is a typo waiting
    /// to be ignored when there is no database to apply it to.
    #[test]
    fn sysroot_database_keys_are_refused_without_a_path() {
        let hash = HASH;
        let bodies = [
            "[sysroot]\narchive = \"root.tar.zst\"\n",
            "[sysroot]\nhash = \"abc\"\n",
            "[sysroot]\nplatform = \"platform-1\"\n",
            "[sysroot]\noptional = [\"mesa\"]\n",
            "[sysroot]\nplatform-line = \"line.txt\"\n",
            "[sysroot]\npolicy = \"policy.txt\"\n",
            "[sysroot]\ntrace = \"trace.txt\"\n",
            "[sysroot]\nkeep = \"keep.txt\"\n",
        ];
        for body in bodies {
            let err =
                load_result(&format!("[package]\ncommand = \"bin/app\"\n\n{body}")).unwrap_err();
            assert!(err.to_string().contains("needs path"), "{body}: {err}");
        }
        // The GL build pin keeps its meaning without a database: both
        // fields name a build to fetch, nothing more.
        let recipe = load_str(&format!(
            "[package]\ncommand = \"bin/app\"\n\n[sysroot]\nplatform-url = \"https://e/gl.onelf\"\nplatform-hash = \"{hash}\"\n"
        ));
        let sr = recipe.sysroot.unwrap();
        assert!(sr.path.is_none());
        assert_eq!(sr.platform_url.as_deref(), Some("https://e/gl.onelf"));
    }
}

#[cfg(test)]
mod input_tests {
    use super::load;

    fn load_result(body: &str) -> std::io::Result<super::Recipe> {
        let dir = std::env::temp_dir().join(format!(
            "onelf-recipe-input-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("onelf.toml");
        std::fs::write(&path, body).unwrap();
        let recipe = load(&path);
        std::fs::remove_dir_all(&dir).unwrap();
        recipe
    }

    #[test]
    fn an_input_section_parses_a_recipe_relative_binary() {
        let recipe = load_result(
            "[package]\ncommand = \"bin/app\"\n\n[input]\nbinary = \"../upstream/app\"\n",
        )
        .unwrap();
        let input = recipe.input.expect("section present");
        assert_eq!(
            input.binary,
            Some(std::path::PathBuf::from("../upstream/app"))
        );
        let bare = load_result("[package]\ncommand = \"bin/app\"\n").unwrap();
        assert!(bare.input.is_none());
    }

    #[test]
    fn an_unknown_input_field_is_refused() {
        let err = load_result("[package]\ncommand = \"bin/app\"\n\n[input]\nbinaryy = \"app\"\n")
            .unwrap_err();
        assert!(err.to_string().contains("unknown field"), "{err}");
    }

    #[test]
    fn an_input_that_names_nothing_is_refused() {
        let err = load_result("[package]\ncommand = \"bin/app\"\n\n[input]\n").unwrap_err();
        assert!(err.to_string().contains("names no binary"), "{err}");
    }

    #[test]
    fn an_absolute_or_empty_binary_is_refused() {
        let err =
            load_result("[package]\ncommand = \"bin/app\"\n\n[input]\nbinary = \"/bin/app\"\n")
                .unwrap_err();
        assert!(err.to_string().contains("must be relative"), "{err}");
        let err = load_result("[package]\ncommand = \"bin/app\"\n\n[input]\nbinary = \"\"\n")
            .unwrap_err();
        assert!(err.to_string().contains("is empty"), "{err}");
    }

    #[test]
    fn an_over_long_binary_path_is_refused() {
        let long = "a".repeat(super::MAX_INPUT_PATH + 1);
        let body = format!("[package]\ncommand = \"bin/app\"\n\n[input]\nbinary = \"{long}\"\n");
        let err = load_result(&body).unwrap_err();
        assert!(err.to_string().contains("path limit"), "{err}");
    }
}

#[cfg(test)]
mod expand_tests {
    use super::expand_env;

    #[test]
    fn dollar_dollar_escapes_and_defers_to_runtime() {
        // $$ -> literal $
        assert_eq!(expand_env("a$$b"), "a$b");
        // $${VAR} must reach the output as ${VAR} (NOT pack-expanded),
        // so the runtime expands it -> PATH prepend instead of replace.
        assert_eq!(
            expand_env("${ONELF_DIR}/bin:$${PATH}"),
            "${ONELF_DIR}/bin:${PATH}"
        );
        // $$ + POSIX default must survive pack-time intact for runtime.
        assert_eq!(
            expand_env("${ONELF_DIR}/bin:$${PATH:-/usr/bin:/bin}"),
            "${ONELF_DIR}/bin:${PATH:-/usr/bin:/bin}"
        );
    }

    #[test]
    fn unset_vars_are_preserved_for_runtime() {
        assert_eq!(expand_env("x${ONELF_DIR}y"), "x${ONELF_DIR}y");
        assert_eq!(
            expand_env("${ONELF_THIS_IS_NOT_SET_4f3a}"),
            "${ONELF_THIS_IS_NOT_SET_4f3a}"
        );
    }

    #[test]
    fn expand_preserves_non_ascii() {
        // Non-ASCII in the literal (non-`${}`) parts must be copied
        // byte-for-byte; the old `bytes[i] as char` path mangled multi-byte
        // UTF-8 into mojibake. No process-env mutation needed: an unset
        // `${VAR}` is preserved verbatim, so the surrounding text carries
        // the assertion.
        assert_eq!(
            expand_env("café ☕ Ω ${ONELF_UNSET_9q}"),
            "café ☕ Ω ${ONELF_UNSET_9q}"
        );
    }
}
#[cfg(test)]
mod selection_tests {
    use super::{SetSelection, SetSelections, load};

    fn load_result(body: &str) -> std::io::Result<super::Recipe> {
        let dir = std::env::temp_dir().join(format!(
            "onelf-recipe-sets-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("onelf.toml");
        std::fs::write(&path, body).unwrap();
        let recipe = load(&path);
        std::fs::remove_dir_all(&dir).unwrap();
        recipe
    }

    fn load_str(body: &str) -> super::Recipe {
        load_result(body).unwrap()
    }

    fn selections(body: &str) -> SetSelections {
        SetSelections::normalize(&load_str(body)).unwrap()
    }

    const SETS: &str = "[sysroot.sets.gtk]\npackages = [\"gtk3\"]\nurl = \"https://e/gtk.onelf\"\nblake3 = \"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\"\n\n[sysroot.sets.audio]\npackages = [\"pipewire\"]\nurl = \"https://e/audio.onelf\"\nblake3 = \"fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210\"\n";

    fn recipe(body: &str) -> String {
        format!("[package]\ncommand = \"bin/app\"\n{body}\n{SETS}\n")
    }

    /// Omission and an explicit empty list are distinct answers: the
    /// first keeps every declared set, the second keeps none.
    #[test]
    fn an_omitted_list_selects_all_and_an_empty_list_selects_none() {
        let s = selections(&recipe(
            "\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\nsets = []\n",
        ));
        assert_eq!(s.primary, SetSelection::All);
        assert_eq!(s.named["cli"], SetSelection::Names(Vec::new()));
        assert!(s.named["cli"].is_explicit());
        let all = selections(&recipe(
            "\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\n",
        ));
        assert_eq!(all.primary, SetSelection::All);
        assert_eq!(all.named["cli"], SetSelection::All);
        assert!(!all.named["cli"].is_explicit());
    }

    /// A written list normalizes to canonical order, whatever order the
    /// author wrote, so selection metadata never depends on list order.
    #[test]
    fn an_explicit_list_is_normalized_to_canonical_order() {
        let s = selections(&recipe("sets = [\"audio\", \"gtk\"]\n"));
        assert_eq!(
            s.primary,
            SetSelection::Names(vec!["audio".to_string(), "gtk".to_string()])
        );
        assert!(s.primary.is_explicit());
    }

    /// One name written twice in one list is refused, for the package
    /// command and for a named entrypoint alike, naming the list.
    #[test]
    fn a_duplicate_set_name_is_refused_with_attribution() {
        let err = load_result(&recipe("sets = [\"gtk\", \"gtk\"]\n")).unwrap_err();
        assert!(
            err.to_string()
                .contains("[package]: duplicate set name 'gtk'"),
            "{err}"
        );
        let err = load_result(&recipe(
            "\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\nsets = [\"audio\", \"audio\"]\n",
        ))
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("entrypoint 'cli': duplicate set name 'audio'"),
            "{err}"
        );
    }

    /// A name the recipe's `[sysroot]` does not declare is refused,
    /// naming the list it was written in.
    #[test]
    fn an_unknown_set_name_is_refused_with_attribution() {
        let err = load_result(&recipe("sets = [\"gui\"]\n")).unwrap_err();
        assert!(
            err.to_string()
                .contains("[package]: unknown set name 'gui'"),
            "{err}"
        );
        let err = load_result(&recipe(
            "\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\nsets = [\"gtk\", \"gfx\"]\n",
        ))
        .unwrap_err();
        assert!(
            err.to_string()
                .contains("entrypoint 'cli': unknown set name 'gfx'"),
            "{err}"
        );
    }

    /// A named entrypoint's omitted list does not inherit the package
    /// command's explicit list: each list is its own answer.
    #[test]
    fn a_named_omission_does_not_inherit_the_primary_list() {
        let s = selections(&recipe(
            "sets = [\"gtk\"]\n\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\n",
        ));
        assert_eq!(s.primary, SetSelection::Names(vec!["gtk".to_string()]));
        assert_eq!(s.named["cli"], SetSelection::All);
    }

    /// A default named entrypoint replaces the package command in the
    /// entrypoint table, so a `[package]` list beside it would apply to
    /// nothing: the recipe is refused at load, naming the entrypoint,
    /// whether or not the default writes a list of its own.
    #[test]
    fn a_package_list_beside_a_default_entrypoint_is_refused() {
        for own in ["", "sets = [\"audio\"]\n"] {
            let err = load_result(&recipe(&format!(
                "sets = [\"gtk\"]\n\n[[entrypoint]]\nname = \"gui\"\npath = \"bin/app\"\n\
                 default = true\n{own}"
            )))
            .unwrap_err();
            let text = err.to_string();
            assert!(text.contains("[package] sets"), "{text}");
            assert!(text.contains("entrypoint 'gui' is the default"), "{text}");
        }
        let s = selections(&recipe(
            "\n[[entrypoint]]\nname = \"gui\"\npath = \"bin/app\"\ndefault = true\nsets = [\"gtk\"]\n",
        ));
        assert_eq!(s.named["gui"], SetSelection::Names(vec!["gtk".to_string()]));
    }

    /// With nothing declared, an omitted list still selects all (of
    /// nothing) and an explicit empty list is still valid, but any name
    /// is unknown.
    #[test]
    fn selections_without_declared_sets_stay_consistent() {
        let s = selections(
            "[package]\ncommand = \"bin/app\"\n\n[[entrypoint]]\nname = \"cli\"\npath = \"bin/app\"\n",
        );
        assert_eq!(s.primary, SetSelection::All);
        assert_eq!(s.named["cli"], SetSelection::All);
        let s = selections("[package]\ncommand = \"bin/app\"\nsets = []\n");
        assert_eq!(s.primary, SetSelection::Names(Vec::new()));
        let err = load_result("[package]\ncommand = \"bin/app\"\nsets = [\"gtk\"]\n").unwrap_err();
        assert!(err.to_string().contains("unknown set name 'gtk'"), "{err}");
    }
}

// The `${VAR}` injection-safety regression is covered by an integration
// test (`recipe_expansion_cannot_inject_keys` in tests/pipeline.rs), which
// sets the variable on a child process rather than mutating this process's
// environment.