| 1 |
import textwrap |
| 2 |
from typing import Type |
| 3 |
|
| 4 |
from django.core.management.base import BaseCommand |
| 5 |
|
| 6 |
|
| 7 |
def command_docstring(cmd: Type[BaseCommand]) -> str: |
| 8 |
base_args = [] |
| 9 |
if cmd is not BaseCommand: |
| 10 |
base_parser = cmd().create_parser("base", "") |
| 11 |
for group in base_parser._action_groups: |
| 12 |
for action in group._group_actions: |
| 13 |
base_args.append(",".join(action.option_strings)) |
| 14 |
parser = cmd().create_parser("command", "") |
| 15 |
doc = parser.description or "" |
| 16 |
|
| 17 |
if cmd.__doc__: |
| 18 |
if doc: |
| 19 |
doc += "\n\n" |
| 20 |
doc += textwrap.dedent(cmd.__doc__) |
| 21 |
args = [] |
| 22 |
for group in parser._action_groups: |
| 23 |
for action in group._group_actions: |
| 24 |
if "--help" in action.option_strings: |
| 25 |
continue |
| 26 |
name = ",".join(action.option_strings) |
| 27 |
action_type = action.type |
| 28 |
if not action_type and action.nargs != 0: |
| 29 |
action_type = str |
| 30 |
if action_type: |
| 31 |
if isinstance(action_type, type): |
| 32 |
action_type = action_type.__name__ |
| 33 |
name += f" ({action_type})" |
| 34 |
help = action.help or "" |
| 35 |
if help and not action.required and action.nargs != 0: |
| 36 |
if not help.endswith("."): |
| 37 |
help += "." |
| 38 |
if action.default is not None: |
| 39 |
help += f" Defaults to {action.default}." |
| 40 |
else: |
| 41 |
help += " Optional." |
| 42 |
args.append((name, help)) |
| 43 |
|
| 44 |
args.sort(key=lambda o: (o[0] in base_args, o[0])) |
| 45 |
if args: |
| 46 |
doc += "\n\nAttributes:" |
| 47 |
for name, description in args: |
| 48 |
doc += f"\n {name}: {description}" |
| 49 |
return doc |