1use std::collections::BTreeMap;
5use std::fmt;
6use std::path::Path;
7
8use serde::{Deserialize, Serialize};
9
10use crate::config::{AssetTarget, Assets};
11
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
14#[serde(try_from = "String")]
15pub enum AssetFormat {
16 #[default]
18 TarGz,
19 Zip,
21 Raw,
23}
24
25impl AssetFormat {
26 #[must_use]
28 pub const fn as_str(self) -> &'static str {
29 match self {
30 Self::TarGz => "tar.gz",
31 Self::Zip => "zip",
32 Self::Raw => "raw",
33 }
34 }
35}
36
37impl fmt::Display for AssetFormat {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str(self.as_str())
40 }
41}
42
43impl Serialize for AssetFormat {
44 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
45 serializer.serialize_str(self.as_str())
46 }
47}
48
49impl TryFrom<String> for AssetFormat {
50 type Error = String;
51
52 fn try_from(word: String) -> Result<Self, Self::Error> {
53 match word.as_str() {
54 "tar.gz" => Ok(Self::TarGz),
55 "zip" => Ok(Self::Zip),
56 "raw" => Ok(Self::Raw),
57 other => Err(format!(
58 "assets format must be tar.gz, zip, or raw, not {other:?}"
59 )),
60 }
61 }
62}
63
64pub const RAW_FILE_PLACEHOLDERS: [&str; 6] =
66 ["{bin}", "{version}", "{id}", "{os}", "{arch}", "{triple}"];
67
68#[must_use]
71pub fn targets_problem(targets: &BTreeMap<String, AssetTarget>) -> Option<String> {
72 for (id, spec) in targets {
73 if spec.tarball.is_some() && spec.name.is_some() {
74 return Some(format!(
75 "assets.{id}.tarball cannot be set beside name; use name"
76 ));
77 }
78 if spec.tarball.is_some() && spec.format != AssetFormat::TarGz {
79 return Some(format!(
80 "assets.{id}.tarball only applies to format: tar.gz; use name instead"
81 ));
82 }
83 if spec.format == AssetFormat::Raw {
84 if spec.files.is_some() {
85 return Some(format!(
86 "assets.{id}.files cannot be set when format is raw; use file instead"
87 ));
88 }
89 if !spec.external && spec.file.is_none() {
90 return Some(format!(
91 "assets.{id}.file is required when format is raw and external is false"
92 ));
93 }
94 if spec.external && spec.file.is_none() && spec.name.is_none() {
95 return Some(format!(
96 "assets.{id}.name is required when format is raw, external is true, and file is omitted"
97 ));
98 }
99 } else if spec.file.is_some() {
100 return Some(format!("assets.{id}.file only applies when format is raw"));
101 }
102 if let Some(file) = &spec.file {
103 let text = file.to_string_lossy();
104 let rest = RAW_FILE_PLACEHOLDERS
105 .iter()
106 .fold(text.to_string(), |rest, placeholder| {
107 rest.replace(placeholder, "")
108 });
109 if rest.contains(['{', '}']) {
110 return Some(format!(
111 "assets.{id}.file has a '{{' or '}}' that is not {}",
112 RAW_FILE_PLACEHOLDERS.join(", ")
113 ));
114 }
115 if text.ends_with('/') || file.file_name().is_none() {
116 return Some(format!(
117 "assets.{id}.file must name a file, not a directory"
118 ));
119 }
120 }
121 }
122 None
123}
124
125pub const DEFAULT_TARBALL: &str = "{bin}_{version}_{os}_{arch}.tar.gz";
127
128pub const DEFAULT_ZIP: &str = "{bin}_{version}_{os}_{arch}.zip";
130
131pub const GENERATED_PLACEHOLDERS: [&str; 5] = ["{bin}", "{id}", "{os}", "{arch}", "{triple}"];
133
134#[derive(Clone, Copy, Debug)]
137pub struct DeclaredTargets {
138 pub id: &'static str,
140 pub labels: &'static [&'static str],
142 pub os: &'static str,
144 pub arch: &'static str,
146 pub triple: &'static str,
148}
149
150pub const KNOWN: &[DeclaredTargets] = &[
152 DeclaredTargets {
153 id: "darwin-arm64",
154 labels: &["xcode-27"],
155 os: "darwin",
156 arch: "arm64",
157 triple: "aarch64-apple-darwin",
158 },
159 DeclaredTargets {
160 id: "linux-x64",
161 labels: &["ubuntu-26.04"],
162 os: "linux",
163 arch: "x64",
164 triple: "x86_64-unknown-linux-gnu",
165 },
166];
167
168#[must_use]
170pub fn known_ids() -> String {
171 KNOWN
172 .iter()
173 .map(|known| known.id)
174 .collect::<Vec<_>>()
175 .join(", ")
176}
177
178#[must_use]
182pub fn tarball_name(
183 template: Option<&str>,
184 bin: &str,
185 version: &str,
186 os: &str,
187 arch: &str,
188) -> String {
189 let os = if os == "darwin" { "macos" } else { os };
190 template
191 .unwrap_or(DEFAULT_TARBALL)
192 .replace("{bin}", bin)
193 .replace("{version}", version)
194 .replace("{os}", os)
195 .replace("{arch}", arch)
196}
197
198#[must_use]
204pub fn asset_name(
205 id: &str,
206 spec: &AssetTarget,
207 bin: &str,
208 version: &str,
209 os: Option<&str>,
210 arch: Option<&str>,
211 triple: Option<&str>,
212) -> Option<String> {
213 let mapped_os = os.map(|value| if value == "darwin" { "macos" } else { value });
214 if let Some(template) = spec.name.as_deref().or(spec.tarball.as_deref()) {
215 if (template.contains("{os}") && mapped_os.is_none())
216 || (template.contains("{arch}") && arch.is_none())
217 {
218 return None;
219 }
220 return Some(
221 template
222 .replace("{bin}", bin)
223 .replace("{version}", version)
224 .replace("{id}", id)
225 .replace("{os}", mapped_os.unwrap_or(""))
226 .replace("{arch}", arch.unwrap_or("")),
227 );
228 }
229 match spec.format {
230 AssetFormat::TarGz | AssetFormat::Zip => {
231 let (Some(os), Some(arch)) = (mapped_os, arch) else {
232 return None;
233 };
234 let default_template = if spec.format == AssetFormat::Zip {
235 DEFAULT_ZIP
236 } else {
237 DEFAULT_TARBALL
238 };
239 Some(
240 default_template
241 .replace("{bin}", bin)
242 .replace("{version}", version)
243 .replace("{os}", os)
244 .replace("{arch}", arch),
245 )
246 }
247 AssetFormat::Raw => {
248 let raw_file = spec.file.as_ref()?.to_str()?;
249 if (raw_file.contains("{os}") && os.is_none())
250 || (raw_file.contains("{arch}") && arch.is_none())
251 || (raw_file.contains("{triple}") && triple.is_none())
252 {
253 return None;
254 }
255 let expanded = raw_file
256 .replace("{bin}", bin)
257 .replace("{version}", version)
258 .replace("{id}", id)
259 .replace("{os}", os.unwrap_or(""))
260 .replace("{arch}", arch.unwrap_or(""))
261 .replace("{triple}", triple.unwrap_or(""));
262 Path::new(&expanded)
263 .file_name()
264 .and_then(|name| name.to_str())
265 .map(str::to_owned)
266 }
267 }
268}
269
270#[must_use]
273pub fn platform<'a>(id: &str, spec: &'a AssetTarget) -> Option<(&'a str, &'a str)> {
274 let known = KNOWN.iter().find(|known| known.id == id);
275 let os = spec.os.as_deref().or(known.map(|known| known.os))?;
276 let arch = spec.arch.as_deref().or(known.map(|known| known.arch))?;
277 Some((os, arch))
278}
279
280#[must_use]
282pub fn triple<'a>(id: &str, spec: &'a AssetTarget) -> Option<&'a str> {
283 let known = KNOWN.iter().find(|known| known.id == id);
284 spec.triple.as_deref().or(known.map(|known| known.triple))
285}
286
287#[must_use]
290pub fn asset_name_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
291 let mut named: BTreeMap<String, &str> = BTreeMap::new();
292 for (id, spec) in &assets.targets {
293 let known = KNOWN.iter().find(|known| known.id == id);
294 let os = spec.os.as_deref().or(known.map(|known| known.os));
295 let arch = spec.arch.as_deref().or(known.map(|known| known.arch));
296 let triple = spec.triple.as_deref().or(known.map(|known| known.triple));
297 let Some(name) = asset_name(id, spec, bin, "{version}", os, arch, triple) else {
298 continue;
299 };
300 if let Some(first) = named.insert(name.clone(), id) {
301 return Some((first.to_owned(), id.clone(), name));
302 }
303 }
304 None
305}
306
307#[must_use]
310pub fn tarball_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
311 asset_name_clash(assets, bin)
312}
313
314#[must_use]
317pub fn generated_problem(assets: &Assets, bin: &str) -> Option<String> {
318 if !assets.generated.is_empty()
319 && !assets.targets.is_empty()
320 && assets
321 .targets
322 .values()
323 .all(|target| target.format == AssetFormat::Raw)
324 {
325 return Some(
326 "assets.generated cannot be set when every assets target uses format: raw".to_owned(),
327 );
328 }
329 for (at, entry) in assets.generated.iter().enumerate() {
330 let rest = GENERATED_PLACEHOLDERS
331 .iter()
332 .fold(entry.path.clone(), |rest, placeholder| {
333 rest.replace(placeholder, "")
334 });
335 if rest.contains(['{', '}']) {
336 return Some(format!(
337 "assets.generated[{at}].path {:?} has a '{{' or '}}' that is not {}",
338 entry.path,
339 GENERATED_PLACEHOLDERS.join(", ")
340 ));
341 }
342 }
343 for (id, spec) in &assets.targets {
344 if spec.format == AssetFormat::Raw {
345 continue;
346 }
347 let (Some((os, arch)), Some(triple)) = (platform(id, spec), triple(id, spec)) else {
348 continue;
349 };
350 let ctx = BTreeMap::from([
351 ("bin", bin.to_owned()),
352 ("id", id.clone()),
353 ("os", os.to_owned()),
354 ("arch", arch.to_owned()),
355 ("triple", triple.to_owned()),
356 ]);
357 let packed: Vec<String> = if assets.dir.is_some() {
358 spec.files
359 .as_ref()
360 .unwrap_or(&assets.files)
361 .iter()
362 .map(|file| expand_one(&file.display().to_string(), &ctx))
363 .collect()
364 } else {
365 vec![bin.to_owned()]
366 };
367 let mut seen: Vec<(usize, Vec<String>)> = Vec::new();
368 for (at, entry) in assets.generated.iter().enumerate() {
369 let expanded = expand_one(&entry.path, &ctx);
370 let named = format!("assets.generated[{at}].path {:?} (target {id})", entry.path);
371 if let Some(reason) = unsafe_path(&expanded) {
372 return Some(format!("{named} {reason}"));
373 }
374 let parts = plain_parts(&expanded);
375 if parts.is_empty() {
376 return Some(format!("{named} names the tarball's directory, not a file"));
377 }
378 if let Some((other, _)) = seen.iter().find(|(_, taken)| overlaps(taken, &parts)) {
379 return Some(format!(
380 "{named} equals, contains, or sits under assets.generated[{other}].path: each names its own file"
381 ));
382 }
383 if let Some(file) = packed.iter().find(|file| {
384 let taken = plain_parts(file);
385 !taken.is_empty() && overlaps(&taken, &parts)
386 }) {
387 return Some(format!(
388 "{named} would replace {file:?}, which the tarball already packs"
389 ));
390 }
391 seen.push((at, parts));
392 }
393 }
394 None
395}
396
397#[must_use]
399pub fn expand_one(part: &str, ctx: &BTreeMap<&str, String>) -> String {
400 let mut out = part.to_owned();
401 for (key, value) in ctx {
402 out = out.replace(&format!("{{{key}}}"), value);
403 }
404 out
405}
406
407#[must_use]
409pub fn unsafe_path(path: &str) -> Option<String> {
410 if path.is_empty() {
411 return Some("is empty".to_owned());
412 }
413 if path.starts_with('/') {
414 return Some("is absolute: write it relative to the tarball's directory".to_owned());
415 }
416 if path.ends_with('/') {
417 return Some("ends in /: it names a directory, not a file".to_owned());
418 }
419 let mut parts = path.split('/');
420 if parts.clone().any(|part| part == "..") {
421 return Some("has a .. component, which leaves the tarball's directory".to_owned());
422 }
423 if let Some(part) = parts.clone().find(|part| part.starts_with('-')) {
424 return Some(format!(
425 "has the component {part:?}, which starts with '-': tar would read it as an option"
426 ));
427 }
428 parts
429 .find(|part| {
430 !part
431 .chars()
432 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
433 })
434 .map(|part| {
435 format!(
436 "has the component {part:?}: use only ASCII letters, digits, '.', '_', and '-', so no spelling names one file two ways"
437 )
438 })
439}
440
441#[must_use]
444pub fn components(path: &str) -> Vec<&str> {
445 path.split('/')
446 .filter(|part| !part.is_empty() && *part != ".")
447 .collect()
448}
449
450#[must_use]
452pub fn plain_parts(path: &str) -> Vec<String> {
453 components(path)
454 .into_iter()
455 .map(str::to_ascii_lowercase)
456 .collect()
457}
458
459#[must_use]
461pub fn overlaps(left: &[String], right: &[String]) -> bool {
462 left.starts_with(right) || right.starts_with(left)
463}