verctl-core 0.9.7

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
use std::path::Path;

use anyhow::{Result, ensure};

use super::PublisherSpec;
use crate::config::{Config, EcosystemSpec, PackageSpec, Prerelease, PublishOptions, StepSpec};
use crate::{members, opt_out};

/// 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
pub(super) 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 {
            if let Some(options) = spec.publish_options().filter(|options| !options.is_empty()) {
                return Err(no_options(&spec.name, name, options));
            }
            return Ok(Self::ReleaseOnly);
        }
        if spec.publisher.is_none()
            && let Some(eco_name) = spec.ecosystem.as_deref()
            && let Some(eco) = config.ecosystems.get(eco_name)
        {
            return Self::declared_from_ecosystem(config, spec, eco_name, eco);
        }
        let step_argv = spec
            .publish_step()
            .and_then(|step| config.steps.get(step))
            .map(StepSpec::argv);
        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() && step_argv.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());
        } else if let Some(argv) = step_argv {
            recipe.argv = Some(argv);
        }
        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,
        })
    }

    fn declared_from_ecosystem(
        config: &Config,
        spec: &PackageSpec,
        eco_name: &str,
        eco: &EcosystemSpec,
    ) -> Result<Self, String> {
        if let Some(options) = spec.publish_options().filter(|options| !options.is_empty()) {
            return Err(no_options(&spec.name, eco_name, options));
        }
        let argv = spec.publish_command().map(<[String]>::to_vec).or_else(|| {
            spec.effective_publish_step(config)
                .and_then(|step| config.steps.get(step))
                .map(StepSpec::argv)
        });
        let Some(argv) = argv else {
            return Ok(Self::ReleaseOnly);
        };
        let query = eco
            .registry
            .as_deref()
            .and_then(|step| config.steps.get(step))
            .map(StepSpec::argv);
        Ok(Self::Command {
            name: eco_name.to_owned(),
            recipe: PublisherSpec {
                noun: spec.noun.clone(),
                argv: Some(argv),
                query,
                ..PublisherSpec::default()
            },
        })
    }

    /// 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);
        };
        if spec.publish_step().is_some() {
            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),
    };
    if spec.publish_command().is_none()
        && let Some(step_name) = spec.effective_publish_step(config)
        && let Some(step) = config.steps.get(step_name)
    {
        let argv = step.argv();
        ensure!(
            !argv.is_empty(),
            "package {:?}: step {step_name:?} renders an empty command",
            spec.name
        );
        let noun = spec
            .noun
            .clone()
            .or_else(|| recipe.noun.clone())
            .unwrap_or_else(|| "package".into());
        return Ok((format!("step {step_name}"), noun, argv));
    }
    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;
    }
    if let Some(ecosystem) = spec.ecosystem.as_deref() {
        if config.ecosystems.contains_key(ecosystem) {
            if spec.effective_publish_step(config).is_some() || spec.publish_command().is_some() {
                return ecosystem;
            }
            return RELEASE_ONLY;
        }
        if matches!(ecosystem, "cargo" | "bun") {
            return ecosystem;
        }
    }
    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()
        || spec.publish_step().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,
    }
}