Separate one-time bootstrap, historical deployment examples and local validation. Document final hostname and historical status; exclude credentials and runtime data.
188 lines
11 KiB
Python
188 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Build fictional exhibition artifacts locally. No network or database access."""
|
|
|
|
import argparse
|
|
import csv
|
|
from datetime import date, datetime, time, timedelta, timezone
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import zipfile
|
|
|
|
CATALOG = Path(__file__).resolve().parents[2] / "deploy/kubernetes/exhibition/demo/catalog.json"
|
|
MARKER = "manifest.json"
|
|
JST = timezone(timedelta(hours=9))
|
|
|
|
|
|
def json_bytes(value):
|
|
return (json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode()
|
|
|
|
|
|
def sha(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def escaped(text):
|
|
return text.replace("\\", "\\\\").replace("\n", "\\n").replace(";", "\\;").replace(",", "\\,")
|
|
|
|
|
|
def folded(lines):
|
|
"""RFC 5545/6350 content lines, at most 75 UTF-8 octets including continuation."""
|
|
result = []
|
|
for line in lines:
|
|
current = ""
|
|
for char in line:
|
|
if len((current + char).encode()) > 75:
|
|
result.append(current)
|
|
current = " "
|
|
current += char
|
|
result.append(current)
|
|
return ("\r\n".join(result) + "\r\n").encode()
|
|
|
|
|
|
def utc(value):
|
|
return value.astimezone(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
|
|
|
|
|
def calendar(component, properties):
|
|
return folded(["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//PagesWiki//Synthetic Exhibition//JA",
|
|
"BEGIN:" + component, *properties, "END:" + component, "END:VCALENDAR"])
|
|
|
|
|
|
def build(base_date, prefix="/exhibition-demo"):
|
|
if not re.fullmatch(r"/[a-zA-Z0-9_-]+(?:/[a-zA-Z0-9_-]+)*", prefix):
|
|
raise ValueError("target prefix must be a dedicated absolute ASCII path, not /")
|
|
source = json.loads(CATALOG.read_text())
|
|
pages = {}
|
|
notice = source["notice"]
|
|
|
|
def link(path, label=None):
|
|
return f"[{label or path.rsplit('/', 1)[-1]}]({prefix}/{path})"
|
|
|
|
def page(path, intro, details=()):
|
|
parent = path.rsplit("/", 1)[0] if "/" in path else "展示案内"
|
|
text = f"# {path.rsplit('/', 1)[-1]}\n\n{intro}\n\n> {notice}\n\n"
|
|
if details:
|
|
text += "## 見どころ\n\n" + "\n".join("- " + item for item in details) + "\n\n"
|
|
text += f"## この場所のページ\n\n{{{{children:{prefix}/{path}}}}}\n\n"
|
|
if path != "展示案内":
|
|
text += f"## 街区を巡る\n\n{link(parent, 'ひとつ上の案内')} · {link('展示案内', '展示全体の案内')}\n"
|
|
pages[path + ".md"] = text
|
|
|
|
page("展示案内", "灯架図書館、雲庭研究街区、帆灯運用街区を巡る展示です。階層の移動から、資料、タスク、予定のつながりを体験できます。")
|
|
pages["展示案内.md"] += "\n## 街区を巡る\n\n| 街区 | 体験 |\n| --- | --- |\n" + "".join(
|
|
f"| {link(d['name'])} | {label} |\n" for d, label in zip(source["districts"], ["資料を読む", "合成データを比べる", "準備と引き継ぎをつなぐ"]))
|
|
# The landing page lives beside the three district roots, not above them.
|
|
pages["展示案内.md"] = pages["展示案内.md"].replace(f"children:{prefix}/展示案内", f"children:{prefix}")
|
|
for district in source["districts"]:
|
|
page(district["name"], district["intro"])
|
|
for street in district["streets"]:
|
|
street_path = district["name"] + "/" + street["name"]
|
|
page(street_path, street["intro"])
|
|
for spot in street["spots"]:
|
|
page(street_path + "/" + spot["name"], spot["intro"], spot["details"])
|
|
for entry in source["deep_pages"]:
|
|
page(entry["parent"] + "/" + entry["name"], entry["intro"], entry["details"])
|
|
csv_path = "雲庭研究街区/観測通り/風見テラス/合成観測.csv"
|
|
pages["雲庭研究街区/観測通り/風見テラス.md"] += f"\n## 合成観測データ\n\n{link(csv_path, '合成観測CSVを開く')}\n\n| 標本 | 回転数 | 注記 |\n| --- | ---: | --- |\n| SYN-001 | 18 | 合成値 |\n| SYN-002 | 25 | 合成値 |\n| SYN-003 | 32 | 合成値 |\n"
|
|
pages["雲庭研究街区/解析通り/再現ノート.md"] += "\n## 集計のコード例\n\n次のコードはCSVを読むだけで、外部通信や書き込みを行いません。\n\n```python\nimport csv\n\nwith open(\"合成観測.csv\", encoding=\"utf-8\", newline=\"\") as source:\n rows = list(csv.DictReader(source))\nprint(sum(int(row[\"rotations\"]) for row in rows))\n```\n"
|
|
pages["帆灯運用街区/案内通り/案内台本.md"] += "\n## 五分の案内コース\n\n1. " + link("灯架図書館/閲覧通り/星図の書棚") + "で四階層目の資料を開きます。\n2. " + link("雲庭研究街区/観測通り/風見テラス") + "で表とCSVを見比べます。\n3. " + link("帆灯運用街区/整備通り/引継ぎ広場") + "からタスクと予定の紹介に進みます。\n"
|
|
stream = io.StringIO(newline="")
|
|
writer = csv.writer(stream, lineterminator="\n")
|
|
writer.writerow(["sample_id", "date", "station", "rotations", "synthetic"])
|
|
for i in range(14):
|
|
writer.writerow([f"SYN-{i+1:03d}", (base_date + timedelta(days=i-6)).isoformat(), ["琥珀", "翡翠", "真珠"][i % 3], 18 + i * 7 % 31, "true"])
|
|
wiki = {path: text.encode() for path, text in pages.items()}
|
|
wiki[csv_path] = stream.getvalue().encode()
|
|
files = {"wiki/" + path: data for path, data in wiki.items()}
|
|
buffer = io.BytesIO()
|
|
with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
|
for path, data in sorted(wiki.items()):
|
|
info = zipfile.ZipInfo(path, date_time=(2020, 1, 1, 0, 0, 0))
|
|
info.compress_type = zipfile.ZIP_DEFLATED
|
|
info.external_attr = 0o100644 << 16
|
|
archive.writestr(info, data)
|
|
files["wiki.zip"] = buffer.getvalue()
|
|
stamp = utc(datetime.combine(base_date, time(), JST))
|
|
fixture = {"schema_version": 1, "dataset_id": source["dataset_id"], "synthetic": True,
|
|
"base_date": base_date.isoformat(), "timezone": "Asia/Tokyo", "target_prefix": prefix,
|
|
"tasks": [], "events": [], "contacts": source["contacts"]}
|
|
for task in source["tasks"]:
|
|
due = base_date + timedelta(days=task["due_offset"])
|
|
uid = task["id"] + "@example.invalid"
|
|
fixture["tasks"].append({**task, "uid": uid, "due_date": due.isoformat(), "page_path": prefix + "/" + task["page"]})
|
|
properties = ["UID:" + uid, "DTSTAMP:" + stamp, "SUMMARY:" + escaped(task["title"]),
|
|
"DESCRIPTION:" + escaped(notice + "\n" + prefix + "/" + task["page"]),
|
|
"DUE;VALUE=DATE:" + due.strftime("%Y%m%d"), "STATUS:" + task["status"],
|
|
"PERCENT-COMPLETE:" + ("100" if task["status"] == "COMPLETED" else "50" if task["status"] == "IN-PROCESS" else "0")]
|
|
if task["status"] == "COMPLETED":
|
|
properties.append("COMPLETED:" + utc(datetime.combine(due, time(15), JST)))
|
|
files["tasks/" + task["id"] + ".ics"] = calendar("VTODO", properties)
|
|
event_components = []
|
|
for event in source["events"]:
|
|
start = datetime.combine(base_date + timedelta(days=event["offset"]), time(event["hour"]), JST)
|
|
end = start + timedelta(minutes=event["duration_minutes"])
|
|
uid = event["id"] + "@example.invalid"
|
|
fixture["events"].append({**event, "uid": uid, "start": start.isoformat(), "end": end.isoformat()})
|
|
properties = ["UID:" + uid, "DTSTAMP:" + stamp, "DTSTART:" + utc(start), "DTEND:" + utc(end),
|
|
"SUMMARY:" + escaped(event["title"]), "DESCRIPTION:" + escaped(notice), "LOCATION:" + escaped(event["location"])]
|
|
files["events/" + event["id"] + ".ics"] = calendar("VEVENT", properties)
|
|
event_components += ["BEGIN:VEVENT", *properties, "END:VEVENT"]
|
|
files["calendar.ics"] = folded(["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//PagesWiki//Synthetic Exhibition//JA", *event_components, "END:VCALENDAR"])
|
|
for contact in source["contacts"]:
|
|
if not re.fullmatch(r"[a-z0-9-]+@example\.invalid", contact["email"]):
|
|
raise ValueError("only example.invalid contact addresses are allowed")
|
|
files["contacts/" + contact["id"] + ".vcf"] = folded(["BEGIN:VCARD", "VERSION:3.0", "UID:" + contact["id"] + "@example.invalid",
|
|
"FN:" + escaped(contact["name"]), "N:;" + escaped(contact["name"]) + ";;;", "ORG:" + escaped(contact["organization"]),
|
|
"EMAIL:" + contact["email"], "NOTE:" + escaped(notice), "END:VCARD"])
|
|
files["fixtures.json"] = json_bytes(fixture)
|
|
manifest = {"dataset_id": source["dataset_id"], "schema_version": 1, "synthetic": True, "base_date": base_date.isoformat(),
|
|
"target_prefix": prefix, "page_count": len(pages), "archive_entry_count": len(wiki),
|
|
"files": {name: sha(data) for name, data in sorted(files.items())}}
|
|
files[MARKER] = json_bytes(manifest)
|
|
return files
|
|
|
|
|
|
def write_output(output, files):
|
|
"""Refuse unrelated/modified files and symlinks; reruns only replace owned artifacts."""
|
|
output = Path(output).absolute()
|
|
if any(path.is_symlink() for path in [output, *output.parents]):
|
|
raise ValueError("output path must not contain symlinks")
|
|
existing = list(output.rglob("*")) if output.exists() else []
|
|
if any(path.is_symlink() for path in existing):
|
|
raise ValueError("output contains a symlink")
|
|
names = {str(path.relative_to(output)) for path in existing if path.is_file()}
|
|
if existing:
|
|
if MARKER not in names:
|
|
raise ValueError("output is not an owned exhibition directory; choose a new directory")
|
|
previous = json.loads((output / MARKER).read_text())
|
|
expected = set(previous.get("files", {})) | {MARKER}
|
|
if previous.get("dataset_id") != "pageswiki-exhibition-fiction-v1" or names != expected or names != set(files):
|
|
raise ValueError("output contains unrelated files or a different dataset layout")
|
|
if any(sha((output / name).read_bytes()) != digest for name, digest in previous["files"].items()):
|
|
raise ValueError("output contains modified artifacts; choose a new directory")
|
|
for name, data in files.items():
|
|
path = output / name
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_bytes(data)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-date", required=True, type=date.fromisoformat, help="展示開始日 YYYY-MM-DD、日本時間")
|
|
parser.add_argument("--output", required=True, type=Path, help="新規またはこのツールが生成したディレクトリ")
|
|
parser.add_argument("--target-prefix", default="/exhibition-demo")
|
|
args = parser.parse_args()
|
|
try:
|
|
files = build(args.base_date, args.target_prefix)
|
|
write_output(args.output, files)
|
|
except (ValueError, OSError) as error:
|
|
parser.exit(2, f"生成を中止しました: {error}\n")
|
|
print(f"ローカル生成完了: {args.output} (Wiki 26ページ、CSV 1件、タスク 8件、予定 6件、連絡先 6件)。投入は未実施です。")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|