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.UICommand-line user interface for COT.
confirmPrompt user to confirm the requested operation. create_parserCreate parserobject for globalcotcommand.create_subparsersPopulate the CLI sub-parsers for all known commands. fill_examplesPretty-print a set of usage examples. fill_usagePretty-print a list of usage strings for a COT subcommand. get_inputPrompt the user to enter a string. get_passwordGet password string from the user. mainMain worker function for COT when invoked from the CLI. parse_argsParse the given CLI arguments into a namespace object. runParse the given CLI args then run. set_verbosityEnable logging and/or change the logging verbosity level. terminal_widthThe 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
titleand each alias inaliasesfor 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
forceis set toTrue.Parameters: prompt (str) -- Message to prompt the user with Returns: bool -- True(user accepts) orFalse(user declines)
-
create_parser()[source]¶ Create
parserobject for globalcotcommand.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
Commandsubclass inCOT.commands.command_classes, then callscreate_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 --helpusage string to the provided list.Parameters: 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_valueifforceis set toTrue.Parameters: Returns: str -- Input value
-
get_password(username, host)[source]¶ Get password string from the user.
Parameters: Raises: InvalidInputError-- ifforceisTrue(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
Commandinstance corresponding to the subcommand that was invoked. - Converts
argsto a dict and callsset_instance_attributes()to pass these args to the instance. - Calls
run()followed byfinished(). - 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.)
- Calls
-
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 bymain().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
instancebased 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
CLILoggingFormatterand 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,objectLogging formatter with colorization and variable verbosity.
COT logs are formatted differently (more or less verbosely) depending on the logging level.
See also
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!'
-
LOG_COLORS= {'CRITICAL': 'purple,bold', 'DEBUG': 'blue', 'ERROR': 'fg_white,bg_red', 'INFO': 'green', 'NOTICE': 'yellow', 'SPAM': '', 'VERBOSE': 'cyan', 'WARNING': 'red'}¶
-