use super::*;
use std::io::Write;
impl Config<'_> {
pub fn format(&self, tokens: &str) -> String {
let preamble = if self.no_comment {
String::new()
} else {
let version = std::env!("CARGO_PKG_VERSION");
format!(
r#"// Bindings generated by `windows-bindgen` {version}
"#
)
};
let allow = if self.no_allow {
""
} else {
"#![allow(non_snake_case, non_upper_case_globals, non_camel_case_types, dead_code, clippy::all)]\n\n"
};
let tokens = format!("{preamble}{allow}{tokens}");
if let Some(result) = self.rustfmt(&tokens) {
result
} else {
self.warnings
.add("failed to format output with `rustfmt`".to_string());
tokens
}
}
fn rustfmt(&self, tokens: &str) -> Option<String> {
let mut cmd = std::process::Command::new("rustfmt");
cmd.stdin(std::process::Stdio::piped());
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::null());
if !self.rustfmt.is_empty() {
cmd.arg("--config");
cmd.arg(self.rustfmt);
}
let mut child = cmd.spawn().ok()?;
let mut stdin = child.stdin.take()?;
stdin.write_all(tokens.as_bytes()).ok()?;
drop(stdin);
let output = child.wait_with_output().ok()?;
if !output.status.success() {
return None;
}
String::from_utf8(output.stdout).ok()
}
}