diff --git a/Cargo.toml b/Cargo.toml index b8f503e..d1cd352 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ exclude = ["/.github/*"] [dependencies] clap = { version = "4.3.19", features = ["derive"] } indexmap = "2.0.0" +owo-colors = "3.5.0" [dev-dependencies] pretty_assertions = { version= "1.4.0" } diff --git a/src/main.rs b/src/main.rs index 4a46c5e..a297682 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use std::process; use bulloak::*; use clap::Parser; +use owo_colors::OwoColorize; #[derive(Parser)] #[command(author, version, about, long_about = None)] // Read from `Cargo.toml` @@ -24,9 +25,16 @@ struct Config { /// Whether to write to files instead of stdout. /// /// This will write the output for each input file to the file - /// specified at the root of the input file. - #[arg(short = 'w', long = "write-files")] + /// specified at the root of the input file if the output file + /// doesn't already exist. To overwrite, use `--force-write` + /// together with `--write-files`. + #[arg(short = 'w', long, group = "file-handling")] write_files: bool, + + /// When `write_files` is specified, use `--force-write` to + /// overwrite the output files. + #[arg(short = 'f', long, requires = "file-handling", default_value = "false")] + force_write: bool, } fn main() -> Result<()> { @@ -41,14 +49,32 @@ fn main() -> Result<()> { } fn run(config: &Config) -> Result<()> { + // For each input file, compile it and print it or write it + // to the filesystem. for file in config.files.iter() { let text = fs::read_to_string(file)?; match scaffold(&text, config.with_actions_as_comments, config.indent) { Ok(compiled) => { if config.write_files { - let mut path = file.clone(); - path.set_file_name(compiled.output_file); - fs::write(path, compiled.emitted)?; + let mut output_path = file.clone(); + + // Get the path to the output file. + output_path.set_file_name(compiled.output_file); + + // Don't overwrite files unless `--force-write` was passed. + if output_path.try_exists().is_ok() && !config.force_write { + eprintln!( + "{}: Skipped emitting to {:?}.\n The file {:?} already exists.", + "WARN".yellow(), + file.as_path().blue(), + output_path.as_path().blue() + ); + continue; + } + + if let Err(e) = fs::write(output_path, compiled.emitted) { + eprintln!("{}: {}", "ERROR".red(), e); + }; } else { println!("{}", compiled.emitted); }