| 26 | |
| 27 | |
| 28 | def save_state(state: LearnedState, directory: Path) -> None: |
| 29 | directory.mkdir(parents=True, exist_ok=True) |
| 30 | data = asdict(state) |
| 31 | data["schema_version"] = SCHEMA_VERSION |
| 32 | target = directory / STATE_FILENAME |
| 33 | fd, tmp_path = tempfile.mkstemp(dir=directory, suffix=".tmp") |
| 34 | try: |
| 35 | with open(fd, "w", encoding="utf-8") as f: |
| 36 | json.dump(data, f, indent=2) |
| 37 | Path(tmp_path).replace(target) |
| 38 | except Exception: |
| 39 | Path(tmp_path).unlink(missing_ok=True) |
| 40 | raise |
| 41 | |
| 42 | |
| 43 | def load_state(directory: Path) -> LearnedState: |