collectstatic.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import os
  2. from django.apps import apps
  3. from django.contrib.staticfiles.finders import get_finders
  4. from django.contrib.staticfiles.storage import staticfiles_storage
  5. from django.core.files.storage import FileSystemStorage
  6. from django.core.management.base import BaseCommand, CommandError
  7. from django.core.management.color import no_style
  8. from django.utils.functional import cached_property
  9. class Command(BaseCommand):
  10. """
  11. Copies or symlinks static files from different locations to the
  12. settings.STATIC_ROOT.
  13. """
  14. help = "Collect static files in a single location."
  15. requires_system_checks = False
  16. def __init__(self, *args, **kwargs):
  17. super().__init__(*args, **kwargs)
  18. self.copied_files = []
  19. self.symlinked_files = []
  20. self.unmodified_files = []
  21. self.post_processed_files = []
  22. self.storage = staticfiles_storage
  23. self.style = no_style()
  24. @cached_property
  25. def local(self):
  26. try:
  27. self.storage.path('')
  28. except NotImplementedError:
  29. return False
  30. return True
  31. def add_arguments(self, parser):
  32. parser.add_argument(
  33. '--noinput', '--no-input', action='store_false', dest='interactive',
  34. help="Do NOT prompt the user for input of any kind.",
  35. )
  36. parser.add_argument(
  37. '--no-post-process', action='store_false', dest='post_process',
  38. help="Do NOT post process collected files.",
  39. )
  40. parser.add_argument(
  41. '-i', '--ignore', action='append', default=[],
  42. dest='ignore_patterns', metavar='PATTERN',
  43. help="Ignore files or directories matching this glob-style "
  44. "pattern. Use multiple times to ignore more.",
  45. )
  46. parser.add_argument(
  47. '-n', '--dry-run', action='store_true',
  48. help="Do everything except modify the filesystem.",
  49. )
  50. parser.add_argument(
  51. '-c', '--clear', action='store_true',
  52. help="Clear the existing files using the storage "
  53. "before trying to copy or link the original file.",
  54. )
  55. parser.add_argument(
  56. '-l', '--link', action='store_true',
  57. help="Create a symbolic link to each file instead of copying.",
  58. )
  59. parser.add_argument(
  60. '--no-default-ignore', action='store_false', dest='use_default_ignore_patterns',
  61. help="Don't ignore the common private glob-style patterns (defaults to 'CVS', '.*' and '*~').",
  62. )
  63. def set_options(self, **options):
  64. """
  65. Set instance variables based on an options dict
  66. """
  67. self.interactive = options['interactive']
  68. self.verbosity = options['verbosity']
  69. self.symlink = options['link']
  70. self.clear = options['clear']
  71. self.dry_run = options['dry_run']
  72. ignore_patterns = options['ignore_patterns']
  73. if options['use_default_ignore_patterns']:
  74. ignore_patterns += apps.get_app_config('staticfiles').ignore_patterns
  75. self.ignore_patterns = list(set(os.path.normpath(p) for p in ignore_patterns))
  76. self.post_process = options['post_process']
  77. def collect(self):
  78. """
  79. Perform the bulk of the work of collectstatic.
  80. Split off from handle() to facilitate testing.
  81. """
  82. if self.symlink and not self.local:
  83. raise CommandError("Can't symlink to a remote destination.")
  84. if self.clear:
  85. self.clear_dir('')
  86. if self.symlink:
  87. handler = self.link_file
  88. else:
  89. handler = self.copy_file
  90. found_files = {}
  91. for finder in get_finders():
  92. for path, storage in finder.list(self.ignore_patterns):
  93. # Prefix the relative path if the source storage contains it
  94. if getattr(storage, 'prefix', None):
  95. prefixed_path = os.path.join(storage.prefix, path)
  96. else:
  97. prefixed_path = path
  98. if prefixed_path not in found_files:
  99. found_files[prefixed_path] = (storage, path)
  100. handler(path, prefixed_path, storage)
  101. else:
  102. self.log(
  103. "Found another file with the destination path '%s'. It "
  104. "will be ignored since only the first encountered file "
  105. "is collected. If this is not what you want, make sure "
  106. "every static file has a unique path." % prefixed_path,
  107. level=1,
  108. )
  109. # Storage backends may define a post_process() method.
  110. if self.post_process and hasattr(self.storage, 'post_process'):
  111. processor = self.storage.post_process(found_files,
  112. dry_run=self.dry_run)
  113. for original_path, processed_path, processed in processor:
  114. if isinstance(processed, Exception):
  115. self.stderr.write("Post-processing '%s' failed!" % original_path)
  116. # Add a blank line before the traceback, otherwise it's
  117. # too easy to miss the relevant part of the error message.
  118. self.stderr.write("")
  119. raise processed
  120. if processed:
  121. self.log("Post-processed '%s' as '%s'" %
  122. (original_path, processed_path), level=2)
  123. self.post_processed_files.append(original_path)
  124. else:
  125. self.log("Skipped post-processing '%s'" % original_path)
  126. return {
  127. 'modified': self.copied_files + self.symlinked_files,
  128. 'unmodified': self.unmodified_files,
  129. 'post_processed': self.post_processed_files,
  130. }
  131. def handle(self, **options):
  132. self.set_options(**options)
  133. message = ['\n']
  134. if self.dry_run:
  135. message.append(
  136. 'You have activated the --dry-run option so no files will be modified.\n\n'
  137. )
  138. message.append(
  139. 'You have requested to collect static files at the destination\n'
  140. 'location as specified in your settings'
  141. )
  142. if self.is_local_storage() and self.storage.location:
  143. destination_path = self.storage.location
  144. message.append(':\n\n %s\n\n' % destination_path)
  145. should_warn_user = (
  146. self.storage.exists(destination_path) and
  147. any(self.storage.listdir(destination_path))
  148. )
  149. else:
  150. destination_path = None
  151. message.append('.\n\n')
  152. # Destination files existence not checked; play it safe and warn.
  153. should_warn_user = True
  154. if self.interactive and should_warn_user:
  155. if self.clear:
  156. message.append('This will DELETE ALL FILES in this location!\n')
  157. else:
  158. message.append('This will overwrite existing files!\n')
  159. message.append(
  160. 'Are you sure you want to do this?\n\n'
  161. "Type 'yes' to continue, or 'no' to cancel: "
  162. )
  163. if input(''.join(message)) != 'yes':
  164. raise CommandError("Collecting static files cancelled.")
  165. collected = self.collect()
  166. modified_count = len(collected['modified'])
  167. unmodified_count = len(collected['unmodified'])
  168. post_processed_count = len(collected['post_processed'])
  169. if self.verbosity >= 1:
  170. template = ("\n%(modified_count)s %(identifier)s %(action)s"
  171. "%(destination)s%(unmodified)s%(post_processed)s.\n")
  172. summary = template % {
  173. 'modified_count': modified_count,
  174. 'identifier': 'static file' + ('' if modified_count == 1 else 's'),
  175. 'action': 'symlinked' if self.symlink else 'copied',
  176. 'destination': (" to '%s'" % destination_path if destination_path else ''),
  177. 'unmodified': (', %s unmodified' % unmodified_count if collected['unmodified'] else ''),
  178. 'post_processed': (collected['post_processed'] and
  179. ', %s post-processed'
  180. % post_processed_count or ''),
  181. }
  182. return summary
  183. def log(self, msg, level=2):
  184. """
  185. Small log helper
  186. """
  187. if self.verbosity >= level:
  188. self.stdout.write(msg)
  189. def is_local_storage(self):
  190. return isinstance(self.storage, FileSystemStorage)
  191. def clear_dir(self, path):
  192. """
  193. Delete the given relative path using the destination storage backend.
  194. """
  195. if not self.storage.exists(path):
  196. return
  197. dirs, files = self.storage.listdir(path)
  198. for f in files:
  199. fpath = os.path.join(path, f)
  200. if self.dry_run:
  201. self.log("Pretending to delete '%s'" % fpath, level=1)
  202. else:
  203. self.log("Deleting '%s'" % fpath, level=1)
  204. try:
  205. full_path = self.storage.path(fpath)
  206. except NotImplementedError:
  207. self.storage.delete(fpath)
  208. else:
  209. if not os.path.exists(full_path) and os.path.lexists(full_path):
  210. # Delete broken symlinks
  211. os.unlink(full_path)
  212. else:
  213. self.storage.delete(fpath)
  214. for d in dirs:
  215. self.clear_dir(os.path.join(path, d))
  216. def delete_file(self, path, prefixed_path, source_storage):
  217. """
  218. Check if the target file should be deleted if it already exists.
  219. """
  220. if self.storage.exists(prefixed_path):
  221. try:
  222. # When was the target file modified last time?
  223. target_last_modified = self.storage.get_modified_time(prefixed_path)
  224. except (OSError, NotImplementedError, AttributeError):
  225. # The storage doesn't support get_modified_time() or failed
  226. pass
  227. else:
  228. try:
  229. # When was the source file modified last time?
  230. source_last_modified = source_storage.get_modified_time(path)
  231. except (OSError, NotImplementedError, AttributeError):
  232. pass
  233. else:
  234. # The full path of the target file
  235. if self.local:
  236. full_path = self.storage.path(prefixed_path)
  237. # If it's --link mode and the path isn't a link (i.e.
  238. # the previous collectstatic wasn't with --link) or if
  239. # it's non-link mode and the path is a link (i.e. the
  240. # previous collectstatic was with --link), the old
  241. # links/files must be deleted so it's not safe to skip
  242. # unmodified files.
  243. can_skip_unmodified_files = not (self.symlink ^ os.path.islink(full_path))
  244. else:
  245. # In remote storages, skipping is only based on the
  246. # modified times since symlinks aren't relevant.
  247. can_skip_unmodified_files = True
  248. # Avoid sub-second precision (see #14665, #19540)
  249. file_is_unmodified = (
  250. target_last_modified.replace(microsecond=0) >=
  251. source_last_modified.replace(microsecond=0)
  252. )
  253. if file_is_unmodified and can_skip_unmodified_files:
  254. if prefixed_path not in self.unmodified_files:
  255. self.unmodified_files.append(prefixed_path)
  256. self.log("Skipping '%s' (not modified)" % path)
  257. return False
  258. # Then delete the existing file if really needed
  259. if self.dry_run:
  260. self.log("Pretending to delete '%s'" % path)
  261. else:
  262. self.log("Deleting '%s'" % path)
  263. self.storage.delete(prefixed_path)
  264. return True
  265. def link_file(self, path, prefixed_path, source_storage):
  266. """
  267. Attempt to link ``path``
  268. """
  269. # Skip this file if it was already copied earlier
  270. if prefixed_path in self.symlinked_files:
  271. return self.log("Skipping '%s' (already linked earlier)" % path)
  272. # Delete the target file if needed or break
  273. if not self.delete_file(path, prefixed_path, source_storage):
  274. return
  275. # The full path of the source file
  276. source_path = source_storage.path(path)
  277. # Finally link the file
  278. if self.dry_run:
  279. self.log("Pretending to link '%s'" % source_path, level=1)
  280. else:
  281. self.log("Linking '%s'" % source_path, level=2)
  282. full_path = self.storage.path(prefixed_path)
  283. os.makedirs(os.path.dirname(full_path), exist_ok=True)
  284. try:
  285. if os.path.lexists(full_path):
  286. os.unlink(full_path)
  287. os.symlink(source_path, full_path)
  288. except AttributeError:
  289. import platform
  290. raise CommandError("Symlinking is not supported by Python %s." %
  291. platform.python_version())
  292. except NotImplementedError:
  293. import platform
  294. raise CommandError("Symlinking is not supported in this "
  295. "platform (%s)." % platform.platform())
  296. except OSError as e:
  297. raise CommandError(e)
  298. if prefixed_path not in self.symlinked_files:
  299. self.symlinked_files.append(prefixed_path)
  300. def copy_file(self, path, prefixed_path, source_storage):
  301. """
  302. Attempt to copy ``path`` with storage
  303. """
  304. # Skip this file if it was already copied earlier
  305. if prefixed_path in self.copied_files:
  306. return self.log("Skipping '%s' (already copied earlier)" % path)
  307. # Delete the target file if needed or break
  308. if not self.delete_file(path, prefixed_path, source_storage):
  309. return
  310. # The full path of the source file
  311. source_path = source_storage.path(path)
  312. # Finally start copying
  313. if self.dry_run:
  314. self.log("Pretending to copy '%s'" % source_path, level=1)
  315. else:
  316. self.log("Copying '%s'" % source_path, level=2)
  317. with source_storage.open(path) as source_file:
  318. self.storage.save(prefixed_path, source_file)
  319. self.copied_files.append(prefixed_path)