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
#![allow(dead_code)]
#![allow(unused_imports)]
use crate::traits::{ReadoutError, ShellFormat};
use crate::extra;
use std::io::Error;
use std::path::Path;
use std::process::{Command, Stdio};
use std::{env, fs};
use std::{ffi::CStr, path::PathBuf};
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
use sysctl::SysctlError;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "android"))]
impl From<SysctlError> for ReadoutError {
fn from(e: SysctlError) -> Self {
ReadoutError::Other(format!("Could not access sysctl: {:?}", e))
}
}
impl From<std::io::Error> for ReadoutError {
fn from(e: Error) -> Self {
ReadoutError::Other(e.to_string())
}
}
#[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))]
pub(crate) fn uptime() -> Result<usize, ReadoutError> {
let uptime_file_text = fs::read_to_string("/proc/uptime")?;
let uptime_text = uptime_file_text.split_whitespace().next().unwrap();
let parsed_uptime = uptime_text.parse::<f64>();
match parsed_uptime {
Ok(s) => Ok(s as usize),
Err(e) => Err(ReadoutError::Other(format!(
"Could not convert '{}' to a digit: {:?}",
uptime_text, e
))),
}
}
#[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))]
pub(crate) fn desktop_environment() -> Result<String, ReadoutError> {
let desktop_env = env::var("DESKTOP_SESSION").or_else(|_| env::var("XDG_CURRENT_DESKTOP"));
match desktop_env {
Ok(de) => {
if de.to_lowercase() == "xinitrc" {
return Err(ReadoutError::Other(
"You appear to be only running a window manager.".to_string(),
));
}
Ok(extra::ucfirst(de))
}
Err(_) => Err(ReadoutError::Other(
"You appear to be only running a window manager.".to_string(),
)),
}
}
#[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))]
pub(crate) fn window_manager() -> Result<String, ReadoutError> {
if extra::which("wmctrl") {
let wmctrl = Command::new("wmctrl")
.arg("-m")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("ERROR: failed to spawn \"wmctrl\" process");
let wmctrl_out = wmctrl
.stdout
.expect("ERROR: failed to open \"wmctrl\" stdout");
let head = Command::new("head")
.args(&["-n", "1"])
.stdin(Stdio::from(wmctrl_out))
.stdout(Stdio::piped())
.spawn()
.expect("ERROR: failed to spawn \"head\" process");
let output = head
.wait_with_output()
.expect("ERROR: failed to wait for \"head\" process to exit");
let window_manager = String::from_utf8(output.stdout)
.expect("ERROR: \"wmctrl -m | head -n1\" process stdout was not valid UTF-8");
let window_man_name =
extra::pop_newline(String::from(window_manager.replace("Name:", "").trim()));
if window_man_name == "N/A" || window_man_name.is_empty() {
return Err(ReadoutError::Other(format!(
"Window manager not available — it could that it is not EWMH-compliant."
)));
}
return Ok(window_man_name);
}
Err(ReadoutError::Other(
"\"wmctrl\" must be installed to display your window manager.".to_string(),
))
}
#[cfg(target_family = "unix")]
fn get_passwd_struct() -> Result<*mut libc::passwd, ReadoutError> {
let uid: libc::uid_t = unsafe { libc::geteuid() };
let passwd = unsafe { libc::getpwuid(uid) };
if passwd != std::ptr::null_mut() {
return Ok(passwd);
}
Err(ReadoutError::Other(String::from(
"Unable to read account information.",
)))
}
#[cfg(target_family = "unix")]
pub(crate) fn username() -> Result<String, ReadoutError> {
let passwd = get_passwd_struct()?;
let name = unsafe { CStr::from_ptr((*passwd).pw_name) };
if let Ok(str) = name.to_str() {
return Ok(String::from(str));
}
Err(ReadoutError::Other(String::from(
"Unable to read username for the current UID.",
)))
}
#[cfg(target_family = "unix")]
pub(crate) fn shell(shorthand: ShellFormat) -> Result<String, ReadoutError> {
let passwd = get_passwd_struct()?;
let shell_name = unsafe { CStr::from_ptr((*passwd).pw_shell) };
if let Ok(str) = shell_name.to_str() {
let path = String::from(str);
match shorthand {
ShellFormat::Relative => {
let path = Path::new(&path);
let relative_name: &str = path.file_stem().unwrap().to_str().unwrap().into();
match relative_name {
"zsh" | "bash" | "fish" => return Ok(extra::ucfirst(relative_name)),
_ => return Ok(String::from(relative_name)),
}
}
_ => {
return Ok(path);
}
}
}
Err(ReadoutError::Other(String::from(
"Unable to read default shell for the current UID.",
)))
}
#[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))]
pub(crate) fn cpu_model_name() -> String {
use std::io::{BufRead, BufReader};
let file = fs::File::open("/proc/cpuinfo");
match file {
Ok(content) => {
let reader = BufReader::new(content);
for line in reader.lines().flatten() {
if line.starts_with("model name") {
return line
.replace("model name", "")
.replace(":", "")
.trim()
.to_string();
}
}
String::new()
}
Err(_e) => String::new(),
}
}
#[cfg(any(target_os = "macos", target_os = "netbsd"))]
pub(crate) fn cpu_usage() -> Result<usize, ReadoutError> {
let nelem: i32 = 1;
let mut value: f64 = 0.0;
let value_ptr: *mut f64 = &mut value;
let cpu_load = unsafe { libc::getloadavg(value_ptr, nelem) };
if cpu_load != -1 {
if let Ok(logical_cores) = cpu_cores() {
return Ok((value as f64 / logical_cores as f64 * 100.0).round() as usize);
}
}
Err(ReadoutError::Other(format!(
"getloadavg failed with return code: {}",
cpu_load
)))
}
#[cfg(target_family = "unix")]
pub(crate) fn cpu_cores() -> Result<usize, ReadoutError> {
Ok(num_cpus::get())
}
#[cfg(target_family = "unix")]
pub(crate) fn cpu_physical_cores() -> Result<usize, ReadoutError> {
Ok(num_cpus::get_physical())
}
#[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "android"))]
pub(crate) fn get_meminfo_value(value: &str) -> u64 {
use std::io::{BufRead, BufReader};
let file = fs::File::open("/proc/meminfo");
match file {
Ok(content) => {
let reader = BufReader::new(content);
for line in reader.lines().flatten() {
if line.starts_with(value) {
let s_mem_kb: String = line.chars().filter(|c| c.is_digit(10)).collect();
return s_mem_kb.parse::<u64>().unwrap_or(0);
}
}
0
}
Err(_e) => 0,
}
}
pub(crate) fn local_ip() -> Result<String, ReadoutError> {
if let Some(s) = local_ipaddress::get() {
Ok(s)
} else {
Err(ReadoutError::Other(String::from(
"Unable to get local IP address.",
)))
}
}
pub(crate) fn count_cargo() -> Option<usize> {
use std::fs::read_dir;
if let Ok(cargo_home) = std::env::var("CARGO_HOME") {
let cargo_bin = PathBuf::from(cargo_home).join("bin");
if cargo_bin.exists() {
if let Ok(read_dir) = read_dir(cargo_bin) {
return Some(read_dir.count());
}
}
return None;
}
None
}