nixfmt_rs 0.4.1

Rust implementation of nixfmt with exact Haskell compatibility
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
//! nixfmt-rs CLI
//!
//! Mirrors the flag surface and exit-code semantics of the Haskell `nixfmt`
//! binary so the two can be used interchangeably by editors / CI.

use std::io::{self, Read, Write};

#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use std::path::Path;
use std::process::exit;
use std::sync::atomic::{AtomicBool, Ordering};

use nixfmt_rs::VERSION;

mod json_diag;

const HELP: &str = "\
nixfmt-rs [OPTIONS] [FILES or -]
  Format Nix source code (Rust implementation of nixfmt)
  Use '-' as a file argument to read from stdin.

Common flags:
  -w --width=INT        Maximum width in characters [default: 100]
     --indent=INT       Number of spaces to use for indentation [default: 2]
  -c --check            Check whether files are formatted without modifying them
  -m --mergetool        Git mergetool mode: format BASE/LOCAL/REMOTE, run
                        'git merge-file', format and move result to MERGED
  -q --quiet            Do not report errors
  -s --strict           Enable a stricter formatting mode (accepted, currently no-op)
  -v --verify           Apply sanity checks on the output after formatting
  -a --ast              Pretty print the internal AST to stderr (debug)
  -f --filename=ITEM    Filename to display when input is read from stdin
     --ir               Pretty print the internal IR to stderr (debug)
     --message-format=FMT
                        How to render diagnostics: 'human' (default) or 'json'
                        (one JSON object per line on stderr, LSP Diagnostic shape)
  -h -? --help          Display help message
  -V --version          Print version information
     --numeric-version  Print just the version number
";

#[derive(Default)]
#[allow(clippy::struct_excessive_bools)] // flat CLI flag bag
struct Opts {
    width: usize,
    indent: usize,
    check: bool,
    quiet: bool,
    #[allow(dead_code)] // accepted for CLI parity; no strict-mode hook yet
    strict: bool,
    verify: bool,
    ast: bool,
    ir: bool,
    parse_only: bool,
    mergetool: bool,
    json_diagnostics: bool,
    filename: Option<String>,
    files: Vec<String>,
}

fn parse_args() -> Result<Opts, lexopt::Error> {
    use lexopt::prelude::*;
    let mut o = Opts {
        width: 100,
        indent: 2,
        ..Opts::default()
    };
    let mut p = lexopt::Parser::from_env();
    while let Some(arg) = p.next()? {
        match arg {
            Short('h' | '?') | Long("help") => {
                print!("{HELP}");
                exit(0);
            }
            Short('V') | Long("version") => {
                println!("nixfmt-rs {VERSION}");
                exit(0);
            }
            Long("numeric-version") => {
                println!("{VERSION}");
                exit(0);
            }
            Short('w') | Long("width") => o.width = p.value()?.parse()?,
            Long("indent") => o.indent = p.value()?.parse()?,
            Short('c') | Long("check") => o.check = true,
            Short('q') | Long("quiet") => o.quiet = true,
            Short('s') | Long("strict") => o.strict = true,
            Short('v') | Long("verify") => o.verify = true,
            Short('a') | Long("ast") => o.ast = true,
            Long("ir") => o.ir = true,
            Long("parse-only") => o.parse_only = true,
            Short('m') | Long("mergetool") => o.mergetool = true,
            Long("message-format") => {
                let v = p.value()?.string()?;
                o.json_diagnostics = match v.as_str() {
                    "human" => false,
                    "json" => true,
                    other => {
                        return Err(lexopt::Error::Custom(
                            format!("Unknown --message-format: {other}").into(),
                        ));
                    }
                };
            }
            Short('f') | Long("filename") => o.filename = Some(p.value()?.string()?),
            Value(path) => o.files.push(path.string()?),
            _ => return Err(arg.unexpected()),
        }
    }
    Ok(o)
}

fn render_err(o: &Opts, source: &str, name: &str, e: &nixfmt_rs::ParseError) -> String {
    if o.json_diagnostics {
        json_diag::parse_error(source, name, e)
    } else {
        nixfmt_rs::format_error(source, Some(name), e)
    }
}

fn report(o: &Opts, file: Option<&str>, severity: &str, msg: &str) {
    eprintln!("{}", render_msg(o, file, severity, msg));
}

fn try_format(o: &Opts, name: &str, source: &str) -> Result<String, String> {
    let fmt = |s: &str| {
        let mut opts = nixfmt_rs::Options::default();
        opts.width = o.width;
        opts.indent = o.indent;
        nixfmt_rs::format_with(s, &opts).map_err(|e| render_err(o, s, name, &e))
    };
    let out = fmt(source)?;
    if o.verify {
        let again = fmt(&out)?;
        if again != out {
            return Err(render_msg(
                o,
                Some(name),
                "error",
                "verify: output is not idempotent",
            ));
        }
    }
    Ok(out)
}

fn render_msg(o: &Opts, file: Option<&str>, severity: &str, msg: &str) -> String {
    if o.json_diagnostics {
        json_diag::message(file, severity, msg)
    } else if let Some(f) = file {
        format!("{f}: {msg}")
    } else {
        msg.to_string()
    }
}

/// Returns `true` on success so the caller can fold exit status across files.
fn process(o: &Opts, name: &str, source: &str, in_place: bool) -> bool {
    if o.parse_only {
        return match nixfmt_rs::parse(source) {
            Ok(_) => true,
            Err(e) => {
                if !o.quiet {
                    eprintln!("{}", render_err(o, source, name, &e));
                }
                false
            }
        };
    }
    if o.ast || o.ir {
        // Upstream routes debug dumps to stderr and exits 1 so scripts never
        // mistake them for formatted output.
        let res = if o.ast {
            nixfmt_rs::format_ast(source)
        } else {
            nixfmt_rs::format_ir(source)
        };
        match res {
            Ok(s) => eprint!("{s}"),
            Err(e) if !o.quiet => {
                eprintln!("{}", render_err(o, source, name, &e));
            }
            Err(_) => {}
        }
        return false;
    }

    let out = match try_format(o, name, source) {
        Ok(s) => s,
        Err(msg) => {
            if !o.quiet {
                eprintln!("{msg}");
            }
            return false;
        }
    };

    if o.check {
        if out != source {
            if !o.quiet {
                report(o, Some(name), "warning", "not formatted");
            }
            return false;
        }
        return true;
    }

    if in_place {
        // Skip the write when unchanged to preserve mtimes for build tools.
        if out != source
            && let Err(e) = std::fs::write(name, &out)
        {
            if !o.quiet {
                report(o, Some(name), "error", &e.to_string());
            }
            return false;
        }
    } else {
        let _ = io::stdout().write_all(out.as_bytes());
    }
    true
}

fn main() {
    let o = match parse_args() {
        Ok(o) => o,
        Err(e) => {
            eprintln!("{e}");
            exit(1);
        }
    };

    let mut ok = true;

    if o.mergetool {
        exit(i32::from(!run_mergetool(&o)));
    }

    let stdin_only = o.files.is_empty() || o.files.iter().all(|f| f == "-");
    if o.files.is_empty() && !o.quiet && !o.json_diagnostics {
        eprintln!(
            "Warning: Bare invocation of nixfmt-rs is deprecated. Use 'nixfmt-rs -' for anonymous stdin."
        );
    }
    if stdin_only {
        let mut buf = String::new();
        if let Err(e) = io::stdin().read_to_string(&mut buf) {
            eprintln!("error: failed to read stdin: {e}");
            exit(1);
        }
        let name = o.filename.as_deref().unwrap_or("<stdin>");
        ok &= process(&o, name, &buf, false);
    } else if o.files.iter().any(|f| f == "-") {
        eprintln!("error: cannot mix '-' (stdin) with file arguments");
        exit(1);
    } else {
        // Debug dumps stream to stderr; running them in parallel would
        // interleave output, so keep those modes sequential.
        let parallel = !(o.ast || o.ir || o.parse_only);
        ok &= walk_and_process(&o, parallel);
    }

    exit(i32::from(!ok));
}

fn process_path(o: &Opts, path: &Path) -> bool {
    let name = path.to_string_lossy();
    match std::fs::read_to_string(path) {
        Ok(source) => process(o, &name, &source, true),
        Err(e) => {
            if !o.quiet {
                report(o, Some(&name), "error", &e.to_string());
            }
            false
        }
    }
}

/// Walk argument paths with `ignore`'s parallel walker and run `process_path`
/// on every match. Explicit file arguments are passed through even without a
/// `.nix` extension; the filter only applies to entries discovered under a
/// directory argument.
fn walk_and_process(o: &Opts, parallel: bool) -> bool {
    let mut args = o.files.iter();
    let first = args.next().expect("caller checked non-empty");
    let mut wb = ignore::WalkBuilder::new(first);
    for a in args {
        wb.add(a);
    }
    // We are a formatter, not a search tool: walk everything.
    wb.standard_filters(false);

    let want = |e: &ignore::DirEntry| {
        e.file_type().is_some_and(|t| t.is_file())
            && (e.depth() == 0 || e.path().extension().is_some_and(|x| x == "nix"))
    };

    let visit = |entry: Result<ignore::DirEntry, ignore::Error>| -> bool {
        match entry {
            Ok(e) if want(&e) => process_path(o, e.path()),
            Ok(_) => true,
            Err(e) => {
                if !o.quiet {
                    report(o, None, "error", &e.to_string());
                }
                false
            }
        }
    };

    if !parallel {
        wb.threads(1);
        return wb.build().map(visit).fold(true, |a, b| a & b);
    }

    let ok = AtomicBool::new(true);
    wb.build_parallel().run(|| {
        Box::new(|entry| {
            if !visit(entry) {
                ok.store(false, Ordering::Relaxed);
            }
            ignore::WalkState::Continue
        })
    });
    ok.load(Ordering::Relaxed)
}

/// `git mergetool` mode: pre-format the three input revisions, invoke
/// `git merge-file`, format its output, then move it onto the MERGED path.
fn run_mergetool(o: &Opts) -> bool {
    let [base, local, remote, merged] = if let [b, l, r, m] = o.files.as_slice() {
        [b.as_str(), l.as_str(), r.as_str(), m.as_str()]
    } else {
        if !o.quiet {
            eprintln!(
                "--mergetool mode expects exactly 4 file arguments ($BASE, $LOCAL, $REMOTE, $MERGED)"
            );
        }
        return false;
    };

    if Path::new(merged)
        .extension()
        .is_none_or(|ext| !ext.eq_ignore_ascii_case("nix"))
    {
        if !o.quiet {
            eprintln!("Skipping non-Nix file {merged}");
        }
        return false;
    }

    let pre_format = |label: &str, path: &str| -> bool {
        if process_path(o, Path::new(path)) {
            return true;
        }
        if !o.quiet {
            eprintln!("pre-formatting the {label} version failed");
        }
        false
    };

    let mut ok = pre_format("base", base);
    ok &= pre_format("local", local);
    ok &= pre_format("remote", remote);
    if !ok {
        return false;
    }

    // git merge-file's nonzero exit is the conflict count, not an error;
    // only spawn / signal failures are fatal here.
    let status = match std::process::Command::new("git")
        .args(["merge-file", local, base, remote])
        .status()
    {
        Ok(s) => s,
        Err(e) => {
            if !o.quiet {
                eprintln!("failed to run git merge-file: {e}");
            }
            return false;
        }
    };
    if status.code().is_none() {
        if !o.quiet {
            eprintln!("git merge-file terminated by signal");
        }
        return false;
    }

    if !process_path(o, Path::new(local)) {
        return false;
    }

    if let Err(e) = std::fs::rename(local, merged) {
        if !o.quiet {
            eprintln!("failed to move {local} to {merged}: {e}");
        }
        return false;
    }

    // Forward merge-file's status so `git mergetool` sees conflict count.
    status.success()
}