# Copyright import codecs import optparse import os.path import sys import libbe import libbe.storage import libbe.ui.util.user import libbe.util.encoding import libbe.util.plugin class UserError(Exception): pass class UnknownCommand(UserError): def __init__(self, cmd): Exception.__init__(self, "Unknown command '%s'" % cmd) self.cmd = cmd def get_command(command_name): """Retrieves the module for a user command >>> try: ... get_command('asdf') ... except UnknownCommand, e: ... print e Unknown command 'asdf' >>> repr(get_command('list')).startswith(">> import_xml_mod = get_command('import-xml') >>> import_xml = get_command_class(import_xml_mod, 'import-xml') >>> repr(import_xml) "" """ try: cname = command_name.capitalize().replace('-', '_') cmd = getattr(module, cname) except ImportError, e: raise UnknownCommand(command_name) return cmd def commands(): for modname in libbe.util.plugin.modnames('libbe.command'): if modname not in ['base', 'util']: yield modname class CommandInput (object): def __init__(self, name, help=''): self.name = name self.help = help class Argument (CommandInput): def __init__(self, metavar=None, default=None, type='string', optional=False, repeatable=False, completion_callback=None, *args, **kwargs): CommandInput.__init__(self, *args, **kwargs) self.metavar = metavar self.default = default self.type = type self.optional = optional self.repeatable = repeatable self.completion_callback = completion_callback if self.metavar == None: self.metavar = self.name.upper() class Option (CommandInput): def __init__(self, callback=None, short_name=None, arg=None, *args, **kwargs): CommandInput.__init__(self, *args, **kwargs) self.callback = callback self.short_name = short_name self.arg = arg if self.arg == None and self.callback == None: # use an implicit boolean argument self.arg = Argument(name=self.name, help=self.help, default=False, type='bool') self.validate() def validate(self): if self.arg == None: assert self.callback != None, self.name return assert self.callback == None, '%s: %s' (self.name, self.callback) assert self.arg.name == self.name, \ 'Name missmatch: %s != %s' % (self.arg.name, self.name) assert self.arg.optional == False, self.name assert self.arg.repeatable == False, self.name def __str__(self): return '--%s' % self.name def __repr__(self): return '