options.rs
This file
Path
src/options.rs
543 lines · 17.4 KiB · Rust
Last changed by
Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
History of this fileTake it
The walk stopped after 200 commits: lines older than c44aa1d point at it.
Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 1why, one step back1use std::fs::File;Remove dependency on `atty` and use `std::io::IsTerminal` insteadLenabefore adoption69ee173
line 2why, one step back2use std::io::IsTerminal;Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 3–11why, one step back3use std::path::PathBuf;4use std::process::{Command, Stdio};5use std::{cmp, env, fmt, io};67use anyhow::ensure;8use clap::ArgMatches;910use crate::command::Commands;11use crate::error::OptionsError;Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
line 12why, one step back12use crate::quantity::{second, Time, TimeUnit};Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 13–40why, one step back1314use anyhow::Result;1516#[cfg(not(windows))]17pub const DEFAULT_SHELL: &str = "sh";1819#[cfg(windows)]20pub const DEFAULT_SHELL: &str = "cmd.exe";2122/// Shell to use for executing benchmarked commands23#[derive(Debug, PartialEq)]24pub enum Shell {25 /// Default shell command26 Default(&'static str),2728 /// Custom shell command specified via --shell29 Custom(Vec<String>),30}3132impl Default for Shell {33 fn default() -> Self {34 Shell::Default(DEFAULT_SHELL)35 }36}3738impl fmt::Display for Shell {39 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {40 match self {style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 41why, one step back41 Shell::Default(cmd) => write!(f, "{cmd}"),Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 42–69why, one step back42 Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),43 }44 }45}4647impl Shell {48 /// Parse given string as shell command line49 pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {50 let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;51 if v.is_empty() || v[0].is_empty() {52 return Err(OptionsError::EmptyShell);53 }54 Ok(Shell::Custom(v))55 }5657 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}6869/// Action to take when an executed command fails.Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
line 70why, one step back70#[derive(Debug, Clone, PartialEq, Eq)]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 71–74why, one step back71pub enum CmdFailureAction {72 /// Exit with an error message73 RaiseError,74Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 75–79why, one step back75 /// Ignore all non-zero exit codes76 IgnoreAllFailures,7778 /// Ignore specific exit codes79 IgnoreSpecificFailures(Vec<i32>),Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 80–100why, one step back80}8182/// Output style type option83#[derive(Debug, Clone, Copy, PartialEq, Eq)]84pub enum OutputStyleOption {85 /// Do not output with colors or any special formatting86 Basic,8788 /// Output with full color and formatting89 Full,9091 /// Keep elements such as progress bar, but use no coloring92 NoColor,9394 /// Keep coloring, but use no progress bar95 Color,9697 /// Disable all the output98 Disabled,99}100Add new --sort optionDavid Peterbefore adoptionac617c8
lines 101–106why, one step back101#[derive(Debug, Clone, Copy, PartialEq, Eq)]102pub enum SortOrder {103 Command,104 MeanTime,105}106Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 107–121why, one step back107/// Bounds for the number of benchmark runs108pub struct RunBounds {109 /// Minimum number of benchmark runs110 pub min: u64,111112 /// Maximum number of benchmark runs113 pub max: Option<u64>,114}115116impl Default for RunBounds {117 fn default() -> Self {118 RunBounds { min: 10, max: None }119 }120}121Fix clippy suggestionsDavid Peterbefore adoption1c7a8cc
line 122why, one step back122#[derive(Debug, Default, Clone, PartialEq)]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 123–124why, one step back123pub enum CommandInputPolicy {124 /// Read from the null deviceFix clippy suggestionsDavid Peterbefore adoption1c7a8cc
line 125why, one step back125 #[default]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 126–147why, one step back126 Null,127128 /// Read input from a file129 File(PathBuf),130}131132impl CommandInputPolicy {133 pub fn get_stdin(&self) -> io::Result<Stdio> {134 let stream: Stdio = match self {135 CommandInputPolicy::Null => Stdio::null(),136137 CommandInputPolicy::File(path) => {138 let file: File = File::open(path)?;139 Stdio::from(file)140 }141 };142143 Ok(stream)144 }145}146147/// How to handle the output of benchmarked commandsFix clippy suggestionsDavid Peterbefore adoption1c7a8cc
line 148why, one step back148#[derive(Debug, Clone, PartialEq, Eq, Default)]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 149–150why, one step back149pub enum CommandOutputPolicy {150 /// Redirect output to the null deviceFix clippy suggestionsDavid Peterbefore adoption1c7a8cc
line 151why, one step back151 #[default]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 152–183why, one step back152 Null,153154 /// Feed output through a pipe before discarding it155 Pipe,156157 /// Redirect output to a file158 File(PathBuf),159160 /// Show command output on the terminal161 Inherit,162}163164impl CommandOutputPolicy {165 pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {166 let streams = match self {167 CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),168169 // Typically only stdout is performance-relevant, so just pipe that170 CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),171172 CommandOutputPolicy::File(path) => {173 let file = File::create(path)?;174 (file.into(), Stdio::null())175 }176177 CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),178 };179180 Ok(streams)181 }182}183Basic scheduler testDavid Peterbefore adoption0705d6c
line 184why, one step back184#[derive(Debug, PartialEq)]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 185–205why, one step back185pub enum ExecutorKind {186 Raw,187 Shell(Shell),188 Mock(Option<String>),189}190191impl Default for ExecutorKind {192 fn default() -> Self {193 ExecutorKind::Shell(Shell::default())194 }195}196197/// The main settings for a hyperfine benchmark session198pub struct Options {199 /// Upper and lower bound for the number of benchmark runs200 pub run_bounds: RunBounds,201202 /// Number of warmup runs203 pub warmup_count: u64,204205 /// Minimum benchmarking timeMerge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 206why, one step back206 pub min_benchmarking_time: Time,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 207–210why, one step back207208 /// Whether or not to ignore non-zero exit codes209 pub command_failure_action: CmdFailureAction,210Added option to manually specify a reference to compare the results to.Jan-Eric Nitschkebefore adoption9806ed7
lines 211–213why, one step back211 // Command to use as a reference for relative speed comparison212 pub reference_command: Option<String>,213Add option to name reference commandNiklas Dewallybefore adoption2166c9f
lines 214–216why, one step back214 // Name of the reference command215 pub reference_name: Option<String>,216Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 217–219why, one step back217 /// Command(s) to run before each timing run218 pub preparation_command: Option<Vec<String>>,219Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 220–222why, one step back220 /// Command(s) to run after each timing run221 pub conclusion_command: Option<Vec<String>>,222Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 223–231why, one step back223 /// Command to run before each *batch* of timing runs, i.e. before each individual benchmark224 pub setup_command: Option<String>,225226 /// Command to run after each *batch* of timing runs, i.e. after each individual benchmark227 pub cleanup_command: Option<String>,228229 /// What color mode to use for the terminal output230 pub output_style: OutputStyleOption,231Add new --sort optionDavid Peterbefore adoptionac617c8
lines 232–237why, one step back232 /// How to order benchmarks in the relative speed comparison233 pub sort_order_speed_comparison: SortOrder,234235 /// How to order benchmarks in the markup format exports236 pub sort_order_exports: SortOrder,237Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 238–243why, one step back238 /// Determines how we run commands239 pub executor_kind: ExecutorKind,240241 /// Where input to the benchmarked command comes from242 pub command_input_policy: CommandInputPolicy,243Multiple output policiesDavid Peterbefore adoption99d24b7
lines 244–245why, one step back244 /// What to do with the output of the benchmarked commands245 pub command_output_policies: Vec<CommandOutputPolicy>,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 246–247why, one step back246247 /// Which time unit to use when displaying resultsMerge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
line 248why, one step back248 pub time_unit: Option<TimeUnit>,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 249–255why, one step back249}250251impl Default for Options {252 fn default() -> Options {253 Options {254 run_bounds: RunBounds::default(),255 warmup_count: 0,Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
line 256why, one step back256 min_benchmarking_time: Time::new::<second>(3.0),Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 257why, one step back257 command_failure_action: CmdFailureAction::RaiseError,Added option to manually specify a reference to compare the results to.Jan-Eric Nitschkebefore adoption9806ed7
line 258why, one step back258 reference_command: None,Add option to name reference commandNiklas Dewallybefore adoption2166c9f
line 259why, one step back259 reference_name: None,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 260why, one step back260 preparation_command: None,Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
line 261why, one step back261 conclusion_command: None,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 262–264why, one step back262 setup_command: None,263 cleanup_command: None,264 output_style: OutputStyleOption::Full,Add new --sort optionDavid Peterbefore adoptionac617c8
lines 265–266why, one step back265 sort_order_speed_comparison: SortOrder::MeanTime,266 sort_order_exports: SortOrder::Command,Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 267why, one step back267 executor_kind: ExecutorKind::default(),Multiple output policiesDavid Peterbefore adoption99d24b7
line 268why, one step back268 command_output_policies: vec![CommandOutputPolicy::Null],Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 269–277why, one step back269 time_unit: None,270 command_input_policy: CommandInputPolicy::Null,271 }272 }273}274275impl Options {276 pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {277 let mut options = Self::default();Fix panic on --runs 0 (#923)Vincentbefore adoption907de26
lines 278–281why, one step back278 options.warmup_count = matches279 .get_one::<u64>("warmup")280 .copied()281 .unwrap_or(options.warmup_count);Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 282why, one step back282Fix panic on --runs 0 (#923)Vincentbefore adoption907de26
lines 283–284why, one step back283 let mut min_runs = matches.get_one::<u64>("min-runs").copied();284 let mut max_runs = matches.get_one::<u64>("max-runs").copied();Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 285why, one step back285Fix panic on --runs 0 (#923)Vincentbefore adoption907de26
line 286why, one step back286 if let Some(&runs) = matches.get_one::<u64>("runs") {Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 287–310why, one step back287 min_runs = Some(runs);288 max_runs = Some(runs);289 }290291 match (min_runs, max_runs) {292 (Some(min), None) => {293 options.run_bounds.min = min;294 }295 (None, Some(max)) => {296 // Since the minimum was not explicit we lower it if max is below the default min.297 options.run_bounds.min = cmp::min(options.run_bounds.min, max);298 options.run_bounds.max = Some(max);299 }300 (Some(min), Some(max)) if min > max => {301 return Err(OptionsError::EmptyRunsRange);302 }303 (Some(min), Some(max)) => {304 options.run_bounds.min = min;305 options.run_bounds.max = Some(max);306 }307 (None, None) => {}308 };309310 options.setup_command = matches.get_one::<String>("setup").map(String::from);Added option to manually specify a reference to compare the results to.Jan-Eric Nitschkebefore adoption9806ed7
lines 311–312why, one step back311312 options.reference_command = matches.get_one::<String>("reference").map(String::from);Add option to name reference commandNiklas Dewallybefore adoption2166c9f
lines 313–315why, one step back313 options.reference_name = matches314 .get_one::<String>("reference-name")315 .map(String::from);Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 316–320why, one step back316317 options.preparation_command = matches318 .get_many::<String>("prepare")319 .map(|values| values.map(String::from).collect::<Vec<String>>());320Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 321–324why, one step back321 options.conclusion_command = matches322 .get_many::<String>("conclude")323 .map(|values| values.map(String::from).collect::<Vec<String>>());324Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 325–326why, one step back325 options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);326Multiple output policiesDavid Peterbefore adoption99d24b7
lines 327–341why, one step back327 options.command_output_policies = if matches.get_flag("show-output") {328 vec![CommandOutputPolicy::Inherit]329 } else if let Some(output_values) = matches.get_many::<String>("output") {330 let mut policies = vec![];331 for value in output_values {332 let policy = match value.as_str() {333 "null" => CommandOutputPolicy::Null,334 "pipe" => CommandOutputPolicy::Pipe,335 "inherit" => CommandOutputPolicy::Inherit,336 arg => {337 let path = PathBuf::from(arg);338 if path.components().count() <= 1 {339 return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));340 }341 CommandOutputPolicy::File(path)Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 342why, one step back342 }Multiple output policiesDavid Peterbefore adoption99d24b7
lines 343–344why, one step back343 };344 policies.push(policy);Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 345why, one step back345 }Multiple output policiesDavid Peterbefore adoption99d24b7
line 346why, one step back346 policiesFix clippy suggestionsDavid Peterbefore adoptionc44aa1d
line 347why, one step back347 } else {Multiple output policiesDavid Peterbefore adoption99d24b7
line 348why, one step back348 vec![CommandOutputPolicy::Null]Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 349–357why, one step back349 };350351 options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {352 Some("full") => OutputStyleOption::Full,353 Some("basic") => OutputStyleOption::Basic,354 Some("nocolor") => OutputStyleOption::NoColor,355 Some("color") => OutputStyleOption::Color,356 Some("none") => OutputStyleOption::Disabled,357 _ => {Multiple output policiesDavid Peterbefore adoption99d24b7
line 358why, one step back358 if optionsFormattingDavid Peterbefore adoptionde07c77
lines 359–360why, one step back359 .command_output_policies360 .contains(&CommandOutputPolicy::Inherit)Remove dependency on `atty` and use `std::io::IsTerminal` insteadLenabefore adoption69ee173
line 361why, one step back361 || !io::stdout().is_terminal()Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 362–385why, one step back362 {363 OutputStyleOption::Basic364 } else if env::var_os("TERM")365 .map(|t| t == "unknown" || t == "dumb")366 .unwrap_or(!cfg!(target_os = "windows"))367 || env::var_os("NO_COLOR")368 .map(|t| !t.is_empty())369 .unwrap_or(false)370 {371 OutputStyleOption::NoColor372 } else {373 OutputStyleOption::Full374 }375 }376 };377378 match options.output_style {379 OutputStyleOption::Basic | OutputStyleOption::NoColor => {380 colored::control::set_override(false)381 }382 OutputStyleOption::Full | OutputStyleOption::Color => {383 colored::control::set_override(true)384 }385 OutputStyleOption::Disabled => {}Add new --sort optionDavid Peterbefore adoptionac617c8
lines 386–395why, one step back386 };387388 (389 options.sort_order_speed_comparison,390 options.sort_order_exports,391 ) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {392 None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),393 Some("command") => (SortOrder::Command, SortOrder::Command),394 Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),395 Some(_) => unreachable!("Unknown sort order"),Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 396–413why, one step back396 };397398 options.executor_kind = if matches.get_flag("no-shell") {399 ExecutorKind::Raw400 } else {401 match (402 matches.get_flag("debug-mode"),403 matches.get_one::<String>("shell"),404 ) {405 (false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()),406 (false, Some(shell)) if shell == "none" => ExecutorKind::Raw,407 (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),408 (false, None) => ExecutorKind::Shell(Shell::default()),409 (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),410 (true, None) => ExecutorKind::Mock(None),411 }412 };413Support list of exit codes in --ignore-failureDavid Peterbefore adoptionb5a6860
lines 414–428why, one step back414 if let Some(mode) = matches.get_one::<String>("ignore-failure") {415 options.command_failure_action = match mode.as_str() {416 "all-non-zero" | "" => CmdFailureAction::IgnoreAllFailures,417 codes => {418 let exit_codes: Result<Vec<i32>, _> = codes419 .split(',')420 .map(|s| {421 s.trim()422 .parse::<i32>()423 .map_err(|e| OptionsError::IntParsingError("ignore-failure", e))424 })425 .collect();426 CmdFailureAction::IgnoreSpecificFailures(exit_codes?)427 }428 };Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 429–431why, one step back429 }430431 options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) {Merge pull request #962 from sharkdp/codex/quantity-module-layoutDavid Peterbefore adoptionecf8a24
lines 432–436why, one step back432 Some("µs" | "us" | "microsecond" | "microseconds") => Some(TimeUnit::MicroSecond),433 Some("ms" | "millisecond" | "milliseconds") => Some(TimeUnit::MilliSecond),434 Some("s" | "second" | "seconds") => Some(TimeUnit::Second),435 Some("min" | "minute" | "minutes") => Some(TimeUnit::Minute),436 Some("h" | "hour" | "hours") => Some(TimeUnit::Hour),Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 437–440why, one step back437 _ => None,438 };439440 if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {Merge pull request #961 from sharkdp/codex/uom-quantitiesDavid Peterbefore adoption975a25c
lines 441–444why, one step back441 options.min_benchmarking_time = Time::new::<second>(442 time.parse::<f64>()443 .map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?,444 );Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 445–447why, one step back445 }446447 options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") {Fix usage of --input=nullDavid Peterbefore adoption80ec1c5
lines 448–457why, one step back448 if path_str == "null" {449 CommandInputPolicy::Null450 } else {451 let path = PathBuf::from(path_str);452 if !path.exists() {453 return Err(OptionsError::StdinDataFileDoesNotExist(454 path_str.to_string(),455 ));456 }457 CommandInputPolicy::File(path)Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 458–465why, one step back458 }459 } else {460 CommandInputPolicy::Null461 };462463 Ok(options)464 }465Multiple output policiesDavid Peterbefore adoption99d24b7
lines 466–469why, one step back466 pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {467 let has_reference_command = self.reference_command.is_some();468 let num_commands = commands.num_commands(has_reference_command);469Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 470–471why, one step back470 if let Some(preparation_command) = &self.preparation_command {471 ensure!(Fix prepare and conclude behaviour and add tests.Jan-Eric Nitschkebefore adoptiond4749b0
line 472why, one step back472 preparation_command.len() <= 1 || num_commands == preparation_command.len(),Multiple output policiesDavid Peterbefore adoption99d24b7
lines 473–474why, one step back473 "The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \474 number of benchmark commands (including a potential reference)."Add --conclude option with testsJack O'Connorbefore adoptione13d0cb
lines 475–479why, one step back475 );476 }477478 if let Some(conclusion_command) = &self.conclusion_command {479 ensure!(Fix prepare and conclude behaviour and add tests.Jan-Eric Nitschkebefore adoptiond4749b0
line 480why, one step back480 conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),Multiple output policiesDavid Peterbefore adoption99d24b7
lines 481–493why, one step back481 "The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \482 number of benchmark commands (including a potential reference)."483 );484 }485486 if self.command_output_policies.len() == 1 {487 self.command_output_policies =488 vec![self.command_output_policies[0].clone(); num_commands];489 } else {490 ensure!(491 self.command_output_policies.len() == num_commands,492 "The '--output' option has to be provided just once or N times, where N={num_commands} is the \493 number of benchmark commands (including a potential reference)."Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 494–504why, one step back494 );495 }496497 Ok(())498 }499}500501#[test]502fn test_default_shell() {503 let shell = Shell::default();504style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 505why, one step back505 let s = format!("{shell}");Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 506–515why, one step back506 assert_eq!(&s, DEFAULT_SHELL);507508 let cmd = shell.command();509 assert_eq!(cmd.get_program(), DEFAULT_SHELL);510}511512#[test]513fn test_can_parse_shell_command_line_from_str() {514 let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();515style: simplify string interpolationHamir Mahalbefore adoptionef12632
line 516why, one step back516 let s = format!("{shell}");Fix clippy suggestionsDavid Peterbefore adoptionc44aa1d
lines 517–543why, one step back517 assert_eq!(&s, "shell -x 'aaa bbb'");518519 let cmd = shell.command();520 assert_eq!(cmd.get_program().to_string_lossy(), "shell");521 assert_eq!(522 cmd.get_args()523 .map(|a| a.to_string_lossy())524 .collect::<Vec<_>>(),525 vec!["-x", "aaa bbb"]526 );527528 // Error cases529 assert!(matches!(530 Shell::parse_from_str("shell 'foo").unwrap_err(),531 OptionsError::ShellParseError(_)532 ));533534 assert!(matches!(535 Shell::parse_from_str("").unwrap_err(),536 OptionsError::EmptyShell537 ));538539 assert!(matches!(540 Shell::parse_from_str("''").unwrap_err(),541 OptionsError::EmptyShell542 ));543}