-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathos.rs
More file actions
262 lines (226 loc) · 7.53 KB
/
Copy pathos.rs
File metadata and controls
262 lines (226 loc) · 7.53 KB
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
use std::{
fmt::{self, Display},
fs,
};
use serde::{Deserialize, Serialize};
use sysinfo::System;
use crate::prelude::*;
/// Typed representation of the host operating system.
///
/// Only operating systems that CodSpeed can run on are represented here.
/// Construction via [`SupportedOs::from_current_system`] bails on unsupported platforms
#[derive(Eq, PartialEq, Hash, Debug, Clone, Serialize)]
#[serde(into = "SupportedOsSerde")]
pub enum SupportedOs {
Linux(LinuxDistribution),
Macos { version: String },
}
impl SupportedOs {
/// Build a [`SupportedOs`] from the given OS family string.
/// Expects `std::env::consts::OS` as input
///
/// For Linux, the distribution is identified via `sysinfo::System::distribution_id()`.
/// The OS version is read from `sysinfo::System::os_version()`, falling back to
/// `VERSION_ID` or `BUILD_ID` from os-release.
pub fn from_os(os: &str) -> Result<Self> {
match os {
"linux" => {
let os_id = System::distribution_id();
let os_version = System::os_version()
.or_else(|| {
OsRelease::read().and_then(|release| release.version().map(str::to_owned))
})
.ok_or_else(|| {
anyhow!("Failed to get Linux OS version from sysinfo or os-release")
})?;
Ok(Self::Linux(LinuxDistribution::from_id(&os_id, &os_version)))
}
"macos" => {
let os_version = System::os_version().ok_or(anyhow!("Failed to get OS version"))?;
Ok(Self::Macos {
version: os_version,
})
}
unsupported => bail!("Unsupported operating system: {unsupported}"),
}
}
/// The distro/OS id as it appears on the wire (matches `sysinfo::System::distribution_id()`).
pub fn id(&self) -> &str {
match self {
Self::Linux(distro) => distro.id(),
Self::Macos { .. } => "macos",
}
}
pub fn version(&self) -> &str {
match self {
Self::Linux(distro) => distro.version(),
Self::Macos { version } => version,
}
}
}
struct OsRelease {
version_id: Option<String>,
build_id: Option<String>,
}
impl OsRelease {
fn read() -> Option<Self> {
["/etc/os-release", "/usr/lib/os-release"]
.into_iter()
.filter_map(|path| fs::read_to_string(path).ok())
.map(|contents| Self::parse(&contents))
.find(|release| release.version().is_some())
}
fn parse(contents: &str) -> Self {
let mut release = Self {
version_id: None,
build_id: None,
};
for line in contents.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.trim();
let value = value
.strip_prefix('"')
.and_then(|value| value.strip_suffix('"'))
.or_else(|| {
value
.strip_prefix('\'')
.and_then(|value| value.strip_suffix('\''))
})
.unwrap_or(value)
.to_string();
match key.trim() {
"VERSION_ID" => release.version_id = Some(value),
"BUILD_ID" => release.build_id = Some(value),
_ => {}
}
}
release
}
fn version(&self) -> Option<&str> {
self.version_id.as_deref().or(self.build_id.as_deref())
}
}
impl Display for SupportedOs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.id(), self.version())
}
}
/// Flat `{os, osVersion}` shape we emit on the wire as part of `SystemInfo`.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SupportedOsSerde {
os: String,
os_version: String,
}
impl From<SupportedOs> for SupportedOsSerde {
fn from(os: SupportedOs) -> Self {
SupportedOsSerde {
os: os.id().to_string(),
os_version: os.version().to_string(),
}
}
}
/// Linux distribution, identified by the `sysinfo` distribution id.
#[derive(Eq, PartialEq, Hash, Debug, Clone)]
pub enum LinuxDistribution {
Ubuntu { version: String },
Debian { version: String },
Other { name: String, version: String },
}
impl LinuxDistribution {
/// Build a [`LinuxDistribution`] from the raw `(os_id, version)` strings reported by `sysinfo`.
fn from_id(os_id: &str, version: &str) -> Self {
match os_id {
"ubuntu" => Self::Ubuntu {
version: version.to_string(),
},
"debian" => Self::Debian {
version: version.to_string(),
},
_ => Self::Other {
name: os_id.to_string(),
version: version.to_string(),
},
}
}
/// The distro id as it appears on the wire (matches `sysinfo::System::distribution_id()`).
pub fn id(&self) -> &str {
match self {
Self::Ubuntu { .. } => "ubuntu",
Self::Debian { .. } => "debian",
Self::Other { name, .. } => name,
}
}
pub fn version(&self) -> &str {
match self {
Self::Ubuntu { version } | Self::Debian { version } | Self::Other { version, .. } => {
version
}
}
}
/// Whether this distribution has first-class support (auto-install via apt, prebuilt .debs, etc.).
pub fn is_supported(&self) -> bool {
matches!(self, Self::Ubuntu { .. } | Self::Debian { .. })
}
}
impl Display for LinuxDistribution {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.id(), self.version())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_os_bails_on_unsupported() {
let err = SupportedOs::from_os("windows").unwrap_err();
assert_eq!(err.to_string(), "Unsupported operating system: windows");
}
#[test]
fn os_release_version_prefers_version_id() {
let contents = r#"
ID=ubuntu
VERSION_ID="24.04"
BUILD_ID=rolling
"#;
let release = OsRelease::parse(contents);
assert_eq!(release.version(), Some("24.04"));
}
#[test]
fn os_release_version_falls_back_to_build_id() {
let contents = r#"
NAME="Arch Linux"
ID=arch
BUILD_ID=rolling
"#;
let release = OsRelease::parse(contents);
assert_eq!(release.version(), Some("rolling"));
}
#[test]
fn os_release_parse_handles_single_quoted_values() {
let contents = "ID=example\nVERSION_ID='1.2'\n";
let release = OsRelease::parse(contents);
assert_eq!(release.version(), Some("1.2"));
}
#[test]
fn os_release_parse_allows_whitespace_around_key() {
let contents = "VERSION_ID = \"24.04\"\n";
let release = OsRelease::parse(contents);
assert_eq!(release.version(), Some("24.04"));
}
#[test]
fn os_release_version_returns_none_without_version_fields() {
let contents = r#"
NAME="Unknown Linux"
ID=unknown
"#;
let release = OsRelease::parse(contents);
assert_eq!(release.version(), None);
}
}