Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow passing multiple input files #18

Merged
merged 1 commit into from
Oct 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading