use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fmt, fs};
use anyhow::{Context, Result, ensure};
use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::value::MapAccessDeserializer;
use serde::de::{MapAccess, Visitor};
use serde::{Deserialize, Serialize, de};
use super::validate_assets::{
a_packslip_table, a_tarball_name, an_asset_name, asset_targets_are_sound, at_least_one_target,
binary_is_not_beside_files, dir_comes_with_files, every_key_is_one_plain_name,
files_come_with_dir, generated_paths_are_sound, one_archive_per_target, one_plain_name,
only_placeholders, runner_is_declared, target_files_come_with_dir,
};
use super::{ArtifactTable, Config};
pub use crate::asset_rules::AssetFormat;
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Runner {
#[garde(custom(at_least_one("label")))]
pub labels: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Job {
pub runners: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Assets {
pub bin: Option<String>,
pub prepare: Option<Vec<String>>,
pub build: Option<Vec<String>>,
#[garde(custom(binary_is_not_beside_files))]
pub binary: Option<String>,
#[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
pub dir: Option<PathBuf>,
#[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
pub files: Vec<PathBuf>,
#[garde(dive, custom(generated_paths_are_sound))]
pub generated: Vec<Generated>,
#[garde(dive, custom(asset_targets_are_sound))]
pub targets: BTreeMap<String, AssetTarget>,
}
impl Assets {
pub const SETTINGS: [&'static str; 7] = [
"bin",
"prepare",
"build",
"binary",
"dir",
"files",
"generated",
];
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Generated {
pub path: String,
#[garde(custom(at_least_one("argument")))]
pub run: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct AssetTarget {
pub runner: Option<String>,
pub os: Option<String>,
pub arch: Option<String>,
pub triple: Option<String>,
#[serde(default)]
pub format: AssetFormat,
pub prepare: Option<Vec<String>>,
pub build: Option<Vec<String>>,
#[garde(inner(custom(an_asset_name)))]
pub name: Option<String>,
#[garde(inner(custom(a_tarball_name)))]
pub tarball: Option<String>,
#[serde(default)]
#[garde(inner(custom(inside_the_repo)))]
pub file: Option<PathBuf>,
#[serde(default)]
pub external: bool,
#[serde(default)]
#[garde(
custom(target_files_come_with_dir),
inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
)]
pub files: Option<Vec<PathBuf>>,
#[serde(default)]
#[garde(custom(a_packslip_table))]
pub packslip: ArtifactTable,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Packslip {
#[garde(inner(custom(inside_the_repo)))]
pub manifest: Option<PathBuf>,
pub attest: Attest,
#[garde(inner(custom(a_public_key_line)))]
pub pubkey: Option<String>,
}
fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
if line.trim().is_empty() {
return Err(garde::Error::new(
"cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
));
}
Ok(())
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PackslipKeys {
#[serde(default)]
manifest: Option<PathBuf>,
#[serde(default)]
attest: Attest,
#[serde(default)]
pubkey: Option<String>,
}
impl<'de> Deserialize<'de> for Packslip {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(PackslipVisitor)
}
}
struct PackslipVisitor;
impl<'de> Visitor<'de> for PackslipVisitor {
type Value = Packslip;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
Err(E::custom(format!(
"packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
)))
}
fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
Ok(Packslip {
manifest: keys.manifest,
attest: keys.attest,
pubkey: keys.pubkey,
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attest {
#[default]
True,
Link,
False,
}
impl Attest {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::True => "true",
Self::Link => "link",
Self::False => "false",
}
}
}
impl fmt::Display for Attest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Attest {
type Err = String;
fn from_str(word: &str) -> Result<Self, String> {
match word {
"true" => Ok(Self::True),
"link" => Ok(Self::Link),
"false" => Ok(Self::False),
other => Err(format!(
"packslip.attest must be true, link, or false, not {other:?}"
)),
}
}
}
impl Serialize for Attest {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for Attest {
fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_any(AttestVisitor)
}
}
struct AttestVisitor;
impl Visitor<'_> for AttestVisitor {
type Value = Attest;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("packslip.attest: true, link, or false")
}
fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
Ok(if v { Attest::True } else { Attest::False })
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
v.parse().map_err(E::custom)
}
}
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Vendored {
#[garde(
custom(cannot_be_empty("it names the release and the archives")),
custom(one_plain_name)
)]
pub version: String,
#[serde(default = "Vendored::default_tag")]
#[garde(
custom(cannot_be_empty("it names the release")),
custom(only_placeholders(&["{name}", "{version}"]))
)]
pub tag: String,
#[serde(default = "Vendored::default_archive")]
#[garde(
custom(one_archive_per_target),
custom(only_placeholders(&["{name}", "{version}", "{id}"]))
)]
pub archive: String,
#[serde(default)]
pub build: Vec<String>,
#[garde(custom(inside_the_repo))]
pub dir: PathBuf,
#[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
pub files: Vec<PathBuf>,
#[garde(inner(custom(inside_the_repo)))]
pub notes: Option<PathBuf>,
#[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
pub targets: BTreeMap<String, VendoredTarget>,
}
impl Vendored {
fn default_tag() -> String {
"{name}-{version}".to_owned()
}
fn default_archive() -> String {
"{name}-{version}-{id}.tar.gz".to_owned()
}
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct VendoredTarget {
#[garde(custom(runner_is_declared))]
pub runner: String,
}
pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
let text = fs::read_to_string(path)
.with_context(|| format!("packslip.manifest: read {}", named.display()))?;
let document = text
.parse::<toml_edit::DocumentMut>()
.with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
ensure!(
!document.contains_key("artifact"),
"packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
named.display()
);
Ok(document)
}