Skip to content

Commit

Permalink
refactor: use anyhow
Browse files Browse the repository at this point in the history
Signed-off-by: Nathanael DEMACON <[email protected]>
  • Loading branch information
quantumsheep committed Feb 21, 2024
1 parent b0870a5 commit 65c03bc
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 24 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ lto = true
codegen-units = 1

[dependencies]
anyhow = "1.0.80"
clap = { version = "4.5.0", features = ["derive"] }
crossterm = "0.27.0"
fuzzy-matcher = "0.3.7"
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ pub mod ssh;
pub mod ssh_config;
pub mod ui;

use anyhow::Result;
use clap::Parser;
use std::error::Error;
use ui::{App, AppConfig};

#[derive(Parser, Debug)]
Expand Down Expand Up @@ -39,7 +39,7 @@ struct Args {
exit: bool,
}

fn main() -> Result<(), Box<dyn Error>> {
fn main() -> Result<()> {
let args = Args::parse();

let mut app = App::new(&AppConfig {
Expand Down
12 changes: 6 additions & 6 deletions src/ssh.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use anyhow::{anyhow, Result};
use handlebars::Handlebars;
use itertools::Itertools;
use serde::Serialize;
use std::collections::VecDeque;
use std::error::Error;
use std::process::Command;

use crate::ssh_config::{self, HostVecExt};
Expand All @@ -27,17 +27,17 @@ impl Host {
/// # Panics
///
/// Will panic if the regex cannot be compiled.
pub fn run_command_template(&self, pattern: &str) -> Result<(), Box<dyn Error>> {
pub fn run_command_template(&self, pattern: &str) -> Result<()> {
let handlebars = Handlebars::new();
let rendered_command = handlebars.render_template(pattern, &self)?;

println!("Running command: {rendered_command}");

let mut args = shlex::split(&rendered_command)
.ok_or(format!("Failed to parse command: {rendered_command}"))?
.ok_or(anyhow!("Failed to parse command: {rendered_command}"))?
.into_iter()
.collect::<VecDeque<String>>();
let command = args.pop_front().ok_or("Failed to get command")?;
let command = args.pop_front().ok_or(anyhow!("Failed to get command"))?;

let status = Command::new(command).args(args).spawn()?.wait()?;
if !status.success() {
Expand All @@ -51,11 +51,11 @@ impl Host {
/// # Errors
///
/// Will return `Err` if the SSH configuration file cannot be parsed.
pub fn parse_config(raw_path: &String) -> Result<Vec<Host>, Box<dyn Error>> {
pub fn parse_config(raw_path: &String) -> Result<Vec<Host>> {
let mut path = shellexpand::tilde(&raw_path).to_string();
path = std::fs::canonicalize(path)?
.to_str()
.ok_or("Failed to convert path to string")?
.ok_or(anyhow!("Failed to convert path to string"))?
.to_string();

let hosts = ssh_config::Parser::new()
Expand Down
25 changes: 15 additions & 10 deletions src/ssh_config/parser.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use anyhow::anyhow;
use anyhow::Result;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::path::Path;
use std::str::FromStr;
use std::{error::Error, io::BufRead};

use super::host::Entry;
use super::{EntryType, Host};
Expand All @@ -29,7 +31,7 @@ impl Parser {
/// # Errors
///
/// Will return `Err` if the SSH configuration cannot be parsed.
pub fn parse_file<P>(&self, path: P) -> Result<Vec<Host>, Box<dyn Error>>
pub fn parse_file<P>(&self, path: P) -> Result<Vec<Host>>
where
P: AsRef<Path>,
{
Expand All @@ -40,7 +42,7 @@ impl Parser {
/// # Errors
///
/// Will return `Err` if the SSH configuration cannot be parsed.
pub fn parse(&self, reader: &mut impl BufRead) -> Result<Vec<Host>, Box<dyn Error>> {
pub fn parse(&self, reader: &mut impl BufRead) -> Result<Vec<Host>> {
let (global_host, mut hosts) = self.parse_raw(reader)?;

if !global_host.is_empty() {
Expand All @@ -52,7 +54,7 @@ impl Parser {
Ok(hosts)
}

fn parse_raw(&self, reader: &mut impl BufRead) -> Result<(Host, Vec<Host>), Box<dyn Error>> {
fn parse_raw(&self, reader: &mut impl BufRead) -> Result<(Host, Vec<Host>)> {
let mut global_host = Host::new(Vec::new());
let mut hosts = Vec::new();

Expand All @@ -69,7 +71,7 @@ impl Parser {
match entry.0 {
EntryType::Unknown(_) => {
if !self.ignore_unknown_entries {
return Err(format!("Unknown entry: {line}").into());
return Err(anyhow!("Unknown entry: {line}"));
}
}
EntryType::Host => {
Expand All @@ -88,7 +90,7 @@ impl Parser {

let path = std::fs::canonicalize(include_path)?
.to_str()
.ok_or("Failed to convert path to string")?
.ok_or(anyhow!("Failed to convert path to string"))?
.to_string();

let mut file = BufReader::new(File::open(path)?);
Expand All @@ -103,10 +105,13 @@ impl Parser {
} else {
// Can't include hosts inside a host block
if !included_hosts.is_empty() {
return Err("Cannot include hosts inside a host block".into());
return Err(anyhow!("Cannot include hosts inside a host block"));
}

hosts.last_mut().unwrap().extend_entries(&included_global_host);
hosts
.last_mut()
.unwrap()
.extend_entries(&included_global_host);
}

continue;
Expand All @@ -125,12 +130,12 @@ impl Parser {
}
}

fn parse_line(line: &str) -> Result<Entry, Box<dyn Error>> {
fn parse_line(line: &str) -> Result<Entry> {
let (mut key, mut value) = line
.trim()
.split_once(' ')
.map(|(k, v)| (k.trim_end(), v.trim_start()))
.ok_or(format!("Invalid line: {line}"))?;
.ok_or(anyhow!("Invalid line: {line}"))?;

// Format can be key=value with whitespaces around the equal sign, strip the equal sign and whitespaces
if key.ends_with('=') {
Expand Down
13 changes: 7 additions & 6 deletions src/ui.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use anyhow::Result;
use crossterm::{
cursor::{Hide, Show},
event::{
Expand All @@ -9,7 +10,7 @@ use crossterm::{
use fuzzy_matcher::{skim::SkimMatcherV2, FuzzyMatcher};
#[allow(clippy::wildcard_imports)]
use ratatui::{prelude::*, widgets::*};
use std::{cell::RefCell, error::Error, io, rc::Rc};
use std::{cell::RefCell, io, rc::Rc};
use style::palette::tailwind;
use tui_input::backend::crossterm::EventHandler;
use tui_input::Input;
Expand Down Expand Up @@ -47,7 +48,7 @@ impl App {
/// # Errors
///
/// Will return `Err` if the SSH configuration file cannot be parsed.
pub fn new(config: &AppConfig) -> Result<App, Box<dyn Error>> {
pub fn new(config: &AppConfig) -> Result<App> {
let mut hosts = ssh::parse_config(&config.config_path)?;
if config.sort_by_name {
hosts.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
Expand Down Expand Up @@ -83,7 +84,7 @@ impl App {
/// # Errors
///
/// Will return `Err` if the terminal cannot be configured.
pub fn start(&mut self) -> Result<(), Box<dyn Error>> {
pub fn start(&mut self) -> Result<()> {
let stdout = io::stdout().lock();
let backend = CrosstermBackend::new(stdout);
let terminal = Rc::new(RefCell::new(Terminal::new(backend)?));
Expand All @@ -102,7 +103,7 @@ impl App {
Ok(())
}

fn run<B: Backend>(&mut self, terminal: &Rc<RefCell<Terminal<B>>>) -> Result<(), Box<dyn Error>>
fn run<B: Backend>(&mut self, terminal: &Rc<RefCell<Terminal<B>>>) -> Result<()>
where
B: std::io::Write,
{
Expand Down Expand Up @@ -276,7 +277,7 @@ impl App {
}
}

fn setup_terminal<B: Backend>(terminal: &Rc<RefCell<Terminal<B>>>) -> Result<(), Box<dyn Error>>
fn setup_terminal<B: Backend>(terminal: &Rc<RefCell<Terminal<B>>>) -> Result<()>
where
B: std::io::Write,
{
Expand All @@ -294,7 +295,7 @@ where
Ok(())
}

fn restore_terminal<B: Backend>(terminal: &Rc<RefCell<Terminal<B>>>) -> Result<(), Box<dyn Error>>
fn restore_terminal<B: Backend>(terminal: &Rc<RefCell<Terminal<B>>>) -> Result<()>
where
B: std::io::Write,
{
Expand Down

0 comments on commit 65c03bc

Please sign in to comment.