Skip to content

Commit

Permalink
feat: added functionality for filter-command + fix windows command ex…
Browse files Browse the repository at this point in the history
…ecution (#27)

* added functionality for filter-command + correct execution on windows

* change filter-command help
  • Loading branch information
miampf authored Jan 21, 2024
1 parent 9ff683e commit 997c5f5
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ mod cli {
/// A command that will be executed on matched files.
pub command: Option<String>,

#[arg(short, long)]
/// A command that must run successfully for a file to be accepted.
pub filter_command: Option<String>,

#[arg(short, long)]
/// Disable coloring.
pub no_color: bool,
Expand All @@ -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!(
Expand All @@ -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<dyn std::error::Error>> {
let args = cli::Cli::new_and_parse();

Expand Down Expand Up @@ -98,10 +127,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
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();
Expand All @@ -111,6 +151,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

if !args.silent {
println!("\t{}", format!("tags: {:?}", file.tags).blue());

if !output.is_empty() {
println!(
"\tOutput of command:\n{}",
Expand Down

0 comments on commit 997c5f5

Please sign in to comment.