aboutsummaryrefslogtreecommitdiff
path: root/xtask/src/command.rs
blob: 100888c07567b3c8f87d458b0ba4d099edbd1e47 (plain) (blame)
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
use crate::{RunResult, TestRunError};
use core::fmt;
use os_pipe::pipe;
use std::{fs::File, io::Read, process::Command};

#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BuildMode {
    Release,
    Debug,
}

#[derive(Debug)]
pub enum CargoCommand<'a> {
    Run {
        example: &'a str,
        target: &'a str,
        features: Option<&'a str>,
        mode: BuildMode,
    },
    BuildAll {
        target: &'a str,
        features: Option<&'a str>,
        mode: BuildMode,
    },
    // Size {
    //     example_paths: Vec<&'a Path>,
    // },
    // Clean,
}

impl<'a> CargoCommand<'a> {
    fn name(&self) -> &str {
        match self {
            CargoCommand::Run { .. } => "run",
            // CargoCommand::Size { example_paths: _ } => "rust-size",
            CargoCommand::BuildAll { .. } => "build",
        }
    }

    pub fn args(&self) -> Vec<&str> {
        match self {
            CargoCommand::Run {
                example,
                target,
                features,
                mode,
            } => {
                let mut args = vec![
                    self.name(),
                    "--example",
                    example,
                    "--target",
                    target,
                    "--features",
                    "test-critical-section",
                ];

                if let Some(feature_name) = features {
                    args.extend_from_slice(&["--features", feature_name]);
                }
                if let Some(flag) = mode.to_flag() {
                    args.push(flag);
                }
                args
            }
            CargoCommand::BuildAll {
                target,
                features,
                mode,
            } => {
                let mut args = vec![self.name(), "--examples", "--target", target];

                if let Some(feature_name) = features {
                    args.extend_from_slice(&["--features", feature_name]);
                }
                if let Some(flag) = mode.to_flag() {
                    args.push(flag);
                }
                args
            } // CargoCommand::Size { example_paths } => {
              //     example_paths.iter().map(|p| p.to_str().unwrap()).collect()
              // }
        }
    }

    pub fn command(&self) -> &str {
        match self {
            // we need to cheat a little here:
            // `cargo size` can't be ran on multiple files, so we're using `rust-size` instead –
            // which isn't a command that starts wizh `cargo`. So we're sneakily swapping them out :)
            // CargoCommand::Size { .. } => "rust-size",
            _ => "cargo",
        }
    }
}

impl BuildMode {
    pub fn to_flag(&self) -> Option<&str> {
        match self {
            BuildMode::Release => Some("--release"),
            BuildMode::Debug => None,
        }
    }
}

impl fmt::Display for BuildMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cmd = match self {
            BuildMode::Release => "release",
            BuildMode::Debug => "debug",
        };

        write!(f, "{}", cmd)
    }
}

pub fn run_command(command: &CargoCommand) -> anyhow::Result<RunResult> {
    let (mut reader, writer) = pipe()?;
    println!("👟 {} {}", command.command(), command.args().join(" "));

    let mut handle = Command::new(command.command())
        .args(command.args())
        .stdout(writer)
        .spawn()?;

    // retrieve output and clean up
    let mut output = String::new();
    reader.read_to_string(&mut output)?;
    let exit_status = handle.wait()?;

    Ok(RunResult {
        exit_status,
        output,
    })
}

/// Check if `run` was sucessful.
/// returns Ok in case the run went as expected,
/// Err otherwise
pub fn run_successful(run: &RunResult, expected_output_file: String) -> Result<(), TestRunError> {
    let mut file_handle =
        File::open(expected_output_file.clone()).map_err(|_| TestRunError::FileError {
            file: expected_output_file.clone(),
        })?;
    let mut expected_output = String::new();
    file_handle
        .read_to_string(&mut expected_output)
        .map_err(|_| TestRunError::FileError {
            file: expected_output_file.clone(),
        })?;

    if expected_output != run.output {
        Err(TestRunError::FileCmpError {
            expected: expected_output.clone(),
            got: run.output.clone(),
        })
    } else if !run.exit_status.success() {
        Err(TestRunError::CommandError(run.clone()))
    } else {
        Ok(())
    }
}