Skip to content

Commit

Permalink
refactor: use custom Result
Browse files Browse the repository at this point in the history
  • Loading branch information
graelo committed Oct 24, 2021
1 parent 077d163 commit 7d1bb69
Show file tree
Hide file tree
Showing 8 changed files with 34 additions and 33 deletions.
6 changes: 3 additions & 3 deletions src/bin/tmux_copyrat.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/config/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clap::{ArgEnum, Parser};
use crate::{
error::ParseError,
textbuf::{alphabet, regexes},
ui,
ui, Result,
};

/// Main configuration, parsed from command line.
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 2 additions & 2 deletions src/config/extended.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -52,7 +52,7 @@ pub struct ConfigExt {
}

impl ConfigExt {
pub fn initialize() -> Result<ConfigExt, ParseError> {
pub fn initialize() -> Result<ConfigExt> {
let mut config_ext = ConfigExt::parse();

if !config_ext.ignore_tmux_options {
Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ pub mod textbuf;
pub mod tmux;
pub mod ui;

pub type Result<T> = std::result::Result<T, error::ParseError>;

/// Run copyrat on an input string `buffer`, configured by `Opt`.
///
/// # Note
///
/// Maybe the decision to take ownership of the buffer is a bit bold.
pub fn run(lines: &[&str], opt: &config::basic::Config) -> Option<ui::Selection> {
let model = textbuf::Model::new(
&lines,
lines,
&opt.alphabet,
opt.use_all_patterns,
&opt.named_patterns,
Expand Down
6 changes: 3 additions & 3 deletions src/textbuf/alphabet.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::error;
use crate::{error::ParseError, Result};

/// Catalog of available alphabets.
///
Expand Down Expand Up @@ -41,15 +41,15 @@ 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<Alphabet, error::ParseError> {
pub fn parse_alphabet(src: &str) -> Result<Alphabet> {
let alphabet_pair = ALPHABETS.iter().find(|&(name, _letters)| name == &src);

match alphabet_pair {
Some((_name, letters)) => {
let letters = letters.replace(&['n', 'N', 'y', 'Y'][..], "");
Ok(Alphabet(letters))
}
None => Err(error::ParseError::UnknownAlphabet),
None => Err(ParseError::UnknownAlphabet),
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/textbuf/regexes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")];
Expand Down Expand Up @@ -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<NamedPattern, error::ParseError> {
pub(crate) fn parse_pattern_name(src: &str) -> Result<NamedPattern> {
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),
}
}
30 changes: 14 additions & 16 deletions src/tmux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Self, Self::Err> {
fn from_str(src: &str) -> std::result::Result<Self, Self::Err> {
let items: Vec<&str> = src.split(':').collect();
assert_eq!(items.len(), 5, "tmux should have returned 5 items per line");

Expand Down Expand Up @@ -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<String, ParseError> {
pub fn capture(&self, region: &CaptureRegion) -> Result<String> {
let mut args_str = format!("capture-pane -t {pane_id} -J -p", pane_id = self.id);

let region_str = match region {
Expand Down Expand Up @@ -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<Self, Self::Err> {
fn from_str(src: &str) -> std::result::Result<Self, Self::Err> {
if !src.starts_with('%') {
return Err(ParseError::ExpectedPaneIdMarker);
}
Expand All @@ -156,7 +157,7 @@ impl fmt::Display for PaneId {
}

/// Returns a list of `Pane` from the current tmux session.
pub fn available_panes() -> Result<Vec<Pane>, ParseError> {
pub fn available_panes() -> Result<Vec<Pane>> {
let args = vec![
"list-panes",
"-F",
Expand All @@ -165,9 +166,9 @@ pub fn available_panes() -> Result<Vec<Pane>, ParseError> {

let output = duct::cmd("tmux", &args).read()?;

// Each call to `Pane::parse` returns a `Result<Pane, _>`. All results
// are collected into a Result<Vec<Pane>, _>, thanks to `collect()`.
let result: Result<Vec<Pane>, ParseError> = output
// Each call to `Pane::parse` returns a `Result<Pane>`. All results
// are collected into a Result<Vec<Pane>>, thanks to `collect()`.
let result: Result<Vec<Pane>> = output
.trim_end() // trim last '\n' as it would create an empty line
.split('\n')
.map(|line| Pane::from_str(line))
Expand All @@ -182,7 +183,7 @@ pub fn available_panes() -> Result<Vec<Pane>, ParseError> {
///
/// # Example
/// ```get_options("@copyrat-")```
pub fn get_options(prefix: &str) -> Result<HashMap<String, String>, ParseError> {
pub fn get_options(prefix: &str) -> Result<HashMap<String, String>> {
let output = duct::cmd!("tmux", "show-options", "-g").read()?;
let lines: Vec<&str> = output.split('\n').collect();

Expand All @@ -205,7 +206,7 @@ pub fn get_options(prefix: &str) -> Result<HashMap<String, String>, 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()?;

Expand All @@ -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<Vec<Pane>, error::ParseError> =
output.iter().map(|&line| Pane::from_str(line)).collect();
let panes: Result<Vec<Pane>> = output.iter().map(|&line| Pane::from_str(line)).collect();
let panes = panes.expect("Could not parse tmux panes");

let expected = vec![
Expand Down
7 changes: 4 additions & 3 deletions src/ui/colors.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use crate::error;
use clap::Parser;
use termion::color;

pub fn parse_color(src: &str) -> Result<Box<dyn color::Color>, error::ParseError> {
use crate::{error::ParseError, Result};

pub fn parse_color(src: &str) -> Result<Box<dyn color::Color>> {
match src {
"black" => Ok(Box::new(color::Black)),
"red" => Ok(Box::new(color::Red)),
Expand All @@ -21,7 +22,7 @@ pub fn parse_color(src: &str) -> Result<Box<dyn color::Color>, 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),
}
}

Expand Down

0 comments on commit 7d1bb69

Please sign in to comment.