Skip to main content

verctl_core/config/
package.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, bail, ensure};
6use serde::Deserialize;
7use serde::de::{Error as DeError, MapAccess, SeqAccess, Visitor};
8
9use super::{AttachPoints, Config};
10use crate::detect;
11use crate::driver::{CommandSpec, Driver, Format, Text};
12
13/// A driver's read or write step: a mise task or an argv.
14#[derive(Debug, Clone)]
15#[non_exhaustive]
16pub enum CommandField {
17    /// A `mise run` task name.
18    Mise(String),
19    /// A program and its arguments, run without a shell.
20    Argv(Vec<String>),
21}
22
23impl CommandField {
24    fn into_spec(self) -> Result<CommandSpec> {
25        match self {
26            Self::Mise(task) => {
27                if task.is_empty() {
28                    bail!("mise task name is empty");
29                }
30                Ok(CommandSpec::Mise(task))
31            }
32            Self::Argv(argv) => {
33                ensure!(!argv.is_empty(), "driver argv is empty");
34                Ok(CommandSpec::Argv(argv))
35            }
36        }
37    }
38}
39
40/// A version driver as declared, before it becomes a [`Driver`]. `format` and
41/// `keys` edit the manifest in place. `read` and `write` run commands instead
42/// and take precedence.
43#[derive(Debug, Clone, Default, Deserialize)]
44#[non_exhaustive]
45pub struct DriverSpec {
46    /// `toml` or `json`, edited at `keys`. `gomod` (the `// vX.Y.Z` comment on
47    /// a `go.mod` module line) and `version` (a file containing only the
48    /// version) take no keys.
49    pub format: Option<String>,
50    /// Key paths containing the version, tried in order.
51    pub keys: Option<Vec<String>>,
52    /// Command that takes the manifest on stdin and prints the version.
53    pub read: Option<CommandField>,
54    /// Command that takes the manifest on stdin and prints it with the new
55    /// version.
56    pub write: Option<CommandField>,
57    /// Command run after the bumps, such as a lockfile refresh. Inferred from
58    /// the tree for stock manifests when omitted.
59    pub after: Option<String>,
60}
61
62impl DriverSpec {
63    /// Build the [`Driver`]. `name` only labels the errors.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error when a `read` and `write` pair has an empty mise task
68    /// name or an empty argv. Without that pair, it returns an error when
69    /// `format` is missing or not `toml`, `json`, `gomod`, or `version`, when
70    /// `keys` is missing or empty for `toml` or `json`, or when `gomod` or
71    /// `version` has `keys`.
72    pub fn into_driver(self, name: &str) -> Result<Driver> {
73        if let (Some(read), Some(write)) = (self.read, self.write) {
74            return Ok(Driver::Command {
75                read: read.into_spec()?,
76                write: write.into_spec()?,
77                after: self.after,
78            });
79        }
80        let format = match self.format.as_deref() {
81            Some("toml") => Format::Toml,
82            Some("json") => Format::Json,
83            Some(text @ ("gomod" | "version")) => {
84                ensure!(
85                    self.keys.is_none(),
86                    "driver {name:?} has format {text}, which reads the whole file and takes no keys"
87                );
88                let text = if text == "gomod" {
89                    Text::GoMod
90                } else {
91                    Text::Version
92                };
93                return Ok(Driver::Text {
94                    text,
95                    after: self.after,
96                });
97            }
98            Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
99            None => bail!("driver {name:?} needs format+keys or read+write"),
100        };
101        let keys = self
102            .keys
103            .filter(|keys| !keys.is_empty())
104            .with_context(|| format!("driver {name:?} needs keys"))?;
105        Ok(Driver::Path {
106            format,
107            keys,
108            after: self.after,
109        })
110    }
111
112    pub(super) fn stock(name: &str) -> Option<Self> {
113        match name {
114            "cargo" => Some(Self {
115                format: Some("toml".into()),
116                keys: Some(vec![
117                    "workspace.package.version".into(),
118                    "package.version".into(),
119                ]),
120                ..Self::default()
121            }),
122            "npm" => Some(Self {
123                format: Some("json".into()),
124                keys: Some(vec!["version".into()]),
125                ..Self::default()
126            }),
127            "pyproject" => Some(Self {
128                format: Some("toml".into()),
129                keys: Some(vec!["project.version".into()]),
130                ..Self::default()
131            }),
132            "go" => Some(Self {
133                format: Some("gomod".into()),
134                ..Self::default()
135            }),
136            "version" => Some(Self {
137                format: Some("version".into()),
138                ..Self::default()
139            }),
140            _ => None,
141        }
142    }
143
144    pub(super) fn merge(self, over: Self) -> Self {
145        Self {
146            format: over.format.or(self.format),
147            keys: over.keys.or(self.keys),
148            read: over.read.or(self.read),
149            write: over.write.or(self.write),
150            after: over.after.or(self.after),
151        }
152    }
153}
154
155/// One released package: its manifest, how that manifest contains the version,
156/// and how it is published.
157#[derive(Debug, Clone)]
158#[non_exhaustive]
159pub struct PackageSpec {
160    /// The name fragments, tags, and the changelog use for the package.
161    pub name: String,
162    /// The manifest, relative to the directory containing `.ctl/`.
163    pub path: PathBuf,
164    /// A `drivers` entry or stock driver name. Omit to infer it from the
165    /// manifest file name.
166    pub driver: Option<String>,
167    /// Stock `cargo` / `bun`, a `publishers` key, or omit to infer. `none`
168    /// releases the package on GitHub only: tag, Release, and assets, with no
169    /// registry upload.
170    pub publisher: Option<String>,
171    /// Pretty noun (`crate`, `package`, `wheel`). Defaults from the publisher.
172    pub noun: Option<String>,
173    /// How the package is published, beyond what its manifest implies.
174    ///
175    /// A mapping contains options of the publisher the package resolves to,
176    /// which keeps its upload command and its registry check: `verify: false`
177    /// for cargo. A list replaces the whole upload command, and the registry
178    /// check goes with it unless `query` is set. When omitted, the publisher
179    /// runs with its defaults.
180    pub publish: Option<Publish>,
181    /// Fills the publisher's `{registry}` placeholder and is named in the plan.
182    /// Empty means none.
183    pub registry: Option<String>,
184    /// Asks the registry whether a version is published, in place of the
185    /// publisher's query or the crates.io index read. When omitted, the
186    /// publisher decides; an empty list turns the check off for this package.
187    pub query: Option<Vec<String>>,
188    /// Package CHANGELOG.md. Defaults to next to the manifest.
189    pub changelog: Option<PathBuf>,
190    /// Lets this package leave `0.0.0` with a `minor` fragment, so its first
191    /// release is `0.1.0`. When omitted, a package at `0.0.0` takes only
192    /// `patch` and first releases `0.0.1`. Inert once the package has released.
193    pub first_minor: bool,
194    /// The tag of the candidate versions this package releases, such as `rc`:
195    /// `verctl version` writes `<base>-<tag>.<count>` while it is set. When
196    /// omitted, the package releases stable versions, and a current prerelease
197    /// version becomes the stable one.
198    pub prerelease: Option<Prerelease>,
199    /// The version is on one marker line of the file, such as
200    /// `# version: 1.2.0`, `// version: 1.2.0`, or `<!-- version: 1.2.0 -->`.
201    /// So a file of any type can be a package, such as one reusable workflow
202    /// or one script.
203    ///
204    /// When unset, a file is read by its stock or named driver, and a stray
205    /// marker line in it means nothing. It takes no `driver` or driver fields,
206    /// and with no publisher the package releases on GitHub only.
207    pub marker: bool,
208    /// The crates.io logins this package's crates must list as owners, which
209    /// `check registry` proves. It replaces the top-level `owners` for this
210    /// package. When omitted, the package expects the top-level list.
211    pub owners: Option<Vec<String>>,
212    /// Whether this package's crates on crates.io must disable API-token
213    /// publishing (`trustpub_only = true`). Overrides the top-level setting
214    /// when set; omit to inherit it.
215    pub trusted_publishing_only: Option<bool>,
216    /// Named ecosystem (`cargo`, `bun`, or an entry under `ecosystems`). Omit
217    /// to infer the built-in ecosystem from the manifest file name.
218    pub ecosystem: Option<String>,
219    /// Named step under `steps` that replaces this package's Lockfile block.
220    /// Omit to use the ecosystem's built-in or declared lockfile block.
221    pub lockfile: Option<String>,
222    /// Package-scoped lifecycle points (`version`, `verify`, `released`) where
223    /// named steps attach. Omit to run no per-package steps.
224    pub at: AttachPoints,
225    /// Inline driver fields. They override the named driver's.
226    pub spec: DriverSpec,
227    /// Every key under the package that no field above reads, checked by
228    /// `no_unknown_package_keys`.
229    pub(super) unknown: BTreeSet<String>,
230}
231
232/// The tag of a candidate version: lowercase ASCII letters.
233///
234/// Letters keep `<tag>.<count>` a valid semver prerelease with a separate
235/// numeric count, keep the tag a valid npm dist-tag, and make tags compare in
236/// semver order as words do (`alpha < beta < rc`). A package's rule in
237/// `a_prerelease_is_lowercase_letters` refuses any other tag at load, so a
238/// tag read from a loaded config always passes [`Prerelease::is_valid`].
239#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
240#[serde(transparent)]
241pub struct Prerelease(String);
242
243impl Prerelease {
244    /// A tag, or the reason `tag` is not one.
245    ///
246    /// # Errors
247    ///
248    /// Returns an error when `tag` is empty or contains anything but lowercase
249    /// ASCII letters.
250    pub fn new(tag: &str) -> Result<Self> {
251        let tag = Self(tag.to_owned());
252        ensure!(tag.is_valid(), "{}", Self::RULE);
253        Ok(tag)
254    }
255
256    /// The tag as written.
257    #[must_use]
258    pub fn as_str(&self) -> &str {
259        &self.0
260    }
261
262    /// Whether the tag is one or more lowercase ASCII letters, and neither `x`
263    /// nor `latest`.
264    #[must_use]
265    pub fn is_valid(&self) -> bool {
266        !self.0.is_empty()
267            && !matches!(self.0.as_str(), "x" | "latest")
268            && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
269    }
270
271    /// Two words are refused besides the letter rule. npm reads `x` alone as
272    /// the version range "any" and refuses it as a dist-tag. `latest` is the
273    /// dist-tag every plain install resolves, so a candidate under it would
274    /// reach every consumer.
275    pub(super) const RULE: &'static str = "a prerelease tag is lowercase ASCII letters only, such as rc, beta, or next; never x, which npm reads as a version range, and never latest, which every plain install resolves; remove digits, dots, and capitals";
276}
277
278impl PackageSpec {
279    /// The upload command this package wrote in place of its publisher's.
280    #[must_use]
281    pub fn publish_command(&self) -> Option<&[String]> {
282        match &self.publish {
283            Some(Publish::Command(argv)) => Some(argv),
284            Some(Publish::Options(_) | Publish::Step(_)) | None => None,
285        }
286    }
287
288    /// The options this package wrote for its publisher.
289    #[must_use]
290    pub fn publish_options(&self) -> Option<&PublishOptions> {
291        match &self.publish {
292            Some(Publish::Options(options)) => Some(options),
293            Some(Publish::Command(_) | Publish::Step(_)) | None => None,
294        }
295    }
296
297    /// The named step under `steps` that replaces this package's upload
298    /// command while keeping its ecosystem's registry query.
299    #[must_use]
300    pub fn publish_step(&self) -> Option<&str> {
301        match &self.publish {
302            Some(Publish::Step(name)) => Some(name.as_str()),
303            Some(Publish::Options(_) | Publish::Command(_)) | None => None,
304        }
305    }
306
307    /// The named step implementing this package's Lockfile block, whether set
308    /// directly on the package or inherited from its declared ecosystem.
309    #[must_use]
310    pub fn lockfile_step<'a>(&'a self, config: &'a Config) -> Option<&'a str> {
311        self.lockfile.as_deref().or_else(|| {
312            self.ecosystem
313                .as_deref()
314                .and_then(|name| config.ecosystems.get(name))
315                .and_then(|ecosystem| ecosystem.lockfile.as_deref())
316        })
317    }
318
319    /// The named step implementing this package's publish upload block,
320    /// whether set directly via `publish: <step>` or inherited from its
321    /// declared ecosystem when no explicit `publisher` overrides it.
322    #[must_use]
323    pub fn effective_publish_step<'a>(&'a self, config: &'a Config) -> Option<&'a str> {
324        self.publish_step().or_else(|| {
325            if self.publisher.is_some() {
326                return None;
327            }
328            self.ecosystem
329                .as_deref()
330                .and_then(|name| config.ecosystems.get(name))
331                .and_then(|ecosystem| ecosystem.publish.as_deref())
332        })
333    }
334
335    /// The package changelog, resolved against `root`.
336    #[must_use]
337    pub fn changelog_path(&self, root: &Path) -> PathBuf {
338        if let Some(path) = &self.changelog {
339            return root.join(path);
340        }
341        root.join(&self.path)
342            .parent()
343            .unwrap_or(root)
344            .join("CHANGELOG.md")
345    }
346
347    /// The version driver. It is the stock or named driver with this package's
348    /// own fields over it. A lockfile follow-up is inferred when none is set.
349    ///
350    /// # Errors
351    ///
352    /// Returns an error when the merged driver is incomplete or invalid, as
353    /// described for [`DriverSpec::into_driver`]. A package whose file is
354    /// not `Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, or
355    /// `VERSION` needs a driver of its own.
356    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
357        if self.marker {
358            return Ok(Driver::Text {
359                text: Text::Marker,
360                after: self.spec.after.clone(),
361            });
362        }
363        let inferred = self
364            .path
365            .file_name()
366            .and_then(|name| name.to_str())
367            .and_then(stock_name_for_file);
368        let driver_name = self.driver.as_deref().or(inferred);
369        let mut spec = driver_name
370            .and_then(|name| config.driver_spec(name))
371            .unwrap_or_default();
372        spec = spec.merge(self.spec.clone());
373        if spec.after.is_none() {
374            spec.after = detect::follow_up(&root.join(&self.path));
375        }
376        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
377    }
378
379    /// The version this package's file contains now, read through its driver.
380    /// Every command that reads a current version reads it here, so each
381    /// error shows the package and its file.
382    ///
383    /// # Errors
384    ///
385    /// Returns an error naming the package when its driver cannot be
386    /// resolved, its file cannot be read, or the driver finds no version in
387    /// it.
388    pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
389        let path = root.join(&self.path);
390        let context = || format!("package {}: {}", self.name, path.display());
391        let driver = self.resolve(config, root).with_context(context)?;
392        let raw = driver.source(&path).with_context(context)?;
393        let version = driver.read(&raw).with_context(context)?.trim().to_owned();
394        Ok(Current {
395            driver,
396            path,
397            raw,
398            version,
399        })
400    }
401}
402
403/// Publisher options as a package wrote them: each key with its value, not
404/// yet read by the publisher they belong to.
405pub type PublishOptions = BTreeMap<String, serde_json::Value>;
406
407/// What a package wrote under `publish`.
408#[derive(Debug, Clone, PartialEq, Eq)]
409#[non_exhaustive]
410pub enum Publish {
411    /// Options of the publisher the package resolves to. The publisher reads
412    /// them, so an option another publisher has is an error at load.
413    Options(PublishOptions),
414    /// The whole upload command, run in place of the publisher's.
415    Command(Vec<String>),
416    /// A named step under `steps` that replaces the upload command while
417    /// keeping the ecosystem's registry query.
418    Step(String),
419}
420
421/// Untagged reads all shapes and then reports "matched no variant", naming a
422/// type nobody wrote. So the shape is read here and reported in the words a
423/// repo uses.
424const PUBLISH_SHAPES: &str = "a mapping of publisher options, a list that is the whole upload command, or a step name from steps";
425
426impl<'de> Deserialize<'de> for Publish {
427    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
428        deserializer.deserialize_any(PublishVisitor)
429    }
430}
431
432struct PublishVisitor;
433
434impl<'de> Visitor<'de> for PublishVisitor {
435    type Value = Publish;
436
437    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
438        write!(formatter, "{PUBLISH_SHAPES}")
439    }
440
441    fn visit_str<E: DeError>(self, v: &str) -> Result<Publish, E> {
442        Ok(Publish::Step(v.to_owned()))
443    }
444
445    fn visit_string<E: DeError>(self, v: String) -> Result<Publish, E> {
446        Ok(Publish::Step(v))
447    }
448
449    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
450        let mut argv = Vec::new();
451        while let Some(part) = seq.next_element::<String>()? {
452            argv.push(part);
453        }
454        Ok(Publish::Command(argv))
455    }
456
457    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
458        let mut options = PublishOptions::new();
459        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
460            options.insert(key, value);
461        }
462        Ok(Publish::Options(options))
463    }
464}
465
466/// A package's version as its file contains it now, from
467/// [`PackageSpec::current`].
468#[derive(Debug, Clone)]
469#[non_exhaustive]
470pub struct Current {
471    /// The driver that read the version and writes the next one.
472    pub driver: Driver,
473    /// The version file, joined to the repository root.
474    pub path: PathBuf,
475    /// The file's text: empty for a `VERSION` file that does not exist yet.
476    pub raw: String,
477    /// The version, trimmed.
478    pub version: String,
479}
480
481fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
482    match file_name {
483        "Cargo.toml" => Some("cargo"),
484        "package.json" => Some("npm"),
485        "pyproject.toml" => Some("pyproject"),
486        "go.mod" => Some("go"),
487        "VERSION" => Some("version"),
488        _ => None,
489    }
490}
491
492/// Build a stock [`Driver`] by its built-in name (`cargo`, `npm`, `pyproject`,
493/// `go`, or `version`).
494///
495/// # Errors
496///
497/// Returns an error when `name` is not a built-in driver or its specification
498/// cannot be compiled.
499pub fn stock_driver(name: &str) -> Result<Driver> {
500    DriverSpec::stock(name)
501        .with_context(|| format!("unknown stock driver {name:?}"))?
502        .into_driver(name)
503}