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: functionality to execute command on matched file #22

Merged
merged 1 commit into from
Jan 20, 2024
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
37 changes: 34 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::{path::PathBuf, process::Command};

use pest::Parser;
use tag::{
parsers::query::{construct_query_ast, evaluate_ast, QueryParser, Rule},
Expand All @@ -11,16 +13,20 @@ mod cli {
#[command(author, version, about, long_about = None)]
pub struct Cli {
#[clap(value_name = "QUERY")]
/// Search query for the tags
/// Search query for the tags.
pub query: String,

#[clap(value_name = "PATH")]
/// The path that will be searched
/// The path that will be searched.
pub path: String,

#[arg(short, long)]
/// Only print the paths of matched files.
pub silent: bool,

#[arg(short, long)]
/// A command that will be executed on matched files.
pub command: String,
}

impl Cli {
Expand All @@ -30,13 +36,32 @@ 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();

if let Err(e) = &output {
println!("Wasn't able to execute command {}: {}", command, e);
}

let output = output.unwrap();
let output_string = std::str::from_utf8(output.stdout.as_slice());

if let Err(e) = &output_string {
println!("Failed to get output from command {}: {}", command, e);
}

output_string.unwrap().to_string()
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = cli::Cli::new_and_parse();

let file_index = get_tags_from_files(args.path.as_str())?;
let query = QueryParser::parse(Rule::tagsearch, args.query.as_str());

if let Err(e) = query {
if let Err(e) = &query {
println!("Error: {}", e);
std::process::exit(1);
}
Expand All @@ -55,8 +80,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

println!("{}", file.path.display());

let mut output = String::new();
if !args.command.is_empty() {
output = execute_command_on_file(file.path.clone(), args.command.clone());
}

if !args.silent {
println!("\ttags:{:?} ", file.tags);
println!("\tOutput of command:\n{}", output);
}
}

Expand Down