Skip to content

Commit

Permalink
refactor: adjust expect messages
Browse files Browse the repository at this point in the history
All expect messages are adjusted or replaced with unwrap following the
guidelines here:

rust-lang/project-error-handling#50
rust-lang/rust#96033
  • Loading branch information
jtroo committed Aug 10, 2022
1 parent 2007321 commit e26c989
Show file tree
Hide file tree
Showing 7 changed files with 29 additions and 37 deletions.
16 changes: 8 additions & 8 deletions example_tcp_client/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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")
Expand Down Expand Up @@ -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}");
}
Expand All @@ -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}\"");
Expand Down
10 changes: 2 additions & 8 deletions src/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,9 +448,7 @@ fn parse_expr(expr: &str) -> Result<Vec<SExpr>> {
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();
Expand All @@ -469,11 +467,7 @@ fn parse_expr(expr: &str) -> Result<Vec<SExpr>> {
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!(
Expand Down
24 changes: 11 additions & 13 deletions src/kanata/mod.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn cli_init() -> Result<ValidatedArgs> {
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() {
Expand Down
2 changes: 1 addition & 1 deletion src/oskbd/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down
2 changes: 1 addition & 1 deletion src/oskbd/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
10 changes: 5 additions & 5 deletions src/tcp_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ impl TcpServer {
}

pub fn start(&mut self, kanata: Arc<Mutex<Kanata>>) {
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();

Expand All @@ -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);
Expand Down

0 comments on commit e26c989

Please sign in to comment.