rustfmt_snippet/
lib.rs

1//! Format given Rust code snippet with rustfmt
2//!
3//! #Example
4//! ```
5//!    let formated = rustfmt_snippet::rustfmt(
6//!        r#"fn main() {
7//!        }"#,
8//!    )
9//!    .unwrap();
10//!    assert_eq!(formated, "fn main() {}\n");
11//! ```
12
13/// Format given Rust code snippet with rustfmt
14pub fn rustfmt(source: &str) -> std::io::Result<String> {
15    use std::{
16        io::Write,
17        process::{Command, Stdio},
18    };
19    let proc = Command::new("rustfmt")
20        .args(["--emit", "stdout", "--edition", "2018"])
21        .stdin(Stdio::piped())
22        .stdout(Stdio::piped())
23        .spawn()?;
24    proc.stdin
25        .as_ref()
26        .expect("It always exists")
27        .write_all(source.as_bytes())?;
28    let output = proc.wait_with_output().unwrap();
29    Ok(String::from_utf8_lossy(output.stdout.as_slice()).to_string())
30}
31
32/// Format given TokenStream with rustfmt
33pub fn rustfmt_token_stream(stream: &proc_macro2::TokenStream) -> std::io::Result<String> {
34    rustfmt(&format!("{stream}"))
35}
36
37#[test]
38fn it_works() {
39    let formated = rustfmt(
40        r#"fn foo() {
41        }"#,
42    )
43    .unwrap();
44    assert_eq!(formated, "fn foo() {}\n");
45}