summaryrefslogtreecommitdiff
path: root/django_pyscss/utils.py
blob: 1f9e4b41920c8eb5653e93460705a66307c0838f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import fnmatch
import os

from django.conf import settings
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage


def find_all_files(glob):
    """
    Finds all files in the django finders for a given glob,
    returns the file path, if available, and the django storage object.
    storage objects must implement the File storage API:
    https://docs.djangoproject.com/en/dev/ref/files/storage/
    """
    for finder in finders.get_finders():
        for path, storage in finder.list([]):
            if fnmatch.fnmatchcase(os.path.join(getattr(storage, 'prefix', '')
                                                or '', path),
                                   glob):
                yield path, storage


def get_file_from_storage(filename):
    try:
        filename = staticfiles_storage.path(filename)
    except NotImplementedError:
        # remote storages don't implement path
        pass
    if staticfiles_storage.exists(filename):
        return filename, staticfiles_storage
    else:
        return None, None


def get_file_from_finders(filename):
    for file_and_storage in find_all_files(filename):
        return file_and_storage
    return None, None


def get_file_and_storage(filename):
    # TODO: the switch probably shouldn't be on DEBUG
    if settings.DEBUG:
        return get_file_from_finders(filename)
    else:
        return get_file_from_storage(filename)