Skip to content

Commit 806670f

Browse files
Update snippet viewer
1 parent 93fbc6e commit 806670f

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

_plugins/snippet_tokens.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
module SnippetTokens
2+
TOKEN = /\{\{\s*snippet:([a-zA-Z0-9_-]+)\s*\}\}/.freeze
3+
4+
module_function
5+
6+
def render(content, site, locale)
7+
return content unless content&.match?(TOKEN)
8+
9+
content.gsub(TOKEN) do
10+
snippet_id = Regexp.last_match(1)
11+
snippet_path = File.join(site.source, "docs", "snippets", snippet_id, "#{locale}.code")
12+
fallback_path = File.join(site.source, "docs", "snippets", snippet_id, "en.code")
13+
resolved_path = File.exist?(snippet_path) ? snippet_path : fallback_path
14+
15+
unless File.exist?(resolved_path)
16+
Jekyll.logger.warn("snippet_tokens:", "missing snippet #{snippet_id} for locale #{locale}")
17+
next "<!-- missing snippet #{snippet_id} for locale #{locale} -->"
18+
end
19+
20+
snippet = File.read(resolved_path, encoding: "utf-8").rstrip
21+
"\n```python\n#{snippet}\n```\n"
22+
end
23+
end
24+
end
25+
26+
Jekyll::Hooks.register [:pages, :documents], :pre_render do |doc|
27+
locale = doc.data["locale"] || "en"
28+
doc.content = SnippetTokens.render(doc.content, doc.site, locale)
29+
end

scripts/check_pages_artifact.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import sys
88
from pathlib import Path
99

10+
SNIPPET_TOKEN = "{{snippet:"
11+
1012

1113
def main() -> int:
1214
parser = argparse.ArgumentParser()
@@ -32,6 +34,20 @@ def main() -> int:
3234
print(f"ERROR: invalid base path (must start with '/'): {args.base_path!r}")
3335
return 1
3436

37+
unresolved = []
38+
for html_file in site_dir.rglob("*.html"):
39+
text = html_file.read_text(encoding="utf-8")
40+
if SNIPPET_TOKEN in text:
41+
unresolved.append(str(html_file))
42+
43+
if unresolved:
44+
print("ERROR: unresolved snippet tokens found in built HTML:")
45+
for path in unresolved[:20]:
46+
print(f" - {path}")
47+
if len(unresolved) > 20:
48+
print(f" - ... and {len(unresolved) - 20} more")
49+
return 1
50+
3551
print(f"Pages artifact sanity checks passed for {site_dir}")
3652
return 0
3753

0 commit comments

Comments
 (0)