Skip to content

Commit

Permalink
fix: bug that caused the fmt to overwrite the input source file wit…
Browse files Browse the repository at this point in the history
…h empty content.

When the input file was syntactically incorrect, `yr fmt` was overwriting the input file with empty content.
  • Loading branch information
plusvic committed Sep 25, 2023
1 parent 2274f4b commit 7c73843
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions yara-x-cli/src/commands/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,45 @@
use std::fs;
use std::fs::File;
use std::io::{stdin, stdout};
use std::io::{stdin, stdout, Cursor, Seek, Write};
use std::path::PathBuf;

use clap::{arg, value_parser, ArgAction, ArgMatches, Command};
use yara_x_fmt::Formatter;

pub fn fmt() -> Command {
super::command("fmt").about("Format source files").arg(
arg!(<RULES_PATH>)
.help("Path to YARA source file or directory")
super::command("fmt").about("Format YARA source files")
.arg(
arg!(<FILE>)
.help("Path to YARA source file")
.value_parser(value_parser!(PathBuf))
.action(ArgAction::Append),
)
)
.arg(
arg!(-w --write ... "Write output to source file instead of stdout")
.action(ArgAction::SetTrue),
)
}

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

let formatter = Formatter::new();

if let Some(files) = rules_path {
if let Some(files) = files {
for file in files {
let input = fs::read(file.as_path())?;
let output = File::create(file.as_path())?;
formatter.format(input.as_slice(), output)?;
if *write.unwrap() {
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())?;
} else {
formatter.format(input.as_slice(), stdout())?;
};
}
} else {
formatter.format(stdin(), stdout())?;
Expand Down

0 comments on commit 7c73843

Please sign in to comment.