okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f9bfe8bc1
main
1"""Replace a file that another program may be reading, on Windows as well as everywhere else. 2 3A job record (a Time-skip `run.json`, a tuning `job.json`) is rewritten at every phase and READ by the app's host every couple of seconds. 4On Windows, `os.replace` onto a file that is open in another process fails with PermissionError ("Access is denied") for as long as the 5reader holds it. That is a split second, but a job saves many times, so a Time-skip or a tune died at random with that error. The fix is 6to wait that split second and try again; any other error, and a PermissionError that does not go away, is raised as before. 7""" 8 9from __future__import annotations 10 11import os 12import time 13from pathlib import Path 14from typing import Union 15 16PathLike = Union [str ,"os.PathLike[str]" ] 17 18#: how long a held file is waited for, in total (seconds) and between tries 19PATIENCE_S = 5.0 20STEP_S = 0.02 21 22 23def replace (src :PathLike ,dst :PathLike ,* ,patience :float = PATIENCE_S ,sleep = time .sleep ,clock = time .monotonic )-> None : 24deadline = clock ()+ patience 25step = STEP_S 26while True : 27try : 28os .replace (src ,dst ) 29return 30except PermissionError : 31if os .name != "nt" or clock ()>= deadline : 32raise 33sleep (step ) 34step = min (step * 1.5 ,0.25 ) 35 36 37def write_text (path :PathLike ,text :str ,* ,encoding :str = "utf-8" )-> None : 38"""Write `text` to `path` through a neighbouring temporary file, so a reader never sees half a record.""" 39target = Path (path ) 40tmp = target .with_suffix (target .suffix + ".tmp" )if target .suffix else target .with_name (target .name + ".tmp" ) 41tmp .write_text (text ,encoding = encoding ) 42replace (tmp ,target )