Skip to content
Myr

Error out if no args provided to --exec or --exec-batch

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Accepting multiple occurances means we need to check this ourselves. See https://github.com/clap-rs/clap/issues/3542.

authored by Thayne McCombs · committed by David Peter · parent 5a12a5e · Browse files · 2 files+41 added−26 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+41 added−26 removed

  • other:+41 added−26 removed

2 files+41 added−26 removed

modified:src/exec/mod.rs+40 added-25 removed
7 unmodified lines
8use std::path::{Component, Path, PathBuf, Prefix};9use std::process::{Command, Stdio};10use std::sync::{Arc, Mutex};1112use anyhow::{anyhow, Result};12use anyhow::{bail, Result};13use once_cell::sync::Lazy;14use regex::Regex;1516use crate::exit_codes::ExitCode;
19 unmodified lines
36 commands: Vec<CommandTemplate>,37}3839impl CommandSet {40 pub fn new<I, S>(input: I, path_separator: Option<String>) -> CommandSet40 pub fn new<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>41 where42 I: IntoIterator<Item = Vec<S>>,43 S: AsRef<str>,44 {45 CommandSet {45 Ok(CommandSet {46 mode: ExecutionMode::OneByOne,47 path_separator,48 commands: input.into_iter().map(CommandTemplate::new).collect(),49 }48 commands: input49 .into_iter()50 .map(CommandTemplate::new)51 .collect::<Result<_>>()?,52 })53 }5455 pub fn new_batch<I, S>(input: I, path_separator: Option<String>) -> Result<CommandSet>56 where
5 unmodified lines
62 path_separator,63 commands: input64 .into_iter()65 .map(|args| {63 let cmd = CommandTemplate::new(args);66 let cmd = CommandTemplate::new(args)?;67 if cmd.number_of_tokens() > 1 {65 return Err(anyhow!("Only one placeholder allowed for batch commands"));68 bail!("Only one placeholder allowed for batch commands");69 }70 if cmd.args[0].has_tokens() {68 return Err(anyhow!(69 "First argument of exec-batch is expected to be a fixed executable"70 ));71 bail!("First argument of exec-batch is expected to be a fixed executable");72 }73 Ok(cmd)74 })75 .collect::<Result<Vec<_>>>()?,
3 unmodified lines
79 pub fn in_batch_mode(&self) -> bool {80 self.mode == ExecutionMode::Batch81 }8282 pub fn execute(83 &self,84 input: &Path,85 mut out_perm: Arc<Mutex<()>>,86 buffer_output: bool,87 ) -> ExitCode {83 pub fn execute(&self, input: &Path, out_perm: Arc<Mutex<()>>, buffer_output: bool) -> ExitCode {84 let path_separator = self.path_separator.as_deref();85 let commands = self86 .commands87 .iter()88 .map(|c| c.generate(input, path_separator));93 execute_commands(commands, &mut out_perm, buffer_output)89 execute_commands(commands, &out_perm, buffer_output)90 }9192 pub fn execute_batch<I>(&self, paths: I) -> ExitCode93 where
21 unmodified lines
115 args: Vec<ArgumentTemplate>,116}117118impl CommandTemplate {123 fn new<I, S>(input: I) -> CommandTemplate119 fn new<I, S>(input: I) -> Result<CommandTemplate>120 where121 I: IntoIterator<Item = S>,122 S: AsRef<str>,123 {
42 unmodified lines
166167 args.push(ArgumentTemplate::Tokens(tokens));168 }169170 // We need to check that we have at least one argument, because if not171 // it will try to execute each file and directory it finds.172 //173 // Sadly, clap can't currently handle this for us, see174 // https://github.com/clap-rs/clap/issues/3542175 if args.is_empty() {176 bail!("No executable provided for --exec or --exec-batch");177 }178179 // If a placeholder token was not supplied, append one at the end of the command.180 if !has_placeholder {181 args.push(ArgumentTemplate::Tokens(vec![Token::Placeholder]));182 }183179 CommandTemplate { args }184 Ok(CommandTemplate { args })185 }186187 fn number_of_tokens(&self) -> usize {188 self.args.iter().filter(|arg| arg.has_tokens()).count()
156 unmodified lines
345346 #[test]347 fn tokens_with_placeholder() {348 assert_eq!(344 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None),349 CommandSet::new(vec![vec![&"echo", &"${SHELL}:"]], None).unwrap(),350 CommandSet {351 commands: vec![CommandTemplate {352 args: vec![353 ArgumentTemplate::Text("echo".into()),
9 unmodified lines
363364 #[test]365 fn tokens_with_no_extension() {366 assert_eq!(362 CommandSet::new(vec![vec!["echo", "{.}"]], None),367 CommandSet::new(vec![vec!["echo", "{.}"]], None).unwrap(),368 CommandSet {369 commands: vec![CommandTemplate {370 args: vec![371 ArgumentTemplate::Text("echo".into()),
8 unmodified lines
380381 #[test]382 fn tokens_with_basename() {383 assert_eq!(379 CommandSet::new(vec![vec!["echo", "{/}"]], None),384 CommandSet::new(vec![vec!["echo", "{/}"]], None).unwrap(),385 CommandSet {386 commands: vec![CommandTemplate {387 args: vec![388 ArgumentTemplate::Text("echo".into()),
8 unmodified lines
397398 #[test]399 fn tokens_with_parent() {400 assert_eq!(396 CommandSet::new(vec![vec!["echo", "{//}"]], None),401 CommandSet::new(vec![vec!["echo", "{//}"]], None).unwrap(),402 CommandSet {403 commands: vec![CommandTemplate {404 args: vec![405 ArgumentTemplate::Text("echo".into()),
8 unmodified lines
414415 #[test]416 fn tokens_with_basename_no_extension() {417 assert_eq!(413 CommandSet::new(vec![vec!["echo", "{/.}"]], None),418 CommandSet::new(vec![vec!["echo", "{/.}"]], None).unwrap(),419 CommandSet {420 commands: vec![CommandTemplate {421 args: vec![422 ArgumentTemplate::Text("echo".into()),
8 unmodified lines
431432 #[test]433 fn tokens_multiple() {434 assert_eq!(430 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None),435 CommandSet::new(vec![vec!["cp", "{}", "{/.}.ext"]], None).unwrap(),436 CommandSet {437 commands: vec![CommandTemplate {438 args: vec![439 ArgumentTemplate::Text("cp".into()),
32 unmodified lines
472 assert!(CommandSet::new_batch(vec![vec!["echo", "{.}", "{}"]], None).is_err());473 }474475 #[test]476 fn template_no_args() {477 assert!(CommandTemplate::new::<Vec<_>, &'static str>(vec![]).is_err());478 }479480 #[test]481 fn command_set_no_args() {482 assert!(CommandSet::new(vec![vec!["echo"], vec![]], None).is_err());483 }484485 #[test]486 fn generate_custom_path_separator() {487 let arg = ArgumentTemplate::Tokens(vec![Token::Placeholder]);488 macro_rules! check {489 ($input:expr, $expected:expr) => {
37 unmodified lines
modified:src/main.rs+1 added-1 removed
392 unmodified lines
393) -> Result<Option<CommandSet>> {394 None.or_else(|| {395 matches396 .grouped_values_of("exec")397 .map(|args| Ok(CommandSet::new(args, path_separator.map(str::to_string))))397 .map(|args| CommandSet::new(args, path_separator.map(str::to_string)))398 })399 .or_else(|| {400 matches401 .grouped_values_of("exec-batch")
163 unmodified lines