From 0fa52a5424e28ed62ef84bdc92868bbfc434e015 Mon Sep 17 00:00:00 2001 From: Daniel Girtler Date: Mon, 9 May 2022 20:02:48 +1000 Subject: Introduce ctrl+c and other bug fixes (#1152) * Intergrate ctrl+c * stash * Update * Fix profile reset * flake8 Co-authored-by: Daniel Girtler --- archinstall/lib/user_interaction/network_conf.py | 37 +++++++++++++++--------- 1 file changed, 24 insertions(+), 13 deletions(-) (limited to 'archinstall/lib/user_interaction/network_conf.py') diff --git a/archinstall/lib/user_interaction/network_conf.py b/archinstall/lib/user_interaction/network_conf.py index 80c9106b..e4e681ce 100644 --- a/archinstall/lib/user_interaction/network_conf.py +++ b/archinstall/lib/user_interaction/network_conf.py @@ -4,6 +4,7 @@ import ipaddress import logging from typing import Any, Optional, TYPE_CHECKING, List, Union +from ..menu.menu import MenuSelectionType from ..menu.text_input import TextInput from ..models.network_configuration import NetworkConfiguration, NicType @@ -66,8 +67,12 @@ class ManualNetworkConfig(ListManager): def _select_iface(self, existing_ifaces: List[str]) -> Optional[str]: all_ifaces = list_interfaces().values() available = set(all_ifaces) - set(existing_ifaces) - iface = Menu(str(_('Select interface to add')), list(available), skip=True).run() - return iface + choice = Menu(str(_('Select interface to add')), list(available), skip=True).run() + + if choice.type_ == MenuSelectionType.Esc: + return None + + return choice.value def _edit_iface(self, edit_iface :NetworkConfiguration): iface_name = edit_iface.iface @@ -75,9 +80,9 @@ class ManualNetworkConfig(ListManager): default_mode = 'DHCP (auto detect)' prompt = _('Select which mode to configure for "{}" or skip to use default mode "{}"').format(iface_name, default_mode) - mode = Menu(prompt, modes, default_option=default_mode).run() + mode = Menu(prompt, modes, default_option=default_mode, skip=False).run() - if mode == 'IP (static)': + if mode.value == 'IP (static)': while 1: prompt = _('Enter the IP and subnet for {} (example: 192.168.0.5/24): ').format(iface_name) ip = TextInput(prompt, edit_iface.ip).run().strip() @@ -107,6 +112,7 @@ class ManualNetworkConfig(ListManager): display_dns = None dns_input = TextInput(_('Enter your DNS servers (space separated, blank for none): '), display_dns).run().strip() + dns = [] if len(dns_input): dns = dns_input.split(' ') @@ -135,23 +141,28 @@ def ask_to_configure_network(preset: Union[None, NetworkConfiguration, List[Netw elif preset.type == 'network_manager': cursor_idx = 1 - nic = Menu(_( - 'Select one network interface to configure'), + warning = str(_('Are you sure you want to reset this setting?')) + + choice = Menu( + _('Select one network interface to configure'), list(network_options.values()), cursor_index=cursor_idx, - sort=False + sort=False, + explode_on_interrupt=True, + explode_warning=warning ).run() - if not nic: - return preset + match choice.type_: + case MenuSelectionType.Esc: return preset + case MenuSelectionType.Ctrl_c: return None - if nic == network_options['none']: + if choice.value == network_options['none']: return None - elif nic == network_options['iso_config']: + elif choice.value == network_options['iso_config']: return NetworkConfiguration(NicType.ISO) - elif nic == network_options['network_manager']: + elif choice.value == network_options['network_manager']: return NetworkConfiguration(NicType.NM) - elif nic == network_options['manual']: + elif choice.value == network_options['manual']: manual = ManualNetworkConfig('Configure interfaces', preset) return manual.run_manual() -- cgit v1.2.3-70-g09d2 From 65a5a335aa21ea44fd99fb200e238df54b3c2e47 Mon Sep 17 00:00:00 2001 From: Daniel Girtler Date: Wed, 18 May 2022 21:59:49 +1000 Subject: Enhance view (#1210) * Add preview for menu entries * Fix mypy * Update * Update * Fix mypy Co-authored-by: Daniel Girtler --- .github/workflows/mypy.yaml | 2 +- archinstall/lib/disk/blockdevice.py | 42 ++++++++++---- archinstall/lib/hsm/fido.py | 2 +- archinstall/lib/menu/global_menu.py | 66 +++++++++++++++++----- archinstall/lib/menu/list_manager.py | 4 +- archinstall/lib/menu/selection_menu.py | 8 ++- archinstall/lib/user_interaction/general_conf.py | 1 - archinstall/lib/user_interaction/network_conf.py | 12 ++-- .../lib/user_interaction/partitioning_conf.py | 19 ++++--- archinstall/lib/user_interaction/utils.py | 1 + 10 files changed, 110 insertions(+), 47 deletions(-) (limited to 'archinstall/lib/user_interaction/network_conf.py') diff --git a/.github/workflows/mypy.yaml b/.github/workflows/mypy.yaml index 6fd0876f..18c33e67 100644 --- a/.github/workflows/mypy.yaml +++ b/.github/workflows/mypy.yaml @@ -15,4 +15,4 @@ jobs: # one day this will be enabled # run: mypy --strict --module archinstall || exit 0 - name: run mypy - run: mypy --follow-imports=skip archinstall/lib/menu/selection_menu.py archinstall/lib/models/network_configuration.py archinstall/lib/menu/list_manager.py archinstall/lib/user_interaction/network_conf.py + run: mypy --follow-imports=silent archinstall/lib/menu/selection_menu.py archinstall/lib/menu/global_menu.py archinstall/lib/models/network_configuration.py archinstall/lib/menu/list_manager.py archinstall/lib/user_interaction/network_conf.py diff --git a/archinstall/lib/disk/blockdevice.py b/archinstall/lib/disk/blockdevice.py index 995ca355..15f03789 100644 --- a/archinstall/lib/disk/blockdevice.py +++ b/archinstall/lib/disk/blockdevice.py @@ -34,11 +34,29 @@ class BlockDevice: def __repr__(self, *args :str, **kwargs :str) -> str: return self._str_repr - + @cached_property def _str_repr(self) -> str: return f"BlockDevice({self.device_or_backfile}, size={self._safe_size}GB, free_space={self._safe_free_space}, bus_type={self.bus_type})" + @cached_property + def display_info(self) -> str: + columns = { + str(_('Device')): self.device_or_backfile, + str(_('Size')): f'{self._safe_size}GB', + str(_('Free space')): f'{self._safe_free_space}', + str(_('Bus-type')): f'{self.bus_type}' + } + + padding = max([len(k) for k in columns.keys()]) + + pretty = '' + for k, v in columns.items(): + k = k.ljust(padding, ' ') + pretty += f'{k} = {v}\n' + + return pretty.rstrip() + def __iter__(self) -> Iterator[Partition]: for partition in self.partitions: yield self.partitions[partition] @@ -79,7 +97,7 @@ class BlockDevice: for device in output['blockdevices']: return device['pttype'] - @property + @cached_property def device_or_backfile(self) -> str: """ Returns the actual device-endpoint of the BlockDevice. @@ -162,7 +180,7 @@ class BlockDevice: from .filesystem import GPT return GPT - @property + @cached_property def uuid(self) -> str: log('BlockDevice().uuid is untested!', level=logging.WARNING, fg='yellow') """ @@ -172,7 +190,7 @@ class BlockDevice: """ return SysCommand(f'blkid -s PTUUID -o value {self.path}').decode('UTF-8') - @property + @cached_property def _safe_size(self) -> float: from .helpers import convert_size_to_gb @@ -184,7 +202,7 @@ class BlockDevice: for device in output['blockdevices']: return convert_size_to_gb(device['size']) - @property + @cached_property def size(self) -> float: from .helpers import convert_size_to_gb @@ -193,28 +211,28 @@ class BlockDevice: for device in output['blockdevices']: return convert_size_to_gb(device['size']) - @property + @cached_property def bus_type(self) -> str: output = json.loads(SysCommand(f"lsblk --json -o+ROTA,TRAN {self.path}").decode('UTF-8')) for device in output['blockdevices']: return device['tran'] - @property + @cached_property def spinning(self) -> bool: output = json.loads(SysCommand(f"lsblk --json -o+ROTA,TRAN {self.path}").decode('UTF-8')) for device in output['blockdevices']: return device['rota'] is True - @property + @cached_property def _safe_free_space(self) -> Tuple[str, ...]: try: return '+'.join(part[2] for part in self.free_space) except SysCallError: return '?' - @property + @cached_property def free_space(self) -> Tuple[str, ...]: # NOTE: parted -s will default to `cancel` on prompt, skipping any partition # that is "outside" the disk. in /dev/sr0 this is usually the case with Archiso, @@ -228,7 +246,7 @@ class BlockDevice: except SysCallError as error: log(f"Could not get free space on {self.path}: {error}", level=logging.DEBUG) - @property + @cached_property def largest_free_space(self) -> List[str]: info = [] for space_info in self.free_space: @@ -240,7 +258,7 @@ class BlockDevice: info = space_info return info - @property + @cached_property def first_free_sector(self) -> str: if info := self.largest_free_space: start = info[0] @@ -248,7 +266,7 @@ class BlockDevice: start = '512MB' return start - @property + @cached_property def first_end_sector(self) -> str: if info := self.largest_free_space: end = info[1] diff --git a/archinstall/lib/hsm/fido.py b/archinstall/lib/hsm/fido.py index 8707ac52..49f36957 100644 --- a/archinstall/lib/hsm/fido.py +++ b/archinstall/lib/hsm/fido.py @@ -40,7 +40,7 @@ def get_fido2_devices() -> typing.Dict[str, typing.Dict[str, str]]: } return devices - + def fido2_enroll(hsm_device_path :pathlib.Path, partition :Partition, password :str) -> bool: worker = SysCommandWorker(f"systemd-cryptenroll --fido2-device={hsm_device_path} {partition.real_device}", peak_output=True) pw_inputted = False diff --git a/archinstall/lib/menu/global_menu.py b/archinstall/lib/menu/global_menu.py index d807433c..53e0941d 100644 --- a/archinstall/lib/menu/global_menu.py +++ b/archinstall/lib/menu/global_menu.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, List, Optional, Union +from typing import Any, List, Optional, Union, Dict, TYPE_CHECKING import archinstall @@ -33,10 +33,15 @@ from ..user_interaction import select_encrypted_partitions from ..user_interaction import select_harddrives from ..user_interaction import select_profile from ..user_interaction import select_additional_repositories +from ..user_interaction.partitioning_conf import current_partition_layout + +if TYPE_CHECKING: + _: Any + class GlobalMenu(GeneralMenu): def __init__(self,data_store): - super().__init__(data_store=data_store, auto_cursor=True) + super().__init__(data_store=data_store, auto_cursor=True, preview_size=0.3) def _setup_selection_menu_options(self): # archinstall.Language will not use preset values @@ -69,7 +74,10 @@ class GlobalMenu(GeneralMenu): self._menu_options['harddrives'] = \ Selector( _('Drive(s)'), - lambda preset: self._select_harddrives(preset)) + lambda preset: self._select_harddrives(preset), + display_func=lambda x: f'{len(x)} ' + str(_('Drive(s)')) if x is not None and len(x) > 0 else '', + preview_func=self._prev_harddrives, + ) self._menu_options['disk_layouts'] = \ Selector( _('Disk layout'), @@ -78,6 +86,8 @@ class GlobalMenu(GeneralMenu): storage['arguments'].get('harddrives', []), storage['arguments'].get('advanced', False) ), + preview_func=self._prev_disk_layouts, + display_func=lambda x: self._display_disk_layout(x), dependencies=['harddrives']) self._menu_options['!encryption-password'] = \ Selector( @@ -131,7 +141,8 @@ class GlobalMenu(GeneralMenu): Selector( _('Profile'), lambda preset: self._select_profile(preset), - display_func=lambda x: x if x else 'None') + display_func=lambda x: x if x else 'None' + ) self._menu_options['audio'] = \ Selector( _('Audio'), @@ -189,7 +200,7 @@ class GlobalMenu(GeneralMenu): def _update_install_text(self, name :str = None, result :Any = None): text = self._install_text() - self._menu_options.get('install').update_description(text) + self._menu_options['install'].update_description(text) def post_callback(self,name :str = None ,result :Any = None): self._update_install_text(name, result) @@ -225,6 +236,35 @@ class GlobalMenu(GeneralMenu): else: return str(cur_value) + def _prev_harddrives(self) -> Optional[str]: + selector = self._menu_options['harddrives'] + if selector.has_selection(): + drives = selector.current_selection + return '\n\n'.join([d.display_info for d in drives]) + return None + + def _prev_disk_layouts(self) -> Optional[str]: + selector = self._menu_options['disk_layouts'] + if selector.has_selection(): + layouts: Dict[str, Dict[str, Any]] = selector.current_selection + + output = '' + for device, layout in layouts.items(): + output += f'{_("Device")}: {device}\n\n' + output += current_partition_layout(layout['partitions'], with_title=False) + output += '\n\n' + + return output.rstrip() + + return None + + def _display_disk_layout(self, current_value: Optional[Dict[str, Any]]) -> str: + if current_value: + total_partitions = [entry['partitions'] for entry in current_value.values()] + total_nr = sum([len(p) for p in total_partitions]) + return f'{total_nr} {_("Partitions")}' + return '' + def _prev_install_missing_config(self) -> Optional[str]: if missing := self._missing_configs(): text = str(_('Missing configurations:\n')) @@ -247,17 +287,17 @@ class GlobalMenu(GeneralMenu): if not check('harddrives'): missing += ['Hard drives'] if check('harddrives'): - if not self._menu_options.get('harddrives').is_empty() and not check('disk_layouts'): + if not self._menu_options['harddrives'].is_empty() and not check('disk_layouts'): missing += ['Disk layout'] return missing - def _set_root_password(self): + def _set_root_password(self) -> Optional[str]: prompt = str(_('Enter root password (leave blank to disable root): ')) password = get_password(prompt=prompt) return password - def _select_encrypted_password(self): + def _select_encrypted_password(self) -> Optional[str]: if passwd := get_password(prompt=str(_('Enter disk encryption password (leave blank for no encryption): '))): return passwd else: @@ -271,7 +311,7 @@ class GlobalMenu(GeneralMenu): return ntp - def _select_harddrives(self, old_harddrives : list) -> list: + def _select_harddrives(self, old_harddrives : list) -> List: harddrives = select_harddrives(old_harddrives) if len(harddrives) == 0: @@ -288,7 +328,7 @@ class GlobalMenu(GeneralMenu): # in case the harddrives got changed we have to reset the disk layout as well if old_harddrives != harddrives: - self._menu_options.get('disk_layouts').set_current_selection(None) + self._menu_options['disk_layouts'].set_current_selection(None) storage['arguments']['disk_layouts'] = {} return harddrives @@ -340,11 +380,11 @@ class GlobalMenu(GeneralMenu): return ret - def _create_superuser_account(self): + def _create_superuser_account(self) -> Optional[Dict[str, Dict[str, str]]]: superusers = ask_for_superuser_account(str(_('Manage superuser accounts: '))) return superusers if superusers else None - def _create_user_account(self): + def _create_user_account(self) -> Dict[str, Dict[str, str | None]]: users = ask_for_additional_users(str(_('Manage ordinary user accounts: '))) return users @@ -356,7 +396,7 @@ class GlobalMenu(GeneralMenu): else: return list(superusers.keys()) if superusers else '' - def _users_resynch(self): + def _users_resynch(self) -> bool: self.synch('!superusers') self.synch('!users') return False diff --git a/archinstall/lib/menu/list_manager.py b/archinstall/lib/menu/list_manager.py index 9faa1c77..7db3b3a9 100644 --- a/archinstall/lib/menu/list_manager.py +++ b/archinstall/lib/menu/list_manager.py @@ -89,7 +89,7 @@ from .text_input import TextInput from .menu import Menu, MenuSelectionType from os import system from copy import copy -from typing import Union, Any, TYPE_CHECKING, Dict +from typing import Union, Any, TYPE_CHECKING, Dict, Optional if TYPE_CHECKING: _: Any @@ -147,7 +147,7 @@ class ListManager: self.base_data = base_list self._data = copy(base_list) # as refs, changes are immediate # default values for the null case - self.target = None + self.target: Optional[Any] = None self.action = self._null_action if len(self._data) == 0 and self._null_action: diff --git a/archinstall/lib/menu/selection_menu.py b/archinstall/lib/menu/selection_menu.py index 26be4cc7..57e290f1 100644 --- a/archinstall/lib/menu/selection_menu.py +++ b/archinstall/lib/menu/selection_menu.py @@ -15,7 +15,7 @@ if TYPE_CHECKING: _: Any -def select_archinstall_language(preset_value: str) -> Optional[str]: +def select_archinstall_language(preset_value: str) -> Optional[Any]: """ copied from user_interaction/general_conf.py as a temporary measure """ @@ -487,6 +487,8 @@ class GeneralMenu: match choice.type_: case MenuSelectionType.Esc: return preset case MenuSelectionType.Selection: - return pathlib.Path(list(fido_devices.keys())[int(choice.value.split('|',1)[0])]) + selection: Any = choice.value + index = int(selection.split('|',1)[0]) + return pathlib.Path(list(fido_devices.keys())[index]) - return None \ No newline at end of file + return None diff --git a/archinstall/lib/user_interaction/general_conf.py b/archinstall/lib/user_interaction/general_conf.py index c3a2a7a7..d4dc60db 100644 --- a/archinstall/lib/user_interaction/general_conf.py +++ b/archinstall/lib/user_interaction/general_conf.py @@ -142,7 +142,6 @@ def select_profile(preset) -> Optional[Profile]: options[option] = profile title = _('This is a list of pre-programmed profiles, they might make it easier to install things like desktop environments') - warning = str(_('Are you sure you want to reset this setting?')) selection = Menu( diff --git a/archinstall/lib/user_interaction/network_conf.py b/archinstall/lib/user_interaction/network_conf.py index e4e681ce..25e9d4c6 100644 --- a/archinstall/lib/user_interaction/network_conf.py +++ b/archinstall/lib/user_interaction/network_conf.py @@ -64,7 +64,7 @@ class ManualNetworkConfig(ListManager): elif self.action == self._action_delete: del data[iface_name] - def _select_iface(self, existing_ifaces: List[str]) -> Optional[str]: + def _select_iface(self, existing_ifaces: List[str]) -> Optional[Any]: all_ifaces = list_interfaces().values() available = set(all_ifaces) - set(existing_ifaces) choice = Menu(str(_('Select interface to add')), list(available), skip=True).run() @@ -94,14 +94,14 @@ class ManualNetworkConfig(ListManager): log("You need to enter a valid IP in IP-config mode.", level=logging.WARNING, fg='red') # Implemented new check for correct gateway IP address + gateway = None + while 1: - gateway = TextInput(_('Enter your gateway (router) IP address or leave blank for none: '), + gateway_input = TextInput(_('Enter your gateway (router) IP address or leave blank for none: '), edit_iface.gateway).run().strip() try: - if len(gateway) == 0: - gateway = None - else: - ipaddress.ip_address(gateway) + if len(gateway_input) > 0: + ipaddress.ip_address(gateway_input) break except ValueError: log("You need to enter a valid gateway (router) IP address.", level=logging.WARNING, fg='red') diff --git a/archinstall/lib/user_interaction/partitioning_conf.py b/archinstall/lib/user_interaction/partitioning_conf.py index 741decc1..bfff5705 100644 --- a/archinstall/lib/user_interaction/partitioning_conf.py +++ b/archinstall/lib/user_interaction/partitioning_conf.py @@ -20,9 +20,9 @@ def partition_overlap(partitions: list, start: str, end: str) -> bool: return False -def _current_partition_layout(partitions: List[Partition], with_idx: bool = False) -> str: +def current_partition_layout(partitions: List[Dict[str, Any]], with_idx: bool = False, with_title: bool = True) -> str: - def do_padding(name, max_len): + def do_padding(name: str, max_len: int): spaces = abs(len(str(name)) - max_len) + 2 pad_left = int(spaces / 2) pad_right = spaces - pad_left @@ -62,8 +62,11 @@ def _current_partition_layout(partitions: List[Partition], with_idx: bool = Fals current_layout += f'{row[:-1]}\n' - title = str(_('Current partition layout')) - return f'\n\n{title}:\n\n{current_layout}' + if with_title: + title = str(_('Current partition layout')) + return f'\n\n{title}:\n\n{current_layout}' + + return current_layout def _get_partitions(partitions :List[Partition], filter_ :Callable = None) -> List[str]: @@ -173,7 +176,7 @@ def manage_new_and_existing_partitions(block_device: 'BlockDevice') -> Dict[str, # show current partition layout: if len(block_device_struct["partitions"]): - title += _current_partition_layout(block_device_struct['partitions']) + '\n' + title += current_partition_layout(block_device_struct['partitions']) + '\n' modes += [save_and_exit, cancel] @@ -246,7 +249,7 @@ def manage_new_and_existing_partitions(block_device: 'BlockDevice') -> Dict[str, block_device_struct.update(suggest_single_disk_layout(block_device)[block_device.path]) else: - current_layout = _current_partition_layout(block_device_struct['partitions'], with_idx=True) + current_layout = current_partition_layout(block_device_struct['partitions'], with_idx=True) if task == delete_partition: title = _('{}\n\nSelect by index which partitions to delete').format(current_layout) @@ -375,7 +378,7 @@ def select_encrypted_partitions( # show current partition layout: if len(partitions): - title += _current_partition_layout(partitions) + '\n' + title += current_partition_layout(partitions) + '\n' choice = Menu(title, partition_indexes, multi=multiple).run() @@ -386,4 +389,4 @@ def select_encrypted_partitions( for partition_index in choice.value: yield int(partition_index) else: - yield (partition_index) \ No newline at end of file + yield (partition_index) diff --git a/archinstall/lib/user_interaction/utils.py b/archinstall/lib/user_interaction/utils.py index ce48607d..fa079bc2 100644 --- a/archinstall/lib/user_interaction/utils.py +++ b/archinstall/lib/user_interaction/utils.py @@ -52,6 +52,7 @@ def get_password(prompt: str = '') -> Optional[str]: continue return passwd + return None -- cgit v1.2.3-70-g09d2 From 870da403e79ab50350803b45f200e0b272334989 Mon Sep 17 00:00:00 2001 From: Daniel Girtler Date: Fri, 27 May 2022 05:48:29 +1000 Subject: Rework user management (#1220) * Rework users * Update user installation * Fix config serialization * Update * Update schemas and documentation * Update * Fix flake8 * Make users mypy compatible * Fix minor copy Co-authored-by: Daniel Girtler Co-authored-by: Anton Hvornum --- .github/workflows/mypy.yaml | 2 +- README.md | 3 +- archinstall/__init__.py | 11 +- archinstall/lib/configuration.py | 2 +- archinstall/lib/installer.py | 16 +- archinstall/lib/menu/global_menu.py | 53 +++--- archinstall/lib/menu/list_manager.py | 37 ++--- archinstall/lib/models/users.py | 77 +++++++++ archinstall/lib/output.py | 38 ++++- archinstall/lib/user_interaction/__init__.py | 2 +- .../lib/user_interaction/manage_users_conf.py | 177 +++++++-------------- archinstall/lib/user_interaction/network_conf.py | 2 + .../lib/user_interaction/subvolume_config.py | 2 + docs/installing/guided.rst | 25 ++- examples/creds-sample.json | 20 ++- examples/guided.py | 10 +- examples/minimal.py | 6 +- examples/swiss.py | 19 ++- profiles/52-54-00-12-34-56.py | 3 +- schema.json | 10 +- 20 files changed, 290 insertions(+), 225 deletions(-) create mode 100644 archinstall/lib/models/users.py (limited to 'archinstall/lib/user_interaction/network_conf.py') diff --git a/.github/workflows/mypy.yaml b/.github/workflows/mypy.yaml index 18c33e67..d14d8553 100644 --- a/.github/workflows/mypy.yaml +++ b/.github/workflows/mypy.yaml @@ -15,4 +15,4 @@ jobs: # one day this will be enabled # run: mypy --strict --module archinstall || exit 0 - name: run mypy - run: mypy --follow-imports=silent archinstall/lib/menu/selection_menu.py archinstall/lib/menu/global_menu.py archinstall/lib/models/network_configuration.py archinstall/lib/menu/list_manager.py archinstall/lib/user_interaction/network_conf.py + run: mypy --follow-imports=silent archinstall/lib/menu/selection_menu.py archinstall/lib/menu/global_menu.py archinstall/lib/models/network_configuration.py archinstall/lib/menu/list_manager.py archinstall/lib/user_interaction/network_conf.py archinstall/lib/models/users.py diff --git a/README.md b/README.md index 05a3c411..79fae095 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,8 @@ with archinstall.Installer('/mnt') as installation: # In this case, we install a minimal profile that is empty installation.install_profile('minimal') - installation.user_create('devel', 'devel') + user = User('devel', 'devel', False) + installation.create_users(user) installation.user_set_pw('root', 'airoot') ``` diff --git a/archinstall/__init__.py b/archinstall/__init__.py index fcb741e6..1e72a60e 100644 --- a/archinstall/__init__.py +++ b/archinstall/__init__.py @@ -1,7 +1,4 @@ """Arch Linux installer - guided, templates etc.""" -import urllib.error -import urllib.parse -import urllib.request from argparse import ArgumentParser from .lib.disk import * @@ -13,6 +10,7 @@ from .lib.locale_helpers import * from .lib.luks import * from .lib.mirrors import * from .lib.models.network_configuration import NetworkConfigurationHandler +from .lib.models.users import User from .lib.networking import * from .lib.output import * from .lib.models.dataclasses import ( @@ -160,7 +158,7 @@ def get_arguments() -> Dict[str, Any]: if args.creds is not None: if not json_stream_to_structure('--creds', args.creds, config): exit(1) - + # load the parameters. first the known, then the unknowns config.update(vars(args)) config.update(parse_unspecified_argument_list(unknowns)) @@ -211,6 +209,11 @@ def load_config(): handler = NetworkConfigurationHandler() handler.parse_arguments(arguments.get('nic')) arguments['nic'] = handler.configuration + if arguments.get('!users', None) is not None or arguments.get('!superusers', None) is not None: + users = arguments.get('!users', None) + superusers = arguments.get('!superusers', None) + arguments['!users'] = User.parse_arguments(users, superusers) + def post_process_arguments(arguments): storage['arguments'] = arguments diff --git a/archinstall/lib/configuration.py b/archinstall/lib/configuration.py index f3fe1e1c..510f7103 100644 --- a/archinstall/lib/configuration.py +++ b/archinstall/lib/configuration.py @@ -37,7 +37,7 @@ class ConfigurationOutput: self._user_creds_file = "user_credentials.json" self._disk_layout_file = "user_disk_layout.json" - self._sensitive = ['!users', '!superusers', '!encryption-password'] + self._sensitive = ['!users', '!encryption-password'] self._ignore = ['abort', 'install', 'config', 'creds', 'dry_run'] self._process_config() diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 5cedc9d6..903d33af 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -23,6 +23,7 @@ from .profiles import Profile from .disk.partition import get_mount_fs_type from .exceptions import DiskError, ServiceException, RequirementError, HardwareIncompatibilityError, SysCallError from .hsm import fido2_enroll +from .models.users import User if TYPE_CHECKING: _: Any @@ -251,7 +252,7 @@ class Installer: loopdev = f"{storage.get('ENC_IDENTIFIER', 'ai')}{pathlib.Path(partition['mountpoint']).name}loop" else: loopdev = f"{storage.get('ENC_IDENTIFIER', 'ai')}{pathlib.Path(partition['device_instance'].path).name}" - + # note that we DON'T auto_unmount (i.e. close the encrypted device so it can be used with (luks_handle := luks2(partition['device_instance'], loopdev, password, auto_unmount=False)) as unlocked_device: if partition.get('generate-encryption-key-file',False) and not self._has_root(partition): @@ -426,7 +427,7 @@ class Installer: if storage['arguments'].get('silent', False) is False: if input('Would you like to re-try this download? (Y/n): ').lower().strip() in ('', 'y'): return self.pacstrap(*packages, **kwargs) - + raise RequirementError("Pacstrap failed. See /var/log/archinstall/install.log or above message for error details.") def set_mirrors(self, mirrors :Mapping[str, Iterator[str]]) -> None: @@ -1062,7 +1063,7 @@ class Installer: self.log(f'Installing archinstall profile {profile}', level=logging.INFO) return profile.install() - def enable_sudo(self, entity: str, group :bool = False) -> bool: + def enable_sudo(self, entity: str, group :bool = False): self.log(f'Enabling sudo permissions for {entity}.', level=logging.INFO) sudoers_dir = f"{self.target}/etc/sudoers.d" @@ -1092,9 +1093,14 @@ class Installer: # Guarantees sudoer conf file recommended perms os.chmod(pathlib.Path(rule_file_name), 0o440) - return True + def create_users(self, users: Union[User, List[User]]): + if not isinstance(users, list): + users = [users] + + for user in users: + self.user_create(user.username, user.password, user.groups, user.sudo) - def user_create(self, user :str, password :Optional[str] = None, groups :Optional[str] = None, sudo :bool = False) -> None: + def user_create(self, user :str, password :Optional[str] = None, groups :Optional[List[str]] = None, sudo :bool = False) -> None: if groups is None: groups = [] diff --git a/archinstall/lib/menu/global_menu.py b/archinstall/lib/menu/global_menu.py index 53e0941d..5cb27cab 100644 --- a/archinstall/lib/menu/global_menu.py +++ b/archinstall/lib/menu/global_menu.py @@ -21,7 +21,6 @@ from ..user_interaction import ask_hostname from ..user_interaction import ask_for_audio_selection from ..user_interaction import ask_additional_packages_to_install from ..user_interaction import ask_to_configure_network -from ..user_interaction import ask_for_superuser_account from ..user_interaction import ask_for_additional_users from ..user_interaction import select_language from ..user_interaction import select_mirror_regions @@ -33,7 +32,9 @@ from ..user_interaction import select_encrypted_partitions from ..user_interaction import select_harddrives from ..user_interaction import select_profile from ..user_interaction import select_additional_repositories +from ..models.users import User from ..user_interaction.partitioning_conf import current_partition_layout +from ..output import FormattedOutput if TYPE_CHECKING: _: Any @@ -122,21 +123,13 @@ class GlobalMenu(GeneralMenu): _('Root password'), lambda preset:self._set_root_password(), display_func=lambda x: secret(x) if x else 'None') - self._menu_options['!superusers'] = \ - Selector( - _('Superuser account'), - lambda preset: self._create_superuser_account(), - default={}, - exec_func=lambda n,v:self._users_resynch(), - dependencies_not=['!root-password'], - display_func=lambda x: self._display_superusers()) self._menu_options['!users'] = \ Selector( _('User account'), - lambda x: self._create_user_account(), + lambda x: self._create_user_account(x), default={}, - exec_func=lambda n,v:self._users_resynch(), - display_func=lambda x: list(x.keys()) if x else '[]') + display_func=lambda x: f'{len(x)} {_("User(s)")}' if len(x) > 0 else None, + preview_func=self._prev_users) self._menu_options['profile'] = \ Selector( _('Profile'), @@ -273,17 +266,28 @@ class GlobalMenu(GeneralMenu): return text[:-1] # remove last new line return None + def _prev_users(self) -> Optional[str]: + selector = self._menu_options['!users'] + if selector.has_selection(): + users: List[User] = selector.current_selection + return FormattedOutput.as_table(users) + return None + def _missing_configs(self) -> List[str]: def check(s): return self._menu_options.get(s).has_selection() + def has_superuser() -> bool: + users = self._menu_options['!users'].current_selection + return any([u.sudo for u in users]) + missing = [] if not check('bootloader'): missing += ['Bootloader'] if not check('hostname'): missing += ['Hostname'] - if not check('!root-password') and not check('!superusers'): - missing += [str(_('Either root-password or at least 1 superuser must be specified'))] + if not check('!root-password') and not has_superuser(): + missing += [str(_('Either root-password or at least 1 user with sudo privileges must be specified'))] if not check('harddrives'): missing += ['Hard drives'] if check('harddrives'): @@ -380,23 +384,6 @@ class GlobalMenu(GeneralMenu): return ret - def _create_superuser_account(self) -> Optional[Dict[str, Dict[str, str]]]: - superusers = ask_for_superuser_account(str(_('Manage superuser accounts: '))) - return superusers if superusers else None - - def _create_user_account(self) -> Dict[str, Dict[str, str | None]]: - users = ask_for_additional_users(str(_('Manage ordinary user accounts: '))) + def _create_user_account(self, defined_users: List[User]) -> List[User]: + users = ask_for_additional_users(defined_users=defined_users) return users - - def _display_superusers(self): - superusers = self._data_store.get('!superusers', {}) - - if self._menu_options.get('!root-password').has_selection(): - return list(superusers.keys()) if superusers else '[]' - else: - return list(superusers.keys()) if superusers else '' - - def _users_resynch(self) -> bool: - self.synch('!superusers') - self.synch('!users') - return False diff --git a/archinstall/lib/menu/list_manager.py b/archinstall/lib/menu/list_manager.py index 7db3b3a9..cb567093 100644 --- a/archinstall/lib/menu/list_manager.py +++ b/archinstall/lib/menu/list_manager.py @@ -84,13 +84,13 @@ The contents in the base class of this methods serve for a very basic usage, and ``` """ - -from .text_input import TextInput -from .menu import Menu, MenuSelectionType +import copy from os import system -from copy import copy from typing import Union, Any, TYPE_CHECKING, Dict, Optional +from .text_input import TextInput +from .menu import Menu + if TYPE_CHECKING: _: Any @@ -144,14 +144,14 @@ class ListManager: self.bottom_list = [self.confirm_action,self.cancel_action] self.bottom_item = [self.cancel_action] self.base_actions = base_actions if base_actions else [str(_('Add')),str(_('Copy')),str(_('Edit')),str(_('Delete'))] - self.base_data = base_list - self._data = copy(base_list) # as refs, changes are immediate + self._original_data = copy.deepcopy(base_list) + self._data = copy.deepcopy(base_list) # as refs, changes are immediate # default values for the null case self.target: Optional[Any] = None self.action = self._null_action if len(self._data) == 0 and self._null_action: - self.exec_action(self._data) + self._data = self.exec_action(self._data) def run(self): while True: @@ -175,12 +175,10 @@ class ListManager: clear_screen=False, clear_menu_on_exit=False, header=self.header, - skip_empty_entries=True + skip_empty_entries=True, + skip=False ).run() - if target.type_ == MenuSelectionType.Esc: - return self.run() - if not target.value or target.value in self.bottom_list: self.action = target break @@ -188,21 +186,23 @@ class ListManager: if target.value and target.value in self._default_action: self.action = target.value self.target = None - self.exec_action(self._data) + self._data = self.exec_action(self._data) continue if isinstance(self._data,dict): data_key = data_formatted[target.value] key = self._data[data_key] self.target = {data_key: key} + elif isinstance(self._data, list): + self.target = [d for d in self._data if d == data_formatted[target.value]][0] else: self.target = self._data[data_formatted[target.value]] # Possible enhacement. If run_actions returns false a message line indicating the failure self.run_actions(target.value) - if not target or target == self.cancel_action: # TODO dubious - return self.base_data # return the original list + if target.value == self.cancel_action: # TODO dubious + return self._original_data # return the original list else: return self._data @@ -221,10 +221,9 @@ class ListManager: self.action = choice.value - if not self.action or self.action == self.cancel_action: - return False - else: - return self.exec_action(self._data) + if self.action and self.action != self.cancel_action: + self._data = self.exec_action(self._data) + """ The following methods are expected to be overwritten by the user if the needs of the list are beyond the simple case """ @@ -293,3 +292,5 @@ class ListManager: self._data[origkey] = value elif self.action == str(_('Delete')): del self._data[origkey] + + return self._data diff --git a/archinstall/lib/models/users.py b/archinstall/lib/models/users.py new file mode 100644 index 00000000..6052b73a --- /dev/null +++ b/archinstall/lib/models/users.py @@ -0,0 +1,77 @@ +from dataclasses import dataclass +from typing import Dict, List, Union, Any, TYPE_CHECKING + +if TYPE_CHECKING: + _: Any + + +@dataclass +class User: + username: str + password: str + sudo: bool + + @property + def groups(self) -> List[str]: + # this property should be transferred into a class attr instead + # if it's every going to be used + return [] + + def json(self) -> Dict[str, Any]: + return { + 'username': self.username, + '!password': self.password, + 'sudo': self.sudo + } + + def display(self) -> str: + password = '*' * len(self.password) + return f'{_("Username")}: {self.username:16} {_("Password")}: {password:16} sudo: {str(self.sudo)}' + + @classmethod + def _parse(cls, config_users: List[Dict[str, Any]]) -> List['User']: + users = [] + + for entry in config_users: + username = entry.get('username', None) + password = entry.get('!password', '') + sudo = entry.get('sudo', False) + + if username is None: + continue + + user = User(username, password, sudo) + users.append(user) + + return users + + @classmethod + def _parse_backwards_compatible(cls, config_users: Dict, sudo: bool) -> List['User']: + if len(config_users.keys()) > 0: + username = list(config_users.keys())[0] + password = config_users[username]['!password'] + + if password: + return [User(username, password, sudo)] + + return [] + + @classmethod + def parse_arguments( + cls, + config_users: Union[List[Dict[str, str]], Dict[str, str]], + config_superusers: Union[List[Dict[str, str]], Dict[str, str]] + ) -> List['User']: + users = [] + + # backwards compability + if isinstance(config_users, dict): + users += cls._parse_backwards_compatible(config_users, False) + else: + users += cls._parse(config_users) + + # backwards compability + if isinstance(config_superusers, dict): + users += cls._parse_backwards_compatible(config_superusers, True) + + return users diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py index 07747091..29b73bc4 100644 --- a/archinstall/lib/output.py +++ b/archinstall/lib/output.py @@ -2,11 +2,47 @@ import logging import os import sys from pathlib import Path -from typing import Dict, Union +from typing import Dict, Union, List, Any from .storage import storage +class FormattedOutput: + + @classmethod + def values(cls, o: Any) -> Dict[str, Any]: + if hasattr(o, 'json'): + return o.json() + else: + return o.__dict__ + + @classmethod + def as_table(cls, obj: List[Any]) -> str: + column_width: Dict[str, int] = {} + for o in obj: + for k, v in cls.values(o).items(): + column_width.setdefault(k, 0) + column_width[k] = max([column_width[k], len(str(v)), len(k)]) + + output = '' + for key, width in column_width.items(): + key = key.replace('!', '') + output += key.ljust(width) + ' | ' + + output = output[:-3] + '\n' + output += '-' * len(output) + '\n' + + for o in obj: + for k, v in cls.values(o).items(): + if '!' in k: + v = '*' * len(str(v)) + output += str(v).ljust(column_width[k]) + ' | ' + output = output[:-3] + output += '\n' + + return output + + class Journald: @staticmethod def log(message :str, level :int = logging.DEBUG) -> None: diff --git a/archinstall/lib/user_interaction/__init__.py b/archinstall/lib/user_interaction/__init__.py index b0174d94..8aba4b4d 100644 --- a/archinstall/lib/user_interaction/__init__.py +++ b/archinstall/lib/user_interaction/__init__.py @@ -1,5 +1,5 @@ from .save_conf import save_config -from .manage_users_conf import ask_for_superuser_account, ask_for_additional_users +from .manage_users_conf import ask_for_additional_users from .backwards_compatible_conf import generic_select, generic_multi_select from .locale_conf import select_locale_lang, select_locale_enc from .system_conf import select_kernel, select_harddrives, select_driver, ask_for_bootloader, ask_for_swap diff --git a/archinstall/lib/user_interaction/manage_users_conf.py b/archinstall/lib/user_interaction/manage_users_conf.py index ea909f35..567a2964 100644 --- a/archinstall/lib/user_interaction/manage_users_conf.py +++ b/archinstall/lib/user_interaction/manage_users_conf.py @@ -1,14 +1,12 @@ from __future__ import annotations -import logging import re -from typing import Any, Dict, TYPE_CHECKING, List +from typing import Any, Dict, TYPE_CHECKING, List, Optional +from .utils import get_password from ..menu import Menu from ..menu.list_manager import ListManager -from ..output import log -from ..storage import storage -from .utils import get_password +from ..models.users import User if TYPE_CHECKING: _: Any @@ -19,7 +17,7 @@ class UserList(ListManager): subclass of ListManager for the managing of user accounts """ - def __init__(self, prompt: str, lusers: dict, sudo: bool = None): + def __init__(self, prompt: str, lusers: List[User]): """ param: prompt type: str @@ -27,140 +25,83 @@ class UserList(ListManager): type: Dict param: sudo. boolean to determine if we handle superusers or users. If None handles both types """ - self.sudo = sudo - self.actions = [ + self._actions = [ str(_('Add a user')), str(_('Change password')), str(_('Promote/Demote user')), str(_('Delete User')) ] - super().__init__(prompt, lusers, self.actions, self.actions[0]) - - def reformat(self, data: List) -> Dict: - def format_element(elem :str): - # secret gives away the length of the password - if data[elem].get('!password'): - pwd = '*' * 16 - else: - pwd = '' - if data[elem].get('sudoer'): - super_user = 'Superuser' - else: - super_user = ' ' - return f"{elem:16}: password {pwd:16} {super_user}" + super().__init__(prompt, lusers, self._actions, self._actions[0]) - return {format_element(e): e for e in data} + def reformat(self, data: List[User]) -> Dict[str, User]: + return {e.display(): e for e in data} def action_list(self): - if self.target: - active_user = list(self.target.keys())[0] - else: - active_user = None - sudoer = self.target[active_user].get('sudoer', False) - if self.sudo is None: - return self.actions - if self.sudo and sudoer: - return self.actions - elif self.sudo and not sudoer: - return [self.actions[2]] - elif not self.sudo and sudoer: - return [self.actions[2]] + active_user = self.target if self.target else None + + if active_user is None: + return [self._actions[0]] else: - return self.actions + return self._actions[1:] - def exec_action(self, data: Any): + def exec_action(self, data: List[User]) -> List[User]: if self.target: - active_user = list(self.target.keys())[0] + active_user = self.target else: active_user = None - if self.action == self.actions[0]: # add - new_user = self.add_user() - # no unicity check, if exists will be replaced - data.update(new_user) - elif self.action == self.actions[1]: # change password - data[active_user]['!password'] = get_password( - prompt=str(_('Password for user "{}": ').format(active_user))) - elif self.action == self.actions[2]: # promote/demote - data[active_user]['sudoer'] = not data[active_user]['sudoer'] - elif self.action == self.actions[3]: # delete - del data[active_user] + if self.action == self._actions[0]: # add + new_user = self._add_user() + if new_user is not None: + # in case a user with the same username as an existing user + # was created we'll replace the existing one + data = [d for d in data if d.username != new_user.username] + data += [new_user] + elif self.action == self._actions[1]: # change password + prompt = str(_('Password for user "{}": ').format(active_user.username)) + new_password = get_password(prompt=prompt) + if new_password: + user = next(filter(lambda x: x == active_user, data), 1) + user.password = new_password + elif self.action == self._actions[2]: # promote/demote + user = next(filter(lambda x: x == active_user, data), 1) + user.sudo = False if user.sudo else True + elif self.action == self._actions[3]: # delete + data = [d for d in data if d != active_user] + + return data def _check_for_correct_username(self, username: str) -> bool: if re.match(r'^[a-z_][a-z0-9_-]*\$?$', username) and len(username) <= 32: return True - log("The username you entered is invalid. Try again", level=logging.WARNING, fg='red') return False - def add_user(self): + def _add_user(self) -> Optional[User]: print(_('\nDefine a new user\n')) - prompt = str(_("User Name : ")) + prompt = str(_('Enter username (leave blank to skip): ')) + while True: - userid = input(prompt).strip(' ') - if not userid: - return {} # end - if not self._check_for_correct_username(userid): - pass + username = input(prompt).strip(' ') + if not username: + return None + if not self._check_for_correct_username(username): + prompt = str(_("The username you entered is invalid. Try again")) + '\n' + prompt else: break - if self.sudo: - sudoer = True - elif self.sudo is not None and not self.sudo: - sudoer = False - else: - sudoer = False - sudo_choice = Menu(str(_('Should {} be a superuser (sudoer)?')).format(userid), Menu.yes_no(), - skip=False, - preset_values=Menu.yes() if sudoer else Menu.no(), - default_option=Menu.no()).run() - sudoer = True if sudo_choice == Menu.yes() else False - - password = get_password(prompt=str(_('Password for user "{}": ').format(userid))) - - return {userid: {"!password": password, "sudoer": sudoer}} - - -def manage_users(prompt: str, sudo: bool) -> tuple[dict, dict]: - # TODO Filtering and some kind of simpler code - lusers = {} - if storage['arguments'].get('!superusers', {}): - lusers.update({ - uid: { - '!password': storage['arguments']['!superusers'][uid].get('!password'), - 'sudoer': True - } - for uid in storage['arguments'].get('!superusers', {}) - }) - if storage['arguments'].get('!users', {}): - lusers.update({ - uid: { - '!password': storage['arguments']['!users'][uid].get('!password'), - 'sudoer': False - } - for uid in storage['arguments'].get('!users', {}) - }) - # processing - lusers = UserList(prompt, lusers, sudo).run() - # return data - superusers = { - uid: { - '!password': lusers[uid].get('!password') - } - for uid in lusers if lusers[uid].get('sudoer', False) - } - users = {uid: {'!password': lusers[uid].get('!password')} for uid in lusers if not lusers[uid].get('sudoer', False)} - storage['arguments']['!superusers'] = superusers - storage['arguments']['!users'] = users - return superusers, users - - -def ask_for_superuser_account(prompt: str) -> Dict[str, Dict[str, str]]: - prompt = prompt if prompt else str(_('Define users with sudo privilege, by username: ')) - superusers, dummy = manage_users(prompt, sudo=True) - return superusers - - -def ask_for_additional_users(prompt: str = '') -> Dict[str, Dict[str, str | None]]: - prompt = prompt if prompt else _('Any additional users to install (leave blank for no users): ') - dummy, users = manage_users(prompt, sudo=False) + + password = get_password(prompt=str(_('Password for user "{}": ').format(username))) + + choice = Menu( + str(_('Should "{}" be a superuser (sudo)?')).format(username), Menu.yes_no(), + skip=False, + default_option=Menu.no() + ).run() + + sudo = True if choice.value == Menu.yes() else False + return User(username, password, sudo) + + +def ask_for_additional_users(prompt: str = '', defined_users: List[User] = []) -> List[User]: + prompt = prompt if prompt else _('Enter username (leave blank to skip): ') + users = UserList(prompt, defined_users).run() return users diff --git a/archinstall/lib/user_interaction/network_conf.py b/archinstall/lib/user_interaction/network_conf.py index 25e9d4c6..5154d8b1 100644 --- a/archinstall/lib/user_interaction/network_conf.py +++ b/archinstall/lib/user_interaction/network_conf.py @@ -64,6 +64,8 @@ class ManualNetworkConfig(ListManager): elif self.action == self._action_delete: del data[iface_name] + return data + def _select_iface(self, existing_ifaces: List[str]) -> Optional[Any]: all_ifaces = list_interfaces().values() available = set(all_ifaces) - set(existing_ifaces) diff --git a/archinstall/lib/user_interaction/subvolume_config.py b/archinstall/lib/user_interaction/subvolume_config.py index 7383b13d..af783639 100644 --- a/archinstall/lib/user_interaction/subvolume_config.py +++ b/archinstall/lib/user_interaction/subvolume_config.py @@ -57,6 +57,8 @@ class SubvolumeList(ListManager): data.update(self.target) + return data + class SubvolumeMenu(GeneralMenu): def __init__(self,parameters,action=None): diff --git a/docs/installing/guided.rst b/docs/installing/guided.rst index ac6254f2..569b2d05 100644 --- a/docs/installing/guided.rst +++ b/docs/installing/guided.rst @@ -163,21 +163,20 @@ Options for ``--creds`` "!root-password" : "SecretSanta2022" } -+----------------------+-----------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ -| Key | Values | Description | Required | -| | | | | -+======================+=====================================================+======================================================================================+===============================================+ -| !encryption-password | any | Password to encrypt disk, not encrypted if password not provided | No | -+----------------------+-----------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ -| !root-password | any | The root account password | No | -+----------------------+-----------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ -| !superusers | { "": { "!password": ""}, ..} | List of superuser credentials, see configuration for reference | Yes[1] | -+----------------------+-----------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ -| !users | { "": { "!password": ""}, ..} | List of regular user credentials, see configuration for reference | No | -+----------------------+-----------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ ++----------------------+--------------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ +| Key | Values | Description | Required | ++======================+========================================================+======================================================================================+===============================================+ +| !encryption-password | any | Password to encrypt disk, not encrypted if password not provided | No | ++----------------------+--------------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ +| !root-password | any | The root account password | No | ++----------------------+--------------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ +| !users | { "username": "" | List of regular user credentials, see configuration for reference | No | +| | "!password": "", | | | +| | "sudo": false|true} | | | ++----------------------+--------------------------------------------------------+--------------------------------------------------------------------------------------+-----------------------------------------------+ .. note:: - [1] ``!superusers`` is optional only if ``!root-password`` was set. ``!superusers`` will be enforced otherwise and the minimum amount of superusers required will be set to 1. + [1] ``!users`` is optional only if ``!root-password`` was set. ``!users`` will be enforced otherwise and the minimum amount of users with sudo privileges required will be set to 1. Options for ``--disk_layouts`` ------------------------------ diff --git a/examples/creds-sample.json b/examples/creds-sample.json index 16aeb8cc..0681e16f 100644 --- a/examples/creds-sample.json +++ b/examples/creds-sample.json @@ -1,9 +1,15 @@ { "!root-password": "", - "!users": { - "username": {"!password": ""} - }, - "!superusers": { - "admin": {"!password": ""} - } -} \ No newline at end of file + "!users": [ + { + "username": "", + "!password": "", + "sudo": false + }, + { + "username": "", + "!password": "", + "sudo": true + } + ] +} diff --git a/examples/guided.py b/examples/guided.py index 3b762a8b..19b0d638 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -72,7 +72,6 @@ def ask_user_questions(): # Ask for a root password (optional, but triggers requirement for super-user if skipped) global_menu.enable('!root-password') - global_menu.enable('!superusers') global_menu.enable('!users') # Ask for archinstall-specific profiles (such as desktop environments etc) @@ -220,13 +219,8 @@ def perform_installation(mountpoint): if archinstall.arguments.get('profile', None): installation.install_profile(archinstall.arguments.get('profile', None)) - if archinstall.arguments.get('!users',{}): - for user, user_info in archinstall.arguments.get('!users', {}).items(): - installation.user_create(user, user_info["!password"], sudo=False) - - if archinstall.arguments.get('!superusers',{}): - for superuser, user_info in archinstall.arguments.get('!superusers', {}).items(): - installation.user_create(superuser, user_info["!password"], sudo=True) + if users := archinstall.arguments.get('!users', None): + installation.create_users(users) if timezone := archinstall.arguments.get('timezone', None): installation.set_timezone(timezone) diff --git a/examples/minimal.py b/examples/minimal.py index d80c4045..8b4c847f 100644 --- a/examples/minimal.py +++ b/examples/minimal.py @@ -1,6 +1,8 @@ import archinstall # Select a harddrive and a disk password +from archinstall import User + archinstall.log("Minimal only supports:") archinstall.log(" * Being installed to a single disk") @@ -28,8 +30,8 @@ def install_on(mountpoint): installation.add_additional_packages(['nano', 'wget', 'git']) installation.install_profile('minimal') - installation.user_create('devel', 'devel') - installation.user_set_pw('root', 'airoot') + user = User('devel', 'devel', False) + installation.create_users(user) # Once this is done, we output some useful information to the user # And the installation is complete. diff --git a/examples/swiss.py b/examples/swiss.py index 2f7d90c4..d0f02dc1 100644 --- a/examples/swiss.py +++ b/examples/swiss.py @@ -219,7 +219,7 @@ class MyMenu(archinstall.GlobalMenu): if self._execution_mode in ('full','lineal'): options_list = ['keyboard-layout', 'mirror-region', 'harddrives', 'disk_layouts', '!encryption-password','swap', 'bootloader', 'hostname', '!root-password', - '!superusers', '!users', 'profile', 'audio', 'kernels', 'packages','additional-repositories','nic', + '!users', 'profile', 'audio', 'kernels', 'packages','additional-repositories','nic', 'timezone', 'ntp'] if archinstall.arguments.get('advanced',False): options_list.extend(['sys-language','sys-encoding']) @@ -229,7 +229,7 @@ class MyMenu(archinstall.GlobalMenu): mandatory_list = ['harddrives'] elif self._execution_mode == 'only_os': options_list = ['keyboard-layout', 'mirror-region','bootloader', 'hostname', - '!root-password', '!superusers', '!users', 'profile', 'audio', 'kernels', + '!root-password', '!users', 'profile', 'audio', 'kernels', 'packages', 'additional-repositories', 'nic', 'timezone', 'ntp'] mandatory_list = ['hostname'] if archinstall.arguments.get('advanced',False): @@ -262,8 +262,12 @@ class MyMenu(archinstall.GlobalMenu): def check(s): return self.option(s).has_selection() + def has_superuser() -> bool: + users = self._menu_options['!users'].current_selection + return any([u.sudo for u in users]) + _, missing = self.mandatory_overview() - if mode in ('full','only_os') and (not check('!root-password') and not check('!superusers')): + if mode in ('full','only_os') and (not check('!root-password') and not has_superuser()): missing += 1 if mode in ('full', 'only_hd') and check('harddrives'): if not self.option('harddrives').is_empty() and not check('disk_layouts'): @@ -420,13 +424,8 @@ def os_setup(installation): if archinstall.arguments.get('profile', None): installation.install_profile(archinstall.arguments.get('profile', None)) - if archinstall.arguments.get('!users',{}): - for user, user_info in archinstall.arguments.get('!users', {}).items(): - installation.user_create(user, user_info["!password"], sudo=False) - - if archinstall.arguments.get('!superusers',{}): - for superuser, user_info in archinstall.arguments.get('!superusers', {}).items(): - installation.user_create(superuser, user_info["!password"], sudo=True) + if users := archinstall.arguments.get('!users', None): + installation.create_users(users) if timezone := archinstall.arguments.get('timezone', None): installation.set_timezone(timezone) diff --git a/profiles/52-54-00-12-34-56.py b/profiles/52-54-00-12-34-56.py index 0a1626d9..3b074629 100644 --- a/profiles/52-54-00-12-34-56.py +++ b/profiles/52-54-00-12-34-56.py @@ -40,7 +40,8 @@ with archinstall.Filesystem(harddrive) as fs: installation.add_additional_packages(__packages__) installation.install_profile('awesome') - installation.user_create('devel', 'devel') + user = User('devel', 'devel', False) + installation.create_users(user) installation.user_set_pw('root', 'toor') print(f'Submitting {archinstall.__version__}: success') diff --git a/schema.json b/schema.json index e6f73c6c..9269e8e8 100644 --- a/schema.json +++ b/schema.json @@ -167,7 +167,15 @@ }, { "required": [ - "!superusers" + "!users": { + "description": "User account", + "type": "object", + "properties": { + "username": "string", + "!password": "string", + "sudo": "boolean" + } + } ] } ] -- cgit v1.2.3-70-g09d2