blob: 9c23cbca2d0e11e81459d184233d48c22d39f6c5 [file] [log] [blame]
Brian Silverman4e662aa2022-05-11 23:10:19 -07001// 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
9use proc_macro2::TokenStream;
10use std::io::Write;
11use std::process::{Command, Stdio};
12
13enum Error {
14 Run(std::io::Error),
15 Write(std::io::Error),
16 Utf8(std::string::FromUtf8Error),
17 Wait(std::io::Error),
18}
19
20pub(crate) fn pretty_print(ts: &TokenStream) -> String {
21 reformat_or_else(ts.to_string())
22}
23
24fn 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
31fn 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}