Skip to content

Commit bac4e1a

Browse files
committed
fix(clap): adjust option usage to changed API
Discovery API now builds and seems to work even ! More testing will have to be done though to be sure. Related #81
1 parent feaa3a0 commit bac4e1a

4 files changed

Lines changed: 69 additions & 76 deletions

File tree

src/mako/cli/lib/cli.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -91,16 +91,12 @@ def mangle_subcommand(name):
9191
def ident(name):
9292
return mangle_subcommand(name).replace('-', '_')
9393

94-
# return the identifier of a command for the given name, suitable to address the command field in the docopt structure
95-
def cmd_ident(name):
96-
return 'cmd_' + ident(name)
97-
9894
# Similar to cmd_ident, but for arguments
9995
def arg_ident(name):
100-
return 'arg_' + ident(name)
96+
return opt_value(name)
10197

102-
def flag_ident(name):
103-
return 'flag_' + ident(name)
98+
def opt_value(name, opt='opt'):
99+
return opt + '.value_of("' + mangle_subcommand(name) + '").unwrap_or("")'
104100

105101
def application_secret_path(program_name):
106102
return program_name + '-secret.json'

src/mako/cli/lib/engine.mako

Lines changed: 38 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,19 @@
55
ADD_SCOPE_FN, TREF)
66
from cli import (mangle_subcommand, new_method_context, PARAM_FLAG, STRUCT_FLAG, UPLOAD_FLAG, OUTPUT_FLAG, VALUE_ARG,
77
CONFIG_DIR, SCOPE_FLAG, is_request_value_property, FIELD_SEP, docopt_mode, FILE_ARG, MIME_ARG, OUT_ARG,
8-
cmd_ident, call_method_ident, arg_ident, POD_TYPES, flag_ident, ident, JSON_TYPE_VALUE_MAP,
8+
call_method_ident, arg_ident, POD_TYPES, opt_value, ident, JSON_TYPE_VALUE_MAP,
99
KEY_VALUE_ARG, to_cli_schema, SchemaEntry, CTYPE_POD, actual_json_type, CTYPE_MAP, CTYPE_ARRAY,
10-
application_secret_path, DEBUG_FLAG, DEBUG_AUTH_FLAG)
10+
application_secret_path, DEBUG_FLAG, DEBUG_AUTH_FLAG, CONFIG_DIR_FLAG)
1111
1212
v_arg = '<%s>' % VALUE_ARG
13-
SOPT = 'self.opt.'
13+
SOPT = 'self.opt'
1414
def to_opt_arg_ident(p):
15-
return SOPT + arg_ident(p.name)
15+
return opt_value(p.name)
1616
1717
def borrow_prefix(p):
1818
ptype = p.get('type', None)
1919
borrow = ''
20-
if (ptype not in POD_TYPES or ptype in ('string', None) or p.get('repeated', False)) and ptype is not None:
20+
if (ptype not in POD_TYPES or ptype is None or p.get('repeated', False)) and ptype is not None:
2121
borrow = '&'
2222
return borrow
2323
@@ -35,17 +35,18 @@ use std::str::FromStr;
3535
3636
use oauth2::{Authenticator, DefaultAuthenticatorDelegate};
3737
use rustc_serialize::json;
38+
use clap::ArgMatches;
3839
39-
struct Engine {
40-
opt: Options,
40+
struct Engine<'n, 'a> {
41+
opt: ArgMatches<'n, 'a>,
4142
hub: ${hub_type_name}<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
4243
}
4344
4445
45-
impl Engine {
46+
impl<'n, 'a> Engine<'n, 'a> {
4647
% for resource in sorted(c.rta_map.keys()):
4748
% for method in sorted(c.rta_map[resource]):
48-
fn ${call_method_ident(resource, method)}(&self, dry_run: bool, err: &mut InvalidOptionsError)
49+
fn ${call_method_ident(resource, method)}(&self, opt: &ArgMatches<'n, 'a>, dry_run: bool, err: &mut InvalidOptionsError)
4950
-> Option<api::Error> {
5051
${self._method_call_impl(c, resource, method) | indent_all_but_first_by(2)}
5152
}
@@ -54,35 +55,27 @@ impl Engine {
5455
% endfor
5556
fn _doit(&self, dry_run: bool) -> (Option<api::Error>, Option<InvalidOptionsError>) {
5657
let mut err = InvalidOptionsError::new();
57-
let mut call_result: Option<api::Error>;
58+
let mut call_result: Option<api::Error> = None;
5859
let mut err_opt: Option<InvalidOptionsError> = None;
5960
## RESOURCE LOOP: check for set primary subcommand
61+
match ${SOPT + '.subcommand()'} {
6062
% for resource in sorted(c.rta_map.keys()):
61-
62-
% if loop.first:
63-
if \
64-
% else:
65-
else if \
66-
% endif
67-
self.opt.${cmd_ident(resource)} {
68-
## METHOD LOOP: Check for method subcommand
69-
% for method in sorted(c.rta_map[resource]):
70-
% if loop.first:
71-
if \
72-
% else:
73-
else if \
74-
% endif
75-
self.opt.${cmd_ident(method)} {
76-
call_result = self.${call_method_ident(resource, method)}(dry_run, &mut err);
77-
}\
78-
% endfor # each method
79-
else {
80-
unreachable!();
81-
}
82-
}\
63+
("${mangle_subcommand(resource)}", Some(opt)) => {
64+
match opt.subcommand() {
65+
% for method in sorted(c.rta_map[resource]):
66+
("${mangle_subcommand(method)}", Some(opt)) => {
67+
call_result = self.${call_method_ident(resource, method)}(opt, dry_run, &mut err);
68+
},
69+
% endfor # each method
70+
_ => {
71+
err.issues.push(CLIError::MissingMethodError("${mangle_subcommand(resource)}".to_string()));
72+
}
73+
}
74+
},
8375
% endfor # each resource
84-
else {
85-
unreachable!();
76+
_ => {
77+
err.issues.push(CLIError::MissingCommandError);
78+
}
8679
}
8780
8881
if dry_run {
@@ -94,9 +87,9 @@ self.opt.${cmd_ident(method)} {
9487
}
9588
9689
// Please note that this call will fail if any part of the opt can't be handled
97-
fn new(opt: Options) -> Result<Engine, InvalidOptionsError> {
90+
fn new(opt: ArgMatches<'a, 'n>) -> Result<Engine<'a, 'n>, InvalidOptionsError> {
9891
let (config_dir, secret) = {
99-
let config_dir = match cmn::assure_config_dir_exists(&opt.flag_config_dir) {
92+
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("${CONFIG_DIR_FLAG}").unwrap_or("${CONFIG_DIR}")) {
10093
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
10194
Ok(p) => p,
10295
};
@@ -137,7 +130,7 @@ self.opt.${cmd_ident(method)} {
137130
</%def>
138131

139132
<%def name="_debug_client(flag_name)" buffered="True">\
140-
if opt.flag_${mangle_ident(flag_name)} {
133+
if opt.is_present("${flag_name}") {
141134
hyper::Client::with_connector(mock::TeeConnector {
142135
connector: hyper::net::HttpConnector(None)
143136
})
@@ -179,7 +172,7 @@ ${self._request_value_impl(c, request_cli_schema, prop_name, request_prop_type)}
179172
% elif p.type != 'string':
180173
% if p.get('repeated', False):
181174
let ${prop_name}: Vec<${prop_type} = Vec::new();
182-
for (arg_id, arg) in ${opt_ident}.iter().enumerate() {
175+
for (arg_id, arg) in opt.values_of().unwrap_or(Vec::new()).iter().enumerate() {
183176
${prop_name}.push(arg_from_str(&arg, err, "<${mangle_subcommand(p.name)}>", arg_id), "${p.type}"));
184177
}
185178
% else:
@@ -204,7 +197,7 @@ let mut download_mode = false;
204197
% endif
205198
let mut call = self.hub.${mangle_ident(resource)}().${mangle_ident(method)}(${', '.join(call_args)});
206199
% if handle_props:
207-
for parg in ${SOPT + arg_ident(VALUE_ARG)}.iter() {
200+
for parg in opt.values_of("${ident(VALUE_ARG)}").unwrap_or(Vec::new()).iter() {
208201
let (key, value) = parse_kv_arg(&*parg, err, false);
209202
match key {
210203
% for p in optional_props:
@@ -267,14 +260,14 @@ let protocol =
267260
% else:
268261
} else if \
269262
% endif
270-
${SOPT + cmd_ident(p.protocol)} {
263+
${opt_value(p.protocol)} {
271264
"${p.protocol}"
272265
% endfor # each media param
273266
} else {
274267
unreachable!()
275268
};
276-
let mut input_file = input_file_from_opts(&${SOPT + arg_ident(FILE_ARG[1:-1])}, err);
277-
let mime_type = input_mime_from_opts(&${SOPT + arg_ident(MIME_ARG[1:-1])}, err);
269+
let mut input_file = input_file_from_opts(&${opt_value(FILE_ARG)}, err);
270+
let mime_type = input_mime_from_opts(&${opt_value(MIME_ARG)}, err);
278271
% else:
279272
let protocol = "${STANDARD}";
280273
% endif # support upload
@@ -283,15 +276,15 @@ if dry_run {
283276
} else {
284277
assert!(err.issues.len() == 0);
285278
% if method_default_scope(mc.m):
286-
<% scope_opt = SOPT + flag_ident('scope') %>\
279+
<% scope_opt = opt_value('scope', SOPT) %>\
287280
if ${scope_opt}.len() > 0 {
288281
call = call.${ADD_SCOPE_FN}(&${scope_opt});
289282
}
290283
% endif
291284
## Make the call, handle uploads, handle downloads (also media downloads|json decoding)
292285
## TODO: unify error handling
293286
% if handle_output:
294-
let mut ostream = writer_from_opts(${SOPT + flag_ident(OUTPUT_FLAG)}, &${SOPT + arg_ident(OUT_ARG[1:-1])});
287+
let mut ostream = writer_from_opts(opt.value_of("${(OUT_ARG)}"));
295288
% endif # handle output
296289
match match protocol {
297290
% if mc.media_params:
@@ -383,7 +376,7 @@ if dry_run {
383376
%>\
384377
let mut ${request_prop_name} = api::${request_prop_type}::default();
385378
let mut field_cursor = FieldCursor::default();
386-
for kvarg in ${SOPT + arg_ident(KEY_VALUE_ARG)}.iter() {
379+
for kvarg in ${opt_value(KEY_VALUE_ARG)}.iter() {
387380
let last_errc = err.issues.len();
388381
let (key, value) = parse_kv_arg(&*kvarg, err, false);
389382
let mut temp_cursor = field_cursor.clone();

src/mako/cli/main.rs.mako

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +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
78
89
c = new_context(schemas, resources, context.get('methods'))
910
default_user_agent = "google-cli-rust-client/" + cargo.build_version
@@ -29,27 +30,26 @@ use clap::{App, SubCommand, Arg};
2930

3031
mod cmn;
3132

32-
## ${engine.new(c)}\
33+
${engine.new(c)}\
3334

3435
fn main() {
3536
${argparse.new(c) | indent_all_but_first_by(1)}\
3637

37-
## let opts: Options = Options::docopt().decode().unwrap_or_else(|e| e.exit());
38-
## let debug = opts.flag_debug;
39-
## match Engine::new(opts) {
40-
## Err(err) => {
41-
## writeln!(io::stderr(), "{}", err).ok();
42-
## env::set_exit_status(err.exit_code);
43-
## },
44-
## 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-
## }
51-
## env::set_exit_status(1);
52-
## }
53-
## }
54-
## }
38+
let debug = matches.is_present("${DEBUG_FLAG}");
39+
match Engine::new(matches) {
40+
Err(err) => {
41+
writeln!(io::stderr(), "{}", err).ok();
42+
env::set_exit_status(err.exit_code);
43+
},
44+
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+
}
51+
env::set_exit_status(1);
52+
}
53+
}
54+
}
5555
}

src/rust/cli/cmn.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,11 @@ pub fn input_mime_from_opts(mime: &str, err: &mut InvalidOptionsError) -> Option
149149

150150
// May panic if we can't open the file - this is anticipated, we can't currently communicate this
151151
// kind of error: TODO: fix this architecture :)
152-
pub fn writer_from_opts(flag: bool, arg: &str) -> Box<Write> {
153-
if !flag || arg == "-" {
154-
Box::new(stdout())
155-
} else {
156-
Box::new(fs::OpenOptions::new().create(true).write(true).open(arg).unwrap())
152+
pub fn writer_from_opts(arg: Option<&str>) -> Box<Write> {
153+
let f = arg.unwrap_or("-");
154+
match f {
155+
"-" => Box::new(stdout()),
156+
_ => Box::new(fs::OpenOptions::new().create(true).write(true).open(f).unwrap())
157157
}
158158
}
159159

@@ -331,6 +331,8 @@ pub enum CLIError {
331331
InvalidKeyValueSyntax(String, bool),
332332
Input(InputError),
333333
Field(FieldError),
334+
MissingCommandError,
335+
MissingMethodError(String),
334336
}
335337

336338
impl fmt::Display for CLIError {
@@ -348,6 +350,8 @@ impl fmt::Display for CLIError {
348350
let hashmap_info = if is_hashmap { "hashmap " } else { "" };
349351
writeln!(f, "'{}' does not match {}pattern <key>=<value>", kv, hashmap_info)
350352
},
353+
CLIError::MissingCommandError => writeln!(f, "Please specify the main sub-command"),
354+
CLIError::MissingMethodError(ref cmd) => writeln!(f, "Please specify the method to call on the {} command", cmd),
351355
}
352356
}
353357
}

0 commit comments

Comments
 (0)