math-core-cli 0.8.0

CLI for converting LaTeX equations to MathML Core
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
//! End-to-end tests that run the `mathcore` binary itself.
//!
//! The unit tests in `main.rs` call `replace` directly and therefore cover none of the argument
//! parsing, config discovery, file handling or exit codes. These tests drive the actual binary
//! that cargo builds for this test run, via `CARGO_BIN_EXE_mathcore`.

use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

// `pass_stdin` resolves through the `SpawnExt` trait that `assert_cmd_snapshot!` brings into
// scope itself, so the trait does not need to be imported here.
use insta_cmd::assert_cmd_snapshot;
use tempfile::TempDir;

/// A document whose *first* formula refers to an equation that only a *later* formula defines.
const FORWARD_REF_DOC: &str = r"<p>See $\eqref{eq:a}$.</p>
<p>$$\begin{align} x = 1 \label{eq:a}\end{align}$$</p>
";

/// A document with a single numbered equation and a reference to it.
const NUMBERED_DOC: &str = r"<p>$$\begin{align} a = 1 \label{eq:x}\end{align}$$ and $\eqref{eq:x}$</p>
";

/// A document that converts without an error but refers to an equation that is never defined,
/// which `math-core` reports as a warning.
const UNDEFINED_REF_DOC: &str = r"<p>See $\eqref{nope}$ and
later $\eqref{alsonope}$.</p>
";

/// Run the `mathcore` binary that cargo built for this test run.
///
/// The working directory is always pinned by the caller: the CLI looks for `mathcore.toml`
/// relative to the current directory, and the repository root has one, so an inherited working
/// directory would silently change the output.
fn mathcore(dir: &Path) -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_mathcore"));
    cmd.current_dir(dir);
    cmd
}

/// A directory that is guaranteed not to contain a `mathcore.toml`, so the defaults apply.
fn empty_dir() -> TempDir {
    TempDir::new().expect("failed to create temporary directory")
}

/// Snapshot settings that drop the ANSI color codes from the `ariadne` error reports, which the
/// CLI emits unconditionally.
fn settings() -> insta::Settings {
    let mut settings = insta::Settings::clone_current();
    settings.set_strip_ansi_escape_codes(true);
    settings
}

fn write(dir: &Path, name: &str, content: &str) -> PathBuf {
    let path = dir.join(name);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("failed to create directory");
    }
    fs::write(&path, content).expect("failed to write file");
    path
}

/// Run a command with `input` on stdin and collect its output.
///
/// `insta_cmd`'s `pass_stdin` only leads into a snapshot assertion, so tests that want to look at
/// the output themselves pipe stdin by hand.
fn run_with_stdin(mut cmd: Command, input: &str) -> Output {
    cmd.stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().expect("failed to run mathcore");
    child
        .stdin
        .take()
        .expect("stdin was not piped")
        .write_all(input.as_bytes())
        .expect("failed to write to stdin");
    child.wait_with_output().expect("failed to run mathcore")
}

fn read(path: &Path) -> String {
    fs::read_to_string(path).expect("failed to read file")
}

// ---------------------------------------------------------------------------------------------
// Single-formula mode
// ---------------------------------------------------------------------------------------------

#[test]
fn formula_block() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).args(["--formula", "x^2", "--block"]));
    });
}

#[test]
fn formula_from_stdin() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).pass_stdin("a + b"));
    });
}

#[test]
fn formula_error_report() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).args(["--formula", r"\frac"]));
    });
}

// ---------------------------------------------------------------------------------------------
// HTML mode via stdin
// ---------------------------------------------------------------------------------------------

#[test]
fn html_from_stdin() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .arg("-")
                .pass_stdin("inline $a+b$ and block $$c$$\n")
        );
    });
}

/// The whole document is converted in one batch, so a reference to an equation further down the
/// document resolves to its number instead of `(??)`.
#[test]
fn forward_reference_resolves() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).arg("-").pass_stdin(FORWARD_REF_DOC));
    });
}

#[test]
fn html_entities_are_decoded() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .arg("-")
                .pass_stdin("$a &lt; b$ and $x &gt; y$\n")
        );
    });
}

#[test]
fn custom_delimiters() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .args(["--inline-open", r"\(", "--inline-close", r"\)", "-"])
                .pass_stdin(r"let \(a=1\) and $not math$")
        );
    });
}

// ---------------------------------------------------------------------------------------------
// Error reporting
// ---------------------------------------------------------------------------------------------

#[test]
fn latex_error_aborts_with_report() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .arg("-")
                .pass_stdin("good $x$ then bad $\\frac$\n")
        );
    });
}

#[test]
fn continue_on_error_inlines_the_error() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .args(["-", "--continue-on-error"])
                .pass_stdin("good $x$ then bad $\\frac$\n")
        );
    });
}

#[test]
fn unclosed_delimiter() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .arg("-")
                .pass_stdin("unclosed $delim\n")
        );
    });
}

#[test]
fn mismatched_delimiters() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(
            mathcore(dir.path())
                .arg("-")
                .pass_stdin("mismatch $$ and $ signs\n")
        );
    });
}

/// Colorization of the error reports follows the same rules as `clap`'s own colored output:
/// `NO_COLOR` wins over `CLICOLOR_FORCE`, which wins over the terminal detection, and both
/// variables count as set when they hold any non-empty value.
///
/// Both places that render a report are checked: the single-formula path and the HTML path, which
/// reports the error for one snippet of a document.
#[test]
fn color_follows_the_environment() {
    /// `stderr` of a run that fails with a colorizable `ariadne` report.
    ///
    /// Note that the test harness captures stderr through a pipe, so the terminal detection says
    /// "no terminal" unless `CLICOLOR_FORCE` overrides it.
    fn stderr_of(html: bool, env: &[(&str, &str)]) -> Vec<u8> {
        let dir = empty_dir();
        let mut cmd = mathcore(dir.path());
        if html {
            write(dir.path(), "doc.html", "good $x$ then bad $\\frac$\n");
            cmd.arg("doc.html");
        } else {
            cmd.args(["--formula", r"\frac"]);
        }
        // Either variable may well be set in the environment running the test suite.
        cmd.env_remove("NO_COLOR").env_remove("CLICOLOR_FORCE");
        for (name, value) in env {
            cmd.env(name, value);
        }

        let out = cmd.output().expect("failed to run mathcore");
        assert_eq!(out.status.code(), Some(2), "expected a conversion error");
        out.stderr
    }

    /// Whether the output contains ANSI escape codes.
    fn colorized(stderr: &[u8]) -> bool {
        stderr.contains(&0x1b)
    }

    /// One row of the truth table.
    struct Case {
        env: &'static [(&'static str, &'static str)],
        /// Whether the report is expected to come out colorized.
        colorized: bool,
        reason: &'static str,
    }

    let cases = [
        Case {
            env: &[],
            colorized: false,
            reason: "stderr is not a terminal, so no colors",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "1")],
            colorized: true,
            reason: "CLICOLOR_FORCE forces colors",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "0")],
            colorized: true,
            reason: "CLICOLOR_FORCE counts as set for any non-empty value, even \"0\"",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "")],
            colorized: false,
            reason: "an empty CLICOLOR_FORCE is not set",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "1"), ("NO_COLOR", "1")],
            colorized: false,
            reason: "NO_COLOR wins over CLICOLOR_FORCE",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "1"), ("NO_COLOR", "0")],
            colorized: false,
            reason: "NO_COLOR counts as set for any non-empty value, even \"0\"",
        },
        Case {
            env: &[("CLICOLOR_FORCE", "1"), ("NO_COLOR", "")],
            colorized: true,
            reason: "an empty NO_COLOR is not set",
        },
    ];

    for html in [false, true] {
        for case in &cases {
            assert_eq!(
                colorized(&stderr_of(html, case.env)),
                case.colorized,
                "html={html}, env={:?}: {}",
                case.env,
                case.reason
            );
        }
    }
}

#[test]
fn missing_config_file() {
    let dir = empty_dir();
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).args([
            "--config-file",
            "nope.toml",
            "--formula",
            "x"
        ]));
    });
}

// ---------------------------------------------------------------------------------------------
// File handling
// ---------------------------------------------------------------------------------------------

#[test]
fn without_write_the_file_is_left_alone() {
    let dir = empty_dir();
    let file = write(dir.path(), "doc.html", NUMBERED_DOC);
    let out = mathcore(dir.path())
        .arg("doc.html")
        .output()
        .expect("failed to run mathcore");

    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("<math"));
    assert_eq!(read(&file), NUMBERED_DOC, "the input file was modified");
}

#[test]
fn write_converts_in_place() {
    let dir = empty_dir();
    let file = write(dir.path(), "doc.html", NUMBERED_DOC);
    let out = mathcore(dir.path())
        .args(["--write", "doc.html"])
        .output()
        .expect("failed to run mathcore");

    assert!(out.status.success());
    assert!(out.stdout.is_empty(), "--write should not print the result");
    assert!(read(&file).contains("<math"));
}

/// Converting an already-converted document must not keep changing it.
#[test]
fn write_is_idempotent() {
    let dir = empty_dir();
    let file = write(dir.path(), "doc.html", NUMBERED_DOC);
    for _ in 0..2 {
        assert!(
            mathcore(dir.path())
                .args(["--write", "doc.html"])
                .status()
                .expect("failed to run mathcore")
                .success()
        );
    }
    let once = read(&file);

    let fresh = empty_dir();
    let fresh_file = write(fresh.path(), "doc.html", NUMBERED_DOC);
    assert!(
        mathcore(fresh.path())
            .args(["--write", "doc.html"])
            .status()
            .expect("failed to run mathcore")
            .success()
    );
    assert_eq!(once, read(&fresh_file), "second run changed the document");
}

#[test]
fn dry_run_writes_nothing() {
    let dir = empty_dir();
    let file = write(dir.path(), "doc.html", NUMBERED_DOC);
    let out = mathcore(dir.path())
        .args(["--dry-run", "--write", "doc.html"])
        .output()
        .expect("failed to run mathcore");

    assert!(out.status.success());
    assert!(out.stdout.is_empty());
    assert_eq!(read(&file), NUMBERED_DOC, "--dry-run modified the file");
}

/// Warnings are reported for every snippet of the file that produced one, prefixed with the name
/// of the file they were found in.
#[test]
fn warnings_of_a_file_go_to_stderr() {
    let dir = empty_dir();
    write(dir.path(), "doc.html", UNDEFINED_REF_DOC);
    settings().bind(|| {
        assert_cmd_snapshot!(mathcore(dir.path()).arg("doc.html"));
    });
}

/// In `--write` mode there is no converted document on stdout, but the warnings still show up on
/// stderr.
#[test]
fn warnings_are_printed_when_writing_in_place() {
    let dir = empty_dir();
    write(dir.path(), "doc.html", UNDEFINED_REF_DOC);
    let out = mathcore(dir.path())
        .args(["--write", "doc.html"])
        .output()
        .expect("failed to run mathcore");

    assert!(out.status.success());
    assert!(out.stdout.is_empty(), "--write should not print the result");
    assert_eq!(
        String::from_utf8_lossy(&out.stderr).lines().count(),
        2,
        "expected one warning per undefined reference"
    );
}

/// A document that came in through stdin has no file name to prefix the warnings with, but the
/// line and column still locate them in the input that was piped in.
#[test]
fn warnings_of_stdin_are_printed_without_a_file_name() {
    let dir = empty_dir();
    let mut cmd = mathcore(dir.path());
    cmd.arg("-");
    let out = run_with_stdin(cmd, UNDEFINED_REF_DOC);

    assert!(out.status.success());
    assert!(String::from_utf8_lossy(&out.stdout).contains("<math"));
    assert_eq!(
        String::from_utf8_lossy(&out.stderr),
        "Warning: undefined reference in the formula on line 1, column 9.\n\
         Warning: undefined reference in the formula on line 2, column 8.\n"
    );
}

#[test]
fn a_failing_file_is_left_untouched() {
    let dir = empty_dir();
    let file = write(dir.path(), "doc.html", "before $x$ and $\\frac$ after\n");
    let out = mathcore(dir.path())
        .args(["--write", "doc.html"])
        .output()
        .expect("failed to run mathcore");

    assert_eq!(out.status.code(), Some(2));
    assert!(String::from_utf8_lossy(&out.stderr).contains("Conversion error in 'doc.html'"));
    assert_eq!(
        read(&file),
        "before $x$ and $\\frac$ after\n",
        "the file was modified despite the error"
    );
}

// ---------------------------------------------------------------------------------------------
// Recursive mode
// ---------------------------------------------------------------------------------------------

/// Each file is converted as its own document, so the equation counter restarts in every file
/// instead of continuing across the whole run.
#[test]
fn recursive_numbers_each_file_from_one() {
    let dir = empty_dir();
    let first = write(dir.path(), "one.html", NUMBERED_DOC);
    let second = write(dir.path(), "sub/two.html", NUMBERED_DOC);

    assert!(
        mathcore(dir.path())
            .args(["--recursive", "."])
            .status()
            .expect("failed to run mathcore")
            .success()
    );

    for file in [&first, &second] {
        let converted = read(file);
        assert!(converted.contains("(1)"), "not converted: {converted}");
        assert!(
            !converted.contains("(2)"),
            "numbering continued across files: {converted}"
        );
    }
}

#[test]
fn recursive_ignores_non_html_files() {
    let dir = empty_dir();
    let htm = write(dir.path(), "old.htm", NUMBERED_DOC);
    let txt = write(dir.path(), "notes.txt", NUMBERED_DOC);

    assert!(
        mathcore(dir.path())
            .args(["--recursive", "."])
            .status()
            .expect("failed to run mathcore")
            .success()
    );

    assert_eq!(read(&htm), NUMBERED_DOC, ".htm files must be ignored");
    assert_eq!(read(&txt), NUMBERED_DOC, ".txt files must be ignored");
}