Skip to content

Commit

Permalink
Use derive(Debug) for Error (#35)
Browse files Browse the repository at this point in the history
This change help us to save 13 LOC.

Additionally, this PR makes config errors more explicit (including file path and line number)
  • Loading branch information
ilai-deutel authored Apr 1, 2020
1 parent 46566d2 commit dfca4be
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 30 deletions.
14 changes: 7 additions & 7 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;

use crate::{sys::conf_dirs, Error};
use crate::{sys::conf_dirs, Error, Error::Config as ConfErr};

/// The global Kibi configuration.
pub struct Config {
Expand Down Expand Up @@ -85,18 +85,18 @@ impl Config {

/// Process an INI file.
///
/// The `deser_fn` will be called for each key-value pair in the file. Typically, this function will
/// update a configuration instance.
pub(crate) fn process_ini_file<F>(path: &Path, deser_fn: &mut F) -> Result<(), Error>
/// The `kv_fn` function will be called for each key-value pair in the file. Typically, this
/// function will update a configuration instance.
pub(crate) fn process_ini_file<F>(path: &Path, kv_fn: &mut F) -> Result<(), Error>
where F: FnMut(&str, &str) -> Result<(), String> {
for line in BufReader::new(File::open(path)?).lines() {
for (i, line) in BufReader::new(File::open(path)?).lines().enumerate() {
let line = line?;
let mut parts = line.trim_start().splitn(2, '=');
match (parts.next(), parts.next()) {
(Some(comment_line), _) if comment_line.starts_with(&['#', ';'][..]) => (),
(Some(k), Some(v)) => deser_fn(k.trim_end(), v).map_err(|r| Error::Config(line, r))?,
(Some(k), Some(v)) => kv_fn(k.trim_end(), v).map_err(|r| ConfErr(path.into(), i, r))?,
(Some(""), None) | (None, _) => (), // Empty line
(Some(_), None) => return Err(Error::Config(line, String::from("No '='"))),
(Some(_), None) => return Err(ConfErr(path.into(), i, String::from("No '='"))),
}
}
Ok(())
Expand Down
36 changes: 14 additions & 22 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,42 +1,34 @@
//! # Errors
use std::fmt::{self, Debug, Formatter};

/// These errors can used in the program.
/// Kibi error type.
#[derive(Debug)]
pub enum Error {
/// Wrapper around `std::io::Error`
IO(std::io::Error),
/// Wrapper around `nix::Error`
#[cfg(unix)]
Nix(nix::Error),
InvalidWindowSize,
/// Wrapper around `std::sync::mpsc::TryRecvError`
MPSCTryRecv(std::sync::mpsc::TryRecvError),
/// Error returned when the window size obtained through a system call is invalid.
InvalidWindowSize,
/// Error setting or retrieving the cursor position.
CursorPosition,
Config(String, String),
/// Configuration error. The three attributes correspond the file path, the line number and the
/// error message.
Config(std::path::PathBuf, usize, String),
/// Too many arguments given to kibi. The attribute corresponds to the total number of command
/// line armuments.
TooManyArguments(usize),
}

impl Debug for Error {
/// Format the value using the given formatter.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::IO(err) => write!(f, "IO error: {}", err),
#[cfg(unix)]
Self::Nix(err) => write!(f, "System call error: {}", err),
Self::InvalidWindowSize => write!(f, "Invalid window size"),
Self::MPSCTryRecv(err) => write!(f, "MSPC try_recv error: {}", err),
Self::CursorPosition => write!(f, "Could not obtain cursor position"),
Self::Config(line, reason) => write!(f, "Could not parse config {}: {}", line, reason),
Self::TooManyArguments(n) => write!(f, "Expected 0 or 1 argument, got {}", n),
}
}
}

impl From<std::io::Error> for Error {
/// Convert an IO Error into a Kibi Error.
fn from(err: std::io::Error) -> Self { Self::IO(err) }
}

#[cfg(unix)]
impl From<nix::Error> for Error {
/// Convert a nix IO Error into a Kibi Error.
/// Convert a nix Error into a Kibi Error.
fn from(err: nix::Error) -> Self { Self::Nix(err) }
}
2 changes: 1 addition & 1 deletion src/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) fn conf_dirs() -> [Option<String>; 3] {

/// Return the current window size as (rows, columns).
///
/// We use the TIOCGWINSZ ioctl to get window size. If it succeeds, a `Winsize` struct will be
/// We use the `TIOCGWINSZ` ioctl to get window size. If it succeeds, a `Winsize` struct will be
/// populated.
/// This ioctl is described here: <http://man7.org/linux/man-pages/man4/tty_ioctl.4.html>
pub(crate) fn get_window_size() -> Result<(usize, usize), Error> {
Expand Down

0 comments on commit dfca4be

Please sign in to comment.