2020-05-26 09:37:31 +00:00
|
|
|
//! This module implements basic `rustfmt` code formatting.
|
|
|
|
|
2022-02-02 20:44:53 +00:00
|
|
|
use eyre::{eyre, Result};
|
2021-10-29 12:29:35 +00:00
|
|
|
use std::{
|
|
|
|
io::Write,
|
|
|
|
process::{Command, Stdio},
|
|
|
|
};
|
2020-05-26 09:37:31 +00:00
|
|
|
|
|
|
|
/// Format the raw input source string and return formatted output.
|
|
|
|
pub fn format<S>(source: S) -> Result<String>
|
|
|
|
where
|
|
|
|
S: AsRef<str>,
|
|
|
|
{
|
2021-10-29 12:29:35 +00:00
|
|
|
let mut rustfmt =
|
|
|
|
Command::new("rustfmt").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn()?;
|
2020-05-26 09:37:31 +00:00
|
|
|
|
|
|
|
{
|
|
|
|
let stdin = rustfmt
|
|
|
|
.stdin
|
|
|
|
.as_mut()
|
2022-02-02 20:44:53 +00:00
|
|
|
.ok_or_else(|| eyre!("stdin was not created for `rustfmt` child process"))?;
|
2020-05-26 09:37:31 +00:00
|
|
|
stdin.write_all(source.as_ref().as_bytes())?;
|
|
|
|
}
|
|
|
|
|
|
|
|
let output = rustfmt.wait_with_output()?;
|
2022-02-02 20:44:53 +00:00
|
|
|
|
|
|
|
eyre::ensure!(
|
|
|
|
output.status.success(),
|
|
|
|
"`rustfmt` exited with code {}:\n{}",
|
|
|
|
output.status,
|
|
|
|
String::from_utf8_lossy(&output.stderr),
|
|
|
|
);
|
2020-05-26 09:37:31 +00:00
|
|
|
|
|
|
|
let stdout = String::from_utf8(output.stdout)?;
|
|
|
|
Ok(stdout)
|
|
|
|
}
|