Format with default line-length=88 (was 79 with Sanic).
This commit is contained in:
@@ -7,14 +7,10 @@ from emoji import EMOJI
|
||||
COLUMN_PATTERN = re.compile(r"---:1\s*(.*?)\s*:--:1\s*(.*?)\s*:---", re.DOTALL)
|
||||
PYTHON_HIGHLIGHT_PATTERN = re.compile(r"```python\{+.*?\}", re.DOTALL)
|
||||
BASH_HIGHLIGHT_PATTERN = re.compile(r"```bash\{+.*?\}", re.DOTALL)
|
||||
NOTIFICATION_PATTERN = re.compile(
|
||||
r":::\s*(\w+)\s*(.*?)\n([\s\S]*?):::", re.MULTILINE
|
||||
)
|
||||
NOTIFICATION_PATTERN = re.compile(r":::\s*(\w+)\s*(.*?)\n([\s\S]*?):::", re.MULTILINE)
|
||||
EMOJI_PATTERN = re.compile(r":(\w+):")
|
||||
CURRENT_DIR = Path(__file__).parent
|
||||
SOURCE_DIR = (
|
||||
CURRENT_DIR.parent.parent.parent.parent / "sanic-guide" / "src" / "en"
|
||||
)
|
||||
SOURCE_DIR = CURRENT_DIR.parent.parent.parent.parent / "sanic-guide" / "src" / "en"
|
||||
|
||||
|
||||
def convert_columns(content: str):
|
||||
|
||||
@@ -13,9 +13,7 @@ def do_footer(builder: Builder, request: Request) -> None:
|
||||
|
||||
|
||||
def _pagination(request: Request) -> Builder:
|
||||
return E.div(
|
||||
_pagination_left(request), _pagination_right(request), class_="level"
|
||||
)
|
||||
return E.div(_pagination_left(request), _pagination_right(request), class_="level")
|
||||
|
||||
|
||||
def _pagination_left(request: Request) -> Builder:
|
||||
@@ -64,9 +62,7 @@ def _content() -> Builder:
|
||||
href="https://github.com/sanic-org/sanic/blob/master/LICENSE",
|
||||
target="_blank",
|
||||
rel="nofollow noopener noreferrer",
|
||||
).br()(
|
||||
E.small(f"Copyright © 2018-{year} Sanic Community Organization")
|
||||
),
|
||||
).br()(E.small(f"Copyright © 2018-{year} Sanic Community Organization")),
|
||||
)
|
||||
return E.div(
|
||||
inner,
|
||||
|
||||
@@ -6,12 +6,9 @@ from webapp.display.layouts.models import MenuItem
|
||||
|
||||
def do_navbar(builder: Builder, request: Request) -> None:
|
||||
navbar_items = [
|
||||
_render_navbar_item(item, request)
|
||||
for item in request.app.config.NAVBAR
|
||||
_render_navbar_item(item, request) for item in request.app.config.NAVBAR
|
||||
]
|
||||
container = E.div(
|
||||
_search_form(request), *navbar_items, class_="navbar-end"
|
||||
)
|
||||
container = E.div(_search_form(request), *navbar_items, class_="navbar-end")
|
||||
|
||||
builder.nav(
|
||||
E.div(container, class_="navbar-menu"),
|
||||
@@ -46,10 +43,7 @@ def _render_navbar_item(item: MenuItem, request: Request) -> Builder:
|
||||
return E.div(
|
||||
E.a(item.label, class_="navbar-link"),
|
||||
E.div(
|
||||
*(
|
||||
_render_navbar_item(subitem, request)
|
||||
for subitem in item.items
|
||||
),
|
||||
*(_render_navbar_item(subitem, request) for subitem in item.items),
|
||||
class_="navbar-dropdown",
|
||||
),
|
||||
class_="navbar-item has-dropdown is-hoverable",
|
||||
|
||||
@@ -15,9 +15,7 @@ def _menu_items(request: Request) -> list[Builder]:
|
||||
_sanic_logo(request),
|
||||
*_sidebar_items(request),
|
||||
E.hr(),
|
||||
E.p("Current with version ").strong(
|
||||
request.app.config.GENERAL.current_version
|
||||
),
|
||||
E.p("Current with version ").strong(request.app.config.GENERAL.current_version),
|
||||
E.hr(),
|
||||
E.p("Want more? ").a(
|
||||
"sanicbook.com", href="https://sanicbook.com", target="_blank"
|
||||
@@ -73,9 +71,7 @@ def _single_sidebar_item(item: MenuItem, request: Request) -> Builder:
|
||||
kwargs = {}
|
||||
classes: list[str] = []
|
||||
li_classes = "menu-item"
|
||||
_, page, _ = request.app.ctx.get_page(
|
||||
request.ctx.language, item.path or ""
|
||||
)
|
||||
_, page, _ = request.app.ctx.get_page(request.ctx.language, item.path or "")
|
||||
if request.path == path:
|
||||
classes.append("is-active")
|
||||
if item.href:
|
||||
|
||||
@@ -36,9 +36,9 @@ class DocsRenderer(HTMLRenderer):
|
||||
class_="code-block__copy",
|
||||
onclick="copyCode(this)",
|
||||
):
|
||||
builder.div(
|
||||
class_="code-block__rectangle code-block__filled"
|
||||
).div(class_="code-block__rectangle code-block__outlined")
|
||||
builder.div(class_="code-block__rectangle code-block__filled").div(
|
||||
class_="code-block__rectangle code-block__outlined"
|
||||
)
|
||||
else:
|
||||
builder.pre(E.code(escape(code)))
|
||||
return str(builder)
|
||||
@@ -46,9 +46,7 @@ class DocsRenderer(HTMLRenderer):
|
||||
def heading(self, text: str, level: int, **attrs) -> str:
|
||||
ident = slugify(text)
|
||||
if level > 1:
|
||||
text += self._make_tag(
|
||||
"a", {"href": f"#{ident}", "class": "anchor"}, "#"
|
||||
)
|
||||
text += self._make_tag("a", {"href": f"#{ident}", "class": "anchor"}, "#")
|
||||
return self._make_tag(
|
||||
f"h{level}", {"id": ident, "class": f"is-size-{level}"}, text
|
||||
)
|
||||
@@ -92,9 +90,7 @@ class DocsRenderer(HTMLRenderer):
|
||||
def _make_tag(
|
||||
self, tag: str, attributes: dict[str, str], text: str | None = None
|
||||
) -> str:
|
||||
attrs = " ".join(
|
||||
f'{key}="{value}"' for key, value in attributes.items()
|
||||
)
|
||||
attrs = " ".join(f'{key}="{value}"' for key, value in attributes.items())
|
||||
if text is None:
|
||||
return f"<{tag} {attrs} />"
|
||||
return f"<{tag} {attrs}>{text}</{tag}>"
|
||||
|
||||
@@ -119,9 +119,7 @@ def _extract_docobjects(package_name: str) -> dict[str, DocObject]:
|
||||
docstrings = {}
|
||||
package = importlib.import_module(package_name)
|
||||
|
||||
for _, name, _ in pkgutil.walk_packages(
|
||||
package.__path__, package_name + "."
|
||||
):
|
||||
for _, name, _ in pkgutil.walk_packages(package.__path__, package_name + "."):
|
||||
module = importlib.import_module(name)
|
||||
for obj_name, obj in inspect.getmembers(module):
|
||||
if (
|
||||
@@ -155,9 +153,7 @@ def _docobject_to_html(
|
||||
) -> None:
|
||||
anchor_id = slugify(docobject.full_name.replace(".", "-"))
|
||||
anchor = E.a("#", class_="anchor", href=f"#{anchor_id}")
|
||||
class_name, heading = _define_heading_and_class(
|
||||
docobject, anchor, as_method
|
||||
)
|
||||
class_name, heading = _define_heading_and_class(docobject, anchor, as_method)
|
||||
|
||||
with builder.div(class_=class_name):
|
||||
builder(heading)
|
||||
@@ -211,9 +207,7 @@ def _docobject_to_html(
|
||||
|
||||
if docobject.docstring.params:
|
||||
with builder.div(class_="box mt-5"):
|
||||
builder.h5(
|
||||
"Parameters", class_="is-size-5 has-text-weight-bold"
|
||||
)
|
||||
builder.h5("Parameters", class_="is-size-5 has-text-weight-bold")
|
||||
_render_params(builder, docobject.docstring.params)
|
||||
|
||||
if docobject.docstring.returns:
|
||||
@@ -238,9 +232,7 @@ def _signature_to_html(
|
||||
parts = []
|
||||
parts.append("<span class='function-signature'>")
|
||||
for decorator in decorators:
|
||||
parts.append(
|
||||
f"<span class='function-decorator'>@{decorator}</span><br>"
|
||||
)
|
||||
parts.append(f"<span class='function-decorator'>@{decorator}</span><br>")
|
||||
parts.append(
|
||||
f"<span class='is-italic'>{object_type}</span> "
|
||||
f"<span class='has-text-weight-bold'>{name}</span>("
|
||||
@@ -254,9 +246,7 @@ def _signature_to_html(
|
||||
annotation = ""
|
||||
if param.annotation != inspect.Parameter.empty:
|
||||
annotation = escape(str(param.annotation))
|
||||
parts.append(
|
||||
f": <span class='param-annotation'>{annotation}</span>"
|
||||
)
|
||||
parts.append(f": <span class='param-annotation'>{annotation}</span>")
|
||||
if param.default != inspect.Parameter.empty:
|
||||
default = escape(str(param.default))
|
||||
if annotation == "str":
|
||||
@@ -267,9 +257,7 @@ def _signature_to_html(
|
||||
parts.append(")")
|
||||
if signature.return_annotation != inspect.Signature.empty:
|
||||
return_annotation = escape(str(signature.return_annotation))
|
||||
parts.append(
|
||||
f": -> <span class='return-annotation'>{return_annotation}</span>"
|
||||
)
|
||||
parts.append(f": -> <span class='return-annotation'>{return_annotation}</span>")
|
||||
parts.append("</span>")
|
||||
return "".join(parts)
|
||||
|
||||
@@ -317,10 +305,7 @@ def _render_params(builder: Builder, params: list[DocstringParam]) -> None:
|
||||
builder.dd(
|
||||
HTML(
|
||||
render_markdown(
|
||||
param.description
|
||||
or param.arg_name
|
||||
or param.type_name
|
||||
or ""
|
||||
param.description or param.arg_name or param.type_name or ""
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -333,11 +318,7 @@ def _render_raises(builder: Builder, raises: list[DocstringRaises]) -> None:
|
||||
with builder.dl(class_="mt-2"):
|
||||
builder.dt(raise_.type_name, class_="is-family-monospace")
|
||||
builder.dd(
|
||||
HTML(
|
||||
render_markdown(
|
||||
raise_.description or raise_.type_name or ""
|
||||
)
|
||||
)
|
||||
HTML(render_markdown(raise_.description or raise_.type_name or ""))
|
||||
)
|
||||
|
||||
|
||||
@@ -353,11 +334,7 @@ def _render_returns(builder: Builder, docobject: DocObject) -> None:
|
||||
if not return_type or return_type == inspect.Signature.empty:
|
||||
return_type = "N/A"
|
||||
|
||||
term = (
|
||||
"Return"
|
||||
if not docobject.docstring.returns.is_generator
|
||||
else "Yields"
|
||||
)
|
||||
term = "Return" if not docobject.docstring.returns.is_generator else "Yields"
|
||||
builder.h5(term, class_="is-size-5 has-text-weight-bold")
|
||||
with builder.dl(class_="mt-2"):
|
||||
builder.dt(return_type, class_="is-family-monospace")
|
||||
@@ -372,17 +349,11 @@ def _render_returns(builder: Builder, docobject: DocObject) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _render_examples(
|
||||
builder: Builder, examples: list[DocstringExample]
|
||||
) -> None:
|
||||
def _render_examples(builder: Builder, examples: list[DocstringExample]) -> None:
|
||||
with builder.div(class_="box mt-5"):
|
||||
builder.h5("Examples", class_="is-size-5 has-text-weight-bold")
|
||||
for example in examples:
|
||||
with builder.div(class_="mt-2"):
|
||||
builder(
|
||||
HTML(
|
||||
render_markdown(
|
||||
example.description or example.snippet or ""
|
||||
)
|
||||
)
|
||||
HTML(render_markdown(example.description or example.snippet or ""))
|
||||
)
|
||||
|
||||
@@ -11,9 +11,7 @@ from ..layouts.main import MainLayout
|
||||
from ..markdown import render_markdown
|
||||
from .docobject import organize_docobjects
|
||||
|
||||
_PAGE_CACHE: dict[
|
||||
str, dict[str, tuple[Page | None, Page | None, Page | None]]
|
||||
] = {}
|
||||
_PAGE_CACHE: dict[str, dict[str, tuple[Page | None, Page | None, Page | None]]] = {}
|
||||
_LAYOUTS_CACHE: dict[str, type[BaseLayout]] = {
|
||||
"home": HomeLayout,
|
||||
"main": MainLayout,
|
||||
|
||||
@@ -20,13 +20,9 @@ class PageRenderer(BaseRenderer):
|
||||
self._body(request, builder, language, path)
|
||||
return builder
|
||||
|
||||
def _body(
|
||||
self, request: Request, builder: Builder, language: str, path: str
|
||||
):
|
||||
def _body(self, request: Request, builder: Builder, language: str, path: str):
|
||||
prev_page, current_page, next_page = Page.get(language, path)
|
||||
request.ctx.language = (
|
||||
Page.DEFAULT_LANGUAGE if language == "api" else language
|
||||
)
|
||||
request.ctx.language = Page.DEFAULT_LANGUAGE if language == "api" else language
|
||||
request.ctx.current_page = current_page
|
||||
request.ctx.previous_page = prev_page
|
||||
request.ctx.next_page = next_page
|
||||
@@ -38,9 +34,7 @@ class PageRenderer(BaseRenderer):
|
||||
|
||||
@contextmanager
|
||||
def _base(self, request: Request, builder: Builder, page: Page | None):
|
||||
layout_type: type[BaseLayout] = (
|
||||
page.get_layout() if page else BaseLayout
|
||||
)
|
||||
layout_type: type[BaseLayout] = page.get_layout() if page else BaseLayout
|
||||
layout = layout_type(builder)
|
||||
with layout(request, builder.full):
|
||||
yield
|
||||
|
||||
@@ -15,9 +15,7 @@ class Attributes(DirectivePlugin):
|
||||
if md.renderer.NAME == "html":
|
||||
md.renderer.register("attrs", self._render)
|
||||
|
||||
def parse(
|
||||
self, block: BlockParser, m: Match, state: BlockState
|
||||
) -> dict[str, Any]:
|
||||
def parse(self, block: BlockParser, m: Match, state: BlockState) -> dict[str, Any]:
|
||||
info = m.groupdict()
|
||||
options = dict(self.parse_options(m))
|
||||
new_state = block.state_cls()
|
||||
|
||||
@@ -10,9 +10,7 @@ from mistune.markdown import Markdown
|
||||
|
||||
|
||||
class Column(DirectivePlugin):
|
||||
def parse(
|
||||
self, block: BlockParser, m: Match, state: BlockState
|
||||
) -> dict[str, Any]:
|
||||
def parse(self, block: BlockParser, m: Match, state: BlockState) -> dict[str, Any]:
|
||||
info = m.groupdict()
|
||||
|
||||
new_state = block.state_cls()
|
||||
@@ -36,9 +34,7 @@ class Column(DirectivePlugin):
|
||||
|
||||
def _render_column(self, renderer: HTMLRenderer, text: str, **attrs):
|
||||
start = (
|
||||
'<div class="columns mt-3 is-multiline">\n'
|
||||
if attrs.get("first")
|
||||
else ""
|
||||
'<div class="columns mt-3 is-multiline">\n' if attrs.get("first") else ""
|
||||
)
|
||||
end = "</div>\n" if attrs.get("last") else ""
|
||||
col = f'<div class="column is-half">{text}</div>\n'
|
||||
|
||||
@@ -16,16 +16,12 @@ class Hook(DirectivePlugin):
|
||||
for type_ in ("column", "tab"):
|
||||
if token["type"] == type_:
|
||||
maybe_next = (
|
||||
state.tokens[idx + 1]
|
||||
if idx + 1 < len(state.tokens)
|
||||
else None
|
||||
state.tokens[idx + 1] if idx + 1 < len(state.tokens) else None
|
||||
)
|
||||
token.setdefault("attrs", {})
|
||||
if prev and prev["type"] != type_:
|
||||
token["attrs"]["first"] = True
|
||||
if (
|
||||
maybe_next and maybe_next["type"] != type_
|
||||
) or not maybe_next:
|
||||
if (maybe_next and maybe_next["type"] != type_) or not maybe_next:
|
||||
token["attrs"]["last"] = True
|
||||
|
||||
prev = token
|
||||
|
||||
@@ -12,9 +12,7 @@ from mistune.markdown import Markdown
|
||||
|
||||
|
||||
class Mermaid(DirectivePlugin):
|
||||
def parse(
|
||||
self, block: BlockParser, m: Match, state: BlockState
|
||||
) -> dict[str, Any]:
|
||||
def parse(self, block: BlockParser, m: Match, state: BlockState) -> dict[str, Any]:
|
||||
info = m.groupdict()
|
||||
|
||||
new_state = block.state_cls()
|
||||
|
||||
@@ -19,12 +19,8 @@ class Notification(Admonition):
|
||||
|
||||
if md.renderer.NAME == "html":
|
||||
md.renderer.register("admonition", self._render_admonition)
|
||||
md.renderer.register(
|
||||
"admonition_title", self._render_admonition_title
|
||||
)
|
||||
md.renderer.register(
|
||||
"admonition_content", self._render_admonition_content
|
||||
)
|
||||
md.renderer.register("admonition_title", self._render_admonition_title)
|
||||
md.renderer.register("admonition_content", self._render_admonition_content)
|
||||
|
||||
def _render_admonition(self, _, text, name, **attrs) -> str:
|
||||
return str(
|
||||
|
||||
@@ -10,9 +10,7 @@ from mistune.markdown import Markdown
|
||||
|
||||
|
||||
class Tabs(DirectivePlugin):
|
||||
def parse(
|
||||
self, block: BlockParser, m: Match, state: BlockState
|
||||
) -> dict[str, Any]:
|
||||
def parse(self, block: BlockParser, m: Match, state: BlockState) -> dict[str, Any]:
|
||||
info = m.groupdict()
|
||||
|
||||
new_state = block.state_cls()
|
||||
@@ -41,9 +39,7 @@ class Tabs(DirectivePlugin):
|
||||
def _render_tab(self, renderer: HTMLRenderer, text: str, **attrs):
|
||||
start = '<div class="tabs mt-6"><ul>\n' if attrs.get("first") else ""
|
||||
end = (
|
||||
'</ul></div><div class="tab-display"></div>\n'
|
||||
if attrs.get("last")
|
||||
else ""
|
||||
'</ul></div><div class="tab-display"></div>\n' if attrs.get("last") else ""
|
||||
)
|
||||
content = f'<div class="tab-content">{text}</div>\n'
|
||||
tab = f'<li><a>{attrs["title"]}</a>{content}</li>\n'
|
||||
|
||||
@@ -92,9 +92,7 @@ def _inverse_document_frequency(docs: list[Document]) -> dict[str, float]:
|
||||
return {word: num_docs / count for word, count in word_count.items()}
|
||||
|
||||
|
||||
def _tf_idf_vector(
|
||||
document: Document, idf: dict[str, float]
|
||||
) -> dict[str, float]:
|
||||
def _tf_idf_vector(document: Document, idf: dict[str, float]) -> dict[str, float]:
|
||||
"""Calculate the TF-IDF vector for a document."""
|
||||
return {
|
||||
word: tf * idf[word]
|
||||
@@ -103,9 +101,7 @@ def _tf_idf_vector(
|
||||
}
|
||||
|
||||
|
||||
def _cosine_similarity(
|
||||
vec1: dict[str, float], vec2: dict[str, float]
|
||||
) -> float:
|
||||
def _cosine_similarity(vec1: dict[str, float], vec2: dict[str, float]) -> float:
|
||||
"""Calculate the cosine similarity between two vectors."""
|
||||
if not vec1 or not vec2:
|
||||
return 0.0
|
||||
@@ -127,9 +123,7 @@ def _search(
|
||||
tf_idf_query = _tf_idf_vector(
|
||||
Document(page=dummy_page, language=language).process(stemmer), idf
|
||||
)
|
||||
similarities = [
|
||||
_cosine_similarity(tf_idf_query, vector) for vector in vectors
|
||||
]
|
||||
similarities = [_cosine_similarity(tf_idf_query, vector) for vector in vectors]
|
||||
return [
|
||||
(similarity, document)
|
||||
for similarity, document in sorted(
|
||||
@@ -156,16 +150,13 @@ class Searcher:
|
||||
}
|
||||
self._vectors = {
|
||||
language: [
|
||||
_tf_idf_vector(document, self._idf[language])
|
||||
for document in documents
|
||||
_tf_idf_vector(document, self._idf[language]) for document in documents
|
||||
]
|
||||
for language, documents in self._documents.items()
|
||||
}
|
||||
self._stemmer = stemmer
|
||||
|
||||
def search(
|
||||
self, query: str, language: str
|
||||
) -> list[tuple[float, Document]]:
|
||||
def search(self, query: str, language: str) -> list[tuple[float, Document]]:
|
||||
return _search(
|
||||
query,
|
||||
language,
|
||||
|
||||
@@ -28,13 +28,9 @@ def create_app(root: Path) -> Sanic:
|
||||
app.config.STYLE_DIR = root / "style"
|
||||
app.config.NODE_MODULES_DIR = root / "node_modules"
|
||||
app.config.LANGUAGES = ["en"]
|
||||
app.config.SIDEBAR = load_menu(
|
||||
app.config.CONFIG_DIR / "en" / "sidebar.yaml"
|
||||
)
|
||||
app.config.SIDEBAR = load_menu(app.config.CONFIG_DIR / "en" / "sidebar.yaml")
|
||||
app.config.NAVBAR = load_menu(app.config.CONFIG_DIR / "en" / "navbar.yaml")
|
||||
app.config.GENERAL = load_config(
|
||||
app.config.CONFIG_DIR / "en" / "general.yaml"
|
||||
)
|
||||
app.config.GENERAL = load_config(app.config.CONFIG_DIR / "en" / "general.yaml")
|
||||
|
||||
setup_livereload(app)
|
||||
setup_style(app)
|
||||
@@ -66,8 +62,6 @@ def create_app(root: Path) -> Sanic:
|
||||
|
||||
@app.on_request
|
||||
async def set_language(request: Request):
|
||||
request.ctx.language = request.match_info.get(
|
||||
"language", Page.DEFAULT_LANGUAGE
|
||||
)
|
||||
request.ctx.language = request.match_info.get("language", Page.DEFAULT_LANGUAGE)
|
||||
|
||||
return app
|
||||
|
||||
@@ -53,16 +53,12 @@ class Livereload:
|
||||
"serverName": SERVER_NAME,
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self, reload_queue: Queue, debug: bool, state: dict[str, Any]
|
||||
):
|
||||
def __init__(self, reload_queue: Queue, debug: bool, state: dict[str, Any]):
|
||||
self.reload_queue = reload_queue
|
||||
self.app = Sanic(self.SERVER_NAME)
|
||||
self.debug = debug
|
||||
self.state = state
|
||||
self.app.static(
|
||||
"/livereload.js", Path(__file__).parent / "livereload.js"
|
||||
)
|
||||
self.app.static("/livereload.js", Path(__file__).parent / "livereload.js")
|
||||
self.app.add_websocket_route(
|
||||
self.livereload_handler, "/livereload", name="livereload"
|
||||
)
|
||||
@@ -108,7 +104,5 @@ class Livereload:
|
||||
break
|
||||
|
||||
|
||||
def _run_reload_server(
|
||||
reload_queue: Queue, debug: bool, state: dict[str, Any]
|
||||
):
|
||||
def _run_reload_server(reload_queue: Queue, debug: bool, state: dict[str, Any]):
|
||||
Livereload(reload_queue, debug, state).run()
|
||||
|
||||
Reference in New Issue
Block a user