1use std::fs::File;
2use std::io::{self, BufRead};
3
4use crate::squire;
5
6fn get_processor_info_darwin(lib_path: &str) -> Result<String, String> {
16 squire::util::run_command(lib_path, &["-n", "machdep.cpu.brand_string"], true)
17}
18
19fn get_processor_info_linux(lib_path: &str) -> Result<String, String> {
29 let file = match File::open(lib_path) {
30 Ok(file) => file,
31 Err(_) => return Err(format!("Failed to open '{}'", lib_path)),
32 };
33 for line in io::BufReader::new(file).lines() {
34 match line {
35 Ok(line) => {
36 if line.contains("model name") {
37 let parts: Vec<&str> = line.split(':').collect();
38 if parts.len() == 2 {
39 return Ok(parts[1].trim().to_string());
40 }
41 }
42 }
43 Err(_) => return Err(format!("Error reading lines in '{}'", lib_path)),
44 }
45 }
46 Err(format!("Model name not found in '{}'", lib_path))
47}
48
49fn get_processor_info_windows(lib_path: &str) -> Result<String, String> {
59 let result = squire::util::run_command(lib_path, &["cpu", "get", "name"], true);
60 let output = match result {
61 Ok(output) => output,
62 Err(_) => return Err("Failed to get processor info".to_string()),
63 };
64 let lines: Vec<&str> = output.trim().split('\n').collect();
65 if lines.len() > 1 {
66 Ok(lines[1].trim().to_string())
67 } else {
68 Err("Invalid output from command".to_string())
69 }
70}
71
72pub fn get_name() -> Option<String> {
78 let operating_system = std::env::consts::OS;
79 let result = match operating_system {
80 "macos" => get_processor_info_darwin("/usr/sbin/sysctl"),
81 "linux" => get_processor_info_linux("/proc/cpuinfo"),
82 "windows" => get_processor_info_windows("C:\\Windows\\System32\\wbem\\wmic.exe"),
83 _ => {
84 log::error!("Unsupported operating system: {}", operating_system);
85 Err("Unsupported operating system".to_string())
86 }
87 };
88 match result {
89 Ok(info) => Some(info),
90 Err(err) => {
91 log::error!("{}", err);
92 None
93 }
94 }
95}