verctl-core 0.9.3

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
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
//! How a package is published.
//!
//! [`Publisher::of`] resolves it once: the built-in cargo or bun upload, a
//! command the repository wrote, or a release on GitHub only. A built-in
//! publisher has typed options a package sets under `publish`, such as
//! [`CargoPublish::verify`], and keeps its registry check. A replaced
//! command has none of either.
//!
//! Placeholders in a `publishers` entry: `{path}` `{dir}` `{registry}`
//! `{config}`, and in a `query` also `{name}` `{version}`. A placeholder with
//! no value fails the run instead of dropping its argument.

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

use anyhow::{Context, Result, bail, ensure};
use serde::Deserialize;

use crate::config::{Config, PackageSpec, Prerelease, PublishOptions};
use crate::{members, opt_out};

/// A publisher recipe: the command to upload a package and where its registry
/// config lives.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct PublisherSpec {
    /// What the registry calls the package. Defaults to `package`.
    pub noun: Option<String>,
    /// Upload command, with the placeholders from the module docs.
    pub argv: Option<Vec<String>>,
    /// Ancestor file that owns registry/auth (`bunfig.toml`).
    pub config_name: Option<String>,
    /// Arguments appended when `config_name` is found.
    pub config_argv: Option<Vec<String>>,
    /// Appended when `registry` is set and does not alias to empty.
    pub registry_argv: Option<Vec<String>>,
    /// Appended when there is no registry (or the alias is empty).
    pub default_argv: Option<Vec<String>>,
    /// Registry aliases. An empty value means the default registry, which needs
    /// no flag.
    #[serde(default)]
    pub registries: BTreeMap<String, String>,
    /// Asks the registry whether a version is published: it exits zero and
    /// prints the version when the registry has it. It runs in the package
    /// directory, where the publisher's registry config is in effect. When
    /// omitted, the stock recipe's query applies; an empty list turns the check
    /// off, leaving the stderr match.
    pub query: Option<Vec<String>>,
}

impl PublisherSpec {
    /// Look up one of the stock publishers (`cargo` or `bun`) by name.
    #[must_use]
    pub fn stock(name: &str) -> Option<Self> {
        match name {
            "cargo" => Some(Self {
                noun: Some("crate".into()),
                argv: Some(vec![
                    "cargo".into(),
                    "publish".into(),
                    "--locked".into(),
                    "--manifest-path".into(),
                    "{path}".into(),
                ]),
                registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
                registries: BTreeMap::from([("crates-io".into(), String::new())]),
                ..Self::default()
            }),
            "bun" => Some(Self {
                noun: Some("package".into()),
                argv: Some(vec![
                    "bun".into(),
                    "publish".into(),
                    "--tolerate-republish".into(),
                    "--cwd".into(),
                    "{dir}".into(),
                ]),
                config_name: Some("bunfig.toml".into()),
                config_argv: Some(vec!["--config".into(), "{config}".into()]),
                registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
                default_argv: Some(vec!["--access".into(), "public".into()]),
                registries: BTreeMap::from([
                    ("npm".into(), String::new()),
                    ("github".into(), "https://npm.pkg.github.com".into()),
                ]),
                query: Some(BUN_QUERY.iter().map(|part| (*part).to_owned()).collect()),
            }),
            _ => None,
        }
    }

    fn merge(self, over: Self) -> Self {
        Self {
            noun: over.noun.or(self.noun),
            argv: over.argv.or(self.argv),
            config_name: over.config_name.or(self.config_name),
            config_argv: over.config_argv.or(self.config_argv),
            registry_argv: over.registry_argv.or(self.registry_argv),
            default_argv: over.default_argv.or(self.default_argv),
            registries: if over.registries.is_empty() {
                self.registries
            } else {
                over.registries
            },
            query: over.query.or(self.query),
        }
    }

    /// Render the noun and argv for one package, expanding placeholders.
    ///
    /// # Errors
    ///
    /// Returns an error when the publisher declares no `argv`, or when an
    /// argument uses a placeholder with no value for this package.
    pub fn render(
        &self,
        name: &str,
        manifest: &Path,
        registry: Option<&str>,
    ) -> Result<(String, Vec<String>)> {
        let argv = self
            .argv
            .as_ref()
            .with_context(|| format!("publisher {name:?} needs argv"))?;
        let out = self.assemble(argv, manifest, registry, &[], ExtraArgs::Upload)?;
        let noun = self.noun.clone().unwrap_or_else(|| "package".into());
        Ok((noun, out))
    }

    /// Expand `argv` for the package in `manifest`, then append what
    /// `appended` requests. `extra` adds placeholders.
    ///
    /// # Errors
    ///
    /// Returns an error when a placeholder has no value.
    pub fn assemble(
        &self,
        argv: &[String],
        manifest: &Path,
        registry: Option<&str>,
        extra: &[(&'static str, String)],
        appended: ExtraArgs,
    ) -> Result<Vec<String>> {
        let dir = package_dir(manifest);
        let config = self
            .config_name
            .as_deref()
            .and_then(|file| find_config(manifest, file));
        let registry = resolve_registry(&self.registries, registry);
        let mut ctx = BTreeMap::from([
            ("path", manifest.display().to_string()),
            ("dir", dir.display().to_string()),
        ]);
        ctx.extend(extra.iter().cloned());
        if let Some(path) = &config {
            ctx.insert("config", path.display().to_string());
        }
        if let Some(registry) = &registry {
            ctx.insert("registry", registry.clone());
        }
        let mut out = expand(argv, &ctx)?;
        let (recipe, default) = match appended {
            ExtraArgs::Upload => (true, true),
            ExtraArgs::StockQuery => (true, false),
            ExtraArgs::Nothing => (false, false),
        };
        if recipe
            && config.is_some()
            && let Some(extra) = &self.config_argv
        {
            out.extend(expand(extra, &ctx)?);
        }
        if recipe && config.is_none() && registry.is_some() {
            if let Some(extra) = &self.registry_argv {
                out.extend(expand(extra, &ctx)?);
            }
        } else if default
            && registry.is_none()
            && let Some(extra) = &self.default_argv
        {
            out.extend(expand(extra, &ctx)?);
        }
        Ok(out)
    }
}

/// What [`PublisherSpec::assemble`] appends after the expanded argv.
#[derive(Debug, Clone, Copy)]
pub enum ExtraArgs {
    /// The recipe's config or registry arguments, else `default_argv`
    /// (`--access public`): the full upload command.
    Upload,
    /// The recipe's config or registry arguments, so a stock query targets the
    /// registry the upload goes to.
    StockQuery,
    /// Nothing: a query a repository declares runs as written, and reaches
    /// the registry through its own `{registry}` or `{config}` placeholder.
    Nothing,
}

/// The directory a manifest sits in; `.` for a bare file name.
#[must_use]
pub fn package_dir(manifest: &Path) -> &Path {
    manifest
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// Resolve a registry alias against `aliases`.
#[must_use]
pub fn resolve_registry(
    aliases: &BTreeMap<String, String>,
    registry: Option<&str>,
) -> Option<String> {
    let raw = registry?.trim();
    if raw.is_empty() {
        return None;
    }
    match aliases.get(raw) {
        Some(mapped) if mapped.is_empty() => None,
        Some(mapped) => Some(mapped.clone()),
        None => Some(raw.to_owned()),
    }
}

/// Replace each `{placeholder}` in `parts` with the value `ctx` provides for
/// it.
///
/// A placeholder left after expansion fails the run instead of dropping its
/// argument. A dropped argument would shorten the command line, and a typo
/// such as `{registr}` would surface later as another tool's error.
///
/// A known placeholder with no value for this package, such as `{registry}`
/// on a package with no registry, fails the same way. Text in braces that is
/// not a placeholder name, such as a JSON argument, passes through.
///
/// # Errors
///
/// Returns an error naming the argument, the placeholder, and the
/// placeholders that have a value here.
pub fn expand(parts: &[String], ctx: &BTreeMap<&str, String>) -> Result<Vec<String>> {
    let mut out = Vec::with_capacity(parts.len());
    for part in parts {
        let mut expanded = part.clone();
        for (key, value) in ctx {
            expanded = expanded.replace(&format!("{{{key}}}"), value);
        }
        if let Some(name) = placeholder_in(&expanded) {
            let known = ctx
                .keys()
                .map(|key| format!("{{{key}}}"))
                .collect::<Vec<_>>()
                .join(" ");
            bail!(
                "argument {part:?} uses {{{name}}}, which has no value for this package; the placeholders with a value are {known}"
            );
        }
        if !expanded.is_empty() {
            out.push(expanded);
        }
    }
    Ok(out)
}

/// The first `{name}` in `text` whose name is a placeholder name: a letter or
/// underscore, then letters, digits, or underscores.
fn placeholder_in(text: &str) -> Option<&str> {
    let mut rest = text;
    while let Some(open) = rest.find('{') {
        let after = &rest[open + 1..];
        let close = after.find('}')?;
        let name = &after[..close];
        let mut chars = name.chars();
        if chars
            .next()
            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            return Some(name);
        }
        rest = after;
    }
    None
}

fn find_config(manifest: &Path, file_name: &str) -> Option<PathBuf> {
    let start = manifest.parent().unwrap_or(manifest);
    for dir in start.ancestors() {
        let candidate = dir.join(file_name);
        if candidate.is_file() {
            return Some(candidate);
        }
        if dir.join(".git").exists() {
            break;
        }
    }
    None
}

/// The stock bun query. `bun pm view` is an alias of `bun info`, which prints
/// one property of the selected version and fails when the version does not
/// exist, as the [`bun info`] page documents.
///
/// [`bun info`]: https://bun.com/docs/pm/cli/info
const BUN_QUERY: [&str; 5] = ["bun", "pm", "view", "{name}@{version}", "version"];

/// The publisher name for a package released only on GitHub: a tag and a
/// Release, with assets when declared, and no registry step. Its argv is
/// empty, and `release` reads that as "nothing to upload". Every other
/// publisher must render a command. An empty argv therefore never passes for
/// this mode.
pub const RELEASE_ONLY: &str = "none";

/// The options of the built-in cargo upload.
///
/// This is the one place that names them, their types, and what each means
/// when omitted. A package writes them under `publish`. They change the
/// built-in command without replacing it, so the crates.io index check and
/// the member-by-member upload of a workspace stay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CargoPublish {
    /// Whether `cargo publish` builds the packed crate before it uploads.
    /// `false` adds `--no-verify`. Set it when CI already builds the packed
    /// crate of every commit the default branch receives, such as a
    /// `cargo package` step the merge queue requires. When omitted, cargo
    /// verifies, as the [`cargo publish`] page describes.
    ///
    /// [`cargo publish`]: https://doc.rust-lang.org/cargo/commands/cargo-publish.html
    pub verify: bool,
}

impl Default for CargoPublish {
    fn default() -> Self {
        Self { verify: true }
    }
}

impl CargoPublish {
    /// Every option cargo has, for the error that names them.
    const OPTIONS: [&'static str; 1] = ["verify"];

    /// The options `package` wrote, over the defaults. The error names what
    /// to change, in the words of `.ctl/ver.yaml`.
    ///
    /// # Errors
    ///
    /// Returns what to change when an option is unknown or has the wrong type.
    pub fn read(package: &str, written: Option<&PublishOptions>) -> Result<Self, String> {
        let mut options = Self::default();
        for (key, value) in written.into_iter().flatten() {
            match key.as_str() {
                "verify" => {
                    options.verify = value.as_bool().ok_or_else(|| {
                        format!("package {package:?}: publish.verify is true or false")
                    })?;
                }
                _ => {
                    return Err(format!(
                        "package {package:?}: cargo has no publish option {key:?}; its options are: {}",
                        Self::OPTIONS.join(", ")
                    ));
                }
            }
        }
        Ok(options)
    }

    /// The arguments these options add to the upload command.
    #[must_use]
    pub fn args(self) -> &'static [&'static str] {
        if self.verify { &[] } else { &["--no-verify"] }
    }

    /// What the plan shows beside the publisher's name: nothing while every
    /// option is at its default.
    #[must_use]
    pub fn note(self) -> Option<&'static str> {
        (!self.verify).then_some("no verify")
    }
}

/// How one package is published, resolved once from what `.ctl/ver.yaml`
/// declares and what the package's manifest states.
///
/// Every command that uploads, checks a registry, or asks whether a package
/// publishes reads this, so the answer is decided in one place.
///
/// Not `#[non_exhaustive]`: `verctl-release` matches every variant
/// exhaustively.
#[derive(Debug, Clone)]
pub enum Publisher {
    /// A tag and a Release, with no registry upload.
    ReleaseOnly,
    /// The built-in cargo upload. The crates.io index decides whether a
    /// version is published, and a virtual workspace uploads member by
    /// member.
    Cargo {
        /// The stock recipe under any `publishers.cargo` fields.
        recipe: PublisherSpec,
        /// The package's cargo options.
        options: CargoPublish,
    },
    /// The built-in bun upload, checked by its stock query.
    Bun {
        /// The stock recipe under any `publishers.bun` fields.
        recipe: PublisherSpec,
    },
    /// A command the repository wrote: a `publish` list on the package, or a
    /// `publishers` entry with its own `argv`. Only a `query` it declares
    /// checks it, because the registry it uploads to cannot be determined
    /// from the config.
    Command {
        /// The `publishers` key, or the package's own name.
        name: String,
        /// The recipe that contains the command.
        recipe: PublisherSpec,
    },
}

impl Publisher {
    /// The publisher of `spec` from `.ctl/ver.yaml` alone, reading no
    /// manifest. The error names what to change in the file.
    fn declared(config: &Config, spec: &PackageSpec) -> Result<Self, String> {
        let name = publisher_name(config, spec);
        if name == RELEASE_ONLY {
            return Ok(Self::ReleaseOnly);
        }
        let over = config.publishers.get(name);
        let stock = PublisherSpec::stock(name);
        let built_in = stock.is_some();
        let entry_replaces = over.is_some_and(|over| over.argv.is_some());
        let mut recipe = match (stock, over) {
            (Some(stock), Some(over)) => stock.merge(over.clone()),
            (Some(stock), None) => stock,
            (None, Some(over)) => over.clone(),
            (None, None) => {
                if spec.publish_command().is_none() {
                    return Err(format!(
                        "package {:?} has no publisher (set publisher / publishers.{name} / argv)",
                        spec.name
                    ));
                }
                PublisherSpec::default()
            }
        };
        if spec.noun.is_some() {
            recipe.noun.clone_from(&spec.noun);
        }
        if let Some(argv) = spec.publish_command() {
            recipe.argv = Some(argv.to_vec());
        }
        let written = spec.publish_options().filter(|options| !options.is_empty());
        if built_in && !entry_replaces && spec.publish_command().is_none() {
            if name == "cargo" {
                return Ok(Self::Cargo {
                    recipe,
                    options: CargoPublish::read(&spec.name, written)?,
                });
            }
            if let Some(options) = written {
                return Err(no_options(&spec.name, name, options));
            }
            return Ok(Self::Bun { recipe });
        }
        if let Some(options) = written {
            return Err(if built_in && entry_replaces {
                format!(
                    "package {:?}: publishers.{name} replaces the upload command, which takes no options; remove publish, or the argv",
                    spec.name
                )
            } else {
                no_options(&spec.name, name, options)
            });
        }
        Ok(Self::Command {
            name: name.to_owned(),
            recipe,
        })
    }

    /// The publisher of `spec` in the repository at `root`.
    ///
    /// A built-in publisher that was inferred from the manifest file name
    /// becomes [`Publisher::ReleaseOnly`] when that manifest opts out of
    /// publishing. A publisher the package names, and a command it writes,
    /// are used as written.
    ///
    /// # Errors
    ///
    /// Returns an error when the package has no publisher, or sets an option
    /// its publisher does not have. It also fails when the manifest cannot be
    /// read or parsed, or opts out while the package sets `registry` or
    /// `publish`.
    pub fn of(config: &Config, spec: &PackageSpec, root: &Path) -> Result<Self> {
        let (publisher, opted_out) = Self::settle(config, spec, root, root)?;
        if let Some(reason) = opted_out {
            ensure!(
                spec.registry.is_none() && spec.publish.is_none(),
                "package {:?} does not publish: {reason}; remove its publish and registry, or the manifest key",
                spec.name
            );
        }
        Ok(publisher)
    }

    /// Whether `spec` publishes, for a copy of the repository: `tree` is the
    /// root of the tree `root` is in, and no manifest lookup leaves it.
    ///
    /// It answers as [`Publisher::of`] does, apart from one case. A manifest
    /// that opts out while the package still sets `registry` or `publish`
    /// gives [`Publisher::ReleaseOnly`] here. The conflict fails the plan, and
    /// `check` reads a merge-base config that may contain it, such as on the
    /// pull request that removes the `registry`.
    ///
    /// # Errors
    ///
    /// Returns an error when the declared publisher is invalid or when the
    /// manifest cannot be read or parsed.
    pub fn of_in(config: &Config, spec: &PackageSpec, root: &Path, tree: &Path) -> Result<Self> {
        Ok(Self::settle(config, spec, root, tree)?.0)
    }

    /// The members this publisher uploads one by one, in publish order, or
    /// `None` when it uploads the package as one.
    ///
    /// # Errors
    ///
    /// Returns an error when the manifest cannot be read or parsed, or when
    /// [`members::members`] fails.
    pub fn members(
        &self,
        config: &Config,
        spec: &PackageSpec,
        root: &Path,
    ) -> Result<Option<Vec<members::Member>>> {
        Ok(self
            .workspace(config, spec, root)?
            .map(|(_, _, members)| members))
    }

    /// A workspace package's cargo recipe, its options, and its members, or
    /// `None` when the package uploads as one.
    ///
    /// # Errors
    ///
    /// Returns an error when the manifest cannot be read or parsed, or when
    /// [`members::members`] fails.
    pub fn workspace(
        &self,
        config: &Config,
        spec: &PackageSpec,
        root: &Path,
    ) -> Result<Option<(PublisherSpec, CargoPublish, Vec<members::Member>)>> {
        let Self::Cargo { recipe, options } = self else {
            return Ok(None);
        };
        let declares_query = spec.query.is_some()
            || config
                .publishers
                .get("cargo")
                .is_some_and(|over| over.query.is_some());
        let manifest = root.join(&spec.path);
        if declares_query || !members::is_virtual(&manifest)? {
            return Ok(None);
        }
        Ok(Some((
            recipe.clone(),
            *options,
            members::members(&manifest)?,
        )))
    }

    /// The publisher of `spec`, and the manifest's reason when its opt-out
    /// turned an inferred built-in publisher into [`Publisher::ReleaseOnly`].
    fn settle(
        config: &Config,
        spec: &PackageSpec,
        root: &Path,
        tree: &Path,
    ) -> Result<(Self, Option<&'static str>)> {
        let declared = Self::declared(config, spec).map_err(anyhow::Error::msg)?;
        let built_in = matches!(
            declared,
            Self::Cargo {
                recipe: _,
                options: _
            } | Self::Bun { recipe: _ }
        );
        if spec.publisher.is_some() || !built_in {
            return Ok((declared, None));
        }
        Ok(opt_out::opt_out(&root.join(&spec.path), tree)?
            .map_or((declared, None), |reason| (Self::ReleaseOnly, Some(reason))))
    }
}

/// The error for options on a publisher that has none.
fn no_options(package: &str, publisher: &str, options: &PublishOptions) -> String {
    let keys: Vec<String> = options.keys().map(|key| format!("publish.{key}")).collect();
    format!(
        "package {package:?} publishes with {publisher}, which has no publish options; remove {}",
        keys.join(", ")
    )
}

/// Whether the `publish` options of `spec` belong to its publisher, checked
/// from `.ctl/ver.yaml` alone so the load can refuse them.
///
/// # Errors
///
/// Returns what to change when an option is unknown to the publisher, has the
/// wrong type, or sits on a publisher that takes none.
pub fn check_options(config: &Config, spec: &PackageSpec) -> Result<(), String> {
    if spec.publish_options().is_none() {
        return Ok(());
    }
    Publisher::declared(config, spec).map(|_| ())
}

/// The npm dist-tag of a candidate: the first identifier of the prerelease of
/// `version`, so `0.8.2-rc.1` gives `rc`. A stable version, and one that is not
/// semver, give none.
///
/// A registry that gets a prerelease with no tag files it under `latest`, which
/// would hand the candidate to every consumer that names no version.
///
/// The first identifier is the tag only when it passes the rule a
/// `prerelease` setting passes ([`Prerelease::is_valid`]): lowercase letters,
/// never `x` or `latest`. npm refuses a dist-tag that parses as a version
/// range, such as `0`, `x` or `v1`, and every plain install resolves
/// `latest`. Any other first identifier gives `next`, the dist-tag npm's docs
/// use for upcoming versions. Only a hand-written version, such as `1.0.0-0`
/// or `1.0.0-v1.1`, has one.
///
/// [`Prerelease::is_valid`]: crate::config::Prerelease::is_valid
#[must_use]
pub fn prerelease_tag(version: &str) -> Option<String> {
    let version = semver::Version::parse(version).ok()?;
    let first = version
        .pre
        .as_str()
        .split('.')
        .next()
        .filter(|tag| !tag.is_empty())?;
    if Prerelease::new(first).is_err() {
        return Some("next".to_owned());
    }
    Some(first.to_owned())
}

/// Resolve a package's label, noun, and upload command.
///
/// The label is the plan's `via`: the publisher, then the registry when one
/// is named, then any option that differs from its default.
///
/// This is the command for a stable version. [`resolve_for_version`] adds what
/// a candidate needs.
///
/// # Errors
///
/// Returns an error when [`Publisher::of`] fails, when the publisher declares
/// no `argv`, or when the rendered command is empty, which only
/// `publisher: none` may be.
pub fn resolve(
    config: &Config,
    spec: &PackageSpec,
    root: &Path,
) -> Result<(String, String, Vec<String>)> {
    resolve_tagged(config, spec, root, None)
}

/// [`resolve`] for the package at `version`.
///
/// The stock bun upload of a candidate adds `--tag <prerelease tag>`. cargo
/// and a command the repository wrote upload as they always do.
///
/// # Errors
///
/// Returns the errors of [`resolve`].
pub fn resolve_for_version(
    config: &Config,
    spec: &PackageSpec,
    root: &Path,
    version: &str,
) -> Result<(String, String, Vec<String>)> {
    resolve_tagged(config, spec, root, prerelease_tag(version).as_deref())
}

/// [`resolve`], with the npm dist-tag the stock bun upload carries, if any.
fn resolve_tagged(
    config: &Config,
    spec: &PackageSpec,
    root: &Path,
    dist_tag: Option<&str>,
) -> Result<(String, String, Vec<String>)> {
    let publisher = Publisher::of(config, spec, root)?;
    let (name, recipe, options) = match &publisher {
        Publisher::ReleaseOnly => {
            let noun = spec.noun.clone().unwrap_or_else(|| "package".into());
            return Ok(("release only".into(), noun, Vec::new()));
        }
        Publisher::Cargo { recipe, options } => ("cargo", recipe, Some(*options)),
        Publisher::Bun { recipe } => ("bun", recipe, None),
        Publisher::Command { name, recipe } => (name.as_str(), recipe, None),
    };
    let manifest = root.join(&spec.path);
    let (noun, mut argv) = recipe.render(name, &manifest, spec.registry.as_deref())?;
    ensure!(
        !argv.is_empty(),
        "package {:?}: publisher {name:?} renders an empty command; set publisher: none to release without a registry",
        spec.name
    );
    let mut label = name.to_owned();
    if let Some(registry) = spec
        .registry
        .as_deref()
        .filter(|registry| !registry.is_empty())
    {
        label = format!("{label} {registry}");
    }
    if let Some(options) = options {
        argv.extend(options.args().iter().map(|part| (*part).to_owned()));
        if let Some(note) = options.note() {
            label = format!("{label}, {note}");
        }
    }
    if matches!(publisher, Publisher::Bun { recipe: _ })
        && let Some(tag) = dist_tag
    {
        argv.extend(["--tag".to_owned(), tag.to_owned()]);
    }
    Ok((label, noun, argv))
}

/// The publisher a package names, tried in order.
///
/// 1. The `publisher` it declares.
/// 2. The stock one its manifest file implies, unless the version is on a
///    marker line: a marker in a `Cargo.toml` shows nothing about crates.io.
/// 3. A `publishers` entry or `publish` command under the package's own name.
/// 4. `none` for a version source no registry reads, such as `go.mod`,
///    `VERSION`, or a marker line, whose release is its tag.
#[must_use]
pub fn publisher_name<'a>(config: &Config, spec: &'a PackageSpec) -> &'a str {
    if let Some(name) = spec.publisher.as_deref() {
        return name;
    }
    let file_name = spec.path.file_name().and_then(|name| name.to_str());
    if !spec.marker
        && let Some(stock) = file_name.and_then(stock_publisher_for_file)
    {
        return stock;
    }
    let names_its_own =
        spec.publish_command().is_some() || config.publishers.contains_key(&spec.name);
    if !names_its_own && (spec.marker || file_name.is_some_and(releases_on_github_only)) {
        return RELEASE_ONLY;
    }
    spec.name.as_str()
}

/// Version sources whose release is a tag and a Release. A Go module is
/// fetched from its tag, and a `VERSION` file names no registry at all, so
/// no upload exists to run.
fn releases_on_github_only(file_name: &str) -> bool {
    matches!(file_name, "go.mod" | "VERSION")
}

/// The built-in publisher inferred from a manifest file name.
#[must_use]
pub fn stock_publisher_for_file(file_name: &str) -> Option<&'static str> {
    match file_name {
        "Cargo.toml" => Some("cargo"),
        "package.json" => Some("bun"),
        _ => None,
    }
}