Skip to main content

nickel_lang_core/
format.rs

1//! Utility module for formatting Nickel files using Topiary
2
3use std::{
4    fmt::Display,
5    io::{Read, Write},
6};
7
8use topiary_core::{Language, Operation, TopiaryQuery, formatter};
9
10#[derive(Debug)]
11/// Errors that may be encountered during formatting
12pub struct FormatError(topiary_core::FormatterError);
13
14impl Display for FormatError {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        self.0.fmt(f)
17    }
18}
19
20/// Format a Nickel file being read from `input`, writing the result to `output`.
21pub fn format(mut input: impl Read, mut output: impl Write) -> Result<(), FormatError> {
22    let grammar = tree_sitter_nickel::LANGUAGE.into();
23    let query = TopiaryQuery::new(&grammar, topiary_queries::nickel()).map_err(FormatError)?;
24    let language = Language {
25        name: "nickel".to_owned(),
26        query,
27        grammar,
28        indent: None,
29    };
30
31    formatter(
32        &mut input,
33        &mut output,
34        &language,
35        Operation::Format {
36            // We only enable the idempotency check in debug mode: it's useful to detect bugs in
37            // the Nickel formatter, but we don't want to report an error or to make production
38            // users pay the cost of the check, although this cost should be fairly low.
39            skip_idempotence: !cfg!(debug_assertions),
40            tolerate_parsing_errors: false,
41        },
42    )
43    .map_err(FormatError)
44}