Skip to content

Commit e7220e1

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 e7220e1

File tree

1 file changed

+37
-55
lines changed

1 file changed

+37
-55
lines changed

src/bin/rustfmt.rs

Lines changed: 37 additions & 55 deletions
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 Error = Box<error::Error + Send + Sync>;
32+
type Result<T> = std::result::Result<T, Error>;
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) -> Result<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(Error::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) -> Result<(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+
-> Result<(Config, Option<PathBuf>)> {
112110

113111
if let Some(config_file) = config_path {
114112
let (toml, path) = try!(resolve_config(config_file.as_ref()));
@@ -119,19 +117,19 @@ 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) -> Result<()> {
123121
config.verbose = matches.opt_present("verbose");
124122
config.skip_children = matches.opt_present("skip-children");
125123

126-
let write_mode = matches.opt_str("write-mode");
127-
match matches.opt_str("write-mode").map(|wm| WriteMode::from_str(&wm)) {
128-
None => Ok(()),
129-
Some(Ok(write_mode)) => {
124+
if let Some(ref write_mode) = matches.opt_str("write-mode") {
125+
if let Ok(write_mode) = WriteMode::from_str(write_mode) {
130126
config.write_mode = write_mode;
131-
Ok(())
127+
} else {
128+
return Err(Error::from(format!("Invalid write-mode: {}", write_mode)));
132129
}
133-
Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
134130
}
131+
132+
Ok(())
135133
}
136134

137135
fn make_opts() -> Options {
@@ -157,35 +155,18 @@ fn make_opts() -> Options {
157155
opts
158156
}
159157

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

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-
}
161+
match try!(determine_operation(&matches)) {
178162
Operation::Help => {
179163
print_usage(&opts, "");
180-
0
181164
}
182165
Operation::Version => {
183166
print_version();
184-
0
185167
}
186168
Operation::ConfigHelp => {
187169
Config::print_docs();
188-
0
189170
}
190171
Operation::Stdin { input, config_path } => {
191172
// try to read config from local directory
@@ -196,7 +177,6 @@ fn execute() -> i32 {
196177
config.write_mode = WriteMode::Plain;
197178

198179
run(Input::Text(input), &config);
199-
0
200180
}
201181
Operation::Format { files, config_path } => {
202182
let mut config = Config::default();
@@ -227,21 +207,26 @@ fn execute() -> i32 {
227207
config = config_tmp;
228208
}
229209

230-
if let Err(e) = update_config(&mut config, &matches) {
231-
print_usage(&opts, &e);
232-
return 1;
233-
}
210+
try!(update_config(&mut config, &matches));
234211
run(Input::File(file), &config);
235212
}
236-
0
237213
}
238214
}
215+
Ok(())
239216
}
240217

241218
fn main() {
242219
let _ = env_logger::init();
243-
let exit_code = execute();
244220

221+
let opts = make_opts();
222+
223+
let exit_code = match execute(&opts) {
224+
Ok(..) => 0,
225+
Err(e) => {
226+
print_usage(&opts, &e.to_string());
227+
1
228+
}
229+
};
245230
// Make sure standard output is flushed before we exit.
246231
std::io::stdout().flush().unwrap();
247232

@@ -267,17 +252,17 @@ fn print_version() {
267252
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
268253
}
269254

270-
fn determine_operation(matches: &Matches) -> Operation {
255+
fn determine_operation(matches: &Matches) -> Result<Operation> {
271256
if matches.opt_present("h") {
272-
return Operation::Help;
257+
return Ok(Operation::Help);
273258
}
274259

275260
if matches.opt_present("config-help") {
276-
return Operation::ConfigHelp;
261+
return Ok(Operation::ConfigHelp);
277262
}
278263

279264
if matches.opt_present("version") {
280-
return Operation::Version;
265+
return Ok(Operation::Version);
281266
}
282267

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

296281
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-
}
282+
try!(io::stdin().read_to_string(&mut buffer));
301283

302-
return Operation::Stdin {
284+
return Ok(Operation::Stdin {
303285
input: buffer,
304286
config_path: config_path,
305-
};
287+
});
306288
}
307289

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

310-
Operation::Format {
292+
Ok(Operation::Format {
311293
files: files,
312294
config_path: config_path,
313-
}
295+
})
314296
}

0 commit comments

Comments
 (0)