From 7d1bb69c6f46866f57f8278d62c3daffee1feb8e Mon Sep 17 00:00:00 2001 From: graelo Date: Sun, 24 Oct 2021 11:57:25 +0200 Subject: [PATCH] refactor: use custom Result --- src/bin/tmux_copyrat.rs | 6 +++--- src/config/basic.rs | 4 ++-- src/config/extended.rs | 4 ++-- src/lib.rs | 4 +++- src/textbuf/alphabet.rs | 6 +++--- src/textbuf/regexes.rs | 6 +++--- src/tmux.rs | 30 ++++++++++++++---------------- src/ui/colors.rs | 7 ++++--- 8 files changed, 34 insertions(+), 33 deletions(-) diff --git a/src/bin/tmux_copyrat.rs b/src/bin/tmux_copyrat.rs index 49e5d66..a8fbaf0 100644 --- a/src/bin/tmux_copyrat.rs +++ b/src/bin/tmux_copyrat.rs @@ -1,11 +1,11 @@ use copyrat::{ config::extended::{ConfigExt, OutputDestination}, - error, tmux, + tmux, ui::Selection, + Result, }; -/// -fn main() -> Result<(), error::ParseError> { +fn main() -> Result<()> { let config = ConfigExt::initialize()?; // Identify active pane and capture its content. diff --git a/src/config/basic.rs b/src/config/basic.rs index 7357264..730191f 100644 --- a/src/config/basic.rs +++ b/src/config/basic.rs @@ -3,7 +3,7 @@ use clap::{ArgEnum, Parser}; use crate::{ error::ParseError, textbuf::{alphabet, regexes}, - ui, + ui, Result, }; /// Main configuration, parsed from command line. @@ -78,7 +78,7 @@ pub enum HintStyleArg { } /// Try to parse a `&str` into a tuple of `char`s. -fn parse_chars(src: &str) -> Result<(char, char), ParseError> { +fn parse_chars(src: &str) -> Result<(char, char)> { if src.chars().count() != 2 { return Err(ParseError::ExpectedSurroundingPair); } diff --git a/src/config/extended.rs b/src/config/extended.rs index afb32e8..0084048 100644 --- a/src/config/extended.rs +++ b/src/config/extended.rs @@ -4,7 +4,7 @@ use std::fmt; use clap::{ArgEnum, Parser}; use super::basic; -use crate::{error::ParseError, textbuf::alphabet, tmux, ui}; +use crate::{error::ParseError, textbuf::alphabet, tmux, ui, Result}; /// Extended configuration for handling Tmux-specific configuration (options /// and outputs). This is only used by `tmux-copyrat` and parsed from command @@ -52,7 +52,7 @@ pub struct ConfigExt { } impl ConfigExt { - pub fn initialize() -> Result { + pub fn initialize() -> Result { let mut config_ext = ConfigExt::parse(); if !config_ext.ignore_tmux_options { diff --git a/src/lib.rs b/src/lib.rs index 5bfd7eb..8efa64e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,8 @@ pub mod textbuf; pub mod tmux; pub mod ui; +pub type Result = std::result::Result; + /// Run copyrat on an input string `buffer`, configured by `Opt`. /// /// # Note @@ -11,7 +13,7 @@ pub mod ui; /// Maybe the decision to take ownership of the buffer is a bit bold. pub fn run(lines: &[&str], opt: &config::basic::Config) -> Option { let model = textbuf::Model::new( - &lines, + lines, &opt.alphabet, opt.use_all_patterns, &opt.named_patterns, diff --git a/src/textbuf/alphabet.rs b/src/textbuf/alphabet.rs index d2dacab..afcfd07 100644 --- a/src/textbuf/alphabet.rs +++ b/src/textbuf/alphabet.rs @@ -1,4 +1,4 @@ -use crate::error; +use crate::{error::ParseError, Result}; /// Catalog of available alphabets. /// @@ -41,7 +41,7 @@ const ALPHABETS: [(&str, &str); 21] = [ /// Letters 'n' and 'N' are systematically removed to prevent conflict with /// navigation keys (arrows and 'n' 'N'). Letters 'y' and 'Y' are also removed /// to prevent conflict with yank/copy. -pub fn parse_alphabet(src: &str) -> Result { +pub fn parse_alphabet(src: &str) -> Result { let alphabet_pair = ALPHABETS.iter().find(|&(name, _letters)| name == &src); match alphabet_pair { @@ -49,7 +49,7 @@ pub fn parse_alphabet(src: &str) -> Result { let letters = letters.replace(&['n', 'N', 'y', 'Y'][..], ""); Ok(Alphabet(letters)) } - None => Err(error::ParseError::UnknownAlphabet), + None => Err(ParseError::UnknownAlphabet), } } diff --git a/src/textbuf/regexes.rs b/src/textbuf/regexes.rs index e83875c..9ed316e 100644 --- a/src/textbuf/regexes.rs +++ b/src/textbuf/regexes.rs @@ -2,7 +2,7 @@ //! //! All patterns must have one capture group. The first group is used. -use crate::error; +use crate::{error::ParseError, Result}; pub(super) const EXCLUDE_PATTERNS: [(&str, &str); 1] = [("ansi_colors", r"[[:cntrl:]]\[([0-9]{1,2};)?([0-9]{1,2})?m")]; @@ -51,9 +51,9 @@ pub(super) const PATTERNS: [(&str, &str); 20] = [ pub struct NamedPattern(pub String, pub String); /// Parse a name string into `NamedPattern`, used during CLI parsing. -pub(crate) fn parse_pattern_name(src: &str) -> Result { +pub(crate) fn parse_pattern_name(src: &str) -> Result { match PATTERNS.iter().find(|&(name, _pattern)| name == &src) { Some((name, pattern)) => Ok(NamedPattern(name.to_string(), pattern.to_string())), - None => Err(error::ParseError::UnknownPatternName), + None => Err(ParseError::UnknownPatternName), } } diff --git a/src/tmux.rs b/src/tmux.rs index e019526..57edd82 100644 --- a/src/tmux.rs +++ b/src/tmux.rs @@ -3,13 +3,14 @@ //! The main use cases are running Tmux commands & parsing Tmux panes //! information. -use regex::Regex; use std::collections::HashMap; use std::fmt; use std::str::FromStr; +use regex::Regex; + use crate::config::extended::CaptureRegion; -use crate::error::ParseError; +use crate::{error::ParseError, Result}; #[derive(Debug, PartialEq)] pub struct Pane { @@ -44,7 +45,7 @@ impl FromStr for Pane { /// /// For definitions, look at `Pane` type, /// and at the tmux man page for definitions. - fn from_str(src: &str) -> Result { + fn from_str(src: &str) -> std::result::Result { let items: Vec<&str> = src.split(':').collect(); assert_eq!(items.len(), 5, "tmux should have returned 5 items per line"); @@ -98,7 +99,7 @@ impl Pane { /// scrolled up by 3 lines. It is necessarily in copy mode. Its start line /// index is `-3`. The index of the last line is `(40-1) - 3 = 36`. /// - pub fn capture(&self, region: &CaptureRegion) -> Result { + pub fn capture(&self, region: &CaptureRegion) -> Result { let mut args_str = format!("capture-pane -t {pane_id} -J -p", pane_id = self.id); let region_str = match region { @@ -133,7 +134,7 @@ impl FromStr for PaneId { /// Parse into PaneId. The `&str` must be start with '%' /// followed by a `u16`. - fn from_str(src: &str) -> Result { + fn from_str(src: &str) -> std::result::Result { if !src.starts_with('%') { return Err(ParseError::ExpectedPaneIdMarker); } @@ -156,7 +157,7 @@ impl fmt::Display for PaneId { } /// Returns a list of `Pane` from the current tmux session. -pub fn available_panes() -> Result, ParseError> { +pub fn available_panes() -> Result> { let args = vec![ "list-panes", "-F", @@ -165,9 +166,9 @@ pub fn available_panes() -> Result, ParseError> { let output = duct::cmd("tmux", &args).read()?; - // Each call to `Pane::parse` returns a `Result`. All results - // are collected into a Result, _>, thanks to `collect()`. - let result: Result, ParseError> = output + // Each call to `Pane::parse` returns a `Result`. All results + // are collected into a Result>, thanks to `collect()`. + let result: Result> = output .trim_end() // trim last '\n' as it would create an empty line .split('\n') .map(|line| Pane::from_str(line)) @@ -182,7 +183,7 @@ pub fn available_panes() -> Result, ParseError> { /// /// # Example /// ```get_options("@copyrat-")``` -pub fn get_options(prefix: &str) -> Result, ParseError> { +pub fn get_options(prefix: &str) -> Result> { let output = duct::cmd!("tmux", "show-options", "-g").read()?; let lines: Vec<&str> = output.split('\n').collect(); @@ -205,7 +206,7 @@ pub fn get_options(prefix: &str) -> Result, ParseError> } /// Ask tmux to swap the current Pane with the target_pane (uses Tmux format). -pub fn swap_pane_with(target_pane: &str) -> Result<(), ParseError> { +pub fn swap_pane_with(target_pane: &str) -> Result<()> { // -Z: keep the window zoomed if it was zoomed. duct::cmd!("tmux", "swap-pane", "-Z", "-s", target_pane).run()?; @@ -214,16 +215,13 @@ pub fn swap_pane_with(target_pane: &str) -> Result<(), ParseError> { #[cfg(test)] mod tests { - use super::Pane; - use super::PaneId; - use crate::error; + use super::*; use std::str::FromStr; #[test] fn test_parse_pass() { let output = vec!["%52:false:62:3:false", "%53:false:23::true"]; - let panes: Result, error::ParseError> = - output.iter().map(|&line| Pane::from_str(line)).collect(); + let panes: Result> = output.iter().map(|&line| Pane::from_str(line)).collect(); let panes = panes.expect("Could not parse tmux panes"); let expected = vec![ diff --git a/src/ui/colors.rs b/src/ui/colors.rs index a6bed3f..e5f2c34 100644 --- a/src/ui/colors.rs +++ b/src/ui/colors.rs @@ -1,8 +1,9 @@ -use crate::error; use clap::Parser; use termion::color; -pub fn parse_color(src: &str) -> Result, error::ParseError> { +use crate::{error::ParseError, Result}; + +pub fn parse_color(src: &str) -> Result> { match src { "black" => Ok(Box::new(color::Black)), "red" => Ok(Box::new(color::Red)), @@ -21,7 +22,7 @@ pub fn parse_color(src: &str) -> Result, error::ParseError "bright-cyan" | "brightcyan" => Ok(Box::new(color::LightCyan)), "bright-white" | "brightwhite" => Ok(Box::new(color::LightWhite)), "none" => Ok(Box::new(color::Reset)), - _ => Err(error::ParseError::UnknownColor), + _ => Err(ParseError::UnknownColor), } }