phora 0.6.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
//! Target DTOs and deploy layout resolution.

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

use globset::{Glob, GlobSet, GlobSetBuilder};
use serde::Deserialize;

use super::TargetHooks;
use super::source::{ParsedSource, Refspec, Source};

const TMPL_SUFFIX: &str = ".tmpl";

/// Per-binding template opt-in. The `.tmpl` suffix convention is on by
/// default; a glob list opts additional files in; `template = false` disables
/// everything, including the suffix.
#[derive(Debug, Clone)]
pub enum TemplateOptIn {
    /// No `template` key: only the `.tmpl` suffix convention renders.
    SuffixOnly,
    /// A `template` glob list: matching files render, plus any `.tmpl` file.
    Globs(GlobSet),
    /// `template = false`: nothing renders, no suffix is stripped.
    Disabled,
}

impl TemplateOptIn {
    /// True when `path` renders: it matches a template glob, or ends in `.tmpl` —
    /// unless rendering is disabled.
    #[must_use]
    pub fn renders(&self, path: &str) -> bool {
        let suffix_opts_in = path.ends_with(TMPL_SUFFIX) && path != TMPL_SUFFIX;
        match self {
            Self::SuffixOnly => suffix_opts_in,
            Self::Globs(set) => set.is_match(path) || suffix_opts_in,
            Self::Disabled => false,
        }
    }

    /// The deployed name: strips a trailing `.tmpl` only when the file renders;
    /// otherwise the name is unchanged.
    #[must_use]
    pub fn deployed_name(&self, path: &str) -> String {
        if self.renders(path)
            && let Some(stripped) = path.strip_suffix(TMPL_SUFFIX)
            && !stripped.is_empty()
        {
            return stripped.to_owned();
        }
        path.to_owned()
    }
}

impl<'de> Deserialize<'de> for TemplateOptIn {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct TemplateVisitor;

        impl<'de> serde::de::Visitor<'de> for TemplateVisitor {
            type Value = TemplateOptIn;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("`false` to disable templating, or a list of glob strings")
            }

            fn visit_bool<E: serde::de::Error>(
                self,
                v: bool,
            ) -> std::result::Result<Self::Value, E> {
                if v {
                    return Err(E::custom(
                        "`template = true` is not valid; omit the key for the default .tmpl opt-in, or give a glob list",
                    ));
                }
                Ok(TemplateOptIn::Disabled)
            }

            fn visit_seq<A: serde::de::SeqAccess<'de>>(
                self,
                mut seq: A,
            ) -> std::result::Result<Self::Value, A::Error> {
                let mut builder = GlobSetBuilder::new();
                let mut count = 0usize;
                while let Some(pattern) = seq.next_element::<String>()? {
                    let glob = Glob::new(&pattern).map_err(serde::de::Error::custom)?;
                    builder.add(glob);
                    count += 1;
                }
                if count == 0 {
                    return Err(serde::de::Error::custom(
                        "template glob list must not be empty; omit the key for the default .tmpl opt-in, or use `template = false` to disable",
                    ));
                }
                let set = builder.build().map_err(serde::de::Error::custom)?;
                Ok(TemplateOptIn::Globs(set))
            }
        }

        deserializer.deserialize_any(TemplateVisitor)
    }
}

/// A binding of a transitive source, moved out of `sources` by `lower_transitive`.
#[derive(Debug, Clone)]
pub struct OfferBinding {
    pub identity: String,
    pub binding: Binding,
}

impl OfferBinding {
    #[must_use]
    pub fn source(&self) -> &str {
        self.binding.effective_source(&self.identity)
    }

    #[must_use]
    pub fn offer(&self) -> &str {
        self.binding.offer.as_deref().unwrap_or(DEFAULT_OFFER)
    }

    #[must_use]
    pub fn refspec(&self) -> Option<Refspec> {
        let binding = &self.binding;
        [
            binding.rev.clone().map(Refspec::Rev),
            binding.tag.clone().map(Refspec::Tag),
            binding.branch.clone().map(Refspec::Branch),
        ]
        .into_iter()
        .flatten()
        .next()
    }

    /// Refines only the ref of an already resolved source.
    pub(crate) fn resolve(&self, source: &ParsedSource) -> crate::error::Result<ParsedSource> {
        let Some(refspec) = self.refspec() else {
            return Ok(source.clone());
        };
        if source.mode() == super::SourceMode::Url {
            return Err(crate::error::Error::Config(format!(
                "binding `{}`: a URL source cannot select a Git ref",
                self.identity
            )));
        }
        let mut source = source.clone();
        source.branch = None;
        source.tag = None;
        source.rev = None;
        match refspec {
            Refspec::Branch(value) => source.branch = Some(value),
            Refspec::Tag(value) => source.tag = Some(value),
            Refspec::Rev(value) => source.rev = Some(value),
            Refspec::Default | Refspec::None => {}
        }
        Ok(source)
    }
}

/// The offer a binding of a transitive source gets when it names none.
pub const DEFAULT_OFFER: &str = "default";

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Target {
    pub path: PathBuf,
    #[serde(default, deserialize_with = "deserialize_bindings")]
    pub sources: Option<BTreeMap<String, Binding>>,
    pub layout: Option<LayoutConfig>,
    #[serde(default)]
    pub hooks: Option<TargetHooks>,
    #[serde(skip)]
    pub offer_bindings: Option<Vec<OfferBinding>>,
    /// Composition-only anchor every destination must stay under; `Some` iff this is a composed dep target.
    #[serde(skip)]
    pub confine: Option<PathBuf>,
}

#[derive(Debug, Clone)]
pub enum TakeEntry {
    Leaf(String),
    Rename { src: String, dest: String },
}

impl<'de> Deserialize<'de> for TakeEntry {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct TakeEntryVisitor;

        impl<'de> serde::de::Visitor<'de> for TakeEntryVisitor {
            type Value = TakeEntry;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a leaf path string or a single-pair rename table")
            }

            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> std::result::Result<Self::Value, E> {
                Ok(TakeEntry::Leaf(v.to_owned()))
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut map: A,
            ) -> std::result::Result<Self::Value, A::Error> {
                let Some((src, dest)) = map.next_entry::<String, String>()? else {
                    return Err(serde::de::Error::custom(
                        "a `take` rename table must carry one source-to-destination pair",
                    ));
                };
                if let Some((extra_src, _)) = map.next_entry::<String, String>()? {
                    return Err(serde::de::Error::custom(format!(
                        "a `take` rename entry must carry exactly one pair; \
                         drop the extra pair `{extra_src}` into its own entry"
                    )));
                }
                Ok(TakeEntry::Rename { src, dest })
            }
        }

        deserializer.deserialize_any(TakeEntryVisitor)
    }
}

/// A per-target binding value. The map key is the binding identity; `source`
/// overrides the effective source only when the alias diverges from the key.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
    pub source: Option<String>,
    pub branch: Option<String>,
    pub tag: Option<String>,
    pub rev: Option<String>,
    #[serde(default)]
    pub template: Option<TemplateOptIn>,
    #[serde(default)]
    pub take: Option<Vec<TakeEntry>>,
    #[serde(default)]
    pub collapse: Option<bool>,
    #[serde(default)]
    pub history: bool,
    #[serde(default)]
    pub offer: Option<String>,
    /// The `take` of the consumer binding that composed this target, applied to its output.
    #[serde(skip)]
    pub composed_take: Option<Vec<TakeEntry>>,
}

impl Binding {
    /// The effective source name: the explicit `source` field, else the
    /// binding's identity (its map key).
    #[must_use]
    pub fn effective_source<'a>(&'a self, identity: &'a str) -> &'a str {
        self.source.as_deref().unwrap_or(identity)
    }

    /// A history binding deploys its git checkout verbatim, so nothing renders.
    #[must_use]
    pub fn template_opt_in(&self) -> TemplateOptIn {
        if self.history {
            return TemplateOptIn::Disabled;
        }
        self.template.clone().unwrap_or(TemplateOptIn::SuffixOnly)
    }
}

fn deserialize_bindings<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<BTreeMap<String, Binding>>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    struct BindingsVisitor;

    impl<'de> serde::de::Visitor<'de> for BindingsVisitor {
        type Value = Option<BTreeMap<String, Binding>>;

        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a keyed binding table or a flat list of source names")
        }

        fn visit_seq<A: serde::de::SeqAccess<'de>>(
            self,
            mut seq: A,
        ) -> std::result::Result<Self::Value, A::Error> {
            let mut map = BTreeMap::new();
            while let Some(name) = seq.next_element::<String>()? {
                if map.insert(name.clone(), Binding::default()).is_some() {
                    return Err(serde::de::Error::custom(format!(
                        "duplicate source `{name}` in the `sources` list"
                    )));
                }
            }
            Ok(Some(map))
        }

        fn visit_map<A: serde::de::MapAccess<'de>>(
            self,
            mut map: A,
        ) -> std::result::Result<Self::Value, A::Error> {
            let mut out = BTreeMap::new();
            while let Some((key, binding)) = map.next_entry::<String, Binding>()? {
                out.insert(key, binding);
            }
            Ok(Some(out))
        }
    }

    deserializer.deserialize_any(BindingsVisitor)
}

#[derive(Debug)]
pub struct ResolvedBinding<'a> {
    pub identity: &'a str,
    pub source: &'a str,
    pub root: Option<&'a Path>,
    pub include: &'a [String],
    pub exclude: &'a [String],
    pub effective_ref: Refspec,
    pub template_opt_in: TemplateOptIn,
    pub take: Option<&'a [TakeEntry]>,
    pub composed_take: Option<&'a [TakeEntry]>,
    pub collapse: Option<bool>,
    pub history: bool,
}

impl ResolvedBinding<'_> {
    pub fn renames(&self) -> impl Iterator<Item = (&str, &str)> {
        self.take
            .into_iter()
            .flatten()
            .filter_map(|entry| match entry {
                TakeEntry::Rename { src, dest } => Some((src.as_str(), dest.as_str())),
                TakeEntry::Leaf(_) => None,
            })
    }

    #[must_use]
    pub fn has_renames(&self) -> bool {
        self.renames().next().is_some()
    }
}

pub trait SourceFields {
    fn intrinsic_root(&self) -> Option<&Path>;
    fn intrinsic_include(&self) -> &[String];
    fn intrinsic_exclude(&self) -> &[String];
    fn intrinsic_refspec(&self) -> Refspec;
}

impl SourceFields for Source {
    fn intrinsic_root(&self) -> Option<&Path> {
        self.root.as_deref()
    }

    fn intrinsic_include(&self) -> &[String] {
        self.include.as_deref().unwrap_or(&[])
    }

    fn intrinsic_exclude(&self) -> &[String] {
        self.exclude.as_deref().unwrap_or(&[])
    }

    fn intrinsic_refspec(&self) -> Refspec {
        if let Some(rev) = &self.rev {
            Refspec::Rev(rev.clone())
        } else if let Some(tag) = &self.tag {
            Refspec::Tag(tag.clone())
        } else if let Some(branch) = &self.branch {
            Refspec::Branch(branch.clone())
        } else {
            Refspec::Default
        }
    }
}

impl SourceFields for ParsedSource {
    fn intrinsic_root(&self) -> Option<&Path> {
        self.root.as_deref()
    }

    fn intrinsic_include(&self) -> &[String] {
        self.includes()
    }

    fn intrinsic_exclude(&self) -> &[String] {
        self.excludes()
    }

    fn intrinsic_refspec(&self) -> Refspec {
        self.refspec()
    }
}

impl Target {
    #[must_use]
    pub(super) fn merged_with(mut self, local: Target) -> Target {
        self.path = local.path;
        if local.sources.is_some() {
            self.sources = local.sources;
        }
        if local.layout.is_some() {
            self.layout = local.layout;
        }
        if local.hooks.is_some() {
            // bare [hooks] section replaces base wholesale, matching layout
            self.hooks = local.hooks;
        }
        self
    }

    #[must_use]
    pub fn layout(&self) -> LayoutConfig {
        self.layout.clone().unwrap_or_default()
    }

    /// Every binding, flat and transitive, as `(identity, binding)`.
    pub fn bindings(&self) -> impl Iterator<Item = (&str, &Binding)> {
        self.sources
            .iter()
            .flatten()
            .map(|(identity, binding)| (identity.as_str(), binding))
            .chain(
                self.offer_bindings
                    .iter()
                    .flatten()
                    .map(|import| (import.identity.as_str(), &import.binding)),
            )
    }

    /// Moves bindings of transitive sources into `offer_bindings`.
    pub(crate) fn lower_transitive(&mut self, is_transitive: impl Fn(&str) -> bool) {
        let Some(bindings) = self.sources.as_mut() else {
            return;
        };
        let (moved, kept): (BTreeMap<_, _>, BTreeMap<_, _>) = std::mem::take(bindings)
            .into_iter()
            .partition(|(identity, binding)| is_transitive(binding.effective_source(identity)));
        *bindings = kept;
        if moved.is_empty() {
            return;
        }
        self.offer_bindings.get_or_insert_with(Vec::new).extend(
            moved
                .into_iter()
                .map(|(identity, binding)| OfferBinding { identity, binding }),
        );
    }

    pub fn declared_sources(&self) -> impl Iterator<Item = &str> {
        self.sources
            .iter()
            .flatten()
            .map(|(identity, binding)| binding.effective_source(identity))
    }

    #[must_use]
    pub fn resolve_sources<'a, S: SourceFields>(
        &'a self,
        all: &'a BTreeMap<String, S>,
    ) -> Vec<ResolvedBinding<'a>> {
        self.sources
            .iter()
            .flatten()
            .filter_map(|(identity, binding)| resolve_binding(identity, binding, all))
            .collect()
    }

    #[must_use]
    pub fn expanded_path(&self) -> PathBuf {
        super::expand_home(&self.path)
    }

    /// Deploy-time snapshot of the target's expanded absolute path, as a lossy string.
    #[must_use]
    pub fn deploy_root(&self) -> String {
        self.expanded_path().to_string_lossy().into_owned()
    }
}

fn resolve_binding<'a, S: SourceFields>(
    identity: &'a str,
    binding: &'a Binding,
    all: &'a BTreeMap<String, S>,
) -> Option<ResolvedBinding<'a>> {
    let source_name = binding.effective_source(identity);
    let source = all.get(source_name)?;
    Some(ResolvedBinding {
        identity,
        source: source_name,
        root: source.intrinsic_root(),
        include: source.intrinsic_include(),
        exclude: source.intrinsic_exclude(),
        effective_ref: binding_refspec(binding).unwrap_or_else(|| source.intrinsic_refspec()),
        template_opt_in: binding.template_opt_in(),
        take: binding.take.as_deref(),
        composed_take: binding.composed_take.as_deref(),
        collapse: binding.collapse,
        history: binding.history,
    })
}

fn binding_refspec(binding: &Binding) -> Option<Refspec> {
    if let Some(rev) = &binding.rev {
        Some(Refspec::Rev(rev.clone()))
    } else if let Some(tag) = &binding.tag {
        Some(Refspec::Tag(tag.clone()))
    } else {
        binding.branch.as_ref().map(|b| Refspec::Branch(b.clone()))
    }
}

#[derive(Debug, Default, Clone, Deserialize)]
#[serde(try_from = "LayoutConfigRaw")]
pub struct LayoutConfig {
    pub kind: LayoutKind,
    pub separator: String,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum LayoutKind {
    #[default]
    Flat,
    BySource,
    Prefixed,
}

impl LayoutConfig {
    #[must_use]
    pub fn artifact_path(&self, source: &str, artifact: &str) -> PathBuf {
        match self.kind {
            LayoutKind::Flat => PathBuf::from(artifact),
            LayoutKind::BySource => PathBuf::from(source).join(artifact),
            LayoutKind::Prefixed => PathBuf::from(format!("{source}{}{artifact}", self.separator)),
        }
    }

    /// `Some` separator to persist for reconstruction only under `Prefixed`, which is the sole layout that joins with one.
    #[must_use]
    pub fn persisted_separator(&self) -> Option<String> {
        matches!(self.kind, LayoutKind::Prefixed).then(|| self.separator.clone())
    }
}

enum LayoutConfigRaw {
    Simple(String),
    Full(LayoutTable),
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LayoutTable {
    r#type: String,
    separator: Option<String>,
}

impl<'de> Deserialize<'de> for LayoutConfigRaw {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct RawVisitor;

        impl<'de> serde::de::Visitor<'de> for RawVisitor {
            type Value = LayoutConfigRaw;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a layout name string or a layout table")
            }

            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> std::result::Result<Self::Value, E> {
                Ok(LayoutConfigRaw::Simple(v.to_owned()))
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                map: A,
            ) -> std::result::Result<Self::Value, A::Error> {
                LayoutTable::deserialize(serde::de::value::MapAccessDeserializer::new(map))
                    .map(LayoutConfigRaw::Full)
            }
        }

        deserializer.deserialize_any(RawVisitor)
    }
}

impl TryFrom<LayoutConfigRaw> for LayoutConfig {
    type Error = String;

    fn try_from(raw: LayoutConfigRaw) -> std::result::Result<Self, Self::Error> {
        let (kind, sep) = match raw {
            LayoutConfigRaw::Simple(s) => (LayoutKind::parse(&s)?, None),
            LayoutConfigRaw::Full(table) => (LayoutKind::parse(&table.r#type)?, table.separator),
        };
        let separator = sep.unwrap_or_else(|| match kind {
            LayoutKind::Prefixed => "-".into(),
            LayoutKind::Flat | LayoutKind::BySource => String::new(),
        });
        Ok(LayoutConfig { kind, separator })
    }
}

impl LayoutKind {
    fn parse(s: &str) -> std::result::Result<Self, String> {
        match s {
            "flat" => Ok(Self::Flat),
            "by-source" => Ok(Self::BySource),
            "prefixed" => Ok(Self::Prefixed),
            other => Err(format!("unknown layout type `{other}`")),
        }
    }

    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::Flat => "flat",
            Self::BySource => "by-source",
            Self::Prefixed => "prefixed",
        }
    }

    #[must_use]
    pub fn from_record_label(label: &str) -> Option<Self> {
        match label {
            "flat" => Some(Self::Flat),
            // `bysource` is the label pre-hardening builds wrote via Debug-lowercasing.
            "by-source" | "bysource" => Some(Self::BySource),
            "prefixed" => Some(Self::Prefixed),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::fmt::Write as _;
    use std::path::{Path, PathBuf};

    use super::{Binding, Source, TakeEntry, resolve_binding};

    fn binding(body: &str) -> Binding {
        toml::from_str::<Binding>(body).expect("binding DTO deserializes")
    }

    fn try_binding(body: &str) -> Result<Binding, toml::de::Error> {
        toml::from_str::<Binding>(body)
    }

    fn source_with(root: Option<&str>, include: &[&str], exclude: &[&str]) -> Source {
        let mut toml = String::from("git = \"https://example.com/x.git\"\n");
        if let Some(r) = root {
            let _ = writeln!(toml, "root = \"{r}\"");
        }
        if !include.is_empty() {
            let list = include
                .iter()
                .map(|p| format!("\"{p}\""))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(toml, "include = [{list}]");
        }
        if !exclude.is_empty() {
            let list = exclude
                .iter()
                .map(|p| format!("\"{p}\""))
                .collect::<Vec<_>>()
                .join(", ");
            let _ = writeln!(toml, "exclude = [{list}]");
        }
        toml::from_str::<Source>(&toml).expect("source DTO deserializes")
    }

    #[test]
    fn binding_rejects_include_field() {
        let err = try_binding("include = [\"editor/**\"]\n")
            .expect_err("binding-level `include` must no longer deserialize");
        assert!(
            err.to_string().contains("include"),
            "the rejection must name the removed `include` field; got:\n{err}"
        );
    }

    #[test]
    fn binding_rejects_exclude_field() {
        try_binding("exclude = [\"editor/**\"]\n")
            .expect_err("binding-level `exclude` must no longer deserialize");
    }

    #[test]
    fn binding_rejects_root_field() {
        try_binding("root = \"editor\"\n")
            .expect_err("binding-level `root` must no longer deserialize");
    }

    #[test]
    fn binding_rejects_map_field() {
        try_binding("map = { \"a/X.md\" = \"a/x.md\" }\n")
            .expect_err("binding-level `map` must no longer deserialize");
    }

    #[test]
    fn take_deserializes_mixed_literal_glob_and_rename() {
        let b = binding(
            "take = [\"skills/gestalt/skill.md\", \"skills/**\", { \"a/X.md\" = \"a/x.md\" }]\n",
        );
        let take = b.take.as_deref().expect("a present `take` parses to Some");
        assert_eq!(take.len(), 3, "all three entries parse; got: {take:?}");

        assert!(
            matches!(&take[0], TakeEntry::Leaf(s) if s == "skills/gestalt/skill.md"),
            "the first entry is a literal leaf captured verbatim; got: {:?}",
            take[0]
        );
        assert!(
            matches!(&take[1], TakeEntry::Leaf(s) if s == "skills/**"),
            "a glob string is captured raw as a leaf entry; classification is SMR-021, not here; got: {:?}",
            take[1]
        );
        match &take[2] {
            TakeEntry::Rename { src, dest } => {
                assert_eq!(src, "a/X.md", "rename src captured verbatim; got: {src}");
                assert_eq!(dest, "a/x.md", "rename dest captured verbatim; got: {dest}");
            }
            leaf @ TakeEntry::Leaf(_) => panic!("the third entry is a rename-map; got: {leaf:?}"),
        }
    }

    #[test]
    fn omitted_take_is_none_project_everything() {
        let b = binding("source = \"s\"\n");
        assert!(
            b.take.is_none(),
            "an omitted `take` must parse to None (project EVERYTHING); got: {:?}",
            b.take
        );
    }

    #[test]
    fn empty_take_is_some_empty_project_nothing() {
        let b = binding("take = []\n");
        let take = b
            .take
            .as_deref()
            .expect("an explicit `take = []` must parse to Some, not None");
        assert!(
            take.is_empty(),
            "`take = []` must parse to Some(empty) (project NOTHING); got: {take:?}"
        );
    }

    #[test]
    fn resolved_binding_surfaces_source_root_include_exclude_without_override() {
        let source = source_with(Some("editor"), &["editor/**"], &["**/*.swp"]);
        let mut all = BTreeMap::new();
        all.insert("s".to_string(), source);

        let b = binding("source = \"s\"\n");
        let resolved =
            resolve_binding("s", &b, &all).expect("binding resolves against the source map");

        assert_eq!(
            resolved.root,
            Some(Path::new("editor")),
            "ResolvedBinding surfaces the SOURCE root (no binding override); got: {:?}",
            resolved.root
        );
        assert_eq!(
            resolved.include,
            &["editor/**".to_string()],
            "ResolvedBinding surfaces the SOURCE include; got: {:?}",
            resolved.include
        );
        assert_eq!(
            resolved.exclude,
            &["**/*.swp".to_string()],
            "ResolvedBinding surfaces the SOURCE exclude; got: {:?}",
            resolved.exclude
        );
    }

    #[test]
    fn resolved_binding_carries_take_not_map() {
        let source = source_with(None, &[], &[]);
        let mut all = BTreeMap::new();
        all.insert("s".to_string(), source);

        let b = binding("source = \"s\"\ntake = [\"a\", { \"b/X.md\" = \"b/x.md\" }]\n");
        let resolved =
            resolve_binding("s", &b, &all).expect("binding resolves against the source map");

        let take = resolved
            .take
            .expect("ResolvedBinding carries the binding `take`");
        assert_eq!(
            take.len(),
            2,
            "both take entries flow through; got: {take:?}"
        );
        assert!(
            matches!(&take[0], TakeEntry::Leaf(s) if s == "a"),
            "first resolved take entry is a literal leaf; got: {:?}",
            take[0]
        );
        assert!(
            matches!(&take[1], TakeEntry::Rename { src, dest } if src == "b/X.md" && dest == "b/x.md"),
            "second resolved take entry is a rename-map; got: {:?}",
            take[1]
        );
    }

    #[test]
    fn binding_collapse_true_parses_to_some_true() {
        let b = binding("source = \"s\"\ncollapse = true\n");
        assert_eq!(
            b.collapse,
            Some(true),
            "`collapse = true` on a binding parses to Some(true); got: {:?}",
            b.collapse
        );
    }

    #[test]
    fn binding_collapse_false_parses_to_some_false() {
        let b = binding("source = \"s\"\ncollapse = false\n");
        assert_eq!(
            b.collapse,
            Some(false),
            "`collapse = false` on a binding parses to Some(false); got: {:?}",
            b.collapse
        );
    }

    #[test]
    fn omitted_binding_collapse_is_none() {
        let b = binding("source = \"s\"\n");
        assert_eq!(
            b.collapse, None,
            "an omitted `collapse` parses to None (algorithmic default); got: {:?}",
            b.collapse
        );
    }

    #[test]
    fn resolved_binding_surfaces_the_binding_collapse() {
        let source = source_with(None, &[], &[]);
        let mut all = BTreeMap::new();
        all.insert("s".to_string(), source);

        let b = binding("source = \"s\"\ncollapse = false\n");
        let resolved = resolve_binding("s", &b, &all).expect("binding resolves");
        assert_eq!(
            resolved.collapse,
            Some(false),
            "ResolvedBinding surfaces the binding `collapse`; got: {:?}",
            resolved.collapse
        );
    }

    #[test]
    fn resolved_binding_collapse_is_none_when_omitted() {
        let source = source_with(None, &[], &[]);
        let mut all = BTreeMap::new();
        all.insert("s".to_string(), source);

        let b = binding("source = \"s\"\n");
        let resolved = resolve_binding("s", &b, &all).expect("binding resolves");
        assert_eq!(
            resolved.collapse, None,
            "an omitted `collapse` stays None through resolution; got: {:?}",
            resolved.collapse
        );
    }

    #[test]
    fn resolved_binding_take_is_none_when_omitted() {
        let source = source_with(None, &[], &[]);
        let mut all: BTreeMap<String, Source> = BTreeMap::new();
        all.insert("s".to_string(), source);

        let b = binding("source = \"s\"\n");
        let resolved = resolve_binding("s", &b, &all).expect("binding resolves");
        assert!(
            resolved.take.is_none(),
            "an omitted `take` stays None through resolution (project everything); got: {:?}",
            resolved.take
        );
        let _ = PathBuf::new();
    }
}