texrs 0.6.8

A TeX engine: Knuth's mouth and expander, lowered for a bytecode VM
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
//! `Texrs.toml`: a document that is more than one file, ported in shape from
//! tectonic's `docmodel`.
//!
//! A TeX document of any size is several files, and today texrs compiles one.
//! Tectonic answers that with a file at the root of the document saying what
//! the document is made of and what should come out of it; the engine stays a
//! thing that compiles what it is handed. That division is why this is driver
//! work and not expander work — nothing here touches the mouth.
//!
//! ```toml
//! [doc]
//! name = "thesis"
//! inputs = ["macros.tex", "body.tex"]
//!
//! [[output]]
//! name = "default"
//! type = "messages"
//! ```
//!
//! The inputs are read in order through [`crate::io`]'s provider stack and
//! compiled as one document, which is what a TeX file that has not yet met
//! `\input` can honestly do: the engine sees one source, and the record of what
//! was read says which files it came from and what each of them hashed to.
//!
//! What is deliberately not carried over from tectonic's schema: `bundle` (there
//! is nothing to fetch — texrs has no package universe), `tex_format` (there is
//! one format, INITEX's), `shell_escape` and `synctex` (no shell, no page).
//! Those fields would describe machinery that does not exist.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::io::{InputProvider, OpenResult, ProviderStack};

/// The file at the root of a document.
pub const DOCUMENT_FILE: &str = "Texrs.toml";

/// Where a build writes what it produced.
pub const BUILD_DIR: &str = "build";

/// What a profile asks the engine for.
///
/// Each is a pipeline texrs already has, named: an output type here exists
/// because the binary can produce it, not because tectonic has one like it.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputType {
    /// The `\message` stream — what an ordinary run prints.
    Messages,
    /// The mouth's token stream, before anything expands.
    Tokens,
    /// The fusevm bytecode the document lowers to.
    Disasm,
}

impl OutputType {
    pub fn extension(self) -> &'static str {
        match self {
            OutputType::Messages => "txt",
            OutputType::Tokens => "tokens",
            OutputType::Disasm => "disasm",
        }
    }
}

/// One way of building the document.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Output {
    pub name: String,
    #[serde(rename = "type")]
    pub kind: OutputType,
}

/// The `[doc]` table.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocSection {
    pub name: String,
    /// Files read before the inputs and dumped as a format: a macro file
    /// compiles once and every later build starts from what it left.
    ///
    /// A preamble may only DEFINE. If lowering it produces run-time commands —
    /// a `\message`, a `\count` assignment — there is nothing in a format to
    /// put them in, so the build compiles the whole document instead and says
    /// so. Silently dropping them would be the worst of the three.
    #[serde(default)]
    pub preamble: Vec<String>,
    /// The files that make up the document, in the order they are read.
    #[serde(default = "default_inputs")]
    pub inputs: Vec<String>,
    /// Extra directories searched for an input, after the document's own.
    #[serde(default)]
    pub extra_paths: Vec<PathBuf>,
    /// A zip of support files, searched last: what a document carries with it
    /// when it is shared as one file rather than a directory.
    ///
    /// tectonic's bundle is fetched; this one is a path, because a build that
    /// reaches the network fails on an aeroplane and depends on a server still
    /// answering years from now. Fetch it with whatever fetches things and hand
    /// the file over.
    #[serde(default)]
    pub bundle: Option<PathBuf>,
    /// Anything the user wants to keep here. texrs does not read it.
    #[serde(default)]
    pub metadata: Option<toml::Value>,
}

fn default_inputs() -> Vec<String> {
    vec!["index.tex".to_string()]
}

/// A whole `Texrs.toml`.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DocumentFile {
    pub doc: DocSection,
    #[serde(rename = "output", default)]
    pub outputs: Vec<Output>,
}

/// A document on disk: its file, and where it lives.
#[derive(Clone, Debug)]
pub struct Document {
    /// The directory holding `Texrs.toml`.
    pub src_dir: PathBuf,
    /// Where builds write, `build/` under the source directory.
    pub build_dir: PathBuf,
    pub file: DocumentFile,
}

/// What a build produced.
#[derive(Debug)]
pub struct Built {
    pub profile: String,
    /// Where the output was written.
    pub path: PathBuf,
    /// Every input the build read, in order, with its digest.
    pub inputs: Vec<crate::io::InputRecord>,
}

impl Document {
    /// Read the document rooted at `dir`.
    pub fn open(dir: impl AsRef<Path>) -> Result<Self, String> {
        let src_dir = dir.as_ref().to_path_buf();
        let path = src_dir.join(DOCUMENT_FILE);
        let text = std::fs::read_to_string(&path)
            .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
        Self::parse(&src_dir, &text)
    }

    /// Read `text` as the document file for `src_dir`.
    pub fn parse(src_dir: impl AsRef<Path>, text: &str) -> Result<Self, String> {
        let file: DocumentFile =
            toml::from_str(text).map_err(|e| format!("{DOCUMENT_FILE}: {e}"))?;
        if file.doc.name.trim().is_empty() {
            return Err(format!("{DOCUMENT_FILE}: the document needs a name"));
        }
        if file.doc.inputs.is_empty() {
            return Err(format!("{DOCUMENT_FILE}: the document needs an input"));
        }
        if file.outputs.is_empty() {
            return Err(format!("{DOCUMENT_FILE}: the document needs an output"));
        }
        // Two profiles under one name is a build whose result depends on which
        // one was found first.
        let mut seen = BTreeMap::new();
        for output in &file.outputs {
            if seen.insert(output.name.clone(), ()).is_some() {
                return Err(format!(
                    "{DOCUMENT_FILE}: two outputs are named {:?}",
                    output.name
                ));
            }
        }
        let src_dir = src_dir.as_ref().to_path_buf();
        Ok(Document {
            build_dir: src_dir.join(BUILD_DIR),
            src_dir,
            file,
        })
    }

    /// The document containing `start`, found by walking up as tectonic does —
    /// so a build works from anywhere inside the tree, not only its root.
    pub fn find_from(start: impl AsRef<Path>) -> Result<Self, String> {
        let mut at = start.as_ref().to_path_buf();
        if at.is_file() {
            at.pop();
        }
        loop {
            if at.join(DOCUMENT_FILE).is_file() {
                return Self::open(&at);
            }
            if !at.pop() {
                return Err(format!(
                    "no {DOCUMENT_FILE} here or in any directory above it"
                ));
            }
        }
    }

    /// The profile named, or the only one, or `default`.
    pub fn profile(&self, name: Option<&str>) -> Result<&Output, String> {
        match name {
            Some(name) => self
                .file
                .outputs
                .iter()
                .find(|o| o.name == name)
                .ok_or_else(|| {
                    let known: Vec<&str> =
                        self.file.outputs.iter().map(|o| o.name.as_str()).collect();
                    format!("no output named {name:?}; this document has {known:?}")
                }),
            None if self.file.outputs.len() == 1 => Ok(&self.file.outputs[0]),
            None => self
                .file
                .outputs
                .iter()
                .find(|o| o.name == "default")
                .ok_or_else(|| {
                    "this document has several outputs and none is `default`; \
                     name one with --profile"
                        .to_string()
                }),
        }
    }

    /// The file a `bundle` key names.
    ///
    /// A path is taken as one, relative to the document. A URL or a
    /// `sha256:<digest>` names something in the fetch cache and is NOT
    /// downloaded here: a build never reaches the network, so an archive that
    /// has not been fetched is an error saying which command fetches it. That
    /// keeps a build reproducible and offline, while still letting a document
    /// say where its bundle came from.
    pub fn bundle_path(&self, bundle: &Path) -> Result<PathBuf, String> {
        let name = bundle.to_string_lossy();
        let digest = if let Some(digest) = name.strip_prefix("sha256:") {
            digest.to_string()
        } else if name.starts_with("https://") || name.starts_with("http://") {
            // A URL is not a name in the cache — what is fetched is filed under
            // its digest — so the document has to say which bytes it meant.
            return Err(format!(
                "{name} is a URL: fetch it with `texrs -X bundle fetch {name}`, \
                 then name the bundle it prints as sha256:<digest>"
            ));
        } else {
            return Ok(match bundle.is_absolute() {
                true => bundle.to_path_buf(),
                false => self.src_dir.join(bundle),
            });
        };
        let path = crate::geturl::path_for(&digest).ok_or("no cache directory")?;
        if !path.is_file() {
            return Err(format!(
                "the bundle sha256:{digest} is not in the cache; \
                 fetch it with `texrs -X bundle fetch <url>`"
            ));
        }
        Ok(path)
    }

    /// Where the format for `digests` lives: one file per distinct preamble,
    /// beside the bytecode cache.
    fn format_path(&self, digests: &[String]) -> Option<PathBuf> {
        let key = crate::script_cache::document_key(digests, "preamble");
        let cache = crate::script_cache::default_cache_path();
        let dir = cache.parent()?.join("formats");
        Some(dir.join(format!("{}.fmt", key.trim_start_matches("doc:"))))
    }

    /// Read every input in order, and say what was read.
    ///
    /// The inputs are concatenated with a newline between them, because a file
    /// that does not end in one would otherwise join the next file's first line
    /// — and in TeX that changes what the line means.
    pub fn assemble(&self) -> Result<(String, Vec<crate::io::InputRecord>), String> {
        self.read(&self.file.doc.inputs)
    }

    /// The preamble's sources, if the document has one.
    pub fn assemble_preamble(
        &self,
    ) -> Result<Option<(String, Vec<crate::io::InputRecord>)>, String> {
        if self.file.doc.preamble.is_empty() {
            return Ok(None);
        }
        self.read(&self.file.doc.preamble).map(Some)
    }

    /// Read `names` in order through the provider stack.
    fn read(&self, names: &[String]) -> Result<(String, Vec<crate::io::InputRecord>), String> {
        let mut roots = vec![self.src_dir.clone()];
        roots.extend(self.file.doc.extra_paths.iter().map(|p| {
            if p.is_absolute() {
                p.clone()
            } else {
                self.src_dir.join(p)
            }
        }));
        let mut stack = ProviderStack::new();
        stack.push(Box::new(crate::io::FilesystemProvider::with_roots(roots)));
        // The bundle is searched last, so a file beside the document overrides
        // the one it was shipped with — which is what lets a recipient change
        // a macro without unpacking the archive.
        if let Some(bundle) = &self.file.doc.bundle {
            stack.push(Box::new(crate::bundle::Bundle::open(
                self.bundle_path(bundle)?,
            )?));
        }

        let mut source = String::new();
        for name in names {
            match stack.input_open(name) {
                OpenResult::Ok(input) => {
                    source.push_str(&input.content);
                    if !input.content.ends_with('\n') {
                        source.push('\n');
                    }
                }
                OpenResult::NotAvailable => {
                    return Err(format!("input {name:?} is not in this document"))
                }
                OpenResult::Err(e) => return Err(format!("input {name:?}: {e}")),
            }
        }
        Ok((source, stack.inputs_read().to_vec()))
    }

    /// Build one profile, writing its output under `build/`.
    pub fn build(&self, profile: Option<&str>) -> Result<Built, String> {
        let output = self.profile(profile)?.clone();
        let (source, inputs) = self.assemble()?;
        let body = self.render(&output, &source, &inputs)?;
        std::fs::create_dir_all(&self.build_dir)
            .map_err(|e| format!("cannot make {}: {e}", self.build_dir.display()))?;
        let path = self.build_dir.join(format!(
            "{}.{}",
            self.file.doc.name,
            output.kind.extension()
        ));
        let mut text = body;
        if !text.ends_with('\n') {
            text.push('\n');
        }
        std::fs::write(&path, text).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
        Ok(Built {
            profile: output.name,
            path,
            inputs,
        })
    }
}

impl Document {
    /// The document's shape, as `-X show` prints it: where it is, what it is
    /// made of, and what it can produce.
    ///
    /// Everything here is read from the document file and the inputs
    /// themselves, so what it prints is what a build would use — not a
    /// remembered summary that can be out of date.
    pub fn show(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!("name       {}\n", self.file.doc.name));
        out.push_str(&format!("source     {}\n", self.src_dir.display()));
        out.push_str(&format!("build      {}\n", self.build_dir.display()));
        for path in &self.file.doc.extra_paths {
            out.push_str(&format!("extra path {}\n", path.display()));
        }
        if let Some(bundle) = &self.file.doc.bundle {
            out.push_str(&format!("bundle     {}\n", bundle.display()));
        }
        out.push_str("\ninputs\n");
        match self.assemble() {
            Ok((_, read)) => {
                for record in read {
                    // Twelve characters of the digest: enough to tell two
                    // versions of a file apart at a glance, and not so much
                    // that the name is pushed off the line.
                    out.push_str(&format!(
                        "  {}  {}\n",
                        &record.digest[..12.min(record.digest.len())],
                        record.name
                    ));
                }
            }
            Err(e) => out.push_str(&format!("  (cannot be read: {e})\n")),
        }
        out.push_str("\noutputs\n");
        for output in &self.file.outputs {
            out.push_str(&format!(
                "  {:<12} {:?} → {}.{}\n",
                output.name,
                output.kind,
                self.file.doc.name,
                output.kind.extension()
            ));
        }
        out
    }

    /// Build a profile and hand back what it produced, writing nothing.
    ///
    /// tectonic's `-X dump` exists so an intermediate can be looked at without
    /// hunting for it in the build directory; this is the same, and it is also
    /// what a pipeline wants — `texrs -X dump | grep` needs the bytes on
    /// stdout, not a path to them.
    pub fn dump(&self, profile: Option<&str>) -> Result<String, String> {
        let output = self.profile(profile)?.clone();
        let (source, inputs) = self.assemble()?;
        self.render(&output, &source, &inputs)
    }

    /// What a profile produces from the assembled source.
    ///
    /// The two that need bytecode take it from the cache when the same inputs
    /// have been compiled by this build before. An assembled document is not a
    /// file, so it cannot be keyed by path and mtime the way a single source
    /// is; the key is what its inputs hashed to, which is valid exactly while
    /// the content is. Rebuilding a document nobody has edited therefore costs
    /// a hash of what was read rather than a compile — which is what makes
    /// `-X watch` cheap on the ticks where nothing changed but something else
    /// in the directory moved.
    ///
    /// The token stream is never cached: it is the mouth's output, which is
    /// cheaper to produce than to look up.
    fn render(
        &self,
        output: &Output,
        source: &str,
        inputs: &[crate::io::InputRecord],
    ) -> Result<String, String> {
        if output.kind == OutputType::Tokens {
            let cats = crate::catcode::CatTable::new();
            let mut lexer = crate::lexer::Lexer::new(source);
            let mut out = String::new();
            while let Some(token) = lexer.next_token(&cats) {
                out.push_str(&format!("{token:?}\n"));
            }
            return Ok(out);
        }

        let digests: Vec<String> = inputs.iter().map(|r| r.digest.clone()).collect();
        // An explicit `-jobname` is baked into the chunk (`\jobname` expands
        // while lowering), so it keys the chunk as the inputs do.
        let profile = match crate::lua::explicit_jobname() {
            Some(job) => format!("{}#jobname={job}", output.name),
            None => output.name.clone(),
        };
        let key = crate::script_cache::document_key(&digests, &profile);
        let chunk = match crate::script_cache::try_load_keyed(&key) {
            Some(chunk) => chunk,
            None => {
                let chunk = self.compile_with_format(source)?;
                crate::script_cache::store_keyed(&key, &chunk);
                chunk
            }
        };
        match output.kind {
            OutputType::Disasm => Ok(chunk.disassemble()),
            // Running is the rest of what `run_messages` does; the compile in
            // front of it is what the cache saved.
            _ => Ok(crate::runtime::run(chunk)?.join(" ")),
        }
    }
}

impl Document {
    /// Compile `source`, starting from the document's format when it has one.
    ///
    /// The preamble is lowered once and what it left is dumped; every later
    /// build applies the dump instead of reading the macro file again. That is
    /// what a TeX format is for, and it is why LaTeX starts in milliseconds
    /// rather than seconds.
    ///
    /// A preamble that produces run-time commands cannot be a format — there is
    /// nowhere in one to keep them — so the document is compiled whole instead.
    /// Dropping them would change what the document means.
    pub fn compile_with_format(&self, source: &str) -> Result<fusevm::Chunk, String> {
        let Some((preamble_source, preamble_inputs)) = self.assemble_preamble()? else {
            return crate::compile(source).map_err(|e| e.0);
        };
        let digests: Vec<String> = preamble_inputs.iter().map(|r| r.digest.clone()).collect();
        let path = self.format_path(&digests);

        let mut lowerer = crate::lower::Lowerer::new();
        let loaded = path
            .as_deref()
            .and_then(crate::format::Format::load)
            .map(|format| {
                let mark = format.apply(&mut lowerer.eng);
                lowerer.set_scratch_mark(mark);
            })
            .is_some();

        if !loaded {
            let commands = lowerer
                .lower(&preamble_source)
                .map_err(|e| format!("preamble: {}", e.0))?;
            if !commands.is_empty() {
                // It does something, so it is not a preamble: compile the whole
                // document, which is what the document means.
                let whole = format!("{preamble_source}{source}");
                return crate::compile(&whole).map_err(|e| e.0);
            }
            if let Some(path) = &path {
                let mark = lowerer.scratch_mark();
                let format = crate::format::Format::capture(&lowerer.eng, mark);
                // A format that cannot be written costs a compile next time
                // and nothing else.
                let _ = format.save(path);
            }
        }

        let commands = lowerer.lower(source).map_err(|e| e.0)?;
        crate::compiler::Compiler::new()
            .compile(&commands)
            .map_err(|e| e.0)
    }
}

/// How often [`Document::watch`] looks, when the caller does not say.
pub const WATCH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(250);

impl Document {
    /// Rebuild whenever an input changes, until `stop` says otherwise.
    ///
    /// Change is decided by the digests a build already records, not by mtimes:
    /// a file touched but not edited is not a rebuild, and an editor that
    /// writes through a temporary file — which most do, so the mtime jumps
    /// while the content does not — does not cause one either. The cost is a
    /// read per input per tick, which for a document is nothing next to
    /// compiling it.
    ///
    /// Polling rather than the operating system's watch API is deliberate:
    /// a poll is fifty lines that behave the same on every platform, where the
    /// APIs disagree about directories, renames and network mounts, and the
    /// crates that paper over them are exactly the kind of dependency that
    /// stops building three years from now.
    pub fn watch(
        &self,
        profile: Option<&str>,
        interval: std::time::Duration,
        status: &mut dyn crate::status::StatusBackend,
        stop: &dyn Fn() -> bool,
    ) -> Result<usize, String> {
        // The profile is resolved once: a name that is not there should fail
        // now rather than on the first change, when the user has looked away.
        let profile = self.profile(profile)?.name.clone();
        let mut builds = 0usize;
        let mut last: Option<Vec<crate::io::InputRecord>> = None;

        while !stop() {
            let (_, current) = match self.assemble() {
                Ok(v) => v,
                Err(e) => {
                    // A missing input is a state to wait out, not a reason to
                    // stop watching: it is what a rename looks like halfway.
                    status.warning(&e);
                    std::thread::sleep(interval);
                    continue;
                }
            };
            let changed = last.as_ref().is_none_or(|previous| {
                previous.len() != current.len()
                    || previous
                        .iter()
                        .zip(&current)
                        .any(|(a, b)| a.digest != b.digest || a.name != b.name)
            });
            if changed {
                match self.build(Some(&profile)) {
                    Ok(built) => {
                        builds += 1;
                        status.note(&format!(
                            "built {} from {} input(s) → {}",
                            built.profile,
                            built.inputs.len(),
                            built.path.display()
                        ));
                    }
                    // A document that does not compile is the normal state of
                    // one being edited; report it and keep watching.
                    Err(e) => status.error(&e),
                }
                last = Some(current);
            }
            std::thread::sleep(interval);
        }
        Ok(builds)
    }
}

/// Write a new document into `dir`: the file, and an `index.tex` that runs.
///
/// The starting document sets the category codes INITEX leaves ordinary,
/// because one that did not would fail on its first group — the same reason the
/// editor templates do it.
pub fn scaffold(dir: impl AsRef<Path>, name: &str) -> Result<PathBuf, String> {
    let dir = dir.as_ref();
    let path = dir.join(DOCUMENT_FILE);
    if path.exists() {
        return Err(format!("{} already exists", path.display()));
    }
    std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?;
    let document = format!(
        "# What this document is made of, and what comes out of it.\n\
         # `texrs -X build` reads this; see texrs(1).\n\
         [doc]\n\
         name = {name:?}\n\
         inputs = [\"index.tex\"]\n\
         \n\
         [[output]]\n\
         name = \"default\"\n\
         type = \"messages\"\n"
    );
    std::fs::write(&path, document).map_err(|e| format!("cannot write {}: {e}", path.display()))?;

    let index = dir.join("index.tex");
    if !index.exists() {
        let body = "% INITEX leaves `{` and `}` ordinary, so a document that wants\n\
                    % groups says so first.\n\
                    \\catcode`\\{=1 \\catcode`\\}=2\n\
                    \n\
                    \\message{hello from texrs}\n\
                    \\end\n";
        std::fs::write(&index, body)
            .map_err(|e| format!("cannot write {}: {e}", index.display()))?;
    }
    Ok(path)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Keep the tests out of the cache the user's own runs are using.
    ///
    /// `script_cache::CACHE` is one per process and resolves on first use, so
    /// this has to run before any build in this binary does — every test that
    /// builds calls it first. Without it these tests read and write the real
    /// shard, which is both a lie (they would pass on a warm cache that a
    /// fresh machine does not have) and a mess (they would leave entries
    /// behind).
    fn without_the_shared_cache() {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| std::env::set_var("TEXRS_CACHE", "0"));
    }

    fn scratch(name: &str) -> PathBuf {
        without_the_shared_cache();
        let dir = std::env::temp_dir().join(format!("texrs_doc_{}_{name}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    const HELLO: &str = "\\catcode`\\{=1 \\catcode`\\}=2 \\message{HI}\n\\end\n";

    #[test]
    fn a_document_file_says_what_it_is_made_of() {
        let dir = scratch("parse");
        let doc = Document::parse(
            &dir,
            r#"
            [doc]
            name = "thesis"
            inputs = ["macros.tex", "body.tex"]

            [[output]]
            name = "default"
            type = "messages"

            [[output]]
            name = "bytecode"
            type = "disasm"
            "#,
        )
        .expect("parses");
        assert_eq!(doc.file.doc.name, "thesis");
        assert_eq!(doc.file.doc.inputs, vec!["macros.tex", "body.tex"]);
        assert_eq!(doc.build_dir, dir.join("build"));
        assert_eq!(
            doc.profile(Some("bytecode")).unwrap().kind,
            OutputType::Disasm
        );
        // With several outputs and no name, `default` is the one.
        assert_eq!(doc.profile(None).unwrap().name, "default");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_document_that_cannot_be_built_is_refused_rather_than_half_read() {
        let dir = scratch("refuse");
        let cases = [
            ("[doc]\nname = \"\"\ninputs = [\"a.tex\"]\n[[output]]\nname=\"d\"\ntype=\"messages\"\n", "needs a name"),
            ("[doc]\nname = \"x\"\ninputs = []\n[[output]]\nname=\"d\"\ntype=\"messages\"\n", "needs an input"),
            ("[doc]\nname = \"x\"\n", "needs an output"),
            (
                "[doc]\nname=\"x\"\n[[output]]\nname=\"d\"\ntype=\"messages\"\n[[output]]\nname=\"d\"\ntype=\"tokens\"\n",
                "two outputs are named",
            ),
            ("[doc]\nname=\"x\"\n[[output]]\nname=\"d\"\ntype=\"pdf\"\n", "unknown variant"),
        ];
        for (text, expected) in cases {
            let err = Document::parse(&dir, text).unwrap_err();
            assert!(err.contains(expected), "{text:?} gave {err:?}");
        }
        // A named profile that is not there says what is.
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"x\"\n[[output]]\nname=\"only\"\ntype=\"messages\"\n",
        )
        .unwrap();
        let err = doc.profile(Some("nope")).unwrap_err();
        assert!(
            err.contains("no output named") && err.contains("only"),
            "{err}"
        );
        // One output and no name needs no `default`.
        assert_eq!(doc.profile(None).unwrap().name, "only");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_document_is_found_by_walking_up() {
        let dir = scratch("find");
        let nested = dir.join("chapters/one");
        std::fs::create_dir_all(&nested).unwrap();
        scaffold(&dir, "thesis").unwrap();

        let found = Document::find_from(&nested).expect("found from below");
        assert_eq!(found.file.doc.name, "thesis");
        assert_eq!(found.src_dir, dir);
        // A file works as well as a directory, since that is what an editor has.
        let found = Document::find_from(dir.join("index.tex")).expect("found from a file");
        assert_eq!(found.src_dir, dir);
        // Nowhere to find one is an error that says so.
        let empty = scratch("find_none");
        assert!(Document::find_from(&empty)
            .unwrap_err()
            .contains("no Texrs.toml"));
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&empty);
    }

    #[test]
    fn several_inputs_are_read_in_order_and_recorded() {
        let dir = scratch("assemble");
        std::fs::write(dir.join("macros.tex"), "\\catcode`\\{=1 \\catcode`\\}=2\n").unwrap();
        // No trailing newline: the join has to add one, or `\def` would run
        // into the next file's first line.
        std::fs::write(dir.join("body.tex"), "\\message{FROM-BODY}\n\\end").unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"multi\"\ninputs=[\"macros.tex\",\"body.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        let (source, read) = doc.assemble().expect("assembles");
        assert!(source.starts_with("\\catcode"), "{source}");
        assert!(source.contains("FROM-BODY"), "{source}");
        assert!(source.ends_with('\n'), "the join ends the last line");
        assert_eq!(read.len(), 2, "both inputs are recorded");
        assert_eq!(read[0].name, "macros.tex");
        assert_eq!(read[1].digest.len(), 64);

        // An input that is not there names itself.
        let missing = Document::parse(
            &dir,
            "[doc]\nname=\"x\"\ninputs=[\"nope.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();
        assert!(missing.assemble().unwrap_err().contains("nope.tex"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_build_writes_what_the_profile_asked_for() {
        let dir = scratch("build");
        std::fs::write(dir.join("index.tex"), HELLO).unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"doc\"\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n\
             [[output]]\nname=\"tok\"\ntype=\"tokens\"\n\
             [[output]]\nname=\"bytes\"\ntype=\"disasm\"\n",
        )
        .unwrap();

        let built = doc.build(None).expect("builds");
        assert_eq!(built.profile, "default");
        assert_eq!(built.path, dir.join("build/doc.txt"));
        assert_eq!(std::fs::read_to_string(&built.path).unwrap().trim(), "HI");
        assert_eq!(built.inputs.len(), 1, "what it read is reported");

        let tokens = doc.build(Some("tok")).expect("builds");
        assert!(std::fs::read_to_string(&tokens.path)
            .unwrap()
            .contains("Cs("));
        let disasm = doc.build(Some("bytes")).expect("builds");
        // A listing is one instruction per line, addressed from zero.
        let listing = std::fs::read_to_string(&disasm.path).unwrap();
        assert!(listing.starts_with("0000"), "{listing}");
        assert!(listing.contains("LoadInt"), "{listing}");

        // Each profile writes its own file, so one does not overwrite another.
        assert_ne!(built.path, tokens.path);
        assert_ne!(tokens.path, disasm.path);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_bundle_supplies_what_the_directory_does_not_and_yields_to_what_it_does() {
        use std::io::Write;

        let dir = scratch("bundle");
        // The bundle carries both macro files; the directory carries a newer
        // copy of one of them.
        let bundle_path = dir.join("support.zip");
        {
            let mut zip = zip::ZipWriter::new(std::fs::File::create(&bundle_path).unwrap());
            for (name, body) in [
                (
                    "macros.tex",
                    "\\catcode`\\{=1 \\catcode`\\}=2 \\def\\who{BUNDLE}\n",
                ),
                ("extra.tex", "\\def\\extra{FROM-BUNDLE}\n"),
            ] {
                zip.start_file(name, zip::write::SimpleFileOptions::default())
                    .unwrap();
                zip.write_all(body.as_bytes()).unwrap();
            }
            zip.finish().unwrap();
        }
        std::fs::write(
            dir.join("macros.tex"),
            "\\catcode`\\{=1 \\catcode`\\}=2 \\def\\who{BESIDE-THE-DOCUMENT}\n",
        )
        .unwrap();
        std::fs::write(dir.join("index.tex"), "\\message{\\who\\extra}\n\\end\n").unwrap();

        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"b\"\nbundle=\"support.zip\"\n\
             inputs=[\"macros.tex\",\"extra.tex\",\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        let built = doc.build(None).expect("builds");
        let output = std::fs::read_to_string(&built.path).unwrap();
        // The directory's copy won for the file it has; the bundle supplied
        // the one it does not.
        assert!(output.contains("BESIDE-THE-DOCUMENT"), "{output}");
        assert!(output.contains("FROM-BUNDLE"), "{output}");
        assert!(!output.contains("BUNDLE\\"), "{output}");

        // What came from where is recorded: a bundle entry has no path.
        let (_, read) = doc.assemble().unwrap();
        let from_bundle = read.iter().find(|r| r.name == "extra.tex").unwrap();
        assert_eq!(from_bundle.origin, crate::io::InputOrigin::Memory);
        assert_eq!(from_bundle.path, None);
        let beside = read.iter().find(|r| r.name == "macros.tex").unwrap();
        assert_eq!(beside.origin, crate::io::InputOrigin::Filesystem);

        // And `-X show` says the document has one.
        assert!(
            doc.show().contains("bundle     support.zip"),
            "{}",
            doc.show()
        );

        // A URL is not resolved during a build: the document has to name the
        // bytes it meant, and the error says which command produces them.
        let by_url = Document::parse(
            &dir,
            "[doc]\nname=\"b\"\nbundle=\"https://example.invalid/support.zip\"\n\
             inputs=[\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();
        let err = by_url.assemble().unwrap_err();
        assert!(err.contains("-X bundle fetch"), "{err}");

        // Nor is one named by a digest nobody has fetched.
        let by_digest = Document::parse(
            &dir,
            "[doc]\nname=\"b\"\nbundle=\"sha256:0000000000000000\"\ninputs=[\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();
        let err = by_digest.assemble().unwrap_err();
        assert!(err.contains("not in the cache"), "{err}");

        // A bundle that is not there stops the build rather than quietly
        // building a document missing half its inputs.
        let broken = Document::parse(
            &dir,
            "[doc]\nname=\"b\"\nbundle=\"absent.zip\"\ninputs=[\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();
        assert!(broken.assemble().unwrap_err().contains("cannot read"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_preamble_is_compiled_once_and_applied_from_the_format_after() {
        let dir = scratch("format");
        std::fs::write(
            dir.join("macros.tex"),
            "\\catcode`\\{=1 \\catcode`\\}=2 \\catcode`\\#=6\n\\def\\greet#1{HELLO-#1}\n",
        )
        .unwrap();
        std::fs::write(dir.join("index.tex"), "\\message{\\greet{WORLD}}\n\\end\n").unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"f\"\npreamble=[\"macros.tex\"]\ninputs=[\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        // The body alone would not compile: the macro and the catcodes it
        // needs are in the preamble.
        assert!(crate::compile("\\message{\\greet{WORLD}}\n\\end\n").is_err());

        let built = doc.build(None).expect("builds with the preamble");
        assert_eq!(
            std::fs::read_to_string(&built.path).unwrap().trim(),
            "HELLO-WORLD"
        );

        // The format was written, and a second build gives the same answer
        // through it rather than by reading the macro file again.
        let (_, preamble_inputs) = doc.assemble_preamble().unwrap().unwrap();
        let digests: Vec<String> = preamble_inputs.iter().map(|r| r.digest.clone()).collect();
        let format_path = doc.format_path(&digests).expect("a cache directory");
        assert!(
            format_path.is_file(),
            "the format was dumped: {format_path:?}"
        );
        assert!(crate::format::Format::load(&format_path).is_some());

        let again = doc.dump(None).expect("builds from the format");
        assert_eq!(again.trim(), "HELLO-WORLD");
        let _ = std::fs::remove_file(&format_path);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_preamble_that_does_something_is_not_made_into_a_format() {
        let dir = scratch("format_runtime");
        // `\message` is work, not a definition: it cannot live in a format.
        std::fs::write(
            dir.join("macros.tex"),
            "\\catcode`\\{=1 \\catcode`\\}=2\n\\message{FROM-PREAMBLE}\n",
        )
        .unwrap();
        std::fs::write(dir.join("index.tex"), "\\message{FROM-BODY}\n\\end\n").unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"r\"\npreamble=[\"macros.tex\"]\ninputs=[\"index.tex\"]\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        // What the preamble does still happens: the document is compiled whole
        // rather than having its first half dropped into a format that cannot
        // hold it.
        let built = doc.build(None).expect("builds");
        let output = std::fs::read_to_string(&built.path).unwrap();
        assert!(output.contains("FROM-PREAMBLE"), "{output}");
        assert!(output.contains("FROM-BODY"), "{output}");

        let (_, inputs) = doc.assemble_preamble().unwrap().unwrap();
        let digests: Vec<String> = inputs.iter().map(|r| r.digest.clone()).collect();
        let path = doc.format_path(&digests).expect("a cache directory");
        assert!(!path.exists(), "and nothing was dumped: {path:?}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn showing_a_document_reads_it_rather_than_remembering_it() {
        let dir = scratch("show");
        std::fs::write(dir.join("index.tex"), HELLO).unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"shown\"\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n\
             [[output]]\nname=\"bytes\"\ntype=\"disasm\"\n",
        )
        .unwrap();

        let shown = doc.show();
        assert!(shown.contains("name       shown"), "{shown}");
        assert!(shown.contains(&dir.display().to_string()), "{shown}");
        assert!(shown.contains("index.tex"), "{shown}");
        assert!(
            shown.contains("default") && shown.contains("bytes"),
            "{shown}"
        );
        assert!(
            shown.contains("shown.disasm"),
            "the file each profile writes: {shown}"
        );

        // The digest shown is the file's, so editing it changes what is shown.
        let before = shown.clone();
        std::fs::write(dir.join("index.tex"), "\\message{OTHER}\n\\end\n").unwrap();
        assert_ne!(doc.show(), before, "it reads the input, not a memory of it");

        // A document whose input has gone says so instead of pretending.
        std::fs::remove_file(dir.join("index.tex")).unwrap();
        assert!(doc.show().contains("cannot be read"), "{}", doc.show());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn dumping_produces_what_a_build_would_write_without_writing_it() {
        let dir = scratch("dump");
        std::fs::write(dir.join("index.tex"), HELLO).unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"d\"\n\
             [[output]]\nname=\"default\"\ntype=\"messages\"\n\
             [[output]]\nname=\"tok\"\ntype=\"tokens\"\n",
        )
        .unwrap();

        assert_eq!(doc.dump(None).unwrap().trim(), "HI");
        assert!(doc.dump(Some("tok")).unwrap().contains("Cs("));
        assert!(
            !dir.join("build").exists(),
            "a dump writes nothing: the build directory was not made"
        );

        // What it dumps is what a build writes, so the two cannot disagree.
        let built = doc.build(None).unwrap();
        assert_eq!(
            std::fs::read_to_string(&built.path).unwrap().trim(),
            doc.dump(None).unwrap().trim()
        );
        assert!(doc
            .dump(Some("nope"))
            .unwrap_err()
            .contains("no output named"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn watching_rebuilds_when_an_input_changes_and_not_otherwise() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::Duration;

        let dir = scratch("watch");
        std::fs::write(dir.join("index.tex"), HELLO).unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        // Tick 0 builds (nothing has been built yet); tick 1 sees no change;
        // tick 2 sees the edit; the fourth tick stops the loop.
        let ticks = AtomicUsize::new(0);
        let edited = dir.join("index.tex");
        let stop = || {
            let n = ticks.fetch_add(1, Ordering::SeqCst);
            if n == 2 {
                std::fs::write(
                    &edited,
                    "\\catcode`\\{=1 \\catcode`\\}=2 \\message{EDITED}\n\\end\n",
                )
                .unwrap();
            }
            n >= 4
        };
        let mut status = crate::status::CollectingStatus::new();
        let builds = doc
            .watch(None, Duration::from_millis(1), &mut status, &stop)
            .expect("watches");

        assert_eq!(builds, 2, "the first build, and the one the edit caused");
        let output = std::fs::read_to_string(dir.join("build/w.txt")).unwrap();
        assert_eq!(output.trim(), "EDITED", "the rebuild used the new content");
        assert_eq!(
            status
                .messages()
                .iter()
                .filter(|(level, _)| *level == crate::status::Level::Note)
                .count(),
            2,
            "one report per build: {:?}",
            status.messages()
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn watching_survives_a_document_that_does_not_compile() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::Duration;

        let dir = scratch("watch_broken");
        std::fs::write(dir.join("index.tex"), "\\undefined@thing\n").unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();

        let ticks = AtomicUsize::new(0);
        let fixed = dir.join("index.tex");
        let stop = || {
            let n = ticks.fetch_add(1, Ordering::SeqCst);
            if n == 1 {
                std::fs::write(&fixed, HELLO).unwrap();
            }
            n >= 3
        };
        let mut status = crate::status::CollectingStatus::new();
        doc.watch(None, Duration::from_millis(1), &mut status, &stop)
            .expect("keeps watching");

        // The broken state was reported and the loop carried on to the fix.
        assert!(status.had_error(), "the failure is reported");
        assert_eq!(
            std::fs::read_to_string(dir.join("build/w.txt"))
                .unwrap()
                .trim(),
            "HI",
            "and the document that compiles is built"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn watching_refuses_a_profile_that_is_not_there_before_it_starts() {
        let dir = scratch("watch_profile");
        std::fs::write(dir.join("index.tex"), HELLO).unwrap();
        let doc = Document::parse(
            &dir,
            "[doc]\nname=\"w\"\n[[output]]\nname=\"default\"\ntype=\"messages\"\n",
        )
        .unwrap();
        let mut status = crate::status::SilentStatus;
        let err = doc
            .watch(
                Some("nope"),
                std::time::Duration::from_millis(1),
                &mut status,
                &|| true,
            )
            .unwrap_err();
        assert!(err.contains("no output named"), "{err}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_scaffolded_document_builds_as_it_stands() {
        let dir = scratch("scaffold");
        let path = scaffold(&dir, "fresh").expect("scaffolds");
        assert!(path.ends_with(DOCUMENT_FILE));
        assert!(dir.join("index.tex").is_file(), "and a document to build");

        let doc = Document::open(&dir).expect("reads back");
        let built = doc.build(None).expect("builds");
        assert_eq!(
            std::fs::read_to_string(&built.path).unwrap().trim(),
            "hello from texrs"
        );

        // Scaffolding over a document is refused rather than overwriting one.
        assert!(scaffold(&dir, "again")
            .unwrap_err()
            .contains("already exists"));
        let _ = std::fs::remove_dir_all(&dir);
    }
}