From b3cb53b68476b11aac70980926c0c05eae475eb3 Mon Sep 17 00:00:00 2001 From: Jan Tache Date: Tue, 9 Aug 2022 22:06:38 -0700 Subject: [PATCH] refactor: adjust expect messages All expect messages are adjusted or replaced with unwrap following the guidelines here: https://github.com/rust-lang/project-error-handling/issues/50 https://github.com/rust-lang/rust/pull/96033 --- example_tcp_client/src/main.rs | 16 ++++++++-------- src/cfg.rs | 10 ++-------- src/kanata/mod.rs | 24 +++++++++++------------- src/main.rs | 2 +- src/oskbd/linux.rs | 2 +- src/oskbd/windows.rs | 2 +- src/tcp_server.rs | 10 +++++----- 7 files changed, 29 insertions(+), 37 deletions(-) diff --git a/example_tcp_client/src/main.rs b/example_tcp_client/src/main.rs index 62166d21c..8b733ec6c 100644 --- a/example_tcp_client/src/main.rs +++ b/example_tcp_client/src/main.rs @@ -31,11 +31,11 @@ fn main() { &SocketAddr::from(([127, 0, 0, 1], args.port)), Duration::from_secs(5), ) - .expect("could not connect to kanata"); + .expect("connect to kanata"); log::info!("successfully connected"); let writer_stream = kanata_conn .try_clone() - .expect("failed to clone socket handle"); + .unwrap(); let reader_stream = kanata_conn; std::thread::spawn(move || write_to_kanata(writer_stream)); read_from_kanata(reader_stream); @@ -57,7 +57,7 @@ fn init_logger(args: &Args) { TerminalMode::Mixed, ColorChoice::AlwaysAnsi, )]) - .expect("failed to initialize logger"); + .unwrap(); log::info!( "kanata_example_tcp_client v{} starting", env!("CARGO_PKG_VERSION") @@ -87,13 +87,13 @@ fn write_to_kanata(mut s: TcpStream) { log::info!("writer: type layer name then press enter to send a change layer request to kanata"); let mut layer = String::new(); loop { - stdin().read_line(&mut layer).expect("failed to read stdin"); + stdin().read_line(&mut layer).expect("stdin is readable"); let new = layer.trim_end().to_owned(); log::info!("writer: telling kanata to change layer to \"{new}\""); let msg = - serde_json::to_string(&ClientMessage::ChangeLayer { new }).expect("deserialize failed"); + serde_json::to_string(&ClientMessage::ChangeLayer { new }).expect("deserializable"); let expected_wsz = msg.len(); - let wsz = s.write(msg.as_bytes()).expect("write failed"); + let wsz = s.write(msg.as_bytes()).expect("stream writable"); if wsz != expected_wsz { panic!("failed to write entire message {wsz} {expected_wsz}"); } @@ -105,9 +105,9 @@ fn read_from_kanata(mut s: TcpStream) { log::info!("reader starting"); let mut buf = vec![0; 256]; loop { - let sz = s.read(&mut buf).expect("read failed"); + let sz = s.read(&mut buf).expect("stream readable"); let msg = String::from_utf8_lossy(&buf[..sz]); - let parsed_msg = ServerMessage::from_str(&msg).expect("invalid msg from kanata"); + let parsed_msg = ServerMessage::from_str(&msg).expect("kanata sends valid message"); match parsed_msg { ServerMessage::LayerChange { new } => { log::info!("reader: kanata changed layers to \"{new}\""); diff --git a/src/cfg.rs b/src/cfg.rs index 5b1f2af86..9dc290fbf 100644 --- a/src/cfg.rs +++ b/src/cfg.rs @@ -448,9 +448,7 @@ fn parse_expr(expr: &str) -> Result> { expr ) } else if token.starts_with('"') { - let mut token = token - .strip_prefix('"') - .expect("Dquote prefix was checked. Cosmic ray?"); + let mut token = token.strip_prefix('"').unwrap(); let mut quoted_tokens = vec![]; loop { let num_dquotes = token.matches('"').count(); @@ -469,11 +467,7 @@ fn parse_expr(expr: &str) -> Result> { if !token.ends_with('"') { bail!("Invalid end of quoted string {}", token); } - quoted_tokens.push( - token - .strip_suffix('"') - .expect("Dquote suffix was checked. Cosmic ray?"), - ); + quoted_tokens.push(token.strip_suffix('"').unwrap()); break; } _ => bail!( diff --git a/src/kanata/mod.rs b/src/kanata/mod.rs index 3654d9f09..d2f9a113c 100644 --- a/src/kanata/mod.rs +++ b/src/kanata/mod.rs @@ -1,6 +1,6 @@ //! Implements the glue between OS input/output and keyberon state management. -use anyhow::{bail, Result}; +use anyhow::{anyhow, bail, Result}; use log::{error, info}; use crossbeam_channel::{Receiver, Sender, TryRecvError}; @@ -75,14 +75,14 @@ impl Kanata { } }; - #[cfg(target_os = "linux")] - let kbd_in_paths = cfg - .items - .get("linux-dev") - .cloned() - .expect("linux-dev required in defcfg"); - #[cfg(target_os = "windows")] - let kbd_in_paths = "unused".into(); + let kbd_in_paths = if cfg!(target_os = "linux") { + cfg.items + .get("linux-dev") + .cloned() + .ok_or_else(|| anyhow!("A linux-dev entry is required in defcfg"))? + } else { + "unused".into() + }; #[cfg(target_os = "windows")] unsafe { @@ -488,9 +488,7 @@ impl Kanata { if kev.value == KeyValue::Release { let mut k = kanata.lock(); info!("Init: releasing {:?}", kev.code); - k.kbd_out - .release_key(kev.code) - .expect("could not release key"); + k.kbd_out.release_key(kev.code).expect("key released"); } } std::thread::sleep(time::Duration::from_millis(1)); @@ -537,7 +535,7 @@ fn run_cmd(cmd_and_args: &'static [String]) -> std::thread::JoinHandle<()> { let mut args = cmd_and_args.iter().cloned(); let mut cmd = std::process::Command::new( args.next() - .expect("Parsing should have forbidden empty cmd"), + .expect("parsing should have forbidden empty cmd"), ); for arg in args { cmd.arg(arg); diff --git a/src/main.rs b/src/main.rs index 5321c41fd..a72760f53 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,7 +71,7 @@ fn cli_init() -> Result { TerminalMode::Mixed, ColorChoice::AlwaysAnsi, )]) - .expect("Couldn't initialize the logger"); + .expect("logger can init"); log::info!("kanata v{} starting", env!("CARGO_PKG_VERSION")); if !cfg_path.exists() { diff --git a/src/oskbd/linux.rs b/src/oskbd/linux.rs index 3f70a25ba..f9327a611 100644 --- a/src/oskbd/linux.rs +++ b/src/oskbd/linux.rs @@ -179,7 +179,7 @@ impl KbdOut { let mut s = String::new(); for c in hex.chars() { s.push(c); - let osc = str_to_oscode(&s).expect("invalid char in unicode output"); + let osc = str_to_oscode(&s).expect("valid keycodes for unicode"); s.clear(); self.press_key(osc)?; self.release_key(osc)?; diff --git a/src/oskbd/windows.rs b/src/oskbd/windows.rs index 65dd75149..aaea79d82 100644 --- a/src/oskbd/windows.rs +++ b/src/oskbd/windows.rs @@ -63,7 +63,7 @@ impl<'a> KeyboardHook<'a> { handle: unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(hook_proc), ptr::null_mut(), 0) .as_mut() - .expect("Failed to install low-level keyboard hook.") + .expect("install low-level keyboard hook successfully") }, lifetime: PhantomData, } diff --git a/src/tcp_server.rs b/src/tcp_server.rs index 2c5d92db0..56c974bac 100644 --- a/src/tcp_server.rs +++ b/src/tcp_server.rs @@ -48,8 +48,8 @@ impl TcpServer { } pub fn start(&mut self, kanata: Arc>) { - let listener = TcpListener::bind(format!("0.0.0.0:{}", self.port)) - .expect("could not start the tcp server"); + let listener = + TcpListener::bind(format!("0.0.0.0:{}", self.port)).expect("TCP server starts"); let connections = self.connections.clone(); @@ -59,16 +59,16 @@ impl TcpServer { Ok(mut stream) => { stream .set_keepalive(Some(Duration::from_secs(30))) - .expect("could not set tcp connection keepalive"); + .expect("TCP keepalive is set"); let addr = stream .peer_addr() - .expect("could not find peer address") + .expect("incoming conn has known address") .to_string(); connections.lock().insert( addr.clone(), - stream.try_clone().expect("could not clone stream"), + stream.try_clone().expect("stream is clonable"), ); log::info!("listening for incoming messages {}", &addr);