rdlfmt 0.2.0

A formatter for SystemRDL
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
//! End-to-end tests for the `rdlfmt` command.
//!
//! What these are for is the behaviour that is not the formatter: which files
//! get touched, what the exit status is, and where the output goes. The
//! formatting itself is covered by `invariants.rs`.
//!
//! Exit status is the part worth being strict about, because it is the whole
//! interface to CI: 0 clean, 1 needs formatting, 2 something went wrong.

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

const EXE: &str = env!("CARGO_BIN_EXE_rdlfmt");

const UNFORMATTED: &str = "addrmap a{name=\"x\";};\n";
const FORMATTED: &str = "addrmap a {\n    name = \"x\";\n};\n";

/// A scratch directory of its own, so tests can run in parallel.
struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> TempDir {
        // Enough to be unique across a parallel run without a dependency:
        // the tag is per-test and the pid is per-run.
        let path = std::env::temp_dir().join(format!("rdlfmt-{}-{tag}", std::process::id()));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).expect("create temp dir");
        TempDir(path)
    }

    fn write(&self, name: &str, contents: &str) -> PathBuf {
        let path = self.0.join(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("create parent");
        }
        std::fs::write(&path, contents).expect("write file");
        path
    }

    fn read(&self, name: &str) -> String {
        std::fs::read_to_string(self.0.join(name)).expect("read file")
    }
}

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

fn run(args: &[&str]) -> Output {
    Command::new(EXE).args(args).output().expect("run binary")
}

fn run_in(dir: &Path, args: &[&str]) -> Output {
    Command::new(EXE)
        .current_dir(dir)
        .args(args)
        .output()
        .expect("run binary")
}

fn pipe(stdin: &str, args: &[&str]) -> Output {
    let mut child = Command::new(EXE)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn binary");
    child
        .stdin
        .take()
        .expect("stdin")
        .write_all(stdin.as_bytes())
        .expect("write stdin");
    child.wait_with_output().expect("wait")
}

#[track_caller]
fn code(output: &Output) -> i32 {
    output.status.code().expect("exit code")
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

//--------------------------------------------------------------------------
// stdin
//--------------------------------------------------------------------------

#[test]
fn no_paths_means_stdin_to_stdout() {
    let out = pipe(UNFORMATTED, &[]);
    assert_eq!(code(&out), 0);
    assert_eq!(stdout(&out), FORMATTED);
}

#[test]
fn check_on_stdin_reports_without_writing_it_out() {
    let out = pipe(UNFORMATTED, &["--check"]);
    assert_eq!(code(&out), 1);
    assert!(!stdout(&out).contains("addrmap"), "formatted text leaked");
}

//--------------------------------------------------------------------------
// Writing, which is the default
//--------------------------------------------------------------------------

#[test]
fn a_path_is_rewritten_in_place() {
    let dir = TempDir::new("write");
    let path = dir.write("a.rdl", UNFORMATTED);

    let out = run(&[path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("a.rdl"), FORMATTED);
}

#[test]
fn an_already_formatted_file_is_left_alone() {
    // Not merely "ends up with the same bytes": the file must not be written
    // at all, or formatting a tree would touch every mtime and trigger a
    // rebuild of everything downstream.
    let dir = TempDir::new("untouched");
    let path = dir.write("a.rdl", FORMATTED);
    let before = std::fs::metadata(&path).unwrap().modified().unwrap();

    let out = run(&[path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(stdout(&out), "", "an untouched file should not be reported");

    let after = std::fs::metadata(&path).unwrap().modified().unwrap();
    assert_eq!(before, after, "file was rewritten");
}

#[test]
fn stdout_mode_does_not_touch_the_file() {
    let dir = TempDir::new("stdout");
    let path = dir.write("a.rdl", UNFORMATTED);

    let out = run(&["--stdout", path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(stdout(&out), FORMATTED);
    assert_eq!(dir.read("a.rdl"), UNFORMATTED, "file was modified");
}

//--------------------------------------------------------------------------
// --check
//--------------------------------------------------------------------------

#[test]
fn check_leaves_the_file_alone_and_exits_one() {
    let dir = TempDir::new("check-dirty");
    let path = dir.write("a.rdl", UNFORMATTED);

    let out = run(&["--check", path.to_str().unwrap()]);
    assert_eq!(code(&out), 1);
    assert_eq!(dir.read("a.rdl"), UNFORMATTED, "check modified the file");
    assert!(stdout(&out).contains("a.rdl"), "got: {}", stdout(&out));
}

#[test]
fn check_exits_zero_when_everything_is_formatted() {
    let dir = TempDir::new("check-clean");
    let path = dir.write("a.rdl", FORMATTED);

    let out = run(&["--check", path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(stdout(&out), "");
}

//--------------------------------------------------------------------------
// --diff
//--------------------------------------------------------------------------

#[test]
fn diff_shows_the_change_and_exits_one() {
    let dir = TempDir::new("diff");
    let path = dir.write("a.rdl", UNFORMATTED);

    let out = run(&["--diff", path.to_str().unwrap()]);
    assert_eq!(code(&out), 1, "--diff reports like --check");
    assert_eq!(dir.read("a.rdl"), UNFORMATTED, "--diff modified the file");

    let text = stdout(&out);
    assert!(text.contains("a.rdl at line 1:"), "no hunk header: {text}");
    assert!(
        text.contains("-addrmap a{name=\"x\";};"),
        "no removed line: {text}"
    );
    assert!(text.contains("+addrmap a {"), "no added line: {text}");
}

#[test]
fn diff_prints_nothing_when_already_formatted() {
    let dir = TempDir::new("diff-clean");
    let path = dir.write("a.rdl", FORMATTED);

    let out = run(&["--diff", path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(stdout(&out), "");
}

#[test]
fn diff_keeps_unchanged_lines_as_context() {
    // The value of a diff over `--check` is seeing the change in place, so the
    // surrounding lines have to survive -- with a leading space, not a sign.
    let dir = TempDir::new("diff-context");
    let mut src = String::from("addrmap a {\n");
    for i in 0..10 {
        src.push_str(&format!("    p{i} = {i};\n"));
    }
    src.push_str("    bad   =   1;\n};\n");
    let path = dir.write("a.rdl", &src);

    let out = run(&["--diff", path.to_str().unwrap()]);
    assert_eq!(code(&out), 1);

    let text = stdout(&out);
    assert!(text.contains(" };"), "closing brace not shown as context");
    assert!(
        !text.contains("p0"),
        "distant lines should be outside the context window: {text}"
    );
}

#[test]
fn diff_output_is_uncoloured_when_piped() {
    // Tests capture stdout through a pipe, so this is the real check that a
    // redirected diff stays machine-readable.
    let dir = TempDir::new("diff-color");
    let path = dir.write("a.rdl", UNFORMATTED);

    let out = run(&["--diff", path.to_str().unwrap()]);
    assert!(!stdout(&out).contains('\x1b'), "escape sequences in a pipe");
}

#[test]
fn diff_and_check_conflict() {
    let out = run(&["--diff", "--check"]);
    assert_eq!(code(&out), 2);
}

//--------------------------------------------------------------------------
// Directories and failures
//--------------------------------------------------------------------------

#[test]
fn a_directory_is_searched_for_rdl_files() {
    let dir = TempDir::new("dir");
    dir.write("a.rdl", UNFORMATTED);
    dir.write("nested/b.rdl", UNFORMATTED);
    dir.write("notes.txt", "not rdl, must be left alone\n");
    dir.write(".hidden/c.rdl", UNFORMATTED);

    let out = run_in(&dir.0, &["."]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("a.rdl"), FORMATTED);
    assert_eq!(dir.read("nested/b.rdl"), FORMATTED);
    assert_eq!(dir.read("notes.txt"), "not rdl, must be left alone\n");
    assert_eq!(
        dir.read(".hidden/c.rdl"),
        UNFORMATTED,
        "hidden directories should be skipped"
    );
}

#[test]
fn a_gitignored_path_is_not_walked_into() {
    let dir = TempDir::new("gitignore");
    dir.write(".gitignore", "build/\ngenerated.rdl\n");
    dir.write("src/a.rdl", UNFORMATTED);
    dir.write("build/b.rdl", UNFORMATTED);
    dir.write("build/deep/c.rdl", UNFORMATTED);
    dir.write("src/generated.rdl", UNFORMATTED);

    let out = run_in(&dir.0, &["."]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("src/a.rdl"), FORMATTED);
    assert_eq!(dir.read("build/b.rdl"), UNFORMATTED, "walked into build/");
    assert_eq!(
        dir.read("build/deep/c.rdl"),
        UNFORMATTED,
        "walked below build/"
    );
    assert_eq!(
        dir.read("src/generated.rdl"),
        UNFORMATTED,
        "ignored name was formatted"
    );
}

#[test]
fn gitignore_applies_without_a_git_directory() {
    // The `.gitignore` is the statement of intent. An exported or vendored
    // tree has no `.git` beside it and should still behave the same way.
    let dir = TempDir::new("gitignore-nogit");
    dir.write(".gitignore", "build/\n");
    dir.write("a.rdl", UNFORMATTED);
    dir.write("build/b.rdl", UNFORMATTED);

    let out = run_in(&dir.0, &["."]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("a.rdl"), FORMATTED);
    assert_eq!(dir.read("build/b.rdl"), UNFORMATTED, "walked into build/");
}

#[test]
fn naming_an_ignored_path_formats_it_anyway() {
    // Ignore rules prune what a walk discovers. They are not a veto on a path
    // the user asked for by name.
    let dir = TempDir::new("gitignore-explicit");
    dir.write(".gitignore", "build/\n");
    let file = dir.write("build/b.rdl", UNFORMATTED);
    dir.write("build/deep/c.rdl", UNFORMATTED);

    let out = run(&[file.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("build/b.rdl"), FORMATTED, "named file was skipped");

    // ...and the same for naming the ignored directory itself.
    let out = run_in(&dir.0, &["build"]);
    assert_eq!(code(&out), 0);
    assert_eq!(
        dir.read("build/deep/c.rdl"),
        FORMATTED,
        "named directory was skipped"
    );
}

// Unix only: creating a symlink on Windows wants either elevation or developer
// mode, which is not something a test run can count on. The behaviour under
// test is the walker's, and it does not vary by platform.
#[cfg(unix)]
#[test]
fn a_symlinked_directory_is_not_followed() {
    // `is_dir()` follows symlinks, so a loop used to be walked until the OS
    // ran out of link resolutions -- reporting the same file dozens of times,
    // and under the default mode rewriting it just as often.
    let dir = TempDir::new("symlink-loop");
    dir.write("a.rdl", UNFORMATTED);
    std::os::unix::fs::symlink(&dir.0, dir.0.join("loop")).expect("symlink");

    let out = run_in(&dir.0, &["--check", "."]);
    assert_eq!(code(&out), 1);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        stdout.lines().count(),
        1,
        "a.rdl reported more than once: {stdout}"
    );
}

#[test]
fn a_file_that_does_not_parse_is_left_alone() {
    let dir = TempDir::new("broken");
    let path = dir.write("a.rdl", "addrmap a {\n");

    let out = run(&[path.to_str().unwrap()]);
    assert_eq!(code(&out), 2);
    assert_eq!(
        dir.read("a.rdl"),
        "addrmap a {\n",
        "broken file was written"
    );

    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("a.rdl:"), "no located error in: {stderr}");
}

#[test]
fn one_bad_file_does_not_stop_the_others() {
    let dir = TempDir::new("mixed");
    dir.write("good.rdl", UNFORMATTED);
    dir.write("bad.rdl", "addrmap a {\n");

    let out = run_in(&dir.0, &["."]);
    assert_eq!(code(&out), 2, "a failure anywhere is exit 2");
    assert_eq!(dir.read("good.rdl"), FORMATTED, "good file was skipped");
}

#[test]
fn a_missing_path_is_an_error() {
    let out = run(&["/nonexistent/nope.rdl"]);
    assert_eq!(code(&out), 2);
}

//--------------------------------------------------------------------------
// Arguments
//--------------------------------------------------------------------------

#[test]
fn indent_width_is_not_an_argument() {
    // Four spaces, and no flag to say otherwise: the style is the product.
    let out = pipe(UNFORMATTED, &["--indent", "2"]);
    assert_eq!(code(&out), 2, "a usage error is exit 2, like any other");
    assert_eq!(stdout(&pipe(UNFORMATTED, &[])), FORMATTED);
}

#[test]
fn help_and_version_succeed() {
    for flag in ["--help", "-h", "--version", "-V"] {
        let out = run(&[flag]);
        assert_eq!(code(&out), 0, "{flag}");
        assert!(!stdout(&out).is_empty(), "{flag} printed nothing");
    }
}

#[test]
fn an_unknown_option_is_rejected() {
    let out = run(&["--nope"]);
    assert_eq!(code(&out), 2, "a usage error is exit 2, like any other");
    // The offending flag, not clap's phrasing, which is not ours to pin.
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("--nope"), "got: {stderr}");
}

#[test]
fn check_and_stdout_conflict() {
    // Writing nothing and writing to stdout cannot both be meant.
    let out = run(&["--check", "--stdout"]);
    assert_eq!(code(&out), 2);
}

#[test]
fn double_dash_ends_the_options() {
    let dir = TempDir::new("ddash");
    // A file whose name looks like a flag is still a path after `--`.
    let path = dir.write("--check", UNFORMATTED);

    let out = run(&["--", path.to_str().unwrap()]);
    assert_eq!(code(&out), 0);
    assert_eq!(dir.read("--check"), FORMATTED);
}