mod.rs
This file
Path
src/exec/mod.rs
351 lines · 10.5 KiB · Rust
Last changed by
Sort search results when using -X optionMarcoIenibefore adoption320d7fc
History of this fileTake it
The walk stopped after 200 commits: lines older than 88fb9d7 point at it.
Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 1–11why, one step back1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89// TODO: Possible optimization could avoid pushing characters on a buffer.10mod command;11mod input;Run latest version of rustfmtsharkdpbefore adoption6a9f16e
lines 12–13why, one step back12mod job;13mod token;Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 14–15why, one step back1415use std::borrow::Cow;Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 16why, one step back16use std::path::{Path, PathBuf};exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 17why, one step back17use std::process::{Command, Stdio};Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 18–19why, one step back18use std::sync::{Arc, Mutex};19[2018 edition] remove all extern crate lines from sourcesAlexandru Macoveibefore adoption051ff59
line 20why, one step back20use lazy_static::lazy_static;Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 21–22why, one step back21use regex::Regex;22Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
lines 23–24why, one step back23use crate::exit_codes::ExitCode;24Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 25why, one step back25use self::command::execute_command;Run latest version of rustfmtsharkdpbefore adoption6a9f16e
line 26why, one step back26use self::input::{basename, dirname, remove_extension};Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 27why, one step back27pub use self::job::{batch, job};Run latest version of rustfmtsharkdpbefore adoption6a9f16e
line 28why, one step back28use self::token::Token;Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 29why, one step back29Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 30–32why, one step back30/// Execution mode of the command31#[derive(Debug, Clone, Copy, PartialEq)]32pub enum ExecutionMode {exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 33why, one step back33 /// Command is executed for each search resultAdd support for batch execution of commandkimsnjbefore adoption45d1b15
lines 34–38why, one step back34 OneByOne,35 /// Command is run for a batch of results at once36 Batch,37}38Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 39–45why, one step back39/// Represents a template that is utilized to generate command strings.40///41/// The template is meant to be coupled with an input in order to generate a command. The42/// `generate_and_execute()` method will be used to generate a command and execute it.43#[derive(Debug, Clone, PartialEq)]44pub struct CommandTemplate {45 args: Vec<ArgumentTemplate>,Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 46why, one step back46 mode: ExecutionMode,Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 47–54why, one step back47}4849impl CommandTemplate {50 pub fn new<I, S>(input: I) -> CommandTemplate51 where52 I: IntoIterator<Item = S>,53 S: AsRef<str>,54 {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 55–63why, one step back55 Self::build(input, ExecutionMode::OneByOne)56 }5758 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>59 where60 I: IntoIterator<Item = S>,61 S: AsRef<str>,62 {63 let cmd = Self::build(input, ExecutionMode::Batch);exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 64why, one step back64 if cmd.number_of_tokens() > 1 {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 65–66why, one step back65 return Err("Only one placeholder allowed for batch commands");66 }exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
lines 67–69why, one step back67 if cmd.args[0].has_tokens() {68 return Err("First argument of exec-batch is expected to be a fixed executable");69 }Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 70–77why, one step back70 Ok(cmd)71 }7273 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate74 where75 I: IntoIterator<Item = S>,76 S: AsRef<str>,77 {Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 78–129why, one step back78 lazy_static! {79 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();80 }8182 let mut args = Vec::new();83 let mut has_placeholder = false;8485 for arg in input {86 let arg = arg.as_ref();8788 let mut tokens = Vec::new();89 let mut start = 0;9091 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {92 // Leading text before the placeholder.93 if placeholder.start() > start {94 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));95 }9697 start = placeholder.end();9899 match placeholder.as_str() {100 "{}" => tokens.push(Token::Placeholder),101 "{.}" => tokens.push(Token::NoExt),102 "{/}" => tokens.push(Token::Basename),103 "{//}" => tokens.push(Token::Parent),104 "{/.}" => tokens.push(Token::BasenameNoExt),105 _ => panic!("Unhandled placeholder"),106 }107108 has_placeholder = true;109 }110111 // Without a placeholder, the argument is just fixed text.112 if tokens.is_empty() {113 args.push(ArgumentTemplate::Text(arg.to_owned()));114 continue;115 }116117 if start < arg.len() {118 // Trailing text after last placeholder.119 tokens.push(Token::Text(arg[start..].to_owned()));120 }121122 args.push(ArgumentTemplate::Tokens(tokens));123 }124125 // If a placeholder token was not supplied, append one at the end of the command.126 if !has_placeholder {127 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));128 }129Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 130why, one step back130 CommandTemplate { args, mode }Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 131–132why, one step back131 }132exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 133why, one step back133 fn number_of_tokens(&self) -> usize {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 134–144why, one step back134 self.args.iter().filter(|arg| arg.has_tokens()).count()135 }136137 fn prepare_path(input: &Path) -> String {138 input139 .strip_prefix(".")140 .unwrap_or(input)141 .to_string_lossy()142 .into_owned()143 }144Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 145–149why, one step back145 /// Generates and executes a command.146 ///147 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be148 /// build. Once all arguments have been processed, the command is executed.149 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 150why, one step back150 let input = Self::prepare_path(input);Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 151–156why, one step back151152 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());153 for arg in &self.args[1..] {154 cmd.arg(arg.generate(&input).as_ref());155 }156Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 157why, one step back157 execute_command(cmd, &out_perm);Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 158why, one step back158 }Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 159why, one step back159exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 160why, one step back160 pub fn in_batch_mode(&self) -> bool {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 161–163why, one step back161 self.mode == ExecutionMode::Batch162 }163Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
line 164why, one step back164 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCodeAdd support for batch execution of commandkimsnjbefore adoption45d1b15
lines 165–168why, one step back165 where166 I: Iterator<Item = PathBuf>,167 {168 let mut cmd = Command::new(self.args[0].generate("").as_ref());exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
lines 169–172why, one step back169 cmd.stdin(Stdio::inherit());170 cmd.stdout(Stdio::inherit());171 cmd.stderr(Stdio::inherit());172Sort search results when using -X optionMarcoIenibefore adoption320d7fc
line 173why, one step back173 let mut paths: Vec<String> = paths.map(|p| Self::prepare_path(&p)).collect();Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 174–177why, one step back174 let mut has_path = false;175176 for arg in &self.args[1..] {177 if arg.has_tokens() {Sort search results when using -X optionMarcoIenibefore adoption320d7fc
lines 178–179why, one step back178 paths.sort();179Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 180why, one step back180 // A single `Tokens` is expectedSort search results when using -X optionMarcoIenibefore adoption320d7fc
line 181why, one step back181 // So we can directly consume the iterator once and for allAdd support for batch execution of commandkimsnjbefore adoption45d1b15
lines 182–191why, one step back182 for path in &mut paths {183 cmd.arg(arg.generate(&path).as_ref());184 has_path = true;185 }186 } else {187 cmd.arg(arg.generate("").as_ref());188 }189 }190191 if has_path {Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd
lines 192–194why, one step back192 execute_command(cmd, &Mutex::new(()))193 } else {194 ExitCode::SuccessAdd support for batch execution of commandkimsnjbefore adoption45d1b15
lines 195–196why, one step back195 }196 }Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 197–209why, one step back197}198199/// Represents a template for a single command argument.200///201/// The argument is either a collection of `Token`s including at least one placeholder variant, or202/// a fixed text.203#[derive(Clone, Debug, PartialEq)]204enum ArgumentTemplate {205 Tokens(Vec<Token>),206 Text(String),207}208209impl ArgumentTemplate {Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 210why, one step back210 pub fn has_tokens(&self) -> bool {exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
lines 211–213why, one step back211 match self {212 ArgumentTemplate::Tokens(_) => true,213 _ => false,Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 214–216why, one step back214 }215 }216Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 217–241why, one step back217 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {218 use self::Token::*;219220 match *self {221 ArgumentTemplate::Tokens(ref tokens) => {222 let mut s = String::new();223 for token in tokens {224 match *token {225 Basename => s += basename(path),226 BasenameNoExt => s += remove_extension(basename(path)),227 NoExt => s += remove_extension(path),228 Parent => s += dirname(path),229 Placeholder => s += path,230 Text(ref string) => s += string,231 }232 }233 Cow::Owned(s)234 }235 ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),236 }237 }238}239240#[cfg(test)]241mod tests {Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
line 242why, one step back242 use super::*;Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 243–244why, one step back243244 #[test]Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 245–253why, one step back245 fn tokens_with_placeholder() {246 assert_eq!(247 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),248 CommandTemplate {249 args: vec![250 ArgumentTemplate::Text("echo".into()),251 ArgumentTemplate::Text("${SHELL}:".into()),252 ArgumentTemplate::Tokens(vec![Token::Placeholder]),253 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 254why, one step back254 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 255–257why, one step back255 }256 );257 }Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 258why, one step back258Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 259–260why, one step back259 #[test]260 fn tokens_with_no_extension() {Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 261–266why, one step back261 assert_eq!(262 CommandTemplate::new(&["echo", "{.}"]),263 CommandTemplate {264 args: vec![265 ArgumentTemplate::Text("echo".into()),266 ArgumentTemplate::Tokens(vec![Token::NoExt]),Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
line 267why, one step back267 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 268why, one step back268 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 269–281why, one step back269 }270 );271 }272273 #[test]274 fn tokens_with_basename() {275 assert_eq!(276 CommandTemplate::new(&["echo", "{/}"]),277 CommandTemplate {278 args: vec![279 ArgumentTemplate::Text("echo".into()),280 ArgumentTemplate::Tokens(vec![Token::Basename]),281 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 282why, one step back282 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 283–295why, one step back283 }284 );285 }286287 #[test]288 fn tokens_with_parent() {289 assert_eq!(290 CommandTemplate::new(&["echo", "{//}"]),291 CommandTemplate {292 args: vec![293 ArgumentTemplate::Text("echo".into()),294 ArgumentTemplate::Tokens(vec![Token::Parent]),295 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 296why, one step back296 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 297–308why, one step back297 }298 );299 }300301 #[test]302 fn tokens_with_basename_no_extension() {303 assert_eq!(304 CommandTemplate::new(&["echo", "{/.}"]),305 CommandTemplate {306 args: vec![307 ArgumentTemplate::Text("echo".into()),308 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 309why, one step back309 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 310why, one step back310 mode: ExecutionMode::OneByOne,Run updated version of rustfmtsharkdpbefore adoption88fb9d7
lines 311–313why, one step back311 }312 );313 }Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
lines 314–327why, one step back314315 #[test]316 fn tokens_multiple() {317 assert_eq!(318 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),319 CommandTemplate {320 args: vec![321 ArgumentTemplate::Text("cp".into()),322 ArgumentTemplate::Tokens(vec![Token::Placeholder]),323 ArgumentTemplate::Tokens(vec![324 Token::BasenameNoExt,325 Token::Text(".ext".into())326 ]),327 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 328why, one step back328 mode: ExecutionMode::OneByOne,Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
lines 329–330why, one step back329 }330 );Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 331–349why, one step back331 }332333 #[test]334 fn tokens_single_batch() {335 assert_eq!(336 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),337 CommandTemplate {338 args: vec![339 ArgumentTemplate::Text("echo".into()),340 ArgumentTemplate::Tokens(vec![Token::NoExt]),341 ],342 mode: ExecutionMode::Batch,343 }344 );345 }346347 #[test]348 fn tokens_multiple_batch() {349 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
line 350why, one step back350 }Run updated version of rustfmtsharkdpbefore adoption88fb9d7
line 351why, one step back351}