aboutsummaryrefslogtreecommitdiff
path: root/syn/codegen/src/file.rs
blob: 5521d75984479cff4a79b645494bce86124ae9d8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use anyhow::Result;
use proc_macro2::TokenStream;
use std::fs;
use std::io::Write;
use std::path::Path;

pub fn write<P: AsRef<Path>>(path: P, content: TokenStream) -> Result<()> {
    let mut formatted = Vec::new();
    writeln!(
        formatted,
        "// This file is @generated by syn-internal-codegen."
    )?;
    writeln!(formatted, "// It is not intended for manual editing.")?;
    writeln!(formatted)?;

    let mut config = rustfmt::Config::default();
    config.set().emit_mode(rustfmt::EmitMode::Stdout);
    config.set().verbose(rustfmt::Verbosity::Quiet);
    config.set().format_macro_matchers(true);
    config.set().normalize_doc_attributes(true);

    let mut session = rustfmt::Session::new(config, Some(&mut formatted));
    session.format(rustfmt::Input::Text(content.to_string()))?;
    drop(session);

    if path.as_ref().is_file() && fs::read(&path)? == formatted {
        return Ok(());
    }

    fs::write(path, formatted)?;
    Ok(())
}