use std::cell::RefCell;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
thread_local! {
static TOUCHED: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
}
pub fn touched(path: &Path) {
if path.extension().is_some_and(|ext| ext == "rs") {
TOUCHED.with(|files| {
let mut files = files.borrow_mut();
if !files.iter().any(|file| file == path) {
files.push(path.to_path_buf());
}
});
}
}
pub fn format_touched() -> usize {
let files: Vec<PathBuf> = TOUCHED.with(|files| std::mem::take(&mut *files.borrow_mut()));
files.iter().filter(|file| format_one(file)).count()
}
fn format_one(file: &Path) -> bool {
let Ok(source) = std::fs::read_to_string(file) else {
return false;
};
let Ok(mut child) = Command::new("rustfmt")
.args(["--edition", "2024", "--emit", "stdout"])
.current_dir(file.parent().unwrap_or(Path::new(".")))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
else {
return false;
};
if let Some(mut stdin) = child.stdin.take()
&& stdin.write_all(source.as_bytes()).is_err()
{
return false;
}
match child.wait_with_output() {
Ok(output) if output.status.success() && !output.stdout.is_empty() => {
output.stdout == source.as_bytes() || std::fs::write(file, output.stdout).is_ok()
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rustfmt_installed() -> bool {
Command::new("rustfmt").arg("--version").output().is_ok()
}
#[test]
fn formats_only_the_files_it_was_given() {
if !rustfmt_installed() {
eprintln!("rustfmt isn't installed; skipped");
return;
}
let dir = tempfile::tempdir().unwrap();
let written = dir.path().join("written.rs");
let untouched = dir.path().join("untouched.rs");
let messy = "mod zeta;\nmod alpha;\nfn main(){let x=1;}\n";
std::fs::write(&written, messy).unwrap();
std::fs::write(&untouched, messy).unwrap();
touched(&written);
touched(&written);
touched(&dir.path().join("schema.sql"));
assert_eq!(format_touched(), 1);
assert_eq!(
std::fs::read_to_string(&written).unwrap(),
"mod alpha;\nmod zeta;\nfn main() {\n let x = 1;\n}\n"
);
assert_eq!(std::fs::read_to_string(&untouched).unwrap(), messy);
assert_eq!(format_touched(), 0);
}
}