use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::config::{AssetTarget, Assets};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub enum AssetFormat {
#[default]
TarGz,
Zip,
Raw,
}
impl AssetFormat {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::TarGz => "tar.gz",
Self::Zip => "zip",
Self::Raw => "raw",
}
}
}
impl fmt::Display for AssetFormat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for AssetFormat {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl TryFrom<String> for AssetFormat {
type Error = String;
fn try_from(word: String) -> Result<Self, Self::Error> {
match word.as_str() {
"tar.gz" => Ok(Self::TarGz),
"zip" => Ok(Self::Zip),
"raw" => Ok(Self::Raw),
other => Err(format!(
"assets format must be tar.gz, zip, or raw, not {other:?}"
)),
}
}
}
pub const RAW_FILE_PLACEHOLDERS: [&str; 6] =
["{bin}", "{version}", "{id}", "{os}", "{arch}", "{triple}"];
#[must_use]
pub fn targets_problem(targets: &BTreeMap<String, AssetTarget>) -> Option<String> {
for (id, spec) in targets {
if spec.tarball.is_some() && spec.name.is_some() {
return Some(format!(
"assets.{id}.tarball cannot be set beside name; use name"
));
}
if spec.tarball.is_some() && spec.format != AssetFormat::TarGz {
return Some(format!(
"assets.{id}.tarball only applies to format: tar.gz; use name instead"
));
}
if spec.format == AssetFormat::Raw {
if spec.files.is_some() {
return Some(format!(
"assets.{id}.files cannot be set when format is raw; use file instead"
));
}
if !spec.external && spec.file.is_none() {
return Some(format!(
"assets.{id}.file is required when format is raw and external is false"
));
}
if spec.external && spec.file.is_none() && spec.name.is_none() {
return Some(format!(
"assets.{id}.name is required when format is raw, external is true, and file is omitted"
));
}
} else if spec.file.is_some() {
return Some(format!("assets.{id}.file only applies when format is raw"));
}
if let Some(file) = &spec.file {
let text = file.to_string_lossy();
let rest = RAW_FILE_PLACEHOLDERS
.iter()
.fold(text.to_string(), |rest, placeholder| {
rest.replace(placeholder, "")
});
if rest.contains(['{', '}']) {
return Some(format!(
"assets.{id}.file has a '{{' or '}}' that is not {}",
RAW_FILE_PLACEHOLDERS.join(", ")
));
}
if text.ends_with('/') || file.file_name().is_none() {
return Some(format!(
"assets.{id}.file must name a file, not a directory"
));
}
}
}
None
}
pub const DEFAULT_TARBALL: &str = "{bin}_{version}_{os}_{arch}.tar.gz";
pub const DEFAULT_ZIP: &str = "{bin}_{version}_{os}_{arch}.zip";
pub const GENERATED_PLACEHOLDERS: [&str; 5] = ["{bin}", "{id}", "{os}", "{arch}", "{triple}"];
#[derive(Clone, Copy, Debug)]
pub struct DeclaredTargets {
pub id: &'static str,
pub labels: &'static [&'static str],
pub os: &'static str,
pub arch: &'static str,
pub triple: &'static str,
}
pub const KNOWN: &[DeclaredTargets] = &[
DeclaredTargets {
id: "darwin-arm64",
labels: &["xcode-27"],
os: "darwin",
arch: "arm64",
triple: "aarch64-apple-darwin",
},
DeclaredTargets {
id: "linux-x64",
labels: &["ubuntu-26.04"],
os: "linux",
arch: "x64",
triple: "x86_64-unknown-linux-gnu",
},
];
#[must_use]
pub fn known_ids() -> String {
KNOWN
.iter()
.map(|known| known.id)
.collect::<Vec<_>>()
.join(", ")
}
#[must_use]
pub fn tarball_name(
template: Option<&str>,
bin: &str,
version: &str,
os: &str,
arch: &str,
) -> String {
let os = if os == "darwin" { "macos" } else { os };
template
.unwrap_or(DEFAULT_TARBALL)
.replace("{bin}", bin)
.replace("{version}", version)
.replace("{os}", os)
.replace("{arch}", arch)
}
#[must_use]
pub fn asset_name(
id: &str,
spec: &AssetTarget,
bin: &str,
version: &str,
os: Option<&str>,
arch: Option<&str>,
triple: Option<&str>,
) -> Option<String> {
let mapped_os = os.map(|value| if value == "darwin" { "macos" } else { value });
if let Some(template) = spec.name.as_deref().or(spec.tarball.as_deref()) {
if (template.contains("{os}") && mapped_os.is_none())
|| (template.contains("{arch}") && arch.is_none())
{
return None;
}
return Some(
template
.replace("{bin}", bin)
.replace("{version}", version)
.replace("{id}", id)
.replace("{os}", mapped_os.unwrap_or(""))
.replace("{arch}", arch.unwrap_or("")),
);
}
match spec.format {
AssetFormat::TarGz | AssetFormat::Zip => {
let (Some(os), Some(arch)) = (mapped_os, arch) else {
return None;
};
let default_template = if spec.format == AssetFormat::Zip {
DEFAULT_ZIP
} else {
DEFAULT_TARBALL
};
Some(
default_template
.replace("{bin}", bin)
.replace("{version}", version)
.replace("{os}", os)
.replace("{arch}", arch),
)
}
AssetFormat::Raw => {
let raw_file = spec.file.as_ref()?.to_str()?;
if (raw_file.contains("{os}") && os.is_none())
|| (raw_file.contains("{arch}") && arch.is_none())
|| (raw_file.contains("{triple}") && triple.is_none())
{
return None;
}
let expanded = raw_file
.replace("{bin}", bin)
.replace("{version}", version)
.replace("{id}", id)
.replace("{os}", os.unwrap_or(""))
.replace("{arch}", arch.unwrap_or(""))
.replace("{triple}", triple.unwrap_or(""));
Path::new(&expanded)
.file_name()
.and_then(|name| name.to_str())
.map(str::to_owned)
}
}
}
#[must_use]
pub fn platform<'a>(id: &str, spec: &'a AssetTarget) -> Option<(&'a str, &'a str)> {
let known = KNOWN.iter().find(|known| known.id == id);
let os = spec.os.as_deref().or(known.map(|known| known.os))?;
let arch = spec.arch.as_deref().or(known.map(|known| known.arch))?;
Some((os, arch))
}
#[must_use]
pub fn triple<'a>(id: &str, spec: &'a AssetTarget) -> Option<&'a str> {
let known = KNOWN.iter().find(|known| known.id == id);
spec.triple.as_deref().or(known.map(|known| known.triple))
}
#[must_use]
pub fn asset_name_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
let mut named: BTreeMap<String, &str> = BTreeMap::new();
for (id, spec) in &assets.targets {
let known = KNOWN.iter().find(|known| known.id == id);
let os = spec.os.as_deref().or(known.map(|known| known.os));
let arch = spec.arch.as_deref().or(known.map(|known| known.arch));
let triple = spec.triple.as_deref().or(known.map(|known| known.triple));
let Some(name) = asset_name(id, spec, bin, "{version}", os, arch, triple) else {
continue;
};
if let Some(first) = named.insert(name.clone(), id) {
return Some((first.to_owned(), id.clone(), name));
}
}
None
}
#[must_use]
pub fn tarball_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
asset_name_clash(assets, bin)
}
#[must_use]
pub fn generated_problem(assets: &Assets, bin: &str) -> Option<String> {
if !assets.generated.is_empty()
&& !assets.targets.is_empty()
&& assets
.targets
.values()
.all(|target| target.format == AssetFormat::Raw)
{
return Some(
"assets.generated cannot be set when every assets target uses format: raw".to_owned(),
);
}
for (at, entry) in assets.generated.iter().enumerate() {
let rest = GENERATED_PLACEHOLDERS
.iter()
.fold(entry.path.clone(), |rest, placeholder| {
rest.replace(placeholder, "")
});
if rest.contains(['{', '}']) {
return Some(format!(
"assets.generated[{at}].path {:?} has a '{{' or '}}' that is not {}",
entry.path,
GENERATED_PLACEHOLDERS.join(", ")
));
}
}
for (id, spec) in &assets.targets {
if spec.format == AssetFormat::Raw {
continue;
}
let (Some((os, arch)), Some(triple)) = (platform(id, spec), triple(id, spec)) else {
continue;
};
let ctx = BTreeMap::from([
("bin", bin.to_owned()),
("id", id.clone()),
("os", os.to_owned()),
("arch", arch.to_owned()),
("triple", triple.to_owned()),
]);
let packed: Vec<String> = if assets.dir.is_some() {
spec.files
.as_ref()
.unwrap_or(&assets.files)
.iter()
.map(|file| expand_one(&file.display().to_string(), &ctx))
.collect()
} else {
vec![bin.to_owned()]
};
let mut seen: Vec<(usize, Vec<String>)> = Vec::new();
for (at, entry) in assets.generated.iter().enumerate() {
let expanded = expand_one(&entry.path, &ctx);
let named = format!("assets.generated[{at}].path {:?} (target {id})", entry.path);
if let Some(reason) = unsafe_path(&expanded) {
return Some(format!("{named} {reason}"));
}
let parts = plain_parts(&expanded);
if parts.is_empty() {
return Some(format!("{named} names the tarball's directory, not a file"));
}
if let Some((other, _)) = seen.iter().find(|(_, taken)| overlaps(taken, &parts)) {
return Some(format!(
"{named} equals, contains, or sits under assets.generated[{other}].path: each names its own file"
));
}
if let Some(file) = packed.iter().find(|file| {
let taken = plain_parts(file);
!taken.is_empty() && overlaps(&taken, &parts)
}) {
return Some(format!(
"{named} would replace {file:?}, which the tarball already packs"
));
}
seen.push((at, parts));
}
}
None
}
#[must_use]
pub fn expand_one(part: &str, ctx: &BTreeMap<&str, String>) -> String {
let mut out = part.to_owned();
for (key, value) in ctx {
out = out.replace(&format!("{{{key}}}"), value);
}
out
}
#[must_use]
pub fn unsafe_path(path: &str) -> Option<String> {
if path.is_empty() {
return Some("is empty".to_owned());
}
if path.starts_with('/') {
return Some("is absolute: write it relative to the tarball's directory".to_owned());
}
if path.ends_with('/') {
return Some("ends in /: it names a directory, not a file".to_owned());
}
let mut parts = path.split('/');
if parts.clone().any(|part| part == "..") {
return Some("has a .. component, which leaves the tarball's directory".to_owned());
}
if let Some(part) = parts.clone().find(|part| part.starts_with('-')) {
return Some(format!(
"has the component {part:?}, which starts with '-': tar would read it as an option"
));
}
parts
.find(|part| {
!part
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
})
.map(|part| {
format!(
"has the component {part:?}: use only ASCII letters, digits, '.', '_', and '-', so no spelling names one file two ways"
)
})
}
#[must_use]
pub fn components(path: &str) -> Vec<&str> {
path.split('/')
.filter(|part| !part.is_empty() && *part != ".")
.collect()
}
#[must_use]
pub fn plain_parts(path: &str) -> Vec<String> {
components(path)
.into_iter()
.map(str::to_ascii_lowercase)
.collect()
}
#[must_use]
pub fn overlaps(left: &[String], right: &[String]) -> bool {
left.starts_with(right) || right.starts_with(left)
}