-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathfield_base.py
83 lines (67 loc) · 2.54 KB
/
field_base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# SPDX-FileCopyrightText: © 2022-2024 Wojciech Trybus <[email protected]>
# SPDX-License-Identifier: GPL-3.0-or-later
from typing import TypeVar, Generic, Callable
from abc import ABC, abstractmethod
from enum import Enum
from .common_utils import SaveLocation
from .field import Field
T = TypeVar('T')
E = TypeVar('E', bound=Enum)
ListT = TypeVar('ListT', bound=list[Enum])
class FieldBase(ABC, Field, Generic[T]):
"""Implementation base of List, and NonList field."""
def __new__(cls, *args, **kwargs) -> 'FieldBase[T]':
obj = object.__new__(cls)
obj.__init__(*args, **kwargs)
return obj
def __init__(
self,
config_group: str,
name: str,
default: T,
parser_type: type | None = None,
local: bool = False,
) -> None:
self.config_group = config_group
self.name = name
self.default = default
self.parser_type = parser_type
self.location = SaveLocation.LOCAL if local else SaveLocation.GLOBAL
self._on_change_callbacks: list[Callable[[], None]] = []
def register_callback(self, callback: Callable[[], None]) -> None:
"""Store callback in internal list."""
self._on_change_callbacks.append(callback)
def write(self, value: T) -> None:
"""Write value to file and run callbacks if it was not redundant."""
if not isinstance(value, type(self.default)):
raise TypeError(f"{value} not of type {type(self.default)}")
if self._is_write_redundant(value):
return
self.location.write(
group=self.config_group,
name=self.name,
value=self._to_string(value))
for callback in self._on_change_callbacks:
callback()
@abstractmethod
def read(self) -> T:
"""Return value from kritarc parsed to field type."""
...
@abstractmethod
def _to_string(self, value: T) -> str:
"""Convert a value of field type to string."""
...
def _is_write_redundant(self, value: T) -> bool:
"""
Return if writing a value is not necessary.
That is when:
- the value is the same as the one stored in file
- value is a default one and it is not present in file
"""
if self.read() == value:
return True
raw = self.location.read(self.config_group, self.name)
return raw is None and value == self.default
def reset_default(self) -> None:
"""Write a default value to kritarc file."""
self.write(self.default)