Brian Silverman | 4e662aa | 2022-05-11 23:10:19 -0700 | [diff] [blame^] | 1 | // Copyright 2020 Google LLC |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
| 6 | // option. This file may not be copied, modified, or distributed |
| 7 | // except according to those terms. |
| 8 | |
| 9 | use proc_macro2::TokenStream; |
| 10 | use std::io::Write; |
| 11 | use std::process::{Command, Stdio}; |
| 12 | |
| 13 | enum Error { |
| 14 | Run(std::io::Error), |
| 15 | Write(std::io::Error), |
| 16 | Utf8(std::string::FromUtf8Error), |
| 17 | Wait(std::io::Error), |
| 18 | } |
| 19 | |
| 20 | pub(crate) fn pretty_print(ts: &TokenStream) -> String { |
| 21 | reformat_or_else(ts.to_string()) |
| 22 | } |
| 23 | |
| 24 | fn reformat_or_else(text: impl std::fmt::Display) -> String { |
| 25 | match reformat(&text) { |
| 26 | Ok(s) => s, |
| 27 | Err(_) => text.to_string(), |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | fn reformat(text: impl std::fmt::Display) -> Result<String, Error> { |
| 32 | let mut rustfmt = Command::new("rustfmt") |
| 33 | .stdin(Stdio::piped()) |
| 34 | .stdout(Stdio::piped()) |
| 35 | .spawn() |
| 36 | .map_err(Error::Run)?; |
| 37 | write!(rustfmt.stdin.take().unwrap(), "{}", text).map_err(Error::Write)?; |
| 38 | let output = rustfmt.wait_with_output().map_err(Error::Wait)?; |
| 39 | String::from_utf8(output.stdout).map_err(Error::Utf8) |
| 40 | } |