__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import collections
  2. import imp
  3. from importlib import import_module
  4. from optparse import OptionParser, NO_DEFAULT
  5. import os
  6. import sys
  7. from django.core.exceptions import ImproperlyConfigured
  8. from django.core.management.base import BaseCommand, CommandError, handle_default_options
  9. from django.core.management.color import color_style
  10. from django.utils import six
  11. # For backwards compatibility: get_version() used to be in this module.
  12. from django import get_version
  13. # A cache of loaded commands, so that call_command
  14. # doesn't have to reload every time it's called.
  15. _commands = None
  16. def find_commands(management_dir):
  17. """
  18. Given a path to a management directory, returns a list of all the command
  19. names that are available.
  20. Returns an empty list if no commands are defined.
  21. """
  22. command_dir = os.path.join(management_dir, 'commands')
  23. try:
  24. return [f[:-3] for f in os.listdir(command_dir)
  25. if not f.startswith('_') and f.endswith('.py')]
  26. except OSError:
  27. return []
  28. def find_management_module(app_name):
  29. """
  30. Determines the path to the management module for the given app_name,
  31. without actually importing the application or the management module.
  32. Raises ImportError if the management module cannot be found for any reason.
  33. """
  34. parts = app_name.split('.')
  35. parts.append('management')
  36. parts.reverse()
  37. part = parts.pop()
  38. path = None
  39. # When using manage.py, the project module is added to the path,
  40. # loaded, then removed from the path. This means that
  41. # testproject.testapp.models can be loaded in future, even if
  42. # testproject isn't in the path. When looking for the management
  43. # module, we need look for the case where the project name is part
  44. # of the app_name but the project directory itself isn't on the path.
  45. try:
  46. f, path, descr = imp.find_module(part, path)
  47. except ImportError as e:
  48. if os.path.basename(os.getcwd()) != part:
  49. raise e
  50. else:
  51. if f:
  52. f.close()
  53. while parts:
  54. part = parts.pop()
  55. f, path, descr = imp.find_module(part, [path] if path else None)
  56. if f:
  57. f.close()
  58. return path
  59. def load_command_class(app_name, name):
  60. """
  61. Given a command name and an application name, returns the Command
  62. class instance. All errors raised by the import process
  63. (ImportError, AttributeError) are allowed to propagate.
  64. """
  65. module = import_module('%s.management.commands.%s' % (app_name, name))
  66. return module.Command()
  67. def get_commands():
  68. """
  69. Returns a dictionary mapping command names to their callback applications.
  70. This works by looking for a management.commands package in django.core, and
  71. in each installed application -- if a commands package exists, all commands
  72. in that package are registered.
  73. Core commands are always included. If a settings module has been
  74. specified, user-defined commands will also be included.
  75. The dictionary is in the format {command_name: app_name}. Key-value
  76. pairs from this dictionary can then be used in calls to
  77. load_command_class(app_name, command_name)
  78. If a specific version of a command must be loaded (e.g., with the
  79. startapp command), the instantiated module can be placed in the
  80. dictionary in place of the application name.
  81. The dictionary is cached on the first call and reused on subsequent
  82. calls.
  83. """
  84. global _commands
  85. if _commands is None:
  86. _commands = dict((name, 'django.core') for name in find_commands(__path__[0]))
  87. # Find the installed apps
  88. from django.conf import settings
  89. try:
  90. apps = settings.INSTALLED_APPS
  91. except ImproperlyConfigured:
  92. # Still useful for commands that do not require functional settings,
  93. # like startproject or help
  94. apps = []
  95. # Find and load the management module for each installed app.
  96. for app_name in apps:
  97. try:
  98. path = find_management_module(app_name)
  99. _commands.update(dict((name, app_name)
  100. for name in find_commands(path)))
  101. except ImportError:
  102. pass # No management module - ignore this app
  103. return _commands
  104. def call_command(name, *args, **options):
  105. """
  106. Calls the given command, with the given options and args/kwargs.
  107. This is the primary API you should use for calling specific commands.
  108. Some examples:
  109. call_command('syncdb')
  110. call_command('shell', plain=True)
  111. call_command('sqlall', 'myapp')
  112. """
  113. # Load the command object.
  114. try:
  115. app_name = get_commands()[name]
  116. except KeyError:
  117. raise CommandError("Unknown command: %r" % name)
  118. if isinstance(app_name, BaseCommand):
  119. # If the command is already loaded, use it directly.
  120. klass = app_name
  121. else:
  122. klass = load_command_class(app_name, name)
  123. # Grab out a list of defaults from the options. optparse does this for us
  124. # when the script runs from the command line, but since call_command can
  125. # be called programmatically, we need to simulate the loading and handling
  126. # of defaults (see #10080 for details).
  127. defaults = {}
  128. for opt in klass.option_list:
  129. if opt.default is NO_DEFAULT:
  130. defaults[opt.dest] = None
  131. else:
  132. defaults[opt.dest] = opt.default
  133. defaults.update(options)
  134. return klass.execute(*args, **defaults)
  135. class LaxOptionParser(OptionParser):
  136. """
  137. An option parser that doesn't raise any errors on unknown options.
  138. This is needed because the --settings and --pythonpath options affect
  139. the commands (and thus the options) that are available to the user.
  140. """
  141. def error(self, msg):
  142. pass
  143. def print_help(self):
  144. """Output nothing.
  145. The lax options are included in the normal option parser, so under
  146. normal usage, we don't need to print the lax options.
  147. """
  148. pass
  149. def print_lax_help(self):
  150. """Output the basic options available to every command.
  151. This just redirects to the default print_help() behavior.
  152. """
  153. OptionParser.print_help(self)
  154. def _process_args(self, largs, rargs, values):
  155. """
  156. Overrides OptionParser._process_args to exclusively handle default
  157. options and ignore args and other options.
  158. This overrides the behavior of the super class, which stop parsing
  159. at the first unrecognized option.
  160. """
  161. while rargs:
  162. arg = rargs[0]
  163. try:
  164. if arg[0:2] == "--" and len(arg) > 2:
  165. # process a single long option (possibly with value(s))
  166. # the superclass code pops the arg off rargs
  167. self._process_long_opt(rargs, values)
  168. elif arg[:1] == "-" and len(arg) > 1:
  169. # process a cluster of short options (possibly with
  170. # value(s) for the last one only)
  171. # the superclass code pops the arg off rargs
  172. self._process_short_opts(rargs, values)
  173. else:
  174. # it's either a non-default option or an arg
  175. # either way, add it to the args list so we can keep
  176. # dealing with options
  177. del rargs[0]
  178. raise Exception
  179. except: # Needed because we might need to catch a SystemExit
  180. largs.append(arg)
  181. class ManagementUtility(object):
  182. """
  183. Encapsulates the logic of the django-admin.py and manage.py utilities.
  184. A ManagementUtility has a number of commands, which can be manipulated
  185. by editing the self.commands dictionary.
  186. """
  187. def __init__(self, argv=None):
  188. self.argv = argv or sys.argv[:]
  189. self.prog_name = os.path.basename(self.argv[0])
  190. def main_help_text(self, commands_only=False):
  191. """
  192. Returns the script's main help text, as a string.
  193. """
  194. if commands_only:
  195. usage = sorted(get_commands().keys())
  196. else:
  197. usage = [
  198. "",
  199. "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
  200. "",
  201. "Available subcommands:",
  202. ]
  203. commands_dict = collections.defaultdict(lambda: [])
  204. for name, app in six.iteritems(get_commands()):
  205. if app == 'django.core':
  206. app = 'django'
  207. else:
  208. app = app.rpartition('.')[-1]
  209. commands_dict[app].append(name)
  210. style = color_style()
  211. for app in sorted(commands_dict.keys()):
  212. usage.append("")
  213. usage.append(style.NOTICE("[%s]" % app))
  214. for name in sorted(commands_dict[app]):
  215. usage.append(" %s" % name)
  216. # Output an extra note if settings are not properly configured
  217. try:
  218. from django.conf import settings
  219. settings.INSTALLED_APPS
  220. except ImproperlyConfigured as e:
  221. usage.append(style.NOTICE(
  222. "Note that only Django core commands are listed as settings "
  223. "are not properly configured (error: %s)." % e))
  224. return '\n'.join(usage)
  225. def fetch_command(self, subcommand):
  226. """
  227. Tries to fetch the given subcommand, printing a message with the
  228. appropriate command called from the command line (usually
  229. "django-admin.py" or "manage.py") if it can't be found.
  230. """
  231. # Get commands outside of try block to prevent swallowing exceptions
  232. commands = get_commands()
  233. try:
  234. app_name = commands[subcommand]
  235. except KeyError:
  236. sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
  237. (subcommand, self.prog_name))
  238. sys.exit(1)
  239. if isinstance(app_name, BaseCommand):
  240. # If the command is already loaded, use it directly.
  241. klass = app_name
  242. else:
  243. klass = load_command_class(app_name, subcommand)
  244. return klass
  245. def autocomplete(self):
  246. """
  247. Output completion suggestions for BASH.
  248. The output of this function is passed to BASH's `COMREPLY` variable and
  249. treated as completion suggestions. `COMREPLY` expects a space
  250. separated string as the result.
  251. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used
  252. to get information about the cli input. Please refer to the BASH
  253. man-page for more information about this variables.
  254. Subcommand options are saved as pairs. A pair consists of
  255. the long option string (e.g. '--exclude') and a boolean
  256. value indicating if the option requires arguments. When printing to
  257. stdout, a equal sign is appended to options which require arguments.
  258. Note: If debugging this function, it is recommended to write the debug
  259. output in a separate file. Otherwise the debug output will be treated
  260. and formatted as potential completion suggestions.
  261. """
  262. # Don't complete if user hasn't sourced bash_completion file.
  263. if 'DJANGO_AUTO_COMPLETE' not in os.environ:
  264. return
  265. cwords = os.environ['COMP_WORDS'].split()[1:]
  266. cword = int(os.environ['COMP_CWORD'])
  267. try:
  268. curr = cwords[cword-1]
  269. except IndexError:
  270. curr = ''
  271. subcommands = list(get_commands()) + ['help']
  272. options = [('--help', None)]
  273. # subcommand
  274. if cword == 1:
  275. print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
  276. # subcommand options
  277. # special case: the 'help' subcommand has no options
  278. elif cwords[0] in subcommands and cwords[0] != 'help':
  279. subcommand_cls = self.fetch_command(cwords[0])
  280. # special case: 'runfcgi' stores additional options as
  281. # 'key=value' pairs
  282. if cwords[0] == 'runfcgi':
  283. from django.core.servers.fastcgi import FASTCGI_OPTIONS
  284. options += [(k, 1) for k in FASTCGI_OPTIONS]
  285. # special case: add the names of installed apps to options
  286. elif cwords[0] in ('dumpdata', 'sql', 'sqlall', 'sqlclear',
  287. 'sqlcustom', 'sqlindexes', 'sqlsequencereset', 'test'):
  288. try:
  289. from django.conf import settings
  290. # Get the last part of the dotted path as the app name.
  291. options += [(a.split('.')[-1], 0) for a in settings.INSTALLED_APPS]
  292. except ImportError:
  293. # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The
  294. # user will find out once they execute the command.
  295. pass
  296. options += [(s_opt.get_opt_string(), s_opt.nargs) for s_opt in
  297. subcommand_cls.option_list]
  298. # filter out previously specified options from available options
  299. prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]]
  300. options = [opt for opt in options if opt[0] not in prev_opts]
  301. # filter options by current input
  302. options = sorted((k, v) for k, v in options if k.startswith(curr))
  303. for option in options:
  304. opt_label = option[0]
  305. # append '=' to options which require args
  306. if option[1]:
  307. opt_label += '='
  308. print(opt_label)
  309. sys.exit(1)
  310. def execute(self):
  311. """
  312. Given the command-line arguments, this figures out which subcommand is
  313. being run, creates a parser appropriate to that command, and runs it.
  314. """
  315. # Preprocess options to extract --settings and --pythonpath.
  316. # These options could affect the commands that are available, so they
  317. # must be processed early.
  318. parser = LaxOptionParser(usage="%prog subcommand [options] [args]",
  319. version=get_version(),
  320. option_list=BaseCommand.option_list)
  321. self.autocomplete()
  322. try:
  323. options, args = parser.parse_args(self.argv)
  324. handle_default_options(options)
  325. except: # Needed because parser.parse_args can raise SystemExit
  326. pass # Ignore any option errors at this point.
  327. try:
  328. subcommand = self.argv[1]
  329. except IndexError:
  330. subcommand = 'help' # Display help if no arguments were given.
  331. if subcommand == 'help':
  332. if len(args) <= 2:
  333. parser.print_lax_help()
  334. sys.stdout.write(self.main_help_text() + '\n')
  335. elif args[2] == '--commands':
  336. sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
  337. else:
  338. self.fetch_command(args[2]).print_help(self.prog_name, args[2])
  339. elif subcommand == 'version':
  340. sys.stdout.write(parser.get_version() + '\n')
  341. # Special-cases: We want 'django-admin.py --version' and
  342. # 'django-admin.py --help' to work, for backwards compatibility.
  343. elif self.argv[1:] == ['--version']:
  344. # LaxOptionParser already takes care of printing the version.
  345. pass
  346. elif self.argv[1:] in (['--help'], ['-h']):
  347. parser.print_lax_help()
  348. sys.stdout.write(self.main_help_text() + '\n')
  349. else:
  350. self.fetch_command(subcommand).run_from_argv(self.argv)
  351. def execute_from_command_line(argv=None):
  352. """
  353. A simple method that runs a ManagementUtility.
  354. """
  355. utility = ManagementUtility(argv)
  356. utility.execute()