fuels_rs/
rustfmt.rs

1//! This module implements basic `rustfmt` code formatting.
2
3use anyhow::{anyhow, Result};
4use std::io::Write;
5use std::process::{Command, Stdio};
6
7/// Format the raw input source string and return formatted output.
8pub fn format<S>(source: S) -> Result<String>
9where
10    S: AsRef<str>,
11{
12    let mut rustfmt = Command::new("rustfmt")
13        .stdin(Stdio::piped())
14        .stdout(Stdio::piped())
15        .spawn()?;
16
17    {
18        let stdin = rustfmt
19            .stdin
20            .as_mut()
21            .ok_or_else(|| anyhow!("stdin was not created for `rustfmt` child process"))?;
22        stdin.write_all(source.as_ref().as_bytes())?;
23    }
24
25    let output = rustfmt.wait_with_output()?;
26    if !output.status.success() {
27        return Err(anyhow!(
28            "`rustfmt` exited with code {}:\n{}",
29            output.status,
30            String::from_utf8_lossy(&output.stderr),
31        ));
32    }
33
34    let stdout = String::from_utf8(output.stdout)?;
35    Ok(stdout)
36}