Files
Pulumi/scripts/sync_en_from_upstream.py

873 lines
39 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把 Pulumi 官方文档(https://github.com/pulumi/docs)的英文原文同步到 docs/en/,不做翻译。
用法(需要 PyYAML):
git clone --depth 1 --filter=blob:none --sparse https://github.com/pulumi/docs.git pulumi-docs
git -C pulumi-docs sparse-checkout set content/docs content/blog static layouts/shortcodes
python scripts/sync_en_from_upstream.py pulumi-docs
每次运行都会重新生成:
docs/en/docs/、docs/en/blog/ 页面(Hugo 短代码转换成 VitePress 写法)
docs/public/en/ 页面引用到的图片、视频等静态文件
.vitepress/sidebar.en.json 英文侧边栏
docs/en/index.md(英文首页)是手写的,不会被覆盖。
"""
import argparse
import datetime
import html
import json
import os
from urllib.parse import urljoin
import re
import shutil
import sys
import textwrap
from collections import Counter, defaultdict
import yaml
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
EN_DIR = os.path.join(ROOT, 'docs', 'en')
PUBLIC_EN = os.path.join(ROOT, 'docs', 'public', 'en')
SIDEBAR_EN = os.path.join(ROOT, '.vitepress', 'sidebar.en.json')
EN = '/en'
PULUMI = 'https://www.pulumi.com'
SECTIONS = ('docs', 'blog')
# Cloudflare Workers 静态资源单个文件上限 25 MiB;更大的文件不复制,直接链接官网。
MAX_ASSET_BYTES = 25 * 1024 * 1024
HTML_TAGS = set('''a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption
cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer
form h1 h2 h3 h4 h5 h6 head header hr html i iframe img input ins kbd label legend li link main map mark meta meter
nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script section select
small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u
ul var video wbr svg path g circle rect line polyline polygon defs use center font'''.split())
COMPONENTS = {'Chooser', 'Choosable'}
FENCE_LANG = {'typescript': 'ts', 'javascript': 'js', 'python': 'python', 'go': 'go', 'csharp': 'csharp',
'fsharp': 'fsharp', 'visualbasic': 'vb', 'java': 'java', 'yaml': 'yaml', 'hcl': 'hcl'}
PROGRAM_FILE = {'javascript': 'index.js', 'typescript': 'index.ts', 'python': '__main__.py', 'go': 'main.go',
'csharp': 'Program.cs', 'java': 'src/main/java/myproject/App.java', 'yaml': 'Pulumi.yaml'}
# 由数据或页面模板生成、在这里无法还原的短代码:直接去掉。
DROP = {'related-posts', 'icon', 'get-started-stepper', 'esc-schema', 'esc-schema-updated', 'neo-card',
'pulumi-cloud-editions', 'rbac-scopes', 'rbac-scopes-updated', 'rbac-permission-sets', 'integration-links',
'audit-log-events', 'audit-log-events-updated', 'changelog-table-body', 'openapi-tag-list', 'glossary',
'package-schema', 'package-schema-version', 'schema-components', 'esc-context-schema',
'esc-oidc-subject-attributes', 'resource-options-table', 'resource-options-inheritance-table',
'resource-option-scope', 'cleanup', 'pulumi-cloud', 'agent-model-provider-setup', 'agent-cli-connection',
'sso-scim-limits-info', 'esc-recommendation', 'get-started-esc', 'experimental-feature', 'link-cards'}
stats = Counter()
unknown = Counter()
def log(*a):
print(*a, file=sys.stderr)
# ---------------------------------------------------------------------------
# 读取上游内容
# ---------------------------------------------------------------------------
def split_front_matter(text):
text = text.replace('\r\n', '\n').lstrip('')
m = re.match(r'---\n(.*?)\n---[ \t]*(?:\n|$)', text, re.S)
if not m:
return {}, text
try:
fm = yaml.safe_load(m.group(1)) or {}
except yaml.YAMLError:
fm = {}
return (fm if isinstance(fm, dict) else {}), text[m.end():]
def norm_url(u):
u = u.strip().split('#')[0].split('?')[0]
if not u.startswith('/'):
return None
if not re.search(r'\.[a-z0-9]+$', u, re.I) and not u.endswith('/'):
u += '/'
return u
class Page:
def __init__(self, section, src, rel):
self.section = section
self.src = src # 上游文件绝对路径
self.rel = rel # 相对 content/ 的路径,如 docs/iac/_index.md
self.fm, self.body = split_front_matter(open(src, encoding='utf-8').read())
base = re.sub(r'(^|/)(_index|index)\.md$', r'\1', rel)
base = re.sub(r'\.md$', '/', base)
self.url = '/' + base # Hugo 的地址,如 /docs/iac/concepts/
self.out = os.path.join(EN_DIR, base, 'index.md')
self.is_section = rel.endswith('_index.md')
@property
def title(self):
return str(self.fm.get('title') or self.fm.get('linktitle') or self.url.strip('/').split('/')[-1])
@property
def nav_title(self):
menu = self.fm.get('menu')
if isinstance(menu, dict):
for v in menu.values():
if isinstance(v, dict) and v.get('name'):
return str(v['name'])
return str(self.fm.get('linktitle') or self.title)
@property
def weight(self):
menu = self.fm.get('menu')
if isinstance(menu, dict):
for v in menu.values():
if isinstance(v, dict) and isinstance(v.get('weight'), (int, float)):
return v['weight']
w = self.fm.get('weight')
return w if isinstance(w, (int, float)) else 10 ** 6
@property
def date(self):
d = self.fm.get('date')
if isinstance(d, datetime.datetime):
return d.date()
if isinstance(d, datetime.date):
return d
if isinstance(d, str):
m = re.match(r'(\d{4})-(\d{2})-(\d{2})', d)
if m:
return datetime.date(*map(int, m.groups()))
return None
def load_pages(upstream):
pages, aliases = [], {}
today = datetime.date.today()
for section in SECTIONS:
base = os.path.join(upstream, 'content', section)
for d, _, files in os.walk(base):
for f in sorted(files):
if not f.endswith('.md'):
continue
src = os.path.join(d, f)
rel = os.path.relpath(src, os.path.join(upstream, 'content')).replace(os.sep, '/')
if section == 'blog' and rel == 'blog/_index.md':
continue # 博客首页由脚本生成
p = Page(section, src, rel)
fm = p.fm
if fm.get('draft') is True:
stats['skip draft'] += 1
continue
build = fm.get('_build') or fm.get('build') or {}
if isinstance(build, dict) and build.get('render') in ('never', False):
stats['skip unrendered'] += 1
continue
if section == 'blog' and p.date and p.date > today:
stats['skip future post'] += 1
continue
if fm.get('redirect_to'):
target = norm_url(str(fm['redirect_to']).replace(PULUMI, ''))
if target:
aliases.setdefault(p.url, target)
stats['skip redirect_to'] += 1
continue
for a in fm.get('aliases') or []:
a = norm_url(str(a))
if a:
aliases.setdefault(a, p.url)
if fm.get('url'):
u = norm_url(str(fm['url']))
if u:
aliases.setdefault(u, p.url)
pages.append(p)
return pages, aliases
# ---------------------------------------------------------------------------
# 链接和静态文件
# ---------------------------------------------------------------------------
class Linker:
def __init__(self, upstream, pages, aliases):
self.upstream = upstream
self.urls = {p.url for p in pages}
self.aliases = aliases
self.copied = set()
def page(self, url):
for _ in range(5):
if url in self.urls:
return url
if url not in self.aliases:
return None
url = self.aliases[url]
return None
def copy_public(self, src, public_rel):
"""把文件复制到 docs/public/en/<public_rel>,返回它的地址。"""
dst = os.path.join(PUBLIC_EN, public_rel)
if os.path.getsize(src) > MAX_ASSET_BYTES:
stats['oversized files linked to pulumi.com'] += 1
static = public_rel[len('static/'):] if public_rel.startswith('static/') else public_rel
return f'{PULUMI}/{static}'
if public_rel not in self.copied:
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copyfile(src, dst)
self.copied.add(public_rel)
return f'{EN}/{public_rel}'
def absolute(self, url):
"""站内绝对地址(/docs/...、/images/... 等)。"""
m = re.match(r'^([^#?]*)([?#].*)?$', url)
path, tail = m.group(1), m.group(2) or ''
n = norm_url(path)
if n:
target = self.page(n)
if target:
return EN + target + (tail if tail.startswith('#') else '')
static = os.path.join(self.upstream, 'static', path.lstrip('/'))
if os.path.isfile(static):
return self.copy_public(static, 'static/' + path.lstrip('/'))
content = os.path.join(self.upstream, 'content', path.lstrip('/'))
if os.path.isfile(content):
return self.copy_public(content, path.lstrip('/'))
return PULUMI + url
def rewrite(self, url, page, asset=False):
url = url.strip()
if not url or url.startswith(('#', 'mailto:', 'tel:', 'data:', 'javascript:')):
return url
if re.match(r'^https?://(www\.)?pulumi\.com(/|$)', url):
rest = re.sub(r'^https?://(www\.)?pulumi\.com', '', url) or '/'
if rest.startswith(('/docs/', '/blog/')):
local = self.absolute(rest)
return local if local.startswith(EN) else url
return url
if re.match(r'^[a-z][a-z0-9+.-]*:', url, re.I) or url.startswith('//'):
return url
if url.startswith('/'):
return self.absolute(url)
# 相对地址:页面目录下的文件放到 public,其余(指向其他页面)保持原样,浏览器按页面地址解析。
path = url.split('#')[0].split('?')[0]
if path and not path.endswith('/') and not path.endswith('.md'):
src = os.path.normpath(os.path.join(os.path.dirname(page.src), path))
if os.path.isfile(src):
rel = os.path.relpath(src, os.path.join(self.upstream, 'content')).replace(os.sep, '/')
if not rel.startswith('..'):
return self.copy_public(src, rel)
if asset or path.endswith('.md'):
# 找不到的图片等:VitePress 会把相对路径当成模块导入,找不到就编译失败,所以改成官网地址。
return PULUMI + urljoin(page.url, url)
return url
# ---------------------------------------------------------------------------
# 短代码
# ---------------------------------------------------------------------------
SC_RE = re.compile(r'\{\{([<%])\s*(/?)\s*([\w./-]+)((?:[^>%}]|>(?!\}\})|%(?!\}\})|\}(?!\}))*?)\s*(/?)\s*[>%]\}\}')
ARG_RE = re.compile(r'''([\w-]+)=(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+))|"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+)''')
def parse_args(s):
named, pos = {}, []
for m in ARG_RE.finditer(s.strip().rstrip('/').strip()):
if m.group(1):
v = next(g for g in (m.group(2), m.group(3), m.group(4)) if g is not None)
named[m.group(1)] = v.replace('\\"', '"')
else:
v = next(g for g in (m.group(5), m.group(6), m.group(7)) if g is not None)
pos.append(v.replace('\\"', '"'))
return named, pos
def attr(s):
return html.escape(str(s), quote=True)
class Converter:
def __init__(self, upstream, linker):
self.upstream = upstream
self.linker = linker
self.sc_dir = os.path.join(upstream, 'layouts', 'shortcodes')
self.latest_version = ''
lv = os.path.join(upstream, 'static', 'latest-version')
if os.path.isfile(lv):
self.latest_version = open(lv, encoding='utf-8').read().strip()
# -- 代码示例 ---------------------------------------------------------
def program_code(self, path, lang, file=None, start=None, end=None):
file = file or PROGRAM_FILE.get(lang)
if not file:
return None
src = os.path.join(self.upstream, 'static', 'programs', f'{path}-{lang}', file)
if not os.path.isfile(src):
return None
lines = open(src, encoding='utf-8').read().replace('\r\n', '\n').split('\n')
a = int(start or 1)
b = int(end or len(lines))
return '\n'.join(lines[a - 1:b]).rstrip('\n')
@staticmethod
def fence(code, lang):
ticks = '````' if '```' in code else '```'
return f'{ticks}{FENCE_LANG.get(lang, lang)}\n{code}\n{ticks}'
def example_program(self, named):
path = named.get('path', '')
langs = named.get('languages') or 'javascript,typescript,python,go,csharp,java,yaml'
blocks = []
for spec in langs.split(','):
parts = spec.split(':')
lang = parts[0]
file = parts[1] if len(parts) > 2 and parts[1] else None
rng = (parts[2] if len(parts) > 2 else parts[1] if len(parts) > 1 else '').split('-')
code = self.program_code(path, lang, file, rng[0] or None, rng[1] if len(rng) > 1 and rng[1] else None)
if code is not None:
blocks.append((lang, code))
if not blocks:
stats['example-program missing'] += 1
return f'[View the example on GitHub](https://github.com/pulumi/docs/tree/master/static/programs/)'
if len(blocks) == 1:
return self.fence(blocks[0][1], blocks[0][0])
out = [f'<Chooser type="language" options="{",".join(l for l, _ in blocks)}" />', '']
for lang, code in blocks:
out += [f'<Choosable type="language" values="{lang}">', '', self.fence(code, lang), '', '</Choosable>', '']
return '\n'.join(out).rstrip()
def snippet(self, named, in_code=False):
lang = named.get('language', 'typescript')
code = self.program_code(named.get('path', ''), lang, named.get('file'), named.get('from'), named.get('to'))
if code is None:
stats['example-program missing'] += 1
return ''
return code if in_code else self.fence(code, lang)
# -- 来自上游模板的静态片段 ----------------------------------------------
def static_template(self, name):
for ext in ('.markdown.md', '.md', '.html'):
f = os.path.join(self.sc_dir, name + ext)
if os.path.isfile(f):
t = open(f, encoding='utf-8').read()
t = re.sub(r'\{\{-?\s*/\*.*?\*/\s*-?\}\}', '', t, flags=re.S) # 模板注释
if '{{' not in t:
return t.strip()
return None
# -- 单个短代码 ---------------------------------------------------------
def single(self, name, named, pos, page, own_line, in_code=False):
if in_code and name == 'example-program-snippet':
return self.snippet(named, in_code=True)
if name in DROP:
stats[f'dropped {name}'] += 1
return DROPPED
if name == 'chooser':
typ = named.get('type') or (pos[0] if pos else 'language')
opts = named.get('options') or (pos[1] if len(pos) > 1 else '')
if named.get('option-style') == 'none':
return ''
return f'<Chooser type="{attr(typ)}" options="{attr(opts)}" />'
if name == 'choosable':
typ = named.get('type') or (pos[0] if pos else 'language')
vals = named.get('values') or named.get('value') or (pos[1] if len(pos) > 1 else '')
inline = '' if own_line else ' inline'
return f'<Choosable{inline} type="{attr(typ)}" values="{attr(vals)}">' + ('\n' if own_line else '')
if name == 'example-program':
return self.example_program(named)
if name == 'example-program-snippet':
return self.snippet(named)
if name == 'youtube':
vid = named.get('id') or (pos[0] if pos else '')
vid = vid.split('?')[0]
return (f'<div class="video-container"><iframe src="https://www.youtube.com/embed/{attr(vid)}" '
f'title="YouTube video" frameborder="0" allowfullscreen></iframe></div>')
if name == 'youtube-iframe':
attrs = ''.join(f' {k}="{attr(v)}"' for k, v in named.items() if k != 'allowfullscreen')
return f'<div class="video-container"><iframe{attrs} allowfullscreen></iframe></div>'
if name in ('video', 'audio'):
src = self.linker.rewrite(named.get('src') or (pos[0] if pos else ''), page, asset=True)
return f'<{name} controls src="{attr(src)}"></{name}>'
if name == 'figure':
src = self.linker.rewrite(named.get('src', ''), page, asset=True)
img = f'<img src="{attr(src)}" alt="{attr(named.get("alt", named.get("caption", "")))}"'
if named.get('width'):
img += f' width="{attr(named["width"])}"'
img += ' />'
cap = f'<figcaption>{html.escape(named["caption"])}</figcaption>' if named.get('caption') else ''
return f'<figure>{img}{cap}</figure>'
if name == 'gist':
user = pos[0] if pos else named.get('user', '')
gid = pos[1] if len(pos) > 1 else named.get('id', '')
return f'[View the code on GitHub Gist](https://gist.github.com/{user}/{gid})'
if name == 'x':
return f'[View the post on X](https://x.com/{named.get("user")}/status/{named.get("id")})'
if name == 'asciicast':
aid = named.get('id') or (pos[0] if pos else '')
return f'[View the recording on asciinema](https://asciinema.org/a/{aid})'
if name == 'github-card':
repo = named.get('repo', '')
return f'[{repo}](https://github.com/{repo})'
if name == 'link-card':
href = self.linker.rewrite(named.get('href', ''), page)
return f'- [{named.get("title", href)}]({href})'
if name == 'blog/cta-button':
text, href = (pos + ['', ''])[:2] if pos else (named.get('text', ''), named.get('link', ''))
return f'<p><a class="cta-button" href="{attr(self.linker.rewrite(href, page))}">{html.escape(text)}</a></p>'
if name == 'pulumi-languages':
s = named.get('set') or (pos[0] if pos else 'all')
if s == 'general-purpose':
return 'Python, TypeScript, JavaScript, Go, .NET, and Java'
if named.get('links') == 'true':
return ('Python, TypeScript, JavaScript, Go, .NET, Java, [YAML](/docs/iac/languages-sdks/yaml/), '
'and [HCL](/docs/iac/languages-sdks/hcl/)')
return 'Python, TypeScript, JavaScript, Go, .NET, Java, YAML, and HCL'
if name == 'self-hosting-trial-note':
product = named.get('product', 'self-hosted Pulumi Cloud')
return (f'> **Note:** If you would like to evaluate the {product}, [request a Proof of Concept (PoC)]'
f'(/product/self-hosted/#self-hosted-trial) or [contact us](/contact/).')
if name == 'latest-version':
return self.latest_version
if name in ('ref', 'relref'):
target = pos[0] if pos else ''
if not target.startswith('/'):
target = '/' + target
target = re.sub(r'(_index|index)\.md$', '', target)
target = re.sub(r'\.md$', '/', target)
return target
if name == 'code-filename':
return f'<p class="code-filename"><code>{html.escape(named.get("file", ""))}</code></p>\n'
if name in ('md', 'figcaption'):
return ''
t = self.static_template(name)
if t is not None:
stats[f'inlined {name}'] += 1
return t
unknown[name] += 1
return DROPPED
def closing(self, name, own_line):
if name == 'choosable':
return ('\n' if own_line else '') + '</Choosable>'
return ''
# -- 成对的短代码(容器)--------------------------------------------------
PAIRED = ('notes', 'details', 'pullquote', 'say', 'highlight', 'blog/card', 'blog/cta-card')
def paired(self, text, page):
names = '|'.join(re.escape(n) for n in self.PAIRED)
open_re = re.compile(r'([ \t]*)\{\{([<%])\s*(' + names + r')\b((?:[^>%]|>(?!\}\})|%(?!\}\}))*?)[>%]\}\}')
while True:
# 找最内层的一对:开标签之后、同名闭标签之前没有其他成对短代码的开标签。
best = None
for m in open_re.finditer(text):
close = re.compile(r'\{\{[<%]\s*/\s*' + re.escape(m.group(3)) + r'\s*[>%]\}\}')
c = close.search(text, m.end())
if not c:
continue
if open_re.search(text[m.end():c.start()]):
continue
best = (m, c)
break
if not best:
return text
m, c = best
indent, name, args = m.group(1), m.group(3), m.group(4)
named, pos = parse_args(args)
inner = text[m.end():c.start()]
text = text[:m.start()] + self.render_pair(name, named, pos, inner, indent, page) + text[c.end():]
def render_pair(self, name, named, pos, inner, indent, page):
body = inner.strip('\n')
first, _, rest = body.partition('\n')
body = (first.strip() + '\n' + textwrap.dedent(rest)).strip('\n') if rest else first.strip()
colons = ':' * max(3, max((len(x) for x in re.findall(r'^\s*(:{3,})', body, re.M)), default=2) + 1)
def block(lines):
return '\n' + '\n'.join((indent + l) if l else '' for l in lines.split('\n')) + '\n'
if name == 'notes':
kind = named.get('type', 'info')
kind = {'info': 'info', 'warning': 'warning', 'tip': 'tip', 'danger': 'danger'}.get(kind, 'info')
return block(f'{colons} {kind}\n{body}\n{colons}')
if name == 'details':
summary = named.get('summary') or (pos[0] if pos else 'Details')
return block(f'{colons} details {summary}\n{body}\n{colons}')
if name == 'highlight':
lang = (pos[0] if pos else named.get('lang', '')).lower()
return block(self.fence(body, lang))
if name == 'say':
who = named.get('author', '')
sig = f'\n\n— {who}' if who else ''
return block('<blockquote>\n\n' + body + sig + '\n\n</blockquote>')
return block('<blockquote>\n\n' + body + '\n\n</blockquote>') if name == 'pullquote' else block(body)
# -- 整个页面 -----------------------------------------------------------
def convert(self, body, page):
body = body.replace('\r\n', '\n')
body = re.sub(r'^[ \t]*<!--\s*more\s*-->[ \t]*\n?', '', body, flags=re.M)
body = ''.join(seg if is_code else block_shortcode_lines(seg) for is_code, seg in split_fences(body))
# 成对短代码可能跨越代码块,所以先在整篇文本上处理(代码块里的短代码 Hugo 也会执行)。
text = self.paired(body, page)
out = []
for is_code, seg in split_fences(text):
if is_code:
seg = re.sub(r'\{\{([<%])/\*\s*(.*?)\s*\*/([>%])\}\}', r'{{\1 \2 \3}}', seg, flags=re.S)
seg = SC_RE.sub(lambda m: self.sc(m, page, seg, in_code=True), seg)
out.append(seg.replace(DROPPED, ''))
else:
seg = SC_RE.sub(lambda m: self.sc(m, page, seg), seg)
seg = re.sub(r'^[ \t]*' + DROPPED + r'[ \t]*\n', '', seg, flags=re.M).replace(DROPPED, '')
out.append(seg)
# 短代码生成的代码块(example-program 等)要和原有代码块一样不做文本处理,所以重新切分。
out2 = []
for is_code, seg in split_fences(''.join(out)):
if not is_code:
seg = fix_html(convert_pulumi_elements(seg))
seg = '\n'.join(self.text_line(l, page) for l in seg.split('\n'))
out2.append(seg)
text = ''.join(out2)
text = re.sub(r'\n{4,}', '\n\n\n', text)
return text.strip('\n') + '\n'
def sc(self, m, page, seg, in_code=False):
start = seg.rfind('\n', 0, m.start()) + 1
end = seg.find('\n', m.end())
end = len(seg) if end < 0 else end
own_line = not seg[start:m.start()].strip() and not seg[m.end():end].strip()
closing, name, args = m.group(2), m.group(3), m.group(4)
if closing:
return self.closing(name, own_line)
named, pos = parse_args(args)
return self.single(name, named, pos, page, own_line, in_code)
# -- 普通文本行:链接改写、Vue 转义 -----------------------------------------
def text_line(self, line, page):
parts = re.split(r'(`+)(.+?)(\1)', line)
# re.split 带三个分组:[text, ticks, code, ticks, text, ...]
res = []
i = 0
while i < len(parts):
t = parts[i]
res.append(self.text_part(t, page))
if i + 1 < len(parts):
ticks, code = parts[i + 1], parts[i + 2]
# 在 HTML 块里 Markdown 不生效,代码里的 <T> 会被当成标签;这类代码直接写成 HTML。
if '{{' in code or '}}' in code or re.search(r'<[A-Za-z/]', code):
res.append(f'<code v-pre>{html.escape(code.strip())}</code>')
else:
res.append(f'{ticks}{code}{ticks}')
i += 4
return ''.join(res)
def text_part(self, t, page):
if not t:
return t
# 链接和图片
t = re.sub(r'(!?)(\[[^\]]*\]\()(<?)([^)\s>]+)(>?)((?:\s+"[^"]*")?\))',
lambda m: m.group(1) + m.group(2) + m.group(3)
+ self.linker.rewrite(m.group(4), page, asset=bool(m.group(1))) + m.group(5) + m.group(6), t)
t = re.sub(r'^(\s*\[[^\]]+\]:\s*)(\S+)', lambda m: m.group(1) + self.linker.rewrite(m.group(2), page), t)
t = re.sub(r'\b(href|src|poster)=(["\'])(.*?)\2',
lambda m: f'{m.group(1)}={m.group(2)}'
f'{self.linker.rewrite(m.group(3), page, asset=m.group(1) != "href")}{m.group(2)}', t)
# 不是 HTML 标签的 <xxx> 会被 Vue 当成组件,转义掉。
t = re.sub(r'<(/?)([A-Za-z][\w.-]*)(?=[\s>/:@])',
lambda m: m.group(0) if (m.group(2).lower() in HTML_TAGS or m.group(2) in COMPONENTS
or t[m.end():m.end() + 1] == ':') # <https://...> 自动链接
else '&lt;' + m.group(1) + m.group(2), t)
# Vue 插值
t = t.replace('{{', '&#123;&#123;').replace('}}', '&#125;&#125;')
return t
def split_fences(text):
"""把文本分成 (是否代码块, 内容) 片段。"""
segs, buf, code, fence = [], [], False, None
for line in text.split('\n'):
m = re.match(r'^\s*(`{3,}|~{3,})', line)
if m and m.group(1)[0] == '`' and '`' in line.strip()[len(m.group(1)):]:
m = None # ```x``` 是行内代码,不是代码块(CommonMark:反引号围栏的信息串不能含反引号)
if not code and m:
if buf:
segs.append((False, '\n'.join(buf) + '\n'))
buf, code, fence = [line], True, m.group(1)
elif code and m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence) \
and not line.strip()[len(m.group(1)):].strip():
# 结束标记比开始标记多缩进 4 格以上时 Markdown 不认,对齐到开始标记。
open_indent = re.match(r'\s*', buf[0]).group(0)
if len(line) - len(line.lstrip()) >= len(open_indent) + 4:
line = open_indent + line.lstrip()
buf.append(line)
segs.append((True, '\n'.join(buf) + '\n'))
buf, code = [], False
else:
buf.append(line)
if buf:
segs.append((code, '\n'.join(buf) + '\n'))
if segs and text and not text.endswith('\n'):
k, s = segs[-1]
segs[-1] = (k, s[:-1])
return segs
DROPPED = '\x00DROPPED\x00'
BLOCK_SC = re.compile(r'\{\{[<%]\s*/?\s*(chooser|choosable)\b(?:[^}]|\}(?!\}))*\}\}')
def block_shortcode_lines(text):
"""每个 chooser/choosable 短代码单独占一行。
同一行上的 chooser + choosable 会被当成行内内容;列表外缩进 4 格的短代码会被当成代码块,所以去掉缩进。
"""
out, context = [], ''
lines = text.split('\n')
def is_sc_line(s):
s = s.strip()
return bool(s) and BLOCK_SC.search(s) and not BLOCK_SC.sub('', s).strip()
for i, line in enumerate(lines):
stripped = line.strip()
if is_sc_line(line):
indent = re.match(r'[ \t]*', line).group(0)
in_list = bool(re.match(r'\s*([-*+]|\d+[.)])\s', context)) or context[:1] in (' ', '\t')
# 只有后面的内容也同样缩进(确实嵌在列表里)时才保留缩进。
nxt = next((l for l in lines[i + 1:] if l.strip() and not is_sc_line(l)), '')
nested = len(nxt) - len(nxt.lstrip()) >= len(indent) > 0
if not (in_list and nested):
indent = ''
out.extend(indent + m.group(0) for m in BLOCK_SC.finditer(stripped))
continue
if stripped:
context = line
out.append(line)
return '\n'.join(out)
def fix_html(t):
"""上游 HTML 里 Hugo 能容忍、Vue 模板编译不了的写法。"""
t = re.sub(r'<(script|style)\b[^>]*>.*?</\1>', '', t, flags=re.S | re.I)
t = re.sub(r'<script\b[^>]*/>', '', t, flags=re.I)
t = re.sub(r'</?pulumi-[\w-]+\b[^>]*>', '', t)
# 单独占一行、包住多个段落的 <i>/<b>:Markdown 会把它们拆到不同的块里,标签无法配对。
t = re.sub(r'^[ \t]*</?(i|b|em|strong)>[ \t]*\n', '', t, flags=re.M)
def dedupe(m):
seen = set()
def one(a):
k = a.group(1).lower()
if k in seen:
return ''
seen.add(k)
return a.group(0)
return re.sub(r'\s([\w:-]+)(?:=("[^"]*"|\'[^\']*\'|[^\s>]+))?(?=[\s/>])', one, m.group(0))
t = re.sub(r'<[A-Za-z][\w-]*\s[^<>]*>', dedupe, t)
def close_li(m):
line = m.group(0)
if '</li>' in line:
return line
return re.sub(r'<li>(.*?)(?=<li>|</ul>|</ol>|$)', r'<li>\1</li>', line)
t = re.sub(r'^.*<li>.*$', close_li, t, flags=re.M)
return t
def convert_pulumi_elements(t):
"""上游 HTML 里的 <pulumi-chooser>/<pulumi-choosable> 自定义元素。"""
def chooser(m):
a = dict(re.findall(r'([\w-]+)="([^"]*)"', m.group(1)))
if a.get('option-style') == 'none':
return ''
return f'<Chooser type="{a.get("type", "language")}" options="{a.get("options", "")}" />'
def choosable(m):
a = dict(re.findall(r'([\w-]+)="([^"]*)"', m.group(1)))
vals = a.get('values') or a.get('value', '')
return f'<Choosable inline type="{a.get("type", "language")}" values="{vals}">'
t = re.sub(r'<pulumi-chooser\b([^>]*)>', chooser, t)
t = t.replace('</pulumi-chooser>', '')
t = re.sub(r'<pulumi-choosable\b([^>]*)>', choosable, t)
t = t.replace('</pulumi-choosable>', '</Choosable>')
return t
# ---------------------------------------------------------------------------
# 输出
# ---------------------------------------------------------------------------
def plain(s):
s = re.sub(r'<[^>]+>', '', str(s or ''))
return html.unescape(re.sub(r'\s+', ' ', s)).strip()
def yaml_str(s):
return json.dumps(str(s), ensure_ascii=False)
def children_of(page, by_parent):
return sorted(by_parent.get(page.url, []), key=lambda p: (p.weight, p.nav_title.lower()))
def parent_url(url):
parts = url.strip('/').split('/')
return '/' + '/'.join(parts[:-1]) + '/' if len(parts) > 1 else None
def render_sections(fm, linker, page):
out = []
for sec in fm.get('sections') or []:
if not isinstance(sec, dict):
continue
if sec.get('heading'):
out.append(f'## {plain(sec["heading"])}\n')
if sec.get('description'):
out.append(plain(sec['description']) + '\n')
items = sec.get('cards') or sec.get('items') or sec.get('links') or []
for c in items if isinstance(items, list) else []:
if not isinstance(c, dict):
continue
title = plain(c.get('heading') or c.get('title') or c.get('name') or '')
link = c.get('link') or c.get('url') or c.get('href')
desc = plain(c.get('description') or '')
if title and link:
out.append(f'- [{title}]({linker.rewrite(str(link), page)})' + (f' — {desc}' if desc else ''))
elif title:
out.append(f'- {title}' + (f' — {desc}' if desc else ''))
out.append('')
return '\n'.join(out).strip()
def write_page(page, body, by_parent, linker):
fm = page.fm
title = plain(page.title)
desc = plain(fm.get('meta_desc') or fm.get('description') or '')
lines = ['---', f'title: {yaml_str(title)}']
if desc:
lines.append(f'description: {yaml_str(desc)}')
if page.section == 'blog':
if page.date:
lines.append(f'date: {page.date.isoformat()}')
authors = fm.get('authors') or []
if authors:
lines.append(f'authors: {json.dumps([str(a) for a in authors], ensure_ascii=False)}')
tags = fm.get('tags') or []
if tags:
lines.append(f'tags: {json.dumps([str(t) for t in tags], ensure_ascii=False)}')
lines.append('---')
head = []
if not re.match(r'\s*#\s', body):
head.append(f'# {plain(fm.get("h1") or title)}\n')
if page.section == 'blog':
meta = ' · '.join(x for x in [page.date.isoformat() if page.date else '',
', '.join(str(a) for a in fm.get('authors') or [])] if x)
if meta:
head.append(f'<p class="blog-meta">{html.escape(meta)}</p>\n')
extra = ''
if page.is_section:
if fm.get('sections'):
extra = render_sections(fm, linker, page)
kids = children_of(page, by_parent)
if kids and len(re.sub(r'\s+', '', body)) < 400 and not fm.get('sections'):
extra = '## In this section\n\n' + '\n'.join(
f'- [{plain(k.nav_title)}]({EN}{k.url})' + (
f' — {plain(k.fm.get("meta_desc"))}' if k.fm.get('meta_desc') else '') for k in kids)
text = '\n'.join(lines) + '\n' + '\n'.join(head) + '\n' + body + ('\n' + extra + '\n' if extra else '')
os.makedirs(os.path.dirname(page.out), exist_ok=True)
with open(page.out, 'w', encoding='utf-8', newline='\n') as f:
f.write(text)
def sidebar_items(page, by_parent, depth=0):
items = []
for k in children_of(page, by_parent):
item = {'text': plain(k.nav_title), 'link': EN + k.url}
sub = sidebar_items(k, by_parent, depth + 1)
if sub:
item['collapsed'] = True
item['items'] = sub
items.append(item)
return items
def build_sidebar(pages, by_parent, by_url):
sidebar = {}
docs_home = by_url.get('/docs/')
if docs_home:
tops = children_of(docs_home, by_parent)
sidebar[f'{EN}/docs/'] = [{'text': 'Documentation', 'link': f'{EN}/docs/'}] + [
{'text': plain(t.nav_title), 'link': EN + t.url} for t in tops]
for t in tops:
items = sidebar_items(t, by_parent)
sidebar[EN + t.url] = [{'text': plain(t.nav_title), 'link': EN + t.url, 'items': items}]
posts = sorted((p for p in pages if p.section == 'blog'), key=lambda p: (p.date or datetime.date.min, p.url),
reverse=True)
years = defaultdict(list)
for p in posts:
years[p.date.year if p.date else 0].append(p)
blog = [{'text': 'All Posts', 'link': f'{EN}/blog/'}]
for i, (y, ps) in enumerate(sorted(years.items(), reverse=True)):
blog.append({'text': str(y) if y else 'Undated', 'collapsed': i > 0,
'items': [{'text': plain(p.title), 'link': EN + p.url} for p in ps]})
sidebar[f'{EN}/blog/'] = blog
return sidebar, years
def write_blog_index(years):
out = ['---', 'title: "Blog"', 'description: "Pulumi blog posts"', 'aside: false', '---', '', '# Pulumi Blog', '']
for y, ps in sorted(years.items(), reverse=True):
out += [f'## {y or "Undated"}', '']
out += [f'- {p.date.isoformat() if p.date else ""} [{plain(p.title).replace("[", "(").replace("]", ")")}]'
f'({EN}{p.url})' for p in ps]
out.append('')
path = os.path.join(EN_DIR, 'blog', 'index.md')
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, 'w', encoding='utf-8', newline='\n') as f:
f.write('\n'.join(out))
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('upstream', help='pulumi/docs 的本地检出目录')
args = ap.parse_args()
upstream = os.path.abspath(args.upstream)
if not os.path.isdir(os.path.join(upstream, 'content', 'docs')):
sys.exit(f'{upstream} 下没有 content/docs,请检查 sparse-checkout。')
pages, aliases = load_pages(upstream)
by_url = {p.url: p for p in pages}
by_parent = defaultdict(list)
for p in pages:
par = parent_url(p.url)
while par and par not in by_url and parent_url(par):
par = parent_url(par)
if par and par != p.url:
by_parent[par].append(p)
for d in [os.path.join(EN_DIR, s) for s in SECTIONS] + [PUBLIC_EN]:
shutil.rmtree(d, ignore_errors=True)
linker = Linker(upstream, pages, aliases)
conv = Converter(upstream, linker)
for p in pages:
body = conv.convert(p.body, p)
write_page(p, body, by_parent, linker)
stats[f'{p.section} pages'] += 1
sidebar, years = build_sidebar(pages, by_parent, by_url)
write_blog_index(years)
with open(SIDEBAR_EN, 'w', encoding='utf-8', newline='\n') as f:
json.dump(sidebar, f, ensure_ascii=False, indent=2)
f.write('\n')
stats['static files copied'] = len(linker.copied)
for k, v in sorted(stats.items()):
log(f'{k}: {v}')
if unknown:
log('unhandled shortcodes (removed):', dict(unknown.most_common()))
if __name__ == '__main__':
main()