forked from DeterminateSystems/nix-installer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathself_test.rs
169 lines (152 loc) · 4.82 KB
/
self_test.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
use std::{process::Output, time::SystemTime};
use tokio::process::Command;
use which::which;
#[non_exhaustive]
#[derive(thiserror::Error, Debug, strum::IntoStaticStr)]
pub enum SelfTestError {
#[error("Shell `{shell}` failed self-test with command `{command}`, stderr:\n{}", String::from_utf8_lossy(&output.stderr))]
ShellFailed {
shell: Shell,
command: String,
output: Output,
},
/// Failed to execute command
#[error("Failed to execute command `{command}`",
command = .command,
)]
Command {
shell: Shell,
command: String,
#[source]
error: std::io::Error,
},
#[error(transparent)]
SystemTime(#[from] std::time::SystemTimeError),
}
#[cfg(feature = "diagnostics")]
impl crate::diagnostics::ErrorDiagnostic for SelfTestError {
fn diagnostic(&self) -> String {
let static_str: &'static str = (self).into();
let context = match self {
Self::ShellFailed { shell, .. } => vec![shell.to_string()],
Self::Command { shell, .. } => vec![shell.to_string()],
Self::SystemTime(_) => vec![],
};
format!(
"{}({})",
static_str,
context
.iter()
.map(|v| format!("\"{v}\""))
.collect::<Vec<_>>()
.join(", ")
)
}
}
#[derive(Clone, Copy, Debug)]
pub enum Shell {
Sh,
Bash,
Fish,
Zsh,
}
impl std::fmt::Display for Shell {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.executable())
}
}
impl Shell {
pub fn all() -> &'static [Shell] {
&[Shell::Sh, Shell::Bash, Shell::Fish, Shell::Zsh]
}
pub fn executable(&self) -> &'static str {
match &self {
Shell::Sh => "sh",
Shell::Bash => "bash",
Shell::Fish => "fish",
Shell::Zsh => "zsh",
}
}
#[tracing::instrument(skip_all)]
pub async fn self_test(&self) -> Result<(), SelfTestError> {
let executable = self.executable();
let mut command = match &self {
// On Mac, `bash -ic nix` won't work, but `bash -lc nix` will.
Shell::Sh | Shell::Bash => {
let mut command = Command::new(executable);
command.arg("-lc");
command
},
Shell::Zsh | Shell::Fish => {
let mut command = Command::new(executable);
command.arg("-ic");
command
},
};
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
const SYSTEM: &str = "x86_64-linux";
#[cfg(all(target_os = "linux", target_arch = "x86"))]
const SYSTEM: &str = "x86-linux";
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
const SYSTEM: &str = "aarch64-linux";
#[cfg(all(target_os = "macos", target_arch = "x86_64"))]
const SYSTEM: &str = "x86_64-darwin";
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
const SYSTEM: &str = "aarch64-darwin";
let timestamp_millis = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_millis();
command.arg(format!(
r#"nix build --no-link --expr 'derivation {{ name = "self-test-{executable}-{timestamp_millis}"; system = "{SYSTEM}"; builder = "/bin/sh"; args = ["-c" "echo hello > \$out"]; }}'"#
));
let command_str = format!("{:?}", command.as_std());
tracing::debug!(
command = command_str,
"Testing Nix install via `{executable}`"
);
let output = command
.output()
.await
.map_err(|error| SelfTestError::Command {
shell: *self,
command: command_str.clone(),
error,
})?;
if output.status.success() {
Ok(())
} else {
Err(SelfTestError::ShellFailed {
shell: *self,
command: command_str,
output,
})
}
}
#[tracing::instrument(skip_all)]
pub fn discover() -> Vec<Shell> {
let mut found_shells = vec![];
for shell in Self::all() {
if which(shell.executable()).is_ok() {
tracing::debug!("Discovered `{shell}`");
found_shells.push(*shell)
}
}
found_shells
}
}
#[tracing::instrument(skip_all)]
pub async fn self_test() -> Result<(), Vec<SelfTestError>> {
let shells = Shell::discover();
let mut failures = vec![];
for shell in shells {
match shell.self_test().await {
Ok(()) => (),
Err(err) => failures.push(err),
}
}
if failures.is_empty() {
Ok(())
} else {
Err(failures)
}
}