mod.rs
This file
Path
src/exec/mod.rs
458 lines · 15.6 KiB · Rust
Last changed by
Merge pull request #861 from jcaplan/no-strip/760David Peterbefore adoptionb211ded
History of this fileTake it
The walk stopped after 200 commits: lines older than d7cc34e point at it.
[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 1–5why, one step back1mod command;2mod input;3mod job;4mod token;5use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 6–8why, one step back6use std::borrow::Cow;7use std::ffi::{OsStr, OsString};8use std::path::{Component, Path, PathBuf, Prefix};[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 9–12why, one step back9use std::process::{Command, Stdio};10use std::sync::{Arc, Mutex};1112use anyhow::{anyhow, Result};Remove `lazy_static` from dependenciesShun Sakaibefore adoption0484486
line 13why, one step back13use once_cell::sync::Lazy;[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 14–39why, one step back14use regex::Regex;1516use crate::exit_codes::ExitCode;1718use self::command::execute_command;19use self::input::{basename, dirname, remove_extension};20pub use self::job::{batch, job};21use self::token::Token;2223/// Execution mode of the command24#[derive(Debug, Clone, Copy, PartialEq)]25pub enum ExecutionMode {26 /// Command is executed for each search result27 OneByOne,28 /// Command is run for a batch of results at once29 Batch,30}3132/// 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>,39 mode: ExecutionMode,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 40why, one step back40 path_separator: Option<String>,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 41–43why, one step back41}4243impl CommandTemplate {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 44why, one step back44 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandTemplate[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 45–48why, one step back45 where46 I: IntoIterator<Item = S>,47 S: AsRef<str>,48 {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 49why, one step back49 Self::build(input, ExecutionMode::OneByOne, path_separator)[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 50–51why, one step back50 }51use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 52why, one step back52 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandTemplate>[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 53–56why, one step back53 where54 I: IntoIterator<Item = S>,55 S: AsRef<str>,56 {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 57why, one step back57 let cmd = Self::build(input, ExecutionMode::Batch, path_separator);[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 58–68why, one step back58 if cmd.number_of_tokens() > 1 {59 return Err(anyhow!("Only one placeholder allowed for batch commands"));60 }61 if cmd.args[0].has_tokens() {62 return Err(anyhow!(63 "First argument of exec-batch is expected to be a fixed executable"64 ));65 }66 Ok(cmd)67 }68use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 69why, one step back69 fn build<I, S>(input: I, mode: ExecutionMode, path_separator: Option<String>) -> CommandTemplate[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 70–73why, one step back70 where71 I: IntoIterator<Item = S>,72 S: AsRef<str>,73 {Remove `lazy_static` from dependenciesShun Sakaibefore adoption0484486
lines 74–75why, one step back74 static PLACEHOLDER_PATTERN: Lazy<Regex> =75 Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 76–124why, one step back7677 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 _ => unreachable!("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 }124use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 125–129why, one step back125 CommandTemplate {126 args,127 mode,128 path_separator,129 }[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 130–139why, one step back130 }131132 fn number_of_tokens(&self) -> usize {133 self.args.iter().filter(|arg| arg.has_tokens()).count()134 }135136 /// Generates and executes a command.137 ///138 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will be139 /// 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 140–145why, one step back140 pub fn generate_and_execute(141 &self,142 input: &Path,143 out_perm: Arc<Mutex<()>>,144 buffer_output: bool,145 ) -> ExitCode {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 146why, one step back146 let mut cmd = Command::new(self.args[0].generate(&input, self.path_separator.as_deref()));[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
line 147why, one step back147 for arg in &self.args[1..] {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 148why, one step back148 cmd.arg(arg.generate(&input, self.path_separator.as_deref()));[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 149–150why, one step back149 }150Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060
line 151why, one step back151 execute_command(cmd, &out_perm, buffer_output)[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 152–157why, one step back152 }153154 pub fn in_batch_mode(&self) -> bool {155 self.mode == ExecutionMode::Batch156 }157Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060
line 158why, one step back158 pub fn generate_and_execute_batch<I>(&self, paths: I, buffer_output: bool) -> ExitCode[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 159–161why, one step back159 where160 I: Iterator<Item = PathBuf>,161 {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 162why, one step back162 let mut cmd = Command::new(self.args[0].generate("", None));[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 163–176why, one step back163 cmd.stdin(Stdio::inherit());164 cmd.stdout(Stdio::inherit());165 cmd.stderr(Stdio::inherit());166167 let mut paths: Vec<_> = paths.collect();168 let mut has_path = false;169170 for arg in &self.args[1..] {171 if arg.has_tokens() {172 paths.sort();173174 // A single `Tokens` is expected175 // So we can directly consume the iterator once and for all176 for path in &mut paths {Merge pull request #861 from jcaplan/no-strip/760David Peterbefore adoptionb211ded
line 177why, one step back177 cmd.arg(arg.generate(path, self.path_separator.as_deref()));[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 178–180why, one step back178 has_path = true;179 }180 } else {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 181why, one step back181 cmd.arg(arg.generate("", None));[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 182–185why, one step back182 }183 }184185 if has_path {Address feedback for removing buffering when running on a single threadThayne McCombsbefore adoptione473060
line 186why, one step back186 execute_command(cmd, &Mutex::new(()), buffer_output)[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 187–204why, one step back187 } else {188 ExitCode::Success189 }190 }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 {204 pub fn has_tokens(&self) -> bool {Fix clippy warningsDavid Peterbefore adoption2a2126c
line 205why, one step back205 matches!(self, ArgumentTemplate::Tokens(_))[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 206–207why, one step back206 }207use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 208–211why, one step back208 /// Generate an argument from this template. If path_separator is Some, then it will replace209 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by210 /// path separator substitution.211 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
line 212why, one step back212 use self::Token::*;use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 213why, one step back213 let path = path.as_ref();[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 214–219why, one step back214215 match *self {216 ArgumentTemplate::Tokens(ref tokens) => {217 let mut s = OsString::new();218 for token in tokens {219 match *token {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 220–231why, one step back220 Basename => s.push(Self::replace_separator(basename(path), path_separator)),221 BasenameNoExt => s.push(Self::replace_separator(222 &remove_extension(basename(path).as_ref()),223 path_separator,224 )),225 NoExt => s.push(Self::replace_separator(226 &remove_extension(path),227 path_separator,228 )),229 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),230 Placeholder => {231 s.push(Self::replace_separator(path.as_ref(), path_separator))[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 232–240why, one step back232 }233 Text(ref string) => s.push(string),234 }235 }236 s237 }238 ArgumentTemplate::Text(ref text) => OsString::from(text),239 }240 }use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 241–295why, one step back241242 /// Replace the path separator in the input with the custom separator string. If path_separator243 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is244 /// interpreted as a Path and its components are iterated through and re-joined into a new245 /// OsString.246 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {247 // fast-path - no replacement necessary248 if path_separator.is_none() {249 return Cow::Borrowed(path);250 }251252 let path_separator = path_separator.unwrap();253 let mut out = OsString::with_capacity(path.len());254 let mut components = Path::new(path).components().peekable();255256 while let Some(comp) = components.next() {257 match comp {258 // Absolute paths on Windows are tricky. A Prefix component is usually a drive259 // letter or UNC path, and is usually followed by RootDir. There are also260 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to261 // ignore verbatim path prefixes here because they're very rare, might be262 // impossible to reach here, and there's no good way to deal with them. If users263 // are doing something advanced involving verbatim windows paths, they can do their264 // own output filtering with a tool like sed.265 Component::Prefix(prefix) => {266 if let Prefix::UNC(server, share) = prefix.kind() {267 // Prefix::UNC is a parsed version of '\\server\share'268 out.push(path_separator);269 out.push(path_separator);270 out.push(server);271 out.push(path_separator);272 out.push(share);273 } else {274 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for275 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,276 // but they're not returned by directories fd can search anyway so we don't worry277 // about them.278 out.push(comp.as_os_str());279 }280 }281282 // Root directory is always replaced with the custom separator.283 Component::RootDir => out.push(path_separator),284285 // Everything else is joined normally, with a trailing separator if we're not last286 _ => {287 out.push(comp.as_os_str());288 if components.peek().is_some() {289 out.push(path_separator);290 }291 }292 }293 }294 Cow::Owned(out)295 }[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 296–304why, one step back296}297298#[cfg(test)]299mod tests {300 use super::*;301302 #[test]303 fn tokens_with_placeholder() {304 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 305why, one step back305 CommandTemplate::new(&[&"echo", &"${SHELL}:"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 306–312why, one step back306 CommandTemplate {307 args: vec![308 ArgumentTemplate::Text("echo".into()),309 ArgumentTemplate::Text("${SHELL}:".into()),310 ArgumentTemplate::Tokens(vec![Token::Placeholder]),311 ],312 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 313why, one step back313 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 314–320why, one step back314 }315 );316 }317318 #[test]319 fn tokens_with_no_extension() {320 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 321why, one step back321 CommandTemplate::new(&["echo", "{.}"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 322–327why, one step back322 CommandTemplate {323 args: vec![324 ArgumentTemplate::Text("echo".into()),325 ArgumentTemplate::Tokens(vec![Token::NoExt]),326 ],327 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 328why, one step back328 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 329–335why, one step back329 }330 );331 }332333 #[test]334 fn tokens_with_basename() {335 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 336why, one step back336 CommandTemplate::new(&["echo", "{/}"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 337–342why, one step back337 CommandTemplate {338 args: vec![339 ArgumentTemplate::Text("echo".into()),340 ArgumentTemplate::Tokens(vec![Token::Basename]),341 ],342 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 343why, one step back343 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 344–350why, one step back344 }345 );346 }347348 #[test]349 fn tokens_with_parent() {350 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 351why, one step back351 CommandTemplate::new(&["echo", "{//}"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 352–357why, one step back352 CommandTemplate {353 args: vec![354 ArgumentTemplate::Text("echo".into()),355 ArgumentTemplate::Tokens(vec![Token::Parent]),356 ],357 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 358why, one step back358 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 359–365why, one step back359 }360 );361 }362363 #[test]364 fn tokens_with_basename_no_extension() {365 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 366why, one step back366 CommandTemplate::new(&["echo", "{/.}"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 367–372why, one step back367 CommandTemplate {368 args: vec![369 ArgumentTemplate::Text("echo".into()),370 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),371 ],372 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 373why, one step back373 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 374–380why, one step back374 }375 );376 }377378 #[test]379 fn tokens_multiple() {380 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 381why, one step back381 CommandTemplate::new(&["cp", "{}", "{/.}.ext"], None),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 382–391why, one step back382 CommandTemplate {383 args: vec![384 ArgumentTemplate::Text("cp".into()),385 ArgumentTemplate::Tokens(vec![Token::Placeholder]),386 ArgumentTemplate::Tokens(vec![387 Token::BasenameNoExt,388 Token::Text(".ext".into())389 ]),390 ],391 mode: ExecutionMode::OneByOne,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 392why, one step back392 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 393–399why, one step back393 }394 );395 }396397 #[test]398 fn tokens_single_batch() {399 assert_eq!(use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 400why, one step back400 CommandTemplate::new_batch(&["echo", "{.}"], None).unwrap(),[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 401–406why, one step back401 CommandTemplate {402 args: vec![403 ArgumentTemplate::Text("echo".into()),404 ArgumentTemplate::Tokens(vec![Token::NoExt]),405 ],406 mode: ExecutionMode::Batch,use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
line 407why, one step back407 path_separator: None,[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 408–413why, one step back408 }409 );410 }411412 #[test]413 fn tokens_multiple_batch() {use custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 414–448why, one step back414 assert!(CommandTemplate::new_batch(&["echo", "{.}", "{}"], None).is_err());415 }416417 #[test]418 fn generate_custom_path_separator() {419 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);420 macro_rules! check {421 ($input:expr, $expected:expr) => {422 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));423 };424 }425426 check!("foo", "foo");427 check!("foo/bar", "foo#bar");428 check!("/foo/bar/baz", "#foo#bar#baz");429 }430431 #[cfg(windows)]432 #[test]433 fn generate_custom_path_separator_windows() {434 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);435 macro_rules! check {436 ($input:expr, $expected:expr) => {437 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));438 };439 }440441 // path starting with a drive letter442 check!(r"C:\foo\bar", "C:#foo#bar");443 // UNC path444 check!(r"\\server\share\path", "##server#share#path");445 // Drive Relative path - no separator after the colon omits the RootDir path component.446 // This is uncommon, but valid447 check!(r"C:foo\bar", "C:foo#bar");448fix spellinga1346054before adoption5b4869a
line 449why, one step back449 // forward slashes should get normalized and interpreted as separatorsuse custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 450–452why, one step back450 check!("C:/foo/bar", "C:#foo#bar");451 check!("C:foo/bar", "C:foo#bar");452fix spellinga1346054before adoption5b4869a
line 453why, one step back453 // Rust does not interpret "//server/share" as a UNC path, but rather as a normaluse custom --path-separator in arguments to --execAllen Wildbefore adoption8a532e5
lines 454–456why, one step back454 // absolute path that begins with RootDir, and the two slashes get combined together as455 // a single path separator during normalization.456 //check!("//server/share/path", "##server#share#path");[ownership] depend on users 0.10.0 on unix; parse user and group namesAlexandru Macoveibefore adoptiond7cc34e
lines 457–458why, one step back457 }458}