Skip to content

Commit

Permalink
Constrain type of WhiteNoise.index_file (#440)
Browse files Browse the repository at this point in the history
  • Loading branch information
adamchainz authored Nov 3, 2022
1 parent 3045a88 commit 636cd37
Showing 1 changed file with 21 additions and 21 deletions.
42 changes: 21 additions & 21 deletions src/whitenoise/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,11 @@ def __init__(
self.charset = charset
self.add_headers_function = add_headers_function
if index_file is True:
self.index_file = "index.html"
else:
self.index_file: str | None = "index.html"
elif isinstance(index_file, str):
self.index_file = index_file
else:
self.index_file = None

if immutable_file_test is not None:
if not callable(immutable_file_test):
Expand Down Expand Up @@ -122,7 +124,7 @@ def update_files_dictionary(self, root, prefix):
def add_file_to_dictionary(self, url, path, stat_cache=None):
if self.is_compressed_variant(path, stat_cache=stat_cache):
return
if self.index_file and url.endswith("/" + self.index_file):
if self.index_file is not None and url.endswith("/" + self.index_file):
index_url = url[: -len(self.index_file)]
index_no_slash = index_url.rstrip("/")
self.files[url] = self.redirect(url, index_url)
Expand All @@ -133,7 +135,7 @@ def add_file_to_dictionary(self, url, path, stat_cache=None):

def find_file(self, url):
# Optimization: bail early if the URL can never match a file
if not self.index_file and url.endswith("/"):
if self.index_file is None and url.endswith("/"):
return
if not self.url_is_canonical(url):
return
Expand All @@ -153,25 +155,23 @@ def candidate_paths_for_url(self, url):
def find_file_at_path(self, path, url):
if self.is_compressed_variant(path):
raise MissingFileError(path)
if self.index_file:
return self.find_file_at_path_with_indexes(path, url)
else:
return self.get_static_file(path, url)

def find_file_at_path_with_indexes(self, path, url):
if url.endswith("/"):
path = os.path.join(path, self.index_file)
return self.get_static_file(path, url)
elif url.endswith("/" + self.index_file):
if os.path.isfile(path):
return self.redirect(url, url[: -len(self.index_file)])
else:
try:
if self.index_file is not None:
if url.endswith("/"):
path = os.path.join(path, self.index_file)
return self.get_static_file(path, url)
except IsDirectoryError:
if os.path.isfile(os.path.join(path, self.index_file)):
return self.redirect(url, url + "/")
raise MissingFileError(path)
elif url.endswith("/" + self.index_file):
if os.path.isfile(path):
return self.redirect(url, url[: -len(self.index_file)])
else:
try:
return self.get_static_file(path, url)
except IsDirectoryError:
if os.path.isfile(os.path.join(path, self.index_file)):
return self.redirect(url, url + "/")
raise MissingFileError(path)

return self.get_static_file(path, url)

@staticmethod
def url_is_canonical(url):
Expand Down

0 comments on commit 636cd37

Please sign in to comment.