findstatic.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import os
  2. from django.contrib.staticfiles import finders
  3. from django.core.management.base import LabelCommand
  4. class Command(LabelCommand):
  5. help = "Finds the absolute paths for the given static file(s)."
  6. label = "staticfile"
  7. def add_arguments(self, parser):
  8. super().add_arguments(parser)
  9. parser.add_argument(
  10. "--first",
  11. action="store_false",
  12. dest="all",
  13. help="Only return the first match for each static file.",
  14. )
  15. def handle_label(self, path, **options):
  16. verbosity = options["verbosity"]
  17. result = finders.find(path, all=options["all"])
  18. if verbosity >= 2:
  19. searched_locations = (
  20. "\nLooking in the following locations:\n %s"
  21. % "\n ".join([str(loc) for loc in finders.searched_locations])
  22. )
  23. else:
  24. searched_locations = ""
  25. if result:
  26. if not isinstance(result, (list, tuple)):
  27. result = [result]
  28. result = (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%s" % (
  32. path,
  33. file_list,
  34. searched_locations,
  35. )
  36. else:
  37. return "\n".join(result)
  38. else:
  39. message = ["No matching file found for '%s'." % path]
  40. if verbosity >= 2:
  41. message.append(searched_locations)
  42. if verbosity >= 1:
  43. self.stderr.write("\n".join(message))