phora 0.4.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
//! The `add` command family: URL/shorthand parsing and `phora.toml` writers.

use std::collections::BTreeMap;

use crate::config::{Host, builtin_forges};
use crate::error::{Error, Result};
use crate::source::{Protocol, is_local_path};

use super::config_edit::BindRefinement;
use super::{config_edit, load_config, read_config_text, render, target_config_file};

pub(super) struct AddRequest<'a> {
    pub(super) url: &'a str,
    pub(super) targets: &'a [String],
    pub(super) name: Option<String>,
    pub(super) branch: Option<String>,
    pub(super) tag: Option<String>,
    pub(super) root: Option<String>,
    pub(super) include: Vec<String>,
    pub(super) exclude: Vec<String>,
    pub(super) local: bool,
    pub(super) symlink: bool,
    pub(super) assume_yes: bool,
    pub(super) refinement: &'a BindRefinement,
}

pub(super) fn run_add(request: AddRequest<'_>) -> Result<()> {
    if request.refinement.r#as.is_some() && request.targets.len() != 1 {
        return Err(Error::Config(
            "`--as` sets a single binding identity and needs exactly one `--to` target".to_owned(),
        ));
    }
    if !request.refinement.is_bare() && !request.refinement.history && request.targets.is_empty() {
        return Err(Error::Config(
            "refinement flags (`--as`/`--take`) need at least one `--to` target".to_owned(),
        ));
    }
    if request.refinement.history && (request.local || request.symlink) {
        return Err(Error::Config(
            "`--local`/`--symlink` overlays do not support `--history`".to_owned(),
        ));
    }
    if (request.local || request.symlink)
        && (!request.targets.is_empty() || !request.refinement.is_bare())
    {
        return Err(Error::Config(
            "`--local`/`--symlink` overlays do not support `--to`/refinement flags".to_owned(),
        ));
    }

    if !request.targets.is_empty() {
        let AddRequest {
            url,
            targets,
            name,
            branch,
            tag,
            root,
            include,
            exclude,
            local,
            symlink,
            assume_yes,
            refinement,
        } = request;
        return run_add_to_targets(
            url,
            targets,
            name,
            branch,
            tag.as_deref(),
            root.as_deref(),
            include,
            exclude,
            local,
            symlink,
            assume_yes,
            refinement,
        );
    }
    if request.local || request.symlink {
        let AddRequest {
            url,
            name,
            branch,
            tag,
            root,
            include,
            exclude,
            symlink,
            ..
        } = request;
        return add_local(
            url,
            name,
            LocalSourceSpec {
                branch: branch.as_deref(),
                tag: tag.as_deref(),
                root: root.as_deref(),
                include,
                exclude,
            },
            symlink,
        );
    }

    run_unbound_add(request)
}

fn run_unbound_add(request: AddRequest<'_>) -> Result<()> {
    let AddRequest {
        url,
        name,
        branch,
        tag,
        root,
        include,
        exclude,
        refinement,
        ..
    } = request;
    let mut parsed = resolve_add_source(url)?;
    parsed.include = include;
    parsed.exclude = exclude;

    let name = name.unwrap_or_else(|| parsed.name.clone());
    let branch = branch.or_else(|| parsed.branch.clone());
    let root = root.or_else(|| parsed.root.clone());

    let doc_text =
        std::fs::read_to_string("phora.toml").unwrap_or_else(|_| "version = 1\n".to_owned());
    let auto_target = super::effective_auto_target();
    if refinement.history && !auto_target {
        return Err(Error::Config(
            "`--history` needs at least one `--to` target".to_owned(),
        ));
    }
    let mut updated = if auto_target {
        add_to_default_target(
            &doc_text,
            &name,
            &parsed,
            branch.as_deref(),
            tag.as_deref(),
            root.as_deref(),
        )?
    } else {
        config_edit::upsert_source(
            &doc_text,
            &name,
            &parsed,
            branch.as_deref(),
            tag.as_deref(),
            root.as_deref(),
        )?
    };
    if refinement.history {
        updated =
            config_edit::bind(&updated, "default", std::slice::from_ref(&name), refinement)?.text;
    }
    super::bind::guard_no_dangling_references(&updated, false)?;
    std::fs::write("phora.toml", &updated)?;

    let refspec = tag
        .or(branch)
        .map_or_else(String::new, |r| format!(" ({r})"));
    let description = format!("{}{refspec}", describe_source(&parsed));
    if auto_target {
        render::print_added_to_default(&name, &description);
    } else {
        render::print_added_declared(&name, &description);
    }

    if parsed.path.is_none() {
        print_add_contribution(&name);
    }
    Ok(())
}

/// Surfaces what an added source's root `phora.toml` would contribute, when one
/// exists in the cache or can be fetched. A source without a phora.toml stays
/// silent (it behaves exactly as a plain `add`); a genuine fetch/parse failure
/// warns to stderr instead of vanishing.
fn print_add_contribution(name: &str) {
    use crate::source::SourceError;

    let Some((backend, source_name, remote, refspec)) = add_contribution_target(name) else {
        return;
    };
    match backend.fetch_root_manifest(&source_name, &remote, &refspec) {
        Ok(bytes) => print_contribution_from_bytes(name, &bytes),
        Err(SourceError::FileAbsent { .. }) => {}
        Err(e) => eprintln!("note: could not inspect {name}'s phora.toml: {e}"),
    }
}

fn add_contribution_target(
    name: &str,
) -> Option<(
    crate::source::GitBackend,
    crate::source::SourceName,
    String,
    crate::config::Refspec,
)> {
    use crate::source::{GitBackend, Protocol as SourceProtocol};

    let config = load_config().ok()?;
    let sources = config.parsed_sources().ok()?;
    let source = sources.get(name)?;
    if source.mode() != crate::config::SourceMode::Git {
        return None;
    }
    let protocol = source
        .protocol()
        .or(config.protocol)
        .unwrap_or(SourceProtocol::Https);
    let remote = source.resolved_remote(&config.hosts, protocol).ok()?;
    let cwd = std::env::current_dir().ok()?;
    let git_dir = crate::paths::cache_root_for(config.paths.cache.as_deref(), &cwd)
        .map(|c| c.join("git"))
        .ok()?;
    let backend = GitBackend::new(git_dir);
    let source_name = crate::source::SourceName::trusted(name.to_owned());
    Some((backend, source_name, remote, source.refspec()))
}

fn print_contribution_from_bytes(name: &str, bytes: &[u8]) {
    use crate::config::transitive::TransitiveManifest;

    let text = match std::str::from_utf8(bytes) {
        Ok(text) => text,
        Err(e) => {
            eprintln!("note: could not inspect {name}'s phora.toml: {e}");
            return;
        }
    };
    match TransitiveManifest::parse(text) {
        Ok(manifest) => print!("{}", render::render_add_contribution(name, &manifest)),
        Err(e) => eprintln!("note: could not inspect {name}'s phora.toml: {e}"),
    }
}

/// A local path resolves to `path =` (local), not forge shorthand — `add` must agree with the config layer, where bare `path =` already means local.
fn resolve_add_source(url: &str) -> Result<AddTarget> {
    if is_local_path(url) {
        return local_path_source(url);
    }
    let hosts = load_config().map(|c| c.hosts).unwrap_or_default();
    parse_add_url(url, &hosts)
}

fn local_path_source(url: &str) -> Result<AddTarget> {
    let canonical = std::fs::canonicalize(url)
        .map_err(|e| Error::Config(format!("local path source `{url}` does not exist: {e}")))?;
    let path = canonical.to_string_lossy().into_owned();
    let name = canonical.file_name().map_or_else(
        || path.clone(),
        |segment| segment.to_string_lossy().into_owned(),
    );
    Ok(AddTarget {
        name,
        git: None,
        host: None,
        repo: None,
        path: Some(path),
        protocol: None,
        branch: None,
        root: None,
        include: Vec::new(),
        exclude: Vec::new(),
    })
}

fn resolve_local_source(url: &str, name: Option<String>) -> Result<(String, AddTarget)> {
    let canonical = std::fs::canonicalize(url).map_err(|e| {
        Error::Config(format!(
            "`--local`/`--symlink` require an existing local checkout, but `{url}` is not one: {e}"
        ))
    })?;
    if !canonical.is_dir() {
        return Err(Error::Config(format!(
            "`--local`/`--symlink` require a directory, but `{url}` is not one"
        )));
    }

    let path = canonical.to_string_lossy().into_owned();
    let name = name.unwrap_or_else(|| {
        canonical
            .file_name()
            .map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())
    });

    let target = AddTarget {
        name: name.clone(),
        git: None,
        host: None,
        repo: None,
        path: Some(path),
        protocol: None,
        branch: None,
        root: None,
        include: Vec::new(),
        exclude: Vec::new(),
    };
    Ok((name, target))
}

fn inject_deploy_link(text: &str, name: &str) -> Result<String> {
    let mut doc = text
        .parse::<toml_edit::DocumentMut>()
        .map_err(|e| Error::Config(format!("parse phora.local.toml: {e}")))?;
    doc["sources"][name]["deploy"] = toml_edit::value("link");
    Ok(doc.to_string())
}

struct LocalSourceSpec<'a> {
    branch: Option<&'a str>,
    tag: Option<&'a str>,
    root: Option<&'a str>,
    include: Vec<String>,
    exclude: Vec<String>,
}

fn add_local(
    url: &str,
    name: Option<String>,
    spec: LocalSourceSpec<'_>,
    symlink: bool,
) -> Result<()> {
    let (name, mut target) = resolve_local_source(url, name)?;
    target.include = spec.include;
    target.exclude = spec.exclude;
    let path = target.path.clone().unwrap_or_default();

    let doc_text =
        std::fs::read_to_string("phora.local.toml").unwrap_or_else(|_| "version = 1\n".to_owned());
    let mut updated =
        config_edit::upsert_source(&doc_text, &name, &target, spec.branch, spec.tag, spec.root)?;
    if symlink {
        updated = inject_deploy_link(&updated, &name)?;
    }
    super::bind::guard_no_dangling_references(&updated, true)?;
    std::fs::write("phora.local.toml", &updated)?;

    println!("Added local source '{name}': {path}");
    Ok(())
}

#[allow(
    clippy::too_many_arguments,
    reason = "mirrors the `phora add` argument surface for the bind-on-add sugar"
)]
fn run_add_to_targets(
    url: &str,
    targets: &[String],
    name: Option<String>,
    branch: Option<String>,
    tag: Option<&str>,
    root: Option<&str>,
    include: Vec<String>,
    exclude: Vec<String>,
    local: bool,
    symlink: bool,
    assume_yes: bool,
    refinement: &BindRefinement,
) -> Result<()> {
    let overlay = local || symlink;
    let (name, mut source, branch) = if overlay {
        let (name, source) = resolve_local_source(url, name)?;
        (name, source, branch)
    } else {
        let parsed = resolve_add_source(url)?;
        let name = name.unwrap_or_else(|| parsed.name.clone());
        let branch = branch.or_else(|| parsed.branch.clone());
        (name, parsed, branch)
    };
    source.include = include;
    source.exclude = exclude;

    let file = target_config_file(overlay);
    let text = read_config_text(file)?;

    let source_root = root.map(ToOwned::to_owned).or_else(|| source.root.clone());
    let mut updated = add_with_binds(
        &text,
        &name,
        &source,
        branch.as_deref(),
        tag,
        source_root.as_deref(),
        targets,
        refinement,
        &super::TtyMissingTarget { assume_yes },
    )?;
    if symlink {
        updated = inject_deploy_link(&updated, &name)?;
    }
    super::bind::guard_no_dangling_references(&updated, overlay)?;
    std::fs::write(file, &updated)?;

    render::print_added_and_bound(&name, &describe_source(&source), targets);
    Ok(())
}

#[cfg(test)]
pub(super) fn insert_source_with_ref(
    doc_text: &str,
    name: &str,
    source: &AddTarget,
    branch: Option<&str>,
    tag: Option<&str>,
    root: Option<&str>,
) -> Result<String> {
    config_edit::upsert_source(doc_text, name, source, branch, tag, root)
}

fn describe_source(source: &AddTarget) -> String {
    match (&source.git, &source.host, &source.repo, &source.path) {
        (Some(git), ..) => git.clone(),
        (None, Some(host), Some(repo), _) => format!("{host}:{repo}"),
        (None, None, None, Some(path)) => path.clone(),
        _ => source.name.clone(),
    }
}

/// A source derived from an `add` URL/shorthand, before name overrides. Either
/// literal (`git` is `Some`), symbolic forge (`host`/`repo` are `Some`), or
/// local path (`path` is `Some`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddTarget {
    pub name: String,
    pub git: Option<String>,
    pub host: Option<String>,
    pub repo: Option<String>,
    pub path: Option<String>,
    pub protocol: Option<Protocol>,
    pub branch: Option<String>,
    pub root: Option<String>,
    pub include: Vec<String>,
    pub exclude: Vec<String>,
}

/// Expands an `add` URL/shorthand into an [`AddTarget`] using the built-in
/// forge registry overlaid by any host in `hosts`.
///
/// # Errors
///
/// Returns [`Error::Config`] if the input cannot be parsed into owner/repo.
pub fn parse_add_url(input: &str, hosts: &BTreeMap<String, Host>) -> Result<AddTarget> {
    if is_scp_ssh(input) {
        return Ok(parse_scp_ssh(input));
    }
    if let Some((scheme, rest)) = split_scheme(input) {
        return parse_full_url(input, scheme, rest);
    }
    if let Some((host, path)) = input.split_once(':') {
        return parse_colon_alias(input, host, path);
    }
    parse_shorthand(input, &domain_to_name(hosts))
}

fn parse_colon_alias(input: &str, host: &str, path: &str) -> Result<AddTarget> {
    if host.is_empty() {
        return Err(Error::Config(format!("empty host in `{input}`")));
    }
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    let [owner, repo, root_segments @ ..] = segments.as_slice() else {
        return Err(Error::Config(format!(
            "expected <host>:<owner>/<repo> in `{input}`"
        )));
    };
    Ok(symbolic_source(
        host.to_owned(),
        &format!("{owner}/{repo}"),
        join_root(root_segments),
    ))
}

/// `domain -> forge name` from the built-in forge registry overlaid by `hosts`.
fn domain_to_name(hosts: &BTreeMap<String, Host>) -> BTreeMap<String, String> {
    let builtins = builtin_forges();
    builtins
        .iter()
        .chain(hosts)
        .filter_map(|(name, host)| {
            let url = host.remote.as_ref()?.https_template()?;
            Some((template_domain(url)?.to_owned(), name.clone()))
        })
        .collect()
}

fn symbolic_source(host: String, repo: &str, root: Option<String>) -> AddTarget {
    AddTarget {
        name: repo_name(repo),
        git: None,
        host: Some(host),
        repo: Some(repo.to_owned()),
        path: None,
        protocol: None,
        branch: None,
        root,
        include: Vec::new(),
        exclude: Vec::new(),
    }
}

/// The host domain embedded in a `remote` template (between scheme/user and the
/// next `/` or `:` port). `ssh://git@git.company.com:2222/...` yields `git.company.com`.
fn template_domain(url: &str) -> Option<&str> {
    let after_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
    let after_user = after_scheme
        .split_once('@')
        .map_or(after_scheme, |(_, rest)| rest);
    let end = after_user.find(['/', ':']).unwrap_or(after_user.len());
    let domain = &after_user[..end];
    (!domain.is_empty()).then_some(domain)
}

fn is_scp_ssh(input: &str) -> bool {
    if input.contains("://") {
        return false;
    }
    match (input.find('@'), input.find(':')) {
        (Some(at), Some(colon)) => at < colon,
        _ => false,
    }
}

fn parse_scp_ssh(input: &str) -> AddTarget {
    literal_source(repo_name(input), input.to_owned(), None, None)
}

fn literal_source(
    name: String,
    git: String,
    branch: Option<String>,
    root: Option<String>,
) -> AddTarget {
    AddTarget {
        name,
        git: Some(git),
        host: None,
        repo: None,
        path: None,
        protocol: None,
        branch,
        root,
        include: Vec::new(),
        exclude: Vec::new(),
    }
}

fn split_scheme(input: &str) -> Option<(&str, &str)> {
    let (scheme, rest) = input.split_once("://")?;
    matches!(scheme, "https" | "http" | "ssh").then_some((scheme, rest))
}

fn parse_full_url(input: &str, scheme: &str, rest: &str) -> Result<AddTarget> {
    let (host, path) = rest
        .split_once('/')
        .ok_or_else(|| Error::Config(format!("cannot parse owner/repo from `{input}`")))?;
    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    let [owner, repo, tail @ ..] = segments.as_slice() else {
        return Err(Error::Config(format!(
            "expected <owner>/<repo> in `{input}`"
        )));
    };
    if let ["tree", git_ref, root_segments @ ..] = tail {
        return Ok(literal_source(
            strip_git(repo).to_owned(),
            with_git_suffix(&format!("{scheme}://{host}/{owner}/{repo}")),
            Some((*git_ref).to_owned()),
            join_root(root_segments),
        ));
    }

    let remote = format!("{scheme}://{host}/{}", segments.join("/"));
    Ok(literal_source(
        repo_name(&remote),
        with_git_suffix(&remote),
        None,
        None,
    ))
}

fn parse_shorthand(input: &str, domains: &BTreeMap<String, String>) -> Result<AddTarget> {
    let segments: Vec<&str> = input.split('/').filter(|s| !s.is_empty()).collect();
    let first = segments
        .first()
        .ok_or_else(|| Error::Config(format!("empty add target `{input}`")))?;

    if let Some(name) = domains.get(*first) {
        let [_, owner, repo, root_segments @ ..] = segments.as_slice() else {
            return Err(Error::Config(format!(
                "expected <host>/<owner>/<repo> in `{input}`"
            )));
        };
        return Ok(symbolic_source(
            name.clone(),
            &format!("{owner}/{repo}"),
            join_root(root_segments),
        ));
    }

    let [owner, repo, root_segments @ ..] = segments.as_slice() else {
        return Err(Error::Config(format!(
            "expected <owner>/<repo> shorthand in `{input}`"
        )));
    };
    Ok(symbolic_source(
        "github".to_owned(),
        &format!("{owner}/{repo}"),
        join_root(root_segments),
    ))
}

fn join_root(segments: &[&str]) -> Option<String> {
    (!segments.is_empty()).then(|| segments.join("/"))
}

fn repo_name(input: &str) -> String {
    let last = input.rsplit('/').next().unwrap_or(input);
    strip_git(last).to_owned()
}

fn strip_git(segment: &str) -> &str {
    segment.strip_suffix(".git").unwrap_or(segment)
}

#[expect(
    clippy::case_sensitive_file_extension_comparisons,
    reason = "git remote URLs are case-sensitive strings, not filesystem paths"
)]
fn with_git_suffix(url: &str) -> String {
    if url.ends_with(".git") {
        url.to_owned()
    } else {
        format!("{url}.git")
    }
}

/// Inserts a `[sources.<name>]` table into existing `phora.toml` text,
/// preserving surrounding content and formatting, and returns the new text.
///
/// # Errors
///
/// Returns [`Error::Config`] if `doc_text` is not valid TOML.
pub fn insert_source(
    doc_text: &str,
    name: &str,
    source: &AddTarget,
    root: Option<&str>,
) -> Result<String> {
    config_edit::upsert_source(doc_text, name, source, source.branch.as_deref(), None, root)
}

/// How to handle a `--to` target absent from the config.
pub(super) enum MissingTarget {
    Create,
    Reject,
}

/// Decides, per missing `--to` target, whether to create it or reject. The real
/// impl prompts on a TTY; tests substitute a fake.
pub(super) trait MissingTargetDecider {
    fn decide(&self, name: &str, path: &str) -> MissingTarget;
}

/// Whether a `--to` target absent from the config may be created.
///
/// `--to` already chose the path, so an existing directory leaves nothing to
/// ask: the answer would be yes every time. Only a directory phora would have
/// to create is worth a question.
pub(super) fn missing_target_decision(
    path_exists: bool,
    assume_yes: bool,
    interactive: bool,
    confirm: impl FnOnce() -> bool,
) -> MissingTarget {
    if path_exists || assume_yes {
        return MissingTarget::Create;
    }
    if !interactive {
        return MissingTarget::Reject;
    }
    if confirm() {
        MissingTarget::Create
    } else {
        MissingTarget::Reject
    }
}

/// Upsert `[sources.<name>]` and bind it into `[targets.default]`, creating that
/// target (flat layout, rooted at `.`) only when it does not already exist.
///
/// # Errors
///
/// Returns [`Error::Config`] if `text` is not valid TOML.
pub(super) fn add_to_default_target(
    text: &str,
    name: &str,
    source: &AddTarget,
    branch: Option<&str>,
    tag: Option<&str>,
    root: Option<&str>,
) -> Result<String> {
    let mut current = config_edit::upsert_source(text, name, source, branch, tag, root)?;
    if !target_exists(&current, "default")? {
        current = config_edit::upsert_target(&current, "default", ".", Some("flat"))?;
    }
    Ok(config_edit::bind(
        &current,
        "default",
        &[name.to_owned()],
        &BindRefinement::default(),
    )?
    .text)
}

/// Atomically upsert `[sources.<name>]` and bind it to every target in `targets`
/// over a single config-text string, returning the final text or erring whole.
/// A missing target is resolved by `decider`: create it (flat layout) or reject.
/// Each bind carries `refinement` so an aliased/scoped `add --to` writes a table
/// binding in every target.
///
/// # Errors
///
/// Returns [`Error::Config`] if a target is missing and the decider rejects it
/// (resolved before any bind, so a failure yields no partial text).
#[allow(
    clippy::too_many_arguments,
    reason = "single-string desugar carries the source shape plus refspec and bind targets"
)]
pub(super) fn add_with_binds(
    text: &str,
    name: &str,
    source: &AddTarget,
    branch: Option<&str>,
    tag: Option<&str>,
    root: Option<&str>,
    targets: &[String],
    refinement: &BindRefinement,
    decider: &dyn MissingTargetDecider,
) -> Result<String> {
    let mut current = config_edit::upsert_source(text, name, source, branch, tag, root)?;
    let bind_names = [name.to_owned()];
    for target in targets {
        if !target_exists(&current, target)? {
            let path = format!("./{target}");
            match decider.decide(target, &path) {
                MissingTarget::Create => {
                    current = config_edit::upsert_target(&current, target, &path, Some("flat"))?;
                }
                MissingTarget::Reject => {
                    return Err(Error::Config(super::bind::missing_target_message(
                        target, false,
                    )));
                }
            }
        }
        current = config_edit::bind(&current, target, &bind_names, refinement)?.text;
    }
    Ok(current)
}

fn target_exists(text: &str, target: &str) -> Result<bool> {
    let doc = text
        .parse::<toml_edit::DocumentMut>()
        .map_err(|e| Error::Config(format!("parse toml: {e}")))?;
    Ok(doc
        .get("targets")
        .and_then(toml_edit::Item::as_table_like)
        .is_some_and(|targets| targets.contains_key(target)))
}