* introduce logcommand.Lager, Whipper(); use argparse for whipper image commands, stub logging * update Lager docstring to mention config.Config() * make incorrect subcommand and --version work on toplevel command * migrate accurip show, expand Lager, do not attempt to return from Lager.__init__. * migrate offset find, add Lager.error * correct offset find drive symlink handling * migrate drive * change Lager.__init__(prog) to arg from kwarg * but actually * remove Whipper.usage * add and use Lager.device_option() context manager * help I married an axe murderer * use unified options namespace for entire command tree * migrate whipper cd without comprehensive config loading * switch to logging module - use logging instead of flog for non-extern modules - use WHIPPER_DEBUG and WHIPPER_LOGFILE env variables * convert self.log calls to logger.debug * convert self.error calls to logger.error * remove log.Loggable, use logger not logging * Logging conversion continues - Convert log.* calls to logger.* - Remove morituri.common.log imports * remove morituri.common.log from tests * remove extern/flog, bare minimum Debug conversion * update README for logging changes * update soxi to use logging * refactor Lager for more declarative subcommands * Refactor Lager.device_option: - inline into __init__ - throw IOError instead of Exception for missing drives - remove CommandError checking in rip/main * rename rip to whipper in rip.main * convert rip.debug commands * Rename logcommand.Lager to command.BaseCommand - remove command.CommandError occurrences - remove python-command external module * remove submodules from README, update rclog formatter * update minor ambiguity in readme for command invocation * update version number to match setup.py * remove gitmodules * update version number in tests as well (boo) * convert logger.error to logger.critical * Change morituri.rip to morituri.command - mv common.command to command.basecommand - move TEMPLATES used only by rip.cd out of rip.common - update entry point for command to command.main * update basecommand documentation * go pyflaking: import fixing * replace self.stdout with sys.stdout * remove BaseCommand.config, alphabetise imports * convert self.stdXXX leftovers * convert last getRootCommand to config.Config * convert last getExceptionMessage's to str * change musicbrainz useragent to whipper
130 lines
4.3 KiB
Python
130 lines
4.3 KiB
Python
# -*- Mode: Python -*-
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
|
|
|
import argparse
|
|
import os
|
|
import sys
|
|
|
|
from morituri.common import drive
|
|
|
|
import logging
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Q: What about argparse.add_subparsers(), you ask?
|
|
# A: Unfortunately add_subparsers() does not support specifying the
|
|
# formatter_class of subparsers, nor does it support epilogs, so
|
|
# it does not quite fit our use case.
|
|
|
|
# Q: Why not subclass ArgumentParser and extend/replace the relevant
|
|
# methods?
|
|
# A: If this can be done in a simpler fashion than this current
|
|
# implementation, by all means submit a patch.
|
|
|
|
# Q: Why not argparse.parse_known_args()?
|
|
# A: The prefix matching prevents passing '-h' (and possibly other
|
|
# options) to the child command.
|
|
|
|
class BaseCommand():
|
|
"""
|
|
A base command class for whipper commands.
|
|
|
|
Creates an argparse.ArgumentParser.
|
|
Override add_arguments() and handle_arguments() to register
|
|
and process arguments before & after argparse.parse_args().
|
|
|
|
Provides self.epilog() formatting command for argparse.
|
|
|
|
device_option = True adds -d / --device option to current command
|
|
no_add_help = True removes -h / --help option from current command
|
|
|
|
Overriding formatter_class sets the argparse formatter class.
|
|
|
|
If the 'subcommands' dictionary is set, __init__ searches the
|
|
arguments for subcommands.keys() and instantiates the class
|
|
implementing the subcommand as self.cmd, passing all non-understood
|
|
arguments, the current options namespace, and the full command path
|
|
name.
|
|
"""
|
|
device_option = False
|
|
no_add_help = False # for rip.main.Whipper
|
|
formatter_class = argparse.RawDescriptionHelpFormatter
|
|
|
|
def __init__(self, argv, prog_name, opts):
|
|
self.opts = opts # for Rip.add_arguments()
|
|
self.prog_name = prog_name
|
|
|
|
self.init_parser()
|
|
self.add_arguments()
|
|
|
|
if hasattr(self, 'subcommands'):
|
|
self.parser.add_argument('remainder',
|
|
nargs=argparse.REMAINDER,
|
|
help=argparse.SUPPRESS)
|
|
|
|
if self.device_option:
|
|
# pick the first drive as default
|
|
drives = drive.getAllDevicePaths()
|
|
if not drives:
|
|
msg = 'No CD-DA drives found!'
|
|
logger.critical(msg)
|
|
# morituri exited with return code 3 here
|
|
raise IOError(msg)
|
|
self.parser.add_argument('-d', '--device',
|
|
action="store",
|
|
dest="device",
|
|
default=drives[0],
|
|
help="CD-DA device")
|
|
|
|
self.options = self.parser.parse_args(argv, namespace=opts)
|
|
|
|
if self.device_option:
|
|
# this can be a symlink to another device
|
|
self.options.device = os.path.realpath(self.options.device)
|
|
if not os.path.exists(self.options.device):
|
|
msg = 'CD-DA device %s not found!' % self.options.device
|
|
logger.critical(msg)
|
|
raise IOError(msg)
|
|
|
|
self.handle_arguments()
|
|
|
|
if hasattr(self, 'subcommands'):
|
|
if not self.options.remainder:
|
|
self.parser.print_help()
|
|
sys.exit(0)
|
|
if not self.options.remainder[0] in self.subcommands:
|
|
sys.stderr.write("incorrect subcommand: %s" %
|
|
self.options.remainder[0])
|
|
sys.exit(1)
|
|
self.cmd = self.subcommands[self.options.remainder[0]](
|
|
self.options.remainder[1:],
|
|
prog_name + " " + self.options.remainder[0],
|
|
self.options
|
|
)
|
|
|
|
def init_parser(self):
|
|
kw = {
|
|
'prog': self.prog_name,
|
|
'description': self.description,
|
|
'formatter_class': self.formatter_class,
|
|
}
|
|
if hasattr(self, 'subcommands'):
|
|
kw['epilog'] = self.epilog()
|
|
if self.no_add_help:
|
|
kw['add_help'] = False
|
|
self.parser = argparse.ArgumentParser(**kw)
|
|
|
|
def add_arguments(self):
|
|
pass
|
|
|
|
def handle_arguments(self):
|
|
pass
|
|
|
|
def do(self):
|
|
return self.cmd.do()
|
|
|
|
def epilog(self):
|
|
s = "commands:\n"
|
|
for com in sorted(self.subcommands.keys()):
|
|
s += " %s %s\n" % (com.ljust(8), self.subcommands[com].summary)
|
|
return s
|