Skip to content

Commit fe5fa87

Browse files
committed
rustfmt: Make error handling more idiomatic
This commit replaces the `Operation::InvalidInput` variant with `Result`, and uses the `try!()` macro instead of explicit matching.
1 parent b55e50f commit fe5fa87

File tree

1 file changed

+35
-50
lines changed

1 file changed

+35
-50
lines changed

src/bin/rustfmt.rs

+35-50
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,16 @@ extern crate getopts;
2020
use rustfmt::{run, Input};
2121
use rustfmt::config::{Config, WriteMode};
2222

23-
use std::env;
23+
use std::{env, error};
2424
use std::fs::{self, File};
2525
use std::io::{self, ErrorKind, Read, Write};
2626
use std::path::{Path, PathBuf};
2727
use std::str::FromStr;
2828

2929
use getopts::{Matches, Options};
3030

31+
type FmtError = Box<error::Error + Send + Sync>;
32+
type FmtResult<T> = std::result::Result<T, FmtError>;
3133

3234
/// Rustfmt operations.
3335
enum Operation {
@@ -42,10 +44,6 @@ enum Operation {
4244
Version,
4345
/// Print detailed configuration help.
4446
ConfigHelp,
45-
/// Invalid program input.
46-
InvalidInput {
47-
reason: String,
48-
},
4947
/// No file specified, read from stdin
5048
Stdin {
5149
input: String,
@@ -55,7 +53,7 @@ enum Operation {
5553

5654
/// Try to find a project file in the given directory and its parents. Returns the path of a the
5755
/// nearest project file if one exists, or `None` if no project file was found.
58-
fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
56+
fn lookup_project_file(dir: &Path) -> FmtResult<Option<PathBuf>> {
5957
let mut current = if dir.is_relative() {
6058
try!(env::current_dir()).join(dir)
6159
} else {
@@ -77,7 +75,7 @@ fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
7775
// return the error.
7876
Err(e) => {
7977
if e.kind() != ErrorKind::NotFound {
80-
return Err(e);
78+
return Err(FmtError::from(e));
8179
}
8280
}
8381
}
@@ -93,7 +91,7 @@ fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
9391
///
9492
/// Returns the `Config` to use, and the path of the project file if there was
9593
/// one.
96-
fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
94+
fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
9795
let path = try!(lookup_project_file(dir));
9896
if path.is_none() {
9997
return Ok((Config::default(), None));
@@ -108,7 +106,7 @@ fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
108106
/// read the given config file path recursively if present else read the project file path
109107
fn match_cli_path_or_file(config_path: Option<PathBuf>,
110108
input_file: &Path)
111-
-> io::Result<(Config, Option<PathBuf>)> {
109+
-> FmtResult<(Config, Option<PathBuf>)> {
112110

113111
if let Some(config_file) = config_path {
114112
let (toml, path) = try!(resolve_config(config_file.as_ref()));
@@ -119,7 +117,7 @@ fn match_cli_path_or_file(config_path: Option<PathBuf>,
119117
resolve_config(input_file)
120118
}
121119

122-
fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
120+
fn update_config(config: &mut Config, matches: &Matches) -> FmtResult<()> {
123121
config.verbose = matches.opt_present("verbose");
124122
config.skip_children = matches.opt_present("skip-children");
125123

@@ -130,7 +128,10 @@ fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
130128
config.write_mode = write_mode;
131129
Ok(())
132130
}
133-
Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
131+
Some(Err(_)) => {
132+
Err(FmtError::from(format!("Invalid write-mode: {}",
133+
write_mode.expect("cannot happen"))))
134+
}
134135
}
135136
}
136137

@@ -157,35 +158,18 @@ fn make_opts() -> Options {
157158
opts
158159
}
159160

160-
fn execute() -> i32 {
161-
let opts = make_opts();
161+
fn execute(opts: &Options) -> FmtResult<()> {
162+
let matches = try!(opts.parse(env::args().skip(1)));
162163

163-
let matches = match opts.parse(env::args().skip(1)) {
164-
Ok(m) => m,
165-
Err(e) => {
166-
print_usage(&opts, &e.to_string());
167-
return 1;
168-
}
169-
};
170-
171-
let operation = determine_operation(&matches);
172-
173-
match operation {
174-
Operation::InvalidInput { reason } => {
175-
print_usage(&opts, &reason);
176-
1
177-
}
164+
match try!(determine_operation(&matches)) {
178165
Operation::Help => {
179166
print_usage(&opts, "");
180-
0
181167
}
182168
Operation::Version => {
183169
print_version();
184-
0
185170
}
186171
Operation::ConfigHelp => {
187172
Config::print_docs();
188-
0
189173
}
190174
Operation::Stdin { input, config_path } => {
191175
// try to read config from local directory
@@ -196,7 +180,6 @@ fn execute() -> i32 {
196180
config.write_mode = WriteMode::Plain;
197181

198182
run(Input::Text(input), &config);
199-
0
200183
}
201184
Operation::Format { files, config_path } => {
202185
let mut config = Config::default();
@@ -227,21 +210,26 @@ fn execute() -> i32 {
227210
config = config_tmp;
228211
}
229212

230-
if let Err(e) = update_config(&mut config, &matches) {
231-
print_usage(&opts, &e);
232-
return 1;
233-
}
213+
try!(update_config(&mut config, &matches));
234214
run(Input::File(file), &config);
235215
}
236-
0
237216
}
238217
}
218+
Ok(())
239219
}
240220

241221
fn main() {
242222
let _ = env_logger::init();
243-
let exit_code = execute();
244223

224+
let opts = make_opts();
225+
226+
let exit_code = match execute(&opts) {
227+
Ok(..) => 0,
228+
Err(e) => {
229+
print_usage(&opts, &e.to_string());
230+
1
231+
}
232+
};
245233
// Make sure standard output is flushed before we exit.
246234
std::io::stdout().flush().unwrap();
247235

@@ -267,17 +255,17 @@ fn print_version() {
267255
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
268256
}
269257

270-
fn determine_operation(matches: &Matches) -> Operation {
258+
fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
271259
if matches.opt_present("h") {
272-
return Operation::Help;
260+
return Ok(Operation::Help);
273261
}
274262

275263
if matches.opt_present("config-help") {
276-
return Operation::ConfigHelp;
264+
return Ok(Operation::ConfigHelp);
277265
}
278266

279267
if matches.opt_present("version") {
280-
return Operation::Version;
268+
return Ok(Operation::Version);
281269
}
282270

283271
// Read the config_path and convert to parent dir if a file is provided.
@@ -294,21 +282,18 @@ fn determine_operation(matches: &Matches) -> Operation {
294282
if matches.free.is_empty() {
295283

296284
let mut buffer = String::new();
297-
match io::stdin().read_to_string(&mut buffer) {
298-
Ok(..) => (),
299-
Err(e) => return Operation::InvalidInput { reason: e.to_string() },
300-
}
285+
try!(io::stdin().read_to_string(&mut buffer));
301286

302-
return Operation::Stdin {
287+
return Ok(Operation::Stdin {
303288
input: buffer,
304289
config_path: config_path,
305-
};
290+
});
306291
}
307292

308293
let files: Vec<_> = matches.free.iter().map(PathBuf::from).collect();
309294

310-
Operation::Format {
295+
Ok(Operation::Format {
311296
files: files,
312297
config_path: config_path,
313-
}
298+
})
314299
}

0 commit comments

Comments
 (0)