mod.rs
This file
Path
src/exec/mod.rs
596 lines · 19.4 KiB · Rust
Last changed by
Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
History of this fileTake it
The walk stopped after 200 commits: lines older than 5ea7cb7 point at it.
A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 1–7why, one step back1mod command;2mod input;3mod job;4mod token;56use std::borrow::Cow;7use std::ffi::{OsStr, OsString};exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 8–9why, one step back8use std::io;9use std::iter;A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 10why, one step back10use std::path::{Component, Path, PathBuf, Prefix};exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 11why, one step back11use std::process::Stdio;A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 12–13why, one step back12use std::sync::{Arc, Mutex};13Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 14why, one step back14use anyhow::{bail, Result};exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 15why, one step back15use argmax::Command;A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 16–18why, one step back16use once_cell::sync::Lazy;17use regex::Regex;18Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 19why, one step back19use crate::exit_codes::{merge_exitcodes, ExitCode};A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 20why, one step back20Group together output from multi exec commandsThayne McCombsbefore adoption9fb0c5d
line 21why, one step back21use self::command::{execute_commands, handle_cmd_error};A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 22–26why, one step back22use self::input::{basename, dirname, remove_extension};23pub use self::job::{batch, job};24use self::token::Token;2526/// Execution mode of the commandFix clippy suggestionsDavid Peterbefore adoption9ea882d
line 27why, one step back27#[derive(Debug, Clone, Copy, PartialEq, Eq)]A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 28–35why, one step back28pub enum ExecutionMode {29 /// Command is executed for each search result30 OneByOne,31 /// Command is run for a batch of results at once32 Batch,33}3435#[derive(Debug, Clone, PartialEq)]Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 36why, one step back36pub struct CommandSet {A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 37why, one step back37 mode: ExecutionMode,Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 38why, one step back38 commands: Vec<CommandTemplate>,A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 39–40why, one step back39}40Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 41why, one step back41impl CommandSet {Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
line 42why, one step back42 pub fn new<I, T, S>(input: I) -> Result<CommandSet>A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 43why, one step back43 whereMerge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
lines 44–45why, one step back44 I: IntoIterator<Item = T>,45 T: IntoIterator<Item = S>,A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 46–47why, one step back46 S: AsRef<str>,47 {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 48why, one step back48 Ok(CommandSet {Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 49why, one step back49 mode: ExecutionMode::OneByOne,Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 50–54why, one step back50 commands: input51 .into_iter()52 .map(CommandTemplate::new)53 .collect::<Result<_>>()?,54 })A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 55–56why, one step back55 }56Merge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
line 57why, one step back57 pub fn new_batch<I, T, S>(input: I) -> Result<CommandSet>A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 58why, one step back58 whereMerge pull request #1244 from tmccombs/grouped-occurrencesDavid Peterbefore adoption73a693e
lines 59–60why, one step back59 I: IntoIterator<Item = T>,60 T: IntoIterator<Item = S>,A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 61–62why, one step back61 S: AsRef<str>,62 {Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 63–67why, one step back63 Ok(CommandSet {64 mode: ExecutionMode::Batch,65 commands: input66 .into_iter()67 .map(|args| {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 68why, one step back68 let cmd = CommandTemplate::new(args)?;Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 69why, one step back69 if cmd.number_of_tokens() > 1 {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 70why, one step back70 bail!("Only one placeholder allowed for batch commands");Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 71–72why, one step back71 }72 if cmd.args[0].has_tokens() {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 73why, one step back73 bail!("First argument of exec-batch is expected to be a fixed executable");Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 74–84why, one step back74 }75 Ok(cmd)76 })77 .collect::<Result<Vec<_>>>()?,78 })79 }8081 pub fn in_batch_mode(&self) -> bool {82 self.mode == ExecutionMode::Batch83 }84Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 85–91why, one step back85 pub fn execute(86 &self,87 input: &Path,88 path_separator: Option<&str>,89 out_perm: Arc<Mutex<()>>,90 buffer_output: bool,91 ) -> ExitCode {Group together output from multi exec commandsThayne McCombsbefore adoption9fb0c5d
lines 92–95why, one step back92 let commands = self93 .commands94 .iter()95 .map(|c| c.generate(input, path_separator));Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 96why, one step back96 execute_commands(commands, &out_perm, buffer_output)Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 97–98why, one step back97 }98Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 99why, one step back99 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCodeSupport multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 100–102why, one step back100 where101 I: Iterator<Item = PathBuf>,102 {exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 103–124why, one step back103 let builders: io::Result<Vec<_>> = self104 .commands105 .iter()106 .map(|c| CommandBuilder::new(c, limit))107 .collect();108109 match builders {110 Ok(mut builders) => {111 for path in paths {112 for builder in &mut builders {113 if let Err(e) = builder.push(&path, path_separator) {114 return handle_cmd_error(Some(&builder.cmd), e);115 }116 }117 }118119 for builder in &mut builders {120 if let Err(e) = builder.finish() {121 return handle_cmd_error(Some(&builder.cmd), e);122 }123 }124Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 125why, one step back125 merge_exitcodes(builders.iter().map(|b| b.exit_code()))Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 126why, one step back126 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 127why, one step back127 Err(e) => handle_cmd_error(None, e),A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 128–129why, one step back128 }129 }Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 130why, one step back130}A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 131why, one step back131exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 132–140why, one step back132/// Represents a multi-exec command as it is built.133#[derive(Debug)]134struct CommandBuilder {135 pre_args: Vec<OsString>,136 path_arg: ArgumentTemplate,137 post_args: Vec<OsString>,138 cmd: Command,139 count: usize,140 limit: usize,Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 141why, one step back141 exit_code: ExitCode,exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 142–152why, one step back142}143144impl CommandBuilder {145 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {146 let mut pre_args = vec![];147 let mut path_arg = None;148 let mut post_args = vec![];149150 for arg in &template.args {151 if arg.has_tokens() {152 path_arg = Some(arg.clone());Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 153why, one step back153 } else if path_arg.is_none() {exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 154–168why, one step back154 pre_args.push(arg.generate("", None));155 } else {156 post_args.push(arg.generate("", None));157 }158 }159160 let cmd = Self::new_command(&pre_args)?;161162 Ok(Self {163 pre_args,164 path_arg: path_arg.unwrap(),165 post_args,166 cmd,167 count: 0,168 limit,Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 169why, one step back169 exit_code: ExitCode::Success,exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 170–202why, one step back170 })171 }172173 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {174 let mut cmd = Command::new(&pre_args[0]);175 cmd.stdin(Stdio::inherit());176 cmd.stdout(Stdio::inherit());177 cmd.stderr(Stdio::inherit());178 cmd.try_args(&pre_args[1..])?;179 Ok(cmd)180 }181182 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {183 if self.limit > 0 && self.count >= self.limit {184 self.finish()?;185 }186187 let arg = self.path_arg.generate(path, separator);188 if !self189 .cmd190 .args_would_fit(iter::once(&arg).chain(&self.post_args))191 {192 self.finish()?;193 }194195 self.cmd.try_arg(arg)?;196 self.count += 1;197 Ok(())198 }199200 fn finish(&mut self) -> io::Result<()> {201 if self.count > 0 {202 self.cmd.try_args(&self.post_args)?;Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
lines 203–205why, one step back203 if !self.cmd.status()?.success() {204 self.exit_code = ExitCode::GeneralError;205 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 206–211why, one step back206207 self.cmd = Self::new_command(&self.pre_args)?;208 self.count = 0;209 }210211 Ok(())Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
lines 212–215why, one step back212 }213214 fn exit_code(&self) -> ExitCode {215 self.exit_codeexec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 216–218why, one step back216 }217}218Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 219–228why, one step back219/// Represents a template that is utilized to generate command strings.220///221/// The template is meant to be coupled with an input in order to generate a command. The222/// `generate_and_execute()` method will be used to generate a command and execute it.223#[derive(Debug, Clone, PartialEq)]224struct CommandTemplate {225 args: Vec<ArgumentTemplate>,226}227228impl CommandTemplate {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 229why, one step back229 fn new<I, S>(input: I) -> Result<CommandTemplate>A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 230–279why, one step back230 where231 I: IntoIterator<Item = S>,232 S: AsRef<str>,233 {234 static PLACEHOLDER_PATTERN: Lazy<Regex> =235 Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());236237 let mut args = Vec::new();238 let mut has_placeholder = false;239240 for arg in input {241 let arg = arg.as_ref();242243 let mut tokens = Vec::new();244 let mut start = 0;245246 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {247 // Leading text before the placeholder.248 if placeholder.start() > start {249 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));250 }251252 start = placeholder.end();253254 match placeholder.as_str() {255 "{}" => tokens.push(Token::Placeholder),256 "{.}" => tokens.push(Token::NoExt),257 "{/}" => tokens.push(Token::Basename),258 "{//}" => tokens.push(Token::Parent),259 "{/.}" => tokens.push(Token::BasenameNoExt),260 _ => unreachable!("Unhandled placeholder"),261 }262263 has_placeholder = true;264 }265266 // Without a placeholder, the argument is just fixed text.267 if tokens.is_empty() {268 args.push(ArgumentTemplate::Text(arg.to_owned()));269 continue;270 }271272 if start < arg.len() {273 // Trailing text after last placeholder.274 tokens.push(Token::Text(arg[start..].to_owned()));275 }276277 args.push(ArgumentTemplate::Tokens(tokens));278 }279Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 280–288why, one step back280 // We need to check that we have at least one argument, because if not281 // it will try to execute each file and directory it finds.282 //283 // Sadly, clap can't currently handle this for us, see284 // https://github.com/clap-rs/clap/issues/3542285 if args.is_empty() {286 bail!("No executable provided for --exec or --exec-batch");287 }288A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 289–293why, one step back289 // If a placeholder token was not supplied, append one at the end of the command.290 if !has_placeholder {291 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));292 }293Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 294why, one step back294 Ok(CommandTemplate { args })A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 295–303why, one step back295 }296297 fn number_of_tokens(&self) -> usize {298 self.args.iter().filter(|arg| arg.has_tokens()).count()299 }300301 /// Generates and executes a command.302 ///303 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will beGroup together output from multi exec commandsThayne McCombsbefore adoption9fb0c5d
line 304why, one step back304 /// build.exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 305why, one step back305 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 306why, one step back306 let mut cmd = Command::new(self.args[0].generate(input, path_separator));A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 307why, one step back307 for arg in &self.args[1..] {Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 308why, one step back308 cmd.try_arg(arg.generate(input, path_separator))?;A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
line 309why, one step back309 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 310why, one step back310 Ok(cmd)A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 311–425why, one step back311 }312}313314/// Represents a template for a single command argument.315///316/// The argument is either a collection of `Token`s including at least one placeholder variant, or317/// a fixed text.318#[derive(Clone, Debug, PartialEq)]319enum ArgumentTemplate {320 Tokens(Vec<Token>),321 Text(String),322}323324impl ArgumentTemplate {325 pub fn has_tokens(&self) -> bool {326 matches!(self, ArgumentTemplate::Tokens(_))327 }328329 /// Generate an argument from this template. If path_separator is Some, then it will replace330 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by331 /// path separator substitution.332 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {333 use self::Token::*;334 let path = path.as_ref();335336 match *self {337 ArgumentTemplate::Tokens(ref tokens) => {338 let mut s = OsString::new();339 for token in tokens {340 match *token {341 Basename => s.push(Self::replace_separator(basename(path), path_separator)),342 BasenameNoExt => s.push(Self::replace_separator(343 &remove_extension(basename(path).as_ref()),344 path_separator,345 )),346 NoExt => s.push(Self::replace_separator(347 &remove_extension(path),348 path_separator,349 )),350 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),351 Placeholder => {352 s.push(Self::replace_separator(path.as_ref(), path_separator))353 }354 Text(ref string) => s.push(string),355 }356 }357 s358 }359 ArgumentTemplate::Text(ref text) => OsString::from(text),360 }361 }362363 /// Replace the path separator in the input with the custom separator string. If path_separator364 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is365 /// interpreted as a Path and its components are iterated through and re-joined into a new366 /// OsString.367 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {368 // fast-path - no replacement necessary369 if path_separator.is_none() {370 return Cow::Borrowed(path);371 }372373 let path_separator = path_separator.unwrap();374 let mut out = OsString::with_capacity(path.len());375 let mut components = Path::new(path).components().peekable();376377 while let Some(comp) = components.next() {378 match comp {379 // Absolute paths on Windows are tricky. A Prefix component is usually a drive380 // letter or UNC path, and is usually followed by RootDir. There are also381 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to382 // ignore verbatim path prefixes here because they're very rare, might be383 // impossible to reach here, and there's no good way to deal with them. If users384 // are doing something advanced involving verbatim windows paths, they can do their385 // own output filtering with a tool like sed.386 Component::Prefix(prefix) => {387 if let Prefix::UNC(server, share) = prefix.kind() {388 // Prefix::UNC is a parsed version of '\\server\share'389 out.push(path_separator);390 out.push(path_separator);391 out.push(server);392 out.push(path_separator);393 out.push(share);394 } else {395 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for396 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,397 // but they're not returned by directories fd can search anyway so we don't worry398 // about them.399 out.push(comp.as_os_str());400 }401 }402403 // Root directory is always replaced with the custom separator.404 Component::RootDir => out.push(path_separator),405406 // Everything else is joined normally, with a trailing separator if we're not last407 _ => {408 out.push(comp.as_os_str());409 if components.peek().is_some() {410 out.push(path_separator);411 }412 }413 }414 }415 Cow::Owned(out)416 }417}418419#[cfg(test)]420mod tests {421 use super::*;422423 #[test]424 fn tokens_with_placeholder() {425 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 426why, one step back426 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 427–434why, one step back427 CommandSet {428 commands: vec![CommandTemplate {429 args: vec![430 ArgumentTemplate::Text("echo".into()),431 ArgumentTemplate::Text("${SHELL}:".into()),432 ArgumentTemplate::Tokens(vec![Token::Placeholder]),433 ]434 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 435–442why, one step back435 mode: ExecutionMode::OneByOne,436 }437 );438 }439440 #[test]441 fn tokens_with_no_extension() {442 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 443why, one step back443 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 444–450why, one step back444 CommandSet {445 commands: vec![CommandTemplate {446 args: vec![447 ArgumentTemplate::Text("echo".into()),448 ArgumentTemplate::Tokens(vec![Token::NoExt]),449 ],450 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 451–458why, one step back451 mode: ExecutionMode::OneByOne,452 }453 );454 }455456 #[test]457 fn tokens_with_basename() {458 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 459why, one step back459 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 460–466why, one step back460 CommandSet {461 commands: vec![CommandTemplate {462 args: vec![463 ArgumentTemplate::Text("echo".into()),464 ArgumentTemplate::Tokens(vec![Token::Basename]),465 ],466 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 467–474why, one step back467 mode: ExecutionMode::OneByOne,468 }469 );470 }471472 #[test]473 fn tokens_with_parent() {474 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 475why, one step back475 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 476–482why, one step back476 CommandSet {477 commands: vec![CommandTemplate {478 args: vec![479 ArgumentTemplate::Text("echo".into()),480 ArgumentTemplate::Tokens(vec![Token::Parent]),481 ],482 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 483–490why, one step back483 mode: ExecutionMode::OneByOne,484 }485 );486 }487488 #[test]489 fn tokens_with_basename_no_extension() {490 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 491why, one step back491 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 492–498why, one step back492 CommandSet {493 commands: vec![CommandTemplate {494 args: vec![495 ArgumentTemplate::Text("echo".into()),496 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),497 ],498 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 499–506why, one step back499 mode: ExecutionMode::OneByOne,500 }501 );502 }503504 #[test]505 fn tokens_multiple() {506 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 507why, one step back507 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 508–518why, one step back508 CommandSet {509 commands: vec![CommandTemplate {510 args: vec![511 ArgumentTemplate::Text("cp".into()),512 ArgumentTemplate::Tokens(vec![Token::Placeholder]),513 ArgumentTemplate::Tokens(vec![514 Token::BasenameNoExt,515 Token::Text(".ext".into())516 ]),517 ],518 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 519–526why, one step back519 mode: ExecutionMode::OneByOne,520 }521 );522 }523524 #[test]525 fn tokens_single_batch() {526 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 527why, one step back527 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 528–529why, one step back528 CommandSet {529 commands: vec![CommandTemplate {Fix clippy lintsThayne McCombsbefore adoptionf27332e
lines 530–533why, one step back530 args: vec![531 ArgumentTemplate::Text("echo".into()),532 ArgumentTemplate::Tokens(vec![Token::NoExt]),533 ],Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 534why, one step back534 }],A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 535–541why, one step back535 mode: ExecutionMode::Batch,536 }537 );538 }539540 #[test]541 fn tokens_multiple_batch() {Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 542why, one step back542 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 543–551why, one step back543 }544545 #[test]546 fn template_no_args() {547 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());548 }549550 #[test]551 fn command_set_no_args() {Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 552why, one step back552 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());A couple of minor recommendations from the Code Quality action (#903)Thayne McCombsbefore adoption5ea7cb7
lines 553–596why, one step back553 }554555 #[test]556 fn generate_custom_path_separator() {557 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);558 macro_rules! check {559 ($input:expr, $expected:expr) => {560 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));561 };562 }563564 check!("foo", "foo");565 check!("foo/bar", "foo#bar");566 check!("/foo/bar/baz", "#foo#bar#baz");567 }568569 #[cfg(windows)]570 #[test]571 fn generate_custom_path_separator_windows() {572 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);573 macro_rules! check {574 ($input:expr, $expected:expr) => {575 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));576 };577 }578579 // path starting with a drive letter580 check!(r"C:\foo\bar", "C:#foo#bar");581 // UNC path582 check!(r"\\server\share\path", "##server#share#path");583 // Drive Relative path - no separator after the colon omits the RootDir path component.584 // This is uncommon, but valid585 check!(r"C:foo\bar", "C:foo#bar");586587 // forward slashes should get normalized and interpreted as separators588 check!("C:/foo/bar", "C:#foo#bar");589 check!("C:foo/bar", "C:foo#bar");590591 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal592 // absolute path that begins with RootDir, and the two slashes get combined together as593 // a single path separator during normalization.594 //check!("//server/share/path", "##server#share#path");595 }596}