Remove most deprecated typing.Dict usage (#2813)

This commit is contained in:
correctmost 2024-11-15 19:57:46 -05:00 committed by GitHub
parent d9fa2718ec
commit c87c723549
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 132 additions and 135 deletions

View File

@ -7,7 +7,7 @@ import curses
import traceback
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Union
from typing import TYPE_CHECKING, Any, Union
from .lib import disk
from .lib import models
@ -150,7 +150,7 @@ def parse_unspecified_argument_list(unknowns: list, multiple: bool = False, err:
return config
def cleanup_empty_args(args: Union[Namespace, Dict]) -> Dict:
def cleanup_empty_args(args: Union[Namespace, dict]) -> dict:
"""
Takes arguments (dictionary or argparse Namespace) and removes any
None values. This ensures clean mergers during dict.update(args)
@ -169,7 +169,7 @@ def cleanup_empty_args(args: Union[Namespace, Dict]) -> Dict:
return clean_args
def get_arguments() -> Dict[str, Any]:
def get_arguments() -> dict[str, Any]:
""" The handling of parameters from the command line
Is done on following steps:
0) we create a dict to store the arguments and their values
@ -183,7 +183,7 @@ def get_arguments() -> Dict[str, Any]:
3) Amend
Change whatever is needed on the configuration dictionary (it could be done in post_process_arguments but this ougth to be left to changes anywhere else in the code, not in the arguments dictionary
"""
config: Dict[str, Any] = {}
config: dict[str, Any] = {}
args, unknowns = parser.parse_known_args()
# preprocess the JSON files.
# TODO Expand the url access to the other JSON file arguments ?
@ -278,7 +278,7 @@ def post_process_arguments(arguments: dict[str, Any]) -> None:
define_arguments()
arguments: Dict[str, Any] = get_arguments()
arguments: dict[str, Any] = get_arguments()
post_process_arguments(arguments)

View File

@ -1,4 +1,4 @@
from typing import Any, TYPE_CHECKING, Optional, Dict
from typing import Any, TYPE_CHECKING, Optional
from archinstall.lib.output import info
from archinstall.lib.profile.profiles_handler import profile_handler
@ -41,7 +41,7 @@ class DesktopProfile(Profile):
@property
def default_greeter_type(self) -> Optional[GreeterType]:
combined_greeters: Dict[GreeterType, int] = {}
combined_greeters: dict[GreeterType, int] = {}
for profile in self.current_selection:
if profile.default_greeter_type:
combined_greeters.setdefault(profile.default_greeter_type, 0)

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import sys
from enum import Enum, auto
from typing import Optional, Any, Dict, TYPE_CHECKING
from typing import Optional, Any, TYPE_CHECKING
from ..lib.storage import storage
@ -62,7 +62,7 @@ class Profile:
self.name = name
self.description = description
self.profile_type = profile_type
self.custom_settings: Dict[str, Any] = {}
self.custom_settings: dict[str, Any] = {}
self.advanced = advanced
self._support_gfx_driver = support_gfx_driver
@ -119,7 +119,7 @@ class Profile:
are needed
"""
def json(self) -> Dict:
def json(self) -> dict:
"""
Returns a json representation of the profile
"""
@ -131,7 +131,7 @@ class Profile:
"""
return SelectResult.NewSelection
def set_custom_settings(self, settings: Dict[str, Any]) -> None:
def set_custom_settings(self, settings: dict[str, Any]) -> None:
"""
Set the custom settings for the profile.
This is also called when the settings are parsed from the config

View File

@ -3,7 +3,7 @@ import json
import stat
import readline
from pathlib import Path
from typing import Optional, Dict, Any, TYPE_CHECKING
from typing import Optional, Any, TYPE_CHECKING
from .storage import storage
from .general import JSON, UNSAFE_JSON
@ -21,17 +21,17 @@ if TYPE_CHECKING:
class ConfigurationOutput:
def __init__(self, config: Dict):
def __init__(self, config: dict):
"""
Configuration output handler to parse the existing configuration data structure and prepare for output on the
console and for saving it to configuration files
:param config: A dictionary containing configurations (basically archinstall.arguments)
:type config: Dict
:type config: dict
"""
self._config = config
self._user_credentials: Dict[str, Any] = {}
self._user_config: Dict[str, Any] = {}
self._user_credentials: dict[str, Any] = {}
self._user_config: dict[str, Any] = {}
self._default_save_path = storage.get('LOG_PATH', Path('.'))
self._user_config_file = 'user_configuration.json'
self._user_creds_file = "user_credentials.json"
@ -134,7 +134,7 @@ class ConfigurationOutput:
self.save_user_creds(dest_path)
def save_config(config: Dict[str, Any]) -> None:
def save_config(config: dict[str, Any]) -> None:
def preview(item: MenuItem) -> Optional[str]:
match item.value:
case "user_config":

View File

@ -1,4 +1,4 @@
from typing import Dict, Optional, Any, TYPE_CHECKING
from typing import Optional, Any, TYPE_CHECKING
from . import DiskLayoutConfiguration, DiskLayoutType
from .device_model import LvmConfiguration
@ -26,7 +26,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
):
self._disk_layout_config = disk_layout_config
self._advanced = advanced
self._data_store: Dict[str, Any] = {}
self._data_store: dict[str, Any] = {}
menu_optioons = self._define_menu_options()
self._item_group = MenuItemGroup(menu_optioons, sort_items=False, checkmarks=True)

View File

@ -1,5 +1,5 @@
from pathlib import Path
from typing import Dict, Optional, Any, TYPE_CHECKING
from typing import Optional, Any, TYPE_CHECKING
from . import LvmConfiguration, LvmVolume
from ..disk import (
@ -36,7 +36,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
else:
self._preset = DiskEncryption()
self._data_store: Dict[str, Any] = {}
self._data_store: dict[str, Any] = {}
self._disk_config = disk_config
menu_optioons = self._define_menu_options()

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Optional, TYPE_CHECKING, Dict, Set
from typing import Any, Optional, TYPE_CHECKING, Set
from ..interactions.general_conf import ask_abort
from .device_handler import device_handler
@ -182,7 +182,7 @@ class FilesystemHandler:
def _setup_lvm(
self,
lvm_config: LvmConfiguration,
enc_mods: Dict[PartitionModification, Luks2] = {}
enc_mods: dict[PartitionModification, Luks2] = {}
) -> None:
self._lvm_create_pvs(lvm_config, enc_mods)
@ -229,7 +229,7 @@ class FilesystemHandler:
def _format_lvm_vols(
self,
lvm_config: LvmConfiguration,
enc_vols: Dict[LvmVolume, Luks2] = {}
enc_vols: dict[LvmVolume, Luks2] = {}
) -> None:
for vol in lvm_config.get_all_volumes():
if enc_vol := enc_vols.get(vol, None):
@ -249,7 +249,7 @@ class FilesystemHandler:
def _lvm_create_pvs(
self,
lvm_config: LvmConfiguration,
enc_mods: Dict[PartitionModification, Luks2] = {}
enc_mods: dict[PartitionModification, Luks2] = {}
) -> None:
pv_paths: Set[Path] = set()
@ -261,7 +261,7 @@ class FilesystemHandler:
def _get_all_pv_dev_paths(
self,
pvs: list[PartitionModification],
enc_mods: Dict[PartitionModification, Luks2] = {}
enc_mods: dict[PartitionModification, Luks2] = {}
) -> Set[Path]:
pv_paths: Set[Path] = set()
@ -279,8 +279,8 @@ class FilesystemHandler:
lvm_config: LvmConfiguration,
enc_config: DiskEncryption,
lock_after_create: bool = True
) -> Dict[LvmVolume, Luks2]:
enc_vols: Dict[LvmVolume, Luks2] = {}
) -> dict[LvmVolume, Luks2]:
enc_vols: dict[LvmVolume, Luks2] = {}
for vol in lvm_config.get_all_volumes():
if vol in enc_config.lvm_volumes:
@ -299,8 +299,8 @@ class FilesystemHandler:
self,
enc_config: DiskEncryption,
lock_after_create: bool = True
) -> Dict[PartitionModification, Luks2]:
enc_mods: Dict[PartitionModification, Luks2] = {}
) -> dict[PartitionModification, Luks2]:
enc_mods: dict[PartitionModification, Luks2] = {}
for mod in self._disk_config.device_modifications:
partitions = mod.partitions

View File

@ -16,7 +16,7 @@ import urllib.error
import pathlib
from datetime import datetime, date
from enum import Enum
from typing import Callable, Optional, Dict, Any, Union, Iterator, TYPE_CHECKING
from typing import Callable, Optional, Any, Union, Iterator, TYPE_CHECKING
from select import epoll, EPOLLIN, EPOLLHUP
from shutil import which
@ -103,9 +103,9 @@ class SysCommandWorker:
def __init__(
self,
cmd: Union[str, list[str]],
callbacks: Optional[Dict[str, Any]] = None,
callbacks: Optional[dict[str, Any]] = None,
peek_output: Optional[bool] = False,
environment_vars: Optional[Dict[str, Any]] = None,
environment_vars: Optional[dict[str, Any]] = None,
logfile: Optional[None] = None,
working_directory: Optional[str] = './',
remove_vt100_escape_codes_from_lines: bool = True
@ -151,7 +151,7 @@ class SysCommandWorker:
return False
def __iter__(self, *args: str, **kwargs: Dict[str, Any]) -> Iterator[bytes]:
def __iter__(self, *args: str, **kwargs: dict[str, Any]) -> Iterator[bytes]:
last_line = self._trace_log.rfind(b'\n')
lines = filter(None, self._trace_log[self._trace_log_pos:last_line].splitlines())
for line in lines:
@ -346,10 +346,10 @@ class SysCommandWorker:
class SysCommand:
def __init__(self,
cmd: Union[str, list[str]],
callbacks: Dict[str, Callable[[Any], Any]] = {},
callbacks: dict[str, Callable[[Any], Any]] = {},
start_callback: Optional[Callable[[Any], Any]] = None,
peek_output: Optional[bool] = False,
environment_vars: Optional[Dict[str, Any]] = None,
environment_vars: Optional[dict[str, Any]] = None,
working_directory: Optional[str] = './',
remove_vt100_escape_codes_from_lines: bool = True):
@ -369,14 +369,14 @@ class SysCommand:
def __enter__(self) -> Optional[SysCommandWorker]:
return self.session
def __exit__(self, *args: str, **kwargs: Dict[str, Any]) -> None:
def __exit__(self, *args: str, **kwargs: dict[str, Any]) -> None:
# b''.join(sys_command('sync')) # No need to, since the underlying fs() object will call sync.
# TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager
if len(args) >= 2 and args[1]:
error(args[1])
def __iter__(self, *args: list[Any], **kwargs: Dict[str, Any]) -> Iterator[bytes]:
def __iter__(self, *args: list[Any], **kwargs: dict[str, Any]) -> Iterator[bytes]:
if self.session:
for line in self.session:
yield line
@ -392,10 +392,10 @@ class SysCommand:
else:
raise ValueError("SysCommand() doesn't have key & value pairs, only slices, SysCommand('ls')[:10] as an example.")
def __repr__(self, *args: list[Any], **kwargs: Dict[str, Any]) -> str:
def __repr__(self, *args: list[Any], **kwargs: dict[str, Any]) -> str:
return self.decode('UTF-8', errors='backslashreplace') or ''
def __json__(self) -> Dict[str, Union[str, bool, list[str], Dict[str, Any], Optional[bool], Optional[Dict[str, Any]]]]:
def __json__(self) -> dict[str, Union[str, bool, list[str], dict[str, Any], Optional[bool], Optional[dict[str, Any]]]]:
return {
'cmd': self.cmd,
'callbacks': self._callbacks,

View File

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import Any, Optional, Dict, TYPE_CHECKING
from typing import Any, Optional, TYPE_CHECKING
from . import disk
from .general import secret
@ -38,7 +38,7 @@ if TYPE_CHECKING:
class GlobalMenu(AbstractMenu):
def __init__(self, data_store: Dict[str, Any]):
def __init__(self, data_store: dict[str, Any]):
self._data_store = data_store
self._translation_handler = TranslationHandler()
@ -54,7 +54,7 @@ class GlobalMenu(AbstractMenu):
super().__init__(self._item_group, data_store)
def _get_menu_options(self, data_store: Dict[str, Any]) -> list[MenuItem]:
def _get_menu_options(self, data_store: dict[str, Any]) -> list[MenuItem]:
return [
MenuItem(
text=str(_('Archinstall language')),
@ -212,7 +212,7 @@ class GlobalMenu(AbstractMenu):
]
def _safe_config(self) -> None:
data: Dict[str, Any] = {}
data: dict[str, Any] = {}
for item in self._item_group.items:
if item.key is not None:
data[item.key] = item.value

View File

@ -2,7 +2,7 @@ import os
from enum import Enum
from functools import cached_property
from pathlib import Path
from typing import Optional, Dict, TYPE_CHECKING, Any
from typing import Optional, TYPE_CHECKING, Any
from .exceptions import SysCallError
from .general import SysCommand
@ -148,12 +148,12 @@ class _SysInfo:
pass
@cached_property
def cpu_info(self) -> Dict[str, str]:
def cpu_info(self) -> dict[str, str]:
"""
Returns system cpu information
"""
cpu_info_path = Path("/proc/cpuinfo")
cpu: Dict[str, str] = {}
cpu: dict[str, str] = {}
with cpu_info_path.open() as file:
for line in file:
@ -164,12 +164,12 @@ class _SysInfo:
return cpu
@cached_property
def mem_info(self) -> Dict[str, int]:
def mem_info(self) -> dict[str, int]:
"""
Returns system memory information
"""
mem_info_path = Path("/proc/meminfo")
mem_info: Dict[str, int] = {}
mem_info: dict[str, int] = {}
with mem_info_path.open() as file:
for line in file:
@ -212,8 +212,8 @@ class SysInfo:
return os.path.isdir('/sys/firmware/efi')
@staticmethod
def _graphics_devices() -> Dict[str, str]:
cards: Dict[str, str] = {}
def _graphics_devices() -> dict[str, str]:
cards: dict[str, str] = {}
for line in SysCommand("lspci"):
if b' VGA ' in line or b' 3D ' in line:
_, identifier = line.split(b': ', 1)

View File

@ -6,7 +6,7 @@ import shutil
import subprocess
import time
from pathlib import Path
from typing import Any, Optional, TYPE_CHECKING, Union, Dict, Callable
from typing import Any, Optional, TYPE_CHECKING, Union, Callable
from . import disk
from .exceptions import DiskError, ServiceException, RequirementError, HardwareIncompatibilityError, SysCallError
@ -62,7 +62,7 @@ class Installer:
self.init_time = time.strftime('%Y-%m-%d_%H-%M-%S')
self.milliseconds = int(str(time.time()).split('.')[1])
self.helper_flags: Dict[str, Any] = {'base': False, 'bootloader': None}
self.helper_flags: dict[str, Any] = {'base': False, 'bootloader': None}
for kernel in self.kernels:
self._base_packages.append(kernel)
@ -203,7 +203,7 @@ class Installer:
def mount_ordered_layout(self) -> None:
debug('Mounting ordered layout')
luks_handlers: Dict[Any, Luks2] = {}
luks_handlers: dict[Any, Luks2] = {}
match self._disk_encryption.encryption_type:
case disk.EncryptionType.NoEncryption:
@ -222,7 +222,7 @@ class Installer:
# mount all regular partitions
self._mount_partition_layout(luks_handlers)
def _mount_partition_layout(self, luks_handlers: Dict[Any, Luks2]) -> None:
def _mount_partition_layout(self, luks_handlers: dict[Any, Luks2]) -> None:
debug('Mounting partition layout')
# do not mount any PVs part of the LVM configuration
@ -253,7 +253,7 @@ class Installer:
else:
self._mount_partition(part_mod)
def _mount_lvm_layout(self, luks_handlers: Dict[Any, Luks2] = {}) -> None:
def _mount_lvm_layout(self, luks_handlers: dict[Any, Luks2] = {}) -> None:
lvm_config = self._disk_config.lvm_config
if not lvm_config:
@ -274,7 +274,7 @@ class Installer:
def _prepare_luks_partitions(
self,
partitions: list[disk.PartitionModification]
) -> Dict[disk.PartitionModification, Luks2]:
) -> dict[disk.PartitionModification, Luks2]:
return {
part_mod: disk.device_handler.unlock_luks2_dev(
part_mod.dev_path,
@ -301,7 +301,7 @@ class Installer:
def _prepare_luks_lvm(
self,
lvm_volumes: list[disk.LvmVolume]
) -> Dict[disk.LvmVolume, Luks2]:
) -> dict[disk.LvmVolume, Luks2]:
return {
vol: disk.device_handler.unlock_luks2_dev(
vol.dev_path,

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Dict, Any, TYPE_CHECKING, Optional
from typing import Any, TYPE_CHECKING, Optional
from .utils import list_keyboard_languages, list_locales, set_kb_layout, get_kb_layout
from ..menu import AbstractSubMenu
@ -26,7 +26,7 @@ class LocaleConfiguration:
return LocaleConfiguration('us', 'en_US', 'UTF-8')
return LocaleConfiguration(layout, 'en_US', 'UTF-8')
def json(self) -> Dict[str, str]:
def json(self) -> dict[str, str]:
return {
'kb_layout': self.kb_layout,
'sys_lang': self.sys_lang,
@ -40,7 +40,7 @@ class LocaleConfiguration:
return output
@classmethod
def _load_config(cls, config: 'LocaleConfiguration', args: Dict[str, Any]) -> 'LocaleConfiguration':
def _load_config(cls, config: 'LocaleConfiguration', args: dict[str, Any]) -> 'LocaleConfiguration':
if 'sys_lang' in args:
config.sys_lang = args['sys_lang']
if 'sys_enc' in args:
@ -51,7 +51,7 @@ class LocaleConfiguration:
return config
@classmethod
def parse_arg(cls, args: Dict[str, Any]) -> 'LocaleConfiguration':
def parse_arg(cls, args: dict[str, Any]) -> 'LocaleConfiguration':
default = cls.default()
if 'locale_config' in args:
@ -68,7 +68,7 @@ class LocaleMenu(AbstractSubMenu):
locale_conf: LocaleConfiguration
):
self._locale_conf = locale_conf
self._data_store: Dict[str, Any] = {}
self._data_store: dict[str, Any] = {}
menu_optioons = self._define_menu_options()
self._item_group = MenuItemGroup(menu_optioons, sort_items=False, checkmarks=True)

View File

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import Callable, Any, Optional, Dict, TYPE_CHECKING
from typing import Callable, Any, Optional, TYPE_CHECKING
from ..output import error
from ..output import unicode_ljust
@ -148,7 +148,7 @@ class AbstractMenu:
def __init__(
self,
item_group: MenuItemGroup,
data_store: Dict[str, Any],
data_store: dict[str, Any],
auto_cursor: bool = True,
allow_reset: bool = False,
reset_warning: Optional[str] = None
@ -242,7 +242,7 @@ class AbstractSubMenu(AbstractMenu):
def __init__(
self,
item_group: MenuItemGroup,
data_store: Dict[str, Any],
data_store: dict[str, Any],
auto_cursor: bool = True,
allow_reset: bool = False
):

View File

@ -1,5 +1,5 @@
import copy
from typing import Any, TYPE_CHECKING, Dict, Optional, Tuple
from typing import Any, TYPE_CHECKING, Optional, Tuple
from ..output import FormattedOutput
from archinstall.tui import (
@ -97,7 +97,7 @@ class ListManager:
else:
return self._data
def _prepare_selection(self, data_formatted: Dict[str, Any]) -> Tuple[list[str], str]:
def _prepare_selection(self, data_formatted: dict[str, Any]) -> Tuple[list[str], str]:
# header rows are mapped to None so make sure
# to exclude those from the selectable data
options: list[str] = [key for key, val in data_formatted.items() if val is not None]
@ -140,7 +140,7 @@ class ListManager:
if value != self._cancel_action:
self._data = self.handle_action(value, entry, self._data)
def reformat(self, data: list[Any]) -> Dict[str, Optional[Any]]:
def reformat(self, data: list[Any]) -> dict[str, Optional[Any]]:
"""
Default implementation of the table to be displayed.
Override if any custom formatting is needed
@ -151,7 +151,7 @@ class ListManager:
# these are the header rows of the table and do not map to any User obviously
# we're adding 2 spaces as prefix because the menu selector '> ' will be put before
# the selectable rows so the header has to be aligned
display_data: Dict[str, Optional[Any]] = {f'{rows[0]}': None, f'{rows[1]}': None}
display_data: dict[str, Optional[Any]] = {f'{rows[0]}': None, f'{rows[1]}': None}
for row, entry in zip(rows[2:], data):
display_data[row] = entry

View File

@ -1,4 +1,4 @@
from typing import Any, Tuple, Dict, Optional
from typing import Any, Tuple, Optional
from archinstall.lib.output import FormattedOutput
@ -39,7 +39,7 @@ class MenuHelper:
return group, header
@staticmethod
def _create_table(data: list[Any], rows: list[str], header_padding: int = 2) -> Dict[str, Any]:
def _create_table(data: list[Any], rows: list[str], header_padding: int = 2) -> dict[str, Any]:
# these are the header rows of the table and do not map to any data obviously
# we're adding 2 spaces as prefix because the menu selector '> ' will be put before
# the selectable rows so the header has to be aligned
@ -52,7 +52,7 @@ class MenuHelper:
return display_data
@staticmethod
def _prepare_selection(table: Dict[str, Any]) -> Tuple[Dict[str, Any], str]:
def _prepare_selection(table: dict[str, Any]) -> Tuple[dict[str, Any], str]:
# header rows are mapped to None so make sure to exclude those from the selectable data
options = {key: val for key, val in table.items() if val is not None}
header = ''

View File

@ -4,7 +4,7 @@ import urllib.parse
from pathlib import Path
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Any, Optional, TYPE_CHECKING, Tuple
from typing import Any, Optional, TYPE_CHECKING, Tuple
from .menu import AbstractSubMenu, ListManager
from .networking import fetch_data_from_url
@ -41,7 +41,7 @@ class CustomMirror:
sign_check: SignCheck
sign_option: SignOption
def table_data(self) -> Dict[str, str]:
def table_data(self) -> dict[str, str]:
return {
'Name': self.name,
'Url': self.url,
@ -49,7 +49,7 @@ class CustomMirror:
'Sign options': self.sign_option.value
}
def json(self) -> Dict[str, str]:
def json(self) -> dict[str, str]:
return {
'name': self.name,
'url': self.url,
@ -58,7 +58,7 @@ class CustomMirror:
}
@classmethod
def parse_args(cls, args: list[Dict[str, str]]) -> list['CustomMirror']:
def parse_args(cls, args: list[dict[str, str]]) -> list['CustomMirror']:
configs = []
for arg in args:
configs.append(
@ -75,14 +75,14 @@ class CustomMirror:
@dataclass
class MirrorConfiguration:
mirror_regions: Dict[str, list[MirrorStatusEntryV3]] = field(default_factory=dict)
mirror_regions: dict[str, list[MirrorStatusEntryV3]] = field(default_factory=dict)
custom_mirrors: list[CustomMirror] = field(default_factory=list)
@property
def regions(self) -> str:
return ', '.join(self.mirror_regions.keys())
def json(self) -> Dict[str, Any]:
def json(self) -> dict[str, Any]:
return {
'mirror_regions': self.mirror_regions,
'custom_mirrors': [c.json() for c in self.custom_mirrors]
@ -111,7 +111,7 @@ class MirrorConfiguration:
return config
@classmethod
def parse_args(cls, args: Dict[str, Any]) -> 'MirrorConfiguration':
def parse_args(cls, args: dict[str, Any]) -> 'MirrorConfiguration':
config = MirrorConfiguration()
if 'mirror_regions' in args:
@ -252,7 +252,7 @@ class MirrorMenu(AbstractSubMenu):
else:
self._mirror_config = MirrorConfiguration()
self._data_store: Dict[str, Any] = {}
self._data_store: dict[str, Any] = {}
menu_optioons = self._define_menu_options()
self._item_group = MenuItemGroup(menu_optioons, checkmarks=True)
@ -278,7 +278,7 @@ class MirrorMenu(AbstractSubMenu):
]
def _prev_regions(self, item: MenuItem) -> Optional[str]:
mirrors: Dict[str, list[MirrorStatusEntryV3]] = item.get_value()
mirrors: dict[str, list[MirrorStatusEntryV3]] = item.get_value()
output = ''
for name, status_list in mirrors.items():
@ -312,8 +312,8 @@ class MirrorMenu(AbstractSubMenu):
)
def select_mirror_regions(preset: Dict[str, list[MirrorStatusEntryV3]]) -> Dict[str, list[MirrorStatusEntryV3]]:
mirrors: Dict[str, list[MirrorStatusEntryV3]] | None = list_mirrors_from_remote()
def select_mirror_regions(preset: dict[str, list[MirrorStatusEntryV3]]) -> dict[str, list[MirrorStatusEntryV3]]:
mirrors: dict[str, list[MirrorStatusEntryV3]] | None = list_mirrors_from_remote()
if not mirrors:
mirrors = list_mirrors_from_local()
@ -348,7 +348,7 @@ def select_custom_mirror(preset: list[CustomMirror] = []):
return custom_mirrors
def list_mirrors_from_remote() -> Optional[Dict[str, list[MirrorStatusEntryV3]]]:
def list_mirrors_from_remote() -> Optional[dict[str, list[MirrorStatusEntryV3]]]:
if not storage['arguments']['offline']:
url = "https://archlinux.org/mirrors/status/json/"
attempts = 3
@ -366,7 +366,7 @@ def list_mirrors_from_remote() -> Optional[Dict[str, list[MirrorStatusEntryV3]]]
return None
def list_mirrors_from_local() -> Dict[str, list[MirrorStatusEntryV3]]:
def list_mirrors_from_local() -> dict[str, list[MirrorStatusEntryV3]]:
with Path('/etc/pacman.d/mirrorlist').open('r') as fp:
mirrorlist = fp.read()
return _parse_locale_mirrors(mirrorlist)
@ -376,10 +376,10 @@ def _sort_mirrors_by_performance(mirror_list: list[MirrorStatusEntryV3]) -> list
return sorted(mirror_list, key=lambda mirror: (mirror.score, mirror.speed))
def _parse_remote_mirror_list(mirrorlist: str) -> Dict[str, list[MirrorStatusEntryV3]]:
def _parse_remote_mirror_list(mirrorlist: str) -> dict[str, list[MirrorStatusEntryV3]]:
mirror_status = MirrorStatusListV3(**json.loads(mirrorlist))
sorting_placeholder: Dict[str, list[MirrorStatusEntryV3]] = {}
sorting_placeholder: dict[str, list[MirrorStatusEntryV3]] = {}
for mirror in mirror_status.urls:
# We filter out mirrors that have bad criteria values
@ -401,7 +401,7 @@ def _parse_remote_mirror_list(mirrorlist: str) -> Dict[str, list[MirrorStatusEnt
if mirror.url.startswith('http'):
sorting_placeholder.setdefault(mirror.country, []).append(mirror)
sorted_by_regions: Dict[str, list[MirrorStatusEntryV3]] = dict({
sorted_by_regions: dict[str, list[MirrorStatusEntryV3]] = dict({
region: unsorted_mirrors
for region, unsorted_mirrors in sorted(sorting_placeholder.items(), key=lambda item: item[0])
})
@ -409,13 +409,13 @@ def _parse_remote_mirror_list(mirrorlist: str) -> Dict[str, list[MirrorStatusEnt
return sorted_by_regions
def _parse_locale_mirrors(mirrorlist: str) -> Dict[str, list[MirrorStatusEntryV3]]:
def _parse_locale_mirrors(mirrorlist: str) -> dict[str, list[MirrorStatusEntryV3]]:
lines = mirrorlist.splitlines()
# remove empty lines
lines = [line for line in lines if line]
mirror_list: Dict[str, list[MirrorStatusEntryV3]] = {}
mirror_list: dict[str, list[MirrorStatusEntryV3]] = {}
current_region = ''
for idx, line in enumerate(lines):

View File

@ -1,6 +1,6 @@
from dataclasses import dataclass
from enum import Enum
from typing import Any, TYPE_CHECKING, Dict
from typing import Any, TYPE_CHECKING
from ..hardware import SysInfo
from ..output import info
@ -21,13 +21,13 @@ class Audio(Enum):
class AudioConfiguration:
audio: Audio
def json(self) -> Dict[str, Any]:
def json(self) -> dict[str, Any]:
return {
'audio': self.audio.value
}
@staticmethod
def parse_arg(arg: Dict[str, Any]) -> 'AudioConfiguration':
def parse_arg(arg: dict[str, Any]) -> 'AudioConfiguration':
return AudioConfiguration(
Audio(arg['audio'])
)

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Optional, Dict, Any
from typing import Optional, Any
@dataclass
@ -88,7 +88,7 @@ class PackageSearchResult:
checkdepends: list[str]
@staticmethod
def from_json(data: Dict[str, Any]) -> 'PackageSearchResult':
def from_json(data: dict[str, Any]) -> 'PackageSearchResult':
return PackageSearchResult(**data)
@property
@ -112,7 +112,7 @@ class PackageSearch:
results: list[PackageSearchResult]
@staticmethod
def from_json(data: Dict[str, Any]) -> 'PackageSearch':
def from_json(data: dict[str, Any]) -> 'PackageSearch':
results = [PackageSearchResult.from_json(r) for r in data['results']]
return PackageSearch(

View File

@ -4,10 +4,7 @@ import http.client
import urllib.error
import urllib.parse
import urllib.request
from typing import (
Dict,
Optional
)
from typing import Optional
from ..networking import ping, DownloadTimer
from ..output import debug
@ -119,8 +116,8 @@ class MirrorStatusListV3(BaseModel):
@classmethod
def check_model(
cls,
data: Dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]
) -> Dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]:
data: dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]
) -> dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]:
if data.get('version') == 3:
return data

View File

@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional, Dict, Any, TYPE_CHECKING, Tuple
from typing import Optional, Any, TYPE_CHECKING, Tuple
from ..profile import ProfileConfiguration
@ -33,7 +33,7 @@ class Nic:
gateway: Optional[str] = None
dns: list[str] = field(default_factory=list)
def table_data(self) -> Dict[str, Any]:
def table_data(self) -> dict[str, Any]:
return {
'iface': self.iface if self.iface else '',
'ip': self.ip if self.ip else '',
@ -42,7 +42,7 @@ class Nic:
'dns': self.dns
}
def json(self) -> Dict[str, Any]:
def json(self) -> dict[str, Any]:
return {
'iface': self.iface,
'ip': self.ip,
@ -52,7 +52,7 @@ class Nic:
}
@staticmethod
def parse_arg(arg: Dict[str, Any]) -> Nic:
def parse_arg(arg: dict[str, Any]) -> Nic:
return Nic(
iface=arg.get('iface', None),
ip=arg.get('ip', None),
@ -94,15 +94,15 @@ class NetworkConfiguration:
type: NicType
nics: list[Nic] = field(default_factory=list)
def json(self) -> Dict[str, Any]:
config: Dict[str, Any] = {'type': self.type.value}
def json(self) -> dict[str, Any]:
config: dict[str, Any] = {'type': self.type.value}
if self.nics:
config['nics'] = [n.json() for n in self.nics]
return config
@staticmethod
def parse_arg(config: Dict[str, Any]) -> Optional[NetworkConfiguration]:
def parse_arg(config: dict[str, Any]) -> Optional[NetworkConfiguration]:
nic_type = config.get('type', None)
if not nic_type:
return None

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Dict, Union, Any, TYPE_CHECKING
from typing import Union, Any, TYPE_CHECKING
from enum import Enum
if TYPE_CHECKING:
@ -102,7 +102,7 @@ class User:
# if it's every going to be used
return []
def json(self) -> Dict[str, Any]:
def json(self) -> dict[str, Any]:
return {
'username': self.username,
'!password': self.password,
@ -110,7 +110,7 @@ class User:
}
@classmethod
def _parse(cls, config_users: list[Dict[str, Any]]) -> list['User']:
def _parse(cls, config_users: list[dict[str, Any]]) -> list['User']:
users = []
for entry in config_users:
@ -127,7 +127,7 @@ class User:
return users
@classmethod
def _parse_backwards_compatible(cls, config_users: Dict, sudo: bool) -> list['User']:
def _parse_backwards_compatible(cls, config_users: dict, sudo: bool) -> list['User']:
if len(config_users.keys()) > 0:
username = list(config_users.keys())[0]
password = config_users[username]['!password']
@ -140,8 +140,8 @@ class User:
@classmethod
def parse_arguments(
cls,
config_users: Union[list[Dict[str, str]], Dict[str, str]],
config_superusers: Union[list[Dict[str, str]], Dict[str, str]]
config_users: Union[list[dict[str, str]], dict[str, str]],
config_superusers: Union[list[dict[str, str]], dict[str, str]]
) -> list['User']:
users = []

View File

@ -5,7 +5,7 @@ import unicodedata
from enum import Enum
from pathlib import Path
from typing import Dict, Union, Any, Callable, Optional, TYPE_CHECKING
from typing import Union, Any, Callable, Optional, TYPE_CHECKING
from dataclasses import asdict, is_dataclass
from .storage import storage
@ -22,7 +22,7 @@ class FormattedOutput:
o: 'DataclassInstance',
class_formatter: Optional[Union[str, Callable]] = None,
filter_list: list[str] = []
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""
the original values returned a dataclass as dict thru the call to some specific methods
this version allows thru the parameter class_formatter to call a dynamically selected formatting method.
@ -67,7 +67,7 @@ class FormattedOutput:
raw_data = [cls._get_values(o, class_formatter, filter_list) for o in obj]
# determine the maximum column size
column_width: Dict[str, int] = {}
column_width: dict[str, int] = {}
for o in raw_data:
for k, v in o.items():
if not filter_list or k in filter_list:

View File

@ -1,7 +1,7 @@
import dataclasses
import json
import ssl
from typing import Dict, Any, Tuple
from typing import Any, Tuple
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import urlopen
@ -15,7 +15,7 @@ BASE_URL_PKG_SEARCH = 'https://archlinux.org/packages/search/json/'
BASE_GROUP_URL = 'https://archlinux.org/groups/search/json/'
def _make_request(url: str, params: Dict) -> Any:
def _make_request(url: str, params: dict) -> Any:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
@ -77,7 +77,7 @@ def find_package(package: str) -> list[PackageSearchResult]:
return results
def find_packages(*names: str) -> Dict[str, Any]:
def find_packages(*names: str) -> dict[str, Any]:
"""
This function returns the search results for many packages.
The function itself is rather slow, so consider not sending to

View File

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Dict
from typing import TYPE_CHECKING, Any, Optional
from archinstall.default_profiles.profile import Profile, GreeterType
from .profile_model import ProfileConfiguration
@ -28,7 +28,7 @@ class ProfileMenu(AbstractSubMenu):
else:
self._preset = ProfileConfiguration()
self._data_store: Dict[str, Any] = {}
self._data_store: dict[str, Any] = {}
menu_optioons = self._define_menu_options()
self._item_group = MenuItemGroup(menu_optioons, checkmarks=True)

View File

@ -1,7 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional, Dict
from typing import TYPE_CHECKING, Any, Optional
from ..hardware import GfxDriver
from archinstall.default_profiles.profile import Profile, GreeterType
@ -16,7 +16,7 @@ class ProfileConfiguration:
gfx_driver: Optional[GfxDriver] = None
greeter: Optional[GreeterType] = None
def json(self) -> Dict[str, Any]:
def json(self) -> dict[str, Any]:
from .profiles_handler import profile_handler
return {
'profile': profile_handler.to_json(self.profile),
@ -25,7 +25,7 @@ class ProfileConfiguration:
}
@classmethod
def parse_arg(cls, arg: Dict[str, Any]) -> 'ProfileConfiguration':
def parse_arg(cls, arg: dict[str, Any]) -> 'ProfileConfiguration':
from .profiles_handler import profile_handler
profile = profile_handler.parse_profile_config(arg['profile'])

View File

@ -8,7 +8,7 @@ from functools import cached_property
from pathlib import Path
from tempfile import NamedTemporaryFile
from types import ModuleType
from typing import TYPE_CHECKING, Any, Optional, Dict, Union
from typing import TYPE_CHECKING, Any, Optional, Union
from ...default_profiles.profile import Profile, GreeterType
from .profile_model import ProfileConfiguration
@ -33,11 +33,11 @@ class ProfileHandler:
# wants to save the configuration
self._url_path = None
def to_json(self, profile: Optional[Profile]) -> Dict[str, Any]:
def to_json(self, profile: Optional[Profile]) -> dict[str, Any]:
"""
Serialize the selected profile setting to JSON
"""
data: Dict[str, Any] = {}
data: dict[str, Any] = {}
if profile is not None:
data = {
@ -51,7 +51,7 @@ class ProfileHandler:
return data
def parse_profile_config(self, profile_config: Dict[str, Any]) -> Optional[Profile]:
def parse_profile_config(self, profile_config: dict[str, Any]) -> Optional[Profile]:
"""
Deserialize JSON configuration for profile
"""

View File

@ -5,11 +5,11 @@
# (4. Added the ~/.config directory as an additional option for future reasons)
#
# And Keeping this in dict ensures that variables are shared across imports.
from typing import Any, Dict
from typing import Any
from pathlib import Path
storage: Dict[str, Any] = {
storage: dict[str, Any] = {
'PROFILE': Path(__file__).parent.parent.joinpath('default_profiles'),
'LOG_PATH': Path('/var/log/archinstall'),
'LOG_FILE': Path('install.log'),

View File

@ -1,6 +1,6 @@
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Optional
from typing import TYPE_CHECKING, Any, Optional
import archinstall
from archinstall import SysInfo, info, debug
@ -34,7 +34,7 @@ class ExecutionMode(Enum):
class SwissMainMenu(GlobalMenu):
def __init__(
self,
data_store: Dict[str, Any],
data_store: dict[str, Any],
mode: ExecutionMode = ExecutionMode.Guided,
advanced: bool = False
):