root / kamaki / cli / argument / __init__.py @ b33d9050
History | View | Annotate | Download (24.5 kB)
1 |
# Copyright 2012-2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from kamaki.cli.config import Config |
35 |
from kamaki.cli.errors import ( |
36 |
CLISyntaxError, raiseCLIError, CLIInvalidArgument) |
37 |
from kamaki.cli.utils import split_input, to_bytes |
38 |
|
39 |
from datetime import datetime as dtm |
40 |
from time import mktime |
41 |
from sys import stderr |
42 |
|
43 |
from logging import getLogger |
44 |
from argparse import ( |
45 |
ArgumentParser, ArgumentError, RawDescriptionHelpFormatter) |
46 |
from progress.bar import ShadyBar as KamakiProgressBar |
47 |
|
48 |
log = getLogger(__name__) |
49 |
|
50 |
|
51 |
class NoAbbrArgumentParser(ArgumentParser): |
52 |
"""This is Argument Parser with disabled argument abbreviation"""
|
53 |
|
54 |
def _get_option_tuples(self, option_string): |
55 |
result = [] |
56 |
chars = self.prefix_chars
|
57 |
if option_string[0] in chars and option_string[1] in chars: |
58 |
if '=' in option_string: |
59 |
option_prefix, explicit_arg = option_string.split('=', 1) |
60 |
else:
|
61 |
option_prefix = option_string |
62 |
explicit_arg = None
|
63 |
for option_string in self._option_string_actions: |
64 |
if option_string == option_prefix:
|
65 |
action = self._option_string_actions[option_string]
|
66 |
tup = action, option_string, explicit_arg |
67 |
result.append(tup) |
68 |
elif option_string[0] in chars and option_string[1] not in chars: |
69 |
option_prefix = option_string |
70 |
explicit_arg = None
|
71 |
short_option_prefix = option_string[:2]
|
72 |
short_explicit_arg = option_string[2:]
|
73 |
|
74 |
for option_string in self._option_string_actions: |
75 |
if option_string == short_option_prefix:
|
76 |
action = self._option_string_actions[option_string]
|
77 |
tup = action, option_string, short_explicit_arg |
78 |
result.append(tup) |
79 |
elif option_string == option_prefix:
|
80 |
action = self._option_string_actions[option_string]
|
81 |
tup = action, option_string, explicit_arg |
82 |
result.append(tup) |
83 |
else:
|
84 |
return super( |
85 |
NoAbbrArgumentParser, self)._get_option_tuples(option_string)
|
86 |
return result
|
87 |
|
88 |
|
89 |
class Argument(object): |
90 |
"""An argument that can be parsed from command line or otherwise.
|
91 |
This is the top-level Argument class. It is suggested to extent this
|
92 |
class into more specific argument types.
|
93 |
"""
|
94 |
lvalue_delimiter = '/'
|
95 |
|
96 |
def __init__(self, arity, help=None, parsed_name=None, default=None): |
97 |
self.arity = int(arity) |
98 |
self.help = '%s' % help or '' |
99 |
|
100 |
assert parsed_name, 'No parsed name for argument %s' % self |
101 |
self.parsed_name = list(parsed_name) if isinstance( |
102 |
parsed_name, list) or isinstance(parsed_name, tuple) else ( |
103 |
'%s' % parsed_name).split()
|
104 |
for name in self.parsed_name: |
105 |
assert name.count(' ') == 0, '%s: Invalid parse name "%s"' % ( |
106 |
self, name)
|
107 |
msg = '%s: Invalid parse name "%s" should start with a "-"' % (
|
108 |
self, name)
|
109 |
assert name.startswith('-'), msg |
110 |
|
111 |
self.default = default or None |
112 |
|
113 |
@property
|
114 |
def value(self): |
115 |
return getattr(self, '_value', self.default) |
116 |
|
117 |
@value.setter
|
118 |
def value(self, newvalue): |
119 |
self._value = newvalue
|
120 |
|
121 |
def update_parser(self, parser, name): |
122 |
"""Update argument parser with self info"""
|
123 |
action = 'append' if self.arity < 0 else ( |
124 |
'store' if self.arity else 'store_true') |
125 |
parser.add_argument( |
126 |
*self.parsed_name,
|
127 |
dest=name, action=action, default=self.default, help=self.help) |
128 |
|
129 |
@property
|
130 |
def lvalue(self): |
131 |
"""A printable form of the left value when calling an argument e.g.,
|
132 |
--left-value=right-value"""
|
133 |
return (self.lvalue_delimiter or ' ').join(self.parsed_name or []) |
134 |
|
135 |
|
136 |
class ConfigArgument(Argument): |
137 |
"""Manage a kamaki configuration (file)"""
|
138 |
|
139 |
def __init__(self, help, parsed_name=('-c', '--config')): |
140 |
super(ConfigArgument, self).__init__(1, help, parsed_name, None) |
141 |
self.file_path = None |
142 |
|
143 |
@property
|
144 |
def value(self): |
145 |
return getattr(self, '_value', None) |
146 |
|
147 |
@value.setter
|
148 |
def value(self, config_file): |
149 |
if config_file:
|
150 |
self._value = Config(config_file)
|
151 |
self.file_path = config_file
|
152 |
elif self.file_path: |
153 |
self._value = Config(self.file_path) |
154 |
else:
|
155 |
self._value = Config()
|
156 |
|
157 |
def get(self, group, term): |
158 |
"""Get a configuration setting from the Config object"""
|
159 |
return self.value.get(group, term) |
160 |
|
161 |
@property
|
162 |
def groups(self): |
163 |
suffix = '_cli'
|
164 |
slen = len(suffix)
|
165 |
return [term[:-slen] for term in self.value.keys('global') if ( |
166 |
term.endswith(suffix))] |
167 |
|
168 |
@property
|
169 |
def cli_specs(self): |
170 |
suffix = '_cli'
|
171 |
slen = len(suffix)
|
172 |
return [(k[:-slen], v) for k, v in self.value.items('global') if ( |
173 |
k.endswith(suffix))] |
174 |
|
175 |
def get_global(self, option): |
176 |
return self.value.get('global', option) |
177 |
|
178 |
def get_cloud(self, cloud, option): |
179 |
return self.value.get_cloud(cloud, option) |
180 |
|
181 |
|
182 |
_config_arg = ConfigArgument('Path to config file')
|
183 |
|
184 |
|
185 |
class RuntimeConfigArgument(Argument): |
186 |
"""Set a run-time setting option (not persistent)"""
|
187 |
|
188 |
def __init__(self, config_arg, help='', parsed_name=None, default=None): |
189 |
super(self.__class__, self).__init__(1, help, parsed_name, default) |
190 |
self._config_arg = config_arg
|
191 |
|
192 |
@property
|
193 |
def value(self): |
194 |
return super(RuntimeConfigArgument, self).value |
195 |
|
196 |
@value.setter
|
197 |
def value(self, options): |
198 |
if options == self.default: |
199 |
return
|
200 |
if not isinstance(options, list): |
201 |
options = ['%s' % options]
|
202 |
for option in options: |
203 |
keypath, sep, val = option.partition('=')
|
204 |
if not sep: |
205 |
raiseCLIError( |
206 |
CLISyntaxError('Argument Syntax Error '),
|
207 |
details=[ |
208 |
'%s is missing a "="',
|
209 |
' (usage: -o section.key=val)' % option])
|
210 |
section, sep, key = keypath.partition('.')
|
211 |
if not sep: |
212 |
key = section |
213 |
section = 'global'
|
214 |
self._config_arg.value.override(
|
215 |
section.strip(), |
216 |
key.strip(), |
217 |
val.strip()) |
218 |
|
219 |
|
220 |
class FlagArgument(Argument): |
221 |
"""
|
222 |
:value: true if set, false otherwise
|
223 |
"""
|
224 |
|
225 |
def __init__(self, help='', parsed_name=None, default=None): |
226 |
super(FlagArgument, self).__init__(0, help, parsed_name, default) |
227 |
|
228 |
|
229 |
class ValueArgument(Argument): |
230 |
"""
|
231 |
:value type: string
|
232 |
:value returns: given value or default
|
233 |
"""
|
234 |
|
235 |
def __init__(self, help='', parsed_name=None, default=None): |
236 |
super(ValueArgument, self).__init__(1, help, parsed_name, default) |
237 |
|
238 |
|
239 |
class CommaSeparatedListArgument(ValueArgument): |
240 |
"""
|
241 |
:value type: string
|
242 |
:value returns: list of the comma separated values
|
243 |
"""
|
244 |
|
245 |
@property
|
246 |
def value(self): |
247 |
return self._value or list() |
248 |
|
249 |
@value.setter
|
250 |
def value(self, newvalue): |
251 |
self._value = newvalue.split(',') if newvalue else list() |
252 |
|
253 |
|
254 |
class IntArgument(ValueArgument): |
255 |
|
256 |
@property
|
257 |
def value(self): |
258 |
"""integer (type checking)"""
|
259 |
return getattr(self, '_value', self.default) |
260 |
|
261 |
@value.setter
|
262 |
def value(self, newvalue): |
263 |
if newvalue == self.default: |
264 |
self._value = newvalue
|
265 |
return
|
266 |
try:
|
267 |
if int(newvalue) == float(newvalue): |
268 |
self._value = int(newvalue) |
269 |
else:
|
270 |
raise ValueError('Raise int argument error') |
271 |
except ValueError: |
272 |
raiseCLIError(CLISyntaxError( |
273 |
'IntArgument Error',
|
274 |
details=['Value %s not an int' % newvalue]))
|
275 |
|
276 |
|
277 |
class DataSizeArgument(ValueArgument): |
278 |
"""Input: a string of the form <number><unit>
|
279 |
Output: the number of bytes
|
280 |
Units: B, KiB, KB, MiB, MB, GiB, GB, TiB, TB
|
281 |
"""
|
282 |
|
283 |
@property
|
284 |
def value(self): |
285 |
return getattr(self, '_value', self.default) |
286 |
|
287 |
def _calculate_limit(self, user_input): |
288 |
limit = 0
|
289 |
try:
|
290 |
limit = int(user_input)
|
291 |
except ValueError: |
292 |
index = 0
|
293 |
digits = [str(num) for num in range(0, 10)] + ['.'] |
294 |
while user_input[index] in digits: |
295 |
index += 1
|
296 |
limit = user_input[:index] |
297 |
format = user_input[index:] |
298 |
try:
|
299 |
return to_bytes(limit, format)
|
300 |
except Exception as qe: |
301 |
msg = 'Failed to convert %s to bytes' % user_input,
|
302 |
raiseCLIError(qe, msg, details=[ |
303 |
'Syntax: containerlimit set <limit>[format] [container]',
|
304 |
'e.g.,: containerlimit set 2.3GB mycontainer',
|
305 |
'Valid formats:',
|
306 |
'(*1024): B, KiB, MiB, GiB, TiB',
|
307 |
'(*1000): B, KB, MB, GB, TB'])
|
308 |
return limit
|
309 |
|
310 |
@value.setter
|
311 |
def value(self, new_value): |
312 |
if new_value:
|
313 |
self._value = self._calculate_limit(new_value) |
314 |
|
315 |
|
316 |
class DateArgument(ValueArgument): |
317 |
|
318 |
DATE_FORMAT = '%a %b %d %H:%M:%S %Y'
|
319 |
|
320 |
INPUT_FORMATS = [DATE_FORMAT, '%d-%m-%Y', '%H:%M:%S %d-%m-%Y'] |
321 |
|
322 |
@property
|
323 |
def timestamp(self): |
324 |
v = getattr(self, '_value', self.default) |
325 |
return mktime(v.timetuple()) if v else None |
326 |
|
327 |
@property
|
328 |
def formated(self): |
329 |
v = getattr(self, '_value', self.default) |
330 |
return v.strftime(self.DATE_FORMAT) if v else None |
331 |
|
332 |
@property
|
333 |
def value(self): |
334 |
return self.timestamp |
335 |
|
336 |
@value.setter
|
337 |
def value(self, newvalue): |
338 |
self._value = self.format_date(newvalue) if newvalue else self.default |
339 |
|
340 |
def format_date(self, datestr): |
341 |
for format in self.INPUT_FORMATS: |
342 |
try:
|
343 |
t = dtm.strptime(datestr, format) |
344 |
except ValueError: |
345 |
continue
|
346 |
return t # .strftime(self.DATE_FORMAT) |
347 |
raiseCLIError(None, 'Date Argument Error', details=[ |
348 |
'%s not a valid date' % datestr,
|
349 |
'Correct formats:\n\t%s' % self.INPUT_FORMATS]) |
350 |
|
351 |
|
352 |
class VersionArgument(FlagArgument): |
353 |
"""A flag argument with that prints current version"""
|
354 |
|
355 |
@property
|
356 |
def value(self): |
357 |
"""bool"""
|
358 |
return super(self.__class__, self).value |
359 |
|
360 |
@value.setter
|
361 |
def value(self, newvalue): |
362 |
self._value = newvalue
|
363 |
if newvalue:
|
364 |
import kamaki |
365 |
print('kamaki %s' % kamaki.__version__)
|
366 |
|
367 |
|
368 |
class RepeatableArgument(Argument): |
369 |
"""A value argument that can be repeated"""
|
370 |
|
371 |
def __init__(self, help='', parsed_name=None, default=None): |
372 |
super(RepeatableArgument, self).__init__( |
373 |
-1, help, parsed_name, default)
|
374 |
|
375 |
@property
|
376 |
def value(self): |
377 |
return getattr(self, '_value', []) |
378 |
|
379 |
@value.setter
|
380 |
def value(self, newvalue): |
381 |
self._value = newvalue
|
382 |
|
383 |
|
384 |
class KeyValueArgument(Argument): |
385 |
"""A Key=Value Argument that can be repeated
|
386 |
|
387 |
:syntax: --<arg> key1=value1 --<arg> key2=value2 ...
|
388 |
"""
|
389 |
|
390 |
def __init__(self, help='', parsed_name=None, default=None): |
391 |
super(KeyValueArgument, self).__init__(-1, help, parsed_name, default) |
392 |
|
393 |
@property
|
394 |
def value(self): |
395 |
"""
|
396 |
:returns: (dict) {key1: val1, key2: val2, ...}
|
397 |
"""
|
398 |
return getattr(self, '_value', {}) |
399 |
|
400 |
@value.setter
|
401 |
def value(self, keyvalue_pairs): |
402 |
"""
|
403 |
:param keyvalue_pairs: (str) ['key1=val1', 'key2=val2', ...]
|
404 |
"""
|
405 |
if keyvalue_pairs:
|
406 |
self._value = self.value |
407 |
try:
|
408 |
for pair in keyvalue_pairs: |
409 |
key, sep, val = pair.partition('=')
|
410 |
assert sep, ' %s misses a "=" (usage: key1=val1 )\n' % ( |
411 |
pair) |
412 |
self._value[key] = val
|
413 |
except Exception as e: |
414 |
raiseCLIError(e, 'KeyValueArgument Syntax Error')
|
415 |
|
416 |
|
417 |
class StatusArgument(ValueArgument): |
418 |
"""Initialize with valid_states=['list', 'of', 'states']
|
419 |
First state is the default"""
|
420 |
|
421 |
def __init__(self, *args, **kwargs): |
422 |
self.valid_states = kwargs.pop('valid_states', ['BUILD', ]) |
423 |
super(StatusArgument, self).__init__(*args, **kwargs) |
424 |
|
425 |
@property
|
426 |
def value(self): |
427 |
return getattr(self, '_value', None) |
428 |
|
429 |
@value.setter
|
430 |
def value(self, new_status): |
431 |
if new_status:
|
432 |
new_status = new_status.upper() |
433 |
if new_status not in self.valid_states: |
434 |
raise CLIInvalidArgument(
|
435 |
'Invalid argument %s' % new_status, details=[
|
436 |
'Usage: '
|
437 |
'%s=[%s]' % (self.lvalue, '|'.join(self.valid_states))]) |
438 |
self._value = new_status
|
439 |
|
440 |
|
441 |
class ProgressBarArgument(FlagArgument): |
442 |
"""Manage a progress bar"""
|
443 |
|
444 |
def __init__(self, help='', parsed_name='', default=True): |
445 |
self.suffix = '%(percent)d%%' |
446 |
super(ProgressBarArgument, self).__init__(help, parsed_name, default) |
447 |
|
448 |
def clone(self): |
449 |
"""Get a modifiable copy of this bar"""
|
450 |
newarg = ProgressBarArgument( |
451 |
self.help, self.parsed_name, self.default) |
452 |
newarg._value = self._value
|
453 |
return newarg
|
454 |
|
455 |
def get_generator( |
456 |
self, message, message_len=25, countdown=False, timeout=100): |
457 |
"""Get a generator to handle progress of the bar (gen.next())"""
|
458 |
if self.value: |
459 |
return None |
460 |
try:
|
461 |
self.bar = KamakiProgressBar(
|
462 |
message.ljust(message_len), max=timeout or 100) |
463 |
except NameError: |
464 |
self.value = None |
465 |
return self.value |
466 |
if countdown:
|
467 |
bar_phases = list(self.bar.phases) |
468 |
self.bar.empty_fill, bar_phases[0] = bar_phases[-1], '' |
469 |
bar_phases.reverse() |
470 |
self.bar.phases = bar_phases
|
471 |
self.bar.bar_prefix = ' ' |
472 |
self.bar.bar_suffix = ' ' |
473 |
self.bar.suffix = '%(remaining)ds to timeout' |
474 |
else:
|
475 |
self.bar.suffix = '%(percent)d%% - %(eta)ds' |
476 |
self.bar.start()
|
477 |
|
478 |
def progress_gen(n): |
479 |
for i in self.bar.iter(range(int(n))): |
480 |
yield
|
481 |
yield
|
482 |
return progress_gen
|
483 |
|
484 |
def finish(self): |
485 |
"""Stop progress bar, return terminal cursor to user"""
|
486 |
if self.value: |
487 |
return
|
488 |
mybar = getattr(self, 'bar', None) |
489 |
if mybar:
|
490 |
mybar.finish() |
491 |
|
492 |
|
493 |
_arguments = dict(
|
494 |
config=_config_arg, |
495 |
cloud=ValueArgument('Chose a cloud to connect to', ('--cloud')), |
496 |
help=Argument(0, 'Show help message', ('-h', '--help')), |
497 |
debug=FlagArgument('Include debug output', ('-d', '--debug')), |
498 |
#include=FlagArgument(
|
499 |
# 'Include raw connection data in the output', ('-i', '--include')),
|
500 |
silent=FlagArgument('Do not output anything', ('-s', '--silent')), |
501 |
verbose=FlagArgument('More info at response', ('-v', '--verbose')), |
502 |
version=VersionArgument('Print current version', ('-V', '--version')), |
503 |
options=RuntimeConfigArgument( |
504 |
_config_arg, 'Override a config value', ('-o', '--options')) |
505 |
) |
506 |
|
507 |
|
508 |
# Initial command line interface arguments
|
509 |
|
510 |
|
511 |
class ArgumentParseManager(object): |
512 |
"""Manage (initialize and update) an ArgumentParser object"""
|
513 |
|
514 |
def __init__( |
515 |
self, exe,
|
516 |
arguments=None, required=None, syntax=None, description=None, |
517 |
check_required=True):
|
518 |
"""
|
519 |
:param exe: (str) the basic command (e.g. 'kamaki')
|
520 |
|
521 |
:param arguments: (dict) if given, overrides the global _argument as
|
522 |
the parsers arguments specification
|
523 |
:param required: (list or tuple) an iterable of argument keys, denoting
|
524 |
which arguments are required. A tuple denoted an AND relation,
|
525 |
while a list denotes an OR relation e.g., ['a', 'b'] means that
|
526 |
either 'a' or 'b' is required, while ('a', 'b') means that both 'a'
|
527 |
and 'b' ar required.
|
528 |
Nesting is allowed e.g., ['a', ('b', 'c'), ['d', 'e']] means that
|
529 |
this command required either 'a', or both 'b' and 'c', or one of
|
530 |
'd', 'e'.
|
531 |
Repeated arguments are also allowed e.g., [('a', 'b'), ('a', 'c'),
|
532 |
['b', 'c']] means that the command required either 'a' and 'b' or
|
533 |
'a' and 'c' or at least one of 'b', 'c' and could be written as
|
534 |
[('a', ['b', 'c']), ['b', 'c']]
|
535 |
:param syntax: (str) The basic syntax of the arguments. Default:
|
536 |
exe <cmd_group> [<cmd_subbroup> ...] <cmd>
|
537 |
:param description: (str) The description of the commands or ''
|
538 |
:param check_required: (bool) Set to False inorder not to check for
|
539 |
required argument values while parsing
|
540 |
"""
|
541 |
self.parser = NoAbbrArgumentParser(
|
542 |
add_help=False, formatter_class=RawDescriptionHelpFormatter)
|
543 |
self._exe = exe
|
544 |
self.syntax = syntax or ( |
545 |
'%s <cmd_group> [<cmd_subbroup> ...] <cmd>' % exe)
|
546 |
self.required, self.check_required = required, check_required |
547 |
self.parser.description = description or '' |
548 |
if arguments:
|
549 |
self.arguments = arguments
|
550 |
else:
|
551 |
global _arguments
|
552 |
self.arguments = _arguments
|
553 |
self._parser_modified, self._parsed, self._unparsed = False, None, None |
554 |
self.parse()
|
555 |
|
556 |
@staticmethod
|
557 |
def required2list(required): |
558 |
if isinstance(required, list) or isinstance(required, tuple): |
559 |
terms = [] |
560 |
for r in required: |
561 |
terms.append(ArgumentParseManager.required2list(r)) |
562 |
return list(set(terms).union()) |
563 |
return required
|
564 |
|
565 |
@staticmethod
|
566 |
def required2str(required, arguments, tab=''): |
567 |
if isinstance(required, list): |
568 |
return ' %sat least one of the following:\n%s' % (tab, ''.join( |
569 |
[ArgumentParseManager.required2str( |
570 |
r, arguments, tab + ' ') for r in required])) |
571 |
elif isinstance(required, tuple): |
572 |
return ' %sall of the following:\n%s' % (tab, ''.join( |
573 |
[ArgumentParseManager.required2str( |
574 |
r, arguments, tab + ' ') for r in required])) |
575 |
else:
|
576 |
lt_pn, lt_all, arg = 23, 80, arguments[required] |
577 |
tab2 = ' ' * lt_pn
|
578 |
ret = '%s%s' % (tab, ', '.join(arg.parsed_name)) |
579 |
if arg.arity != 0: |
580 |
ret += ' %s' % required.upper()
|
581 |
ret = ('{:<%s}' % lt_pn).format(ret)
|
582 |
prefix = ('\n%s' % tab2) if len(ret) > lt_pn else ' ' |
583 |
cur = 0
|
584 |
while arg.help[cur:]:
|
585 |
next = cur + lt_all - lt_pn |
586 |
ret += prefix |
587 |
ret += ('{:<%s}' % (lt_all - lt_pn)).format(arg.help[cur:next]) |
588 |
cur, finish = next, '\n%s' % tab2 |
589 |
return ret + '\n' |
590 |
|
591 |
@staticmethod
|
592 |
def _patch_with_required_args(arguments, required): |
593 |
if isinstance(required, tuple): |
594 |
return ' '.join([ArgumentParseManager._patch_with_required_args( |
595 |
arguments, k) for k in required]) |
596 |
elif isinstance(required, list): |
597 |
return '< %s >' % ' | '.join([ |
598 |
ArgumentParseManager._patch_with_required_args( |
599 |
arguments, k) for k in required]) |
600 |
arg = arguments[required] |
601 |
return '/'.join(arg.parsed_name) + ( |
602 |
' %s [...]' % required.upper() if arg.arity < 0 else ( |
603 |
' %s' % required.upper() if arg.arity else '')) |
604 |
|
605 |
def print_help(self, out=stderr): |
606 |
if self.required: |
607 |
tmp_args = dict(self.arguments) |
608 |
for term in self.required2list(self.required): |
609 |
tmp_args.pop(term) |
610 |
tmp_parser = ArgumentParseManager(self._exe, tmp_args)
|
611 |
tmp_parser.syntax = self.syntax + self._patch_with_required_args( |
612 |
self.arguments, self.required) |
613 |
tmp_parser.parser.description = '%s\n\nrequired arguments:\n%s' % (
|
614 |
self.parser.description,
|
615 |
self.required2str(self.required, self.arguments)) |
616 |
tmp_parser.update_parser() |
617 |
tmp_parser.parser.print_help() |
618 |
else:
|
619 |
self.parser.print_help()
|
620 |
|
621 |
@property
|
622 |
def syntax(self): |
623 |
"""The command syntax (useful for help messages, descriptions, etc)"""
|
624 |
return self.parser.prog |
625 |
|
626 |
@syntax.setter
|
627 |
def syntax(self, new_syntax): |
628 |
self.parser.prog = new_syntax
|
629 |
|
630 |
@property
|
631 |
def arguments(self): |
632 |
""":returns: (dict) arguments the parser should be aware of"""
|
633 |
return self._arguments |
634 |
|
635 |
@arguments.setter
|
636 |
def arguments(self, new_arguments): |
637 |
assert isinstance(new_arguments, dict), 'Arguments must be in a dict' |
638 |
self._arguments = new_arguments
|
639 |
self.update_parser()
|
640 |
|
641 |
@property
|
642 |
def parsed(self): |
643 |
"""(Namespace) parser-matched terms"""
|
644 |
if self._parser_modified: |
645 |
self.parse()
|
646 |
return self._parsed |
647 |
|
648 |
@property
|
649 |
def unparsed(self): |
650 |
"""(list) parser-unmatched terms"""
|
651 |
if self._parser_modified: |
652 |
self.parse()
|
653 |
return self._unparsed |
654 |
|
655 |
def update_parser(self, arguments=None): |
656 |
"""Load argument specifications to parser
|
657 |
|
658 |
:param arguments: if not given, update self.arguments instead
|
659 |
"""
|
660 |
arguments = arguments or self._arguments |
661 |
|
662 |
for name, arg in arguments.items(): |
663 |
try:
|
664 |
arg.update_parser(self.parser, name)
|
665 |
self._parser_modified = True |
666 |
except ArgumentError:
|
667 |
pass
|
668 |
|
669 |
def update_arguments(self, new_arguments): |
670 |
"""Add to / update existing arguments
|
671 |
|
672 |
:param new_arguments: (dict)
|
673 |
"""
|
674 |
if new_arguments:
|
675 |
assert isinstance(new_arguments, dict), 'Arguments not in dict !!!' |
676 |
self._arguments.update(new_arguments)
|
677 |
self.update_parser()
|
678 |
|
679 |
def _parse_required_arguments(self, required, parsed_args): |
680 |
if not (self.check_required and required): |
681 |
return True |
682 |
if isinstance(required, tuple): |
683 |
for item in required: |
684 |
if not self._parse_required_arguments(item, parsed_args): |
685 |
return False |
686 |
return True |
687 |
elif isinstance(required, list): |
688 |
for item in required: |
689 |
if self._parse_required_arguments(item, parsed_args): |
690 |
return True |
691 |
return False |
692 |
return required in parsed_args |
693 |
|
694 |
def parse(self, new_args=None): |
695 |
"""Parse user input"""
|
696 |
try:
|
697 |
pkargs = (new_args,) if new_args else () |
698 |
self._parsed, unparsed = self.parser.parse_known_args(*pkargs) |
699 |
parsed_args = [ |
700 |
k for k, v in vars(self._parsed).items() if v not in (None, )] |
701 |
if not self._parse_required_arguments(self.required, parsed_args): |
702 |
self.print_help()
|
703 |
raise CLISyntaxError('Missing required arguments') |
704 |
except SystemExit: |
705 |
raiseCLIError(CLISyntaxError('Argument Syntax Error'))
|
706 |
for name, arg in self.arguments.items(): |
707 |
arg.value = getattr(self._parsed, name, arg.default) |
708 |
self._unparsed = []
|
709 |
for term in unparsed: |
710 |
self._unparsed += split_input(' \'%s\' ' % term) |
711 |
self._parser_modified = False |