تمرين إعادة البناء
مدقق Frontmatter بسيط
تحقق من وجود مفاتيح frontmatter مطلوبة في ملفات Markdown.
python
~25 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
import argparse
from pathlib import Path
def read_frontmatter(path: Path) -> dict[str, str]:
lines = path.read_text(encoding="utf-8").splitlines()
if not lines or lines[0] != "---":
return {}
data = {}
for line in lines[1:]:
if line == "---":
break
if ":" in line:
key, value = line.split(":", 1)
data[key.strip()] = value.strip()
return data
def main() -> None:
parser = argparse.ArgumentParser(description="Check required frontmatter keys in Markdown files.")
parser.add_argument("root", type=Path)
parser.add_argument("--required", nargs="+", default=["title", "description", "weight"])
args = parser.parse_args()
failed = False
for path in sorted(args.root.rglob("*.md")):
data = read_frontmatter(path)
missing = [key for key in args.required if key not in data]
if missing:
failed = True
print(f"{path}: missing {', '.join(missing)}")
if not failed:
print("All files passed")
if __name__ == "__main__":
main()اكتب هنا