readcon_core/
hostlabel.rs1use std::fs;
8
9pub fn normalize_cpu(raw: &str) -> String {
11 let stripped = raw.replace("(R)", "").replace("(TM)", "").replace('®', "");
12 let cleaned = stripped.split_whitespace().collect::<Vec<_>>().join(" ");
13 if cleaned.contains("Xeon") {
14 return "Intel Xeon Processor".to_string();
15 }
16 if cleaned.is_empty() {
17 "unknown".to_string()
18 } else {
19 cleaned
20 }
21}
22
23pub fn cpu_model() -> String {
25 if let Ok(text) = fs::read_to_string("/proc/cpuinfo") {
26 for line in text.lines() {
27 if line.to_ascii_lowercase().starts_with("model name")
28 && let Some((_, value)) = line.split_once(':')
29 {
30 let value = value.trim();
31 if !value.is_empty() {
32 return normalize_cpu(value);
33 }
34 }
35 }
36 }
37 "unknown".to_string()
38}
39
40#[cfg(test)]
41mod tests {
42 use super::cpu_model;
43 use std::fs;
44
45 #[test]
46 fn cpu_model_value() {
47 println!("CPU_MODEL={}", cpu_model());
48 }
49
50 #[test]
51 fn normalize_cpu_matches_the_python_record_name() {
52 assert_eq!(
53 super::normalize_cpu("Intel(R) Xeon(R) Processor"),
54 "Intel Xeon Processor"
55 );
56 assert_eq!(
57 super::normalize_cpu("Intel(R) Core(TM) i7"),
58 "Intel Core i7"
59 );
60 assert_eq!(super::normalize_cpu(" AMD EPYC "), "AMD EPYC");
61 assert_eq!(super::normalize_cpu(" "), "unknown");
62 }
63
64 #[test]
65 fn cpu_model_is_not_a_hostname_token() {
66 let cpu = cpu_model();
67 assert!(!cpu.is_empty());
68 match fs::read_to_string("/etc/hostname") {
69 Ok(text) => {
70 let node = text.trim();
71 if !node.is_empty() {
72 assert!(cpu.split('-').all(|token| token != node));
73 }
74 }
75 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
76 Err(err) => panic!("reading /etc/hostname failed: {err}"),
77 }
78 }
79}