ellip_dev_utils/
env.rs

1/*
2 * Ellip is licensed under The 3-Clause BSD, see LICENSE.
3 * Copyright 2025 Sira Pornsiriprasert <code@psira.me>
4 */
5
6pub struct Env {
7    pub rust_version: String,
8    pub platform: String,
9    pub ellip_version: String,
10    pub cpu: String,
11    /// Clock speed in Hz
12    pub clock_speed: u64,
13    pub total_memory: u64,
14}
15
16pub fn get_env() -> Env {
17    use std::fs;
18    use std::process::Command;
19
20    let clock_speed = {
21        // sysfs cpuinfo_max_freq (kHz)
22        fs::read_to_string("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq")
23            .ok()
24            .and_then(|s| s.trim().parse::<u64>().ok())
25            .map(|khz| khz * 1000) //Hz
26            .unwrap_or(0)
27    };
28
29    let mut sys = sysinfo::System::new_all();
30    sys.refresh_all();
31    let cpu = match sys.cpus().first() {
32        Some(cpu) => cpu.brand(),
33        None => "Unknown CPU",
34    }
35    .to_string();
36
37    let rust_version = {
38        let output = Command::new("rustc")
39            .arg("--version")
40            .output()
41            .unwrap()
42            .stdout;
43        String::from_utf8_lossy(&output)
44            .split_whitespace()
45            .collect::<Vec<&str>>()[1]
46            .to_owned()
47    };
48
49    let total_memory = sys.total_memory();
50
51    let platform = {
52        let output = Command::new("rustc").arg("-vV").output().unwrap().stdout;
53        String::from_utf8_lossy(&output)
54            .lines()
55            .find(|line| line.starts_with("host:"))
56            .unwrap()
57            .strip_prefix("host: ")
58            .unwrap()
59            .to_owned()
60    };
61
62    let ellip_version: String = {
63        let output = Command::new("cargo")
64            .args(["tree", "--invert", "--package", "ellip"])
65            .output()
66            .unwrap()
67            .stdout;
68        String::from_utf8_lossy(&output)
69            .lines()
70            .next()
71            .and_then(|line| line.strip_prefix("ellip v"))
72            .unwrap()
73            .split_whitespace()
74            .next()
75            .unwrap()
76            .to_owned()
77    };
78
79    Env {
80        rust_version,
81        platform,
82        ellip_version,
83        cpu,
84        clock_speed,
85        total_memory,
86    }
87}
88
89pub fn format_cpu_with_clock_speed(cpu: &str, clock_speed: u64) -> String {
90    if clock_speed == 0 {
91        return cpu.to_string();
92    }
93
94    if clock_speed > 1_000_000_000 {
95        format!("{} @{:.1} GHz", cpu, (clock_speed / 1_000_000_000) as f64)
96    } else {
97        format!("{} MHz", clock_speed / 1_000_000)
98    }
99}