forked from Segate-ekb/oscript-md
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-commonmark.py
More file actions
355 lines (289 loc) · 14.4 KB
/
sync-commonmark.py
File metadata and controls
355 lines (289 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/env python3
"""Загружает CommonMark spec заданной версии, делает dump в JSON и генерирует
OneUnit-сьюты по секциям: tests/commonmark/<section-slug>.os.
Использование:
python tools/sync-commonmark.py [version] [--force]
Пример:
python tools/sync-commonmark.py 0.31.2
Зависимости: только стандартная библиотека Python 3.10+.
Skip-list (тесты, помечаемые как &Выключен в сгенерированных сьютах) встроен
ниже в SKIP_LIST. Это намеренно: список пропусков — часть инвариантов
реализации и должен версионироваться вместе с генератором. Описание каждой
причины и сводка известных ограничений — в README, раздел «Известные
ограничения CommonMark».
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import urllib.request
from pathlib import Path
from typing import Optional
PROJECT_ROOT = Path(__file__).resolve().parent.parent
COMMONMARK_DIR = PROJECT_ROOT / "tests" / "commonmark"
CACHE_DIR = COMMONMARK_DIR / ".cache"
DEFAULT_VERSION = "0.31.2"
# Карта тестов CommonMark, которые помечаются как xfail (&Выключен).
# Структура: {версия_spec: {"sections": {имя: причина}, "examples": {номер: причина}}}.
# Причина выводится как сообщение в &Выключен("…"). Сгруппированное описание
# см. в README → «Известные ограничения CommonMark».
SKIP_LIST: dict[str, dict] = {
"0.31.2": {
"sections": {},
"examples": {
5: "Табуляция в элементах списка — расширение таба на границе контейнера (CM §2.2). Требует корректной обработки префикса строки контейнера.",
6: "Табуляция в цитатах — расширение таба через границу маркера `>`.",
7: "Табуляция в элементах списка — расчёт отступа содержимого при двойном табе.",
93: "Подчёркивание setext в ленивом продолжении цитаты. CM запрещает создание setext-заголовка строкой ленивого продолжения.",
236: "Цитата, за которой следует строка в стиле блока кода с отступом: CM рассматривает внешнее содержимое как отдельный блок кода; наш рекурсивный парсер цитат захватывает его через ленивое продолжение.",
237: "Блок кода с ограждением внутри цитаты без закрытия: закрывающее ограждение тоже должно иметь префикс `>`; без него ограждение остаётся открытым и завершается на границе цитаты.",
},
},
}
# --------------------------------------------------------------------------- #
# Загрузка spec.txt
# --------------------------------------------------------------------------- #
def download_spec(version: str, force: bool = False) -> str:
"""Скачивает spec.txt с сайта CommonMark, кеширует в .cache."""
url = f"https://spec.commonmark.org/{version}/spec.txt"
CACHE_DIR.mkdir(parents=True, exist_ok=True)
cache_file = CACHE_DIR / f"spec-{version}.txt"
if cache_file.exists() and not force:
print(f"[cache] {cache_file.relative_to(PROJECT_ROOT)}")
return cache_file.read_text(encoding="utf-8")
print(f"[download] {url}")
req = urllib.request.Request(url, headers={"User-Agent": "oscript-md-sync"})
with urllib.request.urlopen(req) as resp: # noqa: S310 (trusted host)
content = resp.read().decode("utf-8")
cache_file.write_text(content, encoding="utf-8")
return content
# --------------------------------------------------------------------------- #
# Парсинг spec.txt → список примеров {number, section, markdown, html}
# --------------------------------------------------------------------------- #
FENCE_OPEN = re.compile(r"^`{10,}\s*example\s*$")
FENCE_CLOSE = re.compile(r"^`{10,}\s*$")
HEADER = re.compile(r"^#{1,6}\s+(.+?)(?:\s+#+)?\s*$")
def parse_spec(spec_text: str) -> list[dict]:
"""Парсинг spec.txt в список примеров, аналогично --dump-tests."""
examples: list[dict] = []
section = ""
state = "text"
md_lines: list[str] = []
html_lines: list[str] = []
number = 0
# splitlines(keepends=True) сохраняет \n у каждой строки — это важно,
# потому что итоговый markdown/html собирается через "".join без потери
# переводов строк.
for raw in spec_text.splitlines(keepends=True):
line = raw.rstrip("\n").rstrip("\r")
if state == "text":
if FENCE_OPEN.match(line):
state = "md"
md_lines = []
html_lines = []
continue
m = HEADER.match(line)
if m:
section = m.group(1).strip()
elif state == "md":
if line == ".":
state = "html"
continue
md_lines.append(raw)
elif state == "html":
if FENCE_CLOSE.match(line):
number += 1
md_text = "".join(md_lines).replace("→", "\t")
html_text = "".join(html_lines).replace("→", "\t")
examples.append({
"number": number,
"section": section,
"markdown": md_text,
"html": html_text,
})
state = "text"
continue
html_lines.append(raw)
return examples
# --------------------------------------------------------------------------- #
# Skip-list
# --------------------------------------------------------------------------- #
def load_skip_list(version: str) -> dict:
v = SKIP_LIST.get(version, {})
return {
"sections": dict(v.get("sections", {})),
"examples": {int(k): val for k, val in v.get("examples", {}).items()},
}
def skip_reason(example: dict, skip_list: dict) -> Optional[str]:
if example["number"] in skip_list["examples"]:
return skip_list["examples"][example["number"]]
if example["section"] in skip_list["sections"]:
return skip_list["sections"][example["section"]]
return None
# --------------------------------------------------------------------------- #
# Кодогенерация OneScript
# --------------------------------------------------------------------------- #
def slugify(s: str) -> str:
s = s.lower().strip()
s = re.sub(r"[^a-z0-9]+", "-", s)
return s.strip("-") or "unsorted"
def to_identifier(s: str) -> str:
s = re.sub(r"[^A-Za-z0-9]+", "_", s)
return s.strip("_") or "x"
CONTINUATION_INDENT = " " # 8 пробелов перед `|` и оператором `+`
def to_oscript_literal(s: str) -> str:
"""Превращает Python-строку в выражение OneScript.
Использует многострочный литерал OneScript (`"line1\n|line2"`), чтобы избежать
цепочек `+ Символы.ПС + "..."`. Табы остаются как `Символы.Таб` через `+`,
т.к. внутри строкового литерала их нельзя выделить визуально.
"""
if not s:
return '""'
# Нормализуем \r\n → \n (spec.txt уже LF, но на всякий случай).
s = s.replace("\r\n", "\n").replace("\r", "\n")
segments = s.split("\t")
parts: list[str] = []
for i, seg in enumerate(segments):
if i > 0:
parts.append("Символы.Таб")
if seg:
parts.append(_multiline_literal(seg))
# пустые сегменты между табами не порождают отдельных "" — двойной таб
# выглядит как `Символы.Таб + Символы.Таб`, что и нужно.
if not parts:
return '""'
return _join_with_plus(parts)
def _multiline_literal(s: str) -> str:
"""Tab-free строка → один OneScript-литерал с `|` для продолжений."""
escaped = s.replace('"', '""')
lines = escaped.split("\n")
if len(lines) == 1:
return f'"{lines[0]}"'
out = [f'"{lines[0]}']
for line in lines[1:]:
out.append(f"{CONTINUATION_INDENT}|{line}")
return "\n".join(out) + '"'
def _join_with_plus(parts: list[str]) -> str:
if len(parts) == 1:
return parts[0]
out = [parts[0]]
for p in parts[1:]:
out.append(f"{CONTINUATION_INDENT}+ {p}")
return "\n".join(out)
def escape_quotes(s: str) -> str:
return s.replace('"', '""')
SUITE_TEMPLATE = """\
// AUTO-GENERATED by tools/sync-commonmark.py — DO NOT EDIT MANUALLY.
// CommonMark spec version: {version}
// Section: {section}
// Examples: {total} (skipped: {skipped})
//
// Источник: https://spec.commonmark.org/{version}/spec.txt
// Регенерация: python tools/sync-commonmark.py {version}
#Использовать asserts
#Использовать "../../src"
Перем _Настройки;
&ОтображаемоеИмя("commonmark_{version_id}_{section_id}")
&ТестовыйНабор
Процедура ПриСозданииОбъекта() Экспорт
_Настройки = Новый MarkdownНастройки("commonmark");
КонецПроцедуры
Процедура ПроверитьПример(Знач Номер, Знач Исходник, Знач ОжидаемыйHTML) Экспорт
Фактический = Markdown.ВHTML(Исходник, _Настройки);
Утверждения.ПроверитьРавенство(ОжидаемыйHTML, Фактический,
"CommonMark #" + Номер + " [{section_label}]");
КонецПроцедуры
{methods}
"""
def render_method(example: dict, skip_list: dict) -> str:
reason = skip_reason(example, skip_list)
skip_line = ""
if reason:
skip_line = f'&Выключен("{escape_quotes(reason)}")\n'
md_lit = to_oscript_literal(example["markdown"])
html_lit = to_oscript_literal(example["html"])
return (
f"&Тест\n"
f"{skip_line}"
f"Процедура Пример_{example['number']:04d}() Экспорт\n"
f" Исходник = {md_lit};\n"
f" Ожидаемый = {html_lit};\n"
f" ПроверитьПример({example['number']}, Исходник, Ожидаемый);\n"
f"КонецПроцедуры\n"
)
def render_suite(section: str, examples: list[dict], version: str,
skip_list: dict) -> str:
skipped = sum(1 for e in examples if skip_reason(e, skip_list) is not None)
methods = "\n".join(render_method(e, skip_list) for e in examples)
return SUITE_TEMPLATE.format(
version=version,
section=section,
section_label=escape_quotes(section),
section_id=to_identifier(section),
version_id=to_identifier(version),
total=len(examples),
skipped=skipped,
methods=methods,
)
# --------------------------------------------------------------------------- #
# Main
# --------------------------------------------------------------------------- #
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Sync CommonMark spec tests into OneUnit suites",
)
parser.add_argument("version", nargs="?", default=DEFAULT_VERSION,
help=f"CommonMark spec version (default: {DEFAULT_VERSION})")
parser.add_argument("--force", action="store_true",
help="Re-download spec.txt even if cached")
parser.add_argument("--keep-existing", action="store_true",
help="Don't delete existing tests/commonmark/*.os before generating")
args = parser.parse_args(argv)
print(f"=== Sync CommonMark {args.version} ===")
spec_text = download_spec(args.version, args.force)
examples = parse_spec(spec_text)
print(f"[parse] {len(examples)} examples")
json_path = CACHE_DIR / f"spec-{args.version}.json"
json_path.write_text(
json.dumps(examples, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
print(f"[dump] {json_path.relative_to(PROJECT_ROOT)}")
skip_list = load_skip_list(args.version)
if skip_list["sections"] or skip_list["examples"]:
print(f"[skip] sections={len(skip_list['sections'])}, "
f"examples={len(skip_list['examples'])}")
by_section: dict[str, list[dict]] = {}
for ex in examples:
section = ex["section"] or "Unsorted"
by_section.setdefault(section, []).append(ex)
COMMONMARK_DIR.mkdir(parents=True, exist_ok=True)
if not args.keep_existing:
removed = 0
for f in COMMONMARK_DIR.glob("*.os"):
f.unlink()
removed += 1
if removed:
print(f"[clean] removed {removed} stale .os file(s)")
total_generated = 0
total_examples = 0
total_skipped = 0
for section, exs in by_section.items():
slug = slugify(section)
out = COMMONMARK_DIR / f"{slug}.os"
out.write_text(
render_suite(section, exs, args.version, skip_list),
encoding="utf-8",
)
skipped = sum(1 for e in exs if skip_reason(e, skip_list) is not None)
total_generated += 1
total_examples += len(exs)
total_skipped += skipped
print(f" {out.name}: {len(exs):3d} examples (skipped {skipped})")
print(f"[done] {total_generated} suites, {total_examples} examples, "
f"{total_skipped} skipped")
print("\nRun: oscript tasks/test_commonmark.os")
return 0
if __name__ == "__main__":
sys.exit(main())