Skip to content

Commit 7713d05

Browse files
dtolnaytopecongiro
authored andcommitted
Switch to std::error::Error for errors (#3948)
1 parent 90aaf45 commit 7713d05

File tree

7 files changed

+92
-69
lines changed

7 files changed

+92
-69
lines changed

Cargo.lock

Lines changed: 28 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ log = "0.4"
4646
env_logger = "0.6"
4747
getopts = "0.2"
4848
cargo_metadata = "0.8"
49-
failure = "0.1.3"
5049
bytecount = "0.6"
5150
unicode-width = "0.1.5"
5251
unicode_categories = "0.1.1"
@@ -57,6 +56,8 @@ structopt = "0.3"
5756
rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" }
5857
lazy_static = "1.0.0"
5958
ansi_term = "0.12"
59+
anyhow = "1.0"
60+
thiserror = "1.0"
6061

6162
# A noop dependency that changes in the Rust repository, it's a bit of a hack.
6263
# See the `src/tools/rustc-workspace-hack/README.md` file in `rust-lang/rust`

src/bin/main.rs

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
use anyhow::{format_err, Result};
12
use env_logger;
2-
use failure::{err_msg, format_err, Error as FailureError, Fail};
33
use io::Error as IoError;
4+
use thiserror::Error;
45

56
use rustfmt_nightly as rustfmt;
67

@@ -61,23 +62,23 @@ enum Operation {
6162
}
6263

6364
/// Rustfmt operations errors.
64-
#[derive(Fail, Debug)]
65+
#[derive(Error, Debug)]
6566
pub enum OperationError {
6667
/// An unknown help topic was requested.
67-
#[fail(display = "Unknown help topic: `{}`.", _0)]
68+
#[error("Unknown help topic: `{0}`.")]
6869
UnknownHelpTopic(String),
6970
/// An unknown print-config option was requested.
70-
#[fail(display = "Unknown print-config option: `{}`.", _0)]
71+
#[error("Unknown print-config option: `{0}`.")]
7172
UnknownPrintConfigTopic(String),
7273
/// Attempt to generate a minimal config from standard input.
73-
#[fail(display = "The `--print-config=minimal` option doesn't work with standard input.")]
74+
#[error("The `--print-config=minimal` option doesn't work with standard input.")]
7475
MinimalPathWithStdin,
7576
/// An io error during reading or writing.
76-
#[fail(display = "io error: {}", _0)]
77+
#[error("io error: {0}")]
7778
IoError(IoError),
7879
/// Attempt to use --emit with a mode which is not currently
7980
/// supported with stdandard input.
80-
#[fail(display = "Emit mode {} not supported with standard output.", _0)]
81+
#[error("Emit mode {0} not supported with standard output.")]
8182
StdinBadEmit(EmitMode),
8283
}
8384

@@ -189,7 +190,7 @@ fn is_nightly() -> bool {
189190
}
190191

191192
// Returned i32 is an exit code
192-
fn execute(opts: &Options) -> Result<i32, FailureError> {
193+
fn execute(opts: &Options) -> Result<i32> {
193194
let matches = opts.parse(env::args().skip(1))?;
194195
let options = GetOptsOptions::from_matches(&matches)?;
195196

@@ -211,7 +212,7 @@ fn execute(opts: &Options) -> Result<i32, FailureError> {
211212
Ok(0)
212213
}
213214
Operation::ConfigOutputDefault { path } => {
214-
let toml = Config::default().all_options().to_toml().map_err(err_msg)?;
215+
let toml = Config::default().all_options().to_toml()?;
215216
if let Some(path) = path {
216217
let mut file = File::create(path)?;
217218
file.write_all(toml.as_bytes())?;
@@ -230,7 +231,7 @@ fn execute(opts: &Options) -> Result<i32, FailureError> {
230231
let file = file.canonicalize().unwrap_or(file);
231232

232233
let (config, _) = load_config(Some(file.parent().unwrap()), Some(options.clone()))?;
233-
let toml = config.all_options().to_toml().map_err(err_msg)?;
234+
let toml = config.all_options().to_toml()?;
234235
io::stdout().write_all(toml.as_bytes())?;
235236

236237
Ok(0)
@@ -243,7 +244,7 @@ fn execute(opts: &Options) -> Result<i32, FailureError> {
243244
}
244245
}
245246

246-
fn format_string(input: String, options: GetOptsOptions) -> Result<i32, FailureError> {
247+
fn format_string(input: String, options: GetOptsOptions) -> Result<i32> {
247248
// try to read config from local directory
248249
let (mut config, _) = load_config(Some(Path::new(".")), Some(options.clone()))?;
249250

@@ -289,7 +290,7 @@ fn format(
289290
files: Vec<PathBuf>,
290291
minimal_config_path: Option<String>,
291292
options: &GetOptsOptions,
292-
) -> Result<i32, FailureError> {
293+
) -> Result<i32> {
293294
options.verify_file_lines(&files);
294295
let (config, config_path) = load_config(None, Some(options.clone()))?;
295296

@@ -337,7 +338,7 @@ fn format(
337338
// that were used during formatting as TOML.
338339
if let Some(path) = minimal_config_path {
339340
let mut file = File::create(path)?;
340-
let toml = session.config.used_options().to_toml().map_err(err_msg)?;
341+
let toml = session.config.used_options().to_toml()?;
341342
file.write_all(toml.as_bytes())?;
342343
}
343344

@@ -521,7 +522,7 @@ fn deprecate_skip_children() {
521522
}
522523

523524
impl GetOptsOptions {
524-
pub fn from_matches(matches: &Matches) -> Result<GetOptsOptions, FailureError> {
525+
pub fn from_matches(matches: &Matches) -> Result<GetOptsOptions> {
525526
let mut options = GetOptsOptions::default();
526527
options.verbose = matches.opt_present("verbose");
527528
options.quiet = matches.opt_present("quiet");
@@ -543,7 +544,7 @@ impl GetOptsOptions {
543544
options.error_on_unformatted = Some(true);
544545
}
545546
if let Some(ref file_lines) = matches.opt_str("file-lines") {
546-
options.file_lines = file_lines.parse().map_err(err_msg)?;
547+
options.file_lines = file_lines.parse()?;
547548
}
548549
} else {
549550
let mut unstable_options = vec![];
@@ -686,15 +687,15 @@ impl CliOptions for GetOptsOptions {
686687
}
687688
}
688689

689-
fn edition_from_edition_str(edition_str: &str) -> Result<Edition, FailureError> {
690+
fn edition_from_edition_str(edition_str: &str) -> Result<Edition> {
690691
match edition_str {
691692
"2015" => Ok(Edition::Edition2015),
692693
"2018" => Ok(Edition::Edition2018),
693694
_ => Err(format_err!("Invalid value for `--edition`")),
694695
}
695696
}
696697

697-
fn emit_mode_from_emit_str(emit_str: &str) -> Result<EmitMode, FailureError> {
698+
fn emit_mode_from_emit_str(emit_str: &str) -> Result<EmitMode> {
698699
match emit_str {
699700
"files" => Ok(EmitMode::Files),
700701
"stdout" => Ok(EmitMode::Stdout),

src/config/file_lines.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::{cmp, fmt, iter, str};
88

99
use serde::{ser, Deserialize, Deserializer, Serialize, Serializer};
1010
use serde_json as json;
11+
use thiserror::Error;
1112

1213
use syntax::source_map::{self, SourceFile};
1314

@@ -288,12 +289,20 @@ fn canonicalize_path_string(file: &FileName) -> Option<FileName> {
288289
}
289290
}
290291

292+
#[derive(Error, Debug)]
293+
pub enum FileLinesError {
294+
#[error("{0}")]
295+
Json(json::Error),
296+
#[error("Can't canonicalize {0}")]
297+
CannotCanonicalize(FileName),
298+
}
299+
291300
// This impl is needed for `Config::override_value` to work for use in tests.
292301
impl str::FromStr for FileLines {
293-
type Err = String;
302+
type Err = FileLinesError;
294303

295-
fn from_str(s: &str) -> Result<FileLines, String> {
296-
let v: Vec<JsonSpan> = json::from_str(s).map_err(|e| e.to_string())?;
304+
fn from_str(s: &str) -> Result<FileLines, Self::Err> {
305+
let v: Vec<JsonSpan> = json::from_str(s).map_err(FileLinesError::Json)?;
297306
let mut m = HashMap::new();
298307
for js in v {
299308
let (s, r) = JsonSpan::into_tuple(js)?;
@@ -311,10 +320,10 @@ pub struct JsonSpan {
311320
}
312321

313322
impl JsonSpan {
314-
fn into_tuple(self) -> Result<(FileName, Range), String> {
323+
fn into_tuple(self) -> Result<(FileName, Range), FileLinesError> {
315324
let (lo, hi) = self.range;
316325
let canonical = canonicalize_path_string(&self.file)
317-
.ok_or_else(|| format!("Can't canonicalize {}", &self.file))?;
326+
.ok_or_else(|| FileLinesError::CannotCanonicalize(self.file))?;
318327
Ok((canonical, Range::new(lo, hi)))
319328
}
320329
}

src/config/mod.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
66
use std::{env, fs};
77

88
use regex::Regex;
9+
use thiserror::Error;
910

1011
use crate::config::config_type::ConfigType;
1112
#[allow(unreachable_pub)]
@@ -156,16 +157,20 @@ create_config! {
156157
files that would be formated when used with `--check` mode. ";
157158
}
158159

160+
#[derive(Error, Debug)]
161+
#[error("Could not output config: {0}")]
162+
pub struct ToTomlError(toml::ser::Error);
163+
159164
impl PartialConfig {
160-
pub fn to_toml(&self) -> Result<String, String> {
165+
pub fn to_toml(&self) -> Result<String, ToTomlError> {
161166
// Non-user-facing options can't be specified in TOML
162167
let mut cloned = self.clone();
163168
cloned.file_lines = None;
164169
cloned.verbose = None;
165170
cloned.width_heuristics = None;
166171
cloned.print_misformatted_file_names = None;
167172

168-
::toml::to_string(&cloned).map_err(|e| format!("Could not output config: {}", e))
173+
::toml::to_string(&cloned).map_err(ToTomlError)
169174
}
170175
}
171176

src/format-diff/main.rs

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66

77
use env_logger;
88
#[macro_use]
9-
extern crate failure;
10-
#[macro_use]
119
extern crate log;
1210
use regex;
1311
use serde::{Deserialize, Serialize};
1412
use serde_json as json;
13+
use thiserror::Error;
1514

1615
use std::collections::HashSet;
1716
use std::io::{self, BufRead};
@@ -27,32 +26,14 @@ use structopt::StructOpt;
2726
/// We only want to format rust files by default.
2827
const DEFAULT_PATTERN: &str = r".*\.rs";
2928

30-
#[derive(Fail, Debug)]
29+
#[derive(Error, Debug)]
3130
enum FormatDiffError {
32-
#[fail(display = "{}", _0)]
33-
IncorrectOptions(#[cause] getopts::Fail),
34-
#[fail(display = "{}", _0)]
35-
IncorrectFilter(#[cause] regex::Error),
36-
#[fail(display = "{}", _0)]
37-
IoError(#[cause] io::Error),
38-
}
39-
40-
impl From<getopts::Fail> for FormatDiffError {
41-
fn from(fail: getopts::Fail) -> Self {
42-
FormatDiffError::IncorrectOptions(fail)
43-
}
44-
}
45-
46-
impl From<regex::Error> for FormatDiffError {
47-
fn from(err: regex::Error) -> Self {
48-
FormatDiffError::IncorrectFilter(err)
49-
}
50-
}
51-
52-
impl From<io::Error> for FormatDiffError {
53-
fn from(fail: io::Error) -> Self {
54-
FormatDiffError::IoError(fail)
55-
}
31+
#[error("{0}")]
32+
IncorrectOptions(#[from] getopts::Fail),
33+
#[error("{0}")]
34+
IncorrectFilter(#[from] regex::Error),
35+
#[error("{0}")]
36+
IoError(#[from] io::Error),
5637
}
5738

5839
#[derive(StructOpt, Debug)]

0 commit comments

Comments
 (0)