Skip to main content

devimg_core/
manifest.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::Path;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use serde::{Deserialize, Serialize};
7
8use crate::{DevimgError, Result};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Manifest {
12    #[serde(default = "default_version")]
13    pub version: u32,
14    #[serde(default = "unknown_generated_at")]
15    pub generated_at: String,
16    pub config_path: String,
17    pub config_hash: String,
18    pub outputs: Vec<ManifestOutput>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct ManifestOutput {
23    pub source_path: String,
24    pub source_hash: String,
25    pub source_width: u32,
26    pub source_height: u32,
27    pub source_bytes: u64,
28    pub output_path: String,
29    pub preset: String,
30    #[serde(default = "unknown_fit")]
31    pub fit: String,
32    pub width: u32,
33    pub height: u32,
34    pub format: String,
35    pub bytes: u64,
36    pub hash: String,
37    pub operation_hash: String,
38}
39
40impl Manifest {
41    pub fn new(config_path: String, config_hash: String, outputs: Vec<ManifestOutput>) -> Self {
42        Self {
43            version: default_version(),
44            generated_at: generated_at(),
45            config_path,
46            config_hash,
47            outputs,
48        }
49    }
50
51    pub fn source_bytes_total(&self) -> u64 {
52        let mut seen = Vec::<(&str, u64)>::new();
53        for output in &self.outputs {
54            if !seen.iter().any(|(path, _)| *path == output.source_path) {
55                seen.push((&output.source_path, output.source_bytes));
56            }
57        }
58        seen.iter().map(|(_, bytes)| *bytes).sum()
59    }
60
61    pub fn output_bytes_total(&self) -> u64 {
62        self.outputs.iter().map(|output| output.bytes).sum()
63    }
64}
65
66#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
67pub struct ManifestExport {
68    pub version: u32,
69    pub generated_at: String,
70    pub config_hash: String,
71    pub sources: Vec<ManifestExportSource>,
72}
73
74#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
75pub struct ManifestExportSource {
76    pub source_path: String,
77    pub source_hash: String,
78    pub source_width: u32,
79    pub source_height: u32,
80    pub source_bytes: u64,
81    pub variants: Vec<ManifestExportVariant>,
82}
83
84#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
85pub struct ManifestExportVariant {
86    pub src: String,
87    pub output_path: String,
88    pub preset: String,
89    pub fit: String,
90    pub width: u32,
91    pub height: u32,
92    pub format: String,
93    pub bytes: u64,
94    pub hash: String,
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct ManifestExportOptions {
99    pub strip_prefix: Option<String>,
100    pub url_prefix: String,
101}
102
103#[derive(Debug, Clone, Default, PartialEq, Eq)]
104pub struct ManifestTypescriptOptions {
105    pub include_helpers: bool,
106}
107
108pub fn export_manifest(manifest: &Manifest, options: &ManifestExportOptions) -> ManifestExport {
109    let mut sources = BTreeMap::<String, ManifestExportSource>::new();
110    for output in &manifest.outputs {
111        let source = sources
112            .entry(output.source_path.clone())
113            .or_insert_with(|| ManifestExportSource {
114                source_path: output.source_path.clone(),
115                source_hash: output.source_hash.clone(),
116                source_width: output.source_width,
117                source_height: output.source_height,
118                source_bytes: output.source_bytes,
119                variants: Vec::new(),
120            });
121        source.variants.push(ManifestExportVariant {
122            src: manifest_variant_src(&output.output_path, options),
123            output_path: output.output_path.clone(),
124            preset: output.preset.clone(),
125            fit: output.fit.clone(),
126            width: output.width,
127            height: output.height,
128            format: output.format.clone(),
129            bytes: output.bytes,
130            hash: output.hash.clone(),
131        });
132    }
133
134    ManifestExport {
135        version: manifest.version,
136        generated_at: manifest.generated_at.clone(),
137        config_hash: manifest.config_hash.clone(),
138        sources: sources.into_values().collect(),
139    }
140}
141
142pub fn manifest_export_to_json(manifest: &Manifest, options: &ManifestExportOptions) -> String {
143    let document = export_manifest(manifest, options);
144    serde_json::to_string_pretty(&document).expect("manifest export serialization cannot fail")
145        + "\n"
146}
147
148pub fn manifest_export_to_typescript(
149    manifest: &Manifest,
150    options: &ManifestExportOptions,
151) -> String {
152    manifest_export_to_typescript_with_options(
153        manifest,
154        options,
155        &ManifestTypescriptOptions::default(),
156    )
157}
158
159pub fn manifest_export_to_typescript_with_options(
160    manifest: &Manifest,
161    options: &ManifestExportOptions,
162    typescript_options: &ManifestTypescriptOptions,
163) -> String {
164    export_to_typescript(&export_manifest(manifest, options), typescript_options)
165}
166
167pub fn write_manifest(path: &Path, manifest: &Manifest) -> Result<()> {
168    path.parent().map_or(Ok(()), |parent| {
169        fs::create_dir_all(parent).map_err(|source| DevimgError::io(parent, source))
170    })?;
171    write_manifest_json(path, manifest_to_json(manifest))
172}
173
174pub fn read_manifest(path: &Path) -> Result<Manifest> {
175    let raw = fs::read_to_string(path).map_err(|source| DevimgError::io(path, source))?;
176    parse_manifest_json(path, &raw)
177}
178
179fn write_manifest_json(path: &Path, json: String) -> Result<()> {
180    match fs::write(path, json) {
181        Ok(()) => Ok(()),
182        Err(source) => Err(DevimgError::io(path, source)),
183    }
184}
185
186fn parse_manifest_json(path: &Path, raw: &str) -> Result<Manifest> {
187    match serde_json::from_str(raw) {
188        Ok(manifest) => Ok(manifest),
189        Err(source) => Err(DevimgError::config(
190            path,
191            format!("invalid manifest JSON: {source}"),
192        )),
193    }
194}
195
196pub fn manifest_to_json(manifest: &Manifest) -> String {
197    let document = ManifestDocument {
198        version: manifest.version,
199        generated_at: &manifest.generated_at,
200        config_path: &manifest.config_path,
201        config_hash: &manifest.config_hash,
202        outputs: &manifest.outputs,
203        totals: ManifestTotals {
204            source_bytes: manifest.source_bytes_total(),
205            output_bytes: manifest.output_bytes_total(),
206        },
207    };
208    serde_json::to_string_pretty(&document).expect("manifest serialization cannot fail") + "\n"
209}
210
211#[derive(Serialize)]
212struct ManifestDocument<'a> {
213    version: u32,
214    generated_at: &'a str,
215    config_path: &'a str,
216    config_hash: &'a str,
217    outputs: &'a [ManifestOutput],
218    totals: ManifestTotals,
219}
220
221#[derive(Serialize)]
222struct ManifestTotals {
223    source_bytes: u64,
224    output_bytes: u64,
225}
226
227fn default_version() -> u32 {
228    1
229}
230
231fn unknown_generated_at() -> String {
232    "unknown".to_string()
233}
234
235fn unknown_fit() -> String {
236    "unknown".to_string()
237}
238
239fn generated_at() -> String {
240    let seconds = SystemTime::now()
241        .duration_since(UNIX_EPOCH)
242        .map(|duration| duration.as_secs())
243        .unwrap_or(0);
244    format!("unix:{seconds}")
245}
246
247fn manifest_variant_src(output_path: &str, options: &ManifestExportOptions) -> String {
248    let path = output_path.replace('\\', "/");
249    let stripped = options
250        .strip_prefix
251        .as_deref()
252        .and_then(|prefix| strip_path_prefix(&path, prefix))
253        .unwrap_or(path);
254    join_url_prefix(&options.url_prefix, &stripped)
255}
256
257fn strip_path_prefix(path: &str, prefix: &str) -> Option<String> {
258    let prefix = prefix.replace('\\', "/");
259    let prefix = prefix.trim_matches('/');
260    if prefix.is_empty() {
261        return Some(path.trim_start_matches('/').to_string());
262    }
263    if path == prefix {
264        return Some(String::new());
265    }
266    path.strip_prefix(&format!("{prefix}/"))
267        .map(ToString::to_string)
268}
269
270fn join_url_prefix(url_prefix: &str, path: &str) -> String {
271    let prefix = url_prefix.replace('\\', "/");
272    let prefix = prefix.trim_end_matches('/');
273    let path = path.trim_start_matches('/');
274    if prefix.is_empty() {
275        if url_prefix.starts_with('/') {
276            format!("/{path}")
277        } else {
278            path.to_string()
279        }
280    } else if path.is_empty() {
281        prefix.to_string()
282    } else {
283        format!("{prefix}/{path}")
284    }
285}
286
287fn export_to_typescript(
288    export: &ManifestExport,
289    typescript_options: &ManifestTypescriptOptions,
290) -> String {
291    let mut out = String::new();
292    out.push_str("// Generated by devimg. Do not edit by hand.\n");
293    out.push_str("export const DEVIMG_MANIFEST = {\n");
294    push_ts_number_field(&mut out, 2, "version", u64::from(export.version), true);
295    push_ts_string_field(&mut out, 2, "generated_at", &export.generated_at, true);
296    push_ts_string_field(&mut out, 2, "config_hash", &export.config_hash, true);
297    out.push_str("  sources: [\n");
298    for (source_index, source) in export.sources.iter().enumerate() {
299        out.push_str("    {\n");
300        push_ts_string_field(&mut out, 6, "source_path", &source.source_path, true);
301        push_ts_string_field(&mut out, 6, "source_hash", &source.source_hash, true);
302        push_ts_number_field(
303            &mut out,
304            6,
305            "source_width",
306            u64::from(source.source_width),
307            true,
308        );
309        push_ts_number_field(
310            &mut out,
311            6,
312            "source_height",
313            u64::from(source.source_height),
314            true,
315        );
316        push_ts_number_field(&mut out, 6, "source_bytes", source.source_bytes, true);
317        out.push_str("      variants: [\n");
318        for (variant_index, variant) in source.variants.iter().enumerate() {
319            out.push_str("        {\n");
320            push_ts_string_field(&mut out, 10, "src", &variant.src, true);
321            push_ts_string_field(&mut out, 10, "output_path", &variant.output_path, true);
322            push_ts_string_field(&mut out, 10, "preset", &variant.preset, true);
323            push_ts_string_field(&mut out, 10, "fit", &variant.fit, true);
324            push_ts_number_field(&mut out, 10, "width", u64::from(variant.width), true);
325            push_ts_number_field(&mut out, 10, "height", u64::from(variant.height), true);
326            push_ts_string_field(&mut out, 10, "format", &variant.format, true);
327            push_ts_number_field(&mut out, 10, "bytes", variant.bytes, true);
328            push_ts_string_field(&mut out, 10, "hash", &variant.hash, false);
329            out.push_str("        }");
330            if variant_index + 1 != source.variants.len() {
331                out.push(',');
332            }
333            out.push('\n');
334        }
335        out.push_str("      ]\n");
336        out.push_str("    }");
337        if source_index + 1 != export.sources.len() {
338            out.push(',');
339        }
340        out.push('\n');
341    }
342    out.push_str("  ]\n");
343    out.push_str("} as const\n");
344    if typescript_options.include_helpers {
345        out.push_str(
346            r#"
347export type DevimgManifest = typeof DEVIMG_MANIFEST
348export type DevimgSource = DevimgManifest["sources"][number]
349export type DevimgVariant = DevimgSource["variants"][number]
350
351export type DevimgVariantSelector = {
352  source: string
353  preset?: string
354  format?: string
355  width?: number
356  minWidth?: number
357}
358
359export function findDevimgSource(sourcePath: string): DevimgSource | undefined {
360  return DEVIMG_MANIFEST.sources.find((source) => source.source_path === sourcePath)
361}
362
363export function listDevimgVariants(sourcePath: string): readonly DevimgVariant[] {
364  return findDevimgSource(sourcePath)?.variants ?? []
365}
366
367export function findDevimgVariant(selector: DevimgVariantSelector): DevimgVariant | undefined {
368  let best: DevimgVariant | undefined
369  for (const variant of listDevimgVariants(selector.source)) {
370    if (selector.preset !== undefined && variant.preset !== selector.preset) {
371      continue
372    }
373    if (selector.format !== undefined && variant.format !== selector.format) {
374      continue
375    }
376    if (selector.width !== undefined && variant.width !== selector.width) {
377      continue
378    }
379    if (selector.minWidth !== undefined && variant.width < selector.minWidth) {
380      continue
381    }
382    if (best === undefined || variant.width < best.width) {
383      best = variant
384    }
385  }
386  if (best !== undefined) {
387    return best
388  }
389  if (selector.minWidth === undefined || selector.width !== undefined) {
390    return undefined
391  }
392  for (const variant of listDevimgVariants(selector.source)) {
393    if (selector.preset !== undefined && variant.preset !== selector.preset) {
394      continue
395    }
396    if (selector.format !== undefined && variant.format !== selector.format) {
397      continue
398    }
399    if (best === undefined || variant.width > best.width) {
400      best = variant
401    }
402  }
403  return best
404}
405"#,
406        );
407    }
408    out
409}
410
411fn push_ts_string_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
412    let value = serde_json::to_string(value).expect("string serialization cannot fail");
413    push_ts_field(out, indent, key, &value, comma);
414}
415
416fn push_ts_number_field(out: &mut String, indent: usize, key: &str, value: u64, comma: bool) {
417    push_ts_field(out, indent, key, &value.to_string(), comma);
418}
419
420fn push_ts_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
421    let prefix = " ".repeat(indent);
422    let suffix = if comma { "," } else { "" };
423    let line = format!("{prefix}{key}: {value}{suffix}");
424    if key == "output_path" && line.len() > 100 {
425        out.push_str(&format!("{prefix}{key}:\n{prefix}  {value}{suffix}\n"));
426    } else {
427        out.push_str(&line);
428        out.push('\n');
429    }
430}
431
432#[cfg(test)]
433#[path = "manifest_tests.rs"]
434mod tests;