1use std::collections::{BTreeMap, BTreeSet};
2use std::ffi::OsStr;
3use std::path::{Component, Path, PathBuf};
4use std::str::FromStr;
5use std::{fmt, fs};
6
7use anyhow::{Context, Result, bail, ensure};
8use ctl_core::input::{FieldPath, Input};
9use ctl_core::validate;
10use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
11use garde::Validate;
12use serde::de::value::MapAccessDeserializer;
13use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
14use serde::{Deserialize, Serialize, de};
15
16use crate::driver::{CommandSpec, Driver, Format, Text};
17use crate::publisher_spec::{self as publisher, PublisherSpec, RELEASE_ONLY};
18use crate::{asset_rules as assets, detect};
19
20#[derive(Debug, Clone, Deserialize)]
22#[serde(untagged)]
23#[non_exhaustive]
24pub enum CommandField {
25 Mise(String),
27 Argv(Vec<String>),
29}
30
31impl CommandField {
32 fn into_spec(self) -> Result<CommandSpec> {
33 match self {
34 Self::Mise(task) => {
35 if task.is_empty() {
36 bail!("mise task name is empty");
37 }
38 Ok(CommandSpec::Mise(task))
39 }
40 Self::Argv(argv) => {
41 ensure!(!argv.is_empty(), "driver argv is empty");
42 Ok(CommandSpec::Argv(argv))
43 }
44 }
45 }
46}
47
48#[derive(Debug, Clone, Default, Deserialize)]
52#[non_exhaustive]
53pub struct DriverSpec {
54 pub format: Option<String>,
58 pub keys: Option<Vec<String>>,
60 pub read: Option<CommandField>,
62 pub write: Option<CommandField>,
65 pub after: Option<String>,
68}
69
70impl DriverSpec {
71 pub fn into_driver(self, name: &str) -> Result<Driver> {
81 if let (Some(read), Some(write)) = (self.read, self.write) {
82 return Ok(Driver::Command {
83 read: read.into_spec()?,
84 write: write.into_spec()?,
85 after: self.after,
86 });
87 }
88 let format = match self.format.as_deref() {
89 Some("toml") => Format::Toml,
90 Some("json") => Format::Json,
91 Some(text @ ("gomod" | "version")) => {
92 ensure!(
93 self.keys.is_none(),
94 "driver {name:?} has format {text}, which reads the whole file and takes no keys"
95 );
96 let text = if text == "gomod" {
97 Text::GoMod
98 } else {
99 Text::Version
100 };
101 return Ok(Driver::Text {
102 text,
103 after: self.after,
104 });
105 }
106 Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
107 None => bail!("driver {name:?} needs format+keys or read+write"),
108 };
109 let keys = self
110 .keys
111 .filter(|keys| !keys.is_empty())
112 .with_context(|| format!("driver {name:?} needs keys"))?;
113 Ok(Driver::Path {
114 format,
115 keys,
116 after: self.after,
117 })
118 }
119
120 fn stock(name: &str) -> Option<Self> {
121 match name {
122 "cargo" => Some(Self {
123 format: Some("toml".into()),
124 keys: Some(vec![
125 "workspace.package.version".into(),
126 "package.version".into(),
127 ]),
128 ..Self::default()
129 }),
130 "npm" => Some(Self {
131 format: Some("json".into()),
132 keys: Some(vec!["version".into()]),
133 ..Self::default()
134 }),
135 "pyproject" => Some(Self {
136 format: Some("toml".into()),
137 keys: Some(vec!["project.version".into()]),
138 ..Self::default()
139 }),
140 "go" => Some(Self {
141 format: Some("gomod".into()),
142 ..Self::default()
143 }),
144 "version" => Some(Self {
145 format: Some("version".into()),
146 ..Self::default()
147 }),
148 _ => None,
149 }
150 }
151
152 fn merge(self, over: Self) -> Self {
153 Self {
154 format: over.format.or(self.format),
155 keys: over.keys.or(self.keys),
156 read: over.read.or(self.read),
157 write: over.write.or(self.write),
158 after: over.after.or(self.after),
159 }
160 }
161}
162
163#[derive(Debug, Clone, Deserialize)]
166#[non_exhaustive]
167pub struct PackageSpec {
168 pub name: String,
170 pub path: PathBuf,
172 pub driver: Option<String>,
175 pub publisher: Option<String>,
179 pub noun: Option<String>,
181 #[serde(default)]
189 pub publish: Option<Publish>,
190 pub registry: Option<String>,
193 pub query: Option<Vec<String>>,
197 pub changelog: Option<PathBuf>,
199 #[serde(default)]
203 pub first_minor: bool,
204 pub prerelease: Option<Prerelease>,
209 #[serde(default)]
218 pub marker: bool,
219 pub owners: Option<Vec<String>>,
223 #[serde(flatten)]
225 pub spec: DriverSpec,
226 #[serde(flatten)]
230 #[expect(
231 clippy::zero_sized_map_values,
232 reason = "the keys are all that is read, and serde has no set to flatten into"
233 )]
234 unknown: BTreeMap<String, IgnoredAny>,
235}
236
237#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
245#[serde(transparent)]
246pub struct Prerelease(String);
247
248impl Prerelease {
249 pub fn new(tag: &str) -> Result<Self> {
256 let tag = Self(tag.to_owned());
257 ensure!(tag.is_valid(), "{}", Self::RULE);
258 Ok(tag)
259 }
260
261 #[must_use]
263 pub fn as_str(&self) -> &str {
264 &self.0
265 }
266
267 #[must_use]
270 pub fn is_valid(&self) -> bool {
271 !self.0.is_empty()
272 && !matches!(self.0.as_str(), "x" | "latest")
273 && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
274 }
275
276 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";
281}
282
283impl PackageSpec {
284 #[must_use]
286 pub fn publish_command(&self) -> Option<&[String]> {
287 match &self.publish {
288 Some(Publish::Command(argv)) => Some(argv),
289 Some(Publish::Options(_)) | None => None,
290 }
291 }
292
293 #[must_use]
295 pub fn publish_options(&self) -> Option<&PublishOptions> {
296 match &self.publish {
297 Some(Publish::Options(options)) => Some(options),
298 Some(Publish::Command(_)) | None => None,
299 }
300 }
301
302 #[must_use]
304 pub fn changelog_path(&self, root: &Path) -> PathBuf {
305 if let Some(path) = &self.changelog {
306 return root.join(path);
307 }
308 root.join(&self.path)
309 .parent()
310 .unwrap_or(root)
311 .join("CHANGELOG.md")
312 }
313
314 pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
324 if self.marker {
325 return Ok(Driver::Text {
326 text: Text::Marker,
327 after: self.spec.after.clone(),
328 });
329 }
330 let inferred = self
331 .path
332 .file_name()
333 .and_then(|name| name.to_str())
334 .and_then(stock_name_for_file);
335 let driver_name = self.driver.as_deref().or(inferred);
336 let mut spec = driver_name
337 .and_then(|name| config.driver_spec(name))
338 .unwrap_or_default();
339 spec = spec.merge(self.spec.clone());
340 if spec.after.is_none() {
341 spec.after = detect::follow_up(&root.join(&self.path));
342 }
343 spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
344 }
345
346 pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
356 let path = root.join(&self.path);
357 let context = || format!("package {}: {}", self.name, path.display());
358 let driver = self.resolve(config, root).with_context(context)?;
359 let raw = driver.source(&path).with_context(context)?;
360 let version = driver.read(&raw).with_context(context)?.trim().to_owned();
361 Ok(Current {
362 driver,
363 path,
364 raw,
365 version,
366 })
367 }
368}
369
370pub type PublishOptions = BTreeMap<String, serde_json::Value>;
373
374#[derive(Debug, Clone, PartialEq, Eq)]
376#[non_exhaustive]
377pub enum Publish {
378 Options(PublishOptions),
381 Command(Vec<String>),
383}
384
385const PUBLISH_SHAPES: &str =
389 "a mapping of publisher options, or a list that is the whole upload command";
390
391impl<'de> Deserialize<'de> for Publish {
392 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
393 deserializer.deserialize_any(PublishVisitor)
394 }
395}
396
397struct PublishVisitor;
398
399impl<'de> Visitor<'de> for PublishVisitor {
400 type Value = Publish;
401
402 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403 write!(formatter, "{PUBLISH_SHAPES}")
404 }
405
406 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
407 let mut argv = Vec::new();
408 while let Some(part) = seq.next_element::<String>()? {
409 argv.push(part);
410 }
411 Ok(Publish::Command(argv))
412 }
413
414 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
415 let mut options = PublishOptions::new();
416 while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
417 options.insert(key, value);
418 }
419 Ok(Publish::Options(options))
420 }
421}
422
423#[derive(Debug, Clone)]
426#[non_exhaustive]
427pub struct Current {
428 pub driver: Driver,
430 pub path: PathBuf,
432 pub raw: String,
434 pub version: String,
436}
437
438#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
442#[serde(deny_unknown_fields)]
443#[garde(context(Config))]
444#[non_exhaustive]
445pub struct Runner {
446 #[garde(custom(at_least_one("label")))]
448 pub labels: Vec<String>,
449}
450
451#[derive(Debug, Clone, Deserialize, Default)]
455#[serde(deny_unknown_fields)]
456#[non_exhaustive]
457pub struct Job {
458 pub runners: Option<Vec<String>>,
461}
462
463#[derive(Debug, Clone, Deserialize, Default, Validate)]
471#[garde(context(Config))]
472#[garde(allow_unvalidated)]
473#[non_exhaustive]
474pub struct Assets {
475 pub bin: Option<String>,
477 pub prepare: Option<Vec<String>>,
479 pub build: Option<Vec<String>>,
481 #[garde(custom(binary_is_not_beside_files))]
485 pub binary: Option<String>,
486 #[serde(default)]
490 #[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
491 pub dir: Option<PathBuf>,
492 #[serde(default)]
497 #[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
498 pub files: Vec<PathBuf>,
499 #[serde(default)]
503 #[garde(dive, custom(generated_paths_are_sound))]
504 pub generated: Vec<Generated>,
505 #[serde(flatten)]
512 #[garde(dive)]
513 pub targets: BTreeMap<String, AssetTarget>,
514}
515
516impl Assets {
517 pub const SETTINGS: [&'static str; 7] = [
521 "bin",
522 "prepare",
523 "build",
524 "binary",
525 "dir",
526 "files",
527 "generated",
528 ];
529}
530
531#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
536#[serde(deny_unknown_fields)]
537#[garde(context(Config))]
538#[garde(allow_unvalidated)]
539#[non_exhaustive]
540pub struct Generated {
541 pub path: String,
546 #[garde(custom(at_least_one("argument")))]
551 pub run: Vec<String>,
552}
553
554#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
557#[serde(deny_unknown_fields)]
558#[garde(context(Config))]
559#[garde(allow_unvalidated)]
560#[non_exhaustive]
561pub struct AssetTarget {
562 pub runner: Option<String>,
564 pub os: Option<String>,
566 pub arch: Option<String>,
568 pub triple: Option<String>,
570 pub prepare: Option<Vec<String>>,
574 pub build: Option<Vec<String>>,
577 #[garde(inner(custom(a_tarball_name)))]
583 pub tarball: Option<String>,
584 #[serde(default)]
589 #[garde(
590 custom(target_files_come_with_dir),
591 inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
592 )]
593 pub files: Option<Vec<PathBuf>>,
594 #[serde(default)]
600 #[garde(custom(a_packslip_table))]
601 pub packslip: ArtifactTable,
602}
603
604#[derive(Debug, Clone, Default)]
610pub struct ArtifactTable(toml_edit::Table);
611
612impl ArtifactTable {
613 pub fn entries(&self) -> impl Iterator<Item = (&str, &toml_edit::Item)> {
615 self.0.iter()
616 }
617
618 #[must_use]
620 pub fn contains_key(&self, key: &str) -> bool {
621 self.0.contains_key(key)
622 }
623
624 #[must_use]
626 pub fn get(&self, key: &str) -> Option<&toml_edit::Item> {
627 self.0.get(key)
628 }
629}
630
631impl fmt::Display for ArtifactTable {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 fmt::Display::fmt(&self.0, f)
635 }
636}
637
638impl PartialEq for ArtifactTable {
640 fn eq(&self, other: &Self) -> bool {
641 self.to_string() == other.to_string()
642 }
643}
644
645impl Eq for ArtifactTable {}
646
647impl<'de> Deserialize<'de> for ArtifactTable {
648 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
649 let table = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
650 toml_table(&table).map(Self).map_err(de::Error::custom)
651 }
652}
653
654#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
660#[garde(context(Config))]
661#[garde(allow_unvalidated)]
662#[non_exhaustive]
663pub struct Packslip {
664 #[garde(inner(custom(inside_the_repo)))]
670 pub manifest: Option<PathBuf>,
671 pub attest: Attest,
673 #[garde(inner(custom(a_public_key_line)))]
679 pub pubkey: Option<String>,
680}
681
682fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
684 if line.trim().is_empty() {
685 return Err(garde::Error::new(
686 "cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
687 ));
688 }
689 Ok(())
690}
691
692#[derive(Deserialize)]
694#[serde(deny_unknown_fields)]
695struct PackslipKeys {
696 #[serde(default)]
697 manifest: Option<PathBuf>,
698 #[serde(default)]
699 attest: Attest,
700 #[serde(default)]
701 pubkey: Option<String>,
702}
703
704impl<'de> Deserialize<'de> for Packslip {
705 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
706 deserializer.deserialize_any(PackslipVisitor)
707 }
708}
709
710struct PackslipVisitor;
711
712impl<'de> Visitor<'de> for PackslipVisitor {
713 type Value = Packslip;
714
715 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
716 formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
717 }
718
719 fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
720 Err(E::custom(format!(
721 "packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
722 )))
723 }
724
725 fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
726 let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
727 Ok(Packslip {
728 manifest: keys.manifest,
729 attest: keys.attest,
730 pubkey: keys.pubkey,
731 })
732 }
733}
734
735#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
738#[non_exhaustive]
739pub enum Attest {
740 #[default]
742 True,
743 Link,
746 False,
748}
749
750impl Attest {
751 #[must_use]
753 pub const fn as_str(self) -> &'static str {
754 match self {
755 Self::True => "true",
756 Self::Link => "link",
757 Self::False => "false",
758 }
759 }
760}
761
762impl fmt::Display for Attest {
763 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764 f.write_str(self.as_str())
765 }
766}
767
768impl FromStr for Attest {
769 type Err = String;
770
771 fn from_str(word: &str) -> Result<Self, String> {
772 match word {
773 "true" => Ok(Self::True),
774 "link" => Ok(Self::Link),
775 "false" => Ok(Self::False),
776 other => Err(format!(
777 "packslip.attest must be true, link, or false, not {other:?}"
778 )),
779 }
780 }
781}
782
783impl Serialize for Attest {
784 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
785 serializer.serialize_str(self.as_str())
786 }
787}
788
789impl<'de> Deserialize<'de> for Attest {
790 fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
791 deserializer.deserialize_any(AttestVisitor)
792 }
793}
794
795struct AttestVisitor;
796
797impl Visitor<'_> for AttestVisitor {
798 type Value = Attest;
799
800 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
801 formatter.write_str("packslip.attest: true, link, or false")
802 }
803
804 fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
805 Ok(if v { Attest::True } else { Attest::False })
806 }
807
808 fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
809 v.parse().map_err(E::custom)
810 }
811}
812
813#[derive(Debug, Clone, Deserialize, Validate)]
820#[serde(deny_unknown_fields)]
821#[garde(context(Config))]
822#[garde(allow_unvalidated)]
823#[non_exhaustive]
824pub struct Vendored {
825 #[garde(
827 custom(cannot_be_empty("it names the release and the archives")),
828 custom(one_plain_name)
829 )]
830 pub version: String,
831 #[serde(default = "Vendored::default_tag")]
834 #[garde(
835 custom(cannot_be_empty("it names the release")),
836 custom(only_placeholders(&["{name}", "{version}"]))
837 )]
838 pub tag: String,
839 #[serde(default = "Vendored::default_archive")]
842 #[garde(
843 custom(one_archive_per_target),
844 custom(only_placeholders(&["{name}", "{version}", "{id}"]))
845 )]
846 pub archive: String,
847 #[serde(default)]
851 pub build: Vec<String>,
852 #[garde(custom(inside_the_repo))]
855 pub dir: PathBuf,
856 #[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
859 pub files: Vec<PathBuf>,
860 #[garde(inner(custom(inside_the_repo)))]
863 pub notes: Option<PathBuf>,
864 #[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
866 pub targets: BTreeMap<String, VendoredTarget>,
867}
868
869impl Vendored {
870 fn default_tag() -> String {
871 "{name}-{version}".to_owned()
872 }
873
874 fn default_archive() -> String {
875 "{name}-{version}-{id}.tar.gz".to_owned()
876 }
877}
878
879#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
881#[serde(deny_unknown_fields)]
882#[garde(context(Config))]
883#[non_exhaustive]
884pub struct VendoredTarget {
885 #[garde(custom(runner_is_declared))]
888 pub runner: String,
889}
890
891fn one_archive_per_target(archive: &str, config: &Config) -> garde::Result {
894 validate::one_file_name(archive, config)?;
895 if !archive.contains("{id}") {
896 return Err(garde::Error::new(
897 "must contain {id}, or every target writes the same archive",
898 ));
899 }
900 if !archive.ends_with(".tar.gz") {
901 return Err(garde::Error::new(
902 "must end in .tar.gz, the only archive verctl writes",
903 ));
904 }
905 Ok(())
906}
907
908fn only_placeholders(allowed: &'static [&'static str]) -> impl Fn(&str, &Config) -> garde::Result {
912 move |template, _| {
913 let rest = allowed
914 .iter()
915 .fold(template.to_owned(), |rest, placeholder| {
916 rest.replace(placeholder, "")
917 });
918 if rest.contains(['{', '}']) {
919 return Err(garde::Error::new(format!(
920 "has a '{{' or '}}' that is not {}",
921 allowed.join(", ")
922 )));
923 }
924 Ok(())
925 }
926}
927
928fn one_plain_name(value: &str, _: &Config) -> garde::Result {
933 if value.is_empty() || value == "." || value == ".." || value.contains(['/', '\\']) {
934 return Err(garde::Error::new(format!(
935 "{value:?} must be one plain name, with no / or \\ and not . or .."
936 )));
937 }
938 Ok(())
939}
940
941fn every_key_is_one_plain_name<V>(map: &BTreeMap<String, V>, config: &Config) -> garde::Result {
942 map.keys().try_for_each(|key| one_plain_name(key, config))
943}
944
945fn at_least_one_target(targets: &BTreeMap<String, VendoredTarget>, _: &Config) -> garde::Result {
946 if targets.is_empty() {
947 return Err(garde::Error::new("must declare at least one target"));
948 }
949 Ok(())
950}
951
952fn a_tarball_name(template: &str, config: &Config) -> garde::Result {
955 validate::one_file_name(template, config)?;
956 only_placeholders(&["{bin}", "{version}", "{os}", "{arch}"])(template, config)?;
957 if !template.ends_with(".tar.gz") {
958 return Err(garde::Error::new(
959 "must end in .tar.gz, the only archive verctl writes",
960 ));
961 }
962 Ok(())
963}
964
965#[expect(
969 clippy::ref_option,
970 reason = "garde passes the field as it is declared"
971)]
972fn every_tarball_is_its_own(assets: &Option<Assets>, config: &Config) -> garde::Result {
973 let Some(assets) = assets else {
974 return Ok(());
975 };
976 let Some(package) = config.packages.first() else {
977 return Ok(());
978 };
979 let bin = assets.bin.as_deref().unwrap_or(&package.name);
980 if let Some((first, second, name)) = assets::tarball_clash(assets, bin) {
981 return Err(garde::Error::new(format!(
982 "assets.{first} and assets.{second} both write {name}: set `tarball` on one of them"
983 )));
984 }
985 Ok(())
986}
987
988#[expect(
991 clippy::ref_option,
992 reason = "garde passes the field as it is declared"
993)]
994fn packslip_needs_assets(packslip: &Option<Packslip>, config: &Config) -> garde::Result {
995 let has_targets = config
996 .assets
997 .as_ref()
998 .is_some_and(|assets| !assets.targets.is_empty());
999 if packslip.is_some() && !has_targets {
1000 return Err(garde::Error::new(
1001 "needs at least one assets target: the bundle is an asset of the Release that carries the tarballs",
1002 ));
1003 }
1004 Ok(())
1005}
1006
1007pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
1018 let text = fs::read_to_string(path)
1019 .with_context(|| format!("packslip.manifest: read {}", named.display()))?;
1020 let document = text
1021 .parse::<toml_edit::DocumentMut>()
1022 .with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
1023 ensure!(
1024 !document.contains_key("artifact"),
1025 "packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
1026 named.display()
1027 );
1028 Ok(document)
1029}
1030
1031fn a_packslip_table(table: &ArtifactTable, _: &Config) -> garde::Result {
1035 if table.contains_key("path") {
1036 return Err(garde::Error::new(
1037 "sets `packslip.path`, the tarball's own path, which verctl writes: delete it",
1038 ));
1039 }
1040 Ok(())
1041}
1042
1043fn toml_table(
1051 table: &serde_json::Map<String, serde_json::Value>,
1052) -> Result<toml_edit::Table, String> {
1053 let mut converted = toml_edit::Table::new();
1054 for (key, value) in table {
1055 let value = toml_value(value).map_err(|reason| format!("{key}: {reason}"))?;
1056 converted.insert(key, toml_edit::Item::Value(value));
1057 }
1058 Ok(converted)
1059}
1060
1061fn toml_value(value: &serde_json::Value) -> Result<toml_edit::Value, String> {
1062 match value {
1063 serde_json::Value::Null => Err("null has no TOML form: delete the key".to_owned()),
1064 serde_json::Value::Bool(flag) => Ok((*flag).into()),
1065 serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
1066 (Some(integer), _) => Ok(integer.into()),
1067 (None, Some(float)) if number.is_f64() => Ok(float.into()),
1068 _ => Err(format!("{number} is beyond the integers TOML supports")),
1069 },
1070 serde_json::Value::String(text) => Ok(text.as_str().into()),
1071 serde_json::Value::Array(items) => {
1072 let mut array = toml_edit::Array::new();
1073 for item in items {
1074 array.push(toml_value(item)?);
1075 }
1076 Ok(array.into())
1077 }
1078 serde_json::Value::Object(entries) => {
1079 let mut inline = toml_edit::InlineTable::new();
1080 for (key, entry) in entries {
1081 let entry = toml_value(entry).map_err(|reason| format!("{key}: {reason}"))?;
1082 inline.insert(key.as_str(), entry);
1083 }
1084 Ok(inline.into())
1085 }
1086 }
1087}
1088
1089fn generated_paths_are_sound(_: &[Generated], config: &Config) -> garde::Result {
1092 let Some(assets) = &config.assets else {
1093 return Ok(());
1094 };
1095 let Some(package) = config.packages.first() else {
1096 return Ok(());
1097 };
1098 let bin = assets.bin.as_deref().unwrap_or(&package.name);
1099 assets::generated_problem(assets, bin)
1100 .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
1101}
1102
1103#[expect(
1106 clippy::ref_option,
1107 reason = "garde passes the field as it is declared"
1108)]
1109fn dir_comes_with_files(dir: &Option<PathBuf>, config: &Config) -> garde::Result {
1110 let packs_files = config.assets.as_ref().is_some_and(|assets| {
1111 !assets.files.is_empty()
1112 || (!assets.targets.is_empty()
1113 && assets.targets.values().all(|target| target.files.is_some()))
1114 });
1115 if dir.is_some() && !packs_files {
1116 return Err(garde::Error::new(
1117 "must come with files, the paths packed from it, or a files list on every target",
1118 ));
1119 }
1120 Ok(())
1121}
1122
1123#[expect(
1125 clippy::ref_option,
1126 reason = "garde passes the field as it is declared"
1127)]
1128fn target_files_come_with_dir(files: &Option<Vec<PathBuf>>, config: &Config) -> garde::Result {
1129 let has_dir = config
1130 .assets
1131 .as_ref()
1132 .is_some_and(|assets| assets.dir.is_some());
1133 if files.is_some() && !has_dir {
1134 return Err(garde::Error::new(
1135 "must come with assets.dir, the directory they are packed from",
1136 ));
1137 }
1138 Ok(())
1139}
1140
1141fn files_come_with_dir(files: &[PathBuf], config: &Config) -> garde::Result {
1143 let has_dir = config
1144 .assets
1145 .as_ref()
1146 .is_some_and(|assets| assets.dir.is_some());
1147 if !files.is_empty() && !has_dir {
1148 return Err(garde::Error::new(
1149 "must come with dir, the directory they are packed from",
1150 ));
1151 }
1152 Ok(())
1153}
1154
1155#[expect(
1160 clippy::ref_option,
1161 reason = "garde passes the field as it is declared"
1162)]
1163fn binary_is_not_beside_files(binary: &Option<String>, config: &Config) -> garde::Result {
1164 let (Some(_), Some(assets)) = (binary, config.assets.as_ref()) else {
1165 return Ok(());
1166 };
1167 if let Some(id) = assets
1168 .targets
1169 .iter()
1170 .find_map(|(id, target)| target.files.is_some().then_some(id))
1171 {
1172 return Err(garde::Error::new(format!(
1173 "must be omitted when assets.{id}.files lists what the tarball contains; list the binary in files",
1174 )));
1175 }
1176 if assets.dir.is_some() || !assets.files.is_empty() {
1177 return Err(garde::Error::new(
1178 "must be omitted when dir and files list what the tarball contains; list the binary in files",
1179 ));
1180 }
1181 Ok(())
1182}
1183
1184fn runner_is_declared(runner: &str, config: &Config) -> garde::Result {
1185 if config.runners.contains_key(runner) {
1186 return Ok(());
1187 }
1188 let declared = config.runners.keys().cloned().collect::<Vec<_>>();
1189 Err(garde::Error::new(format!(
1190 "{runner:?} is not declared in runners ({})",
1191 if declared.is_empty() {
1192 "none declared".to_owned()
1193 } else {
1194 format!("declared: {}", declared.join(", "))
1195 }
1196 )))
1197}
1198
1199fn something_to_release(packages: &[PackageSpec], config: &Config) -> garde::Result {
1201 if packages.is_empty() && config.vendored.is_empty() {
1202 return Err(garde::Error::new(
1203 "must declare at least one package, or a vendored set",
1204 ));
1205 }
1206 Ok(())
1207}
1208
1209#[derive(Debug, Clone, Deserialize, Default, Validate)]
1218#[serde(deny_unknown_fields)]
1219#[garde(context(Self as config))]
1220#[garde(allow_unvalidated)]
1221#[non_exhaustive]
1222pub struct Config {
1223 #[serde(default)]
1226 pub drivers: BTreeMap<String, DriverSpec>,
1227 #[serde(default)]
1230 #[garde(
1231 custom(something_to_release),
1232 custom(no_unknown_package_keys),
1233 custom(release_only_names_no_registry),
1234 custom(publish_options_fit_the_publisher),
1235 custom(python_names_its_publisher),
1236 custom(a_marker_names_no_driver),
1237 custom(a_prerelease_is_lowercase_letters),
1238 custom(package_owners_are_logins)
1239 )]
1240 pub packages: Vec<PackageSpec>,
1241 #[serde(default)]
1245 #[garde(inner(custom(owners_are_logins)))]
1246 pub owners: Option<Vec<String>>,
1247 #[serde(default = "Config::default_release_workflow")]
1255 #[garde(custom(a_workflow_file_name))]
1256 pub release_workflow: String,
1257 #[serde(default = "ReleaseCheck::default_list")]
1265 #[garde(custom(each_release_check_once))]
1266 pub release_checks: Vec<ReleaseCheck>,
1267 #[serde(default)]
1269 #[garde(custom(none_is_not_a_publisher))]
1270 pub publishers: BTreeMap<String, PublisherSpec>,
1271 #[serde(default)]
1274 #[garde(dive)]
1275 pub runners: BTreeMap<String, Runner>,
1276 #[serde(default)]
1278 #[garde(dive, custom(every_tarball_is_its_own))]
1279 pub assets: Option<Assets>,
1280 #[serde(default)]
1285 #[garde(dive, custom(packslip_needs_assets))]
1286 pub packslip: Option<Packslip>,
1287 #[serde(default)]
1290 #[garde(custom(every_key_is_one_plain_name), dive)]
1291 pub vendored: BTreeMap<String, Vendored>,
1292 #[serde(default)]
1294 pub ci: BTreeMap<String, Job>,
1295 #[serde(default)]
1297 #[garde(custom(no_version_label))]
1298 pub prepare: Prepare,
1299 #[serde(default)]
1302 pub proposal: Proposal,
1303 #[serde(default)]
1305 pub changelog: Changelog,
1306 #[serde(default)]
1308 #[garde(dive)]
1309 pub templates: Templates,
1310 #[serde(default)]
1314 #[garde(dive)]
1315 pub tags: Tags,
1316 #[serde(default)]
1319 #[garde(custom(every_pattern_says_where_the_version_goes))]
1320 #[garde(custom(every_pattern_bounds_the_version))]
1321 #[garde(custom(every_pattern_is_listed))]
1322 pub patterns: BTreeMap<String, PinPattern>,
1323 #[serde(default)]
1325 #[garde(dive)]
1326 pub pins: Vec<Pin>,
1327}
1328
1329fn every_pattern_says_where_the_version_goes(
1332 patterns: &BTreeMap<String, PinPattern>,
1333 _: &Config,
1334) -> garde::Result {
1335 for (id, pattern) in patterns {
1336 let found = pattern.r#match.matches(PLACEHOLDER).count();
1337 if found != 1 {
1338 return Err(garde::Error::new(format!(
1339 "{id}: match says {PLACEHOLDER} {found} times, and must say it once"
1340 )));
1341 }
1342 }
1343 Ok(())
1344}
1345
1346fn every_pattern_bounds_the_version(
1357 patterns: &BTreeMap<String, PinPattern>,
1358 _: &Config,
1359) -> garde::Result {
1360 for (id, pattern) in patterns {
1361 let Some((before, after)) = pattern.r#match.split_once(PLACEHOLDER) else {
1362 continue;
1363 };
1364 if after.contains(PLACEHOLDER) {
1365 continue;
1366 }
1367 if let Some(problem) = unbounded(before, after, pattern) {
1368 return Err(garde::Error::new(format!("{id}: {problem}")));
1369 }
1370 }
1371 Ok(())
1372}
1373
1374fn unbounded(before: &str, after: &str, pattern: &PinPattern) -> Option<String> {
1386 let sides = [
1387 (
1388 before,
1389 before.chars().rev().collect::<String>(),
1390 "before",
1391 "starts",
1392 ),
1393 (after, after.to_owned(), "after", "ends"),
1394 ];
1395 for (text, outward, side, edge) in sides {
1396 if text.is_empty() {
1397 if pattern.whole_line {
1398 continue;
1399 }
1400 return Some(format!(
1401 "nothing {side} {PLACEHOLDER} marks where the version {edge}: add the text {side} it to match, or set whole_line: true"
1402 ));
1403 }
1404 if text
1405 .chars()
1406 .all(|next| matches!(next, '0'..='9' | '.' | '-' | '+'))
1407 {
1408 return Some(format!(
1409 "{text:?} {side} {PLACEHOLDER} contains only digits, '.', '-', and '+', which a version can continue into: add more of the text {side} it to match"
1410 ));
1411 }
1412 let mut nearest = outward.chars();
1413 if matches!(
1414 (nearest.next(), nearest.next()),
1415 (Some('0'..='9'), _) | (Some('.'), Some('0'..='9'))
1416 ) {
1417 return Some(format!(
1418 "{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}"
1419 ));
1420 }
1421 }
1422 None
1423}
1424
1425fn every_pattern_is_listed(
1428 patterns: &BTreeMap<String, PinPattern>,
1429 config: &Config,
1430) -> garde::Result {
1431 let listed: BTreeSet<&str> = config
1432 .pins
1433 .iter()
1434 .flat_map(|pin| pin.pattern_ids.iter().map(String::as_str))
1435 .collect();
1436 for id in patterns.keys() {
1437 if !listed.contains(id.as_str()) {
1438 return Err(garde::Error::new(format!(
1439 "{id:?} is declared and no pin lists it"
1440 )));
1441 }
1442 }
1443 Ok(())
1444}
1445
1446#[derive(Debug, Clone, Deserialize, Validate)]
1448#[serde(deny_unknown_fields)]
1449#[garde(context(Config as config))]
1450#[garde(allow_unvalidated)]
1451#[non_exhaustive]
1452pub struct Pin {
1453 #[garde(custom(inside_the_repo))]
1455 pub file: PathBuf,
1456 pub tool: Option<String>,
1459 #[serde(default, rename = "patterns")]
1462 #[garde(
1463 custom(each_id_is_declared),
1464 custom(no_id_is_listed_twice),
1465 custom(something_to_rewrite(self.tool.as_deref()))
1466 )]
1467 pub pattern_ids: Vec<String>,
1468 #[serde(skip)]
1471 pub patterns: Vec<PinPattern>,
1472 pub package: String,
1474}
1475
1476fn none_is_not_a_publisher(
1480 publishers: &BTreeMap<String, PublisherSpec>,
1481 _: &Config,
1482) -> garde::Result {
1483 if publishers.contains_key(RELEASE_ONLY) {
1484 return Err(garde::Error::new(
1485 "publishers.none is reserved for release-only packages; rename that publisher",
1486 ));
1487 }
1488 Ok(())
1489}
1490
1491fn no_unknown_package_keys(packages: &[PackageSpec], _: &Config) -> garde::Result {
1495 for package in packages {
1496 if !package.unknown.is_empty() {
1497 let keys: Vec<&str> = package.unknown.keys().map(String::as_str).collect();
1498 return Err(garde::Error::new(format!(
1499 "package {:?} has {} verctl does not read: {}; check the spelling",
1500 package.name,
1501 if keys.len() == 1 { "a key" } else { "keys" },
1502 keys.join(", ")
1503 )));
1504 }
1505 }
1506 Ok(())
1507}
1508
1509fn owners_problem(owners: &[String]) -> Option<String> {
1512 if owners.is_empty() {
1513 return Some(
1514 "must list at least one crates.io login; omit the key to expect no owners".to_owned(),
1515 );
1516 }
1517 let mut seen = BTreeSet::new();
1518 owners
1519 .iter()
1520 .find(|login| !seen.insert(login.as_str()))
1521 .map(|login| format!("lists {login:?} twice; remove one"))
1522}
1523
1524fn owners_are_logins(owners: &[String], _: &Config) -> garde::Result {
1526 owners_problem(owners).map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
1527}
1528
1529fn package_owners_are_logins(packages: &[PackageSpec], _: &Config) -> garde::Result {
1532 for package in packages {
1533 if let Some(problem) = package.owners.as_deref().and_then(owners_problem) {
1534 return Err(garde::Error::new(format!(
1535 "packages[{name}].owners {problem}",
1536 name = package.name
1537 )));
1538 }
1539 }
1540 Ok(())
1541}
1542
1543#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1549#[serde(rename_all = "lowercase", try_from = "String")]
1550pub enum ReleaseCheck {
1551 Registry,
1553 Trust,
1556}
1557
1558impl ReleaseCheck {
1559 pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];
1561
1562 #[must_use]
1564 pub const fn name(self) -> &'static str {
1565 match self {
1566 Self::Registry => "registry",
1567 Self::Trust => "trust",
1568 }
1569 }
1570
1571 fn default_list() -> Vec<Self> {
1573 Self::ALL.to_vec()
1574 }
1575}
1576
1577impl TryFrom<String> for ReleaseCheck {
1581 type Error = String;
1582
1583 fn try_from(name: String) -> Result<Self, Self::Error> {
1584 Self::ALL
1585 .into_iter()
1586 .find(|check| check.name() == name)
1587 .ok_or_else(|| {
1588 format!(
1589 "release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
1590 )
1591 })
1592 }
1593}
1594
1595fn each_release_check_once(checks: &[ReleaseCheck], _: &Config) -> garde::Result {
1598 let mut seen = BTreeSet::new();
1599 checks
1600 .iter()
1601 .find(|check| !seen.insert(check.name()))
1602 .map_or_else(
1603 || Ok(()),
1604 |check| {
1605 Err(garde::Error::new(format!(
1606 "lists {:?} twice; remove one",
1607 check.name()
1608 )))
1609 },
1610 )
1611}
1612
1613fn a_workflow_file_name(name: &str, config: &Config) -> garde::Result {
1616 if validate::one_file_name(name, config).is_err() {
1617 return Err(garde::Error::new(
1618 "must be a file name under .github/workflows/, such as release.yml, with no directory",
1619 ));
1620 }
1621 if !Path::new(name)
1622 .extension()
1623 .is_some_and(|extension| extension == "yml" || extension == "yaml")
1624 {
1625 return Err(garde::Error::new(
1626 "must name a workflow file, ending in .yml or .yaml",
1627 ));
1628 }
1629 Ok(())
1630}
1631
1632fn a_prerelease_is_lowercase_letters(packages: &[PackageSpec], _: &Config) -> garde::Result {
1636 for package in packages {
1637 if let Some(tag) = package.prerelease.as_ref().filter(|tag| !tag.is_valid()) {
1638 return Err(garde::Error::new(format!(
1639 "package {:?} has prerelease {:?}, which is not a tag; {}",
1640 package.name,
1641 tag.as_str(),
1642 Prerelease::RULE
1643 )));
1644 }
1645 }
1646 Ok(())
1647}
1648
1649fn release_only_names_no_registry(packages: &[PackageSpec], config: &Config) -> garde::Result {
1653 for package in packages {
1654 if publisher::publisher_name(config, package) == RELEASE_ONLY
1655 && (package.registry.is_some() || package.publish.is_some())
1656 {
1657 return Err(garde::Error::new(format!(
1658 "package {:?} has publisher: none, which uploads to no registry; remove its registry and publish",
1659 package.name
1660 )));
1661 }
1662 }
1663 Ok(())
1664}
1665
1666fn publish_options_fit_the_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
1670 for package in packages {
1671 if let Err(problem) = publisher::check_options(config, package) {
1672 return Err(garde::Error::new(problem));
1673 }
1674 }
1675 Ok(())
1676}
1677
1678fn a_marker_names_no_driver(packages: &[PackageSpec], _: &Config) -> garde::Result {
1682 for package in packages {
1683 let spec = &package.spec;
1684 if package.marker
1685 && (package.driver.is_some()
1686 || spec.format.is_some()
1687 || spec.keys.is_some()
1688 || spec.read.is_some()
1689 || spec.write.is_some())
1690 {
1691 return Err(garde::Error::new(format!(
1692 "package {:?} has marker: true, which reads the version from its marker line; remove its driver, format, keys, read, and write",
1693 package.name
1694 )));
1695 }
1696 }
1697 Ok(())
1698}
1699
1700fn python_names_its_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
1706 for package in packages {
1707 if package.path.file_name() == Some(OsStr::new("pyproject.toml"))
1708 && package.publisher.is_none()
1709 && package.publish_command().is_none()
1710 && !config.publishers.contains_key(&package.name)
1711 {
1712 return Err(garde::Error::new(format!(
1713 "package {:?} needs a publisher: verctl has no stock Python publisher; set publisher to a publishers entry, or to none to release on GitHub only",
1714 package.name
1715 )));
1716 }
1717 }
1718 Ok(())
1719}
1720
1721fn each_id_is_declared(ids: &[String], config: &Config) -> garde::Result {
1722 for id in ids {
1723 if !config.patterns.contains_key(id) {
1724 return Err(garde::Error::new(format!("no patterns.{id}")));
1725 }
1726 }
1727 Ok(())
1728}
1729
1730fn no_id_is_listed_twice(ids: &[String], _: &Config) -> garde::Result {
1732 let mut seen = BTreeSet::new();
1733 for id in ids {
1734 if !seen.insert(id.as_str()) {
1735 return Err(garde::Error::new(format!("lists {id:?} twice")));
1736 }
1737 }
1738 Ok(())
1739}
1740
1741fn something_to_rewrite(tool: Option<&str>) -> impl Fn(&[String], &Config) -> garde::Result + '_ {
1743 move |ids, _| {
1744 if tool.is_some() || !ids.is_empty() {
1745 return Ok(());
1746 }
1747 Err(garde::Error::new("needs a tool or a pattern to rewrite"))
1748 }
1749}
1750
1751pub const DIR: &str = ".ctl";
1754
1755pub const FILE: &str = ".ctl/ver.yaml";
1758
1759#[must_use]
1766pub fn root_of(config: &Path) -> PathBuf {
1767 let dir = here(config.parent());
1768 if dir.file_name() == Some(OsStr::new(DIR)) {
1769 return here(dir.parent()).to_path_buf();
1770 }
1771 dir.to_path_buf()
1772}
1773
1774fn here(path: Option<&Path>) -> &Path {
1775 path.filter(|path| !path.as_os_str().is_empty())
1776 .unwrap_or_else(|| Path::new("."))
1777}
1778
1779pub const PLACEHOLDER: &str = "{version}";
1781
1782pub const NAME_PLACEHOLDER: &str = "{name}";
1784
1785#[derive(Debug, Clone, Deserialize, Validate)]
1788#[serde(deny_unknown_fields)]
1789#[garde(context(Config))]
1790#[non_exhaustive]
1791pub struct Tags {
1792 #[serde(default = "Tags::default_template")]
1795 #[garde(
1796 custom(cannot_be_empty(
1797 "it is the shape of every release tag, like \"v{version}\" or \"{name}@{version}\""
1798 )),
1799 custom(tag_template_placeholders)
1800 )]
1801 pub template: String,
1802}
1803
1804impl Tags {
1805 fn default_template() -> String {
1806 format!("v{PLACEHOLDER}")
1807 }
1808
1809 #[must_use]
1812 pub fn uses_name(&self) -> bool {
1813 self.template.contains(NAME_PLACEHOLDER)
1814 }
1815
1816 pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
1824 let mut out = self.template.replace(PLACEHOLDER, version);
1825 if let Some(name) = name {
1826 out = out.replace(NAME_PLACEHOLDER, name);
1827 } else if out.contains(NAME_PLACEHOLDER) {
1828 bail!(
1829 "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
1830 self.template
1831 );
1832 }
1833 ensure!(
1834 !out.contains('{') && !out.contains('}'),
1835 "tags.template {:?} still has braces after substitution",
1836 self.template
1837 );
1838 Ok(out)
1839 }
1840}
1841
1842impl Default for Tags {
1843 fn default() -> Self {
1844 Self {
1845 template: Self::default_template(),
1846 }
1847 }
1848}
1849
1850fn tag_template_placeholders(template: &str, _: &Config) -> garde::Result {
1854 let mut saw_version = false;
1855 let mut saw_name = false;
1856 let mut rest = template;
1857 while let Some(start) = rest.find('{') {
1858 let after = &rest[start + 1..];
1859 let Some(end) = after.find('}') else {
1860 return Err(garde::Error::new("has an opening '{' with no closing '}'"));
1861 };
1862 let name = &after[..end];
1863 match name {
1864 "version" => saw_version = true,
1865 "name" => saw_name = true,
1866 _ => {
1867 return Err(garde::Error::new(format!(
1868 "names {{{name}}}, and the only placeholders are {PLACEHOLDER} and {NAME_PLACEHOLDER}"
1869 )));
1870 }
1871 }
1872 rest = &after[end + 1..];
1873 }
1874 if !saw_version && !saw_name {
1875 return Err(garde::Error::new(format!(
1876 "has no placeholder — put {PLACEHOLDER} where the version goes"
1877 )));
1878 }
1879 if !saw_version {
1880 return Err(garde::Error::new(format!(
1881 "must say {PLACEHOLDER} — a tag with only {NAME_PLACEHOLDER} cannot date a release"
1882 )));
1883 }
1884 let leftover = template
1885 .replace(PLACEHOLDER, "")
1886 .replace(NAME_PLACEHOLDER, "");
1887 if leftover.contains('{') || leftover.contains('}') {
1888 return Err(garde::Error::new(format!(
1889 "has a '{{' or '}}' that is not {PLACEHOLDER} or {NAME_PLACEHOLDER}"
1890 )));
1891 }
1892 let _ = saw_name;
1893 Ok(())
1894}
1895
1896#[derive(Debug, Clone, Deserialize, Validate)]
1899#[serde(deny_unknown_fields)]
1900#[garde(context(Config))]
1901#[non_exhaustive]
1902pub struct Templates {
1903 #[serde(default = "Templates::default_source")]
1906 #[garde(custom(inside_the_repo))]
1907 pub source: PathBuf,
1908 #[serde(default = "Templates::default_suffix")]
1910 #[garde(custom(cannot_be_empty(
1911 "it is what marks a file in the source tree as a template, like \".jinja\""
1912 )))]
1913 pub suffix: String,
1914}
1915
1916impl Templates {
1917 fn default_source() -> PathBuf {
1918 Path::new(DIR).join("templates")
1919 }
1920
1921 fn default_suffix() -> String {
1922 ".jinja".to_owned()
1923 }
1924}
1925
1926impl Default for Templates {
1927 fn default() -> Self {
1928 Self {
1929 source: Self::default_source(),
1930 suffix: Self::default_suffix(),
1931 }
1932 }
1933}
1934
1935#[derive(Debug, Clone, Deserialize)]
1937#[serde(deny_unknown_fields)]
1938#[non_exhaustive]
1939pub struct PinPattern {
1940 pub r#match: String,
1953 #[serde(default)]
1957 pub occurrences: Occurrences,
1958 #[serde(default)]
1971 pub whole_line: bool,
1972}
1973
1974#[derive(Debug, Clone, Copy, Default)]
1978#[non_exhaustive]
1979pub enum Occurrences {
1980 #[default]
1982 Once,
1983 Many,
1986 Never,
1989 Exactly(usize),
1991 AtLeast(usize),
1993}
1994
1995const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";
2003
2004impl<'de> Deserialize<'de> for Occurrences {
2005 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2006 deserializer.deserialize_any(OccurrencesVisitor)
2007 }
2008}
2009
2010struct OccurrencesVisitor;
2011
2012impl<'de> Visitor<'de> for OccurrencesVisitor {
2013 type Value = Occurrences;
2014
2015 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2016 write!(formatter, "{ARITY}")
2017 }
2018
2019 fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
2020 match v {
2021 "once" => Ok(Occurrences::Once),
2022 "many" => Ok(Occurrences::Many),
2023 "never" => Ok(Occurrences::Never),
2024 _ => Err(E::custom(format!("must be {ARITY}"))),
2025 }
2026 }
2027
2028 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
2029 use serde::de::Error;
2030 let wrong = || A::Error::custom(format!("must be {ARITY}"));
2031 let key: String = map.next_key()?.ok_or_else(wrong)?;
2032 #[expect(
2033 clippy::map_err_ignore,
2034 reason = "the report names the accepted shapes; the number parse error adds nothing"
2035 )]
2036 let count: usize = map.next_value().map_err(|_| wrong())?;
2037 if map.next_key::<IgnoredAny>()?.is_some() {
2038 return Err(wrong());
2039 }
2040 match key.as_str() {
2041 "exactly" => Ok(Occurrences::Exactly(count)),
2042 "at_least" => Ok(Occurrences::AtLeast(count)),
2043 _ => Err(wrong()),
2044 }
2045 }
2046}
2047
2048impl Occurrences {
2049 #[must_use]
2051 pub const fn allows(self, found: usize) -> bool {
2052 match self {
2053 Self::Once => found == 1,
2054 Self::Many => found >= 1,
2055 Self::Never => found == 0,
2056 Self::Exactly(count) => found == count,
2057 Self::AtLeast(count) => found >= count,
2058 }
2059 }
2060}
2061
2062impl fmt::Display for Occurrences {
2063 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064 match self {
2065 Self::Once => f.write_str("exactly once"),
2066 Self::Many => f.write_str("one or more"),
2067 Self::Never => f.write_str("never"),
2068 Self::Exactly(count) => write!(f, "exactly {count} times"),
2069 Self::AtLeast(count) => write!(f, "{count} or more times"),
2070 }
2071 }
2072}
2073
2074#[derive(Debug, Clone, Default, Deserialize)]
2079#[serde(deny_unknown_fields)]
2080#[non_exhaustive]
2081pub struct Changelog {
2082 #[serde(default)]
2085 pub internal_authors: Vec<String>,
2086}
2087
2088impl Changelog {
2089 #[must_use]
2091 pub fn is_internal(&self, login: &str) -> bool {
2092 self.internal_authors
2093 .iter()
2094 .any(|listed| listed.eq_ignore_ascii_case(login))
2095 }
2096}
2097
2098#[derive(Debug, Clone, Deserialize, Default)]
2102#[serde(deny_unknown_fields)]
2103#[non_exhaustive]
2104pub struct Prepare {
2105 pub after: Option<Vec<String>>,
2107 #[serde(default)]
2109 pub stage: Vec<String>,
2110 #[serde(default)]
2112 pub stage_ignored: bool,
2113 #[serde(default, deserialize_with = "key_present")]
2119 version_label: bool,
2120}
2121
2122fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
2127 IgnoredAny::deserialize(deserializer).map(|_| true)
2128}
2129
2130#[derive(Debug, Clone, Default, Deserialize)]
2135#[serde(deny_unknown_fields)]
2136#[non_exhaustive]
2137pub struct Proposal {
2138 #[serde(default)]
2141 pub title: Option<String>,
2142 #[serde(default)]
2145 pub commit_message: Option<String>,
2146}
2147
2148impl Proposal {
2149 pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";
2151
2152 #[must_use]
2154 pub fn title(&self) -> &str {
2155 self.title
2156 .as_deref()
2157 .filter(|title| !title.is_empty())
2158 .unwrap_or(Self::DEFAULT_TITLE)
2159 }
2160
2161 #[must_use]
2163 pub fn commit_message(&self) -> &str {
2164 self.commit_message
2165 .as_deref()
2166 .filter(|message| !message.is_empty())
2167 .unwrap_or_else(|| self.title())
2168 }
2169}
2170
2171fn no_version_label(prepare: &Prepare, _: &Config) -> garde::Result {
2174 if prepare.version_label {
2175 return Err(garde::Error::new(
2176 "prepare.version_label is removed: the Version PR is no longer labeled; delete this key",
2177 ));
2178 }
2179 Ok(())
2180}
2181
2182impl Config {
2183 pub fn load(path: &Path) -> Result<Self> {
2197 let config = Self::from_input(Input::read(path)?)?;
2198 config.packslip_manifest_is_sound(&root_of(path))?;
2199 Ok(config)
2200 }
2201
2202 fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
2207 let Some(manifest) = self
2208 .packslip
2209 .as_ref()
2210 .and_then(|packslip| packslip.manifest.as_ref())
2211 else {
2212 return Ok(());
2213 };
2214 read_packslip_manifest(&root.join(manifest), manifest).map(drop)
2215 }
2216
2217 pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
2224 let Some(manifest) = self
2225 .packslip
2226 .as_ref()
2227 .and_then(|packslip| packslip.manifest.as_ref())
2228 else {
2229 return Ok(());
2230 };
2231 let plain = |path: &Path| {
2232 path.components()
2233 .filter(|part| !matches!(part, Component::CurDir))
2234 .collect::<PathBuf>()
2235 };
2236 let wanted = plain(manifest);
2237 let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
2238 ensure!(
2239 is_tracked,
2240 "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
2241 manifest.display()
2242 );
2243 Ok(())
2244 }
2245
2246 pub fn parse(raw: &str) -> Result<Self> {
2253 Self::from_input(Input::new(".ctl/ver.yaml", raw))
2254 }
2255
2256 fn from_input(input: Input) -> Result<Self> {
2264 let input = input.flattened(FieldPath::root().key("assets").key("targets"));
2265 let mut config: Self = input.parse()?;
2266 input.check(&config, &config)?;
2267 config.resolve_patterns();
2268 Ok(config)
2269 }
2270
2271 fn resolve_patterns(&mut self) {
2275 let declared = self.patterns.clone();
2276 for pin in &mut self.pins {
2277 pin.patterns = pin
2278 .pattern_ids
2279 .iter()
2280 .filter_map(|id| declared.get(id).cloned())
2281 .collect();
2282 }
2283 }
2284
2285 fn default_release_workflow() -> String {
2287 "release.yml".to_owned()
2288 }
2289
2290 #[must_use]
2294 pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
2295 package.owners.as_deref().or(self.owners.as_deref())
2296 }
2297
2298 pub fn find(&self, name: &str) -> Result<&PackageSpec> {
2304 self.packages
2305 .iter()
2306 .find(|package| package.name == name)
2307 .with_context(|| format!("package {name:?} is not in verctl config"))
2308 }
2309
2310 #[must_use]
2313 pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
2314 match (DriverSpec::stock(name), self.drivers.get(name)) {
2315 (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
2316 (Some(stock), None) => Some(stock),
2317 (None, Some(over)) => Some(over.clone()),
2318 (None, None) => None,
2319 }
2320 }
2321}
2322
2323fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
2324 match file_name {
2325 "Cargo.toml" => Some("cargo"),
2326 "package.json" => Some("npm"),
2327 "pyproject.toml" => Some("pyproject"),
2328 "go.mod" => Some("go"),
2329 "VERSION" => Some("version"),
2330 _ => None,
2331 }
2332}
2333
2334pub fn stock_driver(name: &str) -> Result<Driver> {
2342 DriverSpec::stock(name)
2343 .with_context(|| format!("unknown stock driver {name:?}"))?
2344 .into_driver(name)
2345}
2346
2347#[cfg(test)]
2348mod tests {
2349 use indoc::{formatdoc, indoc};
2350
2351 use super::*;
2352
2353 fn load(body: &str) -> Result<Config> {
2355 Config::parse(body)
2356 }
2357
2358 const PACKAGE: &str = indoc! {"
2360 packages:
2361 - name: demo
2362 path: Cargo.toml
2363 "};
2364
2365 #[test]
2368 fn a_release_only_package_names_no_registry() {
2369 let config = load(indoc! {"
2370 packages:
2371 - name: demo
2372 path: Cargo.toml
2373 publisher: none
2374 "})
2375 .unwrap();
2376 assert_eq!(config.packages[0].publisher.as_deref(), Some("none"));
2377 let error = load(&formatdoc! {r#"
2378 {PACKAGE}
2379 publishers:
2380 none:
2381 argv: ["true"]
2382 "#})
2383 .expect_err("publishers.none is reserved");
2384 assert!(
2385 format!("{error:#}").contains("publishers.none is reserved"),
2386 "{error:#}"
2387 );
2388 for extra in ["registry: crates-io", "publish: [cargo, publish]"] {
2389 let error = load(&formatdoc! {"
2390 packages:
2391 - name: demo
2392 path: Cargo.toml
2393 publisher: none
2394 {extra}
2395 "})
2396 .expect_err(extra);
2397 assert!(
2398 format!("{error:#}").contains("has publisher: none"),
2399 "{extra}: {error:#}"
2400 );
2401 }
2402 }
2403
2404 #[test]
2407 fn packslip_is_a_mapping_and_the_path_form_shows_it() {
2408 let with = |packslip: &str| {
2409 load(&formatdoc! {"
2410 {PACKAGE}
2411 assets:
2412 linux-x64: {{}}
2413 packslip: {packslip}
2414 "})
2415 };
2416 let both = with("{ manifest: .ctl/packslip.toml, attest: link }").unwrap();
2417 let both = both.packslip.expect("packslip");
2418 assert_eq!(
2419 both.manifest.as_deref(),
2420 Some(Path::new(".ctl/packslip.toml"))
2421 );
2422 assert_eq!(both.attest, Attest::Link);
2423 let off = with("{ attest: false }")
2424 .unwrap()
2425 .packslip
2426 .expect("packslip");
2427 assert_eq!((off.manifest, off.attest), (None, Attest::False));
2428 let empty = with("{}").unwrap().packslip.expect("packslip");
2429 assert_eq!(
2430 (empty.manifest, empty.attest, empty.pubkey),
2431 (None, Attest::True, None)
2432 );
2433 let keyed = with("{ pubkey: RWQexample }")
2434 .unwrap()
2435 .packslip
2436 .expect("packslip");
2437 assert_eq!(keyed.pubkey.as_deref(), Some("RWQexample"));
2438 let report = format!("{:#}", with(".ctl/packslip.toml").expect_err("path form"));
2439 assert!(
2440 report.contains("packslip: { manifest: .ctl/packslip.toml }"),
2441 "{report}"
2442 );
2443 }
2444
2445 #[test]
2447 fn a_blank_pubkey_fails_the_load() {
2448 for blank in ["''", "' '"] {
2449 let error = load(&formatdoc! {"
2450 {PACKAGE}
2451 assets:
2452 linux-x64: {{}}
2453 packslip: {{ pubkey: {blank} }}
2454 "})
2455 .expect_err(blank);
2456 let report = format!("{error:#}");
2457 assert!(report.contains("packslip.pubkey"), "{blank}: {report}");
2458 assert!(report.contains("cannot be empty"), "{blank}: {report}");
2459 }
2460 }
2461
2462 #[test]
2465 fn an_unknown_attest_mode_names_the_three_values() {
2466 let error = load(&formatdoc! {"
2467 {PACKAGE}
2468 assets:
2469 linux-x64: {{}}
2470 packslip: {{ attest: maybe }}
2471 "})
2472 .expect_err("maybe is no mode");
2473 let report = format!("{error:#}");
2474 assert!(report.contains("packslip.attest"), "{report}");
2475 assert!(report.contains("true, link, or false"), "{report}");
2476 }
2477
2478 #[test]
2480 fn a_target_packslip_table_is_kept_unread() {
2481 let config = load(&formatdoc! {r#"
2482 {PACKAGE}
2483 assets:
2484 darwin-arm64:
2485 packslip:
2486 requires: {{ os_min: "11.0" }}
2487 "#})
2488 .unwrap();
2489 let table = config.assets.expect("assets").targets["darwin-arm64"]
2490 .packslip
2491 .clone();
2492 assert_eq!(table.to_string(), "requires = { os_min = \"11.0\" }\n");
2493 }
2494
2495 #[test]
2497 fn a_target_without_a_packslip_table_has_an_empty_one() {
2498 let config = load(&formatdoc! {"
2499 {PACKAGE}
2500 assets:
2501 linux-x64: {{}}
2502 "})
2503 .unwrap();
2504 let table = &config.assets.expect("assets").targets["linux-x64"].packslip;
2505 assert_eq!(table.entries().count(), 0);
2506 }
2507
2508 #[test]
2510 fn a_target_packslip_table_refuses_a_path_and_a_null() {
2511 for (key, said) in [
2512 ("path: elsewhere.tar.gz", "packslip.path"),
2513 ("requires: ~", "null has no TOML form"),
2514 ] {
2515 let error = load(&formatdoc! {"
2516 {PACKAGE}
2517 assets:
2518 darwin-arm64:
2519 packslip:
2520 {key}
2521 "})
2522 .expect_err(key);
2523 let report = format!("{error:#}");
2524 assert!(report.contains(said), "{key}: {report}");
2525 }
2526 }
2527
2528 #[test]
2531 fn a_prerelease_is_lowercase_letters() {
2532 for tag in ["rc", "alpha", "beta", "next", "canary"] {
2533 let config = load(&formatdoc! {"
2534 packages:
2535 - name: demo
2536 path: Cargo.toml
2537 prerelease: {tag}
2538 "})
2539 .expect(tag);
2540 let spec = config.find("demo").expect("demo");
2541 assert_eq!(spec.prerelease.as_ref().map(Prerelease::as_str), Some(tag));
2542 }
2543 for tag in ["rc1", "RC", "rc.1", "1", "x", "latest", "\"\""] {
2544 let error = load(&formatdoc! {"
2545 packages:
2546 - name: demo
2547 path: Cargo.toml
2548 prerelease: {tag}
2549 "})
2550 .expect_err(tag);
2551 let message = format!("{error:#}");
2552 assert!(
2553 message.contains("package \"demo\" has prerelease")
2554 && message.contains("lowercase ASCII letters"),
2555 "{tag}: {message}"
2556 );
2557 }
2558 }
2559
2560 #[test]
2563 fn a_marker_names_no_driver() {
2564 for extra in [
2565 "driver: cargo",
2566 "format: toml",
2567 "keys: [project.version]",
2568 "read: [cat]",
2569 "write: [cat]",
2570 ] {
2571 let error = load(&formatdoc! {"
2572 packages:
2573 - name: ci
2574 path: ci.yml
2575 marker: true
2576 {extra}
2577 "})
2578 .expect_err(extra);
2579 assert!(
2580 format!("{error:#}").contains("has marker: true"),
2581 "{extra}: {error:#}"
2582 );
2583 }
2584 load(indoc! {"
2585 packages:
2586 - name: ci
2587 path: ci.yml
2588 marker: true
2589 after: mise run render
2590 "})
2591 .expect("after runs beside a marker");
2592 }
2593
2594 #[test]
2597 fn a_python_package_names_its_publisher() {
2598 let error = load(indoc! {"
2599 packages:
2600 - name: demo
2601 path: pyproject.toml
2602 "})
2603 .expect_err("no publisher");
2604 assert!(
2605 format!("{error:#}").contains("needs a publisher"),
2606 "{error:#}"
2607 );
2608 for named in [
2609 "publisher: none",
2610 "publish: [uv, publish]",
2611 "publisher: pypi",
2612 ] {
2613 load(&formatdoc! {"
2614 packages:
2615 - name: demo
2616 path: pyproject.toml
2617 {named}
2618 publishers:
2619 pypi:
2620 argv: [uv, publish]
2621 "})
2622 .unwrap_or_else(|error| panic!("{named}: {error:#}"));
2623 }
2624 load(indoc! {"
2625 packages:
2626 - name: demo
2627 path: pyproject.toml
2628 publishers:
2629 demo:
2630 argv: [uv, publish]
2631 "})
2632 .expect("a publishers entry under the package name");
2633 }
2634
2635 #[test]
2638 fn the_root_is_the_directory_holding_the_ctl_dir() {
2639 let cases = [
2640 (".ctl/ver.yaml", "."),
2641 ("crates/foo/.ctl/ver.yaml", "crates/foo"),
2642 ("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
2643 ("ver.yaml", "."),
2644 ("/tmp/scratch/ver.yaml", "/tmp/scratch"),
2645 ];
2646 for (config, expected) in cases {
2647 assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
2648 }
2649 }
2650
2651 #[test]
2653 fn every_occurrence_form_parses_and_means_what_it_says() {
2654 let config = load(&formatdoc! {r#"
2655 {PACKAGE}
2656 patterns:
2657 omitted:
2658 match: "a@{{version}} --"
2659 once:
2660 match: "b@{{version}} --"
2661 occurrences: once
2662 many:
2663 match: "c@{{version}} --"
2664 occurrences: many
2665 never:
2666 match: "d@{{version}} --"
2667 occurrences: never
2668 twice:
2669 match: "e@{{version}} --"
2670 occurrences: {{exactly: 2}}
2671 floor:
2672 match: "f@{{version}} --"
2673 occurrences: {{at_least: 2}}
2674
2675 pins:
2676 - file: README.md
2677 package: demo
2678 patterns: [omitted, once, many, never, twice, floor]
2679 "#})
2680 .unwrap();
2681 let allowed: Vec<Vec<usize>> = config.pins[0]
2682 .patterns
2683 .iter()
2684 .map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
2685 .collect();
2686 assert_eq!(
2687 allowed,
2688 [
2689 vec![1], vec![1], vec![1, 2, 3], vec![0], vec![2], vec![2, 3], ]
2696 );
2697 }
2698
2699 #[test]
2702 fn a_misspelled_section_stops_the_load() {
2703 let error = load(&formatdoc! {r#"
2704 {PACKAGE}
2705 pattern:
2706 install:
2707 match: "demo@{{version}} --"
2708 "#})
2709 .expect_err("pattern is not a section");
2710 assert!(format!("{error:#}").contains("pattern"), "{error:#}");
2711 }
2712
2713 #[test]
2717 fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
2718 let error = load(&formatdoc! {r#"
2719 {PACKAGE}
2720 patterns:
2721 wrong:
2722 match: "a@{{version}} --"
2723 occurrences: {{exactly: 2, at_leats: 3}}
2724
2725 pins:
2726 - file: README.md
2727 package: demo
2728 patterns: [wrong]
2729 "#})
2730 .expect_err("at_leats is not a key");
2731 assert!(format!("{error:#}").contains(ARITY), "{error:#}");
2732 }
2733
2734 #[test]
2737 fn a_bound_with_a_bad_count_names_the_arity() {
2738 for count in ["-1", "many"] {
2739 let error = load(&formatdoc! {r#"
2740 {PACKAGE}
2741 patterns:
2742 wrong:
2743 match: "a@{{version}} --"
2744 occurrences: {{exactly: {count}}}
2745
2746 pins:
2747 - file: README.md
2748 package: demo
2749 patterns: [wrong]
2750 "#})
2751 .expect_err("the count is not a whole number");
2752 assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
2753 }
2754 }
2755
2756 #[test]
2757 fn an_unknown_arity_is_not_silently_a_default() {
2758 let broken = load(&formatdoc! {r#"
2759 {PACKAGE}
2760 patterns:
2761 wrong:
2762 match: "a@{{version}} --"
2763 occurrences: sometimes
2764
2765 pins:
2766 - file: README.md
2767 package: demo
2768 patterns: [wrong]
2769 "#});
2770 let _ = broken.expect_err("unknown occurrences");
2771 }
2772
2773 #[test]
2775 fn one_named_pattern_serves_every_file_that_lists_it() {
2776 let config = load(&formatdoc! {r#"
2777 {PACKAGE}
2778 patterns:
2779 install:
2780 match: "demo@{{version}} --"
2781 mention:
2782 match: "v{{version}} --"
2783 occurrences: many
2784
2785 pins:
2786 - file: README.md
2787 package: demo
2788 patterns: [install, mention]
2789 - file: docs/install.md
2790 package: demo
2791 patterns: [install]
2792 "#})
2793 .unwrap();
2794 let carried: Vec<Vec<&str>> = config
2795 .pins
2796 .iter()
2797 .map(|pin| {
2798 pin.patterns
2799 .iter()
2800 .map(|pattern| pattern.r#match.as_str())
2801 .collect()
2802 })
2803 .collect();
2804 assert_eq!(
2805 carried,
2806 [
2807 vec!["demo@{version} --", "v{version} --"],
2808 vec!["demo@{version} --"]
2809 ],
2810 "each file carries the patterns it lists, in the order it lists them"
2811 );
2812 }
2813
2814 #[test]
2817 fn a_pattern_marks_where_the_version_starts_and_ends() {
2818 let only = "contains only digits, '.', '-', and '+'";
2819 let cases = [
2820 ("name-{version}.tar.gz", false, None),
2821 ("download/v{version}-linux", false, None),
2822 ("v{version}.tar", false, None),
2823 ("demo@{version} --", false, None),
2824 ("`demo@{version}`", false, None),
2825 ("verctl-{version}", true, None),
2826 ("version: {version}", true, None),
2827 ("{version}", true, None),
2828 (
2829 "{version}",
2830 false,
2831 Some("nothing before {version}".to_owned()),
2832 ),
2833 (
2834 "verctl-{version}",
2835 false,
2836 Some("nothing after {version}".to_owned()),
2837 ),
2838 (
2839 "version: {version}",
2840 false,
2841 Some("skill: nothing after {version}".to_owned()),
2842 ),
2843 (
2844 "verctl@{version}.",
2845 false,
2846 Some(format!("\".\" after {{version}} {only}")),
2847 ),
2848 (
2849 "v{version}-",
2850 false,
2851 Some(format!("\"-\" after {{version}} {only}")),
2852 ),
2853 (
2854 "v{version}+",
2855 false,
2856 Some(format!("\"+\" after {{version}} {only}")),
2857 ),
2858 (
2859 "-{version}",
2860 false,
2861 Some(format!("\"-\" before {{version}} {only}")),
2862 ),
2863 (
2864 "{version}.1",
2865 false,
2866 Some("nothing before {version}".to_owned()),
2867 ),
2868 (
2869 "{version}.1",
2870 true,
2871 Some(format!("\".1\" after {{version}} {only}")),
2872 ),
2873 (
2874 "version: {version}-",
2875 true,
2876 Some(format!("\"-\" after {{version}} {only}")),
2877 ),
2878 ];
2879 assert_bounds(cases);
2880 }
2881
2882 #[test]
2885 fn a_digit_next_to_the_version_leaves_the_side_open() {
2886 let near = "puts a digit, or a '.' and a digit, next to the version";
2887 assert_bounds([
2888 ("v{version}.tar", false, None),
2889 ("v{version}-1x", false, None),
2890 (
2891 "v{version}.5x",
2892 false,
2893 Some(format!("\".5x\" after {{version}} {near}")),
2894 ),
2895 (
2896 "v{version}1x",
2897 false,
2898 Some(format!("\"1x\" after {{version}} {near}")),
2899 ),
2900 (
2901 "x1.{version}-linux",
2902 false,
2903 Some(format!("\"x1.\" before {{version}} {near}")),
2904 ),
2905 (
2906 "x1{version}-linux",
2907 false,
2908 Some(format!("\"x1\" before {{version}} {near}")),
2909 ),
2910 (
2911 "{version}.1x",
2912 true,
2913 Some(format!("\".1x\" after {{version}} {near}")),
2914 ),
2915 ]);
2916 }
2917
2918 fn assert_bounds<const N: usize>(cases: [(&str, bool, Option<String>); N]) {
2921 for (text, whole_line, refusal) in cases {
2922 let loaded = load(&formatdoc! {"
2923 {PACKAGE}
2924 patterns:
2925 skill:
2926 match: '{text}'
2927 whole_line: {whole_line}
2928
2929 pins:
2930 - file: README.md
2931 package: demo
2932 patterns: [skill]
2933 "});
2934 match (loaded, refusal) {
2935 (Ok(_), None) => {}
2936 (Err(error), Some(needle)) => {
2937 let report = format!("{error:#}");
2938 assert!(report.contains(needle.as_str()), "{text}: {report}");
2939 }
2940 (outcome, _) => panic!("{text} (whole_line: {whole_line}): {outcome:?}"),
2941 }
2942 }
2943 }
2944
2945 #[test]
2947 #[expect(
2948 clippy::too_many_lines,
2949 reason = "one case per rule; a table, not logic"
2950 )]
2951 fn a_config_that_breaks_a_rule_stops_the_load() {
2952 let cases = [
2953 (
2954 "an id no patterns section declares",
2955 formatdoc! {r#"
2956 {PACKAGE}
2957 patterns:
2958 install:
2959 match: "demo@{{version}} --"
2960
2961 pins:
2962 - file: README.md
2963 package: demo
2964 patterns: [install, instal]
2965 "#},
2966 "pins[0].pattern_ids: no patterns.instal",
2967 ),
2968 (
2969 "the same id listed twice",
2970 formatdoc! {r#"
2971 {PACKAGE}
2972 patterns:
2973 install:
2974 match: "demo@{{version}} --"
2975
2976 pins:
2977 - file: README.md
2978 package: demo
2979 patterns: [install, install]
2980 "#},
2981 r#"pins[0].pattern_ids: lists "install" twice"#,
2982 ),
2983 (
2984 "a pattern no pin lists",
2985 formatdoc! {r#"
2986 {PACKAGE}
2987 patterns:
2988 install:
2989 match: "demo@{{version}} --"
2990 orphan:
2991 match: "old@{{version}} --"
2992
2993 pins:
2994 - file: README.md
2995 package: demo
2996 patterns: [install]
2997 "#},
2998 r#"patterns: "orphan" is declared and no pin lists it"#,
2999 ),
3000 (
3001 "a pin with nothing to rewrite",
3002 formatdoc! {"
3003 {PACKAGE}
3004 pins:
3005 - file: README.md
3006 package: demo
3007 "},
3008 "pins[0].pattern_ids: needs a tool or a pattern to rewrite",
3009 ),
3010 (
3011 "a spelling with nowhere to put the version",
3012 formatdoc! {r#"
3013 {PACKAGE}
3014 patterns:
3015 install:
3016 match: "demo@1.2.3"
3017
3018 pins:
3019 - file: README.md
3020 package: demo
3021 patterns: [install]
3022 "#},
3023 "patterns: install: match says {version} 0 times",
3024 ),
3025 (
3026 "a pin reaching out of the repository",
3027 formatdoc! {r#"
3028 {PACKAGE}
3029 patterns:
3030 install:
3031 match: "demo@{{version}} --"
3032
3033 pins:
3034 - file: ../elsewhere/README.md
3035 package: demo
3036 patterns: [install]
3037 "#},
3038 "pins[0].file: must stay inside the repository",
3039 ),
3040 (
3041 "a machine no label can find",
3042 formatdoc! {"
3043 {PACKAGE}
3044 runners:
3045 ghost:
3046 labels: []
3047 "},
3048 "runners.ghost.labels: must declare at least one label",
3049 ),
3050 (
3051 "a suffix that makes every file a template",
3052 formatdoc! {r#"
3053 {PACKAGE}
3054 templates:
3055 suffix: ""
3056 "#},
3057 "templates.suffix: cannot be empty — it is what marks a file",
3058 ),
3059 (
3060 "a tag template naming a placeholder that does not exist",
3061 formatdoc! {r#"
3062 {PACKAGE}
3063 tags:
3064 template: "v{{ver}}"
3065 "#},
3066 "tags.template: names {ver}, and the only placeholders are {version} and {name}",
3067 ),
3068 (
3069 "a tag template with no placeholder",
3070 formatdoc! {r#"
3071 {PACKAGE}
3072 tags:
3073 template: "latest"
3074 "#},
3075 "tags.template: has no placeholder",
3076 ),
3077 (
3078 "a tag template with only the package name",
3079 formatdoc! {r#"
3080 {PACKAGE}
3081 tags:
3082 template: "{{name}}"
3083 "#},
3084 "tags.template: must say {version}",
3085 ),
3086 (
3087 "an empty tag template",
3088 formatdoc! {r#"
3089 {PACKAGE}
3090 tags:
3091 template: ""
3092 "#},
3093 "tags.template: cannot be empty",
3094 ),
3095 (
3096 "a tag template with a leftover brace",
3097 formatdoc! {r#"
3098 {PACKAGE}
3099 tags:
3100 template: "v{{version}}}}"
3101 "#},
3102 "tags.template: has a '{' or '}' that is not {version} or {name}",
3103 ),
3104 ];
3105 for (scenario, body, expected) in cases {
3106 let error = load(&body).expect_err(scenario);
3107 assert!(
3108 format!("{error:#}").contains(expected),
3109 "{scenario}: {error:#}"
3110 );
3111 }
3112 }
3113
3114 fn vendored(extra: &str) -> String {
3117 formatdoc! {"
3118 runners:
3119 linux:
3120 labels: [ubuntu-26.04]
3121 vendored:
3122 lib:
3123 version: 1.4.0
3124 dir: out
3125 files: [lib]
3126 targets:
3127 linux-x64:
3128 runner: linux
3129 {extra}
3130 "}
3131 }
3132
3133 #[test]
3134 fn a_vendored_set_alone_is_a_config_and_takes_the_default_names() {
3135 let config = load(&vendored("")).unwrap();
3136 assert!(config.packages.is_empty());
3137 let set = &config.vendored["lib"];
3138 assert_eq!(set.tag, "{name}-{version}");
3139 assert_eq!(set.archive, "{name}-{version}-{id}.tar.gz");
3140 assert_eq!(set.build, Vec::<String>::new());
3141 assert_eq!(set.notes, None);
3142 }
3143
3144 #[test]
3145 fn a_config_with_no_package_and_no_vendored_set_fails() {
3146 let error = load("runners: {}\n").unwrap_err();
3147 assert!(
3148 format!("{error:#}").contains("must declare at least one package, or a vendored set"),
3149 "{error:#}"
3150 );
3151 }
3152
3153 #[test]
3154 fn a_vendored_set_without_targets_fails() {
3155 let error = load(indoc! {"
3156 vendored:
3157 lib:
3158 version: 1.4.0
3159 dir: out
3160 files: [lib]
3161 targets: {}
3162 "})
3163 .unwrap_err();
3164 assert!(
3165 format!("{error:#}").contains("must declare at least one target"),
3166 "{error:#}"
3167 );
3168 }
3169
3170 #[test]
3171 fn a_vendored_set_rejects_what_it_cannot_publish() {
3172 let base = vendored("");
3173 let cases = [
3174 (
3175 "archive without the target",
3176 vendored("archive: lib.tar.gz"),
3177 "must contain {id}",
3178 ),
3179 (
3180 "archive in another format",
3181 vendored("archive: \"{id}.zip\""),
3182 "must end in .tar.gz",
3183 ),
3184 (
3185 "archive in a directory",
3186 vendored("archive: \"dist/{id}.tar.gz\""),
3187 "must be one file name",
3188 ),
3189 (
3190 "archive with a typo",
3191 vendored("archive: \"{ids}.tar.gz\""),
3192 "that is not {name}, {version}, {id}",
3193 ),
3194 (
3195 "tag that varies by target",
3196 vendored("tag: \"lib-{id}\""),
3197 "that is not {name}, {version}",
3198 ),
3199 ("empty tag", vendored("tag: \"\""), "cannot be empty"),
3200 (
3201 "notes outside the repo",
3202 vendored("notes: ../notes.md"),
3203 "must stay inside the repository",
3204 ),
3205 ("unknown key", vendored("bin: lib"), "bin"),
3206 (
3207 "empty version",
3208 base.replace("version: 1.4.0", "version: \"\""),
3209 "cannot be empty",
3210 ),
3211 (
3212 "dir outside the repo",
3213 base.replace("dir: out", "dir: /tmp"),
3214 "must stay inside the repository",
3215 ),
3216 (
3217 "no files",
3218 base.replace("files: [lib]", "files: []"),
3219 "must declare at least one file",
3220 ),
3221 (
3222 "a file outside the repo",
3223 base.replace("files: [lib]", "files: [../secret]"),
3224 "must stay inside the repository",
3225 ),
3226 (
3227 "version with a path separator",
3228 base.replace("version: 1.4.0", "version: 1.4/../../x"),
3229 "must be one plain name",
3230 ),
3231 (
3232 "target key with a parent step",
3233 base.replace("linux-x64:", "\"..\":"),
3234 "must be one plain name",
3235 ),
3236 (
3237 "target key with a path separator",
3238 base.replace("linux-x64:", "a/b:"),
3239 "must be one plain name",
3240 ),
3241 (
3242 "set name with a path separator",
3243 base.replace(" lib:", " \"../lib\":"),
3244 "must be one plain name",
3245 ),
3246 (
3247 "undeclared machine",
3248 base.replace("runner: linux", "runner: big"),
3249 "\"big\" is not declared in runners (declared: linux)",
3250 ),
3251 ];
3252 for (scenario, body, expected) in cases {
3253 let error = load(&body).expect_err(scenario);
3254 assert!(
3255 format!("{error:#}").contains(expected),
3256 "{scenario}: {error:#}"
3257 );
3258 }
3259 }
3260
3261 fn assets(section: &str) -> String {
3263 format!("{PACKAGE}{section}")
3264 }
3265
3266 #[test]
3267 fn asset_files_are_packed_from_their_dir() {
3268 let config = load(&assets(indoc! {"
3269 assets:
3270 dir: target/{triple}/release
3271 files: [demo, demod, LICENSE]
3272 linux-x64: {}
3273 "}))
3274 .unwrap();
3275 let recipe = config.assets.unwrap();
3276 assert_eq!(recipe.dir, Some(PathBuf::from("target/{triple}/release")));
3277 assert_eq!(
3278 recipe.files,
3279 [
3280 PathBuf::from("demo"),
3281 PathBuf::from("demod"),
3282 PathBuf::from("LICENSE")
3283 ]
3284 );
3285 assert_eq!(recipe.targets.keys().collect::<Vec<_>>(), ["linux-x64"]);
3286 }
3287
3288 #[test]
3289 fn a_target_lists_its_own_files() {
3290 let config = load(&assets(indoc! {"
3291 assets:
3292 dir: out/{triple}
3293 darwin-arm64:
3294 files: [proof]
3295 linux-x64:
3296 files: [bench, proof]
3297 "}))
3298 .unwrap();
3299 let recipe = config.assets.unwrap();
3300 assert_eq!(recipe.files, Vec::<PathBuf>::new());
3301 assert_eq!(
3302 recipe.targets["darwin-arm64"].files,
3303 Some(vec![PathBuf::from("proof")])
3304 );
3305 assert_eq!(
3306 recipe.targets["linux-x64"].files,
3307 Some(vec![PathBuf::from("bench"), PathBuf::from("proof")])
3308 );
3309 }
3310
3311 #[test]
3312 fn asset_files_reject_what_they_cannot_pack() {
3313 let cases = [
3314 (
3315 "dir without files",
3316 indoc! {"
3317 assets:
3318 dir: out
3319 linux-x64: {}
3320 "},
3321 "must come with files",
3322 ),
3323 (
3324 "dir with no files",
3325 indoc! {"
3326 assets:
3327 dir: out
3328 files: []
3329 linux-x64: {}
3330 "},
3331 "must come with files",
3332 ),
3333 (
3334 "files without dir",
3335 indoc! {"
3336 assets:
3337 files: [demo]
3338 linux-x64: {}
3339 "},
3340 "must come with dir",
3341 ),
3342 (
3343 "binary beside files",
3344 indoc! {"
3345 assets:
3346 binary: out/{bin}
3347 dir: out
3348 files: [demo]
3349 linux-x64: {}
3350 "},
3351 "list the binary in files",
3352 ),
3353 (
3354 "dir outside the repo",
3355 indoc! {"
3356 assets:
3357 dir: /tmp
3358 files: [demo]
3359 linux-x64: {}
3360 "},
3361 "must stay inside the repository",
3362 ),
3363 (
3364 "a file outside the repo",
3365 indoc! {"
3366 assets:
3367 dir: out
3368 files: [../secret]
3369 linux-x64: {}
3370 "},
3371 "must stay inside the repository",
3372 ),
3373 ];
3374 for (scenario, section, expected) in cases {
3375 let error = load(&assets(section)).expect_err(scenario);
3376 assert!(
3377 format!("{error:#}").contains(expected),
3378 "{scenario}: {error:#}"
3379 );
3380 }
3381 }
3382
3383 #[test]
3384 fn asset_target_files_reject_what_they_cannot_pack() {
3385 let cases = [
3386 (
3387 "target files without dir",
3388 indoc! {"
3389 assets:
3390 linux-x64:
3391 files: [demo]
3392 "},
3393 "assets.linux-x64.files: must come with assets.dir",
3394 ),
3395 (
3396 "an empty target list",
3397 indoc! {"
3398 assets:
3399 dir: out
3400 files: [demo]
3401 linux-x64:
3402 files: []
3403 "},
3404 "assets.linux-x64.files: must declare at least one file",
3405 ),
3406 (
3407 "binary beside target files",
3408 indoc! {"
3409 assets:
3410 binary: out/{bin}
3411 darwin-arm64: {}
3412 linux-x64:
3413 files: [demo]
3414 "},
3415 "assets.binary: must be omitted when assets.linux-x64.files lists what the tarball contains",
3416 ),
3417 (
3418 "a target file outside the repo",
3419 indoc! {"
3420 assets:
3421 dir: out
3422 linux-x64:
3423 files: [../secret]
3424 "},
3425 "assets.linux-x64.files[0]: must stay inside the repository",
3426 ),
3427 (
3428 "dir with a target that lists no files",
3429 indoc! {"
3430 assets:
3431 dir: out
3432 darwin-arm64: {}
3433 linux-x64:
3434 files: [demo]
3435 "},
3436 "must come with files",
3437 ),
3438 ];
3439 for (scenario, section, expected) in cases {
3440 let error = load(&assets(section)).expect_err(scenario);
3441 assert!(
3442 format!("{error:#}").contains(expected),
3443 "{scenario}: {error:#}"
3444 );
3445 }
3446 }
3447
3448 #[test]
3452 fn an_asset_target_problem_sits_on_its_own_line() {
3453 let error = load(&assets(indoc! {"
3454 assets:
3455 linux-x64:
3456 files: [demo]
3457 "}))
3458 .expect_err("target files without dir");
3459 assert!(
3460 format!("{error:#}")
3461 .contains(".ctl/ver.yaml:6:12: assets.linux-x64.files: must come with assets.dir"),
3462 "{error:#}"
3463 );
3464 }
3465
3466 const ONE_PACKAGE: &str = indoc! {"
3467 packages:
3468 - name: demo
3469 path: Cargo.toml
3470 "};
3471
3472 #[test]
3473 fn a_proposal_left_out_is_todays_title_and_message() {
3474 let config = load(ONE_PACKAGE).unwrap();
3475 assert_eq!(config.proposal.title(), "chore(release): version packages");
3476 assert_eq!(
3477 config.proposal.commit_message(),
3478 "chore(release): version packages"
3479 );
3480 }
3481
3482 #[test]
3483 fn a_title_alone_is_also_the_commit_message() {
3484 let config = load(&formatdoc! {"
3485 {ONE_PACKAGE}proposal:
3486 title: 'chore: release'
3487 "})
3488 .unwrap();
3489 assert_eq!(config.proposal.title(), "chore: release");
3490 assert_eq!(config.proposal.commit_message(), "chore: release");
3491 }
3492
3493 #[test]
3494 fn an_empty_title_and_message_are_unset() {
3495 let config = load(&formatdoc! {"
3496 {ONE_PACKAGE}proposal:
3497 title: ''
3498 commit_message: ''
3499 "})
3500 .unwrap();
3501 assert_eq!(config.proposal.title(), "chore(release): version packages");
3502 assert_eq!(
3503 config.proposal.commit_message(),
3504 "chore(release): version packages"
3505 );
3506 }
3507
3508 #[test]
3509 fn a_commit_message_differs_from_the_title() {
3510 let config = load(&formatdoc! {"
3511 {ONE_PACKAGE}proposal:
3512 title: 'chore: release'
3513 commit_message: 'chore: release [skip ci]'
3514 "})
3515 .unwrap();
3516 assert_eq!(config.proposal.title(), "chore: release");
3517 assert_eq!(config.proposal.commit_message(), "chore: release [skip ci]");
3518 }
3519
3520 #[test]
3521 fn a_version_label_is_refused_with_what_to_do() {
3522 for value in [" release", "", " ~", " null"] {
3523 let error = load(&formatdoc! {"
3524 {ONE_PACKAGE}prepare:
3525 version_label:{value}
3526 "})
3527 .unwrap_err();
3528 let error = format!("{error:#}");
3529 assert!(
3530 error.contains("prepare.version_label is removed"),
3531 "{value:?}: {error}"
3532 );
3533 assert!(error.contains("no longer labeled"), "{value:?}: {error}");
3534 assert!(error.contains("delete this key"), "{value:?}: {error}");
3535 }
3536 }
3537
3538 #[test]
3541 fn an_unknown_key_under_a_package_fails() {
3542 for (line, key) in [
3543 ("publsher: none", "publsher"),
3544 ("foramt: toml", "foramt"),
3545 ("keys: [package.version]\n kes: [x]", "kes"),
3546 ] {
3547 let error = load(&formatdoc! {"
3548 packages:
3549 - name: demo
3550 path: Cargo.toml
3551 {line}
3552 "})
3553 .unwrap_err();
3554 let error = format!("{error:#}");
3555 assert!(error.contains(key), "{line}: {error}");
3556 assert!(error.contains("\"demo\""), "{line}: {error}");
3557 }
3558 load(indoc! {"
3559 packages:
3560 - name: demo
3561 path: Cargo.toml
3562 format: toml
3563 keys: [package.version]
3564 publisher: none
3565 "})
3566 .unwrap();
3567 }
3568
3569 #[test]
3570 fn an_unknown_key_under_a_pin_fails() {
3571 let error = load(&formatdoc! {"
3572 {ONE_PACKAGE}pins:
3573 - file: README.md
3574 package: demo
3575 tool: github:acme/demo
3576 pattern: [readme]
3577 "})
3578 .unwrap_err();
3579 assert!(format!("{error:#}").contains("pattern"), "{error:#}");
3580 }
3581
3582 #[test]
3583 fn an_unknown_key_under_a_pattern_fails() {
3584 let error = load(&formatdoc! {"
3585 {ONE_PACKAGE}patterns:
3586 readme:
3587 match: 'demo@{{version}} in CI'
3588 ocurrences: many
3589 pins:
3590 - file: README.md
3591 package: demo
3592 patterns: [readme]
3593 "})
3594 .unwrap_err();
3595 assert!(format!("{error:#}").contains("ocurrences"), "{error:#}");
3596 }
3597
3598 #[test]
3599 fn an_unknown_key_under_prepare_fails() {
3600 let error = load(&formatdoc! {"
3601 {ONE_PACKAGE}prepare:
3602 stages: [docs]
3603 "})
3604 .unwrap_err();
3605 assert!(format!("{error:#}").contains("stages"), "{error:#}");
3606 }
3607
3608 #[test]
3609 fn an_unknown_key_under_proposal_fails() {
3610 let error = load(&formatdoc! {"
3611 {ONE_PACKAGE}proposal:
3612 label: release
3613 "})
3614 .unwrap_err();
3615 assert!(format!("{error:#}").contains("label"), "{error:#}");
3616 }
3617
3618 #[test]
3619 fn publish_reads_options_or_a_whole_command() {
3620 let config = load(indoc! {"
3621 packages:
3622 - name: demo
3623 path: Cargo.toml
3624 publish:
3625 verify: false
3626 - name: tool
3627 path: tool/pyproject.toml
3628 publish: [uv, publish]
3629 - name: quiet
3630 path: quiet/Cargo.toml
3631 publish: []
3632 "})
3633 .unwrap();
3634 let options = config.packages[0].publish_options().unwrap();
3635 assert_eq!(options.get("verify"), Some(&serde_json::Value::Bool(false)));
3636 assert_eq!(config.packages[0].publish_command(), None);
3637 assert_eq!(
3638 config.packages[1].publish_command(),
3639 Some(["uv".to_owned(), "publish".to_owned()].as_slice())
3640 );
3641 assert_eq!(config.packages[2].publish_command(), Some([].as_slice()));
3642 }
3643
3644 #[test]
3645 fn publish_of_another_shape_names_both() {
3646 let error = load(indoc! {"
3647 packages:
3648 - name: demo
3649 path: Cargo.toml
3650 publish: fast
3651 "})
3652 .unwrap_err();
3653 assert!(
3654 format!("{error:#}").contains(
3655 "a mapping of publisher options, or a list that is the whole upload command"
3656 ),
3657 "{error:#}"
3658 );
3659 }
3660
3661 #[test]
3664 fn options_are_checked_against_the_publisher_at_load() {
3665 for (yaml, message) in [
3666 (
3667 indoc! {"
3668 packages:
3669 - name: web
3670 path: package.json
3671 publish:
3672 verify: false
3673 "},
3674 r#"package "web" publishes with bun, which has no publish options; remove publish.verify"#,
3675 ),
3676 (
3677 indoc! {"
3678 packages:
3679 - name: demo
3680 path: Cargo.toml
3681 publish:
3682 allow_dirty: true
3683 "},
3684 r#"package "demo": cargo has no publish option "allow_dirty"; its options are: verify"#,
3685 ),
3686 (
3687 indoc! {"
3688 packages:
3689 - name: demo
3690 path: Cargo.toml
3691 publish:
3692 verify: no thanks
3693 "},
3694 r#"package "demo": publish.verify is true or false"#,
3695 ),
3696 (
3697 indoc! {"
3698 publishers:
3699 cargo:
3700 argv: [cargo, publish, --workspace]
3701 packages:
3702 - name: demo
3703 path: Cargo.toml
3704 publish:
3705 verify: false
3706 "},
3707 r#"package "demo": publishers.cargo replaces the upload command, which takes no options; remove publish, or the argv"#,
3708 ),
3709 ] {
3710 let error = load(yaml).unwrap_err();
3711 assert!(format!("{error:#}").contains(message), "{error:#}");
3712 }
3713 }
3714
3715 fn with_owners(top: &str, app: &str) -> Result<Config> {
3718 load(&formatdoc! {"
3719 {top}
3720 packages:
3721 - name: core
3722 path: core/Cargo.toml
3723 - name: app
3724 path: app/Cargo.toml
3725 {app}
3726 "})
3727 }
3728
3729 #[test]
3733 fn owners_default_to_the_top_level_list() {
3734 let config = with_owners("owners: [any-victor]", "").unwrap();
3735 for name in ["core", "app"] {
3736 let package = config.find(name).unwrap();
3737 assert_eq!(
3738 config.owners_of(package),
3739 Some(["any-victor".to_owned()].as_slice()),
3740 "{name}"
3741 );
3742 }
3743 let config = with_owners("owners: [any-victor]", "owners: [any-victor, alice]").unwrap();
3744 assert_eq!(
3745 config.owners_of(config.find("app").unwrap()),
3746 Some(["any-victor".to_owned(), "alice".to_owned()].as_slice())
3747 );
3748 assert_eq!(
3749 config.owners_of(config.find("core").unwrap()),
3750 Some(["any-victor".to_owned()].as_slice())
3751 );
3752 let config = with_owners("", "").unwrap();
3753 assert_eq!(config.owners_of(config.find("app").unwrap()), None);
3754 }
3755
3756 #[test]
3759 fn an_empty_or_repeated_owners_list_fails_naming_the_field() {
3760 for (top, app, expected) in [
3761 (
3762 "owners: []",
3763 "",
3764 "owners: must list at least one crates.io login",
3765 ),
3766 (
3767 "owners: [any-victor, any-victor]",
3768 "",
3769 r#"owners: lists "any-victor" twice"#,
3770 ),
3771 (
3772 "",
3773 "owners: []",
3774 "packages[app].owners must list at least one crates.io login",
3775 ),
3776 (
3777 "owners: [any-victor]",
3778 "owners: [alice, alice]",
3779 r#"packages[app].owners lists "alice" twice"#,
3780 ),
3781 ] {
3782 let error = format!("{:#}", with_owners(top, app).unwrap_err());
3783 assert!(error.contains(expected), "{top} {app}: {error}");
3784 }
3785 }
3786
3787 #[test]
3791 fn release_workflow_is_a_workflow_file_name() {
3792 assert_eq!(load(PACKAGE).unwrap().release_workflow, "release.yml");
3793 for name in ["self-release.yml", "publish.yaml"] {
3794 let config = load(&formatdoc! {"
3795 {PACKAGE}release_workflow: {name}
3796 "})
3797 .unwrap();
3798 assert_eq!(config.release_workflow, name);
3799 }
3800 for (name, problem) in [
3801 (
3802 ".github/workflows/release.yml",
3803 "be a file name under .github/workflows/",
3804 ),
3805 (
3806 "release.toml",
3807 "name a workflow file, ending in .yml or .yaml",
3808 ),
3809 ("\"\"", "be a file name under .github/workflows/"),
3810 ] {
3811 let error = load(&formatdoc! {"
3812 {PACKAGE}release_workflow: {name}
3813 "})
3814 .unwrap_err();
3815 let error = format!("{error:#}");
3816 assert!(
3817 error.contains(&format!("release_workflow: must {problem}")),
3818 "{name}: {error}"
3819 );
3820 }
3821 }
3822
3823 #[test]
3827 fn release_checks_name_the_checks_release_runs() {
3828 assert_eq!(
3829 load(PACKAGE).unwrap().release_checks,
3830 [ReleaseCheck::Registry, ReleaseCheck::Trust]
3831 );
3832 for (list, expected) in [
3833 ("[]", [].as_slice()),
3834 ("[registry]", [ReleaseCheck::Registry].as_slice()),
3835 (
3836 "[trust, registry]",
3837 [ReleaseCheck::Trust, ReleaseCheck::Registry].as_slice(),
3838 ),
3839 ] {
3840 let config = load(&formatdoc! {"
3841 {PACKAGE}release_checks: {list}
3842 "})
3843 .unwrap();
3844 assert_eq!(config.release_checks, expected, "{list}");
3845 }
3846 let error = format!(
3847 "{:#}",
3848 load(&formatdoc! {"
3849 {PACKAGE}release_checks: [registry, registry]
3850 "})
3851 .unwrap_err()
3852 );
3853 assert!(
3854 error.contains(r#"release_checks: lists "registry" twice"#),
3855 "{error}"
3856 );
3857 let error = format!(
3858 "{:#}",
3859 load(&formatdoc! {"
3860 {PACKAGE}release_checks: [versions]
3861 "})
3862 .unwrap_err()
3863 );
3864 for name in ["release_checks", "versions", "registry", "trust"] {
3865 assert!(error.contains(name), "{name}: {error}");
3866 }
3867 }
3868}