mod.rs
This file
Path
src/exec/mod.rs
340 lines · 10.0 KiB · Rust
Last changed by
Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
History of this fileTake it
The walk stopped after 200 commits: lines older than 8c197d2 point at it.
Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 1–5why, one step back1mod command;2mod input;3mod job;4mod token;5Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 6why, one step back6use std::ffi::OsString;Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 7–10why, one step back7use std::path::{Path, PathBuf};8use std::process::{Command, Stdio};9use std::sync::{Arc, Mutex};10Proper error handling in main.rssharkdpbefore adoptionbce9527
line 11why, one step back11use anyhow::{anyhow, Result};Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 12–14why, one step back12use lazy_static::lazy_static;13use regex::Regex;14Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 15why, one step back15use crate::exit_codes::ExitCode;Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c
line 16why, one step back16use crate::filesystem::strip_current_dir;Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 17why, one step back17Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 18–50why, one step back18use self::command::execute_command;19use self::input::{basename, dirname, remove_extension};20pub use self::job::{batch, job};21use self::token::Token;2223/// Execution mode of the command24#[derive(Debug, Clone, Copy, PartialEq)]25pub enum ExecutionMode {26 /// Command is executed for each search result27 OneByOne,28 /// Command is run for a batch of results at once29 Batch,30}3132/// Represents a template that is utilized to generate command strings.33///34/// The template is meant to be coupled with an input in order to generate a command. The35/// `generate_and_execute()` method will be used to generate a command and execute it.36#[derive(Debug, Clone, PartialEq)]37pub struct CommandTemplate {38 args: Vec<ArgumentTemplate>,39 mode: ExecutionMode,40}4142impl CommandTemplate {43 pub fn new<I, S>(input: I) -> CommandTemplate44 where45 I: IntoIterator<Item = S>,46 S: AsRef<str>,47 {48 Self::build(input, ExecutionMode::OneByOne)49 }50Proper error handling in main.rssharkdpbefore adoptionbce9527
line 51why, one step back51 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate>Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 52–57why, one step back52 where53 I: IntoIterator<Item = S>,54 S: AsRef<str>,55 {56 let cmd = Self::build(input, ExecutionMode::Batch);57 if cmd.number_of_tokens() > 1 {Proper error handling in main.rssharkdpbefore adoptionbce9527
line 58why, one step back58 return Err(anyhow!("Only one placeholder allowed for batch commands"));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 59–60why, one step back59 }60 if cmd.args[0].has_tokens() {Proper error handling in main.rssharkdpbefore adoptionbce9527
lines 61–63why, one step back61 return Err(anyhow!(62 "First argument of exec-batch is expected to be a fixed executable"63 ));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 64–99why, one step back64 }65 Ok(cmd)66 }6768 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate69 where70 I: IntoIterator<Item = S>,71 S: AsRef<str>,72 {73 lazy_static! {74 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();75 }7677 let mut args = Vec::new();78 let mut has_placeholder = false;7980 for arg in input {81 let arg = arg.as_ref();8283 let mut tokens = Vec::new();84 let mut start = 0;8586 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {87 // Leading text before the placeholder.88 if placeholder.start() > start {89 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));90 }9192 start = placeholder.end();9394 match placeholder.as_str() {95 "{}" => tokens.push(Token::Placeholder),96 "{.}" => tokens.push(Token::NoExt),97 "{/}" => tokens.push(Token::Basename),98 "{//}" => tokens.push(Token::Parent),99 "{/.}" => tokens.push(Token::BasenameNoExt),panic => unreachablesharkdpbefore adoption439548c
line 100why, one step back100 _ => unreachable!("Unhandled placeholder"),Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 101–135why, one step back101 }102103 has_placeholder = true;104 }105106 // Without a placeholder, the argument is just fixed text.107 if tokens.is_empty() {108 args.push(ArgumentTemplate::Text(arg.to_owned()));109 continue;110 }111112 if start < arg.len() {113 // Trailing text after last placeholder.114 tokens.push(Token::Text(arg[start..].to_owned()));115 }116117 args.push(ArgumentTemplate::Tokens(tokens));118 }119120 // If a placeholder token was not supplied, append one at the end of the command.121 if !has_placeholder {122 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));123 }124125 CommandTemplate { args, mode }126 }127128 fn number_of_tokens(&self) -> usize {129 self.args.iter().filter(|arg| arg.has_tokens()).count()130 }131132 /// Generates and executes a command.133 ///134 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be135 /// build. Once all arguments have been processed, the command is executed.Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492
line 136why, one step back136 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c
line 137why, one step back137 let input = strip_current_dir(input);Update to new lscolors versionsharkdpbefore adoption8c197d2
line 138why, one step back138Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 139why, one step back139 let mut cmd = Command::new(self.args[0].generate(&input));Update to new lscolors versionsharkdpbefore adoption8c197d2
line 140why, one step back140 for arg in &self.args[1..] {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 141why, one step back141 cmd.arg(arg.generate(&input));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 142–143why, one step back142 }143Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492
line 144why, one step back144 execute_command(cmd, &out_perm)Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 145–150why, one step back145 }146147 pub fn in_batch_mode(&self) -> bool {148 self.mode == ExecutionMode::Batch149 }150Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 151why, one step back151 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCodeUpdate to new lscolors versionsharkdpbefore adoption8c197d2
lines 152–154why, one step back152 where153 I: Iterator<Item = PathBuf>,154 {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 155why, one step back155 let mut cmd = Command::new(self.args[0].generate(""));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 156–159why, one step back156 cmd.stdin(Stdio::inherit());157 cmd.stdout(Stdio::inherit());158 cmd.stderr(Stdio::inherit());159Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c
line 160why, one step back160 let mut paths: Vec<_> = paths.collect();Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 161–164why, one step back161 let mut has_path = false;162163 for arg in &self.args[1..] {164 if arg.has_tokens() {Sort search results when using -X optionMarcoIenibefore adoption320d7fc
lines 165–166why, one step back165 paths.sort();166Update to new lscolors versionsharkdpbefore adoption8c197d2
line 167why, one step back167 // A single `Tokens` is expectedSort search results when using -X optionMarcoIenibefore adoption320d7fc
line 168why, one step back168 // So we can directly consume the iterator once and for allUpdate to new lscolors versionsharkdpbefore adoption8c197d2
line 169why, one step back169 for path in &mut paths {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 170why, one step back170 cmd.arg(arg.generate(strip_current_dir(path)));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 171–173why, one step back171 has_path = true;172 }173 } else {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 174why, one step back174 cmd.arg(arg.generate(""));Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 175–178why, one step back175 }176 }177178 if has_path {Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
lines 179–181why, one step back179 execute_command(cmd, &Mutex::new(()))180 } else {181 ExitCode::SuccessUpdate to new lscolors versionsharkdpbefore adoption8c197d2
lines 182–203why, one step back182 }183 }184}185186/// Represents a template for a single command argument.187///188/// The argument is either a collection of `Token`s including at least one placeholder variant, or189/// a fixed text.190#[derive(Clone, Debug, PartialEq)]191enum ArgumentTemplate {192 Tokens(Vec<Token>),193 Text(String),194}195196impl ArgumentTemplate {197 pub fn has_tokens(&self) -> bool {198 match self {199 ArgumentTemplate::Tokens(_) => true,200 _ => false,201 }202 }203Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 204why, one step back204 pub fn generate<'a>(&'a self, path: impl AsRef<Path>) -> OsString {Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 205–208why, one step back205 use self::Token::*;206207 match *self {208 ArgumentTemplate::Tokens(ref tokens) => {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 209why, one step back209 let mut s = OsString::new();Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 210–211why, one step back210 for token in tokens {211 match *token {Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
lines 212–219why, one step back212 Basename => s.push(basename(path.as_ref())),213 BasenameNoExt => {214 s.push(remove_extension(&PathBuf::from(basename(path.as_ref()))))215 }216 NoExt => s.push(remove_extension(path.as_ref())),217 Parent => s.push(dirname(path.as_ref())),218 Placeholder => s.push(path.as_ref()),219 Text(ref string) => s.push(string),Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 220–221why, one step back220 }221 }Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 222why, one step back222 sUpdate to new lscolors versionsharkdpbefore adoption8c197d2
line 223why, one step back223 }Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c
line 224why, one step back224 ArgumentTemplate::Text(ref text) => OsString::from(text),Update to new lscolors versionsharkdpbefore adoption8c197d2
lines 225–340why, one step back225 }226 }227}228229#[cfg(test)]230mod tests {231 use super::*;232233 #[test]234 fn tokens_with_placeholder() {235 assert_eq!(236 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),237 CommandTemplate {238 args: vec![239 ArgumentTemplate::Text("echo".into()),240 ArgumentTemplate::Text("${SHELL}:".into()),241 ArgumentTemplate::Tokens(vec![Token::Placeholder]),242 ],243 mode: ExecutionMode::OneByOne,244 }245 );246 }247248 #[test]249 fn tokens_with_no_extension() {250 assert_eq!(251 CommandTemplate::new(&["echo", "{.}"]),252 CommandTemplate {253 args: vec![254 ArgumentTemplate::Text("echo".into()),255 ArgumentTemplate::Tokens(vec![Token::NoExt]),256 ],257 mode: ExecutionMode::OneByOne,258 }259 );260 }261262 #[test]263 fn tokens_with_basename() {264 assert_eq!(265 CommandTemplate::new(&["echo", "{/}"]),266 CommandTemplate {267 args: vec![268 ArgumentTemplate::Text("echo".into()),269 ArgumentTemplate::Tokens(vec![Token::Basename]),270 ],271 mode: ExecutionMode::OneByOne,272 }273 );274 }275276 #[test]277 fn tokens_with_parent() {278 assert_eq!(279 CommandTemplate::new(&["echo", "{//}"]),280 CommandTemplate {281 args: vec![282 ArgumentTemplate::Text("echo".into()),283 ArgumentTemplate::Tokens(vec![Token::Parent]),284 ],285 mode: ExecutionMode::OneByOne,286 }287 );288 }289290 #[test]291 fn tokens_with_basename_no_extension() {292 assert_eq!(293 CommandTemplate::new(&["echo", "{/.}"]),294 CommandTemplate {295 args: vec![296 ArgumentTemplate::Text("echo".into()),297 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),298 ],299 mode: ExecutionMode::OneByOne,300 }301 );302 }303304 #[test]305 fn tokens_multiple() {306 assert_eq!(307 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),308 CommandTemplate {309 args: vec![310 ArgumentTemplate::Text("cp".into()),311 ArgumentTemplate::Tokens(vec![Token::Placeholder]),312 ArgumentTemplate::Tokens(vec![313 Token::BasenameNoExt,314 Token::Text(".ext".into())315 ]),316 ],317 mode: ExecutionMode::OneByOne,318 }319 );320 }321322 #[test]323 fn tokens_single_batch() {324 assert_eq!(325 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),326 CommandTemplate {327 args: vec![328 ArgumentTemplate::Text("echo".into()),329 ArgumentTemplate::Tokens(vec![Token::NoExt]),330 ],331 mode: ExecutionMode::Batch,332 }333 );334 }335336 #[test]337 fn tokens_multiple_batch() {338 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());339 }340}