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::{MapAccess, SeqAccess, Visitor};
8
9use super::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    /// Inline driver fields. They override the named driver's.
217    pub spec: DriverSpec,
218    /// Every key under the package that no field above reads, checked by
219    /// `no_unknown_package_keys`.
220    pub(super) unknown: BTreeSet<String>,
221}
222
223/// The tag of a candidate version: lowercase ASCII letters.
224///
225/// Letters keep `<tag>.<count>` a valid semver prerelease with a separate
226/// numeric count, keep the tag a valid npm dist-tag, and make tags compare in
227/// semver order as words do (`alpha < beta < rc`). A package's rule in
228/// `a_prerelease_is_lowercase_letters` refuses any other tag at load, so a
229/// tag read from a loaded config always passes [`Prerelease::is_valid`].
230#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
231#[serde(transparent)]
232pub struct Prerelease(String);
233
234impl Prerelease {
235    /// A tag, or the reason `tag` is not one.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error when `tag` is empty or contains anything but lowercase
240    /// ASCII letters.
241    pub fn new(tag: &str) -> Result<Self> {
242        let tag = Self(tag.to_owned());
243        ensure!(tag.is_valid(), "{}", Self::RULE);
244        Ok(tag)
245    }
246
247    /// The tag as written.
248    #[must_use]
249    pub fn as_str(&self) -> &str {
250        &self.0
251    }
252
253    /// Whether the tag is one or more lowercase ASCII letters, and neither `x`
254    /// nor `latest`.
255    #[must_use]
256    pub fn is_valid(&self) -> bool {
257        !self.0.is_empty()
258            && !matches!(self.0.as_str(), "x" | "latest")
259            && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
260    }
261
262    /// Two words are refused besides the letter rule. npm reads `x` alone as
263    /// the version range "any" and refuses it as a dist-tag. `latest` is the
264    /// dist-tag every plain install resolves, so a candidate under it would
265    /// reach every consumer.
266    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";
267}
268
269impl PackageSpec {
270    /// The upload command this package wrote in place of its publisher's.
271    #[must_use]
272    pub fn publish_command(&self) -> Option<&[String]> {
273        match &self.publish {
274            Some(Publish::Command(argv)) => Some(argv),
275            Some(Publish::Options(_)) | None => None,
276        }
277    }
278
279    /// The options this package wrote for its publisher.
280    #[must_use]
281    pub fn publish_options(&self) -> Option<&PublishOptions> {
282        match &self.publish {
283            Some(Publish::Options(options)) => Some(options),
284            Some(Publish::Command(_)) | None => None,
285        }
286    }
287
288    /// The package changelog, resolved against `root`.
289    #[must_use]
290    pub fn changelog_path(&self, root: &Path) -> PathBuf {
291        if let Some(path) = &self.changelog {
292            return root.join(path);
293        }
294        root.join(&self.path)
295            .parent()
296            .unwrap_or(root)
297            .join("CHANGELOG.md")
298    }
299
300    /// The version driver. It is the stock or named driver with this package's
301    /// own fields over it. A lockfile follow-up is inferred when none is set.
302    ///
303    /// # Errors
304    ///
305    /// Returns an error when the merged driver is incomplete or invalid, as
306    /// described for [`DriverSpec::into_driver`]. A package whose file is
307    /// not `Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, or
308    /// `VERSION` needs a driver of its own.
309    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
310        if self.marker {
311            return Ok(Driver::Text {
312                text: Text::Marker,
313                after: self.spec.after.clone(),
314            });
315        }
316        let inferred = self
317            .path
318            .file_name()
319            .and_then(|name| name.to_str())
320            .and_then(stock_name_for_file);
321        let driver_name = self.driver.as_deref().or(inferred);
322        let mut spec = driver_name
323            .and_then(|name| config.driver_spec(name))
324            .unwrap_or_default();
325        spec = spec.merge(self.spec.clone());
326        if spec.after.is_none() {
327            spec.after = detect::follow_up(&root.join(&self.path));
328        }
329        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
330    }
331
332    /// The version this package's file contains now, read through its driver.
333    /// Every command that reads a current version reads it here, so each
334    /// error shows the package and its file.
335    ///
336    /// # Errors
337    ///
338    /// Returns an error naming the package when its driver cannot be
339    /// resolved, its file cannot be read, or the driver finds no version in
340    /// it.
341    pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
342        let path = root.join(&self.path);
343        let context = || format!("package {}: {}", self.name, path.display());
344        let driver = self.resolve(config, root).with_context(context)?;
345        let raw = driver.source(&path).with_context(context)?;
346        let version = driver.read(&raw).with_context(context)?.trim().to_owned();
347        Ok(Current {
348            driver,
349            path,
350            raw,
351            version,
352        })
353    }
354}
355
356/// Publisher options as a package wrote them: each key with its value, not
357/// yet read by the publisher they belong to.
358pub type PublishOptions = BTreeMap<String, serde_json::Value>;
359
360/// What a package wrote under `publish`.
361#[derive(Debug, Clone, PartialEq, Eq)]
362#[non_exhaustive]
363pub enum Publish {
364    /// Options of the publisher the package resolves to. The publisher reads
365    /// them, so an option another publisher has is an error at load.
366    Options(PublishOptions),
367    /// The whole upload command, run in place of the publisher's.
368    Command(Vec<String>),
369}
370
371/// Untagged reads both shapes and then reports "matched no variant", naming a
372/// type nobody wrote. So the shape is read here and reported in the words a
373/// repo uses.
374const PUBLISH_SHAPES: &str =
375    "a mapping of publisher options, or a list that is the whole upload command";
376
377impl<'de> Deserialize<'de> for Publish {
378    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
379        deserializer.deserialize_any(PublishVisitor)
380    }
381}
382
383struct PublishVisitor;
384
385impl<'de> Visitor<'de> for PublishVisitor {
386    type Value = Publish;
387
388    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
389        write!(formatter, "{PUBLISH_SHAPES}")
390    }
391
392    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
393        let mut argv = Vec::new();
394        while let Some(part) = seq.next_element::<String>()? {
395            argv.push(part);
396        }
397        Ok(Publish::Command(argv))
398    }
399
400    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
401        let mut options = PublishOptions::new();
402        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
403            options.insert(key, value);
404        }
405        Ok(Publish::Options(options))
406    }
407}
408
409/// A package's version as its file contains it now, from
410/// [`PackageSpec::current`].
411#[derive(Debug, Clone)]
412#[non_exhaustive]
413pub struct Current {
414    /// The driver that read the version and writes the next one.
415    pub driver: Driver,
416    /// The version file, joined to the repository root.
417    pub path: PathBuf,
418    /// The file's text: empty for a `VERSION` file that does not exist yet.
419    pub raw: String,
420    /// The version, trimmed.
421    pub version: String,
422}
423
424fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
425    match file_name {
426        "Cargo.toml" => Some("cargo"),
427        "package.json" => Some("npm"),
428        "pyproject.toml" => Some("pyproject"),
429        "go.mod" => Some("go"),
430        "VERSION" => Some("version"),
431        _ => None,
432    }
433}
434
435/// Build a stock [`Driver`] by its built-in name (`cargo`, `npm`, `pyproject`,
436/// `go`, or `version`).
437///
438/// # Errors
439///
440/// Returns an error when `name` is not a built-in driver or its specification
441/// cannot be compiled.
442pub fn stock_driver(name: &str) -> Result<Driver> {
443    DriverSpec::stock(name)
444        .with_context(|| format!("unknown stock driver {name:?}"))?
445        .into_driver(name)
446}