|
5 | 5 | import argparse |
6 | 6 | import shlex |
7 | 7 | import sys |
| 8 | +import webbrowser |
| 9 | +from contextlib import asynccontextmanager |
8 | 10 | from pathlib import Path |
9 | 11 |
|
10 | 12 | import colorama |
|
22 | 24 | from sphinx_autobuild.filter import IgnoreFilter |
23 | 25 | from sphinx_autobuild.middleware import JavascriptInjectorMiddleware |
24 | 26 | from sphinx_autobuild.server import RebuildServer |
25 | | -from sphinx_autobuild.utils import find_free_port, open_browser, show_message |
| 27 | +from sphinx_autobuild.utils import find_free_port, show_message |
26 | 28 |
|
27 | 29 |
|
28 | 30 | def main(argv=()): |
@@ -81,32 +83,40 @@ def main(argv=()): |
81 | 83 | ignore_dirs = list(filter(None, ignore_dirs)) |
82 | 84 | ignore_handler = IgnoreFilter(ignore_dirs, args.re_ignore) |
83 | 85 |
|
84 | | - app = _create_app(watch_dirs, ignore_handler, builder, serve_dir, url_host) |
| 86 | + app = _create_app( |
| 87 | + watch_dirs, ignore_handler, builder, serve_dir, url_host, args.open_browser |
| 88 | + ) |
85 | 89 |
|
86 | 90 | if not args.no_initial_build: |
87 | 91 | show_message("Starting initial build") |
88 | 92 | builder(changed_paths=()) |
89 | 93 |
|
90 | | - if args.open_browser: |
91 | | - open_browser(url_host) |
92 | | - |
93 | 94 | show_message("Waiting to detect changes...") |
94 | 95 | try: |
95 | 96 | uvicorn.run(app, host=host_name, port=port_num, log_level="warning") |
96 | 97 | except KeyboardInterrupt: |
97 | 98 | show_message("Server ceasing operations. Cheerio!") |
98 | 99 |
|
99 | 100 |
|
100 | | -def _create_app(watch_dirs, ignore_handler, builder, out_dir, url_host): |
| 101 | +def _create_app( |
| 102 | + watch_dirs, ignore_handler, builder, out_dir, url_host, open_browser=False |
| 103 | +): |
101 | 104 | watcher = RebuildServer(watch_dirs, ignore_handler, change_callback=builder) |
102 | 105 |
|
| 106 | + @asynccontextmanager |
| 107 | + async def lifespan(app): |
| 108 | + async with watcher.lifespan(app): |
| 109 | + if open_browser: |
| 110 | + webbrowser.open(f"http://{url_host}") |
| 111 | + yield |
| 112 | + |
103 | 113 | return Starlette( |
104 | 114 | routes=[ |
105 | 115 | WebSocketRoute("/websocket-reload", watcher, name="reload"), |
106 | 116 | Mount("/", app=StaticFiles(directory=out_dir, html=True), name="static"), |
107 | 117 | ], |
108 | 118 | middleware=[Middleware(JavascriptInjectorMiddleware, ws_url=url_host)], |
109 | | - lifespan=watcher.lifespan, |
| 119 | + lifespan=lifespan, |
110 | 120 | ) |
111 | 121 |
|
112 | 122 |
|
|
0 commit comments