molt-framework 2.0.0

Fast, type-safe HTML DSL and static site generation engine in Rust and WebAssembly
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
//! Static site generation.
//!
//!
//! Compiled out on `wasm32` regardless of the `ssg` feature — there is no filesystem
//! there.

use std::ffi::OsStr;
use std::fs;
use std::io::{self, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::core::{Node, Render, RenderOptions};
use crate::document::Document;

/// Why a static site operation failed.
///
/// A real error type rather than `io::Error::other(String)`, so a caller can tell an
/// unsafe path from a full disk and can read which page of a bulk build failed. It
/// converts into [`io::Error`] (`?` works in a function returning `io::Result`), keeping
/// `InvalidInput` for the two refusals.
///
/// # Examples
/// ```
/// use molt::ssg::{SsgError, StaticSiteGenerator};
///
/// let site = StaticSiteGenerator::new("dist");
/// let error = site.write_file("x", "../escape.html").expect_err("refused");
/// assert!(matches!(error, SsgError::InvalidPath { .. }));
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub enum SsgError {
    /// A page or asset path that cannot be written under the output directory: a `..`, a
    /// root or drive prefix, no file name, or a symbolic link on the way.
    InvalidPath {
        /// The path as given.
        path: String,
        /// What is wrong with it.
        reason: &'static str,
    },
    /// `clean` refused to delete the output directory.
    UnsafeCleanTarget {
        /// The directory as given.
        path: PathBuf,
        /// Why it is too dangerous to remove.
        reason: &'static str,
    },
    /// The filesystem failed.
    Io {
        /// The file or directory the operation was working on.
        path: PathBuf,
        /// The underlying error.
        source: io::Error,
    },
    /// Several pages of a bulk build failed. Every failure is here, not just the first.
    Pages(Vec<(String, SsgError)>),
}

impl std::fmt::Display for SsgError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidPath { path, reason } => write!(f, "path {path:?} {reason}"),
            Self::UnsafeCleanTarget { path, reason } => {
                write!(f, "refusing to clean {}: {reason}", path.display())
            }
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::Pages(failures) => {
                write!(f, "{} page(s) failed to generate:", failures.len())?;
                for (path, error) in failures {
                    write!(f, "\n  {path}: {error}")?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for SsgError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

impl From<SsgError> for io::Error {
    fn from(error: SsgError) -> Self {
        match error {
            SsgError::InvalidPath { .. } | SsgError::UnsafeCleanTarget { .. } => {
                Self::new(io::ErrorKind::InvalidInput, error)
            }
            SsgError::Io { source, .. } => source,
            SsgError::Pages(_) => Self::other(error),
        }
    }
}

/// Result alias for this module's operations.
type Result<T> = std::result::Result<T, SsgError>;

/// The name of the file a [`StaticSiteGenerator`] leaves in its output directory.
///
/// [`StaticSiteGenerator::clean`] deletes a directory only if it is missing, empty, or holds
/// this file, so a relative output path that happens to name someone else's directory (the
/// process may run from another project) is refused instead of emptied. Writing a page or
/// an asset creates it. To let `clean` empty a directory Molt did not create, create the file
/// yourself. It is an ordinary dotfile and is uploaded with the rest of the site; its
/// contents are one line of text.
///
/// # Examples
/// ```
/// assert_eq!(molt::ssg::OUTPUT_MARKER, ".molt-output");
/// ```
pub const OUTPUT_MARKER: &str = ".molt-output";

/// What the marker says, for whoever finds it in a deployed site.
const MARKER_TEXT: &str = "Created by molt-framework. StaticSiteGenerator::clean() only empties \
a directory that is missing, empty, or has this file.\n";

/// Attaches the path an I/O operation was working on.
fn io_error(path: &Path) -> impl FnOnce(io::Error) -> SsgError + '_ {
    move |source| SsgError::Io {
        path: path.to_path_buf(),
        source,
    }
}

/// Writes rendered pages and assets into an output directory.
///
/// # Examples
/// ```no_run
/// use molt::prelude::*;
/// use molt::{Document, ssg::StaticSiteGenerator};
///
/// let site = StaticSiteGenerator::new("dist");
/// site.clean(true)?;
/// site.generate(&Document::new(Some("pt-BR")), "index.html", &RenderOptions::pretty())?;
/// # Ok::<(), molt::ssg::SsgError>(())
/// ```
#[derive(Debug, Clone)]
pub struct StaticSiteGenerator {
    output_directory: PathBuf,
}

impl StaticSiteGenerator {
    /// Creates a generator writing into `output_directory`.
    pub fn new(output_directory: impl Into<PathBuf>) -> Self {
        Self {
            output_directory: output_directory.into(),
        }
    }

    /// The directory pages are written into.
    #[must_use]
    pub fn output_directory(&self) -> &Path {
        &self.output_directory
    }

    /// Renders a document to `path`, relative to the output directory.
    ///
    /// The page is written with [`Document::render_to`], section by section, into a
    /// temporary file that is then renamed. The bytes match [`Document::render_with`].
    ///
    /// # Errors
    /// Returns an error if the path escapes the output directory, or if the write fails.
    pub fn generate(&self, document: &Document, path: &str, options: &RenderOptions) -> Result<()> {
        self.write_atomic(path, |file| {
            let mut buffered = io::BufWriter::new(file);
            document.render_to(&mut buffered, options)?;
            buffered.flush()
        })
    }

    /// Renders several documents.
    ///
    /// With the `parallel` feature the pages are rendered concurrently — sound because the
    /// node tree is `Send + Sync`.
    ///
    /// **Every** failure is reported, not just the first: a bulk build that names one of
    /// twelve broken pages is worse than useless.
    ///
    /// # Errors
    /// Returns an error naming every page that failed.
    pub fn generate_multiple(
        &self,
        documents: &[(Document, String)],
        options: &RenderOptions,
    ) -> Result<()> {
        #[cfg(feature = "parallel")]
        let results: Vec<(String, Result<()>)> = {
            use rayon::prelude::*;
            documents
                .par_iter()
                .map(|(doc, path)| (path.clone(), self.generate(doc, path, options)))
                .collect()
        };

        #[cfg(not(feature = "parallel"))]
        let results: Vec<(String, Result<()>)> = documents
            .iter()
            .map(|(doc, path)| (path.clone(), self.generate(doc, path, options)))
            .collect();

        collect_failures(results)
    }

    /// Renders a bare node to `path`, optionally prefixed by the doctype.
    ///
    /// # Errors
    /// Returns an error if the path is unsafe or the write fails.
    pub fn generate_page(
        &self,
        page: &Node,
        path: &str,
        options: &RenderOptions,
        doctype: bool,
    ) -> Result<()> {
        let mut content = String::with_capacity(1024);
        if doctype {
            content.push_str("<!DOCTYPE html>\n");
        }
        page.write_into(&mut content, options, 0);
        self.write_file(&content, path)
    }

    /// Copies a file into the output directory, replacing any existing destination.
    ///
    /// # Errors
    /// Returns an error if the destination is unsafe or the copy fails.
    pub fn copy_asset(&self, from: impl AsRef<Path>, to: &str) -> Result<()> {
        let destination = self.resolve(to)?;
        if let Some(parent) = destination.parent() {
            fs::create_dir_all(parent).map_err(io_error(parent))?;
        }
        self.mark_output()?;
        // Copy beside the destination and rename over it, so a failed copy leaves the old
        // file in place instead of the delete-then-copy gap this used to have.
        let temporary = temporary_path(&destination);
        if let Err(error) = fs::copy(from.as_ref(), &temporary) {
            let _ = fs::remove_file(&temporary);
            return Err(io_error(from.as_ref())(error));
        }
        if let Err(error) = fs::rename(&temporary, &destination) {
            let _ = fs::remove_file(&temporary);
            return Err(io_error(&destination)(error));
        }
        Ok(())
    }

    /// Copies a directory tree into the output directory, replacing files that already exist.
    ///
    /// `to` names the destination directory under the output directory; `""` or `"."` copies
    /// into the output directory itself. Returns how many files were copied. Every file goes
    /// through [`copy_asset`](Self::copy_asset), so each copy is atomic.
    ///
    /// Symbolic links in `from` are **not followed**: a link to a file or a directory is
    /// skipped, because what it points at may lie outside the tree you meant to publish. The
    /// output directory is skipped too if it sits inside `from`, so copying `.` cannot copy
    /// the site into itself. Use [`copy_dir_where`](Self::copy_dir_where) to leave out names
    /// such as `.DS_Store`.
    ///
    /// # Errors
    /// Returns an error if `from` cannot be read, if `to` is unsafe (see
    /// [`copy_asset`](Self::copy_asset)), if a name under `from` is not valid UTF-8, or if a
    /// copy fails.
    ///
    /// # Examples
    /// ```
    /// use molt::ssg::StaticSiteGenerator;
    ///
    /// let base = std::env::temp_dir().join(format!("molt-copy-dir-{}", std::process::id()));
    /// std::fs::create_dir_all(base.join("static/img"))?;
    /// std::fs::write(base.join("static/app.css"), "a{}")?;
    /// std::fs::write(base.join("static/img/logo.svg"), "<svg/>")?;
    ///
    /// let site = StaticSiteGenerator::new(base.join("dist"));
    /// assert_eq!(site.copy_dir(base.join("static"), "assets")?, 2);
    /// assert!(base.join("dist/assets/img/logo.svg").is_file());
    /// # std::fs::remove_dir_all(&base)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn copy_dir(&self, from: impl AsRef<Path>, to: &str) -> Result<usize> {
        self.copy_dir_where(from, to, |_| true)
    }

    /// As [`copy_dir`](Self::copy_dir), copying only the entries `keep` accepts.
    ///
    /// `keep` sees each file or directory *name* (not the path). A directory it rejects is
    /// skipped with everything under it.
    ///
    /// # Errors
    /// The same as [`copy_dir`](Self::copy_dir).
    ///
    /// # Examples
    /// ```
    /// use molt::ssg::StaticSiteGenerator;
    ///
    /// let base = std::env::temp_dir().join(format!("molt-copy-where-{}", std::process::id()));
    /// std::fs::create_dir_all(base.join("static"))?;
    /// std::fs::write(base.join("static/app.css"), "a{}")?;
    /// std::fs::write(base.join("static/.DS_Store"), "junk")?;
    ///
    /// let site = StaticSiteGenerator::new(base.join("dist"));
    /// let copied = site.copy_dir_where(base.join("static"), "", |name| name != ".DS_Store")?;
    /// assert_eq!(copied, 1);
    /// assert!(!base.join("dist/.DS_Store").exists());
    /// # std::fs::remove_dir_all(&base)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn copy_dir_where(
        &self,
        from: impl AsRef<Path>,
        to: &str,
        keep: impl Fn(&OsStr) -> bool,
    ) -> Result<usize> {
        // Checked before anything is read, so an unsafe `to` copies nothing.
        // Only a trailing slash is forgiven: a leading one is a root, which `resolve` refuses,
        // and trimming it would turn `/etc` into the relative `etc`.
        if to.starts_with(['/', '\\']) {
            self.resolve(to)?;
        }
        let prefix = to.trim_end_matches(['/', '\\']);
        let prefix = if prefix == "." { "" } else { prefix };
        if !prefix.is_empty() {
            self.resolve(prefix)?;
        }
        let output = fs::canonicalize(&self.output_directory).ok();

        let mut copied = 0;
        // An explicit stack, like the tree walkers: the depth of a directory is not ours to
        // bound, and recursion would make it a stack limit.
        let mut pending = vec![(from.as_ref().to_path_buf(), prefix.to_owned())];
        while let Some((directory, relative)) = pending.pop() {
            for entry in fs::read_dir(&directory).map_err(io_error(&directory))? {
                let entry = entry.map_err(io_error(&directory))?;
                let name = entry.file_name();
                if !keep(&name) {
                    continue;
                }
                let path = entry.path();
                let Some(name) = name.to_str() else {
                    return Err(SsgError::InvalidPath {
                        path: path.to_string_lossy().into_owned(),
                        reason: "is not valid UTF-8",
                    });
                };
                let target = if relative.is_empty() {
                    name.to_owned()
                } else {
                    format!("{relative}/{name}")
                };
                // `file_type` does not follow links, which is what makes skipping them safe.
                let kind = entry.file_type().map_err(io_error(&path))?;
                if kind.is_dir() {
                    if output.is_some() && fs::canonicalize(&path).ok() == output {
                        continue;
                    }
                    pending.push((path, target));
                } else if kind.is_file() {
                    self.copy_asset(&path, &target)?;
                    copied += 1;
                }
            }
        }
        Ok(copied)
    }

    /// Copies a file into `dir` under a name that holds a hash of its content, and returns the
    /// URL to use for it.
    ///
    /// `site.css` copied to `"css"` becomes `css/site.<hash>.css` and the result is
    /// `"/css/site.<hash>.css"`, ready for [`stylesheet`](crate::elements::stylesheet) or
    /// [`script_src`](crate::elements::script_src). The same bytes always give the same name and
    /// different bytes a different one, so a cache can keep the file for a year
    /// (`Cache-Control: public, max-age=31536000, immutable`) and a new build still reaches
    /// every visitor. `dir` of `""` or `"."` is the output directory itself. The copy is atomic,
    /// like [`copy_asset`](Self::copy_asset), and writes the bytes that were hashed, so a file
    /// that changes mid-build cannot get the wrong name.
    ///
    /// The hash is 64-bit FNV-1a, written out in full as 16 hex digits. It names content for a
    /// cache and is **not** a security measure: it is trivially forged. For a hash a browser
    /// checks, see [`Element::csp_hash`](crate::core::Element::csp_hash).
    ///
    /// # What it does not do
    ///
    /// It renames one file and rewrites nothing. A module that imports another by relative
    /// path (`import './motion.js'`) keeps asking for the old name, and so does a `url(...)` in
    /// a stylesheet. Either concatenate those scripts into one file before copying it, or copy
    /// the files they refer to first and write their returned URLs into the file you then copy.
    /// An earlier version of the file stays in the directory until [`clean`](Self::clean).
    /// The file name should be URL-safe, because it is returned as it is.
    ///
    /// # Errors
    /// Returns an error if `from` cannot be read, its name is not valid UTF-8, or `dir` is
    /// unsafe (see [`copy_asset`](Self::copy_asset)).
    ///
    /// # Examples
    /// ```
    /// use molt::prelude::*;
    /// use molt::ssg::StaticSiteGenerator;
    ///
    /// let base = std::env::temp_dir().join(format!("molt-hashed-{}", std::process::id()));
    /// std::fs::create_dir_all(&base)?;
    /// std::fs::write(base.join("site.css"), "body{color:red}")?;
    ///
    /// let site = StaticSiteGenerator::new(base.join("dist"));
    /// let url = site.copy_asset_hashed(base.join("site.css"), "css")?;
    /// assert_eq!(url, "/css/site.c0e0533c847ec633.css");
    /// assert_eq!(
    ///     stylesheet(&url).render(),
    ///     r#"<link href="/css/site.c0e0533c847ec633.css" rel="stylesheet">"#
    /// );
    /// assert!(base.join("dist/css/site.c0e0533c847ec633.css").is_file());
    /// # std::fs::remove_dir_all(&base)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn copy_asset_hashed(&self, from: impl AsRef<Path>, dir: &str) -> Result<String> {
        let from = from.as_ref();
        let bytes = fs::read(from).map_err(io_error(from))?;
        let Some(name) = from.file_name().and_then(OsStr::to_str) else {
            return Err(SsgError::InvalidPath {
                path: from.to_string_lossy().into_owned(),
                reason: "has no file name in UTF-8",
            });
        };

        // A leading dot is part of the stem (`.htaccess`), not an extension.
        let hashed = match name.rsplit_once('.') {
            Some((stem, extension)) if !stem.is_empty() => {
                format!("{stem}.{:016x}.{extension}", fnv1a_64(&bytes))
            }
            _ => format!("{name}.{:016x}", fnv1a_64(&bytes)),
        };
        // Splitting drops the empty segment a leading slash leaves, which would turn `/etc`
        // into the relative `etc`; a root is refused by `resolve`, so ask it first.
        if dir.starts_with(['/', '\\']) {
            self.resolve(dir)?;
        }
        let relative = dir
            .split('/')
            .filter(|part| !part.is_empty() && *part != ".")
            .chain(std::iter::once(hashed.as_str()))
            .collect::<Vec<_>>()
            .join("/");

        self.write_atomic(&relative, |file| file.write_all(&bytes))?;
        Ok(format!("/{relative}"))
    }

    /// Removes the output directory, optionally recreating it empty.
    ///
    /// Only a directory Molt can show is its own is emptied: one that does not exist, is
    /// empty, or holds the [`OUTPUT_MARKER`] file that writing a page or an asset leaves
    /// there. A relative path such as `"dist"` is resolved against the **current directory of
    /// the process**, so the same code run from another project would otherwise empty that
    /// project's `dist`.
    ///
    /// # Errors
    /// Returns an error if the output directory is unsafe to delete — empty, a filesystem
    /// root, a top-level directory, the home directory, the working directory or one of its
    /// ancestors, or containing a `..` component, because removing it recursively would delete
    /// whatever it points at. It also refuses a symbolic link, and a directory that has
    /// contents but no [`OUTPUT_MARKER`]; for one made before the marker existed, remove it by
    /// hand once or create the file.
    ///
    /// # Examples
    /// ```
    /// use molt::ssg::StaticSiteGenerator;
    ///
    /// let base = std::env::temp_dir().join(format!("molt-clean-{}", std::process::id()));
    /// let site = StaticSiteGenerator::new(base.join("dist"));
    /// site.write_file("<p>old</p>", "old.html")?; // leaves the marker behind
    /// site.clean(true)?;
    /// assert!(!base.join("dist/old.html").exists());
    ///
    /// // A directory the generator did not make is left alone.
    /// std::fs::write(base.join("dist/keep.txt"), "mine")?;
    /// std::fs::remove_file(base.join("dist").join(molt::ssg::OUTPUT_MARKER))?;
    /// assert!(site.clean(true).is_err());
    /// assert!(base.join("dist/keep.txt").exists());
    /// # std::fs::remove_dir_all(&base)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn clean(&self, create_directory: bool) -> Result<()> {
        guard_destructive_path(&self.output_directory)?;
        guard_ownership(&self.output_directory)?;

        let directory = &self.output_directory;
        if directory.exists() {
            fs::remove_dir_all(directory).map_err(io_error(directory))?;
        }
        if create_directory {
            fs::create_dir_all(directory).map_err(io_error(directory))?;
            self.mark_output()?;
        }
        Ok(())
    }

    /// Leaves [`OUTPUT_MARKER`] in the output directory, which must exist. An existing marker
    /// is kept as it is.
    fn mark_output(&self) -> Result<()> {
        let marker = self.output_directory.join(OUTPUT_MARKER);
        // `create_new` refuses an existing path, a planted symlink included.
        match fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&marker)
        {
            Ok(mut file) => file
                .write_all(MARKER_TEXT.as_bytes())
                .map_err(io_error(&marker)),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => Ok(()),
            Err(error) => Err(io_error(&marker)(error)),
        }
    }

    /// Writes UTF-8 `content` to `path`, creating parent directories.
    ///
    /// The write is atomic: content goes to a temporary file in the same directory and is
    /// then renamed, so a reader never sees a half-written page.
    ///
    /// # Errors
    /// Returns an error if the path escapes the output directory or the write fails.
    pub fn write_file(&self, content: &str, path: &str) -> Result<()> {
        self.write_atomic(path, |file| file.write_all(content.as_bytes()))
    }

    /// Writes through a temporary file in the destination directory, then renames.
    ///
    /// The closure receives the open temporary file. On any error the temporary file is
    /// removed, so a reader never observes a half-written page under the final name.
    fn write_atomic(
        &self,
        path: &str,
        write_contents: impl FnOnce(&mut fs::File) -> io::Result<()>,
    ) -> Result<()> {
        let destination = self.resolve(path)?;
        if let Some(parent) = destination.parent() {
            fs::create_dir_all(parent).map_err(io_error(parent))?;
        }
        self.mark_output()?;

        let temporary = temporary_path(&destination);
        // `create_new` refuses an existing path, symlinks included, so the temporary file
        // can never be a pre-planted link that redirects the write.
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temporary)
            .map_err(io_error(&temporary))?;
        if let Err(error) = write_contents(&mut file) {
            let _ = fs::remove_file(&temporary);
            return Err(io_error(&destination)(error));
        }
        if let Err(error) = fs::rename(&temporary, &destination) {
            let _ = fs::remove_file(&temporary);
            return Err(io_error(&destination)(error));
        }
        Ok(())
    }

    /// Joins `path` onto the output directory, rejecting anything that escapes it.
    ///
    /// Only plain names are accepted: `..`, a root and a Windows drive prefix (`C:foo`
    /// replaces the base on `join`) are refused, and so is a path with no file name
    /// (`""`, `"."`, `"a/"`), which would name the output directory itself. A component
    /// that already exists as a symlink is refused too, because writing through it lands
    /// wherever the link points.
    ///
    /// The symlink check is not atomic with the write: someone who can create links inside
    /// the output directory *while it is being generated* can still race it.
    fn resolve(&self, path: &str) -> Result<PathBuf> {
        let reject = |reason: &'static str| {
            Err(SsgError::InvalidPath {
                path: path.to_owned(),
                reason,
            })
        };

        let candidate = Path::new(path);
        let mut names = 0;
        for component in candidate.components() {
            match component {
                Component::Normal(_) => names += 1,
                Component::CurDir => {}
                _ => return reject("escapes the output directory"),
            }
        }
        if names == 0 || path.ends_with(['/', '\\']) {
            return reject("does not name a file");
        }

        let mut resolved = self.output_directory.clone();
        for component in candidate.components() {
            if let Component::Normal(name) = component {
                resolved.push(name);
                // Absent components cannot be links; only existing ones are inspected.
                if fs::symlink_metadata(&resolved).is_ok_and(|m| m.file_type().is_symlink()) {
                    return reject("passes through a symbolic link");
                }
            }
        }
        Ok(resolved)
    }
}

/// 64-bit FNV-1a. Names content for a cache; it is not a security hash.
fn fnv1a_64(bytes: &[u8]) -> u64 {
    bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
        (hash ^ u64::from(*byte)).wrapping_mul(0x0100_0000_01b3)
    })
}

/// A sibling of `destination` that no other writer will pick.
///
/// `with_extension` was the wrong tool: it *replaces* the extension, so `index.html` and
/// `index.xml` both became `index.tmp` and two pages written in parallel shared one
/// file. The full file name, the process id and a counter make the name unique.
fn temporary_path(destination: &Path) -> PathBuf {
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let name = destination
        .file_name()
        .map_or_else(|| "page".into(), |n| n.to_string_lossy().into_owned());
    let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
    destination.with_file_name(format!(".{name}.molt-{}-{unique}.tmp", std::process::id()))
}

/// Rejects output directories that are dangerous to delete recursively.
///
/// Beyond the empty path, a filesystem root and `..`, this refuses the directory the
/// process is running in or any ancestor of it (`"."` has a non-empty parent, which is how
/// the old check let `clean(".")` through), the home directory, and anything fewer than two
/// levels below the root (`/usr`, `/home`). The guard only reads the filesystem; it never
/// removes anything, so it can be tested directly.
fn guard_destructive_path(path: &Path) -> Result<()> {
    let reject = |reason: &'static str| {
        Err(SsgError::UnsafeCleanTarget {
            path: path.to_path_buf(),
            reason,
        })
    };

    if path.as_os_str().is_empty() {
        return reject("the output directory is empty");
    }
    if path.parent().is_none() {
        return reject("the output directory is a filesystem root");
    }
    if path.components().any(|c| c == Component::ParentDir) {
        return reject("the output directory contains a `..` component");
    }

    let absolute = absolute_path(path).map_err(io_error(path))?;
    let depth = absolute
        .components()
        .filter(|c| matches!(c, Component::Normal(_)))
        .count();
    if depth < 2 {
        return reject("the output directory is a top-level directory");
    }
    if let Ok(cwd) = std::env::current_dir().and_then(fs::canonicalize) {
        if cwd.starts_with(&absolute) {
            return reject("the output directory is, or contains, the working directory");
        }
    }
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
    if let Some(home) = home.and_then(|h| fs::canonicalize(h).ok()) {
        if home == absolute {
            return reject("the output directory is the home directory");
        }
    }
    Ok(())
}

/// Refuses to empty a directory that Molt cannot show is its own: a symbolic link, or one that
/// has contents but no [`OUTPUT_MARKER`]. A missing or empty directory is fine, since there is
/// nothing to lose. Like [`guard_destructive_path`] it only reads the filesystem, so it can be
/// tested directly, without changing the working directory.
fn guard_ownership(path: &Path) -> Result<()> {
    let reject = |reason: &'static str| {
        Err(SsgError::UnsafeCleanTarget {
            path: path.to_path_buf(),
            reason,
        })
    };

    let Ok(metadata) = fs::symlink_metadata(path) else {
        return Ok(());
    };
    if metadata.file_type().is_symlink() {
        return reject("the output directory is a symbolic link");
    }
    if !metadata.is_dir() || path.join(OUTPUT_MARKER).symlink_metadata().is_ok() {
        return Ok(());
    }
    let is_empty = fs::read_dir(path).map_err(io_error(path))?.next().is_none();
    if is_empty {
        Ok(())
    } else {
        reject(
            "the output directory has contents but no `.molt-output` marker, so Molt did not \
             make it; remove it yourself once, or create the marker file to hand it over",
        )
    }
}

/// `path` made absolute and, when it exists, with symlinks resolved.
fn absolute_path(path: &Path) -> io::Result<PathBuf> {
    if let Ok(canonical) = fs::canonicalize(path) {
        return Ok(canonical);
    }
    let mut absolute = fs::canonicalize(std::env::current_dir()?)?;
    for component in path.components() {
        match component {
            Component::Normal(name) => absolute.push(name),
            Component::RootDir | Component::Prefix(_) => {
                absolute = PathBuf::from(component.as_os_str());
            }
            _ => {}
        }
    }
    Ok(absolute)
}

/// Turns per-page results into one error carrying every failure.
fn collect_failures(results: Vec<(String, Result<()>)>) -> Result<()> {
    let failures: Vec<(String, SsgError)> = results
        .into_iter()
        .filter_map(|(path, result)| result.err().map(|error| (path, error)))
        .collect();

    if failures.is_empty() {
        Ok(())
    } else {
        Err(SsgError::Pages(failures))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::elements::{body, h1, head, html_tag, title};

    /// A throwaway directory that removes itself. Avoids a dev-dependency for six tests.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(name: &str) -> Self {
            // The process id keeps two test runs (or two checkouts) off the same directory.
            let path = std::env::temp_dir().join(format!("molt-{name}-{}", std::process::id()));
            let _ = fs::remove_dir_all(&path);
            fs::create_dir_all(&path).expect("temp dir is creatable");
            Self(path)
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    /// Whether `dir` holds exactly these entries, i.e. no temporary file was left behind. The
    /// marker is not one of them: it is meant to be there.
    fn only_files_named(dir: &Path, names: &[&str]) -> bool {
        let mut found: Vec<String> = fs::read_dir(dir)
            .expect("readable")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .filter(|name| name != OUTPUT_MARKER)
            .collect();
        found.sort();
        found == names
    }

    fn page(text: &str) -> Document {
        Document::new(Some("en"))
            .head_children([title().text(text)])
            .body_children([h1().text(text)])
    }

    #[test]
    fn generate_writes_a_rendered_document() {
        let dir = TempDir::new("generate");
        let site = StaticSiteGenerator::new(&dir.0);
        site.generate(&page("Home"), "index.html", &RenderOptions::pretty())
            .expect("written");

        let written = fs::read_to_string(dir.0.join("index.html")).expect("readable");
        assert!(written.starts_with("<!DOCTYPE html>"));
        assert!(written.contains("<h1>Home</h1>"));
    }

    /// A generated file is the streamed render, replaces an existing one, and reports failures.
    #[test]
    fn generate_replaces_a_file_with_the_rendered_bytes() {
        let dir = TempDir::new("stream");
        let site = StaticSiteGenerator::new(&dir.0);
        let destination = dir.0.join("index.html");
        fs::write(&destination, "old").expect("seed");

        let page = page("Home");
        site.generate(&page, "index.html", &RenderOptions::pretty())
            .expect("written");

        let written = fs::read(destination).expect("readable");
        assert_eq!(
            written,
            page.render_with(&RenderOptions::pretty()).into_bytes()
        );
        assert!(only_files_named(&dir.0, &["index.html"]));
    }

    #[test]
    fn nested_paths_create_their_parent_directories() {
        let dir = TempDir::new("nested");
        let site = StaticSiteGenerator::new(&dir.0);
        site.generate(
            &page("Post"),
            "blog/2026/post.html",
            &RenderOptions::compact(),
        )
        .expect("written");
        assert!(dir.0.join("blog/2026/post.html").exists());
    }

    #[test]
    fn a_bare_page_can_be_written_without_a_doctype() {
        let dir = TempDir::new("doctype");
        let site = StaticSiteGenerator::new(&dir.0);
        let node = Node::from(h1().text("Fragment"));

        site.generate_page(&node, "with.html", &RenderOptions::compact(), true)
            .expect("written");
        site.generate_page(&node, "without.html", &RenderOptions::compact(), false)
            .expect("written");

        assert!(
            fs::read_to_string(dir.0.join("with.html"))
                .unwrap()
                .starts_with("<!DOCTYPE")
        );
        assert!(
            !fs::read_to_string(dir.0.join("without.html"))
                .unwrap()
                .contains("DOCTYPE")
        );
    }

    #[test]
    fn fnv1a_matches_the_published_vectors() {
        assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325);
        assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
        assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
    }

    #[test]
    fn a_hashed_copy_is_named_by_its_content_and_returns_the_url() {
        let dir = TempDir::new("hashed");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        let source = dir.0.join("site.css");

        fs::write(&source, "body{color:red}").expect("written");
        let red = site.copy_asset_hashed(&source, "css").expect("copied");
        assert_eq!(red, "/css/site.c0e0533c847ec633.css");
        assert_eq!(
            fs::read_to_string(dir.0.join("out/css/site.c0e0533c847ec633.css")).expect("copy"),
            "body{color:red}"
        );

        // Same bytes, same name; different bytes, a different one; the old file stays.
        assert_eq!(site.copy_asset_hashed(&source, "css").expect("again"), red);
        fs::write(&source, "body{color:blue}").expect("written");
        let blue = site.copy_asset_hashed(&source, "css").expect("copied");
        assert_eq!(blue, "/css/site.91db968e2dbb7470.css");
        assert!(dir.0.join("out/css/site.c0e0533c847ec633.css").is_file());
        assert!(only_files_named(
            &dir.0.join("out/css"),
            &["site.91db968e2dbb7470.css", "site.c0e0533c847ec633.css"]
        ));
    }

    #[test]
    fn a_hashed_name_keeps_the_last_extension_and_copes_with_none() {
        let dir = TempDir::new("hashed-names");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        for (name, expected) in [
            ("app.min.js", "/app.min.af63dc4c8601ec8c.js"),
            ("LICENSE", "/LICENSE.af63dc4c8601ec8c"),
            (".htaccess", "/.htaccess.af63dc4c8601ec8c"),
        ] {
            let source = dir.0.join(name);
            fs::write(&source, "a").expect("written");
            assert_eq!(
                site.copy_asset_hashed(&source, "").expect("copied"),
                expected
            );
        }
        assert_eq!(
            site.copy_asset_hashed(dir.0.join("LICENSE"), "./a//b/")
                .expect("copied"),
            "/a/b/LICENSE.af63dc4c8601ec8c"
        );
    }

    #[test]
    fn a_hashed_copy_refuses_a_destination_that_escapes_and_a_missing_source() {
        let dir = TempDir::new("hashed-refused");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        let source = dir.0.join("a.css");
        fs::write(&source, "a").expect("written");

        for to in ["../x", "/abs", "/", "a/../../b"] {
            let error = site.copy_asset_hashed(&source, to).expect_err("refused");
            assert!(
                matches!(error, SsgError::InvalidPath { .. }),
                "{to}: {error}"
            );
        }
        assert!(!dir.0.join("out").exists());
        let error = site
            .copy_asset_hashed(dir.0.join("missing.css"), "css")
            .expect_err("fails");
        assert!(matches!(error, SsgError::Io { .. }), "{error}");
    }

    #[test]
    fn copy_asset_replaces_an_existing_destination() {
        let dir = TempDir::new("assets");
        let source = dir.0.join("source.css");
        fs::write(&source, "body{}").expect("written");

        let site = StaticSiteGenerator::new(dir.0.join("out"));
        site.copy_asset(&source, "css/style.css").expect("copied");
        fs::write(&source, "body{color:red}").expect("written");
        site.copy_asset(&source, "css/style.css").expect("recopied");

        let copied = fs::read_to_string(dir.0.join("out/css/style.css")).expect("readable");
        assert_eq!(copied, "body{color:red}");
    }

    #[test]
    fn clean_empties_the_output_directory() {
        let dir = TempDir::new("clean");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        site.write_file("x", "a.html").expect("written");

        site.clean(true).expect("cleaned");
        assert!(dir.0.join("out").exists());
        assert!(!dir.0.join("out/a.html").exists());
    }

    /// The report behind #115: `"dist"` is resolved against the current directory of the
    /// process, so code run from another project pointed at that project's `dist`. A directory
    /// with contents and no marker is not Molt's to empty, however the path was spelled.
    #[test]
    fn clean_refuses_a_directory_it_did_not_make() {
        let dir = TempDir::new("clean-foreign");
        let foreign = dir.0.join("other-project/dist");
        fs::create_dir_all(&foreign).expect("created");
        fs::write(foreign.join("precious.txt"), "mine").expect("written");

        let error = StaticSiteGenerator::new(&foreign)
            .clean(true)
            .expect_err("refused");
        assert!(
            matches!(error, SsgError::UnsafeCleanTarget { .. }),
            "{error}"
        );
        assert!(error.to_string().contains(OUTPUT_MARKER), "{error}");
        assert_eq!(
            fs::read_to_string(foreign.join("precious.txt")).expect("kept"),
            "mine"
        );
    }

    #[test]
    fn clean_empties_a_directory_that_has_the_marker() {
        let dir = TempDir::new("clean-marked");
        let out = dir.0.join("out");
        fs::create_dir_all(&out).expect("created");
        fs::write(out.join(OUTPUT_MARKER), "").expect("marker");
        fs::write(out.join("old.html"), "old").expect("written");

        StaticSiteGenerator::new(&out).clean(true).expect("cleaned");

        assert!(!out.join("old.html").exists());
        assert!(out.join(OUTPUT_MARKER).is_file(), "the marker is kept");
    }

    #[test]
    fn clean_accepts_a_missing_or_an_empty_directory() {
        let dir = TempDir::new("clean-empty");
        let missing = StaticSiteGenerator::new(dir.0.join("missing"));
        missing.clean(false).expect("nothing to remove");
        assert!(!dir.0.join("missing").exists());
        missing.clean(true).expect("created");
        assert!(dir.0.join("missing").join(OUTPUT_MARKER).is_file());

        fs::create_dir_all(dir.0.join("empty")).expect("created");
        StaticSiteGenerator::new(dir.0.join("empty"))
            .clean(true)
            .expect("an empty directory has nothing to lose");
    }

    #[test]
    fn writing_a_page_or_an_asset_leaves_the_marker_and_keeps_it() {
        let dir = TempDir::new("marker-written");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        site.write_file("a", "a.html").expect("written");
        let marker = dir.0.join("out").join(OUTPUT_MARKER);
        assert!(
            fs::read_to_string(&marker)
                .expect("marker")
                .starts_with("Created by molt")
        );

        fs::write(&marker, "adopted by hand").expect("edited");
        let source = dir.0.join("s.css");
        fs::write(&source, "b").expect("written");
        site.copy_asset(&source, "s.css").expect("copied");
        assert_eq!(
            fs::read_to_string(&marker).expect("kept"),
            "adopted by hand"
        );
    }

    #[cfg(unix)]
    #[test]
    fn clean_refuses_an_output_directory_that_is_a_symlink() {
        let dir = TempDir::new("clean-link");
        let target = dir.0.join("target");
        fs::create_dir_all(&target).expect("created");
        fs::write(target.join(OUTPUT_MARKER), "").expect("marker");
        fs::write(target.join("x"), "x").expect("written");
        let link = dir.0.join("out");
        std::os::unix::fs::symlink(&target, &link).expect("linked");

        let error = StaticSiteGenerator::new(&link)
            .clean(true)
            .expect_err("refused");
        assert!(
            matches!(error, SsgError::UnsafeCleanTarget { .. }),
            "{error}"
        );
        assert!(target.join("x").is_file());
    }

    /// `clean` refuses a directory that would be dangerous to remove.
    #[test]
    fn clean_refuses_an_unsafe_output_directory() {
        for unsafe_path in ["", "/"] {
            let site = StaticSiteGenerator::new(unsafe_path);
            assert!(
                site.clean(false).is_err(),
                "{unsafe_path:?} should be rejected"
            );
        }
        assert!(StaticSiteGenerator::new("dist/../..").clean(false).is_err());
    }

    #[test]
    fn a_page_path_cannot_escape_the_output_directory() {
        let dir = TempDir::new("escape");
        let site = StaticSiteGenerator::new(&dir.0);
        assert!(site.write_file("x", "../escaped.html").is_err());
        assert!(site.write_file("x", "/etc/escaped.html").is_err());
    }

    #[test]
    fn a_path_that_does_not_name_a_file_is_rejected() {
        let dir = TempDir::new("nameless");
        let site = StaticSiteGenerator::new(&dir.0);
        for path in ["", ".", "./", "a/", "a\\", "a/../../x.html", "C:\\x.html"] {
            // `C:\x.html` is an ordinary file name on Unix, so it is only rejected on Windows.
            if path.starts_with("C:") && !cfg!(windows) {
                continue;
            }
            let outcome = site.write_file("x", path);
            assert!(outcome.is_err(), "{path:?} should be rejected");
        }
        // Nothing was created beside the output directory by `with_extension`.
        let parent = dir.0.parent().expect("temp dir has a parent");
        let name = dir
            .0
            .file_name()
            .expect("named")
            .to_string_lossy()
            .into_owned();
        assert!(!parent.join(format!("{name}.tmp")).exists());
        assert!(only_files_named(&dir.0, &[]));
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_inside_the_output_directory_is_not_followed() {
        let dir = TempDir::new("symlink");
        let outside = dir.0.join("outside");
        fs::create_dir_all(&outside).expect("created");
        let out = dir.0.join("out");
        fs::create_dir_all(&out).expect("created");
        std::os::unix::fs::symlink(&outside, out.join("link")).expect("linked");

        let site = StaticSiteGenerator::new(&out);
        assert!(site.write_file("x", "link/x.html").is_err());
        let asset = dir.0.join("a.css");
        fs::write(&asset, "a{}").expect("written");
        assert!(site.copy_asset(&asset, "link/a.css").is_err());
        assert!(only_files_named(&outside, &[]));
    }

    /// `with_extension` made `index.html` and `index.xml` share `index.tmp`.
    #[test]
    fn pages_with_the_same_stem_do_not_share_a_temporary_file() {
        let dir = TempDir::new("stem");
        let site = StaticSiteGenerator::new(&dir.0);
        std::thread::scope(|scope| {
            for round in 0..8 {
                for name in ["index.html", "index.xml", "index.htm"] {
                    let site = &site;
                    scope.spawn(move || {
                        site.write_file(&format!("{name}:{round}"), name)
                            .expect("written");
                    });
                }
            }
        });
        assert!(only_files_named(
            &dir.0,
            &["index.htm", "index.html", "index.xml"]
        ));
        for name in ["index.html", "index.xml", "index.htm"] {
            let content = fs::read_to_string(dir.0.join(name)).expect("readable");
            assert!(
                content.starts_with(&format!("{name}:")),
                "{name}: {content}"
            );
        }
    }

    #[test]
    fn a_failed_asset_copy_keeps_the_previous_file() {
        let dir = TempDir::new("asset-atomic");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        let source = dir.0.join("source.css");
        fs::write(&source, "old").expect("written");
        site.copy_asset(&source, "style.css").expect("copied");

        assert!(
            site.copy_asset(dir.0.join("missing.css"), "style.css")
                .is_err()
        );
        assert_eq!(
            fs::read_to_string(dir.0.join("out/style.css")).expect("readable"),
            "old"
        );
        assert!(only_files_named(&dir.0.join("out"), &["style.css"]));
    }

    /// Builds `static/` with a nested file, a junk file and a hidden directory.
    fn static_tree(base: &Path) -> PathBuf {
        let root = base.join("static");
        fs::create_dir_all(root.join("img")).expect("created");
        fs::create_dir_all(root.join(".cache")).expect("created");
        fs::write(root.join("app.css"), "a{}").expect("written");
        fs::write(root.join("img/logo.svg"), "<svg/>").expect("written");
        fs::write(root.join(".DS_Store"), "junk").expect("written");
        fs::write(root.join(".cache/x"), "x").expect("written");
        root
    }

    #[test]
    fn copy_dir_copies_a_nested_tree_and_counts_the_files() {
        let dir = TempDir::new("copy-dir");
        let source = static_tree(&dir.0);
        let site = StaticSiteGenerator::new(dir.0.join("out"));

        assert_eq!(site.copy_dir(&source, "assets").expect("copied"), 4);
        let out = dir.0.join("out/assets");
        assert_eq!(fs::read_to_string(out.join("app.css")).expect("css"), "a{}");
        assert_eq!(
            fs::read_to_string(out.join("img/logo.svg")).expect("svg"),
            "<svg/>"
        );
        assert!(out.join(".DS_Store").is_file());
    }

    #[test]
    fn copy_dir_where_leaves_out_the_names_it_rejects_with_what_is_under_them() {
        let dir = TempDir::new("copy-dir-where");
        let source = static_tree(&dir.0);
        let site = StaticSiteGenerator::new(dir.0.join("out"));

        let copied = site
            .copy_dir_where(&source, "", |name| name != ".DS_Store" && name != ".cache")
            .expect("copied");

        assert_eq!(copied, 2);
        let out = dir.0.join("out");
        assert!(out.join("app.css").is_file() && out.join("img/logo.svg").is_file());
        assert!(!out.join(".DS_Store").exists() && !out.join(".cache").exists());
    }

    #[test]
    fn copy_dir_replaces_existing_files_and_leaves_no_temporary_file() {
        let dir = TempDir::new("copy-dir-replace");
        let source = static_tree(&dir.0);
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        site.write_file("old", "assets/app.css").expect("written");

        site.copy_dir_where(&source, "assets", |name| name == "app.css")
            .expect("copied");

        let out = dir.0.join("out/assets");
        assert_eq!(fs::read_to_string(out.join("app.css")).expect("css"), "a{}");
        assert!(only_files_named(&out, &["app.css"]));
    }

    #[test]
    fn copy_dir_refuses_a_destination_that_escapes_before_copying_anything() {
        let dir = TempDir::new("copy-dir-escape");
        let source = static_tree(&dir.0);
        let site = StaticSiteGenerator::new(dir.0.join("out"));

        for to in ["../escape", "/abs", "/", "a/../../b"] {
            let error = site.copy_dir(&source, to).expect_err("refused");
            assert!(
                matches!(error, SsgError::InvalidPath { .. }),
                "{to}: {error}"
            );
        }
        assert!(!dir.0.join("out").exists());
        assert!(!dir.0.join("escape").exists());
    }

    #[test]
    fn copy_dir_reports_a_missing_source() {
        let dir = TempDir::new("copy-dir-missing");
        let site = StaticSiteGenerator::new(dir.0.join("out"));
        let error = site
            .copy_dir(dir.0.join("nope"), "assets")
            .expect_err("fails");
        assert!(matches!(error, SsgError::Io { .. }), "{error}");
    }

    #[test]
    fn copy_dir_does_not_copy_the_output_directory_into_itself() {
        let dir = TempDir::new("copy-dir-self");
        let source = dir.0.join("project");
        fs::create_dir_all(source.join("dist")).expect("created");
        fs::write(source.join("a.txt"), "a").expect("written");
        fs::write(source.join("dist/old.html"), "old").expect("written");
        let site = StaticSiteGenerator::new(source.join("dist"));

        assert_eq!(site.copy_dir(&source, "copy").expect("copied"), 1);
        assert!(source.join("dist/copy/a.txt").is_file());
        assert!(!source.join("dist/copy/dist").exists());
    }

    #[cfg(unix)]
    #[test]
    fn copy_dir_skips_a_symlink_to_a_file_or_a_directory() {
        let dir = TempDir::new("copy-dir-links");
        let source = static_tree(&dir.0);
        let secret = dir.0.join("secret");
        fs::create_dir_all(&secret).expect("created");
        fs::write(secret.join("key"), "k").expect("written");
        std::os::unix::fs::symlink(secret.join("key"), source.join("link-file")).expect("linked");
        std::os::unix::fs::symlink(&secret, source.join("link-dir")).expect("linked");
        let site = StaticSiteGenerator::new(dir.0.join("out"));

        assert_eq!(site.copy_dir(&source, "assets").expect("copied"), 4);
        let out = dir.0.join("out/assets");
        assert!(!out.join("link-file").exists() && !out.join("link-dir").exists());
    }

    /// `Path::new(".").parent()` is `Some("")`, so the old guard let `clean(".")` through.
    #[test]
    fn the_clean_guard_refuses_the_working_directory_and_what_contains_it() {
        let cwd = std::env::current_dir().expect("cwd");
        let mut unsafe_paths = vec![PathBuf::from("."), PathBuf::from("./"), cwd.clone()];
        unsafe_paths.extend(cwd.ancestors().skip(1).map(Path::to_path_buf));
        unsafe_paths.push(PathBuf::from("/usr"));
        if let Some(home) = std::env::var_os("HOME") {
            unsafe_paths.push(PathBuf::from(home));
        }
        for path in unsafe_paths {
            assert!(
                guard_destructive_path(&path).is_err(),
                "{path:?} should be refused"
            );
        }
        // A directory of its own, even one that does not exist yet, is fine.
        assert!(guard_destructive_path(&cwd.join("dist")).is_ok());
        assert!(guard_destructive_path(Path::new("dist")).is_ok());
    }

    #[test]
    fn generate_multiple_writes_every_page() {
        let dir = TempDir::new("multiple");
        let site = StaticSiteGenerator::new(&dir.0);
        let documents = vec![
            (page("A"), "a.html".to_string()),
            (page("B"), "nested/b.html".to_string()),
        ];

        site.generate_multiple(&documents, &RenderOptions::pretty())
            .expect("written");
        assert!(dir.0.join("a.html").exists());
        assert!(dir.0.join("nested/b.html").exists());
    }

    #[test]
    fn generate_multiple_reports_every_failure_not_just_the_first() {
        let dir = TempDir::new("failures");
        let site = StaticSiteGenerator::new(&dir.0);
        let documents = vec![
            (page("ok"), "ok.html".to_string()),
            (page("bad"), "../one.html".to_string()),
            (page("bad"), "../two.html".to_string()),
        ];

        let error = site
            .generate_multiple(&documents, &RenderOptions::compact())
            .expect_err("two pages are unwritable");
        let message = error.to_string();
        assert!(message.contains("../one.html"), "{message}");
        assert!(message.contains("../two.html"), "{message}");

        // The failures are data, not only text.
        let SsgError::Pages(failures) = error else {
            panic!("a bulk build reports Pages");
        };
        let paths: Vec<&str> = failures.iter().map(|(path, _)| path.as_str()).collect();
        assert_eq!(paths, ["../one.html", "../two.html"]);
        assert!(
            failures
                .iter()
                .all(|(_, e)| matches!(e, SsgError::InvalidPath { .. }))
        );
    }

    #[test]
    fn each_failure_has_its_own_variant_and_converts_to_an_io_error() {
        use std::error::Error;

        let dir = TempDir::new("variants");
        let site = StaticSiteGenerator::new(&dir.0);

        let refused = site.write_file("x", "../out.html").expect_err("path");
        assert!(matches!(refused, SsgError::InvalidPath { ref path, .. } if path == "../out.html"));
        assert!(refused.source().is_none());
        assert_eq!(io::Error::from(refused).kind(), io::ErrorKind::InvalidInput);

        let unsafe_clean = StaticSiteGenerator::new(".")
            .clean(false)
            .expect_err("guard");
        assert!(matches!(unsafe_clean, SsgError::UnsafeCleanTarget { .. }));
        assert_eq!(
            io::Error::from(unsafe_clean).kind(),
            io::ErrorKind::InvalidInput
        );

        // A directory sits where the page should go, so the rename fails.
        fs::create_dir_all(dir.0.join("page.html")).expect("created");
        let failed = site
            .write_file("x", "page.html")
            .expect_err("rename onto a directory");
        assert!(matches!(failed, SsgError::Io { .. }));
        assert!(failed.source().is_some());
        assert!(failed.to_string().contains("page.html"));
        assert!(
            only_files_named(&dir.0, &["page.html"]),
            "no temp left behind"
        );
    }

    #[test]
    fn a_page_is_written_with_its_doctype() {
        let directory = TempDir::new("doctype-and-markup");
        let site = StaticSiteGenerator::new(&directory.0);

        let page = Node::from(
            html_tag()
                .child(head().child(title().text("Home")))
                .child(body().child(h1().text("Hello"))),
        );
        site.generate_page(&page, "index.html", &RenderOptions::pretty(), true)
            .expect("write");

        let written = fs::read_to_string(directory.0.join("index.html")).expect("read");
        assert!(written.starts_with("<!DOCTYPE html>\n"));
        assert!(written.contains("<title>Home</title>"));
        assert!(written.contains("<h1>Hello</h1>"));
    }

    #[test]
    fn generate_multiple_writes_each_document_to_its_own_path() {
        let directory = TempDir::new("multiple-documents");
        let site = StaticSiteGenerator::new(&directory.0);

        let pages = vec![
            (page("Home"), "index.html".to_string()),
            (page("About"), "about/index.html".to_string()),
        ];
        site.generate_multiple(&pages, &RenderOptions::compact())
            .expect("write");

        assert!(
            fs::read_to_string(directory.0.join("index.html"))
                .expect("read")
                .contains("<h1>Home</h1>")
        );
        assert!(
            fs::read_to_string(directory.0.join("about/index.html"))
                .expect("read")
                .contains("<h1>About</h1>")
        );
    }
}