#!/usr/bin/env python3 """ตรวจความสมดุลของ tag ในไฟล์ HTML (ไม่ต้องพึ่ง dependency ภายนอก) ใช้: python tools/check_html_balance.py index.html คืน exit code 1 ถ้าพบ tag ค้างหรือปิดเกิน · 0 ถ้าผ่าน """ import sys from html.parser import HTMLParser VOID_ELEMENTS = { "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", } class BalanceChecker(HTMLParser): def __init__(self): super().__init__(convert_charrefs=True) self.stack = [] self.errors = [] def handle_starttag(self, tag, attrs): if tag not in VOID_ELEMENTS: self.stack.append((tag, self.getpos())) def handle_startendtag(self, tag, attrs): pass # ปิดในตัว def handle_endtag(self, tag): if tag in VOID_ELEMENTS: return if not self.stack: self.errors.append("ปิด %s เกิน (บรรทัด %d)" % (tag, self.getpos()[0])) return open_tag, pos = self.stack[-1] if open_tag == tag: self.stack.pop() else: self.errors.append( "ไม่ตรงกัน: เปิด <%s> ที่บรรทัด %d แต่ปิด ที่บรรทัด %d" % (open_tag, pos[0], tag, self.getpos()[0]) ) def main(paths): failed = False for path in paths: checker = BalanceChecker() with open(path, encoding="utf-8") as handle: checker.feed(handle.read()) print(path) for tag, pos in checker.stack: failed = True print(" ค้าง: <%s> เปิดที่บรรทัด %d ไม่ปิด" % (tag, pos[0])) for message in checker.errors: failed = True print(" " + message) if not checker.stack and not checker.errors: print(" OK — tag สมดุล") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:] or ["index.html"]))