|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Inject canonical, robots, description, and Open Graph tags into every |
| 3 | +docs/*.html page that doesn't already have them. |
| 4 | +
|
| 5 | +Idempotent: re-running on the same tree adds nothing. |
| 6 | +
|
| 7 | +Strategy: |
| 8 | + - Skip 404.html (intentionally minimal). |
| 9 | + - Read <title> for og:title / fallback description. |
| 10 | + - Read first <h1> + first sentence of first <p> for a richer description |
| 11 | + when no <meta name="description"> is present. |
| 12 | + - Insert tags immediately after the existing <link rel="stylesheet"> line |
| 13 | + (or, failing that, before </head>). |
| 14 | +""" |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import re |
| 18 | +import sys |
| 19 | +from pathlib import Path |
| 20 | + |
| 21 | +DOCS = Path(__file__).resolve().parent.parent |
| 22 | +SITE = "https://sauravbhattacharya001.github.io/GraphVisual/" |
| 23 | +SKIP = {"404.html"} |
| 24 | + |
| 25 | +TITLE_RE = re.compile(r"<title>(.*?)</title>", re.IGNORECASE | re.DOTALL) |
| 26 | +H1_RE = re.compile(r"<h1[^>]*>(.*?)</h1>", re.IGNORECASE | re.DOTALL) |
| 27 | +P_RE = re.compile(r"<p[^>]*>(.*?)</p>", re.IGNORECASE | re.DOTALL) |
| 28 | +TAG_STRIP_RE = re.compile(r"<[^>]+>") |
| 29 | +WS_RE = re.compile(r"\s+") |
| 30 | +STYLE_LINK_RE = re.compile( |
| 31 | + r'(\s*)<link\s+rel="stylesheet"\s+href="styles\.css"\s*/?>\s*\n', |
| 32 | + re.IGNORECASE, |
| 33 | +) |
| 34 | +HEAD_END_RE = re.compile(r"\s*</head>", re.IGNORECASE) |
| 35 | + |
| 36 | + |
| 37 | +def _clean(s: str) -> str: |
| 38 | + return WS_RE.sub(" ", TAG_STRIP_RE.sub("", s)).strip() |
| 39 | + |
| 40 | + |
| 41 | +def _truncate(text: str, limit: int = 160) -> str: |
| 42 | + text = text.strip() |
| 43 | + if len(text) <= limit: |
| 44 | + return text |
| 45 | + cut = text[: limit - 1] |
| 46 | + sp = cut.rfind(" ") |
| 47 | + if sp > limit * 0.6: |
| 48 | + cut = cut[:sp] |
| 49 | + return cut.rstrip(",.;:- ") + "\u2026" |
| 50 | + |
| 51 | + |
| 52 | +def _attr_escape(value: str) -> str: |
| 53 | + return ( |
| 54 | + value.replace("&", "&") |
| 55 | + .replace('"', """) |
| 56 | + .replace("<", "<") |
| 57 | + .replace(">", ">") |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +def derive_meta(html: str, filename: str) -> tuple[str, str, str]: |
| 62 | + """Return (page_title, og_title, description).""" |
| 63 | + title_match = TITLE_RE.search(html) |
| 64 | + raw_title = _clean(title_match.group(1)) if title_match else filename |
| 65 | + # og:title strips the " - GraphVisual" / " - GraphVisual Docs" suffix. |
| 66 | + og_title = re.sub(r"\s*[\u2013\u2014\-]\s*GraphVisual.*$", "", raw_title).strip() or raw_title |
| 67 | + |
| 68 | + desc_match = re.search( |
| 69 | + r'<meta\s+name="description"\s+content="([^"]+)"', html, re.IGNORECASE |
| 70 | + ) |
| 71 | + if desc_match: |
| 72 | + description = desc_match.group(1).strip() |
| 73 | + else: |
| 74 | + h1 = H1_RE.search(html) |
| 75 | + h1_text = _clean(h1.group(1)) if h1 else og_title |
| 76 | + p_text = "" |
| 77 | + for p in P_RE.finditer(html): |
| 78 | + candidate = _clean(p.group(1)) |
| 79 | + if len(candidate) >= 40: |
| 80 | + p_text = candidate |
| 81 | + break |
| 82 | + if p_text: |
| 83 | + description = f"{h1_text}: {p_text}" if h1_text and h1_text not in p_text else p_text |
| 84 | + else: |
| 85 | + description = f"{h1_text} - GraphVisual documentation." |
| 86 | + # Strip leading emoji / symbols so descriptions read cleanly. |
| 87 | + description = re.sub(r"^[^\w]+", "", description).strip() |
| 88 | + return raw_title, og_title, _truncate(description) |
| 89 | + |
| 90 | + |
| 91 | +def inject(html: str, filename: str) -> tuple[str, bool]: |
| 92 | + raw_title, og_title, description = derive_meta(html, filename) |
| 93 | + canonical_url = SITE + filename |
| 94 | + |
| 95 | + new_tags: list[str] = [] |
| 96 | + if 'name="description"' not in html.lower(): |
| 97 | + new_tags.append( |
| 98 | + f' <meta name="description" content="{_attr_escape(description)}">' |
| 99 | + ) |
| 100 | + if 'rel="canonical"' not in html.lower(): |
| 101 | + new_tags.append(f' <link rel="canonical" href="{canonical_url}">') |
| 102 | + if 'name="robots"' not in html.lower(): |
| 103 | + new_tags.append(' <meta name="robots" content="index, follow">') |
| 104 | + if "og:title" not in html.lower(): |
| 105 | + new_tags.append( |
| 106 | + f' <meta property="og:title" content="{_attr_escape(og_title)}">' |
| 107 | + ) |
| 108 | + if "og:description" not in html.lower(): |
| 109 | + new_tags.append( |
| 110 | + f' <meta property="og:description" content="{_attr_escape(description)}">' |
| 111 | + ) |
| 112 | + if "og:type" not in html.lower(): |
| 113 | + new_tags.append(' <meta property="og:type" content="website">') |
| 114 | + if "og:url" not in html.lower(): |
| 115 | + new_tags.append(f' <meta property="og:url" content="{canonical_url}">') |
| 116 | + if "og:site_name" not in html.lower(): |
| 117 | + new_tags.append(' <meta property="og:site_name" content="GraphVisual">') |
| 118 | + if "twitter:card" not in html.lower(): |
| 119 | + new_tags.append( |
| 120 | + ' <meta name="twitter:card" content="summary_large_image">' |
| 121 | + ) |
| 122 | + if "twitter:title" not in html.lower(): |
| 123 | + new_tags.append( |
| 124 | + f' <meta name="twitter:title" content="{_attr_escape(og_title)}">' |
| 125 | + ) |
| 126 | + if "twitter:description" not in html.lower(): |
| 127 | + new_tags.append( |
| 128 | + f' <meta name="twitter:description" content="{_attr_escape(description)}">' |
| 129 | + ) |
| 130 | + |
| 131 | + if not new_tags: |
| 132 | + return html, False |
| 133 | + |
| 134 | + block = "\n".join(new_tags) + "\n" |
| 135 | + |
| 136 | + style_match = STYLE_LINK_RE.search(html) |
| 137 | + if style_match: |
| 138 | + insert_at = style_match.start() |
| 139 | + return html[:insert_at] + "\n" + block + html[insert_at:].lstrip("\n"), True |
| 140 | + |
| 141 | + head_end_match = HEAD_END_RE.search(html) |
| 142 | + if head_end_match: |
| 143 | + insert_at = head_end_match.start() |
| 144 | + return html[:insert_at] + "\n" + block + html[insert_at:].lstrip("\n"), True |
| 145 | + |
| 146 | + # No <head> closing tag found; bail out without modification. |
| 147 | + return html, False |
| 148 | + |
| 149 | + |
| 150 | +def main() -> int: |
| 151 | + docs = DOCS |
| 152 | + if not docs.exists(): |
| 153 | + print(f"docs dir not found at {docs}", file=sys.stderr) |
| 154 | + return 1 |
| 155 | + |
| 156 | + updated: list[str] = [] |
| 157 | + for path in sorted(docs.glob("*.html")): |
| 158 | + if path.name in SKIP: |
| 159 | + continue |
| 160 | + original = path.read_text(encoding="utf-8") |
| 161 | + new_html, changed = inject(original, path.name) |
| 162 | + if changed: |
| 163 | + path.write_text(new_html, encoding="utf-8", newline="\n") |
| 164 | + updated.append(path.name) |
| 165 | + |
| 166 | + print(f"Updated {len(updated)} page(s).") |
| 167 | + for name in updated: |
| 168 | + print(f" - {name}") |
| 169 | + return 0 |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + raise SystemExit(main()) |
0 commit comments