|
5 | 5 | import code |
6 | 6 | import warnings |
7 | 7 | import string |
| 8 | +import inspect |
8 | 9 |
|
9 | 10 | import argparse |
10 | 11 |
|
11 | 12 | from flask import _request_ctx_stack |
12 | 13 |
|
13 | 14 | from .cli import prompt, prompt_pass, prompt_bool, prompt_choices |
| 15 | +from ._compat import izip, text_type |
14 | 16 |
|
15 | 17 |
|
16 | 18 | class InvalidCommand(Exception): |
@@ -90,11 +92,56 @@ def __init__(self, *args, **kwargs): |
90 | 92 | class Command(object): |
91 | 93 | """ |
92 | 94 | Base class for creating commands. |
| 95 | +
|
| 96 | + :param func: Initialize this command by introspecting the function. |
93 | 97 | """ |
94 | 98 |
|
95 | 99 | option_list = [] |
96 | 100 | add_help = True |
97 | 101 |
|
| 102 | + def __init__(self, func=None): |
| 103 | + if func is None: |
| 104 | + return |
| 105 | + |
| 106 | + args, varargs, keywords, defaults = inspect.getargspec(func) |
| 107 | + if inspect.ismethod(func): |
| 108 | + args = args[1:] |
| 109 | + |
| 110 | + options = [] |
| 111 | + |
| 112 | + # first arg is always "app" : ignore |
| 113 | + |
| 114 | + defaults = defaults or [] |
| 115 | + kwargs = dict(izip(*[reversed(l) for l in (args, defaults)])) |
| 116 | + |
| 117 | + for arg in args: |
| 118 | + |
| 119 | + if arg in kwargs: |
| 120 | + |
| 121 | + default = kwargs[arg] |
| 122 | + |
| 123 | + if isinstance(default, bool): |
| 124 | + options.append(Option('-%s' % arg[0], |
| 125 | + '--%s' % arg, |
| 126 | + action="store_true", |
| 127 | + dest=arg, |
| 128 | + required=False, |
| 129 | + default=default)) |
| 130 | + else: |
| 131 | + options.append(Option('-%s' % arg[0], |
| 132 | + '--%s' % arg, |
| 133 | + dest=arg, |
| 134 | + type=text_type, |
| 135 | + required=False, |
| 136 | + default=default)) |
| 137 | + |
| 138 | + else: |
| 139 | + options.append(Option(arg, type=text_type)) |
| 140 | + |
| 141 | + self.run = func |
| 142 | + self.__doc__ = func.__doc__ |
| 143 | + self.option_list = options |
| 144 | + |
98 | 145 | @property |
99 | 146 | def description(self): |
100 | 147 | description = self.__doc__ or '' |
|
0 commit comments