Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

343 lines · 10.1 KiB · Rust

Last changed by

Remove outdated license headers (not strictly required by Apache-2.0)sharkdpbefore adoption4274075

History of this file

Take it

The walk stopped after 200 commits: lines older than 8fb25f1 point at it.

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 1–7why, one step back
1// TODO: Possible optimization could avoid pushing characters on a buffer.
2mod command;3mod input;4mod job;5mod token;67use std::borrow::Cow;

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

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

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

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 13–14why, one step back
13use regex::Regex;
14

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

lines 15–16why, one step back
15use crate::exit_codes::ExitCode;
16

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 17–18why, one step back
17use self::command::execute_command;
18use self::input::{basename, dirname, remove_extension};

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 20–21why, one step back
20use self::token::Token;
21

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 22–24why, one step back
22/// Execution mode of the command
23#[derive(Debug, Clone, Copy, PartialEq)]24pub enum ExecutionMode {

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

line 25why, one step back
25 /// Command is executed for each search result

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 26–30why, one step back
26 OneByOne,
27 /// Command is run for a batch of results at once28 Batch,29}30

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 31–37why, one step back
31/// Represents a template that is utilized to generate command strings.
32///33/// The template is meant to be coupled with an input in order to generate a command. The34/// `generate_and_execute()` method will be used to generate a command and execute it.35#[derive(Debug, Clone, PartialEq)]36pub struct CommandTemplate {37 args: Vec<ArgumentTemplate>,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 38why, one step back
38 mode: ExecutionMode,

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 39–46why, one step back
39}
4041impl CommandTemplate {42 pub fn new<I, S>(input: I) -> CommandTemplate43 where44 I: IntoIterator<Item = S>,45 S: AsRef<str>,46 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 47–55why, one step back
47 Self::build(input, ExecutionMode::OneByOne)
48 }4950 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate, &'static str>51 where52 I: IntoIterator<Item = S>,53 S: AsRef<str>,54 {55 let cmd = Self::build(input, ExecutionMode::Batch);

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

line 56why, one step back
56 if cmd.number_of_tokens() > 1 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 57–58why, one step back
57 return Err("Only one placeholder allowed for batch commands");
58 }

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

lines 59–61why, one step back
59 if cmd.args[0].has_tokens() {
60 return Err("First argument of exec-batch is expected to be a fixed executable");61 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 62–69why, one step back
62 Ok(cmd)
63 }6465 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate66 where67 I: IntoIterator<Item = S>,68 S: AsRef<str>,69 {

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 70–121why, one step back
70 lazy_static! {
71 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();72 }7374 let mut args = Vec::new();75 let mut has_placeholder = false;7677 for arg in input {78 let arg = arg.as_ref();7980 let mut tokens = Vec::new();81 let mut start = 0;8283 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {84 // Leading text before the placeholder.85 if placeholder.start() > start {86 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));87 }8889 start = placeholder.end();9091 match placeholder.as_str() {92 "{}" => tokens.push(Token::Placeholder),93 "{.}" => tokens.push(Token::NoExt),94 "{/}" => tokens.push(Token::Basename),95 "{//}" => tokens.push(Token::Parent),96 "{/.}" => tokens.push(Token::BasenameNoExt),97 _ => panic!("Unhandled placeholder"),98 }99100 has_placeholder = true;101 }102103 // Without a placeholder, the argument is just fixed text.104 if tokens.is_empty() {105 args.push(ArgumentTemplate::Text(arg.to_owned()));106 continue;107 }108109 if start < arg.len() {110 // Trailing text after last placeholder.111 tokens.push(Token::Text(arg[start..].to_owned()));112 }113114 args.push(ArgumentTemplate::Tokens(tokens));115 }116117 // If a placeholder token was not supplied, append one at the end of the command.118 if !has_placeholder {119 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));120 }121

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 123–124why, one step back
123 }
124

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 126–136why, one step back
126 self.args.iter().filter(|arg| arg.has_tokens()).count()
127 }128129 fn prepare_path(input: &Path) -> String {130 input131 .strip_prefix(".")132 .unwrap_or(input)133 .to_string_lossy()134 .into_owned()135 }136

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 137–140why, one step back
137 /// Generates and executes a command.
138 ///139 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be140 /// build. Once all arguments have been processed, the command is executed.

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

line 141why, one step back
141 pub fn generate_and_execute(&self, input: &Path, out_perm: Arc<Mutex<()>>) -> ExitCode {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 142why, one step back
142 let input = Self::prepare_path(input);

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 143–148why, one step back
143
144 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());145 for arg in &self.args[1..] {146 cmd.arg(arg.generate(&input).as_ref());147 }148

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

line 150why, one step back
150 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 151why, one step back
151

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 153–155why, one step back
153 self.mode == ExecutionMode::Batch
154 }155

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 157–160why, one step back
157 where
158 I: Iterator<Item = PathBuf>,159 {160 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 161–164why, one step back
161 cmd.stdin(Stdio::inherit());
162 cmd.stdout(Stdio::inherit());163 cmd.stderr(Stdio::inherit());164

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

line 165why, one step back
165 let mut paths: Vec<String> = paths.map(|p| Self::prepare_path(&p)).collect();

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 166–169why, one step back
166 let mut has_path = false;
167168 for arg in &self.args[1..] {169 if arg.has_tokens() {

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

lines 170–171why, one step back
170 paths.sort();
171

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 174–183why, one step back
174 for path in &mut paths {
175 cmd.arg(arg.generate(&path).as_ref());176 has_path = true;177 }178 } else {179 cmd.arg(arg.generate("").as_ref());180 }181 }182183 if has_path {

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

lines 184–186why, one step back
184 execute_command(cmd, &Mutex::new(()))
185 } else {186 ExitCode::Success

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 187–188why, one step back
187 }
188 }

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 189–201why, one step back
189}
190191/// Represents a template for a single command argument.192///193/// The argument is either a collection of `Token`s including at least one placeholder variant, or194/// a fixed text.195#[derive(Clone, Debug, PartialEq)]196enum ArgumentTemplate {197 Tokens(Vec<Token>),198 Text(String),199}200201impl ArgumentTemplate {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 203–205why, one step back
203 match self {
204 ArgumentTemplate::Tokens(_) => true,205 _ => false,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 206–208why, one step back
206 }
207 }208

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 209–233why, one step back
209 pub fn generate<'a>(&'a self, path: &str) -> Cow<'a, str> {
210 use self::Token::*;211212 match *self {213 ArgumentTemplate::Tokens(ref tokens) => {214 let mut s = String::new();215 for token in tokens {216 match *token {217 Basename => s += basename(path),218 BasenameNoExt => s += remove_extension(basename(path)),219 NoExt => s += remove_extension(path),220 Parent => s += dirname(path),221 Placeholder => s += path,222 Text(ref string) => s += string,223 }224 }225 Cow::Owned(s)226 }227 ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),228 }229 }230}231232#[cfg(test)]233mod tests {

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

line 234why, one step back
234 use super::*;

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 235–236why, one step back
235
236 #[test]

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

lines 237–245why, one step back
237 fn tokens_with_placeholder() {
238 assert_eq!(239 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),240 CommandTemplate {241 args: vec![242 ArgumentTemplate::Text("echo".into()),243 ArgumentTemplate::Text("${SHELL}:".into()),244 ArgumentTemplate::Tokens(vec![Token::Placeholder]),245 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 247–249why, one step back
247 }
248 );249 }

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

line 250why, one step back
250

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

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 253–258why, one step back
253 assert_eq!(
254 CommandTemplate::new(&["echo", "{.}"]),255 CommandTemplate {256 args: vec![257 ArgumentTemplate::Text("echo".into()),258 ArgumentTemplate::Tokens(vec![Token::NoExt]),

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

line 259why, one step back
259 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 261–273why, one step back
261 }
262 );263 }264265 #[test]266 fn tokens_with_basename() {267 assert_eq!(268 CommandTemplate::new(&["echo", "{/}"]),269 CommandTemplate {270 args: vec![271 ArgumentTemplate::Text("echo".into()),272 ArgumentTemplate::Tokens(vec![Token::Basename]),273 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 275–287why, one step back
275 }
276 );277 }278279 #[test]280 fn tokens_with_parent() {281 assert_eq!(282 CommandTemplate::new(&["echo", "{//}"]),283 CommandTemplate {284 args: vec![285 ArgumentTemplate::Text("echo".into()),286 ArgumentTemplate::Tokens(vec![Token::Parent]),287 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 289–300why, one step back
289 }
290 );291 }292293 #[test]294 fn tokens_with_basename_no_extension() {295 assert_eq!(296 CommandTemplate::new(&["echo", "{/.}"]),297 CommandTemplate {298 args: vec![299 ArgumentTemplate::Text("echo".into()),300 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

line 301why, one step back
301 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

lines 303–305why, one step back
303 }
304 );305 }

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 306–319why, one step back
306
307 #[test]308 fn tokens_multiple() {309 assert_eq!(310 CommandTemplate::new(&["cp", "{}", "{/.}.ext"]),311 CommandTemplate {312 args: vec![313 ArgumentTemplate::Text("cp".into()),314 ArgumentTemplate::Tokens(vec![Token::Placeholder]),315 ArgumentTemplate::Tokens(vec![316 Token::BasenameNoExt,317 Token::Text(".ext".into())318 ]),319 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 321–322why, one step back
321 }
322 );

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 323–341why, one step back
323 }
324325 #[test]326 fn tokens_single_batch() {327 assert_eq!(328 CommandTemplate::new_batch(&["echo", "{.}"]).unwrap(),329 CommandTemplate {330 args: vec![331 ArgumentTemplate::Text("echo".into()),332 ArgumentTemplate::Tokens(vec![Token::NoExt]),333 ],334 mode: ExecutionMode::Batch,335 }336 );337 }338339 #[test]340 fn tokens_multiple_batch() {341 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"]).is_err());

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

line 342why, one step back
342 }

Just reference --max-depth in --maxdepth helpsharkdpbefore adoption8fb25f1

line 343why, one step back
343}