use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr;
use std::{fmt, fs};
use anyhow::{Context, Result, bail, ensure};
use ctl_core::input::{FieldPath, Input};
use ctl_core::validate;
use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::value::MapAccessDeserializer;
use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Serialize, de};
use crate::driver::{CommandSpec, Driver, Format, Text};
use crate::publisher_spec::{self as publisher, PublisherSpec, RELEASE_ONLY};
use crate::{asset_rules as assets, detect};
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum CommandField {
Mise(String),
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))
}
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct DriverSpec {
pub format: Option<String>,
pub keys: Option<Vec<String>>,
pub read: Option<CommandField>,
pub write: Option<CommandField>,
pub after: Option<String>,
}
impl DriverSpec {
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,
})
}
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,
}
}
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),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct PackageSpec {
pub name: String,
pub path: PathBuf,
pub driver: Option<String>,
pub publisher: Option<String>,
pub noun: Option<String>,
#[serde(default)]
pub publish: Option<Publish>,
pub registry: Option<String>,
pub query: Option<Vec<String>>,
pub changelog: Option<PathBuf>,
#[serde(default)]
pub first_minor: bool,
pub prerelease: Option<Prerelease>,
#[serde(default)]
pub marker: bool,
pub owners: Option<Vec<String>>,
#[serde(flatten)]
pub spec: DriverSpec,
#[serde(flatten)]
#[expect(
clippy::zero_sized_map_values,
reason = "the keys are all that is read, and serde has no set to flatten into"
)]
unknown: BTreeMap<String, IgnoredAny>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct Prerelease(String);
impl Prerelease {
pub fn new(tag: &str) -> Result<Self> {
let tag = Self(tag.to_owned());
ensure!(tag.is_valid(), "{}", Self::RULE);
Ok(tag)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[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())
}
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 {
#[must_use]
pub fn publish_command(&self) -> Option<&[String]> {
match &self.publish {
Some(Publish::Command(argv)) => Some(argv),
Some(Publish::Options(_)) | None => None,
}
}
#[must_use]
pub fn publish_options(&self) -> Option<&PublishOptions> {
match &self.publish {
Some(Publish::Options(options)) => Some(options),
Some(Publish::Command(_)) | None => None,
}
}
#[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")
}
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()))
}
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,
})
}
}
pub type PublishOptions = BTreeMap<String, serde_json::Value>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Publish {
Options(PublishOptions),
Command(Vec<String>),
}
const PUBLISH_SHAPES: &str =
"a mapping of publisher options, or a list that is the whole upload command";
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_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))
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Current {
pub driver: Driver,
pub path: PathBuf,
pub raw: String,
pub version: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Runner {
#[garde(custom(at_least_one("label")))]
pub labels: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Job {
pub runners: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Assets {
pub bin: Option<String>,
pub prepare: Option<Vec<String>>,
pub build: Option<Vec<String>>,
#[garde(custom(binary_is_not_beside_files))]
pub binary: Option<String>,
#[serde(default)]
#[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
pub dir: Option<PathBuf>,
#[serde(default)]
#[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
pub files: Vec<PathBuf>,
#[serde(default)]
#[garde(dive, custom(generated_paths_are_sound))]
pub generated: Vec<Generated>,
#[serde(flatten)]
#[garde(dive)]
pub targets: BTreeMap<String, AssetTarget>,
}
impl Assets {
pub const SETTINGS: [&'static str; 7] = [
"bin",
"prepare",
"build",
"binary",
"dir",
"files",
"generated",
];
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Generated {
pub path: String,
#[garde(custom(at_least_one("argument")))]
pub run: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct AssetTarget {
pub runner: Option<String>,
pub os: Option<String>,
pub arch: Option<String>,
pub triple: Option<String>,
pub prepare: Option<Vec<String>>,
pub build: Option<Vec<String>>,
#[garde(inner(custom(a_tarball_name)))]
pub tarball: Option<String>,
#[serde(default)]
#[garde(
custom(target_files_come_with_dir),
inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
)]
pub files: Option<Vec<PathBuf>>,
#[serde(default)]
#[garde(custom(a_packslip_table))]
pub packslip: ArtifactTable,
}
#[derive(Debug, Clone, Default)]
pub struct ArtifactTable(toml_edit::Table);
impl ArtifactTable {
pub fn entries(&self) -> impl Iterator<Item = (&str, &toml_edit::Item)> {
self.0.iter()
}
#[must_use]
pub fn contains_key(&self, key: &str) -> bool {
self.0.contains_key(key)
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&toml_edit::Item> {
self.0.get(key)
}
}
impl fmt::Display for ArtifactTable {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl PartialEq for ArtifactTable {
fn eq(&self, other: &Self) -> bool {
self.to_string() == other.to_string()
}
}
impl Eq for ArtifactTable {}
impl<'de> Deserialize<'de> for ArtifactTable {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let table = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
toml_table(&table).map(Self).map_err(de::Error::custom)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Packslip {
#[garde(inner(custom(inside_the_repo)))]
pub manifest: Option<PathBuf>,
pub attest: Attest,
#[garde(inner(custom(a_public_key_line)))]
pub pubkey: Option<String>,
}
fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
if line.trim().is_empty() {
return Err(garde::Error::new(
"cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
));
}
Ok(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PackslipKeys {
#[serde(default)]
manifest: Option<PathBuf>,
#[serde(default)]
attest: Attest,
#[serde(default)]
pubkey: Option<String>,
}
impl<'de> Deserialize<'de> for Packslip {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(PackslipVisitor)
}
}
struct PackslipVisitor;
impl<'de> Visitor<'de> for PackslipVisitor {
type Value = Packslip;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
Err(E::custom(format!(
"packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
)))
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
Ok(Packslip {
manifest: keys.manifest,
attest: keys.attest,
pubkey: keys.pubkey,
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attest {
#[default]
True,
Link,
False,
}
impl Attest {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::True => "true",
Self::Link => "link",
Self::False => "false",
}
}
}
impl fmt::Display for Attest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Attest {
type Err = String;
fn from_str(word: &str) -> Result<Self, String> {
match word {
"true" => Ok(Self::True),
"link" => Ok(Self::Link),
"false" => Ok(Self::False),
other => Err(format!(
"packslip.attest must be true, link, or false, not {other:?}"
)),
}
}
}
impl Serialize for Attest {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Attest {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(AttestVisitor)
}
}
struct AttestVisitor;
impl Visitor<'_> for AttestVisitor {
type Value = Attest;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("packslip.attest: true, link, or false")
}
fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
Ok(if v { Attest::True } else { Attest::False })
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
v.parse().map_err(E::custom)
}
}
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Vendored {
#[garde(
custom(cannot_be_empty("it names the release and the archives")),
custom(one_plain_name)
)]
pub version: String,
#[serde(default = "Vendored::default_tag")]
#[garde(
custom(cannot_be_empty("it names the release")),
custom(only_placeholders(&["{name}", "{version}"]))
)]
pub tag: String,
#[serde(default = "Vendored::default_archive")]
#[garde(
custom(one_archive_per_target),
custom(only_placeholders(&["{name}", "{version}", "{id}"]))
)]
pub archive: String,
#[serde(default)]
pub build: Vec<String>,
#[garde(custom(inside_the_repo))]
pub dir: PathBuf,
#[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
pub files: Vec<PathBuf>,
#[garde(inner(custom(inside_the_repo)))]
pub notes: Option<PathBuf>,
#[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
pub targets: BTreeMap<String, VendoredTarget>,
}
impl Vendored {
fn default_tag() -> String {
"{name}-{version}".to_owned()
}
fn default_archive() -> String {
"{name}-{version}-{id}.tar.gz".to_owned()
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct VendoredTarget {
#[garde(custom(runner_is_declared))]
pub runner: String,
}
fn one_archive_per_target(archive: &str, config: &Config) -> garde::Result {
validate::one_file_name(archive, config)?;
if !archive.contains("{id}") {
return Err(garde::Error::new(
"must contain {id}, or every target writes the same archive",
));
}
if !archive.ends_with(".tar.gz") {
return Err(garde::Error::new(
"must end in .tar.gz, the only archive verctl writes",
));
}
Ok(())
}
fn only_placeholders(allowed: &'static [&'static str]) -> impl Fn(&str, &Config) -> garde::Result {
move |template, _| {
let rest = allowed
.iter()
.fold(template.to_owned(), |rest, placeholder| {
rest.replace(placeholder, "")
});
if rest.contains(['{', '}']) {
return Err(garde::Error::new(format!(
"has a '{{' or '}}' that is not {}",
allowed.join(", ")
)));
}
Ok(())
}
}
fn one_plain_name(value: &str, _: &Config) -> garde::Result {
if value.is_empty() || value == "." || value == ".." || value.contains(['/', '\\']) {
return Err(garde::Error::new(format!(
"{value:?} must be one plain name, with no / or \\ and not . or .."
)));
}
Ok(())
}
fn every_key_is_one_plain_name<V>(map: &BTreeMap<String, V>, config: &Config) -> garde::Result {
map.keys().try_for_each(|key| one_plain_name(key, config))
}
fn at_least_one_target(targets: &BTreeMap<String, VendoredTarget>, _: &Config) -> garde::Result {
if targets.is_empty() {
return Err(garde::Error::new("must declare at least one target"));
}
Ok(())
}
fn a_tarball_name(template: &str, config: &Config) -> garde::Result {
validate::one_file_name(template, config)?;
only_placeholders(&["{bin}", "{version}", "{os}", "{arch}"])(template, config)?;
if !template.ends_with(".tar.gz") {
return Err(garde::Error::new(
"must end in .tar.gz, the only archive verctl writes",
));
}
Ok(())
}
#[expect(
clippy::ref_option,
reason = "garde passes the field as it is declared"
)]
fn every_tarball_is_its_own(assets: &Option<Assets>, config: &Config) -> garde::Result {
let Some(assets) = assets else {
return Ok(());
};
let Some(package) = config.packages.first() else {
return Ok(());
};
let bin = assets.bin.as_deref().unwrap_or(&package.name);
if let Some((first, second, name)) = assets::tarball_clash(assets, bin) {
return Err(garde::Error::new(format!(
"assets.{first} and assets.{second} both write {name}: set `tarball` on one of them"
)));
}
Ok(())
}
#[expect(
clippy::ref_option,
reason = "garde passes the field as it is declared"
)]
fn packslip_needs_assets(packslip: &Option<Packslip>, config: &Config) -> garde::Result {
let has_targets = config
.assets
.as_ref()
.is_some_and(|assets| !assets.targets.is_empty());
if packslip.is_some() && !has_targets {
return Err(garde::Error::new(
"needs at least one assets target: the bundle is an asset of the Release that carries the tarballs",
));
}
Ok(())
}
pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
let text = fs::read_to_string(path)
.with_context(|| format!("packslip.manifest: read {}", named.display()))?;
let document = text
.parse::<toml_edit::DocumentMut>()
.with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
ensure!(
!document.contains_key("artifact"),
"packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
named.display()
);
Ok(document)
}
fn a_packslip_table(table: &ArtifactTable, _: &Config) -> garde::Result {
if table.contains_key("path") {
return Err(garde::Error::new(
"sets `packslip.path`, the tarball's own path, which verctl writes: delete it",
));
}
Ok(())
}
fn toml_table(
table: &serde_json::Map<String, serde_json::Value>,
) -> Result<toml_edit::Table, String> {
let mut converted = toml_edit::Table::new();
for (key, value) in table {
let value = toml_value(value).map_err(|reason| format!("{key}: {reason}"))?;
converted.insert(key, toml_edit::Item::Value(value));
}
Ok(converted)
}
fn toml_value(value: &serde_json::Value) -> Result<toml_edit::Value, String> {
match value {
serde_json::Value::Null => Err("null has no TOML form: delete the key".to_owned()),
serde_json::Value::Bool(flag) => Ok((*flag).into()),
serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
(Some(integer), _) => Ok(integer.into()),
(None, Some(float)) if number.is_f64() => Ok(float.into()),
_ => Err(format!("{number} is beyond the integers TOML supports")),
},
serde_json::Value::String(text) => Ok(text.as_str().into()),
serde_json::Value::Array(items) => {
let mut array = toml_edit::Array::new();
for item in items {
array.push(toml_value(item)?);
}
Ok(array.into())
}
serde_json::Value::Object(entries) => {
let mut inline = toml_edit::InlineTable::new();
for (key, entry) in entries {
let entry = toml_value(entry).map_err(|reason| format!("{key}: {reason}"))?;
inline.insert(key.as_str(), entry);
}
Ok(inline.into())
}
}
}
fn generated_paths_are_sound(_: &[Generated], config: &Config) -> garde::Result {
let Some(assets) = &config.assets else {
return Ok(());
};
let Some(package) = config.packages.first() else {
return Ok(());
};
let bin = assets.bin.as_deref().unwrap_or(&package.name);
assets::generated_problem(assets, bin)
.map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}
#[expect(
clippy::ref_option,
reason = "garde passes the field as it is declared"
)]
fn dir_comes_with_files(dir: &Option<PathBuf>, config: &Config) -> garde::Result {
let packs_files = config.assets.as_ref().is_some_and(|assets| {
!assets.files.is_empty()
|| (!assets.targets.is_empty()
&& assets.targets.values().all(|target| target.files.is_some()))
});
if dir.is_some() && !packs_files {
return Err(garde::Error::new(
"must come with files, the paths packed from it, or a files list on every target",
));
}
Ok(())
}
#[expect(
clippy::ref_option,
reason = "garde passes the field as it is declared"
)]
fn target_files_come_with_dir(files: &Option<Vec<PathBuf>>, config: &Config) -> garde::Result {
let has_dir = config
.assets
.as_ref()
.is_some_and(|assets| assets.dir.is_some());
if files.is_some() && !has_dir {
return Err(garde::Error::new(
"must come with assets.dir, the directory they are packed from",
));
}
Ok(())
}
fn files_come_with_dir(files: &[PathBuf], config: &Config) -> garde::Result {
let has_dir = config
.assets
.as_ref()
.is_some_and(|assets| assets.dir.is_some());
if !files.is_empty() && !has_dir {
return Err(garde::Error::new(
"must come with dir, the directory they are packed from",
));
}
Ok(())
}
#[expect(
clippy::ref_option,
reason = "garde passes the field as it is declared"
)]
fn binary_is_not_beside_files(binary: &Option<String>, config: &Config) -> garde::Result {
let (Some(_), Some(assets)) = (binary, config.assets.as_ref()) else {
return Ok(());
};
if let Some(id) = assets
.targets
.iter()
.find_map(|(id, target)| target.files.is_some().then_some(id))
{
return Err(garde::Error::new(format!(
"must be omitted when assets.{id}.files lists what the tarball contains; list the binary in files",
)));
}
if assets.dir.is_some() || !assets.files.is_empty() {
return Err(garde::Error::new(
"must be omitted when dir and files list what the tarball contains; list the binary in files",
));
}
Ok(())
}
fn runner_is_declared(runner: &str, config: &Config) -> garde::Result {
if config.runners.contains_key(runner) {
return Ok(());
}
let declared = config.runners.keys().cloned().collect::<Vec<_>>();
Err(garde::Error::new(format!(
"{runner:?} is not declared in runners ({})",
if declared.is_empty() {
"none declared".to_owned()
} else {
format!("declared: {}", declared.join(", "))
}
)))
}
fn something_to_release(packages: &[PackageSpec], config: &Config) -> garde::Result {
if packages.is_empty() && config.vendored.is_empty() {
return Err(garde::Error::new(
"must declare at least one package, or a vendored set",
));
}
Ok(())
}
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Self as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Config {
#[serde(default)]
pub drivers: BTreeMap<String, DriverSpec>,
#[serde(default)]
#[garde(
custom(something_to_release),
custom(no_unknown_package_keys),
custom(release_only_names_no_registry),
custom(publish_options_fit_the_publisher),
custom(python_names_its_publisher),
custom(a_marker_names_no_driver),
custom(a_prerelease_is_lowercase_letters),
custom(package_owners_are_logins)
)]
pub packages: Vec<PackageSpec>,
#[serde(default)]
#[garde(inner(custom(owners_are_logins)))]
pub owners: Option<Vec<String>>,
#[serde(default = "Config::default_release_workflow")]
#[garde(custom(a_workflow_file_name))]
pub release_workflow: String,
#[serde(default = "ReleaseCheck::default_list")]
#[garde(custom(each_release_check_once))]
pub release_checks: Vec<ReleaseCheck>,
#[serde(default)]
#[garde(custom(none_is_not_a_publisher))]
pub publishers: BTreeMap<String, PublisherSpec>,
#[serde(default)]
#[garde(dive)]
pub runners: BTreeMap<String, Runner>,
#[serde(default)]
#[garde(dive, custom(every_tarball_is_its_own))]
pub assets: Option<Assets>,
#[serde(default)]
#[garde(dive, custom(packslip_needs_assets))]
pub packslip: Option<Packslip>,
#[serde(default)]
#[garde(custom(every_key_is_one_plain_name), dive)]
pub vendored: BTreeMap<String, Vendored>,
#[serde(default)]
pub ci: BTreeMap<String, Job>,
#[serde(default)]
#[garde(custom(no_version_label))]
pub prepare: Prepare,
#[serde(default)]
pub proposal: Proposal,
#[serde(default)]
pub changelog: Changelog,
#[serde(default)]
#[garde(dive)]
pub templates: Templates,
#[serde(default)]
#[garde(dive)]
pub tags: Tags,
#[serde(default)]
#[garde(custom(every_pattern_says_where_the_version_goes))]
#[garde(custom(every_pattern_bounds_the_version))]
#[garde(custom(every_pattern_is_listed))]
pub patterns: BTreeMap<String, PinPattern>,
#[serde(default)]
#[garde(dive)]
pub pins: Vec<Pin>,
}
fn every_pattern_says_where_the_version_goes(
patterns: &BTreeMap<String, PinPattern>,
_: &Config,
) -> garde::Result {
for (id, pattern) in patterns {
let found = pattern.r#match.matches(PLACEHOLDER).count();
if found != 1 {
return Err(garde::Error::new(format!(
"{id}: match says {PLACEHOLDER} {found} times, and must say it once"
)));
}
}
Ok(())
}
fn every_pattern_bounds_the_version(
patterns: &BTreeMap<String, PinPattern>,
_: &Config,
) -> garde::Result {
for (id, pattern) in patterns {
let Some((before, after)) = pattern.r#match.split_once(PLACEHOLDER) else {
continue;
};
if after.contains(PLACEHOLDER) {
continue;
}
if let Some(problem) = unbounded(before, after, pattern) {
return Err(garde::Error::new(format!("{id}: {problem}")));
}
}
Ok(())
}
fn unbounded(before: &str, after: &str, pattern: &PinPattern) -> Option<String> {
let sides = [
(
before,
before.chars().rev().collect::<String>(),
"before",
"starts",
),
(after, after.to_owned(), "after", "ends"),
];
for (text, outward, side, edge) in sides {
if text.is_empty() {
if pattern.whole_line {
continue;
}
return Some(format!(
"nothing {side} {PLACEHOLDER} marks where the version {edge}: add the text {side} it to match, or set whole_line: true"
));
}
if text
.chars()
.all(|next| matches!(next, '0'..='9' | '.' | '-' | '+'))
{
return Some(format!(
"{text:?} {side} {PLACEHOLDER} contains only digits, '.', '-', and '+', which a version can continue into: add more of the text {side} it to match"
));
}
let mut nearest = outward.chars();
if matches!(
(nearest.next(), nearest.next()),
(Some('0'..='9'), _) | (Some('.'), Some('0'..='9'))
) {
return Some(format!(
"{text:?} {side} {PLACEHOLDER} puts a digit, or a '.' and a digit, next to the version, so a longer version would match only in part: put a character other than a digit or '.' next to {PLACEHOLDER}"
));
}
}
None
}
fn every_pattern_is_listed(
patterns: &BTreeMap<String, PinPattern>,
config: &Config,
) -> garde::Result {
let listed: BTreeSet<&str> = config
.pins
.iter()
.flat_map(|pin| pin.pattern_ids.iter().map(String::as_str))
.collect();
for id in patterns.keys() {
if !listed.contains(id.as_str()) {
return Err(garde::Error::new(format!(
"{id:?} is declared and no pin lists it"
)));
}
}
Ok(())
}
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Pin {
#[garde(custom(inside_the_repo))]
pub file: PathBuf,
pub tool: Option<String>,
#[serde(default, rename = "patterns")]
#[garde(
custom(each_id_is_declared),
custom(no_id_is_listed_twice),
custom(something_to_rewrite(self.tool.as_deref()))
)]
pub pattern_ids: Vec<String>,
#[serde(skip)]
pub patterns: Vec<PinPattern>,
pub package: String,
}
fn none_is_not_a_publisher(
publishers: &BTreeMap<String, PublisherSpec>,
_: &Config,
) -> garde::Result {
if publishers.contains_key(RELEASE_ONLY) {
return Err(garde::Error::new(
"publishers.none is reserved for release-only packages; rename that publisher",
));
}
Ok(())
}
fn no_unknown_package_keys(packages: &[PackageSpec], _: &Config) -> garde::Result {
for package in packages {
if !package.unknown.is_empty() {
let keys: Vec<&str> = package.unknown.keys().map(String::as_str).collect();
return Err(garde::Error::new(format!(
"package {:?} has {} verctl does not read: {}; check the spelling",
package.name,
if keys.len() == 1 { "a key" } else { "keys" },
keys.join(", ")
)));
}
}
Ok(())
}
fn owners_problem(owners: &[String]) -> Option<String> {
if owners.is_empty() {
return Some(
"must list at least one crates.io login; omit the key to expect no owners".to_owned(),
);
}
let mut seen = BTreeSet::new();
owners
.iter()
.find(|login| !seen.insert(login.as_str()))
.map(|login| format!("lists {login:?} twice; remove one"))
}
fn owners_are_logins(owners: &[String], _: &Config) -> garde::Result {
owners_problem(owners).map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}
fn package_owners_are_logins(packages: &[PackageSpec], _: &Config) -> garde::Result {
for package in packages {
if let Some(problem) = package.owners.as_deref().and_then(owners_problem) {
return Err(garde::Error::new(format!(
"packages[{name}].owners {problem}",
name = package.name
)));
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum ReleaseCheck {
Registry,
Trust,
}
impl ReleaseCheck {
pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Registry => "registry",
Self::Trust => "trust",
}
}
fn default_list() -> Vec<Self> {
Self::ALL.to_vec()
}
}
impl TryFrom<String> for ReleaseCheck {
type Error = String;
fn try_from(name: String) -> Result<Self, Self::Error> {
Self::ALL
.into_iter()
.find(|check| check.name() == name)
.ok_or_else(|| {
format!(
"release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
)
})
}
}
fn each_release_check_once(checks: &[ReleaseCheck], _: &Config) -> garde::Result {
let mut seen = BTreeSet::new();
checks
.iter()
.find(|check| !seen.insert(check.name()))
.map_or_else(
|| Ok(()),
|check| {
Err(garde::Error::new(format!(
"lists {:?} twice; remove one",
check.name()
)))
},
)
}
fn a_workflow_file_name(name: &str, config: &Config) -> garde::Result {
if validate::one_file_name(name, config).is_err() {
return Err(garde::Error::new(
"must be a file name under .github/workflows/, such as release.yml, with no directory",
));
}
if !Path::new(name)
.extension()
.is_some_and(|extension| extension == "yml" || extension == "yaml")
{
return Err(garde::Error::new(
"must name a workflow file, ending in .yml or .yaml",
));
}
Ok(())
}
fn a_prerelease_is_lowercase_letters(packages: &[PackageSpec], _: &Config) -> garde::Result {
for package in packages {
if let Some(tag) = package.prerelease.as_ref().filter(|tag| !tag.is_valid()) {
return Err(garde::Error::new(format!(
"package {:?} has prerelease {:?}, which is not a tag; {}",
package.name,
tag.as_str(),
Prerelease::RULE
)));
}
}
Ok(())
}
fn release_only_names_no_registry(packages: &[PackageSpec], config: &Config) -> garde::Result {
for package in packages {
if publisher::publisher_name(config, package) == RELEASE_ONLY
&& (package.registry.is_some() || package.publish.is_some())
{
return Err(garde::Error::new(format!(
"package {:?} has publisher: none, which uploads to no registry; remove its registry and publish",
package.name
)));
}
}
Ok(())
}
fn publish_options_fit_the_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
for package in packages {
if let Err(problem) = publisher::check_options(config, package) {
return Err(garde::Error::new(problem));
}
}
Ok(())
}
fn a_marker_names_no_driver(packages: &[PackageSpec], _: &Config) -> garde::Result {
for package in packages {
let spec = &package.spec;
if package.marker
&& (package.driver.is_some()
|| spec.format.is_some()
|| spec.keys.is_some()
|| spec.read.is_some()
|| spec.write.is_some())
{
return Err(garde::Error::new(format!(
"package {:?} has marker: true, which reads the version from its marker line; remove its driver, format, keys, read, and write",
package.name
)));
}
}
Ok(())
}
fn python_names_its_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
for package in packages {
if package.path.file_name() == Some(OsStr::new("pyproject.toml"))
&& package.publisher.is_none()
&& package.publish_command().is_none()
&& !config.publishers.contains_key(&package.name)
{
return Err(garde::Error::new(format!(
"package {:?} needs a publisher: verctl has no stock Python publisher; set publisher to a publishers entry, or to none to release on GitHub only",
package.name
)));
}
}
Ok(())
}
fn each_id_is_declared(ids: &[String], config: &Config) -> garde::Result {
for id in ids {
if !config.patterns.contains_key(id) {
return Err(garde::Error::new(format!("no patterns.{id}")));
}
}
Ok(())
}
fn no_id_is_listed_twice(ids: &[String], _: &Config) -> garde::Result {
let mut seen = BTreeSet::new();
for id in ids {
if !seen.insert(id.as_str()) {
return Err(garde::Error::new(format!("lists {id:?} twice")));
}
}
Ok(())
}
fn something_to_rewrite(tool: Option<&str>) -> impl Fn(&[String], &Config) -> garde::Result + '_ {
move |ids, _| {
if tool.is_some() || !ids.is_empty() {
return Ok(());
}
Err(garde::Error::new("needs a tool or a pattern to rewrite"))
}
}
pub const DIR: &str = ".ctl";
pub const FILE: &str = ".ctl/ver.yaml";
#[must_use]
pub fn root_of(config: &Path) -> PathBuf {
let dir = here(config.parent());
if dir.file_name() == Some(OsStr::new(DIR)) {
return here(dir.parent()).to_path_buf();
}
dir.to_path_buf()
}
fn here(path: Option<&Path>) -> &Path {
path.filter(|path| !path.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
}
pub const PLACEHOLDER: &str = "{version}";
pub const NAME_PLACEHOLDER: &str = "{name}";
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Tags {
#[serde(default = "Tags::default_template")]
#[garde(
custom(cannot_be_empty(
"it is the shape of every release tag, like \"v{version}\" or \"{name}@{version}\""
)),
custom(tag_template_placeholders)
)]
pub template: String,
}
impl Tags {
fn default_template() -> String {
format!("v{PLACEHOLDER}")
}
#[must_use]
pub fn uses_name(&self) -> bool {
self.template.contains(NAME_PLACEHOLDER)
}
pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
let mut out = self.template.replace(PLACEHOLDER, version);
if let Some(name) = name {
out = out.replace(NAME_PLACEHOLDER, name);
} else if out.contains(NAME_PLACEHOLDER) {
bail!(
"tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
self.template
);
}
ensure!(
!out.contains('{') && !out.contains('}'),
"tags.template {:?} still has braces after substitution",
self.template
);
Ok(out)
}
}
impl Default for Tags {
fn default() -> Self {
Self {
template: Self::default_template(),
}
}
}
fn tag_template_placeholders(template: &str, _: &Config) -> garde::Result {
let mut saw_version = false;
let mut saw_name = false;
let mut rest = template;
while let Some(start) = rest.find('{') {
let after = &rest[start + 1..];
let Some(end) = after.find('}') else {
return Err(garde::Error::new("has an opening '{' with no closing '}'"));
};
let name = &after[..end];
match name {
"version" => saw_version = true,
"name" => saw_name = true,
_ => {
return Err(garde::Error::new(format!(
"names {{{name}}}, and the only placeholders are {PLACEHOLDER} and {NAME_PLACEHOLDER}"
)));
}
}
rest = &after[end + 1..];
}
if !saw_version && !saw_name {
return Err(garde::Error::new(format!(
"has no placeholder — put {PLACEHOLDER} where the version goes"
)));
}
if !saw_version {
return Err(garde::Error::new(format!(
"must say {PLACEHOLDER} — a tag with only {NAME_PLACEHOLDER} cannot date a release"
)));
}
let leftover = template
.replace(PLACEHOLDER, "")
.replace(NAME_PLACEHOLDER, "");
if leftover.contains('{') || leftover.contains('}') {
return Err(garde::Error::new(format!(
"has a '{{' or '}}' that is not {PLACEHOLDER} or {NAME_PLACEHOLDER}"
)));
}
let _ = saw_name;
Ok(())
}
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Templates {
#[serde(default = "Templates::default_source")]
#[garde(custom(inside_the_repo))]
pub source: PathBuf,
#[serde(default = "Templates::default_suffix")]
#[garde(custom(cannot_be_empty(
"it is what marks a file in the source tree as a template, like \".jinja\""
)))]
pub suffix: String,
}
impl Templates {
fn default_source() -> PathBuf {
Path::new(DIR).join("templates")
}
fn default_suffix() -> String {
".jinja".to_owned()
}
}
impl Default for Templates {
fn default() -> Self {
Self {
source: Self::default_source(),
suffix: Self::default_suffix(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PinPattern {
pub r#match: String,
#[serde(default)]
pub occurrences: Occurrences,
#[serde(default)]
pub whole_line: bool,
}
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub enum Occurrences {
#[default]
Once,
Many,
Never,
Exactly(usize),
AtLeast(usize),
}
const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";
impl<'de> Deserialize<'de> for Occurrences {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(OccurrencesVisitor)
}
}
struct OccurrencesVisitor;
impl<'de> Visitor<'de> for OccurrencesVisitor {
type Value = Occurrences;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{ARITY}")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
match v {
"once" => Ok(Occurrences::Once),
"many" => Ok(Occurrences::Many),
"never" => Ok(Occurrences::Never),
_ => Err(E::custom(format!("must be {ARITY}"))),
}
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
use serde::de::Error;
let wrong = || A::Error::custom(format!("must be {ARITY}"));
let key: String = map.next_key()?.ok_or_else(wrong)?;
#[expect(
clippy::map_err_ignore,
reason = "the report names the accepted shapes; the number parse error adds nothing"
)]
let count: usize = map.next_value().map_err(|_| wrong())?;
if map.next_key::<IgnoredAny>()?.is_some() {
return Err(wrong());
}
match key.as_str() {
"exactly" => Ok(Occurrences::Exactly(count)),
"at_least" => Ok(Occurrences::AtLeast(count)),
_ => Err(wrong()),
}
}
}
impl Occurrences {
#[must_use]
pub const fn allows(self, found: usize) -> bool {
match self {
Self::Once => found == 1,
Self::Many => found >= 1,
Self::Never => found == 0,
Self::Exactly(count) => found == count,
Self::AtLeast(count) => found >= count,
}
}
}
impl fmt::Display for Occurrences {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Once => f.write_str("exactly once"),
Self::Many => f.write_str("one or more"),
Self::Never => f.write_str("never"),
Self::Exactly(count) => write!(f, "exactly {count} times"),
Self::AtLeast(count) => write!(f, "{count} or more times"),
}
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Changelog {
#[serde(default)]
pub internal_authors: Vec<String>,
}
impl Changelog {
#[must_use]
pub fn is_internal(&self, login: &str) -> bool {
self.internal_authors
.iter()
.any(|listed| listed.eq_ignore_ascii_case(login))
}
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Prepare {
pub after: Option<Vec<String>>,
#[serde(default)]
pub stage: Vec<String>,
#[serde(default)]
pub stage_ignored: bool,
#[serde(default, deserialize_with = "key_present")]
version_label: bool,
}
fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
IgnoredAny::deserialize(deserializer).map(|_| true)
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Proposal {
#[serde(default)]
pub title: Option<String>,
#[serde(default)]
pub commit_message: Option<String>,
}
impl Proposal {
pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";
#[must_use]
pub fn title(&self) -> &str {
self.title
.as_deref()
.filter(|title| !title.is_empty())
.unwrap_or(Self::DEFAULT_TITLE)
}
#[must_use]
pub fn commit_message(&self) -> &str {
self.commit_message
.as_deref()
.filter(|message| !message.is_empty())
.unwrap_or_else(|| self.title())
}
}
fn no_version_label(prepare: &Prepare, _: &Config) -> garde::Result {
if prepare.version_label {
return Err(garde::Error::new(
"prepare.version_label is removed: the Version PR is no longer labeled; delete this key",
));
}
Ok(())
}
impl Config {
pub fn load(path: &Path) -> Result<Self> {
let config = Self::from_input(Input::read(path)?)?;
config.packslip_manifest_is_sound(&root_of(path))?;
Ok(config)
}
fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
let Some(manifest) = self
.packslip
.as_ref()
.and_then(|packslip| packslip.manifest.as_ref())
else {
return Ok(());
};
read_packslip_manifest(&root.join(manifest), manifest).map(drop)
}
pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
let Some(manifest) = self
.packslip
.as_ref()
.and_then(|packslip| packslip.manifest.as_ref())
else {
return Ok(());
};
let plain = |path: &Path| {
path.components()
.filter(|part| !matches!(part, Component::CurDir))
.collect::<PathBuf>()
};
let wanted = plain(manifest);
let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
ensure!(
is_tracked,
"packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
manifest.display()
);
Ok(())
}
pub fn parse(raw: &str) -> Result<Self> {
Self::from_input(Input::new(".ctl/ver.yaml", raw))
}
fn from_input(input: Input) -> Result<Self> {
let input = input.flattened(FieldPath::root().key("assets").key("targets"));
let mut config: Self = input.parse()?;
input.check(&config, &config)?;
config.resolve_patterns();
Ok(config)
}
fn resolve_patterns(&mut self) {
let declared = self.patterns.clone();
for pin in &mut self.pins {
pin.patterns = pin
.pattern_ids
.iter()
.filter_map(|id| declared.get(id).cloned())
.collect();
}
}
fn default_release_workflow() -> String {
"release.yml".to_owned()
}
#[must_use]
pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
package.owners.as_deref().or(self.owners.as_deref())
}
pub fn find(&self, name: &str) -> Result<&PackageSpec> {
self.packages
.iter()
.find(|package| package.name == name)
.with_context(|| format!("package {name:?} is not in verctl config"))
}
#[must_use]
pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
match (DriverSpec::stock(name), self.drivers.get(name)) {
(Some(stock), Some(over)) => Some(stock.merge(over.clone())),
(Some(stock), None) => Some(stock),
(None, Some(over)) => Some(over.clone()),
(None, None) => None,
}
}
}
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,
}
}
pub fn stock_driver(name: &str) -> Result<Driver> {
DriverSpec::stock(name)
.with_context(|| format!("unknown stock driver {name:?}"))?
.into_driver(name)
}
#[cfg(test)]
mod tests {
use indoc::{formatdoc, indoc};
use super::*;
fn load(body: &str) -> Result<Config> {
Config::parse(body)
}
const PACKAGE: &str = indoc! {"
packages:
- name: demo
path: Cargo.toml
"};
#[test]
fn a_release_only_package_names_no_registry() {
let config = load(indoc! {"
packages:
- name: demo
path: Cargo.toml
publisher: none
"})
.unwrap();
assert_eq!(config.packages[0].publisher.as_deref(), Some("none"));
let error = load(&formatdoc! {r#"
{PACKAGE}
publishers:
none:
argv: ["true"]
"#})
.expect_err("publishers.none is reserved");
assert!(
format!("{error:#}").contains("publishers.none is reserved"),
"{error:#}"
);
for extra in ["registry: crates-io", "publish: [cargo, publish]"] {
let error = load(&formatdoc! {"
packages:
- name: demo
path: Cargo.toml
publisher: none
{extra}
"})
.expect_err(extra);
assert!(
format!("{error:#}").contains("has publisher: none"),
"{extra}: {error:#}"
);
}
}
#[test]
fn packslip_is_a_mapping_and_the_path_form_shows_it() {
let with = |packslip: &str| {
load(&formatdoc! {"
{PACKAGE}
assets:
linux-x64: {{}}
packslip: {packslip}
"})
};
let both = with("{ manifest: .ctl/packslip.toml, attest: link }").unwrap();
let both = both.packslip.expect("packslip");
assert_eq!(
both.manifest.as_deref(),
Some(Path::new(".ctl/packslip.toml"))
);
assert_eq!(both.attest, Attest::Link);
let off = with("{ attest: false }")
.unwrap()
.packslip
.expect("packslip");
assert_eq!((off.manifest, off.attest), (None, Attest::False));
let empty = with("{}").unwrap().packslip.expect("packslip");
assert_eq!(
(empty.manifest, empty.attest, empty.pubkey),
(None, Attest::True, None)
);
let keyed = with("{ pubkey: RWQexample }")
.unwrap()
.packslip
.expect("packslip");
assert_eq!(keyed.pubkey.as_deref(), Some("RWQexample"));
let report = format!("{:#}", with(".ctl/packslip.toml").expect_err("path form"));
assert!(
report.contains("packslip: { manifest: .ctl/packslip.toml }"),
"{report}"
);
}
#[test]
fn a_blank_pubkey_fails_the_load() {
for blank in ["''", "' '"] {
let error = load(&formatdoc! {"
{PACKAGE}
assets:
linux-x64: {{}}
packslip: {{ pubkey: {blank} }}
"})
.expect_err(blank);
let report = format!("{error:#}");
assert!(report.contains("packslip.pubkey"), "{blank}: {report}");
assert!(report.contains("cannot be empty"), "{blank}: {report}");
}
}
#[test]
fn an_unknown_attest_mode_names_the_three_values() {
let error = load(&formatdoc! {"
{PACKAGE}
assets:
linux-x64: {{}}
packslip: {{ attest: maybe }}
"})
.expect_err("maybe is no mode");
let report = format!("{error:#}");
assert!(report.contains("packslip.attest"), "{report}");
assert!(report.contains("true, link, or false"), "{report}");
}
#[test]
fn a_target_packslip_table_is_kept_unread() {
let config = load(&formatdoc! {r#"
{PACKAGE}
assets:
darwin-arm64:
packslip:
requires: {{ os_min: "11.0" }}
"#})
.unwrap();
let table = config.assets.expect("assets").targets["darwin-arm64"]
.packslip
.clone();
assert_eq!(table.to_string(), "requires = { os_min = \"11.0\" }\n");
}
#[test]
fn a_target_without_a_packslip_table_has_an_empty_one() {
let config = load(&formatdoc! {"
{PACKAGE}
assets:
linux-x64: {{}}
"})
.unwrap();
let table = &config.assets.expect("assets").targets["linux-x64"].packslip;
assert_eq!(table.entries().count(), 0);
}
#[test]
fn a_target_packslip_table_refuses_a_path_and_a_null() {
for (key, said) in [
("path: elsewhere.tar.gz", "packslip.path"),
("requires: ~", "null has no TOML form"),
] {
let error = load(&formatdoc! {"
{PACKAGE}
assets:
darwin-arm64:
packslip:
{key}
"})
.expect_err(key);
let report = format!("{error:#}");
assert!(report.contains(said), "{key}: {report}");
}
}
#[test]
fn a_prerelease_is_lowercase_letters() {
for tag in ["rc", "alpha", "beta", "next", "canary"] {
let config = load(&formatdoc! {"
packages:
- name: demo
path: Cargo.toml
prerelease: {tag}
"})
.expect(tag);
let spec = config.find("demo").expect("demo");
assert_eq!(spec.prerelease.as_ref().map(Prerelease::as_str), Some(tag));
}
for tag in ["rc1", "RC", "rc.1", "1", "x", "latest", "\"\""] {
let error = load(&formatdoc! {"
packages:
- name: demo
path: Cargo.toml
prerelease: {tag}
"})
.expect_err(tag);
let message = format!("{error:#}");
assert!(
message.contains("package \"demo\" has prerelease")
&& message.contains("lowercase ASCII letters"),
"{tag}: {message}"
);
}
}
#[test]
fn a_marker_names_no_driver() {
for extra in [
"driver: cargo",
"format: toml",
"keys: [project.version]",
"read: [cat]",
"write: [cat]",
] {
let error = load(&formatdoc! {"
packages:
- name: ci
path: ci.yml
marker: true
{extra}
"})
.expect_err(extra);
assert!(
format!("{error:#}").contains("has marker: true"),
"{extra}: {error:#}"
);
}
load(indoc! {"
packages:
- name: ci
path: ci.yml
marker: true
after: mise run render
"})
.expect("after runs beside a marker");
}
#[test]
fn a_python_package_names_its_publisher() {
let error = load(indoc! {"
packages:
- name: demo
path: pyproject.toml
"})
.expect_err("no publisher");
assert!(
format!("{error:#}").contains("needs a publisher"),
"{error:#}"
);
for named in [
"publisher: none",
"publish: [uv, publish]",
"publisher: pypi",
] {
load(&formatdoc! {"
packages:
- name: demo
path: pyproject.toml
{named}
publishers:
pypi:
argv: [uv, publish]
"})
.unwrap_or_else(|error| panic!("{named}: {error:#}"));
}
load(indoc! {"
packages:
- name: demo
path: pyproject.toml
publishers:
demo:
argv: [uv, publish]
"})
.expect("a publishers entry under the package name");
}
#[test]
fn the_root_is_the_directory_holding_the_ctl_dir() {
let cases = [
(".ctl/ver.yaml", "."),
("crates/foo/.ctl/ver.yaml", "crates/foo"),
("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
("ver.yaml", "."),
("/tmp/scratch/ver.yaml", "/tmp/scratch"),
];
for (config, expected) in cases {
assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
}
}
#[test]
fn every_occurrence_form_parses_and_means_what_it_says() {
let config = load(&formatdoc! {r#"
{PACKAGE}
patterns:
omitted:
match: "a@{{version}} --"
once:
match: "b@{{version}} --"
occurrences: once
many:
match: "c@{{version}} --"
occurrences: many
never:
match: "d@{{version}} --"
occurrences: never
twice:
match: "e@{{version}} --"
occurrences: {{exactly: 2}}
floor:
match: "f@{{version}} --"
occurrences: {{at_least: 2}}
pins:
- file: README.md
package: demo
patterns: [omitted, once, many, never, twice, floor]
"#})
.unwrap();
let allowed: Vec<Vec<usize>> = config.pins[0]
.patterns
.iter()
.map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
.collect();
assert_eq!(
allowed,
[
vec![1], vec![1], vec![1, 2, 3], vec![0], vec![2], vec![2, 3], ]
);
}
#[test]
fn a_misspelled_section_stops_the_load() {
let error = load(&formatdoc! {r#"
{PACKAGE}
pattern:
install:
match: "demo@{{version}} --"
"#})
.expect_err("pattern is not a section");
assert!(format!("{error:#}").contains("pattern"), "{error:#}");
}
#[test]
fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
let error = load(&formatdoc! {r#"
{PACKAGE}
patterns:
wrong:
match: "a@{{version}} --"
occurrences: {{exactly: 2, at_leats: 3}}
pins:
- file: README.md
package: demo
patterns: [wrong]
"#})
.expect_err("at_leats is not a key");
assert!(format!("{error:#}").contains(ARITY), "{error:#}");
}
#[test]
fn a_bound_with_a_bad_count_names_the_arity() {
for count in ["-1", "many"] {
let error = load(&formatdoc! {r#"
{PACKAGE}
patterns:
wrong:
match: "a@{{version}} --"
occurrences: {{exactly: {count}}}
pins:
- file: README.md
package: demo
patterns: [wrong]
"#})
.expect_err("the count is not a whole number");
assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
}
}
#[test]
fn an_unknown_arity_is_not_silently_a_default() {
let broken = load(&formatdoc! {r#"
{PACKAGE}
patterns:
wrong:
match: "a@{{version}} --"
occurrences: sometimes
pins:
- file: README.md
package: demo
patterns: [wrong]
"#});
let _ = broken.expect_err("unknown occurrences");
}
#[test]
fn one_named_pattern_serves_every_file_that_lists_it() {
let config = load(&formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@{{version}} --"
mention:
match: "v{{version}} --"
occurrences: many
pins:
- file: README.md
package: demo
patterns: [install, mention]
- file: docs/install.md
package: demo
patterns: [install]
"#})
.unwrap();
let carried: Vec<Vec<&str>> = config
.pins
.iter()
.map(|pin| {
pin.patterns
.iter()
.map(|pattern| pattern.r#match.as_str())
.collect()
})
.collect();
assert_eq!(
carried,
[
vec!["demo@{version} --", "v{version} --"],
vec!["demo@{version} --"]
],
"each file carries the patterns it lists, in the order it lists them"
);
}
#[test]
fn a_pattern_marks_where_the_version_starts_and_ends() {
let only = "contains only digits, '.', '-', and '+'";
let cases = [
("name-{version}.tar.gz", false, None),
("download/v{version}-linux", false, None),
("v{version}.tar", false, None),
("demo@{version} --", false, None),
("`demo@{version}`", false, None),
("verctl-{version}", true, None),
("version: {version}", true, None),
("{version}", true, None),
(
"{version}",
false,
Some("nothing before {version}".to_owned()),
),
(
"verctl-{version}",
false,
Some("nothing after {version}".to_owned()),
),
(
"version: {version}",
false,
Some("skill: nothing after {version}".to_owned()),
),
(
"verctl@{version}.",
false,
Some(format!("\".\" after {{version}} {only}")),
),
(
"v{version}-",
false,
Some(format!("\"-\" after {{version}} {only}")),
),
(
"v{version}+",
false,
Some(format!("\"+\" after {{version}} {only}")),
),
(
"-{version}",
false,
Some(format!("\"-\" before {{version}} {only}")),
),
(
"{version}.1",
false,
Some("nothing before {version}".to_owned()),
),
(
"{version}.1",
true,
Some(format!("\".1\" after {{version}} {only}")),
),
(
"version: {version}-",
true,
Some(format!("\"-\" after {{version}} {only}")),
),
];
assert_bounds(cases);
}
#[test]
fn a_digit_next_to_the_version_leaves_the_side_open() {
let near = "puts a digit, or a '.' and a digit, next to the version";
assert_bounds([
("v{version}.tar", false, None),
("v{version}-1x", false, None),
(
"v{version}.5x",
false,
Some(format!("\".5x\" after {{version}} {near}")),
),
(
"v{version}1x",
false,
Some(format!("\"1x\" after {{version}} {near}")),
),
(
"x1.{version}-linux",
false,
Some(format!("\"x1.\" before {{version}} {near}")),
),
(
"x1{version}-linux",
false,
Some(format!("\"x1\" before {{version}} {near}")),
),
(
"{version}.1x",
true,
Some(format!("\".1x\" after {{version}} {near}")),
),
]);
}
fn assert_bounds<const N: usize>(cases: [(&str, bool, Option<String>); N]) {
for (text, whole_line, refusal) in cases {
let loaded = load(&formatdoc! {"
{PACKAGE}
patterns:
skill:
match: '{text}'
whole_line: {whole_line}
pins:
- file: README.md
package: demo
patterns: [skill]
"});
match (loaded, refusal) {
(Ok(_), None) => {}
(Err(error), Some(needle)) => {
let report = format!("{error:#}");
assert!(report.contains(needle.as_str()), "{text}: {report}");
}
(outcome, _) => panic!("{text} (whole_line: {whole_line}): {outcome:?}"),
}
}
}
#[test]
#[expect(
clippy::too_many_lines,
reason = "one case per rule; a table, not logic"
)]
fn a_config_that_breaks_a_rule_stops_the_load() {
let cases = [
(
"an id no patterns section declares",
formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@{{version}} --"
pins:
- file: README.md
package: demo
patterns: [install, instal]
"#},
"pins[0].pattern_ids: no patterns.instal",
),
(
"the same id listed twice",
formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@{{version}} --"
pins:
- file: README.md
package: demo
patterns: [install, install]
"#},
r#"pins[0].pattern_ids: lists "install" twice"#,
),
(
"a pattern no pin lists",
formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@{{version}} --"
orphan:
match: "old@{{version}} --"
pins:
- file: README.md
package: demo
patterns: [install]
"#},
r#"patterns: "orphan" is declared and no pin lists it"#,
),
(
"a pin with nothing to rewrite",
formatdoc! {"
{PACKAGE}
pins:
- file: README.md
package: demo
"},
"pins[0].pattern_ids: needs a tool or a pattern to rewrite",
),
(
"a spelling with nowhere to put the version",
formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@1.2.3"
pins:
- file: README.md
package: demo
patterns: [install]
"#},
"patterns: install: match says {version} 0 times",
),
(
"a pin reaching out of the repository",
formatdoc! {r#"
{PACKAGE}
patterns:
install:
match: "demo@{{version}} --"
pins:
- file: ../elsewhere/README.md
package: demo
patterns: [install]
"#},
"pins[0].file: must stay inside the repository",
),
(
"a machine no label can find",
formatdoc! {"
{PACKAGE}
runners:
ghost:
labels: []
"},
"runners.ghost.labels: must declare at least one label",
),
(
"a suffix that makes every file a template",
formatdoc! {r#"
{PACKAGE}
templates:
suffix: ""
"#},
"templates.suffix: cannot be empty — it is what marks a file",
),
(
"a tag template naming a placeholder that does not exist",
formatdoc! {r#"
{PACKAGE}
tags:
template: "v{{ver}}"
"#},
"tags.template: names {ver}, and the only placeholders are {version} and {name}",
),
(
"a tag template with no placeholder",
formatdoc! {r#"
{PACKAGE}
tags:
template: "latest"
"#},
"tags.template: has no placeholder",
),
(
"a tag template with only the package name",
formatdoc! {r#"
{PACKAGE}
tags:
template: "{{name}}"
"#},
"tags.template: must say {version}",
),
(
"an empty tag template",
formatdoc! {r#"
{PACKAGE}
tags:
template: ""
"#},
"tags.template: cannot be empty",
),
(
"a tag template with a leftover brace",
formatdoc! {r#"
{PACKAGE}
tags:
template: "v{{version}}}}"
"#},
"tags.template: has a '{' or '}' that is not {version} or {name}",
),
];
for (scenario, body, expected) in cases {
let error = load(&body).expect_err(scenario);
assert!(
format!("{error:#}").contains(expected),
"{scenario}: {error:#}"
);
}
}
fn vendored(extra: &str) -> String {
formatdoc! {"
runners:
linux:
labels: [ubuntu-26.04]
vendored:
lib:
version: 1.4.0
dir: out
files: [lib]
targets:
linux-x64:
runner: linux
{extra}
"}
}
#[test]
fn a_vendored_set_alone_is_a_config_and_takes_the_default_names() {
let config = load(&vendored("")).unwrap();
assert!(config.packages.is_empty());
let set = &config.vendored["lib"];
assert_eq!(set.tag, "{name}-{version}");
assert_eq!(set.archive, "{name}-{version}-{id}.tar.gz");
assert_eq!(set.build, Vec::<String>::new());
assert_eq!(set.notes, None);
}
#[test]
fn a_config_with_no_package_and_no_vendored_set_fails() {
let error = load("runners: {}\n").unwrap_err();
assert!(
format!("{error:#}").contains("must declare at least one package, or a vendored set"),
"{error:#}"
);
}
#[test]
fn a_vendored_set_without_targets_fails() {
let error = load(indoc! {"
vendored:
lib:
version: 1.4.0
dir: out
files: [lib]
targets: {}
"})
.unwrap_err();
assert!(
format!("{error:#}").contains("must declare at least one target"),
"{error:#}"
);
}
#[test]
fn a_vendored_set_rejects_what_it_cannot_publish() {
let base = vendored("");
let cases = [
(
"archive without the target",
vendored("archive: lib.tar.gz"),
"must contain {id}",
),
(
"archive in another format",
vendored("archive: \"{id}.zip\""),
"must end in .tar.gz",
),
(
"archive in a directory",
vendored("archive: \"dist/{id}.tar.gz\""),
"must be one file name",
),
(
"archive with a typo",
vendored("archive: \"{ids}.tar.gz\""),
"that is not {name}, {version}, {id}",
),
(
"tag that varies by target",
vendored("tag: \"lib-{id}\""),
"that is not {name}, {version}",
),
("empty tag", vendored("tag: \"\""), "cannot be empty"),
(
"notes outside the repo",
vendored("notes: ../notes.md"),
"must stay inside the repository",
),
("unknown key", vendored("bin: lib"), "bin"),
(
"empty version",
base.replace("version: 1.4.0", "version: \"\""),
"cannot be empty",
),
(
"dir outside the repo",
base.replace("dir: out", "dir: /tmp"),
"must stay inside the repository",
),
(
"no files",
base.replace("files: [lib]", "files: []"),
"must declare at least one file",
),
(
"a file outside the repo",
base.replace("files: [lib]", "files: [../secret]"),
"must stay inside the repository",
),
(
"version with a path separator",
base.replace("version: 1.4.0", "version: 1.4/../../x"),
"must be one plain name",
),
(
"target key with a parent step",
base.replace("linux-x64:", "\"..\":"),
"must be one plain name",
),
(
"target key with a path separator",
base.replace("linux-x64:", "a/b:"),
"must be one plain name",
),
(
"set name with a path separator",
base.replace(" lib:", " \"../lib\":"),
"must be one plain name",
),
(
"undeclared machine",
base.replace("runner: linux", "runner: big"),
"\"big\" is not declared in runners (declared: linux)",
),
];
for (scenario, body, expected) in cases {
let error = load(&body).expect_err(scenario);
assert!(
format!("{error:#}").contains(expected),
"{scenario}: {error:#}"
);
}
}
fn assets(section: &str) -> String {
format!("{PACKAGE}{section}")
}
#[test]
fn asset_files_are_packed_from_their_dir() {
let config = load(&assets(indoc! {"
assets:
dir: target/{triple}/release
files: [demo, demod, LICENSE]
linux-x64: {}
"}))
.unwrap();
let recipe = config.assets.unwrap();
assert_eq!(recipe.dir, Some(PathBuf::from("target/{triple}/release")));
assert_eq!(
recipe.files,
[
PathBuf::from("demo"),
PathBuf::from("demod"),
PathBuf::from("LICENSE")
]
);
assert_eq!(recipe.targets.keys().collect::<Vec<_>>(), ["linux-x64"]);
}
#[test]
fn a_target_lists_its_own_files() {
let config = load(&assets(indoc! {"
assets:
dir: out/{triple}
darwin-arm64:
files: [proof]
linux-x64:
files: [bench, proof]
"}))
.unwrap();
let recipe = config.assets.unwrap();
assert_eq!(recipe.files, Vec::<PathBuf>::new());
assert_eq!(
recipe.targets["darwin-arm64"].files,
Some(vec![PathBuf::from("proof")])
);
assert_eq!(
recipe.targets["linux-x64"].files,
Some(vec![PathBuf::from("bench"), PathBuf::from("proof")])
);
}
#[test]
fn asset_files_reject_what_they_cannot_pack() {
let cases = [
(
"dir without files",
indoc! {"
assets:
dir: out
linux-x64: {}
"},
"must come with files",
),
(
"dir with no files",
indoc! {"
assets:
dir: out
files: []
linux-x64: {}
"},
"must come with files",
),
(
"files without dir",
indoc! {"
assets:
files: [demo]
linux-x64: {}
"},
"must come with dir",
),
(
"binary beside files",
indoc! {"
assets:
binary: out/{bin}
dir: out
files: [demo]
linux-x64: {}
"},
"list the binary in files",
),
(
"dir outside the repo",
indoc! {"
assets:
dir: /tmp
files: [demo]
linux-x64: {}
"},
"must stay inside the repository",
),
(
"a file outside the repo",
indoc! {"
assets:
dir: out
files: [../secret]
linux-x64: {}
"},
"must stay inside the repository",
),
];
for (scenario, section, expected) in cases {
let error = load(&assets(section)).expect_err(scenario);
assert!(
format!("{error:#}").contains(expected),
"{scenario}: {error:#}"
);
}
}
#[test]
fn asset_target_files_reject_what_they_cannot_pack() {
let cases = [
(
"target files without dir",
indoc! {"
assets:
linux-x64:
files: [demo]
"},
"assets.linux-x64.files: must come with assets.dir",
),
(
"an empty target list",
indoc! {"
assets:
dir: out
files: [demo]
linux-x64:
files: []
"},
"assets.linux-x64.files: must declare at least one file",
),
(
"binary beside target files",
indoc! {"
assets:
binary: out/{bin}
darwin-arm64: {}
linux-x64:
files: [demo]
"},
"assets.binary: must be omitted when assets.linux-x64.files lists what the tarball contains",
),
(
"a target file outside the repo",
indoc! {"
assets:
dir: out
linux-x64:
files: [../secret]
"},
"assets.linux-x64.files[0]: must stay inside the repository",
),
(
"dir with a target that lists no files",
indoc! {"
assets:
dir: out
darwin-arm64: {}
linux-x64:
files: [demo]
"},
"must come with files",
),
];
for (scenario, section, expected) in cases {
let error = load(&assets(section)).expect_err(scenario);
assert!(
format!("{error:#}").contains(expected),
"{scenario}: {error:#}"
);
}
}
#[test]
fn an_asset_target_problem_sits_on_its_own_line() {
let error = load(&assets(indoc! {"
assets:
linux-x64:
files: [demo]
"}))
.expect_err("target files without dir");
assert!(
format!("{error:#}")
.contains(".ctl/ver.yaml:6:12: assets.linux-x64.files: must come with assets.dir"),
"{error:#}"
);
}
const ONE_PACKAGE: &str = indoc! {"
packages:
- name: demo
path: Cargo.toml
"};
#[test]
fn a_proposal_left_out_is_todays_title_and_message() {
let config = load(ONE_PACKAGE).unwrap();
assert_eq!(config.proposal.title(), "chore(release): version packages");
assert_eq!(
config.proposal.commit_message(),
"chore(release): version packages"
);
}
#[test]
fn a_title_alone_is_also_the_commit_message() {
let config = load(&formatdoc! {"
{ONE_PACKAGE}proposal:
title: 'chore: release'
"})
.unwrap();
assert_eq!(config.proposal.title(), "chore: release");
assert_eq!(config.proposal.commit_message(), "chore: release");
}
#[test]
fn an_empty_title_and_message_are_unset() {
let config = load(&formatdoc! {"
{ONE_PACKAGE}proposal:
title: ''
commit_message: ''
"})
.unwrap();
assert_eq!(config.proposal.title(), "chore(release): version packages");
assert_eq!(
config.proposal.commit_message(),
"chore(release): version packages"
);
}
#[test]
fn a_commit_message_differs_from_the_title() {
let config = load(&formatdoc! {"
{ONE_PACKAGE}proposal:
title: 'chore: release'
commit_message: 'chore: release [skip ci]'
"})
.unwrap();
assert_eq!(config.proposal.title(), "chore: release");
assert_eq!(config.proposal.commit_message(), "chore: release [skip ci]");
}
#[test]
fn a_version_label_is_refused_with_what_to_do() {
for value in [" release", "", " ~", " null"] {
let error = load(&formatdoc! {"
{ONE_PACKAGE}prepare:
version_label:{value}
"})
.unwrap_err();
let error = format!("{error:#}");
assert!(
error.contains("prepare.version_label is removed"),
"{value:?}: {error}"
);
assert!(error.contains("no longer labeled"), "{value:?}: {error}");
assert!(error.contains("delete this key"), "{value:?}: {error}");
}
}
#[test]
fn an_unknown_key_under_a_package_fails() {
for (line, key) in [
("publsher: none", "publsher"),
("foramt: toml", "foramt"),
("keys: [package.version]\n kes: [x]", "kes"),
] {
let error = load(&formatdoc! {"
packages:
- name: demo
path: Cargo.toml
{line}
"})
.unwrap_err();
let error = format!("{error:#}");
assert!(error.contains(key), "{line}: {error}");
assert!(error.contains("\"demo\""), "{line}: {error}");
}
load(indoc! {"
packages:
- name: demo
path: Cargo.toml
format: toml
keys: [package.version]
publisher: none
"})
.unwrap();
}
#[test]
fn an_unknown_key_under_a_pin_fails() {
let error = load(&formatdoc! {"
{ONE_PACKAGE}pins:
- file: README.md
package: demo
tool: github:acme/demo
pattern: [readme]
"})
.unwrap_err();
assert!(format!("{error:#}").contains("pattern"), "{error:#}");
}
#[test]
fn an_unknown_key_under_a_pattern_fails() {
let error = load(&formatdoc! {"
{ONE_PACKAGE}patterns:
readme:
match: 'demo@{{version}} in CI'
ocurrences: many
pins:
- file: README.md
package: demo
patterns: [readme]
"})
.unwrap_err();
assert!(format!("{error:#}").contains("ocurrences"), "{error:#}");
}
#[test]
fn an_unknown_key_under_prepare_fails() {
let error = load(&formatdoc! {"
{ONE_PACKAGE}prepare:
stages: [docs]
"})
.unwrap_err();
assert!(format!("{error:#}").contains("stages"), "{error:#}");
}
#[test]
fn an_unknown_key_under_proposal_fails() {
let error = load(&formatdoc! {"
{ONE_PACKAGE}proposal:
label: release
"})
.unwrap_err();
assert!(format!("{error:#}").contains("label"), "{error:#}");
}
#[test]
fn publish_reads_options_or_a_whole_command() {
let config = load(indoc! {"
packages:
- name: demo
path: Cargo.toml
publish:
verify: false
- name: tool
path: tool/pyproject.toml
publish: [uv, publish]
- name: quiet
path: quiet/Cargo.toml
publish: []
"})
.unwrap();
let options = config.packages[0].publish_options().unwrap();
assert_eq!(options.get("verify"), Some(&serde_json::Value::Bool(false)));
assert_eq!(config.packages[0].publish_command(), None);
assert_eq!(
config.packages[1].publish_command(),
Some(["uv".to_owned(), "publish".to_owned()].as_slice())
);
assert_eq!(config.packages[2].publish_command(), Some([].as_slice()));
}
#[test]
fn publish_of_another_shape_names_both() {
let error = load(indoc! {"
packages:
- name: demo
path: Cargo.toml
publish: fast
"})
.unwrap_err();
assert!(
format!("{error:#}").contains(
"a mapping of publisher options, or a list that is the whole upload command"
),
"{error:#}"
);
}
#[test]
fn options_are_checked_against_the_publisher_at_load() {
for (yaml, message) in [
(
indoc! {"
packages:
- name: web
path: package.json
publish:
verify: false
"},
r#"package "web" publishes with bun, which has no publish options; remove publish.verify"#,
),
(
indoc! {"
packages:
- name: demo
path: Cargo.toml
publish:
allow_dirty: true
"},
r#"package "demo": cargo has no publish option "allow_dirty"; its options are: verify"#,
),
(
indoc! {"
packages:
- name: demo
path: Cargo.toml
publish:
verify: no thanks
"},
r#"package "demo": publish.verify is true or false"#,
),
(
indoc! {"
publishers:
cargo:
argv: [cargo, publish, --workspace]
packages:
- name: demo
path: Cargo.toml
publish:
verify: false
"},
r#"package "demo": publishers.cargo replaces the upload command, which takes no options; remove publish, or the argv"#,
),
] {
let error = load(yaml).unwrap_err();
assert!(format!("{error:#}").contains(message), "{error:#}");
}
}
fn with_owners(top: &str, app: &str) -> Result<Config> {
load(&formatdoc! {"
{top}
packages:
- name: core
path: core/Cargo.toml
- name: app
path: app/Cargo.toml
{app}
"})
}
#[test]
fn owners_default_to_the_top_level_list() {
let config = with_owners("owners: [any-victor]", "").unwrap();
for name in ["core", "app"] {
let package = config.find(name).unwrap();
assert_eq!(
config.owners_of(package),
Some(["any-victor".to_owned()].as_slice()),
"{name}"
);
}
let config = with_owners("owners: [any-victor]", "owners: [any-victor, alice]").unwrap();
assert_eq!(
config.owners_of(config.find("app").unwrap()),
Some(["any-victor".to_owned(), "alice".to_owned()].as_slice())
);
assert_eq!(
config.owners_of(config.find("core").unwrap()),
Some(["any-victor".to_owned()].as_slice())
);
let config = with_owners("", "").unwrap();
assert_eq!(config.owners_of(config.find("app").unwrap()), None);
}
#[test]
fn an_empty_or_repeated_owners_list_fails_naming_the_field() {
for (top, app, expected) in [
(
"owners: []",
"",
"owners: must list at least one crates.io login",
),
(
"owners: [any-victor, any-victor]",
"",
r#"owners: lists "any-victor" twice"#,
),
(
"",
"owners: []",
"packages[app].owners must list at least one crates.io login",
),
(
"owners: [any-victor]",
"owners: [alice, alice]",
r#"packages[app].owners lists "alice" twice"#,
),
] {
let error = format!("{:#}", with_owners(top, app).unwrap_err());
assert!(error.contains(expected), "{top} {app}: {error}");
}
}
#[test]
fn release_workflow_is_a_workflow_file_name() {
assert_eq!(load(PACKAGE).unwrap().release_workflow, "release.yml");
for name in ["self-release.yml", "publish.yaml"] {
let config = load(&formatdoc! {"
{PACKAGE}release_workflow: {name}
"})
.unwrap();
assert_eq!(config.release_workflow, name);
}
for (name, problem) in [
(
".github/workflows/release.yml",
"be a file name under .github/workflows/",
),
(
"release.toml",
"name a workflow file, ending in .yml or .yaml",
),
("\"\"", "be a file name under .github/workflows/"),
] {
let error = load(&formatdoc! {"
{PACKAGE}release_workflow: {name}
"})
.unwrap_err();
let error = format!("{error:#}");
assert!(
error.contains(&format!("release_workflow: must {problem}")),
"{name}: {error}"
);
}
}
#[test]
fn release_checks_name_the_checks_release_runs() {
assert_eq!(
load(PACKAGE).unwrap().release_checks,
[ReleaseCheck::Registry, ReleaseCheck::Trust]
);
for (list, expected) in [
("[]", [].as_slice()),
("[registry]", [ReleaseCheck::Registry].as_slice()),
(
"[trust, registry]",
[ReleaseCheck::Trust, ReleaseCheck::Registry].as_slice(),
),
] {
let config = load(&formatdoc! {"
{PACKAGE}release_checks: {list}
"})
.unwrap();
assert_eq!(config.release_checks, expected, "{list}");
}
let error = format!(
"{:#}",
load(&formatdoc! {"
{PACKAGE}release_checks: [registry, registry]
"})
.unwrap_err()
);
assert!(
error.contains(r#"release_checks: lists "registry" twice"#),
"{error}"
);
let error = format!(
"{:#}",
load(&formatdoc! {"
{PACKAGE}release_checks: [versions]
"})
.unwrap_err()
);
for name in ["release_checks", "versions", "registry", "trust"] {
assert!(error.contains(name), "{name}: {error}");
}
}
}