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
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, bail, ensure};
use serde::Deserialize;
use serde::de::{Error as DeError, MapAccess, SeqAccess, Visitor};

use super::{AttachPoints, Config};
use crate::detect;
use crate::driver::{CommandSpec, Driver, Format, Text};

/// A driver's read or write step: a mise task or an argv.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum CommandField {
    /// A `mise run` task name.
    Mise(String),
    /// A program and its arguments, run without a shell.
    Argv(Vec<String>),
}

impl CommandField {
    fn into_spec(self) -> Result<CommandSpec> {
        match self {
            Self::Mise(task) => {
                if task.is_empty() {
                    bail!("mise task name is empty");
                }
                Ok(CommandSpec::Mise(task))
            }
            Self::Argv(argv) => {
                ensure!(!argv.is_empty(), "driver argv is empty");
                Ok(CommandSpec::Argv(argv))
            }
        }
    }
}

/// A version driver as declared, before it becomes a [`Driver`]. `format` and
/// `keys` edit the manifest in place. `read` and `write` run commands instead
/// and take precedence.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct DriverSpec {
    /// `toml` or `json`, edited at `keys`. `gomod` (the `// vX.Y.Z` comment on
    /// a `go.mod` module line) and `version` (a file containing only the
    /// version) take no keys.
    pub format: Option<String>,
    /// Key paths containing the version, tried in order.
    pub keys: Option<Vec<String>>,
    /// Command that takes the manifest on stdin and prints the version.
    pub read: Option<CommandField>,
    /// Command that takes the manifest on stdin and prints it with the new
    /// version.
    pub write: Option<CommandField>,
    /// Command run after the bumps, such as a lockfile refresh. Inferred from
    /// the tree for stock manifests when omitted.
    pub after: Option<String>,
}

impl DriverSpec {
    /// Build the [`Driver`]. `name` only labels the errors.
    ///
    /// # Errors
    ///
    /// Returns an error when a `read` and `write` pair has an empty mise task
    /// name or an empty argv. Without that pair, it returns an error when
    /// `format` is missing or not `toml`, `json`, `gomod`, or `version`, when
    /// `keys` is missing or empty for `toml` or `json`, or when `gomod` or
    /// `version` has `keys`.
    pub fn into_driver(self, name: &str) -> Result<Driver> {
        if let (Some(read), Some(write)) = (self.read, self.write) {
            return Ok(Driver::Command {
                read: read.into_spec()?,
                write: write.into_spec()?,
                after: self.after,
            });
        }
        let format = match self.format.as_deref() {
            Some("toml") => Format::Toml,
            Some("json") => Format::Json,
            Some(text @ ("gomod" | "version")) => {
                ensure!(
                    self.keys.is_none(),
                    "driver {name:?} has format {text}, which reads the whole file and takes no keys"
                );
                let text = if text == "gomod" {
                    Text::GoMod
                } else {
                    Text::Version
                };
                return Ok(Driver::Text {
                    text,
                    after: self.after,
                });
            }
            Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
            None => bail!("driver {name:?} needs format+keys or read+write"),
        };
        let keys = self
            .keys
            .filter(|keys| !keys.is_empty())
            .with_context(|| format!("driver {name:?} needs keys"))?;
        Ok(Driver::Path {
            format,
            keys,
            after: self.after,
        })
    }

    pub(super) fn stock(name: &str) -> Option<Self> {
        match name {
            "cargo" => Some(Self {
                format: Some("toml".into()),
                keys: Some(vec![
                    "workspace.package.version".into(),
                    "package.version".into(),
                ]),
                ..Self::default()
            }),
            "npm" => Some(Self {
                format: Some("json".into()),
                keys: Some(vec!["version".into()]),
                ..Self::default()
            }),
            "pyproject" => Some(Self {
                format: Some("toml".into()),
                keys: Some(vec!["project.version".into()]),
                ..Self::default()
            }),
            "go" => Some(Self {
                format: Some("gomod".into()),
                ..Self::default()
            }),
            "version" => Some(Self {
                format: Some("version".into()),
                ..Self::default()
            }),
            _ => None,
        }
    }

    pub(super) fn merge(self, over: Self) -> Self {
        Self {
            format: over.format.or(self.format),
            keys: over.keys.or(self.keys),
            read: over.read.or(self.read),
            write: over.write.or(self.write),
            after: over.after.or(self.after),
        }
    }
}

/// One released package: its manifest, how that manifest contains the version,
/// and how it is published.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PackageSpec {
    /// The name fragments, tags, and the changelog use for the package.
    pub name: String,
    /// The manifest, relative to the directory containing `.ctl/`.
    pub path: PathBuf,
    /// A `drivers` entry or stock driver name. Omit to infer it from the
    /// manifest file name.
    pub driver: Option<String>,
    /// Stock `cargo` / `bun`, a `publishers` key, or omit to infer. `none`
    /// releases the package on GitHub only: tag, Release, and assets, with no
    /// registry upload.
    pub publisher: Option<String>,
    /// Pretty noun (`crate`, `package`, `wheel`). Defaults from the publisher.
    pub noun: Option<String>,
    /// How the package is published, beyond what its manifest implies.
    ///
    /// A mapping contains options of the publisher the package resolves to,
    /// which keeps its upload command and its registry check: `verify: false`
    /// for cargo. A list replaces the whole upload command, and the registry
    /// check goes with it unless `query` is set. When omitted, the publisher
    /// runs with its defaults.
    pub publish: Option<Publish>,
    /// Fills the publisher's `{registry}` placeholder and is named in the plan.
    /// Empty means none.
    pub registry: Option<String>,
    /// Asks the registry whether a version is published, in place of the
    /// publisher's query or the crates.io index read. When omitted, the
    /// publisher decides; an empty list turns the check off for this package.
    pub query: Option<Vec<String>>,
    /// Package CHANGELOG.md. Defaults to next to the manifest.
    pub changelog: Option<PathBuf>,
    /// Lets this package leave `0.0.0` with a `minor` fragment, so its first
    /// release is `0.1.0`. When omitted, a package at `0.0.0` takes only
    /// `patch` and first releases `0.0.1`. Inert once the package has released.
    pub first_minor: bool,
    /// The tag of the candidate versions this package releases, such as `rc`:
    /// `verctl version` writes `<base>-<tag>.<count>` while it is set. When
    /// omitted, the package releases stable versions, and a current prerelease
    /// version becomes the stable one.
    pub prerelease: Option<Prerelease>,
    /// The version is on one marker line of the file, such as
    /// `# version: 1.2.0`, `// version: 1.2.0`, or `<!-- version: 1.2.0 -->`.
    /// So a file of any type can be a package, such as one reusable workflow
    /// or one script.
    ///
    /// When unset, a file is read by its stock or named driver, and a stray
    /// marker line in it means nothing. It takes no `driver` or driver fields,
    /// and with no publisher the package releases on GitHub only.
    pub marker: bool,
    /// The crates.io logins this package's crates must list as owners, which
    /// `check registry` proves. It replaces the top-level `owners` for this
    /// package. When omitted, the package expects the top-level list.
    pub owners: Option<Vec<String>>,
    /// Whether this package's crates on crates.io must disable API-token
    /// publishing (`trustpub_only = true`). Overrides the top-level setting
    /// when set; omit to inherit it.
    pub trusted_publishing_only: Option<bool>,
    /// Named ecosystem (`cargo`, `bun`, or an entry under `ecosystems`). Omit
    /// to infer the built-in ecosystem from the manifest file name.
    pub ecosystem: Option<String>,
    /// Named step under `steps` that replaces this package's Lockfile block.
    /// Omit to use the ecosystem's built-in or declared lockfile block.
    pub lockfile: Option<String>,
    /// Package-scoped lifecycle points (`version`, `verify`, `released`) where
    /// named steps attach. Omit to run no per-package steps.
    pub at: AttachPoints,
    /// Inline driver fields. They override the named driver's.
    pub spec: DriverSpec,
    /// Every key under the package that no field above reads, checked by
    /// `no_unknown_package_keys`.
    pub(super) unknown: BTreeSet<String>,
}

/// The tag of a candidate version: lowercase ASCII letters.
///
/// Letters keep `<tag>.<count>` a valid semver prerelease with a separate
/// numeric count, keep the tag a valid npm dist-tag, and make tags compare in
/// semver order as words do (`alpha < beta < rc`). A package's rule in
/// `a_prerelease_is_lowercase_letters` refuses any other tag at load, so a
/// tag read from a loaded config always passes [`Prerelease::is_valid`].
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct Prerelease(String);

impl Prerelease {
    /// A tag, or the reason `tag` is not one.
    ///
    /// # Errors
    ///
    /// Returns an error when `tag` is empty or contains anything but lowercase
    /// ASCII letters.
    pub fn new(tag: &str) -> Result<Self> {
        let tag = Self(tag.to_owned());
        ensure!(tag.is_valid(), "{}", Self::RULE);
        Ok(tag)
    }

    /// The tag as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether the tag is one or more lowercase ASCII letters, and neither `x`
    /// nor `latest`.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self.0.is_empty()
            && !matches!(self.0.as_str(), "x" | "latest")
            && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
    }

    /// Two words are refused besides the letter rule. npm reads `x` alone as
    /// the version range "any" and refuses it as a dist-tag. `latest` is the
    /// dist-tag every plain install resolves, so a candidate under it would
    /// reach every consumer.
    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";
}

impl PackageSpec {
    /// The upload command this package wrote in place of its publisher's.
    #[must_use]
    pub fn publish_command(&self) -> Option<&[String]> {
        match &self.publish {
            Some(Publish::Command(argv)) => Some(argv),
            Some(Publish::Options(_) | Publish::Step(_)) | None => None,
        }
    }

    /// The options this package wrote for its publisher.
    #[must_use]
    pub fn publish_options(&self) -> Option<&PublishOptions> {
        match &self.publish {
            Some(Publish::Options(options)) => Some(options),
            Some(Publish::Command(_) | Publish::Step(_)) | None => None,
        }
    }

    /// The named step under `steps` that replaces this package's upload
    /// command while keeping its ecosystem's registry query.
    #[must_use]
    pub fn publish_step(&self) -> Option<&str> {
        match &self.publish {
            Some(Publish::Step(name)) => Some(name.as_str()),
            Some(Publish::Options(_) | Publish::Command(_)) | None => None,
        }
    }

    /// The named step implementing this package's Lockfile block, whether set
    /// directly on the package or inherited from its declared ecosystem.
    #[must_use]
    pub fn lockfile_step<'a>(&'a self, config: &'a Config) -> Option<&'a str> {
        self.lockfile.as_deref().or_else(|| {
            self.ecosystem
                .as_deref()
                .and_then(|name| config.ecosystems.get(name))
                .and_then(|ecosystem| ecosystem.lockfile.as_deref())
        })
    }

    /// The named step implementing this package's publish upload block,
    /// whether set directly via `publish: <step>` or inherited from its
    /// declared ecosystem when no explicit `publisher` overrides it.
    #[must_use]
    pub fn effective_publish_step<'a>(&'a self, config: &'a Config) -> Option<&'a str> {
        self.publish_step().or_else(|| {
            if self.publisher.is_some() {
                return None;
            }
            self.ecosystem
                .as_deref()
                .and_then(|name| config.ecosystems.get(name))
                .and_then(|ecosystem| ecosystem.publish.as_deref())
        })
    }

    /// The package changelog, resolved against `root`.
    #[must_use]
    pub fn changelog_path(&self, root: &Path) -> PathBuf {
        if let Some(path) = &self.changelog {
            return root.join(path);
        }
        root.join(&self.path)
            .parent()
            .unwrap_or(root)
            .join("CHANGELOG.md")
    }

    /// The version driver. It is the stock or named driver with this package's
    /// own fields over it. A lockfile follow-up is inferred when none is set.
    ///
    /// # Errors
    ///
    /// Returns an error when the merged driver is incomplete or invalid, as
    /// described for [`DriverSpec::into_driver`]. A package whose file is
    /// not `Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, or
    /// `VERSION` needs a driver of its own.
    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
        if self.marker {
            return Ok(Driver::Text {
                text: Text::Marker,
                after: self.spec.after.clone(),
            });
        }
        let inferred = self
            .path
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(stock_name_for_file);
        let driver_name = self.driver.as_deref().or(inferred);
        let mut spec = driver_name
            .and_then(|name| config.driver_spec(name))
            .unwrap_or_default();
        spec = spec.merge(self.spec.clone());
        if spec.after.is_none() {
            spec.after = detect::follow_up(&root.join(&self.path));
        }
        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
    }

    /// The version this package's file contains now, read through its driver.
    /// Every command that reads a current version reads it here, so each
    /// error shows the package and its file.
    ///
    /// # Errors
    ///
    /// Returns an error naming the package when its driver cannot be
    /// resolved, its file cannot be read, or the driver finds no version in
    /// it.
    pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
        let path = root.join(&self.path);
        let context = || format!("package {}: {}", self.name, path.display());
        let driver = self.resolve(config, root).with_context(context)?;
        let raw = driver.source(&path).with_context(context)?;
        let version = driver.read(&raw).with_context(context)?.trim().to_owned();
        Ok(Current {
            driver,
            path,
            raw,
            version,
        })
    }
}

/// Publisher options as a package wrote them: each key with its value, not
/// yet read by the publisher they belong to.
pub type PublishOptions = BTreeMap<String, serde_json::Value>;

/// What a package wrote under `publish`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Publish {
    /// Options of the publisher the package resolves to. The publisher reads
    /// them, so an option another publisher has is an error at load.
    Options(PublishOptions),
    /// The whole upload command, run in place of the publisher's.
    Command(Vec<String>),
    /// A named step under `steps` that replaces the upload command while
    /// keeping the ecosystem's registry query.
    Step(String),
}

/// Untagged reads all shapes and then reports "matched no variant", naming a
/// type nobody wrote. So the shape is read here and reported in the words a
/// repo uses.
const PUBLISH_SHAPES: &str = "a mapping of publisher options, a list that is the whole upload command, or a step name from steps";

impl<'de> Deserialize<'de> for Publish {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(PublishVisitor)
    }
}

struct PublishVisitor;

impl<'de> Visitor<'de> for PublishVisitor {
    type Value = Publish;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{PUBLISH_SHAPES}")
    }

    fn visit_str<E: DeError>(self, v: &str) -> Result<Publish, E> {
        Ok(Publish::Step(v.to_owned()))
    }

    fn visit_string<E: DeError>(self, v: String) -> Result<Publish, E> {
        Ok(Publish::Step(v))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
        let mut argv = Vec::new();
        while let Some(part) = seq.next_element::<String>()? {
            argv.push(part);
        }
        Ok(Publish::Command(argv))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
        let mut options = PublishOptions::new();
        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
            options.insert(key, value);
        }
        Ok(Publish::Options(options))
    }
}

/// A package's version as its file contains it now, from
/// [`PackageSpec::current`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Current {
    /// The driver that read the version and writes the next one.
    pub driver: Driver,
    /// The version file, joined to the repository root.
    pub path: PathBuf,
    /// The file's text: empty for a `VERSION` file that does not exist yet.
    pub raw: String,
    /// The version, trimmed.
    pub version: String,
}

fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
    match file_name {
        "Cargo.toml" => Some("cargo"),
        "package.json" => Some("npm"),
        "pyproject.toml" => Some("pyproject"),
        "go.mod" => Some("go"),
        "VERSION" => Some("version"),
        _ => None,
    }
}

/// Build a stock [`Driver`] by its built-in name (`cargo`, `npm`, `pyproject`,
/// `go`, or `version`).
///
/// # Errors
///
/// Returns an error when `name` is not a built-in driver or its specification
/// cannot be compiled.
pub fn stock_driver(name: &str) -> Result<Driver> {
    DriverSpec::stock(name)
        .with_context(|| format!("unknown stock driver {name:?}"))?
        .into_driver(name)
}