use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};
use anyhow::{Result, bail, ensure};
use ctl_core::validate::{cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::{IgnoredAny, MapAccess, Visitor};
use serde::{Deserialize, Serialize, de};
use super::Config;
use super::validate::{
each_id_is_declared, no_id_is_listed_twice, non_empty_hook_argv, something_to_rewrite,
tag_template_placeholders,
};
#[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,
}
#[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",
}
}
pub(super) 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"
)
})
}
}
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(
r#"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(),
}
}
}
#[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(
r#"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),
}
pub(super) 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")]
pub(super) 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, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config as config))]
#[non_exhaustive]
pub struct PublishHooks {
#[garde(inner(custom(non_empty_hook_argv)))]
pub before: Option<Vec<String>>,
#[garde(inner(custom(non_empty_hook_argv)))]
pub after: Option<Vec<String>>,
}
#[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())
}
}