mirror of
https://github.com/sharkdp/bat.git
synced 2025-08-18 20:10:13 +02:00
Replace deprecated 'error-chain' with 'thiserror' (#1820)
We can't use #[from] on Error::Msg(String) because String does not implement Error. (Which it shouldn't; see e.g. https://internals.rust-lang.org/t/impl-error-for-string/8881.) So we implement From manually for Error::Msg, since our current code was written in that way for error-chain.
This commit is contained in:
@@ -163,7 +163,7 @@ impl HighlightingAssets {
|
||||
syntax_set
|
||||
.find_syntax_by_token(language)
|
||||
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
|
||||
.ok_or_else(|| ErrorKind::UnknownSyntax(language.to_owned()).into())
|
||||
.ok_or_else(|| Error::UnknownSyntax(language.to_owned()))
|
||||
} else {
|
||||
let line_syntax = self.get_first_line_syntax(&mut input.reader)?;
|
||||
|
||||
@@ -189,30 +189,27 @@ impl HighlightingAssets {
|
||||
.unwrap_or_else(|| path.to_owned());
|
||||
|
||||
match mapping.get_syntax_for(absolute_path) {
|
||||
Some(MappingTarget::MapToUnknown) => line_syntax.ok_or_else(|| {
|
||||
ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
|
||||
}),
|
||||
Some(MappingTarget::MapToUnknown) => line_syntax
|
||||
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into())),
|
||||
|
||||
Some(MappingTarget::MapTo(syntax_name)) => {
|
||||
let syntax_set = self.get_syntax_set()?;
|
||||
syntax_set
|
||||
.find_syntax_by_name(syntax_name)
|
||||
.map(|syntax| SyntaxReferenceInSet { syntax, syntax_set })
|
||||
.ok_or_else(|| ErrorKind::UnknownSyntax(syntax_name.to_owned()).into())
|
||||
.ok_or_else(|| Error::UnknownSyntax(syntax_name.to_owned()))
|
||||
}
|
||||
|
||||
None => {
|
||||
let file_name = path.file_name().unwrap_or_default();
|
||||
self.get_extension_syntax(file_name)?
|
||||
.or(line_syntax)
|
||||
.ok_or_else(|| {
|
||||
ErrorKind::UndetectedSyntax(path.to_string_lossy().into()).into()
|
||||
})
|
||||
.ok_or_else(|| Error::UndetectedSyntax(path.to_string_lossy().into()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If a path wasn't provided, we fall back to the detect first-line syntax.
|
||||
line_syntax.ok_or_else(|| ErrorKind::UndetectedSyntax("[unknown]".into()).into())
|
||||
line_syntax.ok_or_else(|| Error::UndetectedSyntax("[unknown]".into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -314,14 +311,14 @@ pub(crate) fn get_integrated_themeset() -> ThemeSet {
|
||||
}
|
||||
|
||||
fn asset_from_cache<T: serde::de::DeserializeOwned>(path: &Path, description: &str) -> Result<T> {
|
||||
let contents = fs::read(path).chain_err(|| {
|
||||
let contents = fs::read(path).map_err(|_| {
|
||||
format!(
|
||||
"Could not load cached {} '{}'",
|
||||
description,
|
||||
path.to_string_lossy()
|
||||
)
|
||||
})?;
|
||||
from_reader(&contents[..]).chain_err(|| format!("Could not parse cached {}", description))
|
||||
from_reader(&contents[..]).map_err(|_| format!("Could not parse cached {}", description).into())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@@ -52,16 +52,15 @@ impl AssetsMetadata {
|
||||
pub fn load_from_folder(path: &Path) -> Result<Option<Self>> {
|
||||
match Self::try_load_from_folder(path) {
|
||||
Ok(metadata) => Ok(Some(metadata)),
|
||||
Err(e) => match e.kind() {
|
||||
ErrorKind::SerdeYamlError(_) => Err(e),
|
||||
_ => {
|
||||
if path.join("syntaxes.bin").exists() || path.join("themes.bin").exists() {
|
||||
Ok(Some(Self::default()))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) => {
|
||||
if let Error::SerdeYamlError(_) = e {
|
||||
Err(e)
|
||||
} else if path.join("syntaxes.bin").exists() || path.join("themes.bin").exists() {
|
||||
Ok(Some(Self::default()))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -62,7 +62,7 @@ impl App {
|
||||
// Read arguments from bats config file
|
||||
let mut args = get_args_from_env_var()
|
||||
.unwrap_or_else(get_args_from_config_file)
|
||||
.chain_err(|| "Could not parse configuration file")?;
|
||||
.map_err(|_| "Could not parse configuration file")?;
|
||||
|
||||
// Put the zero-th CLI argument (program name) first
|
||||
args.insert(0, cli_args.next().unwrap());
|
||||
|
@@ -1,6 +1,3 @@
|
||||
// `error_chain!` can recurse deeply
|
||||
#![recursion_limit = "1024"]
|
||||
|
||||
mod app;
|
||||
mod assets;
|
||||
mod clap_app;
|
||||
|
@@ -267,7 +267,7 @@ impl SyntaxSetDependencyBuilder {
|
||||
|
||||
fn asset_to_cache<T: serde::Serialize>(asset: &T, path: &Path, description: &str) -> Result<()> {
|
||||
print!("Writing {} to {} ... ", description, path.to_string_lossy());
|
||||
syntect::dumps::dump_to_file(asset, &path).chain_err(|| {
|
||||
syntect::dumps::dump_to_file(asset, &path).map_err(|_| {
|
||||
format!(
|
||||
"Could not save {} to {}",
|
||||
description,
|
||||
|
64
src/error.rs
64
src/error.rs
@@ -1,42 +1,52 @@
|
||||
use error_chain::error_chain;
|
||||
use std::io::Write;
|
||||
use thiserror::Error;
|
||||
|
||||
error_chain! {
|
||||
foreign_links {
|
||||
Clap(::clap::Error) #[cfg(feature = "minimal-application")];
|
||||
Io(::std::io::Error);
|
||||
SyntectError(::syntect::LoadingError);
|
||||
ParseIntError(::std::num::ParseIntError);
|
||||
GlobParsingError(::globset::Error);
|
||||
SerdeYamlError(::serde_yaml::Error);
|
||||
}
|
||||
#[derive(Error, Debug)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
Io(#[from] ::std::io::Error),
|
||||
#[error(transparent)]
|
||||
SyntectError(#[from] ::syntect::LoadingError),
|
||||
#[error(transparent)]
|
||||
ParseIntError(#[from] ::std::num::ParseIntError),
|
||||
#[error(transparent)]
|
||||
GlobParsingError(#[from] ::globset::Error),
|
||||
#[error(transparent)]
|
||||
SerdeYamlError(#[from] ::serde_yaml::Error),
|
||||
#[error("unable to detect syntax for {0}")]
|
||||
UndetectedSyntax(String),
|
||||
#[error("unknown syntax: '{0}'")]
|
||||
UnknownSyntax(String),
|
||||
#[error("Unknown style '{0}'")]
|
||||
UnknownStyle(String),
|
||||
#[error("Use of bat as a pager is disallowed in order to avoid infinite recursion problems")]
|
||||
InvalidPagerValueBat,
|
||||
#[error("{0}")]
|
||||
Msg(String),
|
||||
}
|
||||
|
||||
errors {
|
||||
UndetectedSyntax(input: String) {
|
||||
description("unable to detect syntax"),
|
||||
display("unable to detect syntax for {}", input)
|
||||
}
|
||||
UnknownSyntax(name: String) {
|
||||
description("unknown syntax"),
|
||||
display("unknown syntax: '{}'", name)
|
||||
}
|
||||
InvalidPagerValueBat {
|
||||
description("invalid value `bat` for pager property"),
|
||||
display("Use of bat as a pager is disallowed in order to avoid infinite recursion problems")
|
||||
}
|
||||
impl From<&'static str> for Error {
|
||||
fn from(s: &'static str) -> Self {
|
||||
Error::Msg(s.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Error {
|
||||
fn from(s: String) -> Self {
|
||||
Error::Msg(s)
|
||||
}
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
pub fn default_error_handler(error: &Error, output: &mut dyn Write) {
|
||||
use ansi_term::Colour::Red;
|
||||
|
||||
match error {
|
||||
Error(ErrorKind::Io(ref io_error), _)
|
||||
if io_error.kind() == ::std::io::ErrorKind::BrokenPipe =>
|
||||
{
|
||||
Error::Io(ref io_error) if io_error.kind() == ::std::io::ErrorKind::BrokenPipe => {
|
||||
::std::process::exit(0);
|
||||
}
|
||||
Error(ErrorKind::SerdeYamlError(_), _) => {
|
||||
Error::SerdeYamlError(_) => {
|
||||
writeln!(
|
||||
output,
|
||||
"{}: Error while parsing metadata.yaml file: {}",
|
||||
|
@@ -52,7 +52,7 @@ impl OutputType {
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
let pager_opt =
|
||||
pager::get_pager(pager_from_config).chain_err(|| "Could not parse pager command.")?;
|
||||
pager::get_pager(pager_from_config).map_err(|_| "Could not parse pager command.")?;
|
||||
|
||||
let pager = match pager_opt {
|
||||
Some(pager) => pager,
|
||||
@@ -60,7 +60,7 @@ impl OutputType {
|
||||
};
|
||||
|
||||
if pager.kind == PagerKind::Bat {
|
||||
return Err(ErrorKind::InvalidPagerValueBat.into());
|
||||
return Err(Error::InvalidPagerValueBat);
|
||||
}
|
||||
|
||||
let resolved_path = match grep_cli::resolve_binary(&pager.bin) {
|
||||
@@ -142,7 +142,7 @@ impl OutputType {
|
||||
OutputType::Pager(ref mut command) => command
|
||||
.stdin
|
||||
.as_mut()
|
||||
.chain_err(|| "Could not open stdin for pager")?,
|
||||
.ok_or("Could not open stdin for pager")?,
|
||||
OutputType::Stdout(ref mut handle) => handle,
|
||||
})
|
||||
}
|
||||
|
@@ -174,7 +174,7 @@ impl<'a> InteractivePrinter<'a> {
|
||||
let syntax_in_set =
|
||||
match assets.get_syntax(config.language, input, &config.syntax_mapping) {
|
||||
Ok(syntax_in_set) => syntax_in_set,
|
||||
Err(Error(ErrorKind::UndetectedSyntax(_), _)) => {
|
||||
Err(Error::UndetectedSyntax(_)) => {
|
||||
let syntax_set = assets.get_syntax_set()?;
|
||||
let syntax = syntax_set.find_syntax_plain_text();
|
||||
SyntaxReferenceInSet { syntax, syntax_set }
|
||||
|
Reference in New Issue
Block a user