#!/usr/bin/env python3 # -*- coding: utf-8 -*- """stamp-schedules.py — เติม/อัปเดตฟิลด์ "updated" (ISO YYYY-MM-DD) ใน scheduleslist/*.json ที่มา: หน้า #/check แสดง "อัปเดตล่าสุด ... ที่แล้ว" โดยนับจากฟิลด์ "updated" ในไฟล์ตาราง เบราว์เซอร์อ่าน Last-Modified ของไฟล์ไม่ได้ (CORS) → ต้องบันทึกวันลงในไฟล์เอง หลักการ: - วันที่ = mtime ของไฟล์จริง (เวลาแก้ไขล่าสุดบนดิสก์) แปลงเป็นเวลาไทย UTC+7 - --check : ดูอย่างเดียว ไม่เขียนอะไร (dry run) - ไม่มี flag: เขียนไฟล์ที่ต้องแก้ (คง CRLF เดิมไว้) ใช้: python resource/tools/stamp-schedules.py --check python resource/tools/stamp-schedules.py """ import datetime import json import re import sys from pathlib import Path R = Path(__file__).resolve().parents[2] D = R / "resource/data/scheduleslist" TZ_OFFSET = datetime.timedelta(hours=7) # เวลาไทย dry = "--check" in sys.argv def today_th(): return (datetime.datetime.now(datetime.timezone.utc) + TZ_OFFSET).date() def mtime_date(p): return (datetime.datetime.fromtimestamp(p.stat().st_mtime, datetime.timezone.utc) + TZ_OFFSET).date() def stamp_file(p): """เติม/แก้ 'updated' หลัง route_id · คงรูปแบบ/CRLF เดิม · คืน (old, new, changed)""" raw = p.read_bytes() eol = b"\r\n" if b"\r\n" in raw[:4000] else b"\n" txt = raw.decode("utf-8") d = json.loads(txt) if not isinstance(d, dict) or "route_id" not in d: return None, None, False want = mtime_date(p).isoformat() have = str(d.get("updated") or "") if have == want: return have, want, False if re.search(r'^\s*"updated"\s*:\s*"[^"]*",\s*$', txt, re.M): new = re.sub(r'(^\s*"updated"\s*:\s*")[^"]*(",\s*$)', lambda m: m.group(1) + want + m.group(2), txt, count=1, flags=re.M) else: # แทรกหลังบรรทัด route_id (คงการเยื้องเดิม) m = re.search(r'^(\s*)"route_id"\s*:\s*("[^"]*"\s*,?\s*)$', txt, re.M) if not m: return have, want, False indent = m.group(1) new = txt[:m.end(1) + len(m.group(0)) - len(m.group(0).lstrip())] # กันพลาด ins = m.group(0) if m.group(0).rstrip().endswith(",") else m.group(0).rstrip() + "," eol_s = eol.decode() new = txt.replace(m.group(0), ins + eol_s + indent + '"updated": "' + want + '",', 1) try: json.loads(new) except Exception as e: print(f" !! JSON พังหลังแก้ — ข้ามไฟล์นี้ ({e})") return have, want, False if not dry: p.write_bytes(new.encode("utf-8")) return have, want, True def main(): files = sorted(D.glob("schedules*.json")) if not files: print(f"ไม่พบไฟล์ใน {D}") return 1 print(f"สแกน {len(files)} ไฟล์ · วันที่อ้างอิง = mtime ของไฟล์ (เวลาไทย UTC+7)") print("ไฟล์ เดิม → ใหม่ สถานะ") print("-" * 68) n_chg = 0 for p in files: old, new, changed = stamp_file(p) if new is None: print(f"{p.name:<24} (ไม่มี route_id — ข้าม)") continue mark = "แก้ไข" if changed else "ตรงแล้ว" if changed: n_chg += 1 print(f"{p.name:<24} {old or '(ไม่มี)':<12} → {new:<12} {mark}") print("-" * 68) if dry: print(f"รวมจะแก้ {n_chg} ไฟล์ (dry run — ยังไม่เขียนจริง) · รันโดยไม่ใส่ --check เพื่อเขียน") else: print(f"เขียนแล้ว {n_chg} ไฟล์") return 0 if __name__ == "__main__": sys.exit(main())