Skip to content

Commit

Permalink
fix(cli): stop overwriting output files (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfertel authored Aug 24, 2023
1 parent 05a0c7b commit a1395d3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
36 changes: 31 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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<()> {
Expand All @@ -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);
}
Expand Down

0 comments on commit a1395d3

Please sign in to comment.