Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

345 lines · 10.1 KiB · Rust

Last changed by

Remove irrelevant TODOsharkdpbefore adoptionf9372b5

History of this file

Take it

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 1–6why, one step back
1mod command;
2mod input;3mod job;4mod token;56use std::borrow::Cow;

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 11why, one step back
11use anyhow::{anyhow, Result};

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

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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};

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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,

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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–49why, one step back
47 Self::build(input, ExecutionMode::OneByOne)
48 }49

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 50why, one step back
50 pub fn new_batch<I, S>(input: I) -> Result<CommandTemplate>

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 51–55why, one step back
51 where
52 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 {

Proper error handling in main.rssharkdpbefore adoptionbce9527

line 57why, one step back
57 return Err(anyhow!("Only one placeholder allowed for batch commands"));

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 58why, one step back
58 }

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

line 59why, one step back
59 if cmd.args[0].has_tokens() {

Proper error handling in main.rssharkdpbefore adoptionbce9527

lines 60–62why, one step back
60 return Err(anyhow!(
61 "First argument of exec-batch is expected to be a fixed executable"62 ));

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

line 63why, one step back
63 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 64–71why, one step back
64 Ok(cmd)
65 }6667 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate68 where69 I: IntoIterator<Item = S>,70 S: AsRef<str>,71 {

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 72–123why, one step back
72 lazy_static! {
73 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();74 }7576 let mut args = Vec::new();77 let mut has_placeholder = false;7879 for arg in input {80 let arg = arg.as_ref();8182 let mut tokens = Vec::new();83 let mut start = 0;8485 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {86 // Leading text before the placeholder.87 if placeholder.start() > start {88 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));89 }9091 start = placeholder.end();9293 match placeholder.as_str() {94 "{}" => tokens.push(Token::Placeholder),95 "{.}" => tokens.push(Token::NoExt),96 "{/}" => tokens.push(Token::Basename),97 "{//}" => tokens.push(Token::Parent),98 "{/.}" => tokens.push(Token::BasenameNoExt),99 _ => panic!("Unhandled placeholder"),100 }101102 has_placeholder = true;103 }104105 // Without a placeholder, the argument is just fixed text.106 if tokens.is_empty() {107 args.push(ArgumentTemplate::Text(arg.to_owned()));108 continue;109 }110111 if start < arg.len() {112 // Trailing text after last placeholder.113 tokens.push(Token::Text(arg[start..].to_owned()));114 }115116 args.push(ArgumentTemplate::Tokens(tokens));117 }118119 // If a placeholder token was not supplied, append one at the end of the command.120 if !has_placeholder {121 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));122 }123

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 125–126why, one step back
125 }
126

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 128–138why, one step back
128 self.args.iter().filter(|arg| arg.has_tokens()).count()
129 }130131 fn prepare_path(input: &Path) -> String {132 input133 .strip_prefix(".")134 .unwrap_or(input)135 .to_string_lossy()136 .into_owned()137 }138

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

line 152why, one step back
152 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 153why, one step back
153

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

lines 172–173why, one step back
172 paths.sort();
173

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 189–190why, one step back
189 }
190 }

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 191–203why, one step back
191}
192193/// 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 back
204 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 back
205 match self {
206 ArgumentTemplate::Tokens(_) => true,207 _ => false,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 208–210why, one step back
208 }
209 }210

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 211–247why, one step back
211 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}233234#[cfg(test)]235mod tests {236 use super::*;237238 #[test]239 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 back
248 mode: ExecutionMode::OneByOne,

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 249–261why, one step back
249 }
250 );251 }252253 #[test]254 fn tokens_with_no_extension() {255 assert_eq!(256 CommandTemplate::new(&["echo", "{.}"]),257 CommandTemplate {258 args: vec![259 ArgumentTemplate::Text("echo".into()),260 ArgumentTemplate::Tokens(vec![Token::NoExt]),261 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 263–275why, one step back
263 }
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 back
276 mode: ExecutionMode::OneByOne,

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 277–289why, one step back
277 }
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 back
290 mode: ExecutionMode::OneByOne,

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 291–303why, one step back
291 }
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]),303 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 305–307why, one step back
305 }
306 );307 }

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 308–321why, one step back
308
309 #[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 back
322 mode: ExecutionMode::OneByOne,

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 323–324why, one step back
323 }
324 );

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 325–343why, one step back
325 }
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 back
344 }

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

line 345why, one step back
345}