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

feat: adds --test flag in yr fmt #72

Closed
wants to merge 2 commits into from
Closed
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
33 changes: 26 additions & 7 deletions yara-x-cli/src/commands/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::fs;
use std::fs::File;
use std::io::{stdin, stdout, Cursor, Seek, Write};
use std::path::PathBuf;
use std::process;

use clap::{arg, value_parser, ArgAction, ArgMatches, Command};
use yara_x_fmt::Formatter;
Expand All @@ -18,29 +19,47 @@ pub fn fmt() -> Command {
arg!(-w --write ... "Write output to source file instead of stdout")
.action(ArgAction::SetTrue),
)
.arg(
arg!(-t --test ... "Exit with failure if reformatting changed the file")
.action(ArgAction::SetTrue),
)
}

pub fn exec_fmt(args: &ArgMatches) -> anyhow::Result<()> {
let files = args.get_many::<PathBuf>("FILE");
let write = args.get_one::<bool>("write");
let test = args.get_one::<bool>("test");

let formatter = Formatter::new();

if let Some(files) = files {
let mut changed_files = Vec::new();

for file in files {
let input = fs::read(file.as_path())?;
if *write.unwrap() {
let mut formatted = Cursor::new(Vec::new());

formatter.format(input.as_slice(), &mut formatted)?;
formatted.rewind()?;
let mut formatted = Cursor::new(Vec::new());

formatter.format(input.as_slice(), &mut formatted)?;
formatted.rewind()?;

File::create(file.as_path())?
.write_all(formatted.into_inner().as_slice())?;
let output = formatted.into_inner();

if *test.unwrap() && input != output {
changed_files.push(file.display().to_string());
}

if *write.unwrap() {
File::create(file.as_path())?.write_all(output.as_slice())?;
} else {
formatter.format(input.as_slice(), stdout())?;
print!("{}", String::from_utf8(output)?);
};
}

if changed_files.len() >= 1 {
eprintln!("File(s) to format: {}", changed_files.join(", "));
process::exit(2)
}
} else {
formatter.format(stdin(), stdout())?;
}
Expand Down