Require an explicit shell choice for shell operators
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent e8cdbf2 · Browse files · 4 files·+282 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+282 added−2 removed
- tests:+36 added−0 removed
- other:+246 added−2 removed
Provenance
- Commit
6cb7bb0- Tree
bfdb8b1- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
e8cdbf2
4 files changed+282 added−2 removed
modified:src/main.rs+24 added-2 removed
9 unmodified lines10 use cli::get_cli_arguments;11 use command::Commands;12 use error::ConsoleOutputError;13 use export::ExportManager;14-use options::Options;14+use options::{ExecutorKind, Options};15 16-use anyhow::Result;16+use anyhow::{bail, Result};17 use colored::*;18 19 pub mod benchmark;20 pub mod cli;5 unmodified lines26 pub mod outlier_detection;27 pub mod output;28 pub mod parameter;29 pub mod quantity;30+pub mod shell_syntax;31 pub mod timer;32 pub mod util;33 34 fn run() -> Result<()> {5 unmodified lines40 let mut options = Options::from_cli_arguments(&cli_arguments)?;41 let commands = Commands::from_cli_arguments(&cli_arguments)?;42 options.validate_against_command_list(&commands)?;43 44+ if matches!(options.executor_kind, ExecutorKind::Raw)45+ && !cli_arguments.get_flag("no-shell")46+ && cli_arguments.get_one::<String>("shell").is_none()47+ {48+ for command in commands.iter() {49+ let command_line = command.get_command_line();50+ if let Some(operator) = shell_syntax::first_unquoted_operator(&command_line) {51+ bail!(52+ concat!(53+ "Command '{command_line}' contains unquoted shell syntax ('{operator}').\n",54+ "Explicitly choose how to execute it:\n",55+ " -S / --shell=default Interpret shell syntax.\n",56+ " -N / --shell=none Run directly, passing '{operator}' as a literal argument.",57+ ),58+ command_line = command_line,59+ operator = operator,60+ );61+ }62+ }63+ }64+65 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;66 67 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);68 scheduler.run_benchmarks()?;26 unmodified linesadded:src/shell_syntax.rs+218 added
1+//! Conservative detection of shell operators in commands run without a shell.2+3+use std::iter::Peekable;4+use std::str::CharIndices;5+6+/// Find the first standalone operator that is neither quoted nor escaped.7+///8+/// Operators attached to another word (such as `hello>out`), expansions, and9+/// other shell syntax are deliberately outside the scope of this check.10+pub fn first_unquoted_operator(command: &str) -> Option<&'static str> {11+ tokenize(command).find_map(|token| {12+ ["&&", "||", "|", ";", ">", ">>", "<"]13+ .iter()14+ .copied()15+ .find(|operator| {16+ // An escaped newline joins lines without quoting either side.17+ // All other quotes and escapes remain in the token, preventing18+ // it from matching an operator.19+ token20+ .split("\\\n")21+ .flat_map(str::bytes)22+ .eq(operator.bytes())23+ })24+ })25+}26+27+/// Split words while preserving their original quoting and escaping.28+///29+/// Word boundaries and comments follow the same rules as `shell_words`, which30+/// parses commands for direct execution. This tokenizer neither expands shell31+/// expressions nor validates balanced quotes; command parsing handles errors.32+fn tokenize(command: &str) -> impl Iterator<Item = &str> {33+ Tokens {34+ command,35+ chars: command.char_indices().peekable(),36+ }37+}38+39+struct Tokens<'a> {40+ command: &'a str,41+ chars: Peekable<CharIndices<'a>>,42+}43+44+impl<'a> Iterator for Tokens<'a> {45+ type Item = &'a str;46+47+ fn next(&mut self) -> Option<Self::Item> {48+ // Whitespace, comments, and line continuations cannot start a word.49+ let start = loop {50+ let &(index, character) = self.chars.peek()?;51+ match character {52+ ' ' | '\t' | '\n' => {53+ self.chars.next();54+ }55+ '#' => {56+ for (_, character) in self.chars.by_ref() {57+ if character == '\n' {58+ break;59+ }60+ }61+ }62+ '\\' if self.chars.clone().nth(1).map(|(_, c)| c) == Some('\n') => {63+ self.chars.next();64+ self.chars.next();65+ }66+ _ => break index,67+ }68+ };69+70+ let mut quote = None;71+ while let Some((index, character)) = self.chars.next() {72+ match (quote, character) {73+ (Some('\''), '\'') | (Some('"'), '"') => quote = None,74+ (Some('\''), _) => {}75+ (_, '\\') => {76+ // Within double quotes, skipping a non-special escaped77+ // character is also safe: it cannot end the quoted word.78+ self.chars.next();79+ }80+ (Some('"'), _) => {}81+ (None, '\'' | '"') => quote = Some(character),82+ (None, ' ' | '\t' | '\n') => return Some(&self.command[start..index]),83+ _ => {}84+ }85+ }86+87+ Some(&self.command[start..])88+ }89+}90+91+#[cfg(test)]92+mod tests {93+ use super::{first_unquoted_operator, tokenize};94+95+ #[test]96+ fn tokenizer_preserves_words_quotes_and_escapes() {97+ for (command, expected) in [98+ ("", vec![]),99+ (" \t\n", vec![]),100+ (" echo\thello\nworld ", vec!["echo", "hello", "world"]),101+ (102+ r#"echo '' "" 'hello world'"#,103+ vec!["echo", "''", "\"\"", "'hello world'"],104+ ),105+ (106+ r#"echo pre'quoted part'"more"post"#,107+ vec!["echo", r#"pre'quoted part'"more"post"#],108+ ),109+ (110+ r"echo hello\ world \&\&",111+ vec!["echo", r"hello\ world", r"\&\&"],112+ ),113+ (r#"echo "a\" b" 'a\'"#, vec!["echo", r#""a\" b""#, r"'a\'"]),114+ ("echo hello>out", vec!["echo", "hello>out"]),115+ (116+ "echo café\t&&\n日本語",117+ vec!["echo", "café", "&&", "日本語"],118+ ),119+ ("echo a\r\u{a0}b", vec!["echo", "a\r\u{a0}b"]),120+ ] {121+ assert_eq!(122+ tokenize(command).collect::<Vec<_>>(),123+ expected,124+ "{command:?}"125+ );126+ }127+ }128+129+ #[test]130+ fn tokenizer_handles_comments_and_continuations() {131+ for (command, expected) in [132+ ("# ignored &&", vec![]),133+ (134+ "echo # ignored &&\nnext | cat",135+ vec!["echo", "next", "|", "cat"],136+ ),137+ (138+ r##"echo a#b \#c "#d" '#e'"##,139+ vec!["echo", "a#b", r"\#c", "\"#d\"", "'#e'"],140+ ),141+ ("\\\n echo \\\n&& more", vec!["echo", "&&", "more"]),142+ ("echo hello\\\nworld", vec!["echo", "hello\\\nworld"]),143+ ("\\\n# comment\necho", vec!["echo"]),144+ ] {145+ assert_eq!(146+ tokenize(command).collect::<Vec<_>>(),147+ expected,148+ "{command:?}"149+ );150+ }151+ }152+153+ #[test]154+ fn finds_supported_operators_in_command_order() {155+ for operator in ["&&", "||", "|", ";", ">", ">>", "<"] {156+ let command = format!("echo café\t{operator}\n日本語");157+ assert_eq!(first_unquoted_operator(&command), Some(operator));158+ assert_eq!(first_unquoted_operator(operator), Some(operator));159+ }160+ assert_eq!(first_unquoted_operator("echo a >> out && next"), Some(">>"));161+ assert_eq!(first_unquoted_operator("echo \\\n&& next"), Some("&&"));162+ assert_eq!(first_unquoted_operator("echo &\\\n& next"), Some("&&"));163+ assert_eq!(first_unquoted_operator("echo &&\\\n next"), Some("&&"));164+ assert_eq!(first_unquoted_operator("echo # &&\nnext | cat"), Some("|"));165+ assert_eq!(first_unquoted_operator(r#"echo "&&" || next"#), Some("||"));166+ assert_eq!(first_unquoted_operator(r"echo \&\& | cat"), Some("|"));167+ }168+169+ #[test]170+ fn ignores_quoted_escaped_and_attached_operators() {171+ for command in [172+ r#"echo "&&""#,173+ "echo '&&'",174+ r"echo \&\&",175+ r"echo &\&",176+ r#"echo '&'"&""#,177+ r#"echo ""&&"#,178+ "echo &&''",179+ r#"python -c "print(1 > 0)""#,180+ "sh -c 'true && false'",181+ r#"sh -c "echo 'a | b' && false""#,182+ r#"sh -c 'echo "a | b" && false'"#,183+ r#"echo "escaped \" && still quoted""#,184+ "echo hello>out",185+ "true&&false",186+ "echo a;",187+ "echo 2> out",188+ "echo >>> out",189+ "echo $VARIABLE *.rs ~/path NAME=value",190+ "echo # && ignored",191+ "echo foo#bar",192+ "echo\u{a0}&&",193+ "echo &&\r",194+ ] {195+ assert_eq!(first_unquoted_operator(command), None, "{command:?}");196+ }197+ }198+199+ #[test]200+ fn handles_empty_and_malformed_commands_without_panicking() {201+ for (command, expected) in [202+ ("", vec![]),203+ ("\\\n", vec![]),204+ ("\\", vec!["\\"]),205+ (r"echo \", vec!["echo", r"\"]),206+ ("echo 'unclosed &&", vec!["echo", "'unclosed &&"]),207+ ("echo \"unclosed &&", vec!["echo", "\"unclosed &&"]),208+ ("echo \"unclosed\\", vec!["echo", "\"unclosed\\"]),209+ ] {210+ assert_eq!(211+ tokenize(command).collect::<Vec<_>>(),212+ expected,213+ "{command:?}"214+ );215+ assert_eq!(first_unquoted_operator(command), None, "{command:?}");216+ }217+ }218+}modified:tests/integration_tests.rs+36 added
265 unmodified lines266 .stderr(predicate::str::contains("Duplicate parameter names: x"));267 }268 269 #[test]270+fn requires_explicit_shell_for_shell_syntax() {271+ let directory = tempfile::tempdir().unwrap();272+273+ let assert = hyperfine()274+ .current_dir(directory.path())275+ .arg("rm -rf cache/ && ./my_command")276+ .assert()277+ .failure();278+279+ insta::assert_snapshot!(String::from_utf8_lossy(&assert.get_output().stderr), @"280+ Error: Command 'rm -rf cache/ && ./my_command' contains unquoted shell syntax ('&&').281+ Explicitly choose how to execute it:282+ -S / --shell=default Interpret shell syntax.283+ -N / --shell=none Run directly, passing '&&' as a literal argument.284+ ");285+286+ hyperfine()287+ .arg("--show-output")288+ .arg("--command-name=benchmark")289+ .args(["--shell=default", "--runs=1", "echo before && echo after"])290+ .assert()291+ .success()292+ .stdout(predicate::str::contains("before"))293+ .stdout(predicate::str::contains("after"))294+ .stdout(predicate::str::contains("&&").not());295+296+ hyperfine()297+ .arg("--show-output")298+ .arg("--command-name=benchmark")299+ .args(["--shell=none", "--runs=1", "echo before && echo after"])300+ .assert()301+ .success()302+ .stdout(predicate::str::contains("before && echo after"));303+}304+305+#[test]306 fn fails_for_unknown_command() {307 hyperfine()308 .arg("--shell=default")309 .arg("--runs=1")1001 unmodified linesmodified:README.md+4 added
112 unmodified lines113 Shell syntax such as pipes, redirections, environment-variable expansion, `*`, and `~` is not interpreted.114 This avoids shell startup overhead and the noise from correcting for it, especially for fast commands115 (< 5 ms).116 117+Commands containing unquoted, standalone shell operators such as `&&` or `>` require an explicit118+choice: use `-S` / `--shell=default` to interpret shell syntax, or `-N` / `--shell=none` to pass119+the operators as literal arguments.120+121 To enable shell syntax, use `-S` (an alias for `--shell=default`). This selects `sh`122 on Unix (resolved through `PATH`) or `cmd.exe` on Windows:123 ```sh124 hyperfine -S 'sleep 0.1 && echo done'338 unmodified lines