Skip to content
Myr

mod.rs

This file

Path

src/exec/mod.rs

462 lines · 15.7 KiB · Rust

Last changed by

fix spellinga1346054before adoption5b4869a

History of this file

Take it

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 9–40why, 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;17use crate::filesystem::strip_current_dir;1819use 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>,

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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)

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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>

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 71–126why, 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),102 _ => unreachable!("Unhandled placeholder"),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 }

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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.

Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060

lines 142–147why, one step back
142 pub fn generate_and_execute(
143 &self,144 input: &Path,145 out_perm: Arc<Mutex<()>>,146 buffer_output: bool,147 ) -> ExitCode {

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 148–149why, one step back
148 let input = strip_current_dir(input);
149

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 153–154why, one step back
153 }
154

Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 156–161why, one step back
156 }
157158 pub fn in_batch_mode(&self) -> bool {159 self.mode == ExecutionMode::Batch160 }161

Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 163–165why, one step back
163 where
164 I: Iterator<Item = PathBuf>,165 {

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 167–180why, one step back
167 cmd.stdin(Stdio::inherit());
168 cmd.stdout(Stdio::inherit());169 cmd.stderr(Stdio::inherit());170171 let mut paths: Vec<_> = paths.collect();172 let mut has_path = false;173174 for arg in &self.args[1..] {175 if arg.has_tokens() {176 paths.sort();177178 // A single `Tokens` is expected179 // So we can directly consume the iterator once and for all180 for path in &mut paths {

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 182–184why, one step back
182 has_path = true;
183 }184 } else {

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 186–189why, one step back
186 }
187 }188189 if has_path {

Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060

line 190why, one step back
190 execute_command(cmd, &Mutex::new(()), buffer_output)

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 191–208why, one step back
191 } else {
192 ExitCode::Success193 }194 }195}196197/// Represents a template for a single command argument.198///199/// The argument is either a collection of `Token`s including at least one placeholder variant, or200/// a fixed text.201#[derive(Clone, Debug, PartialEq)]202enum ArgumentTemplate {203 Tokens(Vec<Token>),204 Text(String),205}206207impl ArgumentTemplate {208 pub fn has_tokens(&self) -> bool {

Fix clippy warningsDavid Peterbefore adoption2a2126c

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 210–211why, one step back
210 }
211

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

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

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 218–223why, one step back
218
219 match *self {220 ArgumentTemplate::Tokens(ref tokens) => {221 let mut s = OsString::new();222 for token in tokens {223 match *token {

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

lines 224–235why, one step back
224 Basename => s.push(Self::replace_separator(basename(path), path_separator)),
225 BasenameNoExt => s.push(Self::replace_separator(226 &remove_extension(basename(path).as_ref()),227 path_separator,228 )),229 NoExt => s.push(Self::replace_separator(230 &remove_extension(path),231 path_separator,232 )),233 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),234 Placeholder => {235 s.push(Self::replace_separator(path.as_ref(), path_separator))

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 236–244why, one step back
236 }
237 Text(ref string) => s.push(string),238 }239 }240 s241 }242 ArgumentTemplate::Text(ref text) => OsString::from(text),243 }244 }

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

lines 245–299why, one step back
245
246 /// Replace the path separator in the input with the custom separator string. If path_separator247 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is248 /// interpreted as a Path and its components are iterated through and re-joined into a new249 /// OsString.250 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {251 // fast-path - no replacement necessary252 if path_separator.is_none() {253 return Cow::Borrowed(path);254 }255256 let path_separator = path_separator.unwrap();257 let mut out = OsString::with_capacity(path.len());258 let mut components = Path::new(path).components().peekable();259260 while let Some(comp) = components.next() {261 match comp {262 // Absolute paths on Windows are tricky. A Prefix component is usually a drive263 // letter or UNC path, and is usually followed by RootDir. There are also264 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to265 // ignore verbatim path prefixes here because they're very rare, might be266 // impossible to reach here, and there's no good way to deal with them. If users267 // are doing something advanced involving verbatim windows paths, they can do their268 // own output filtering with a tool like sed.269 Component::Prefix(prefix) => {270 if let Prefix::UNC(server, share) = prefix.kind() {271 // Prefix::UNC is a parsed version of '\\server\share'272 out.push(path_separator);273 out.push(path_separator);274 out.push(server);275 out.push(path_separator);276 out.push(share);277 } else {278 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for279 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,280 // but they're not returned by directories fd can search anyway so we don't worry281 // about them.282 out.push(comp.as_os_str());283 }284 }285286 // Root directory is always replaced with the custom separator.287 Component::RootDir => out.push(path_separator),288289 // Everything else is joined normally, with a trailing separator if we're not last290 _ => {291 out.push(comp.as_os_str());292 if components.peek().is_some() {293 out.push(path_separator);294 }295 }296 }297 }298 Cow::Owned(out)299 }

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 300–308why, one step back
300}
301302#[cfg(test)]303mod tests {304 use super::*;305306 #[test]307 fn tokens_with_placeholder() {308 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 310–316why, one step back
310 CommandTemplate {
311 args: vec![312 ArgumentTemplate::Text("echo".into()),313 ArgumentTemplate::Text("${SHELL}:".into()),314 ArgumentTemplate::Tokens(vec![Token::Placeholder]),315 ],316 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 318–324why, one step back
318 }
319 );320 }321322 #[test]323 fn tokens_with_no_extension() {324 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 326–331why, one step back
326 CommandTemplate {
327 args: vec![328 ArgumentTemplate::Text("echo".into()),329 ArgumentTemplate::Tokens(vec![Token::NoExt]),330 ],331 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 333–339why, one step back
333 }
334 );335 }336337 #[test]338 fn tokens_with_basename() {339 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 341–346why, one step back
341 CommandTemplate {
342 args: vec![343 ArgumentTemplate::Text("echo".into()),344 ArgumentTemplate::Tokens(vec![Token::Basename]),345 ],346 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 348–354why, one step back
348 }
349 );350 }351352 #[test]353 fn tokens_with_parent() {354 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 356–361why, one step back
356 CommandTemplate {
357 args: vec![358 ArgumentTemplate::Text("echo".into()),359 ArgumentTemplate::Tokens(vec![Token::Parent]),360 ],361 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 363–369why, one step back
363 }
364 );365 }366367 #[test]368 fn tokens_with_basename_no_extension() {369 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 371–376why, one step back
371 CommandTemplate {
372 args: vec![373 ArgumentTemplate::Text("echo".into()),374 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),375 ],376 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 378–384why, one step back
378 }
379 );380 }381382 #[test]383 fn tokens_multiple() {384 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 386–395why, one step back
386 CommandTemplate {
387 args: vec![388 ArgumentTemplate::Text("cp".into()),389 ArgumentTemplate::Tokens(vec![Token::Placeholder]),390 ArgumentTemplate::Tokens(vec![391 Token::BasenameNoExt,392 Token::Text(".ext".into())393 ]),394 ],395 mode: ExecutionMode::OneByOne,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 397–403why, one step back
397 }
398 );399 }400401 #[test]402 fn tokens_single_batch() {403 assert_eq!(

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 405–410why, one step back
405 CommandTemplate {
406 args: vec![407 ArgumentTemplate::Text("echo".into()),408 ArgumentTemplate::Tokens(vec![Token::NoExt]),409 ],410 mode: ExecutionMode::Batch,

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

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

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 412–417why, one step back
412 }
413 );414 }415416 #[test]417 fn tokens_multiple_batch() {

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

lines 418–452why, one step back
418 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());
419 }420421 #[test]422 fn generate_custom_path_separator() {423 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);424 macro_rules! check {425 ($input:expr, $expected:expr) => {426 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));427 };428 }429430 check!("foo", "foo");431 check!("foo/bar", "foo#bar");432 check!("/foo/bar/baz", "#foo#bar#baz");433 }434435 #[cfg(windows)]436 #[test]437 fn generate_custom_path_separator_windows() {438 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);439 macro_rules! check {440 ($input:expr, $expected:expr) => {441 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));442 };443 }444445 // path starting with a drive letter446 check!(r"C:\foo\bar", "C:#foo#bar");447 // UNC path448 check!(r"\\server\share\path", "##server#share#path");449 // Drive Relative path - no separator after the colon omits the RootDir path component.450 // This is uncommon, but valid451 check!(r"C:foo\bar", "C:foo#bar");452

fix spellinga1346054before adoption5b4869a

line 453why, one step back
453 // forward slashes should get normalized and interpreted as separators

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

lines 454–456why, one step back
454 check!("C:/foo/bar", "C:#foo#bar");
455 check!("C:foo/bar", "C:foo#bar");456

fix spellinga1346054before adoption5b4869a

line 457why, one step back
457 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal

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

lines 458–460why, one step back
458 // absolute path that begins with RootDir, and the two slashes get combined together as
459 // a single path separator during normalization.460 //check!("//server/share/path", "##server#share#path");

Fix some clippy lints, and formatAlexandru Macoveibefore adoption4f43301

lines 461–462why, one step back
461 }
462}