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
//! Config DTOs (`phora.toml`). This module is a boundary, so it carries serde.

mod hooks;
mod host;
pub mod link;
mod migrate;
mod source;
mod target;
pub mod tools;
pub mod transitive;

#[cfg(test)]
mod tests;

#[cfg(test)]
mod transitive_tests;

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

use serde::Deserialize;

use crate::error::{Error, Result};
pub use crate::source::Protocol;

pub(crate) use hooks::DEFAULT_SHELL_PREFIX;
pub use hooks::{
    CandidateHook, GlobalHooks, HookAdmissionDiagnostic, HookCommand, HookWhen, PreDeployOnFail,
    TargetHooks, admit_transitive_hooks, hook_preimage,
};
pub use host::{AuthConfig, Host, RemoteConfig, builtin_forges};
pub use migrate::MigrationWarning;
pub use source::{
    BuildInputs, BuildSpec, BuildTool, DeployMode, Offer, ParsedSource, Refspec, Remote, Source,
    SourceMode, ToolSpec,
};
pub use target::{
    Binding, DEFAULT_OFFER, LayoutConfig, LayoutKind, OfferBinding, ResolvedBinding, SourceFields,
    TakeEntry, Target, TemplateOptIn,
};
pub use tools::ToolGrant;

fn expand_home(path: &Path) -> PathBuf {
    if let Ok(relative) = path.strip_prefix("~")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(relative);
    }
    path.to_path_buf()
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Paths {
    #[serde(default)]
    pub cache: Option<PathBuf>,
    #[serde(default)]
    pub state: Option<PathBuf>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Defaults {
    #[serde(default)]
    pub auto_target: Option<bool>,
}

impl Defaults {
    #[must_use]
    pub fn auto_target(&self) -> bool {
        self.auto_target.unwrap_or(true)
    }
}

/// The only schema version phora speaks; omitting `version` selects it.
pub const SCHEMA_VERSION: u32 = 1;

const fn default_schema_version() -> u32 {
    SCHEMA_VERSION
}

#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default = "default_schema_version")]
    pub version: u32,
    #[serde(default)]
    pub protocol: Option<Protocol>,
    #[serde(default)]
    pub hosts: BTreeMap<String, Host>,
    #[serde(default)]
    pub sources: BTreeMap<String, Source>,
    #[serde(default)]
    pub targets: BTreeMap<String, Target>,
    #[serde(default)]
    pub defaults: Defaults,
    #[serde(default)]
    pub paths: Paths,
    #[serde(default)]
    pub hooks: Option<GlobalHooks>,
    #[serde(default)]
    pub vars: BTreeMap<String, String>,
    /// What this repo publishes to configs that bind it as a transitive source.
    #[serde(default)]
    pub offers: BTreeMap<String, transitive::ManifestOffer>,
    #[serde(default)]
    pub tools: BTreeMap<String, ToolGrant>,
}

impl Config {
    /// Parses and validates a `phora.toml` document.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if the document is not valid TOML, contains an
    /// unknown key, or a source sets more than one of `branch`/`tag`/`rev`.
    pub fn parse(s: &str) -> Result<Self> {
        if let Ok(doc) = toml::from_str::<toml::Value>(s) {
            reject_legacy_binding_arrays(&doc)?;
            reject_binding_scope_keys(&doc)?;
        }
        let config: Self = toml::from_str(s).map_err(|e| Error::Config(e.to_string()))?;
        config.reject_malformed_take_globs()?;
        for (name, host) in &config.hosts {
            if let Some(remote) = &host.remote
                && remote.https_template().is_none()
                && remote.ssh_template().is_none()
            {
                return Err(Error::Config(format!(
                    "host `{name}`: `remote` must set at least one protocol template (https or ssh)"
                )));
            }
        }
        for (name, source) in &config.sources {
            source.classify(name)?;
        }
        Ok(config)
    }

    pub(crate) fn parse_local(s: &str) -> Result<Self> {
        let config = Self::parse(s)?;
        if !config.offers.is_empty() {
            return Err(Error::Config(
                "phora.local.toml cannot declare `[offers]`; offers publish what phora.toml commits"
                    .to_owned(),
            ));
        }
        Ok(config)
    }

    /// Post-merge validation: host references resolve, the effective protocol has
    /// a matching remote template, and every source resolves to exactly one mode.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if a source references an unknown host, requests
    /// a protocol its host's `remote` does not provide, or does not resolve to a
    /// single complete mode (git, or host+path).
    pub fn validate(&self) -> Result<()> {
        if let Some(key) =
            transitive::unnamespaceable_key(self.sources.keys().chain(self.targets.keys()))
        {
            return Err(Error::Config(format!(
                "key `{key}` cannot contain `{}`",
                transitive::MEMBER_SEPARATOR
            )));
        }
        for (name, source) in &self.sources {
            if source.is_transitive()
                && let Some(key) = [
                    ("root", source.root.is_some()),
                    ("include", source.include.is_some()),
                    ("exclude", source.exclude.is_some()),
                ]
                .into_iter()
                .find_map(|(key, set)| set.then_some(key))
            {
                return Err(Error::Config(format!(
                    "source `{name}`: a transitive source cannot set `{key}`; its manifest declares \
                     the offers, and a binding selects one with `offer`"
                )));
            }
            let parsed = ParsedSource::parse(name, source)?;
            let Remote::Host {
                host: host_name,
                repo,
                ..
            } = &parsed.remote
            else {
                continue;
            };
            if repo.trim().is_empty() || repo.split('/').any(str::is_empty) {
                return Err(Error::Config(format!(
                    "source `{name}`: `repo` `{repo}` is not a valid forge path \
                     (no empty, leading, trailing, or doubled `/` segments)"
                )));
            }
            let Some(host) = self.effective_host(host_name) else {
                return Err(Error::Config(format!(
                    "source `{name}` references unknown host `{host_name}`"
                )));
            };
            let protocol = source.protocol.or(self.protocol).unwrap_or(Protocol::Https);
            let template = host.remote.as_ref().and_then(|remote| match protocol {
                Protocol::Https => remote.https_template(),
                Protocol::Ssh => remote.ssh_template(),
            });
            if template.is_none() {
                let proto = match protocol {
                    Protocol::Https => "https",
                    Protocol::Ssh => "ssh",
                };
                return Err(Error::Config(format!(
                    "source `{name}`: protocol `{proto}` but host `{host_name}` has no {proto} remote template"
                )));
            }
        }
        self.validate_bindings()?;
        self.validate_transitive_sources_are_bound()?;
        self.validate_builds()?;
        self.validate_offers()?;
        Ok(())
    }

    fn validate_builds(&self) -> Result<()> {
        for (name, source) in &self.sources {
            let Some(build) = &source.build else {
                continue;
            };
            if let BuildTool::Tool { spec, .. } = &build.tool
                && !self.tools.contains_key(&spec.identity)
            {
                return Err(Error::Config(format!(
                    "source `{name}`: build runs tool `{spec}`; {}",
                    tools::grant_hint(&spec.identity)
                )));
            }
            if build.inputs == BuildInputs::Repo {
                transitive::resolve_offer(
                    build.offer.as_deref().unwrap_or(DEFAULT_OFFER),
                    &self.offers,
                    &self.sources,
                    &self.targets,
                )
                .map_err(|e| Error::Config(format!("source `{name}`: {e}")))?;
            }
            if build.offer.is_some()
                && let Some(flat) = build
                    .named_inputs()
                    .iter()
                    .find(|input| !self.sources.get(*input).is_some_and(Source::is_transitive))
            {
                return Err(Error::Config(format!(
                    "source `{name}`: `build.offer` binds transitive inputs, but `{flat}` is flat"
                )));
            }
            for input in build.named_inputs() {
                let Some(input_source) = self.sources.get(input) else {
                    return Err(Error::Config(format!(
                        "source `{name}`: `build.inputs` references undefined source `{input}`"
                    )));
                };
                if input_source.build.is_some() {
                    return Err(Error::Config(format!(
                        "source `{name}`: `build.inputs` names build source `{input}`; \
                         a build reads only fetched or local sources"
                    )));
                }
            }
        }
        Ok(())
    }

    fn is_build_input(&self, name: &str) -> bool {
        self.sources
            .values()
            .filter_map(|s| s.build.as_ref())
            .any(|b| b.named_inputs().iter().any(|i| i == name))
    }

    /// A flat fetch bypasses the recursive pre-pass, so a `transitive = true` source that
    /// no target binds is a silent downgrade past escape-remote rejection and depth fail-fast.
    fn validate_transitive_sources_are_bound(&self) -> Result<()> {
        for (name, source) in &self.sources {
            if !source.is_transitive() || self.is_bound_anywhere(name) || self.is_build_input(name)
            {
                continue;
            }
            return Err(Error::Config(format!(
                "source `{name}` is `transitive = true` but no target binds it; a transitive \
                 source must be bound by a target or it is never resolved"
            )));
        }
        Ok(())
    }

    fn validate_offers(&self) -> Result<()> {
        for name in self
            .offers
            .keys()
            .map(String::as_str)
            .chain([DEFAULT_OFFER])
        {
            transitive::resolve_offer(name, &self.offers, &self.sources, &self.targets)?;
        }
        Ok(())
    }

    fn is_bound_anywhere(&self, name: &str) -> bool {
        self.targets.values().any(|target| {
            target
                .bindings()
                .any(|(identity, binding)| binding.effective_source(identity) == name)
        })
    }

    /// Sources no target binds and no build reads.
    #[must_use]
    pub fn unbound_sources(&self) -> Vec<&str> {
        self.sources
            .keys()
            .map(String::as_str)
            .filter(|name| !self.is_bound_anywhere(name) && !self.is_build_input(name))
            .collect()
    }

    /// Moves every binding of a `transitive = true` source into its target's `offer_bindings`.
    pub fn lower_transitive(&mut self) {
        let sources = &self.sources;
        for target in self.targets.values_mut() {
            target.lower_transitive(|name| sources.get(name).is_some_and(Source::is_transitive));
        }
    }

    fn validate_bindings(&self) -> Result<()> {
        for (target_name, target) in &self.targets {
            for (identity, binding) in target.bindings() {
                if crate::source::safe_component(identity).is_err() {
                    return Err(Error::Config(format!(
                        "target `{target_name}`: binding identity `{identity}` must be a single safe path component"
                    )));
                }
                let effective = binding.effective_source(identity);
                let Some(source) = self.sources.get(effective) else {
                    return Err(Error::Config(format!(
                        "target `{target_name}` references undefined source `{effective}`"
                    )));
                };
                reject_url_slice(effective, binding, source)?;
                reject_build_ref(effective, binding, source)?;
                reject_link_ref(effective, binding, source)?;
                reject_history_binding_options(target_name, identity, effective, binding, source)?;
                reject_multi_ref(effective, binding)?;
                reject_offer_mismatch(target_name, identity, effective, binding, source)?;
            }
        }
        Ok(())
    }

    fn reject_malformed_take_globs(&self) -> Result<()> {
        for target in self.targets.values() {
            for (_, binding) in target.bindings() {
                reject_malformed_take_entries(binding.take.iter().flatten())?;
            }
        }
        Ok(())
    }

    fn effective_host(&self, name: &str) -> Option<Host> {
        effective_host(&self.hosts, name)
    }

    /// Parses every source into its typed form, keyed by name.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Config`] if any source fails the typed parse.
    pub fn parsed_sources(&self) -> Result<BTreeMap<String, ParsedSource>> {
        self.sources
            .iter()
            .map(|(name, source)| Ok((name.clone(), ParsedSource::parse(name, source)?)))
            .collect()
    }

    /// `base_dir` resolves relative `path` values for the local-dir check.
    #[must_use]
    pub fn migration_warnings(&self, base_dir: &std::path::Path) -> Vec<MigrationWarning> {
        self.sources
            .iter()
            .filter_map(|(name, source)| migrate::warning_for(name, source, base_dir))
            .collect()
    }
}

use crate::projection::model::{
    CollapsePreference, LayoutSpec, LayoutStyle, MaterializationPolicy, OfferSpec, TakeSpec,
    TemplatePolicy,
};

impl TakeSpec {
    #[must_use]
    pub fn from_entries(entries: Option<&[TakeEntry]>) -> Self {
        let Some(entries) = entries else {
            return Self::ProjectAll;
        };
        let mut literals = Vec::new();
        let mut globs = Vec::new();
        let mut renames = Vec::new();
        for entry in entries {
            match entry {
                TakeEntry::Leaf(leaf) if crate::projection::take::is_take_glob(leaf) => {
                    globs.push(leaf.clone());
                }
                TakeEntry::Leaf(leaf) => literals.push(leaf.clone()),
                TakeEntry::Rename { src, dest } => renames.push((src.clone(), dest.clone())),
            }
        }
        Self::Explicit {
            literals,
            globs,
            renames,
        }
    }
}

impl From<Offer<'_>> for OfferSpec {
    fn from(offer: Offer<'_>) -> Self {
        Self::new(
            offer.includes().to_vec(),
            offer.excludes().to_vec(),
            offer.root().map(std::path::Path::to_path_buf),
        )
    }
}

impl From<&LayoutConfig> for LayoutSpec {
    fn from(layout: &LayoutConfig) -> Self {
        let style = match layout.kind {
            LayoutKind::Flat => LayoutStyle::Flat,
            LayoutKind::BySource => LayoutStyle::BySource,
            LayoutKind::Prefixed => LayoutStyle::Prefixed,
        };
        Self::new(style, layout.separator.clone())
    }
}

impl From<&TemplateOptIn> for TemplatePolicy {
    fn from(opt_in: &TemplateOptIn) -> Self {
        match opt_in {
            TemplateOptIn::SuffixOnly => Self::suffix_only(),
            TemplateOptIn::Globs(set) => Self::globs(set.clone()),
            TemplateOptIn::Disabled => Self::disabled(),
        }
    }
}

impl From<&DeployMode> for MaterializationPolicy {
    fn from(mode: &DeployMode) -> Self {
        match mode {
            DeployMode::Link => Self::Link,
            DeployMode::Copy => Self::Copy,
        }
    }
}

impl From<Option<bool>> for CollapsePreference {
    fn from(collapse: Option<bool>) -> Self {
        match collapse {
            None => Self::Default,
            Some(false) => Self::ForcePerLeaf,
            Some(true) => Self::ForceCollapse,
        }
    }
}

fn reject_legacy_binding_arrays(doc: &toml::Value) -> Result<()> {
    let Some(targets) = doc.get("targets").and_then(toml::Value::as_table) else {
        return Ok(());
    };
    for (target_name, target) in targets {
        let Some(array) = target.get("sources").and_then(toml::Value::as_array) else {
            continue;
        };
        let mut seen = BTreeSet::new();
        for element in array {
            match element {
                toml::Value::String(name) => {
                    if !seen.insert(name.as_str()) {
                        return Err(Error::Config(format!(
                            "target `{target_name}`: duplicate source `{name}` in the `sources` list"
                        )));
                    }
                }
                _ => {
                    return Err(Error::Config(format!(
                        "target `{target_name}`: table entries in a `sources` list are no longer \
                         supported; use a keyed `[targets.{target_name}.sources]` table instead"
                    )));
                }
            }
        }
    }
    Ok(())
}

fn reject_malformed_take_entries<'a>(
    entries: impl Iterator<Item = &'a target::TakeEntry>,
) -> Result<()> {
    for entry in entries {
        let target::TakeEntry::Leaf(pattern) = entry else {
            continue;
        };
        if crate::projection::take::is_take_glob(pattern)
            && let Err(e) = crate::projection::offer::compile_take_glob(pattern)
        {
            return Err(Error::Config(format!(
                "`take` entry `{pattern}` is not a well-formed glob: {e}"
            )));
        }
    }
    Ok(())
}

const BINDING_SCOPE_KEYS: [&str; 4] = ["root", "include", "exclude", "map"];

fn reject_binding_scope_keys(doc: &toml::Value) -> Result<()> {
    let Some(targets) = doc.get("targets").and_then(toml::Value::as_table) else {
        return Ok(());
    };
    for (target_name, target) in targets {
        let Some(bindings) = target.get("sources").and_then(toml::Value::as_table) else {
            continue;
        };
        for (binding_name, binding) in bindings {
            let Some(table) = binding.as_table() else {
                continue;
            };
            for key in BINDING_SCOPE_KEYS {
                if table.contains_key(key) {
                    return Err(binding_scope_diagnostic(target_name, binding_name, key).config());
                }
            }
        }
    }
    Ok(())
}

fn binding_scope_diagnostic(
    target_name: &str,
    binding_name: &str,
    key: &str,
) -> crate::diagnostic::SelectionDiagnostic {
    let remedy = if key == "map" {
        "rename via the binding's `take`; binding-level `map` is gone, \
         e.g. `take = [{ \"old\" = \"new\" }]`"
            .to_owned()
    } else {
        format!(
            "move `{key}` to the source offer on `[sources.{binding_name}]`; scope is owned by the source, not the binding"
        )
    };
    crate::diagnostic::SelectionDiagnostic {
        entry: key.to_string(),
        matched_against: format!("binding `{binding_name}` of target `{target_name}`"),
        why: "binding-level scope is removed".to_string(),
        did_you_mean: None,
        remedy,
        debug_hint: Some(format!("phora explain {target_name} {binding_name}")),
        details: Vec::new(),
    }
}

fn reject_offer_mismatch(
    target_name: &str,
    identity: &str,
    source_name: &str,
    binding: &Binding,
    source: &Source,
) -> Result<()> {
    let option = if source.is_transitive() {
        if binding.template.is_some() {
            "template"
        } else {
            return Ok(());
        }
    } else if binding.offer.is_some() {
        "offer"
    } else {
        return Ok(());
    };
    let kind = if source.is_transitive() {
        "transitive"
    } else {
        "flat"
    };
    Err(Error::Config(format!(
        "target `{target_name}`: binding `{identity}` of {kind} source `{source_name}` cannot set `{option}`"
    )))
}

fn reject_history_binding_options(
    target_name: &str,
    identity: &str,
    source_name: &str,
    binding: &Binding,
    source: &Source,
) -> Result<()> {
    if !binding.history {
        return Ok(());
    }
    let option = if source.url.is_some() {
        "url"
    } else if source.build.is_some() {
        "build"
    } else if source.deploy == Some(DeployMode::Link) {
        "deploy"
    } else if source.root.is_some() {
        "root"
    } else if source.include.is_some() {
        "include"
    } else if source.exclude.is_some() {
        "exclude"
    } else if source.transitive == Some(true) {
        "transitive"
    } else if source.preserve_executable == Some(false) {
        "preserve_executable"
    } else if binding.take.is_some() {
        "take"
    } else if binding.template.is_some() {
        "template"
    } else if binding.collapse.is_some() {
        "collapse"
    } else {
        return Ok(());
    };
    Err(Error::Config(format!(
        "target `{target_name}`: binding `{identity}` for source `{source_name}`: `history` cannot be combined with `{option}`"
    )))
}

fn reject_build_ref(source_name: &str, binding: &Binding, source: &Source) -> Result<()> {
    if source.build.is_none() {
        return Ok(());
    }
    let field = if binding.branch.is_some() {
        "branch"
    } else if binding.tag.is_some() {
        "tag"
    } else if binding.rev.is_some() {
        "rev"
    } else {
        return Ok(());
    };
    Err(Error::Config(format!(
        "source `{source_name}`: `{field}` is meaningless on a `build` source"
    )))
}

fn reject_url_slice(source_name: &str, binding: &Binding, source: &Source) -> Result<()> {
    if source.url.is_none() {
        return Ok(());
    }
    let field = if binding.branch.is_some() {
        "branch"
    } else if binding.tag.is_some() {
        "tag"
    } else if binding.rev.is_some() {
        "rev"
    } else if binding.template.is_some() {
        "template"
    } else if binding.take.is_some() {
        "take"
    } else {
        return Ok(());
    };
    Err(Error::Config(format!(
        "source `{source_name}`: `{field}` is meaningless on a `url` source"
    )))
}

fn reject_link_ref(source_name: &str, binding: &Binding, source: &Source) -> Result<()> {
    if source.deploy != Some(DeployMode::Link) {
        return Ok(());
    }
    let field = if binding.branch.is_some() {
        "branch"
    } else if binding.tag.is_some() {
        "tag"
    } else if binding.rev.is_some() {
        "rev"
    } else {
        return Ok(());
    };
    Err(Error::Config(format!(
        "source `{source_name}`: `{field}` is meaningless on a `link` source"
    )))
}

fn reject_multi_ref(source_name: &str, binding: &Binding) -> Result<()> {
    let set: Vec<&str> = [
        ("branch", binding.branch.is_some()),
        ("tag", binding.tag.is_some()),
        ("rev", binding.rev.is_some()),
    ]
    .into_iter()
    .filter_map(|(name, present)| present.then_some(name))
    .collect();
    if set.len() > 1 {
        let fields = set
            .iter()
            .map(|f| format!("`{f}`"))
            .collect::<Vec<_>>()
            .join(", ");
        return Err(Error::Config(format!(
            "source `{source_name}`: sets more than one of branch/tag/rev ({fields})"
        )));
    }
    Ok(())
}

/// The effective host for `name`: the built-in forge overlaid by a user
/// `[hosts]` entry of the same name (user wins), or whichever is defined.
#[must_use]
fn effective_host(hosts: &BTreeMap<String, Host>, name: &str) -> Option<Host> {
    match (builtin_forges().remove(name), hosts.get(name).cloned()) {
        (Some(b), Some(u)) => Some(b.merged_with(u)),
        (Some(h), None) | (None, Some(h)) => Some(h),
        (None, None) => None,
    }
}

/// Fills a remote template from `path`: `{path}` verbatim, `{owner}` the first
/// `/`-segment, `{repo}` the remainder (so `{owner}/{repo}` ≡ `{path}` at any depth).
#[must_use]
pub fn fill_template(template: &str, path: &str) -> String {
    let (owner, repo) = path.split_once('/').unwrap_or((path, ""));
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(open) = rest.find('{') {
        out.push_str(&rest[..open]);
        let tail = &rest[open..];
        if let Some((token, value)) = [("{path}", path), ("{owner}", owner), ("{repo}", repo)]
            .into_iter()
            .find(|(token, _)| tail.starts_with(token))
        {
            out.push_str(value);
            rest = &tail[token.len()..];
        } else {
            out.push('{');
            rest = &tail[1..];
        }
    }
    out.push_str(rest);
    out
}

/// Computes the effective config: `base` overlaid by `local` per spec merge semantics.
#[must_use]
pub fn merge_configs(base: Config, local: Option<Config>) -> Config {
    let mut merged = overlay(base, local);
    merged.lower_transitive();
    merged
}

fn overlay(base: Config, local: Option<Config>) -> Config {
    let Some(local) = local else { return base };
    let mut merged = base;
    merged.version = local.version;
    if local.protocol.is_some() {
        merged.protocol = local.protocol;
    }
    for (name, host) in local.hosts {
        match merged.hosts.remove(&name) {
            Some(base_host) => {
                merged.hosts.insert(name, base_host.merged_with(host));
            }
            None => {
                merged.hosts.insert(name, host);
            }
        }
    }
    for (name, source) in local.sources {
        match merged.sources.remove(&name) {
            Some(base_source) => {
                merged.sources.insert(name, base_source.merged_with(source));
            }
            None => {
                merged.sources.insert(name, source);
            }
        }
    }
    for (name, target) in local.targets {
        match merged.targets.remove(&name) {
            Some(base_target) => {
                merged.targets.insert(name, base_target.merged_with(target));
            }
            None => {
                merged.targets.insert(name, target);
            }
        }
    }
    if local.defaults.auto_target.is_some() {
        merged.defaults.auto_target = local.defaults.auto_target;
    }
    if local.paths.cache.is_some() {
        merged.paths.cache = local.paths.cache;
    }
    if local.paths.state.is_some() {
        merged.paths.state = local.paths.state;
    }
    if local.hooks.is_some() {
        merged.hooks = local.hooks;
    }
    merged.vars.extend(local.vars);
    merged.tools.extend(local.tools);
    merged
}