1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#![allow(missing_docs)]

use crate::ExitStatus;
use getopts::Options;
use std::{
    path::{Path, PathBuf},
    str::FromStr,
};

/// Command line arguments.
#[derive(Debug)]
#[non_exhaustive]
pub struct Args {
    pub list: bool,
    pub filter: Option<String>,
    pub filter_exact: bool,
    pub run_ignored: bool,
    pub run_tests: bool,
    pub run_benchmarks: bool,
    pub logfile: Option<PathBuf>,
    pub nocapture: bool,
    pub color: ColorConfig,
    pub format: OutputFormat,
    pub test_threads: Option<usize>,
    pub skip: Vec<String>,
}

impl Args {
    /// Parse command line arguments.
    pub fn from_env() -> Result<Self, ExitStatus> {
        let parser = Parser::new();
        match parser.parse_args() {
            Ok(Some(args)) => Ok(args),
            Ok(None) => {
                parser.print_usage();
                Err(ExitStatus::OK)
            }
            Err(err) => {
                eprintln!("CLI argument error: {}", err);
                Err(ExitStatus::FAILED)
            }
        }
    }

    pub(crate) fn is_filtered(&self, name: &str) -> bool {
        if let Some(ref filter) = self.filter {
            if self.filter_exact && name != filter {
                return true;
            }
            if !name.contains(filter) {
                return true;
            }
        }

        for skip_filter in &self.skip {
            if self.filter_exact && name != skip_filter {
                return true;
            }
            if !name.contains(skip_filter) {
                return true;
            }
        }

        false
    }
}

struct TestThreads(usize);

impl FromStr for TestThreads {
    type Err = Box<dyn std::error::Error>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let n = s.parse().map_err(|e| {
            format!(
                "argument for --test-threads must be a number > 0 (error: {})",
                e
            )
        })?;
        if n == 0 {
            return Err("argument for --test-threads must not be 0".into());
        }
        Ok(Self(n))
    }
}

/// The color configuration.
#[derive(Copy, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ColorConfig {
    Auto,
    Always,
    Never,
}

impl FromStr for ColorConfig {
    type Err = Box<dyn std::error::Error>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "auto" => Ok(ColorConfig::Auto),
            "always" => Ok(ColorConfig::Always),
            "never" => Ok(ColorConfig::Never),
            v => Err(format!(
                "argument for --color must be auto, always, or never (was {})",
                v
            )
            .into()),
        }
    }
}

/// The output format.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum OutputFormat {
    Pretty,
    Terse,
    Json,
}

impl FromStr for OutputFormat {
    type Err = Box<dyn std::error::Error>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "pretty" => Ok(OutputFormat::Pretty),
            "terse" => Ok(OutputFormat::Terse),
            "json" => Ok(OutputFormat::Json),
            s => Err(format!(
                "argument for --format must be pretty, terse, or json (was {})",
                s
            )
            .into()),
        }
    }
}

struct Parser {
    args: Vec<String>,
    opts: Options,
}

impl Parser {
    fn new() -> Self {
        let mut opts = Options::new();
        opts.optflag("", "ignored", "Run only ignored tests");
        opts.optflag("", "test", "Run tests and not benchmarks");
        opts.optflag("", "bench", "Run benchmarks instead of tests");
        opts.optflag("", "list", "List all tests and benchmarks");
        opts.optflag("h", "help", "Display this message (longer with --help)");
        opts.optopt(
            "",
            "logfile",
            "Write logs to the specified file instead of stdout.
             (placeholder. not implemented yet)",
            "PATH",
        );
        opts.optflag(
            "",
            "nocapture",
            "don't capture stdout/stderr of each task, allow printing directly.
             (placeholder, not implemented yet)",
        );
        opts.optopt(
            "",
            "test-threads",
            "Number of threads used for running tests in parallel.
             (placeholder, not implemented yet)",
            "n_threads",
        );
        opts.optmulti(
            "",
            "skip",
            "Skip tests whose names contain FILTER (this flag can be used multiple times)",
            "FILTER",
        );
        opts.optflag(
            "q",
            "quiet",
            "Display one character per test instead of one line. Alias to --format=terse",
        );
        opts.optflag(
            "",
            "exact",
            "Exactly match filters rather than by substring",
        );
        opts.optopt(
            "",
            "color",
            "Configure coloring of output:
                auto   = colorize if stdout is a tty and tests are run on serially (default);
                always = always colorize output;
                never  = never colorize output;",
            "auto|always|never",
        );
        opts.optopt(
            "",
            "format",
            "Configure formatting of output:
                pretty = Print verbose output;
                terse  = Display one character per test;
                json   = Output a json document (placeholder, not implemented yet)",
            "pretty|terse|json",
        );

        Self {
            args: std::env::args().collect(),
            opts,
        }
    }

    fn print_usage(&self) {
        let binary = &self.args[0];
        let progname = Path::new(binary)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(binary);

        let message = format!("Usage: {} [OPTIONS] [FILTER]", progname);
        eprintln!(
            r#"{usage}
    
    The FILTER string is tested against the name of all tests, and only those
    tests whose names contain the filter are run."#,
            usage = self.opts.usage(&message)
        );
    }

    fn parse_args(&self) -> Result<Option<Args>, Box<dyn std::error::Error>> {
        let args = &self.args[..];

        let matches = self.opts.parse(args.get(1..).unwrap_or(args))?;
        if matches.opt_present("h") {
            return Ok(None);
        }

        let filter = matches.free.get(0).cloned();
        let run_ignored = matches.opt_present("ignored");
        let quiet = matches.opt_present("quiet");
        let filter_exact = matches.opt_present("exact");
        let list = matches.opt_present("list");
        let logfile = matches.opt_get("logfile")?;

        let run_benchmarks = matches.opt_present("bench");
        let run_tests = !run_benchmarks || matches.opt_present("test");

        let nocapture = matches.opt_present("nocapture") || {
            std::env::var("RUST_TEST_NOCAPTURE")
                .ok()
                .map_or(false, |val| &val != "0")
        };

        let test_threads = matches.opt_get("test-threads")?.map(|TestThreads(n)| n);

        let color = matches.opt_get("color")?.unwrap_or(ColorConfig::Auto);

        let format = matches.opt_get("format")?.unwrap_or_else(|| {
            if quiet {
                OutputFormat::Terse
            } else {
                OutputFormat::Pretty
            }
        });

        let skip = matches.opt_strs("skip");

        Ok(Some(Args {
            list,
            filter,
            filter_exact,
            run_ignored,
            run_tests,
            run_benchmarks,
            logfile,
            nocapture,
            color,
            format,
            test_threads,
            skip,
        }))
    }
}