use std::collections::BTreeMap;
use crate::config::{AssetTarget, Assets};
pub const DEFAULT_TARBALL: &str = "{bin}_{version}_{os}_{arch}.tar.gz";
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 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 tarball_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
let mut named: BTreeMap<String, &str> = BTreeMap::new();
for (id, spec) in &assets.targets {
let Some((os, arch)) = platform(id, spec) else {
continue;
};
let name = tarball_name(spec.tarball.as_deref(), bin, "{version}", os, arch);
if let Some(first) = named.insert(name.clone(), id) {
return Some((first.to_owned(), id.clone(), name));
}
}
None
}
#[must_use]
pub fn generated_problem(assets: &Assets, bin: &str) -> Option<String> {
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 {
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)
}