Skip to content
Myr

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 file

Take it

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 1–9why, 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.

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

line 10why, one step back
10mod command;

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 11why, one step back
11mod input;

Run latest version of rustfmtsharkdpbefore adoption6a9f16e

lines 12–13why, one step back
12mod job;
13mod token;

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 14why, one step back
14

Remove shell with --execMatthias Reitingerbefore adoption18709b1

line 15why, one step back
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};

Fix some clippy warningssharkdpbefore adoptionbba5c4f

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;

Remove shell with --execMatthias Reitingerbefore adoption18709b1

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

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

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

Run latest version of rustfmtsharkdpbefore adoption6a9f16e

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Run latest version of rustfmtsharkdpbefore adoption6a9f16e

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 27why, one step back
27

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 32–36why, one step back
32 OneByOne,
33 /// Command is run for a batch of results at once34 Batch,35}36

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

line 37why, one step back
37/// Represents a template that is utilized to generate command strings.

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 38why, one step back
38///

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 39–40why, one step back
39/// The template is meant to be coupled with an input in order to generate a command. The
40/// `generate_and_execute()` method will be used to generate a command and execute it.

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 41why, one step back
41#[derive(Debug, Clone, PartialEq)]

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 42–43why, one step back
42pub struct CommandTemplate {
43 args: Vec<ArgumentTemplate>,

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 45–46why, one step back
45}
46

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 47–48why, one step back
47impl CommandTemplate {
48 pub fn new<I, S>(input: I) -> CommandTemplate

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 49–52why, one step back
49 where
50 I: IntoIterator<Item = S>,51 S: AsRef<str>,52 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 53–61why, one step back
53 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 back
62 if cmd.number_of_tokens() > 1 {

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 63–64why, one step back
63 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 back
65 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 back
68 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 back
76 lazy_static! {

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

line 77why, one step back
77 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 78–88why, one step back
78 }
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;88

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

line 89why, one step back
89 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 90–92why, one step back
90 // 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 back
93 }

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 94–103why, one step back
94
95 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 back
104 }

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 105–106why, one step back
105
106 has_placeholder = true;

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 107–108why, one step back
107 }
108

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 109–110why, one step back
109 // Without a placeholder, the argument is just fixed text.
110 if tokens.is_empty() {

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

line 111why, one step back
111 args.push(ArgumentTemplate::Text(arg.to_owned()));

Remove shell with --execMatthias Reitingerbefore adoption18709b1

lines 112–119why, one step back
112 continue;
113 }114115 if start < arg.len() {116 // Trailing text after last placeholder.117 tokens.push(Token::Text(arg[start..].to_owned()));118 }119

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

line 120why, one step back
120 args.push(ArgumentTemplate::Tokens(tokens));

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 121–123why, one step back
121 }
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 back
124 if !has_placeholder {

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

line 125why, one step back
125 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));

Fix some clippy warningssharkdpbefore adoptionbba5c4f

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 129–130why, one step back
129 }
130

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

line 143why, one step back
143 /// Generates and executes a command.

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 144why, one step back
144 ///

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

lines 145–147why, one step back
145 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be
146 /// 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 back
148 let input = Self::prepare_path(input);

Remove shell with --execMatthias Reitingerbefore adoption18709b1

line 149why, one step back
149

Remove CommandTicket to avoid Vec allocationMatthias Reitingerbefore adoptionc18caaa

lines 150–152why, one step back
150 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 back
153 }
154

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 156why, one step back
156 }

Add support for batch execution of commandkimsnjbefore adoption45d1b15

line 157why, one step back
157

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

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 159–166why, one step back
159 self.mode == ExecutionMode::Batch
160 }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 back
167 cmd.stdin(Stdio::inherit());
168 cmd.stdout(Stdio::inherit());169 cmd.stderr(Stdio::inherit());170

Add support for batch execution of commandkimsnjbefore adoption45d1b15

lines 171–190why, one step back
171 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 back
191}
192

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 193–203why, one step back
193/// 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

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 211–233why, 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}233

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 234–235why, one step back
234#[cfg(test)]
235mod tests {

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

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

lines 237–238why, one step back
237
238 #[test]

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

lines 239–247why, one step back
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 exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 249–251why, one step back
249 }
250 );251 }

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 252why, one step back
252

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

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 255why, one step back
255 assert_eq!(

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

lines 256–257why, one step back
256 CommandTemplate::new(&["echo", "{.}"]),
257 CommandTemplate {

Remove shell with --execMatthias Reitingerbefore adoption18709b1

line 258why, one step back
258 args: vec![

Rename TokenizedCommand to CommandTemplateMatthias Reitingerbefore adoption0f82fe7

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

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

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

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 exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

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 exec tests and cfg(test) compiler guardsJosh Leeb-du Toitbefore adoptionadc467b

lines 291–302why, 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]),

Remove shell with --execMatthias Reitingerbefore adoption18709b1

line 303why, one step back
303 ],

Add support for batch execution of commandkimsnjbefore adoption45d1b15

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

Remove shell with --execMatthias Reitingerbefore adoption18709b1

line 305why, one step back
305 }

Fix some clippy warningssharkdpbefore adoptionbba5c4f

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

Fix some clippy warningssharkdpbefore adoptionbba5c4f

line 345why, one step back
345}