dictscheme: rename from dataclass as it's confusing with builtin dataclasses

This commit is contained in:
InsanePrawn 2023-04-17 02:32:28 +02:00
parent b84d2202db
commit acee95a003
9 changed files with 34 additions and 34 deletions

View file

@ -3,11 +3,11 @@ from __future__ import annotations
from munch import Munch from munch import Munch
from typing import Any, Optional, Mapping, Union from typing import Any, Optional, Mapping, Union
from dataclass import DataClass from dictscheme import DictScheme
from constants import Arch from constants import Arch
class SparseProfile(DataClass): class SparseProfile(DictScheme):
parent: Optional[str] parent: Optional[str]
device: Optional[str] device: Optional[str]
flavour: Optional[str] flavour: Optional[str]
@ -34,11 +34,11 @@ class Profile(SparseProfile):
size_extra_mb: Union[str, int] size_extra_mb: Union[str, int]
class WrapperSection(DataClass): class WrapperSection(DictScheme):
type: str # NOTE: rename to 'wrapper_type' if this causes problems type: str # NOTE: rename to 'wrapper_type' if this causes problems
class BuildSection(DataClass): class BuildSection(DictScheme):
ccache: bool ccache: bool
clean_mode: bool clean_mode: bool
crosscompile: bool crosscompile: bool
@ -46,18 +46,18 @@ class BuildSection(DataClass):
threads: int threads: int
class PkgbuildsSection(DataClass): class PkgbuildsSection(DictScheme):
git_repo: str git_repo: str
git_branch: str git_branch: str
class PacmanSection(DataClass): class PacmanSection(DictScheme):
parallel_downloads: int parallel_downloads: int
check_space: bool check_space: bool
repo_branch: str repo_branch: str
class PathsSection(DataClass): class PathsSection(DictScheme):
cache_dir: str cache_dir: str
chroots: str chroots: str
pacman: str pacman: str
@ -69,7 +69,7 @@ class PathsSection(DataClass):
rust: str rust: str
class ProfilesSection(DataClass): class ProfilesSection(DictScheme):
current: str current: str
default: SparseProfile default: SparseProfile
@ -94,7 +94,7 @@ class ProfilesSection(DataClass):
return f'{type(self)}{dict.__repr__(self.toDict())}' return f'{type(self)}{dict.__repr__(self.toDict())}'
class Config(DataClass): class Config(DictScheme):
wrapper: WrapperSection wrapper: WrapperSection
build: BuildSection build: BuildSection
pkgbuilds: PkgbuildsSection pkgbuilds: PkgbuildsSection
@ -130,7 +130,7 @@ class Config(DataClass):
return Config(_vals, validate=validate) return Config(_vals, validate=validate)
class RuntimeConfiguration(DataClass): class RuntimeConfiguration(DictScheme):
verbose: bool verbose: bool
no_wrap: bool no_wrap: bool
error_shell: bool error_shell: bool
@ -142,7 +142,7 @@ class RuntimeConfiguration(DataClass):
colors: Optional[bool] colors: Optional[bool]
class ConfigLoadState(DataClass): class ConfigLoadState(DictScheme):
load_finished: bool load_finished: bool
exception: Optional[Exception] exception: Optional[Exception]

View file

@ -7,7 +7,7 @@ from typing import Mapping, Optional
from constants import DEFAULT_PACKAGE_BRANCH from constants import DEFAULT_PACKAGE_BRANCH
from .scheme import Config, ConfigLoadState, DataClass, Profile, RuntimeConfiguration from .scheme import Config, ConfigLoadState, DictScheme, Profile, RuntimeConfiguration
from .profile import PROFILE_DEFAULTS, PROFILE_DEFAULTS_DICT, resolve_profile from .profile import PROFILE_DEFAULTS, PROFILE_DEFAULTS_DICT, resolve_profile
CONFIG_DIR = appdirs.user_config_dir('kupfer') CONFIG_DIR = appdirs.user_config_dir('kupfer')
@ -95,7 +95,7 @@ def merge_configs(conf_new: Mapping[str, dict], conf_base={}, warn_missing_defau
continue continue
logging.debug(f'Parsing config section "{outer_name}"') logging.debug(f'Parsing config section "{outer_name}"')
# check if outer_conf is a dict # check if outer_conf is a dict
if not (isinstance(outer_conf, (dict, DataClass))): if not (isinstance(outer_conf, (dict, DictScheme))):
parsed[outer_name] = outer_conf parsed[outer_name] = outer_conf
else: else:
# init section # init section

View file

@ -157,7 +157,7 @@ def test_config_save_modified(configstate_emptyfile: ConfigStateHolder):
def get_config_scheme(data: dict[str, Any], validate=True, allow_incomplete=False) -> Config: def get_config_scheme(data: dict[str, Any], validate=True, allow_incomplete=False) -> Config:
""" """
helper func to ignore a false type error. helper func to ignore a false type error.
for some reason, mypy argues about DataClass.fromDict() instead of Config.fromDict() here for some reason, mypy argues about DictScheme.fromDict() instead of Config.fromDict() here
""" """
return Config.fromDict(data, validate=validate, allow_incomplete=allow_incomplete) # type: ignore[call-arg] return Config.fromDict(data, validate=validate, allow_incomplete=allow_incomplete) # type: ignore[call-arg]

View file

@ -5,7 +5,7 @@ from typing import Optional
from config.state import config from config.state import config
from constants import Arch, ARCHES from constants import Arch, ARCHES
from dataclass import DataClass from dictscheme import DictScheme
from distro.distro import get_kupfer_local from distro.distro import get_kupfer_local
from distro.package import LocalPackage from distro.package import LocalPackage
from packages.pkgbuild import Pkgbuild, _pkgbuilds_cache, discover_pkgbuilds, get_pkgbuild_by_path, init_pkgbuilds from packages.pkgbuild import Pkgbuild, _pkgbuilds_cache, discover_pkgbuilds, get_pkgbuild_by_path, init_pkgbuilds
@ -22,7 +22,7 @@ DEVICE_DEPRECATIONS = {
} }
class DeviceSummary(DataClass): class DeviceSummary(DictScheme):
name: str name: str
description: str description: str
arch: str arch: str
@ -43,7 +43,7 @@ class DeviceSummary(DataClass):
return separator.join([f"{color_str(name, bold=True, use_colors=colors)}: {value}" for name, value in fields.items()]) return separator.join([f"{color_str(name, bold=True, use_colors=colors)}: {value}" for name, value in fields.items()])
class Device(DataClass): class Device(DictScheme):
name: str name: str
arch: Arch arch: Arch
package: Pkgbuild package: Pkgbuild

View file

@ -9,14 +9,14 @@ from typing import Any, Mapping, Optional
from config.state import config from config.state import config
from constants import Arch from constants import Arch
from dataclass import DataClass from dictscheme import DictScheme
PMOS_ARCHES_OVERRIDES: dict[str, Arch] = { PMOS_ARCHES_OVERRIDES: dict[str, Arch] = {
"armv7": 'armv7h', "armv7": 'armv7h',
} }
class DeviceInfo(DataClass): class DeviceInfo(DictScheme):
arch: Arch arch: Arch
name: str name: str
manufacturer: str manufacturer: str

View file

@ -45,7 +45,7 @@ def resolve_dict_hints(hints: Any) -> Generator[tuple[Any, ...], None, None]:
continue continue
class DataClass(Munch): class DictScheme(Munch):
_type_hints: ClassVar[dict[str, Any]] _type_hints: ClassVar[dict[str, Any]]
_strip_hidden: ClassVar[bool] = False _strip_hidden: ClassVar[bool] = False
@ -118,7 +118,7 @@ class DataClass(Munch):
if not (optional and value is None): if not (optional and value is None):
assert issubclass(target_class, Munch) assert issubclass(target_class, Munch)
# despite the above assert, mypy doesn't seem to understand target_class is a Munch here # despite the above assert, mypy doesn't seem to understand target_class is a Munch here
kwargs = {'validate': validate} if issubclass(target_class, DataClass) else {} kwargs = {'validate': validate} if issubclass(target_class, DictScheme) else {}
value = target_class(value, **kwargs) # type:ignore[attr-defined] value = target_class(value, **kwargs) # type:ignore[attr-defined]
else: else:
# print(f"nothing to do: '{key}' was already {target_class}) # print(f"nothing to do: '{key}' was already {target_class})
@ -217,7 +217,7 @@ class DataClass(Munch):
if not v: if not v:
result[k] = {} result[k] = {}
continue continue
if isinstance(v, DataClass): if isinstance(v, DictScheme):
# pass None in sparse and strip_hidden # pass None in sparse and strip_hidden
result[k] = v.toDict(strip_hidden=strip_hidden, sparse=sparse) result[k] = v.toDict(strip_hidden=strip_hidden, sparse=sparse)
continue continue
@ -228,13 +228,13 @@ class DataClass(Munch):
_subhints = {} _subhints = {}
_hints = resolve_type_hint(hints[k], [dict]) _hints = resolve_type_hint(hints[k], [dict])
hints_flat = list(flatten_hints(_hints)) hints_flat = list(flatten_hints(_hints))
subclass = DataClass subclass = DictScheme
for hint in hints_flat: for hint in hints_flat:
if get_origin(hint) == dict: if get_origin(hint) == dict:
_valtype = get_args(hint)[1] _valtype = get_args(hint)[1]
_subhints = {n: _valtype for n in v.keys()} _subhints = {n: _valtype for n in v.keys()}
break break
if isinstance(hint, type) and issubclass(hint, DataClass): if isinstance(hint, type) and issubclass(hint, DictScheme):
subclass = hint subclass = hint
_subhints = hint._type_hints _subhints = hint._type_hints
break break

View file

@ -10,7 +10,7 @@ from typing import ClassVar, Optional, Mapping, Union
from config.state import config from config.state import config
from constants import Arch, BASE_DISTROS, KUPFER_HTTPS, REPOS_CONFIG_FILE, REPOSITORIES from constants import Arch, BASE_DISTROS, KUPFER_HTTPS, REPOS_CONFIG_FILE, REPOSITORIES
from dataclass import DataClass, toml_inline_dicts, TomlPreserveInlineDictEncoder from dictscheme import DictScheme, toml_inline_dicts, TomlPreserveInlineDictEncoder
from utils import sha256sum from utils import sha256sum
REPOS_KEY = 'repos' REPOS_KEY = 'repos'
@ -22,7 +22,7 @@ BASEDISTROS_KEY = 'base_distros'
_current_config: Optional[ReposConfigFile] _current_config: Optional[ReposConfigFile]
class AbstrRepoConfig(DataClass): class AbstrRepoConfig(DictScheme):
options: Optional[dict[str, str]] options: Optional[dict[str, str]]
_strip_hidden: ClassVar[bool] = True _strip_hidden: ClassVar[bool] = True
_sparse: ClassVar[bool] = True _sparse: ClassVar[bool] = True
@ -37,12 +37,12 @@ class RepoConfig(AbstrRepoConfig):
local_only: Optional[bool] local_only: Optional[bool]
class BaseDistro(DataClass): class BaseDistro(DictScheme):
remote_url: Optional[str] remote_url: Optional[str]
repos: dict[str, BaseDistroRepo] repos: dict[str, BaseDistroRepo]
class ReposConfigFile(DataClass): class ReposConfigFile(DictScheme):
remote_url: Optional[str] remote_url: Optional[str]
repos: dict[str, RepoConfig] repos: dict[str, RepoConfig]
base_distros: dict[Arch, BaseDistro] base_distros: dict[Arch, BaseDistro]

View file

@ -8,12 +8,12 @@ from typing import Optional
from config.state import config from config.state import config
from constants import FLAVOUR_DESCRIPTION_PREFIX, FLAVOUR_INFO_FILE from constants import FLAVOUR_DESCRIPTION_PREFIX, FLAVOUR_INFO_FILE
from dataclass import DataClass from dictscheme import DictScheme
from packages.pkgbuild import discover_pkgbuilds, get_pkgbuild_by_name, init_pkgbuilds, Pkgbuild from packages.pkgbuild import discover_pkgbuilds, get_pkgbuild_by_name, init_pkgbuilds, Pkgbuild
from utils import color_str from utils import color_str
class FlavourInfo(DataClass): class FlavourInfo(DictScheme):
rootfs_size: int # rootfs size in GB rootfs_size: int # rootfs size in GB
description: Optional[str] description: Optional[str]
@ -21,7 +21,7 @@ class FlavourInfo(DataClass):
return f'rootfs_size: {self.rootfs_size}' return f'rootfs_size: {self.rootfs_size}'
class Flavour(DataClass): class Flavour(DictScheme):
name: str name: str
pkgbuild: Pkgbuild pkgbuild: Pkgbuild
description: str description: str
@ -53,7 +53,7 @@ class Flavour(DataClass):
def get_lines(k, v, key_prefix=''): def get_lines(k, v, key_prefix=''):
results = [] results = []
full_k = f'{key_prefix}.{k}' if key_prefix else k full_k = f'{key_prefix}.{k}' if key_prefix else k
if not isinstance(v, (dict, DataClass)): if not isinstance(v, (dict, DictScheme)):
results = [f'{color_str(full_k, bold=True)}: {v}'] results = [f'{color_str(full_k, bold=True)}: {v}']
else: else:
for _k, _v in v.items(): for _k, _v in v.items():

View file

@ -9,14 +9,14 @@ from typing import Any, ClassVar, Optional
from config.state import config from config.state import config
from constants import MAKEPKG_CMD, SRCINFO_FILE, SRCINFO_METADATA_FILE, SRCINFO_INITIALISED_FILE from constants import MAKEPKG_CMD, SRCINFO_FILE, SRCINFO_METADATA_FILE, SRCINFO_INITIALISED_FILE
from dataclass import DataClass from dictscheme import DictScheme
from exec.cmd import run_cmd from exec.cmd import run_cmd
from utils import sha256sum from utils import sha256sum
SRCINFO_CHECKSUM_FILES = ['PKGBUILD', SRCINFO_FILE] SRCINFO_CHECKSUM_FILES = ['PKGBUILD', SRCINFO_FILE]
class JsonFile(DataClass): class JsonFile(DictScheme):
_filename: ClassVar[str] _filename: ClassVar[str]
_relative_path: str _relative_path: str