mac_sys_info/lib.rs
1/*
2MIT License
3
4Copyright (c) 2020 Philipp Schuster
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24
25//! Library to get Mac-specific system info. The information is retrieved from the `$ sysctl -a`
26//! command. It gives you structured access to system info as well as raw access to all keys.
27
28#[macro_use]
29extern crate log;
30
31use crate::error::MacSysInfoError;
32use unix_exec_output_catcher::{fork_exec_and_catch, OCatchStrategy};
33use crate::parse::{parse_sysctl_line};
34use crate::structs::MacSysInfo;
35use std::collections::{BTreeMap};
36
37pub mod error;
38pub mod generated_sysctl_keys;
39mod parse;
40pub mod structs;
41
42/// Executes the "sysctl" binary with the "-a" option in a child process
43/// and captures it's output.
44fn fetch_info_from_sysctl() -> Result<Vec<(String, String)>, MacSysInfoError> {
45 let res = fork_exec_and_catch("sysctl", vec!["sysctl", "-a"], OCatchStrategy::StdSeparately)
46 .map_err(|inner| MacSysInfoError::CantFetchData(inner))?;
47 let res = res.stdout_lines().ok_or(MacSysInfoError::NoCapturedOutput)?;
48 let res = res.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
49 let key_value_vector = res.iter()
50 .map(|s| parse_sysctl_line(s))
51 .collect::<Vec<(String, String)>>();
52
53 Ok(key_value_vector)
54}
55
56/// Returns system information about your Mac. The information is retrieved
57/// from the `sysctl -a` command.
58pub fn get_mac_sys_info() -> Result<MacSysInfo, MacSysInfoError> {
59 let key_value_vector = fetch_info_from_sysctl()?;
60
61 // build the raw string to string map of all supported information
62 let mut all_keys = BTreeMap::new();
63 key_value_vector.into_iter()
64 .for_each(|(sys_key, sys_value)| {
65 all_keys.insert(sys_key, sys_value);
66 });
67
68 Ok(
69 MacSysInfo::new(all_keys)?
70 )
71}
72
73#[cfg(test)]
74mod tests {
75 use crate::get_mac_sys_info;
76
77 #[test]
78 fn test_get_sys_info() {
79 let _res = get_mac_sys_info();
80 }
81}