From 997c5f52a5681a7aace7b7e1bb0a22eda7db0779 Mon Sep 17 00:00:00 2001 From: miampf Date: Sun, 21 Jan 2024 15:05:05 +0000 Subject: [PATCH] feat: added functionality for filter-command + fix windows command execution (#27) * added functionality for filter-command + correct execution on windows * change filter-command help --- src/main.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 23f2482..19b97e8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,10 @@ mod cli { /// A command that will be executed on matched files. pub command: Option, + #[arg(short, long)] + /// A command that must run successfully for a file to be accepted. + pub filter_command: Option, + #[arg(short, long)] /// Disable coloring. pub no_color: bool, @@ -44,7 +48,11 @@ mod cli { fn execute_command_on_file(path: PathBuf, command: String) -> String { let command = command.replace("#FILE#", path.to_str().unwrap()); - let output = Command::new("bash").arg("-c").arg(command.clone()).output(); + let output = if cfg!(target_os = "windows") { + Command::new("cmd").arg("/C").arg(command.clone()).output() + } else { + Command::new("bash").arg("-c").arg(command.clone()).output() + }; if let Err(e) = &output { eprintln!( @@ -70,6 +78,27 @@ fn execute_command_on_file(path: PathBuf, command: String) -> String { output_string.unwrap().to_string() } +fn execute_filter_command_on_file(path: PathBuf, command: String) -> bool { + let command = command.replace("#FILE#", path.to_str().unwrap()); + + let output = if cfg!(target_os = "windows") { + Command::new("cmd").arg("/C").arg(command.clone()).output() + } else { + Command::new("bash").arg("-c").arg(command.clone()).output() + }; + + if let Err(e) = &output { + eprintln!( + "{} Wasn't able to execute command {}: {}", + "[ERROR]".red().bold(), + command.blue().underline(), + e.to_string().red() + ); + } + + output.unwrap().status.success() +} + fn main() -> Result<(), Box> { let args = cli::Cli::new_and_parse(); @@ -98,10 +127,21 @@ fn main() -> Result<(), Box> { file.tags.iter().map(|tag| tag.as_str()).collect(), ); + // skip the file if tags don't match query if !evaluate_ast(ast) { continue; } + // skip the file if filter command is unsuccessful + if args.filter_command.is_some() + && !execute_filter_command_on_file( + file.path.clone(), + args.filter_command.clone().unwrap(), + ) + { + continue; + } + println!("{}", file.path.display().to_string().green()); let mut output = String::new(); @@ -111,6 +151,7 @@ fn main() -> Result<(), Box> { if !args.silent { println!("\t{}", format!("tags: {:?}", file.tags).blue()); + if !output.is_empty() { println!( "\tOutput of command:\n{}",