Refactor main.rs handling of network stats

This commit is contained in:
Stephen Seo 2022-07-10 17:47:51 +09:00
parent 251125366c
commit 35ff17ef0f
2 changed files with 46 additions and 50 deletions

View file

@ -16,7 +16,7 @@ pub fn get_args() -> HashMap<String, String> {
} else if arg.starts_with("--interval-sec=") {
let (_, back) = arg.split_at(15);
map.insert("interval-sec".into(), back.into());
} else if arg.starts_with("--help") || arg.starts_with("-h") {
} else if arg == "--help" || arg == "-h" {
map.insert("help".into(), "".into());
} else {
let mut stderr_handle = io::stderr().lock();
@ -32,7 +32,9 @@ pub fn get_args() -> HashMap<String, String> {
pub fn print_usage() {
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(b"Usage:\n").ok();
stderr_handle.write_all(b" --help\t\t\tPrints help\n").ok();
stderr_handle
.write_all(b" -h | --help\t\t\tPrints help\n")
.ok();
stderr_handle
.write_all(b" --netdev=<device_name>\tCheck network traffic on specified device\n")
.ok();

View file

@ -73,26 +73,12 @@ fn main() {
}
};
loop {
let is_empty = array.is_empty();
// network traffic
if let Some(net) = &mut net_obj {
if let Err(e) = net.update() {
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(e.to_string().as_bytes()).ok();
net_obj = None;
set_net_error(is_empty, &mut array);
} else {
let netinfo_result = net.get_netstring();
if let Err(e) = netinfo_result {
{
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(e.to_string().as_bytes()).ok();
}
set_net_error(is_empty, &mut array);
} else {
let netinfo_string = netinfo_result.unwrap();
let handle_net = |is_empty: bool,
net: &mut proc::NetInfo,
array: &mut SwaybarArray|
-> Result<(), proc::Error> {
net.update()?;
let netinfo_string = net.get_netstring()?;
let netinfo_parts: Vec<&str> = netinfo_string.split_whitespace().collect();
if is_empty {
@ -115,20 +101,28 @@ fn main() {
}
} else {
if let Some(down_object) = array.get_by_name_mut("net_down") {
down_object.update_as_net_down(format!(
"{} {}",
netinfo_parts[0], netinfo_parts[1]
));
down_object
.update_as_net_down(format!("{} {}", netinfo_parts[0], netinfo_parts[1]));
}
if let Some(up_object) = array.get_by_name_mut("net_up") {
up_object.update_as_net_up(format!(
"{} {}",
netinfo_parts[2], netinfo_parts[3]
));
}
up_object.update_as_net_up(format!("{} {}", netinfo_parts[2], netinfo_parts[3]));
}
}
Ok(())
};
loop {
let is_empty = array.is_empty();
// network traffic
if let Some(net) = net_obj.as_mut() {
if let Err(e) = handle_net(is_empty, net, &mut array) {
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(e.to_string().as_bytes()).ok();
net_obj = None;
set_net_error(is_empty, &mut array);
}
}