integration_tests/
nextest_cli.rs

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
// Copyright (c) The nextest Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

use camino::Utf8PathBuf;
use color_eyre::{
    eyre::{bail, Context},
    Result,
};
use nextest_metadata::TestListSummary;
use std::{
    borrow::Cow,
    collections::HashMap,
    ffi::OsString,
    fmt,
    process::{Command, ExitStatus},
};

pub fn cargo_bin() -> String {
    match std::env::var("CARGO") {
        Ok(v) => v,
        Err(std::env::VarError::NotPresent) => "cargo".to_owned(),
        Err(err) => panic!("error obtaining CARGO env var: {err}"),
    }
}

#[derive(Clone, Debug)]
pub struct CargoNextestCli {
    bin: Utf8PathBuf,
    args: Vec<String>,
    envs: HashMap<OsString, OsString>,
    unchecked: bool,
}

impl CargoNextestCli {
    pub fn for_test() -> Self {
        let bin = std::env::var("NEXTEST_BIN_EXE_cargo-nextest-dup")
            .expect("unable to find cargo-nextest-dup");
        Self {
            bin: bin.into(),
            args: vec!["nextest".to_owned()],
            envs: HashMap::new(),
            unchecked: false,
        }
    }

    /// Creates a new CargoNextestCli instance for use in a setup script.
    ///
    /// Scripts don't have access to the `NEXTEST_BIN_EXE_cargo-nextest-dup` environment variable,
    /// so we run `cargo run --bin cargo-nextest-dup nextest debug current-exe` instead.
    pub fn for_script() -> Result<Self> {
        let cargo_bin = cargo_bin();
        let mut command = std::process::Command::new(&cargo_bin);
        command.args([
            "run",
            "--bin",
            "cargo-nextest-dup",
            "--",
            "nextest",
            "debug",
            "current-exe",
        ]);
        let output = command.output().wrap_err("failed to get current exe")?;

        let output = CargoNextestOutput {
            command,
            exit_status: output.status,
            stdout: output.stdout,
            stderr: output.stderr,
        };

        if !output.exit_status.success() {
            bail!("failed to get current exe:\n\n{output:?}");
        }

        // The output is the path to the current exe.
        let exe =
            String::from_utf8(output.stdout).wrap_err("current exe output isn't valid UTF-8")?;

        Ok(Self {
            bin: Utf8PathBuf::from(exe.trim_end()),
            args: vec!["nextest".to_owned()],
            envs: HashMap::new(),
            unchecked: false,
        })
    }

    pub fn arg(&mut self, arg: impl Into<String>) -> &mut Self {
        self.args.push(arg.into());
        self
    }

    pub fn args(&mut self, arg: impl IntoIterator<Item = impl Into<String>>) -> &mut Self {
        self.args.extend(arg.into_iter().map(Into::into));
        self
    }

    pub fn env(&mut self, k: impl Into<OsString>, v: impl Into<OsString>) -> &mut Self {
        self.envs.insert(k.into(), v.into());
        self
    }

    pub fn envs(
        &mut self,
        envs: impl IntoIterator<Item = (impl Into<OsString>, impl Into<OsString>)>,
    ) -> &mut Self {
        self.envs
            .extend(envs.into_iter().map(|(k, v)| (k.into(), v.into())));
        self
    }

    pub fn unchecked(&mut self, unchecked: bool) -> &mut Self {
        self.unchecked = unchecked;
        self
    }

    pub fn output(&self) -> CargoNextestOutput {
        let mut command = std::process::Command::new(&self.bin);
        command.args(&self.args);
        command.envs(&self.envs);
        let output = command.output().expect("failed to execute");

        let ret = CargoNextestOutput {
            command,
            exit_status: output.status,
            stdout: output.stdout,
            stderr: output.stderr,
        };

        if !self.unchecked && !output.status.success() {
            panic!("command failed:\n\n{ret}");
        }

        ret
    }
}

pub struct CargoNextestOutput {
    pub command: Command,
    pub exit_status: ExitStatus,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
}

impl CargoNextestOutput {
    pub fn stdout_as_str(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stdout)
    }

    pub fn stderr_as_str(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.stderr)
    }

    pub fn decode_test_list_json(&self) -> Result<TestListSummary> {
        Ok(serde_json::from_slice(&self.stdout)?)
    }
}

impl fmt::Display for CargoNextestOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "command: {:?}\nexit code: {:?}\n\
                   --- stdout ---\n{}\n\n--- stderr ---\n{}\n\n",
            self.command,
            self.exit_status.code(),
            String::from_utf8_lossy(&self.stdout),
            String::from_utf8_lossy(&self.stderr)
        )
    }
}

// Make Debug output the same as Display output, so `.unwrap()` and `.expect()` are nicer.
impl fmt::Debug for CargoNextestOutput {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}