Use anyhow::Result

This commit is contained in:
Denis Isidoro 2021-04-16 08:29:04 -03:00 committed by GitHub
parent 06d728c377
commit 649832bc41
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 76 additions and 83 deletions

View file

@ -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;
@ -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);
@ -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);
@ -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" {

View file

@ -3,7 +3,7 @@ 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};
@ -11,7 +11,7 @@ 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
{}",
@ -19,7 +19,7 @@ fn lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String, Err
)
.lines()
.map(|line| Ok(map_line(line)))
.collect::<Vec<Result<String, Error>>>()
.collect::<Vec<Result<String>>>()
.into_iter()
}
@ -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();
@ -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")
@ -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)
}

View file

@ -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

View file

@ -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
@ -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

View file

@ -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)]
@ -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(
@ -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")
@ -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)?;

View file

@ -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()?)?),
}

View file

@ -1,6 +1,6 @@
use crate::writer;
use anyhow::Error;
use anyhow::Result;
use std::process;
@ -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)
}

View file

@ -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");
@ -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()),
@ -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());

View file

@ -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"),

View file

@ -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"

View file

@ -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};
@ -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());
@ -34,7 +34,7 @@ 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 {
@ -42,7 +42,7 @@ pub fn cheat_paths(path: Option<String>) -> Result<String, Error> {
}
}
pub fn tmp_pathbuf() -> Result<PathBuf, Error> {
pub fn tmp_pathbuf() -> Result<PathBuf> {
let mut root = default_cheat_pathbuf()?;
root.push("tmp");
Ok(root)
@ -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();

View file

@ -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};
@ -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")?
@ -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",

View file

@ -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#"
@ -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()

View file

@ -1,4 +1,4 @@
use anyhow::{Context, Error};
use anyhow::{Context, Error, Result};
use core::fmt::Display;
use remove_dir_all::remove_dir_all;
use std::fmt::Debug;
@ -19,7 +19,7 @@ pub struct UnreadableDir {
source: anyhow::Error,
}
pub fn read_lines<P>(filename: P) -> Result<impl Iterator<Item = Result<String, Error>>, Error>
pub fn read_lines<P>(filename: P) -> Result<impl Iterator<Item = Result<String>>>
where
P: AsRef<Path> + Display + Copy,
{
@ -29,7 +29,7 @@ where
.map(|line| line.map_err(Error::from)))
}
pub fn pathbuf_to_string(pathbuf: &Path) -> Result<String, Error> {
pub fn pathbuf_to_string(pathbuf: &Path) -> Result<String> {
Ok(pathbuf
.as_os_str()
.to_str()
@ -37,7 +37,7 @@ pub fn pathbuf_to_string(pathbuf: &Path) -> Result<String, Error> {
.map(str::to_string)?)
}
fn follow_symlink(pathbuf: PathBuf) -> Result<PathBuf, Error> {
fn follow_symlink(pathbuf: PathBuf) -> Result<PathBuf> {
fs::read_link(pathbuf.clone())
.map(|o| {
let o_str = o
@ -58,16 +58,16 @@ fn follow_symlink(pathbuf: PathBuf) -> Result<PathBuf, Error> {
.unwrap_or(Ok(pathbuf))
}
fn exe_pathbuf() -> Result<PathBuf, Error> {
fn exe_pathbuf() -> Result<PathBuf> {
let pathbuf = std::env::current_exe().context("Unable to acquire executable's path")?;
follow_symlink(pathbuf)
}
pub fn exe_string() -> Result<String, Error> {
pub fn exe_string() -> Result<String> {
pathbuf_to_string(&exe_pathbuf()?)
}
pub fn create_dir(path: &Path) -> Result<(), Error> {
pub fn create_dir(path: &Path) -> Result<()> {
create_dir_all(path).with_context(|| {
format!(
"Failed to create directory `{}`",
@ -76,7 +76,7 @@ pub fn create_dir(path: &Path) -> Result<(), Error> {
})
}
pub fn remove_dir(path: &Path) -> Result<(), Error> {
pub fn remove_dir(path: &Path) -> Result<()> {
remove_dir_all(path).with_context(|| {
format!(
"Failed to remove directory `{}`",

View file

@ -1,8 +1,8 @@
use crate::shell::ShellSpawnError;
use anyhow::{Context, Error};
use anyhow::{Context, Result};
use std::process::Command;
pub fn shallow_clone(uri: &str, target: &str) -> Result<(), Error> {
pub fn shallow_clone(uri: &str, target: &str) -> Result<()> {
Command::new("git")
.args(&["clone", uri, target, "--depth", "1"])
.spawn()

View file

@ -2,9 +2,9 @@ use crate::cmds;
use crate::structures::config::Command::{Fn, Info, Preview, PreviewVar, Repo, Widget};
use crate::structures::config::{Config, RepoCommand};
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
pub fn handle_config(config: Config) -> Result<(), Error> {
pub fn handle_config(config: Config) -> Result<()> {
match config.cmd.as_ref() {
None => cmds::core::main(config),

View file

@ -3,7 +3,7 @@ use crate::hash::fnv;
use crate::structures::cheat::VariableMap;
use crate::structures::item::Item;
use crate::writer::{self, Writer};
use anyhow::{Context, Error};
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashSet;
use std::io::Write;
@ -12,7 +12,7 @@ lazy_static! {
pub static ref VAR_LINE_REGEX: Regex = Regex::new(r"^\$\s*([^:]+):(.*)").expect("Invalid regex");
}
fn parse_opts(text: &str) -> Result<FinderOpts, Error> {
fn parse_opts(text: &str) -> Result<FinderOpts> {
let mut multi = false;
let mut prevent_extra = false;
let mut opts = FinderOpts::default();
@ -81,7 +81,7 @@ fn parse_opts(text: &str) -> Result<FinderOpts, Error> {
Ok(opts)
}
fn parse_variable_line(line: &str) -> Result<(&str, &str, Option<FinderOpts>), Error> {
fn parse_variable_line(line: &str) -> Result<(&str, &str, Option<FinderOpts>)> {
let caps = VAR_LINE_REGEX
.captures(line)
.ok_or_else(|| anyhow!("No variables, command, and options found in the line `{}`", line))?;
@ -108,7 +108,7 @@ fn write_cmd(
stdin: &mut std::process::ChildStdin,
allowlist: Option<&Vec<String>>,
denylist: Option<&Vec<String>>,
) -> Result<(), Error> {
) -> Result<()> {
if item.snippet.len() <= 1 {
return Ok(());
}
@ -141,7 +141,7 @@ fn without_prefix(line: &str) -> String {
#[allow(clippy::too_many_arguments)]
pub fn read_lines(
lines: impl Iterator<Item = Result<String, Error>>,
lines: impl Iterator<Item = Result<String>>,
id: &str,
file_index: usize,
variables: &mut VariableMap,
@ -150,7 +150,7 @@ pub fn read_lines(
stdin: &mut std::process::ChildStdin,
allowlist: Option<&Vec<String>>,
denylist: Option<&Vec<String>>,
) -> Result<(), Error> {
) -> Result<()> {
let mut item = Item::new();
item.file_index = file_index;

View file

@ -1,6 +1,6 @@
use crate::structures::cheat::VariableMap;
use crate::writer::Writer;
use anyhow::Error;
use anyhow::Result;
pub trait Fetcher {
fn fetch(
@ -8,5 +8,5 @@ pub trait Fetcher {
stdin: &mut std::process::ChildStdin,
writer: &mut dyn Writer,
files: &mut Vec<String>,
) -> Result<Option<VariableMap>, Error>;
) -> Result<Option<VariableMap>>;
}

View file

@ -2,7 +2,7 @@ use crate::parser;
use crate::structures::cheat::VariableMap;
use crate::structures::fetcher;
use crate::writer::Writer;
use anyhow::{Context, Error};
use anyhow::{Context, Result};
use regex::Regex;
use std::collections::HashSet;
@ -47,7 +47,7 @@ fn convert_tldr(line: &str) -> String {
}
}
fn markdown_lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String, Error>> {
fn markdown_lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<String>> {
format!(
"% {}, tldr
{}",
@ -55,7 +55,7 @@ fn markdown_lines(query: &str, markdown: &str) -> impl Iterator<Item = Result<St
)
.lines()
.map(|line| Ok(convert_tldr(line)))
.collect::<Vec<Result<String, Error>>>()
.collect::<Vec<Result<String>>>()
.into_iter()
}
@ -64,7 +64,7 @@ fn read_all(
markdown: &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();
parser::read_lines(
@ -81,7 +81,7 @@ fn read_all(
Ok(Some(variables))
}
pub fn fetch(query: &str) -> Result<String, Error> {
pub fn fetch(query: &str) -> Result<String> {
let args = [query, "--markdown"];
let child = Command::new("tldr")
@ -156,7 +156,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 markdown = fetch(&self.query)?;
read_all(&self.query, &markdown, stdin, writer)
}

View file

@ -1,7 +1,7 @@
use crate::shell::{self, ShellSpawnError};
use anyhow::Error;
use anyhow::Result;
pub fn open(args: Vec<String>) -> Result<(), Error> {
pub fn open(args: Vec<String>) -> Result<()> {
let url = args
.into_iter()
.next()