mod.rs
This file
Path
src/exec/mod.rs
594 lines · 19.3 KiB · Rust
Last changed by
Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
History of this fileTake it
The walk stopped after 200 commits: lines older than 04fac46 point at it.
Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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;Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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;Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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;Remove `lazy_static` from dependenciesShun Sakaibefore adoption0484486
line 16why, one step back16use once_cell::sync::Lazy;Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 17–18why, one step back17use regex::Regex;18Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 19why, one step back19use crate::exit_codes::{merge_exitcodes, ExitCode};Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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};Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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)]Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
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 {Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 37why, one step back37 mode: ExecutionMode,Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 38why, one step back38 commands: Vec<CommandTemplate>,Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 39–40why, one step back39}40Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 41why, one step back41impl CommandSet {Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 42why, one step back42 pub fn new<I, S>(input: I) -> Result<CommandSet>Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 43why, one step back43 whereSupport multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 44why, one step back44 I: IntoIterator<Item = Vec<S>>,Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 45–46why, one step back45 S: AsRef<str>,46 {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 47why, one step back47 Ok(CommandSet {Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 48why, one step back48 mode: ExecutionMode::OneByOne,Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 49–53why, one step back49 commands: input50 .into_iter()51 .map(CommandTemplate::new)52 .collect::<Result<_>>()?,53 })Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 54–55why, one step back54 }55Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 56why, one step back56 pub fn new_batch<I, S>(input: I) -> Result<CommandSet>Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 57why, one step back57 whereSupport multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 58why, one step back58 I: IntoIterator<Item = Vec<S>>,Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 59–60why, one step back59 S: AsRef<str>,60 {Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 61–65why, one step back61 Ok(CommandSet {62 mode: ExecutionMode::Batch,63 commands: input64 .into_iter()65 .map(|args| {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 66why, one step back66 let cmd = CommandTemplate::new(args)?;Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 67why, one step back67 if cmd.number_of_tokens() > 1 {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 68why, one step back68 bail!("Only one placeholder allowed for batch commands");Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 69–70why, one step back69 }70 if cmd.args[0].has_tokens() {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 71why, one step back71 bail!("First argument of exec-batch is expected to be a fixed executable");Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 72–82why, one step back72 }73 Ok(cmd)74 })75 .collect::<Result<Vec<_>>>()?,76 })77 }7879 pub fn in_batch_mode(&self) -> bool {80 self.mode == ExecutionMode::Batch81 }82Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
lines 83–89why, one step back83 pub fn execute(84 &self,85 input: &Path,86 path_separator: Option<&str>,87 out_perm: Arc<Mutex<()>>,88 buffer_output: bool,89 ) -> ExitCode {Group together output from multi exec commandsThayne McCombsbefore adoption9fb0c5d
lines 90–93why, one step back90 let commands = self91 .commands92 .iter()93 .map(|c| c.generate(input, path_separator));Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 94why, one step back94 execute_commands(commands, &out_perm, buffer_output)Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 95–96why, one step back95 }96Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 97why, one step back97 pub fn execute_batch<I>(&self, paths: I, limit: usize, path_separator: Option<&str>) -> ExitCodeSupport multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 98–100why, one step back98 where99 I: Iterator<Item = PathBuf>,100 {exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 101–122why, one step back101 let builders: io::Result<Vec<_>> = self102 .commands103 .iter()104 .map(|c| CommandBuilder::new(c, limit))105 .collect();106107 match builders {108 Ok(mut builders) => {109 for path in paths {110 for builder in &mut builders {111 if let Err(e) = builder.push(&path, path_separator) {112 return handle_cmd_error(Some(&builder.cmd), e);113 }114 }115 }116117 for builder in &mut builders {118 if let Err(e) = builder.finish() {119 return handle_cmd_error(Some(&builder.cmd), e);120 }121 }122Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 123why, one step back123 merge_exitcodes(builders.iter().map(|b| b.exit_code()))Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 124why, one step back124 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 125why, one step back125 Err(e) => handle_cmd_error(None, e),Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 126–127why, one step back126 }127 }Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 128why, one step back128}Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 129why, one step back129exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 130–138why, one step back130/// Represents a multi-exec command as it is built.131#[derive(Debug)]132struct CommandBuilder {133 pre_args: Vec<OsString>,134 path_arg: ArgumentTemplate,135 post_args: Vec<OsString>,136 cmd: Command,137 count: usize,138 limit: usize,Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 139why, one step back139 exit_code: ExitCode,exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 140–150why, one step back140}141142impl CommandBuilder {143 fn new(template: &CommandTemplate, limit: usize) -> io::Result<Self> {144 let mut pre_args = vec![];145 let mut path_arg = None;146 let mut post_args = vec![];147148 for arg in &template.args {149 if arg.has_tokens() {150 path_arg = Some(arg.clone());Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 151why, one step back151 } else if path_arg.is_none() {exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 152–166why, one step back152 pre_args.push(arg.generate("", None));153 } else {154 post_args.push(arg.generate("", None));155 }156 }157158 let cmd = Self::new_command(&pre_args)?;159160 Ok(Self {161 pre_args,162 path_arg: path_arg.unwrap(),163 post_args,164 cmd,165 count: 0,166 limit,Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
line 167why, one step back167 exit_code: ExitCode::Success,exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 168–200why, one step back168 })169 }170171 fn new_command(pre_args: &[OsString]) -> io::Result<Command> {172 let mut cmd = Command::new(&pre_args[0]);173 cmd.stdin(Stdio::inherit());174 cmd.stdout(Stdio::inherit());175 cmd.stderr(Stdio::inherit());176 cmd.try_args(&pre_args[1..])?;177 Ok(cmd)178 }179180 fn push(&mut self, path: &Path, separator: Option<&str>) -> io::Result<()> {181 if self.limit > 0 && self.count >= self.limit {182 self.finish()?;183 }184185 let arg = self.path_arg.generate(path, separator);186 if !self187 .cmd188 .args_would_fit(iter::once(&arg).chain(&self.post_args))189 {190 self.finish()?;191 }192193 self.cmd.try_arg(arg)?;194 self.count += 1;195 Ok(())196 }197198 fn finish(&mut self) -> io::Result<()> {199 if self.count > 0 {200 self.cmd.try_args(&self.post_args)?;Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
lines 201–203why, one step back201 if !self.cmd.status()?.success() {202 self.exit_code = ExitCode::GeneralError;203 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 204–209why, one step back204205 self.cmd = Self::new_command(&self.pre_args)?;206 self.count = 0;207 }208209 Ok(())Merge pull request #1137 from amesgen/batch-exit-codeDavid Peterbefore adoptionb57ed11
lines 210–213why, one step back210 }211212 fn exit_code(&self) -> ExitCode {213 self.exit_codeexec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
lines 214–216why, one step back214 }215}216Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 217–226why, one step back217/// Represents a template that is utilized to generate command strings.218///219/// The template is meant to be coupled with an input in order to generate a command. The220/// `generate_and_execute()` method will be used to generate a command and execute it.221#[derive(Debug, Clone, PartialEq)]222struct CommandTemplate {223 args: Vec<ArgumentTemplate>,224}225226impl CommandTemplate {Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 227why, one step back227 fn new<I, S>(input: I) -> Result<CommandTemplate>Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 228–231why, one step back228 where229 I: IntoIterator<Item = S>,230 S: AsRef<str>,231 {Remove `lazy_static` from dependenciesShun Sakaibefore adoption0484486
lines 232–233why, one step back232 static PLACEHOLDER_PATTERN: Lazy<Regex> =233 Lazy::new(|| Regex::new(r"\{(/?\.?|//)\}").unwrap());Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 234–277why, one step back234235 let mut args = Vec::new();236 let mut has_placeholder = false;237238 for arg in input {239 let arg = arg.as_ref();240241 let mut tokens = Vec::new();242 let mut start = 0;243244 for placeholder in PLACEHOLDER_PATTERN.find_iter(arg) {245 // Leading text before the placeholder.246 if placeholder.start() > start {247 tokens.push(Token::Text(arg[start..placeholder.start()].to_owned()));248 }249250 start = placeholder.end();251252 match placeholder.as_str() {253 "{}" => tokens.push(Token::Placeholder),254 "{.}" => tokens.push(Token::NoExt),255 "{/}" => tokens.push(Token::Basename),256 "{//}" => tokens.push(Token::Parent),257 "{/.}" => tokens.push(Token::BasenameNoExt),258 _ => unreachable!("Unhandled placeholder"),259 }260261 has_placeholder = true;262 }263264 // Without a placeholder, the argument is just fixed text.265 if tokens.is_empty() {266 args.push(ArgumentTemplate::Text(arg.to_owned()));267 continue;268 }269270 if start < arg.len() {271 // Trailing text after last placeholder.272 tokens.push(Token::Text(arg[start..].to_owned()));273 }274275 args.push(ArgumentTemplate::Tokens(tokens));276 }277Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 278–286why, one step back278 // We need to check that we have at least one argument, because if not279 // it will try to execute each file and directory it finds.280 //281 // Sadly, clap can't currently handle this for us, see282 // https://github.com/clap-rs/clap/issues/3542283 if args.is_empty() {284 bail!("No executable provided for --exec or --exec-batch");285 }286Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 287–291why, one step back287 // If a placeholder token was not supplied, append one at the end of the command.288 if !has_placeholder {289 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));290 }291Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
line 292why, one step back292 Ok(CommandTemplate { args })Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 293–301why, one step back293 }294295 fn number_of_tokens(&self) -> usize {296 self.args.iter().filter(|arg| arg.has_tokens()).count()297 }298299 /// Generates and executes a command.300 ///301 /// Using the internal `args` field, and a supplied `input` variable, a `Command` will beGroup together output from multi exec commandsThayne McCombsbefore adoption9fb0c5d
line 302why, one step back302 /// build.exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 303why, one step back303 fn generate(&self, input: &Path, path_separator: Option<&str>) -> io::Result<Command> {Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 304why, one step back304 let mut cmd = Command::new(self.args[0].generate(input, path_separator));Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 305why, one step back305 for arg in &self.args[1..] {Merge pull request #1168 from tmccombs/clippy-fixes-2Thayne McCombsbefore adoption9e88f91
line 306why, one step back306 cmd.try_arg(arg.generate(input, path_separator))?;Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
line 307why, one step back307 }exec: Execute batches before they get too longTavian Barnesbefore adoption40b368e
line 308why, one step back308 Ok(cmd)Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 309–423why, one step back309 }310}311312/// Represents a template for a single command argument.313///314/// The argument is either a collection of `Token`s including at least one placeholder variant, or315/// a fixed text.316#[derive(Clone, Debug, PartialEq)]317enum ArgumentTemplate {318 Tokens(Vec<Token>),319 Text(String),320}321322impl ArgumentTemplate {323 pub fn has_tokens(&self) -> bool {324 matches!(self, ArgumentTemplate::Tokens(_))325 }326327 /// Generate an argument from this template. If path_separator is Some, then it will replace328 /// the path separator in all placeholder tokens. Text arguments and tokens are not affected by329 /// path separator substitution.330 pub fn generate(&self, path: impl AsRef<Path>, path_separator: Option<&str>) -> OsString {331 use self::Token::*;332 let path = path.as_ref();333334 match *self {335 ArgumentTemplate::Tokens(ref tokens) => {336 let mut s = OsString::new();337 for token in tokens {338 match *token {339 Basename => s.push(Self::replace_separator(basename(path), path_separator)),340 BasenameNoExt => s.push(Self::replace_separator(341 &remove_extension(basename(path).as_ref()),342 path_separator,343 )),344 NoExt => s.push(Self::replace_separator(345 &remove_extension(path),346 path_separator,347 )),348 Parent => s.push(Self::replace_separator(&dirname(path), path_separator)),349 Placeholder => {350 s.push(Self::replace_separator(path.as_ref(), path_separator))351 }352 Text(ref string) => s.push(string),353 }354 }355 s356 }357 ArgumentTemplate::Text(ref text) => OsString::from(text),358 }359 }360361 /// Replace the path separator in the input with the custom separator string. If path_separator362 /// is None, simply return a borrowed Cow<OsStr> of the input. Otherwise, the input is363 /// interpreted as a Path and its components are iterated through and re-joined into a new364 /// OsString.365 fn replace_separator<'a>(path: &'a OsStr, path_separator: Option<&str>) -> Cow<'a, OsStr> {366 // fast-path - no replacement necessary367 if path_separator.is_none() {368 return Cow::Borrowed(path);369 }370371 let path_separator = path_separator.unwrap();372 let mut out = OsString::with_capacity(path.len());373 let mut components = Path::new(path).components().peekable();374375 while let Some(comp) = components.next() {376 match comp {377 // Absolute paths on Windows are tricky. A Prefix component is usually a drive378 // letter or UNC path, and is usually followed by RootDir. There are also379 // "verbatim" prefixes beginning with "\\?\" that skip normalization. We choose to380 // ignore verbatim path prefixes here because they're very rare, might be381 // impossible to reach here, and there's no good way to deal with them. If users382 // are doing something advanced involving verbatim windows paths, they can do their383 // own output filtering with a tool like sed.384 Component::Prefix(prefix) => {385 if let Prefix::UNC(server, share) = prefix.kind() {386 // Prefix::UNC is a parsed version of '\\server\share'387 out.push(path_separator);388 out.push(path_separator);389 out.push(server);390 out.push(path_separator);391 out.push(share);392 } else {393 // All other Windows prefix types are rendered as-is. This results in e.g. "C:" for394 // drive letters. DeviceNS and Verbatim* prefixes won't have backslashes converted,395 // but they're not returned by directories fd can search anyway so we don't worry396 // about them.397 out.push(comp.as_os_str());398 }399 }400401 // Root directory is always replaced with the custom separator.402 Component::RootDir => out.push(path_separator),403404 // Everything else is joined normally, with a trailing separator if we're not last405 _ => {406 out.push(comp.as_os_str());407 if components.peek().is_some() {408 out.push(path_separator);409 }410 }411 }412 }413 Cow::Owned(out)414 }415}416417#[cfg(test)]418mod tests {419 use super::*;420421 #[test]422 fn tokens_with_placeholder() {423 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 424why, one step back424 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 425–432why, one step back425 CommandSet {426 commands: vec![CommandTemplate {427 args: vec![428 ArgumentTemplate::Text("echo".into()),429 ArgumentTemplate::Text("${SHELL}:".into()),430 ArgumentTemplate::Tokens(vec![Token::Placeholder]),431 ]432 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 433–440why, one step back433 mode: ExecutionMode::OneByOne,434 }435 );436 }437438 #[test]439 fn tokens_with_no_extension() {440 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 441why, one step back441 CommandSet::new(vec![vec!["echo", "{.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 442–448why, one step back442 CommandSet {443 commands: vec![CommandTemplate {444 args: vec![445 ArgumentTemplate::Text("echo".into()),446 ArgumentTemplate::Tokens(vec![Token::NoExt]),447 ],448 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 449–456why, one step back449 mode: ExecutionMode::OneByOne,450 }451 );452 }453454 #[test]455 fn tokens_with_basename() {456 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 457why, one step back457 CommandSet::new(vec![vec!["echo", "{/}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 458–464why, one step back458 CommandSet {459 commands: vec![CommandTemplate {460 args: vec![461 ArgumentTemplate::Text("echo".into()),462 ArgumentTemplate::Tokens(vec![Token::Basename]),463 ],464 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 465–472why, one step back465 mode: ExecutionMode::OneByOne,466 }467 );468 }469470 #[test]471 fn tokens_with_parent() {472 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 473why, one step back473 CommandSet::new(vec![vec!["echo", "{//}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 474–480why, one step back474 CommandSet {475 commands: vec![CommandTemplate {476 args: vec![477 ArgumentTemplate::Text("echo".into()),478 ArgumentTemplate::Tokens(vec![Token::Parent]),479 ],480 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 481–488why, one step back481 mode: ExecutionMode::OneByOne,482 }483 );484 }485486 #[test]487 fn tokens_with_basename_no_extension() {488 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 489why, one step back489 CommandSet::new(vec![vec!["echo", "{/.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 490–496why, one step back490 CommandSet {491 commands: vec![CommandTemplate {492 args: vec![493 ArgumentTemplate::Text("echo".into()),494 ArgumentTemplate::Tokens(vec![Token::BasenameNoExt]),495 ],496 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 497–504why, one step back497 mode: ExecutionMode::OneByOne,498 }499 );500 }501502 #[test]503 fn tokens_multiple() {504 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 505why, one step back505 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 506–516why, one step back506 CommandSet {507 commands: vec![CommandTemplate {508 args: vec![509 ArgumentTemplate::Text("cp".into()),510 ArgumentTemplate::Tokens(vec![Token::Placeholder]),511 ArgumentTemplate::Tokens(vec![512 Token::BasenameNoExt,513 Token::Text(".ext".into())514 ]),515 ],516 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 517–524why, one step back517 mode: ExecutionMode::OneByOne,518 }519 );520 }521522 #[test]523 fn tokens_single_batch() {524 assert_eq!(Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 525why, one step back525 CommandSet::new_batch(vec![vec!["echo", "{.}"]]).unwrap(),Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
lines 526–527why, one step back526 CommandSet {527 commands: vec![CommandTemplate {Fix clippy lintsThayne McCombsbefore adoptionf27332e
lines 528–531why, one step back528 args: vec![529 ArgumentTemplate::Text("echo".into()),530 ArgumentTemplate::Tokens(vec![Token::NoExt]),531 ],Support multiple `--exec` instancesThayne McCombsbefore adoption0aee9b0
line 532why, one step back532 }],Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 533–539why, one step back533 mode: ExecutionMode::Batch,534 }535 );536 }537538 #[test]539 fn tokens_multiple_batch() {Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 540why, one step back540 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]]).is_err());Error out if no args provided to --exec or --exec-batchThayne McCombsbefore adoptionc577b08
lines 541–549why, one step back541 }542543 #[test]544 fn template_no_args() {545 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());546 }547548 #[test]549 fn command_set_no_args() {Merge pull request #1067 from tmccombs/clap-deriveDavid Peterbefore adoption13a47c3
line 550why, one step back550 assert!(CommandSet::new(vec![vec!["echo"], vec![]]).is_err());Merge pull request #857 from exploide/short-help-completionTavian Barnesbefore adoption04fac46
lines 551–594why, one step back551 }552553 #[test]554 fn generate_custom_path_separator() {555 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);556 macro_rules! check {557 ($input:expr, $expected:expr) => {558 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));559 };560 }561562 check!("foo", "foo");563 check!("foo/bar", "foo#bar");564 check!("/foo/bar/baz", "#foo#bar#baz");565 }566567 #[cfg(windows)]568 #[test]569 fn generate_custom_path_separator_windows() {570 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);571 macro_rules! check {572 ($input:expr, $expected:expr) => {573 assert_eq!(arg.generate($input, Some("#")), OsString::from($expected));574 };575 }576577 // path starting with a drive letter578 check!(r"C:\foo\bar", "C:#foo#bar");579 // UNC path580 check!(r"\\server\share\path", "##server#share#path");581 // Drive Relative path - no separator after the colon omits the RootDir path component.582 // This is uncommon, but valid583 check!(r"C:foo\bar", "C:foo#bar");584585 // forward slashes should get normalized and interpreted as separators586 check!("C:/foo/bar", "C:#foo#bar");587 check!("C:foo/bar", "C:foo#bar");588589 // Rust does not interpret "//server/share" as a UNC path, but rather as a normal590 // absolute path that begins with RootDir, and the two slashes get combined together as591 // a single path separator during normalization.592 //check!("//server/share/path", "##server#share#path");593 }594}