Skip to content
Myr

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

4 files+282 added−2 removed

modified:src/main.rs+24 added-2 removed
9 unmodified lines
10use cli::get_cli_arguments;11use command::Commands;12use error::ConsoleOutputError;13use export::ExportManager;14use options::Options;14use options::{ExecutorKind, Options};1516use anyhow::Result;16use anyhow::{bail, Result};17use colored::*;1819pub mod benchmark;20pub mod cli;
5 unmodified lines
26pub mod outlier_detection;27pub mod output;28pub mod parameter;29pub mod quantity;30pub mod shell_syntax;31pub mod timer;32pub mod util;3334fn run() -> Result<()> {
5 unmodified lines
40 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)?;4344 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 }6465 let export_manager = ExportManager::from_cli_arguments(&cli_arguments, options.metrics[0])?;6667 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);68 scheduler.run_benchmarks()?;
26 unmodified lines
added:src/shell_syntax.rs+218 added
1//! Conservative detection of shell operators in commands run without a shell.23use std::iter::Peekable;4use std::str::CharIndices;56/// 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.10pub 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}2627/// 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.32fn tokenize(command: &str) -> impl Iterator<Item = &str> {33 Tokens {34 command,35 chars: command.char_indices().peekable(),36 }37}3839struct Tokens<'a> {40 command: &'a str,41 chars: Peekable<CharIndices<'a>>,42}4344impl<'a> Iterator for Tokens<'a> {45 type Item = &'a str;4647 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 };6970 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 }8687 Some(&self.command[start..])88 }89}9091#[cfg(test)]92mod tests {93 use super::{first_unquoted_operator, tokenize};9495 #[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 }128129 #[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 }152153 #[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 }168169 #[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 }198199 #[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 lines
266 .stderr(predicate::str::contains("Duplicate parameter names: x"));267}268269#[test]270fn requires_explicit_shell_for_shell_syntax() {271 let directory = tempfile::tempdir().unwrap();272273 let assert = hyperfine()274 .current_dir(directory.path())275 .arg("rm -rf cache/ && ./my_command")276 .assert()277 .failure();278279 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 ");285286 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());295296 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}304305#[test]306fn fails_for_unknown_command() {307 hyperfine()308 .arg("--shell=default")309 .arg("--runs=1")
1001 unmodified lines
modified:README.md+4 added
112 unmodified lines
113Shell syntax such as pipes, redirections, environment-variable expansion, `*`, and `~` is not interpreted.114This avoids shell startup overhead and the noise from correcting for it, especially for fast commands115(< 5 ms).116117Commands containing unquoted, standalone shell operators such as `&&` or `>` require an explicit118choice: use `-S` / `--shell=default` to interpret shell syntax, or `-N` / `--shell=none` to pass119the operators as literal arguments.120121To enable shell syntax, use `-S` (an alias for `--shell=default`). This selects `sh`122on Unix (resolved through `PATH`) or `cmd.exe` on Windows:123```sh124hyperfine -S 'sleep 0.1 && echo done'
338 unmodified lines