Move Command struct to new module
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 b5bd054 · Browse files · 6 files·+130 added−120 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+130 added−120 removed
- other:+130 added−120 removed
Provenance
- Commit
eee3230- Tree
ccfdecf- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
b5bd054
6 files changed+130 added−120 removed
modified:src/hyperfine/benchmark.rs+2 added-1 removed
3 unmodified lines4 5 use colored::*;6 use statistical::{mean, median, standard_deviation};7 8+use crate::hyperfine::command::Command;9 use crate::hyperfine::format::{format_duration, format_duration_unit};10 use crate::hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};11 use crate::hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};12 use crate::hyperfine::shell::execute_and_time;13 use crate::hyperfine::timer::wallclocktimer::WallClockTimer;14 use crate::hyperfine::timer::{TimerStart, TimerStop};15 use crate::hyperfine::types::{15- BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,16+ BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption,17 };18 use crate::hyperfine::units::Second;19 use crate::hyperfine::warnings::Warnings;20 465 unmodified linesadded:src/hyperfine/command.rs+115 added
1+use std::collections::BTreeMap;2+use std::fmt;3+4+use super::types::ParameterValue;5+6+/// A command that should be benchmarked.7+#[derive(Debug, Clone, PartialEq, Eq)]8+pub struct Command<'a> {9+ /// The command name (without parameter substitution)10+ name: Option<&'a str>,11+12+ /// The command that should be executed (without parameter substitution)13+ expression: &'a str,14+15+ /// Zero or more parameter values.16+ parameters: Vec<(&'a str, ParameterValue)>,17+}18+19+impl<'a> Command<'a> {20+ pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {21+ Command {22+ name,23+ expression,24+ parameters: Vec::new(),25+ }26+ }27+28+ pub fn new_parametrized(29+ name: Option<&'a str>,30+ expression: &'a str,31+ parameters: Vec<(&'a str, ParameterValue)>,32+ ) -> Command<'a> {33+ Command {34+ name,35+ expression,36+ parameters,37+ }38+ }39+40+ pub fn get_name(&self) -> String {41+ self.name.map_or_else(42+ || self.get_shell_command(),43+ |name| self.replace_parameters_in(name),44+ )45+ }46+47+ pub fn get_shell_command(&self) -> String {48+ self.replace_parameters_in(self.expression)49+ }50+51+ pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52+ &self.parameters53+ }54+55+ fn replace_parameters_in(&self, original: &str) -> String {56+ let mut result = String::new();57+ let mut replacements = BTreeMap::<String, String>::new();58+ for (param_name, param_value) in &self.parameters {59+ replacements.insert(60+ format!("{{{param_name}}}", param_name = param_name),61+ param_value.to_string(),62+ );63+ }64+ let mut remaining = original;65+ // Manually replace consecutive occurrences to avoid double-replacing: e.g.,66+ //67+ // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'68+ //69+ // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.70+ 'outer: while let Some(head) = remaining.chars().next() {71+ for (k, v) in &replacements {72+ if remaining.starts_with(k.as_str()) {73+ result.push_str(v);74+ remaining = &remaining[k.len()..];75+ continue 'outer;76+ }77+ }78+ result.push(head);79+ remaining = &remaining[head.len_utf8()..];80+ }81+ result82+ }83+}84+85+#[test]86+fn test_get_shell_command_nonoverlapping() {87+ let cmd = Command::new_parametrized(88+ None,89+ "echo {foo} {bar}",90+ vec![91+ ("foo", ParameterValue::Text("{bar} baz".into())),92+ ("bar", ParameterValue::Text("quux".into())),93+ ],94+ );95+ assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");96+}97+98+#[test]99+fn test_get_parameterized_command_name() {100+ let cmd = Command::new_parametrized(101+ Some("name-{bar}-{foo}"),102+ "echo {foo} {bar}",103+ vec![104+ ("foo", ParameterValue::Text("baz".into())),105+ ("bar", ParameterValue::Text("quux".into())),106+ ],107+ );108+ assert_eq!(cmd.get_name(), "name-quux-baz");109+}110+111+impl<'a> fmt::Display for Command<'a> {112+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {113+ write!(f, "{}", self.get_shell_command())114+ }115+}modified:src/hyperfine/mod.rs+1 added
1 pub mod app;2 pub mod benchmark;3+pub mod command;4 pub mod error;5 pub mod export;6 pub mod format;7 pub mod internal;7 unmodified linesmodified:src/hyperfine/parameter_range.rs+7 added-4 removed
1-use crate::hyperfine::error::ParameterScanError;2-use crate::hyperfine::types::{Command, NumericType, ParameterValue};3-use clap::Values;4-use rust_decimal::Decimal;1 use std::convert::TryInto;2 use std::ops::{Add, AddAssign, Div, Sub};3 use std::str::FromStr;4 5+use clap::Values;6+use rust_decimal::Decimal;7+8+use crate::hyperfine::command::Command;9+use crate::hyperfine::error::ParameterScanError;10+use crate::hyperfine::types::{NumericType, ParameterValue};11+12 trait Numeric:13 Add<Output = Self>14 + Sub<Output = Self>15 + Div<Output = Self>302 unmodified linesmodified:src/hyperfine/types.rs+3 added-114 removed
1-use rust_decimal::prelude::ToPrimitive;2-use rust_decimal::Decimal;3-/// This module contains common internal types.1 use serde::*;2 use std::collections::BTreeMap;3 use std::convert::TryFrom;4 use std::fmt;5 6+use rust_decimal::prelude::ToPrimitive;7+use rust_decimal::Decimal;8+9 use crate::hyperfine::units::{Second, Unit};10 11 #[cfg(not(windows))]12 pub const DEFAULT_SHELL: &str = "sh";57 unmodified lines70 }71 }72 }73 74-/// A command that should be benchmarked.75-#[derive(Debug, Clone, PartialEq, Eq)]76-pub struct Command<'a> {77- /// The command name (without parameter substitution)78- name: Option<&'a str>,79-80- /// The command that should be executed (without parameter substitution)81- expression: &'a str,82-83- /// Zero or more parameter values.84- parameters: Vec<(&'a str, ParameterValue)>,85-}86-87-impl<'a> Command<'a> {88- pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {89- Command {90- name,91- expression,92- parameters: Vec::new(),93- }94- }95-96- pub fn new_parametrized(97- name: Option<&'a str>,98- expression: &'a str,99- parameters: Vec<(&'a str, ParameterValue)>,100- ) -> Command<'a> {101- Command {102- name,103- expression,104- parameters,105- }106- }107-108- pub fn get_name(&self) -> String {109- self.name.map_or_else(110- || self.get_shell_command(),111- |name| self.replace_parameters_in(name),112- )113- }114-115- pub fn get_shell_command(&self) -> String {116- self.replace_parameters_in(self.expression)117- }118-119- pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {120- &self.parameters121- }122-123- fn replace_parameters_in(&self, original: &str) -> String {124- let mut result = String::new();125- let mut replacements = BTreeMap::<String, String>::new();126- for (param_name, param_value) in &self.parameters {127- replacements.insert(128- format!("{{{param_name}}}", param_name = param_name),129- param_value.to_string(),130- );131- }132- let mut remaining = original;133- // Manually replace consecutive occurrences to avoid double-replacing: e.g.,134- //135- // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'136- //137- // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.138- 'outer: while let Some(head) = remaining.chars().next() {139- for (k, v) in &replacements {140- if remaining.starts_with(k.as_str()) {141- result.push_str(v);142- remaining = &remaining[k.len()..];143- continue 'outer;144- }145- }146- result.push(head);147- remaining = &remaining[head.len_utf8()..];148- }149- result150- }151-}152-153-#[test]154-fn test_get_shell_command_nonoverlapping() {155- let cmd = Command::new_parametrized(156- None,157- "echo {foo} {bar}",158- vec![159- ("foo", ParameterValue::Text("{bar} baz".into())),160- ("bar", ParameterValue::Text("quux".into())),161- ],162- );163- assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");164-}165-166-#[test]167-fn test_get_parameterized_command_name() {168- let cmd = Command::new_parametrized(169- Some("name-{bar}-{foo}"),170- "echo {foo} {bar}",171- vec![172- ("foo", ParameterValue::Text("baz".into())),173- ("bar", ParameterValue::Text("quux".into())),174- ],175- );176- assert_eq!(cmd.get_name(), "name-quux-baz");177-}178-179-impl<'a> fmt::Display for Command<'a> {180- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {181- write!(f, "{}", self.get_shell_command())182- }183-}184-74 /// Action to take when an executed command fails.75 #[derive(Debug, Clone, Copy, PartialEq)]76 pub enum CmdFailureAction {77 /// Exit with an error message168 unmodified linesmodified:src/main.rs+2 added-1 removed
9 unmodified lines10 mod hyperfine;11 12 use crate::hyperfine::app::get_arg_matches;13 use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};14+use crate::hyperfine::command::Command;15 use crate::hyperfine::error::OptionsError;16 use crate::hyperfine::export::{ExportManager, ExportType};17 use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};18 use crate::hyperfine::parameter_range::get_parameterized_commands;19 use crate::hyperfine::types::{19- CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,20+ CmdFailureAction, HyperfineOptions, OutputStyleOption, ParameterValue,21 };22 use crate::hyperfine::units::Unit;23 24 /// Print error message to stderr and terminate384 unmodified lines