diff --git a/.github/workflows/translation-check.yaml b/.github/workflows/translation-check.yaml new file mode 100644 index 00000000..15be16cf --- /dev/null +++ b/.github/workflows/translation-check.yaml @@ -0,0 +1,22 @@ +name: Translation validation +on: + push: + paths: + - 'archinstall/**/*.py' + - 'archinstall/locales/**' + - '.github/workflows/translation-check.yaml' + pull_request: + paths: + - 'archinstall/**/*.py' + - 'archinstall/locales/**' + - '.github/workflows/translation-check.yaml' +jobs: + translations: + name: Validate translations + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 + - name: Install gettext + run: sudo apt-get update && sudo apt-get install -y gettext + - name: Run translation checks + run: bash archinstall/locales/locales_generator.sh check diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6cf16130..de2bcef4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,7 @@ default_stages: ['pre-commit'] repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.15.12 + rev: v0.15.13 hooks: # fix unused imports and sort them - id: ruff @@ -31,7 +31,7 @@ repos: args: [--config=.flake8] fail_fast: true - repo: https://github.com/pre-commit/mirrors-mypy - rev: v2.0.0 + rev: v2.1.0 hooks: - id: mypy args: [ @@ -41,6 +41,7 @@ repos: additional_dependencies: - pydantic - pytest + - hypothesis - cryptography - textual - repo: local diff --git a/archinstall/applications/audio.py b/archinstall/applications/audio.py index b749fe67..e5d79718 100644 --- a/archinstall/applications/audio.py +++ b/archinstall/applications/audio.py @@ -1,9 +1,9 @@ from typing import TYPE_CHECKING from archinstall.lib.hardware import SysInfo +from archinstall.lib.log import debug from archinstall.lib.models.application import Audio, AudioConfiguration from archinstall.lib.models.users import User -from archinstall.lib.output import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/applications/bluetooth.py b/archinstall/applications/bluetooth.py index a0ffbc75..6bd4999e 100644 --- a/archinstall/applications/bluetooth.py +++ b/archinstall/applications/bluetooth.py @@ -1,6 +1,6 @@ from typing import TYPE_CHECKING -from archinstall.lib.output import debug +from archinstall.lib.log import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/applications/firewall.py b/archinstall/applications/firewall.py index e450dbc6..dadaa05b 100644 --- a/archinstall/applications/firewall.py +++ b/archinstall/applications/firewall.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING +from archinstall.lib.log import debug from archinstall.lib.models.application import Firewall, FirewallConfiguration -from archinstall.lib.output import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/applications/fonts.py b/archinstall/applications/fonts.py index 3fa54c67..73eb326e 100644 --- a/archinstall/applications/fonts.py +++ b/archinstall/applications/fonts.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING +from archinstall.lib.log import debug from archinstall.lib.models.application import FontsConfiguration -from archinstall.lib.output import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/applications/power_management.py b/archinstall/applications/power_management.py index b9f32b05..744411f3 100644 --- a/archinstall/applications/power_management.py +++ b/archinstall/applications/power_management.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING +from archinstall.lib.log import debug from archinstall.lib.models.application import PowerManagement, PowerManagementConfiguration -from archinstall.lib.output import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/applications/print_service.py b/archinstall/applications/print_service.py index 3e4913f0..fbe28f89 100644 --- a/archinstall/applications/print_service.py +++ b/archinstall/applications/print_service.py @@ -1,6 +1,6 @@ from typing import TYPE_CHECKING -from archinstall.lib.output import debug +from archinstall.lib.log import debug if TYPE_CHECKING: from archinstall.lib.installer import Installer diff --git a/archinstall/default_profiles/desktop.py b/archinstall/default_profiles/desktop.py index daf70831..b70f9f11 100644 --- a/archinstall/default_profiles/desktop.py +++ b/archinstall/default_profiles/desktop.py @@ -1,8 +1,8 @@ from typing import TYPE_CHECKING, Self, override from archinstall.default_profiles.profile import DisplayServerType, GreeterType, Profile, ProfileType, SelectResult +from archinstall.lib.log import info from archinstall.lib.menu.helpers import Selection -from archinstall.lib.output import info from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType diff --git a/archinstall/default_profiles/desktops/budgie.py b/archinstall/default_profiles/desktops/budgie.py index f156a53b..da147851 100644 --- a/archinstall/default_profiles/desktops/budgie.py +++ b/archinstall/default_profiles/desktops/budgie.py @@ -18,12 +18,13 @@ class BudgieProfile(Profile): return [ 'materia-gtk-theme', 'budgie', - 'konsole', - 'dolphin', + 'mate-terminal', + 'nemo', + 'nemo-fileroller', 'papirus-icon-theme', ] @property @override def default_greeter_type(self) -> GreeterType: - return GreeterType.Sddm + return GreeterType.LightdmSlick diff --git a/archinstall/default_profiles/server.py b/archinstall/default_profiles/server.py index bdd3d079..0e2506e0 100644 --- a/archinstall/default_profiles/server.py +++ b/archinstall/default_profiles/server.py @@ -1,8 +1,8 @@ from typing import TYPE_CHECKING, Self, override from archinstall.default_profiles.profile import Profile, ProfileType, SelectResult +from archinstall.lib.log import info from archinstall.lib.menu.helpers import Selection -from archinstall.lib.output import info from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType diff --git a/archinstall/lib/args.py b/archinstall/lib/args.py index d8aaaa83..e3729504 100644 --- a/archinstall/lib/args.py +++ b/archinstall/lib/args.py @@ -6,6 +6,7 @@ import urllib.error import urllib.parse from argparse import ArgumentParser, Namespace from dataclasses import dataclass, field +from enum import Enum, StrEnum from pathlib import Path from typing import Any, Self from urllib.request import Request, urlopen @@ -13,10 +14,12 @@ from urllib.request import Request, urlopen from pydantic.dataclasses import dataclass as p_dataclass from archinstall.lib.crypt import decrypt +from archinstall.lib.log import debug, error, logger, warn from archinstall.lib.menu.util import get_password from archinstall.lib.models.application import ApplicationConfiguration, ZramConfiguration from archinstall.lib.models.authentication import AuthenticationConfiguration from archinstall.lib.models.bootloader import Bootloader, BootloaderConfiguration +from archinstall.lib.models.config import SubConfig from archinstall.lib.models.device import DiskEncryption, DiskLayoutConfiguration from archinstall.lib.models.locale import LocaleConfiguration from archinstall.lib.models.mirrors import MirrorConfiguration @@ -26,13 +29,16 @@ from archinstall.lib.models.packages import Repository from archinstall.lib.models.pacman import PacmanConfiguration from archinstall.lib.models.profile import ProfileConfiguration from archinstall.lib.models.users import Password, User, UserSerialization -from archinstall.lib.output import debug, error, logger, warn from archinstall.lib.plugins import load_plugin from archinstall.lib.translationhandler import Language, tr, translation_handler from archinstall.lib.version import get_version from archinstall.tui.components import tui +class SubCommand(Enum): + SHARE_LOG = 'share-log' + + @p_dataclass class Arguments: config: Path | None = None @@ -56,6 +62,83 @@ class Arguments: advanced: bool = False verbose: bool = False + command: SubCommand | None = None + + +class ArchConfigType(StrEnum): + VERSION = 'version' + SCRIPT = 'script' + LOCALE_CONFIG = 'locale_config' + ARCHINSTALL_LANGUAGE = 'archinstall_language' + DISK_CONFIG = 'disk_config' + PROFILE_CONFIG = 'profile_config' + MIRROR_CONFIG = 'mirror_config' + NETWORK_CONFIG = 'network_config' + BOOTLOADER_CONFIG = 'bootloader_config' + APP_CONFIG = 'app_config' + AUTH_CONFIG = 'auth_config' + SWAP = 'swap' + USERS = 'users' + ROOT_ENC_PASSWORD = 'root_enc_password' + ENCRYPTION_PASSWORD = 'encryption_password' + HOSTNAME = 'hostname' + KERNELS = 'kernels' + NTP = 'ntp' + TIMEZONE = 'timezone' + SERVICES = 'services' + PACKAGES = 'packages' + PACMAN_CONFIG = 'pacman_config' + CUSTOM_COMMANDS = 'custom_commands' + + def text(self) -> str: + match self: + case ArchConfigType.ARCHINSTALL_LANGUAGE: + return tr('ArchInstall Language') + case ArchConfigType.VERSION: + return tr('Version') + case ArchConfigType.SCRIPT: + return tr('Installation Script') + case ArchConfigType.LOCALE_CONFIG: + return tr('Locales') + case ArchConfigType.DISK_CONFIG: + return tr('Disk configuration') + case ArchConfigType.PROFILE_CONFIG: + return tr('Profile') + case ArchConfigType.MIRROR_CONFIG: + return tr('Mirrors and repositories') + case ArchConfigType.NETWORK_CONFIG: + return tr('Network') + case ArchConfigType.BOOTLOADER_CONFIG: + return tr('Bootloader') + case ArchConfigType.APP_CONFIG: + return tr('Application') + case ArchConfigType.AUTH_CONFIG: + return tr('Authentication') + case ArchConfigType.SWAP: + return tr('Swap') + case ArchConfigType.HOSTNAME: + return tr('Hostname') + case ArchConfigType.KERNELS: + return tr('Kernels') + case ArchConfigType.NTP: + return tr('Automatic time sync (NTP)') + case ArchConfigType.TIMEZONE: + return tr('Timezone') + case ArchConfigType.SERVICES: + return tr('Services') + case ArchConfigType.PACKAGES: + return tr('Additional packages') + case ArchConfigType.PACMAN_CONFIG: + return tr('Pacman') + case ArchConfigType.CUSTOM_COMMANDS: + return tr('Custom commands') + case ArchConfigType.USERS: + return tr('Users') + case ArchConfigType.ROOT_ENC_PASSWORD: + return tr('Root encrypted password') + case ArchConfigType.ENCRYPTION_PASSWORD: + return tr('Disk encryption password') + @dataclass class ArchConfig: @@ -80,58 +163,84 @@ class ArchConfig: services: list[str] = field(default_factory=list) custom_commands: list[str] = field(default_factory=list) - def unsafe_config(self) -> dict[str, Any]: - config: dict[str, list[UserSerialization] | str | None] = {} + def unsafe_config(self) -> dict[ArchConfigType, Any]: + config: dict[ArchConfigType, list[UserSerialization] | str | None] = {} if self.auth_config: if self.auth_config.users: - config['users'] = [user.json() for user in self.auth_config.users] + config[ArchConfigType.USERS] = [user.json() for user in self.auth_config.users] if self.auth_config.root_enc_password: - config['root_enc_password'] = self.auth_config.root_enc_password.enc_password + config[ArchConfigType.ROOT_ENC_PASSWORD] = self.auth_config.root_enc_password.enc_password if self.disk_config: disk_encryption = self.disk_config.disk_encryption if disk_encryption and disk_encryption.encryption_password: - config['encryption_password'] = disk_encryption.encryption_password.plaintext + config[ArchConfigType.ENCRYPTION_PASSWORD] = disk_encryption.encryption_password.plaintext return config - def safe_config(self) -> dict[str, Any]: - config: Any = { - 'version': self.version, - 'script': self.script, - 'archinstall-language': self.archinstall_language.json(), - 'hostname': self.hostname, - 'kernels': self.kernels, - 'ntp': self.ntp, - 'packages': self.packages, - 'pacman_config': self.pacman_config.json(), - 'swap': self.swap, - 'timezone': self.timezone, - 'services': self.services, - 'custom_commands': self.custom_commands, - 'bootloader_config': self.bootloader_config.json() if self.bootloader_config else None, - 'app_config': self.app_config.json() if self.app_config else None, - 'auth_config': self.auth_config.json() if self.auth_config else None, + def safe_config(self) -> dict[ArchConfigType, Any]: + base_config: dict[ArchConfigType, Any] = { + ArchConfigType.VERSION: self.version, + ArchConfigType.SCRIPT: self.script, + ArchConfigType.ARCHINSTALL_LANGUAGE: self.archinstall_language.json(), } - if self.locale_config: - config['locale_config'] = self.locale_config.json() + base_config.update(self.plain_cfg()) + sub_config = self.sub_cfg() - if self.disk_config: - config['disk_config'] = self.disk_config.json() + for config_type, value in sub_config.items(): + if not hasattr(value, 'json'): + raise ValueError(f'Config value for {config_type} must implement json() method') + base_config[config_type] = value.json() - if self.profile_config: - config['profile_config'] = self.profile_config.json() + return base_config + + def plain_cfg(self) -> dict[ArchConfigType, str | list[str] | bool]: + return { + ArchConfigType.HOSTNAME: self.hostname, + ArchConfigType.KERNELS: self.kernels, + ArchConfigType.NTP: self.ntp, + ArchConfigType.TIMEZONE: self.timezone, + ArchConfigType.SERVICES: self.services, + ArchConfigType.PACKAGES: self.packages, + ArchConfigType.CUSTOM_COMMANDS: self.custom_commands, + } + + def sub_cfg(self) -> dict[ArchConfigType, SubConfig]: + cfg: dict[ArchConfigType, SubConfig] = { + ArchConfigType.PACMAN_CONFIG: self.pacman_config, + } if self.mirror_config: - config['mirror_config'] = self.mirror_config.json() + cfg[ArchConfigType.MIRROR_CONFIG] = self.mirror_config + + if self.bootloader_config: + cfg[ArchConfigType.BOOTLOADER_CONFIG] = self.bootloader_config + + if self.disk_config: + cfg[ArchConfigType.DISK_CONFIG] = self.disk_config + + if self.swap: + cfg[ArchConfigType.SWAP] = self.swap + + if self.auth_config: + cfg[ArchConfigType.AUTH_CONFIG] = self.auth_config + + if self.locale_config: + cfg[ArchConfigType.LOCALE_CONFIG] = self.locale_config + + if self.profile_config: + cfg[ArchConfigType.PROFILE_CONFIG] = self.profile_config if self.network_config: - config['network_config'] = self.network_config.json() + cfg[ArchConfigType.NETWORK_CONFIG] = self.network_config - return config + if self.app_config: + cfg[ArchConfigType.APP_CONFIG] = self.app_config + + return cfg @classmethod def from_config(cls, args_config: dict[str, Any], args: Arguments) -> Self: @@ -262,13 +371,13 @@ class ArchConfig: class ArchConfigHandler: def __init__(self) -> None: self._parser: ArgumentParser = self._define_arguments() - args: Arguments = self._parse_args() - self._args = args + self._add_sub_parsers() + self._args: Arguments = self._parse_args() config = self._parse_config() try: - self._config = ArchConfig.from_config(config, args) + self._config = ArchConfig.from_config(config, self._args) self._config.version = get_version() except ValueError as err: warn(str(err)) @@ -294,8 +403,13 @@ class ArchConfigHandler: def print_help(self) -> None: self._parser.print_help() + def _add_sub_parsers(self) -> None: + subparsers = self._parser.add_subparsers(dest='command', help='Available subcommands') + _ = subparsers.add_parser(SubCommand.SHARE_LOG.value, help='Upload log file to public server') + def _define_arguments(self) -> ArgumentParser: parser = ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) + parser.add_argument( '-v', '--version', diff --git a/archinstall/lib/authentication/authentication_handler.py b/archinstall/lib/authentication/authentication_handler.py index 3a3b8cd4..bae192fd 100644 --- a/archinstall/lib/authentication/authentication_handler.py +++ b/archinstall/lib/authentication/authentication_handler.py @@ -3,9 +3,9 @@ from pathlib import Path from typing import TYPE_CHECKING from archinstall.lib.command import SysCommandWorker +from archinstall.lib.log import debug, info from archinstall.lib.models.authentication import AuthenticationConfiguration, U2FLoginConfiguration, U2FLoginMethod from archinstall.lib.models.users import User -from archinstall.lib.output import debug, info from archinstall.lib.translationhandler import tr if TYPE_CHECKING: diff --git a/archinstall/lib/authentication/authentication_menu.py b/archinstall/lib/authentication/authentication_menu.py index 5453099f..497b925b 100644 --- a/archinstall/lib/authentication/authentication_menu.py +++ b/archinstall/lib/authentication/authentication_menu.py @@ -6,9 +6,9 @@ from archinstall.lib.menu.helpers import Confirmation, Selection from archinstall.lib.menu.util import get_password from archinstall.lib.models.authentication import AuthenticationConfiguration, U2FLoginConfiguration, U2FLoginMethod from archinstall.lib.models.users import Password, User -from archinstall.lib.output import FormattedOutput from archinstall.lib.translationhandler import tr from archinstall.lib.user.user_menu import select_users +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -65,7 +65,7 @@ class AuthenticationMenu(AbstractSubMenu[AuthenticationConfiguration]): users: list[User] | None = item.value if users: - return FormattedOutput.as_table(users) + return as_table(users) return None def _prev_root_pwd(self, item: MenuItem) -> str | None: diff --git a/archinstall/lib/boot.py b/archinstall/lib/boot.py index b1e8c888..e8fa4c88 100644 --- a/archinstall/lib/boot.py +++ b/archinstall/lib/boot.py @@ -6,7 +6,7 @@ from typing import ClassVar, Self from archinstall.lib.command import SysCommand, SysCommandWorker from archinstall.lib.exceptions import SysCallError -from archinstall.lib.output import error +from archinstall.lib.log import error class Boot: diff --git a/archinstall/lib/command.py b/archinstall/lib/command.py index b99854d2..b0d45754 100644 --- a/archinstall/lib/command.py +++ b/archinstall/lib/command.py @@ -11,7 +11,7 @@ from types import TracebackType from typing import Any, Self, override from archinstall.lib.exceptions import RequirementError, SysCallError -from archinstall.lib.output import debug, error, logger +from archinstall.lib.log import debug, error, logger from archinstall.lib.utils.encoding import clear_vt100_escape_codes diff --git a/archinstall/lib/configuration.py b/archinstall/lib/configuration.py index aba835d9..f0096872 100644 --- a/archinstall/lib/configuration.py +++ b/archinstall/lib/configuration.py @@ -6,14 +6,14 @@ from typing import Any from pydantic import TypeAdapter -from archinstall.lib.args import ArchConfig +from archinstall.lib.args import ArchConfig, ArchConfigType from archinstall.lib.crypt import encrypt +from archinstall.lib.log import debug, logger, warn from archinstall.lib.menu.helpers import Confirmation, Selection from archinstall.lib.menu.util import get_password, prompt_dir -from archinstall.lib.models.bootloader import Bootloader from archinstall.lib.models.network import NetworkConfiguration -from archinstall.lib.output import debug, logger, warn from archinstall.lib.translationhandler import tr +from archinstall.lib.utils.format import as_key_value_pair from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -45,15 +45,15 @@ class ConfigurationOutput: def user_config_to_json(self) -> str: config = self._config.safe_config() - adapter = TypeAdapter(dict[str, Any]) + adapter = TypeAdapter(dict[ArchConfigType, Any]) python_dict = adapter.dump_python(config) return json.dumps(python_dict, indent=4, sort_keys=True) def user_credentials_to_json(self) -> str: - config = self._config.unsafe_config() + cfg = self._config.unsafe_config() - adapter = TypeAdapter(dict[str, Any]) - python_dict = adapter.dump_python(config) + adapter = TypeAdapter(dict[ArchConfigType, Any]) + python_dict = adapter.dump_python(cfg) return json.dumps(python_dict, indent=4, sort_keys=True) def write_debug(self) -> None: @@ -64,65 +64,24 @@ class ConfigurationOutput: """ Render a concise two-column summary of the current configuration. - The left column holds section labels, the right column holds values. - Column width adapts to the longest translated label so translations - do not break the alignment. Rows whose underlying config is not set - are skipped. - Returns an empty string if nothing meaningful to show. """ - rows: list[tuple[str, str]] = [] + cfg: dict[str, str | list[str] | bool] = {} - disk_config = self._config.disk_config - if disk_config and disk_config.device_modifications: - disk_parts: list[str] = [] - for mod in disk_config.device_modifications: - path = str(mod.device_path) - root_part = mod.get_root_partition() - flags: list[str] = [] - if root_part and root_part.fs_type: - flags.append(root_part.fs_type.value) - if disk_config.disk_encryption: - flags.append(tr('LUKS')) - disk_parts.append(f'{path} ({" + ".join(flags)})' if flags else path) - rows.append((tr('Disks'), ', '.join(disk_parts))) + for key, value in self._config.plain_cfg().items(): + cfg[key.text()] = value - bl_config = self._config.bootloader_config - if bl_config and bl_config.bootloader != Bootloader.NO_BOOTLOADER: - rows.append((tr('Bootloader'), bl_config.bootloader.value)) + for config_type, obj in self._config.sub_cfg().items(): + if not hasattr(obj, 'summary'): + continue - kernels = self._config.kernels - if kernels: - rows.append((tr('Kernel'), ', '.join(kernels))) + summary = obj.summary() + if summary: + cfg[config_type.text()] = summary - profile_config = self._config.profile_config - if profile_config and profile_config.profile: - names = profile_config.profile.current_selection_names() - rows.append((tr('Profile'), ', '.join(names) if names else profile_config.profile.name)) - if profile_config.greeter: - rows.append((tr('Greeter'), profile_config.greeter.value)) + simple_summary = as_key_value_pair(cfg, ignore_empty=True) - packages = self._config.packages - if packages: - rows.append((tr('Packages'), str(len(packages)))) - - net_config = self._config.network_config - if isinstance(net_config, NetworkConfiguration): - rows.append((tr('Network'), net_config.type.display_msg())) - - locale_config = self._config.locale_config - if locale_config: - rows.append((tr('Locale'), locale_config.sys_lang)) - - tz = self._config.timezone - if tz: - rows.append((tr('Timezone'), tz)) - - if not rows: - return '' - - label_width = max(len(label) for label, _ in rows) + 2 - return '\n'.join(f'{label:<{label_width}}{value}' for label, value in rows) + return simple_summary async def confirm_config(self, show_install_warnings: bool = False) -> bool: header = f'{tr("The specified configuration will be applied")}. ' diff --git a/archinstall/lib/crypt.py b/archinstall/lib/crypt.py index 99fa62d6..b7ad4edf 100644 --- a/archinstall/lib/crypt.py +++ b/archinstall/lib/crypt.py @@ -6,7 +6,7 @@ from pathlib import Path from cryptography.fernet import Fernet, InvalidToken from cryptography.hazmat.primitives.kdf.argon2 import Argon2id -from archinstall.lib.output import debug +from archinstall.lib.log import debug libcrypt = ctypes.CDLL('libcrypt.so') diff --git a/archinstall/lib/disk/device_handler.py b/archinstall/lib/disk/device_handler.py index 2e51d3d2..360cbfd1 100644 --- a/archinstall/lib/disk/device_handler.py +++ b/archinstall/lib/disk/device_handler.py @@ -15,6 +15,7 @@ from archinstall.lib.disk.utils import ( umount, ) from archinstall.lib.exceptions import DiskError, SysCallError, UnknownFilesystemFormat +from archinstall.lib.log import debug, error, info, log from archinstall.lib.models.device import ( DEFAULT_ITER_TIME, BDevice, @@ -35,7 +36,6 @@ from archinstall.lib.models.device import ( _PartitionInfo, ) from archinstall.lib.models.users import Password -from archinstall.lib.output import debug, error, info, log from archinstall.lib.pathnames import ARCHISO_MOUNTPOINT diff --git a/archinstall/lib/disk/disk_menu.py b/archinstall/lib/disk/disk_menu.py index 26aa145d..f8e8e2e3 100644 --- a/archinstall/lib/disk/disk_menu.py +++ b/archinstall/lib/disk/disk_menu.py @@ -5,6 +5,7 @@ from typing import override from archinstall.lib.disk.device_handler import device_handler from archinstall.lib.disk.encryption_menu import DiskEncryptionMenu from archinstall.lib.disk.partitioning_menu import manual_partitioning +from archinstall.lib.log import debug from archinstall.lib.menu.abstract_menu import AbstractSubMenu from archinstall.lib.menu.helpers import Confirmation, Notify, Selection, Table from archinstall.lib.menu.util import prompt_dir @@ -35,8 +36,8 @@ from archinstall.lib.models.device import ( Unit, _DeviceInfo, ) -from archinstall.lib.output import FormattedOutput, debug from archinstall.lib.translationhandler import tr +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -221,7 +222,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu[DiskMenuConfig]): for mod in device_mods: # create partition table - partition_table = FormattedOutput.as_table(mod.partitions) + partition_table = as_table(mod.partitions) output_partition += f'{mod.device_path}: {mod.device.device_info.model}\n' output_partition += '{}: {}\n'.format(tr('Wipe'), mod.wipe) @@ -230,7 +231,7 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu[DiskMenuConfig]): # create btrfs table btrfs_partitions = [p for p in mod.partitions if p.btrfs_subvols] for partition in btrfs_partitions: - output_btrfs += FormattedOutput.as_table(partition.btrfs_subvols) + '\n' + output_btrfs += as_table(partition.btrfs_subvols) + '\n' output = output_partition + output_btrfs return output.rstrip() @@ -246,12 +247,12 @@ class DiskLayoutConfigurationMenu(AbstractSubMenu[DiskMenuConfig]): output = '{}: {}\n'.format(tr('Configuration'), lvm_config.config_type.display_msg()) for vol_gp in lvm_config.vol_groups: - pv_table = FormattedOutput.as_table(vol_gp.pvs) + pv_table = as_table(vol_gp.pvs) output += '{}:\n{}'.format(tr('Physical volumes'), pv_table) output += f'\nVolume Group: {vol_gp.name}' - lvm_volumes = FormattedOutput.as_table(vol_gp.volumes) + lvm_volumes = as_table(vol_gp.volumes) output += '\n\n{}:\n{}'.format(tr('Volumes'), lvm_volumes) return output @@ -302,7 +303,7 @@ async def select_devices(preset: list[BDevice] | None = []) -> list[BDevice] | N dev = device_handler.get_device(device.path) if dev and dev.partition_infos: - return FormattedOutput.as_table(dev.partition_infos) + return as_table(dev.partition_infos) return None if preset is None: diff --git a/archinstall/lib/disk/encryption_menu.py b/archinstall/lib/disk/encryption_menu.py index f5d4f095..53aa73fe 100644 --- a/archinstall/lib/disk/encryption_menu.py +++ b/archinstall/lib/disk/encryption_menu.py @@ -17,8 +17,8 @@ from archinstall.lib.models.device import ( PartitionModification, ) from archinstall.lib.models.users import Password -from archinstall.lib.output import FormattedOutput from archinstall.lib.translationhandler import tr +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -199,7 +199,7 @@ class DiskEncryptionMenu(AbstractSubMenu[DiskEncryption]): def _prev_partitions(self, item: MenuItem) -> str | None: if item.value: output = tr('Partitions to be encrypted') + '\n' - output += FormattedOutput.as_table(item.value) + output += as_table(item.value) return output.rstrip() return None @@ -207,7 +207,7 @@ class DiskEncryptionMenu(AbstractSubMenu[DiskEncryption]): def _prev_lvm_vols(self, item: MenuItem) -> str | None: if item.value: output = tr('LVM volumes to be encrypted') + '\n' - output += FormattedOutput.as_table(item.value) + output += as_table(item.value) return output.rstrip() return None diff --git a/archinstall/lib/disk/fido.py b/archinstall/lib/disk/fido.py index 0538417f..6392b55c 100644 --- a/archinstall/lib/disk/fido.py +++ b/archinstall/lib/disk/fido.py @@ -4,9 +4,9 @@ from typing import ClassVar from archinstall.lib.command import SysCommand, SysCommandWorker from archinstall.lib.exceptions import SysCallError +from archinstall.lib.log import error, info from archinstall.lib.models.device import Fido2Device from archinstall.lib.models.users import Password -from archinstall.lib.output import error, info from archinstall.lib.utils.encoding import clear_vt100_escape_codes_from_str diff --git a/archinstall/lib/disk/filesystem.py b/archinstall/lib/disk/filesystem.py index 1afa8c6e..2c51b09d 100644 --- a/archinstall/lib/disk/filesystem.py +++ b/archinstall/lib/disk/filesystem.py @@ -13,6 +13,7 @@ from archinstall.lib.disk.lvm import ( lvm_vol_reduce, ) from archinstall.lib.disk.utils import udev_sync +from archinstall.lib.log import debug, info from archinstall.lib.models.device import ( DiskEncryption, DiskLayoutConfiguration, @@ -27,7 +28,6 @@ from archinstall.lib.models.device import ( Size, Unit, ) -from archinstall.lib.output import debug, info class FilesystemHandler: diff --git a/archinstall/lib/disk/luks.py b/archinstall/lib/disk/luks.py index 275222f8..5d62abc8 100644 --- a/archinstall/lib/disk/luks.py +++ b/archinstall/lib/disk/luks.py @@ -7,9 +7,9 @@ from types import TracebackType from archinstall.lib.command import SysCommand, SysCommandWorker, run from archinstall.lib.disk.utils import get_lsblk_info, umount from archinstall.lib.exceptions import DiskError, SysCallError +from archinstall.lib.log import debug, info from archinstall.lib.models.device import DEFAULT_ITER_TIME from archinstall.lib.models.users import Password -from archinstall.lib.output import debug, info from archinstall.lib.utils.util import generate_password diff --git a/archinstall/lib/disk/lvm.py b/archinstall/lib/disk/lvm.py index 34ae9a26..c2c5b6a6 100644 --- a/archinstall/lib/disk/lvm.py +++ b/archinstall/lib/disk/lvm.py @@ -7,6 +7,7 @@ from typing import Literal, overload from archinstall.lib.command import SysCommand, SysCommandWorker from archinstall.lib.disk.utils import udev_sync from archinstall.lib.exceptions import SysCallError +from archinstall.lib.log import debug from archinstall.lib.models.device import ( LvmGroupInfo, LvmPVInfo, @@ -17,7 +18,6 @@ from archinstall.lib.models.device import ( Size, Unit, ) -from archinstall.lib.output import debug def _lvm_info( diff --git a/archinstall/lib/disk/partitioning_menu.py b/archinstall/lib/disk/partitioning_menu.py index a524cf99..b8ddd231 100644 --- a/archinstall/lib/disk/partitioning_menu.py +++ b/archinstall/lib/disk/partitioning_menu.py @@ -19,8 +19,8 @@ from archinstall.lib.models.device import ( Size, Unit, ) -from archinstall.lib.output import FormattedOutput from archinstall.lib.translationhandler import tr +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -479,7 +479,7 @@ class PartitioningList(ListManager[DiskSegment]): sector_size = device_info.sector_size text = tr('Selected free space segment on device {}:').format(device_info.path) + '\n\n' - free_space_table = FormattedOutput.as_table([free_space]) + free_space_table = as_table([free_space]) prompt = text + free_space_table + '\n' max_sectors = free_space.length.format_size(Unit.sectors, sector_size) diff --git a/archinstall/lib/disk/utils.py b/archinstall/lib/disk/utils.py index 808ff451..900445e1 100644 --- a/archinstall/lib/disk/utils.py +++ b/archinstall/lib/disk/utils.py @@ -4,8 +4,8 @@ from pydantic import BaseModel from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import DiskError, SysCallError +from archinstall.lib.log import debug, info, warn from archinstall.lib.models.device import LsblkInfo -from archinstall.lib.output import debug, info, warn class LsblkOutput(BaseModel): diff --git a/archinstall/lib/general/general_menu.py b/archinstall/lib/general/general_menu.py index be5498d8..dcf7d8aa 100644 --- a/archinstall/lib/general/general_menu.py +++ b/archinstall/lib/general/general_menu.py @@ -1,8 +1,8 @@ from enum import Enum from archinstall.lib.locale.utils import list_timezones +from archinstall.lib.log import warn from archinstall.lib.menu.helpers import Confirmation, Input, Selection -from archinstall.lib.output import warn from archinstall.lib.translationhandler import Language, tr from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType diff --git a/archinstall/lib/global_menu.py b/archinstall/lib/global_menu.py index eac936bd..45a0e3b4 100644 --- a/archinstall/lib/global_menu.py +++ b/archinstall/lib/global_menu.py @@ -27,11 +27,11 @@ from archinstall.lib.models.packages import Repository from archinstall.lib.models.pacman import PacmanConfiguration from archinstall.lib.models.profile import ProfileConfiguration from archinstall.lib.network.network_menu import select_network -from archinstall.lib.output import FormattedOutput from archinstall.lib.packages.packages import list_available_packages, select_additional_packages from archinstall.lib.pacman.config import PacmanConfig from archinstall.lib.pacman.pacman_menu import PacmanMenu from archinstall.lib.translationhandler import Language, tr, translation_handler +from archinstall.lib.utils.format import as_table from archinstall.tui.components import tui from archinstall.tui.menu_item import MenuItem, MenuItemGroup @@ -299,7 +299,7 @@ class GlobalMenu(AbstractMenu[None]): if item.value: network_config: NetworkConfiguration = item.value if network_config.type == NicType.MANUAL: - output = FormattedOutput.as_table(network_config.nics) + output = as_table(network_config.nics) else: output = f'{tr("Network configuration")}:\n{network_config.type.display_msg()}' @@ -321,7 +321,7 @@ class GlobalMenu(AbstractMenu[None]): output += f'{tr("Root password")}: {auth_config.root_enc_password.hidden()}\n' if auth_config.users: - output += FormattedOutput.as_table(auth_config.users) + '\n' + output += as_table(auth_config.users) + '\n' if auth_config.u2f_config: u2f_config = auth_config.u2f_config @@ -502,7 +502,7 @@ class GlobalMenu(AbstractMenu[None]): return text[:-1] # remove last new line if error := self._validate_bootloader(): - return tr(f'Invalid configuration: {error}') + return tr('Invalid configuration: {}').format(error) self.sync_all_to_config() summary = ConfigurationOutput(self._arch_config).as_summary() @@ -612,7 +612,7 @@ class GlobalMenu(AbstractMenu[None]): if mirror_config.custom_repositories: title = tr('Custom repositories') - table = FormattedOutput.as_table(mirror_config.custom_repositories) + table = as_table(mirror_config.custom_repositories) output += f'{title}:\n\n{table}' return output.strip() diff --git a/archinstall/lib/hardware.py b/archinstall/lib/hardware.py index 2cfdb706..f1587a3c 100644 --- a/archinstall/lib/hardware.py +++ b/archinstall/lib/hardware.py @@ -6,8 +6,8 @@ from typing import Self from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import SysCallError +from archinstall.lib.log import debug from archinstall.lib.networking import enrich_iface_types, list_interfaces -from archinstall.lib.output import debug from archinstall.lib.translationhandler import tr diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 801eaee2..bf7d91ba 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -29,6 +29,7 @@ from archinstall.lib.exceptions import DiskError, HardwareIncompatibilityError, from archinstall.lib.hardware import SysInfo from archinstall.lib.linux_path import LPath from archinstall.lib.locale.utils import verify_keyboard_layout, verify_x11_keyboard_layout +from archinstall.lib.log import debug, error, info, log, logger, warn from archinstall.lib.mirror.mirror_handler import MirrorListHandler from archinstall.lib.models.application import ZramAlgorithm from archinstall.lib.models.bootloader import Bootloader, BootloaderConfiguration @@ -52,7 +53,6 @@ from archinstall.lib.models.package_types import DEFAULT_KERNEL, Kernel from archinstall.lib.models.packages import Repository from archinstall.lib.models.pacman import PacmanConfiguration from archinstall.lib.models.users import User -from archinstall.lib.output import debug, error, info, log, logger, warn from archinstall.lib.packages.packages import installed_package from archinstall.lib.pacman.config import PacmanConfig from archinstall.lib.pacman.pacman import Pacman @@ -375,7 +375,12 @@ class Installer: # it would be none if it's btrfs as the subvolumes will have the mountpoints defined if part_mod.mountpoint: target = self.target / part_mod.relative_mountpoint - mount(part_mod.dev_path, target, options=part_mod.mount_options) + options = part_mod.mount_options + + if part_mod.is_efi(): + options = list(dict.fromkeys(options + ['fmask=0077', 'dmask=0077'])) + + mount(part_mod.dev_path, target, options=options) elif part_mod.fs_type == FilesystemType.BTRFS: # Only mount BTRFS subvolumes that have mountpoints specified subvols_with_mountpoints = [sv for sv in part_mod.btrfs_subvols if sv.mountpoint is not None] diff --git a/archinstall/lib/locale/utils.py b/archinstall/lib/locale/utils.py index 497e1fcb..31946028 100644 --- a/archinstall/lib/locale/utils.py +++ b/archinstall/lib/locale/utils.py @@ -3,7 +3,7 @@ from pathlib import Path from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import ServiceException, SysCallError -from archinstall.lib.output import error +from archinstall.lib.log import error from archinstall.lib.utils.util import running_from_iso diff --git a/archinstall/lib/log.py b/archinstall/lib/log.py new file mode 100644 index 00000000..bd060e99 --- /dev/null +++ b/archinstall/lib/log.py @@ -0,0 +1,259 @@ +import logging +import os +import sys +import urllib.error +import urllib.request +from enum import Enum +from pathlib import Path + +from archinstall.lib.utils.util import timestamp + + +class Logger: + def __init__(self, path: Path | None = None) -> None: + if path is None: + path = Path('/var/log/archinstall') + + self._path: Path = path + + @property + def path(self) -> Path: + return self._path / 'install.log' + + @path.setter + def path(self, value: Path) -> None: + self._path = value + + @property + def directory(self) -> Path: + return self._path + + def _check_permissions(self) -> None: + log_file = self.path + + try: + self._path.mkdir(exist_ok=True, parents=True) + log_file.touch(exist_ok=True) + + with log_file.open('a') as f: + f.write('') + except PermissionError: + # Fallback to creating the log file in the current folder + logger._path = Path('./').absolute() + + warn(f'Not enough permission to place log file at {log_file}, creating it in {logger.path} instead') + + def log(self, level: int, content: str) -> None: + self._check_permissions() + + with self.path.open('a') as f: + ts = timestamp() + level_name = logging.getLevelName(level) + f.write(f'[{ts}] - {level_name} - {content}\n') + + def get_content(self, max_bytes: int | None = None) -> bytes: + content = self.path.read_bytes() + + if max_bytes is not None: + size = self.path.stat().st_size + + if size > max_bytes: + content = content[-max_bytes:] + + return content + + +logger = Logger() + + +def _supports_color() -> bool: + """ + Found first reference here: + https://stackoverflow.com/questions/7445658/how-to-detect-if-the-console-does-support-ansi-escape-codes-in-python + And re-used this: + https://github.com/django/django/blob/master/django/core/management/color.py#L12 + + Return True if the running system's terminal supports color, + and False otherwise. + """ + supported_platform = sys.platform != 'win32' or 'ANSICON' in os.environ + + # isatty is not always implemented, #6223. + is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() + return supported_platform and is_a_tty + + +class Font(Enum): + bold = '1' + italic = '3' + underscore = '4' + blink = '5' + reverse = '7' + conceal = '8' + + +def _stylize_output( + text: str, + fg: str, + bg: str | None, + reset: bool, + font: list[Font] = [], +) -> str: + """ + Heavily influenced by: + https://github.com/django/django/blob/ae8338daf34fd746771e0678081999b656177bae/django/utils/termcolors.py#L13 + Color options here: + https://askubuntu.com/questions/528928/how-to-do-underline-bold-italic-strikethrough-color-background-and-size-i + + Adds styling to a text given a set of color arguments. + """ + colors = { + 'black': '0', + 'red': '1', + 'green': '2', + 'yellow': '3', + 'blue': '4', + 'magenta': '5', + 'cyan': '6', + 'white': '7', + 'teal': '8;5;109', # Extended 256-bit colors (not always supported) + 'orange': '8;5;208', # https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#256-colors + 'darkorange': '8;5;202', + 'gray': '8;5;246', + 'grey': '8;5;246', + 'darkgray': '8;5;240', + 'lightgray': '8;5;256', + } + + foreground = {key: f'3{colors[key]}' for key in colors} + background = {key: f'4{colors[key]}' for key in colors} + code_list = [] + + if text == '' and reset: + return '\x1b[0m' + + code_list.append(foreground[str(fg)]) + + if bg: + code_list.append(background[str(bg)]) + + for o in font: + code_list.append(o.value) + + ansi = ';'.join(code_list) + + return f'\033[{ansi}m{text}\033[0m' + + +def journal_log(message: str, level: int = logging.DEBUG) -> None: + try: + import systemd.journal # type: ignore[import-not-found] + except ModuleNotFoundError: + return + + log_adapter = logging.getLogger('archinstall') + log_fmt = logging.Formatter('[%(levelname)s]: %(message)s') + log_ch = systemd.journal.JournalHandler() + log_ch.setFormatter(log_fmt) + log_adapter.addHandler(log_ch) + log_adapter.setLevel(logging.DEBUG) + + log_adapter.log(level, message) + + +def info( + *msgs: str, + level: int = logging.INFO, + fg: str = 'white', + bg: str | None = None, + reset: bool = False, + font: list[Font] = [], +) -> None: + log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) + + +def debug( + *msgs: str, + level: int = logging.DEBUG, + fg: str = 'white', + bg: str | None = None, + reset: bool = False, + font: list[Font] = [], +) -> None: + log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) + + +def error( + *msgs: str, + level: int = logging.ERROR, + fg: str = 'red', + bg: str | None = None, + reset: bool = False, + font: list[Font] = [], +) -> None: + log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) + + +def warn( + *msgs: str, + level: int = logging.WARNING, + fg: str = 'yellow', + bg: str | None = None, + reset: bool = False, + font: list[Font] = [], +) -> None: + log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) + + +def log( + *msgs: str, + level: int = logging.INFO, + fg: str = 'white', + bg: str | None = None, + reset: bool = False, + font: list[Font] = [], +) -> None: + text = ' '.join(str(x) for x in msgs) + + logger.log(level, text) + + # Attempt to colorize the output if supported + # Insert default colors and override with **kwargs + if _supports_color(): + text = _stylize_output(text, fg, bg, reset, font) + + journal_log(text, level=level) + + if level != logging.DEBUG: + print(text) + + +def share_install_log( + paste_url: str, + max_bytes: int | None = None, +) -> str | None: + log_path = logger.path + + if not log_path.exists(): + info(f'Log file not found: {log_path}') + return None + + content = logger.get_content(max_bytes=max_bytes) + + if len(content) == 0: + info(f'Log file is empty: {log_path}') + return None + + try: + req = urllib.request.Request(paste_url, data=content) + with urllib.request.urlopen(req) as response: + url = response.read().decode().strip() + except urllib.error.URLError as e: + info(f'Upload failed: {e}') + return None + + if not url.startswith('http'): + info(f'Unexpected response from {paste_url}: {url[:200]!r}') + return None + + return url diff --git a/archinstall/lib/menu/abstract_menu.py b/archinstall/lib/menu/abstract_menu.py index 590cabf1..c37f5657 100644 --- a/archinstall/lib/menu/abstract_menu.py +++ b/archinstall/lib/menu/abstract_menu.py @@ -2,8 +2,8 @@ from enum import Enum from types import TracebackType from typing import Any, Self, override +from archinstall.lib.log import error from archinstall.lib.menu.helpers import Selection -from archinstall.lib.output import error from archinstall.lib.translationhandler import tr from archinstall.tui.components import InstanceRunnable from archinstall.tui.menu_item import MenuItem, MenuItemGroup diff --git a/archinstall/lib/menu/menu_helper.py b/archinstall/lib/menu/menu_helper.py index 6ca3b953..0d9a4032 100644 --- a/archinstall/lib/menu/menu_helper.py +++ b/archinstall/lib/menu/menu_helper.py @@ -1,4 +1,4 @@ -from archinstall.lib.output import FormattedOutput +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup @@ -32,7 +32,7 @@ class MenuHelper[ValueT]: display_data: dict[str, ValueT | str | None] = {} if data: - table = FormattedOutput.as_table(data) + table = as_table(data) rows = table.split('\n') # these are the header rows of the table diff --git a/archinstall/lib/mirror/mirror_handler.py b/archinstall/lib/mirror/mirror_handler.py index ef0ba1a9..8117605d 100644 --- a/archinstall/lib/mirror/mirror_handler.py +++ b/archinstall/lib/mirror/mirror_handler.py @@ -2,10 +2,10 @@ import time import urllib.parse from pathlib import Path +from archinstall.lib.log import debug, info from archinstall.lib.models import MirrorRegion from archinstall.lib.models.mirrors import MirrorStatusEntryV3, MirrorStatusListV3 from archinstall.lib.networking import fetch_data_from_url -from archinstall.lib.output import debug, info from archinstall.lib.pathnames import MIRRORLIST diff --git a/archinstall/lib/mirror/mirror_menu.py b/archinstall/lib/mirror/mirror_menu.py index 5158bffd..6c5de14a 100644 --- a/archinstall/lib/mirror/mirror_menu.py +++ b/archinstall/lib/mirror/mirror_menu.py @@ -13,8 +13,8 @@ from archinstall.lib.models.mirrors import ( SignOption, ) from archinstall.lib.models.packages import Repository -from archinstall.lib.output import FormattedOutput from archinstall.lib.translationhandler import tr +from archinstall.lib.utils.format import as_table from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import ResultType @@ -65,7 +65,7 @@ class CustomMirrorRepositoriesList(ListManager[CustomRepository]): async def _add_custom_repository(self, preset: CustomRepository | None = None) -> CustomRepository | None: edit_result = await Input( - header=tr('Enter a respository name'), + header=tr('Enter a repository name'), allow_skip=True, default_value=preset.name if preset else None, ).show() @@ -281,7 +281,7 @@ class MirrorMenu(AbstractSubMenu[MirrorConfiguration]): return None custom_mirrors: list[CustomRepository] = item.value - output = FormattedOutput.as_table(custom_mirrors) + output = as_table(custom_mirrors) return output.strip() def _prev_custom_servers(self, item: MenuItem) -> str | None: diff --git a/archinstall/lib/models/application.py b/archinstall/lib/models/application.py index 04d1a342..1e97a784 100644 --- a/archinstall/lib/models/application.py +++ b/archinstall/lib/models/application.py @@ -1,7 +1,8 @@ from dataclasses import dataclass from enum import StrEnum, auto -from typing import Any, NotRequired, Self, TypedDict +from typing import Any, NotRequired, Self, TypedDict, override +from archinstall.lib.models.config import SubConfig from archinstall.lib.translationhandler import tr @@ -168,7 +169,7 @@ class FontsConfiguration: @dataclass(frozen=True) -class ZramConfiguration: +class ZramConfiguration(SubConfig): enabled: bool algorithm: ZramAlgorithm = ZramAlgorithm.ZSTD @@ -181,9 +182,28 @@ class ZramConfiguration: algo = arg.get('algorithm', arg.get('algo', ZramAlgorithm.ZSTD.value)) return cls(enabled=enabled, algorithm=ZramAlgorithm(algo)) + @override + def json(self) -> dict[str, bool | str]: + return { + 'enabled': self.enabled, + 'algorithm': self.algorithm.value, + } + + @override + def summary(self) -> list[str] | None: + out: list[str] = [] + + if self.enabled: + out.append(tr('Zram enabled')) + + out.append(tr('Zram algorithm {}').format(self.algorithm)) + return out + + return None + @dataclass -class ApplicationConfiguration: +class ApplicationConfiguration(SubConfig): bluetooth_config: BluetoothConfiguration | None = None audio_config: AudioConfiguration | None = None power_management_config: PowerManagementConfiguration | None = None @@ -223,6 +243,7 @@ class ApplicationConfiguration: return app_config + @override def json(self) -> ApplicationSerialization: config: ApplicationSerialization = {} @@ -245,3 +266,28 @@ class ApplicationConfiguration: config['fonts_config'] = self.fonts_config.json() return config + + @override + def summary(self) -> list[str]: + out: list[str] = [] + + if self.bluetooth_config and self.bluetooth_config.enabled: + out.append(tr('Bluetooth enabled')) + + if self.audio_config: + out.append(tr('Audio server "{}"').format(self.audio_config.audio)) + + if self.power_management_config: + out.append(tr('Power management "{}"').format(self.power_management_config.power_management)) + + if self.print_service_config and self.print_service_config.enabled: + out.append(tr('Print service enabled')) + + if self.firewall_config: + out.append(tr('Firewall "{}"').format(self.firewall_config.firewall)) + + if self.fonts_config and self.fonts_config.fonts: + fonts = ', '.join(f.value for f in self.fonts_config.fonts) + out.append(tr('Extra fonts "{}"').format(fonts)) + + return out diff --git a/archinstall/lib/models/authentication.py b/archinstall/lib/models/authentication.py index 51120479..37261e7c 100644 --- a/archinstall/lib/models/authentication.py +++ b/archinstall/lib/models/authentication.py @@ -1,7 +1,8 @@ from dataclasses import dataclass, field from enum import Enum -from typing import Any, NotRequired, Self, TypedDict +from typing import Any, NotRequired, Self, TypedDict, override +from archinstall.lib.models.config import SubConfig from archinstall.lib.models.users import Password, User from archinstall.lib.translationhandler import tr @@ -58,7 +59,7 @@ class U2FLoginConfiguration: @dataclass -class AuthenticationConfiguration: +class AuthenticationConfiguration(SubConfig): root_enc_password: Password | None = None users: list[User] = field(default_factory=list) u2f_config: U2FLoginConfiguration | None = None @@ -75,6 +76,7 @@ class AuthenticationConfiguration: return auth_config + @override def json(self) -> AuthenticationSerialization: config: AuthenticationSerialization = {} @@ -83,6 +85,21 @@ class AuthenticationConfiguration: return config + @override + def summary(self) -> list[str]: + out: list[str] = [] + + if self.root_enc_password: + out.append(tr('Root password set')) + + if self.users: + out.append(tr('Configured {} user(s)').format(len(self.users))) + + if self.u2f_config: + out.append(tr('U2F set up')) + + return out + def has_superuser(self) -> bool: return any(u.sudo for u in self.users) diff --git a/archinstall/lib/models/bootloader.py b/archinstall/lib/models/bootloader.py index 5d8d0d80..bd6bce7e 100644 --- a/archinstall/lib/models/bootloader.py +++ b/archinstall/lib/models/bootloader.py @@ -1,9 +1,10 @@ import sys from dataclasses import dataclass from enum import Enum -from typing import Any, Self +from typing import Any, Self, override -from archinstall.lib.output import warn +from archinstall.lib.log import warn +from archinstall.lib.models.config import SubConfig from archinstall.lib.translationhandler import tr @@ -60,14 +61,26 @@ class Bootloader(Enum): @dataclass -class BootloaderConfiguration: +class BootloaderConfiguration(SubConfig): bootloader: Bootloader uki: bool = False removable: bool = True + @override def json(self) -> dict[str, Any]: return {'bootloader': self.bootloader.json(), 'uki': self.uki, 'removable': self.removable} + @override + def summary(self) -> list[str]: + out = [tr('Bootloader "{}"').format(self.bootloader.value)] + + if self.uki: + out.append(tr('UKI enabled')) + if self.removable: + out.append(tr('Removable')) + + return out + @classmethod def parse_arg(cls, config: dict[str, Any], skip_boot: bool) -> Self: bootloader = Bootloader.from_arg(config.get('bootloader', ''), skip_boot) diff --git a/archinstall/lib/models/config.py b/archinstall/lib/models/config.py new file mode 100644 index 00000000..45835bc0 --- /dev/null +++ b/archinstall/lib/models/config.py @@ -0,0 +1,12 @@ +from abc import ABC, abstractmethod +from typing import Any + + +class SubConfig(ABC): + @abstractmethod + def json(self) -> Any: + pass + + @abstractmethod + def summary(self) -> str | list[str] | None: + pass diff --git a/archinstall/lib/models/device.py b/archinstall/lib/models/device.py index 7fa05407..a50f7d8e 100644 --- a/archinstall/lib/models/device.py +++ b/archinstall/lib/models/device.py @@ -12,8 +12,9 @@ from parted import Disk, Geometry, Partition from pydantic import BaseModel, Field, ValidationInfo, field_serializer, field_validator from archinstall.lib.hardware import SysInfo +from archinstall.lib.log import debug +from archinstall.lib.models.config import SubConfig from archinstall.lib.models.users import Password -from archinstall.lib.output import debug from archinstall.lib.translationhandler import tr ENC_IDENTIFIER = 'ainst' @@ -34,6 +35,15 @@ class DiskLayoutType(Enum): case DiskLayoutType.Pre_mount: return tr('Pre-mounted configuration') + def short_msg(self) -> str: + match self: + case DiskLayoutType.Default: + return tr('Default') + case DiskLayoutType.Manual: + return tr('Manual') + case DiskLayoutType.Pre_mount: + return tr('Pre-mount') + class _DiskLayoutConfigurationSerialization(TypedDict): config_type: str @@ -45,7 +55,7 @@ class _DiskLayoutConfigurationSerialization(TypedDict): @dataclass -class DiskLayoutConfiguration: +class DiskLayoutConfiguration(SubConfig): config_type: DiskLayoutType device_modifications: list[DeviceModification] = field(default_factory=list) lvm_config: LvmConfiguration | None = None @@ -55,6 +65,7 @@ class DiskLayoutConfiguration: # used for pre-mounted config mountpoint: Path | None = None + @override def json(self) -> _DiskLayoutConfigurationSerialization: if self.config_type == DiskLayoutType.Pre_mount: return { @@ -78,6 +89,28 @@ class DiskLayoutConfiguration: return config + @override + def summary(self) -> list[str]: + out = [tr('{} layout').format(self.config_type.short_msg())] + + devices = set(mod.device_path for mod in self.device_modifications) + + if devices: + dev_str = ', '.join(str(d) for d in devices) + out.append(tr('Devices {}').format(dev_str)) + + if self.lvm_config is not None: + out.append(tr('LVM set up')) + + if self.disk_encryption is not None: + out.append(tr('{} encryption').format(self.disk_encryption.encryption_type.type_to_text())) + + if self.btrfs_options is not None: + if self.btrfs_options.snapshot_config: + out.append(tr('Btrfs snapshot "{}"').format(self.btrfs_options.snapshot_config.snapshot_type)) + + return out + @classmethod def parse_arg( cls, @@ -1321,7 +1354,7 @@ class _SnapshotConfigSerialization(TypedDict): type: str -class SnapshotType(Enum): +class SnapshotType(StrEnum): Snapper = 'Snapper' Timeshift = 'Timeshift' diff --git a/archinstall/lib/models/locale.py b/archinstall/lib/models/locale.py index 8f580989..26ab3cc0 100644 --- a/archinstall/lib/models/locale.py +++ b/archinstall/lib/models/locale.py @@ -1,12 +1,13 @@ from dataclasses import dataclass -from typing import Any, Self +from typing import Any, Self, override from archinstall.lib.locale.utils import get_kb_layout +from archinstall.lib.models.config import SubConfig from archinstall.lib.translationhandler import tr @dataclass -class LocaleConfiguration: +class LocaleConfiguration(SubConfig): kb_layout: str sys_lang: str sys_enc: str @@ -23,6 +24,7 @@ class LocaleConfiguration: layout = 'us' return cls(layout, 'en_US.UTF-8', 'UTF-8') + @override def json(self) -> dict[str, str]: return { 'kb_layout': self.kb_layout, @@ -31,6 +33,15 @@ class LocaleConfiguration: 'console_font': self.console_font, } + @override + def summary(self) -> list[str]: + return [ + tr('Keyboard layout "{}"').format(self.kb_layout), + tr('Locale language "{}"').format(self.sys_lang), + tr('Locale encoding "{}"').format(self.sys_enc), + tr('Console font "{}"').format(self.console_font), + ] + def preview(self) -> str: output = '{}: {}\n'.format(tr('Keyboard layout'), self.kb_layout) output += '{}: {}\n'.format(tr('Locale language'), self.sys_lang) diff --git a/archinstall/lib/models/mirrors.py b/archinstall/lib/models/mirrors.py index 0a596c13..1d678328 100644 --- a/archinstall/lib/models/mirrors.py +++ b/archinstall/lib/models/mirrors.py @@ -9,9 +9,11 @@ from typing import TYPE_CHECKING, Any, Self, TypedDict, override from pydantic import BaseModel, ValidationInfo, field_validator, model_validator +from archinstall.lib.log import debug +from archinstall.lib.models.config import SubConfig from archinstall.lib.models.packages import Repository from archinstall.lib.networking import DownloadTimer, ping -from archinstall.lib.output import debug +from archinstall.lib.translationhandler import tr if TYPE_CHECKING: from archinstall.lib.mirror.mirror_handler import MirrorListHandler @@ -236,7 +238,7 @@ class _MirrorConfigurationSerialization(TypedDict): @dataclass -class MirrorConfiguration: +class MirrorConfiguration(SubConfig): mirror_regions: list[MirrorRegion] = field(default_factory=list) custom_servers: list[CustomServer] = field(default_factory=list) optional_repositories: list[Repository] = field(default_factory=list) @@ -250,6 +252,7 @@ class MirrorConfiguration: def custom_server_urls(self) -> str: return '\n'.join(s.url for s in self.custom_servers) + @override def json(self) -> _MirrorConfigurationSerialization: regions = {} for m in self.mirror_regions: @@ -262,6 +265,24 @@ class MirrorConfiguration: 'custom_repositories': [c.json() for c in self.custom_repositories], } + @override + def summary(self) -> list[str]: + out: list[str] = [] + + if self.mirror_regions: + out.append(tr('Mirror regions "{}"').format(', '.join(m.name for m in self.mirror_regions))) + + if self.optional_repositories: + out.append(tr('Optional repositories "{}"').format(', '.join(r.value for r in self.optional_repositories))) + + if self.custom_servers: + out.append(tr('Custom servers set up')) + + if self.custom_repositories: + out.append(tr('Custom repositories set up')) + + return out + def custom_servers_config(self) -> str: config = '' diff --git a/archinstall/lib/models/network.py b/archinstall/lib/models/network.py index 71f3dca2..bcbd288a 100644 --- a/archinstall/lib/models/network.py +++ b/archinstall/lib/models/network.py @@ -3,7 +3,8 @@ from dataclasses import dataclass, field from enum import Enum from typing import NotRequired, Self, TypedDict, override -from archinstall.lib.output import debug +from archinstall.lib.log import debug +from archinstall.lib.models.config import SubConfig from archinstall.lib.translationhandler import tr @@ -11,6 +12,7 @@ class NicType(Enum): ISO = 'iso' NM = 'nm' NM_IWD = 'nm_iwd' + IWD = 'iwd' MANUAL = 'manual' def display_msg(self) -> str: @@ -21,6 +23,8 @@ class NicType(Enum): return tr('Use Network Manager (default backend)') case NicType.NM_IWD: return tr('Use Network Manager (iwd backend)') + case NicType.IWD: + return tr('Use standalone iwd') case NicType.MANUAL: return tr('Manual configuration') @@ -103,10 +107,11 @@ class _NetworkConfigurationSerialization(TypedDict): @dataclass -class NetworkConfiguration: +class NetworkConfiguration(SubConfig): type: NicType nics: list[Nic] = field(default_factory=list) + @override def json(self) -> _NetworkConfigurationSerialization: config: _NetworkConfigurationSerialization = {'type': self.type.value} if self.nics: @@ -114,6 +119,10 @@ class NetworkConfiguration: return config + @override + def summary(self) -> str: + return self.type.display_msg() + @classmethod def parse_arg(cls, config: _NetworkConfigurationSerialization) -> Self | None: nic_type = config.get('type', None) @@ -125,6 +134,10 @@ class NetworkConfiguration: return cls(NicType.ISO) case NicType.NM: return cls(NicType.NM) + case NicType.NM_IWD: + return cls(NicType.NM_IWD) + case NicType.IWD: + return cls(NicType.IWD) case NicType.MANUAL: nics_arg = config.get('nics', []) if nics_arg: diff --git a/archinstall/lib/models/pacman.py b/archinstall/lib/models/pacman.py index 5d271ea9..004dfbc3 100644 --- a/archinstall/lib/models/pacman.py +++ b/archinstall/lib/models/pacman.py @@ -1,6 +1,7 @@ from dataclasses import dataclass -from typing import Self, TypedDict +from typing import Self, TypedDict, override +from archinstall.lib.models.config import SubConfig from archinstall.lib.translationhandler import tr @@ -10,7 +11,7 @@ class PacmanConfigSerialization(TypedDict): @dataclass -class PacmanConfiguration: +class PacmanConfiguration(SubConfig): parallel_downloads: int = 5 color: bool = True @@ -18,12 +19,19 @@ class PacmanConfiguration: def default(cls) -> Self: return cls() + @override def json(self) -> PacmanConfigSerialization: return { 'parallel_downloads': self.parallel_downloads, 'color': self.color, } + @override + def summary(self) -> str | None: + if self.color: + return tr('Color enabled') + return None + def preview(self) -> str: color_str = str(self.color) output = '{}: {}\n'.format(tr('Parallel Downloads'), self.parallel_downloads) diff --git a/archinstall/lib/models/profile.py b/archinstall/lib/models/profile.py index e7ae8c8c..fa890a1e 100644 --- a/archinstall/lib/models/profile.py +++ b/archinstall/lib/models/profile.py @@ -1,8 +1,10 @@ from dataclasses import dataclass -from typing import TYPE_CHECKING, Self, TypedDict +from typing import TYPE_CHECKING, Self, TypedDict, override from archinstall.default_profiles.profile import GreeterType, Profile from archinstall.lib.hardware import GfxDriver +from archinstall.lib.models.config import SubConfig +from archinstall.lib.translationhandler import tr if TYPE_CHECKING: from archinstall.lib.profile.profiles_handler import ProfileSerialization @@ -15,11 +17,12 @@ class _ProfileConfigurationSerialization(TypedDict): @dataclass -class ProfileConfiguration: +class ProfileConfiguration(SubConfig): profile: Profile | None = None gfx_driver: GfxDriver | None = None greeter: GreeterType | None = None + @override def json(self) -> _ProfileConfigurationSerialization: from archinstall.lib.profile.profiles_handler import profile_handler @@ -29,6 +32,23 @@ class ProfileConfiguration: 'greeter': self.greeter.value if self.greeter else None, } + @override + def summary(self) -> list[str] | None: + out: list[str] = [] + + if self.profile: + out.append(self.profile.name) + + if self.gfx_driver: + out.append(tr('{} grphics driver').format(self.gfx_driver.value)) + + if self.greeter: + out.append(tr('{} greeter').format(self.greeter.value)) + + return out + + return None + @classmethod def parse_arg(cls, arg: _ProfileConfigurationSerialization) -> Self: from archinstall.lib.profile.profiles_handler import profile_handler diff --git a/archinstall/lib/network/network_handler.py b/archinstall/lib/network/network_handler.py index 13548584..09d2750c 100644 --- a/archinstall/lib/network/network_handler.py +++ b/archinstall/lib/network/network_handler.py @@ -1,3 +1,5 @@ +import textwrap + from archinstall.lib.installer import Installer from archinstall.lib.models.network import NetworkConfiguration, NicType from archinstall.lib.models.profile import ProfileConfiguration @@ -32,6 +34,13 @@ def install_network_config( _configure_nm_iwd(installation) installation.disable_service('iwd.service') + case NicType.IWD: + installation.add_additional_packages(['iwd']) + _configure_iwd_standalone(installation) + installation.enable_service('iwd.service') + installation.enable_service('systemd-networkd.service') + installation.enable_service('systemd-resolved.service') + case NicType.MANUAL: for nic in network_config.nics: installation.configure_nic(nic) @@ -45,3 +54,36 @@ def _configure_nm_iwd(installation: Installer) -> None: iwd_backend_conf = nm_conf_dir / 'wifi_backend.conf' _ = iwd_backend_conf.write_text('[device]\nwifi.backend=iwd\n') + + +def _configure_iwd_standalone(installation: Installer) -> None: + # iwd manages wireless only; systemd-networkd handles wired DHCP. + iwd_conf_dir = installation.target / 'etc/iwd' + iwd_conf_dir.mkdir(parents=True, exist_ok=True) + + main_conf = iwd_conf_dir / 'main.conf' + main_conf_content = textwrap.dedent("""\ + [General] + EnableNetworkConfiguration=true + + [Network] + NameResolvingService=systemd + """) + _ = main_conf.write_text(main_conf_content) + + networkd_dir = installation.target / 'etc/systemd/network' + networkd_dir.mkdir(parents=True, exist_ok=True) + wired_conf = networkd_dir / '20-wired.network' + wired_conf_content = textwrap.dedent("""\ + [Match] + Type=ether + Kind=!* + + [Network] + DHCP=yes + """) + _ = wired_conf.write_text(wired_conf_content) + + resolv = installation.target / 'etc/resolv.conf' + resolv.unlink(missing_ok=True) + resolv.symlink_to('/run/systemd/resolve/stub-resolv.conf') diff --git a/archinstall/lib/network/network_menu.py b/archinstall/lib/network/network_menu.py index 120af19e..88c26dba 100644 --- a/archinstall/lib/network/network_menu.py +++ b/archinstall/lib/network/network_menu.py @@ -202,6 +202,8 @@ async def select_network(preset: NetworkConfiguration | None) -> NetworkConfigur return NetworkConfiguration(NicType.NM) case NicType.NM_IWD: return NetworkConfiguration(NicType.NM_IWD) + case NicType.IWD: + return NetworkConfiguration(NicType.IWD) case NicType.MANUAL: preset_nics = preset.nics if preset else [] nics = await ManualNetworkConfig(tr('Configure interfaces'), preset_nics).show() diff --git a/archinstall/lib/network/wifi_handler.py b/archinstall/lib/network/wifi_handler.py index 4c858601..b5590343 100644 --- a/archinstall/lib/network/wifi_handler.py +++ b/archinstall/lib/network/wifi_handler.py @@ -5,9 +5,9 @@ from typing import assert_never, override from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import SysCallError +from archinstall.lib.log import debug from archinstall.lib.models.network import WifiConfiguredNetwork, WifiNetwork from archinstall.lib.network.wpa_supplicant import WpaSupplicantConfig -from archinstall.lib.output import debug from archinstall.lib.translationhandler import tr from archinstall.tui.components import ConfirmationScreen, InputScreen, InstanceRunnable, LoadingScreen, NotifyScreen, TableSelectionScreen, tui from archinstall.tui.menu_item import MenuItem, MenuItemGroup diff --git a/archinstall/lib/network/wpa_supplicant.py b/archinstall/lib/network/wpa_supplicant.py index 935e9b4d..17ed3227 100644 --- a/archinstall/lib/network/wpa_supplicant.py +++ b/archinstall/lib/network/wpa_supplicant.py @@ -1,8 +1,8 @@ from dataclasses import dataclass, field from pathlib import Path +from archinstall.lib.log import debug from archinstall.lib.models.network import WifiNetwork -from archinstall.lib.output import debug @dataclass diff --git a/archinstall/lib/networking.py b/archinstall/lib/networking.py index e950a697..97701e89 100644 --- a/archinstall/lib/networking.py +++ b/archinstall/lib/networking.py @@ -13,7 +13,7 @@ from urllib.parse import urlencode from urllib.request import urlopen from archinstall.lib.exceptions import DownloadTimeout, SysCallError -from archinstall.lib.output import debug, error, info +from archinstall.lib.log import debug, error, info from archinstall.lib.pacman.pacman import Pacman diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py deleted file mode 100644 index 3a972dfb..00000000 --- a/archinstall/lib/output.py +++ /dev/null @@ -1,385 +0,0 @@ -import logging -import os -import sys -import urllib.error -import urllib.request -from collections.abc import Callable -from dataclasses import asdict, is_dataclass -from datetime import UTC, datetime -from enum import Enum -from pathlib import Path -from typing import TYPE_CHECKING, Any - -from archinstall.lib.utils.encoding import unicode_ljust, unicode_rjust - -if TYPE_CHECKING: - from _typeshed import DataclassInstance - - -class FormattedOutput: - @staticmethod - def _get_values( - o: DataclassInstance, - class_formatter: str | Callable | None = None, # type: ignore[type-arg] - filter_list: list[str] = [], - ) -> dict[str, Any]: - """ - the original values returned a dataclass as dict thru the call to some specific methods - this version allows thru the parameter class_formatter to call a dynamically selected formatting method. - Can transmit a filter list to the class_formatter, - """ - if class_formatter: - # if invoked per reference it has to be a standard function or a classmethod. - # A method of an instance does not make sense - if callable(class_formatter): - return class_formatter(o, filter_list) - # if is invoked by name we restrict it to a method of the class. No need to mess more - elif hasattr(o, class_formatter) and callable(getattr(o, class_formatter)): - func = getattr(o, class_formatter) - return func(filter_list) - - raise ValueError('Unsupported formatting call') - elif hasattr(o, 'table_data'): - return o.table_data() - elif hasattr(o, 'json'): - return o.json() - elif is_dataclass(o): - return asdict(o) - else: - return o.__dict__ # type: ignore[unreachable] - - @classmethod - def as_table( - cls, - obj: list[Any], - class_formatter: str | Callable | None = None, # type: ignore[type-arg] - filter_list: list[str] = [], - capitalize: bool = False, - ) -> str: - """variant of as_table (subtly different code) which has two additional parameters - filter which is a list of fields which will be shown - class_formatter a special method to format the outgoing data - - A general comment, the format selected for the output (a string where every data record is separated by newline) - is for compatibility with a print statement - As_table_filter can be a drop in replacement for as_table - """ - raw_data = [cls._get_values(o, class_formatter, filter_list) for o in obj] - - # determine the maximum column size - column_width: dict[str, int] = {} - for o in raw_data: - for k, v in o.items(): - if not filter_list or k in filter_list: - column_width.setdefault(k, 0) - column_width[k] = max([column_width[k], len(str(v)), len(k)]) - - if not filter_list: - filter_list = list(column_width.keys()) - - # create the header lines - output = '' - key_list = [] - for key in filter_list: - width = column_width[key] - key = key.replace('!', '').replace('_', ' ') - - if capitalize: - key = key.capitalize() - - key_list.append(unicode_ljust(key, width)) - - output += ' | '.join(key_list) + '\n' - output += '-' * len(output) + '\n' - - # create the data lines - for record in raw_data: - obj_data = [] - for key in filter_list: - width = column_width.get(key, len(key)) - value = record.get(key, '') - - if '!' in key: - value = '*' * len(value) - - if isinstance(value, (int, float)) or (isinstance(value, str) and value.isnumeric()): - obj_data.append(unicode_rjust(str(value), width)) - else: - obj_data.append(unicode_ljust(str(value), width)) - - output += ' | '.join(obj_data) + '\n' - - return output - - @staticmethod - def as_columns(entries: list[str], cols: int) -> str: - """ - Will format a list into a given number of columns - """ - chunks = [] - output = '' - - for i in range(0, len(entries), cols): - chunks.append(entries[i : i + cols]) - - for row in chunks: - out_fmt = '{: <30} ' * len(row) - output += out_fmt.format(*row) + '\n' - - return output - - -class Journald: - @staticmethod - def log(message: str, level: int = logging.DEBUG) -> None: - try: - import systemd.journal # type: ignore[import-not-found] - except ModuleNotFoundError: - return - - log_adapter = logging.getLogger('archinstall') - log_fmt = logging.Formatter('[%(levelname)s]: %(message)s') - log_ch = systemd.journal.JournalHandler() - log_ch.setFormatter(log_fmt) - log_adapter.addHandler(log_ch) - log_adapter.setLevel(logging.DEBUG) - - log_adapter.log(level, message) - - -class Logger: - def __init__(self, path: Path = Path('/var/log/archinstall')) -> None: - self._path = path - - @property - def path(self) -> Path: - return self._path / 'install.log' - - @property - def directory(self) -> Path: - return self._path - - def _check_permissions(self) -> None: - log_file = self.path - - try: - self._path.mkdir(exist_ok=True, parents=True) - log_file.touch(exist_ok=True) - - with log_file.open('a') as f: - f.write('') - except PermissionError: - # Fallback to creating the log file in the current folder - logger._path = Path('./').absolute() - - warn(f'Not enough permission to place log file at {log_file}, creating it in {logger.path} instead') - - def log(self, level: int, content: str) -> None: - self._check_permissions() - - with self.path.open('a') as f: - ts = _timestamp() - level_name = logging.getLevelName(level) - f.write(f'[{ts}] - {level_name} - {content}\n') - - -logger = Logger() - - -def _supports_color() -> bool: - """ - Found first reference here: - https://stackoverflow.com/questions/7445658/how-to-detect-if-the-console-does-support-ansi-escape-codes-in-python - And re-used this: - https://github.com/django/django/blob/master/django/core/management/color.py#L12 - - Return True if the running system's terminal supports color, - and False otherwise. - """ - supported_platform = sys.platform != 'win32' or 'ANSICON' in os.environ - - # isatty is not always implemented, #6223. - is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() - return supported_platform and is_a_tty - - -class Font(Enum): - bold = '1' - italic = '3' - underscore = '4' - blink = '5' - reverse = '7' - conceal = '8' - - -def _stylize_output( - text: str, - fg: str, - bg: str | None, - reset: bool, - font: list[Font] = [], -) -> str: - """ - Heavily influenced by: - https://github.com/django/django/blob/ae8338daf34fd746771e0678081999b656177bae/django/utils/termcolors.py#L13 - Color options here: - https://askubuntu.com/questions/528928/how-to-do-underline-bold-italic-strikethrough-color-background-and-size-i - - Adds styling to a text given a set of color arguments. - """ - colors = { - 'black': '0', - 'red': '1', - 'green': '2', - 'yellow': '3', - 'blue': '4', - 'magenta': '5', - 'cyan': '6', - 'white': '7', - 'teal': '8;5;109', # Extended 256-bit colors (not always supported) - 'orange': '8;5;208', # https://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#256-colors - 'darkorange': '8;5;202', - 'gray': '8;5;246', - 'grey': '8;5;246', - 'darkgray': '8;5;240', - 'lightgray': '8;5;256', - } - - foreground = {key: f'3{colors[key]}' for key in colors} - background = {key: f'4{colors[key]}' for key in colors} - code_list = [] - - if text == '' and reset: - return '\x1b[0m' - - code_list.append(foreground[str(fg)]) - - if bg: - code_list.append(background[str(bg)]) - - for o in font: - code_list.append(o.value) - - ansi = ';'.join(code_list) - - return f'\033[{ansi}m{text}\033[0m' - - -def info( - *msgs: str, - level: int = logging.INFO, - fg: str = 'white', - bg: str | None = None, - reset: bool = False, - font: list[Font] = [], -) -> None: - log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) - - -def _timestamp() -> str: - now = datetime.now(tz=UTC) - return now.strftime('%Y-%m-%d %H:%M:%S') - - -def debug( - *msgs: str, - level: int = logging.DEBUG, - fg: str = 'white', - bg: str | None = None, - reset: bool = False, - font: list[Font] = [], -) -> None: - log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) - - -def error( - *msgs: str, - level: int = logging.ERROR, - fg: str = 'red', - bg: str | None = None, - reset: bool = False, - font: list[Font] = [], -) -> None: - log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) - - -def warn( - *msgs: str, - level: int = logging.WARNING, - fg: str = 'yellow', - bg: str | None = None, - reset: bool = False, - font: list[Font] = [], -) -> None: - log(*msgs, level=level, fg=fg, bg=bg, reset=reset, font=font) - - -def log( - *msgs: str, - level: int = logging.INFO, - fg: str = 'white', - bg: str | None = None, - reset: bool = False, - font: list[Font] = [], -) -> None: - text = ' '.join(str(x) for x in msgs) - - logger.log(level, text) - - # Attempt to colorize the output if supported - # Insert default colors and override with **kwargs - if _supports_color(): - text = _stylize_output(text, fg, bg, reset, font) - - Journald.log(text, level=level) - - if level != logging.DEBUG: - print(text) - - -def share_install_log( - paste_url: str = 'https://paste.rs', - max_size: int = 10 * 1024 * 1024, - confirm: Callable[[str], bool] = lambda _: True, -) -> int: - log_path = logger.path - - if not log_path.exists(): - info(f'Log file not found: {log_path}') - return 1 - - size = log_path.stat().st_size - if size == 0: - info(f'Log file is empty: {log_path}') - return 1 - - if size > max_size: - info(f'Log file exceeds {max_size} bytes, uploading last {max_size} bytes') - content = log_path.read_bytes()[-max_size:] - else: - content = log_path.read_bytes() - - header = f'About to upload {log_path} ({len(content)} bytes) to {paste_url}\n\n' - header += 'The log may contain hostname, mirror URLs, package list and partition layout.\n' - header += 'The uploaded paste is public.\n\n' - header += 'Continue?' - - if not confirm(header): - info('Cancelled.') - return 1 - - try: - req = urllib.request.Request(paste_url, data=content) - with urllib.request.urlopen(req) as response: - url = response.read().decode().strip() - except urllib.error.URLError as e: - info(f'Upload failed: {e}') - return 1 - - if not url.startswith('http'): - info(f'Unexpected response from {paste_url}: {url[:200]!r}') - return 1 - - # raw print so the URL is pipe-friendly (no ANSI colors, no log prefix) - print(url) - return 0 diff --git a/archinstall/lib/packages/packages.py b/archinstall/lib/packages/packages.py index a7422986..5b276f76 100644 --- a/archinstall/lib/packages/packages.py +++ b/archinstall/lib/packages/packages.py @@ -1,9 +1,9 @@ from functools import lru_cache from archinstall.lib.exceptions import SysCallError +from archinstall.lib.log import debug from archinstall.lib.menu.helpers import Loading, Notify, Selection from archinstall.lib.models.packages import AvailablePackage, LocalPackage, PackageGroup, Repository -from archinstall.lib.output import debug from archinstall.lib.pacman.pacman import Pacman from archinstall.lib.translationhandler import tr from archinstall.tui.menu_item import MenuItem, MenuItemGroup diff --git a/archinstall/lib/packages/util.py b/archinstall/lib/packages/util.py index 335d312e..134592bb 100644 --- a/archinstall/lib/packages/util.py +++ b/archinstall/lib/packages/util.py @@ -1,6 +1,6 @@ from functools import lru_cache -from archinstall.lib.output import debug +from archinstall.lib.log import debug from archinstall.lib.packages.packages import check_package_upgrade diff --git a/archinstall/lib/pacman/pacman.py b/archinstall/lib/pacman/pacman.py index 83f8b40d..c78f6145 100644 --- a/archinstall/lib/pacman/pacman.py +++ b/archinstall/lib/pacman/pacman.py @@ -5,7 +5,7 @@ from pathlib import Path from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import RequirementError -from archinstall.lib.output import error, info, warn +from archinstall.lib.log import error, info, warn from archinstall.lib.pathnames import PACMAN_CONF from archinstall.lib.plugins import plugins from archinstall.lib.translationhandler import tr diff --git a/archinstall/lib/plugins.py b/archinstall/lib/plugins.py index 919fcf23..ac8383b1 100644 --- a/archinstall/lib/plugins.py +++ b/archinstall/lib/plugins.py @@ -7,7 +7,7 @@ import urllib.request from importlib import metadata from pathlib import Path -from archinstall.lib.output import error, info, warn +from archinstall.lib.log import error, info, warn from archinstall.lib.version import get_version plugins = {} diff --git a/archinstall/lib/profile/profiles_handler.py b/archinstall/lib/profile/profiles_handler.py index c75f95c0..d937a520 100644 --- a/archinstall/lib/profile/profiles_handler.py +++ b/archinstall/lib/profile/profiles_handler.py @@ -9,9 +9,9 @@ from typing import TYPE_CHECKING, NotRequired, TypedDict from archinstall.default_profiles.profile import CustomSetting, GreeterType, Profile from archinstall.lib.hardware import GfxDriver, GfxPackage +from archinstall.lib.log import debug, error, info from archinstall.lib.models.profile import ProfileConfiguration from archinstall.lib.networking import fetch_data_from_url -from archinstall.lib.output import debug, error, info from archinstall.lib.translationhandler import tr if TYPE_CHECKING: diff --git a/archinstall/lib/translationhandler.py b/archinstall/lib/translationhandler.py index 093ca6de..c2736f35 100644 --- a/archinstall/lib/translationhandler.py +++ b/archinstall/lib/translationhandler.py @@ -9,7 +9,7 @@ from typing import override from archinstall.lib.command import SysCommand from archinstall.lib.exceptions import SysCallError -from archinstall.lib.output import debug +from archinstall.lib.log import debug from archinstall.lib.utils.util import running_from_iso diff --git a/archinstall/lib/utils/format.py b/archinstall/lib/utils/format.py new file mode 100644 index 00000000..2ac8c377 --- /dev/null +++ b/archinstall/lib/utils/format.py @@ -0,0 +1,148 @@ +from collections.abc import Callable +from dataclasses import asdict, is_dataclass +from typing import TYPE_CHECKING, Any + +from archinstall.lib.utils.encoding import unicode_ljust, unicode_rjust +from archinstall.tui.rich import BaseRichTable + +if TYPE_CHECKING: + from _typeshed import DataclassInstance + + +def as_key_value_pair( + entries: dict[str, str | list[str] | bool], + ignore_empty: bool = True, +) -> str: + """ + Formats key-values as a Rich Table: + key1 : value1 + key2 : value2 + ... + """ + table = BaseRichTable() + table.add_column('key', style='bold', no_wrap=True) + table.add_column('value', style='white', max_width=70) + + for label, value in entries.items(): + if ignore_empty and not value: + continue + + if isinstance(value, bool): + value = 'Yes' if value else 'No' + + if isinstance(value, list): + value = '\n '.join(str(val) for val in value) + + table.add_row(label.title(), f': {value}') + + return table.stringify() + + +def as_columns(entries: list[str], cols: int) -> str: + """ + Will format a list into a given number of columns + """ + chunks: list[list[str]] = [] + output = '' + + for i in range(0, len(entries), cols): + chunks.append(entries[i : i + cols]) + + for row in chunks: + out_fmt = '{: <30} ' * len(row) + output += out_fmt.format(*row) + '\n' + + return output + + +def _get_values( + o: DataclassInstance, + class_formatter: str | Callable | None = None, # type: ignore[type-arg] # pyright: ignore[reportMissingTypeArgument] + filter_list: list[str] = [], +) -> dict[str, Any]: + """ + the original values returned a dataclass as dict thru the call to some specific methods + this version allows thru the parameter class_formatter to call a dynamically selected formatting method. + Can transmit a filter list to the class_formatter, + """ + if class_formatter: + # if invoked per reference it has to be a standard function or a classmethod. + # A method of an instance does not make sense + if callable(class_formatter): + return class_formatter(o, filter_list) + # if is invoked by name we restrict it to a method of the class. No need to mess more + elif hasattr(o, class_formatter) and callable(getattr(o, class_formatter)): + func = getattr(o, class_formatter) + return func(filter_list) + + raise ValueError('Unsupported formatting call') + elif hasattr(o, 'table_data'): + return o.table_data() + elif hasattr(o, 'json'): + return o.json() + elif is_dataclass(o): + return asdict(o) + else: + return o.__dict__ # type: ignore[unreachable] + + +def as_table( + obj: list[Any], + class_formatter: str | Callable | None = None, # type: ignore[type-arg] + filter_list: list[str] = [], + capitalize: bool = False, +) -> str: + """variant of as_table (subtly different code) which has two additional parameters + filter which is a list of fields which will be shown + class_formatter a special method to format the outgoing data + + A general comment, the format selected for the output (a string where every data record is separated by newline) + is for compatibility with a print statement + As_table_filter can be a drop in replacement for as_table + """ + raw_data = [_get_values(o, class_formatter, filter_list) for o in obj] + + # determine the maximum column size + column_width: dict[str, int] = {} + for o in raw_data: + for k, v in o.items(): + if not filter_list or k in filter_list: + column_width.setdefault(k, 0) + column_width[k] = max([column_width[k], len(str(v)), len(k)]) + + if not filter_list: + filter_list = list(column_width.keys()) + + # create the header lines + output = '' + key_list = [] + for key in filter_list: + width = column_width[key] + key = key.replace('!', '').replace('_', ' ') + + if capitalize: + key = key.capitalize() + + key_list.append(unicode_ljust(key, width)) + + output += ' | '.join(key_list) + '\n' + output += '-' * len(output) + '\n' + + # create the data lines + for record in raw_data: + obj_data = [] + for key in filter_list: + width = column_width.get(key, len(key)) + value = record.get(key, '') + + if '!' in key: + value = '*' * len(value) + + if isinstance(value, (int, float)) or (isinstance(value, str) and value.isnumeric()): + obj_data.append(unicode_rjust(str(value), width)) + else: + obj_data.append(unicode_ljust(str(value), width)) + + output += ' | '.join(obj_data) + '\n' + + return output diff --git a/archinstall/lib/utils/util.py b/archinstall/lib/utils/util.py index 574cc8d5..f94ca18c 100644 --- a/archinstall/lib/utils/util.py +++ b/archinstall/lib/utils/util.py @@ -1,8 +1,14 @@ import secrets import string +from datetime import UTC, datetime -from archinstall.lib.output import FormattedOutput from archinstall.lib.pathnames import ARCHISO_MOUNTPOINT +from archinstall.lib.utils.format import as_columns + + +def timestamp() -> str: + now = datetime.now(tz=UTC) + return now.strftime('%Y-%m-%d %H:%M:%S') def running_from_iso() -> bool: @@ -36,7 +42,7 @@ def format_cols(items: list[str], header: str | None = None) -> str: else: col = 4 - text += FormattedOutput.as_columns(items, col) + text += as_columns(items, col) # remove whitespaces on each row text = '\n'.join(t.strip() for t in text.split('\n')) return text diff --git a/archinstall/locales/base.pot b/archinstall/locales/base.pot index 0b08df29..4db4554c 100644 --- a/archinstall/locales/base.pot +++ b/archinstall/locales/base.pot @@ -1245,7 +1245,7 @@ msgid "Product" msgstr "" #, python-brace-format -msgid "Invalid configuration: {error}" +msgid "Invalid configuration: {}" msgstr "" msgid "Ready to install" @@ -2304,3 +2304,162 @@ msgstr "" #, python-brace-format msgid "Choose an option how to give {} access to your hardware" msgstr "" + +#, python-brace-format +msgid "About to upload \"{}\" to the publicly accessible {}" +msgstr "" + +msgid "Do you want to continue?" +msgstr "" + +#, python-brace-format +msgid "Log uploaded successfully. URL: {}" +msgstr "" + +msgid "Failed to upload log." +msgstr "" + +msgid "ArchInstall Language" +msgstr "" + +msgid "Version" +msgstr "" + +msgid "Installation Script" +msgstr "" + +msgid "Application" +msgstr "" + +msgid "Services" +msgstr "" + +msgid "Custom commands" +msgstr "" + +msgid "Users" +msgstr "" + +msgid "Root encrypted password" +msgstr "" + +msgid "Zram enabled" +msgstr "" + +#, python-brace-format +msgid "Zram algorithm {}" +msgstr "" + +msgid "Bluetooth enabled" +msgstr "" + +#, python-brace-format +msgid "Audio server \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Power management \"{}\"" +msgstr "" + +msgid "Print service enabled" +msgstr "" + +#, python-brace-format +msgid "Firewall \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Extra fonts \"{}\"" +msgstr "" + +msgid "Root password set" +msgstr "" + +#, python-brace-format +msgid "Configured {} user(s)" +msgstr "" + +msgid "U2F set up" +msgstr "" + +#, python-brace-format +msgid "Bootloader \"{}\"" +msgstr "" + +msgid "UKI enabled" +msgstr "" + +msgid "Default" +msgstr "" + +msgid "Manual" +msgstr "" + +msgid "Pre-mount" +msgstr "" + +#, python-brace-format +msgid "{} layout" +msgstr "" + +#, python-brace-format +msgid "Devices {}" +msgstr "" + +msgid "LVM set up" +msgstr "" + +#, python-brace-format +msgid "{} encryption" +msgstr "" + +#, python-brace-format +msgid "Btrfs snapshot \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Keyboard layout \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Locale language \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Locale encoding \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Console font \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Mirror regions \"{}\"" +msgstr "" + +#, python-brace-format +msgid "Optional repositories \"{}\"" +msgstr "" + +msgid "Custom servers set up" +msgstr "" + +msgid "Custom repositories set up" +msgstr "" + +msgid "Use standalone iwd" +msgstr "" + +msgid "Color enabled" +msgstr "" + +#, python-brace-format +msgid "{} grphics driver" +msgstr "" + +#, python-brace-format +msgid "{} greeter" +msgstr "" + +msgid "Enter a repository name" +msgstr "" diff --git a/archinstall/locales/fi/LC_MESSAGES/base.po b/archinstall/locales/fi/LC_MESSAGES/base.po index 31cf6af2..9534151e 100644 --- a/archinstall/locales/fi/LC_MESSAGES/base.po +++ b/archinstall/locales/fi/LC_MESSAGES/base.po @@ -2190,7 +2190,7 @@ msgstr "Valittu työpöydän profiili vaati tavallisen käyttäjän kirjautumise #, python-brace-format msgid "Environment type: {} {}" -msgstr "Ympäristötyyppi: {}" +msgstr "Ympäristötyyppi: {} {}" msgid "Input cannot be empty" msgstr "Syöttö ei voi olla tyhjä" @@ -2245,4 +2245,4 @@ msgstr "Määritetään U2F laitetta käyttäjälle: {}" #, python-brace-format msgid "Default: {}ms, Recommended range: 1000-60000" -msgstr "Oletusarvo: 10000ms, suositeltu 1000-60000ms" +msgstr "Oletusarvo: {}ms, suositeltu 1000-60000ms" diff --git a/archinstall/locales/hi/LC_MESSAGES/base.po b/archinstall/locales/hi/LC_MESSAGES/base.po index 9d64d477..3cfe309f 100644 --- a/archinstall/locales/hi/LC_MESSAGES/base.po +++ b/archinstall/locales/hi/LC_MESSAGES/base.po @@ -1502,9 +1502,6 @@ msgstr "सक्षम" msgid "Disabled" msgstr "अक्षम" -msgid "Please submit this issue (and file) to https://github.com/archlinux/archinstall/issues" -msgstr "कृपया इस समस्या (और फ़ाइल) को https://github.com/archlinux/archinstall/issues पर सबमिट करें।" - msgid "Mirror name" msgstr "मिरर का नाम" diff --git a/archinstall/locales/it/LC_MESSAGES/base.mo b/archinstall/locales/it/LC_MESSAGES/base.mo index 79d934d4..a4166e67 100644 Binary files a/archinstall/locales/it/LC_MESSAGES/base.mo and b/archinstall/locales/it/LC_MESSAGES/base.mo differ diff --git a/archinstall/locales/it/LC_MESSAGES/base.po b/archinstall/locales/it/LC_MESSAGES/base.po index 55585263..f46e8a73 100644 --- a/archinstall/locales/it/LC_MESSAGES/base.po +++ b/archinstall/locales/it/LC_MESSAGES/base.po @@ -2,7 +2,7 @@ msgid "" msgstr "" "Project-Id-Version: \n" "POT-Creation-Date: \n" -"PO-Revision-Date: 2026-04-12 10:26+0200\n" +"PO-Revision-Date: 2026-05-16 12:52+0200\n" "Last-Translator: Van Matten\n" "Language-Team: Alessio Cuccovillo , Van Matten\n" "Language: it\n" @@ -56,7 +56,7 @@ msgid "Only packages such as base, base-devel, linux, linux-firmware, efibootmgr msgstr "Vengono installati solo pacchetti come base, base-devel, linux, linux-firmware, efibootmgr e pacchetti di profilo opzionali." msgid "Note: base-devel is no longer installed by default. Add it here if you need build tools." -msgstr "Nota: base-devel non è più installato di default. Aggiungilo qui se ti servono i build tools." +msgstr "Nota: base-devel non è più installato come predefinito. Aggiungilo qui se ti servono i build tools." msgid "If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt." msgstr "Se desideri un browser web, come Firefox o Chromium, puoi specificarlo nel seguente prompt." @@ -118,7 +118,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona per indice quali partizioni eliminare" +"Seleziona per indice le partizioni da eliminare" msgid "" "{}\n" @@ -127,13 +127,13 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona per indice quale partizione montare dove" +"Seleziona per indice la partizione dove montare" msgid " * Partition mount-points are relative to inside the installation, the boot would be /boot as an example." -msgstr " * I punti di mount della partizione sono relativi all'interno dell'installazione, per esempio l'avvio sarebbe /boot." +msgstr " * I punti di montaggio della partizione sono relativi all'interno dell'installazione, per esempio l'avvio sarebbe /boot." msgid "Select where to mount partition (leave blank to remove mountpoint): " -msgstr "Seleziona dove montare la partizione (lascia vuoto per rimuovere il punto di mount): " +msgstr "Seleziona dove montare la partizione (lascia vuoto per rimuovere il punto di montaggio): " msgid "" "{}\n" @@ -142,7 +142,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona quale partizione mascherare per la formattazione" +"Seleziona la partizione da mascherare per la formattazione" msgid "" "{}\n" @@ -151,7 +151,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona quale partizione contrassegnare come crittografata" +"Seleziona la partizione da contrassegnare come crittografata" msgid "" "{}\n" @@ -160,7 +160,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona quale partizione contrassegnare come avviabile" +"Seleziona la partizione da contrassegnare come avviabile" msgid "" "{}\n" @@ -169,7 +169,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona su quale partizione impostare un filesystem" +"Seleziona la partizione su cui impostare un filesystem" msgid "Enter a desired filesystem type for the partition: " msgstr "Inserisci un tipo di filesystem desiderato per la partizione: " @@ -187,7 +187,7 @@ msgid "Select what you wish to do with the selected block devices" msgstr "Seleziona cosa desideri fare con i dispositivi a blocchi selezionati" msgid "This is a list of pre-programmed profiles, they might make it easier to install things like desktop environments" -msgstr "Questo è un elenco di profili pre-programmati, che potrebbero semplificare l'installazione di elementi come gli ambienti desktop" +msgstr "Questo è un elenco di profili preprogrammati, che potrebbero semplificare l'installazione di elementi come gli ambienti desktop" msgid "Select keyboard layout" msgstr "Seleziona il layout della tastiera" @@ -196,7 +196,7 @@ msgid "Select one of the regions to download packages from" msgstr "Seleziona una delle regioni da cui scaricare i pacchetti" msgid "Select one or more hard drives to use and configure" -msgstr "Seleziona uno o più dischi rigidi da utilizzare e configurare" +msgstr "Seleziona uno o più unità da utilizzare e configurare" msgid "For the best compatibility with your AMD hardware, you may want to use either the all open-source or AMD / ATI options." msgstr "Per la migliore compatibilità con il tuo hardware AMD, potresti voler utilizzare tutte le opzioni open source o AMD / ATI." @@ -220,13 +220,13 @@ msgid "All open-source (default)" msgstr "Tutti gli open source (predefinito)" msgid "Choose which kernels to use or leave blank for default \"{}\"" -msgstr "Scegli quali kernel usare o lascia vuoto per il predefinito \"{}\"" +msgstr "Scegli i kernel da usare o lascia vuoto per il predefinito \"{}\"" msgid "Choose which locale language to use" -msgstr "Scegli quale lingua locale utilizzare" +msgstr "Scegli la lingua da usare" msgid "Choose which locale encoding to use" -msgstr "Scegli quale codifica locale utilizzare" +msgstr "Scegli la codifica da usare" msgid "Select one of the values shown below: " msgstr "Seleziona uno dei valori mostrati di seguito: " @@ -235,7 +235,7 @@ msgid "Select one or more of the options below: " msgstr "Seleziona una o più delle seguenti opzioni " msgid "Adding partition...." -msgstr "Aggiungendo la partizione...." +msgstr "Aggiunta della partizione in corso..." msgid "You need to enter a valid fs-type in order to continue. See `man parted` for valid fs-type's." msgstr "Devi inserire un tipo di filesystem valido per continuare. Vedi `man parted` per tipi di filesystem validi." @@ -253,13 +253,16 @@ msgid "Mirror region" msgstr "Regione dei mirror" msgid "Locale language" -msgstr "Lingua locale" +msgstr "Lingua" msgid "Locale encoding" -msgstr "Codifica locale" +msgstr "Codifica" + +msgid "Console font" +msgstr "Font della console" msgid "Drive(s)" -msgstr "Dischi" +msgstr "Unità" msgid "Disk layout" msgstr "Layout del disco" @@ -301,7 +304,7 @@ msgid "Automatic time sync (NTP)" msgstr "Sincronizzazione automatica dell'ora (NTP)" msgid "Install ({} config(s) missing)" -msgstr "Installa ({} configurazioni mancanti)" +msgstr "Installa ({} configurazione/i mancante/i)" msgid "" "You decided to skip harddrive selection\n" @@ -309,7 +312,7 @@ msgid "" "WARNING: Archinstall won't check the suitability of this setup\n" "Do you wish to continue?" msgstr "" -"Hai deciso di saltare la selezione del disco rigido\n" +"Hai deciso di saltare la selezione dell'unità\n" "e utilizzerà qualsiasi configurazione dell'unità montata su {} (sperimentale)\n" "ATTENZIONE: Archinstall non verificherà l'idoneità di questa configurazione\n" "Vuoi continuare?" @@ -327,7 +330,7 @@ msgid "Clear/Delete all partitions" msgstr "Cancella/Elimina tutte le partizioni" msgid "Assign mount-point for a partition" -msgstr "Assegna punto di mount per una partizione" +msgstr "Assegna punto di montaggio per una partizione" msgid "Mark/Unmark a partition to be formatted (wipes data)" msgstr "Seleziona/Deseleziona una partizione da formattare (cancella i dati)" @@ -376,7 +379,7 @@ msgid "Enter a encryption password for {}" msgstr "Inserisci una password di crittografia per {}" msgid "Enter disk encryption password (leave blank for no encryption): " -msgstr "Inserisci la password di crittografia del disco (lasciare vuoto per nessuna crittografia): " +msgstr "Inserisci la password di crittografia del disco (lascia vuoto per nessuna crittografia): " msgid "Create a required super-user with sudo privileges: " msgstr "Crea un superuser richiesto con privilegi sudo: " @@ -454,7 +457,7 @@ msgid "Pre-existing pacman lock never exited. Please clean up any existing pacma msgstr "Il lock di pacman preesistente non è mai terminato. Rimuovi ogni sessione pacman esistente prima di usare archinstall." msgid "Choose which optional additional repositories to enable" -msgstr "Scegli quali repository aggiuntivi facoltativi abilitare" +msgstr "Scegli i repository aggiuntivi facoltativi da abilitare" msgid "Add a user" msgstr "Aggiungi un utente" @@ -476,7 +479,7 @@ msgstr "" "Definisci un nuovo utente\n" msgid "User Name : " -msgstr "Nome utente : " +msgstr "Nome utente: " msgid "Should {} be a superuser (sudoer)?" msgstr "{} dovrebbe essere un superuser (sudoer)?" @@ -497,7 +500,7 @@ msgid "" msgstr "" "{}\n" "\n" -"Seleziona su quale partizione impostare i sottovolumi" +"Seleziona la partizione su cui impostare i sottovolumi" msgid "Manage btrfs subvolumes for current partition" msgstr "Gestisci i sottovolumi btrfs per la partizione corrente" @@ -518,7 +521,7 @@ msgid "Save all" msgstr "Salva tutto" msgid "Choose which configuration to save" -msgstr "Scegli quale configurazione salvare" +msgstr "Scegli la configurazione da salvare" msgid "Enter a directory for the configuration(s) to be saved: " msgstr "Inserisci una cartella in cui salvare le configurazioni: " @@ -570,7 +573,7 @@ msgid "Subvolume name " msgstr "Nome del sottovolume " msgid "Subvolume mountpoint" -msgstr "Punto di mount del sottovolume" +msgstr "Punto di montaggio del sottovolume" msgid "Subvolume options" msgstr "Opzioni del sottovolume" @@ -579,10 +582,10 @@ msgid "Save" msgstr "Salva" msgid "Subvolume name :" -msgstr "Nome del sottovolume :" +msgstr "Nome del sottovolume:" msgid "Select a mount point :" -msgstr "Seleziona un punto di mount:" +msgstr "Seleziona un punto di montaggio:" msgid "Select the desired subvolume options " msgstr "Seleziona le opzioni del sottovolume desiderate " @@ -607,10 +610,10 @@ msgid "The selected drives do not have the minimum capacity required for an auto msgstr "Le unità selezionate non hanno la capacità minima richiesta per un suggerimento automatico\n" msgid "Minimum capacity for /home partition: {}GB\n" -msgstr "Capacità minima per la partizione /home: {}GB\n" +msgstr "Capacità minima per la partizione /home: {} GB\n" msgid "Minimum capacity for Arch Linux partition: {}GB" -msgstr "Capacità minima per la partizione Arch Linux: {}GB" +msgstr "Capacità minima per la partizione Arch Linux: {} GB" msgid "Continue" msgstr "Continua" @@ -661,13 +664,13 @@ msgid "Select your desired desktop environment" msgstr "Seleziona l'ambiente desktop desiderato" msgid "A very basic installation that allows you to customize Arch Linux as you see fit." -msgstr "Un'installazione molto semplice che ti consente di personalizzare Arch Linux come meglio credi." +msgstr "Un'installazione molto semplificata che ti consente di personalizzare Arch Linux come meglio credi." msgid "Provides a selection of various server packages to install and enable, e.g. httpd, nginx, mariadb" msgstr "Fornisce una selezione di vari pacchetti server da installare e abilitare, per esempio httpd, nginx, mariadb" msgid "Choose which servers to install, if none then a minimal installation will be done" -msgstr "Scegli quali server installare, se nessuno verrà eseguita un'installazione minima" +msgstr "Scegli i server da installare, se non ne sarà selezionato nessuno, verrà eseguita un'installazione minima" msgid "Installs a minimal system as well as xorg and graphics drivers." msgstr "Installa un sistema minimo oltre a xorg e driver grafici." @@ -682,13 +685,13 @@ msgid "Are you sure you want to reset this setting?" msgstr "Sei sicuro di voler ripristinare questa impostazione?" msgid "Select one or more hard drives to use and configure\n" -msgstr "Seleziona uno o più dischi rigidi da utilizzare e configurare\n" +msgstr "Seleziona uno o più unità da utilizzare e configurare\n" msgid "Any modifications to the existing setting will reset the disk layout!" msgstr "Qualsiasi modifica all'impostazione esistente ripristinerà il layout del disco!" msgid "If you reset the harddrive selection this will also reset the current disk layout. Are you sure?" -msgstr "Se si ripristina la selezione del disco rigido, verrà ripristinato anche il layout del disco corrente. Sei sicuro?" +msgstr "Se ripristini la selezione dell'unità, verrà ripristinato anche il layout del disco corrente. Sei sicuro?" msgid "Save and exit" msgstr "Salva ed esci" @@ -741,7 +744,7 @@ msgid "Select one of the disks or skip and use /mnt as default" msgstr "Seleziona uno dei dischi o salta e usa /mnt come predefinito" msgid "Select which partitions to mark for formatting:" -msgstr "Seleziona quali partizioni contrassegnare per la formattazione:" +msgstr "Seleziona le partizioni da contrassegnare per la formattazione:" msgid "Use HSM to unlock encrypted drive" msgstr "Utilizza HSM per sbloccare l'unità crittografata" @@ -798,14 +801,14 @@ msgid "Configured {} interfaces" msgstr "Interfacce {} configurate" msgid "This option enables the number of parallel downloads that can occur during installation" -msgstr "Questa opzione consente di impostare il numero di download paralleli che possono avvenire durante l'installazione" +msgstr "Questa opzione consente di impostare il numero di download in parallelo che possono avvenire durante l'installazione" msgid "" "Enter the number of parallel downloads to be enabled.\n" " (Enter a value between 1 to {})\n" "Note:" msgstr "" -"Inserisci il numero di download paralleli da abilitare.\n" +"Inserisci il numero di download in parallelo da abilitare.\n" " (Inserisci un valore compreso tra 1 e {})\n" "Nota:" @@ -816,20 +819,33 @@ msgid " - Minimum value : 1 ( Allows 1 parallel download, allows 2 downloads a msgstr " - Valore minimo : 1 ( Consente 1 download parallelo, consente 2 download alla volta )" msgid " - Disable/Default : 0 ( Disables parallel downloading, allows only 1 download at a time )" -msgstr " - Disabilita/Predefinito : 0 ( Disabilita il download parallelo, consente solo 1 download alla volta )" +msgstr " - Disabilita/Predefinito : 0 ( Disabilita il download in parallelo, consente solo 1 download alla volta )" #, python-brace-format msgid "Invalid input! Try again with a valid input [1 to {max_downloads}, or 0 to disable]" msgstr "Input non valido! Riprova con un input valido [da 1 a {max_downloads}, o 0 per disabilitare]." msgid "Parallel Downloads" -msgstr "Download paralleli" +msgstr "Download in parallelo" + +msgid "Pacman" +msgstr "Pacman" + +msgid "Color" +msgstr "Colore" + +#, python-brace-format +msgid "Enter the number of parallel downloads (1-{})" +msgstr "Inserisci il numero di download in parallelo (1-{})" + +msgid "Enable colored output for pacman" +msgstr "Attiva l'output colorato di pacman" msgid "ESC to skip" msgstr "ESC per saltare" msgid "CTRL+C to reset" -msgstr "CTRL+C per resettare" +msgstr "CTRL+C per ripristinare" msgid "TAB to select" msgstr "TAB per selezionare" @@ -861,27 +877,27 @@ msgid "Select one or more devices to use and configure" msgstr "Seleziona uno o più dispositivi da utilizzare e configurare" msgid "If you reset the device selection this will also reset the current disk layout. Are you sure?" -msgstr "Se si ripristina la selezione del disco rigido, verrà ripristinato anche il layout del disco corrente. Sei sicuro?" +msgstr "Se ripristini la selezione del dispositivo, verrà ripristinato anche il layout del disco corrente. Sei sicuro?" msgid "Existing Partitions" msgstr "Partizioni esistenti" msgid "Select a partitioning option" -msgstr "Selezione opzione di partizionamento" +msgstr "Seleziona un'opzione di partizionamento" msgid "Enter the root directory of the mounted devices: " msgstr "Inserisci la cartella principale dei dispositivi montati: " #, python-brace-format msgid "Minimum capacity for /home partition: {}GiB\n" -msgstr "Capacità minima per la partizione /home: {}GiB\n" +msgstr "Capacità minima per la partizione /home: {} GiB\n" #, python-brace-format msgid "Minimum capacity for Arch Linux partition: {}GiB" -msgstr "Capacità minima per la partizione Arch Linux: {}GiB" +msgstr "Capacità minima per la partizione Arch Linux: {} GiB" msgid "This is a list of pre-programmed profiles_bck, they might make it easier to install things like desktop environments" -msgstr "Questo è un elenco di profili pre-programmati, che potrebbero semplificare l'installazione di elementi come gli ambienti desktop" +msgstr "Questo è un elenco di profiles_bck preprogrammati, che potrebbero semplificare l'installazione di elementi come gli ambienti desktop" msgid "Current profile selection" msgstr "Selezione profilo corrente" @@ -890,7 +906,7 @@ msgid "Remove all newly added partitions" msgstr "Elimina tutte le partizioni appena aggiunte" msgid "Assign mountpoint" -msgstr "Assegna punto di mount" +msgstr "Assegna punto di montaggio" msgid "Mark/Unmark to be formatted (wipes data)" msgstr "Seleziona/Deseleziona come da formattare (cancella i dati)" @@ -917,13 +933,13 @@ msgid "This partition is currently encrypted, to format it a filesystem has to b msgstr "Questa partizione è attualmente crittografata, per formattarla è necessario specificare un filesystem" msgid "Partition mount-points are relative to inside the installation, the boot would be /boot as an example." -msgstr "I punti di mount della partizione sono relativi all'interno dell'installazione, l'avvio sarebbe per esempio /boot." +msgstr "I punti di montaggio della partizione sono relativi all'interno dell'installazione, l'avvio sarebbe per esempio /boot." msgid "If mountpoint /boot is set, then the partition will also be marked as bootable." -msgstr "Se il punto di mount /boot è impostato, anche la partizione sarà contrassegnata come avviabile." +msgstr "Se il punto di montaggio /boot è impostato, anche la partizione sarà contrassegnata come avviabile." msgid "Mountpoint: " -msgstr "Punto di mount: " +msgstr "Punto di montaggio: " msgid "Current free sectors on device {}:" msgstr "Settori attualmente liberi sul dispositivo {}:" @@ -985,7 +1001,7 @@ msgid "Partitions to be encrypted" msgstr "Partizioni da crittografare" msgid "Select disk encryption option" -msgstr "Selezione opzione per crittografia disco" +msgstr "Seleziona un'opzione per la crittografia del disco" msgid "Select a FIDO2 device to use for HSM" msgstr "Seleziona un dispositivo FIDO2 da utilizzare per HSM" @@ -1028,7 +1044,7 @@ msgid "Back" msgstr "Indietro" msgid "Please chose which greeter to install for the chosen profiles: {}" -msgstr "Scegli quale greeter installare per i profili scelti: {}" +msgstr "Scegli il greeter da installare per i profili scelti: {}" #, python-brace-format msgid "Environment type: {}" @@ -1075,7 +1091,7 @@ msgstr "" "Seleziona un driver grafico o lascia vuoto per installare tutti i driver open source" msgid "Sway needs access to your seat (collection of hardware devices i.e. keyboard, mouse, etc)" -msgstr "Sway ha bisogno dell’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" +msgstr "Sway richiede l’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" msgid "" "\n" @@ -1093,13 +1109,13 @@ msgid "Greeter" msgstr "Greeter" msgid "Please chose which greeter to install" -msgstr "Scegli quale greeter installare" +msgstr "Scegli il greeter da installare" msgid "This is a list of pre-programmed default_profiles" msgstr "Questo è un elenco di default_profiles preprogrammati" msgid "Disk configuration" -msgstr "Configurazione disco" +msgstr "Configurazione del disco" msgid "Profiles" msgstr "Profili" @@ -1144,7 +1160,7 @@ msgid "" "Enter a directory for the configuration(s) to be saved (tab completion enabled)\n" "Save directory: " msgstr "" -"Inserisci una cartella in cui salvare le configurazioni (completamento col tasto tab abilitato)\n" +"Inserisci una cartella in cui salvare le configurazioni (completamento col tasto tab attivo)\n" "Cartella di salvataggio: " msgid "" @@ -1166,7 +1182,7 @@ msgid "Mirror regions" msgstr "Regione dei mirror" msgid " - Maximum value : {} ( Allows {} parallel downloads, allows {max_downloads+1} downloads at a time )" -msgstr " - Valore massimo : {} ( Consente {} download paralleli, consente {max_downloads+1} downloads alla volta )" +msgstr " - Valore massimo : {} ( Consente {} download in parallelo, consente {max_downloads+1} download alla volta )" msgid "Invalid input! Try again with a valid input [1 to {}, or 0 to disable]" msgstr "Input non valido! Riprova con un input valido [da 1 a {}, o 0 per disabilitare]." @@ -1208,33 +1224,48 @@ msgstr "Prodotto" msgid "Invalid configuration: {error}" msgstr "Configurazione non valida: {error}" +msgid "Ready to install" +msgstr "Pronto per l'installazione" + +msgid "Disks" +msgstr "Dischi" + +msgid "Packages" +msgstr "Pacchetti" + +msgid "Network" +msgstr "Rete" + +msgid "Locale" +msgstr "Localizzazione" + msgid "Type" msgstr "Tipo" msgid "This option enables the number of parallel downloads that can occur during package downloads" -msgstr "Questa opzione consente di impostare il numero di download paralleli che possono avvenire durante l'installazione" +msgstr "Questa opzione consente di impostare il numero di download in parallelo che possono avvenire durante l'installazione" msgid "" "Enter the number of parallel downloads to be enabled.\n" "\n" "Note:\n" msgstr "" -"Inserisci il numero di download paralleli da abilitare.\n" +"Inserisci il numero di download in parallelo da abilitare.\n" "\n" "Nota:\n" #, python-brace-format msgid " - Maximum recommended value : {} ( Allows {} parallel downloads at a time )" -msgstr " - Valore massimo raccomandato : {} ( Consente {} download paralleli)" +msgstr " - Valore massimo raccomandato : {} ( Consente {} download in parallelo)" msgid " - Disable/Default : 0 ( Disables parallel downloading, allows only 1 download at a time )\n" -msgstr " - Disabilita/Predefinito : 0 ( Disabilita il download parallelo, consente solo 1 download alla volta )\n" +msgstr " - Disabilita/Predefinito : 0 ( Disabilita il download in parallelo, consente solo 1 download alla volta )\n" msgid "Invalid input! Try again with a valid input [or 0 to disable]" msgstr "Input non valido! Riprova con un input valido [0 per disabilitare]." msgid "Hyprland needs access to your seat (collection of hardware devices i.e. keyboard, mouse, etc)" -msgstr "Hyprland ha bisogno dell’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" +msgstr "Hyprland richiede l’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" msgid "" "\n" @@ -1270,7 +1301,7 @@ msgid "Selected profiles: " msgstr "Profili selezionati: " msgid "Time synchronization not completing, while you wait - check the docs for workarounds: https://archinstall.readthedocs.io/" -msgstr "La sincronizzazione dell’orario non si sta completando, in attesa, leggi la documentazione alla ricerca di una soluzione: https://archinstall.readthedocs.io/" +msgstr "La sincronizzazione dell’orario non si sta completando, mentre aspetti leggi la documentazione alla ricerca di una soluzione: https://archinstall.readthedocs.io/" msgid "Mark/Unmark as nodatacow" msgstr "Seleziona/Deseleziona come nodatacow" @@ -1322,7 +1353,7 @@ msgid "LVM volumes to be encrypted" msgstr "Volumi LVM da crittografare" msgid "Select which LVM volumes to encrypt" -msgstr "Seleziona volumi LVM da crittografare" +msgstr "Seleziona i volumi LVM da crittografare" msgid "Default layout" msgstr "Layout predefinito" @@ -1361,7 +1392,7 @@ msgid "Seat access" msgstr "Accesso al posto" msgid "Mountpoint" -msgstr "Punto di mount" +msgstr "Punto di montaggio" msgid "HSM" msgstr "HSM" @@ -1479,7 +1510,7 @@ msgid "Directory" msgstr "Cartella" msgid "Enter a directory for the configuration(s) to be saved (tab completion enabled)" -msgstr "Inserisci una cartella in cui salvare le configurazioni (completamento col tasto tab abilitato)" +msgstr "Inserisci una cartella in cui salvare le configurazioni (completamento col tasto tab attivo)" #, python-brace-format msgid "Do you want to save the configuration file(s) to {}?" @@ -1513,7 +1544,7 @@ msgid "Choose an option to give Hyprland access to your hardware" msgstr "Scegli un’opzione per concedere a Hyprland l'accesso al tuo hardware" msgid "Additional repositories" -msgstr "Repository aggiuntive" +msgstr "Repository aggiuntivi" msgid "NTP" msgstr "NTP" @@ -1543,7 +1574,7 @@ msgid "HSM device" msgstr "Dispositivo HSM" msgid "Some packages could not be found in the repository" -msgstr "Alcuni pacchetti non sono stati trovati nella repository" +msgstr "Alcuni pacchetti non sono stati trovati nel repository" msgid "User" msgstr "Utente" @@ -1564,16 +1595,16 @@ msgid "Select any packages from the below list that should be installed addition msgstr "Seleziona dalla lista sotto i pacchetti aggiuntivi da installare" msgid "Add a custom repository" -msgstr "Aggiungi una repository personalizzata" +msgstr "Aggiungi un repository personalizzato" msgid "Change custom repository" -msgstr "Cambia repository personalizzata" +msgstr "Cambia repository personalizzato" msgid "Delete custom repository" -msgstr "Elimina repository personalizzata" +msgstr "Elimina repository personalizzato" msgid "Repository name" -msgstr "Nome repository" +msgstr "Nome del repository" msgid "Add a custom server" msgstr "Aggiungi un server personalizzato" @@ -1594,7 +1625,7 @@ msgid "Add custom servers" msgstr "Aggiungi server personalizzati" msgid "Add custom repository" -msgstr "Aggiungi repository personalizzate" +msgstr "Aggiungi repository personalizzato" msgid "Loading mirror regions..." msgstr "Caricamento regioni dei mirror in corso..." @@ -1609,7 +1640,7 @@ msgid "Custom servers" msgstr "Server personalizzati" msgid "Custom repositories" -msgstr "Repository personalizzate" +msgstr "Repository personalizzati" msgid "Only ASCII characters are supported" msgstr "Sono supportati solo caratteri ASCII" @@ -1756,7 +1787,7 @@ msgid "Toggle option" msgstr "Opzioni di attivazione" msgid "Scroll Up" -msgstr "Scorri Su" +msgstr "Scorri su" msgid "Scroll Down" msgstr "Scorri giù" @@ -1783,13 +1814,13 @@ msgid "Copy selected text" msgstr "Copia il testo selezionato" msgid "labwc needs access to your seat (collection of hardware devices i.e. keyboard, mouse, etc)" -msgstr "labwc ha bisogno dell’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" +msgstr "labwc richiede l’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" msgid "Choose an option to give labwc access to your hardware" msgstr "Scegli un’opzione per concedere a labwc l’accesso al tuo hardware" msgid "niri needs access to your seat (collection of hardware devices i.e. keyboard, mouse, etc)" -msgstr "niri ha bisogno dell’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" +msgstr "niri richiede l’accesso al tuo posto (insieme di dispositivi hardware, ad esempio tastiera, mouse, ecc.)" msgid "Choose an option to give niri access to your hardware" msgstr "Scegli un’opzione per concedere a niri l’accesso al tuo hardware" @@ -1832,7 +1863,7 @@ msgid "Do you want to encrypt the user_credentials.json file?" msgstr "Vuoi criptare il file di user_credentials.json?" msgid "Credentials file encryption password" -msgstr "Password di crittazione del file delle credenziali" +msgstr "Password di crittografia del file delle credenziali" #, python-brace-format msgid "Repositories: {}" @@ -1917,7 +1948,7 @@ msgid "No network connection found" msgstr "Nessuna connessione di rete trovata" msgid "Would you like to connect to a Wifi?" -msgstr "Desideri connetterti ad una Wi-FI?" +msgstr "Desideri connetterti ad una Wi-Fi?" msgid "No wifi interface found" msgstr "Nessuna interfaccia Wi-Fi trovata" @@ -2000,11 +2031,26 @@ msgstr "Usa NetworkManager (backend iwd)" msgid "Firewall" msgstr "Firewall" +msgid "Additional fonts" +msgstr "Font aggiuntivi" + +msgid "Select font packages to install" +msgstr "Seleziona i pacchetti di font da installare" + +msgid "Unicode font coverage for most languages" +msgstr "Copertura Unicode del font per la maggior parte delle lingue" + +msgid "color emoji for browsers and apps" +msgstr "emoji a colori per browser e app" + +msgid "Chinese, Japanese, Korean characters" +msgstr "Caratteri cinesi, giapponesi, coreani" + msgid "Select audio configuration" msgstr "Seleziona la configurazione audio" msgid "Enter credentials file decryption password" -msgstr "Inserici la password di decrittazione del file delle credenziali" +msgstr "Inserisci la password di decrittazione del file delle credenziali" msgid "Enter root password" msgstr "Inserisci la password di root" @@ -2025,7 +2071,7 @@ msgid "Select disks for the installation" msgstr "Seleziona il disco per l'installazione" msgid "Enter a mountpoint" -msgstr "Inserisci un punto di mount" +msgstr "Inserisci un punto di montaggio" #, python-brace-format msgid "Enter a size (default: {}): " @@ -2035,7 +2081,7 @@ msgid "Enter subvolume name" msgstr "Inserisci il nome del sottovolume" msgid "Enter subvolume mountpoint" -msgstr "Inserisci il punto di mount del sottovolume" +msgstr "Inserisci il punto di montaggio del sottovolume" msgid "Select a disk configuration" msgstr "Seleziona una configurazione del disco" @@ -2047,7 +2093,7 @@ msgid "You will use whatever drive-setup is mounted at the specified directory" msgstr "Userai qualunque configurazione del disco che sia montata nella cartella specificata" msgid "WARNING: Archinstall won't check the suitability of this setup" -msgstr "ATTENZIONE: Archinstall non verificherà la compatibilità di di questa configurazione" +msgstr "ATTENZIONE: Archinstall non verificherà la compatibilità di questa configurazione" msgid "Select main filesystem" msgstr "Seleziona il filesystem principale" @@ -2066,22 +2112,22 @@ msgid "Value must be between 1 and {}" msgstr "Il valore deve essere tra 1 e {}" msgid "Select which kernel(s) to install" -msgstr "Scegli quali kernel installare" +msgstr "Seleziona i kernel da installare" msgid "Enter a respository name" msgstr "Inserisci il nome di un repository" msgid "Enter the repository url" -msgstr "Inserisci l'URL della repository" +msgstr "Inserisci l'URL del repository" msgid "Enter server url" msgstr "Inserisci l'URL del server" msgid "Select mirror regions to be enabled" -msgstr "Seleziona quali regioni dei mirror abilitare" +msgstr "Seleziona le regioni dei mirror da abilitare" msgid "Select optional repositories to be enabled" -msgstr "Seleziona quali repository aggiuntive opzionali abilitare" +msgstr "Seleziona i repository opzionali da abilitare" msgid "Select an interface" msgstr "Seleziona un'interfaccia" @@ -2089,11 +2135,17 @@ msgstr "Seleziona un'interfaccia" msgid "Choose network configuration" msgstr "Scegli la configurazione di rete" +msgid "Recommended: Network Manager for desktop, Manual for server" +msgstr "Raccomandato: Network Manager per computer, Manuale per server" + +msgid "Warning: no network configuration selected. Network will need to be set up manually on the installed system." +msgstr "Attenzione: nessuna configurazione di rete selezionata. La rete dovrà essere impostata manualmente sul sistema installato." + msgid "No packages found" msgstr "Nessun pacchetto trovato" msgid "Select which greeter to install" -msgstr "Seleziona quale greeter installare" +msgstr "Seleziona il greeter da installare" msgid "Select a profile type" msgstr "Seleziona un tipo di profilo" @@ -2126,6 +2178,9 @@ msgstr "Il profilo desktop selezionato richiede un utente regolare per accedere msgid "Environment type: {} {}" msgstr "Tipo di ambiente: {} {}" +msgid "Input cannot be empty" +msgstr "Il campo non può essere vuoto" + msgid "Recommended" msgstr "Raccomandato" @@ -2156,5 +2211,194 @@ msgstr "Descrizione" msgid "Select a flavor of KDE Plasma to install" msgstr "Seleziona la configurazione di KDE Plasma da installare" -msgid "Input cannot be empty" -msgstr "Il campo non può essere vuoto" +msgid "Arial/Times/Courier replacement, Cyrillic support for Steam/games" +msgstr "Sostituto di Arial/Times/Courier, supporta il cirillico per Steam/giochi" + +msgid "wide Unicode coverage, good fallback font" +msgstr "ampia copertura Unicode, ottimo font di riserva" + +#, python-brace-format +msgid "Setting up U2F login: {u2f_config.u2f_login_method.value}" +msgstr "Impostazione accesso U2F: {u2f_config.u2f_login_method.value}" + +#, python-brace-format +msgid "Default: {DEFAULT_ITER_TIME}ms, Recommended range: 1000-60000" +msgstr "Predefinito: {DEFAULT_ITER_TIME} ms, Intervallo consigliato: 1000-60000" + +#, python-brace-format +msgid "Setting up U2F login: {}" +msgstr "Impostazione accesso U2F: {}" + +#, python-brace-format +msgid "Default: {}ms, Recommended range: 1000-60000" +msgstr "Predefinito: {} ms, Intervallo consigliato: 1000-60000" + +#, python-brace-format +msgid "{} needs access to your seat" +msgstr "{} richiede l’accesso al tuo posto" + +msgid "collection of hardware devices i.e. keyboard, mouse" +msgstr "insieme di dispositivi hardware, ad esempio tastiera e mouse" + +#, python-brace-format +msgid "Choose an option how to give {} access to your hardware" +msgstr "Scegli un’opzione per concedere a {} l’accesso al tuo hardware" + +#, python-brace-format +msgid "About to upload \"{}\" to the publicly accessible {}" +msgstr "\"{}\" sta per essere caricato per essere pubblicamente accessibile {}" + +msgid "Do you want to continue?" +msgstr "Vuoi continuare?" + +#, python-brace-format +msgid "Log uploaded successfully. URL: {}" +msgstr "Log caricato con successo. URL: {}" + +msgid "Failed to upload log." +msgstr "Impossibile caricare il log." + +msgid "ArchInstall Language" +msgstr "Lingua di ArchInstall" + +msgid "Version" +msgstr "Versione" + +msgid "Installation Script" +msgstr "Script di installazione" + +msgid "Application" +msgstr "Applicazione" + +msgid "Services" +msgstr "Servizi" + +msgid "Custom commands" +msgstr "Comandi personalizzati" + +msgid "Users" +msgstr "Utenti" + +msgid "Root encrypted password" +msgstr "Password di root crittografata" + +msgid "Zram enabled" +msgstr "Zram attiva" + +#, python-brace-format +msgid "Zram algorithm {}" +msgstr "Algoritmo Zram {}" + +msgid "Bluetooth enabled" +msgstr "Bluetooth attivo" + +#, python-brace-format +msgid "Audio server \"{}\"" +msgstr "Server audio \"{}\"" + +#, python-brace-format +msgid "Power management \"{}\"" +msgstr "Gestione energetica \"{}\"" + +msgid "Print service enabled" +msgstr "Servizio di stampa attivo" + +#, python-brace-format +msgid "Firewall \"{}\"" +msgstr "Firewall \"{}\"" + +#, python-brace-format +msgid "Extra fonts \"{}\"" +msgstr "Font aggiuntivi \"{}\"" + +msgid "Root password set" +msgstr "Imposta la password di root" + +#, python-brace-format +msgid "Configured {} user(s)" +msgstr "{} utente/i configurato/i" + +msgid "U2F set up" +msgstr "Imposta U2F" + +#, python-brace-format +msgid "Bootloader \"{}\"" +msgstr "Bootloader \"{}\"" + +msgid "UKI enabled" +msgstr "UKI attiva" + +msgid "Default" +msgstr "Predefinito" + +msgid "Manual" +msgstr "Manuale" + +msgid "Pre-mount" +msgstr "Premontaggio" + +#, python-brace-format +msgid "{} layout" +msgstr "Layout {}" + +#, python-brace-format +msgid "Devices {}" +msgstr "Dispositivi {}" + +msgid "LVM set up" +msgstr "Imposta LVM" + +#, python-brace-format +msgid "{} encryption" +msgstr "Crittografia {}" + +#, python-brace-format +msgid "Btrfs snapshot \"{}\"" +msgstr "Snapshot Btrfs \"{}\"" + +#, python-brace-format +msgid "Keyboard layout \"{}\"" +msgstr "Layout della tastiera \"{}\"" + +#, python-brace-format +msgid "Locale language \"{}\"" +msgstr "Lingua \"{}\"" + +#, python-brace-format +msgid "Locale encoding \"{}\"" +msgstr "Codifica \"{}\"" + +#, python-brace-format +msgid "Console font \"{}\"" +msgstr "Font della console \"{}\"" + +#, python-brace-format +msgid "Mirror regions \"{}\"" +msgstr "Regioni dei mirror \"{}\"" + +#, python-brace-format +msgid "Optional repositories \"{}\"" +msgstr "Repository opzionali \"{}\"" + +msgid "Custom servers set up" +msgstr "Imposta server personalizzati" + +msgid "Custom repositories set up" +msgstr "Imposta repository personalizzati" + +msgid "Use standalone iwd" +msgstr "Usa iwd standalone" + +msgid "Color enabled" +msgstr "Colore attivo" + +#, python-brace-format +msgid "{} grphics driver" +msgstr "Driver grafici {}" + +#, python-brace-format +msgid "{} greeter" +msgstr "Greeter {}" + +msgid "Enter a repository name" +msgstr "Inserisci il nome di un repository" diff --git a/archinstall/locales/ja/LC_MESSAGES/base.mo b/archinstall/locales/ja/LC_MESSAGES/base.mo index 96b625c6..7d6b89f3 100644 Binary files a/archinstall/locales/ja/LC_MESSAGES/base.mo and b/archinstall/locales/ja/LC_MESSAGES/base.mo differ diff --git a/archinstall/locales/ja/LC_MESSAGES/base.po b/archinstall/locales/ja/LC_MESSAGES/base.po index 1e0f52e1..6fbb4b3f 100644 --- a/archinstall/locales/ja/LC_MESSAGES/base.po +++ b/archinstall/locales/ja/LC_MESSAGES/base.po @@ -830,7 +830,7 @@ msgid "Pacman" msgstr "Pacman" msgid "Color" -msgstr "カラー" +msgstr "カラー出力" #, python-brace-format msgid "Enter the number of parallel downloads (1-{})" @@ -1223,7 +1223,7 @@ msgid "Invalid configuration: {error}" msgstr "無効な設定: {error}" msgid "Ready to install" -msgstr "インストール準備完了" +msgstr "インストールの準備が完了" msgid "Disks" msgstr "ディスク" @@ -1548,7 +1548,7 @@ msgid "NTP" msgstr "NTP" msgid "Swap on zram" -msgstr "zram のスワップ" +msgstr "Zram 上でスワップ" msgid "Name" msgstr "名前" @@ -2230,3 +2230,170 @@ msgstr "U2F ログインの設定: {}" #, python-brace-format msgid "Default: {}ms, Recommended range: 1000-60000" msgstr "デフォルト: {}ms, 推奨範囲: 1000-60000" + +#, python-brace-format +msgid "{} needs access to your seat" +msgstr "{} はお使いの Seat へのアクセスを必要とします" + +msgid "collection of hardware devices i.e. keyboard, mouse" +msgstr "ハードウェアデバイス群。キーボード、マウスなど" + +#, python-brace-format +msgid "Choose an option how to give {} access to your hardware" +msgstr "{} にハードウェアへのアクセスを許可する方法を選択" + +msgid "Zram enabled" +msgstr "Zram を有効にする" + +#, python-brace-format +msgid "Zram algorithm {}" +msgstr "Zram アルゴリズム {}" + +msgid "Bluetooth enabled" +msgstr "Bluetooth を有効にする" + +#, python-brace-format +msgid "Audio server \"{}\"" +msgstr "オーディオサーバー \"{}\"" + +#, python-brace-format +msgid "Power management \"{}\"" +msgstr "電力管理 \"{}\"" + +msgid "Print service enabled" +msgstr "印刷サービスを有効にする" + +#, python-brace-format +msgid "Firewall \"{}\"" +msgstr "ファイアウォール \"{}\"" + +#, python-brace-format +msgid "Extra fonts \"{}\"" +msgstr "追加フォント \"{}\"" + +msgid "Root password set" +msgstr "Root パスワードを設定" + +#, python-brace-format +msgid "Configured {} user(s)" +msgstr "{} 人のユーザーを設定" + +msgid "U2F set up" +msgstr "U2F を設定" + +#, python-brace-format +msgid "Keyboard layout \"{}\"" +msgstr "キーボードレイアウト \"{}\"" + +#, python-brace-format +msgid "Locale language \"{}\"" +msgstr "ロケール言語 \"{}\"" + +#, python-brace-format +msgid "Locale encoding \"{}\"" +msgstr "ロケールエンコーディング \"{}\"" + +#, python-brace-format +msgid "Console font \"{}\"" +msgstr "コンソールフォント \"{}\"" + +msgid "Default" +msgstr "デフォルト" + +msgid "Manual" +msgstr "マニュアル" + +msgid "Pre-mount" +msgstr "プレマウント" + +#, python-brace-format +msgid "{} layout" +msgstr "{} レイアウト" + +#, python-brace-format +msgid "Devices {}" +msgstr "デバイス {}" + +msgid "LVM set up" +msgstr "LVM の設定" + +#, python-brace-format +msgid "{} encryption" +msgstr "{} 暗号化" + +#, python-brace-format +msgid "Btrfs snapshot \"{}\"" +msgstr "Btrfs スナップショット \"{}\"" + +msgid "Use standalone iwd" +msgstr "スタンドアロンの iwd を使用" + +#, python-brace-format +msgid "Mirror regions \"{}\"" +msgstr "ミラーの地域 \"{}\"" + +#, python-brace-format +msgid "Optional repositories \"{}\"" +msgstr "オプションリポジトリ \"{}\"" + +msgid "Custom servers set up" +msgstr "カスタムサーバーを設定" + +msgid "Custom repositories set up" +msgstr "カスタムリポジトリを設定" + +#, python-brace-format +msgid "Bootloader \"{}\"" +msgstr "ブートローダー \"{}\"" + +msgid "UKI enabled" +msgstr "UKI を有効にする" + +msgid "Color enabled" +msgstr "カラー出力を有効にする" + +#, python-brace-format +msgid "{} grphics driver" +msgstr "{} グラフィックドライバー" + +#, python-brace-format +msgid "{} greeter" +msgstr "{} グリーター" + +msgid "ArchInstall Language" +msgstr "ArchInstall の言語" + +msgid "Version" +msgstr "バージョン" + +msgid "Installation Script" +msgstr "インストールスクリプト" + +msgid "Application" +msgstr "アプリケーション" + +msgid "Services" +msgstr "サービス" + +msgid "Custom commands" +msgstr "カスタムコマンド" + +msgid "Users" +msgstr "ユーザー" + +msgid "Root encrypted password" +msgstr "Root 暗号化パスワード" + +#, python-brace-format +msgid "About to upload \"{}\" to the publicly accessible {}" +msgstr "\"{}\" を公開アクセス可能な {} にアップロードしようとしています" + +msgid "Do you want to continue?" +msgstr "続行しますか?" + +#, python-brace-format +msgid "Log uploaded successfully. URL: {}" +msgstr "ログのアップロードに成功しました。URL: {}" + +msgid "Failed to upload log." +msgstr "ログのアップロードに失敗しました。" diff --git a/archinstall/locales/locales_generator.sh b/archinstall/locales/locales_generator.sh index 7ce2ea19..18977dfc 100755 --- a/archinstall/locales/locales_generator.sh +++ b/archinstall/locales/locales_generator.sh @@ -1,48 +1,109 @@ #!/usr/bin/env bash set -euo pipefail -cd $(dirname "$0")/.. +cd "$(dirname "$0")/.." -function update_lang() { - file=${1} +usage() { + echo "Usage: ${0} " + echo "" + echo "Commands:" + echo " all Regenerate base.pot and update all languages" + echo " Regenerate base.pot and update a single language" + echo " check Run translation validation checks" + echo " -h, --help Show this help" +} +generate_pot() { + find . -type f -iname '*.py' | sort \ + | xargs xgettext --no-location --omit-header --keyword='tr' \ + -d base -o locales/base.pot +} + +update_lang() { + local file=${1} echo "Updating: ${file}" + local path path=$(dirname "${file}") msgmerge --quiet --no-location --width 512 --backup none --update "${file}" locales/base.pot msgfmt -o "${path}/base.mo" "${file}" } - -function generate_all() { +cmd_generate_all() { + generate_pot for file in $(find locales/ -name "base.po"); do update_lang "${file}" done } -function generate_single_lang() { - lang_file="locales/${1}/LC_MESSAGES/base.po" - +cmd_generate_single() { + local lang_file="locales/${1}/LC_MESSAGES/base.po" if [ ! -f "${lang_file}" ]; then echo "Language files not found: ${lang_file}" exit 1 fi - + generate_pot update_lang "${lang_file}" } +cmd_check_po_syntax() { + echo "Checking .po syntax..." + local failed=0 + while IFS= read -r po; do + if ! msgfmt --check --output-file=/dev/null "$po" 2>&1; then + echo "FAIL: $po" + failed=1 + fi + done < <(find locales/ -name '*.po') + if [ "$failed" -eq 1 ]; then + echo "ERROR: some .po files have syntax errors" >&2 + return 1 + fi + echo "All .po files passed syntax check." +} + +cmd_check_no_tr_fstring() { + echo "Checking for tr(f-string) anti-pattern..." + if grep -rnE "tr\(\s*f['\"]" . --include='*.py'; then + echo "ERROR: use tr('...{}').format(...) instead of tr(f'...')" >&2 + return 1 + fi + echo "No tr(f-string) anti-pattern found." +} + +cmd_check_pot_freshness() { + # msgcmp (not diff) because base.pot carries legacy stale entries from + # --join-existing; diff would always fail until a full cleanup is done. + echo "Checking base.pot for missing strings..." + find . -type f -iname '*.py' | sort \ + | xargs xgettext --no-location --omit-header --keyword='tr' \ + -d base -o /tmp/generated.pot + if ! msgcmp --use-untranslated locales/base.pot /tmp/generated.pot; then + echo "ERROR: base.pot is missing strings - run: locales_generator.sh all" >&2 + return 1 + fi + echo "base.pot contains all translatable strings." +} + +cmd_check() { + local failed=0 + cmd_check_po_syntax || failed=1 + cmd_check_no_tr_fstring || failed=1 + cmd_check_pot_freshness || failed=1 + if [ "$failed" -eq 1 ]; then + echo "Some translation checks failed." >&2 + exit 1 + fi + echo "All translation checks passed." +} if [ $# -eq 0 ]; then - echo "Usage: ${0} " - echo "Special case 'all' for builds all languages." + usage exit 1 fi -lang=${1} - -# Update the base file containing all translatable strings -find . -type f -iname "*.py" | xargs xgettext --join-existing --no-location --omit-header --keyword='tr' -d base -o locales/base.pot - -case "${lang}" in - "all") generate_all;; - *) generate_single_lang "${lang}" +case "${1}" in + check) cmd_check ;; + all) cmd_generate_all ;; + -h|--help) usage ;; + *) cmd_generate_single "${1}" ;; esac diff --git a/archinstall/main.py b/archinstall/main.py index 9b91681b..e38b3d48 100644 --- a/archinstall/main.py +++ b/archinstall/main.py @@ -8,13 +8,13 @@ import time import traceback from pathlib import Path -from archinstall.lib.args import ArchConfigHandler +from archinstall.lib.args import ArchConfigHandler, SubCommand from archinstall.lib.disk.utils import disk_layouts from archinstall.lib.hardware import SysInfo +from archinstall.lib.log import debug, error, info, logger, share_install_log, warn from archinstall.lib.menu.helpers import Confirmation from archinstall.lib.network.wifi_handler import WifiHandler from archinstall.lib.networking import ping -from archinstall.lib.output import debug, error, info, share_install_log, warn from archinstall.lib.packages.util import check_version_upgrade from archinstall.lib.pacman.pacman import Pacman from archinstall.lib.translationhandler import tr, translation_handler @@ -75,17 +75,36 @@ def _list_scripts() -> str: return '\n'.join(lines) -def _tui_confirm(header: str) -> bool: - async def _ask() -> bool: +def _share_log_command() -> None: + paste_url: str = 'https://paste.rs' + log_path = logger.path + max_size = 10 * 1024 * 1024 # max supported size by paste.rs + content = logger.get_content(max_bytes=max_size).decode() + + header = tr('About to upload "{}" to the publicly accessible {}').format(log_path, paste_url) + '\n\n' + header += tr('Do you want to continue?') + + group = MenuItemGroup.yes_no() + group.set_preview_for_all(lambda _: content) + + async def _confirm() -> bool: result = await Confirmation( - group=MenuItemGroup.yes_no(), header=header, allow_skip=False, - preset=False, + group=group, + preview_header='Log content', + preview_location='bottom', ).show() return result.get_value() - return tui.run(_ask) + result = tui.run(_confirm) + + if result is True: + res = share_install_log(paste_url=paste_url, max_bytes=max_size) + if res is not None: + info(tr('Log uploaded successfully. URL: {}').format(res)) + else: + error(tr('Failed to upload log.')) def run() -> int: @@ -94,15 +113,19 @@ def run() -> int: OR straight as a module: python -m archinstall In any case we will be attempting to load the provided script to be run from the scripts/ folder """ - if 'share-log' in sys.argv: - return share_install_log(confirm=_tui_confirm) - arch_config_handler = ArchConfigHandler() if '--help' in sys.argv or '-h' in sys.argv: arch_config_handler.print_help() return 0 + match arch_config_handler.args.command: + case SubCommand.SHARE_LOG: + _share_log_command() + exit(0) + case None: + pass + script = arch_config_handler.get_script() if script == 'list': diff --git a/archinstall/scripts/guided.py b/archinstall/scripts/guided.py index aab02cfd..6f484910 100644 --- a/archinstall/scripts/guided.py +++ b/archinstall/scripts/guided.py @@ -12,13 +12,13 @@ from archinstall.lib.disk.utils import disk_layouts from archinstall.lib.general.general_menu import PostInstallationAction, select_post_installation from archinstall.lib.global_menu import GlobalMenu from archinstall.lib.installer import Installer, accessibility_tools_in_use, run_custom_user_commands +from archinstall.lib.log import debug, error, info from archinstall.lib.menu.util import delayed_warning from archinstall.lib.mirror.mirror_handler import MirrorListHandler from archinstall.lib.models import Bootloader from archinstall.lib.models.device import DiskLayoutType, EncryptionType from archinstall.lib.models.users import User from archinstall.lib.network.network_handler import install_network_config -from archinstall.lib.output import debug, error, info from archinstall.lib.packages.util import check_version_upgrade from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.lib.translationhandler import tr diff --git a/archinstall/scripts/minimal.py b/archinstall/scripts/minimal.py index ee4b49c7..c6eda03d 100644 --- a/archinstall/scripts/minimal.py +++ b/archinstall/scripts/minimal.py @@ -4,12 +4,12 @@ from archinstall.lib.configuration import ConfigurationOutput from archinstall.lib.disk.disk_menu import DiskLayoutConfigurationMenu from archinstall.lib.disk.filesystem import FilesystemHandler from archinstall.lib.installer import Installer +from archinstall.lib.log import debug, error, info from archinstall.lib.menu.util import delayed_warning from archinstall.lib.models import Bootloader from archinstall.lib.models.profile import ProfileConfiguration from archinstall.lib.models.users import Password, User from archinstall.lib.network.network_handler import install_network_config -from archinstall.lib.output import debug, error, info from archinstall.lib.profile.profiles_handler import profile_handler from archinstall.lib.translationhandler import tr from archinstall.tui.components import tui diff --git a/archinstall/scripts/only_hd.py b/archinstall/scripts/only_hd.py index 5df72965..c7349c51 100644 --- a/archinstall/scripts/only_hd.py +++ b/archinstall/scripts/only_hd.py @@ -7,8 +7,8 @@ from archinstall.lib.disk.filesystem import FilesystemHandler from archinstall.lib.disk.utils import disk_layouts from archinstall.lib.global_menu import GlobalMenu from archinstall.lib.installer import Installer +from archinstall.lib.log import debug, error from archinstall.lib.menu.util import delayed_warning -from archinstall.lib.output import debug, error from archinstall.lib.translationhandler import tr from archinstall.tui.components import tui diff --git a/archinstall/tui/components.py b/archinstall/tui/components.py index f732c21f..efbb64f9 100644 --- a/archinstall/tui/components.py +++ b/archinstall/tui/components.py @@ -19,7 +19,7 @@ from textual.widgets.option_list import Option from textual.widgets.selection_list import Selection from textual.worker import WorkerCancelled -from archinstall.lib.output import debug +from archinstall.lib.log import debug from archinstall.lib.translationhandler import tr from archinstall.tui.menu_item import MenuItem, MenuItemGroup from archinstall.tui.result import Result, ResultType @@ -350,11 +350,6 @@ class OptionListScreen(BaseScreen[ValueT]): ] ) - # debug(f'Index: {index}') - # debug(f'Region: {option_list.region}') - # debug(f'Scroll offset: {option_list.scroll_offset}') - # debug(f'Target_Y: {target_y}') - self.app.cursor_position = Offset(option_list.region.x, target_y) self.app.refresh() @@ -1163,8 +1158,6 @@ class TableSelectionScreen(BaseScreen[ValueT]): ] ) - debug(f'Setting cursor to target_y: {target_y}') - self.app.cursor_position = Offset(data_table.region.x, target_y) self.app.refresh() diff --git a/archinstall/tui/rich.py b/archinstall/tui/rich.py new file mode 100644 index 00000000..055ec22c --- /dev/null +++ b/archinstall/tui/rich.py @@ -0,0 +1,25 @@ +from io import StringIO + +from rich import box +from rich.console import Console +from rich.table import Table as RichTable + + +class BaseRichTable(RichTable): + def __init__(self) -> None: + super().__init__( + box=box.SIMPLE, + show_header=False, + pad_edge=False, + show_edge=False, + ) + + def stringify(self) -> str: + string_io = StringIO() + buf = Console(file=string_io, highlight=False) + buf.print(self) + + _ = string_io.seek(0) + output = string_io.read() + + return output diff --git a/pyproject.toml b/pyproject.toml index 9fee23fa..0f455c30 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,9 +19,9 @@ classifiers = [ ] dependencies = [ "pyparted==3.13.0", - "pydantic==2.12.5", + "pydantic==2.13.4", "cryptography==48.0.0", - "textual==8.2.5", + "textual==8.2.6", "markdown-it-py==4.0.0", "linkify-it-py==2.1.0", ] @@ -34,12 +34,13 @@ Source = "https://github.com/archlinux/archinstall" [project.optional-dependencies] log = ["systemd_python==235"] dev = [ - "mypy==2.0.0", + "mypy==2.1.0", "flake8==7.3.0", "pre-commit==4.6.0", - "ruff==0.15.12", + "ruff==0.15.13", "pylint==4.0.5", "pytest==9.0.3", + "hypothesis>=6.152.4", ] doc = ["sphinx"] diff --git a/tests/test_share_log.py b/tests/test_share_log.py index c1c3ca84..1a19ba26 100644 --- a/tests/test_share_log.py +++ b/tests/test_share_log.py @@ -1,94 +1,127 @@ # pylint: disable=redefined-outer-name +import string import urllib.error from io import BytesIO from pathlib import Path -from unittest.mock import MagicMock, patch +from unittest.mock import patch import pytest +from hypothesis import HealthCheck, given, settings +from hypothesis import strategies as st -from archinstall.lib.output import share_install_log +from archinstall.lib.log import share_install_log + +urls = st.builds( + '{}://{}.{}/{}'.format, + st.sampled_from(['http', 'https']), + st.text(alphabet=string.ascii_lowercase, min_size=3, max_size=10), + st.sampled_from(['com', 'net', 'org', 'rs']), + st.text(alphabet=string.ascii_lowercase + string.digits, min_size=0, max_size=8), +) + +max_bytes = st.one_of(st.none(), st.integers(min_value=1, max_value=130)) + +random_paths = st.lists( + st.text( + alphabet=string.ascii_lowercase + string.digits, + min_size=1, + max_size=10, + ), + min_size=1, + max_size=5, +).map(lambda parts: Path(*parts)) -@pytest.fixture() +@pytest.fixture def log_file(tmp_path: Path) -> Path: log_dir = tmp_path / 'archinstall' log_dir.mkdir() return log_dir / 'install.log' -def _fake_logger(log_file: Path) -> MagicMock: - mock = MagicMock() - mock.path = log_file - return mock +# def _fake_logger(log_file: Path) -> MagicMock: +# mock = MagicMock() +# mock.path = log_file +# return mock -def test_file_not_found(tmp_path: Path) -> None: - missing = tmp_path / 'no-such' / 'install.log' - with patch('archinstall.lib.output.logger', _fake_logger(missing)): - assert share_install_log() == 1 +@given(paste_url=urls, max_byte=max_bytes, sub_path=random_paths) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_file_not_found( + tmp_path: Path, + sub_path: Path, + paste_url: str, + max_byte: int | None, +) -> None: + missing_log = tmp_path / sub_path / 'install.log' + + with patch('archinstall.lib.log.logger._path', new=missing_log): + assert share_install_log(paste_url, max_byte) is None -def test_empty_file(log_file: Path) -> None: +@given(paste_url=urls, max_byte=max_bytes) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_empty_file(log_file: Path, paste_url: str, max_byte: int | None) -> None: log_file.write_bytes(b'') - with patch('archinstall.lib.output.logger', _fake_logger(log_file)): - assert share_install_log() == 1 + + with patch('archinstall.lib.log.logger._path', new=log_file.parent): + # with patch('archinstall.lib.log.logger', _fake_logger(log_file)): + assert share_install_log(paste_url, max_byte) is None -def test_user_cancels(log_file: Path) -> None: +@given(paste_url=urls, resp_url=urls, max_byte=max_bytes) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_successful_upload(log_file: Path, resp_url: str, paste_url: str, max_byte: int | None) -> None: log_file.write_text('some log content') - with patch('archinstall.lib.output.logger', _fake_logger(log_file)): - assert share_install_log(confirm=lambda _: False) == 1 - - -def test_successful_upload(log_file: Path) -> None: - log_file.write_text('some log content') - fake_response = BytesIO(b'https://paste.rs/abc.def') + fake_response = BytesIO(resp_url.encode()) with ( - patch('archinstall.lib.output.logger', _fake_logger(log_file)), - patch('urllib.request.urlopen', return_value=fake_response) as mock_open, + patch('archinstall.lib.log.logger._path', new=log_file.parent), + patch('urllib.request.urlopen', return_value=fake_response), ): - result = share_install_log() - - assert result == 0 - req = mock_open.call_args[0][0] - assert req.data == b'some log content' + result = share_install_log(paste_url, max_byte) + assert result == resp_url -def test_truncation(log_file: Path) -> None: - max_size = 100 +@given(paste_url=urls, resp_url=urls, max_byte=max_bytes) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_truncation(log_file: Path, resp_url: str, paste_url: str, max_byte: int | None) -> None: content = b'A' * 50 + b'B' * 80 log_file.write_bytes(content) - fake_response = BytesIO(b'https://paste.rs/abc.def') + fake_response = BytesIO(resp_url.encode()) + + exptected_byte = len(content) if max_byte is None else max_byte with ( - patch('archinstall.lib.output.logger', _fake_logger(log_file)), + patch('archinstall.lib.log.logger._path', new=log_file.parent), patch('urllib.request.urlopen', return_value=fake_response) as mock_open, ): - result = share_install_log(max_size=max_size) - - assert result == 0 - req = mock_open.call_args[0][0] - assert len(req.data) == max_size - assert req.data == content[-max_size:] + _ = share_install_log(paste_url, max_byte) + req = mock_open.call_args[0][0] + assert len(req.data) == exptected_byte + assert req.data == content[-exptected_byte:] -def test_network_error(log_file: Path) -> None: +@given(paste_url=urls, max_byte=max_bytes) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_network_error(log_file: Path, paste_url: str, max_byte: int | None) -> None: log_file.write_text('some log content') with ( - patch('archinstall.lib.output.logger', _fake_logger(log_file)), + patch('archinstall.lib.log.logger._path', new=log_file.parent), patch('urllib.request.urlopen', side_effect=urllib.error.URLError('no network')), ): - assert share_install_log() == 1 + assert share_install_log(paste_url, max_byte) is None -def test_unexpected_response(log_file: Path) -> None: +@given(paste_url=urls, max_byte=max_bytes) +@settings(max_examples=3, suppress_health_check=[HealthCheck.function_scoped_fixture]) +def test_unexpected_response(log_file: Path, paste_url: str, max_byte: int | None) -> None: log_file.write_text('some log content') fake_response = BytesIO(b'ERROR: something went wrong') with ( - patch('archinstall.lib.output.logger', _fake_logger(log_file)), + patch('archinstall.lib.log.logger._path', new=log_file.parent), patch('urllib.request.urlopen', return_value=fake_response), ): - assert share_install_log() == 1 + assert share_install_log(paste_url, max_byte) is None