We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Check directory exists when instantiating `StaticFiles`
The `StaticFiles` application should ensure that the directory exists at the point it is instantiated.

(With an optional switch to turn this behavior off)

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlette/staticfiles.py`
Content:
```
1 import os
2 import stat
3 
4 from aiofiles.os import stat as aio_stat
5 
6 from starlette.responses import FileResponse, PlainTextResponse, Response
7 from starlette.types import ASGIInstance, Receive, Scope, Send
8 
9 
10 class StaticFiles:
11     def __init__(self, *, directory: str) -> None:
12         self.directory = directory
13         self.config_checked = False
14 
15     def __call__(self, scope: Scope) -> ASGIInstance:
16         assert scope["type"] == "http"
17         if scope["method"] not in ("GET", "HEAD"):
18             return PlainTextResponse("Method Not Allowed", status_code=405)
19         path = os.path.normpath(os.path.join(*scope["path"].split("/")))
20         if path.startswith(".."):
21             return PlainTextResponse("Not Found", status_code=404)
22         path = os.path.join(self.directory, path)
23         if self.config_checked:
24             check_directory = None
25         else:
26             check_directory = self.directory
27             self.config_checked = True
28         return _StaticFilesResponder(scope, path=path, check_directory=check_directory)
29 
30 
31 class _StaticFilesResponder:
32     def __init__(self, scope: Scope, path: str, check_directory: str = None) -> None:
33         self.scope = scope
34         self.path = path
35         self.check_directory = check_directory
36 
37     async def check_directory_configured_correctly(self) -> None:
38         """
39         Perform a one-off configuration check that StaticFiles is actually
40         pointed at a directory, so that we can raise loud errors rather than
41         just returning 404 responses.
42         """
43         directory = self.check_directory
44         try:
45             stat_result = await aio_stat(directory)
46         except FileNotFoundError:
47             raise RuntimeError("StaticFiles directory '%s' does not exist." % directory)
48         if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
49             raise RuntimeError("StaticFiles path '%s' is not a directory." % directory)
50 
51     async def __call__(self, receive: Receive, send: Send) -> None:
52         if self.check_directory is not None:
53             await self.check_directory_configured_correctly()
54 
55         try:
56             stat_result = await aio_stat(self.path)
57         except FileNotFoundError:
58             response = PlainTextResponse("Not Found", status_code=404)  # type: Response
59         else:
60             mode = stat_result.st_mode
61             if not stat.S_ISREG(mode):
62                 response = PlainTextResponse("Not Found", status_code=404)
63             else:
64                 response = FileResponse(self.path, stat_result=stat_result)
65 
66         await response(receive, send)
67
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py
--- a/starlette/staticfiles.py
+++ b/starlette/staticfiles.py
@@ -8,7 +8,9 @@
 
 
 class StaticFiles:
-    def __init__(self, *, directory: str) -> None:
+    def __init__(self, *, directory: str, check_dir: bool = True) -> None:
+        if check_dir and not os.path.isdir(directory):
+            raise RuntimeError("Directory '%s' does not exist" % directory)
         self.directory = directory
         self.config_checked = False

{"golden_diff": "diff --git a/starlette/staticfiles.py b/starlette/staticfiles.py\n--- a/starlette/staticfiles.py\n+++ b/starlette/staticfiles.py\n@@ -8,7 +8,9 @@\n \n \n class StaticFiles:\n-    def __init__(self, *, directory: str) -> None:\n+    def __init__(self, *, directory: str, check_dir: bool = True) -> None:\n+        if check_dir and not os.path.isdir(directory):\n+            raise RuntimeError(\"Directory '%s' does not exist\" % directory)\n         self.directory = directory\n         self.config_checked = False\n", "issue": "Check directory exists when instantiating `StaticFiles`\nThe `StaticFiles` application should ensure that the directory exists at the point it is instantiated.\r\n\r\n(With an optional switch to turn this behavior off)\n", "before_files": [{"content": "import os\nimport stat\n\nfrom aiofiles.os import stat as aio_stat\n\nfrom starlette.responses import FileResponse, PlainTextResponse, Response\nfrom starlette.types import ASGIInstance, Receive, Scope, Send\n\n\nclass StaticFiles:\n    def __init__(self, *, directory: str) -> None:\n        self.directory = directory\n        self.config_checked = False\n\n    def __call__(self, scope: Scope) -> ASGIInstance:\n        assert scope[\"type\"] == \"http\"\n        if scope[\"method\"] not in (\"GET\", \"HEAD\"):\n            return PlainTextResponse(\"Method Not Allowed\", status_code=405)\n        path = os.path.normpath(os.path.join(*scope[\"path\"].split(\"/\")))\n        if path.startswith(\"..\"):\n            return PlainTextResponse(\"Not Found\", status_code=404)\n        path = os.path.join(self.directory, path)\n        if self.config_checked:\n            check_directory = None\n        else:\n            check_directory = self.directory\n            self.config_checked = True\n        return _StaticFilesResponder(scope, path=path, check_directory=check_directory)\n\n\nclass _StaticFilesResponder:\n    def __init__(self, scope: Scope, path: str, check_directory: str = None) -> None:\n        self.scope = scope\n        self.path = path\n        self.check_directory = check_directory\n\n    async def check_directory_configured_correctly(self) -> None:\n        \"\"\"\n        Perform a one-off configuration check that StaticFiles is actually\n        pointed at a directory, so that we can raise loud errors rather than\n        just returning 404 responses.\n        \"\"\"\n        directory = self.check_directory\n        try:\n            stat_result = await aio_stat(directory)\n        except FileNotFoundError:\n            raise RuntimeError(\"StaticFiles directory '%s' does not exist.\" % directory)\n        if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):\n            raise RuntimeError(\"StaticFiles path '%s' is not a directory.\" % directory)\n\n    async def __call__(self, receive: Receive, send: Send) -> None:\n        if self.check_directory is not None:\n            await self.check_directory_configured_correctly()\n\n        try:\n            stat_result = await aio_stat(self.path)\n        except FileNotFoundError:\n            response = PlainTextResponse(\"Not Found\", status_code=404)  # type: Response\n        else:\n            mode = stat_result.st_mode\n            if not stat.S_ISREG(mode):\n                response = PlainTextResponse(\"Not Found\", status_code=404)\n            else:\n                response = FileResponse(self.path, stat_result=stat_result)\n\n        await response(receive, send)\n", "path": "starlette/staticfiles.py"}], "after_files": [{"content": "import os\nimport stat\n\nfrom aiofiles.os import stat as aio_stat\n\nfrom starlette.responses import FileResponse, PlainTextResponse, Response\nfrom starlette.types import ASGIInstance, Receive, Scope, Send\n\n\nclass StaticFiles:\n    def __init__(self, *, directory: str, check_dir: bool = True) -> None:\n        if check_dir and not os.path.isdir(directory):\n            raise RuntimeError(\"Directory '%s' does not exist\" % directory)\n        self.directory = directory\n        self.config_checked = False\n\n    def __call__(self, scope: Scope) -> ASGIInstance:\n        assert scope[\"type\"] == \"http\"\n        if scope[\"method\"] not in (\"GET\", \"HEAD\"):\n            return PlainTextResponse(\"Method Not Allowed\", status_code=405)\n        path = os.path.normpath(os.path.join(*scope[\"path\"].split(\"/\")))\n        if path.startswith(\"..\"):\n            return PlainTextResponse(\"Not Found\", status_code=404)\n        path = os.path.join(self.directory, path)\n        if self.config_checked:\n            check_directory = None\n        else:\n            check_directory = self.directory\n            self.config_checked = True\n        return _StaticFilesResponder(scope, path=path, check_directory=check_directory)\n\n\nclass _StaticFilesResponder:\n    def __init__(self, scope: Scope, path: str, check_directory: str = None) -> None:\n        self.scope = scope\n        self.path = path\n        self.check_directory = check_directory\n\n    async def check_directory_configured_correctly(self) -> None:\n        \"\"\"\n        Perform a one-off configuration check that StaticFiles is actually\n        pointed at a directory, so that we can raise loud errors rather than\n        just returning 404 responses.\n        \"\"\"\n        directory = self.check_directory\n        try:\n            stat_result = await aio_stat(directory)\n        except FileNotFoundError:\n            raise RuntimeError(\"StaticFiles directory '%s' does not exist.\" % directory)\n        if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):\n            raise RuntimeError(\"StaticFiles path '%s' is not a directory.\" % directory)\n\n    async def __call__(self, receive: Receive, send: Send) -> None:\n        if self.check_directory is not None:\n            await self.check_directory_configured_correctly()\n\n        try:\n            stat_result = await aio_stat(self.path)\n        except FileNotFoundError:\n            response = PlainTextResponse(\"Not Found\", status_code=404)  # type: Response\n        else:\n            mode = stat_result.st_mode\n            if not stat.S_ISREG(mode):\n                response = PlainTextResponse(\"Not Found\", status_code=404)\n            else:\n                response = FileResponse(self.path, stat_result=stat_result)\n\n        await response(receive, send)\n", "path": "starlette/staticfiles.py"}]}