| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import Any |
| 4 |
|
| 5 |
from argparse import Action, Namespace |
| 6 |
|
| 7 |
from django.core.management.base import CommandParser |
| 8 |
from django.core.management.commands.loaddata import Command as LoadDataCommand |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
from modeltranslation import settings as mt_settings |
| 13 |
from modeltranslation.utils import auto_populate |
| 14 |
from modeltranslation._typing import AutoPopulate |
| 15 |
|
| 16 |
ALLOWED = (None, False, "all", "default", "required") |
| 17 |
ALLOWED_FOR_PRINT = ", ".join(str(i) for i in (0,) + ALLOWED[1:]) |
| 18 |
|
| 19 |
|
| 20 |
def check_mode( |
| 21 |
option: Command.CheckAction, |
| 22 |
opt_str: str | None, |
| 23 |
value: str, |
| 24 |
parser: CommandParser, |
| 25 |
namespace: Namespace | None = None, |
| 26 |
) -> None: |
| 27 |
if value == "0" or value.lower() == "false": |
| 28 |
value = False |
| 29 |
if value not in ALLOWED: |
| 30 |
raise ValueError("{} option can be only one of: {}".format(opt_str, ALLOWED_FOR_PRINT)) |
| 31 |
setattr(namespace or parser.values, option.dest, value) |
| 32 |
|
| 33 |
|
| 34 |
class Command(LoadDataCommand): |
| 35 |
leave_locale_alone = mt_settings.LOADDATA_RETAIN_LOCALE |
| 36 |
|
| 37 |
class CheckAction(Action): |
| 38 |
def __call__( |
| 39 |
self, |
| 40 |
parser: CommandParser, |
| 41 |
namespace: Namespace, |
| 42 |
value: str, |
| 43 |
option_string: str | None = None, |
| 44 |
) -> None: |
| 45 |
check_mode(self, option_string, value, parser, namespace) |
| 46 |
|
| 47 |
def add_arguments(self, parser: CommandParser) -> None: |
| 48 |
super().add_arguments(parser) |
| 49 |
parser.add_argument( |
| 50 |
"--populate", |
| 51 |
action=self.CheckAction, |
| 52 |
type=str, |
| 53 |
dest="populate", |
| 54 |
metavar="MODE", |
| 55 |
help=( |
| 56 |
"Using this option will cause fixtures to be loaded under auto-population MODE. " |
| 57 |
+ "Allowed values are: %s" % ALLOWED_FOR_PRINT |
| 58 |
), |
| 59 |
) |
| 60 |
|
| 61 |
def handle(self, *fixture_labels: Any, **options: Any) -> str | None: |
| 62 |
mode: AutoPopulate | None = options.get("populate") |
| 63 |
if mode is not None: |
| 64 |
with auto_populate(mode): |
| 65 |
return super().handle(*fixture_labels, **options) |
| 66 |
else: |
| 67 |
return super().handle(*fixture_labels, **options) |