Skip to content

Commit

Permalink
Format generated code with prettyplease
Browse files Browse the repository at this point in the history
  • Loading branch information
schmidma committed May 5, 2024
1 parent 9457266 commit 1d0be89
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 14 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ path_serde = { path = "crates/path_serde" }
path_serde_derive = { path = "crates/path_serde_derive" }
petgraph = "0.6.2"
png = "0.17.6"
prettyplease = "0.2.19"
proc-macro-error = "1.0.4"
proc-macro2 = { version = "1.0.44", features = ["span-locations"] }
projection = { path = "crates/projection" }
Expand Down
1 change: 1 addition & 0 deletions crates/code_generation/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ homepage.workspace = true
[dependencies]
convert_case = { workspace = true }
itertools = { workspace = true }
prettyplease = { workspace = true }
proc-macro2 = { workspace = true }
quote = { workspace = true }
source_analyzer = { workspace = true }
Expand Down
23 changes: 9 additions & 14 deletions crates/code_generation/src/write_to_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::{
fs::File,
io::{self, Write},
path::{Path, PathBuf},
process::Command,
};

use proc_macro2::TokenStream;
Expand All @@ -15,27 +14,23 @@ pub enum Error {
Environment(#[from] VarError),
#[error("failed to perform io")]
Io(#[from] io::Error),
#[error("failed to run rustfmt")]
RustFmt,
#[error("failed to parse token stream")]
Parse(#[from] syn::Error),
}

pub trait WriteToFile {
fn write_to_file(&self, file_name: impl AsRef<Path>) -> Result<(), Error>;
fn write_to_file(self, file_name: impl AsRef<Path>) -> Result<(), Error>;
}

impl WriteToFile for TokenStream {
fn write_to_file(&self, file_name: impl AsRef<Path>) -> Result<(), Error> {
fn write_to_file(self, file_name: impl AsRef<Path>) -> Result<(), Error> {
let syntax_tree = syn::parse2(self)?;
let pretty = prettyplease::unparse(&syntax_tree);

let out_dir = var("OUT_DIR")?;
let file_path = PathBuf::from(out_dir).join(file_name);
{
let mut file = File::create(&file_path)?;
write!(file, "{self}")?;
}

let status = Command::new("rustfmt").arg(file_path).status()?;
if !status.success() {
return Err(Error::RustFmt);
}
let mut file = File::create(file_path)?;
write!(file, "{pretty}")?;

Ok(())
}
Expand Down

0 comments on commit 1d0be89

Please sign in to comment.