Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: adjust expect messages #102

Merged
merged 1 commit into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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