Skip to content

Commit

Permalink
Allow passing multiple input files
Browse files Browse the repository at this point in the history
  • Loading branch information
bbannier committed Oct 12, 2023
1 parent b075f97 commit 8966ef2
Showing 1 changed file with 24 additions and 30 deletions.
54 changes: 24 additions & 30 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ use {
#[clap(version = option_env!("VERGEN_GIT_SHA"))]
struct Args {
#[clap(
help = "input file to operate on",
long_help = "if not provided read the input from stdin"
help = "input files to operate on",
long_help = "if not provided read input from stdin"
)]
input_file: Option<PathBuf>,
input_files: Vec<PathBuf>,

#[clap(short, long, help = "skip idempotency check")]
skip_idempotence: bool,
Expand Down Expand Up @@ -45,44 +45,38 @@ fn main() -> Result<()> {
)
}))?;

let input = if let Some(input_file) = &args.input_file {
std::fs::read_to_string(input_file)
.map_err(Error::Io)
.wrap_err(format!("while reading input file {}", input_file.display()))?
} else {
let format = |code: &str, source: &str| {
format(code, args.skip_idempotence, !args.reject_parse_errors)
.wrap_err(format!("while formatting '{source}'",))
};

if args.input_files.is_empty() {
let stdin = std::io::stdin();
let mut buf = String::new();
stdin
.lock()
.read_to_string(&mut buf)
.map_err(Error::Io)
.wrap_err("while reading input from stdin")?;
buf
};
println!("{}", format(&buf, "<stdin>")?);
} else {
for input_file in &args.input_files {
let source = std::fs::read_to_string(input_file)
.map_err(Error::Io)
.wrap_err(format!("while reading input file {}", input_file.display()))?;

let formatted =
format(&input, args.skip_idempotence, !args.reject_parse_errors).wrap_err(format!(
"while formatting '{}'",
if let Some(i) = &args.input_file {
i.display().to_string()
let formatted = format(&source, &input_file.display().to_string())?;
if args.inplace {
std::fs::write(input_file, formatted)
.map_err(Error::Io)
.wrap_err(format!(
"while writing output file {}",
input_file.display()
))?;
} else {
"<stdin>".to_string()
println!("{formatted}");
}
))?;

if let Some(input_file) = &args.input_file {
if args.inplace {
std::fs::write(input_file, formatted)
.map_err(Error::Io)
.wrap_err(format!(
"while writing output file {}",
input_file.display()
))?;
} else {
println!("{formatted}");
}
} else {
println!("{formatted}");
}

Ok(())
Expand Down

0 comments on commit 8966ef2

Please sign in to comment.