devimg-core 0.2.8

Core image pipeline logic for devimg
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::{DevimgError, Result};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Manifest {
    #[serde(default = "default_version")]
    pub version: u32,
    #[serde(default = "unknown_generated_at")]
    pub generated_at: String,
    pub config_path: String,
    pub config_hash: String,
    pub outputs: Vec<ManifestOutput>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestOutput {
    pub source_path: String,
    pub source_hash: String,
    pub source_width: u32,
    pub source_height: u32,
    pub source_bytes: u64,
    pub output_path: String,
    pub preset: String,
    #[serde(default = "unknown_fit")]
    pub fit: String,
    pub width: u32,
    pub height: u32,
    pub format: String,
    pub bytes: u64,
    pub hash: String,
    pub operation_hash: String,
}

impl Manifest {
    pub fn new(config_path: String, config_hash: String, outputs: Vec<ManifestOutput>) -> Self {
        Self {
            version: default_version(),
            generated_at: generated_at(),
            config_path,
            config_hash,
            outputs,
        }
    }

    pub fn source_bytes_total(&self) -> u64 {
        let mut seen = Vec::<(&str, u64)>::new();
        for output in &self.outputs {
            if !seen.iter().any(|(path, _)| *path == output.source_path) {
                seen.push((&output.source_path, output.source_bytes));
            }
        }
        seen.iter().map(|(_, bytes)| *bytes).sum()
    }

    pub fn output_bytes_total(&self) -> u64 {
        self.outputs.iter().map(|output| output.bytes).sum()
    }
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ManifestExport {
    pub version: u32,
    pub generated_at: String,
    pub config_hash: String,
    pub sources: Vec<ManifestExportSource>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ManifestExportSource {
    pub source_path: String,
    pub source_hash: String,
    pub source_width: u32,
    pub source_height: u32,
    pub source_bytes: u64,
    pub variants: Vec<ManifestExportVariant>,
}

#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ManifestExportVariant {
    pub src: String,
    pub output_path: String,
    pub preset: String,
    pub fit: String,
    pub width: u32,
    pub height: u32,
    pub format: String,
    pub bytes: u64,
    pub hash: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ManifestExportOptions {
    pub strip_prefix: Option<String>,
    pub url_prefix: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ManifestTypescriptOptions {
    pub include_helpers: bool,
}

pub fn export_manifest(manifest: &Manifest, options: &ManifestExportOptions) -> ManifestExport {
    let mut sources = BTreeMap::<String, ManifestExportSource>::new();
    for output in &manifest.outputs {
        let source = sources
            .entry(output.source_path.clone())
            .or_insert_with(|| ManifestExportSource {
                source_path: output.source_path.clone(),
                source_hash: output.source_hash.clone(),
                source_width: output.source_width,
                source_height: output.source_height,
                source_bytes: output.source_bytes,
                variants: Vec::new(),
            });
        source.variants.push(ManifestExportVariant {
            src: manifest_variant_src(&output.output_path, options),
            output_path: output.output_path.clone(),
            preset: output.preset.clone(),
            fit: output.fit.clone(),
            width: output.width,
            height: output.height,
            format: output.format.clone(),
            bytes: output.bytes,
            hash: output.hash.clone(),
        });
    }

    ManifestExport {
        version: manifest.version,
        generated_at: manifest.generated_at.clone(),
        config_hash: manifest.config_hash.clone(),
        sources: sources.into_values().collect(),
    }
}

pub fn manifest_export_to_json(manifest: &Manifest, options: &ManifestExportOptions) -> String {
    let document = export_manifest(manifest, options);
    serde_json::to_string_pretty(&document).expect("manifest export serialization cannot fail")
        + "\n"
}

pub fn manifest_export_to_typescript(
    manifest: &Manifest,
    options: &ManifestExportOptions,
) -> String {
    manifest_export_to_typescript_with_options(
        manifest,
        options,
        &ManifestTypescriptOptions::default(),
    )
}

pub fn manifest_export_to_typescript_with_options(
    manifest: &Manifest,
    options: &ManifestExportOptions,
    typescript_options: &ManifestTypescriptOptions,
) -> String {
    export_to_typescript(&export_manifest(manifest, options), typescript_options)
}

pub fn write_manifest(path: &Path, manifest: &Manifest) -> Result<()> {
    path.parent().map_or(Ok(()), |parent| {
        fs::create_dir_all(parent).map_err(|source| DevimgError::io(parent, source))
    })?;
    write_manifest_json(path, manifest_to_json(manifest))
}

pub fn read_manifest(path: &Path) -> Result<Manifest> {
    let raw = fs::read_to_string(path).map_err(|source| DevimgError::io(path, source))?;
    parse_manifest_json(path, &raw)
}

fn write_manifest_json(path: &Path, json: String) -> Result<()> {
    match fs::write(path, json) {
        Ok(()) => Ok(()),
        Err(source) => Err(DevimgError::io(path, source)),
    }
}

fn parse_manifest_json(path: &Path, raw: &str) -> Result<Manifest> {
    match serde_json::from_str(raw) {
        Ok(manifest) => Ok(manifest),
        Err(source) => Err(DevimgError::config(
            path,
            format!("invalid manifest JSON: {source}"),
        )),
    }
}

pub fn manifest_to_json(manifest: &Manifest) -> String {
    let document = ManifestDocument {
        version: manifest.version,
        generated_at: &manifest.generated_at,
        config_path: &manifest.config_path,
        config_hash: &manifest.config_hash,
        outputs: &manifest.outputs,
        totals: ManifestTotals {
            source_bytes: manifest.source_bytes_total(),
            output_bytes: manifest.output_bytes_total(),
        },
    };
    serde_json::to_string_pretty(&document).expect("manifest serialization cannot fail") + "\n"
}

#[derive(Serialize)]
struct ManifestDocument<'a> {
    version: u32,
    generated_at: &'a str,
    config_path: &'a str,
    config_hash: &'a str,
    outputs: &'a [ManifestOutput],
    totals: ManifestTotals,
}

#[derive(Serialize)]
struct ManifestTotals {
    source_bytes: u64,
    output_bytes: u64,
}

fn default_version() -> u32 {
    1
}

fn unknown_generated_at() -> String {
    "unknown".to_string()
}

fn unknown_fit() -> String {
    "unknown".to_string()
}

fn generated_at() -> String {
    let seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_secs())
        .unwrap_or(0);
    format!("unix:{seconds}")
}

fn manifest_variant_src(output_path: &str, options: &ManifestExportOptions) -> String {
    let path = output_path.replace('\\', "/");
    let stripped = options
        .strip_prefix
        .as_deref()
        .and_then(|prefix| strip_path_prefix(&path, prefix))
        .unwrap_or(path);
    join_url_prefix(&options.url_prefix, &stripped)
}

fn strip_path_prefix(path: &str, prefix: &str) -> Option<String> {
    let prefix = prefix.replace('\\', "/");
    let prefix = prefix.trim_matches('/');
    if prefix.is_empty() {
        return Some(path.trim_start_matches('/').to_string());
    }
    if path == prefix {
        return Some(String::new());
    }
    path.strip_prefix(&format!("{prefix}/"))
        .map(ToString::to_string)
}

fn join_url_prefix(url_prefix: &str, path: &str) -> String {
    let prefix = url_prefix.replace('\\', "/");
    let prefix = prefix.trim_end_matches('/');
    let path = path.trim_start_matches('/');
    if prefix.is_empty() {
        if url_prefix.starts_with('/') {
            format!("/{path}")
        } else {
            path.to_string()
        }
    } else if path.is_empty() {
        prefix.to_string()
    } else {
        format!("{prefix}/{path}")
    }
}

fn export_to_typescript(
    export: &ManifestExport,
    typescript_options: &ManifestTypescriptOptions,
) -> String {
    let mut out = String::new();
    out.push_str("// Generated by devimg. Do not edit by hand.\n");
    out.push_str("export const DEVIMG_MANIFEST = {\n");
    push_ts_number_field(&mut out, 2, "version", u64::from(export.version), true);
    push_ts_string_field(&mut out, 2, "generated_at", &export.generated_at, true);
    push_ts_string_field(&mut out, 2, "config_hash", &export.config_hash, true);
    out.push_str("  sources: [\n");
    for (source_index, source) in export.sources.iter().enumerate() {
        out.push_str("    {\n");
        push_ts_string_field(&mut out, 6, "source_path", &source.source_path, true);
        push_ts_string_field(&mut out, 6, "source_hash", &source.source_hash, true);
        push_ts_number_field(
            &mut out,
            6,
            "source_width",
            u64::from(source.source_width),
            true,
        );
        push_ts_number_field(
            &mut out,
            6,
            "source_height",
            u64::from(source.source_height),
            true,
        );
        push_ts_number_field(&mut out, 6, "source_bytes", source.source_bytes, true);
        out.push_str("      variants: [\n");
        for (variant_index, variant) in source.variants.iter().enumerate() {
            out.push_str("        {\n");
            push_ts_string_field(&mut out, 10, "src", &variant.src, true);
            push_ts_string_field(&mut out, 10, "output_path", &variant.output_path, true);
            push_ts_string_field(&mut out, 10, "preset", &variant.preset, true);
            push_ts_string_field(&mut out, 10, "fit", &variant.fit, true);
            push_ts_number_field(&mut out, 10, "width", u64::from(variant.width), true);
            push_ts_number_field(&mut out, 10, "height", u64::from(variant.height), true);
            push_ts_string_field(&mut out, 10, "format", &variant.format, true);
            push_ts_number_field(&mut out, 10, "bytes", variant.bytes, true);
            push_ts_string_field(&mut out, 10, "hash", &variant.hash, false);
            out.push_str("        }");
            if variant_index + 1 != source.variants.len() {
                out.push(',');
            }
            out.push('\n');
        }
        out.push_str("      ]\n");
        out.push_str("    }");
        if source_index + 1 != export.sources.len() {
            out.push(',');
        }
        out.push('\n');
    }
    out.push_str("  ]\n");
    out.push_str("} as const\n");
    if typescript_options.include_helpers {
        out.push_str(
            r#"
export type DevimgManifest = typeof DEVIMG_MANIFEST
export type DevimgSource = DevimgManifest["sources"][number]
export type DevimgVariant = DevimgSource["variants"][number]

export type DevimgVariantSelector = {
  source: string
  preset?: string
  format?: string
  width?: number
  minWidth?: number
}

export function findDevimgSource(sourcePath: string): DevimgSource | undefined {
  return DEVIMG_MANIFEST.sources.find((source) => source.source_path === sourcePath)
}

export function listDevimgVariants(sourcePath: string): readonly DevimgVariant[] {
  return findDevimgSource(sourcePath)?.variants ?? []
}

export function findDevimgVariant(selector: DevimgVariantSelector): DevimgVariant | undefined {
  let best: DevimgVariant | undefined
  for (const variant of listDevimgVariants(selector.source)) {
    if (selector.preset !== undefined && variant.preset !== selector.preset) {
      continue
    }
    if (selector.format !== undefined && variant.format !== selector.format) {
      continue
    }
    if (selector.width !== undefined && variant.width !== selector.width) {
      continue
    }
    if (selector.minWidth !== undefined && variant.width < selector.minWidth) {
      continue
    }
    if (best === undefined || variant.width < best.width) {
      best = variant
    }
  }
  if (best !== undefined) {
    return best
  }
  if (selector.minWidth === undefined || selector.width !== undefined) {
    return undefined
  }
  for (const variant of listDevimgVariants(selector.source)) {
    if (selector.preset !== undefined && variant.preset !== selector.preset) {
      continue
    }
    if (selector.format !== undefined && variant.format !== selector.format) {
      continue
    }
    if (best === undefined || variant.width > best.width) {
      best = variant
    }
  }
  return best
}
"#,
        );
    }
    out
}

fn push_ts_string_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
    let value = serde_json::to_string(value).expect("string serialization cannot fail");
    push_ts_field(out, indent, key, &value, comma);
}

fn push_ts_number_field(out: &mut String, indent: usize, key: &str, value: u64, comma: bool) {
    push_ts_field(out, indent, key, &value.to_string(), comma);
}

fn push_ts_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
    let prefix = " ".repeat(indent);
    let suffix = if comma { "," } else { "" };
    let line = format!("{prefix}{key}: {value}{suffix}");
    if key == "output_path" && line.len() > 100 {
        out.push_str(&format!("{prefix}{key}:\n{prefix}  {value}{suffix}\n"));
    } else {
        out.push_str(&line);
        out.push('\n');
    }
}

#[cfg(test)]
#[path = "manifest_tests.rs"]
mod tests;