about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorNick Cameron <nrc@ncameron.org>2018-04-27 15:14:47 +1200
committerGitHub <noreply@github.com>2018-04-27 15:14:47 +1200
commitd19fc450c06cd480ef2b9e1031b55ff10df080a7 (patch)
treed8dbe4dcea5b97bdfbd078f98ff53c5497d32e57 /src
parent0f4ed08d0e3d180d66e46904126c3792f57668a9 (diff)
parente06c9c8c5304d1d187e3adb603446bfb63afdd6d (diff)
Merge pull request #2650 from thibaultdelor/useFailureCrate
Use failure crate
Diffstat (limited to 'src')
-rw-r--r--src/bin/main.rs11
-rw-r--r--src/config/mod.rs25
-rw-r--r--src/config/options.rs19
-rw-r--r--src/format-diff/main.rs38
-rw-r--r--src/lib.rs34
5 files changed, 56 insertions, 71 deletions
diff --git a/src/bin/main.rs b/src/bin/main.rs
index 453c7806d23..0ddf2f8c3df 100644
--- a/src/bin/main.rs
+++ b/src/bin/main.rs
@@ -11,6 +11,7 @@
 #![cfg(not(test))]
 
 extern crate env_logger;
+extern crate failure;
 extern crate getopts;
 extern crate rustfmt_nightly as rustfmt;
 
@@ -19,6 +20,8 @@ use std::fs::File;
 use std::io::{self, stdout, Read, Write};
 use std::path::PathBuf;
 
+use failure::err_msg;
+
 use getopts::{Matches, Options};
 
 use rustfmt::{emit_post_matter, emit_pre_matter, load_config, CliOptions, Config, FmtResult,
@@ -167,7 +170,7 @@ fn execute(opts: &Options) -> FmtResult<(WriteMode, Summary)> {
             Ok((WriteMode::None, Summary::default()))
         }
         Operation::ConfigOutputDefault { path } => {
-            let toml = Config::default().all_options().to_toml()?;
+            let toml = Config::default().all_options().to_toml().map_err(err_msg)?;
             if let Some(path) = path {
                 let mut file = File::create(path)?;
                 file.write_all(toml.as_bytes())?;
@@ -186,7 +189,9 @@ fn execute(opts: &Options) -> FmtResult<(WriteMode, Summary)> {
 
             // parse file_lines
             if let Some(ref file_lines) = matches.opt_str("file-lines") {
-                config.set().file_lines(file_lines.parse()?);
+                config
+                    .set()
+                    .file_lines(file_lines.parse().map_err(err_msg)?);
                 for f in config.file_lines().files() {
                     match *f {
                         FileName::Custom(ref f) if f == "stdin" => {}
@@ -273,7 +278,7 @@ fn format(
     // that were used during formatting as TOML.
     if let Some(path) = minimal_config_path {
         let mut file = File::create(path)?;
-        let toml = config.used_options().to_toml()?;
+        let toml = config.used_options().to_toml().map_err(err_msg)?;
         file.write_all(toml.as_bytes())?;
     }
 
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 8dde1e05c3d..23897f3cc32 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -16,8 +16,6 @@ use std::io::{Error, ErrorKind, Read};
 use std::path::{Path, PathBuf};
 use std::{env, fs};
 
-use {FmtError, FmtResult};
-
 use config::config_type::ConfigType;
 use config::file_lines::FileLines;
 pub use config::lists::*;
@@ -154,18 +152,16 @@ create_config! {
 pub fn load_config(
     file_path: Option<&Path>,
     options: Option<&CliOptions>,
-) -> FmtResult<(Config, Option<PathBuf>)> {
+) -> Result<(Config, Option<PathBuf>), Error> {
     let over_ride = match options {
         Some(opts) => config_path(opts)?,
         None => None,
     };
 
     let result = if let Some(over_ride) = over_ride {
-        Config::from_toml_path(over_ride.as_ref())
-            .map(|p| (p, Some(over_ride.to_owned())))
-            .map_err(FmtError::from)
+        Config::from_toml_path(over_ride.as_ref()).map(|p| (p, Some(over_ride.to_owned())))
     } else if let Some(file_path) = file_path {
-        Config::from_resolved_toml_path(file_path).map_err(FmtError::from)
+        Config::from_resolved_toml_path(file_path)
     } else {
         Ok((Config::default(), None))
     };
@@ -202,12 +198,15 @@ fn get_toml_path(dir: &Path) -> Result<Option<PathBuf>, Error> {
     Ok(None)
 }
 
-fn config_path(options: &CliOptions) -> FmtResult<Option<PathBuf>> {
-    let config_path_not_found = |path: &str| -> FmtResult<Option<PathBuf>> {
-        Err(FmtError::from(format!(
-            "Error: unable to find a config file for the given path: `{}`",
-            path
-        )))
+fn config_path(options: &CliOptions) -> Result<Option<PathBuf>, Error> {
+    let config_path_not_found = |path: &str| -> Result<Option<PathBuf>, Error> {
+        Err(Error::new(
+            ErrorKind::NotFound,
+            format!(
+                "Error: unable to find a config file for the given path: `{}`",
+                path
+            ),
+        ))
     };
 
     // Read the config_path and convert to parent dir if a file is provided.
diff --git a/src/config/options.rs b/src/config/options.rs
index 73dbdb88663..9721815eeee 100644
--- a/src/config/options.rs
+++ b/src/config/options.rs
@@ -14,7 +14,9 @@ use config::config_type::ConfigType;
 use config::file_lines::FileLines;
 use config::lists::*;
 use config::Config;
-use {FmtError, FmtResult, WRITE_MODE_LIST};
+use {FmtResult, WRITE_MODE_LIST};
+
+use failure::err_msg;
 
 use getopts::Matches;
 use std::collections::HashSet;
@@ -332,8 +334,8 @@ impl CliOptions {
             .map(|c| c == "nightly")
             .unwrap_or(false);
         if unstable_features && !rust_nightly {
-            return Err(FmtError::from(
-                "Unstable features are only available on Nightly channel",
+            return Err(format_err!(
+                "Unstable features are only available on Nightly channel"
             ));
         } else {
             options.unstable_features = unstable_features;
@@ -345,22 +347,23 @@ impl CliOptions {
             if let Ok(write_mode) = WriteMode::from_str(write_mode) {
                 options.write_mode = Some(write_mode);
             } else {
-                return Err(FmtError::from(format!(
+                return Err(format_err!(
                     "Invalid write-mode: {}, expected one of {}",
-                    write_mode, WRITE_MODE_LIST
-                )));
+                    write_mode,
+                    WRITE_MODE_LIST
+                ));
             }
         }
 
         if let Some(ref color) = matches.opt_str("color") {
             match Color::from_str(color) {
                 Ok(color) => options.color = Some(color),
-                _ => return Err(FmtError::from(format!("Invalid color: {}", color))),
+                _ => return Err(format_err!("Invalid color: {}", color)),
             }
         }
 
         if let Some(ref file_lines) = matches.opt_str("file-lines") {
-            options.file_lines = file_lines.parse()?;
+            options.file_lines = file_lines.parse().map_err(err_msg)?;
         }
 
         if matches.opt_present("skip-children") {
diff --git a/src/format-diff/main.rs b/src/format-diff/main.rs
index 402f7ab507a..fe528a6c0ea 100644
--- a/src/format-diff/main.rs
+++ b/src/format-diff/main.rs
@@ -15,6 +15,8 @@
 #![deny(warnings)]
 
 extern crate env_logger;
+#[macro_use]
+extern crate failure;
 extern crate getopts;
 #[macro_use]
 extern crate log;
@@ -24,9 +26,8 @@ extern crate serde_derive;
 extern crate serde_json as json;
 
 use std::collections::HashSet;
-use std::error::Error;
 use std::io::{self, BufRead};
-use std::{env, fmt, process};
+use std::{env, process};
 
 use regex::Regex;
 
@@ -35,31 +36,14 @@ use regex::Regex;
 /// We only want to format rust files by default.
 const DEFAULT_PATTERN: &str = r".*\.rs";
 
-#[derive(Debug)]
+#[derive(Fail, Debug)]
 enum FormatDiffError {
-    IncorrectOptions(getopts::Fail),
-    IncorrectFilter(regex::Error),
-    IoError(io::Error),
-}
-
-impl fmt::Display for FormatDiffError {
-    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        fmt::Display::fmt(self.cause().unwrap(), f)
-    }
-}
-
-impl Error for FormatDiffError {
-    fn description(&self) -> &str {
-        self.cause().unwrap().description()
-    }
-
-    fn cause(&self) -> Option<&Error> {
-        Some(match *self {
-            FormatDiffError::IoError(ref e) => e,
-            FormatDiffError::IncorrectFilter(ref e) => e,
-            FormatDiffError::IncorrectOptions(ref e) => e,
-        })
-    }
+    #[fail(display = "{}", _0)]
+    IncorrectOptions(#[cause] getopts::Fail),
+    #[fail(display = "{}", _0)]
+    IncorrectFilter(#[cause] regex::Error),
+    #[fail(display = "{}", _0)]
+    IoError(#[cause] io::Error),
 }
 
 impl From<getopts::Fail> for FormatDiffError {
@@ -99,7 +83,7 @@ fn main() {
     );
 
     if let Err(e) = run(&opts) {
-        println!("{}", opts.usage(e.description()));
+        println!("{}", opts.usage(&format!("{}", e)));
         process::exit(1);
     }
 }
diff --git a/src/lib.rs b/src/lib.rs
index 0a5c7307e4f..b272402b20f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -19,6 +19,8 @@
 #[macro_use]
 extern crate derive_new;
 extern crate diff;
+#[macro_use]
+extern crate failure;
 extern crate getopts;
 extern crate itertools;
 #[cfg(test)]
@@ -37,7 +39,6 @@ extern crate toml;
 extern crate unicode_segmentation;
 
 use std::collections::HashMap;
-use std::error;
 use std::fmt;
 use std::io::{self, stdout, Write};
 use std::panic::{catch_unwind, AssertUnwindSafe};
@@ -53,6 +54,7 @@ use syntax::errors::{DiagnosticBuilder, Handler};
 use syntax::parse::{self, ParseSess};
 
 use comment::{CharClasses, FullCodeCharKind, LineClasses};
+use failure::Fail;
 use issues::{BadIssueSeeker, Issue};
 use shape::Indent;
 use utils::use_colored_tty;
@@ -62,8 +64,7 @@ pub use config::options::CliOptions;
 pub use config::summary::Summary;
 pub use config::{file_lines, load_config, Config, WriteMode};
 
-pub type FmtError = Box<error::Error + Send + Sync>;
-pub type FmtResult<T> = std::result::Result<T, FmtError>;
+pub type FmtResult<T> = std::result::Result<T, failure::Error>;
 
 pub const WRITE_MODE_LIST: &str =
     "[replace|overwrite|display|plain|diff|coverage|checkstyle|check]";
@@ -109,33 +110,26 @@ pub(crate) type FileMap = Vec<FileRecord>;
 
 pub(crate) type FileRecord = (FileName, String);
 
-#[derive(Clone, Copy)]
+#[derive(Fail, Debug, Clone, Copy)]
 pub enum ErrorKind {
     // Line has exceeded character limit (found, maximum)
+    #[fail(
+        display = "line formatted, but exceeded maximum width (maximum: {} (see `max_width` option), found: {})",
+        _0,
+        _1
+    )]
     LineOverflow(usize, usize),
     // Line ends in whitespace
+    #[fail(display = "left behind trailing whitespace")]
     TrailingWhitespace,
     // TODO or FIXME item without an issue number
+    #[fail(display = "found {}", _0)]
     BadIssue(Issue),
     // License check has failed
+    #[fail(display = "license check failed")]
     LicenseCheck,
 }
 
-impl fmt::Display for ErrorKind {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
-        match *self {
-            ErrorKind::LineOverflow(found, maximum) => write!(
-                fmt,
-                "line formatted, but exceeded maximum width (maximum: {} (see `max_width` option), found: {})",
-                maximum, found,
-            ),
-            ErrorKind::TrailingWhitespace => write!(fmt, "left behind trailing whitespace"),
-            ErrorKind::BadIssue(issue) => write!(fmt, "found {}", issue),
-            ErrorKind::LicenseCheck => write!(fmt, "license check failed"),
-        }
-    }
-}
-
 // Formatting errors that are identified *after* rustfmt has run.
 struct FormattingError {
     line: usize,
@@ -901,7 +895,7 @@ pub enum Input {
 
 pub fn format_and_emit_report(input: Input, config: &Config) -> FmtResult<Summary> {
     if !config.version_meets_requirement() {
-        return Err(FmtError::from("Version mismatch"));
+        return Err(format_err!("Version mismatch"));
     }
     let out = &mut stdout();
     match format_input(input, config, Some(out)) {