Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

457 lines · 15.7 KiB · Rust

Last changed by

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

History of this file

Take it

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 1–5why, one step back
1mod command;
2mod input;3mod job;4mod token;5

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 6–8why, one step back
6use std::borrow::Cow;
7use std::ffi::{OsStr, OsString};8use std::path::{Component, Path, PathBuf, Prefix};

Clean up build.rssharkdpbefore adoptiona85f33c

lines 9–16why, one step back
9use std::process::{Command, Stdio};
10use std::sync::{Arc, Mutex};1112use anyhow::{anyhow, Result};13use lazy_static::lazy_static;14use regex::Regex;1516use crate::exit_codes::ExitCode;

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 18–40why, one step back
18
19use self::command::execute_command;20use self::input::{basename, dirname, remove_extension};21pub use self::job::{batch, job};22use self::token::Token;2324/// Execution mode of the command25#[derive(Debug, Clone, Copy, PartialEq)]26pub enum ExecutionMode {27 /// Command is executed for each search result28 OneByOne,29 /// Command is run for a batch of results at once30 Batch,31}3233/// Represents a template that is utilized to generate command strings.34///35/// The template is meant to be coupled with an input in order to generate a command. The36/// `generate_and_execute()` method will be used to generate a command and execute it.37#[derive(Debug, Clone, PartialEq)]38pub struct CommandTemplate {39 args: Vec<ArgumentTemplate>,40 mode: ExecutionMode,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 41why, one step back
41 path_separator: Option<String>,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 42–44why, one step back
42}
4344impl CommandTemplate {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 45why, one step back
45 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate

Clean up build.rssharkdpbefore adoptiona85f33c

lines 46–49why, one step back
46 where
47 I: IntoIterator<Item = S>,48 S: AsRef<str>,49 {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 50why, one step back
50 Self::build(input, ExecutionMode::OneByOne, path_separator)

Clean up build.rssharkdpbefore adoptiona85f33c

lines 51–52why, one step back
51 }
52

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 54–57why, one step back
54 where
55 I: IntoIterator<Item = S>,56 S: AsRef<str>,57 {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 58why, one step back
58 let cmd = Self::build(input, ExecutionMode::Batch, path_separator);

Clean up build.rssharkdpbefore adoptiona85f33c

lines 59–69why, one step back
59 if cmd.number_of_tokens() > 1 {
60 return Err(anyhow!("Only one placeholder allowed for batch commands"));61 }62 if cmd.args[0].has_tokens() {63 return Err(anyhow!(64 "First argument of exec-batch is expected to be a fixed executable"65 ));66 }67 Ok(cmd)68 }69

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 70why, one step back
70 fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate

Clean up build.rssharkdpbefore adoptiona85f33c

lines 71–101why, one step back
71 where
72 I: IntoIterator<Item = S>,73 S: AsRef<str>,74 {75 lazy_static! {76 static ref PLACEHOLDER_PATTERN: Regex = Regex::new(r"\{(/?\.?|//)\}").unwrap();77 }7879 let mut args = Vec::new();80 let mut has_placeholder = false;8182 for arg in input {83 let arg = arg.as_ref();8485 let mut tokens = Vec::new();86 let mut start = 0;8788 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {89 // Leading text before the placeholder.90 if placeholder.start() > start {91 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));92 }9394 start = placeholder.end();9596 match placeholder.as_str() {97 "{}" => tokens.push(Token::Placeholder),98 "{.}" => tokens.push(Token::NoExt),99 "{/}" => tokens.push(Token::Basename),100 "{//}" => tokens.push(Token::Parent),101 "{/.}" => tokens.push(Token::BasenameNoExt),

panic => unreachablesharkdpbefore adoption439548c

line 102why, one step back
102 _ => unreachable!("Unhandled placeholder"),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 103–126why, one step back
103 }
104105 has_placeholder = true;106 }107108 // Without a placeholder, the argument is just fixed text.109 if tokens.is_empty() {110 args.push(ArgumentTemplate::Text(arg.to_owned()));111 continue;112 }113114 if start < arg.len() {115 // Trailing text after last placeholder.116 tokens.push(Token::Text(arg[start..].to_owned()));117 }118119 args.push(ArgumentTemplate::Tokens(tokens));120 }121122 // If a placeholder token was not supplied, append one at the end of the command.123 if !has_placeholder {124 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));125 }126

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 127–131why, one step back
127 CommandTemplate {
128 args,129 mode,130 path_separator,131 }

Clean up build.rssharkdpbefore adoptiona85f33c

lines 132–141why, one step back
132 }
133134 fn number_of_tokens(&self) -> usize {135 self.args.iter().filter(|arg| arg.has_tokens()).count()136 }137138 /// Generates and executes a command.139 ///140 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be141 /// build. Once all arguments have been processed, the command is executed.

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

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

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

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

Clean up build.rssharkdpbefore adoptiona85f33c

line 144why, one step back
144

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 145why, one step back
145 let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));

Clean up build.rssharkdpbefore adoptiona85f33c

line 146why, one step back
146 for arg in &self.args[1..] {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 147why, one step back
147 cmd.arg(arg.generate(&input, self.path_separator.as_deref()));

Clean up build.rssharkdpbefore adoptiona85f33c

lines 148–149why, one step back
148 }
149

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 151–156why, one step back
151 }
152153 pub fn in_batch_mode(&self) -> bool {154 self.mode == ExecutionMode::Batch155 }156

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 158–160why, one step back
158 where
159 I: Iterator<Item = PathBuf>,160 {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 161why, one step back
161 let mut cmd = Command::new(self.args[0].generate("", None));

Clean up build.rssharkdpbefore adoptiona85f33c

lines 162–165why, one step back
162 cmd.stdin(Stdio::inherit());
163 cmd.stdout(Stdio::inherit());164 cmd.stderr(Stdio::inherit());165

Remove duplicate 'strip prefix' functionsharkdpbefore adoptioned45d1c

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

Clean up build.rssharkdpbefore adoptiona85f33c

lines 167–175why, one step back
167 let mut has_path = false;
168169 for arg in &self.args[1..] {170 if arg.has_tokens() {171 paths.sort();172173 // A single `Tokens` is expected174 // So we can directly consume the iterator once and for all175 for path in &mut paths {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 176why, one step back
176 cmd.arg(arg.generate(strip_current_dir(path), self.path_separator.as_deref()));

Clean up build.rssharkdpbefore adoptiona85f33c

lines 177–179why, one step back
177 has_path = true;
178 }179 } else {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 180why, one step back
180 cmd.arg(arg.generate("", None));

Clean up build.rssharkdpbefore adoptiona85f33c

lines 181–184why, one step back
181 }
182 }183184 if has_path {

No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967

line 185why, one step back
185 execute_command(cmd, &Mutex::new(()), is_multithread)

Clean up build.rssharkdpbefore adoptiona85f33c

lines 186–203why, one step back
186 } else {
187 ExitCode::Success188 }189 }190}191192/// Represents a template for a single command argument.193///194/// The argument is either a collection of `Token`s including at least one placeholder variant, or195/// a fixed text.196#[derive(Clone, Debug, PartialEq)]197enum ArgumentTemplate {198 Tokens(Vec<Token>),199 Text(String),200}201202impl ArgumentTemplate {203 pub fn has_tokens(&self) -> bool {

Fix clippy warningsDavid Peterbefore adoption2a2126c

line 204why, one step back
204 matches!(self, ArgumentTemplate::Tokens(_))

Clean up build.rssharkdpbefore adoptiona85f33c

lines 205–206why, one step back
205 }
206

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 207–210why, one step back
207 /// Generate an argument from this template. If path_separator is Some, then it will replace
208 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by209 /// path separator substitution.210 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {

Clean up build.rssharkdpbefore adoptiona85f33c

line 211why, one step back
211 use self::Token::*;

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 212why, one step back
212 let path = path.as_ref();

Clean up build.rssharkdpbefore adoptiona85f33c

lines 213–215why, one step back
213
214 match *self {215 ArgumentTemplate::Tokens(ref tokens) => {

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 216why, one step back
216 let mut s = OsString::new();

Clean up build.rssharkdpbefore adoptiona85f33c

lines 217–218why, one step back
217 for token in tokens {
218 match *token {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 219–230why, one step back
219 Basename => s.push(Self::replace_separator(basename(path), path_separator)),
220 BasenameNoExt => s.push(Self::replace_separator(221 &remove_extension(basename(path).as_ref()),222 path_separator,223 )),224 NoExt => s.push(Self::replace_separator(225 &remove_extension(path),226 path_separator,227 )),228 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),229 Placeholder => {230 s.push(Self::replace_separator(path.as_ref(), path_separator))

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

lines 231–232why, one step back
231 }
232 Text(ref string) => s.push(string),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 233–234why, one step back
233 }
234 }

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 235why, one step back
235 s

Clean up build.rssharkdpbefore adoptiona85f33c

line 236why, one step back
236 }

Reimplement dirname, basename, remove_extension for OsStrsharkdpbefore adoption7e3c69c

line 237why, one step back
237 ArgumentTemplate::Text(ref text) => OsString::from(text),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 238–239why, one step back
238 }
239 }

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 240–294why, one step back
240
241 /// Replace the path separator in the input with the custom separator string. If path_separator242 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is243 /// interpreted as a Path and its components are iterated through and re-joined into a new244 /// OsString.245 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {246 // fast-path - no replacement necessary247 if path_separator.is_none() {248 return Cow::Borrowed(path);249 }250251 let path_separator = path_separator.unwrap();252 let mut out = OsString::with_capacity(path.len());253 let mut components = Path::new(path).components().peekable();254255 while let Some(comp) = components.next() {256 match comp {257 // Absolute paths on Windows are tricky. A Prefix component is usually a drive258 // letter or UNC path, and is usually followed by RootDir. There are also259 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to260 // ignore verbatim path prefixes here because they're very rare, might be261 // impossible to reach here, and there's no good way to deal with them. If users262 // are doing something advanced involving verbatim windows paths, they can do their263 // own output filtering with a tool like sed.264 Component::Prefix(prefix) => {265 if let Prefix::UNC(server, share) = prefix.kind() {266 // Prefix::UNC is a parsed version of '\\server\share'267 out.push(path_separator);268 out.push(path_separator);269 out.push(server);270 out.push(path_separator);271 out.push(share);272 } else {273 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for274 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,275 // but they're not returned by directories fd can search anyway so we don't worry276 // about them.277 out.push(comp.as_os_str());278 }279 }280281 // Root directory is always replaced with the custom separator.282 Component::RootDir => out.push(path_separator),283284 // Everything else is joined normally, with a trailing separator if we're not last285 _ => {286 out.push(comp.as_os_str());287 if components.peek().is_some() {288 out.push(path_separator);289 }290 }291 }292 }293 Cow::Owned(out)294 }

Clean up build.rssharkdpbefore adoptiona85f33c

lines 295–303why, one step back
295}
296297#[cfg(test)]298mod tests {299 use super::*;300301 #[test]302 fn tokens_with_placeholder() {303 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 304why, one step back
304 CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 305–311why, one step back
305 CommandTemplate {
306 args: vec![307 ArgumentTemplate::Text("echo".into()),308 ArgumentTemplate::Text("${SHELL}:".into()),309 ArgumentTemplate::Tokens(vec![Token::Placeholder]),310 ],311 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 312why, one step back
312 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 313–319why, one step back
313 }
314 );315 }316317 #[test]318 fn tokens_with_no_extension() {319 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 320why, one step back
320 CommandTemplate::new(&["echo", "{.}"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 321–326why, one step back
321 CommandTemplate {
322 args: vec![323 ArgumentTemplate::Text("echo".into()),324 ArgumentTemplate::Tokens(vec![Token::NoExt]),325 ],326 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 327why, one step back
327 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 328–334why, one step back
328 }
329 );330 }331332 #[test]333 fn tokens_with_basename() {334 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 335why, one step back
335 CommandTemplate::new(&["echo", "{/}"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 336–341why, one step back
336 CommandTemplate {
337 args: vec![338 ArgumentTemplate::Text("echo".into()),339 ArgumentTemplate::Tokens(vec![Token::Basename]),340 ],341 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 342why, one step back
342 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 343–349why, one step back
343 }
344 );345 }346347 #[test]348 fn tokens_with_parent() {349 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 350why, one step back
350 CommandTemplate::new(&["echo", "{//}"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 351–356why, one step back
351 CommandTemplate {
352 args: vec![353 ArgumentTemplate::Text("echo".into()),354 ArgumentTemplate::Tokens(vec![Token::Parent]),355 ],356 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 357why, one step back
357 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 358–364why, one step back
358 }
359 );360 }361362 #[test]363 fn tokens_with_basename_no_extension() {364 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 365why, one step back
365 CommandTemplate::new(&["echo", "{/.}"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 366–371why, one step back
366 CommandTemplate {
367 args: vec![368 ArgumentTemplate::Text("echo".into()),369 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),370 ],371 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 372why, one step back
372 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 373–379why, one step back
373 }
374 );375 }376377 #[test]378 fn tokens_multiple() {379 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 380why, one step back
380 CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 381–390why, one step back
381 CommandTemplate {
382 args: vec![383 ArgumentTemplate::Text("cp".into()),384 ArgumentTemplate::Tokens(vec![Token::Placeholder]),385 ArgumentTemplate::Tokens(vec![386 Token::BasenameNoExt,387 Token::Text(".ext".into())388 ]),389 ],390 mode: ExecutionMode::OneByOne,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 391why, one step back
391 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 392–398why, one step back
392 }
393 );394 }395396 #[test]397 fn tokens_single_batch() {398 assert_eq!(

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 399why, one step back
399 CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),

Clean up build.rssharkdpbefore adoptiona85f33c

lines 400–405why, one step back
400 CommandTemplate {
401 args: vec![402 ArgumentTemplate::Text("echo".into()),403 ArgumentTemplate::Tokens(vec![Token::NoExt]),404 ],405 mode: ExecutionMode::Batch,

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

line 406why, one step back
406 path_separator: None,

Clean up build.rssharkdpbefore adoptiona85f33c

lines 407–412why, one step back
407 }
408 );409 }410411 #[test]412 fn tokens_multiple_batch() {

use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5

lines 413–455why, one step back
413 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());
414 }415416 #[test]417 fn generate_custom_path_separator() {418 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);419 macro_rules! check {420 ($input:expr, $expected:expr) => {421 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));422 };423 }424425 check!("foo", "foo");426 check!("foo/bar", "foo#bar");427 check!("/foo/bar/baz", "#foo#bar#baz");428 }429430 #[cfg(windows)]431 #[test]432 fn generate_custom_path_separator_windows() {433 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);434 macro_rules! check {435 ($input:expr, $expected:expr) => {436 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));437 };438 }439440 // path starting with a drive letter441 check!(r"C:\foo\bar", "C:#foo#bar");442 // UNC path443 check!(r"\\server\share\path", "##server#share#path");444 // Drive Relative path - no separator after the colon omits the RootDir path component.445 // This is uncommon, but valid446 check!(r"C:foo\bar", "C:foo#bar");447448 // forward slashses should get normalized and interpreted as separators449 check!("C:/foo/bar", "C:#foo#bar");450 check!("C:foo/bar", "C:foo#bar");451452 // Rust does not intrepret "//server/share" as a UNC path, but rather as a normal453 // absolute path that begins with RootDir, and the two slashes get combined together as454 // a single path separator during normalization.455 //check!("//server/share/path", "##server#share#path");

Clean up build.rssharkdpbefore adoptiona85f33c

lines 456–457why, one step back
456 }
457}