Debian Codegraph @

test/integration/targets/cache-plugins/cache_plugins/dummy_cache.py

raw
1 from __future__ import annotations
2
3 DOCUMENTATION = """
4 name: dummy_cache
5 short_description: dummy cache
6 options:
7 dummy:
8 type: str
9 """
10
11 import json
12 import os
13 import pathlib
14 import typing as t
15
16 from ansible.plugins.cache import BaseCacheModule
17
18
19 class CacheModule(BaseCacheModule):
20 def __init__(self, *args, **kwargs):
21 if not os.environ.get('DUMMY_CACHE_SKIP_SUPER'):
22 super().__init__(*args, **kwargs)
23
24 self._storage_dir = pathlib.Path(os.environ.get('OUTPUT_DIR')) / 'cache-storage'
25 self._storage_dir.mkdir(parents=True, exist_ok=True)
26
27 def _get_key_path(self, key: str) -> pathlib.Path:
28 return self._storage_dir / key
29
30 def get(self, key: t.Any) -> object:
31 try:
32 return json.loads(self._get_key_path(key).read_text())
33 except FileNotFoundError:
34 raise KeyError(key) from None
35
36 def set(self, key: str, value: object) -> None:
37 self._get_key_path(key).write_text(json.dumps(value))
38
39 def keys(self) -> list[str]:
40 path: pathlib.Path
41
42 return [path.name for path in self._storage_dir.iterdir()]
43
44 def contains(self, key: object) -> bool:
45 try:
46 self.get(key)
47 except KeyError:
48 return False
49
50 return True
51
52 def delete(self, key: str) -> None:
53 self._get_key_path(key).unlink(missing_ok=True)
54
55 def flush(self) -> None:
56 for key in self.keys():
57 self.delete(key)