2013-10-16 22:24:59 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2012-02-08 02:46:29 +08:00
|
|
|
import collections
|
2013-07-29 21:50:58 +08:00
|
|
|
from importlib import import_module
|
2007-08-16 14:06:55 +08:00
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
|
2013-12-31 20:09:47 +08:00
|
|
|
import django
|
2013-12-31 20:16:34 +08:00
|
|
|
from django.apps import apps
|
2013-12-19 22:57:23 +08:00
|
|
|
from django.conf import settings
|
2012-09-09 04:12:18 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2013-10-16 22:24:59 +08:00
|
|
|
from django.core.management.base import (BaseCommand, CommandError,
|
|
|
|
CommandParser, handle_default_options)
|
2012-02-08 02:46:29 +08:00
|
|
|
from django.core.management.color import color_style
|
2014-01-02 01:01:06 +08:00
|
|
|
from django.utils import lru_cache
|
2012-07-21 03:14:27 +08:00
|
|
|
from django.utils import six
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-09-22 00:19:20 +08:00
|
|
|
def find_commands(management_dir):
|
|
|
|
"""
|
2007-10-19 09:26:09 +08:00
|
|
|
Given a path to a management directory, returns a list of all the command
|
|
|
|
names that are available.
|
|
|
|
|
|
|
|
Returns an empty list if no commands are defined.
|
2007-08-16 14:06:55 +08:00
|
|
|
"""
|
2007-10-19 09:26:09 +08:00
|
|
|
command_dir = os.path.join(management_dir, 'commands')
|
2007-09-22 00:19:20 +08:00
|
|
|
try:
|
2007-10-19 09:26:09 +08:00
|
|
|
return [f[:-3] for f in os.listdir(command_dir)
|
|
|
|
if not f.startswith('_') and f.endswith('.py')]
|
2007-09-22 00:19:20 +08:00
|
|
|
except OSError:
|
|
|
|
return []
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-09-22 00:19:20 +08:00
|
|
|
def load_command_class(app_name, name):
|
|
|
|
"""
|
2007-10-19 09:26:09 +08:00
|
|
|
Given a command name and an application name, returns the Command
|
2007-12-04 13:46:46 +08:00
|
|
|
class instance. All errors raised by the import process
|
2007-09-22 00:19:20 +08:00
|
|
|
(ImportError, AttributeError) are allowed to propagate.
|
|
|
|
"""
|
2009-03-19 00:55:59 +08:00
|
|
|
module = import_module('%s.management.commands.%s' % (app_name, name))
|
|
|
|
return module.Command()
|
2007-09-22 00:19:20 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2014-01-02 01:01:06 +08:00
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
2008-08-10 16:42:49 +08:00
|
|
|
def get_commands():
|
2007-09-22 00:19:20 +08:00
|
|
|
"""
|
2007-12-04 13:46:46 +08:00
|
|
|
Returns a dictionary mapping command names to their callback applications.
|
|
|
|
|
|
|
|
This works by looking for a management.commands package in django.core, and
|
|
|
|
in each installed application -- if a commands package exists, all commands
|
|
|
|
in that package are registered.
|
2007-09-22 00:19:20 +08:00
|
|
|
|
2007-11-26 20:32:57 +08:00
|
|
|
Core commands are always included. If a settings module has been
|
2011-12-23 06:38:02 +08:00
|
|
|
specified, user-defined commands will also be included.
|
2007-09-22 00:19:20 +08:00
|
|
|
|
|
|
|
The dictionary is in the format {command_name: app_name}. Key-value
|
2007-10-19 09:26:09 +08:00
|
|
|
pairs from this dictionary can then be used in calls to
|
2007-09-22 00:19:20 +08:00
|
|
|
load_command_class(app_name, command_name)
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2007-09-22 01:52:36 +08:00
|
|
|
If a specific version of a command must be loaded (e.g., with the
|
|
|
|
startapp command), the instantiated module can be placed in the
|
|
|
|
dictionary in place of the application name.
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2007-12-04 13:46:46 +08:00
|
|
|
The dictionary is cached on the first call and reused on subsequent
|
2007-09-22 00:19:20 +08:00
|
|
|
calls.
|
|
|
|
"""
|
2014-01-02 01:01:06 +08:00
|
|
|
commands = {name: 'django.core' for name in find_commands(__path__[0])}
|
2007-12-04 13:53:33 +08:00
|
|
|
|
2014-05-28 00:57:53 +08:00
|
|
|
if not settings.configured:
|
|
|
|
return commands
|
|
|
|
|
2014-05-28 06:28:13 +08:00
|
|
|
for app_config in reversed(list(apps.get_app_configs())):
|
2014-05-28 04:18:51 +08:00
|
|
|
path = os.path.join(app_config.path, 'management')
|
|
|
|
commands.update({name: app_config.name for name in find_commands(path)})
|
2014-01-02 01:01:06 +08:00
|
|
|
|
|
|
|
return commands
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
def call_command(name, *args, **options):
|
|
|
|
"""
|
|
|
|
Calls the given command, with the given options and args/kwargs.
|
2007-09-10 05:57:59 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
This is the primary API you should use for calling specific commands.
|
2007-09-10 05:57:59 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
Some examples:
|
|
|
|
call_command('syncdb')
|
|
|
|
call_command('shell', plain=True)
|
|
|
|
call_command('sqlall', 'myapp')
|
|
|
|
"""
|
2009-04-06 01:27:26 +08:00
|
|
|
# Load the command object.
|
2007-09-22 00:19:20 +08:00
|
|
|
try:
|
|
|
|
app_name = get_commands()[name]
|
|
|
|
except KeyError:
|
2010-01-11 02:36:20 +08:00
|
|
|
raise CommandError("Unknown command: %r" % name)
|
2009-04-06 01:27:26 +08:00
|
|
|
|
2012-11-08 01:24:49 +08:00
|
|
|
if isinstance(app_name, BaseCommand):
|
|
|
|
# If the command is already loaded, use it directly.
|
2013-10-16 22:24:59 +08:00
|
|
|
command = app_name
|
2012-11-08 01:24:49 +08:00
|
|
|
else:
|
2013-10-16 22:24:59 +08:00
|
|
|
command = load_command_class(app_name, name)
|
2008-09-01 02:21:06 +08:00
|
|
|
|
2013-10-16 22:24:59 +08:00
|
|
|
# Simulate argument parsing to get the option defaults (see #10080 for details).
|
|
|
|
parser = command.create_parser('', name)
|
|
|
|
if command.use_argparse:
|
2014-08-10 03:03:19 +08:00
|
|
|
# Use the `dest` option name from the parser option
|
|
|
|
opt_mapping = dict((sorted(s_opt.option_strings)[0].lstrip('-').replace('-', '_'), s_opt.dest)
|
2014-08-14 00:33:18 +08:00
|
|
|
for s_opt in parser._actions if s_opt.option_strings)
|
2014-08-10 03:03:19 +08:00
|
|
|
arg_options = dict((opt_mapping.get(key, key), value) for key, value in options.items())
|
2013-10-16 22:24:59 +08:00
|
|
|
defaults = parser.parse_args(args=args)
|
2014-08-10 03:03:19 +08:00
|
|
|
defaults = dict(defaults._get_kwargs(), **arg_options)
|
2014-08-18 06:29:49 +08:00
|
|
|
# Move positional args out of options to mimic legacy optparse
|
|
|
|
args = defaults.pop('args', ())
|
2013-10-16 22:24:59 +08:00
|
|
|
else:
|
|
|
|
# Legacy optparse method
|
|
|
|
defaults, _ = parser.parse_args(args=[])
|
|
|
|
defaults = dict(defaults.__dict__, **options)
|
2014-10-20 03:17:38 +08:00
|
|
|
if 'skip_checks' not in options:
|
|
|
|
defaults['skip_checks'] = True
|
2008-09-01 02:21:06 +08:00
|
|
|
|
2013-10-16 22:24:59 +08:00
|
|
|
return command.execute(*args, **defaults)
|
2007-09-05 22:01:31 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
class ManagementUtility(object):
|
|
|
|
"""
|
2014-07-26 19:21:52 +08:00
|
|
|
Encapsulates the logic of the django-admin and manage.py utilities.
|
2007-08-16 14:06:55 +08:00
|
|
|
|
|
|
|
A ManagementUtility has a number of commands, which can be manipulated
|
|
|
|
by editing the self.commands dictionary.
|
|
|
|
"""
|
2007-09-11 12:24:35 +08:00
|
|
|
def __init__(self, argv=None):
|
|
|
|
self.argv = argv or sys.argv[:]
|
|
|
|
self.prog_name = os.path.basename(self.argv[0])
|
2014-05-28 00:57:53 +08:00
|
|
|
self.settings_exception = None
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2012-02-08 02:46:29 +08:00
|
|
|
def main_help_text(self, commands_only=False):
|
2007-08-16 14:06:55 +08:00
|
|
|
"""
|
2007-09-11 12:24:35 +08:00
|
|
|
Returns the script's main help text, as a string.
|
2007-08-16 14:06:55 +08:00
|
|
|
"""
|
2012-02-08 02:46:29 +08:00
|
|
|
if commands_only:
|
|
|
|
usage = sorted(get_commands().keys())
|
|
|
|
else:
|
|
|
|
usage = [
|
|
|
|
"",
|
|
|
|
"Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
|
|
|
|
"",
|
|
|
|
"Available subcommands:",
|
|
|
|
]
|
|
|
|
commands_dict = collections.defaultdict(lambda: [])
|
2012-07-21 03:14:27 +08:00
|
|
|
for name, app in six.iteritems(get_commands()):
|
2012-02-08 02:46:29 +08:00
|
|
|
if app == 'django.core':
|
|
|
|
app = 'django'
|
|
|
|
else:
|
|
|
|
app = app.rpartition('.')[-1]
|
|
|
|
commands_dict[app].append(name)
|
|
|
|
style = color_style()
|
|
|
|
for app in sorted(commands_dict.keys()):
|
|
|
|
usage.append("")
|
|
|
|
usage.append(style.NOTICE("[%s]" % app))
|
|
|
|
for name in sorted(commands_dict[app]):
|
|
|
|
usage.append(" %s" % name)
|
2013-10-22 03:21:49 +08:00
|
|
|
# Output an extra note if settings are not properly configured
|
2014-05-28 00:57:53 +08:00
|
|
|
if self.settings_exception is not None:
|
2013-10-22 03:21:49 +08:00
|
|
|
usage.append(style.NOTICE(
|
2014-05-28 00:57:53 +08:00
|
|
|
"Note that only Django core commands are listed "
|
|
|
|
"as settings are not properly configured (error: %s)."
|
|
|
|
% self.settings_exception))
|
2013-10-22 03:21:49 +08:00
|
|
|
|
2007-09-11 12:24:35 +08:00
|
|
|
return '\n'.join(usage)
|
2007-09-10 05:57:59 +08:00
|
|
|
|
2007-09-11 12:24:35 +08:00
|
|
|
def fetch_command(self, subcommand):
|
2007-09-10 05:57:59 +08:00
|
|
|
"""
|
|
|
|
Tries to fetch the given subcommand, printing a message with the
|
|
|
|
appropriate command called from the command line (usually
|
2014-07-26 19:21:52 +08:00
|
|
|
"django-admin" or "manage.py") if it can't be found.
|
2007-09-10 05:57:59 +08:00
|
|
|
"""
|
2013-10-18 00:57:44 +08:00
|
|
|
# Get commands outside of try block to prevent swallowing exceptions
|
|
|
|
commands = get_commands()
|
2007-09-10 05:57:59 +08:00
|
|
|
try:
|
2013-10-18 00:57:44 +08:00
|
|
|
app_name = commands[subcommand]
|
2007-09-10 05:57:59 +08:00
|
|
|
except KeyError:
|
2014-05-11 00:40:44 +08:00
|
|
|
# This might trigger ImproperlyConfigured (masked in get_commands)
|
|
|
|
settings.INSTALLED_APPS
|
2013-10-18 08:24:41 +08:00
|
|
|
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
|
2007-12-04 13:46:46 +08:00
|
|
|
(subcommand, self.prog_name))
|
2007-09-10 05:57:59 +08:00
|
|
|
sys.exit(1)
|
2010-08-05 21:18:50 +08:00
|
|
|
if isinstance(app_name, BaseCommand):
|
|
|
|
# If the command is already loaded, use it directly.
|
|
|
|
klass = app_name
|
|
|
|
else:
|
|
|
|
klass = load_command_class(app_name, subcommand)
|
2007-09-22 00:19:20 +08:00
|
|
|
return klass
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2009-09-12 07:15:59 +08:00
|
|
|
def autocomplete(self):
|
|
|
|
"""
|
|
|
|
Output completion suggestions for BASH.
|
|
|
|
|
|
|
|
The output of this function is passed to BASH's `COMREPLY` variable and
|
|
|
|
treated as completion suggestions. `COMREPLY` expects a space
|
|
|
|
separated string as the result.
|
|
|
|
|
|
|
|
The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
|
|
|
|
to get information about the cli input. Please refer to the BASH
|
|
|
|
man-page for more information about this variables.
|
|
|
|
|
|
|
|
Subcommand options are saved as pairs. A pair consists of
|
|
|
|
the long option string (e.g. '--exclude') and a boolean
|
|
|
|
value indicating if the option requires arguments. When printing to
|
2014-05-29 08:39:14 +08:00
|
|
|
stdout, an equal sign is appended to options which require arguments.
|
2009-09-12 07:15:59 +08:00
|
|
|
|
|
|
|
Note: If debugging this function, it is recommended to write the debug
|
|
|
|
output in a separate file. Otherwise the debug output will be treated
|
|
|
|
and formatted as potential completion suggestions.
|
|
|
|
"""
|
|
|
|
# Don't complete if user hasn't sourced bash_completion file.
|
2011-09-10 03:33:40 +08:00
|
|
|
if 'DJANGO_AUTO_COMPLETE' not in os.environ:
|
2009-09-12 07:15:59 +08:00
|
|
|
return
|
|
|
|
|
|
|
|
cwords = os.environ['COMP_WORDS'].split()[1:]
|
|
|
|
cword = int(os.environ['COMP_CWORD'])
|
|
|
|
|
|
|
|
try:
|
2013-11-04 02:08:55 +08:00
|
|
|
curr = cwords[cword - 1]
|
2009-09-12 07:15:59 +08:00
|
|
|
except IndexError:
|
|
|
|
curr = ''
|
|
|
|
|
2012-08-08 22:33:15 +08:00
|
|
|
subcommands = list(get_commands()) + ['help']
|
2014-09-20 22:38:37 +08:00
|
|
|
options = [('--help', False)]
|
2009-09-12 07:15:59 +08:00
|
|
|
|
|
|
|
# subcommand
|
|
|
|
if cword == 1:
|
2012-04-29 00:02:01 +08:00
|
|
|
print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
|
2009-09-12 07:15:59 +08:00
|
|
|
# subcommand options
|
|
|
|
# special case: the 'help' subcommand has no options
|
|
|
|
elif cwords[0] in subcommands and cwords[0] != 'help':
|
|
|
|
subcommand_cls = self.fetch_command(cwords[0])
|
|
|
|
# special case: 'runfcgi' stores additional options as
|
|
|
|
# 'key=value' pairs
|
|
|
|
if cwords[0] == 'runfcgi':
|
|
|
|
from django.core.servers.fastcgi import FASTCGI_OPTIONS
|
|
|
|
options += [(k, 1) for k in FASTCGI_OPTIONS]
|
|
|
|
# special case: add the names of installed apps to options
|
2012-03-31 20:38:11 +08:00
|
|
|
elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
|
|
|
|
'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
|
2009-09-12 07:15:59 +08:00
|
|
|
try:
|
2013-12-24 19:25:17 +08:00
|
|
|
app_configs = apps.get_app_configs()
|
2009-09-12 07:15:59 +08:00
|
|
|
# Get the last part of the dotted path as the app name.
|
2013-12-19 22:57:23 +08:00
|
|
|
options += [(app_config.label, 0) for app_config in app_configs]
|
2009-09-12 07:15:59 +08:00
|
|
|
except ImportError:
|
|
|
|
# Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
|
|
|
|
# user will find out once they execute the command.
|
|
|
|
pass
|
2013-10-16 22:24:59 +08:00
|
|
|
parser = subcommand_cls.create_parser('', cwords[0])
|
|
|
|
if subcommand_cls.use_argparse:
|
|
|
|
options += [(sorted(s_opt.option_strings)[0], s_opt.nargs != 0) for s_opt in
|
|
|
|
parser._actions if s_opt.option_strings]
|
|
|
|
else:
|
|
|
|
options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in
|
|
|
|
parser.option_list]
|
2009-09-12 07:15:59 +08:00
|
|
|
# filter out previously specified options from available options
|
2013-11-04 02:08:55 +08:00
|
|
|
prev_opts = [x.split('=')[0] for x in cwords[1:cword - 1]]
|
2012-07-20 19:52:16 +08:00
|
|
|
options = [opt for opt in options if opt[0] not in prev_opts]
|
2009-09-12 07:15:59 +08:00
|
|
|
|
|
|
|
# filter options by current input
|
2013-08-30 07:20:00 +08:00
|
|
|
options = sorted((k, v) for k, v in options if k.startswith(curr))
|
2009-09-12 07:15:59 +08:00
|
|
|
for option in options:
|
|
|
|
opt_label = option[0]
|
|
|
|
# append '=' to options which require args
|
|
|
|
if option[1]:
|
|
|
|
opt_label += '='
|
2012-04-29 00:02:01 +08:00
|
|
|
print(opt_label)
|
2009-09-12 07:15:59 +08:00
|
|
|
sys.exit(1)
|
|
|
|
|
2007-09-11 12:24:35 +08:00
|
|
|
def execute(self):
|
2007-08-16 14:06:55 +08:00
|
|
|
"""
|
2007-09-11 11:46:35 +08:00
|
|
|
Given the command-line arguments, this figures out which subcommand is
|
|
|
|
being run, creates a parser appropriate to that command, and runs it.
|
2007-08-16 14:06:55 +08:00
|
|
|
"""
|
2013-10-16 22:24:59 +08:00
|
|
|
try:
|
|
|
|
subcommand = self.argv[1]
|
|
|
|
except IndexError:
|
|
|
|
subcommand = 'help' # Display help if no arguments were given.
|
|
|
|
|
2007-10-19 09:26:09 +08:00
|
|
|
# Preprocess options to extract --settings and --pythonpath.
|
|
|
|
# These options could affect the commands that are available, so they
|
|
|
|
# must be processed early.
|
2013-10-16 22:24:59 +08:00
|
|
|
parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
|
|
|
|
parser.add_argument('--settings')
|
|
|
|
parser.add_argument('--pythonpath')
|
|
|
|
parser.add_argument('args', nargs='*') # catch-all
|
2007-09-22 00:52:32 +08:00
|
|
|
try:
|
2013-10-16 22:24:59 +08:00
|
|
|
options, args = parser.parse_known_args(self.argv[2:])
|
2007-09-22 00:52:32 +08:00
|
|
|
handle_default_options(options)
|
2013-10-16 22:24:59 +08:00
|
|
|
except CommandError:
|
2013-11-03 05:02:56 +08:00
|
|
|
pass # Ignore any option errors at this point.
|
2007-10-19 09:26:09 +08:00
|
|
|
|
2014-05-28 00:57:53 +08:00
|
|
|
no_settings_commands = [
|
|
|
|
'help', 'version', '--help', '--version', '-h',
|
|
|
|
'compilemessages', 'makemessages',
|
|
|
|
'startapp', 'startproject',
|
|
|
|
]
|
|
|
|
|
2014-01-03 03:43:45 +08:00
|
|
|
try:
|
2014-01-07 05:57:56 +08:00
|
|
|
settings.INSTALLED_APPS
|
2014-05-28 00:57:53 +08:00
|
|
|
except ImproperlyConfigured as exc:
|
|
|
|
self.settings_exception = exc
|
|
|
|
# A handful of built-in management commands work without settings.
|
|
|
|
# Load the default settings -- where INSTALLED_APPS is empty.
|
|
|
|
if subcommand in no_settings_commands:
|
|
|
|
settings.configure()
|
|
|
|
|
|
|
|
if settings.configured:
|
2014-01-07 05:57:56 +08:00
|
|
|
django.setup()
|
2014-01-03 03:43:45 +08:00
|
|
|
|
2014-01-13 05:29:27 +08:00
|
|
|
self.autocomplete()
|
|
|
|
|
2007-09-10 12:33:24 +08:00
|
|
|
if subcommand == 'help':
|
2013-10-16 22:24:59 +08:00
|
|
|
if '--commands' in args:
|
2012-02-08 02:46:29 +08:00
|
|
|
sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
|
2013-10-16 22:24:59 +08:00
|
|
|
elif len(options.args) < 1:
|
|
|
|
sys.stdout.write(self.main_help_text() + '\n')
|
2012-02-08 02:46:29 +08:00
|
|
|
else:
|
2013-10-16 22:24:59 +08:00
|
|
|
self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
|
2014-07-26 19:21:52 +08:00
|
|
|
# Special-cases: We want 'django-admin --version' and
|
|
|
|
# 'django-admin --help' to work, for backwards compatibility.
|
2013-10-16 22:24:59 +08:00
|
|
|
elif subcommand == 'version' or self.argv[1:] == ['--version']:
|
|
|
|
sys.stdout.write(django.get_version() + '\n')
|
2011-02-21 21:45:57 +08:00
|
|
|
elif self.argv[1:] in (['--help'], ['-h']):
|
2011-03-27 01:45:42 +08:00
|
|
|
sys.stdout.write(self.main_help_text() + '\n')
|
2007-09-10 05:57:59 +08:00
|
|
|
else:
|
2007-09-11 12:24:35 +08:00
|
|
|
self.fetch_command(subcommand).run_from_argv(self.argv)
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2007-08-16 14:06:55 +08:00
|
|
|
def execute_from_command_line(argv=None):
|
|
|
|
"""
|
|
|
|
A simple method that runs a ManagementUtility.
|
|
|
|
"""
|
2007-09-11 12:24:35 +08:00
|
|
|
utility = ManagementUtility(argv)
|
|
|
|
utility.execute()
|