use proc_macro2::TokenStream;
use std::io::Write;
use std::process::{Command, Stdio};
enum Error {
RunError(std::io::Error),
WriteError(std::io::Error),
Utf8Error(std::string::FromUtf8Error),
WaitError(std::io::Error),
}
pub(crate) fn pretty_print(ts: &TokenStream) -> String {
reformat_or_else(ts.to_string())
}
fn reformat_or_else(text: impl std::fmt::Display) -> String {
match reformat(&text) {
Ok(s) => s,
Err(_) => text.to_string(),
}
}
fn reformat(text: impl std::fmt::Display) -> Result<String, Error> {
let mut rustfmt = Command::new("rustfmt")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(Error::RunError)?;
write!(rustfmt.stdin.take().unwrap(), "{}", text).map_err(Error::WriteError)?;
let output = rustfmt.wait_with_output().map_err(Error::WaitError)?;
String::from_utf8(output.stdout).map_err(Error::Utf8Error)
}