Skip to content

Commit 1824669

Browse files
committed
Merge pull request #914 from kamalmarhubi/invalid-operation-result
rustfmt: Make error handling more idiomatic
2 parents 58b022c + 7242735 commit 1824669

File tree

1 file changed

+44
-55
lines changed

1 file changed

+44
-55
lines changed

src/bin/rustfmt.rs

Lines changed: 44 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 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 {
@@ -67,19 +65,17 @@ fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
6765
loop {
6866
let config_file = current.join("rustfmt.toml");
6967
match fs::metadata(&config_file) {
70-
Ok(md) => {
71-
// Properly handle unlikely situation of a directory named `rustfmt.toml`.
72-
if md.is_file() {
73-
return Ok(Some(config_file));
74-
}
75-
}
76-
// If it's not found, we continue searching; otherwise something went wrong and we
77-
// return the error.
68+
// Only return if it's a file to handle the unlikely situation of a directory named
69+
// `rustfmt.toml`.
70+
Ok(ref md) if md.is_file() => return Ok(Some(config_file)),
71+
// Return the error if it's something other than `NotFound`; otherwise we didn't find
72+
// the project file yet, and continue searching.
7873
Err(e) => {
7974
if e.kind() != ErrorKind::NotFound {
80-
return Err(e);
75+
return Err(FmtError::from(e));
8176
}
8277
}
78+
_ => {}
8379
}
8480

8581
// If the current directory has no parent, we're done searching.
@@ -93,7 +89,7 @@ fn lookup_project_file(dir: &Path) -> io::Result<Option<PathBuf>> {
9389
///
9490
/// Returns the `Config` to use, and the path of the project file if there was
9591
/// one.
96-
fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
92+
fn resolve_config(dir: &Path) -> FmtResult<(Config, Option<PathBuf>)> {
9793
let path = try!(lookup_project_file(dir));
9894
if path.is_none() {
9995
return Ok((Config::default(), None));
@@ -108,7 +104,7 @@ fn resolve_config(dir: &Path) -> io::Result<(Config, Option<PathBuf>)> {
108104
/// read the given config file path recursively if present else read the project file path
109105
fn match_cli_path_or_file(config_path: Option<PathBuf>,
110106
input_file: &Path)
111-
-> io::Result<(Config, Option<PathBuf>)> {
107+
-> FmtResult<(Config, Option<PathBuf>)> {
112108

113109
if let Some(config_file) = config_path {
114110
let (toml, path) = try!(resolve_config(config_file.as_ref()));
@@ -119,7 +115,7 @@ fn match_cli_path_or_file(config_path: Option<PathBuf>,
119115
resolve_config(input_file)
120116
}
121117

122-
fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
118+
fn update_config(config: &mut Config, matches: &Matches) -> FmtResult<()> {
123119
config.verbose = matches.opt_present("verbose");
124120
config.skip_children = matches.opt_present("skip-children");
125121

@@ -130,11 +126,14 @@ fn update_config(config: &mut Config, matches: &Matches) -> Result<(), String> {
130126
config.write_mode = write_mode;
131127
Ok(())
132128
}
133-
Some(Err(_)) => Err(format!("Invalid write-mode: {}", write_mode.expect("cannot happen"))),
129+
Some(Err(_)) => {
130+
Err(FmtError::from(format!("Invalid write-mode: {}",
131+
write_mode.expect("cannot happen"))))
132+
}
134133
}
135134
}
136135

137-
fn execute() -> i32 {
136+
fn make_opts() -> Options {
138137
let mut opts = Options::new();
139138
opts.optflag("h", "help", "show this message");
140139
opts.optflag("V", "version", "show version information");
@@ -154,32 +153,21 @@ fn execute() -> i32 {
154153
found reverts to the input file path",
155154
"[Path for the configuration file]");
156155

157-
let matches = match opts.parse(env::args().skip(1)) {
158-
Ok(m) => m,
159-
Err(e) => {
160-
print_usage(&opts, &e.to_string());
161-
return 1;
162-
}
163-
};
156+
opts
157+
}
164158

165-
let operation = determine_operation(&matches);
159+
fn execute(opts: &Options) -> FmtResult<()> {
160+
let matches = try!(opts.parse(env::args().skip(1)));
166161

167-
match operation {
168-
Operation::InvalidInput { reason } => {
169-
print_usage(&opts, &reason);
170-
1
171-
}
162+
match try!(determine_operation(&matches)) {
172163
Operation::Help => {
173164
print_usage(&opts, "");
174-
0
175165
}
176166
Operation::Version => {
177167
print_version();
178-
0
179168
}
180169
Operation::ConfigHelp => {
181170
Config::print_docs();
182-
0
183171
}
184172
Operation::Stdin { input, config_path } => {
185173
// try to read config from local directory
@@ -190,7 +178,6 @@ fn execute() -> i32 {
190178
config.write_mode = WriteMode::Plain;
191179

192180
run(Input::Text(input), &config);
193-
0
194181
}
195182
Operation::Format { files, config_path } => {
196183
let mut config = Config::default();
@@ -221,21 +208,26 @@ fn execute() -> i32 {
221208
config = config_tmp;
222209
}
223210

224-
if let Err(e) = update_config(&mut config, &matches) {
225-
print_usage(&opts, &e);
226-
return 1;
227-
}
211+
try!(update_config(&mut config, &matches));
228212
run(Input::File(file), &config);
229213
}
230-
0
231214
}
232215
}
216+
Ok(())
233217
}
234218

235219
fn main() {
236220
let _ = env_logger::init();
237-
let exit_code = execute();
238221

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

@@ -261,17 +253,17 @@ fn print_version() {
261253
option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));
262254
}
263255

264-
fn determine_operation(matches: &Matches) -> Operation {
256+
fn determine_operation(matches: &Matches) -> FmtResult<Operation> {
265257
if matches.opt_present("h") {
266-
return Operation::Help;
258+
return Ok(Operation::Help);
267259
}
268260

269261
if matches.opt_present("config-help") {
270-
return Operation::ConfigHelp;
262+
return Ok(Operation::ConfigHelp);
271263
}
272264

273265
if matches.opt_present("version") {
274-
return Operation::Version;
266+
return Ok(Operation::Version);
275267
}
276268

277269
// Read the config_path and convert to parent dir if a file is provided.
@@ -288,21 +280,18 @@ fn determine_operation(matches: &Matches) -> Operation {
288280
if matches.free.is_empty() {
289281

290282
let mut buffer = String::new();
291-
match io::stdin().read_to_string(&mut buffer) {
292-
Ok(..) => (),
293-
Err(e) => return Operation::InvalidInput { reason: e.to_string() },
294-
}
283+
try!(io::stdin().read_to_string(&mut buffer));
295284

296-
return Operation::Stdin {
285+
return Ok(Operation::Stdin {
297286
input: buffer,
298287
config_path: config_path,
299-
};
288+
});
300289
}
301290

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

304-
Operation::Format {
293+
Ok(Operation::Format {
305294
files: files,
306295
config_path: config_path,
307-
}
296+
})
308297
}

0 commit comments

Comments
 (0)