Skip to content

Commit

Permalink
make clippy (pedantic) happy (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
VuiMuich authored Dec 18, 2022
1 parent 83a4098 commit 76da11c
Show file tree
Hide file tree
Showing 9 changed files with 43 additions and 31 deletions.
6 changes: 3 additions & 3 deletions lefthk-core/src/child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ impl Default for Children {

impl Children {
pub fn new() -> Self {
let (guard, _task_guard) = oneshot::channel();
let (guard, task_guard) = oneshot::channel();
let task_notify = Arc::new(Notify::new());
let notify = task_notify.clone();
let mut signals = Signals::new(&[signal::SIGCHLD]).expect("Couldn't setup signals.");
let mut signals = Signals::new([signal::SIGCHLD]).expect("Couldn't setup signals.");
tokio::task::spawn_blocking(move || loop {
if guard.is_closed() {
return;
Expand All @@ -45,7 +45,7 @@ impl Children {

Self {
task_notify,
_task_guard,
_task_guard: task_guard,
inner: HashMap::default(),
}
}
Expand Down
4 changes: 2 additions & 2 deletions lefthk-core/src/config/command/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ inventory::submit! {DenormalizeCommandFunction::new::<Execute>()}
pub struct Execute(String);

impl Execute {
pub fn new<T: ToString>(shell_command: T) -> Self {
pub fn new<T: ToString>(shell_command: &T) -> Self {
Self(shell_command.to_string())
}
}
Expand Down Expand Up @@ -59,7 +59,7 @@ mod tests {

#[test]
fn normalize_process() {
let command = Execute::new("echo 'I use Arch by the way'");
let command = Execute::new(&"echo 'I use Arch by the way'");

let normalized = command.normalize();
let denormalized = Execute::denormalize(&normalized).unwrap();
Expand Down
16 changes: 11 additions & 5 deletions lefthk-core/src/config/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,30 @@ pub use self::{chord::Chord, execute::Execute, exit_chord::ExitChord, kill::Kill

inventory::collect!(DenormalizeCommandFunction);

// When adding a command:
// - a command has to submit itself to the inventory
// - write a test that it's conversion between normalizel and denormalize works
/// When adding a command:
/// - a command has to submit itself to the inventory
/// - write a test that it's conversion between normalizel and denormalize works
pub trait Command: std::fmt::Debug {
fn normalize(&self) -> NormalizedCommand;

fn denormalize(generalized: &NormalizedCommand) -> Option<Box<Self>>
where
Self: Sized;

/// # Errors
///
/// This errors when the command cannot be executed by the worker
fn execute(&self, worker: &mut Worker) -> Error;

fn get_name(&self) -> &'static str;
}

pub fn denormalize(normalized_command: NormalizedCommand) -> Result<Box<dyn Command>> {
/// # Errors
///
/// This errors when the command cannot be matched with the known commands
pub fn denormalize(normalized_command: &NormalizedCommand) -> Result<Box<dyn Command>> {
for denormalizer in inventory::iter::<DenormalizeCommandFunction> {
if let Some(denormalized_command) = (denormalizer.0)(&normalized_command) {
if let Some(denormalized_command) = (denormalizer.0)(normalized_command) {
return Ok(denormalized_command);
}
}
Expand Down
8 changes: 4 additions & 4 deletions lefthk-core/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl Drop for Pipe {

// Open fifo for write to unblock pending open for read operation that prevents tokio runtime
// from shutting down.
let _ = std::fs::OpenOptions::new()
let _unplock_pending_open = std::fs::OpenOptions::new()
.write(true)
.custom_flags(nix::fcntl::OFlag::O_NONBLOCK.bits())
.open(self.pipe_file.clone());
Expand All @@ -35,7 +35,7 @@ impl Pipe {
/// Will error if unable to `mkfifo`, likely a filesystem issue
/// such as inadequate permissions.
pub async fn new(pipe_file: PathBuf) -> Result<Self> {
let _ = fs::remove_file(pipe_file.as_path()).await;
let _pipe_reset = fs::remove_file(pipe_file.as_path()).await;
nix::unistd::mkfifo(&pipe_file, nix::sys::stat::Mode::S_IRWXU)?;

let path = pipe_file.clone();
Expand All @@ -61,7 +61,7 @@ impl Pipe {

pub async fn get_next_command(&mut self) -> Option<Box<dyn Command>> {
if let Some(normalized_command) = self.rx.recv().await {
return command::denormalize(normalized_command).ok();
return command::denormalize(&normalized_command).ok();
}
None
}
Expand All @@ -74,7 +74,7 @@ async fn read_from_pipe<'a>(pipe_file: &Path, tx: &mpsc::UnboundedSender<Normali
while let Ok(line) = lines.next_line().await {
if let Some(content) = line {
if let Ok(normalized_command) = NormalizedCommand::try_from(content) {
if command::denormalize(normalized_command.clone()).is_ok() {
if command::denormalize(&normalized_command.clone()).is_ok() {
if let Err(err) = tx.send(normalized_command) {
tracing::error!("{}", err);
}
Expand Down
2 changes: 1 addition & 1 deletion lefthk-core/src/worker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl Worker {
let key = self.xwrap.keycode_to_keysym(event.keycode);
let mask = xkeysym_lookup::clean_mask(event.state);
if let Some(keybind) = self.get_keybind((mask, key)) {
if let Ok(command) = command::denormalize(keybind.command) {
if let Ok(command) = command::denormalize(&keybind.command) {
return command.execute(self);
}
} else {
Expand Down
6 changes: 4 additions & 2 deletions lefthk-core/src/xwrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ impl XWrap {
///
/// Panics if unable to contact xorg.
#[must_use]
#[allow(clippy::items_after_statements)]
pub fn new() -> Self {
const SERVER: mio::Token = mio::Token(0);
let xlib = errors::exit_on_error!(xlib::Xlib::open());
let display = unsafe { (xlib.XOpenDisplay)(ptr::null()) };
assert!(!display.is_null(), "Null pointer in display");

let fd = unsafe { (xlib.XConnectionNumber)(display) };
let (guard, _task_guard) = oneshot::channel();
let (guard, task_guard) = oneshot::channel();
let notify = Arc::new(Notify::new());
let task_notify = notify.clone();
let mut poll = errors::exit_on_error!(mio::Poll::new());
Expand Down Expand Up @@ -69,7 +70,7 @@ impl XWrap {
display,
root,
task_notify,
_task_guard,
_task_guard: task_guard,
};

// Setup cached keymap/modifier information, otherwise MappingNotify might never be called
Expand All @@ -80,6 +81,7 @@ impl XWrap {
// This is allowed for now as const extern fns
// are not yet stable (1.56.0, 16 Sept 2021)
// see issue #64926 <https://github.com/rust-lang/rust/issues/64926> for more information
// also this is the reason for #[allow(clippy::items_after_statements)] above
#[allow(clippy::missing_const_for_fn)]
extern "C" fn on_error_from_xlib(
_: *mut xlib::Display,
Expand Down
7 changes: 3 additions & 4 deletions lefthk/src/config/keybind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl TryFrom<Keybind> for Vec<core_keybind> {
Command::Chord(_) => return Err(LeftError::ChildrenNotFound),
Command::Execute(value) if !value.is_empty() => {
let keys = get_key!(kb.key);
vec![(Box::new(command_mod::Execute::new(value)), keys)]
vec![(Box::new(command_mod::Execute::new(&value)), keys)]
}
Command::Execute(_) => return Err(LeftError::ValueNotFound),
Command::Executes(values) if !values.is_empty() => {
Expand All @@ -73,8 +73,7 @@ impl TryFrom<Keybind> for Vec<core_keybind> {
.enumerate()
.map(|(i, v)| {
(
Box::new(command_mod::Execute::new(v.to_owned()))
as Box<dyn core_command>,
Box::new(command_mod::Execute::new(&v)) as Box<dyn core_command>,
keys[i].clone(),
)
})
Expand All @@ -99,7 +98,7 @@ impl TryFrom<Keybind> for Vec<core_keybind> {
.map(|(c, k)| core_keybind {
command: c.normalize(),
modifier: kb.modifier.clone(),
key: k.to_owned(),
key: k.clone(),
})
.collect();
Ok(keybinds)
Expand Down
10 changes: 7 additions & 3 deletions lefthk/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ impl lefthk_core::config::Config for Config {
}
}

/// # Errors
///
/// Thes will error when no config file is found, most propably as system or
/// user error for provideng a wrong path
pub fn load() -> Result<Config> {
let path = BaseDirectories::with_prefix(lefthk_core::LEFTHK_DIR_NAME)?;
fs::create_dir_all(&path.get_config_home())?;
Expand All @@ -51,14 +55,14 @@ pub fn load() -> Result<Config> {
.iter_mut()
.filter(|kb| matches!(kb.command, Command::Chord(_)))
.collect();
propagate_exit_chord(chords, global_exit_chord);
propagate_exit_chord(chords, &global_exit_chord);

return Ok(config);
}
Err(LeftError::NoConfigFound)
}

fn propagate_exit_chord(chords: Vec<&mut Keybind>, exit_chord: Option<Keybind>) {
fn propagate_exit_chord(chords: Vec<&mut Keybind>, exit_chord: &Option<Keybind>) {
for chord in chords {
if let Command::Chord(children) = &mut chord.command {
if !children.iter().any(|kb| kb.command == Command::ExitChord) {
Expand All @@ -74,7 +78,7 @@ fn propagate_exit_chord(chords: Vec<&mut Keybind>, exit_chord: Option<Keybind>)
.iter_mut()
.filter(|kb| matches!(kb.command, Command::Chord(_)))
.collect();
propagate_exit_chord(sub_chords, parent_exit_chord);
propagate_exit_chord(sub_chords, &parent_exit_chord);
}
}
}
15 changes: 8 additions & 7 deletions lefthk/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,24 @@ fn main() {
tracing::info!("lefthk booted!");

if matches.contains_id(QUIT_COMMAND) {
send_command(command::Kill::new());
send_command(&command::Kill::new());
} else if matches.contains_id(RELOAD_COMMAND) {
send_command(command::Reload::new());
send_command(&command::Reload::new());
} else {
let mut old_config = None;
let path =
errors::exit_on_error!(BaseDirectories::with_prefix(lefthk_core::LEFTHK_DIR_NAME));
loop {
let config = match config::load() {
Ok(config) => config,
Err(err) => match old_config {
Some(config) => config,
None => {
Err(err) => {
if let Some(config) = old_config {
config
} else {
tracing::error!("Unable to load new config due to error: {}", err);
return;
}
},
}
};
let kill_requested = AtomicBool::new(false);
let completed = std::panic::catch_unwind(|| {
Expand All @@ -65,7 +66,7 @@ fn main() {
}
}

fn send_command(command: impl Command) {
fn send_command(command: &impl Command) {
let path = errors::exit_on_error!(BaseDirectories::with_prefix(lefthk_core::LEFTHK_DIR_NAME));
let pipe_name = Pipe::pipe_name();
let pipe_file = errors::exit_on_error!(path.place_runtime_file(pipe_name));
Expand Down

0 comments on commit 76da11c

Please sign in to comment.