Added --stdin-data argument
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This argument accepts a path to a file. The data contained in the file will be passed to the command via stdin. Closes sharkdp/hyperfine#541
authored by Steve Nease · committed by David Peter · parent 531fee3 · Browse files · 6 files·+91 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+91 added−3 removed
- tests:+29 added−0 removed
- other:+62 added−3 removed
Provenance
- Commit
e38acdb- Tree
17f6dfc- Author
Steve Nease <stephen.h.nease@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
531fee3
6 files changed+91 added−3 removed
modified:src/benchmark/executor.rs+6 added-2 removed
1 use std::process::{ExitStatus, Stdio};2 3 use crate::command::Command;4-use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};4+use crate::options::{CmdFailureAction, CommandInputPolicy, CommandOutputPolicy, Options, OutputStyleOption, Shell};5 use crate::output::progress_bar::get_progress_bar;6 use crate::timer::{execute_and_measure, TimerResult};7 use crate::util::randomized_environment_offset;8 use crate::util::units::Second;26 unmodified lines35 36 fn run_command_and_measure_common(37 mut command: std::process::Command,38 command_failure_action: CmdFailureAction,39+ command_input_policy: &CommandInputPolicy,40 command_output_policy: &CommandOutputPolicy,41 command_name: &str,42 ) -> Result<TimerResult> {43 let (stdout, stderr) = command_output_policy.get_stdout_stderr()?;44+ let stdin = command_input_policy.get_stdin()?;43- command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);45+ command.stdin(stdin).stdout(stdout).stderr(stderr);46 47 command.env(48 "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",49 randomized_environment_offset::value(),34 unmodified lines84 ) -> Result<(TimingResult, ExitStatus)> {85 let result = run_command_and_measure_common(86 command.get_command()?,87 command_failure_action.unwrap_or(self.options.command_failure_action),88+ &self.options.command_input_policy,89 &self.options.command_output_policy,90 &command.get_command_line(),91 )?;92 51 unmodified lines144 145 let mut result = run_command_and_measure_common(146 command_builder,147 command_failure_action.unwrap_or(self.options.command_failure_action),148+ &self.options.command_input_policy,149 &self.options.command_output_policy,150 &command.get_command_line(),151 )?;152 145 unmodified linesmodified:src/cli.rs+8 added
310 unmodified lines311 .action(ArgAction::SetTrue)312 .hide(true)313 .help("Enable debug mode which does not actually run commands, but returns fake times when the command is 'sleep <time>'.")314 )315+ .arg(316+ Arg::new("stdin-data")317+ .long("stdin-data")318+ .takes_value(true)319+ .number_of_values(1)320+ .value_name("FILE")321+ .help("Path to file containing stdin data to provide to the command"),322+ )323 }324 325 #[test]326 fn verify_app() {2 unmodified linesmodified:src/error.rs+2 added
51 unmodified lines52 #[error("Failed to parse '--shell <command>' expression as command line: {0}")]53 ShellParseError(shell_words::ParseError),54 #[error("Unknown output policy '{0}'. Use './{0}' to output to a file named '{0}'.")]55 UnknownOutputPolicy(String),56+ #[error("File containing stdin data '{0}' does not exist")]57+ StdinDataFileDoesNotExist(String),58 }modified:src/options.rs+46 added-1 removed
108 unmodified lines109 RunBounds { min: 10, max: None }110 }111 }112 113+#[derive(Debug, Clone, PartialEq)]114+pub enum CommandInputPolicy {115+ /// Redirect from the null device116+ Null,117+118+ /// Redirect input from a file119+ File(PathBuf),120+}121+122+impl Default for CommandInputPolicy {123+ fn default() -> Self {124+ CommandInputPolicy::Null125+ }126+}127+128+impl CommandInputPolicy {129+ pub fn get_stdin(&self) -> io::Result<Stdio> {130+ let stream: Stdio = match self {131+ CommandInputPolicy::Null => Stdio::null(),132+133+ CommandInputPolicy::File(path) => {134+ let file: File = File::open(&path)?;135+ Stdio::from(file)136+ }137+ };138+139+ Ok(stream)140+ }141+}142+143 /// How to handle the output of benchmarked commands144 #[derive(Debug, Clone, PartialEq, Eq)]145 pub enum CommandOutputPolicy {146 /// Redirect output to the null device78 unmodified lines225 226 /// What to do with the output of the benchmarked command227 pub command_output_policy: CommandOutputPolicy,228 199- /// Which time unit to use when displaying resuls229+ /// Which time unit to use when displaying results230 pub time_unit: Option<Unit>,231+232+ /// Where input to the benchmarked command comes from233+ pub command_input_policy: CommandInputPolicy,234+235 }236 237 impl Default for Options {238 fn default() -> Options {8 unmodified lines247 output_style: OutputStyleOption::Full,248 executor_kind: ExecutorKind::default(),249 command_output_policy: CommandOutputPolicy::Null,250 time_unit: None,251+ command_input_policy: CommandInputPolicy::Null,252 }253 }254 }255 132 unmodified lines388 .parse::<f64>()389 .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?;390 }391 392+ options.command_input_policy = if let Some(path_str) = matches.value_of("stdin-data") {393+ let path = PathBuf::from(path_str);394+ if !path.exists() {395+ return Err(OptionsError::StdinDataFileDoesNotExist(path_str.to_string()))396+ }397+ CommandInputPolicy::File(path)398+ } else {399+ CommandInputPolicy::Null400+ };401+402 Ok(options)403 }404 405 pub fn validate_against_command_list(&self, commands: &Commands) -> Result<()> {56 unmodified linesadded:tests/example_stdin_data+1 added
1+This data is passed to the command via stdinmodified:tests/integration_tests.rs+28 added
214 unmodified lines215 );216 }217 218 #[test]219+fn can_pass_file_data_to_command_via_stdin(){220+ hyperfine()221+ .arg("--runs=1")222+ .arg("--stdin-data=example_stdin_data")223+ .arg("--show-output")224+ .arg("cat")225+ .assert()226+ .success()227+ .stdout(228+ predicate::str::contains("This data is passed to the command via stdin")229+ );230+}231+232+#[test]233+fn fails_if_invalid_stdin_data_file_provided(){234+ hyperfine()235+ .arg("--runs=1")236+ .arg("--stdin-data=example_stdin_data_invalid")237+ .arg("--show-output")238+ .arg("cat")239+ .assert()240+ .failure()241+ .stderr(242+ predicate::str::contains("File containing stdin data 'example_stdin_data_invalid' does not exist")243+ );244+}245+246+#[test]247 fn returns_mean_time_in_correct_unit() {248 hyperfine_debug()249 .arg("sleep 1.234")250 .assert()99 unmodified lines