| 1 |
import argparse |
| 2 |
import importlib.metadata |
| 3 |
import logging |
| 4 |
import sys |
| 5 |
from warnings import warn |
| 6 |
|
| 7 |
log = logging.getLogger(__name__) |
| 8 |
|
| 9 |
|
| 10 |
class HelpfulArgumentParser(argparse.ArgumentParser): |
| 11 |
|
| 12 |
def error(self, message): # pragma: nocover |
| 13 |
"""error(message: string) |
| 14 |
|
| 15 |
Prints a usage message incorporating the message to stderr and |
| 16 |
exits. |
| 17 |
|
| 18 |
If you override this in a subclass, it should not return -- it |
| 19 |
should either exit or raise an exception. |
| 20 |
""" |
| 21 |
self.print_help(sys.stderr) |
| 22 |
self._print_message('\n') |
| 23 |
self.exit(2, '%s: %s\n' % (self.prog, message)) |
| 24 |
|
| 25 |
|
| 26 |
class CommandManager(object): |
| 27 |
""" Used to discover `pecan.command` entry points. """ |
| 28 |
|
| 29 |
def __init__(self): |
| 30 |
self.commands = {} |
| 31 |
self.load_commands() |
| 32 |
|
| 33 |
def load_commands(self): |
| 34 |
for ep in importlib.metadata.entry_points(group='pecan.command'): |
| 35 |
log.debug('%s loading plugin %s', self.__class__.__name__, ep) |
| 36 |
if ep.name in self.commands: |
| 37 |
warn( |
| 38 |
"Duplicate entry points found on `%s` - ignoring %s" % ( |
| 39 |
ep.name, |
| 40 |
ep |
| 41 |
), |
| 42 |
RuntimeWarning |
| 43 |
) |
| 44 |
continue |
| 45 |
try: |
| 46 |
cmd = ep.load() |
| 47 |
cmd.run # ensure existance; catch AttributeError otherwise |
| 48 |
except Exception as e: # pragma: nocover |
| 49 |
warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning) |
| 50 |
continue |
| 51 |
self.add({ep.name: cmd}) |
| 52 |
|
| 53 |
def add(self, cmd): |
| 54 |
self.commands.update(cmd) |
| 55 |
|
| 56 |
|
| 57 |
class CommandRunner(object): |
| 58 |
""" Dispatches `pecan` command execution requests. """ |
| 59 |
|
| 60 |
def __init__(self): |
| 61 |
self.manager = CommandManager() |
| 62 |
self.parser = HelpfulArgumentParser(add_help=True) |
| 63 |
self.parser.add_argument( |
| 64 |
'--version', |
| 65 |
action='version', |
| 66 |
version='Pecan %s' % self.version |
| 67 |
) |
| 68 |
self.parse_sub_commands() |
| 69 |
|
| 70 |
def parse_sub_commands(self): |
| 71 |
subparsers = self.parser.add_subparsers( |
| 72 |
dest='command_name', |
| 73 |
metavar='command' |
| 74 |
) |
| 75 |
for name, cmd in self.commands.items(): |
| 76 |
sub = subparsers.add_parser( |
| 77 |
name, |
| 78 |
help=cmd.summary |
| 79 |
) |
| 80 |
for arg in getattr(cmd, 'arguments', tuple()): |
| 81 |
arg = arg.copy() |
| 82 |
if isinstance(arg.get('name'), str): |
| 83 |
sub.add_argument(arg.pop('name'), **arg) |
| 84 |
elif isinstance(arg.get('name'), list): |
| 85 |
sub.add_argument(*arg.pop('name'), **arg) |
| 86 |
|
| 87 |
def run(self, args): |
| 88 |
ns = self.parser.parse_args(args) |
| 89 |
if ns.command_name is None: |
| 90 |
self.run(['--help']) |
| 91 |
return |
| 92 |
self.commands[ns.command_name]().run(ns) |
| 93 |
|
| 94 |
@classmethod |
| 95 |
def handle_command_line(cls): # pragma: nocover |
| 96 |
runner = CommandRunner() |
| 97 |
runner.run(sys.argv[1:]) |
| 98 |
|
| 99 |
@property |
| 100 |
def version(self): |
| 101 |
return importlib.metadata.version('pecan') |
| 102 |
|
| 103 |
@property |
| 104 |
def commands(self): |
| 105 |
return self.manager.commands |
| 106 |
|
| 107 |
|
| 108 |
class BaseCommandMeta(type): |
| 109 |
|
| 110 |
@property |
| 111 |
def summary(cls): |
| 112 |
""" |
| 113 |
This is used to populate the --help argument on the command line. |
| 114 |
|
| 115 |
This provides a default behavior which takes the first sentence of the |
| 116 |
command's docstring and uses it. |
| 117 |
""" |
| 118 |
return cls.__doc__.strip().splitlines()[0].rstrip('.') |
| 119 |
|
| 120 |
|
| 121 |
class BaseCommandParent(object): |
| 122 |
""" |
| 123 |
A base interface for Pecan commands. |
| 124 |
|
| 125 |
Can be extended to support ``pecan`` command extensions in individual Pecan |
| 126 |
projects, e.g., |
| 127 |
|
| 128 |
$ ``pecan my-custom-command config.py`` |
| 129 |
|
| 130 |
:: |
| 131 |
|
| 132 |
# myapp/myapp/custom_command.py |
| 133 |
class CustomCommand(pecan.commands.base.BaseCommand): |
| 134 |
''' |
| 135 |
(First) line of the docstring is used to summarize the command. |
| 136 |
''' |
| 137 |
|
| 138 |
arguments = ({ |
| 139 |
'name': '--extra_arg', |
| 140 |
'help': 'an extra command line argument', |
| 141 |
'optional': True |
| 142 |
}) |
| 143 |
|
| 144 |
def run(self, args): |
| 145 |
super(SomeCommand, self).run(args) |
| 146 |
if args.extra_arg: |
| 147 |
pass |
| 148 |
""" |
| 149 |
|
| 150 |
arguments = ({ |
| 151 |
'name': 'config_file', |
| 152 |
'help': 'a Pecan configuration file', |
| 153 |
'nargs': '?', |
| 154 |
'default': None, |
| 155 |
},) |
| 156 |
|
| 157 |
def run(self, args): |
| 158 |
"""To be implemented by subclasses.""" |
| 159 |
self.args = args |
| 160 |
|
| 161 |
def load_app(self): |
| 162 |
from pecan import load_app |
| 163 |
return load_app(self.args.config_file) |
| 164 |
|
| 165 |
|
| 166 |
BaseCommand = BaseCommandMeta('BaseCommand', (BaseCommandParent,), { |
| 167 |
'__doc__': BaseCommandParent.__doc__ |
| 168 |
}) |