hauchiwa 0.17.0

Flexible static website generator library with incremental rebuilds and cached image optimization
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
//! # Image optimization pipeline
//!
//! Automated image processing, format conversion, and optimization.
//!
//! This module processes source images into multiple modern web formats (AVIF,
//! WebP) with configurable compression. It handles the heavy lifting of
//! encoding and content-hashing, ensuring your site serves the smallest
//! possible assets with perfect caching headers.
//!
//! ## Capabilities
//!
//! * **Format Conversion**: Automatically generate AVIF, WebP, and PNG variants from a single source.
//! * **Smart Caching**: Uses content-addressable storage; images are only re-processed if pixels change.
//! * **Metadata Extraction**: Calculates dimensions (width/height) upfront to prevent layout shifts (CLS).
//! * **Configurable Quality**: Fine-tune lossy compression or opt for lossless.
//!
//! ## Usage
//!
//! Register the loader to generate a handle containing paths to all generated
//! formats. This data is structured to easily generate HTML `<picture>`
//! elements.
//!
//! ```rust,no_run
//! use hauchiwa::{Blueprint, Many};
//! use hauchiwa::loader::image::{Image, ImageFormat, Quality};
//!
//! fn configure(config: &mut Blueprint<()>) -> Result<Many<Image>, hauchiwa::error::HauchiwaError> {
//!     // Process images
//!     let images = config.load_images()
//!         .glob("assets/photos/**/*.jpg")?
//!         // Generate AVIF for modern browsers (smaller, better quality)
//!         .format(ImageFormat::Avif(Quality::Lossy(75)))
//!         // Generate WebP as a solid fallback
//!         .format(ImageFormat::WebP)
//!         .register();
//!
//!     Ok(images)
//! }
//! ```
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{BufReader, BufWriter};

use camino::{Utf8Path, Utf8PathBuf};
use glob::Pattern;
use image::{ExtendedColorType, ImageReader};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::engine::Many;
use crate::error::{BuildError, HauchiwaError};
use crate::loader::{GlobFiles, Input, Store};
use crate::{Blueprint, TaskContext};

const DIR_STORE: &str = "/hash/img/";
const DIR_CACHE: &str = ".cache/hash/img/";
const DIR_DIST: &str = "dist/hash/img/";

/// Errors that can occur when processing images.
#[derive(Debug, Error)]
pub enum ImageError {
    /// An I/O error occurred while reading or writing image files.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// An error occurred during image decoding or encoding.
    #[error("Image processing error: {0}")]
    Image(#[from] image::ImageError),

    /// An internal build error.
    #[error("Build error: {0}")]
    Build(#[from] BuildError),

    /// An image processing invariant was violated (e.g. no output formats produced).
    #[error("Invalid output: {0}")]
    InvalidOutput(&'static str),
}

/// Configuration for image compression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Quality {
    /// Lossless compression.
    Lossless,
    /// Lossy compression with a quality factor (0-100).
    Lossy(u8),
}

impl Default for Quality {
    fn default() -> Self {
        // A sensible default for most web images
        Self::Lossy(80)
    }
}

/// Supported output image formats with specific configuration.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ImageFormat {
    #[default]
    WebP,
    Avif(Quality),
    Png,
}

impl ImageFormat {
    fn extension(&self) -> &'static str {
        match self {
            ImageFormat::WebP => "webp",
            ImageFormat::Avif(_) => "avif",
            ImageFormat::Png => "png",
        }
    }
}

/// Represents a processed image asset with multiple formats.
#[derive(Clone, Debug)]
pub struct Image {
    /// The default image path (usually the first configured format).
    pub default: Utf8PathBuf,
    /// A map of available formats to their web-accessible paths.
    pub sources: HashMap<ImageFormat, Utf8PathBuf>,
    /// The original width of the image.
    pub width: u32,
    /// The original height of the image.
    pub height: u32,
}

impl Image {
    /// Helper to get the path for a specific format.
    pub fn get(&self, format: ImageFormat) -> Option<&Utf8PathBuf> {
        self.sources.get(&format)
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct ImageMetadata {
    width: u32,
    height: u32,
}

/// A builder for configuring the image loading task.
pub struct ImageLoader<'a, G>
where
    G: Send + Sync,
{
    blueprint: &'a mut Blueprint<G>,
    entry: Vec<String>,
    watch: Vec<Pattern>,
    formats: Vec<ImageFormat>,
}

impl<'a, G> ImageLoader<'a, G>
where
    G: Send + Sync + 'static,
{
    fn new(blueprint: &'a mut Blueprint<G>) -> Self {
        Self {
            blueprint,
            entry: Vec::new(),
            watch: Vec::new(),
            formats: Vec::new(),
        }
    }

    /// Adds a glob pattern to find images.
    pub fn glob(mut self, glob: impl Into<String>) -> Result<Self, HauchiwaError> {
        let glob = glob.into();
        let pattern = Pattern::new(&glob)?;
        self.entry.push(glob);
        self.watch.push(pattern);
        Ok(self)
    }

    /// Adds an output format to generate.
    ///
    /// The first format added will be considered the "default" for the `Image` struct.
    pub fn format(mut self, format: ImageFormat) -> Self {
        if !self.formats.contains(&format) {
            self.formats.push(format);
        }
        self
    }

    /// Registers the task with the Blueprint.
    pub fn register(self) -> Many<Image> {
        let mut formats = self.formats;

        // Default to WebP if no format is specified
        if formats.is_empty() {
            formats.push(ImageFormat::default());
        }

        let task = GlobFiles::new(
            self.entry,
            self.watch,
            move |_: &TaskContext<G>, store: &mut Store, input: Input| {
                let (image, dist_paths) = process_image(&input, &formats)?;
                store.store_paths.extend(dist_paths);
                Ok((input.path, image))
            },
        );

        self.blueprint.add_task_fine(task)
    }
}

impl<G> Blueprint<G>
where
    G: Send + Sync + 'static,
{
    /// Starts configuring an image loader task.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # let mut config = hauchiwa::Blueprint::<()>::new();
    /// config.load_images()
    ///     .glob("assets/images/*.jpg")?
    ///     .format(hauchiwa::loader::image::ImageFormat::WebP)
    ///     .register();
    /// # Ok::<(), hauchiwa::error::HauchiwaError>(())
    /// ```
    pub fn load_images(&mut self) -> ImageLoader<'_, G> {
        ImageLoader::new(self)
    }
}

fn process_image(file: &Input, formats: &[ImageFormat]) -> Result<(Image, Vec<Utf8PathBuf>), ImageError> {
    let source_hash = file.hash.to_hex();

    let meta_file_name = format!("{}.meta.cbor", source_hash);
    let meta_file_path = Utf8Path::new(DIR_CACHE).join(&meta_file_name);

    fs::create_dir_all(DIR_CACHE)?;
    fs::create_dir_all(DIR_DIST)?;

    // Try to load serialized metadata
    let metadata = if meta_file_path.exists() {
        let file = File::open(&meta_file_path)?;
        let file = BufReader::new(file);

        ciborium::from_reader::<ImageMetadata, _>(file).ok()
    } else {
        None
    };

    // Calculate paths for all formats
    let mut outputs = Vec::new();
    let mut cached = true;

    for &format in formats {
        // Include configuration in the hash to ensure cache invalidation if quality changes
        let config = match format {
            ImageFormat::WebP => "webp".to_string(),
            ImageFormat::Avif(Quality::Lossy(q)) => format!("avif-q{}", q),
            ImageFormat::Avif(Quality::Lossless) => "avif-ll".to_string(),
            ImageFormat::Png => "png".to_string(),
        };

        // Final filename: <hash>.<config>.<ext>
        let file_name = format!("{}.{}.{}", source_hash, config, format.extension());

        let path_store = Utf8Path::new(DIR_STORE).join(&file_name);
        let path_cache = Utf8Path::new(DIR_CACHE).join(&file_name);
        let path_dist = Utf8Path::new(DIR_DIST).join(&file_name);

        if !path_cache.exists() {
            // cache miss
            cached = false;
        }

        outputs.push((format, path_store, path_cache, path_dist));
    }

    // FAST PATH: If metadata exists and all output formats are cached
    if cached && let Some(meta) = metadata {
        let mut sources = HashMap::new();
        let mut default_path = None;
        let mut dist_paths = Vec::new();

        for (format, path_store, path_cache, path_dist) in outputs {
            // Ensure artifact is in dist
            if !path_dist.exists() {
                // hard link with fallback to copy
                if std::fs::hard_link(&path_cache, &path_dist).is_err() {
                    std::fs::copy(&path_cache, &path_dist)?;
                }
            }

            dist_paths.push(Utf8Path::new("hash/img").join(
    path_dist.file_name().ok_or(ImageError::InvalidOutput("path_dist has no filename"))?,
));
            sources.insert(format, path_store.clone());

            if default_path.is_none() {
                default_path = Some(path_store);
            }
        }

        return Ok((
            Image {
                default: default_path.ok_or(ImageError::InvalidOutput("at least one image format must be produced"))?,
                sources,
                width: meta.width,
                height: meta.height,
            },
            dist_paths,
        ));
    }

    // SLOW PATH: Decode source image
    let reader = BufReader::new(File::open(&file.path)?);
    let img = ImageReader::new(reader).with_guessed_format()?.decode()?;
    let width = img.width();
    let height = img.height();
    let rgba = img.to_rgba8();

    // Save metadata
    let meta_data = ImageMetadata { width, height };
    let meta_file = File::create(&meta_file_path)?;
    ciborium::into_writer(&meta_data, meta_file).map_err(std::io::Error::other)?;

    let mut sources = HashMap::new();
    let mut default_path = None;
    let mut dist_paths = Vec::new();

    for (format, path_store, path_cache, path_dist) in outputs {
        if !path_cache.exists() {
            let cache_file = File::create(&path_cache)?;
            let mut writer = BufWriter::new(cache_file);

            match format {
                ImageFormat::WebP => {
                    use image::codecs::webp::WebPEncoder;

                    WebPEncoder::new_lossless(&mut writer).encode(
                        &rgba,
                        width,
                        height,
                        ExtendedColorType::Rgba8,
                    )?;
                }
                ImageFormat::Avif(quality) => match quality {
                    Quality::Lossless => {
                        use image::ImageEncoder;
                        use image::codecs::avif::AvifEncoder;

                        AvifEncoder::new(&mut writer).write_image(
                            &rgba,
                            width,
                            height,
                            ExtendedColorType::Rgba8,
                        )?;
                    }
                    Quality::Lossy(q) => {
                        use image::ImageEncoder;
                        use image::codecs::avif::AvifEncoder;

                        AvifEncoder::new_with_speed_quality(&mut writer, 10, q).write_image(
                            &rgba,
                            width,
                            height,
                            ExtendedColorType::Rgba8,
                        )?;
                    }
                },
                ImageFormat::Png => {
                    use image::ImageEncoder;
                    use image::codecs::png::PngEncoder;

                    PngEncoder::new(&mut writer).write_image(
                        &rgba,
                        width,
                        height,
                        ExtendedColorType::Rgba8,
                    )?;
                }
            }
        }

        if !path_dist.exists() {
            // hard link with fallback to copy
            if std::fs::hard_link(&path_cache, &path_dist).is_err() {
                std::fs::copy(&path_cache, &path_dist)?;
            }
        }

        dist_paths.push(Utf8Path::new("hash/img").join(
    path_dist.file_name().ok_or(ImageError::InvalidOutput("path_dist has no filename"))?,
));
        sources.insert(format, path_store.clone());

        if default_path.is_none() {
            default_path = Some(path_store);
        }
    }

    Ok((
        Image {
            default: default_path
                .ok_or(ImageError::InvalidOutput("at least one image format must be produced"))?,
            sources,
            width,
            height,
        },
        dist_paths,
    ))
}