Skip to content
Myr

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 file

Take 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 back
1// Copyright (c) 2017 fd developers
2// 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 back
12mod job;
13mod token;

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 14–15why, one step back
14
15use std::borrow::Cow;

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 16why, one step back
16use std::path::{Path, PathBuf};

exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07

line 17why, one step back
17use std::process::{Command, Stdio};

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 18–19why, one step back
18use std::sync::{Arc, Mutex};
19

[2018 edition] remove all extern crate lines from sourcesAlexandru Macoveibefore adoption051ff59

line 20why, one step back
20use lazy_static::lazy_static;

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 21–22why, one step back
21use regex::Regex;
22

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

lines 23–24why, one step back
23use crate::exit_codes::ExitCode;
24

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

line 25why, one step back
25use self::command::execute_command;

Run latest version of rustfmtsharkdpbefore adoption6a9f16e

line 26why, one step back
26use self::input::{basename, dirname, remove_extension};

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 27why, one step back
27pub use self::job::{batch, job};

Run latest version of rustfmtsharkdpbefore adoption6a9f16e

line 28why, one step back
28use self::token::Token;

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

line 29why, one step back
29

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 30–32why, one step back
30/// Execution mode of the command
31#[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 back
33 /// Command is executed for each search result

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 34–38why, one step back
34 OneByOne,
35 /// Command is run for a batch of results at once36 Batch,37}38

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 39–45why, one step back
39/// 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 back
46 mode: ExecutionMode,

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 47–54why, one step back
47}
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 back
55 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 back
64 if cmd.number_of_tokens() > 1 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 65–66why, one step back
65 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 back
67 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 back
70 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 back
78 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 }129

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 130why, one step back
130 CommandTemplate { args, mode }

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 131–132why, one step back
131 }
132

exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07

line 133why, one step back
133 fn number_of_tokens(&self) -> usize {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 134–144why, one step back
134 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 }144

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 145–149why, one step back
145 /// 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 back
150 let input = Self::prepare_path(input);

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 151–156why, one step back
151
152 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 }156

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

line 157why, one step back
157 execute_command(cmd, &out_perm);

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

line 158why, one step back
158 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 159why, one step back
159

exec-batch: fix a panic with -X "echo {}" and pass stdio to child cmdkimsnjbefore adoption6b40a07

line 160why, one step back
160 pub fn in_batch_mode(&self) -> bool {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 161–163why, one step back
161 self.mode == ExecutionMode::Batch
162 }163

Expose exit status from `--exec-batch <cmd>`sharkdpbefore adoptiona0505bd

line 164why, one step back
164 pub fn generate_and_execute_batch<I>(&self, paths: I) -> ExitCode

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 165–168why, one step back
165 where
166 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 back
169 cmd.stdin(Stdio::inherit());
170 cmd.stdout(Stdio::inherit());171 cmd.stderr(Stdio::inherit());172

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

line 173why, one step back
173 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 back
174 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 back
178 paths.sort();
179

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 180why, one step back
180 // A single `Tokens` is expected

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

line 181why, one step back
181 // So we can directly consume the iterator once and for all

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 182–191why, one step back
182 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 back
192 execute_command(cmd, &Mutex::new(()))
193 } else {194 ExitCode::Success

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 195–196why, one step back
195 }
196 }

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 197–209why, one step back
197}
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 back
210 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 back
211 match self {
212 ArgumentTemplate::Tokens(_) => true,213 _ => false,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 214–216why, one step back
214 }
215 }216

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 217–241why, one step back
217 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 back
242 use super::*;

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 243–244why, one step back
243
244 #[test]

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 245–253why, one step back
245 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 back
254 mode: ExecutionMode::OneByOne,

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 255–257why, one step back
255 }
256 );257 }

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

line 258why, one step back
258

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 259–260why, one step back
259 #[test]
260 fn tokens_with_no_extension() {

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 261–266why, one step back
261 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 back
267 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 268why, one step back
268 mode: ExecutionMode::OneByOne,

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 269–281why, one step back
269 }
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 back
282 mode: ExecutionMode::OneByOne,

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 283–295why, one step back
283 }
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 back
296 mode: ExecutionMode::OneByOne,

Add exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 297–308why, one step back
297 }
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 back
309 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 310why, one step back
310 mode: ExecutionMode::OneByOne,

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

lines 311–313why, one step back
311 }
312 );313 }

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 314–327why, one step back
314
315 #[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 back
328 mode: ExecutionMode::OneByOne,

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 329–330why, one step back
329 }
330 );

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 331–349why, one step back
331 }
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 back
350 }

Run updated version of rustfmtsharkdpbefore adoption88fb9d7

line 351why, one step back
351}