✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.
Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.
Move the configuration to config/common.toml and translate the README
to English.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
30
tools/doccheck/Cargo.toml
Normal file
30
tools/doccheck/Cargo.toml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
[package]
|
||||
name = "doccheck"
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
description = "Compiles and runs the Rust examples of the PageTop guides (see tools/doccheck.sh)."
|
||||
publish = false
|
||||
|
||||
# Independent of the website package: it only exists to check the guides.
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
pagetop = { path = "../../../pagetop" }
|
||||
pagetop-bootsier = { path = "../../../pagetop/extensions/pagetop-bootsier" }
|
||||
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
||||
pagetop-htmx = { path = "../../../pagetop/extensions/pagetop-htmx" }
|
||||
pagetop-seaorm = { path = "../../../pagetop/extensions/pagetop-seaorm", features = ["sqlite"] }
|
||||
pagetop-admin = { path = "../../../pagetop/extensions/pagetop-admin" }
|
||||
pagetop-user = { path = "../../../pagetop/extensions/pagetop-user" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
thiserror = "2"
|
||||
tower-http = { version = "0.7", features = ["compression-gzip", "cors", "limit", "timeout"] }
|
||||
|
||||
[build-dependencies]
|
||||
pagetop-build = { path = "../../../pagetop/helpers/pagetop-build" }
|
||||
|
||||
# The examples are only compiled and run to check them: without debug info or incremental caches
|
||||
# they take far less disk.
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
incremental = false
|
||||
7
tools/doccheck/build.rs
Normal file
7
tools/doccheck/build.rs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// Bundle named "app", so that the examples using `serve_static_files!(router, [app] => ...)`
|
||||
// compile like they would in an application.
|
||||
fn main() -> std::io::Result<()> {
|
||||
pagetop_build::StaticFilesBundle::from_dir("./bundle", None)
|
||||
.with_name("app")
|
||||
.build()
|
||||
}
|
||||
1
tools/doccheck/bundle/css/app.css
Normal file
1
tools/doccheck/bundle/css/app.css
Normal file
|
|
@ -0,0 +1 @@
|
|||
body {}
|
||||
37
tools/doccheck/check_links.py
Normal file
37
tools/doccheck/check_links.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
"""Checks the internal links (pages and anchors) of a book built by mdBook.
|
||||
|
||||
Usage: check_links.py <built book dir>. Exits with 1 if any link is broken.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import posixpath
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
|
||||
|
||||
def main():
|
||||
out = pathlib.Path(sys.argv[1])
|
||||
pages = {p.relative_to(out).as_posix(): p.read_text() for p in out.rglob("*.html")}
|
||||
ids = {name: set(re.findall(r'id="([^"]+)"', html)) for name, html in pages.items()}
|
||||
broken = 0
|
||||
for name, html in pages.items():
|
||||
content = html[html.find("<main>") : html.find("</main>")]
|
||||
for link, anchor in re.findall(r'href="([^"#:]*\.html)(?:#([^"]*))?"', content):
|
||||
page = posixpath.normpath(posixpath.join(posixpath.dirname(name), link))
|
||||
if page not in ids:
|
||||
print(f"{name}: missing page {page}")
|
||||
broken += 1
|
||||
elif anchor and urllib.parse.unquote(anchor) not in ids[page]:
|
||||
print(f"{name}: missing anchor {page}#{urllib.parse.unquote(anchor)}")
|
||||
broken += 1
|
||||
for anchor in re.findall(r'href="#([^"]+)"', content):
|
||||
if urllib.parse.unquote(anchor) not in ids[name]:
|
||||
print(f"{name}: missing anchor #{anchor}")
|
||||
broken += 1
|
||||
print(f"{broken} broken links")
|
||||
sys.exit(1 if broken else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
11
tools/doccheck/config/common.toml
Normal file
11
tools/doccheck/config/common.toml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
# Settings for the examples and tests of the guides that start an application. Those that use a
|
||||
# database get a new in-memory SQLite one on every run (one connection, so all queries share it).
|
||||
[database]
|
||||
db_type = "sqlite"
|
||||
db_name = "doccheck?mode=memory"
|
||||
max_pool_size = 1
|
||||
|
||||
# Only errors: the expected warnings (such as [database] in an application without a database)
|
||||
# would hide the result of the checks.
|
||||
[log]
|
||||
tracing = "Error"
|
||||
72
tools/doccheck/extract.py
Normal file
72
tools/doccheck/extract.py
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
"""Extracts the Rust code blocks of an mdBook book into the doccheck crate.
|
||||
|
||||
Usage: extract.py <book src dir> <doccheck dir>
|
||||
|
||||
Every ```rust block becomes a file, after removing the `# ` prefix of the lines that mdBook hides:
|
||||
|
||||
- Blocks marked `ignore` are skipped (loose fragments that are not meant to compile).
|
||||
- Blocks with `#[pagetop::test]` go to `tests/generated_*.rs` and run with `cargo test`.
|
||||
- The rest go to `examples/*.rs`. Those not marked `no_run` end in `_run` and are executed, so
|
||||
their `assert!` are checked. Blocks without `fn main` get one: statements are wrapped in it, like
|
||||
rustdoc does; items get an empty one.
|
||||
"""
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
STATEMENT = re.compile(r"(let |assert|[A-Za-z_:]+::[a-z_]+\(|[a-z_]+\.)")
|
||||
HEADER = re.compile(r"(use |#!|include_locales!)")
|
||||
|
||||
|
||||
def unhide(code):
|
||||
lines = []
|
||||
for line in code.splitlines():
|
||||
if line.startswith("# "):
|
||||
line = line[2:]
|
||||
elif line == "#":
|
||||
line = ""
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def with_main(lines):
|
||||
code = "\n".join(lines)
|
||||
if "fn main" in code:
|
||||
return code
|
||||
if any(STATEMENT.match(line) for line in lines):
|
||||
head = [line for line in lines if HEADER.match(line)]
|
||||
body = [line for line in lines if not HEADER.match(line)]
|
||||
return "\n".join(head) + "\nfn main() {\n" + "\n".join(body) + "\n}\n"
|
||||
return code + "\n\nfn main() {}\n"
|
||||
|
||||
|
||||
def main():
|
||||
book, crate = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
|
||||
examples, tests = crate / "examples", crate / "tests"
|
||||
examples.mkdir(exist_ok=True)
|
||||
for old in list(examples.glob("*.rs")) + list(tests.glob("generated_*.rs")):
|
||||
old.unlink()
|
||||
|
||||
count = {"examples": 0, "tests": 0}
|
||||
for md in sorted(book.rglob("*.md")):
|
||||
blocks = re.finditer(r"```rust([^\n]*)\n(.*?)```", md.read_text(), re.S)
|
||||
for i, block in enumerate(blocks):
|
||||
attrs, lines = block.group(1), unhide(block.group(2))
|
||||
if "ignore" in attrs:
|
||||
continue
|
||||
name = md.relative_to(book).with_suffix("").as_posix()
|
||||
stem = re.sub(r"[^a-z0-9]", "_", name.lower()) + f"_{i:02d}"
|
||||
prelude = "#![allow(dead_code, unused)]\n"
|
||||
if any("#[pagetop::test]" in line for line in lines):
|
||||
(tests / f"generated_{stem}.rs").write_text(prelude + "\n".join(lines) + "\n")
|
||||
count["tests"] += 1
|
||||
else:
|
||||
suffix = "" if "no_run" in attrs else "_run"
|
||||
(examples / f"{stem}{suffix}.rs").write_text(prelude + with_main(lines))
|
||||
count["examples"] += 1
|
||||
print(f"{count['examples']} examples and {count['tests']} tests extracted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
2
tools/doccheck/src/lib.rs
Normal file
2
tools/doccheck/src/lib.rs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
//! Empty on purpose: the examples of the guides are extracted into `examples/` and `tests/` by
|
||||
//! `tools/doccheck.sh`. The translations in `src/locale` are the ones the localization chapter uses.
|
||||
14
tools/doccheck/src/locale/en-US/app.ftl
Normal file
14
tools/doccheck/src/locale/en-US/app.ftl
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
greeting = Hello!
|
||||
welcome = Welcome, { $name }.
|
||||
notices = { $total ->
|
||||
[one] You have one notice
|
||||
*[other] You have { $total } notices
|
||||
}
|
||||
|
||||
# Used by the tour (tutorials/tour.md).
|
||||
gardens = Community gardens
|
||||
free-plots = { $count ->
|
||||
[0] No free plots
|
||||
[one] One free plot
|
||||
*[other] { $count } free plots
|
||||
}
|
||||
14
tools/doccheck/src/locale/es-ES/app.ftl
Normal file
14
tools/doccheck/src/locale/es-ES/app.ftl
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
greeting = ¡Hola!
|
||||
welcome = Te damos la bienvenida, { $name }.
|
||||
notices = { $total ->
|
||||
[one] Tienes un aviso
|
||||
*[other] Tienes { $total } avisos
|
||||
}
|
||||
|
||||
# Used by the tour (tutorials/tour.md).
|
||||
gardens = Huertos vecinales
|
||||
free-plots = { $count ->
|
||||
[0] Sin parcelas libres
|
||||
[one] Una parcela libre
|
||||
*[other] { $count } parcelas libres
|
||||
}
|
||||
41
tools/doccheck/tests/localization.rs
Normal file
41
tools/doccheck/tests/localization.rs
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
// Runtime check of the localization chapter: translations, arguments and plurals in both languages.
|
||||
use pagetop::prelude::*;
|
||||
|
||||
include_locales!(LOCALES_APP);
|
||||
|
||||
struct App;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for App {
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router.route("/", web::get(home))
|
||||
}
|
||||
}
|
||||
|
||||
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
Page::new(request)
|
||||
.with_child(Html::with(|cx| {
|
||||
let welcome = Lc::t("welcome", &LOCALES_APP).with_arg("name", "Ana");
|
||||
let many = Lc::t("notices", &LOCALES_APP).with_number("total", 3);
|
||||
let one = Lc::t("notices", &LOCALES_APP).with_number("total", 1);
|
||||
html! { p { (welcome.using(cx)) } p { (many.using(cx)) } p { (one.using(cx)) } }
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn translates_with_arguments_and_plurals() {
|
||||
let app = web::test::init_router(Application::prepare(&App).await.test());
|
||||
for (lang, expected) in [
|
||||
("es", ["Te damos la bienvenida, Ana.", "Tienes 3 avisos", "Tienes un aviso"]),
|
||||
("en", ["Welcome, Ana.", "You have 3 notices", "You have one notice"]),
|
||||
] {
|
||||
let request = web::test::TestRequest::get().uri(format!("/?lang={lang}")).to_request();
|
||||
let response = web::test::send_request(&app, request).await;
|
||||
let body = web::test::read_body_text(response).await;
|
||||
for text in expected {
|
||||
assert!(body.contains(text), "{lang}: {text:?} not found in the page");
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue