Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

443 lines · 20.3 KiB · Rust

Last changed by

Make --shell=none the default (#982)David Peterbefore adoptionab86cb9

History of this file

Take it

1use std::ffi::OsString;23use clap::{4    builder::styling::{AnsiColor, Effects},5    builder::NonEmptyStringValueParser,6    builder::Styles,7    crate_version, Arg, ArgAction, ArgMatches, Command, ValueHint,8};910pub fn get_cli_arguments<'a, I, T>(args: I) -> ArgMatches11where12    I: IntoIterator<Item = T>,13    T: Into<OsString> + Clone + 'a,14{15    let command = build_command();16    command.get_matches_from(args)17}1819const STYLES: Styles = Styles::styled()20    .header(AnsiColor::Green.on_default().effects(Effects::BOLD))21    .usage(AnsiColor::Green.on_default().effects(Effects::BOLD))22    .literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))23    .placeholder(AnsiColor::Cyan.on_default());2425/// Build the clap command for parsing command line arguments26fn build_command() -> Command {27    Command::new("hyperfine")28        .version(crate_version!())29        .styles(STYLES)30        .next_line_help(true)31        .hide_possible_values(true)32        .about("A command-line benchmarking tool.")33        .help_expected(true)34        .max_term_width(80)35        .arg(36            Arg::new("command")37                .help("The command to benchmark. This can be the name of an executable, a command \38                       line like \"grep -i todo\" or a shell command like \"sleep 0.5 && echo test\". \39                       The latter requires a shell, which can be enabled via '-S' or '--shell=...'. \40                       If multiple commands are given, hyperfine will show a \41                       comparison of the respective runtimes.")42                .required(true)43                .action(ArgAction::Append)44                .value_hint(ValueHint::CommandString)45                .value_parser(NonEmptyStringValueParser::new()),46        )47        .arg(48            Arg::new("warmup")49                .long("warmup")50                .short('w')51                .value_name("NUM")52                .action(ArgAction::Set)53                .value_parser(clap::value_parser!(u64))54                .help(55                    "Perform NUM warmup runs before the actual benchmark. This can be used \56                     to fill (disk) caches for I/O-heavy programs.",57                ),58        )59        .arg(60            Arg::new("min-runs")61                .long("min-runs")62                .short('m')63                .action(ArgAction::Set)64                .value_name("NUM")65                .value_parser(clap::value_parser!(u64).range(1..))66                .help("Perform at least NUM runs for each command (default: 10)."),67        )68        .arg(69            Arg::new("max-runs")70                .long("max-runs")71                .short('M')72                .action(ArgAction::Set)73                .value_name("NUM")74                .value_parser(clap::value_parser!(u64).range(1..))75                .help("Perform at most NUM runs for each command. By default, there is no limit."),76        )77        .arg(78            Arg::new("runs")79                .long("runs")80                .conflicts_with_all(["max-runs", "min-runs"])81                .short('r')82                .action(ArgAction::Set)83                .value_name("NUM")84                .value_parser(clap::value_parser!(u64).range(1..))85                .help("Perform exactly NUM runs for each command. If this option is not specified, \86                       hyperfine automatically determines the number of runs."),87        )88        .arg(89            Arg::new("setup")90                .long("setup")91                .short('s')92                .action(ArgAction::Set)93                .value_name("CMD")94                .value_hint(ValueHint::CommandString)95                .help(96                    "Execute CMD before each set of timing runs. This is useful for \97                     compiling your software with the provided parameters, or to do any \98                     other work that should happen once before a series of benchmark runs, \99                     not every time as would happen with the --prepare option."100                ),101        )102        .arg(103            Arg::new("reference")104                .long("reference")105                .action(ArgAction::Set)106                .value_name("CMD")107                .help(108                    "The reference for the relative comparison of results. Without parameters, \109                    CMD is run as a separate reference command. With --parameter-scan or \110                    --parameter-list, CMD must exactly match one unique benchmark name as \111                    shown in the output. If this is unset, results are compared with the \112                    fastest command as reference."113                )114        )115        .arg(116            Arg::new("reference-name")117                .long("reference-name")118                .action(ArgAction::Set)119                .value_name("CMD")120                .help("Give a meaningful name to the reference command. This cannot be used \121                       with parameterized benchmarks; use --command-name instead.")122                .requires("reference")123        )124        .arg(125            Arg::new("prepare")126                .long("prepare")127                .short('p')128                .action(ArgAction::Append)129                .num_args(1)130                .value_name("CMD")131                .value_hint(ValueHint::CommandString)132                .help(133                    "Execute CMD before each timing run. This is useful for \134                     clearing disk caches, for example.\nThe --prepare option can \135                     be specified once for all commands or multiple times, once for \136                     each command. In the latter case, each preparation command will \137                     be run prior to the corresponding benchmark command.",138                ),139        )140        .arg(141            Arg::new("conclude")142                .long("conclude")143                .short('C')144                .action(ArgAction::Append)145                .num_args(1)146                .value_name("CMD")147                .value_hint(ValueHint::CommandString)148                .help(149                    "Execute CMD after each timing run. This is useful for killing \150                     long-running processes started (e.g. a web server started in --prepare), \151                     for example.\nThe --conclude option can be specified once for all \152                     commands or multiple times, once for each command. In the latter case, \153                     each conclude command will be run after the corresponding benchmark \154                     command.",155                ),156        )157        .arg(158            Arg::new("cleanup")159                .long("cleanup")160                .short('c')161                .action(ArgAction::Set)162                .value_name("CMD")163                .value_hint(ValueHint::CommandString)164                .help(165                    "Execute CMD after the completion of all benchmarking \166                     runs for each individual command to be benchmarked. \167                     This is useful if the commands to be benchmarked produce \168                     artifacts that need to be cleaned up."169                ),170        )171        .arg(172            Arg::new("parameter-scan")173                .long("parameter-scan")174                .short('P')175                .action(ArgAction::Set)176                .allow_hyphen_values(true)177                .value_names(["VAR", "MIN", "MAX"])178                .help(179                    "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \180                     string '{VAR}' in each command by the current parameter value.\n\n  \181                     Example:  hyperfine --prepare 'make clean' -P threads 1 8 'make -j {threads}'\n\n\182                     This performs benchmarks for 'make -j 1', 'make -j 2', …, 'make -j 8'.\n\n\183                     To have the value increase following different patterns, use shell arithmetic.\n\n  \184                     Example: hyperfine --shell=bash -P size 0 3 'sleep $((2**{size}))'\n\n\185                     This performs benchmarks with power of 2 increases: 'sleep 1', 'sleep 2', 'sleep 4', …\n\186                     The exact syntax may vary depending on your shell and OS."187                ),188        )189        .arg(190            Arg::new("parameter-step-size")191                .long("parameter-step-size")192                .short('D')193                .action(ArgAction::Set)194                .value_names(["DELTA"])195                .requires("parameter-scan")196                .help(197                    "This argument requires --parameter-scan to be specified as well. \198                     Traverse the range MIN..MAX in steps of DELTA, which must be positive.\n\n  \199                     Example:  hyperfine -P delay 0.3 0.7 -D 0.2 'sleep {delay}'\n\n\200                     This performs benchmarks for 'sleep 0.3', 'sleep 0.5' and 'sleep 0.7'.",201                ),202        )203        .arg(204            Arg::new("parameter-list")205                .long("parameter-list")206                .short('L')207                .action(ArgAction::Append)208                .allow_hyphen_values(true)209                .value_names(["VAR", "VALUES"])210                .conflicts_with_all(["parameter-scan", "parameter-step-size"])211                .help(212                    "Perform benchmark runs for each value in the comma-separated list VALUES. \213                     Replaces the string '{VAR}' in each command by the current parameter value\214                     .\n\nExample:  hyperfine -L compiler g++,clang++ '{compiler} -O2 main.cpp'\n\n\215                     This performs benchmarks for 'g++ -O2 main.cpp' and 'clang++ -O2 main.cpp'.\n\n\216                     The option can be specified multiple times to run benchmarks for all \217                     possible parameter combinations.\n"218                ),219        )220        .arg(221            Arg::new("shell")222                .long("shell")223                .action(ArgAction::Set)224                .value_name("SHELL")225                .overrides_with("shell")226                .value_hint(ValueHint::CommandString)227                .help("Set the shell to use for executing commands (default: none). This can be the \228                       name or the path to the shell executable, or a full command line \229                       like \"bash --norc\". It can also be set to \"default\" to explicitly select \230                       the platform shell (sh on Unix, cmd.exe on Windows). It can also be set to \231                       \"none\" to disable the shell. In this case, commands will be executed \232                       directly. They can still have arguments, but more complex things like \233                       \"sleep 0.1; sleep 0.2\" are not possible without a shell. This option also \234                       applies to setup, prepare, conclude, and cleanup commands.")235        )236        .arg(237            Arg::new("default-shell")238                .short('S')239                .action(ArgAction::SetTrue)240                .conflicts_with_all(["shell", "no-shell", "debug-mode"])241                .help("An alias for '--shell=default' (sh on Unix, cmd.exe on Windows).")242        )243        .arg(244            Arg::new("no-shell")245                .short('N')246                .action(ArgAction::SetTrue)247                .conflicts_with_all(["shell", "debug-mode"])248                .help("An alias for '--shell=none'.")249        )250        .arg(251            Arg::new("ignore-failure")252                .long("ignore-failure")253                .action(ArgAction::Set)254                .value_name("MODE")255                .num_args(0..=1)256                .default_missing_value("all-non-zero")257                .require_equals(true)258                .short('i')259                .help("Ignore failures of the benchmarked programs. Without a value or with \260                       'all-non-zero', all non-zero exit codes are ignored. You can also provide \261                       a comma-separated list of exit codes to ignore (e.g., --ignore-failure=1,2)."),262        )263        .arg(264            Arg::new("style")265                .long("style")266                .action(ArgAction::Set)267                .value_name("TYPE")268                .value_parser(["auto", "basic", "full", "nocolor", "color", "none"])269                .help(270                    "Set output style type (default: auto). Set this to 'basic' to disable output \271                     coloring and interactive elements. Set it to 'full' to enable all effects \272                     even if no interactive terminal was detected. Set this to 'nocolor' to \273                     keep the interactive output without any colors. Set this to 'color' to keep \274                     the colors without any interactive output. Set this to 'none' to disable all \275                     the output of the tool.",276                ),277        )278        .arg(279            Arg::new("sort")280            .long("sort")281            .action(ArgAction::Set)282            .value_name("METHOD")283            .value_parser(["auto", "command", "mean-time"])284            .default_value("auto")285            .hide_default_value(true)286            .help(287                "Specify the sort order of the speed comparison summary and the exported tables for \288                 markup formats (Markdown, AsciiDoc, org-mode):\n  \289                   * 'auto' (default): the speed comparison will be ordered by time and\n    \290                     the markup tables will be ordered by command (input order).\n  \291                   * 'command': order benchmarks in the way they were specified\n  \292                   * 'mean-time': order benchmarks by mean runtime\n"293            ),294        )295        .arg(296            Arg::new("time-unit")297                .long("time-unit")298                .short('u')299                .action(ArgAction::Set)300                .value_name("UNIT")301                .value_parser(["µs", "us", "microsecond", "microseconds", "ms", "millisecond", "milliseconds", "s", "second", "seconds", "min", "minute", "minutes", "h", "hour", "hours"])302                .help("Set the time unit to be used. If the option is not given, the time unit is determined automatically. \303                       This option affects the standard output as well as all export formats except for CSV and JSON.\n\304                       Possible values:\n  \305                         * 'µs', 'us', 'microsecond', 'microseconds'\n  \306                         * 'ms', 'millisecond', 'milliseconds'\n  \307                         * 's', 'second', 'seconds'\n  \308                         * 'min', 'minute', 'minutes'\n  \309                         * 'h', 'hour', 'hours'"),310        )311        .arg(312            Arg::new("export-asciidoc")313                .long("export-asciidoc")314                .action(ArgAction::Set)315                .value_name("FILE")316                .value_hint(ValueHint::FilePath)317                .help("Export the timing summary statistics as an AsciiDoc table to the given FILE. \318                       The output time unit can be changed using the --time-unit option."),319        )320        .arg(321            Arg::new("export-csv")322                .long("export-csv")323                .action(ArgAction::Set)324                .value_name("FILE")325                .value_hint(ValueHint::FilePath)326                .help("Export the timing summary statistics as CSV to the given FILE. If you need \327                       the timing results for each individual run, use the JSON export format. \328                       The output time unit is always seconds."),329        )330        .arg(331            Arg::new("export-json")332                .long("export-json")333                .action(ArgAction::Set)334                .value_name("FILE")335                .value_hint(ValueHint::FilePath)336                .help("Export the timing summary statistics and timings of individual runs as JSON to the given FILE. \337                       The output time unit is always seconds"),338        )339        .arg(340            Arg::new("export-markdown")341                .long("export-markdown")342                .action(ArgAction::Set)343                .value_name("FILE")344                .value_hint(ValueHint::FilePath)345                .help("Export the timing summary statistics as a Markdown table to the given FILE. \346                       The output time unit can be changed using the --time-unit option."),347        )348        .arg(349            Arg::new("export-orgmode")350                .long("export-orgmode")351                .action(ArgAction::Set)352                .value_name("FILE")353                .value_hint(ValueHint::FilePath)354                .help("Export the timing summary statistics as an Emacs org-mode table to the given FILE. \355                       The output time unit can be changed using the --time-unit option."),356        )357        .arg(358            Arg::new("show-output")359                .long("show-output")360                .action(ArgAction::SetTrue)361                .conflicts_with("style")362                .help(363                    "Print the stdout and stderr of the benchmark instead of suppressing it. \364                     This will increase the time it takes for benchmarks to run, \365                     so it should only be used for debugging purposes or \366                     when trying to benchmark output speed.",367                ),368        )369        .arg(370            Arg::new("output")371                .long("output")372                .conflicts_with("show-output")373                .action(ArgAction::Append)374                .value_name("WHERE")375                .help(376                    "Control where the output of the benchmark is redirected. Note \377                     that some programs like 'grep' detect when standard output is \378                     /dev/null and apply certain optimizations. To avoid that, consider \379                     using '--output=pipe'.\n\380                     \n\381                     <WHERE> can be:\n\382                     \n  \383                       null:     Redirect output to /dev/null (the default).\n\384                     \n  \385                       pipe:     Feed the output through a pipe before discarding it.\n\386                     \n  \387                       inherit:  Don't redirect the output at all (same as '--show-output').\n\388                     \n  \389                       <FILE>:   Write the output to the given file.\n\n\390                    This option can be specified once for all commands or multiple times, once for \391                    each command. Note: If you want to log the output of each and every iteration, \392                    you can use a shell redirection and the '$HYPERFINE_ITERATION' environment variable:\n    \393                    hyperfine -S 'my-command > output-${HYPERFINE_ITERATION}.log'\n\n",394                ),395        )396        .arg(397            Arg::new("input")398                .long("input")399                .action(ArgAction::Set)400                .num_args(1)401                .value_name("WHERE")402                .help("Control where the input of the benchmark comes from.\n\403                       \n\404                       <WHERE> can be:\n\405                       \n  \406                         null:     Read from /dev/null (the default).\n\407                       \n  \408                         <FILE>:   Read the input from the given file."),409        )410        .arg(411            Arg::new("command-name")412                .long("command-name")413                .short('n')414                .action(ArgAction::Append)415                .num_args(1)416                .value_name("NAME")417                .help("Give a meaningful name to a command. This can be specified multiple times \418                       if several commands are benchmarked."),419        )420        // This option is hidden for now, as it is not yet clear yet if we want to 'stabilize' this,421        // see discussion in https://github.com/sharkdp/hyperfine/issues/527422        .arg(423            Arg::new("min-benchmarking-time")424            .long("min-benchmarking-time")425            .action(ArgAction::Set)426            .hide(true)427            .help("Set the minimum time (in seconds) to run benchmarks. Note that the number of \428                   benchmark runs is additionally influenced by the `--min-runs`, `--max-runs`, and \429                   `--runs` option.")430        )431        .arg(432            Arg::new("debug-mode")433            .long("debug-mode")434            .action(ArgAction::SetTrue)435            .hide(true)436            .help("Enable debug mode which does not actually run commands, but returns fake times when the command is 'sleep <time>'.")437        )438}439440#[test]441fn verify_app() {442    build_command().debug_assert();443}