use std::fs;
use std::path::PathBuf;
use std::process::ExitCode;
const MARKER: &str = "/* FORMATTED */";
fn main() -> ExitCode {
let mut write_mode = false;
let mut dry_run = false;
let mut werror = false;
let mut style_argument_seen = false;
let mut files: Vec<PathBuf> = Vec::new();
for arg in std::env::args().skip(1) {
match arg.as_str() {
"-i" => write_mode = true,
"--dry-run" => dry_run = true,
"-Werror" => werror = true,
other if other.starts_with("--style=") => style_argument_seen = true,
other => files.push(PathBuf::from(other)),
}
}
if !style_argument_seen {
eprintln!(
"cabin-fmt-fake-formatter: expected --style=<value>; cabin fmt must always pass --style=file"
);
return ExitCode::from(3);
}
if write_mode {
for path in &files {
let body = match fs::read_to_string(path) {
Ok(b) => b,
Err(err) => {
eprintln!("cabin-fmt-fake-formatter: {}: {}", path.display(), err);
return ExitCode::from(2);
}
};
if !body.trim_end().ends_with(MARKER) {
let mut updated = body.clone();
if !updated.ends_with('\n') {
updated.push('\n');
}
updated.push_str(MARKER);
updated.push('\n');
if let Err(err) = fs::write(path, updated) {
eprintln!("cabin-fmt-fake-formatter: {}: {}", path.display(), err);
return ExitCode::from(2);
}
}
}
return ExitCode::SUCCESS;
}
if dry_run && werror {
let mut needs_format = false;
for path in &files {
let body = match fs::read_to_string(path) {
Ok(b) => b,
Err(err) => {
eprintln!("cabin-fmt-fake-formatter: {}: {}", path.display(), err);
return ExitCode::from(2);
}
};
if !body.trim_end().ends_with(MARKER) {
needs_format = true;
eprintln!("{}: would be reformatted", path.display());
}
}
if needs_format {
return ExitCode::from(1);
}
return ExitCode::SUCCESS;
}
ExitCode::SUCCESS
}