|
| 1 | +#!/usr/bin/env python |
| 2 | +"""Update frontmatter of markdown files.""" |
| 3 | + |
| 4 | +import argparse |
| 5 | +from pathlib import Path |
| 6 | +from typing import Any, Dict, Optional |
| 7 | + |
| 8 | +import frontmatter |
| 9 | + |
| 10 | + |
| 11 | +def extract_main_heading(markdown_content: str) -> Optional[str]: |
| 12 | + """ |
| 13 | + Extracts the first level 1 heading from the provided Markdown content. |
| 14 | +
|
| 15 | + Args: |
| 16 | + markdown_content: A string containing Markdown text. |
| 17 | +
|
| 18 | + Returns: |
| 19 | + The text of the first level 1 heading, or None if no such heading is found. |
| 20 | + """ |
| 21 | + lines = markdown_content.split("\n") |
| 22 | + |
| 23 | + return next((line[2:] for line in lines if line.startswith("# ")), None) |
| 24 | + |
| 25 | + |
| 26 | +def calc_title(post: frontmatter.Post) -> str: |
| 27 | + """Calculate the title of the post.""" |
| 28 | + return extract_main_heading(post.content) or post.get("title", "") |
| 29 | + |
| 30 | + |
| 31 | +def calc_comment(post: frontmatter.Post) -> bool: |
| 32 | + """Calculate if the post has comments.""" |
| 33 | + return bool(post.get("comments", True)) |
| 34 | + |
| 35 | + |
| 36 | +def calculate_update(post: frontmatter.Post) -> dict: |
| 37 | + """Calculate if the frontmatter needs to be updated.""" |
| 38 | + expected_title = calc_title(post) |
| 39 | + expected_comment = calc_comment(post) |
| 40 | + update: Dict[str, Any] = {} |
| 41 | + if expected_title and expected_title != post.get("title"): |
| 42 | + update["title"] = expected_title |
| 43 | + if expected_comment != post.get("comments"): |
| 44 | + update["comments"] = expected_comment |
| 45 | + return update |
| 46 | + |
| 47 | + |
| 48 | +def process_file(markdown_path: Path) -> None: |
| 49 | + """Process a single file.""" |
| 50 | + if not (markdown_path.is_file() and markdown_path.suffix == ".md"): |
| 51 | + return |
| 52 | + raw_text = markdown_path.read_text() |
| 53 | + post = frontmatter.loads(raw_text) |
| 54 | + |
| 55 | + update = calculate_update(post) |
| 56 | + if update: |
| 57 | + for key, value in update.items(): |
| 58 | + post[key] = value |
| 59 | + new_text = frontmatter.dumps(post) |
| 60 | + print(f"Updating {markdown_path}") # noqa: T201 |
| 61 | + markdown_path.write_text(new_text) |
| 62 | + |
| 63 | + |
| 64 | +def parse_args() -> argparse.Namespace: |
| 65 | + """Parse command line arguments.""" |
| 66 | + parser = argparse.ArgumentParser(description="Update frontmatter of markdown files") |
| 67 | + parser.add_argument("markdown_path", type=str, nargs="+", help="Path or glob to markdown files") |
| 68 | + return parser.parse_args() |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + args = parse_args() |
| 73 | + documents = args.markdown_path |
| 74 | + for document in documents: |
| 75 | + for path in Path().glob(document): |
| 76 | + process_file(path) |
0 commit comments