Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/watch.rs

41.4 KiB, 65 runs

created by r1870400018:68736, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The settings of `austenite watch` and `austenite build`, and the loop that keeps a PDF fresh.
2//!
3//! The cases hold the precedence (default, then file, then each `--set`, and a named source over the
4//! `document` setting), every refusal by the key's name, the dotted `--set`, the choice of a document, the
5//! atomic swap of the finished PDF under readers that interleave their opens, the last good PDF kept when
6//! a compile or a settings reload fails, the cold compile a settings edit forces, and the absence of every
7//! metadata key from a default `build`.
8
9use oxedyne_fe2o3_austenite::compile::Session;
10use oxedyne_fe2o3_austenite::emit::pdf::PdfOptions;
11use oxedyne_fe2o3_austenite::flow::text::FontStore;
12use oxedyne_fe2o3_austenite::settings::{
13 self,
14 Settings,
15};
16use oxedyne_fe2o3_austenite::watch::{
17 self,
18 Bare,
19 Plan,
20 Run,
21 Spec,
22 Tick,
23};
24use oxedyne_fe2o3_core::prelude::Outcome;
25
26use std::path::{
27 Path,
28 PathBuf,
29};
30use std::sync::atomic::{
31 AtomicBool,
32 Ordering,
33};
34use std::sync::Arc;
35use std::time::Duration;
36
37// The footer reads the final page count, so a cold compile needs a second pass to learn it.
38const HEAD: &str = "#set page(width: 220pt, height: 130pt, margin: 16pt, numbering: \"1\",\n\
39 footer: context [Page #counter(page).display() of #counter(page).final().first()])\n\
40 #set text(size: 9pt)\n";
41
42const PARA: &str = "A paragraph with enough ordinary words in it to run on to a second line of the page.";
43
44// The invariant keys of a PDF that carries metadata, none of which a default build may hold.
45const META: &[&str] = &[
46 "/Info", "/Metadata", "xmpmeta", "/CreationDate", "/ModDate", "/Author", "/Creator", "/Producer", "/Keywords",
47];
48
49fn dir(name: &str) -> PathBuf {
50 let d = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("watch").join(name);
51 let _ = std::fs::remove_dir_all(&d);
52 std::fs::create_dir_all(&d).expect("the case's directory");
53 std::fs::canonicalize(&d).expect("the case's canonical path")
54}
55
56fn write(path: &Path, text: &str) {
57 if let Some(parent) = path.parent() {
58 std::fs::create_dir_all(parent).expect("a project directory");
59 }
60 std::fs::write(path, text).expect("a project file");
61}
62
63fn source(paras: usize, tag: &str) -> String {
64 let mut s = String::from(HEAD);
65 for i in 0..paras {
66 s.push_str(&format!("{} {}\n\n", PARA, if i == 0 { tag } else { "" }));
67 }
68 s
69}
70
71// Waits out the clock's grain so that a file written next carries a different modification time.
72fn later() {
73 std::thread::sleep(Duration::from_millis(30));
74}
75
76fn sets(items: &[&str]) -> Vec<String> {
77 items.iter().map(|s| s.to_string()).collect()
78}
79
80// A settings file's text: the viewer is off whatever else it holds, so that no test opens a window.
81fn conf(extra: &str) -> String {
82 if extra.is_empty() {
83 "{\"view\": {\"open\": false}}".to_string()
84 } else {
85 format!("{{\"view\": {{\"open\": false}}, {}}}", extra)
86 }
87}
88
89// A project of one document with a settings file; the viewer is always off.
90fn project(name: &str, extra: &str) -> (PathBuf, PathBuf) {
91 let d = dir(name);
92 let main = d.join("main.typ");
93 write(&main, &source(9, "q"));
94 write(&d.join(settings::FILE), &conf(extra));
95 // A file saved within a few milliseconds of a build's start is built again once, so a loop under test
96 // begins after the files are old enough to count as seen.
97 later();
98 (d, main)
99}
100
101// The reason a result was refused.
102fn why<T>(r: Outcome<T>) -> String {
103 match r {
104 Ok(_) => panic!("expected a refusal"),
105 Err(e) => e.plain(),
106 }
107}
108
109fn count(bytes: &[u8], needle: &str) -> usize {
110 let n = needle.as_bytes();
111 bytes.windows(n.len()).filter(|w| *w == n).count()
112}
113
114fn has(bytes: &[u8], needle: &str) -> bool {
115 count(bytes, needle) > 0
116}
117
118// ┌───────────────────────────────────────────────────────────────────────────┐
119// │ PRECEDENCE │
120// └───────────────────────────────────────────────────────────────────────────┘
121
122#[test]
123fn with_no_file_and_no_set_every_setting_is_its_default() {
124 let s = Settings::resolve(None, &[]).expect("the defaults");
125 assert_eq!(s.output, "{stem}.pdf");
126 assert_eq!(s.fonts, vec!["assets/fonts".to_string()]);
127 assert!(s.document.is_empty() && s.root.is_empty());
128 assert!(!s.strict);
129 assert_eq!(s.diagnostics, "errors");
130 assert_eq!((s.watch.poll_ms, s.watch.warm), (200, true));
131 assert_eq!((s.figs.dir.as_str(), s.figs.render), ("figs", true));
132 assert_eq!((s.colour.space.as_str(), s.colour.black.as_str()), ("native", "k"));
133 assert_eq!((s.metadata.document, s.metadata.engine), (false, false));
134 assert_eq!((s.pdf.version.as_str(), s.pdf.compress, s.pdf.outline), ("1.7", true, true));
135 assert_eq!((s.view.open, s.view.app.as_str()), (true, "auto"));
136}
137
138#[test]
139fn the_file_overrides_the_default_and_a_set_overrides_the_file() {
140 let d = dir("precedence");
141 let f = d.join(settings::FILE);
142 write(&f, "{\"strict\": true, \"pdf\": {\"compress\": false, \"version\": \"1.5\"}, \"watch\": {\"poll_ms\": 500}}");
143 let s = Settings::resolve(Some(&f), &sets(&["watch.poll_ms=50", "pdf.compress=true"])).expect("file and sets");
144 assert!(s.strict, "the file beats the default");
145 assert_eq!(s.pdf.version, "1.5", "the file beats the default");
146 assert_eq!(s.watch.poll_ms, 50, "a set beats the file");
147 assert!(s.pdf.compress, "a set beats the file, whatever the key's order");
148 assert!(s.watch.warm, "a key neither names keeps its default");
149}
150
151#[test]
152fn of_two_sets_for_one_key_the_later_wins() {
153 let s = Settings::resolve(None, &sets(&["watch.poll_ms=20", "watch.poll_ms=30"])).expect("two sets");
154 assert_eq!(s.watch.poll_ms, 30);
155}
156
157#[test]
158fn a_named_source_wins_over_the_document_setting() {
159 let (d, main) = project("named", "\"document\": \"main.typ\"");
160 let other = d.join("other.typ");
161 write(&other, &source(2, "z"));
162 let named = Plan::at(&d, Some(&other), &sets(&["view.open=false"]), None).expect("a named source");
163 assert_eq!(named.spec.main, other, "the source on the command line");
164 assert_eq!(named.spec.out, d.join("other.pdf"));
165 let unnamed = Plan::at(&d, None, &sets(&["view.open=false"]), None).expect("the document setting");
166 assert_eq!(unnamed.spec.main, main, "with no source the setting names the document");
167 // A set on the command line beats the file's `document` too, when no source is named.
168 let by_set = Plan::at(&d, None, &sets(&["document=other.typ"]), None).expect("a document by set");
169 assert_eq!(by_set.spec.main, other);
170}
171
172#[test]
173fn the_settings_file_is_found_by_walking_up_from_the_source() {
174 let (d, _) = project("walk", "\"output\": \"out/{stem}.pdf\"");
175 let deep = d.join("a").join("b").join("deep.typ");
176 write(&deep, &source(1, "d"));
177 let plan = Plan::at(&d, Some(&deep), &[], None).expect("a deep source");
178 assert_eq!(plan.file, Some(d.join(settings::FILE)));
179 assert_eq!(plan.spec.out, d.join("a").join("b").join("out").join("deep.pdf"), "an output beside the source");
180}
181
182// ┌───────────────────────────────────────────────────────────────────────────┐
183// │ REFUSALS │
184// └───────────────────────────────────────────────────────────────────────────┘
185
186#[test]
187fn an_unknown_key_is_refused_by_its_dotted_name_in_the_file_and_in_a_set() {
188 let d = dir("unknown");
189 let f = d.join(settings::FILE);
190 write(&f, "{\"pdf\": {\"compres\": true}}");
191 let m = why(Settings::resolve(Some(&f), &[]));
192 assert!(m.contains("pdf.compres"), "{}", m);
193 write(&f, "{\"nope\": 1}");
194 let m = why(Settings::resolve(Some(&f), &[]));
195 assert!(m.contains("nope"), "{}", m);
196 let m = why(Settings::resolve(None, &sets(&["colour.spce=rgb"])));
197 assert!(m.contains("colour.spce"), "{}", m);
198 let m = why(Settings::resolve(None, &sets(&["strict"])));
199 assert!(m.contains("strict") && m.contains('='), "{}", m);
200}
201
202#[test]
203fn a_value_of_the_wrong_type_is_refused_by_the_keys_name() {
204 let d = dir("types");
205 let f = d.join(settings::FILE);
206 write(&f, "{\"pdf\": {\"compress\": \"yes\"}}");
207 let m = why(Settings::resolve(Some(&f), &[]));
208 assert!(m.contains("pdf.compress"), "{}", m);
209 write(&f, "{\"output\": 5}");
210 let m = why(Settings::resolve(Some(&f), &[]));
211 assert!(m.contains("output"), "{}", m);
212 for (arg, key) in [("watch.poll_ms=fast", "watch.poll_ms"), ("strict=maybe", "strict"), ("view.open=1", "view.open")] {
213 let m = why(Settings::resolve(None, &sets(&[arg])));
214 assert!(m.contains(key), "{}: {}", arg, m);
215 }
216}
217
218#[test]
219fn a_value_out_of_range_is_refused_by_the_keys_name() {
220 let d = dir("range");
221 let f = d.join(settings::FILE);
222 write(&f, "{\"watch\": {\"poll_ms\": 5}}");
223 let m = why(Settings::resolve(Some(&f), &[]));
224 assert!(m.contains("watch.poll_ms"), "{}", m);
225 for arg in ["watch.poll_ms=5", "watch.poll_ms=60001"] {
226 let m = why(Settings::resolve(None, &sets(&[arg])));
227 assert!(m.contains("watch.poll_ms"), "{}: {}", arg, m);
228 }
229 for (arg, key) in [("pdf.version=1.3", "pdf.version"), ("diagnostics=loud", "diagnostics"), ("colour.black=pink", "colour.black")] {
230 let m = why(Settings::resolve(None, &sets(&[arg])));
231 assert!(m.contains(key), "{}: {}", arg, m);
232 }
233 assert!(Settings::resolve(None, &sets(&["watch.poll_ms=10", "watch.poll_ms=60000"])).is_ok(), "the ends of the range stand");
234}
235
236#[test]
237fn a_dotted_set_makes_the_levels_the_file_lacks_and_keeps_the_siblings() {
238 let s = Settings::resolve(None, &sets(&["colour.space=rgb", "fonts=a,b", "view.open=false"])).expect("dotted sets");
239 assert_eq!(s.colour.space, "rgb");
240 assert_eq!(s.colour.black, "k", "a sibling keeps its default");
241 assert_eq!(s.fonts, vec!["a".to_string(), "b".to_string()], "a list is comma separated");
242 assert!(!s.view.open);
243 let d = dir("dotted");
244 let f = d.join(settings::FILE);
245 write(&f, "{\"colour\": {\"black\": \"k\", \"intent\": \"perceptual\"}}");
246 let s = Settings::resolve(Some(&f), &sets(&["colour.space=rgb"])).expect("a set into a group");
247 assert_eq!((s.colour.space.as_str(), s.colour.intent.as_str()), ("rgb", "perceptual"));
248 // A key whose parent in the file is no map cannot take the set.
249 write(&f, "{\"colour\": 3}");
250 assert!(Settings::resolve(Some(&f), &sets(&["colour.space=rgb"])).is_err());
251}
252
253// The bundled profile, as a file, for a setting that names a profile by its path.
254fn fogra_file() -> String {
255 Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("fe2o3_graphics").join("data").join("icc")
256 .join("FOGRA39L_coated.icc").display().to_string()
257}
258
259#[test]
260fn a_colour_key_that_the_space_does_not_read_is_refused_by_its_key() {
261 let (d, main) = project("unread", "");
262 // Native and rgb read none of the profiles, the intent, the black point or the black.
263 for space in ["native", "rgb"] {
264 for (arg, key) in [
265 ("colour.rgb_profile=adobe", "colour.rgb_profile"),
266 ("colour.grey_profile=gamma", "colour.grey_profile"),
267 ("colour.cmyk_profile=swop", "colour.cmyk_profile"),
268 ("colour.intent=relative", "colour.intent"),
269 ("colour.black=rich", "colour.black"),
270 ("colour.black_point=false", "colour.black_point"),
271 ] {
272 let m = why(Plan::at(&d, Some(&main), &sets(&[format!("colour.space={}", space).as_str(), arg]), None));
273 assert!(m.contains(key), "{} {}: {}", space, arg, m);
274 assert!(m.contains("applies only when 'colour.space' is"), "{} {}: {}", space, arg, m);
275 }
276 }
277 // Cmyk does not read the grey profile, and grey does not read the black.
278 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk", "colour.grey_profile=gamma"]), None));
279 assert!(m.contains("colour.grey_profile") && m.contains("\"grey\""), "{}", m);
280 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=grey", "colour.black=rich"]), None));
281 assert!(m.contains("colour.black") && m.contains("\"cmyk\""), "{}", m);
282 // What is read is accepted, and what is only the default is never refused.
283 for arg in [
284 &["colour.space=native"][..], &["colour.space=rgb", "colour.black=k", "colour.black_point=true"],
285 &["colour.space=cmyk", "colour.black=rich", "colour.intent=relative", "colour.black_point=false"],
286 &["colour.space=grey", "colour.intent=relative", "colour.black_point=false"],
287 ] {
288 assert!(Plan::at(&d, Some(&main), &sets(arg), None).is_ok(), "{:?} is built", arg);
289 }
290}
291
292#[test]
293fn turning_off_a_black_point_compensation_that_every_transform_forces_is_refused_by_its_key() {
294 let (d, main) = project("forced-bpc", "");
295 // The built-in grey profile is version 4, into which perceptual and saturation always compensate, and the
296 // absolute intent never does: the setting would change nothing.
297 for intent in ["perceptual", "saturation", "absolute"] {
298 let i = format!("colour.intent={}", intent);
299 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=grey", i.as_str(), "colour.black_point=false"]), None));
300 assert!(m.contains("colour.black_point") && m.contains(intent), "{}: {}", intent, m);
301 }
302 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk", "colour.intent=absolute", "colour.black_point=false"]), None));
303 assert!(m.contains("colour.black_point"), "cmyk absolute: {}", m);
304 // The bundled CMYK profile is version 2, so perceptual compensates only when asked.
305 for arg in [
306 &["colour.space=cmyk", "colour.black_point=false"][..],
307 &["colour.space=grey", "colour.intent=relative", "colour.black_point=false"],
308 &["colour.space=grey", "colour.black_point=true"],
309 ] {
310 assert!(Plan::at(&d, Some(&main), &sets(arg), None).is_ok(), "{:?} is built", arg);
311 }
312}
313
314#[test]
315fn a_file_setting_a_set_makes_inapplicable_is_warned_once_and_the_run_goes_on() {
316 let (d, main) = project("layered_warn", "\"colour\": {\"space\": \"cmyk\", \"black\": \"rich\"}");
317 let plan = Plan::at(&d, Some(&main), &sets(&["colour.space=grey"]), None).expect("the run goes on");
318 assert_eq!(plan.warned.len(), 1, "one warning: {:?}", plan.warned);
319 assert!(plan.warned[0].contains("colour.black") && plan.warned[0].contains("\"grey\""), "{}", plan.warned[0]);
320 let plan = Plan::at(&d, Some(&main), &[], None).expect("the file alone is consistent");
321 assert!(plan.warned.is_empty(), "{:?}", plan.warned);
322}
323
324#[test]
325fn a_file_inconsistent_in_itself_is_refused_whatever_the_sets() {
326 let (d, main) = project("layered_file", "\"colour\": {\"space\": \"rgb\", \"black\": \"rich\"}");
327 let m = why(Plan::at(&d, Some(&main), &[], None));
328 assert!(m.contains("colour.black"), "{}", m);
329 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk"]), None));
330 assert!(m.contains("colour.black") && m.contains(settings::FILE), "{}", m);
331}
332
333#[test]
334fn a_set_that_is_itself_inapplicable_is_refused_over_a_file() {
335 let (d, main) = project("layered_set", "\"colour\": {\"space\": \"cmyk\"}");
336 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.space=grey", "colour.black=rich"]), None));
337 assert!(m.contains("colour.black"), "{}", m);
338 let (d, main) = project("layered_set_grey", "\"colour\": {\"space\": \"grey\"}");
339 let m = why(Plan::at(&d, Some(&main), &sets(&["colour.black=rich"]), None));
340 assert!(m.contains("colour.black"), "{}", m);
341}
342
343#[test]
344fn a_profile_that_cannot_serve_its_role_is_refused_by_its_key() {
345 let (d, main) = project("profiles", "");
346 let fogra = fogra_file();
347 let cases: [(&str, String); 4] = [
348 ("colour.cmyk_profile", "missing.icc".to_string()),
349 ("colour.rgb_profile", fogra.clone()),
350 ("colour.grey_profile", fogra.clone()),
351 ("colour.cmyk_profile", format!("{}", d.join("main.typ").display())),
352 ];
353 for (key, value) in cases {
354 let space = if key == "colour.grey_profile" { "grey" } else { "cmyk" };
355 let m = why(Plan::at(&d, Some(&main), &sets(&[format!("colour.space={}", space).as_str(), format!("{}={}", key, value).as_str()]), None));
356 assert!(m.contains(key), "{} = {}: {}", key, value, m);
357 }
358 // A CMYK profile named by its path serves, as the bundled word does.
359 let named = format!("colour.cmyk_profile={}", fogra);
360 assert!(Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk", named.as_str()]), None).is_ok());
361 assert!(Plan::at(&d, Some(&main), &sets(&["colour.space=grey", named.as_str()]), None).is_ok());
362}
363
364#[test]
365fn the_colour_space_builds_the_writers_mode() {
366 let (d, main) = project("modes", "");
367 for (space, converts) in [("native", false), ("rgb", false), ("cmyk", true), ("grey", true)] {
368 let p = Plan::at(&d, Some(&main), &sets(&[format!("colour.space={}", space).as_str()]), None).expect("a built space");
369 assert_eq!(p.spec.pdf.colour.converts(), converts, "{}", space);
370 assert_eq!(p.spec.pdf.colour.group_space().is_some(), converts, "{}", space);
371 }
372 let rich = Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk", "colour.black=rich"]), None).expect("rich");
373 let k = Plan::at(&d, Some(&main), &sets(&["colour.space=cmyk"]), None).expect("k only");
374 assert_ne!(rich.spec.pdf.colour, k.spec.pdf.colour, "the black changes what is written");
375}
376
377#[test]
378fn figure_rendering_is_refused_while_a_figures_directory_stands_beside_the_document() {
379 let (d, main) = project("figs", "");
380 assert!(Plan::at(&d, Some(&main), &[], None).is_ok(), "no figures directory, nothing to render");
381 write(&d.join("figs").join("one.typ"), "x");
382 let m = why(Plan::at(&d, Some(&main), &[], None));
383 assert!(m.contains("figs.render"), "{}", m);
384 assert!(Plan::at(&d, Some(&main), &sets(&["figs.render=false"]), None).is_ok(), "switched off, it goes on");
385 assert!(Plan::at(&d, Some(&main), &sets(&["figs.dir=pictures"]), None).is_ok(), "another name, nothing there");
386}
387
388// ┌───────────────────────────────────────────────────────────────────────────┐
389// │ THE DOCUMENT │
390// └───────────────────────────────────────────────────────────────────────────┘
391
392#[test]
393fn the_document_is_the_one_typ_that_no_other_imports() {
394 let d = dir("select_one");
395 write(&d.join("main.typ"), "#include \"part.typ\"\n#import \"lib.typ\": f\n");
396 write(&d.join("part.typ"), "x");
397 write(&d.join("lib.typ"), "#let f = 1");
398 write(&d.join("notes.txt"), "not a source");
399 assert_eq!(settings::select_document(&d).expect("one root"), d.join("main.typ"));
400}
401
402#[test]
403fn several_roots_are_refused_and_named() {
404 let d = dir("select_many");
405 write(&d.join("a.typ"), "a");
406 write(&d.join("b.typ"), "b");
407 let m = why(settings::select_document(&d));
408 assert!(m.contains("a.typ") && m.contains("b.typ"), "{}", m);
409}
410
411#[test]
412fn a_directory_with_no_root_or_no_source_is_refused() {
413 let d = dir("select_none");
414 let m = why(settings::select_document(&d));
415 assert!(m.contains("No document"), "{}", m);
416 write(&d.join("a.typ"), "#import \"b.typ\"");
417 write(&d.join("b.typ"), "#import \"a.typ\"");
418 let m = why(settings::select_document(&d));
419 assert!(m.contains("No document"), "{}", m);
420}
421
422// ┌───────────────────────────────────────────────────────────────────────────┐
423// │ BUILD │
424// └───────────────────────────────────────────────────────────────────────────┘
425
426#[test]
427fn a_default_build_holds_none_of_the_metadata_keys() {
428 let (_, main) = project("meta", "");
429 let mut text = String::from("#set document(title: \"Title\", author: \"Author\", keywords: (\"kw\",))\n");
430 text.push_str(&source(9, "q"));
431 write(&main, &text);
432 let (plan, report) = watch::build(Some(&main), &sets(&["view.open=false"]), &[], None).expect("a build");
433 assert!(report.pages >= 1);
434 let bytes = std::fs::read(&plan.spec.out).expect("the PDF");
435 assert!(bytes.starts_with(b"%PDF-1.7"), "the default version");
436 for key in META {
437 assert!(!has(&bytes, key), "the default PDF holds {}", key);
438 }
439 // The same document asked for its metadata does carry it, so the absence above is the setting's doing.
440 let (plan, _) = watch::build(Some(&main), &sets(&["metadata.document=true", "metadata.engine=true"]), &[], None).expect("a build");
441 let bytes = std::fs::read(&plan.spec.out).expect("the PDF");
442 for key in ["/Info", "/Title", "/Author", "/Keywords", "/Creator", "/Producer"] {
443 assert!(has(&bytes, key), "the PDF with metadata lacks {}", key);
444 }
445 assert!(!has(&bytes, "/CreationDate") && !has(&bytes, "/ModDate"), "no date is ever written");
446}
447
448#[test]
449fn the_pdf_settings_shape_the_file() {
450 let (d, main) = project("shape", "");
451 let (plan, _) = watch::build(Some(&main), &[], &[], None).expect("the default");
452 let plain = std::fs::read(&plan.spec.out).expect("the PDF");
453 assert!(has(&plain, "/FlateDecode"), "compressed by default");
454 assert_eq!(plan.spec.out, d.join("main.pdf"));
455 let (plan, _) = watch::build(Some(&main), &sets(&["pdf.compress=false", "pdf.version=1.5", "output=sub/{stem}-x.pdf"]), &[], None).expect("changed");
456 let big = std::fs::read(&plan.spec.out).expect("the PDF");
457 assert_eq!(plan.spec.out, d.join("sub").join("main-x.pdf"));
458 assert!(big.starts_with(b"%PDF-1.5"));
459 // The fonts' streams stay compressed whatever the setting; the pages' do not.
460 assert!(count(&big, "/FlateDecode") < count(&plain, "/FlateDecode"), "page streams left whole");
461 assert!(big.len() > plain.len());
462 let (plan, _) = watch::build(Some(&main), &sets(&["pdf.outline=false"]), &[], None).expect("no outline");
463 let flat = std::fs::read(&plan.spec.out).expect("the PDF");
464 assert!(!has(&flat, "/Outlines"), "no bookmarks when the outline is off");
465}
466
467#[test]
468fn a_build_with_no_source_builds_the_document_the_settings_name() {
469 let (d, main) = project("nosource", "\"document\": \"main.typ\"");
470 let other = d.join("other.typ");
471 write(&other, &source(2, "z"));
472 later();
473 let (plan, report) = watch::build_at(&d, None, &[], &[], None).expect("the document setting");
474 assert_eq!(plan.spec.main, main, "with no source the setting names the document");
475 assert!(report.pages >= 1);
476 let named = std::fs::read(&plan.spec.out).expect("the PDF");
477 assert!(named.starts_with(b"%PDF-"), "a PDF was written");
478 // A named source still wins over the setting.
479 let (plan, _) = watch::build_at(&d, Some(&other), &[], &[], None).expect("a named source");
480 assert_eq!(plan.spec.main, other, "the named source");
481 assert_eq!(plan.spec.out, d.join("other.pdf"));
482 // With neither a source nor a setting, the one document that no other imports is built.
483 let (alone, only) = project("nosource_rule", "");
484 let (plan, _) = watch::build_at(&alone, None, &[], &[], None).expect("the selection rule");
485 assert_eq!(plan.spec.main, only, "the rule picks the one root");
486}
487
488#[test]
489fn two_builds_of_one_document_are_the_same_bytes() {
490 let (_, main) = project("again", "");
491 let (plan, _) = watch::build(Some(&main), &[], &[], None).expect("first");
492 let one = std::fs::read(&plan.spec.out).expect("the PDF");
493 let (plan, _) = watch::build(Some(&main), &[], &[], None).expect("second");
494 let two = std::fs::read(&plan.spec.out).expect("the PDF");
495 assert!(one == two, "a build is deterministic");
496}
497
498// ┌───────────────────────────────────────────────────────────────────────────┐
499// │ THE SWAP │
500// └───────────────────────────────────────────────────────────────────────────┘
501
502fn spec(main: &Path, out: &Path) -> Spec {
503 Spec {
504 main: main.to_path_buf(),
505 root: main.parent().expect("the main's directory").to_path_buf(),
506 out: out.to_path_buf(),
507 strict: false,
508 diag_summary: false,
509 timings: None,
510 timings_fine: false,
511 pdf: PdfOptions { compress: false, ..PdfOptions::default() },
512 inputs: Vec::new(),
513 }
514}
515
516#[test]
517fn a_reader_meets_one_whole_pdf_or_the_other_while_the_compile_swaps_a_new_one_in() {
518 let d = dir("swap");
519 let a = d.join("a.typ");
520 let b = d.join("b.typ");
521 write(&a, &source(40, "a"));
522 write(&b, &source(40, "b"));
523 let mut session = Session::new(FontStore::default());
524 let mut read = Vec::new();
525 let mut known = Vec::new();
526 for (main, name) in [(&a, "a.pdf"), (&b, "b.pdf")] {
527 let out = d.join(name);
528 watch::compile_pdf(&spec(main, &out), &mut session, true, false, &mut read).expect("a known PDF");
529 known.push(std::fs::read(&out).expect("its bytes"));
530 }
531 let (known_a, known_b) = (Arc::new(known[0].clone()), Arc::new(known[1].clone()));
532 assert!(known_a != known_b, "the two documents differ");
533 let live = d.join("live.pdf");
534 watch::compile_pdf(&spec(&a, &live), &mut session, true, false, &mut read).expect("the first live PDF");
535 let stop = Arc::new(AtomicBool::new(false));
536 let mut readers = Vec::new();
537 for _ in 0..3 {
538 let (live, stop, ka, kb) = (live.clone(), stop.clone(), known_a.clone(), known_b.clone());
539 readers.push(std::thread::spawn(move || {
540 let (mut reads, mut torn) = (0u32, 0u32);
541 while !stop.load(Ordering::Relaxed) {
542 match std::fs::read(&live) {
543 Ok(bytes) => {
544 reads += 1;
545 if bytes != *ka && bytes != *kb {
546 torn += 1;
547 }
548 },
549 Err(_) => torn += 1,
550 }
551 }
552 (reads, torn)
553 }));
554 }
555 for i in 0..14 {
556 let main = if i % 2 == 0 { &b } else { &a };
557 watch::compile_pdf(&spec(main, &live), &mut session, true, false, &mut read).expect("a swap");
558 }
559 stop.store(true, Ordering::Relaxed);
560 let (mut reads, mut torn) = (0, 0);
561 for r in readers {
562 let (n, t) = r.join().expect("a reader");
563 reads += n;
564 torn += t;
565 }
566 assert!(reads > 50, "the readers read {} times, too few to mean anything", reads);
567 assert_eq!(torn, 0, "{} of {} reads met something other than a whole PDF", torn, reads);
568 assert_eq!(temporaries(&d), Vec::<String>::new(), "no half-written file is left beside the PDF");
569}
570
571// What a writer may have left in `d`: a `.part`, a `.tmp`, or any hidden file.
572fn temporaries(d: &Path) -> Vec<String> {
573 let mut left: Vec<String> = std::fs::read_dir(d).expect("the case's directory")
574 .map(|e| e.expect("an entry").file_name().to_string_lossy().into_owned())
575 .filter(|n| n.ends_with(".part") || n.ends_with(".tmp") || n.starts_with('.'))
576 .collect();
577 left.sort();
578 left
579}
580
581#[test]
582fn a_slow_writer_still_writing_its_temporary_never_reaches_the_finished_pdf() {
583 let d = dir("slow_writer");
584 let a = d.join("a.typ");
585 write(&a, &source(40, "a"));
586 let out = d.join("out.pdf");
587 // The other writer, as `austenite build` beside a watch: it has its temporary open and has yet to write.
588 let mut beside = out.as_os_str().to_owned();
589 beside.push(".part");
590 let held = PathBuf::from(beside);
591 let mut slow = std::fs::OpenOptions::new().write(true).create(true).truncate(true).open(&held).expect("the slow writer's file");
592 let mut session = Session::new(FontStore::default());
593 let mut read = Vec::new();
594 watch::compile_pdf(&spec(&a, &out), &mut session, true, false, &mut read).expect("the fast writer");
595 std::io::Write::write_all(&mut slow, b"%PDF-1.7 the slow writer's bytes\n%%EOF\n").expect("the slow writer's write");
596 drop(slow);
597 let bytes = std::fs::read(&out).expect("the PDF");
598 assert!(bytes.starts_with(b"%PDF-"), "the finished PDF begins as a PDF");
599 assert_eq!(count(&bytes, "%%EOF"), 1, "the finished PDF holds one end-of-file marker, its own");
600 assert!(!has(&bytes, "slow writer"), "nothing the other writer wrote reached the finished PDF");
601 std::fs::remove_file(&held).expect("the slow writer's file");
602 assert_eq!(temporaries(&d), Vec::<String>::new(), "the fast writer left nothing beside the PDF");
603}
604
605#[test]
606fn two_writers_of_one_output_leave_one_whole_pdf_and_no_temporary() {
607 let d = dir("two_writers");
608 let a = d.join("a.typ");
609 let b = d.join("b.typ");
610 write(&a, &source(40, "a"));
611 write(&b, &source(40, "b"));
612 let out = d.join("out.pdf");
613 let mut workers = Vec::new();
614 for main in [a.clone(), b.clone()] {
615 let out = out.clone();
616 workers.push(std::thread::spawn(move || {
617 let mut session = Session::new(FontStore::default());
618 let mut read = Vec::new();
619 for _ in 0..6 {
620 watch::compile_pdf(&spec(&main, &out), &mut session, true, false, &mut read).expect("each writer's compile");
621 }
622 }));
623 }
624 for w in workers {
625 w.join().expect("a writer");
626 }
627 let bytes = std::fs::read(&out).expect("the PDF");
628 assert_eq!(count(&bytes, "%%EOF"), 1, "one whole PDF, one end-of-file marker");
629 assert_eq!(temporaries(&d), Vec::<String>::new(), "no temporary is left beside the PDF");
630}
631
632#[test]
633fn a_write_that_fails_leaves_no_temporary_beside_the_output() {
634 let d = dir("failed_write");
635 let a = d.join("a.typ");
636 write(&a, &source(3, "a"));
637 // An output the swap cannot land on: a directory that is not empty.
638 let held = d.join("held");
639 write(&held.join("inner.txt"), "kept");
640 let mut session = Session::new(FontStore::default());
641 let mut read = Vec::new();
642 assert!(watch::compile_pdf(&spec(&a, &held), &mut session, true, false, &mut read).is_err(), "the write fails");
643 assert_eq!(std::fs::read_to_string(held.join("inner.txt")).expect("the directory's file"), "kept");
644 assert_eq!(temporaries(&d), Vec::<String>::new(), "a failed write leaves nothing beside the output");
645}
646
647// ┌───────────────────────────────────────────────────────────────────────────┐
648// │ THE OUTPUT │
649// └───────────────────────────────────────────────────────────────────────────┘
650
651#[test]
652fn an_output_that_would_replace_the_source_a_directory_or_a_link_is_refused_by_name() {
653 let (d, main) = project("output_refused", "");
654 write(&d.join("sub").join("x.txt"), "x");
655 write(&d.join("elsewhere.pdf"), "the link's target");
656 std::os::unix::fs::symlink(d.join("elsewhere.pdf"), d.join("link.pdf")).expect("a symlink");
657 for (set, said) in [
658 ("output=", "empty"),
659 ("output=main.typ", "main.typ"),
660 ("output=sub", "sub"),
661 ("output=link.pdf", "link.pdf"),
662 ] {
663 let m = why(Plan::at(&d, Some(&main), &sets(&[set]), None));
664 assert!(m.contains("'output'"), "{}: {}", set, m);
665 assert!(m.contains(said), "{}: {}", set, m);
666 }
667 assert_eq!(std::fs::read_to_string(d.join("link.pdf")).expect("through the link"), "the link's target");
668 assert!(std::fs::symlink_metadata(d.join("link.pdf")).expect("the link").file_type().is_symlink());
669 assert!(Plan::at(&d, Some(&main), &sets(&["output=out/new.pdf"]), None).is_ok(), "a new file is fine");
670}
671
672#[test]
673fn an_output_the_compile_reads_is_refused_and_left_untouched() {
674 let (d, main) = project("output_read", "");
675 let fore = "A foreword of a few words.\n";
676 write(&d.join("foreword.typ"), fore);
677 write(&main, &format!("{}#include \"foreword.typ\"\n\n{}\n", HEAD, PARA));
678 let m = why(watch::build_at(&d, Some(&main), &sets(&["view.open=false", "output=foreword.typ"]), &[], None));
679 assert!(m.contains("'output'") && m.contains("foreword.typ"), "{}", m);
680 assert_eq!(std::fs::read_to_string(d.join("foreword.typ")).expect("the foreword"), fore, "the foreword is untouched");
681 assert_eq!(temporaries(&d), Vec::<String>::new(), "a refused write leaves nothing beside the output");
682}
683
684// ┌───────────────────────────────────────────────────────────────────────────┐
685// │ THE LOOP │
686// └───────────────────────────────────────────────────────────────────────────┘
687
688fn run_of(main: &Path, extra: &[&str]) -> Run {
689 let mut s = vec!["view.open=false"];
690 s.extend_from_slice(extra);
691 Run::new(Some(main.to_path_buf()), sets(&s), Vec::new(), false, None).expect("a run")
692}
693
694fn built(t: Tick) -> watch::Report {
695 match t {
696 Tick::Built(r) => r,
697 Tick::Idle => panic!("expected a build, the tick was idle"),
698 Tick::Failed(why) => panic!("expected a build, it failed: {}", why),
699 }
700}
701
702#[test]
703fn the_first_tick_builds_cold_and_an_untouched_project_is_idle() {
704 let (d, main) = project("tick_first", "");
705 let mut run = run_of(&main, &[]);
706 let r = built(run.tick().expect("tick one"));
707 assert!(!r.warm && r.passes >= 2, "cold: warm {}, passes {}", r.warm, r.passes);
708 assert!(d.join("main.pdf").is_file());
709 assert!(matches!(run.tick().expect("tick two"), Tick::Idle), "nothing changed");
710 assert!(run.line(&r).contains("cold"), "{}", run.line(&r));
711}
712
713#[test]
714fn an_edit_is_compiled_warm_in_one_pass_to_the_bytes_a_cold_build_gives() {
715 let (d, main) = project("tick_warm", "");
716 let mut run = run_of(&main, &[]);
717 built(run.tick().expect("tick one"));
718 later();
719 write(&main, &source(9, "edited"));
720 let r = built(run.tick().expect("tick two"));
721 assert!(r.warm, "the second compile starts from the first's introspector");
722 assert_eq!(r.passes, 1, "and settles in one pass");
723 let warm = std::fs::read(d.join("main.pdf")).expect("the PDF");
724 let cold_dir = dir("tick_warm_cold");
725 let cold_main = cold_dir.join("main.typ");
726 write(&cold_main, &source(9, "edited"));
727 let (plan, _) = watch::build(Some(&cold_main), &sets(&["view.open=false"]), &[], None).expect("a cold build");
728 assert!(warm == std::fs::read(&plan.spec.out).expect("the cold PDF"), "warm and cold bytes differ");
729 assert!(run.line(&r).contains("warm"));
730}
731
732#[test]
733fn a_compile_that_fails_leaves_the_last_good_pdf_as_it_was_and_the_loop_goes_on() {
734 let (d, main) = project("tick_fail", "");
735 let mut run = run_of(&main, &[]);
736 built(run.tick().expect("tick one"));
737 let out = d.join("main.pdf");
738 let good = std::fs::read(&out).expect("the PDF");
739 later();
740 write(&main, &format!("{}\n#nosuchname\n", source(9, "q")));
741 match run.tick().expect("tick two") {
742 Tick::Failed(why) => assert!(!why.is_empty(), "the failure is told"),
743 other => panic!("expected a failure, got {:?}", other),
744 }
745 assert!(std::fs::read(&out).expect("the PDF still there") == good, "the last good PDF is as it was");
746 assert!(matches!(run.tick().expect("tick three"), Tick::Idle), "the failure is told once");
747 later();
748 write(&main, &source(9, "mended"));
749 built(run.tick().expect("tick four"));
750 assert!(std::fs::read(&out).expect("the PDF") != good, "the mended source gives a new PDF");
751}
752
753#[test]
754fn a_settings_edit_reloads_the_settings_and_compiles_cold_once() {
755 let (d, main) = project("tick_settings", "\"pdf\": {\"version\": \"1.7\"}");
756 let mut run = run_of(&main, &[]);
757 built(run.tick().expect("tick one"));
758 let out = d.join("main.pdf");
759 assert!(std::fs::read(&out).expect("the PDF").starts_with(b"%PDF-1.7"));
760 later();
761 write(&main, &source(9, "edited"));
762 assert!(built(run.tick().expect("tick two")).warm, "an edit of the source compiles warm");
763 later();
764 write(&d.join(settings::FILE), &conf("\"pdf\": {\"version\": \"1.5\"}"));
765 let r = built(run.tick().expect("tick three"));
766 assert!(!r.warm, "a settings edit compiles cold");
767 assert!(std::fs::read(&out).expect("the PDF").starts_with(b"%PDF-1.5"), "the new setting is in force");
768 later();
769 write(&main, &source(9, "edited again"));
770 assert!(built(run.tick().expect("tick four")).warm, "and the compile after it is warm again");
771}
772
773#[test]
774fn a_settings_file_that_no_longer_reads_keeps_the_old_settings_and_is_told_once() {
775 let (d, main) = project("tick_badsettings", "\"pdf\": {\"version\": \"1.6\"}");
776 let mut run = run_of(&main, &[]);
777 built(run.tick().expect("tick one"));
778 let out = d.join("main.pdf");
779 let good = std::fs::read(&out).expect("the PDF");
780 assert!(good.starts_with(b"%PDF-1.6"));
781 later();
782 write(&d.join(settings::FILE), &conf("\"pdf\": {\"version\": \"9.9\"}"));
783 match run.tick().expect("tick two") {
784 Tick::Failed(why) => assert!(why.contains("pdf.version"), "{}", why),
785 other => panic!("expected a failure, got {:?}", other),
786 }
787 assert!(std::fs::read(&out).expect("the PDF") == good, "the last good PDF is as it was");
788 assert!(matches!(run.tick().expect("tick three"), Tick::Idle), "told once");
789 later();
790 write(&d.join(settings::FILE), &conf("\"pdf\": {\"version\": \"1.4\"}"));
791 built(run.tick().expect("tick four"));
792 assert!(std::fs::read(&out).expect("the PDF").starts_with(b"%PDF-1.4"), "the mended file takes effect");
793}
794
795#[test]
796fn watch_warm_off_compiles_cold_every_time() {
797 let (_, main) = project("tick_nowarm", "\"watch\": {\"warm\": false}");
798 let mut run = run_of(&main, &[]);
799 built(run.tick().expect("tick one"));
800 later();
801 write(&main, &source(9, "edited"));
802 assert!(!built(run.tick().expect("tick two")).warm);
803}
804
805
806// ┌───────────────────────────────────────────────────────────────────────────┐
807// │ THE ALIAS │
808// └───────────────────────────────────────────────────────────────────────────┘
809
810// What `--eval --watch SRC OUT` hands the plan, with nothing else asked.
811fn bare(source: &str, out: &str) -> Bare {
812 Bare {
813 source: PathBuf::from(source),
814 out_dir: PathBuf::from(out),
815 root: None,
816 fonts: Vec::new(),
817 strict: false,
818 diag_summary: false,
819 timings: None,
820 timings_fine: false,
821 inputs: Vec::new(),
822 }
823}
824
825// A settings file above the source that a bare run would obey in every particular, were it read.
826const LOUD: &str = "{\"output\": \"elsewhere.pdf\", \"strict\": true, \"colour\": {\"space\": \"cmyk\"}, \
827 \"pdf\": {\"version\": \"1.5\"}}";
828
829#[test]
830fn a_bare_plan_reads_no_settings_file_and_takes_its_paths_from_the_working_directory() {
831 let d = dir("bare_plan");
832 write(&d.join("sub").join("doc.typ"), &source(2, "q"));
833 write(&d.join("sub").join("figs").join("one.typ"), "x");
834 write(&d.join(settings::FILE), LOUD);
835 let p = Plan::bare(&d, &bare("sub/doc.typ", "out")).expect("a bare plan");
836 assert!(p.file.is_none(), "no settings file is found, though one stands above the source");
837 assert_eq!((p.settings.colour.space.as_str(), p.settings.strict, p.settings.pdf.version.as_str()), ("native", false, "1.7"));
838 assert_eq!(p.spec.out, d.join("out").join("document.pdf"), "the directory is the working directory's, not the source's");
839 assert_eq!(p.spec.root, d.join("sub"), "the source's directory is the root");
840 assert!(!p.settings.view.open && p.settings.viewer().is_none(), "no viewer opens");
841 assert!(!p.settings.figs.render, "a figures directory beside the document is not refused");
842 assert!(p.settings.fonts.is_empty(), "no font directory but the ones named");
843 let mut named = bare("sub/doc.typ", "/elsewhere");
844 named.root = Some(PathBuf::from("."));
845 named.fonts = vec![PathBuf::from("fonts"), PathBuf::from("/abs/fonts")];
846 named.diag_summary = true;
847 named.timings_fine = true;
848 let q = Plan::bare(&d, &named).expect("a bare plan with its flags");
849 assert_eq!(q.spec.out, PathBuf::from("/elsewhere/document.pdf"), "an absolute directory stands");
850 assert_eq!(std::fs::canonicalize(&q.spec.root).expect("the root"), d, "--root is taken from the working directory");
851 assert_eq!(q.settings.fonts, vec![d.join("fonts").display().to_string(), "/abs/fonts".to_string()]);
852 assert!(q.spec.diag_summary && q.spec.timings_fine);
853}
854
855#[test]
856fn a_bare_run_neither_reads_nor_watches_a_settings_file() {
857 let d = dir("bare_run");
858 let main = d.join("main.typ");
859 write(&main, &source(9, "q"));
860 write(&d.join(settings::FILE), LOUD);
861 later();
862 let mut run = Run::bare(&d, &bare("main.typ", "out")).expect("a bare run");
863 built(run.tick().expect("tick one"));
864 let out = d.join("out").join("document.pdf");
865 let first = std::fs::read(&out).expect("the PDF in the output directory");
866 assert!(first.starts_with(b"%PDF-1.7"), "the file above is not read");
867 assert!(!has(&first, "/DeviceCMYK"), "and its colour space is not applied");
868 assert!(!d.join("elsewhere.pdf").exists() && !d.join("main.pdf").exists(), "nothing is written beside the source");
869 assert!(matches!(run.tick().expect("tick two"), Tick::Idle), "nothing changed");
870 later();
871 write(&d.join(settings::FILE), &conf("\"pdf\": {\"version\": \"1.5\"}"));
872 assert!(matches!(run.tick().expect("tick three"), Tick::Idle), "an edit of the settings file is not seen");
873 later();
874 write(&main, &source(9, "edited"));
875 assert!(built(run.tick().expect("tick four")).warm, "an edit of the source compiles warm: no settings reload");
876 assert!(std::fs::read(&out).expect("the PDF").starts_with(b"%PDF-1.7"), "still the defaults");
877}
878
879#[test]
880fn the_same_file_read_by_a_watch_is_applied() {
881 // The foil of the cases above: were the file read, its colour space would be in the PDF.
882 let d = dir("bare_foil");
883 let main = d.join("main.typ");
884 write(&main, &source(2, "q"));
885 write(&d.join(settings::FILE), &conf("\"colour\": {\"space\": \"cmyk\"}"));
886 later();
887 let mut run = run_of(&main, &[]);
888 built(run.tick().expect("tick one"));
889 assert!(has(&std::fs::read(d.join("main.pdf")).expect("the PDF"), "/DeviceCMYK"), "the CMYK group is written");
890}