Parse --shell option value as shell command
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by rhysd · committed by David Peter · parent 5c6879e · Browse files · 7 files·+96 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+96 added−20 removed
- other:+96 added−20 removed
Provenance
- Commit
e2fdace- Tree
eaaccaa- Author
rhysd <lin90162@yahoo.co.jp>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
5c6879e
7 files changed+96 added−20 removed
modified:src/benchmark.rs+6 added-6 removed
7 unmodified lines8 use crate::benchmark_result::BenchmarkResult;9 use crate::command::Command;10 use crate::format::{format_duration, format_duration_unit};11 use crate::min_max::{max, min};12-use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};12+use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Shell};13 use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14 use crate::progress_bar::get_progress_bar;15 use crate::shell::execute_and_time;16 use crate::timer::wallclocktimer::WallClockTimer;27 unmodified lines44 }45 46 /// Run the given shell command and measure the execution time47 pub fn time_shell_command(48- shell: &str,48+ shell: &Shell,49 command: &Command<'_>,50 show_output: bool,51 failure_action: CmdFailureAction,52 shell_spawning_time: Option<TimingResult>,44 unmodified lines97 }98 99 /// Measure the average shell spawning time100 pub fn mean_shell_spawning_time(101- shell: &str,101+ shell: &Shell,102 style: OutputStyleOption,103 show_output: bool,104 ) -> io::Result<TimingResult> {105 const COUNT: u64 = 50;61 unmodified lines167 })168 }169 170 fn run_intermediate_command(171- shell: &str,171+ shell: &Shell,172 command: &Option<Command<'_>>,173 show_output: bool,174 error_output: &'static str,175 ) -> io::Result<TimingResult> {10 unmodified lines186 }187 188 /// Run the command specified by `--prepare`.189 fn run_preparation_command(190- shell: &str,190+ shell: &Shell,191 command: &Option<Command<'_>>,192 show_output: bool,193 ) -> io::Result<TimingResult> {194 let error_output = "The preparation command terminated with a non-zero exit code. \3 unmodified lines198 }199 200 /// Run the command specified by `--cleanup`.201 fn run_cleanup_command(202- shell: &str,202+ shell: &Shell,203 command: &Option<Command<'_>>,204 show_output: bool,205 ) -> io::Result<TimingResult> {206 let error_output = "The cleanup command terminated with a non-zero exit code. \282 unmodified linesmodified:src/error.rs+6 added
60 unmodified lines61 EmptyRunsRange,62 TooManyCommandNames(usize),63 UnexpectedCommandNameCount(usize, usize),64 NumericParsingError(&'a str, ParseIntError),65+ EmptyShell,66+ ShellParseError(shell_words::ParseError),67 }68 69 impl<'a> fmt::Display for OptionsError<'a> {70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {15 unmodified lines86 "Could not read numeric argument to '--{cmd}': {err}",87 cmd = cmd,88 err = err89 ),90+ OptionsError::EmptyShell => write!(f, "Empty command at --shell option"),91+ OptionsError::ShellParseError(ref err) => {92+ write!(f, "Could not parse --shell value as command line: {}", err)93+ }94 }95 }96 }97 1 unmodified linemodified:src/main.rs+4 added-5 removed
31 unmodified lines32 use benchmark_result::BenchmarkResult;33 use command::Command;34 use error::OptionsError;35 use export::{ExportManager, ExportType};36-use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};36+use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Shell};37 use parameter_range::get_parameterized_commands;38 use tokenize::tokenize;39 use types::ParameterValue;40 use units::Unit;187 unmodified lines228 OutputStyleOption::Full | OutputStyleOption::Color => colored::control::set_override(true),229 OutputStyleOption::Disabled => {}230 };231 232- options.shell = matches233- .value_of("shell")234- .unwrap_or(&options.shell)235- .to_string();232+ if let Some(shell) = matches.value_of("shell") {233+ options.shell = Shell::parse(shell)?;234+ }235 236 if matches.is_present("ignore-failure") {237 options.failure_action = CmdFailureAction::Ignore;238 }221 unmodified linesmodified:src/options.rs+62 added-2 removed
1+use std::fmt;2+use std::process::Command;3+4+use crate::error::OptionsError;5 use crate::units::{Second, Unit};6 7 #[cfg(not(windows))]8 pub const DEFAULT_SHELL: &str = "sh";9 10 #[cfg(windows)]11 pub const DEFAULT_SHELL: &str = "cmd.exe";12 13+/// Shell to use for executing benchmarked commands14+pub enum Shell {15+ /// Default shell command16+ Default(&'static str),17+ /// Custom shell command specified via --shell18+ Custom(Vec<String>),19+}20+21+impl Default for Shell {22+ fn default() -> Self {23+ Shell::Default(DEFAULT_SHELL)24+ }25+}26+27+impl fmt::Display for Shell {28+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {29+ match self {30+ Shell::Default(cmd) => write!(f, "{}", cmd),31+ Shell::Custom(cmdline) => {32+ let mut first = true;33+ for s in cmdline.iter() {34+ if first {35+ first = false;36+ write!(f, "{}", s)?;37+ } else {38+ write!(f, " {}", s)?;39+ }40+ }41+ Ok(())42+ }43+ }44+ }45+}46+47+impl Shell {48+ /// Parse given string as shell command line49+ pub fn parse<'a>(s: &str) -> Result<Self, OptionsError<'a>> {50+ let v = shell_words::split(s.as_ref()).map_err(OptionsError::ShellParseError)?;51+ if v.is_empty() {52+ return Err(OptionsError::EmptyShell);53+ }54+ Ok(Shell::Custom(v))55+ }56+57+ pub fn command(&self) -> Command {58+ match self {59+ Shell::Default(cmd) => Command::new(cmd),60+ Shell::Custom(cmdline) => {61+ let mut c = Command::new(&cmdline[0]);62+ c.args(&cmdline[1..]);63+ c64+ }65+ }66+ }67+}68+69 /// Action to take when an executed command fails.70 #[derive(Debug, Clone, Copy, PartialEq)]71 pub enum CmdFailureAction {72 /// Exit with an error message60 unmodified lines133 /// What color mode to use for output134 pub output_style: OutputStyleOption,135 136 /// The shell to use for executing commands.77- pub shell: String,137+ pub shell: Shell,138 139 /// Forward benchmark's stdout to hyperfine's stdout140 pub show_output: bool,141 16 unmodified lines158 failure_action: CmdFailureAction::RaiseError,159 preparation_command: None,160 cleanup_command: None,161 output_style: OutputStyleOption::Full,102- shell: DEFAULT_SHELL.to_string(),162+ shell: Shell::default(),163 show_output: false,164 time_unit: None,165 }166 }1 unmodified linemodified:src/shell.rs+10 added-7 removed
1 use std::io;2-use std::process::{Command, ExitStatus, Stdio};2+use std::process::{ExitStatus, Stdio};3 4+use crate::options::Shell;5 use crate::timer::get_cpu_timer;6 7 /// Used to indicate the result of running a command8 #[derive(Debug, Copy, Clone)]13 unmodified lines22 pub fn execute_and_time(23 stdout: Stdio,24 stderr: Stdio,25 command: &str,25- shell: &str,26+ shell: &Shell,27 ) -> io::Result<ExecuteResult> {28 let mut child = run_shell_command(stdout, stderr, command, shell)?;29 let cpu_timer = get_cpu_timer(&child);30 let status = child.wait()?;11 unmodified lines42 pub fn execute_and_time(43 stdout: Stdio,44 stderr: Stdio,45 command: &str,45- shell: &str,46+ shell: &Shell,47 ) -> io::Result<ExecuteResult> {48 let cpu_timer = get_cpu_timer();49 50 let status = run_shell_command(stdout, stderr, command, shell)?;12 unmodified lines63 fn run_shell_command(64 stdout: Stdio,65 stderr: Stdio,66 command: &str,66- shell: &str,67+ shell: &Shell,68 ) -> io::Result<std::process::ExitStatus> {68- Command::new(shell)69+ shell70+ .command()71 .arg("-c")72 .arg(command)73 .env(74 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",10 unmodified lines85 fn run_shell_command(86 stdout: Stdio,87 stderr: Stdio,88 command: &str,87- shell: &str,89+ shell: &Shell,90 ) -> io::Result<std::process::Child> {89- Command::new(shell)91+ shell92+ .command()93 .arg("/C")94 .arg(command)95 .stdin(Stdio::null())96 .stdout(stdout)3 unmodified linesmodified:Cargo.lock+7 added
241 unmodified lines242 "rand 0.8.4",243 "rust_decimal",244 "serde",245 "serde_json",246+ "shell-words",247 "statistical",248 "tempfile",249 "winapi",250 ]430 unmodified lines681 "serde",682 ]683 684 [[package]]685+name = "shell-words"686+version = "1.0.0"687+source = "registry+https://github.com/rust-lang/crates.io-index"688+checksum = "b6fa3938c99da4914afedd13bf3d79bcb6c277d1b2c398d23257a304d9e1b074"689+690+[[package]]691 name = "statistical"692 version = "1.0.0"693 source = "registry+https://github.com/rust-lang/crates.io-index"694 checksum = "49d57902bb128e5e38b5218d3681215ae3e322d99f65d5420e9849730d2ea372"126 unmodified linesmodified:Cargo.toml+1 added
19 unmodified lines20212223242526272820 unmodified lines19 unmodified linesserde = { version = "1.0", features = ["derive"] }serde_json = "1.0"rust_decimal = "1.16"rand = "0.8"shell-words = "1.0"
[target.'cfg(not(windows))'.dependencies]libc = "0.2"
20 unmodified lines