hauchiwa 0.21.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io;
use std::path::Path;

use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
use petgraph::graph::NodeIndex;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

use crate::core::Hash32;
use crate::output::Output;

/// What a snapshot entry represents in `dist`.
///
/// The path (the `Snapshot` HashMap key) is always dist-relative
/// (e.g. `posts/hello/index.html`, `hash/abc123.png`, `styles/main.css`).
pub(crate) enum SnapshotEntry {
    /// An [`Output`] file whose content is held in memory and written by `commit()`.
    Page {
        task: String,
        output: Output,
        /// Blake3 hash of `output.data`, computed once at insert time.
        /// Used by `commit_diff` to skip unchanged pages without touching the disk.
        content_hash: Hash32,
    },
    /// A content-addressed asset already written to `dist/hash/` by `Store::save()`
    /// during task execution. Tracked here so reconciliation can detect orphans.
    HashAsset { task: String },
    /// A static file copied from the source tree via `Blueprint::copy_static()`.
    /// The copy happens in `clone_static()`; this entry records provenance for
    /// the reconciliation pass.
    StaticFile { source: Utf8PathBuf },
}

fn validate_dist_path(path: &Utf8Path) -> Result<(), crate::error::BuildError> {
    let normalized = crate::output::normalize_path(path);
    let safe = !path.as_str().is_empty()
        && !path.as_str().split('/').any(|component| component == ".")
        && normalized == path
        && path
            .components()
            .all(|component| matches!(component, Utf8Component::Normal(_)));

    if safe {
        Ok(())
    } else {
        Err(crate::error::BuildError::Other(anyhow::anyhow!(
            "Output path `{path}` is outside the configured dist directory"
        )))
    }
}

fn existing_producer(entry: &SnapshotEntry) -> String {
    match entry {
        SnapshotEntry::Page { task, .. } | SnapshotEntry::HashAsset { task, .. } => task.clone(),
        SnapshotEntry::StaticFile { source } => format!("static file `{source}`"),
    }
}

fn output_conflict(path: Utf8PathBuf, existing: String, new: String) -> crate::error::BuildError {
    crate::error::BuildError::Other(anyhow::anyhow!(
        "Output conflict at `{path}`: produced by `{existing}` and `{new}`"
    ))
}

/// A virtual representation of the `dist` directory after a build.
///
/// The `Snapshot` is assembled from all task outputs before anything is
/// written to disk. It serves as the single authority on what files should
/// exist in `dist` and which task produced each one.
///
/// Conflict detection happens at insert time: if two producers claim the same
/// output path, the build fails before anything is written.
pub(crate) struct Snapshot {
    entries: HashMap<Utf8PathBuf, SnapshotEntry>,
}

impl Snapshot {
    pub(crate) fn new() -> Self {
        Self {
            entries: HashMap::new(),
        }
    }

    /// Inserts an [`Output`] page. Fails if another producer already claimed the same dist path.
    pub(crate) fn insert_page(
        &mut self,
        _node: NodeIndex,
        task_name: &str,
        output: Output,
    ) -> Result<(), crate::error::BuildError> {
        let path = output.path.clone();
        validate_dist_path(&path)?;
        if let Some(existing) = self.entries.get(&path) {
            return Err(output_conflict(
                path,
                existing_producer(existing),
                task_name.to_string(),
            ));
        }
        tracing::debug!("snapshot: page `{}` <- task `{}`", path, task_name);
        let content_hash = Hash32::hash(&output.data);
        self.entries.insert(
            path,
            SnapshotEntry::Page {
                task: task_name.to_string(),
                content_hash,
                output,
            },
        );
        Ok(())
    }

    /// Inserts a content-addressed hash asset (dist-relative path, e.g. `hash/abc.png`).
    ///
    /// Multiple tasks may reference the same content-addressed path - that is valid
    /// (same hash = same content). The first claimant is recorded for provenance.
    pub(crate) fn insert_hash_asset(
        &mut self,
        _node: NodeIndex,
        task_name: &str,
        path: Utf8PathBuf,
    ) -> Result<(), crate::error::BuildError> {
        validate_dist_path(&path)?;
        if let Some(existing) = self.entries.get(&path) {
            if matches!(existing, SnapshotEntry::HashAsset { .. }) {
                return Ok(());
            }
            return Err(output_conflict(
                path,
                existing_producer(existing),
                task_name.to_string(),
            ));
        }
        self.entries.insert(
            path,
            SnapshotEntry::HashAsset {
                task: task_name.to_string(),
            },
        );
        Ok(())
    }

    /// Inserts a static file entry (dist-relative path → source path).
    ///
    /// The file is already copied to dist by `clone_static()`; this records
    /// provenance so the reconciliation pass can run without `clear_dist()`.
    pub(crate) fn insert_static_file(
        &mut self,
        dist_rel: Utf8PathBuf,
        source: Utf8PathBuf,
    ) -> Result<(), crate::error::BuildError> {
        validate_dist_path(&dist_rel)?;
        if let Some(existing) = self.entries.get(&dist_rel) {
            return Err(output_conflict(
                dist_rel,
                existing_producer(existing),
                format!("static file `{source}`"),
            ));
        }
        self.entries
            .insert(dist_rel, SnapshotEntry::StaticFile { source });
        Ok(())
    }

    /// Number of [`SnapshotEntry::Page`] entries (HTML/binary outputs from tasks).
    pub(crate) fn page_count(&self) -> usize {
        self.entries
            .values()
            .filter(|e| matches!(e, SnapshotEntry::Page { .. }))
            .count()
    }

    /// Full reconcile against `dist` - intended for the initial build.
    ///
    /// 1. Walks `dist` and deletes any file not present in this snapshot.
    /// 2. Writes every [`SnapshotEntry::Page`] whose content differs from
    ///    what is already on disk (blake3 comparison).
    ///
    /// [`SnapshotEntry::HashAsset`] and [`SnapshotEntry::StaticFile`] entries
    /// are already on disk before `commit()` is called.
    pub(crate) fn commit(&self, dist: &camino::Utf8Path) -> io::Result<()> {
        let dist = dist.as_std_path();
        fs::create_dir_all(dist)?;

        tracing::debug!(
            "commit: {} total entries ({} pages, {} hash assets, {} static files)",
            self.entries.len(),
            self.entries
                .values()
                .filter(|e| matches!(e, SnapshotEntry::Page { .. }))
                .count(),
            self.entries
                .values()
                .filter(|e| matches!(e, SnapshotEntry::HashAsset { .. }))
                .count(),
            self.entries
                .values()
                .filter(|e| matches!(e, SnapshotEntry::StaticFile { .. }))
                .count(),
        );

        let desired: HashSet<Utf8PathBuf> = self.entries.keys().cloned().collect();
        let removed = remove_stale(dist, Utf8Path::new(""), &desired)?;
        if removed > 0 {
            tracing::info!("removed {} stale file(s) from dist", removed);
        }

        write_pages(
            dist,
            self.entries.iter().filter_map(|(path, entry)| match entry {
                SnapshotEntry::Page {
                    output,
                    content_hash,
                    ..
                } => Some((path, output, content_hash)),
                _ => None,
            }),
        )
    }

    /// Incremental diff against a previous snapshot - intended for watch rebuilds.
    ///
    /// Compared to `commit()`, this avoids walking `dist` on disk: the diff is
    /// computed entirely from the two in-memory snapshots.
    ///
    /// 1. Deletes files present in `prev` but absent from `self`.
    /// 2. Writes pages that are new or whose content hash changed.
    ///    Pages with identical hashes are skipped entirely - no disk read needed.
    pub(crate) fn commit_diff(&self, prev: &Snapshot, dist: &camino::Utf8Path) -> io::Result<()> {
        let dist = dist.as_std_path();
        fs::create_dir_all(dist)?;

        tracing::debug!(
            "commit_diff: {} prev entries -> {} new entries",
            prev.entries.len(),
            self.entries.len(),
        );

        // Delete files that disappeared from the snapshot.
        let mut removed = 0;
        let mut dirs_to_prune: HashSet<std::path::PathBuf> = HashSet::new();
        for path in prev.entries.keys() {
            if !self.entries.contains_key(path) {
                let abs = dist.join(path.as_std_path());
                tracing::debug!("removing stale dist file: {}", path);
                match fs::remove_file(&abs) {
                    Ok(()) => removed += 1,
                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
                        tracing::debug!("stale file already gone: {}", path);
                    }
                    Err(e) => return Err(e),
                }
                if let Some(parent) = abs.parent() {
                    dirs_to_prune.insert(parent.to_path_buf());
                }
            }
        }
        if removed > 0 {
            tracing::info!("removed {} stale file(s) from dist", removed);
            prune_empty_dirs(dist, dirs_to_prune)?;
        }

        // Write pages that are new or whose content changed.
        write_pages(
            dist,
            self.entries.iter().filter_map(|(path, entry)| {
                let SnapshotEntry::Page {
                    output,
                    content_hash,
                    ..
                } = entry
                else {
                    return None;
                };
                match prev.entries.get(path) {
                    None => {
                        tracing::debug!("new page: {}", path);
                        Some((path, output, content_hash))
                    }
                    Some(SnapshotEntry::Page {
                        content_hash: prev_hash,
                        ..
                    }) => {
                        let abs_path = dist.join(path.as_std_path());
                        if prev_hash != content_hash || !abs_path.exists() {
                            tracing::debug!("changed or missing page: {}", path);
                            Some((path, output, content_hash))
                        } else {
                            tracing::debug!("unchanged page, skipping: {}", path);
                            None
                        }
                    }
                    _ => {
                        tracing::debug!("new page (replaced non-page entry): {}", path);
                        Some((path, output, content_hash))
                    }
                }
            }),
        )
    }

    /// Converts this snapshot into a slim, serializable form suitable for
    /// persisting to disk. Page output data is not included - only the
    /// content hash is retained for future diffing.
    pub(crate) fn to_meta(&self) -> SnapshotMeta {
        let entries = self
            .entries
            .iter()
            .map(|(path, entry)| {
                let meta_entry = match entry {
                    SnapshotEntry::Page { content_hash, .. } => MetaEntry::Page {
                        content_hash: content_hash.to_bytes(),
                    },
                    SnapshotEntry::HashAsset { .. } => MetaEntry::HashAsset,
                    SnapshotEntry::StaticFile { .. } => MetaEntry::StaticFile,
                };
                (path.to_string(), meta_entry)
            })
            .collect();
        SnapshotMeta { entries }
    }

    /// Incremental diff against a persisted snapshot - intended for cold-start
    /// builds where no in-memory previous snapshot is available.
    ///
    /// Semantics are identical to [`commit_diff`](Self::commit_diff).
    pub(crate) fn commit_diff_meta(
        &self,
        prev: &SnapshotMeta,
        dist: &camino::Utf8Path,
    ) -> io::Result<()> {
        let dist = dist.as_std_path();
        fs::create_dir_all(dist)?;

        tracing::debug!(
            "commit_diff_meta: {} prev entries -> {} new entries",
            prev.entries.len(),
            self.entries.len(),
        );

        // Delete files that disappeared from the snapshot.
        let mut removed = 0;
        let mut dirs_to_prune: HashSet<std::path::PathBuf> = HashSet::new();
        for path in prev.entries.keys() {
            if !self.entries.contains_key(Utf8Path::new(path)) {
                let abs = dist.join(path.as_str());
                tracing::debug!("removing stale dist file: {}", path);
                match fs::remove_file(&abs) {
                    Ok(()) => removed += 1,
                    Err(e) if e.kind() == io::ErrorKind::NotFound => {
                        tracing::debug!("stale file already gone: {}", path);
                    }
                    Err(e) => return Err(e),
                }
                if let Some(parent) = abs.parent() {
                    dirs_to_prune.insert(parent.to_path_buf());
                }
            }
        }
        if removed > 0 {
            tracing::info!("removed {} stale file(s) from dist", removed);
            prune_empty_dirs(dist, dirs_to_prune)?;
        }

        // Write pages that are new or whose content hash changed.
        write_pages(
            dist,
            self.entries.iter().filter_map(|(path, entry)| {
                let SnapshotEntry::Page {
                    output,
                    content_hash,
                    ..
                } = entry
                else {
                    return None;
                };
                match prev.entries.get(path.as_str()) {
                    None => {
                        tracing::debug!("new page: {}", path);
                        Some((path, output, content_hash))
                    }
                    Some(MetaEntry::Page {
                        content_hash: prev_hash,
                    }) => {
                        let abs_path = dist.join(path.as_std_path());
                        if prev_hash != &content_hash.to_bytes() || !abs_path.exists() {
                            tracing::debug!("changed or missing page: {}", path);
                            Some((path, output, content_hash))
                        } else {
                            tracing::debug!("unchanged page, skipping: {}", path);
                            None
                        }
                    }
                    _ => {
                        tracing::debug!("new page (replaced non-page entry): {}", path);
                        Some((path, output, content_hash))
                    }
                }
            }),
        )
    }
}

/// Slim, serializable representation of a [`Snapshot`].
///
/// Stored at `.cache/snapshot/metadata.cbor` after each successful build.
/// Loaded on the next cold start to drive [`Snapshot::commit_diff_meta`],
/// skipping unchanged pages without a full `dist` walk.
#[derive(Serialize, Deserialize)]
pub(crate) struct SnapshotMeta {
    entries: HashMap<String, MetaEntry>,
}

#[derive(Serialize, Deserialize)]
enum MetaEntry {
    Page { content_hash: [u8; 32] },
    HashAsset,
    StaticFile,
}

impl SnapshotMeta {
    const RELATIVE_PATH: &'static str = "snapshot/metadata.cbor";

    /// Loads the persisted snapshot meta from disk.
    ///
    /// Returns `None` if the file does not exist (e.g. first build).
    /// Returns an error for I/O or deserialization failures.
    pub(crate) fn load(cache_dir: &camino::Utf8Path) -> io::Result<Option<Self>> {
        let path = cache_dir.join(Self::RELATIVE_PATH);
        let file = match fs::File::open(&path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e),
        };
        tracing::debug!("loading snapshot meta from {}", path);
        ciborium::from_reader(file)
            .map(Some)
            .map_err(io::Error::other)
    }

    /// Persists this snapshot meta to `{cache_dir}/snapshot/metadata.cbor`.
    pub(crate) fn save(&self, cache_dir: &camino::Utf8Path) -> io::Result<()> {
        let path = cache_dir.join(Self::RELATIVE_PATH);
        fs::create_dir_all(cache_dir.join("snapshot"))?;
        let file = fs::File::create(&path)?;
        tracing::debug!("saving snapshot meta to {}", path);
        ciborium::into_writer(self, file).map_err(io::Error::other)
    }
}

/// Writes a set of pages to `dist` in parallel.
///
/// Pre-creates all unique parent directories before spawning rayon workers
/// so workers never race on directory creation.
fn write_pages<'a>(
    dist: &Path,
    pages: impl Iterator<Item = (&'a Utf8PathBuf, &'a Output, &'a Hash32)>,
) -> io::Result<()> {
    let pages: Vec<_> = pages.collect();

    let parent_dirs: HashSet<std::path::PathBuf> = pages
        .iter()
        .filter_map(|(path, _, _)| {
            dist.join(path.as_std_path())
                .parent()
                .map(|p| p.to_path_buf())
        })
        .collect();
    for dir in parent_dirs {
        fs::create_dir_all(dir)?;
    }

    pages.par_iter().try_for_each(|(path, output, _hash)| {
        fs::write(dist.join(path.as_std_path()), &output.data)
    })
}

/// Removes empty directories left after deletions.
///
/// Sorts candidates deepest-first so a parent is only attempted after all
/// its children have been processed. `fs::remove_dir` is a no-op on
/// non-empty directories - errors are silently ignored.
fn prune_empty_dirs(dist: &Path, dirs: HashSet<std::path::PathBuf>) -> io::Result<()> {
    let mut dirs: Vec<_> = dirs.into_iter().collect();
    dirs.sort_by_key(|d| std::cmp::Reverse(d.components().count()));
    for dir in dirs {
        if dir == dist {
            continue;
        }
        if fs::remove_dir(&dir).is_ok() {
            tracing::debug!("pruned empty dir: {}", dir.display());
        }
    }
    Ok(())
}

/// Walks `dist/<rel>` and removes any file whose dist-relative path is not in `desired`.
/// Empty directories left behind after removal are pruned as well.
/// Returns the number of files deleted.
fn remove_stale(dist: &Path, rel: &Utf8Path, desired: &HashSet<Utf8PathBuf>) -> io::Result<usize> {
    let dir = if rel.as_str().is_empty() {
        dist.to_path_buf()
    } else {
        dist.join(rel.as_std_path())
    };

    let read_dir = match fs::read_dir(&dir) {
        Ok(rd) => rd,
        // Nothing to sweep if dist doesn't exist yet (first build).
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(0),
        Err(e) => return Err(e),
    };

    let mut removed = 0;

    for entry in read_dir {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_str().ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidData, "non-UTF-8 filename in dist")
        })?;

        let entry_rel = if rel.as_str().is_empty() {
            Utf8PathBuf::from(name_str)
        } else {
            rel.join(name_str)
        };

        let entry_abs = dist.join(entry_rel.as_std_path());
        if entry.file_type()?.is_dir() {
            removed += remove_stale(dist, &entry_rel, desired)?;
            if fs::read_dir(&entry_abs)?.next().is_none() {
                fs::remove_dir(&entry_abs)?;
            }
        } else if !desired.contains(entry_rel.as_path()) {
            tracing::debug!("removing stale dist file: {}", entry_rel);
            fs::remove_file(&entry_abs)?;
            removed += 1;
        }
    }

    Ok(removed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Output, output::OutputData};

    #[test]
    fn rejects_paths_outside_dist() {
        let mut snapshot = Snapshot::new();
        let result = snapshot.insert_page(
            NodeIndex::new(0),
            "escape",
            Output {
                path: Utf8PathBuf::from("../escape.txt"),
                data: OutputData::Utf8("bad".into()),
            },
        );

        assert!(result.is_err());
    }

    #[test]
    fn rejects_absolute_paths() {
        let mut snapshot = Snapshot::new();
        let result = snapshot.insert_page(
            NodeIndex::new(0),
            "escape",
            Output {
                path: Utf8PathBuf::from("/tmp/escape.txt"),
                data: OutputData::Utf8("bad".into()),
            },
        );

        assert!(result.is_err());
    }

    #[test]
    fn rejects_duplicate_outputs() {
        let mut snapshot = Snapshot::new();
        let first = Output::binary("same.txt", b"first".to_vec());
        let second = Output::binary("same.txt", b"second".to_vec());

        assert!(
            snapshot
                .insert_page(NodeIndex::new(0), "first", first)
                .is_ok()
        );
        let result = snapshot.insert_page(NodeIndex::new(1), "second", second);

        assert!(result.is_err());
    }

    #[test]
    fn rejects_current_dir_components() {
        let mut snapshot = Snapshot::new();
        let result = snapshot.insert_page(
            NodeIndex::new(0),
            "curdir",
            Output {
                path: Utf8PathBuf::from("same/./file.txt"),
                data: OutputData::Utf8("bad".into()),
            },
        );

        assert!(result.is_err());
    }
}