Start replacing Optional with union syntax in lib/ (#2837)

This commit is contained in:
correctmost 2024-11-16 17:03:01 -05:00 committed by GitHub
parent 8cda091e6d
commit 25172bd0f8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 111 additions and 113 deletions

View File

@ -3,7 +3,7 @@ import json
import stat
import readline
from pathlib import Path
from typing import Optional, Any, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from .storage import storage
from .general import JSON, UNSAFE_JSON
@ -69,7 +69,7 @@ class ConfigurationOutput:
'version': storage['__version__']
}, indent=4, sort_keys=True, cls=JSON)
def user_credentials_to_json(self) -> Optional[str]:
def user_credentials_to_json(self) -> str | None:
if self._user_credentials:
return json.dumps(self._user_credentials, indent=4, sort_keys=True, cls=UNSAFE_JSON)
return None
@ -126,7 +126,7 @@ class ConfigurationOutput:
target.write_text(user_creds)
os.chmod(target, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP)
def save(self, dest_path: Optional[Path] = None) -> None:
def save(self, dest_path: Path | None = None) -> None:
dest_path = dest_path or self._default_save_path
if self._is_valid_path(dest_path):
@ -135,7 +135,7 @@ class ConfigurationOutput:
def save_config(config: dict[str, Any]) -> None:
def preview(item: MenuItem) -> Optional[str]:
def preview(item: MenuItem) -> str | None:
match item.value:
case "user_config":
serialized = config_output.user_config_to_json()

View File

@ -1,4 +1,4 @@
from typing import Optional, Any, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from . import DiskLayoutConfiguration, DiskLayoutType
from .device_model import LvmConfiguration
@ -21,7 +21,7 @@ if TYPE_CHECKING:
class DiskLayoutConfigurationMenu(AbstractSubMenu):
def __init__(
self,
disk_layout_config: Optional[DiskLayoutConfiguration],
disk_layout_config: DiskLayoutConfiguration | None,
advanced: bool = False
):
self._disk_layout_config = disk_layout_config
@ -52,10 +52,10 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
),
]
def run(self) -> Optional[DiskLayoutConfiguration]:
def run(self) -> DiskLayoutConfiguration | None:
super().run()
disk_layout_config: Optional[DiskLayoutConfiguration] = self._data_store.get('disk_config', None)
disk_layout_config: DiskLayoutConfiguration | None = self._data_store.get('disk_config', None)
if disk_layout_config:
disk_layout_config.lvm_config = self._data_store.get('lvm_config', None)
@ -63,7 +63,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
return disk_layout_config
def _check_dep_lvm(self) -> bool:
disk_layout_conf: Optional[DiskLayoutConfiguration] = self._menu_item_group.find_by_key('disk_config').value
disk_layout_conf: DiskLayoutConfiguration | None = self._menu_item_group.find_by_key('disk_config').value
if disk_layout_conf and disk_layout_conf.config_type == DiskLayoutType.Default:
return True
@ -72,8 +72,8 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
def _select_disk_layout_config(
self,
preset: Optional[DiskLayoutConfiguration]
) -> Optional[DiskLayoutConfiguration]:
preset: DiskLayoutConfiguration | None
) -> DiskLayoutConfiguration | None:
disk_config = select_disk_config(preset, advanced_option=self._advanced)
if disk_config != preset:
@ -81,15 +81,15 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
return disk_config
def _select_lvm_config(self, preset: Optional[LvmConfiguration]) -> Optional[LvmConfiguration]:
disk_config: Optional[DiskLayoutConfiguration] = self._item_group.find_by_key('disk_config').value
def _select_lvm_config(self, preset: LvmConfiguration | None) -> LvmConfiguration | None:
disk_config: DiskLayoutConfiguration | None = self._item_group.find_by_key('disk_config').value
if disk_config:
return select_lvm_config(disk_config, preset=preset)
return preset
def _prev_disk_layouts(self, item: MenuItem) -> Optional[str]:
def _prev_disk_layouts(self, item: MenuItem) -> str | None:
if not item.value:
return None
@ -126,7 +126,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu):
return None
def _prev_lvm_config(self, item: MenuItem) -> Optional[str]:
def _prev_lvm_config(self, item: MenuItem) -> str | None:
if not item.value:
return None

View File

@ -1,5 +1,5 @@
from pathlib import Path
from typing import Optional, Any, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from . import LvmConfiguration, LvmVolume
from ..disk import (
@ -29,7 +29,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
def __init__(
self,
disk_config: DiskLayoutConfiguration,
preset: Optional[DiskEncryption] = None
preset: DiskEncryption | None = None
):
if preset:
self._preset = preset
@ -93,28 +93,28 @@ class DiskEncryptionMenu(AbstractSubMenu):
return []
def _check_dep_enc_type(self) -> bool:
enc_type: Optional[EncryptionType] = self._item_group.find_by_key('encryption_type').value
enc_type: EncryptionType | None = self._item_group.find_by_key('encryption_type').value
if enc_type and enc_type != EncryptionType.NoEncryption:
return True
return False
def _check_dep_partitions(self) -> bool:
enc_type: Optional[EncryptionType] = self._item_group.find_by_key('encryption_type').value
enc_type: EncryptionType | None = self._item_group.find_by_key('encryption_type').value
if enc_type and enc_type in [EncryptionType.Luks, EncryptionType.LvmOnLuks]:
return True
return False
def _check_dep_lvm_vols(self) -> bool:
enc_type: Optional[EncryptionType] = self._item_group.find_by_key('encryption_type').value
enc_type: EncryptionType | None = self._item_group.find_by_key('encryption_type').value
if enc_type and enc_type == EncryptionType.LuksOnLvm:
return True
return False
def run(self) -> Optional[DiskEncryption]:
def run(self) -> DiskEncryption | None:
super().run()
enc_type: Optional[EncryptionType] = self._item_group.find_by_key('encryption_type').value
enc_password: Optional[str] = self._item_group.find_by_key('encryption_password').value
enc_type: EncryptionType | None = self._item_group.find_by_key('encryption_type').value
enc_password: str | None = self._item_group.find_by_key('encryption_password').value
enc_partitions = self._item_group.find_by_key('partitions').value
enc_lvm_vols = self._item_group.find_by_key('lvm_vols').value
@ -139,7 +139,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None
def _preview(self, item: MenuItem) -> Optional[str]:
def _preview(self, item: MenuItem) -> str | None:
output = ''
if (enc_type := self._prev_type()) is not None:
@ -162,7 +162,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return output
def _prev_type(self) -> Optional[str]:
def _prev_type(self) -> str | None:
enc_type = self._item_group.find_by_key('encryption_type').value
if enc_type:
@ -171,7 +171,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None
def _prev_password(self) -> Optional[str]:
def _prev_password(self) -> str | None:
enc_pwd = self._item_group.find_by_key('encryption_password').value
if enc_pwd:
@ -180,8 +180,8 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None
def _prev_partitions(self) -> Optional[str]:
partitions: Optional[list[PartitionModification]] = self._item_group.find_by_key('partitions').value
def _prev_partitions(self) -> str | None:
partitions: list[PartitionModification] | None = self._item_group.find_by_key('partitions').value
if partitions:
output = str(_('Partitions to be encrypted')) + '\n'
@ -190,8 +190,8 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None
def _prev_lvm_vols(self) -> Optional[str]:
volumes: Optional[list[PartitionModification]] = self._item_group.find_by_key('lvm_vols').value
def _prev_lvm_vols(self) -> str | None:
volumes: list[PartitionModification] | None = self._item_group.find_by_key('lvm_vols').value
if volumes:
output = str(_('LVM volumes to be encrypted')) + '\n'
@ -200,8 +200,8 @@ class DiskEncryptionMenu(AbstractSubMenu):
return None
def _prev_hsm(self) -> Optional[str]:
fido_device: Optional[Fido2Device] = self._item_group.find_by_key('HSM').value
def _prev_hsm(self) -> str | None:
fido_device: Fido2Device | None = self._item_group.find_by_key('HSM').value
if not fido_device:
return None
@ -211,7 +211,7 @@ class DiskEncryptionMenu(AbstractSubMenu):
return f'{_("HSM device")}: {output}'
def select_encryption_type(disk_config: DiskLayoutConfiguration, preset: EncryptionType) -> Optional[EncryptionType]:
def select_encryption_type(disk_config: DiskLayoutConfiguration, preset: EncryptionType) -> EncryptionType | None:
options: list[EncryptionType] = []
preset_value = EncryptionType.type_to_text(preset)
@ -239,7 +239,7 @@ def select_encryption_type(disk_config: DiskLayoutConfiguration, preset: Encrypt
return result.get_value()
def select_encrypted_password() -> Optional[str]:
def select_encrypted_password() -> str | None:
header = str(_('Enter disk encryption password (leave blank for no encryption)')) + '\n'
password = get_password(
text=str(_('Disk encryption password')),
@ -250,7 +250,7 @@ def select_encrypted_password() -> Optional[str]:
return password
def select_hsm(preset: Optional[Fido2Device] = None) -> Optional[Fido2Device]:
def select_hsm(preset: Fido2Device | None = None) -> Fido2Device | None:
header = str(_('Select a FIDO2 device to use for HSM'))
try:

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import time
from pathlib import Path
from typing import Any, Optional, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from ..interactions.general_conf import ask_abort
from .device_handler import device_handler
@ -28,7 +28,7 @@ class FilesystemHandler:
def __init__(
self,
disk_config: DiskLayoutConfiguration,
enc_conf: Optional[DiskEncryption] = None
enc_conf: DiskEncryption | None = None
):
self._disk_config = disk_config
self._enc_config = enc_conf

View File

@ -2,7 +2,7 @@ from __future__ import annotations
import re
from pathlib import Path
from typing import Any, TYPE_CHECKING, Optional
from typing import Any, TYPE_CHECKING
from dataclasses import dataclass
from ..utils.util import prompt_dir
@ -93,7 +93,7 @@ class PartitioningList(ListManager):
def handle_action(
self,
action: str,
entry: Optional[PartitionModification],
entry: PartitionModification | None,
data: list[PartitionModification]
) -> list[PartitionModification]:
action_key = [k for k, v in self._actions.items() if v == action][0]
@ -208,7 +208,7 @@ class PartitioningList(ListManager):
return mountpoint
def _prompt_partition_fs_type(self, prompt: Optional[str] = None) -> FilesystemType:
def _prompt_partition_fs_type(self, prompt: str | None = None) -> FilesystemType:
fs_types = filter(lambda fs: fs != FilesystemType.Crypto_luks, FilesystemType)
items = [MenuItem(fs.value, value=fs) for fs in fs_types]
group = MenuItemGroup(items, sort_items=False)
@ -232,8 +232,8 @@ class PartitioningList(ListManager):
sector_size: SectorSize,
total_size: Size,
text: str,
start: Optional[Size]
) -> Optional[Size]:
start: Size | None
) -> Size | None:
match = re.match(r'([0-9]+)([a-zA-Z|%]*)', text, re.I)
if match:
@ -261,9 +261,9 @@ class PartitioningList(ListManager):
text: str,
header: str,
default: Size,
start: Optional[Size],
start: Size | None,
) -> Size:
def validate(value: str) -> Optional[str]:
def validate(value: str) -> str | None:
size = self._validate_value(sector_size, total_size, value, start)
if not size:
return str(_('Invalid size'))
@ -276,7 +276,7 @@ class PartitioningList(ListManager):
validator=validate
).input()
size: Optional[Size] = None
size: Size | None = None
value = result.text()
if value is None:
@ -342,11 +342,11 @@ class PartitioningList(ListManager):
return start_size, end_size
def _find_default_free_space(self) -> Optional[DefaultFreeSector]:
def _find_default_free_space(self) -> DefaultFreeSector | None:
device_info = self._device.device_info
largest_free_area: Optional[DeviceGeometry] = None
largest_deleted_area: Optional[PartitionModification] = None
largest_free_area: DeviceGeometry | None = None
largest_deleted_area: PartitionModification | None = None
if len(device_info.free_space_regions) > 0:
largest_free_area = max(device_info.free_space_regions, key=lambda r: r.get_length())

View File

@ -1,5 +1,5 @@
from pathlib import Path
from typing import Optional, Any, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from .device_model import SubvolumeModification
from ..menu import ListManager
@ -25,7 +25,7 @@ class SubvolumeMenu(ListManager):
def selected_action_display(self, subvolume: SubvolumeModification) -> str:
return str(subvolume.name)
def _add_subvolume(self, preset: Optional[SubvolumeModification] = None) -> Optional[SubvolumeModification]:
def _add_subvolume(self, preset: SubvolumeModification | None = None) -> SubvolumeModification | None:
result = EditMenu(
str(_('Subvolume name')),
alignment=Alignment.CENTER,
@ -57,7 +57,7 @@ class SubvolumeMenu(ListManager):
def handle_action(
self,
action: str,
entry: Optional[SubvolumeModification],
entry: SubvolumeModification | None,
data: list[SubvolumeModification]
) -> list[SubvolumeModification]:
if action == self._actions[0]: # add

View File

@ -2,7 +2,7 @@ import os
from enum import Enum
from functools import cached_property
from pathlib import Path
from typing import Optional, TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any
from .exceptions import SysCallError
from .general import SysCommand
@ -33,7 +33,7 @@ class CpuVendor(Enum):
case _:
return False
def get_ucode(self) -> Optional[Path]:
def get_ucode(self) -> Path | None:
if self._has_microcode():
return Path(self.value + '-ucode.img')
return None
@ -233,13 +233,13 @@ class SysInfo:
return any('intel' in x.lower() for x in SysInfo._graphics_devices())
@staticmethod
def cpu_vendor() -> Optional[CpuVendor]:
def cpu_vendor() -> CpuVendor | None:
if vendor := _sys_info.cpu_info.get('vendor_id'):
return CpuVendor.get_vendor(vendor)
return None
@staticmethod
def cpu_model() -> Optional[str]:
def cpu_model() -> str | None:
return _sys_info.cpu_info.get('model name', None)
@staticmethod
@ -265,7 +265,7 @@ class SysInfo:
return _sys_info.mem_info_by_key('MemTotal')
@staticmethod
def virtualization() -> Optional[str]:
def virtualization() -> str | None:
try:
return str(SysCommand("systemd-detect-virt")).strip('\r\n')
except SysCallError as err:

View File

@ -1,7 +1,7 @@
from __future__ import annotations
import re
from typing import Any, TYPE_CHECKING, Optional
from typing import Any, TYPE_CHECKING
from ..utils.util import get_password
from ..menu import ListManager
@ -31,7 +31,7 @@ class UserList(ListManager):
def selected_action_display(self, user: User) -> str:
return user.username
def handle_action(self, action: str, entry: Optional[User], data: list[User]) -> list[User]:
def handle_action(self, action: str, entry: User | None, data: list[User]) -> list[User]:
if action == self._actions[0]: # add
new_user = self._add_user()
if new_user is not None:
@ -54,12 +54,12 @@ class UserList(ListManager):
return data
def _check_for_correct_username(self, username: str) -> Optional[str]:
def _check_for_correct_username(self, username: str) -> str | None:
if re.match(r'^[a-z_][a-z0-9_-]*\$?$', username) and len(username) <= 32:
return None
return str(_("The username you entered is invalid"))
def _add_user(self) -> Optional[User]:
def _add_user(self) -> User | None:
editResult = EditMenu(
str(_('Username')),
allow_skip=True,

View File

@ -1,7 +1,7 @@
from __future__ import annotations
import ipaddress
from typing import Any, Optional, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from ..models.network_configuration import NetworkConfiguration, NicType, Nic
@ -29,7 +29,7 @@ class ManualNetworkConfig(ListManager):
def selected_action_display(self, nic: Nic) -> str:
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: Nic | None, data: list[Nic]) -> list[Nic]:
if action == self._actions[0]: # add
iface = self._select_iface(data)
if iface:
@ -45,7 +45,7 @@ class ManualNetworkConfig(ListManager):
return data
def _select_iface(self, data: list[Nic]) -> Optional[str]:
def _select_iface(self, data: list[Nic]) -> str | None:
all_ifaces = list_interfaces().values()
existing_ifaces = [d.iface for d in data]
available = set(all_ifaces) - set(existing_ifaces)
@ -80,9 +80,9 @@ class ManualNetworkConfig(ListManager):
header: str,
allow_skip: bool,
multi: bool,
preset: Optional[str] = None
) -> Optional[str]:
def validator(ip: str) -> Optional[str]:
preset: str | None = None
) -> str | None:
def validator(ip: str) -> str | None:
if multi:
ips = ip.split(' ')
else:
@ -166,7 +166,7 @@ class ManualNetworkConfig(ListManager):
return Nic(iface=iface_name)
def ask_to_configure_network(preset: Optional[NetworkConfiguration]) -> Optional[NetworkConfiguration]:
def ask_to_configure_network(preset: NetworkConfiguration | None) -> NetworkConfiguration | None:
"""
Configure the network on the newly installed system
"""

View File

@ -4,7 +4,6 @@ import shlex
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from . import disk
from .general import SysCommand, generate_password, SysCommandWorker
@ -16,16 +15,16 @@ from .storage import storage
@dataclass
class Luks2:
luks_dev_path: Path
mapper_name: Optional[str] = None
password: Optional[str] = None
key_file: Optional[Path] = None
mapper_name: str | None = None
password: str | None = None
key_file: Path | None = None
auto_unmount: bool = False
# will be set internally after unlocking the device
_mapper_dev: Optional[Path] = None
_mapper_dev: Path | None = None
@property
def mapper_dev(self) -> Optional[Path]:
def mapper_dev(self) -> Path | None:
if self.mapper_name:
return Path(f'/dev/mapper/{self.mapper_name}')
return None
@ -71,7 +70,7 @@ class Luks2:
key_size: int = 512,
hash_type: str = 'sha512',
iter_time: int = 10000,
key_file: Optional[Path] = None
key_file: Path | None = None
) -> Path:
debug(f'Luks2 encrypting: {self.luks_dev_path}')
@ -143,7 +142,7 @@ class Luks2:
def is_unlocked(self) -> bool:
return self.mapper_name is not None and Path(f'/dev/mapper/{self.mapper_name}').exists()
def unlock(self, key_file: Optional[Path] = None) -> None:
def unlock(self, key_file: Path | None = None) -> None:
"""
Unlocks the luks device, an optional key file location for unlocking can be specified,
otherwise a default location for the key file will be used.

View File

@ -1,5 +1,5 @@
import copy
from typing import Any, TYPE_CHECKING, Optional
from typing import Any, TYPE_CHECKING
from ..output import FormattedOutput
from archinstall.tui import (
@ -47,10 +47,10 @@ class ListManager:
self._base_actions = base_actions
self._sub_menu_actions = sub_menu_actions
self._last_choice: Optional[str] = None
self._last_choice: str | None = None
@property
def last_choice(self) -> Optional[str]:
def last_choice(self) -> str | None:
return self._last_choice
def is_last_choice_cancel(self) -> bool:
@ -140,7 +140,7 @@ class ListManager:
if value != self._cancel_action:
self._data = self.handle_action(value, entry, self._data)
def reformat(self, data: list[Any]) -> dict[str, Optional[Any]]:
def reformat(self, data: list[Any]) -> dict[str, Any | None]:
"""
Default implementation of the table to be displayed.
Override if any custom formatting is needed
@ -151,7 +151,7 @@ class ListManager:
# these are the header rows of the table and do not map to any User obviously
# we're adding 2 spaces as prefix because the menu selector '> ' will be put before
# the selectable rows so the header has to be aligned
display_data: dict[str, Optional[Any]] = {f'{rows[0]}': None, f'{rows[1]}': None}
display_data: dict[str, Any | None] = {f'{rows[0]}': None, f'{rows[1]}': None}
for row, entry in zip(rows[2:], data):
display_data[row] = entry
@ -165,7 +165,7 @@ class ListManager:
"""
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: Any | None, data: list[Any]) -> list[Any]:
"""
this function is called when a base action or
a specific action for an entry is triggered

View File

@ -1,4 +1,4 @@
from typing import Any, Optional
from typing import Any
from archinstall.lib.output import FormattedOutput
@ -10,8 +10,8 @@ from archinstall.tui import (
class MenuHelper:
@staticmethod
def create_table(
data: Optional[list[Any]] = None,
table_data: Optional[tuple[list[Any], str]] = None,
data: list[Any] | None = None,
table_data: tuple[list[Any], str] | None = None,
) -> tuple[MenuItemGroup, str]:
if data is not None:
table_text = FormattedOutput.as_table(data)

View File

@ -4,7 +4,7 @@ import urllib.parse
from pathlib import Path
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Optional, TYPE_CHECKING
from typing import Any, TYPE_CHECKING
from .menu import AbstractSubMenu, ListManager
from .networking import fetch_data_from_url
@ -143,7 +143,7 @@ class CustomMirrorList(ListManager):
def handle_action(
self,
action: str,
entry: Optional[CustomMirror],
entry: CustomMirror | None,
data: list[CustomMirror]
) -> list[CustomMirror]:
if action == self._actions[0]: # add
@ -161,7 +161,7 @@ class CustomMirrorList(ListManager):
return data
def _add_custom_mirror(self, preset: Optional[CustomMirror] = None) -> Optional[CustomMirror]:
def _add_custom_mirror(self, preset: CustomMirror | None = None) -> CustomMirror | None:
edit_result = EditMenu(
str(_('Mirror name')),
alignment=Alignment.CENTER,
@ -245,7 +245,7 @@ class CustomMirrorList(ListManager):
class MirrorMenu(AbstractSubMenu):
def __init__(
self,
preset: Optional[MirrorConfiguration] = None
preset: MirrorConfiguration | None = None
):
if preset:
self._mirror_config = preset
@ -277,7 +277,7 @@ class MirrorMenu(AbstractSubMenu):
)
]
def _prev_regions(self, item: MenuItem) -> Optional[str]:
def _prev_regions(self, item: MenuItem) -> str | None:
mirrors: dict[str, list[MirrorStatusEntryV3]] = item.get_value()
output = ''
@ -292,7 +292,7 @@ class MirrorMenu(AbstractSubMenu):
return output
def _prev_custom_mirror(self, item: MenuItem) -> Optional[str]:
def _prev_custom_mirror(self, item: MenuItem) -> str | None:
if not item.value:
return None
@ -348,7 +348,7 @@ def select_custom_mirror(preset: list[CustomMirror] = []):
return custom_mirrors
def list_mirrors_from_remote() -> Optional[dict[str, list[MirrorStatusEntryV3]]]:
def list_mirrors_from_remote() -> dict[str, list[MirrorStatusEntryV3]] | None:
if not storage['arguments']['offline']:
url = "https://archlinux.org/mirrors/status/json/"
attempts = 3

View File

@ -1,5 +1,5 @@
from dataclasses import dataclass
from typing import Optional, Any
from typing import Any
@dataclass
@ -20,7 +20,7 @@ class VersionDef:
return self.parse_version()[0]
@classmethod
def minor(cls) -> Optional[str]:
def minor(cls) -> str | None:
versions = cls.parse_version()
if len(versions) >= 2:
return versions[1]
@ -28,7 +28,7 @@ class VersionDef:
return None
@classmethod
def patch(cls) -> Optional[str]:
def patch(cls) -> str | None:
versions = cls.parse_version()
if '-' in versions[-1]:
_, patch_version = versions[-1].split('-', 1)
@ -74,7 +74,7 @@ class PackageSearchResult:
installed_size: int
build_date: str
last_update: str
flag_date: Optional[str]
flag_date: str | None
maintainers: list[str]
packager: str
groups: list[str]

View File

@ -7,7 +7,7 @@ import select
import signal
import random
from types import FrameType
from typing import Union, Any, Optional
from typing import Union, Any
from urllib.error import URLError
from urllib.parse import urlencode
from urllib.request import urlopen
@ -29,11 +29,11 @@ class DownloadTimer:
The download timeout in seconds. The DownloadTimeout exception
will be raised in the context after this many seconds.
'''
self.time: Optional[float] = None
self.start_time: Optional[float] = None
self.time: float | None = None
self.start_time: float | None = None
self.timeout = timeout
self.previous_handler = None
self.previous_timer: Optional[int] = None
self.previous_timer: int | None = None
def raise_timeout(self, signl: int, frame: FrameType | None) -> None:
'''
@ -120,7 +120,7 @@ def enrich_iface_types(interfaces: Union[dict[str, Any], list[str]]) -> dict[str
return result
def fetch_data_from_url(url: str, params: Optional[dict[str, str]] = None) -> str:
def fetch_data_from_url(url: str, params: dict[str, str] | None = None) -> str:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE

View File

@ -6,7 +6,7 @@ from collections.abc import Callable
from enum import Enum
from pathlib import Path
from typing import Union, Any, Optional, TYPE_CHECKING
from typing import Union, Any, TYPE_CHECKING
from dataclasses import asdict, is_dataclass
from .storage import storage
@ -21,7 +21,7 @@ class FormattedOutput:
def _get_values(
cls,
o: 'DataclassInstance',
class_formatter: Optional[Union[str, Callable]] = None,
class_formatter: Union[str, Callable] | None = None,
filter_list: list[str] = []
) -> dict[str, Any]:
"""
@ -53,7 +53,7 @@ class FormattedOutput:
def as_table(
cls,
obj: list[Any],
class_formatter: Optional[Union[str, Callable]] = None,
class_formatter: Union[str, Callable] | None = None,
filter_list: list[str] = [],
capitalize: bool = False
) -> str:
@ -203,7 +203,7 @@ class Font(Enum):
def _stylize_output(
text: str,
fg: str,
bg: Optional[str],
bg: str | None,
reset: bool,
font: list[Font] = [],
) -> str:
@ -257,7 +257,7 @@ def info(
*msgs: str,
level: int = logging.INFO,
fg: str = 'white',
bg: Optional[str] = None,
bg: str | None = None,
reset: bool = False,
font: list[Font] = []
) -> None:
@ -268,7 +268,7 @@ def debug(
*msgs: str,
level: int = logging.DEBUG,
fg: str = 'white',
bg: Optional[str] = None,
bg: str | None = None,
reset: bool = False,
font: list[Font] = []
) -> None:
@ -279,7 +279,7 @@ def error(
*msgs: str,
level: int = logging.ERROR,
fg: str = 'red',
bg: Optional[str] = None,
bg: str | None = None,
reset: bool = False,
font: list[Font] = []
) -> None:
@ -290,7 +290,7 @@ def warn(
*msgs: str,
level: int = logging.WARNING,
fg: str = 'yellow',
bg: Optional[str] = None,
bg: str | None = None,
reset: bool = False,
font: list[Font] = []
) -> None:
@ -301,7 +301,7 @@ def log(
*msgs: str,
level: int = logging.INFO,
fg: str = 'white',
bg: Optional[str] = None,
bg: str | None = None,
reset: bool = False,
font: list[Font] = []
) -> None:

View File

@ -6,7 +6,6 @@ import urllib.parse
import urllib.request
from importlib import metadata
from pathlib import Path
from typing import Optional
from .output import error, info, warn
from .storage import storage
@ -46,7 +45,7 @@ def _localize_path(path: Path) -> Path:
return path
def _import_via_path(path: Path, namespace: Optional[str] = None) -> Optional[str]:
def _import_via_path(path: Path, namespace: str | None = None) -> str | None:
if not namespace:
namespace = os.path.basename(path)
@ -75,7 +74,7 @@ def _import_via_path(path: Path, namespace: Optional[str] = None) -> Optional[st
return namespace
def _find_nth(haystack: list[str], needle: str, n: int) -> Optional[int]:
def _find_nth(haystack: list[str], needle: str, n: int) -> int | None:
indices = [idx for idx, elem in enumerate(haystack) if elem == needle]
if n <= len(indices):
return indices[n - 1]
@ -83,7 +82,7 @@ def _find_nth(haystack: list[str], needle: str, n: int) -> Optional[int]:
def load_plugin(path: Path) -> None:
namespace: Optional[str] = None
namespace: str | None = None
parsed_url = urllib.parse.urlparse(str(path))
info(f"Loading plugin from url {parsed_url}")