Fix/Refactor based on clippy warnings

Also log errors/warnings to stderr instead of stdout, since swaybar
expects formatted stdout output.
This commit is contained in:
Stephen Seo 2022-07-09 22:53:01 +09:00
parent 750cc7065c
commit 49e50371a7
3 changed files with 84 additions and 49 deletions

View file

@ -1,4 +1,6 @@
use std::collections::HashMap;
use std::io;
use std::io::Write;
pub fn get_args() -> HashMap<String, String> {
let mut map = HashMap::new();
@ -19,8 +21,13 @@ pub fn get_args() -> HashMap<String, String> {
}
pub fn print_usage() {
println!("Usage:");
println!(" --help\t\t\tPrints help");
println!(" --netdev=<device_name>\tCheck network traffic on specified device");
println!(" --interval-sec=<seconds>\tOutput at intervals of <seconds> (default 5)");
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" --netdev=<device_name>\tCheck network traffic on specified device\n")
.ok();
stderr_handle
.write_all(b" --interval-sec=<seconds>\tOutput at intervals of <seconds> (default 5)\n")
.ok();
}

View file

@ -2,6 +2,7 @@ mod args;
mod proc;
mod swaybar_object;
use std::io::{self, Write};
use std::time::Duration;
use swaybar_object::*;
@ -25,13 +26,22 @@ fn main() {
if seconds_value > 0 {
interval = Duration::from_secs(seconds_value as u64);
} else {
println!(
"WARNING: Invalid --interval-sec=\"{}\", defaulting to 5!",
seconds_value
);
let mut stderr_handle = io::stderr().lock();
stderr_handle
.write_all(
format!(
"WARNING: Invalid --interval-sec=\"{}\", defaulting to 5!\n",
seconds_value
)
.as_bytes(),
)
.ok();
}
} else {
println!("WARNING: Failed to parse --interval-sec=?, defaulting to 5!");
let mut stderr_handle = io::stderr().lock();
stderr_handle
.write_all(b"WARNING: Failed to parse --interval-sec=?, defaulting to 5!\n")
.ok();
}
}
@ -48,28 +58,35 @@ fn main() {
// network traffic
if let Some(net) = &mut net_obj {
if let Err(e) = net.update() {
println!("{}", e);
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(e.to_string().as_bytes()).ok();
net_obj = None;
} else {
let netinfo_string = net.get_netstring();
let netinfo_parts: Vec<&str> = netinfo_string.split_whitespace().collect();
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();
} else {
let netinfo_string = netinfo_result.unwrap();
let netinfo_parts: Vec<&str> = netinfo_string.split_whitespace().collect();
{
let mut down_object = SwaybarObject::from_string(format!(
"{} {}",
netinfo_parts[0], netinfo_parts[1]
));
down_object.color = Some("#ff8888ff".into());
array.push_object(down_object);
}
{
let mut down_object = SwaybarObject::from_string(format!(
"{} {}",
netinfo_parts[0], netinfo_parts[1]
));
down_object.color = Some("#ff8888ff".into());
array.push_object(down_object);
}
{
let mut up_object = SwaybarObject::from_string(format!(
"{} {}",
netinfo_parts[2], netinfo_parts[3]
));
up_object.color = Some("#88ff88ff".into());
array.push_object(up_object);
{
let mut up_object = SwaybarObject::from_string(format!(
"{} {}",
netinfo_parts[2], netinfo_parts[3]
));
up_object.color = Some("#88ff88ff".into());
array.push_object(up_object);
}
}
}
}
@ -79,7 +96,8 @@ fn main() {
let meminfo_result = proc::get_meminfo();
let meminfo_string: String;
if let Err(e) = meminfo_result {
println!("{}", e);
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(format!("{}\n", e).as_bytes()).ok();
meminfo_string = String::from("MEMINFO ERROR");
} else {
meminfo_string = meminfo_result.unwrap();
@ -93,7 +111,8 @@ fn main() {
let loadavg_result = proc::get_loadavg();
let loadavg_string: String;
if let Err(e) = loadavg_result {
println!("{}", e);
let mut stderr_handle = io::stderr().lock();
stderr_handle.write_all(format!("{}\n", e).as_bytes()).ok();
loadavg_string = String::from("LOADAVG ERROR");
} else {
loadavg_string = loadavg_result.unwrap();

View file

@ -1,38 +1,47 @@
use std::fmt::Write;
use std::fs::File;
use std::io;
use std::io::prelude::*;
#[derive(Debug)]
pub enum Error {
IOError(std::io::Error),
ParseIntError(std::num::ParseIntError),
GenericError(String),
IO(std::io::Error),
ParseInt(std::num::ParseIntError),
Format(std::fmt::Error),
Generic(String),
}
impl From<std::io::Error> for Error {
fn from(io_error: std::io::Error) -> Self {
Self::IOError(io_error)
Self::IO(io_error)
}
}
impl From<std::num::ParseIntError> for Error {
fn from(parse_error: std::num::ParseIntError) -> Self {
Self::ParseIntError(parse_error)
Self::ParseInt(parse_error)
}
}
impl From<std::fmt::Error> for Error {
fn from(fmt_error: std::fmt::Error) -> Self {
Self::Format(fmt_error)
}
}
impl From<String> for Error {
fn from(string: String) -> Self {
Self::GenericError(string)
Self::Generic(string)
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::IOError(e) => e.fmt(f),
Error::ParseIntError(e) => e.fmt(f),
Error::GenericError(s) => f.write_str(s),
Error::IO(e) => e.fmt(f),
Error::ParseInt(e) => e.fmt(f),
Error::Format(e) => e.fmt(f),
Error::Generic(s) => f.write_str(s),
}
}
}
@ -40,8 +49,8 @@ impl std::fmt::Display for Error {
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::IOError(e) => e.source(),
Error::ParseIntError(e) => e.source(),
Error::IO(e) => e.source(),
Error::ParseInt(e) => e.source(),
_ => None,
}
}
@ -100,7 +109,7 @@ impl NetInfo {
Ok(())
}
pub fn get_netstring(&mut self) -> String {
pub fn get_netstring(&mut self) -> Result<String, Error> {
let down_diff: f64 = (self.down - self.prev_down) as f64;
self.prev_down = self.down;
let up_diff: f64 = (self.up - self.prev_up) as f64;
@ -108,22 +117,22 @@ impl NetInfo {
let mut output = String::new();
if down_diff > 1024.0 * 1024.0 {
output.push_str(&format!("{:.2} MiB ", down_diff / (1024.0 * 1024.0)));
write!(&mut output, "{:.2} MiB ", down_diff / (1024.0 * 1024.0))?;
} else if down_diff > 1024.0 {
output.push_str(&format!("{:.2} KiB ", down_diff / 1024.0));
write!(&mut output, "{:.2} KiB ", down_diff / 1024.0)?;
} else {
output.push_str(&format!("{:.0} B ", down_diff));
write!(&mut output, "{:.0} B ", down_diff)?;
}
if up_diff > 1024.0 * 1024.0 {
output.push_str(&format!("{:.2} MiB", up_diff / (1024.0 * 1024.0)));
write!(&mut output, "{:.2} MiB", up_diff / (1024.0 * 1024.0))?;
} else if up_diff > 1024.0 {
output.push_str(&format!("{:.2} KiB", up_diff / 1024.0));
write!(&mut output, "{:.2} KiB", up_diff / 1024.0)?;
} else {
output.push_str(&format!("{:.0} B", up_diff));
write!(&mut output, "{:.0} B", up_diff)?;
}
output
Ok(output)
}
}
@ -180,7 +189,7 @@ pub fn get_meminfo() -> Result<String, Error> {
output.push_str("KiB / ");
}
output.push_str(&format!("{} ", total));
write!(&mut output, "{} ", total)?;
if is_total_mega {
output.push_str("MiB");
} else {