# or implied, of GRNET S.A.
from kamaki.cli.config import Config
-from kamaki.cli.errors import CLISyntaxError
+from kamaki.cli.errors import CLISyntaxError, raiseCLIError
from kamaki.cli.utils import split_input
+from logging import getLogger
+from datetime import datetime as dtm
+from time import mktime
+
from argparse import ArgumentParser, ArgumentError
+from argparse import RawDescriptionHelpFormatter
try:
- from progress.bar import FillingCirclesBar as KamakiProgressBar
- # IncrementalBar
+ from progress.bar import ShadyBar as KamakiProgressBar
except ImportError:
+ try:
+ from progress.bar import Bar as KamakiProgressBar
+ except ImportError:
+ pass
# progress not installed - pls, pip install progress
pass
+kloger = getLogger('kamaki')
+
class Argument(object):
"""An argument that can be parsed from command line or otherwise.
def __init__(self, arity, help=None, parsed_name=None, default=None):
self.arity = int(arity)
- if help is not None:
+ if help:
self.help = help
- if parsed_name is not None:
+ if parsed_name:
self.parsed_name = parsed_name
- if default is not None:
- self.default = default
+ self.default = default
@property
def parsed_name(self):
action = 'append' if self.arity < 0\
else 'store_true' if self.arity == 0\
else 'store'
- parser.add_argument(*self.parsed_name, dest=name, action=action,
- default=self.default, help=self.help)
+ parser.add_argument(
+ *self.parsed_name,
+ dest=name,
+ action=action,
+ default=self.default,
+ help=self.help)
def main(self):
"""Overide this method to give functionality to your args"""
for option in options:
keypath, sep, val = option.partition('=')
if not sep:
- raise CLISyntaxError('Argument Syntax Error ',
- details='%s is missing a "=" (usage: -o section.key=val)'\
- % option)
+ raiseCLIError(
+ CLISyntaxError('Argument Syntax Error '),
+ details=[
+ '%s is missing a "="',
+ ' (usage: -o section.key=val)' % option])
section, sep, key = keypath.partition('.')
if not sep:
key = section
try:
self._value = int(newvalue)
except ValueError:
- raise CLISyntaxError('IntArgument Error',
- details='Value %s not an int' % newvalue)
+ raiseCLIError(CLISyntaxError(
+ 'IntArgument Error',
+ details=['Value %s not an int' % newvalue]))
+
+
+class DateArgument(ValueArgument):
+ """
+ :value type: a string formated in an acceptable date format
+
+ :value returns: same date in first of DATE_FORMATS
+ """
+
+ DATE_FORMATS = [
+ "%a %b %d %H:%M:%S %Y",
+ "%A, %d-%b-%y %H:%M:%S GMT",
+ "%a, %d %b %Y %H:%M:%S GMT"]
+
+ INPUT_FORMATS = DATE_FORMATS + ["%d-%m-%Y", "%H:%M:%S %d-%m-%Y"]
+
+ @property
+ def timestamp(self):
+ v = getattr(self, '_value', self.default)
+ return mktime(v.timetuple()) if v else None
+
+ @property
+ def formated(self):
+ v = getattr(self, '_value', self.default)
+ return v.strftime(self.DATE_FORMATS[0]) if v else None
+
+ @property
+ def value(self):
+ return self.timestamp
+
+ @value.setter
+ def value(self, newvalue):
+ if newvalue:
+ self._value = self.format_date(newvalue)
+
+ def format_date(self, datestr):
+ for format in self.INPUT_FORMATS:
+ try:
+ t = dtm.strptime(datestr, format)
+ except ValueError:
+ continue
+ return t # .strftime(self.DATE_FORMATS[0])
+ raiseCLIError(
+ None,
+ 'Date Argument Error',
+ details='%s not a valid date. correct formats:\n\t%s' % (
+ datestr, self.INPUT_FORMATS))
class VersionArgument(FlagArgument):
for pair in keyvalue_pairs:
key, sep, val = pair.partition('=')
if not sep:
- raise CLISyntaxError('Argument syntax error ',
+ raiseCLIError(
+ CLISyntaxError('Argument syntax error '),
details='%s is missing a "=" (usage: key1=val1 )\n' % pair)
self._value[key.strip()] = val.strip()
try:
KamakiProgressBar
except NameError:
- print('Warning: no progress bar functionality')
+ kloger.debug('WARNING: no progress bar functionality')
def clone(self):
"""Get a modifiable copy of this bar"""
mybar.finish()
-_arguments = dict(config=_config_arg,
+_arguments = dict(
+ config=_config_arg,
help=Argument(0, 'Show help message', ('-h', '--help')),
debug=FlagArgument('Include debug output', ('-d', '--debug')),
- include=FlagArgument('Include protocol headers in the output',
+ include=FlagArgument(
+ 'Include raw connection data in the output',
('-i', '--include')),
silent=FlagArgument('Do not output anything', ('-s', '--silent')),
verbose=FlagArgument('More info at response', ('-v', '--verbose')),
version=VersionArgument('Print current version', ('-V', '--version')),
- options=CmdLineConfigArgument(_config_arg,
+ options=CmdLineConfigArgument(
+ _config_arg,
'Override a config value',
('-o', '--options'))
)
"""
-def init_parser(exe, arguments):
- """Create and initialize an ArgumentParser object"""
- parser = ArgumentParser(add_help=False)
- parser.prog = '%s <cmd_group> [<cmd_subbroup> ...] <cmd>' % exe
- update_arguments(parser, arguments)
- return parser
+class ArgumentParseManager(object):
+ """Manage (initialize and update) an ArgumentParser object"""
+ parser = None
+ _arguments = {}
+ _parser_modified = False
+ _parsed = None
+ _unparsed = None
-def parse_known_args(parser, arguments=None):
- """Fill in arguments from user input"""
- parsed, unparsed = parser.parse_known_args()
- for name, arg in arguments.items():
- arg.value = getattr(parsed, name, arg.default)
- newparsed = []
- for term in unparsed:
- newparsed += split_input(' \'%s\' ' % term)
- return parsed, newparsed
+ def __init__(self, exe, arguments=None):
+ """
+ :param exe: (str) the basic command (e.g. 'kamaki')
+ :param arguments: (dict) if given, overrides the global _argument as
+ the parsers arguments specification
+ """
+ self.parser = ArgumentParser(
+ add_help=False,
+ formatter_class=RawDescriptionHelpFormatter)
+ self.syntax = '%s <cmd_group> [<cmd_subbroup> ...] <cmd>' % exe
+ if arguments:
+ self.arguments = arguments
+ else:
+ global _arguments
+ self.arguments = _arguments
+ self.parse()
-def update_arguments(parser, arguments):
- """Update arguments dict from user input
+ @property
+ def syntax(self):
+ """The command syntax (useful for help messages, descriptions, etc)"""
+ return self.parser.prog
- """
- for name, argument in arguments.items():
+ @syntax.setter
+ def syntax(self, new_syntax):
+ self.parser.prog = new_syntax
+
+ @property
+ def arguments(self):
+ """(dict) arguments the parser should be aware of"""
+ return self._arguments
+
+ @arguments.setter
+ def arguments(self, new_arguments):
+ if new_arguments:
+ assert isinstance(new_arguments, dict)
+ self._arguments = new_arguments
+ self.update_parser()
+
+ @property
+ def parsed(self):
+ """(Namespace) parser-matched terms"""
+ if self._parser_modified:
+ self.parse()
+ return self._parsed
+
+ @property
+ def unparsed(self):
+ """(list) parser-unmatched terms"""
+ if self._parser_modified:
+ self.parse()
+ return self._unparsed
+
+ def update_parser(self, arguments=None):
+ """Load argument specifications to parser
+
+ :param arguments: if not given, update self.arguments instead
+ """
+ if not arguments:
+ arguments = self._arguments
+
+ for name, arg in arguments.items():
+ try:
+ arg.update_parser(self.parser, name)
+ self._parser_modified = True
+ except ArgumentError:
+ pass
+
+ def update_arguments(self, new_arguments):
+ """Add to / update existing arguments
+
+ :param new_arguments: (dict)
+ """
+ if new_arguments:
+ assert isinstance(new_arguments, dict)
+ self._arguments.update(new_arguments)
+ self.update_parser()
+
+ def parse(self, new_args=None):
+ """Do parse user input"""
try:
- argument.update_parser(parser, name)
- except ArgumentError:
- pass
+ if new_args:
+ self._parsed, unparsed = self.parser.parse_known_args(new_args)
+ else:
+ self._parsed, unparsed = self.parser.parse_known_args()
+ except SystemExit:
+ # deal with the fact that argparse error system is STUPID
+ raiseCLIError(CLISyntaxError('Argument Syntax Error'))
+ for name, arg in self.arguments.items():
+ arg.value = getattr(self._parsed, name, arg.default)
+ self._unparsed = []
+ for term in unparsed:
+ self._unparsed += split_input(' \'%s\' ' % term)
+ self._parser_modified = False