mod.rs
This file
Path
src/exec/mod.rs
345 lines · 10.3 KiB · Rust
Last changed by
[2018 edition] remove all extern crate lines from sourcesAlexandru Macoveibefore adoption051ff59
History of this fileTake it
The walk stopped after 200 commits: lines older than bba5c4f point at it.
Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 1–9why, 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.Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
line 10why, one step back10mod command;Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 11why, one step back11mod input;Run latest version of rustfmtsharkdpbefore adoption6a9f16e
lines 12–13why, one step back12mod job;13mod token;Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 14why, one step back14Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 15why, one step back15use 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};Fix some clippy warningssharkdpbefore adoptionbba5c4f
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;Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 21–22why, one step back21use regex::Regex;22Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
line 23why, one step back23use self::command::execute_command;Run latest version of rustfmtsharkdpbefore adoption6a9f16e
line 24why, one step back24use self::input::{basename, dirname, remove_extension};Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 25why, one step back25pub use self::job::{batch, job};Run latest version of rustfmtsharkdpbefore adoption6a9f16e
line 26why, one step back26use self::token::Token;Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 27why, one step back27Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 28–30why, one step back28/// Execution mode of the command29#[derive(Debug, Clone, Copy, PartialEq)]30pub enum ExecutionMode {exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 31why, one step back31 /// Command is executed for each search resultAdd support for batch execution of commandkimsnjbefore adoption45d1b15
lines 32–36why, one step back32 OneByOne,33 /// Command is run for a batch of results at once34 Batch,35}36Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
line 37why, one step back37/// Represents a template that is utilized to generate command strings.Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 38why, one step back38///Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 39–40why, one step back39/// The template is meant to be coupled with an input in order to generate a command. The40/// `generate_and_execute()` method will be used to generate a command and execute it.Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 41why, one step back41#[derive(Debug, Clone, PartialEq)]Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 42–43why, one step back42pub struct CommandTemplate {43 args: Vec<ArgumentTemplate>,Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 44why, one step back44 mode: ExecutionMode,Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 45–46why, one step back45}46Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 47–48why, one step back47impl CommandTemplate {48 pub fn new<I, S>(input: I) -> CommandTemplateRemove shell with --execMatthias Reitingerbefore adoption18709b1
lines 49–52why, one step back49 where50 I: IntoIterator<Item = S>,51 S: AsRef<str>,52 {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 53–61why, one step back53 Self::build(input, ExecutionMode::OneByOne)54 }5556 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>57 where58 I: IntoIterator<Item = S>,59 S: AsRef<str>,60 {61 let cmd = Self::build(input, ExecutionMode::Batch);exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 62why, one step back62 if cmd.number_of_tokens() > 1 {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 63–64why, one step back63 return Err("Only one placeholder allowed for batch commands");64 }exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
lines 65–67why, one step back65 if cmd.args[0].has_tokens() {66 return Err("First argument of exec-batch is expected to be a fixed executable");67 }Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 68–75why, one step back68 Ok(cmd)69 }7071 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate72 where73 I: IntoIterator<Item = S>,74 S: AsRef<str>,75 {Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 76why, one step back76 lazy_static! {Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
line 77why, one step back77 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 78–88why, one step back78 }7980 let mut args = Vec::new();81 let mut has_placeholder = false;8283 for arg in input {84 let arg = arg.as_ref();8586 let mut tokens = Vec::new();87 let mut start = 0;88Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
line 89why, one step back89 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 90–92why, one step back90 // Leading text before the placeholder.91 if placeholder.start() > start {92 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 93why, one step back93 }Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 94–103why, one step back9495 start = placeholder.end();9697 match placeholder.as_str() {98 "{}" => tokens.push(Token::Placeholder),99 "{.}" => tokens.push(Token::NoExt),100 "{/}" => tokens.push(Token::Basename),101 "{//}" => tokens.push(Token::Parent),102 "{/.}" => tokens.push(Token::BasenameNoExt),103 _ => panic!("Unhandled placeholder"),Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 104why, one step back104 }Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 105–106why, one step back105106 has_placeholder = true;Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 107–108why, one step back107 }108Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 109–110why, one step back109 // Without a placeholder, the argument is just fixed text.110 if tokens.is_empty() {Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
line 111why, one step back111 args.push(ArgumentTemplate::Text(arg.to_owned()));Remove shell with --execMatthias Reitingerbefore adoption18709b1
lines 112–119why, one step back112 continue;113 }114115 if start < arg.len() {116 // Trailing text after last placeholder.117 tokens.push(Token::Text(arg[start..].to_owned()));118 }119Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
line 120why, one step back120 args.push(ArgumentTemplate::Tokens(tokens));Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 121–123why, one step back121 }122123 // If a placeholder token was not supplied, append one at the end of the command.Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 124why, one step back124 if !has_placeholder {Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
line 125why, one step back125 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 126–127why, one step back126 }127Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 128why, one step back128 CommandTemplate { args, mode }Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 129–130why, one step back129 }130exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 131why, one step back131 fn number_of_tokens(&self) -> usize {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 132–142why, one step back132 self.args.iter().filter(|arg| arg.has_tokens()).count()133 }134135 fn prepare_path(input: &Path) -> String {136 input137 .strip_prefix(".")138 .unwrap_or(input)139 .to_string_lossy()140 .into_owned()141 }142Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
line 143why, one step back143 /// Generates and executes a command.Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 144why, one step back144 ///Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
lines 145–147why, one step back145 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be146 /// build. Once all arguments have been processed, the command is executed.147 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) {Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 148why, one step back148 let input = Self::prepare_path(input);Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 149why, one step back149Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa
lines 150–152why, one step back150 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());151 for arg in &self.args[1..] {152 cmd.arg(arg.generate(&input).as_ref());Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 153–154why, one step back153 }154Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 155why, one step back155 execute_command(cmd, &out_perm)Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 156why, one step back156 }Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 157why, one step back157exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
line 158why, one step back158 pub fn in_batch_mode(&self) -> bool {Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 159–166why, one step back159 self.mode == ExecutionMode::Batch160 }161162 pub fn generate_and_execute_batch<I>(&self, paths: I)163 where164 I: Iterator<Item = PathBuf>,165 {166 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 167–170why, one step back167 cmd.stdin(Stdio::inherit());168 cmd.stdout(Stdio::inherit());169 cmd.stderr(Stdio::inherit());170Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 171–190why, one step back171 let mut paths = paths.map(|p| Self::prepare_path(&p));172 let mut has_path = false;173174 for arg in &self.args[1..] {175 if arg.has_tokens() {176 // A single `Tokens` is expected177 // So we can directy consume the iterator once and for all178 for path in &mut paths {179 cmd.arg(arg.generate(&path).as_ref());180 has_path = true;181 }182 } else {183 cmd.arg(arg.generate("").as_ref());184 }185 }186187 if has_path {188 execute_command(cmd, &Mutex::new(()));189 }190 }Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 191–192why, one step back191}192Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 193–203why, one step back193/// Represents a template for a single command argument.194///195/// The argument is either a collection of `Token`s including at least one placeholder variant, or196/// a fixed text.197#[derive(Clone, Debug, PartialEq)]198enum ArgumentTemplate {199 Tokens(Vec<Token>),200 Text(String),201}202203impl ArgumentTemplate {Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 204why, one step back204 pub fn has_tokens(&self) -> bool {exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07
lines 205–207why, one step back205 match self {206 ArgumentTemplate::Tokens(_) => true,207 _ => false,Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 208–210why, one step back208 }209 }210Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 211–233why, one step back211 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {212 use self::Token::*;213214 match *self {215 ArgumentTemplate::Tokens(ref tokens) => {216 let mut s = String::new();217 for token in tokens {218 match *token {219 Basename => s += basename(path),220 BasenameNoExt => s += remove_extension(basename(path)),221 NoExt => s += remove_extension(path),222 Parent => s += dirname(path),223 Placeholder => s += path,224 Text(ref string) => s += string,225 }226 }227 Cow::Owned(s)228 }229 ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),230 }231 }232}233Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 234–235why, one step back234#[cfg(test)]235mod tests {Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
line 236why, one step back236 use super::*;Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 237–238why, one step back237238 #[test]Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 239–247why, one step back239 fn tokens_with_placeholder() {240 assert_eq!(241 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),242 CommandTemplate {243 args: vec![244 ArgumentTemplate::Text("echo".into()),245 ArgumentTemplate::Text("${SHELL}:".into()),246 ArgumentTemplate::Tokens(vec![Token::Placeholder]),247 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 248why, one step back248 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 249–251why, one step back249 }250 );251 }Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 252why, one step back252Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 253–254why, one step back253 #[test]254 fn tokens_with_no_extension() {Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 255why, one step back255 assert_eq!(Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 256–257why, one step back256 CommandTemplate::new(&["echo", "{.}"]),257 CommandTemplate {Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 258why, one step back258 args: vec![Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7
lines 259–260why, one step back259 ArgumentTemplate::Text("echo".into()),260 ArgumentTemplate::Tokens(vec![Token::NoExt]),Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
line 261why, one step back261 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 262why, one step back262 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 263–275why, one step back263 }264 );265 }266267 #[test]268 fn tokens_with_basename() {269 assert_eq!(270 CommandTemplate::new(&["echo", "{/}"]),271 CommandTemplate {272 args: vec![273 ArgumentTemplate::Text("echo".into()),274 ArgumentTemplate::Tokens(vec![Token::Basename]),275 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 276why, one step back276 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 277–289why, one step back277 }278 );279 }280281 #[test]282 fn tokens_with_parent() {283 assert_eq!(284 CommandTemplate::new(&["echo", "{//}"]),285 CommandTemplate {286 args: vec![287 ArgumentTemplate::Text("echo".into()),288 ArgumentTemplate::Tokens(vec![Token::Parent]),289 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 290why, one step back290 mode: ExecutionMode::OneByOne,Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b
lines 291–302why, one step back291 }292 );293 }294295 #[test]296 fn tokens_with_basename_no_extension() {297 assert_eq!(298 CommandTemplate::new(&["echo", "{/.}"]),299 CommandTemplate {300 args: vec![301 ArgumentTemplate::Text("echo".into()),302 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 303why, one step back303 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 304why, one step back304 mode: ExecutionMode::OneByOne,Remove shell with --execMatthias Reitingerbefore adoption18709b1
line 305why, one step back305 }Fix some clippy warningssharkdpbefore adoptionbba5c4f
lines 306–307why, one step back306 );307 }Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
lines 308–321why, one step back308309 #[test]310 fn tokens_multiple() {311 assert_eq!(312 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),313 CommandTemplate {314 args: vec![315 ArgumentTemplate::Text("cp".into()),316 ArgumentTemplate::Tokens(vec![Token::Placeholder]),317 ArgumentTemplate::Tokens(vec![318 Token::BasenameNoExt,319 Token::Text(".ext".into())320 ]),321 ],Add support for batch execution of commandkimsnjbefore adoption45d1b15
line 322why, one step back322 mode: ExecutionMode::OneByOne,Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
lines 323–324why, one step back323 }324 );Add support for batch execution of commandkimsnjbefore adoption45d1b15
lines 325–343why, one step back325 }326327 #[test]328 fn tokens_single_batch() {329 assert_eq!(330 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),331 CommandTemplate {332 args: vec![333 ArgumentTemplate::Text("echo".into()),334 ArgumentTemplate::Tokens(vec![Token::NoExt]),335 ],336 mode: ExecutionMode::Batch,337 }338 );339 }340341 #[test]342 fn tokens_multiple_batch() {343 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af
line 344why, one step back344 }Fix some clippy warningssharkdpbefore adoptionbba5c4f
line 345why, one step back345}