findstatic.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import unicode_literals
  2. import os
  3. from optparse import make_option
  4. from django.core.management.base import LabelCommand
  5. from django.utils.encoding import force_text
  6. from django.contrib.staticfiles import finders
  7. class Command(LabelCommand):
  8. help = "Finds the absolute paths for the given static file(s)."
  9. args = "[file ...]"
  10. label = 'static file'
  11. option_list = LabelCommand.option_list + (
  12. make_option('--first', action='store_false', dest='all', default=True,
  13. help="Only return the first match for each static file."),
  14. )
  15. def handle_label(self, path, **options):
  16. verbosity = int(options.get('verbosity', 1))
  17. result = finders.find(path, all=options['all'])
  18. path = force_text(path)
  19. if verbosity >= 2:
  20. searched_locations = ("Looking in the following locations:\n %s" %
  21. "\n ".join(force_text(location)
  22. for location in finders.searched_locations))
  23. else:
  24. searched_locations = ''
  25. if result:
  26. if not isinstance(result, (list, tuple)):
  27. result = [result]
  28. result = (force_text(os.path.realpath(path)) for path in result)
  29. if verbosity >= 1:
  30. file_list = '\n '.join(result)
  31. return ("Found '%s' here:\n %s\n%s" %
  32. (path, file_list, searched_locations))
  33. else:
  34. return '\n'.join(result)
  35. else:
  36. message = ["No matching file found for '%s'." % path]
  37. if verbosity >= 2:
  38. message.append(searched_locations)
  39. if verbosity >= 1:
  40. self.stderr.write('\n'.join(message))