Skip to content

Commit 72424c5

Browse files
Move build and serve commands into cli module
1 parent 4b55f00 commit 72424c5

File tree

2 files changed

+67
-91
lines changed

2 files changed

+67
-91
lines changed

src/mkdocs/cli.py

Lines changed: 52 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,60 @@
11
import click
22
import mkdocs
33

4+
import pathlib
5+
import flask
46

5-
@click.group()
6-
def cli():
7-
pass
7+
8+
CONTENT_TYPES = {
9+
".json": "application/json",
10+
".js": "application/javascript",
11+
".html": "text/html",
12+
".css": "text/css",
13+
".png": "image/png",
14+
".jpeg": "image/jpeg",
15+
".jpg": "image/jpeg",
16+
".gif": "image/gif",
17+
}
18+
19+
20+
def build(mk: mkdocs.MkDocs) -> None:
21+
buildpath = pathlib.Path('site')
22+
for resource in mk.resources:
23+
output = mk.render(resource)
24+
build_path = buildpath.joinpath(resource.output_path)
25+
build_path.parent.mkdir(parents=True, exist_ok=True)
26+
build_path.write_bytes(output)
827

928

10-
@cli.command(name="build")
11-
def build():
12-
m = mkdocs.MkDocs()
13-
m.build()
29+
def serve(mk: mkdocs.MkDocs) -> None:
30+
urls = {resource.url: resource for resource in mk.resources}
31+
app = flask.Flask(__name__)
1432

33+
@app.route("/")
34+
@app.route("/<path:path>")
35+
def _(path=''):
36+
# path = flask.request.url.path
37+
resource = urls.get(f"/{path}")
38+
if resource is None:
39+
redirect = f"/{path}/"
40+
if urls.get(redirect) is not None:
41+
# return flask.redirect(redirect)
42+
return flask.Response(status=302, headers={'Location': redirect})
43+
# not_found = httpx.Text('Not Found')
44+
text = 'Not Found'
45+
return flask.Response(text, status=404)
46+
# return flask.make_response(not_found, 404)
47+
content = mk.render(resource)
48+
content_type = CONTENT_TYPES.get(resource.output_path.suffix)
49+
return flask.Response(content, status=200, headers={'Content-Type': content_type})
1550

16-
@cli.command(name="serve")
17-
def serve():
18-
m = mkdocs.MkDocs()
19-
m.serve()
51+
app.run()
52+
53+
54+
def cli():
55+
mk = mkdocs.MkDocs()
56+
group = click.Group(commands=[
57+
click.Command(name='build', callback=lambda: build(mk)),
58+
click.Command(name='serve', callback=lambda: serve(mk)),
59+
])
60+
return group()

src/mkdocs/mkdocs.py

Lines changed: 15 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ def __init__(self, path: pathlib.Path, url: str, handler: Handler) -> None:
170170
self.path = path
171171
self.url = url
172172
self.handler = handler
173-
173+
174174
@property
175175
def output_path(self) -> pathlib.Path:
176176
if self.url.endswith('/'):
@@ -238,29 +238,17 @@ def get_source(self, environment: jinja2.Environment, template: str):
238238
raise jinja2.TemplateNotFound(template)
239239

240240

241-
###############################################################################
242-
# A mapping of file extensions to content types.
243-
# TODO: Expand this to use the same defaults as nginx...
244-
# https://github.com/nginx/nginx/blob/master/conf/mime.types
245-
246-
CONTENT_TYPES = {
247-
".json": "application/json",
248-
".js": "application/javascript",
249-
".html": "text/html",
250-
".css": "text/css",
251-
".png": "image/png",
252-
".jpeg": "image/jpeg",
253-
".jpg": "image/jpeg",
254-
".gif": "image/gif",
255-
}
256-
257241

258242
###############################################################################
259243
# Here we go...
260244

261245
class MkDocs:
262246
def __init__(self):
263-
pass
247+
self.config = self.load_config('mkdocs.toml')
248+
self.handlers = self.load_handlers(self.config)
249+
self.resources, self.templates = self.load_resources(self.handlers)
250+
self.env = self.load_env(self.templates)
251+
self.md = self.load_md(self.config)
264252

265253
def path_to_url(self, path: pathlib.Path) -> str:
266254
if str(path).lower() in ('readme.md', 'index.md', 'index.html'):
@@ -384,73 +372,20 @@ def nav_lines(self, nav: dict, indent="") -> list[str]:
384372
lines.extend(sub_lines)
385373
return lines
386374

387-
def render(self, resource: Resource, resources: list[Resource], config: dict, env: jinja2.Environment, md: markdown.Markdown) -> bytes:
375+
def render(self, resource: Resource) -> bytes:
388376
if resource.path.suffix == '.md':
389-
mapping = {resource.path: resource.url for resource in resources}
377+
mapping = {resource.path: resource.url for resource in self.resources}
390378
with PageContext(resource.path, mapping, relative=False) as ctx:
391-
nav_config = config['mkdocs'].get('nav', [])
379+
nav_config = self.config['mkdocs'].get('nav', [])
392380
nav_lines = self.nav_lines(nav_config)
393381
nav_text = '\n'.join(nav_lines)
394-
nav_html = md.reset().convert(nav_text)
382+
nav_html = self.md.reset().convert(nav_text)
395383
nav = Nav(html=nav_html, current=ctx.current, previous=ctx.previous, next=ctx.next)
396384
with PageContext(resource.path, mapping, relative=True):
397385
text = resource.read().decode('utf-8')
398-
html = md.reset().convert(text)
399-
title = md.toc_tokens[0]['name'] if md.toc_tokens else ''
400-
page = Page(text=text, html=html, toc=md.toc, title=title, url=resource.url, path=resource.path)
401-
base = env.get_template('base.html')
402-
return base.render(page=page, nav=nav, config=config).encode('utf-8')
386+
html = self.md.reset().convert(text)
387+
title = self.md.toc_tokens[0]['name'] if self.md.toc_tokens else ''
388+
page = Page(text=text, html=html, toc=self.md.toc, title=title, url=resource.url, path=resource.path)
389+
base = self.env.get_template('base.html')
390+
return base.render(page=page, nav=nav, config=self.config).encode('utf-8')
403391
return resource.read()
404-
405-
###########################################################################
406-
# Commands...
407-
408-
def build(self):
409-
"""
410-
$ mkdocs build
411-
"""
412-
config = self.load_config('mkdocs.toml')
413-
handlers = self.load_handlers(config)
414-
resources, templates = self.load_resources(handlers)
415-
env = self.load_env(templates)
416-
md = self.load_md(config)
417-
418-
buildpath = pathlib.Path('site')
419-
for resource in resources:
420-
output = self.render(resource, resources, config, env, md)
421-
build_path = buildpath.joinpath(resource.output_path)
422-
build_path.parent.mkdir(parents=True, exist_ok=True)
423-
build_path.write_bytes(output)
424-
425-
def serve(self):
426-
"""
427-
$ mkdocs serve
428-
"""
429-
config = self.load_config('mkdocs.toml')
430-
handlers = self.load_handlers(config)
431-
resources, templates = self.load_resources(handlers)
432-
env = self.load_env(templates)
433-
md = self.load_md(config)
434-
435-
urls = {resource.url: resource for resource in resources}
436-
app = flask.Flask(__name__)
437-
438-
@app.route("/")
439-
@app.route("/<path:path>")
440-
def _(path=''):
441-
# path = flask.request.url.path
442-
resource = urls.get(f"/{path}")
443-
if resource is None:
444-
redirect = f"/{path}/"
445-
if urls.get(redirect) is not None:
446-
# return flask.redirect(redirect)
447-
return flask.Response(status=302, headers={'Location': redirect})
448-
# not_found = httpx.Text('Not Found')
449-
text = 'Not Found'
450-
return flask.Response(text, status=404)
451-
# return flask.make_response(not_found, 404)
452-
content = self.render(resource, resources, config, env, md)
453-
content_type = CONTENT_TYPES.get(resource.output_path.suffix)
454-
return flask.Response(content, status=200, headers={'Content-Type': content_type})
455-
456-
app.run()

0 commit comments

Comments
 (0)