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
pub use self::machineid::get;
pub use self::machineid::get_via_windows_shell;
pub use self::machineid::get_via_linux_shell;
pub use self::machineid::transform_windows_output;
pub mod machineid {
use std::process::Command;
pub fn get() -> String
{
let mut uuid = String::from("");
if cfg!(windows) {
let output = get_via_windows_shell();
uuid = transform_windows_output(output);
} else if cfg!(unix) {
uuid = get_via_linux_shell();
}
return uuid;
}
pub fn get_via_windows_shell() -> String {
let output = Command::new("cmd")
.args(&["/C", "wmic csproduct get UUID"])
.output()
.expect("failed to execute process");
let result = match String::from_utf8(output.stdout)
{
Ok(line) => line,
Err(_) => {
println!("Failed to retrieve UUID from windows shell.");
String::from("")
}
};
return result;
}
pub fn get_via_linux_shell() -> String {
let output = Command::new("sh")
.arg("-c")
.arg("cat /etc/machine-id")
.output()
.expect("failed to execute process");
let result = match String::from_utf8(output.stdout)
{
Ok(line) => line,
Err(_) => {
println!("Failed to retrieve UUID from linux shell.");
String::from("")
}
};
return result;
}
pub fn transform_windows_output(output: String) -> String {
let parts: Vec<&str> = output.splitn(2, ' ').collect();
return String::from(parts[1].trim());
}
}
#[cfg(test)]
mod tests {
use super::*;
use regex::Regex;
#[test]
fn test_if_gets_uuid() {
if cfg!(windows) {
let output = machineid::get_via_windows_shell();
let result = transform_windows_output(output);
let re = Regex::new(r"\b[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}\b").unwrap();
assert!(re.is_match(&result.to_lowercase()));
} else {
let result = machineid::get_via_linux_shell();
assert!(result.trim().len() == 32);
}
}
}