| 28 | |
| 29 | |
| 30 | class JargonLoader: |
| 31 | |
| 32 | def __init__(self): |
| 33 | self._user_jargon_mtime = 0 # type: int |
| 34 | self._jargon = None # type: Jargon |
| 35 | |
| 36 | def get_jargon(self) -> Jargon: |
| 37 | if self._is_stale(): |
| 38 | self._load_jargon() |
| 39 | return self._jargon |
| 40 | |
| 41 | def _is_stale(self): |
| 42 | return (not self._jargon or not self._user_jargon_mtime or |
| 43 | self.jargon_mtime != self._get_user_jargon_mtime()) |
| 44 | |
| 45 | def _load_jargon(self): |
| 46 | jargondata = yaml.load(DEFAULT_DATA, Loader=yaml.SafeLoader) |
| 47 | if USER_JARGON_PATH is not None and os.path.isfile(USER_JARGON_PATH): |
| 48 | with open(USER_JARGON_PATH) as f: |
| 49 | userdata = yaml.load(f, Loader=yaml.SafeLoader) |
| 50 | if userdata: |
| 51 | jargondata.update(userdata) |
| 52 | self.jargon_mtime = self._get_user_jargon_mtime() |
| 53 | self._jargon = Jargon(jargondata) |
| 54 | |
| 55 | def _get_user_jargon_mtime(self) -> int: |
| 56 | if USER_JARGON_PATH is None or not os.path.isfile(USER_JARGON_PATH): |
| 57 | return 0 |
| 58 | return os.stat(USER_JARGON_PATH).st_mtime |
| 59 | |
| 60 | @staticmethod |
| 61 | def init_user_jargon(jargon_path): |
| 62 | if not os.path.exists(jargon_path): |
| 63 | with open(jargon_path, 'w') as f: |
| 64 | f.write(DEFAULT_HEADER) |
| 65 | f.write('\n\n') |
| 66 | |
| 67 | _instance = None |
| 68 | |
| 69 | @staticmethod |
| 70 | def instance(): |
| 71 | if not JargonLoader._instance: |
| 72 | JargonLoader._instance = JargonLoader() |
| 73 | return JargonLoader._instance |
| 74 | |
| 75 | |
| 76 | if USER_JARGON_PATH is not None: |