Skip to content

Commit

Permalink
Use anyhow::Result
Browse files Browse the repository at this point in the history
  • Loading branch information
denisidoro committed Apr 16, 2021
1 parent 06d728c commit 649832b
Show file tree
Hide file tree
Showing 20 changed files with 76 additions and 83 deletions.
10 changes: 5 additions & 5 deletions src/actor.rs
Expand Up @@ -10,7 +10,7 @@ use crate::structures::config::Action;
use crate::structures::config::Config;
use crate::writer;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use std::io::Write;
use std::path::Path;
use std::process::Stdio;
Expand All @@ -20,7 +20,7 @@ fn prompt_finder(
config: &Config,
suggestion: Option<&Suggestion>,
variable_count: usize,
) -> Result<String, Error> {
) -> Result<String> {
env_var::remove(env_var::PREVIEW_COLUMN);
env_var::remove(env_var::PREVIEW_DELIMITER);
env_var::remove(env_var::PREVIEW_MAP);
Expand Down Expand Up @@ -135,7 +135,7 @@ fn replace_variables_from_snippet(
tags: &str,
variables: VariableMap,
config: &Config,
) -> Result<String, Error> {
) -> Result<String> {
let mut interpolated_snippet = String::from(snippet);
let variables_found: Vec<&str> = writer::VAR_REGEX.find_iter(snippet).map(|m| m.as_str()).collect();
let variable_count = unique_result_count(&variables_found);
Expand Down Expand Up @@ -171,11 +171,11 @@ fn replace_variables_from_snippet(

// TODO: make it depend on less inputs
pub fn act(
extractions: Result<extractor::Output, Error>,
extractions: Result<extractor::Output>,
config: Config,
files: Vec<String>,
variables: Option<VariableMap>,
) -> Result<(), Error> {
) -> Result<()> {
let (key, tags, comment, snippet, file_index) = extractions.unwrap();

if key == "ctrl-o" {
Expand Down
12 changes: 6 additions & 6 deletions src/cheatsh.rs
Expand Up @@ -3,23 +3,23 @@ use crate::structures::cheat::VariableMap;
use crate::structures::fetcher;
use crate::writer::Writer;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use std::collections::HashSet;
use std::process::{self, Command, Stdio};

fn map_line(line: &str) -> String {
line.trim().trim_end_matches(':').to_string()
}

fn lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String, Error>> {
fn lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String>> {
format!(
"% {}, cheat.sh
{}",
query, markdown
)
.lines()
.map(|line| Ok(map_line(line)))
.collect::<Vec<Result<String, Error>>>()
.collect::<Vec<Result<String>>>()
.into_iter()
}

Expand All @@ -28,7 +28,7 @@ fn read_all(
cheat: &str,
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
) -> Result<Option<VariableMap>, Error> {
) -> Result<Option<VariableMap>> {
let mut variables = VariableMap::new();
let mut visited_lines = HashSet::new();

Expand Down Expand Up @@ -58,7 +58,7 @@ Output:
Ok(Some(variables))
}

pub fn fetch(query: &str) -> Result<String, Error> {
pub fn fetch(query: &str) -> Result<String> {
let args = ["-qO-", &format!("cheat.sh/{}", query)];

let child = Command::new("wget")
Expand Down Expand Up @@ -121,7 +121,7 @@ impl fetcher::Fetcher for Fetcher {
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
_files: &mut Vec<String>,
) -> Result<Option<VariableMap>, Error> {
) -> Result<Option<VariableMap>> {
let cheat = fetch(&self.query)?;
read_all(&self.query, &cheat, stdin, writer)
}
Expand Down
4 changes: 2 additions & 2 deletions src/clipboard.rs
@@ -1,7 +1,7 @@
use crate::shell::{self, ShellSpawnError};
use anyhow::Error;
use anyhow::Result;

pub fn copy(text: String) -> Result<(), Error> {
pub fn copy(text: String) -> Result<()> {
let cmd = r#"
exst() {
type "$1" &>/dev/null
Expand Down
6 changes: 3 additions & 3 deletions src/cmds/core.rs
Expand Up @@ -16,9 +16,9 @@ use crate::structures::config::Source;
use crate::tldr;
use crate::welcome;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;

fn gen_core_finder_opts(config: &Config) -> Result<FinderOpts, Error> {
fn gen_core_finder_opts(config: &Config) -> Result<FinderOpts> {
let opts = FinderOpts {
preview: if config.no_preview {
None
Expand All @@ -43,7 +43,7 @@ fn gen_core_finder_opts(config: &Config) -> Result<FinderOpts, Error> {
Ok(opts)
}

pub fn main(config: Config) -> Result<(), Error> {
pub fn main(config: Config) -> Result<()> {
let opts = gen_core_finder_opts(&config).context("Failed to generate finder options")?;

let (raw_selection, variables, files) = config
Expand Down
8 changes: 4 additions & 4 deletions src/cmds/func.rs
Expand Up @@ -2,7 +2,7 @@ use crate::handler;
use crate::shell::{self, ShellSpawnError};
use crate::structures::config;
use crate::url;
use anyhow::Error;
use anyhow::Result;
use std::io::{self, Read};

#[derive(Debug)]
Expand All @@ -13,7 +13,7 @@ pub enum Func {
MapExpand,
}

pub fn main(func: &Func, args: Vec<String>) -> Result<(), Error> {
pub fn main(func: &Func, args: Vec<String>) -> Result<()> {
match func {
Func::UrlOpen => url::open(args),
Func::Welcome => handler::handle_config(config::config_from_iter(
Expand All @@ -24,7 +24,7 @@ pub fn main(func: &Func, args: Vec<String>) -> Result<(), Error> {
}
}

fn map_expand() -> Result<(), Error> {
fn map_expand() -> Result<()> {
let cmd = r#"sed -e 's/^.*$/"&"/' | tr '\n' ' '"#;
shell::command()
.arg("-c")
Expand All @@ -35,7 +35,7 @@ fn map_expand() -> Result<(), Error> {
Ok(())
}

fn widget_last_command() -> Result<(), Error> {
fn widget_last_command() -> Result<()> {
let mut text = String::new();
io::stdin().read_to_string(&mut text)?;

Expand Down
4 changes: 2 additions & 2 deletions src/cmds/info.rs
@@ -1,13 +1,13 @@
use crate::filesystem::default_cheat_pathbuf;
use crate::fs::pathbuf_to_string;
use anyhow::Error;
use anyhow::Result;

#[derive(Debug)]
pub enum Info {
CheatsPath,
}

pub fn main(info: &Info) -> Result<(), Error> {
pub fn main(info: &Info) -> Result<()> {
match info {
Info::CheatsPath => println!("{}", pathbuf_to_string(&default_cheat_pathbuf()?)?),
}
Expand Down
6 changes: 3 additions & 3 deletions src/cmds/preview.rs
@@ -1,6 +1,6 @@
use crate::writer;

use anyhow::Error;
use anyhow::Result;

use std::process;

Expand All @@ -12,13 +12,13 @@ fn extract_elements(argstr: &str) -> (&str, &str, &str) {
(tags, comment, snippet)
}

pub fn main(line: &str) -> Result<(), Error> {
pub fn main(line: &str) -> Result<()> {
let (tags, comment, snippet) = extract_elements(line);
writer::terminal::preview(comment, tags, snippet);
process::exit(0)
}

pub fn main_var(selection: &str, query: &str, variable: &str) -> Result<(), Error> {
pub fn main_var(selection: &str, query: &str, variable: &str) -> Result<()> {
writer::terminal::preview_var(selection, query, variable);
process::exit(0)
}
8 changes: 4 additions & 4 deletions src/cmds/repo.rs
Expand Up @@ -4,12 +4,12 @@ use crate::finder::{Finder, FinderChoice};
use crate::fs::pathbuf_to_string;
use crate::git;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use std::fs;
use std::io::Write;
use std::path;

pub fn browse(finder: &FinderChoice) -> Result<(), Error> {
pub fn browse(finder: &FinderChoice) -> Result<()> {
let repo_pathbuf = {
let mut p = filesystem::tmp_pathbuf()?;
p.push("featured");
Expand Down Expand Up @@ -53,7 +53,7 @@ pub fn browse(finder: &FinderChoice) -> Result<(), Error> {
add(repo, finder)
}

pub fn ask_if_should_import_all(finder: &FinderChoice) -> Result<bool, Error> {
pub fn ask_if_should_import_all(finder: &FinderChoice) -> Result<bool> {
let opts = FinderOpts {
column: Some(1),
header: Some("Do you want to import all files from this repo?".to_string()),
Expand All @@ -76,7 +76,7 @@ pub fn ask_if_should_import_all(finder: &FinderChoice) -> Result<bool, Error> {
}
}

pub fn add(uri: String, finder: &FinderChoice) -> Result<(), Error> {
pub fn add(uri: String, finder: &FinderChoice) -> Result<()> {
let should_import_all = ask_if_should_import_all(finder).unwrap_or(false);
let (actual_uri, user, repo) = git::meta(uri.as_str());

Expand Down
4 changes: 2 additions & 2 deletions src/cmds/shell.rs
@@ -1,7 +1,7 @@
use crate::shell::Shell;
use anyhow::Error;
use anyhow::Result;

pub fn main(shell: &Shell) -> Result<(), Error> {
pub fn main(shell: &Shell) -> Result<()> {
let content = match shell {
Shell::Bash => include_str!("../../shell/navi.plugin.bash"),
Shell::Zsh => include_str!("../../shell/navi.plugin.zsh"),
Expand Down
4 changes: 2 additions & 2 deletions src/extractor.rs
@@ -1,11 +1,11 @@
use crate::writer;

use anyhow::Context;
use anyhow::Error;
use anyhow::Result;

pub type Output<'a> = (&'a str, &'a str, &'a str, &'a str, Option<usize>);

pub fn extract_from_selections(raw_snippet: &str, is_single: bool) -> Result<Output, Error> {
pub fn extract_from_selections(raw_snippet: &str, is_single: bool) -> Result<Output> {
let mut lines = raw_snippet.split('\n');
let key = if is_single {
"enter"
Expand Down
10 changes: 5 additions & 5 deletions src/filesystem.rs
Expand Up @@ -5,7 +5,7 @@ use crate::parser;
use crate::structures::cheat::VariableMap;
use crate::structures::fetcher;
use crate::writer::Writer;
use anyhow::Error;
use anyhow::Result;
use directories_next::BaseDirs;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
Expand All @@ -25,7 +25,7 @@ fn paths_from_path_param(env_var: &str) -> impl Iterator<Item = &str> {
env_var.split(':').filter(|folder| folder != &"")
}

pub fn default_cheat_pathbuf() -> Result<PathBuf, Error> {
pub fn default_cheat_pathbuf() -> Result<PathBuf> {
let base_dirs = BaseDirs::new().ok_or_else(|| anyhow!("Unable to get base dirs"))?;

let mut pathbuf = PathBuf::from(base_dirs.data_dir());
Expand All @@ -34,15 +34,15 @@ pub fn default_cheat_pathbuf() -> Result<PathBuf, Error> {
Ok(pathbuf)
}

pub fn cheat_paths(path: Option<String>) -> Result<String, Error> {
pub fn cheat_paths(path: Option<String>) -> Result<String> {
if let Some(p) = path {
Ok(p)
} else {
pathbuf_to_string(&default_cheat_pathbuf()?)
}
}

pub fn tmp_pathbuf() -> Result<PathBuf, Error> {
pub fn tmp_pathbuf() -> Result<PathBuf> {
let mut root = default_cheat_pathbuf()?;
root.push("tmp");
Ok(root)
Expand Down Expand Up @@ -105,7 +105,7 @@ impl fetcher::Fetcher for Fetcher {
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
files: &mut Vec<String>,
) -> Result<Option<VariableMap>, Error> {
) -> Result<Option<VariableMap>> {
let mut variables = VariableMap::new();
let mut found_something = false;
let mut visited_lines = HashSet::new();
Expand Down
16 changes: 6 additions & 10 deletions src/finder/mod.rs
Expand Up @@ -2,7 +2,7 @@ use crate::shell;
use crate::structures::cheat::VariableMap;
use crate::writer;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use std::process::{self, Output};
use std::process::{Command, Stdio};

Expand All @@ -20,12 +20,12 @@ pub enum FinderChoice {
}

pub trait Finder {
fn call<F>(&self, opts: Opts, stdin_fn: F) -> Result<(String, Option<VariableMap>, Vec<String>), Error>
fn call<F>(&self, opts: Opts, stdin_fn: F) -> Result<(String, Option<VariableMap>, Vec<String>)>
where
F: Fn(&mut process::ChildStdin, &mut Vec<String>) -> Result<Option<VariableMap>, Error>;
F: Fn(&mut process::ChildStdin, &mut Vec<String>) -> Result<Option<VariableMap>>;
}

fn parse(out: Output, opts: Opts) -> Result<String, Error> {
fn parse(out: Output, opts: Opts) -> Result<String> {
let text = match out.status.code() {
Some(0) | Some(1) | Some(2) => {
String::from_utf8(out.stdout).context("Invalid utf8 received from finder")?
Expand All @@ -43,13 +43,9 @@ fn parse(out: Output, opts: Opts) -> Result<String, Error> {
}

impl Finder for FinderChoice {
fn call<F>(
&self,
finder_opts: Opts,
stdin_fn: F,
) -> Result<(String, Option<VariableMap>, Vec<String>), Error>
fn call<F>(&self, finder_opts: Opts, stdin_fn: F) -> Result<(String, Option<VariableMap>, Vec<String>)>
where
F: Fn(&mut process::ChildStdin, &mut Vec<String>) -> Result<Option<VariableMap>, Error>,
F: Fn(&mut process::ChildStdin, &mut Vec<String>) -> Result<Option<VariableMap>>,
{
let finder_str = match self {
Self::Fzf => "fzf",
Expand Down
11 changes: 4 additions & 7 deletions src/finder/post.rs
@@ -1,10 +1,10 @@
use crate::finder::structures::SuggestionType;
use crate::shell;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use std::process::Stdio;

fn apply_map(text: String, map_fn: Option<String>) -> Result<String, Error> {
fn apply_map(text: String, map_fn: Option<String>) -> Result<String> {
if let Some(m) = map_fn {
let cmd = format!(
r#"
Expand Down Expand Up @@ -58,14 +58,11 @@ pub fn process(
column: Option<u8>,
delimiter: Option<&str>,
map_fn: Option<String>,
) -> Result<String, Error> {
) -> Result<String> {
apply_map(get_column(text, column, delimiter), map_fn)
}

pub(super) fn parse_output_single(
mut text: String,
suggestion_type: SuggestionType,
) -> Result<String, Error> {
pub(super) fn parse_output_single(mut text: String, suggestion_type: SuggestionType) -> Result<String> {
Ok(match suggestion_type {
SuggestionType::SingleSelection => text
.lines()
Expand Down

0 comments on commit 649832b

Please sign in to comment.