lscpu: Use common function to read fields from /proc/cpuinfo

This commit is contained in:
alxndrv 2025-02-12 17:05:37 +02:00
parent 9e1b825a7d
commit edb3b83ec9

@ -67,14 +67,21 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
// Add more CPU information here... // Add more CPU information here...
if let Ok(contents) = fs::read_to_string("/proc/cpuinfo") { if let Ok(contents) = fs::read_to_string("/proc/cpuinfo") {
let re = RegexBuilder::new(r"^model name\s+:\s+(.*)$") if let Some(cpu_model) = find_cpuinfo_value(&contents, "model name") {
.multi_line(true) if let Some(addr_sizes) = find_cpuinfo_value(&contents, "address sizes") {
.build() cpu_infos.push(
.unwrap(); "Model name",
// Assuming all CPUs have the same model name cpu_model.as_str(),
if let Some(cap) = re.captures_iter(&contents).next() { Some(vec![CpuInfo {
cpu_infos.push("Model name", &cap[1], None); field: "Address sizes".to_string(),
}; data: addr_sizes,
children: vec![],
}]),
);
} else {
cpu_infos.push("Model name", cpu_model.as_str(), None);
}
}
} }
if json { if json {
@ -87,6 +94,20 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
Ok(()) Ok(())
} }
fn find_cpuinfo_value(contents: &str, key: &str) -> Option<String> {
let pattern = format!(r"^{}\s+:\s+(.*)$", key);
let re = RegexBuilder::new(pattern.as_str())
.multi_line(true)
.build()
.unwrap();
if let Some(cap) = re.captures_iter(contents).next() {
return Some(cap[1].to_string());
};
None
}
fn get_architecture() -> String { fn get_architecture() -> String {
if cfg!(target_arch = "x86") { if cfg!(target_arch = "x86") {
"x86".to_string() "x86".to_string()