|
| 1 | +""" |
| 2 | +Restores options on startup and saves changed options on termination. |
| 3 | +""" |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import sys |
| 7 | +import json |
| 8 | +import atexit |
| 9 | +from pathlib import Path |
| 10 | +from functools import partial |
| 11 | +from enum import Enum |
| 12 | +from typing import TYPE_CHECKING |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from python_input import PythonInput |
| 16 | + |
| 17 | + |
| 18 | +class OptionsSaver: |
| 19 | + "Manages options saving and restoring" |
| 20 | + def __init__(self, repl: "PythonInput", filename: str) -> None: |
| 21 | + "Instance created at program startup" |
| 22 | + self.repl = repl |
| 23 | + |
| 24 | + # Add suffix if given file does not have one |
| 25 | + self.file = Path(filename) |
| 26 | + if not self.file.suffix: |
| 27 | + self.file = self.file.with_suffix(".json") |
| 28 | + |
| 29 | + self.file_bad = False |
| 30 | + |
| 31 | + # Read all stored options from file. Skip and report at |
| 32 | + # termination if the file is corrupt/unreadable. |
| 33 | + self.stored = {} |
| 34 | + if self.file.exists(): |
| 35 | + try: |
| 36 | + with self.file.open() as fp: |
| 37 | + self.stored = json.load(fp) |
| 38 | + except Exception: |
| 39 | + self.file_bad = True |
| 40 | + |
| 41 | + # Iterate over all options and save record of defaults and also |
| 42 | + # activate any saved options |
| 43 | + self.defaults = {} |
| 44 | + for category in self.repl.options: |
| 45 | + for option in category.options: |
| 46 | + field = option.field_name |
| 47 | + def_val, val_type = self.get_option(field) |
| 48 | + self.defaults[field] = def_val |
| 49 | + val = self.stored.get(field) |
| 50 | + if val is not None and val != def_val: |
| 51 | + |
| 52 | + # Handle special case to convert enums from int |
| 53 | + if issubclass(val_type, Enum): |
| 54 | + val = list(val_type)[val] |
| 55 | + |
| 56 | + # Handle special cases where a function must be |
| 57 | + # called to store and enact change |
| 58 | + funcs = option.get_values() |
| 59 | + if isinstance(list(funcs.values())[0], partial): |
| 60 | + if val_type is float: |
| 61 | + val = f"{val:.2f}" |
| 62 | + funcs[val]() |
| 63 | + else: |
| 64 | + setattr(self.repl, field, val) |
| 65 | + |
| 66 | + # Save changes at program exit |
| 67 | + atexit.register(self.save) |
| 68 | + |
| 69 | + def get_option(self, field: str) -> tuple[object, type]: |
| 70 | + "Returns option value and type for specified field" |
| 71 | + val = getattr(self.repl, field) |
| 72 | + val_type = type(val) |
| 73 | + |
| 74 | + # Handle special case to convert enums to int |
| 75 | + if issubclass(val_type, Enum): |
| 76 | + val = list(val_type).index(val) |
| 77 | + |
| 78 | + # Floats should be rounded to 2 decimal places |
| 79 | + if isinstance(val, float): |
| 80 | + val = round(val, 2) |
| 81 | + |
| 82 | + return val, val_type |
| 83 | + |
| 84 | + def save(self) -> None: |
| 85 | + "Save changed options to file (called once at termination)" |
| 86 | + # Ignore if abnormal (i.e. within exception) termination |
| 87 | + if sys.exc_info()[0]: |
| 88 | + return |
| 89 | + |
| 90 | + new = {} |
| 91 | + for category in self.repl.options: |
| 92 | + for option in category.options: |
| 93 | + field = option.field_name |
| 94 | + val, _ = self.get_option(field) |
| 95 | + if val != self.defaults[field]: |
| 96 | + new[field] = val |
| 97 | + |
| 98 | + # Save if file will change. We only save options which are |
| 99 | + # different to the defaults and we always prune all other |
| 100 | + # options. |
| 101 | + if new != self.stored and not self.file_bad: |
| 102 | + if new: |
| 103 | + try: |
| 104 | + self.file.parent.mkdir(parents=True, exist_ok=True) |
| 105 | + with self.file.open("w") as fp: |
| 106 | + json.dump(new, fp, indent=2) |
| 107 | + except Exception: |
| 108 | + self.file_bad = True |
| 109 | + |
| 110 | + elif self.file.exists(): |
| 111 | + try: |
| 112 | + self.file.unlink() |
| 113 | + except Exception: |
| 114 | + self.file_bad = True |
| 115 | + |
| 116 | + if self.file_bad: |
| 117 | + print(f"Failed to read/write file: {self.file}", file=sys.stderr) |
| 118 | + |
| 119 | +def create(repl: "PythonInput", filename: str) -> None: |
| 120 | + 'Create/activate the options saver' |
| 121 | + # Note, no need to save the instance because it is kept alive by |
| 122 | + # reference from atexit() |
| 123 | + OptionsSaver(repl, filename) |
0 commit comments