1use anyhow::{anyhow, Result};
4use std::io::Write;
5use std::process::{Command, Stdio};
6
7pub 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}