Remove most deprecated typing.List usage (#2810)

This commit is contained in:
correctmost 2024-11-15 18:13:51 -05:00 committed by GitHub
parent 360118f68f
commit dff101e279
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
45 changed files with 288 additions and 296 deletions

View File

@ -1,4 +1,4 @@
from typing import Any, TYPE_CHECKING, List, Optional, Dict from typing import Any, TYPE_CHECKING, Optional, Dict
from archinstall.lib.output import info from archinstall.lib.output import info
from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.lib.profile.profiles_handler import profile_handler
@ -15,7 +15,7 @@ if TYPE_CHECKING:
class DesktopProfile(Profile): class DesktopProfile(Profile):
def __init__(self, current_selection: List[Profile] = []) -> None: def __init__(self, current_selection: list[Profile] = []) -> None:
super().__init__( super().__init__(
'Desktop', 'Desktop',
ProfileType.Desktop, ProfileType.Desktop,
@ -25,7 +25,7 @@ class DesktopProfile(Profile):
) )
@property @property
def packages(self) -> List[str]: def packages(self) -> list[str]:
return [ return [
'nano', 'nano',
'vim', 'vim',

View File

@ -1,5 +1,5 @@
from enum import Enum from enum import Enum
from typing import List, Optional, TYPE_CHECKING, Any from typing import Optional, TYPE_CHECKING, Any
from archinstall.default_profiles.profile import ProfileType, GreeterType, SelectResult from archinstall.default_profiles.profile import ProfileType, GreeterType, SelectResult
from archinstall.default_profiles.xorg import XorgProfile from archinstall.default_profiles.xorg import XorgProfile
@ -25,7 +25,7 @@ class HyprlandProfile(XorgProfile):
self.custom_settings = {'seat_access': None} self.custom_settings = {'seat_access': None}
@property @property
def packages(self) -> List[str]: def packages(self) -> list[str]:
return [ return [
"hyprland", "hyprland",
"dunst", "dunst",
@ -45,7 +45,7 @@ class HyprlandProfile(XorgProfile):
return GreeterType.Sddm return GreeterType.Sddm
@property @property
def services(self) -> List[str]: def services(self) -> list[str]:
if pref := self.custom_settings.get('seat_access', None): if pref := self.custom_settings.get('seat_access', None):
return [pref] return [pref]
return [] return []

View File

@ -1,5 +1,5 @@
from enum import Enum from enum import Enum
from typing import List, Optional, TYPE_CHECKING, Any from typing import Optional, TYPE_CHECKING, Any
from archinstall.default_profiles.profile import ProfileType, GreeterType, SelectResult from archinstall.default_profiles.profile import ProfileType, GreeterType, SelectResult
from archinstall.default_profiles.xorg import XorgProfile from archinstall.default_profiles.xorg import XorgProfile
@ -30,7 +30,7 @@ class SwayProfile(XorgProfile):
self.custom_settings = {'seat_access': None} self.custom_settings = {'seat_access': None}
@property @property
def packages(self) -> List[str]: def packages(self) -> list[str]:
additional = [] additional = []
if seat := self.custom_settings.get('seat_access', None): if seat := self.custom_settings.get('seat_access', None):
additional = [seat] additional = [seat]
@ -55,7 +55,7 @@ class SwayProfile(XorgProfile):
return GreeterType.Lightdm return GreeterType.Lightdm
@property @property
def services(self) -> List[str]: def services(self) -> list[str]:
if pref := self.custom_settings.get('seat_access', None): if pref := self.custom_settings.get('seat_access', None):
return [pref] return [pref]
return [] return []

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import sys import sys
from enum import Enum, auto from enum import Enum, auto
from typing import List, Optional, Any, Dict, TYPE_CHECKING from typing import Optional, Any, Dict, TYPE_CHECKING
from ..lib.storage import storage from ..lib.storage import storage
@ -52,9 +52,9 @@ class Profile:
name: str, name: str,
profile_type: ProfileType, profile_type: ProfileType,
description: str = '', description: str = '',
current_selection: List[Profile] = [], current_selection: list[Profile] = [],
packages: List[str] = [], packages: list[str] = [],
services: List[str] = [], services: list[str] = [],
support_gfx_driver: bool = False, support_gfx_driver: bool = False,
support_greeter: bool = False, support_greeter: bool = False,
advanced: bool = False advanced: bool = False
@ -78,7 +78,7 @@ class Profile:
self.custom_enabled = False self.custom_enabled = False
@property @property
def packages(self) -> List[str]: def packages(self) -> list[str]:
""" """
Returns a list of packages that should be installed when Returns a list of packages that should be installed when
this profile is among the chosen ones this profile is among the chosen ones
@ -86,7 +86,7 @@ class Profile:
return self._packages return self._packages
@property @property
def services(self) -> List[str]: def services(self) -> list[str]:
""" """
Returns a list of services that should be enabled when Returns a list of services that should be enabled when
this profile is among the chosen ones this profile is among the chosen ones
@ -139,7 +139,7 @@ class Profile:
""" """
self.custom_settings = settings self.custom_settings = settings
def current_selection_names(self) -> List[str]: def current_selection_names(self) -> list[str]:
if self.current_selection: if self.current_selection:
return [s.name for s in self.current_selection] return [s.name for s in self.current_selection]
return [] return []

View File

@ -1,4 +1,4 @@
from typing import Any, TYPE_CHECKING, List, Optional from typing import Any, TYPE_CHECKING, Optional
from archinstall.lib.output import info from archinstall.lib.output import info
from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.lib.profile.profiles_handler import profile_handler
@ -15,7 +15,7 @@ if TYPE_CHECKING:
class ServerProfile(Profile): class ServerProfile(Profile):
def __init__(self, current_value: List[Profile] = []): def __init__(self, current_value: list[Profile] = []):
super().__init__( super().__init__(
'Server', 'Server',
ProfileType.Server, ProfileType.Server,

View File

@ -1,4 +1,4 @@
from typing import Dict, Optional, Any, TYPE_CHECKING, List from typing import Dict, Optional, Any, TYPE_CHECKING
from . import DiskLayoutConfiguration, DiskLayoutType from . import DiskLayoutConfiguration, DiskLayoutType
from .device_model import LvmConfiguration from .device_model import LvmConfiguration
@ -33,7 +33,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
super().__init__(self._item_group, data_store=self._data_store, allow_reset=True) super().__init__(self._item_group, data_store=self._data_store, allow_reset=True)
def _define_menu_options(self) -> List[MenuItem]: def _define_menu_options(self) -> list[MenuItem]:
return [ return [
MenuItem( MenuItem(
text=str(_('Partitioning')), text=str(_('Partitioning')),
@ -100,7 +100,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
msg += str(_('Mountpoint')) + ': ' + str(disk_layout_conf.mountpoint) msg += str(_('Mountpoint')) + ': ' + str(disk_layout_conf.mountpoint)
return msg return msg
device_mods: List[DeviceModification] = \ device_mods: list[DeviceModification] = \
list(filter(lambda x: len(x.partitions) > 0, disk_layout_conf.device_modifications)) list(filter(lambda x: len(x.partitions) > 0, disk_layout_conf.device_modifications))
if device_mods: if device_mods:

View File

@ -1,5 +1,5 @@
from pathlib import Path from pathlib import Path
from typing import Dict, Optional, Any, TYPE_CHECKING, List from typing import Dict, Optional, Any, TYPE_CHECKING
from . import LvmConfiguration, LvmVolume from . import LvmConfiguration, LvmVolume
from ..disk import ( from ..disk import (
@ -44,7 +44,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
super().__init__(self._item_group, data_store=self._data_store, allow_reset=True) super().__init__(self._item_group, data_store=self._data_store, allow_reset=True)
def _define_menu_options(self) -> List[MenuItem]: def _define_menu_options(self) -> list[MenuItem]:
return [ return [
MenuItem( MenuItem(
text=str(_('Encryption type')), text=str(_('Encryption type')),
@ -87,7 +87,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
), ),
] ]
def _select_lvm_vols(self, preset: List[LvmVolume]) -> List[LvmVolume]: def _select_lvm_vols(self, preset: list[LvmVolume]) -> list[LvmVolume]:
if self._disk_config.lvm_config: if self._disk_config.lvm_config:
return select_lvm_vols_to_encrypt(self._disk_config.lvm_config, preset=preset) return select_lvm_vols_to_encrypt(self._disk_config.lvm_config, preset=preset)
return [] return []
@ -181,7 +181,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None return None
def _prev_partitions(self) -> Optional[str]: def _prev_partitions(self) -> Optional[str]:
partitions: Optional[List[PartitionModification]] = self._item_group.find_by_key('partitions').value partitions: Optional[list[PartitionModification]] = self._item_group.find_by_key('partitions').value
if partitions: if partitions:
output = str(_('Partitions to be encrypted')) + '\n' output = str(_('Partitions to be encrypted')) + '\n'
@ -191,7 +191,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None return None
def _prev_lvm_vols(self) -> Optional[str]: def _prev_lvm_vols(self) -> Optional[str]:
volumes: Optional[List[PartitionModification]] = self._item_group.find_by_key('lvm_vols').value volumes: Optional[list[PartitionModification]] = self._item_group.find_by_key('lvm_vols').value
if volumes: if volumes:
output = str(_('LVM volumes to be encrypted')) + '\n' output = str(_('LVM volumes to be encrypted')) + '\n'
@ -212,7 +212,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
def select_encryption_type(disk_config: DiskLayoutConfiguration, preset: EncryptionType) -> Optional[EncryptionType]: def select_encryption_type(disk_config: DiskLayoutConfiguration, preset: EncryptionType) -> Optional[EncryptionType]:
options: List[EncryptionType] = [] options: list[EncryptionType] = []
preset_value = EncryptionType.type_to_text(preset) preset_value = EncryptionType.type_to_text(preset)
if disk_config.lvm_config: if disk_config.lvm_config:
@ -278,10 +278,10 @@ def select_hsm(preset: Optional[Fido2Device] = None) -> Optional[Fido2Device]:
def select_partitions_to_encrypt( def select_partitions_to_encrypt(
modification: List[DeviceModification], modification: list[DeviceModification],
preset: List[PartitionModification] preset: list[PartitionModification]
) -> List[PartitionModification]: ) -> list[PartitionModification]:
partitions: List[PartitionModification] = [] partitions: list[PartitionModification] = []
# do not allow encrypting the boot partition # do not allow encrypting the boot partition
for mod in modification: for mod in modification:
@ -312,9 +312,9 @@ def select_partitions_to_encrypt(
def select_lvm_vols_to_encrypt( def select_lvm_vols_to_encrypt(
lvm_config: LvmConfiguration, lvm_config: LvmConfiguration,
preset: List[LvmVolume] preset: list[LvmVolume]
) -> List[LvmVolume]: ) -> list[LvmVolume]:
volumes: List[LvmVolume] = lvm_config.get_all_volumes() volumes: list[LvmVolume] = lvm_config.get_all_volumes()
if volumes: if volumes:
group, header = MenuHelper.create_table(data=volumes) group, header = MenuHelper.create_table(data=volumes)

View File

@ -2,7 +2,6 @@ from __future__ import annotations
import getpass import getpass
from pathlib import Path from pathlib import Path
from typing import List
from .device_model import Fido2Device from .device_model import Fido2Device
from ..general import SysCommand, SysCommandWorker, clear_vt100_escape_codes from ..general import SysCommand, SysCommandWorker, clear_vt100_escape_codes
@ -12,10 +11,10 @@ from ..exceptions import SysCallError
class Fido2: class Fido2:
_loaded: bool = False _loaded: bool = False
_fido2_devices: List[Fido2Device] = [] _fido2_devices: list[Fido2Device] = []
@classmethod @classmethod
def get_fido2_devices(cls, reload: bool = False) -> List[Fido2Device]: def get_fido2_devices(cls, reload: bool = False) -> list[Fido2Device]:
""" """
Uses systemd-cryptenroll to list the FIDO2 devices Uses systemd-cryptenroll to list the FIDO2 devices
connected that supports FIDO2. connected that supports FIDO2.

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import time import time
from pathlib import Path from pathlib import Path
from typing import Any, Optional, TYPE_CHECKING, List, Dict, Set from typing import Any, Optional, TYPE_CHECKING, Dict, Set
from ..interactions.general_conf import ask_abort from ..interactions.general_conf import ask_abort
from .device_handler import device_handler from .device_handler import device_handler
@ -85,7 +85,7 @@ class FilesystemHandler:
def _format_partitions( def _format_partitions(
self, self,
partitions: List[PartitionModification], partitions: list[PartitionModification],
device_path: Path device_path: Path
) -> None: ) -> None:
""" """
@ -119,7 +119,7 @@ class FilesystemHandler:
part_mod.partuuid = lsblk_info.partuuid part_mod.partuuid = lsblk_info.partuuid
part_mod.uuid = lsblk_info.uuid part_mod.uuid = lsblk_info.uuid
def _validate_partitions(self, partitions: List[PartitionModification]) -> None: def _validate_partitions(self, partitions: list[PartitionModification]) -> None:
checks = { checks = {
# verify that all partitions have a path set (which implies that they have been created) # verify that all partitions have a path set (which implies that they have been created)
lambda x: x.dev_path is None: ValueError('When formatting, all partitions must have a path set'), lambda x: x.dev_path is None: ValueError('When formatting, all partitions must have a path set'),
@ -260,7 +260,7 @@ class FilesystemHandler:
def _get_all_pv_dev_paths( def _get_all_pv_dev_paths(
self, self,
pvs: List[PartitionModification], pvs: list[PartitionModification],
enc_mods: Dict[PartitionModification, Luks2] = {} enc_mods: Dict[PartitionModification, Luks2] = {}
) -> Set[Path]: ) -> Set[Path]:
pv_paths: Set[Path] = set() pv_paths: Set[Path] = set()

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import re import re
from pathlib import Path from pathlib import Path
from typing import Any, TYPE_CHECKING, List, Optional, Tuple from typing import Any, TYPE_CHECKING, Optional, Tuple
from dataclasses import dataclass from dataclasses import dataclass
from ..utils.util import prompt_dir from ..utils.util import prompt_dir
@ -33,7 +33,7 @@ class DefaultFreeSector:
class PartitioningList(ListManager): class PartitioningList(ListManager):
def __init__(self, prompt: str, device: BDevice, device_partitions: List[PartitionModification]): def __init__(self, prompt: str, device: BDevice, device_partitions: list[PartitionModification]):
self._device = device self._device = device
self._actions = { self._actions = {
'create_new_partition': str(_('Create a new partition')), 'create_new_partition': str(_('Create a new partition')),
@ -58,7 +58,7 @@ class PartitioningList(ListManager):
else: else:
return str(partition.dev_path) return str(partition.dev_path)
def filter_options(self, selection: PartitionModification, options: List[str]) -> List[str]: def filter_options(self, selection: PartitionModification, options: list[str]) -> list[str]:
not_filter = [] not_filter = []
# only display formatting if the partition exists already # only display formatting if the partition exists already
@ -94,8 +94,8 @@ class PartitioningList(ListManager):
self, self,
action: str, action: str,
entry: Optional[PartitionModification], entry: Optional[PartitionModification],
data: List[PartitionModification] data: list[PartitionModification]
) -> List[PartitionModification]: ) -> list[PartitionModification]:
action_key = [k for k, v in self._actions.items() if v == action][0] action_key = [k for k, v in self._actions.items() if v == action][0]
match action_key: match action_key:
@ -142,8 +142,8 @@ class PartitioningList(ListManager):
def _delete_partition( def _delete_partition(
self, self,
entry: PartitionModification, entry: PartitionModification,
data: List[PartitionModification] data: list[PartitionModification]
) -> List[PartitionModification]: ) -> list[PartitionModification]:
if entry.is_exists_or_modify(): if entry.is_exists_or_modify():
entry.status = ModificationStatus.Delete entry.status = ModificationStatus.Delete
return data return data
@ -421,7 +421,7 @@ class PartitioningList(ListManager):
return result.item() == MenuItem.yes() return result.item() == MenuItem.yes()
def _suggest_partition_layout(self, data: List[PartitionModification]) -> List[PartitionModification]: def _suggest_partition_layout(self, data: list[PartitionModification]) -> list[PartitionModification]:
# if modifications have been done already, inform the user # if modifications have been done already, inform the user
# that this operation will erase those modifications # that this operation will erase those modifications
if any([not entry.exists() for entry in data]): if any([not entry.exists() for entry in data]):
@ -437,8 +437,8 @@ class PartitioningList(ListManager):
def manual_partitioning( def manual_partitioning(
device: BDevice, device: BDevice,
prompt: str = '', prompt: str = '',
preset: List[PartitionModification] = [] preset: list[PartitionModification] = []
) -> List[PartitionModification]: ) -> list[PartitionModification]:
if not prompt: if not prompt:
prompt = str(_('Partition management: {}')).format(device.device_info.path) + '\n' prompt = str(_('Partition management: {}')).format(device.device_info.path) + '\n'
prompt += str(_('Total length: {}')).format(device.device_info.total_size.format_size(Unit.MiB)) prompt += str(_('Total length: {}')).format(device.device_info.total_size.format_size(Unit.MiB))
@ -455,7 +455,7 @@ def manual_partitioning(
manual_preset = preset manual_preset = preset
menu_list = PartitioningList(prompt, device, manual_preset) menu_list = PartitioningList(prompt, device, manual_preset)
partitions: List[PartitionModification] = menu_list.run() partitions: list[PartitionModification] = menu_list.run()
if menu_list.is_last_choice_cancel(): if menu_list.is_last_choice_cancel():
return preset return preset

View File

@ -1,5 +1,5 @@
from pathlib import Path from pathlib import Path
from typing import List, Optional, Any, TYPE_CHECKING from typing import Optional, Any, TYPE_CHECKING
from .device_model import SubvolumeModification from .device_model import SubvolumeModification
from ..menu import ListManager from ..menu import ListManager
@ -14,7 +14,7 @@ if TYPE_CHECKING:
class SubvolumeMenu(ListManager): class SubvolumeMenu(ListManager):
def __init__(self, prompt: str, btrfs_subvols: List[SubvolumeModification]): def __init__(self, prompt: str, btrfs_subvols: list[SubvolumeModification]):
self._actions = [ self._actions = [
str(_('Add subvolume')), str(_('Add subvolume')),
str(_('Edit subvolume')), str(_('Edit subvolume')),
@ -58,8 +58,8 @@ class SubvolumeMenu(ListManager):
self, self,
action: str, action: str,
entry: Optional[SubvolumeModification], entry: Optional[SubvolumeModification],
data: List[SubvolumeModification] data: list[SubvolumeModification]
) -> List[SubvolumeModification]: ) -> list[SubvolumeModification]:
if action == self._actions[0]: # add if action == self._actions[0]: # add
new_subvolume = self._add_subvolume() new_subvolume = self._add_subvolume()

View File

@ -16,7 +16,7 @@ import urllib.error
import pathlib import pathlib
from datetime import datetime, date from datetime import datetime, date
from enum import Enum from enum import Enum
from typing import Callable, Optional, Dict, Any, List, Union, Iterator, TYPE_CHECKING from typing import Callable, Optional, Dict, Any, Union, Iterator, TYPE_CHECKING
from select import epoll, EPOLLIN, EPOLLHUP from select import epoll, EPOLLIN, EPOLLHUP
from shutil import which from shutil import which
@ -102,7 +102,7 @@ class UNSAFE_JSON(json.JSONEncoder, json.JSONDecoder):
class SysCommandWorker: class SysCommandWorker:
def __init__( def __init__(
self, self,
cmd: Union[str, List[str]], cmd: Union[str, list[str]],
callbacks: Optional[Dict[str, Any]] = None, callbacks: Optional[Dict[str, Any]] = None,
peek_output: Optional[bool] = False, peek_output: Optional[bool] = False,
environment_vars: Optional[Dict[str, Any]] = None, environment_vars: Optional[Dict[str, Any]] = None,
@ -345,7 +345,7 @@ class SysCommandWorker:
class SysCommand: class SysCommand:
def __init__(self, def __init__(self,
cmd: Union[str, List[str]], cmd: Union[str, list[str]],
callbacks: Dict[str, Callable[[Any], Any]] = {}, callbacks: Dict[str, Callable[[Any], Any]] = {},
start_callback: Optional[Callable[[Any], Any]] = None, start_callback: Optional[Callable[[Any], Any]] = None,
peek_output: Optional[bool] = False, peek_output: Optional[bool] = False,
@ -376,7 +376,7 @@ class SysCommand:
if len(args) >= 2 and args[1]: if len(args) >= 2 and args[1]:
error(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: if self.session:
for line in self.session: for line in self.session:
yield line yield line
@ -392,10 +392,10 @@ class SysCommand:
else: else:
raise ValueError("SysCommand() doesn't have key & value pairs, only slices, SysCommand('ls')[:10] as an example.") 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 '' 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 { return {
'cmd': self.cmd, 'cmd': self.cmd,
'callbacks': self._callbacks, 'callbacks': self._callbacks,
@ -472,7 +472,7 @@ def _pid_exists(pid: int) -> bool:
return False return False
def run_custom_user_commands(commands: List[str], installation: Installer) -> None: def run_custom_user_commands(commands: list[str], installation: Installer) -> None:
for index, command in enumerate(commands): for index, command in enumerate(commands):
script_path = f"/var/tmp/user-command.{index}.sh" script_path = f"/var/tmp/user-command.{index}.sh"
chroot_path = f"{installation.target}/{script_path}" chroot_path = f"{installation.target}/{script_path}"

View File

@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import Any, List, Optional, Dict, TYPE_CHECKING from typing import Any, Optional, Dict, TYPE_CHECKING
from . import disk from . import disk
from .general import secret from .general import secret
@ -54,7 +54,7 @@ class GlobalMenu(AbstractMenu):
super().__init__(self._item_group, data_store) 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 [ return [
MenuItem( MenuItem(
text=str(_('Archinstall language')), text=str(_('Archinstall language')),
@ -219,7 +219,7 @@ class GlobalMenu(AbstractMenu):
save_config(data) save_config(data)
def _missing_configs(self) -> List[str]: def _missing_configs(self) -> list[str]:
def check(s) -> bool: def check(s) -> bool:
item = self._item_group.find_by_key(s) item = self._item_group.find_by_key(s)
return item.has_value() return item.has_value()
@ -462,7 +462,7 @@ class GlobalMenu(AbstractMenu):
return None return None
def _prev_users(self, item: MenuItem) -> Optional[str]: def _prev_users(self, item: MenuItem) -> Optional[str]:
users: Optional[List[User]] = item.value users: Optional[list[User]] = item.value
if users: if users:
return FormattedOutput.as_table(users) return FormattedOutput.as_table(users)
@ -521,7 +521,7 @@ class GlobalMenu(AbstractMenu):
profile_config = ProfileMenu(preset=current_profile).run() profile_config = ProfileMenu(preset=current_profile).run()
return profile_config return profile_config
def _create_user_account(self, preset: Optional[List[User]] = None) -> List[User]: def _create_user_account(self, preset: Optional[list[User]] = None) -> list[User]:
preset = [] if preset is None else preset preset = [] if preset is None else preset
users = ask_for_additional_users(defined_users=preset) users = ask_for_additional_users(defined_users=preset)
return users return users

View File

@ -2,7 +2,7 @@ import os
from enum import Enum from enum import Enum
from functools import cached_property from functools import cached_property
from pathlib import Path from pathlib import Path
from typing import Optional, Dict, List, TYPE_CHECKING, Any from typing import Optional, Dict, TYPE_CHECKING, Any
from .exceptions import SysCallError from .exceptions import SysCallError
from .general import SysCommand from .general import SysCommand
@ -85,7 +85,7 @@ class GfxDriver(Enum):
return text return text
def gfx_packages(self) -> List[GfxPackage]: def gfx_packages(self) -> list[GfxPackage]:
packages = [GfxPackage.XorgServer, GfxPackage.XorgXinit] packages = [GfxPackage.XorgServer, GfxPackage.XorgXinit]
match self: match self:
@ -183,12 +183,12 @@ class _SysInfo:
return self.mem_info[key] return self.mem_info[key]
@cached_property @cached_property
def loaded_modules(self) -> List[str]: def loaded_modules(self) -> list[str]:
""" """
Returns loaded kernel modules Returns loaded kernel modules
""" """
modules_path = Path('/proc/modules') modules_path = Path('/proc/modules')
modules: List[str] = [] modules: list[str] = []
with modules_path.open() as file: with modules_path.open() as file:
for line in file: for line in file:

View File

@ -6,7 +6,7 @@ import shutil
import subprocess import subprocess
import time import time
from pathlib import Path from pathlib import Path
from typing import Any, List, Optional, TYPE_CHECKING, Union, Dict, Callable from typing import Any, Optional, TYPE_CHECKING, Union, Dict, Callable
from . import disk from . import disk
from .exceptions import DiskError, ServiceException, RequirementError, HardwareIncompatibilityError, SysCallError from .exceptions import DiskError, ServiceException, RequirementError, HardwareIncompatibilityError, SysCallError
@ -46,8 +46,8 @@ class Installer:
target: Path, target: Path,
disk_config: disk.DiskLayoutConfiguration, disk_config: disk.DiskLayoutConfiguration,
disk_encryption: Optional[disk.DiskEncryption] = None, disk_encryption: Optional[disk.DiskEncryption] = None,
base_packages: List[str] = [], base_packages: list[str] = [],
kernels: Optional[List[str]] = None kernels: Optional[list[str]] = None
): ):
""" """
`Installer()` is the wrapper for most basic installation steps. `Installer()` is the wrapper for most basic installation steps.
@ -71,24 +71,24 @@ class Installer:
if accessibility_tools_in_use(): if accessibility_tools_in_use():
self._base_packages.extend(__accessibility_packages__) self._base_packages.extend(__accessibility_packages__)
self.post_base_install: List[Callable] = [] self.post_base_install: list[Callable] = []
# TODO: Figure out which one of these two we'll use.. But currently we're mixing them.. # TODO: Figure out which one of these two we'll use.. But currently we're mixing them..
storage['session'] = self storage['session'] = self
storage['installation_session'] = self storage['installation_session'] = self
self._modules: List[str] = [] self._modules: list[str] = []
self._binaries: List[str] = [] self._binaries: list[str] = []
self._files: List[str] = [] self._files: list[str] = []
# systemd, sd-vconsole and sd-encrypt will be replaced by udev, keymap and encrypt # systemd, sd-vconsole and sd-encrypt will be replaced by udev, keymap and encrypt
# if HSM is not used to encrypt the root volume. Check mkinitcpio() function for that override. # if HSM is not used to encrypt the root volume. Check mkinitcpio() function for that override.
self._hooks: List[str] = [ self._hooks: list[str] = [
"base", "systemd", "autodetect", "microcode", "modconf", "kms", "keyboard", "base", "systemd", "autodetect", "microcode", "modconf", "kms", "keyboard",
"sd-vconsole", "block", "filesystems", "fsck" "sd-vconsole", "block", "filesystems", "fsck"
] ]
self._kernel_params: List[str] = [] self._kernel_params: list[str] = []
self._fstab_entries: List[str] = [] self._fstab_entries: list[str] = []
self._zram_enabled = False self._zram_enabled = False
self._disable_fstrim = False self._disable_fstrim = False
@ -273,7 +273,7 @@ class Installer:
def _prepare_luks_partitions( def _prepare_luks_partitions(
self, self,
partitions: List[disk.PartitionModification] partitions: list[disk.PartitionModification]
) -> Dict[disk.PartitionModification, Luks2]: ) -> Dict[disk.PartitionModification, Luks2]:
return { return {
part_mod: disk.device_handler.unlock_luks2_dev( part_mod: disk.device_handler.unlock_luks2_dev(
@ -300,7 +300,7 @@ class Installer:
def _prepare_luks_lvm( def _prepare_luks_lvm(
self, self,
lvm_volumes: List[disk.LvmVolume] lvm_volumes: list[disk.LvmVolume]
) -> Dict[disk.LvmVolume, Luks2]: ) -> Dict[disk.LvmVolume, Luks2]:
return { return {
vol: disk.device_handler.unlock_luks2_dev( vol: disk.device_handler.unlock_luks2_dev(
@ -355,8 +355,8 @@ class Installer:
def _mount_btrfs_subvol( def _mount_btrfs_subvol(
self, self,
dev_path: Path, dev_path: Path,
subvolumes: List[disk.SubvolumeModification], subvolumes: list[disk.SubvolumeModification],
mount_options: List[str] = [] mount_options: list[str] = []
) -> None: ) -> None:
for subvol in subvolumes: for subvol in subvolumes:
mountpoint = self.target / subvol.relative_mountpoint mountpoint = self.target / subvol.relative_mountpoint
@ -455,7 +455,7 @@ class Installer:
self._kernel_params.append(f'resume=UUID={resume_uuid}') self._kernel_params.append(f'resume=UUID={resume_uuid}')
self._kernel_params.append(f'resume_offset={resume_offset}') self._kernel_params.append(f'resume_offset={resume_offset}')
def post_install_check(self, *args: str, **kwargs: str) -> List[str]: def post_install_check(self, *args: str, **kwargs: str) -> list[str]:
return [step for step, flag in self.helper_flags.items() if flag is False] return [step for step, flag in self.helper_flags.items() if flag is False]
def set_mirrors(self, mirror_config: MirrorConfiguration, on_target: bool = False) -> None: def set_mirrors(self, mirror_config: MirrorConfiguration, on_target: bool = False) -> None:
@ -607,7 +607,7 @@ class Installer:
# fstrim is owned by util-linux, a dependency of both base and systemd. # fstrim is owned by util-linux, a dependency of both base and systemd.
self.enable_service("fstrim.timer") self.enable_service("fstrim.timer")
def enable_service(self, services: Union[str, List[str]]) -> None: def enable_service(self, services: Union[str, list[str]]) -> None:
if isinstance(services, str): if isinstance(services, str):
services = [services] services = [services]
@ -701,7 +701,7 @@ class Installer:
return True return True
def mkinitcpio(self, flags: List[str]) -> bool: def mkinitcpio(self, flags: list[str]) -> bool:
for plugin in plugins.values(): for plugin in plugins.values():
if hasattr(plugin, 'on_mkinitcpio'): if hasattr(plugin, 'on_mkinitcpio'):
# Allow plugins to override the usage of mkinitcpio altogether. # Allow plugins to override the usage of mkinitcpio altogether.
@ -943,7 +943,7 @@ class Installer:
root_partition: disk.PartitionModification, root_partition: disk.PartitionModification,
id_root: bool = True, id_root: bool = True,
partuuid: bool = True partuuid: bool = True
) -> List[str]: ) -> list[str]:
kernel_parameters = [] kernel_parameters = []
if root_partition in self._disk_encryption.partitions: if root_partition in self._disk_encryption.partitions:
@ -979,7 +979,7 @@ class Installer:
def _get_kernel_params_lvm( def _get_kernel_params_lvm(
self, self,
lvm: disk.LvmVolume lvm: disk.LvmVolume
) -> List[str]: ) -> list[str]:
kernel_parameters = [] kernel_parameters = []
match self._disk_encryption.encryption_type: match self._disk_encryption.encryption_type:
@ -1020,7 +1020,7 @@ class Installer:
root: disk.PartitionModification | disk.LvmVolume, root: disk.PartitionModification | disk.LvmVolume,
id_root: bool = True, id_root: bool = True,
partuuid: bool = True partuuid: bool = True
) -> List[str]: ) -> list[str]:
kernel_parameters = [] kernel_parameters = []
if isinstance(root, disk.LvmVolume): if isinstance(root, disk.LvmVolume):
@ -1466,7 +1466,7 @@ Exec = /bin/sh -c "{hook_command}"
case Bootloader.Limine: case Bootloader.Limine:
self._add_limine_bootloader(boot_partition, efi_partition, root) self._add_limine_bootloader(boot_partition, efi_partition, root)
def add_additional_packages(self, packages: Union[str, List[str]]) -> None: def add_additional_packages(self, packages: Union[str, list[str]]) -> None:
return self.pacman.strap(packages) return self.pacman.strap(packages)
def enable_sudo(self, entity: str, group: bool = False): def enable_sudo(self, entity: str, group: bool = False):
@ -1499,14 +1499,14 @@ Exec = /bin/sh -c "{hook_command}"
# Guarantees sudoer conf file recommended perms # Guarantees sudoer conf file recommended perms
os.chmod(Path(rule_file_name), 0o440) os.chmod(Path(rule_file_name), 0o440)
def create_users(self, users: Union[User, List[User]]) -> None: def create_users(self, users: Union[User, list[User]]) -> None:
if not isinstance(users, list): if not isinstance(users, list):
users = [users] users = [users]
for user in users: for user in users:
self.user_create(user.username, user.password, user.groups, user.sudo) self.user_create(user.username, user.password, user.groups, user.sudo)
def user_create(self, user: str, password: Optional[str] = None, groups: Optional[List[str]] = None, def user_create(self, user: str, password: Optional[str] = None, groups: Optional[list[str]] = None,
sudo: bool = False) -> None: sudo: bool = False) -> None:
if groups is None: if groups is None:
groups = [] groups = []
@ -1567,7 +1567,7 @@ Exec = /bin/sh -c "{hook_command}"
except SysCallError: except SysCallError:
return False return False
def chown(self, owner: str, path: str, options: List[str] = []) -> bool: def chown(self, owner: str, path: str, options: list[str] = []) -> bool:
cleaned_path = path.replace('\'', '\\\'') cleaned_path = path.replace('\'', '\\\'')
try: try:
SysCommand(f"/usr/bin/arch-chroot {self.target} sh -c 'chown {' '.join(options)} {owner} {cleaned_path}'") SysCommand(f"/usr/bin/arch-chroot {self.target} sh -c 'chown {' '.join(options)} {owner} {cleaned_path}'")

View File

@ -2,7 +2,7 @@ from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Any, TYPE_CHECKING from typing import Any, TYPE_CHECKING
from typing import Optional, List, Tuple from typing import Optional, Tuple
from .. import disk from .. import disk
from ..disk.device_model import BtrfsMountOption from ..disk.device_model import BtrfsMountOption
@ -22,7 +22,7 @@ if TYPE_CHECKING:
_: Any _: Any
def select_devices(preset: Optional[List[disk.BDevice]] = []) -> List[disk.BDevice]: def select_devices(preset: Optional[list[disk.BDevice]] = []) -> list[disk.BDevice]:
def _preview_device_selection(selection: disk._DeviceInfo) -> Optional[str]: def _preview_device_selection(selection: disk._DeviceInfo) -> Optional[str]:
dev = disk.device_handler.get_device(selection.path) dev = disk.device_handler.get_device(selection.path)
if dev and dev.partition_infos: if dev and dev.partition_infos:
@ -50,7 +50,7 @@ def select_devices(preset: Optional[List[disk.BDevice]] = []) -> List[disk.BDevi
case ResultType.Reset: return [] case ResultType.Reset: return []
case ResultType.Skip: return preset case ResultType.Skip: return preset
case ResultType.Selection: case ResultType.Selection:
selected_device_info: List[disk._DeviceInfo] = result.get_values() selected_device_info: list[disk._DeviceInfo] = result.get_values()
selected_devices = [] selected_devices = []
for device in devices: for device in devices:
@ -61,10 +61,10 @@ def select_devices(preset: Optional[List[disk.BDevice]] = []) -> List[disk.BDevi
def get_default_partition_layout( def get_default_partition_layout(
devices: List[disk.BDevice], devices: list[disk.BDevice],
filesystem_type: Optional[disk.FilesystemType] = None, filesystem_type: Optional[disk.FilesystemType] = None,
advanced_option: bool = False advanced_option: bool = False
) -> List[disk.DeviceModification]: ) -> list[disk.DeviceModification]:
if len(devices) == 1: if len(devices) == 1:
device_modification = suggest_single_disk_layout( device_modification = suggest_single_disk_layout(
devices[0], devices[0],
@ -81,9 +81,9 @@ def get_default_partition_layout(
def _manual_partitioning( def _manual_partitioning(
preset: List[disk.DeviceModification], preset: list[disk.DeviceModification],
devices: List[disk.BDevice] devices: list[disk.BDevice]
) -> List[disk.DeviceModification]: ) -> list[disk.DeviceModification]:
modifications = [] modifications = []
for device in devices: for device in devices:
mod = next(filter(lambda x: x.device == device, preset), None) mod = next(filter(lambda x: x.device == device, preset), None)
@ -248,7 +248,7 @@ def select_main_filesystem_format(advanced_options: bool = False) -> disk.Filesy
raise ValueError('Unhandled result type') raise ValueError('Unhandled result type')
def select_mount_options() -> List[str]: def select_mount_options() -> list[str]:
prompt = str(_('Would you like to use compression or disable CoW?')) + '\n' prompt = str(_('Would you like to use compression or disable CoW?')) + '\n'
compression = str(_('Use compression')) compression = str(_('Use compression'))
disable_cow = str(_('Disable Copy-on-Write')) disable_cow = str(_('Disable Copy-on-Write'))
@ -423,10 +423,10 @@ def suggest_single_disk_layout(
def suggest_multi_disk_layout( def suggest_multi_disk_layout(
devices: List[disk.BDevice], devices: list[disk.BDevice],
filesystem_type: Optional[disk.FilesystemType] = None, filesystem_type: Optional[disk.FilesystemType] = None,
advanced_options: bool = False advanced_options: bool = False
) -> List[disk.DeviceModification]: ) -> list[disk.DeviceModification]:
if not devices: if not devices:
return [] return []
@ -452,7 +452,7 @@ def suggest_multi_disk_layout(
delta = device.device_info.total_size - desired_root_partition_size delta = device.device_info.total_size - desired_root_partition_size
devices_delta[device] = delta devices_delta[device] = delta
sorted_delta: List[Tuple[disk.BDevice, Any]] = sorted(devices_delta.items(), key=lambda x: x[1]) sorted_delta: list[Tuple[disk.BDevice, Any]] = sorted(devices_delta.items(), key=lambda x: x[1])
root_device: Optional[disk.BDevice] = sorted_delta[0][0] root_device: Optional[disk.BDevice] = sorted_delta[0][0]
if home_device is None or root_device is None: if home_device is None or root_device is None:
@ -575,7 +575,7 @@ def suggest_lvm_layout(
home_volume = False home_volume = False
boot_part: Optional[disk.PartitionModification] = None boot_part: Optional[disk.PartitionModification] = None
other_part: List[disk.PartitionModification] = [] other_part: list[disk.PartitionModification] = []
for mod in disk_config.device_modifications: for mod in disk_config.device_modifications:
for part in mod.partitions: for part in mod.partitions:

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import pathlib import pathlib
from typing import List, Any, Optional, TYPE_CHECKING from typing import Any, Optional, TYPE_CHECKING
from ..locale import list_timezones from ..locale import list_timezones
from ..models.audio_configuration import Audio, AudioConfiguration from ..models.audio_configuration import Audio, AudioConfiguration
@ -128,7 +128,7 @@ def select_language(preset: Optional[str] = None) -> Optional[str]:
return select_kb_layout(preset) return select_kb_layout(preset)
def select_archinstall_language(languages: List[Language], preset: Language) -> Language: def select_archinstall_language(languages: list[Language], preset: Language) -> Language:
# these are the displayed language names which can either be # these are the displayed language names which can either be
# the english name of a language or, if present, the # the english name of a language or, if present, the
# name of the language in its own language # name of the language in its own language
@ -159,7 +159,7 @@ def select_archinstall_language(languages: List[Language], preset: Language) ->
raise ValueError('Language selection not handled') raise ValueError('Language selection not handled')
def ask_additional_packages_to_install(preset: List[str] = []) -> List[str]: def ask_additional_packages_to_install(preset: list[str] = []) -> list[str]:
# Additional packages (with some light weight error handling for invalid package names) # Additional packages (with some light weight error handling for invalid package names)
header = str(_('Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.')) + '\n' header = str(_('Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.')) + '\n'
header += str(_('If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.')) + '\n' header += str(_('If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.')) + '\n'
@ -253,7 +253,7 @@ def add_number_of_parallel_downloads(preset: Optional[int] = None) -> Optional[i
return downloads return downloads
def select_additional_repositories(preset: List[str]) -> List[str]: def select_additional_repositories(preset: list[str]) -> list[str]:
""" """
Allows the user to select additional repositories (multilib, and testing) if desired. Allows the user to select additional repositories (multilib, and testing) if desired.

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import re import re
from typing import Any, TYPE_CHECKING, List, Optional from typing import Any, TYPE_CHECKING, Optional
from ..utils.util import get_password from ..utils.util import get_password
from ..menu import ListManager from ..menu import ListManager
@ -19,7 +19,7 @@ if TYPE_CHECKING:
class UserList(ListManager): class UserList(ListManager):
def __init__(self, prompt: str, lusers: List[User]): def __init__(self, prompt: str, lusers: list[User]):
self._actions = [ self._actions = [
str(_('Add a user')), str(_('Add a user')),
str(_('Change password')), str(_('Change password')),
@ -31,7 +31,7 @@ class UserList(ListManager):
def selected_action_display(self, user: User) -> str: def selected_action_display(self, user: User) -> str:
return user.username return user.username
def handle_action(self, action: str, entry: Optional[User], data: List[User]) -> List[User]: def handle_action(self, action: str, entry: Optional[User], data: list[User]) -> list[User]:
if action == self._actions[0]: # add if action == self._actions[0]: # add
new_user = self._add_user() new_user = self._add_user()
if new_user is not None: if new_user is not None:
@ -106,6 +106,6 @@ class UserList(ListManager):
return User(username, password, sudo) return User(username, password, sudo)
def ask_for_additional_users(prompt: str = '', defined_users: List[User] = []) -> List[User]: def ask_for_additional_users(prompt: str = '', defined_users: list[User] = []) -> list[User]:
users = UserList(prompt, defined_users).run() users = UserList(prompt, defined_users).run()
return users return users

View File

@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import ipaddress import ipaddress
from typing import Any, Optional, TYPE_CHECKING, List from typing import Any, Optional, TYPE_CHECKING
from ..models.network_configuration import NetworkConfiguration, NicType, Nic from ..models.network_configuration import NetworkConfiguration, NicType, Nic
@ -18,7 +18,7 @@ if TYPE_CHECKING:
class ManualNetworkConfig(ListManager): class ManualNetworkConfig(ListManager):
def __init__(self, prompt: str, preset: List[Nic]): def __init__(self, prompt: str, preset: list[Nic]):
self._actions = [ self._actions = [
str(_('Add interface')), str(_('Add interface')),
str(_('Edit interface')), str(_('Edit interface')),
@ -29,7 +29,7 @@ class ManualNetworkConfig(ListManager):
def selected_action_display(self, nic: Nic) -> str: def selected_action_display(self, nic: Nic) -> str:
return nic.iface if nic.iface else '' return nic.iface if nic.iface else ''
def handle_action(self, action: str, entry: Optional[Nic], data: List[Nic]) -> list[Nic]: def handle_action(self, action: str, entry: Optional[Nic], data: list[Nic]) -> list[Nic]:
if action == self._actions[0]: # add if action == self._actions[0]: # add
iface = self._select_iface(data) iface = self._select_iface(data)
if iface: if iface:
@ -45,7 +45,7 @@ class ManualNetworkConfig(ListManager):
return data return data
def _select_iface(self, data: List[Nic]) -> Optional[str]: def _select_iface(self, data: list[Nic]) -> Optional[str]:
all_ifaces = list_interfaces().values() all_ifaces = list_interfaces().values()
existing_ifaces = [d.iface for d in data] existing_ifaces = [d.iface for d in data]
available = set(all_ifaces) - set(existing_ifaces) available = set(all_ifaces) - set(existing_ifaces)

View File

@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import List, Any, TYPE_CHECKING, Optional from typing import Any, TYPE_CHECKING, Optional
from ..hardware import SysInfo, GfxDriver from ..hardware import SysInfo, GfxDriver
from ..models.bootloader import Bootloader from ..models.bootloader import Bootloader
@ -15,7 +15,7 @@ if TYPE_CHECKING:
_: Any _: Any
def select_kernel(preset: List[str] = []) -> List[str]: def select_kernel(preset: list[str] = []) -> list[str]:
""" """
Asks the user to select a kernel for system. Asks the user to select a kernel for system.
@ -103,7 +103,7 @@ def ask_for_uki(preset: bool = True) -> bool:
raise ValueError('Unhandled result type') raise ValueError('Unhandled result type')
def select_driver(options: List[GfxDriver] = [], preset: Optional[GfxDriver] = None) -> Optional[GfxDriver]: def select_driver(options: list[GfxDriver] = [], preset: Optional[GfxDriver] = None) -> Optional[GfxDriver]:
""" """
Some what convoluted function, whose job is simple. Some what convoluted function, whose job is simple.
Select a graphics driver from a pre-defined set of popular options. Select a graphics driver from a pre-defined set of popular options.

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import Dict, Any, TYPE_CHECKING, Optional, List from typing import Dict, Any, TYPE_CHECKING, Optional
from .utils import list_keyboard_languages, list_locales, set_kb_layout, get_kb_layout from .utils import list_keyboard_languages, list_locales, set_kb_layout, get_kb_layout
from ..menu import AbstractSubMenu from ..menu import AbstractSubMenu
@ -74,7 +74,7 @@ class LocaleMenu(AbstractSubMenu):
self._item_group = MenuItemGroup(menu_optioons, sort_items=False, checkmarks=True) self._item_group = MenuItemGroup(menu_optioons, sort_items=False, checkmarks=True)
super().__init__(self._item_group, data_store=self._data_store, allow_reset=True) super().__init__(self._item_group, data_store=self._data_store, allow_reset=True)
def _define_menu_options(self) -> List[MenuItem]: def _define_menu_options(self) -> list[MenuItem]:
return [ return [
MenuItem( MenuItem(
text=str(_('Keyboard layout')), text=str(_('Keyboard layout')),

View File

@ -1,18 +1,16 @@
from typing import List
from ..exceptions import ServiceException, SysCallError from ..exceptions import ServiceException, SysCallError
from ..general import SysCommand from ..general import SysCommand
from ..output import error from ..output import error
def list_keyboard_languages() -> List[str]: def list_keyboard_languages() -> list[str]:
return SysCommand( return SysCommand(
"localectl --no-pager list-keymaps", "localectl --no-pager list-keymaps",
environment_vars={'SYSTEMD_COLORS': '0'} environment_vars={'SYSTEMD_COLORS': '0'}
).decode().splitlines() ).decode().splitlines()
def list_locales() -> List[str]: def list_locales() -> list[str]:
locales = [] locales = []
with open('/usr/share/i18n/SUPPORTED') as file: with open('/usr/share/i18n/SUPPORTED') as file:
@ -23,7 +21,7 @@ def list_locales() -> List[str]:
return locales return locales
def list_x11_keyboard_languages() -> List[str]: def list_x11_keyboard_languages() -> list[str]:
return SysCommand( return SysCommand(
"localectl --no-pager list-x11-keymap-layouts", "localectl --no-pager list-x11-keymap-layouts",
environment_vars={'SYSTEMD_COLORS': '0'} environment_vars={'SYSTEMD_COLORS': '0'}
@ -84,7 +82,7 @@ def set_kb_layout(locale: str) -> bool:
return False return False
def list_timezones() -> List[str]: def list_timezones() -> list[str]:
return SysCommand( return SysCommand(
"timedatectl --no-pager list-timezones", "timedatectl --no-pager list-timezones",
environment_vars={'SYSTEMD_COLORS': '0'} environment_vars={'SYSTEMD_COLORS': '0'}

View File

@ -4,7 +4,7 @@ import shlex
import time import time
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Optional, List from typing import Optional
from . import disk from . import disk
from .general import SysCommand, generate_password, SysCommandWorker from .general import SysCommand, generate_password, SysCommandWorker
@ -253,7 +253,7 @@ class Luks2:
self, self,
crypttab_path: Path, crypttab_path: Path,
key_file: Path, key_file: Path,
options: List[str] options: list[str]
) -> None: ) -> None:
debug(f'Adding crypttab entry for key {key_file}') debug(f'Adding crypttab entry for key {key_file}')

View File

@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import Callable, Any, List, Optional, Dict, TYPE_CHECKING from typing import Callable, Any, Optional, Dict, TYPE_CHECKING
from ..output import error from ..output import error
from ..output import unicode_ljust from ..output import unicode_ljust
@ -22,8 +22,8 @@ class Selector:
display_func: Optional[Callable] = None, display_func: Optional[Callable] = None,
default: Optional[Any] = None, default: Optional[Any] = None,
enabled: bool = False, enabled: bool = False,
dependencies: List = [], dependencies: list = [],
dependencies_not: List = [], dependencies_not: list = [],
exec_func: Optional[Callable] = None, exec_func: Optional[Callable] = None,
preview_func: Optional[Callable] = None, preview_func: Optional[Callable] = None,
mandatory: bool = False, mandatory: bool = False,

View File

@ -1,5 +1,5 @@
import copy import copy
from typing import Any, TYPE_CHECKING, Dict, Optional, Tuple, List from typing import Any, TYPE_CHECKING, Dict, Optional, Tuple
from ..output import FormattedOutput from ..output import FormattedOutput
from archinstall.tui import ( from archinstall.tui import (
@ -15,9 +15,9 @@ class ListManager:
def __init__( def __init__(
self, self,
prompt: str, prompt: str,
entries: List[Any], entries: list[Any],
base_actions: List[str], base_actions: list[str],
sub_menu_actions: List[str] sub_menu_actions: list[str]
): ):
""" """
:param prompt: Text which will appear at the header :param prompt: Text which will appear at the header
@ -58,7 +58,7 @@ class ListManager:
return self._last_choice == self._cancel_action return self._last_choice == self._cancel_action
return False return False
def run(self) -> List[Any]: def run(self) -> list[Any]:
while True: while True:
# this will return a dictionary with the key as the menu entry to be displayed # this will return a dictionary with the key as the menu entry to be displayed
# and the value is the original value from the self._data container # and the value is the original value from the self._data container
@ -97,10 +97,10 @@ class ListManager:
else: else:
return self._data 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 # header rows are mapped to None so make sure
# to exclude those from the selectable data # to exclude those from the selectable data
options: List[str] = [key for key, val in data_formatted.items() if val is not None] options: list[str] = [key for key, val in data_formatted.items() if val is not None]
header = '' header = ''
if len(options) > 0: if len(options) > 0:
@ -140,7 +140,7 @@ class ListManager:
if value != self._cancel_action: if value != self._cancel_action:
self._data = self.handle_action(value, entry, self._data) 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. Default implementation of the table to be displayed.
Override if any custom formatting is needed Override if any custom formatting is needed
@ -165,14 +165,14 @@ class ListManager:
""" """
raise NotImplementedError('Please implement me in the child class') raise NotImplementedError('Please implement me in the child class')
def handle_action(self, action: Any, entry: Optional[Any], data: List[Any]) -> List[Any]: def handle_action(self, action: Any, entry: Optional[Any], data: list[Any]) -> list[Any]:
""" """
this function is called when a base action or this function is called when a base action or
a specific action for an entry is triggered a specific action for an entry is triggered
""" """
raise NotImplementedError('Please implement me in the child class') raise NotImplementedError('Please implement me in the child class')
def filter_options(self, selection: Any, options: List[str]) -> List[str]: def filter_options(self, selection: Any, options: list[str]) -> list[str]:
""" """
filter which actions to show for an specific selection filter which actions to show for an specific selection
""" """

View File

@ -1,4 +1,4 @@
from typing import Any, Tuple, List, Dict, Optional from typing import Any, Tuple, Dict, Optional
from archinstall.lib.output import FormattedOutput from archinstall.lib.output import FormattedOutput
@ -10,8 +10,8 @@ from archinstall.tui import (
class MenuHelper: class MenuHelper:
@staticmethod @staticmethod
def create_table( def create_table(
data: Optional[List[Any]] = None, data: Optional[list[Any]] = None,
table_data: Optional[Tuple[List[Any], str]] = None, table_data: Optional[Tuple[list[Any], str]] = None,
) -> Tuple[MenuItemGroup, str]: ) -> Tuple[MenuItemGroup, str]:
if data is not None: if data is not None:
table_text = FormattedOutput.as_table(data) table_text = FormattedOutput.as_table(data)
@ -39,7 +39,7 @@ class MenuHelper:
return group, header return group, header
@staticmethod @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 # 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 # 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 # the selectable rows so the header has to be aligned

View File

@ -4,7 +4,7 @@ import urllib.parse
from pathlib import Path from pathlib import Path
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from typing import Dict, Any, List, Optional, TYPE_CHECKING, Tuple from typing import Dict, Any, Optional, TYPE_CHECKING, Tuple
from .menu import AbstractSubMenu, ListManager from .menu import AbstractSubMenu, ListManager
from .networking import fetch_data_from_url from .networking import fetch_data_from_url
@ -58,7 +58,7 @@ class CustomMirror:
} }
@classmethod @classmethod
def parse_args(cls, args: List[Dict[str, str]]) -> List['CustomMirror']: def parse_args(cls, args: list[Dict[str, str]]) -> list['CustomMirror']:
configs = [] configs = []
for arg in args: for arg in args:
configs.append( configs.append(
@ -75,8 +75,8 @@ class CustomMirror:
@dataclass @dataclass
class MirrorConfiguration: 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) custom_mirrors: list[CustomMirror] = field(default_factory=list)
@property @property
def regions(self) -> str: def regions(self) -> str:
@ -124,7 +124,7 @@ class MirrorConfiguration:
class CustomMirrorList(ListManager): class CustomMirrorList(ListManager):
def __init__(self, custom_mirrors: List[CustomMirror]): def __init__(self, custom_mirrors: list[CustomMirror]):
self._actions = [ self._actions = [
str(_('Add a custom mirror')), str(_('Add a custom mirror')),
str(_('Change custom mirror')), str(_('Change custom mirror')),
@ -144,8 +144,8 @@ class CustomMirrorList(ListManager):
self, self,
action: str, action: str,
entry: Optional[CustomMirror], entry: Optional[CustomMirror],
data: List[CustomMirror] data: list[CustomMirror]
) -> List[CustomMirror]: ) -> list[CustomMirror]:
if action == self._actions[0]: # add if action == self._actions[0]: # add
new_mirror = self._add_custom_mirror() new_mirror = self._add_custom_mirror()
if new_mirror is not None: if new_mirror is not None:
@ -259,7 +259,7 @@ class MirrorMenu(AbstractSubMenu):
super().__init__(self._item_group, data_store=self._data_store, allow_reset=True) super().__init__(self._item_group, data_store=self._data_store, allow_reset=True)
def _define_menu_options(self) -> List[MenuItem]: def _define_menu_options(self) -> list[MenuItem]:
return [ return [
MenuItem( MenuItem(
text=str(_('Mirror region')), text=str(_('Mirror region')),
@ -278,7 +278,7 @@ class MirrorMenu(AbstractSubMenu):
] ]
def _prev_regions(self, item: MenuItem) -> Optional[str]: 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 = '' output = ''
for name, status_list in mirrors.items(): for name, status_list in mirrors.items():
@ -296,7 +296,7 @@ class MirrorMenu(AbstractSubMenu):
if not item.value: if not item.value:
return None return None
custom_mirrors: List[CustomMirror] = item.value custom_mirrors: list[CustomMirror] = item.value
output = FormattedOutput.as_table(custom_mirrors) output = FormattedOutput.as_table(custom_mirrors)
return output.strip() return output.strip()
@ -312,8 +312,8 @@ class MirrorMenu(AbstractSubMenu):
) )
def select_mirror_regions(preset: Dict[str, List[MirrorStatusEntryV3]]) -> Dict[str, List[MirrorStatusEntryV3]]: def select_mirror_regions(preset: Dict[str, list[MirrorStatusEntryV3]]) -> Dict[str, list[MirrorStatusEntryV3]]:
mirrors: Dict[str, List[MirrorStatusEntryV3]] | None = list_mirrors_from_remote() mirrors: Dict[str, list[MirrorStatusEntryV3]] | None = list_mirrors_from_remote()
if not mirrors: if not mirrors:
mirrors = list_mirrors_from_local() mirrors = list_mirrors_from_local()
@ -339,16 +339,16 @@ def select_mirror_regions(preset: Dict[str, List[MirrorStatusEntryV3]]) -> Dict[
case ResultType.Reset: case ResultType.Reset:
return {} return {}
case ResultType.Selection: case ResultType.Selection:
selected_mirrors: List[Tuple[str, List[MirrorStatusEntryV3]]] = result.get_values() selected_mirrors: list[Tuple[str, list[MirrorStatusEntryV3]]] = result.get_values()
return {name: mirror for name, mirror in selected_mirrors} return {name: mirror for name, mirror in selected_mirrors}
def select_custom_mirror(preset: List[CustomMirror] = []): def select_custom_mirror(preset: list[CustomMirror] = []):
custom_mirrors = CustomMirrorList(preset).run() custom_mirrors = CustomMirrorList(preset).run()
return custom_mirrors 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']: if not storage['arguments']['offline']:
url = "https://archlinux.org/mirrors/status/json/" url = "https://archlinux.org/mirrors/status/json/"
attempts = 3 attempts = 3
@ -366,20 +366,20 @@ def list_mirrors_from_remote() -> Optional[Dict[str, List[MirrorStatusEntryV3]]]
return None 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: with Path('/etc/pacman.d/mirrorlist').open('r') as fp:
mirrorlist = fp.read() mirrorlist = fp.read()
return _parse_locale_mirrors(mirrorlist) return _parse_locale_mirrors(mirrorlist)
def _sort_mirrors_by_performance(mirror_list: List[MirrorStatusEntryV3]) -> List[MirrorStatusEntryV3]: def _sort_mirrors_by_performance(mirror_list: list[MirrorStatusEntryV3]) -> list[MirrorStatusEntryV3]:
return sorted(mirror_list, key=lambda mirror: (mirror.score, mirror.speed)) 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)) mirror_status = MirrorStatusListV3(**json.loads(mirrorlist))
sorting_placeholder: Dict[str, List[MirrorStatusEntryV3]] = {} sorting_placeholder: Dict[str, list[MirrorStatusEntryV3]] = {}
for mirror in mirror_status.urls: for mirror in mirror_status.urls:
# We filter out mirrors that have bad criteria values # 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'): if mirror.url.startswith('http'):
sorting_placeholder.setdefault(mirror.country, []).append(mirror) 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 region: unsorted_mirrors
for region, unsorted_mirrors in sorted(sorting_placeholder.items(), key=lambda item: item[0]) 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 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() lines = mirrorlist.splitlines()
# remove empty lines # remove empty lines
lines = [line for line in lines if line] lines = [line for line in lines if line]
mirror_list: Dict[str, List[MirrorStatusEntryV3]] = {} mirror_list: Dict[str, list[MirrorStatusEntryV3]] = {}
current_region = '' current_region = ''
for idx, line in enumerate(lines): for idx, line in enumerate(lines):

View File

@ -2,7 +2,6 @@ from __future__ import annotations
import sys import sys
from enum import Enum from enum import Enum
from typing import List
from ..hardware import SysInfo from ..hardware import SysInfo
from ..output import warn from ..output import warn
@ -25,7 +24,7 @@ class Bootloader(Enum):
return self.value return self.value
@staticmethod @staticmethod
def values() -> List[str]: def values() -> list[str]:
return [e.value for e in Bootloader] return [e.value for e in Bootloader]
@classmethod @classmethod

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional, List, Dict, Any from typing import Optional, Dict, Any
@dataclass @dataclass
@ -7,7 +7,7 @@ class VersionDef:
version_string: str version_string: str
@classmethod @classmethod
def parse_version(cls) -> List[str]: def parse_version(cls) -> list[str]:
if '.' in cls.version_string: if '.' in cls.version_string:
versions = cls.version_string.split('.') versions = cls.version_string.split('.')
else: else:
@ -75,17 +75,17 @@ class PackageSearchResult:
build_date: str build_date: str
last_update: str last_update: str
flag_date: Optional[str] flag_date: Optional[str]
maintainers: List[str] maintainers: list[str]
packager: str packager: str
groups: List[str] groups: list[str]
licenses: List[str] licenses: list[str]
conflicts: List[str] conflicts: list[str]
provides: List[str] provides: list[str]
replaces: List[str] replaces: list[str]
depends: List[str] depends: list[str]
optdepends: List[str] optdepends: list[str]
makedepends: List[str] makedepends: list[str]
checkdepends: List[str] checkdepends: list[str]
@staticmethod @staticmethod
def from_json(data: Dict[str, Any]) -> 'PackageSearchResult': def from_json(data: Dict[str, Any]) -> 'PackageSearchResult':
@ -109,7 +109,7 @@ class PackageSearch:
valid: bool valid: bool
num_pages: int num_pages: int
page: int page: int
results: List[PackageSearchResult] results: list[PackageSearchResult]
@staticmethod @staticmethod
def from_json(data: Dict[str, Any]) -> 'PackageSearch': def from_json(data: Dict[str, Any]) -> 'PackageSearch':

View File

@ -6,7 +6,6 @@ import urllib.parse
import urllib.request import urllib.request
from typing import ( from typing import (
Dict, Dict,
List,
Optional Optional
) )
@ -113,15 +112,15 @@ class MirrorStatusListV3(BaseModel):
cutoff: int cutoff: int
last_check: datetime.datetime last_check: datetime.datetime
num_checks: int num_checks: int
urls: List[MirrorStatusEntryV3] urls: list[MirrorStatusEntryV3]
version: int version: int
@model_validator(mode='before') @model_validator(mode='before')
@classmethod @classmethod
def check_model( def check_model(
cls, cls,
data: Dict[str, int | datetime.datetime | List[MirrorStatusEntryV3]] data: Dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]
) -> Dict[str, int | datetime.datetime | List[MirrorStatusEntryV3]]: ) -> Dict[str, int | datetime.datetime | list[MirrorStatusEntryV3]]:
if data.get('version') == 3: if data.get('version') == 3:
return data return data

View File

@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from typing import List, Optional, Dict, Any, TYPE_CHECKING, Tuple from typing import Optional, Dict, Any, TYPE_CHECKING, Tuple
from ..profile import ProfileConfiguration from ..profile import ProfileConfiguration
@ -31,7 +31,7 @@ class Nic:
ip: Optional[str] = None ip: Optional[str] = None
dhcp: bool = True dhcp: bool = True
gateway: Optional[str] = None gateway: Optional[str] = None
dns: List[str] = field(default_factory=list) dns: list[str] = field(default_factory=list)
def table_data(self) -> Dict[str, Any]: def table_data(self) -> Dict[str, Any]:
return { return {
@ -62,8 +62,8 @@ class Nic:
) )
def as_systemd_config(self) -> str: def as_systemd_config(self) -> str:
match: List[Tuple[str, str]] = [] match: list[Tuple[str, str]] = []
network: List[Tuple[str, str]] = [] network: list[Tuple[str, str]] = []
if self.iface: if self.iface:
match.append(('Name', self.iface)) match.append(('Name', self.iface))
@ -92,7 +92,7 @@ class Nic:
@dataclass @dataclass
class NetworkConfiguration: class NetworkConfiguration:
type: NicType type: NicType
nics: List[Nic] = field(default_factory=list) nics: list[Nic] = field(default_factory=list)
def json(self) -> Dict[str, Any]: def json(self) -> Dict[str, Any]:
config: Dict[str, Any] = {'type': self.type.value} config: Dict[str, Any] = {'type': self.type.value}

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import Dict, List, Union, Any, TYPE_CHECKING from typing import Dict, Union, Any, TYPE_CHECKING
from enum import Enum from enum import Enum
if TYPE_CHECKING: if TYPE_CHECKING:
@ -97,7 +97,7 @@ class User:
sudo: bool sudo: bool
@property @property
def groups(self) -> List[str]: def groups(self) -> list[str]:
# this property should be transferred into a class attr instead # this property should be transferred into a class attr instead
# if it's every going to be used # if it's every going to be used
return [] return []
@ -110,7 +110,7 @@ class User:
} }
@classmethod @classmethod
def _parse(cls, config_users: List[Dict[str, Any]]) -> List['User']: def _parse(cls, config_users: list[Dict[str, Any]]) -> list['User']:
users = [] users = []
for entry in config_users: for entry in config_users:
@ -127,7 +127,7 @@ class User:
return users return users
@classmethod @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: if len(config_users.keys()) > 0:
username = list(config_users.keys())[0] username = list(config_users.keys())[0]
password = config_users[username]['!password'] password = config_users[username]['!password']
@ -140,9 +140,9 @@ class User:
@classmethod @classmethod
def parse_arguments( def parse_arguments(
cls, cls,
config_users: 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]] config_superusers: Union[list[Dict[str, str]], Dict[str, str]]
) -> List['User']: ) -> list['User']:
users = [] users = []
# backwards compatibility # backwards compatibility

View File

@ -5,7 +5,7 @@ import unicodedata
from enum import Enum from enum import Enum
from pathlib import Path from pathlib import Path
from typing import Dict, Union, List, Any, Callable, Optional, TYPE_CHECKING from typing import Dict, Union, Any, Callable, Optional, TYPE_CHECKING
from dataclasses import asdict, is_dataclass from dataclasses import asdict, is_dataclass
from .storage import storage from .storage import storage
@ -21,7 +21,7 @@ class FormattedOutput:
cls, cls,
o: 'DataclassInstance', o: 'DataclassInstance',
class_formatter: Optional[Union[str, Callable]] = None, class_formatter: Optional[Union[str, Callable]] = None,
filter_list: List[str] = [] 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 the original values returned a dataclass as dict thru the call to some specific methods
@ -51,9 +51,9 @@ class FormattedOutput:
@classmethod @classmethod
def as_table( def as_table(
cls, cls,
obj: List[Any], obj: list[Any],
class_formatter: Optional[Union[str, Callable]] = None, class_formatter: Optional[Union[str, Callable]] = None,
filter_list: List[str] = [], filter_list: list[str] = [],
capitalize: bool = False capitalize: bool = False
) -> str: ) -> str:
""" variant of as_table (subtly different code) which has two additional parameters """ variant of as_table (subtly different code) which has two additional parameters
@ -112,7 +112,7 @@ class FormattedOutput:
return output return output
@classmethod @classmethod
def as_columns(cls, entries: List[str], cols: int) -> str: def as_columns(cls, entries: list[str], cols: int) -> str:
""" """
Will format a list into a given number of columns Will format a list into a given number of columns
""" """
@ -204,7 +204,7 @@ def _stylize_output(
fg: str, fg: str,
bg: Optional[str], bg: Optional[str],
reset: bool, reset: bool,
font: List[Font] = [], font: list[Font] = [],
) -> str: ) -> str:
""" """
Heavily influenced by: Heavily influenced by:
@ -258,7 +258,7 @@ def info(
fg: str = 'white', fg: str = 'white',
bg: Optional[str] = None, bg: Optional[str] = None,
reset: bool = False, reset: bool = False,
font: List[Font] = [] font: list[Font] = []
) -> None: ) -> None:
log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font)
@ -269,7 +269,7 @@ def debug(
fg: str = 'white', fg: str = 'white',
bg: Optional[str] = None, bg: Optional[str] = None,
reset: bool = False, reset: bool = False,
font: List[Font] = [] font: list[Font] = []
) -> None: ) -> None:
log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font)
@ -280,7 +280,7 @@ def error(
fg: str = 'red', fg: str = 'red',
bg: Optional[str] = None, bg: Optional[str] = None,
reset: bool = False, reset: bool = False,
font: List[Font] = [] font: list[Font] = []
) -> None: ) -> None:
log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font)
@ -291,7 +291,7 @@ def warn(
fg: str = 'yellow', fg: str = 'yellow',
bg: Optional[str] = None, bg: Optional[str] = None,
reset: bool = False, reset: bool = False,
font: List[Font] = [] font: list[Font] = []
) -> None: ) -> None:
log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font)
@ -302,7 +302,7 @@ def log(
fg: str = 'white', fg: str = 'white',
bg: Optional[str] = None, bg: Optional[str] = None,
reset: bool = False, reset: bool = False,
font: List[Font] = [] font: list[Font] = []
) -> None: ) -> None:
# leave this check here as we need to setup the logging # leave this check here as we need to setup the logging
# right from the beginning when the modules are loaded # right from the beginning when the modules are loaded

View File

@ -1,7 +1,7 @@
import dataclasses import dataclasses
import json import json
import ssl import ssl
from typing import Dict, Any, Tuple, List from typing import Dict, Any, Tuple
from urllib.error import HTTPError from urllib.error import HTTPError
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.request import urlopen from urllib.request import urlopen
@ -26,7 +26,7 @@ def _make_request(url: str, params: Dict) -> Any:
return urlopen(full_url, context=ssl_context) return urlopen(full_url, context=ssl_context)
def group_search(name: str) -> List[PackageSearchResult]: def group_search(name: str) -> list[PackageSearchResult]:
# TODO UPSTREAM: Implement /json/ for the groups search # TODO UPSTREAM: Implement /json/ for the groups search
try: try:
response = _make_request(BASE_GROUP_URL, {'name': name}) response = _make_request(BASE_GROUP_URL, {'name': name})
@ -59,7 +59,7 @@ def package_search(package: str) -> PackageSearch:
return PackageSearch.from_json(json_data) return PackageSearch.from_json(json_data)
def find_package(package: str) -> List[PackageSearchResult]: def find_package(package: str) -> list[PackageSearchResult]:
data = package_search(package) data = package_search(package)
results = [] results = []

View File

@ -1,7 +1,6 @@
import re import re
from pathlib import Path from pathlib import Path
from shutil import copy2 from shutil import copy2
from typing import List
from .repo import Repo from .repo import Repo
@ -10,7 +9,7 @@ class Config:
def __init__(self, target: Path): def __init__(self, target: Path):
self.path = Path("/etc") / "pacman.conf" self.path = Path("/etc") / "pacman.conf"
self.chroot_path = target / "etc" / "pacman.conf" self.chroot_path = target / "etc" / "pacman.conf"
self.repos: List[Repo] = [] self.repos: list[Repo] = []
def enable(self, repo: Repo) -> None: def enable(self, repo: Repo) -> None:
self.repos.append(repo) self.repos.append(repo)

View File

@ -6,7 +6,7 @@ import urllib.parse
import urllib.request import urllib.request
from importlib import metadata from importlib import metadata
from pathlib import Path from pathlib import Path
from typing import Optional, List from typing import Optional
from .output import error, info, warn from .output import error, info, warn
from .storage import storage from .storage import storage
@ -75,7 +75,7 @@ def _import_via_path(path: Path, namespace: Optional[str] = None) -> Optional[st
return namespace return namespace
def _find_nth(haystack: List[str], needle: str, n: int) -> Optional[int]: def _find_nth(haystack: list[str], needle: str, n: int) -> Optional[int]:
indices = [idx for idx, elem in enumerate(haystack) if elem == needle] indices = [idx for idx, elem in enumerate(haystack) if elem == needle]
if n <= len(indices): if n <= len(indices):
return indices[n - 1] return indices[n - 1]

View File

@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional, Dict, List from typing import TYPE_CHECKING, Any, Optional, Dict
from archinstall.default_profiles.profile import Profile, GreeterType from archinstall.default_profiles.profile import Profile, GreeterType
from .profile_model import ProfileConfiguration from .profile_model import ProfileConfiguration
@ -35,7 +35,7 @@ class ProfileMenu(AbstractSubMenu):
super().__init__(self._item_group, data_store=self._data_store, allow_reset=True) super().__init__(self._item_group, data_store=self._data_store, allow_reset=True)
def _define_menu_options(self) -> List[MenuItem]: def _define_menu_options(self) -> list[MenuItem]:
return [ return [
MenuItem( MenuItem(
text=str(_('Type')), text=str(_('Type')),

View File

@ -8,7 +8,7 @@ from functools import cached_property
from pathlib import Path from pathlib import Path
from tempfile import NamedTemporaryFile from tempfile import NamedTemporaryFile
from types import ModuleType from types import ModuleType
from typing import List, TYPE_CHECKING, Any, Optional, Dict, Union from typing import TYPE_CHECKING, Any, Optional, Dict, Union
from ...default_profiles.profile import Profile, GreeterType from ...default_profiles.profile import Profile, GreeterType
from .profile_model import ProfileConfiguration from .profile_model import ProfileConfiguration
@ -101,9 +101,9 @@ class ProfileHandler:
if not profile: if not profile:
return None return None
valid_sub_profiles: List[Profile] = [] valid_sub_profiles: list[Profile] = []
invalid_sub_profiles: List[str] = [] invalid_sub_profiles: list[str] = []
details: List[str] = profile_config.get('details', []) details: list[str] = profile_config.get('details', [])
if details: if details:
for detail in filter(None, details): for detail in filter(None, details):
@ -127,7 +127,7 @@ class ProfileHandler:
return profile return profile
@property @property
def profiles(self) -> List[Profile]: def profiles(self) -> list[Profile]:
""" """
List of all available default_profiles List of all available default_profiles
""" """
@ -135,10 +135,10 @@ class ProfileHandler:
return self._profiles return self._profiles
@cached_property @cached_property
def _local_mac_addresses(self) -> List[str]: def _local_mac_addresses(self) -> list[str]:
return list(list_interfaces()) return list(list_interfaces())
def add_custom_profiles(self, profiles: Union[Profile, List[Profile]]) -> None: def add_custom_profiles(self, profiles: Union[Profile, list[Profile]]) -> None:
if not isinstance(profiles, list): if not isinstance(profiles, list):
profiles = [profiles] profiles = [profiles]
@ -147,7 +147,7 @@ class ProfileHandler:
self._verify_unique_profile_names(self.profiles) self._verify_unique_profile_names(self.profiles)
def remove_custom_profiles(self, profiles: Union[Profile, List[Profile]]) -> None: def remove_custom_profiles(self, profiles: Union[Profile, list[Profile]]) -> None:
if not isinstance(profiles, list): if not isinstance(profiles, list):
profiles = [profiles] profiles = [profiles]
@ -157,19 +157,19 @@ class ProfileHandler:
def get_profile_by_name(self, name: str) -> Optional[Profile]: def get_profile_by_name(self, name: str) -> Optional[Profile]:
return next(filter(lambda x: x.name == name, self.profiles), None) # type: ignore return next(filter(lambda x: x.name == name, self.profiles), None) # type: ignore
def get_top_level_profiles(self) -> List[Profile]: def get_top_level_profiles(self) -> list[Profile]:
return list(filter(lambda x: x.is_top_level_profile(), self.profiles)) return list(filter(lambda x: x.is_top_level_profile(), self.profiles))
def get_server_profiles(self) -> List[Profile]: def get_server_profiles(self) -> list[Profile]:
return list(filter(lambda x: x.is_server_type_profile(), self.profiles)) return list(filter(lambda x: x.is_server_type_profile(), self.profiles))
def get_desktop_profiles(self) -> List[Profile]: def get_desktop_profiles(self) -> list[Profile]:
return list(filter(lambda x: x.is_desktop_type_profile(), self.profiles)) return list(filter(lambda x: x.is_desktop_type_profile(), self.profiles))
def get_custom_profiles(self) -> List[Profile]: def get_custom_profiles(self) -> list[Profile]:
return list(filter(lambda x: x.is_custom_type_profile(), self.profiles)) return list(filter(lambda x: x.is_custom_type_profile(), self.profiles))
def get_mac_addr_profiles(self) -> List[Profile]: def get_mac_addr_profiles(self) -> list[Profile]:
tailored = list(filter(lambda x: x.is_tailored(), self.profiles)) tailored = list(filter(lambda x: x.is_tailored(), self.profiles))
match_mac_addr_profiles = list(filter(lambda x: x.name in self._local_mac_addresses, tailored)) match_mac_addr_profiles = list(filter(lambda x: x.name in self._local_mac_addresses, tailored))
return match_mac_addr_profiles return match_mac_addr_profiles
@ -265,7 +265,7 @@ class ProfileHandler:
err = str(_('Unable to fetch profile from specified url: {}')).format(url) err = str(_('Unable to fetch profile from specified url: {}')).format(url)
error(err) error(err)
def _load_profile_class(self, module: ModuleType) -> List[Profile]: def _load_profile_class(self, module: ModuleType) -> list[Profile]:
""" """
Load all default_profiles defined in a module Load all default_profiles defined in a module
""" """
@ -284,7 +284,7 @@ class ProfileHandler:
return profiles return profiles
def _verify_unique_profile_names(self, profiles: List[Profile]): def _verify_unique_profile_names(self, profiles: list[Profile]):
""" """
All profile names have to be unique, this function will verify All profile names have to be unique, this function will verify
that the provided list contains only default_profiles with unique names that the provided list contains only default_profiles with unique names
@ -308,7 +308,7 @@ class ProfileHandler:
return True return True
return False return False
def _process_profile_file(self, file: Path) -> List[Profile]: def _process_profile_file(self, file: Path) -> list[Profile]:
""" """
Process a file for profile definitions Process a file for profile definitions
""" """
@ -334,7 +334,7 @@ class ProfileHandler:
return [] return []
def _find_available_profiles(self) -> List[Profile]: def _find_available_profiles(self) -> list[Profile]:
""" """
Search the profile path for profile definitions Search the profile path for profile definitions
""" """
@ -348,7 +348,7 @@ class ProfileHandler:
self._verify_unique_profile_names(profiles) self._verify_unique_profile_names(profiles)
return profiles return profiles
def reset_top_level_profiles(self, exclude: List[Profile] = []): def reset_top_level_profiles(self, exclude: list[Profile] = []):
""" """
Reset all top level profile configurations, this is usually necessary Reset all top level profile configurations, this is usually necessary
when a new top level profile is selected when a new top level profile is selected

View File

@ -1,5 +1,5 @@
from pathlib import Path from pathlib import Path
from typing import Any, TYPE_CHECKING, Optional, List from typing import Any, TYPE_CHECKING, Optional
from ..output import FormattedOutput from ..output import FormattedOutput
from ..general import secret from ..general import secret
@ -107,7 +107,7 @@ def is_subpath(first: Path, second: Path) -> bool:
return False return False
def format_cols(items: List[str], header: Optional[str] = None) -> str: def format_cols(items: list[str], header: Optional[str] = None) -> str:
if header: if header:
text = f'{header}:\n' text = f'{header}:\n'
else: else:

View File

@ -1,5 +1,5 @@
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, Any, List from typing import TYPE_CHECKING, Any
import archinstall import archinstall
from archinstall import info, debug from archinstall import info, debug
@ -75,8 +75,8 @@ def prompt_disk_layout() -> None:
def parse_disk_encryption() -> None: def parse_disk_encryption() -> None:
if enc_password := archinstall.arguments.get('!encryption-password', None): if enc_password := archinstall.arguments.get('!encryption-password', None):
modification: List[disk.DeviceModification] = archinstall.arguments['disk_config'] modification: list[disk.DeviceModification] = archinstall.arguments['disk_config']
partitions: List[disk.PartitionModification] = [] partitions: list[disk.PartitionModification] = []
# encrypt all partitions except the /boot # encrypt all partitions except the /boot
for mod in modification: for mod in modification:

View File

@ -7,7 +7,7 @@ import signal
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
from curses.textpad import Textbox from curses.textpad import Textbox
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any, Optional, Tuple, List, TYPE_CHECKING, Literal from typing import Any, Optional, Tuple, TYPE_CHECKING, Literal
from typing import Callable from typing import Callable
from .help import Help from .help import Help
@ -94,7 +94,7 @@ class AbstractCurses(metaclass=ABCMeta):
self, self,
header: Optional[str], header: Optional[str],
offset: int = 0 offset: int = 0
) -> List[ViewportEntry]: ) -> list[ViewportEntry]:
cur_row = 0 cur_row = 0
full_header = [] full_header = []
@ -120,12 +120,12 @@ class AbstractViewport:
def add_frame( def add_frame(
self, self,
entries: List[ViewportEntry], entries: list[ViewportEntry],
max_width: int, max_width: int,
max_height: int, max_height: int,
frame: FrameProperties, frame: FrameProperties,
scroll_pct: Optional[int] = None scroll_pct: Optional[int] = None
) -> List[ViewportEntry]: ) -> list[ViewportEntry]:
if not entries: if not entries:
return [] return []
@ -155,7 +155,7 @@ class AbstractViewport:
return framed_entries return framed_entries
def align_center(self, lines: List[ViewportEntry], width: int) -> int: def align_center(self, lines: list[ViewportEntry], width: int) -> int:
max_col = self._max_col(lines) max_col = self._max_col(lines)
x_offset = int((width / 2) - (max_col / 2)) x_offset = int((width / 2) - (max_col / 2))
return x_offset return x_offset
@ -164,7 +164,7 @@ class AbstractViewport:
self, self,
dim: _FrameDim, dim: _FrameDim,
scroll_percentage: Optional[int] = None scroll_percentage: Optional[int] = None
) -> List[ViewportEntry]: ) -> list[ViewportEntry]:
right_frame = {} right_frame = {}
scroll_height = int(dim.height * scroll_percentage // 100) if scroll_percentage else 0 scroll_height = int(dim.height * scroll_percentage // 100) if scroll_percentage else 0
@ -214,7 +214,7 @@ class AbstractViewport:
def _get_frame_dim( def _get_frame_dim(
self, self,
entries: List[ViewportEntry], entries: list[ViewportEntry],
max_width: int, max_width: int,
max_height: int, max_height: int,
frame: FrameProperties frame: FrameProperties
@ -245,9 +245,9 @@ class AbstractViewport:
def _adjust_entries( def _adjust_entries(
self, self,
entries: List[ViewportEntry], entries: list[ViewportEntry],
frame_dim: _FrameDim frame_dim: _FrameDim
) -> List[ViewportEntry]: ) -> list[ViewportEntry]:
for entry in entries: for entry in entries:
# top row frame offset # top row frame offset
entry.row += 1 entry.row += 1
@ -256,10 +256,10 @@ class AbstractViewport:
return entries return entries
def _num_unique_rows(self, entries: List[ViewportEntry]) -> int: def _num_unique_rows(self, entries: list[ViewportEntry]) -> int:
return len(set([e.row for e in entries])) return len(set([e.row for e in entries]))
def _max_col(self, entries: List[ViewportEntry]) -> int: def _max_col(self, entries: list[ViewportEntry]) -> int:
values = [len(e.text) + e.col for e in entries] values = [len(e.text) + e.col for e in entries]
if not values: if not values:
return 0 return 0
@ -269,7 +269,7 @@ class AbstractViewport:
len_replace = len(replacement) len_replace = len(replacement)
return f'{text[:index]}{replacement}{text[index + len_replace:]}' return f'{text[:index]}{replacement}{text[index + len_replace:]}'
def _assemble_entries(self, entries: List[ViewportEntry]) -> str: def _assemble_entries(self, entries: list[ViewportEntry]) -> str:
if not entries: if not entries:
return '' return ''
@ -385,7 +385,7 @@ class EditViewport(AbstractViewport):
@dataclass @dataclass
class ViewportState: class ViewportState:
cur_pos: int cur_pos: int
displayed_entries: List[ViewportEntry] displayed_entries: list[ViewportEntry]
scroll_pct: Optional[int] scroll_pct: Optional[int]
scroll_pos: Optional[int] = 0 scroll_pos: Optional[int] = 0
@ -436,7 +436,7 @@ class Viewport(AbstractViewport):
def update( def update(
self, self,
lines: List[ViewportEntry], lines: list[ViewportEntry],
cur_pos: int = 0, cur_pos: int = 0,
scroll_pos: Optional[int] = None scroll_pos: Optional[int] = None
): ):
@ -490,7 +490,7 @@ class Viewport(AbstractViewport):
def _get_viewport_state( def _get_viewport_state(
self, self,
entries: List[ViewportEntry], entries: list[ViewportEntry],
cur_pos: int, cur_pos: int,
scroll_pos: Optional[int] = 0 scroll_pos: Optional[int] = 0
) -> ViewportState: ) -> ViewportState:
@ -535,7 +535,7 @@ class Viewport(AbstractViewport):
def _get_visible_entries( def _get_visible_entries(
self, self,
entries: List[ViewportEntry], entries: list[ViewportEntry],
cur_pos: int, cur_pos: int,
screen_rows: int, screen_rows: int,
scroll_pos: Optional[int], scroll_pos: Optional[int],
@ -570,7 +570,7 @@ class Viewport(AbstractViewport):
return [entry for entry in entries if start <= entry.row < end] return [entry for entry in entries if start <= entry.row < end]
def _adjust_entries_row(self, entries: List[ViewportEntry]) -> List[ViewportEntry]: def _adjust_entries_row(self, entries: list[ViewportEntry]) -> list[ViewportEntry]:
assert self._state is not None assert self._state is not None
modified = [] modified = []
@ -585,7 +585,7 @@ class Viewport(AbstractViewport):
len_replace = len(replacement) len_replace = len(replacement)
return f'{text[:index]}{replacement}{text[index + len_replace:]}' return f'{text[:index]}{replacement}{text[index + len_replace:]}'
def _unique_rows(self, entries: List[ViewportEntry]) -> int: def _unique_rows(self, entries: list[ViewportEntry]) -> int:
return len(set([e.row for e in entries])) return len(set([e.row for e in entries]))
@ -847,11 +847,11 @@ class SelectMenu(AbstractCurses):
else: else:
self._horizontal_cols = 1 self._horizontal_cols = 1
self._row_entries: List[List[MenuCell]] = [] self._row_entries: list[list[MenuCell]] = []
self._prev_scroll_pos: int = 0 self._prev_scroll_pos: int = 0
self._cur_pos: Optional[int] = None self._cur_pos: Optional[int] = None
self._visible_entries: List[ViewportEntry] = [] self._visible_entries: list[ViewportEntry] = []
self._max_height, self._max_width = Tui.t().max_yx self._max_height, self._max_width = Tui.t().max_yx
self._help_vp: Optional[Viewport] = None self._help_vp: Optional[Viewport] = None
@ -911,7 +911,7 @@ class SelectMenu(AbstractCurses):
if self._help_vp: if self._help_vp:
self._help_vp.erase() self._help_vp.erase()
def _footer_entries(self) -> List[ViewportEntry]: def _footer_entries(self) -> list[ViewportEntry]:
if self._active_search: if self._active_search:
filter_pattern = self._item_group.filter_pattern filter_pattern = self._item_group.filter_pattern
return [ViewportEntry(f'/{filter_pattern}', 0, 0, STYLE.NORMAL)] return [ViewportEntry(f'/{filter_pattern}', 0, 0, STYLE.NORMAL)]
@ -1078,7 +1078,7 @@ class SelectMenu(AbstractCurses):
def _update_viewport( def _update_viewport(
self, self,
viewport: Viewport, viewport: Viewport,
entries: List[ViewportEntry], entries: list[ViewportEntry],
cur_pos: int = 0 cur_pos: int = 0
) -> None: ) -> None:
if entries: if entries:
@ -1093,13 +1093,13 @@ class SelectMenu(AbstractCurses):
return idx return idx
return 0 return 0
def _get_visible_items(self) -> List[MenuItem]: def _get_visible_items(self) -> list[MenuItem]:
return [it for it in self._item_group.items if self._item_group.should_enable_item(it)] return [it for it in self._item_group.items if self._item_group.should_enable_item(it)]
def _list_to_cols(self, items: List[MenuItem], cols: int) -> List[List[MenuItem]]: def _list_to_cols(self, items: list[MenuItem], cols: int) -> list[list[MenuItem]]:
return [items[i:i + cols] for i in range(0, len(items), cols)] return [items[i:i + cols] for i in range(0, len(items), cols)]
def _get_col_widths(self) -> List[int]: def _get_col_widths(self) -> list[int]:
cols_widths = self._calc_col_widths(self._row_entries, self._horizontal_cols) cols_widths = self._calc_col_widths(self._row_entries, self._horizontal_cols)
return [col_width + len(self._cursor_char) + self._item_distance() for col_width in cols_widths] return [col_width + len(self._cursor_char) + self._item_distance() for col_width in cols_widths]
@ -1109,7 +1109,7 @@ class SelectMenu(AbstractCurses):
else: else:
return self._column_spacing return self._column_spacing
def _get_row_entries(self) -> List[ViewportEntry]: def _get_row_entries(self) -> list[ViewportEntry]:
cells = self._assemble_menu_cells() cells = self._assemble_menu_cells()
entries = [] entries = []
@ -1141,9 +1141,9 @@ class SelectMenu(AbstractCurses):
def _calc_col_widths( def _calc_col_widths(
self, self,
row_chunks: List[List[MenuCell]], row_chunks: list[list[MenuCell]],
cols: int cols: int
) -> List[int]: ) -> list[int]:
col_widths = [] col_widths = []
for col in range(cols): for col in range(cols):
col_entries = [] col_entries = []
@ -1156,7 +1156,7 @@ class SelectMenu(AbstractCurses):
return col_widths return col_widths
def _assemble_menu_cells(self) -> List[MenuCell]: def _assemble_menu_cells(self) -> list[MenuCell]:
items = self._get_visible_items() items = self._get_visible_items()
entries = [] entries = []
@ -1195,7 +1195,7 @@ class SelectMenu(AbstractCurses):
self._preview_vp.update(entries, scroll_pos=self._prev_scroll_pos) self._preview_vp.update(entries, scroll_pos=self._prev_scroll_pos)
def _calc_prev_scroll_pos(self, entries: List[ViewportEntry]): def _calc_prev_scroll_pos(self, entries: list[ViewportEntry]):
total_rows = max([e.row for e in entries]) + 1 # rows start with 0 and we need the count total_rows = max([e.row for e in entries]) + 1 # rows start with 0 and we need the count
if self._prev_scroll_pos >= total_rows: if self._prev_scroll_pos >= total_rows:

View File

@ -1,6 +1,5 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from enum import Enum from enum import Enum
from typing import List
class HelpTextGroupId(Enum): class HelpTextGroupId(Enum):
@ -13,13 +12,13 @@ class HelpTextGroupId(Enum):
@dataclass @dataclass
class HelpText: class HelpText:
description: str description: str
keys: List[str] = field(default_factory=list) keys: list[str] = field(default_factory=list)
@dataclass @dataclass
class HelpGroup: class HelpGroup:
group_id: HelpTextGroupId group_id: HelpTextGroupId
group_entries: List[HelpText] group_entries: list[HelpText]
def get_desc_width(self) -> int: def get_desc_width(self) -> int:
return max([len(e.description) for e in self.group_entries]) return max([len(e.description) for e in self.group_entries])

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Any, Optional, List, TYPE_CHECKING from typing import Any, Optional, TYPE_CHECKING
from typing import Callable, ClassVar from typing import Callable, ClassVar
from ..lib.output import unicode_ljust from ..lib.output import unicode_ljust
@ -15,8 +15,8 @@ class MenuItem:
action: Optional[Callable[[Any], Any]] = None action: Optional[Callable[[Any], Any]] = None
enabled: bool = True enabled: bool = True
mandatory: bool = False mandatory: bool = False
dependencies: List[str | Callable[[], bool]] = field(default_factory=list) dependencies: list[str | Callable[[], bool]] = field(default_factory=list)
dependencies_not: List[str] = field(default_factory=list) dependencies_not: list[str] = field(default_factory=list)
display_action: Optional[Callable[[Any], str]] = None display_action: Optional[Callable[[Any], str]] = None
preview_action: Optional[Callable[[Any], Optional[str]]] = None preview_action: Optional[Callable[[Any], Optional[str]]] = None
key: Optional[str] = None key: Optional[str] = None
@ -64,10 +64,10 @@ class MenuItem:
@dataclass @dataclass
class MenuItemGroup: class MenuItemGroup:
menu_items: List[MenuItem] menu_items: list[MenuItem]
focus_item: Optional[MenuItem] = None focus_item: Optional[MenuItem] = None
default_item: Optional[MenuItem] = None default_item: Optional[MenuItem] = None
selected_items: List[MenuItem] = field(default_factory=list) selected_items: list[MenuItem] = field(default_factory=list)
sort_items: bool = False sort_items: bool = False
checkmarks: bool = False checkmarks: bool = False
@ -119,7 +119,7 @@ class MenuItemGroup:
self.default_item = item self.default_item = item
break break
def set_selected_by_value(self, values: Optional[Any | List[Any]]) -> None: def set_selected_by_value(self, values: Optional[Any | list[Any]]) -> None:
if values is None: if values is None:
return return
@ -194,7 +194,7 @@ class MenuItemGroup:
return '' return ''
@property @property
def items(self) -> List[MenuItem]: def items(self) -> list[MenuItem]:
f = self._filter_pattern.lower() f = self._filter_pattern.lower()
items = filter(lambda item: item.is_empty() or f in item.text.lower(), self.menu_items) items = filter(lambda item: item.is_empty() or f in item.text.lower(), self.menu_items)
return list(items) return list(items)
@ -246,7 +246,7 @@ class MenuItemGroup:
else: else:
return item == self.focus_item return item == self.focus_item
def _first(self, items: List[MenuItem], ignore_empty: bool) -> Optional[MenuItem]: def _first(self, items: list[MenuItem], ignore_empty: bool) -> Optional[MenuItem]:
for item in items: for item in items:
if not ignore_empty: if not ignore_empty:
return item return item

View File

@ -1,7 +1,7 @@
import curses import curses
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum, auto from enum import Enum, auto
from typing import Optional, List, Any from typing import Optional, Any
from .menu_item import MenuItem from .menu_item import MenuItem
@ -52,7 +52,7 @@ class MenuKeys(Enum):
SCROLL_DOWN = {540} SCROLL_DOWN = {540}
@classmethod @classmethod
def from_ord(cls, key: int) -> List['MenuKeys']: def from_ord(cls, key: int) -> list['MenuKeys']:
matches = [] matches = []
for group in MenuKeys: for group in MenuKeys:
@ -139,7 +139,7 @@ class Chars:
@dataclass @dataclass
class Result: class Result:
type_: ResultType type_: ResultType
_item: Optional[MenuItem | List[MenuItem] | str] _item: Optional[MenuItem | list[MenuItem] | str]
def has_item(self) -> bool: def has_item(self) -> bool:
return self._item is not None return self._item is not None
@ -147,14 +147,14 @@ class Result:
def get_value(self) -> Any: def get_value(self) -> Any:
return self.item().get_value() return self.item().get_value()
def get_values(self) -> List[Any]: def get_values(self) -> list[Any]:
return [i.get_value() for i in self.items()] return [i.get_value() for i in self.items()]
def item(self) -> MenuItem: def item(self) -> MenuItem:
assert self._item is not None and isinstance(self._item, MenuItem) assert self._item is not None and isinstance(self._item, MenuItem)
return self._item return self._item
def items(self) -> List[MenuItem]: def items(self) -> list[MenuItem]:
assert self._item is not None and isinstance(self._item, list) assert self._item is not None and isinstance(self._item, list)
return self._item return self._item

View File

@ -1,5 +1,4 @@
from pathlib import Path from pathlib import Path
from typing import List
import archinstall import archinstall
from archinstall import info, debug from archinstall import info, debug
@ -72,8 +71,8 @@ def prompt_disk_layout() -> None:
def parse_disk_encryption() -> None: def parse_disk_encryption() -> None:
if enc_password := archinstall.arguments.get('!encryption-password', None): if enc_password := archinstall.arguments.get('!encryption-password', None):
modification: List[disk.DeviceModification] = archinstall.arguments['disk_config'] modification: list[disk.DeviceModification] = archinstall.arguments['disk_config']
partitions: List[disk.PartitionModification] = [] partitions: list[disk.PartitionModification] = []
# encrypt all partitions except the /boot # encrypt all partitions except the /boot
for mod in modification: for mod in modification: