Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- from watchdog.events import FileSystemEventHandler
- from watchdog.observers import Observer
- import aops
- import bon
- envs = {
- "problem": ("\\begin{problem}", "\\end{problem}"),
- "solution": ("\\begin{soln}", "\\end{soln}"),
- }
- WATCH_FILE = os.path.join(bon.TMP_PATH, bon.TMP_FILE_NAME)
- OUTPUT_FILE = os.path.join(bon.HOME, "bon/bon-db/", f"{bon.DB_NAME}{bon.DB_FILE_EXT}")
- # class TexChangeHandler(FileSystemEventHandler):
- # def on_modified(self, event):
- # log(f"Modified: {event.src_path}")
- # if os.path.abspath(event.src_path) == os.path.abspath(WATCH_FILE):
- # log("Ignored: Not the target file.")
- # with open(WATCH_FILE, "r", encoding="utf-8") as f:
- # tex_content = f.read()
- # with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
- # db_content = f.read()
- # with open(OUTPUT_FILE, "w", encoding="utf-8") as out:
- # out.write(transform(db_content, tex_content))
- # print("yes")
- #
- class TexChangeHandler(FileSystemEventHandler):
- def on_modified(self, event):
- log(f"🔔 Modified: {event.src_path}")
- if os.path.abspath(event.src_path) != os.path.abspath(WATCH_FILE):
- log("❌ Ignored: Not the target file.")
- return
- try:
- with open(WATCH_FILE, "r", encoding="utf-8") as f:
- tex_content = f.read()
- with open(OUTPUT_FILE, "r", encoding="utf-8") as f:
- db_content = f.read()
- updated = transform(db_content, tex_content)
- with open(OUTPUT_FILE, "w", encoding="utf-8") as out:
- out.write(updated)
- log("✅ Wrote updated content to DB file.")
- except Exception as e:
- log(f"❌ ERROR: {e}")
- def transform(db_content: str, tex_content: str) -> str:
- fin_list = []
- db_list = db_content.split(bon.SEPARATOR)
- prob_spos = tex_content.index(envs["problem"][0])
- prob_epos = tex_content.index(envs["problem"][1])
- prob_cont = tex_content[prob_spos : prob_epos + len(envs["problem"][1])]
- fin_list.append(db_list[0])
- fin_list.append(prob_cont)
- i = 0
- while tex_content[i:].find(envs["solution"][0]) != -1:
- j = tex_content[i:].index(envs["solution"][0])
- j_cpos = aops.bracket_cpos(tex_content[i:], envs["solution"], j)
- fin_list.append(tex_content[j : j_cpos + len(envs["solution"][1])])
- i = j_cpos
- return (bon.SEPARATOR).join(fin_list)
- def start_watcher():
- log("Watcher started")
- event_handler = TexChangeHandler()
- observer = Observer()
- observer.schedule(event_handler, path=os.path.dirname(WATCH_FILE), recursive=False)
- observer.start()
- log("Watcher actually started")
- return observer
- def log(msg):
- with open("/tmp/tmptex_watcher.log", "a", encoding="utf-8") as f:
- f.write(msg + "\n")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement