Skip to content

Commit 2f20021

Browse files
committed
fix(CLI): unified error handling
* Use `Result` everywhere, instead of Option or tuples * Properly handle error occurring after the dry-run. We do it in an extensible way, in case we need to do more than handle invalid output files at some point. Output files that could not be opened will now result in a nice error message with all the information we have. Fixes #66
1 parent 894b5b5 commit 2f20021

3 files changed

Lines changed: 47 additions & 28 deletions

File tree

src/mako/cli/lib/engine.mako

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ use oauth2::{Authenticator, DefaultAuthenticatorDelegate};
3636
use serde::json;
3737
use clap::ArgMatches;
3838
39+
enum DoitError {
40+
IoError(String, io::Error),
41+
ApiError(api::Error),
42+
}
43+
3944
struct Engine<'n, 'a> {
4045
opt: ArgMatches<'n, 'a>,
4146
hub: ${hub_type_name}<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
@@ -46,15 +51,15 @@ impl<'n, 'a> Engine<'n, 'a> {
4651
% for resource in sorted(c.rta_map.keys()):
4752
% for method in sorted(c.rta_map[resource]):
4853
fn ${call_method_ident(resource, method)}(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError)
49-
-> Option<api::Error> {
54+
-> Result<(), DoitError> {
5055
${self._method_call_impl(c, resource, method) | indent_all_but_first_by(2)}
5156
}
5257
5358
% endfor # each method
5459
% endfor
55-
fn _doit(&self, dry_run: bool) -> (Option<api::Error>, Option<InvalidOptionsError>) {
60+
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
5661
let mut err = InvalidOptionsError::new();
57-
let mut call_result: Option<api::Error> = None;
62+
let mut call_result: Result<(), DoitError> = Ok(());
5863
let mut err_opt: Option<InvalidOptionsError> = None;
5964
## RESOURCE LOOP: check for set primary subcommand
6065
match ${SOPT + '.subcommand()'} {
@@ -83,8 +88,10 @@ impl<'n, 'a> Engine<'n, 'a> {
8388
if err.issues.len() > 0 {
8489
err_opt = Some(err);
8590
}
91+
Err(err_opt)
92+
} else {
93+
Ok(call_result)
8694
}
87-
(call_result, err_opt)
8895
}
8996
9097
// Please note that this call will fail if any part of the opt can't be handled
@@ -117,15 +124,17 @@ impl<'n, 'a> Engine<'n, 'a> {
117124
};
118125
119126
match engine._doit(true) {
120-
(_, Some(err)) => Err(err),
121-
_ => Ok(engine),
127+
Err(Some(err)) => Err(err),
128+
Err(None) => Ok(engine),
129+
Ok(_) => unreachable!(),
122130
}
123131
}
124132
125-
// Execute the call with all the bells and whistles, informing the caller only if there was an error.
126-
// The absense of one indicates success.
127-
fn doit(&self) -> Option<api::Error> {
128-
self._doit(false).0
133+
fn doit(&self) -> Result<(), DoitError> {
134+
match self._doit(false) {
135+
Ok(res) => res,
136+
Err(_) => unreachable!(),
137+
}
129138
}
130139
}
131140
</%def>
@@ -261,7 +270,7 @@ let mime_type = input_mime_from_opts(${opt_value(MIME_ARG, default=DEFAULT_MIME)
261270
let protocol = CallType::Standard;
262271
% endif # support upload
263272
if dry_run {
264-
None
273+
Ok(())
265274
} else {
266275
assert!(err.issues.len() == 0);
267276
% if method_default_scope(mc.m):
@@ -270,9 +279,11 @@ if dry_run {
270279
}
271280
% endif
272281
## Make the call, handle uploads, handle downloads (also media downloads|json decoding)
273-
## TODO: unify error handling
274282
% if handle_output:
275-
let mut ostream = writer_from_opts(opt.value_of("${(OUT_ARG)}"));
283+
let mut ostream = match writer_from_opts(opt.value_of("${(OUT_ARG)}")) {
284+
Ok(mut f) => f,
285+
Err(io_err) => return Err(DoitError::IoError(${opt_value(OUT_ARG, default='-')}.to_string(), io_err)),
286+
};
276287
% endif # handle output
277288
match match protocol {
278289
% if mc.media_params:
@@ -285,7 +296,7 @@ if dry_run {
285296
_ => unreachable!()
286297
% endif
287298
} {
288-
Err(api_err) => Some(api_err),
299+
Err(api_err) => Err(DoitError::ApiError(api_err)),
289300
% if mc.response_schema:
290301
Ok((mut response, output_schema)) => {
291302
% else:
@@ -310,7 +321,7 @@ if dry_run {
310321
% if track_download_flag:
311322
}
312323
% endif
313-
None
324+
Ok(())
314325
}
315326
}
316327
}\

src/mako/cli/main.rs.mako

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<%
55
from util import (new_context, rust_comment, to_extern_crate_name, library_to_crate_name, library_name,
66
indent_all_but_first_by)
7-
from cli import DEBUG_FLAG
7+
from cli import OUT_ARG, DEBUG_FLAG, opt_value
88
99
c = new_context(schemas, resources, context.get('methods'))
1010
default_user_agent = "google-cli-rust-client/" + cargo.build_version
@@ -38,17 +38,24 @@ fn main() {
3838
let debug = matches.is_present("${DEBUG_FLAG}");
3939
match Engine::new(matches) {
4040
Err(err) => {
41-
writeln!(io::stderr(), "{}", err).ok();
4241
env::set_exit_status(err.exit_code);
42+
writeln!(io::stderr(), "{}", err).ok();
4343
},
4444
Ok(engine) => {
45-
if let Some(err) = engine.doit() {
46-
if debug {
47-
writeln!(io::stderr(), "{:?}", err).ok();
48-
} else {
49-
writeln!(io::stderr(), "{}", err).ok();
50-
}
45+
if let Err(doit_err) = engine.doit() {
5146
env::set_exit_status(1);
47+
match doit_err {
48+
DoitError::IoError(path, err) => {
49+
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
50+
},
51+
DoitError::ApiError(err) => {
52+
if debug {
53+
writeln!(io::stderr(), "{:?}", err).ok();
54+
} else {
55+
writeln!(io::stderr(), "{}", err).ok();
56+
}
57+
}
58+
}
5259
}
5360
}
5461
}

src/rust/cli/cmn.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -169,13 +169,14 @@ pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option
169169
}
170170
}
171171

172-
// May panic if we can't open the file - this is anticipated, we can't currently communicate this
173-
// kind of error: TODO: fix this architecture :)
174-
pub fn writer_from_opts(arg: Option<&str>) -> Box<Write> {
172+
pub fn writer_from_opts(arg: Option<&str>) -> Result<Box<Write>, io::Error> {
175173
let f = arg.unwrap_or("-");
176174
match f {
177-
"-" => Box::new(stdout()),
178-
_ => Box::new(fs::OpenOptions::new().create(true).write(true).open(f).unwrap())
175+
"-" => Ok(Box::new(stdout())),
176+
_ => match fs::OpenOptions::new().create(true).write(true).open(f) {
177+
Ok(f) => Ok(Box::new(f)),
178+
Err(io_err) => Err(io_err),
179+
}
179180
}
180181
}
181182

0 commit comments

Comments
 (0)