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