COT.ui.cli module

CLI entry point for the Common OVF Tool (COT) suite.

Classes

CLI Command-line user interface for COT.
CLILoggingFormatter Logging formatter with colorization and variable verbosity.
class CLI(terminal_width=None)[source]

Bases: COT.ui.ui.UI

Command-line user interface for COT.

confirm Prompt user to confirm the requested operation.
create_parser Create parser object for global cot command.
create_subparsers Populate the CLI sub-parsers for all known commands.
fill_examples Pretty-print a set of usage examples.
fill_usage Pretty-print a list of usage strings for a COT subcommand.
get_input Prompt the user to enter a string.
get_password Get password string from the user.
main Main worker function for COT when invoked from the CLI.
parse_args Parse the given CLI arguments into a namespace object.
run Parse the given CLI args then run.
set_verbosity Enable logging and/or change the logging verbosity level.
terminal_width The width of the terminal in columns.
__init__(terminal_width=None)[source]

Create CLI handler instance.

Parameters:terminal_width (int) -- (optional) Set the terminal width for this CLI, independent of the actual terminal in use.
add_subparser(title, parent=None, aliases=None, lookup_prefix='', **kwargs)[source]

Create a subparser under the specified parent.

Parameters:
  • title (str) -- Canonical keyword for this subparser
  • parent (object) -- Subparser grouping object returned by ArgumentParser.add_subparsers()
  • aliases (list) -- Aliases for title. Only used in Python 3.x.
  • lookup_prefix (str) -- String to prepend to title and each alias in aliases for lookup purposes.
  • kwargs (dict) -- Passed through to parent.add_parser()
Returns:

object -- Subparser object

adjust_verbosity(delta)[source]

Set the logging verbosity relative to the COT default.

Wrapper for set_verbosity(), to be used when you have a delta (number of steps to offset more or less verbose) rather than an actual logging level in mind.

Parameters:delta (int) -- Shift in verbosity level. 0 = default verbosity; positive implies more verbose; negative implies less verbose.
static args_to_dict(args)[source]

Convert args to a dict and perform any needed cleanup.

Parameters:args (argparse.Namespace) -- Namespace from parse_args().
Returns:dict -- Dictionary of arg to value
confirm(prompt)[source]

Prompt user to confirm the requested operation.

Auto-accepts if force is set to True.

Parameters:prompt (str) -- Message to prompt the user with
Returns:bool -- True (user accepts) or False (user declines)
create_parser()[source]

Create parser object for global cot command.

Includes a number of globally applicable CLI options.

create_subparsers()[source]

Populate the CLI sub-parsers for all known commands.

Creates an instance of each Command subclass in COT.commands.command_classes, then calls create_subparser() for each.

fill_examples(example_list)[source]

Pretty-print a set of usage examples.

Parameters:example_list (list) -- List of (description, CLI example) tuples.
Returns:str -- Concatenation of examples, each wrapped appropriately to the terminal_width() value. CLI examples will be wrapped with backslashes and a hanging indent.

Examples

>>> print(CLI(68).fill_examples([
...  ("Deploy to vSphere/ESXi server 192.0.2.100 with credentials"
...   " admin/admin, creating a VM named 'test_vm' from foo.ova.",
...   'cot deploy foo.ova esxi 192.0.2.100 -u admin -p admin'
...   ' -n test_vm'),
...  ("Deploy to vSphere/ESXi server 192.0.2.100, with username"
...   " admin (prompting the user to input a password at runtime),"
...   " creating a VM based on profile '1CPU-2.5GB' in foo.ova.",
...   'cot deploy foo.ova esxi 192.0.2.100 -u admin -c 1CPU-2.5GB')
... ]))
Examples:
  Deploy to vSphere/ESXi server 192.0.2.100 with credentials
  admin/admin, creating a VM named 'test_vm' from foo.ova.

    cot deploy foo.ova esxi 192.0.2.100 -u admin -p admin \
        -n test_vm

  Deploy to vSphere/ESXi server 192.0.2.100, with username admin
  (prompting the user to input a password at runtime), creating a
  VM based on profile '1CPU-2.5GB' in foo.ova.

    cot deploy foo.ova esxi 192.0.2.100 -u admin -c 1CPU-2.5GB
fill_usage(subcommand, usage_list)[source]

Pretty-print a list of usage strings for a COT subcommand.

Automatically prepends a cot subcommand --help usage string to the provided list.

Parameters:
  • subcommand (str) -- Subcommand name/keyword
  • usage_list (list) -- List of usage strings for this subcommand.
Returns:

string -- All usage strings, each appropriately wrapped to the terminal_width() value.

Examples

>>> print(CLI(50).fill_usage('add-file',
...       ["FILE PACKAGE [-o OUTPUT] [-f FILE_ID]"]))

  cot add-file --help
  cot <opts> add-file FILE PACKAGE [-o OUTPUT]
                      [-f FILE_ID]
get_input(prompt, default_value)[source]

Prompt the user to enter a string.

Auto-inputs the default_value if force is set to True.

Parameters:
  • prompt (str) -- Message to prompt the user with
  • default_value (str) -- Default value to input if the user simply hits Enter without entering a value, or if force.
Returns:

str -- Input value

get_password(username, host)[source]

Get password string from the user.

Parameters:
  • username (str) -- Username the password is associated with
  • host (str) -- Host the password is associated with
Raises:

InvalidInputError -- if force is True (as there is no "default" password value)

Returns:

str -- Password string

main(args)[source]

Main worker function for COT when invoked from the CLI.

  • Calls adjust_verbosity() with the appropriate verbosity level derived from the args.
  • Looks up the appropriate Command instance corresponding to the subcommand that was invoked.
  • Converts args to a dict and calls set_instance_attributes() to pass these args to the instance.
  • Calls run() followed by finished().
  • Catches various exceptions and handles them appropriately.
Parameters:args (argparse.Namespace) -- Parser namespace object returned from parse_args().
Returns:int --

Exit code for the COT executable.

  • 0 on successful completion
  • 1 on runtime error
  • 2 on input error (parser error, InvalidInputError, etc.)
parse_args(argv)[source]

Parse the given CLI arguments into a namespace object.

Parameters:argv (list) -- List of CLI arguments, not including argv0
Returns:argparse.Namespace -- Parser namespace object
run(argv)[source]

Parse the given CLI args then run.

Calls parse_args() followed by main().

Parameters:argv (list) -- The CLI argv value (not including argv[0])
Returns:int -- Return code from main()
static set_instance_attributes(arg_dict)[source]

Set attributes of the instance based on the given arg_dict.

Parameters:arg_dict (dict) -- Dictionary of (attribute, value).
Raises:InvalidInputError -- if attributes are not validly set.
set_verbosity(level)[source]

Enable logging and/or change the logging verbosity level.

Will create a CLILoggingFormatter and use it for colorized, appropriately verbose log formatting.

Parameters:level (int) -- Logging level as defined in logging.
terminal_width

The width of the terminal in columns.

class CLILoggingFormatter(verbosity=20)[source]

Bases: colorlog.colorlog.ColoredFormatter, object

Logging formatter with colorization and variable verbosity.

COT logs are formatted differently (more or less verbosely) depending on the logging level.

Parameters:verbosity (int) -- Logging level as defined by logging.

Examples:

>>> record = logging.LogRecord(
... "COT.doctests",   # logger name
... logging.INFO,     # message level
... "/fakemodule.py", # file reporting the message
... 22,               # line number in file
... "Hello world!",   # message text
... None,             # %-style args for message
... None,             # exception info
... "test_func")      # function reporting the message
>>> record.created = 0
>>> record.msecs = 0
>>> CLILoggingFormatter(logging.NOTICE).format(record)
'\x1b[32mINFO    :\x1b[0m Hello world!'
>>> CLILoggingFormatter(logging.INFO).format(record) 
'\x1b[32mINFO    : fakemodule ... Hello world!'
>>> CLILoggingFormatter(logging.VERBOSE).format(
... record) 
'\x1b[32mINFO    : fakemodule ... test_func()... Hello world!'
>>> CLILoggingFormatter(logging.DEBUG).format(record) 
'\x1b[32mINFO ...:00.0 : fakemodule ...22...test_func()...Hello world!'
__init__(verbosity=20)[source]

Create formatter for COT log output with the given verbosity.

LOG_COLORS = {'CRITICAL': 'purple,bold', 'DEBUG': 'blue', 'ERROR': 'fg_white,bg_red', 'INFO': 'green', 'NOTICE': 'yellow', 'SPAM': '', 'VERBOSE': 'cyan', 'WARNING': 'red'}
main()[source]

Launch COT from the CLI.