Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

340 lines · 10.0 KiB · Rust

Last changed by

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

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

line 15why, one step back
15use crate::exit_codes::ExitCode;

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 16why, one step back
16use crate::filesystem::strip_current_dir;

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

line 17why, one step back
17

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 27–31why, one step back
27 OneByOne,
28 /// Command is run for a batch of results at once29 Batch,30}31

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 40–47why, one step back
40}
4142impl CommandTemplate {43 pub fn new<I, S>(input: I) -> CommandTemplate44 where45 I: IntoIterator<Item = S>,46 S: AsRef<str>,47 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 48–50why, one step back
48 Self::build(input, ExecutionMode::OneByOne)
49 }50

Proper error handling in main.rssharkdpbefore adoptionbce9527

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 52–56why, one step back
52 where
53 I: IntoIterator<Item = S>,54 S: AsRef<str>,55 {56 let cmd = Self::build(input, ExecutionMode::Batch);

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

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

Proper error handling in main.rssharkdpbefore adoptionbce9527

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 59why, one step back
59 }

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

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

Proper error handling in main.rssharkdpbefore adoptionbce9527

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

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

line 64why, one step back
64 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 65–72why, one step back
65 Ok(cmd)
66 }6768 fn build<I, S>(input: I, mode: ExecutionMode) -> CommandTemplate69 where70 I: IntoIterator<Item = S>,71 S: AsRef<str>,72 {

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 73–124why, one step back
73 lazy_static! {
74 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();75 }7677 let mut args = Vec::new();78 let mut has_placeholder = false;7980 for arg in input {81 let arg = arg.as_ref();8283 let mut tokens = Vec::new();84 let mut start = 0;8586 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {87 // Leading text before the placeholder.88 if placeholder.start() > start {89 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));90 }9192 start = placeholder.end();9394 match placeholder.as_str() {95 "{}" => tokens.push(Token::Placeholder),96 "{.}" => tokens.push(Token::NoExt),97 "{/}" => tokens.push(Token::Basename),98 "{//}" => tokens.push(Token::Parent),99 "{/.}" => tokens.push(Token::BasenameNoExt),100 _ => panic!("Unhandled placeholder"),101 }102103 has_placeholder = true;104 }105106 // Without a placeholder, the argument is just fixed text.107 if tokens.is_empty() {108 args.push(ArgumentTemplate::Text(arg.to_owned()));109 continue;110 }111112 if start < arg.len() {113 // Trailing text after last placeholder.114 tokens.push(Token::Text(arg[start..].to_owned()));115 }116117 args.push(ArgumentTemplate::Tokens(tokens));118 }119120 // If a placeholder token was not supplied, append one at the end of the command.121 if !has_placeholder {122 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));123 }124

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

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

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 129–131why, one step back
129 self.args.iter().filter(|arg| arg.has_tokens()).count()
130 }131

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 132–135why, one step back
132 /// Generates and executes a command.
133 ///134 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be135 /// build. Once all arguments have been processed, the command is executed.

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

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

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 137why, one step back
137 let input = strip_current_dir(input);

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 138–143why, one step back
138
139 let mut cmd = Command::new(self.args[0].generate(&input).as_ref());140 for arg in &self.args[1..] {141 cmd.arg(arg.generate(&input).as_ref());142 }143

Restun exit code for generate_and_execute?fusillicodebefore adoptionfa7d492

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

line 145why, one step back
145 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 146why, one step back
146

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 148–150why, one step back
148 self.mode == ExecutionMode::Batch
149 }150

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 152–155why, one step back
152 where
153 I: Iterator<Item = PathBuf>,154 {155 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 156–159why, one step back
156 cmd.stdin(Stdio::inherit());
157 cmd.stdout(Stdio::inherit());158 cmd.stderr(Stdio::inherit());159

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 160why, one step back
160 let mut paths: Vec<_> = paths.collect();

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

lines 165–166why, one step back
165 paths.sort();
166

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Sort search results when using -X optionMarcoIenibefore adoption320d7fc

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 169why, one step back
169 for path in &mut paths {

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 170why, one step back
170 cmd.arg(arg.generate(strip_current_dir(path)).as_ref());

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 171–178why, one step back
171 has_path = true;
172 }173 } else {174 cmd.arg(arg.generate("").as_ref());175 }176 }177178 if has_path {

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

lines 179–181why, one step back
179 execute_command(cmd, &Mutex::new(()))
180 } else {181 ExitCode::Success

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 182–183why, one step back
182 }
183 }

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 184–196why, one step back
184}
185186/// Represents a template for a single command argument.187///188/// The argument is either a collection of `Token`s including at least one placeholder variant, or189/// a fixed text.190#[derive(Clone, Debug, PartialEq)]191enum ArgumentTemplate {192 Tokens(Vec<Token>),193 Text(String),194}195196impl ArgumentTemplate {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

lines 198–200why, one step back
198 match self {
199 ArgumentTemplate::Tokens(_) => true,200 _ => false,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 201–203why, one step back
201 }
202 }203

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

line 204why, one step back
204 pub fn generate<'a>(&'a self, path: impl AsRef<Path>) -> Cow<'a, str> {

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 205–206why, one step back
205 use self::Token::*;
206

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

lines 207–208why, one step back
207 let path = path.as_ref().to_string_lossy(); // TODO
208

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 209–213why, one step back
209 match *self {
210 ArgumentTemplate::Tokens(ref tokens) => {211 let mut s = String::new();212 for token in tokens {213 match *token {

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

lines 214–218why, one step back
214 Basename => s += basename(&path),
215 BasenameNoExt => s += remove_extension(basename(&path)),216 NoExt => s += remove_extension(&path),217 Parent => s += dirname(&path),218 Placeholder => s += &path,

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 219–242why, one step back
219 Text(ref string) => s += string,
220 }221 }222 Cow::Owned(s)223 }224 ArgumentTemplate::Text(ref text) => Cow::Borrowed(text),225 }226 }227}228229#[cfg(test)]230mod tests {231 use super::*;232233 #[test]234 fn tokens_with_placeholder() {235 assert_eq!(236 CommandTemplate::new(&[&"echo", &"${SHELL}:"]),237 CommandTemplate {238 args: vec![239 ArgumentTemplate::Text("echo".into()),240 ArgumentTemplate::Text("${SHELL}:".into()),241 ArgumentTemplate::Tokens(vec![Token::Placeholder]),242 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 244–256why, one step back
244 }
245 );246 }247248 #[test]249 fn tokens_with_no_extension() {250 assert_eq!(251 CommandTemplate::new(&["echo", "{.}"]),252 CommandTemplate {253 args: vec![254 ArgumentTemplate::Text("echo".into()),255 ArgumentTemplate::Tokens(vec![Token::NoExt]),256 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 258–270why, one step back
258 }
259 );260 }261262 #[test]263 fn tokens_with_basename() {264 assert_eq!(265 CommandTemplate::new(&["echo", "{/}"]),266 CommandTemplate {267 args: vec![268 ArgumentTemplate::Text("echo".into()),269 ArgumentTemplate::Tokens(vec![Token::Basename]),270 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 272–284why, one step back
272 }
273 );274 }275276 #[test]277 fn tokens_with_parent() {278 assert_eq!(279 CommandTemplate::new(&["echo", "{//}"]),280 CommandTemplate {281 args: vec![282 ArgumentTemplate::Text("echo".into()),283 ArgumentTemplate::Tokens(vec![Token::Parent]),284 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 286–298why, one step back
286 }
287 );288 }289290 #[test]291 fn tokens_with_basename_no_extension() {292 assert_eq!(293 CommandTemplate::new(&["echo", "{/.}"]),294 CommandTemplate {295 args: vec![296 ArgumentTemplate::Text("echo".into()),297 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),298 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

lines 300–302why, one step back
300 }
301 );302 }

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

lines 318–319why, one step back
318 }
319 );

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add test with multiple tokens in an argumentkimsnjbefore adoption32ec7af

line 339why, one step back
339 }

Add `search-path` optionCasey Primozicbefore adoptioncdf737b

line 340why, one step back
340}