Skip to content

Commit

Permalink
Merge branch 'feature/pep8' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
glennmatthews committed Jan 22, 2015
2 parents 0b19ee5 + 5600021 commit 23e8130
Show file tree
Hide file tree
Showing 37 changed files with 1,071 additions and 1,108 deletions.
2 changes: 0 additions & 2 deletions COT/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
# of COT, including this file, may be copied, modified, propagated, or
# distributed except according to the terms contained in the LICENSE.txt file.

import os.path

from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
Expand Down
50 changes: 24 additions & 26 deletions COT/add_disk.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@
import logging
import os.path

from .data_validation import InvalidInputError
from .data_validation import *

from .data_validation import InvalidInputError, ValueUnsupportedError
from .data_validation import check_for_conflict, device_address, match_or_die
from .submodule import COTSubmodule

logger = logging.getLogger(__name__)


class COTAddDisk(COTSubmodule):
"""Add or replace a disk in a virtual machine"""

Expand Down Expand Up @@ -64,7 +64,6 @@ def validate_arg(self, arg, value):

return valid, value_or_reason


def validate_controller_address(self, controller, address):
if controller is not None:
input_value = controller
Expand All @@ -85,7 +84,6 @@ def validate_controller_address(self, controller, address):

return True, input_value


def ready_to_run(self):
"""Are we ready to go?
Returns the tuple (ready, reason)"""
Expand All @@ -97,15 +95,13 @@ def ready_to_run(self):
"specify the controller type")
return super(COTAddDisk, self).ready_to_run()


def run(self):
super(COTAddDisk, self).run()

add_disk_worker(self.vm,
UI=self.UI,
**self.args)


def create_subparser(self, parent):
p = parent.add_parser(
'add-disk', add_help=False,
Expand All @@ -130,8 +126,8 @@ def create_subparser(self, parent):
group.add_argument('-h', '--help', action='help',
help="""Show this help message and exit""")
group.add_argument('-o', '--output',
help="""Name/path of new OVF/OVA package to create """
"""instead of updating the existing OVF""")
help="""Name/path of new OVF/OVA package to """
"""create instead of updating the existing OVF""")

group = p.add_argument_group("disk-related options")

Expand All @@ -148,24 +144,24 @@ def create_subparser(self, parent):

group.add_argument('-c', '--controller',
choices=['ide', 'scsi'],
help="""Disk controller type (default: determined by """
"""disk type and platform)""")
help="""Disk controller type (default: """
"""determined by disk type and platform)""")
group.add_argument('-a', '--address', type=device_address,
help="""Address of the disk, such as "1:0". Requires """
"""that --controller be explicitly set. """
"""(default: use first unused address on the """
"""controller)""")
help="""Address of the disk, such as "1:0". """
"""Requires that --controller be explicitly set. """
"""(default: use first unused address on the """
"""controller)""")
group.add_argument('-s', '--subtype',
help="""Disk controller subtype such as "virtio" or """
""""lsilogic".""")
help="""Disk controller subtype such as "virtio" """
"""or "lsilogic".""")

group = p.add_argument_group("descriptive options")

group.add_argument('-d', '--description',
help="""Description of this disk (optional)""")
group.add_argument('-n', '--name', dest='diskname',
help="""Name of this disk (default: "Hard disk #" or """
""""CD-ROM #" as appropriate)""")
help="""Name of this disk (default: """
""""Hard disk #" or "CD-ROM #" as appropriate)""")

p.add_argument('DISK_IMAGE',
help="""Disk image file to add to the package""")
Expand Down Expand Up @@ -208,8 +204,8 @@ def add_disk_worker(vm,
"Please specify '--type harddisk' or '--type cdrom'."
.format(DISK_IMAGE, disk_extension,
ext_type_map.keys()))
logger.warning("New disk type not specified, guessing it should be "
"'{0}' based on file extension".format(type))
logger.warning("New disk type not specified, guessing it should "
"be '{0}' based on file extension".format(type))

# Convert the disk to a new format if needed...
DISK_IMAGE = vm.convert_disk_if_needed(DISK_IMAGE, type)
Expand All @@ -224,7 +220,7 @@ def add_disk_worker(vm,
# Item (defines the disk drive, links to controller and File or Disk)
#
# For each of these four sections, we need to know whether to add
# a new one or overwrite an existing one. Depending on the user-provided
# a new one or overwrite an existing one. Depending on the user
# arguments, we can do this by as many as three different approaches:
#
# 1) Check whether the DISK_IMAGE file name matches an existing File
Expand Down Expand Up @@ -277,7 +273,7 @@ def add_disk_worker(vm,
if file is None:
# This will happen if we're replacing a placeholder entry
# (disk exists but has no associated file)
logger.verbose("Found Disk but not File - maybe a placeholder?")
logger.verbose("Found Disk but not File - maybe placeholder?")

if disk_item is not None:
if type is not None:
Expand Down Expand Up @@ -334,8 +330,9 @@ def add_disk_worker(vm,
logger.warning("Overwriting existing File in OVF")

if file is None and (disk is not None or disk_item is not None):
UI.confirm_or_die("Add disk file to existing (but empty) {0} drive?"
.format(type))
UI.confirm_or_die(
"Add disk file to existing (but empty) {0} drive?"
.format(type))

if disk is not None:
logger.warning("Overwriting existing Disk in OVF")
Expand Down Expand Up @@ -382,7 +379,8 @@ def add_disk_worker(vm,
ctrl_addr = address.split(":")[0]
disk_addr = address.split(":")[1]
else:
ctrl_addr = None # let VM choose it if necessary
# let VM choose controller address if necessary
ctrl_addr = None
disk_addr = 0

ctrl_item = vm.add_controller_device(controller, subtype,
Expand Down
8 changes: 2 additions & 6 deletions COT/add_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@
import logging
import sys

from .data_validation import check_for_conflict, InvalidInputError
from .data_validation import check_for_conflict
from .submodule import COTSubmodule

logger = logging.getLogger(__name__)


class COTAddFile(COTSubmodule):
"""Add a file (such as a README) to the package."""

Expand All @@ -36,7 +37,6 @@ def __init__(self, UI):
"file_id"
])


def validate_arg(self, arg, value):
"""Check whether it's OK to set the given argument to the given value.
Returns either (True, massaged_value) or (False, reason)"""
Expand All @@ -53,19 +53,16 @@ def validate_arg(self, arg, value):

return valid, value_or_reason


def set_value(self, arg, value):
super(COTAddFile, self).set_value(arg, value)


def ready_to_run(self):
"""Are we ready to go?
Returns the tuple (ready, reason)"""
if self.get_value("FILE") is None:
return False, "FILE is a mandatory argument!"
return super(COTAddFile, self).ready_to_run()


def run(self):
super(COTAddFile, self).run()

Expand All @@ -92,7 +89,6 @@ def run(self):

vm.add_file(FILE, file_id, file)


def create_subparser(self, parent):
p = parent.add_parser(
'add-file',
Expand Down
37 changes: 17 additions & 20 deletions COT/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@
import sys
import argparse
import logging
import os.path
import re
import textwrap

# Set logging defaults for all of COT
from verboselogs import VerboseLogger
logging.setLoggerClass(VerboseLogger)

from coloredlogs import ColoredStreamHandler


class COTStreamHandler(ColoredStreamHandler, object):

def __init__(self, level=logging.DEBUG, **kwargs):
Expand Down Expand Up @@ -77,7 +77,7 @@ def emit(self, record):
def render_timestamp(self, created, msecs):
import time
return "%s.%03d" % (time.strftime('%H:%M:%S',
time.localtime(created)),
time.localtime(created)),
msecs)

def render_name(self, name):
Expand All @@ -86,19 +86,18 @@ def render_name(self, name):
COTHandler = COTStreamHandler()
logging.getLogger('COT').addHandler(COTHandler)

# Proceed with importing the rest of the needed modules now that logging is set

# Proceed with importing the rest of the needed modules now that we have logging

from COT import __version__, __version_long__
from COT import __version_long__
from COT.data_validation import InvalidInputError
from COT.data_validation import *
from COT.ui_shared import UI

logger = logging.getLogger(__name__)

# Where do we want to wrap lines when pretty-printing?
TEXT_WIDTH = 79


class CLI(UI):
"""Command-line user interface for COT"""

Expand All @@ -113,12 +112,10 @@ def __init__(self):
self.create_parser()
self.create_subparsers()


def run(self, argv):
args = self.parse_args(argv)
return self.main(args)


def confirm(self, prompt):
"""Prompts user to confirm the requested operation, or auto-accepts if
args.force is set to True."""
Expand All @@ -142,7 +139,6 @@ def confirm(self, prompt):
else:
print("Please enter 'y' or 'n'")


def get_input(self, prompt, default_value):
"""Prompt the user to enter a string, or auto-accepts the default if
force is set to True."""
Expand All @@ -165,7 +161,6 @@ def get_password(self, username, host):
return getpass.getpass("Password for {0}@{1}: "
.format(username, host))


def create_parser(self):
# Top-level command definition and any global options
parser = argparse.ArgumentParser(
Expand All @@ -178,8 +173,8 @@ def create_parser(self):
A tool for editing Open Virtualization Format (.ovf, .ova) virtual appliances,
with a focus on virtualized network appliances such as the Cisco CSR 1000V and
Cisco IOS XRv platforms."""),
epilog=(
"""Note: some subcommands rely on external software tools, including:
epilog=("""
Note: some subcommands rely on external software tools, including:
* qemu-img (http://www.qemu.org/)
* mkisofs (http://cdrecord.org/)
* ovftool (https://www.vmware.com/support/developer/ovf/)
Expand All @@ -196,13 +191,16 @@ def create_parser(self):

parser.set_defaults(_verbosity=logging.INFO)
debug_group = parser.add_mutually_exclusive_group()
debug_group.add_argument('-q', '--quiet', dest='_verbosity',
debug_group.add_argument(
'-q', '--quiet', dest='_verbosity',
action='store_const', const=logging.WARNING,
help="Quiet output and logging (warnings and errors only)")
debug_group.add_argument('-v', '--verbose', dest='_verbosity',
debug_group.add_argument(
'-v', '--verbose', dest='_verbosity',
action='store_const', const=logging.VERBOSE,
help="Verbose output and logging")
debug_group.add_argument('-vv', '-d', '--debug', dest='_verbosity',
debug_group.add_argument(
'-vv', '-d', '--debug', dest='_verbosity',
action='store_const', const=logging.DEBUG,
help="Debug (most verbose) output and logging")

Expand All @@ -215,7 +213,6 @@ def create_parser(self):

self.subparser_lookup = {}


def create_subparsers(self):
from COT.add_disk import COTAddDisk
from COT.add_file import COTAddFile
Expand All @@ -241,7 +238,7 @@ def create_subparsers(self):
def parse_args(self, argv):
# By now all subparsers have been created so we can safely set usage.
# See comment above.
self.parser.usage=("""
self.parser.usage = ("""
cot --help
cot --version
cot <command> --help
Expand All @@ -258,7 +255,6 @@ def parse_args(self, argv):

return args


def main(self, args):
logging.getLogger('COT').setLevel(args._verbosity)
COTHandler.setLevel(args._verbosity)
Expand All @@ -277,7 +273,7 @@ def main(self, args):
# as [[1, 2][3]] rather than the desired [1, 2, 3].
# Flatten it back out before we pass it through to the submodule!
if (isinstance(value, list) and
all(isinstance(v, list) for v in value)):
all(isinstance(v, list) for v in value)):
arg_hash[arg] = [v for l in value for v in l]
del arg_hash["_verbosity"]
try:
Expand Down Expand Up @@ -308,6 +304,7 @@ def main(self, args):
# can provide, the better!
return 0


def main():
CLI().run(sys.argv[1:])

Expand Down

0 comments on commit 23e8130

Please sign in to comment.