From ee3c48c965b2e7a2ed9427c2b5179318d52887c0 Mon Sep 17 00:00:00 2001 From: advaithm Date: Fri, 12 Mar 2021 12:02:03 +0530 Subject: updated examples --- examples/minimal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/minimal.py b/examples/minimal.py index 664bad0d..b5bb34e0 100644 --- a/examples/minimal.py +++ b/examples/minimal.py @@ -8,7 +8,7 @@ archinstall.sys_command(f'cryptsetup close /dev/mapper/luksloop', suppress_error harddrive = archinstall.select_disk(archinstall.all_disks()) disk_password = getpass.getpass(prompt='Disk password (won\'t echo): ') -with archinstall.Filesystem(harddrive, archinstall.GPT) as fs: +with archinstall.Filesystem(harddrive) as fs: # Use the entire disk instead of setting up partitions on your own fs.use_entire_disk('luks2') -- cgit v1.2.3-54-g00ecf From b974b93004efa9912e404f5d3fca7c44a58dc0e3 Mon Sep 17 00:00:00 2001 From: advaithm Date: Fri, 2 Apr 2021 10:08:16 +0530 Subject: fixed some issues with the changes --- archinstall/lib/disk.py | 7 ++----- archinstall/lib/installer.py | 12 +++++++++++- examples/guided.py | 8 +++++++- 3 files changed, 20 insertions(+), 7 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/disk.py b/archinstall/lib/disk.py index fbc11ca3..8e9e0234 100644 --- a/archinstall/lib/disk.py +++ b/archinstall/lib/disk.py @@ -390,12 +390,9 @@ class Filesystem(): # TODO: # When instance of a HDD is selected, check all usages and gracefully unmount them # as well as close any crypto handles. - def __init__(self, blockdevice): + def __init__(self, blockdevice,mode): self.blockdevice = blockdevice - if hasUEFI(): - self.mode = GPT - else: - self.mode = MBR + self.mode = mode def __enter__(self, *args, **kwargs): if self.blockdevice.keep_partitions is False: diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index d161c3b7..492d7715 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -1,4 +1,4 @@ -import os, stat, time, shutil, pathlib +import os, stat, time, shutil, pathlib, subprocess from .exceptions import * from .disk import * @@ -398,6 +398,16 @@ class Installer(): break raise RequirementError(f"Could not identify the UUID of {self.partition}, there for {self.mountpoint}/boot/loader/entries/arch.conf will be broken until fixed.") + elif bootloader == "grub-install": + if hasUEFI(): + o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.mountpoint} grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=GRUB')) + sys_command('/usr/bin/arch-chroot grub-mkconfig -o /boot/grub/grub.cfg') + else: + root_device = subprocess.check_output(f'basename "$(readlink -f "/sys/class/block/{self.partition.path.strip("/dev/")}/..")',shell=True).decode().strip() + if root_device == "block": + root_device = f"{self.partition.path}" + o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.mountpoint} grub-install --target=--target=i386-pc /dev/{root_device}')) + sys_command('/usr/bin/arch-chroot grub-mkconfig -o /boot/grub/grub.cfg') else: raise RequirementError(f"Unknown (or not yet implemented) bootloader added to add_bootloader(): {bootloader}") diff --git a/examples/guided.py b/examples/guided.py index 71e1e01d..f374a41c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -1,5 +1,6 @@ import getpass, time, json, sys, signal, os import archinstall +from archinstall.lib.hardware import hasUEFI """ This signal-handler chain (and global variable) @@ -244,7 +245,12 @@ def perform_installation_steps(): Setup the blockdevice, filesystem (and optionally encryption). Once that's done, we'll hand over to perform_installation() """ - with archinstall.Filesystem(archinstall.arguments['harddrive'], archinstall.GPT) as fs: + # maybe we can ask the user what they would prefer on uefi systems? + if hasUEFI(): + mode = archinstall.GPT + else: + mode = archinstall.MBR + with archinstall.Filesystem(archinstall.arguments['harddrive'],mode) as fs: # Wipe the entire drive if the disk flag `keep_partitions`is False. if archinstall.arguments['harddrive'].keep_partitions is False: fs.use_entire_disk(root_filesystem_type=archinstall.arguments.get('filesystem', 'btrfs')) -- cgit v1.2.3-54-g00ecf From ae5f9b08c4a670d2c020923a042fdcbaa5c2a1d6 Mon Sep 17 00:00:00 2001 From: advaithm Date: Sun, 4 Apr 2021 07:33:17 +0530 Subject: updated guided.py to allow network manager as nic --- examples/guided.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index f374a41c..ec66e892 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -317,7 +317,8 @@ def perform_installation(device, boot_partition, language, mirrors): # Perform a copy of the config if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. - + elif archinstall.arguments.get('NetworkManager',None) == True: + installation.enable_service('NetworkManager.service') # Otherwise, if a interface was selected, configure that interface elif archinstall.arguments.get('nic', None): installation.configure_nic(**archinstall.arguments.get('nic', {})) -- cgit v1.2.3-54-g00ecf From 9e3ded83119df6a5f2b470ee648754869d4eb824 Mon Sep 17 00:00:00 2001 From: advaithm Date: Sun, 4 Apr 2021 08:54:35 +0530 Subject: install networkmanager, if required --- examples/guided.py | 1 + 1 file changed, 1 insertion(+) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index ec66e892..5ca45008 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -318,6 +318,7 @@ def perform_installation(device, boot_partition, language, mirrors): if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. elif archinstall.arguments.get('NetworkManager',None) == True: + installation.add_additional_packages("networkmanager") installation.enable_service('NetworkManager.service') # Otherwise, if a interface was selected, configure that interface elif archinstall.arguments.get('nic', None): -- cgit v1.2.3-54-g00ecf From 9daa3f49242227e0cc6c2272b9322578edaab644 Mon Sep 17 00:00:00 2001 From: advaithm Date: Sun, 4 Apr 2021 09:26:28 +0530 Subject: fixed some typos and changed up how we detect if we have to enable/install network manager --- archinstall/lib/user_interaction.py | 4 ++-- examples/guided.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 83e59e90..f8b4d9c5 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -94,11 +94,11 @@ def ask_to_configure_network(): # Optionally configure one network interface. #while 1: # {MAC: Ifname} - interfaces = {'ISO-CONFIG' : 'Copy ISO network configuration to installation','NetworkManager':'Use NetworkManager to control and manage you internet conntetion', **list_interfaces()} + interfaces = {'ISO-CONFIG' : 'Copy ISO network configuration to installation','NetworkManager':'Use NetworkManager to control and manage your internet connection', **list_interfaces()} nic = generic_select(interfaces.values(), "Select one network interface to configure (leave blank to skip): ") if nic and nic != 'Copy ISO network configuration to installation': - if nic == 'Use NetworkManager to control and manage you internet conntetion': + if nic == 'Use NetworkManager to control and manage your internet connection': return {'nic': nic,'NetworkManager':True} mode = generic_select(['DHCP (auto detect)', 'IP (static)'], f"Select which mode to configure for {nic}: ") if mode == 'IP (static)': diff --git a/examples/guided.py b/examples/guided.py index 5ca45008..1e077169 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -317,7 +317,7 @@ def perform_installation(device, boot_partition, language, mirrors): # Perform a copy of the config if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. - elif archinstall.arguments.get('NetworkManager',None) == True: + elif archinstall.arguments.get('nic',None) == 'Use NetworkManager to control and manage your internet connection': installation.add_additional_packages("networkmanager") installation.enable_service('NetworkManager.service') # Otherwise, if a interface was selected, configure that interface -- cgit v1.2.3-54-g00ecf From 8ad4a7d1c42ec5aaf665d4f769cc4860780225d2 Mon Sep 17 00:00:00 2001 From: Advaith Madhukar Date: Sun, 4 Apr 2021 14:42:19 +0530 Subject: fixed network manager check --- examples/guided.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 1e077169..1a1cf84c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -317,7 +317,7 @@ def perform_installation(device, boot_partition, language, mirrors): # Perform a copy of the config if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. - elif archinstall.arguments.get('nic',None) == 'Use NetworkManager to control and manage your internet connection': + elif archinstall.arguments.get('nic',{}).get('NetworkManager',False): installation.add_additional_packages("networkmanager") installation.enable_service('NetworkManager.service') # Otherwise, if a interface was selected, configure that interface @@ -347,4 +347,4 @@ def perform_installation(device, boot_partition, language, mirrors): ask_user_questions() -perform_installation_steps() \ No newline at end of file +perform_installation_steps() -- cgit v1.2.3-54-g00ecf From dbe7f3fcb8fa71d14bb27a9963d841cc12007117 Mon Sep 17 00:00:00 2001 From: advaithm Date: Sun, 4 Apr 2021 19:20:08 +0530 Subject: Fixed issue with no network configueration --- examples/guided.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 1a1cf84c..ee8c5d57 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -317,6 +317,9 @@ def perform_installation(device, boot_partition, language, mirrors): # Perform a copy of the config if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. + elif archinstall.arguments.get('nic',None) == None: + #skip if we don't have a network + pass elif archinstall.arguments.get('nic',{}).get('NetworkManager',False): installation.add_additional_packages("networkmanager") installation.enable_service('NetworkManager.service') @@ -326,7 +329,6 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') - if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) -- cgit v1.2.3-54-g00ecf From e2a6a85d66ef0d43c5bb941d9ec945c854f45849 Mon Sep 17 00:00:00 2001 From: advaithm Date: Mon, 5 Apr 2021 20:47:42 +0530 Subject: Revert "Fixed issue with no network configueration" This reverts commit dbe7f3fcb8fa71d14bb27a9963d841cc12007117. --- examples/guided.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index ee8c5d57..1a1cf84c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -317,9 +317,6 @@ def perform_installation(device, boot_partition, language, mirrors): # Perform a copy of the config if archinstall.arguments.get('nic', None) == 'Copy ISO network configuration to installation': installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. - elif archinstall.arguments.get('nic',None) == None: - #skip if we don't have a network - pass elif archinstall.arguments.get('nic',{}).get('NetworkManager',False): installation.add_additional_packages("networkmanager") installation.enable_service('NetworkManager.service') @@ -329,6 +326,7 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') + if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) -- cgit v1.2.3-54-g00ecf From 463d1b5fd37db1435f15987929963ee2f2c2dc02 Mon Sep 17 00:00:00 2001 From: advaithm Date: Mon, 5 Apr 2021 20:58:38 +0530 Subject: add shell drop for i3 and i3-gaps --- examples/guided.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 1a1cf84c..74db0ce5 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -344,7 +344,11 @@ def perform_installation(device, boot_partition, language, mirrors): if (root_pw := archinstall.arguments.get('!root-password', None)) and len(root_pw): installation.user_set_pw('root', root_pw) - + if archinstall.arguments.get('profile', None) == "i3-wm" or archinstall.arguments.get('profile', None) == "i3-gaps": + print("the installation of i3/i3-gaps does not conatain any configuerations for the wm. in this shell you should add your configuerations") + installation.arch_chroot("bash") ask_user_questions() perform_installation_steps() + + \ No newline at end of file -- cgit v1.2.3-54-g00ecf From 947700a605b5c9a066f29b9a51e36a079ccfd45a Mon Sep 17 00:00:00 2001 From: advaithm Date: Mon, 5 Apr 2021 21:03:56 +0530 Subject: use subprocess to launch the shell --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 74db0ce5..fd4ee906 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -346,7 +346,7 @@ def perform_installation(device, boot_partition, language, mirrors): installation.user_set_pw('root', root_pw) if archinstall.arguments.get('profile', None) == "i3-wm" or archinstall.arguments.get('profile', None) == "i3-gaps": print("the installation of i3/i3-gaps does not conatain any configuerations for the wm. in this shell you should add your configuerations") - installation.arch_chroot("bash") + subprocess.check_call("arch-chroot /mnt") ask_user_questions() perform_installation_steps() -- cgit v1.2.3-54-g00ecf From 9404dbe967beaa060101c4d53758ee308f754740 Mon Sep 17 00:00:00 2001 From: advaithm Date: Mon, 5 Apr 2021 21:05:15 +0530 Subject: Update guided.py --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index fd4ee906..b3c5ca04 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -1,4 +1,4 @@ -import getpass, time, json, sys, signal, os +import getpass, time, json, sys, signal, os, subprocess import archinstall from archinstall.lib.hardware import hasUEFI -- cgit v1.2.3-54-g00ecf From b56f7d0515d7dc3b31f2c255c20bc514df9155b1 Mon Sep 17 00:00:00 2001 From: advaithm Date: Mon, 5 Apr 2021 21:28:20 +0530 Subject: fixed subprocess call --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index b3c5ca04..032a1f39 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -346,7 +346,7 @@ def perform_installation(device, boot_partition, language, mirrors): installation.user_set_pw('root', root_pw) if archinstall.arguments.get('profile', None) == "i3-wm" or archinstall.arguments.get('profile', None) == "i3-gaps": print("the installation of i3/i3-gaps does not conatain any configuerations for the wm. in this shell you should add your configuerations") - subprocess.check_call("arch-chroot /mnt") + subprocess.check_call("arch-chroot /mnt",shell=True) ask_user_questions() perform_installation_steps() -- cgit v1.2.3-54-g00ecf From f0e40f56765156aff22cb270b28aa15c5547534f Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 6 Apr 2021 07:21:11 +0530 Subject: added _post_install hook. --- archinstall/lib/profiles.py | 15 +++++++++++++++ examples/guided.py | 14 ++++++++++---- profiles/i3-gaps.py | 10 +++++++++- profiles/i3-wm.py | 9 ++++++++- 4 files changed, 42 insertions(+), 6 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/profiles.py b/archinstall/lib/profiles.py index 08b1d618..77c9c6b2 100644 --- a/archinstall/lib/profiles.py +++ b/archinstall/lib/profiles.py @@ -177,6 +177,21 @@ class Profile(Script): if hasattr(imported, '_prep_function'): return True return False + def has_post_install(self): + with open(self.path, 'r') as source: + source_data = source.read() + + # Some crude safety checks, make sure the imported profile has + # a __name__ check and if so, check if it's got a _prep_function() + # we can call to ask for more user input. + # + # If the requirements are met, import with .py in the namespace to not + # trigger a traditional: + # if __name__ == 'moduleName' + if '__name__' in source_data and '_post_install' in source_data: + with self.load_instructions(namespace=f"{self.namespace}.py") as imported: + if hasattr(imported, '_post_install'): + return True class Application(Profile): def __repr__(self, *args, **kwargs): diff --git a/examples/guided.py b/examples/guided.py index 032a1f39..3f11b7a8 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -1,4 +1,4 @@ -import getpass, time, json, sys, signal, os, subprocess +import getpass, time, json, sys, signal, os import archinstall from archinstall.lib.hardware import hasUEFI @@ -344,9 +344,15 @@ def perform_installation(device, boot_partition, language, mirrors): if (root_pw := archinstall.arguments.get('!root-password', None)) and len(root_pw): installation.user_set_pw('root', root_pw) - if archinstall.arguments.get('profile', None) == "i3-wm" or archinstall.arguments.get('profile', None) == "i3-gaps": - print("the installation of i3/i3-gaps does not conatain any configuerations for the wm. in this shell you should add your configuerations") - subprocess.check_call("arch-chroot /mnt",shell=True) + if archinstall.arguments['profile'] and archinstall.arguments['profile'].has_post_install(): + with archinstall.arguments['profile'].load_instructions(namespace=f"{archinstall.arguments['profile'].namespace}.py") as imported: + if not imported._post_install(): + archinstall.log( + ' * Profile\'s preparation requirements was not fulfilled.', + bg='black', + fg='red' + ) + exit(1) ask_user_questions() perform_installation_steps() diff --git a/profiles/i3-gaps.py b/profiles/i3-gaps.py index bf8227ba..d9469dcd 100644 --- a/profiles/i3-gaps.py +++ b/profiles/i3-gaps.py @@ -1,4 +1,4 @@ -import archinstall +import archinstall, subprocess def _prep_function(*args, **kwargs): """ @@ -16,6 +16,14 @@ def _prep_function(*args, **kwargs): else: print('Deprecated (??): xorg profile has no _prep_function() anymore') +def _post_install(*args, **kwargs): + """ + Another magic function called after the system + has been installed. + """ + print("the installation of i3 does not conatain any configuerations for the wm. in this shell you take your time should add your configuerations") + subprocess.check_call("arch-chroot /mnt",shell=True) + if __name__ == 'i3-wm': # Install dependency profiles installation.install_profile('xorg') diff --git a/profiles/i3-wm.py b/profiles/i3-wm.py index 168abb72..8b541bbf 100644 --- a/profiles/i3-wm.py +++ b/profiles/i3-wm.py @@ -1,4 +1,4 @@ -import archinstall +import archinstall, subprocess def _prep_function(*args, **kwargs): """ @@ -15,6 +15,13 @@ def _prep_function(*args, **kwargs): return imported._prep_function() else: print('Deprecated (??): xorg profile has no _prep_function() anymore') +def _post_install(*args, **kwargs): + """ + Another magic function called after the system + has been installed. + """ + print("the installation of i3-gaps does not conatain any configuerations for the wm. in this shell you should take your time to add your configuerations") + subprocess.check_call("arch-chroot /mnt",shell=True) if __name__ == 'i3-wm': # Install dependency profiles -- cgit v1.2.3-54-g00ecf From 4af3bbac2306146ce038666f2911690c655bcb63 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 6 Apr 2021 09:55:12 +0200 Subject: Phrasing and removed background coloring --- examples/guided.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 3f11b7a8..85492a81 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -348,8 +348,7 @@ def perform_installation(device, boot_partition, language, mirrors): with archinstall.arguments['profile'].load_instructions(namespace=f"{archinstall.arguments['profile'].namespace}.py") as imported: if not imported._post_install(): archinstall.log( - ' * Profile\'s preparation requirements was not fulfilled.', - bg='black', + ' * Profile\'s post configuration requirements was not fulfilled.', fg='red' ) exit(1) @@ -357,4 +356,4 @@ def perform_installation(device, boot_partition, language, mirrors): ask_user_questions() perform_installation_steps() - \ No newline at end of file + -- cgit v1.2.3-54-g00ecf From d9984550b6ad4f4e7d659adb32cef541e85d69d9 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 6 Apr 2021 18:04:03 -0400 Subject: Move choice into guided installation instead of DEs Arch wiki says packages should enable the user services automatically --- archinstall/lib/user_interaction.py | 8 ++++++++ examples/guided.py | 10 +++++++++- profiles/applications/pipewire.py | 4 ++-- profiles/awesome.py | 6 ------ profiles/cinnamon.py | 6 ------ profiles/gnome.py | 6 ------ profiles/i3-gaps.py | 8 +------- profiles/i3-wm.py | 6 ------ profiles/kde.py | 6 ------ profiles/xfce4.py | 6 ------ 10 files changed, 20 insertions(+), 46 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 58f88bd2..3c5115ea 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -89,6 +89,14 @@ def ask_for_a_timezone(): level=LOG_LEVELS.Warning, fg='red' ) + +def ask_for_audio_selection(): + audio = "pulseaudio" # Default for most desktop environments + pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() + if pipewire_choice == "y": + audio = "pipewire" + + return audio def ask_to_configure_network(): # Optionally configure one network interface. diff --git a/examples/guided.py b/examples/guided.py index 81cc2991..cd45bef5 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -182,6 +182,10 @@ def ask_user_questions(): ) exit(1) + # Ask about audio server selection (this right now just asks for pipewire and defaults to pulseaudio otherwise) + if not archinstall.arguments.get('audio', None): + archinstall.arguments['audio'] = archinstall.ask_for_audio_selection() + # Additional packages (with some light weight error handling for invalid package names) if not archinstall.arguments.get('packages', None): archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] @@ -329,7 +333,11 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') - + print('This audio server will be used: ' + archinstall.arguments.get('audio', None)) + if archinstall.arguments.get('audio', None) == 'pipewire': + print('Installing pipewire ...') + installation.install_profile('pipewire') + if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) diff --git a/profiles/applications/pipewire.py b/profiles/applications/pipewire.py index 2d9f6a6c..aea5b50d 100644 --- a/profiles/applications/pipewire.py +++ b/profiles/applications/pipewire.py @@ -1,5 +1,5 @@ import archinstall -__packages__ = ["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"] +packages = ["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"] -installation.add_additional_packages(__packages__) +installation.add_additional_packages(packages) diff --git a/profiles/awesome.py b/profiles/awesome.py index fcad1839..8004fc62 100644 --- a/profiles/awesome.py +++ b/profiles/awesome.py @@ -25,12 +25,6 @@ def _prep_function(*args, **kwargs): # through importlib.util.spec_from_file_location("awesome", "/somewhere/awesome.py") # or through conventional import awesome if __name__ == 'awesome': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install the application awesome from the template under /applications/ awesome = archinstall.Application(installation, 'awesome') awesome.install() diff --git a/profiles/cinnamon.py b/profiles/cinnamon.py index a3225c30..dac38bd3 100644 --- a/profiles/cinnamon.py +++ b/profiles/cinnamon.py @@ -22,12 +22,6 @@ def _prep_function(*args, **kwargs): # through importlib.util.spec_from_file_location("cinnamon", "/somewhere/cinnamon.py") # or through conventional import cinnamon if __name__ == 'cinnamon': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install dependency profiles installation.install_profile('xorg') diff --git a/profiles/gnome.py b/profiles/gnome.py index d13e6eee..63fcd57d 100644 --- a/profiles/gnome.py +++ b/profiles/gnome.py @@ -23,12 +23,6 @@ def _prep_function(*args, **kwargs): # through importlib.util.spec_from_file_location("gnome", "/somewhere/gnome.py") # or through conventional import gnome if __name__ == 'gnome': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install dependency profiles installation.install_profile('xorg') diff --git a/profiles/i3-gaps.py b/profiles/i3-gaps.py index f75dfb11..50511dce 100644 --- a/profiles/i3-gaps.py +++ b/profiles/i3-gaps.py @@ -29,13 +29,7 @@ def _post_install(*args, **kwargs): return True -if __name__ == 'i3-wm': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - +if __name__ == 'i3-wm': # Install dependency profiles installation.install_profile('xorg') # gaps is installed by deafult so we are overriding it here diff --git a/profiles/i3-wm.py b/profiles/i3-wm.py index 6d40065c..cd6cbc81 100644 --- a/profiles/i3-wm.py +++ b/profiles/i3-wm.py @@ -29,12 +29,6 @@ def _post_install(*args, **kwargs): return True if __name__ == 'i3-wm': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install dependency profiles installation.install_profile('xorg') # we are installing lightdm to auto start i3 diff --git a/profiles/kde.py b/profiles/kde.py index dabba57b..0207ed22 100644 --- a/profiles/kde.py +++ b/profiles/kde.py @@ -32,12 +32,6 @@ def _post_install(*args, **kwargs): # through importlib.util.spec_from_file_location("kde", "/somewhere/kde.py") # or through conventional import kde if __name__ == 'kde': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install dependency profiles installation.install_profile('xorg') diff --git a/profiles/xfce4.py b/profiles/xfce4.py index 8e418578..36c9958a 100644 --- a/profiles/xfce4.py +++ b/profiles/xfce4.py @@ -23,12 +23,6 @@ def _prep_function(*args, **kwargs): # through importlib.util.spec_from_file_location("xfce4", "/somewhere/xfce4.py") # or through conventional import xfce4 if __name__ == 'xfce4': - # Install the pipewire audio server if the user wants to use it - pipewire_choice = input("Would you like to install the pipewire audio server? [Y/n] ").lower() - if choice == "y": - pipewire = archinstall.Application(installation, 'pipewire') - pipewire.install() - # Install dependency profiles installation.install_profile('xorg') -- cgit v1.2.3-54-g00ecf From 93750dbd223269804c2a9a3a7dbdf30d4f17ac82 Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Tue, 6 Apr 2021 20:44:44 -0400 Subject: Try removing pipewire.py and calling add additional packages Unfortunately, calling the profile was not working. --- examples/guided.py | 2 +- profiles/applications/pipewire.py | 5 ----- profiles/gnome.py | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) delete mode 100644 profiles/applications/pipewire.py (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index cd45bef5..90828d87 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -336,7 +336,7 @@ def perform_installation(device, boot_partition, language, mirrors): print('This audio server will be used: ' + archinstall.arguments.get('audio', None)) if archinstall.arguments.get('audio', None) == 'pipewire': print('Installing pipewire ...') - installation.install_profile('pipewire') + installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) diff --git a/profiles/applications/pipewire.py b/profiles/applications/pipewire.py deleted file mode 100644 index aea5b50d..00000000 --- a/profiles/applications/pipewire.py +++ /dev/null @@ -1,5 +0,0 @@ -import archinstall - -packages = ["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"] - -installation.add_additional_packages(packages) diff --git a/profiles/gnome.py b/profiles/gnome.py index 63fcd57d..b37679de 100644 --- a/profiles/gnome.py +++ b/profiles/gnome.py @@ -29,7 +29,7 @@ if __name__ == 'gnome': # Install the application gnome from the template under /applications/ gnome = archinstall.Application(installation, 'gnome') gnome.install() - + installation.enable_service('gdm') # Gnome Display Manager # We could also start it via xinitrc since we do have Xorg, # but for gnome that's deprecated and wayland is preferred. -- cgit v1.2.3-54-g00ecf From fb2c9aca397f6fc0ffba097b4c4dcb5e96257362 Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Tue, 6 Apr 2021 20:47:30 -0400 Subject: Have pulseaudio installed just in case DEs don't depend on it if pipewire is not requested. --- examples/guided.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 90828d87..74df899f 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -337,6 +337,9 @@ def perform_installation(device, boot_partition, language, mirrors): if archinstall.arguments.get('audio', None) == 'pipewire': print('Installing pipewire ...') installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) + elif archinstall.arguments.get('audio', None) == 'pulseaudio': + print('Installing pulseaudio ...') + installation.add_additional_packages("pulseaudio") if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) -- cgit v1.2.3-54-g00ecf From 86699ae23ebb3eabb3817ccb456eb1ddd9dcebbf Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Wed, 7 Apr 2021 09:28:16 +0200 Subject: Switched from print to installation.log --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 74df899f..a5442d77 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -333,7 +333,7 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') - print('This audio server will be used: ' + archinstall.arguments.get('audio', None)) + installation.log(f"The {archinstall.arguments.get('audio', None)} audio server will be used.", level=archinstall.LOG_LEVELS.Info) if archinstall.arguments.get('audio', None) == 'pipewire': print('Installing pipewire ...') installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) -- cgit v1.2.3-54-g00ecf From f85fb66bc61ee9b90537da59be00b37f49e5ffb8 Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Wed, 7 Apr 2021 09:12:33 -0400 Subject: Add filtration on top level profile --- archinstall/lib/profiles.py | 8 ++++++++ examples/guided.py | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/archinstall/lib/profiles.py b/archinstall/lib/profiles.py index 39411553..1948a819 100644 --- a/archinstall/lib/profiles.py +++ b/archinstall/lib/profiles.py @@ -177,6 +177,7 @@ class Profile(Script): if hasattr(imported, '_prep_function'): return True return False + def has_post_install(self): with open(self.path, 'r') as source: source_data = source.read() @@ -193,6 +194,13 @@ class Profile(Script): if hasattr(imported, '_post_install'): return True + def is_top_level_profile(self): + with open(self.path, 'r') as source: + source_data = source.read() + + # TODO: I imagine that there is probably a better way to write this. + return 'top_level_profile = True' in source_data + @property def packages(self) -> list: """ diff --git a/examples/guided.py b/examples/guided.py index 0a655e8a..a7cc7edc 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -1,6 +1,7 @@ import getpass, time, json, sys, signal, os import archinstall from archinstall.lib.hardware import hasUEFI +from archinstall.lib.profiles import Profile """ This signal-handler chain (and global variable) @@ -167,7 +168,7 @@ def ask_user_questions(): # Ask for archinstall-specific profiles (such as desktop environments etc) if not archinstall.arguments.get('profile', None): - archinstall.arguments['profile'] = archinstall.select_profile(archinstall.list_profiles()) + archinstall.arguments['profile'] = archinstall.select_profile(filter(lambda profile: (Profile(None, profile).is_top_level_profile()), archinstall.list_profiles())) else: archinstall.arguments['profile'] = archinstall.list_profiles()[archinstall.arguments['profile']] -- cgit v1.2.3-54-g00ecf From fd7510a88ccd68c600e6f1c10b30152126d0351a Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Wed, 7 Apr 2021 19:51:16 -0400 Subject: Make audio server selection only prompt for desktop profiles --- examples/guided.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 55855d1b..4c3cb58c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -182,9 +182,16 @@ def ask_user_questions(): ) exit(1) - # Ask about audio server selection (this right now just asks for pipewire and defaults to pulseaudio otherwise) + # Ask about audio server selection if one is not already set if not archinstall.arguments.get('audio', None): - archinstall.arguments['audio'] = archinstall.ask_for_audio_selection() + + # only ask for audio server selection on a desktop profile + if str(archinstall.arguments['profile']) == 'Profile(desktop)': + archinstall.arguments['audio'] = archinstall.ask_for_audio_selection() + else: + # packages installed by a profile may depend on audio and something may get installed anyways, not much we can do about that. + # we will not try to remove packages post-installation to not have audio, as that may cause multiple issues + archinstall.arguments['audio'] = 'none' # Additional packages (with some light weight error handling for invalid package names) if not archinstall.arguments.get('packages', None): @@ -334,13 +341,14 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') - installation.log(f"The {archinstall.arguments.get('audio', None)} audio server will be used.", level=archinstall.LOG_LEVELS.Info) - if archinstall.arguments.get('audio', None) == 'pipewire': - print('Installing pipewire ...') - installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) - elif archinstall.arguments.get('audio', None) == 'pulseaudio': - print('Installing pulseaudio ...') - installation.add_additional_packages("pulseaudio") + if archinstall.arguments['audio'] != 'none': + installation.log(f"The {archinstall.arguments.get('audio', None)} audio server will be used.", level=archinstall.LOG_LEVELS.Info) + if archinstall.arguments.get('audio', None) == 'pipewire': + print('Installing pipewire ...') + installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-docs", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) + elif archinstall.arguments.get('audio', None) == 'pulseaudio': + print('Installing pulseaudio ...') + installation.add_additional_packages("pulseaudio") if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) -- cgit v1.2.3-54-g00ecf From cdf6fc796fc7d00b29c62c09e0788a74e05461a1 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Thu, 8 Apr 2021 08:17:40 +0200 Subject: Safety precaution by using .get instead of ["..."] --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 4c3cb58c..fa74fbba 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -341,7 +341,7 @@ def perform_installation(device, boot_partition, language, mirrors): installation.enable_service('systemd-networkd') installation.enable_service('systemd-resolved') - if archinstall.arguments['audio'] != 'none': + if archinstall.arguments.get('audio', None) != None: installation.log(f"The {archinstall.arguments.get('audio', None)} audio server will be used.", level=archinstall.LOG_LEVELS.Info) if archinstall.arguments.get('audio', None) == 'pipewire': print('Installing pipewire ...') -- cgit v1.2.3-54-g00ecf From 459f161cf0432393443272ac5b1aa5fc0cd7fd16 Mon Sep 17 00:00:00 2001 From: Aggam Rahamim Date: Fri, 16 Apr 2021 12:01:20 +0300 Subject: added option to choose kernel --- .gitignore | 2 +- archinstall/lib/installer.py | 3 ++- examples/guided.py | 11 ++++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/.gitignore b/.gitignore index dc75bed8..246880ba 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,4 @@ SAFETY_LOCK **/**.network **/**.target **/**.qcow2 -**/test.py +**/test.py \ No newline at end of file diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 758033a7..d21040fa 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -34,7 +34,8 @@ class Installer(): :type hostname: str, optional """ - def __init__(self, target, *, base_packages='base base-devel linux linux-firmware efibootmgr'): + def __init__(self, target, *, base_packages='base base-devel linux-firmware efibootmgr', kernel='linux'): + base_packages += ' '+kernel self.target = target self.init_time = time.strftime('%Y-%m-%d_%H-%M-%S') self.milliseconds = int(str(time.time()).split('.')[1]) diff --git a/examples/guided.py b/examples/guided.py index d47a949c..a927d86b 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -176,6 +176,15 @@ def ask_user_questions(): # packages installed by a profile may depend on audio and something may get installed anyways, not much we can do about that. # we will not try to remove packages post-installation to not have audio, as that may cause multiple issues archinstall.arguments['audio'] = None + + # Ask what kernel user wants: + kernel = input("choose a kernel:\n1. linux\n2. linux-lts\n3. linux-zen") + try: + archinstall.arguments['kernel'] = ['linux', 'linux-lts', 'linux-zen'][int(kernel) - 1] + except: + archinstall.log('invalid kernel selected. defaulting to \'linux\'.') + archinstall.arguments['kernel'] = 'linux' + # Additional packages (with some light weight error handling for invalid package names) if not archinstall.arguments.get('packages', None): @@ -272,7 +281,7 @@ def perform_installation(mountpoint): Only requirement is that the block devices are formatted and setup prior to entering this function. """ - with archinstall.Installer(mountpoint) as installation: + with archinstall.Installer(mountpoint, kernel=archinstall.arguments['kernel']) as installation: ## if len(mirrors): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist -- cgit v1.2.3-54-g00ecf From f6fdc119276457d18d5ff1fb30ab9ff06826f576 Mon Sep 17 00:00:00 2001 From: Aggam Rahamim Date: Fri, 16 Apr 2021 13:54:22 +0300 Subject: fixing - letting user choose kernel --- .gitignore | 3 +- archinstall/lib/installer.py | 4 +- "archiso;\n\t\techo Running" | 0 examples/guided.py | 2 +- guided.py | 359 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 364 insertions(+), 4 deletions(-) create mode 100644 "archiso;\n\t\techo Running" create mode 100644 guided.py (limited to 'examples') diff --git a/.gitignore b/.gitignore index 246880ba..78595b08 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,5 @@ SAFETY_LOCK **/**.network **/**.target **/**.qcow2 -**/test.py \ No newline at end of file +**/test.py +**/archiso \ No newline at end of file diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index d21040fa..9b0f9c8b 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -34,8 +34,8 @@ class Installer(): :type hostname: str, optional """ - def __init__(self, target, *, base_packages='base base-devel linux-firmware efibootmgr', kernel='linux'): - base_packages += ' '+kernel + def __init__(self, target, *, base_packages=' base base-devel linux-firmware efibootmgr', kernel='linux'): + base_packages = kernel + base_packages self.target = target self.init_time = time.strftime('%Y-%m-%d_%H-%M-%S') self.milliseconds = int(str(time.time()).split('.')[1]) diff --git "a/archiso;\n\t\techo Running" "b/archiso;\n\t\techo Running" new file mode 100644 index 00000000..e69de29b diff --git a/examples/guided.py b/examples/guided.py index a927d86b..f4ab0b70 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -178,7 +178,7 @@ def ask_user_questions(): archinstall.arguments['audio'] = None # Ask what kernel user wants: - kernel = input("choose a kernel:\n1. linux\n2. linux-lts\n3. linux-zen") + kernel = input("\n1. linux\n2. linux-lts\n3. linux-zen\nchoose a kernel of the following: ") try: archinstall.arguments['kernel'] = ['linux', 'linux-lts', 'linux-zen'][int(kernel) - 1] except: diff --git a/guided.py b/guided.py new file mode 100644 index 00000000..a927d86b --- /dev/null +++ b/guided.py @@ -0,0 +1,359 @@ +import getpass, time, json, os +import archinstall +from archinstall.lib.hardware import hasUEFI +from archinstall.lib.profiles import Profile + +if hasUEFI() is False: + log("ArchInstall currently only supports machines booted with UEFI. MBR & GRUB support is coming in version 2.2.0!", fg="red", level=archinstall.LOG_LEVELS.Error) + exit(1) + +def ask_user_questions(): + """ + First, we'll ask the user for a bunch of user input. + Not until we're satisfied with what we want to install + will we continue with the actual installation steps. + """ + if not archinstall.arguments.get('keyboard-language', None): + archinstall.arguments['keyboard-language'] = archinstall.select_language(archinstall.list_keyboard_languages()).strip() + + # Before continuing, set the preferred keyboard layout/language in the current terminal. + # This will just help the user with the next following questions. + if len(archinstall.arguments['keyboard-language']): + archinstall.set_keyboard_language(archinstall.arguments['keyboard-language']) + + # Set which region to download packages from during the installation + if not archinstall.arguments.get('mirror-region', None): + archinstall.arguments['mirror-region'] = archinstall.select_mirror_regions(archinstall.list_mirrors()) + else: + selected_region = archinstall.arguments['mirror-region'] + archinstall.arguments['mirror-region'] = {selected_region : archinstall.list_mirrors()[selected_region]} + + + # Ask which harddrive/block-device we will install to + if archinstall.arguments.get('harddrive', None): + archinstall.arguments['harddrive'] = archinstall.BlockDevice(archinstall.arguments['harddrive']) + else: + archinstall.arguments['harddrive'] = archinstall.select_disk(archinstall.all_disks()) + if archinstall.arguments['harddrive'] is None: + archinstall.arguments['target-mount'] = '/mnt' + + # Perform a quick sanity check on the selected harddrive. + # 1. Check if it has partitions + # 3. Check that we support the current partitions + # 2. If so, ask if we should keep them or wipe everything + if archinstall.arguments['harddrive'] and archinstall.arguments['harddrive'].has_partitions(): + archinstall.log(f"{archinstall.arguments['harddrive']} contains the following partitions:", fg='yellow') + + # We curate a list pf supported partitions + # and print those that we don't support. + partition_mountpoints = {} + for partition in archinstall.arguments['harddrive']: + try: + if partition.filesystem_supported(): + archinstall.log(f" {partition}") + partition_mountpoints[partition] = None + except archinstall.UnknownFilesystemFormat as err: + archinstall.log(f" {partition} (Filesystem not supported)", fg='red') + + # We then ask what to do with the partitions. + if (option := archinstall.ask_for_disk_layout()) == 'abort': + archinstall.log(f"Safely aborting the installation. No changes to the disk or system has been made.") + exit(1) + elif option == 'keep-existing': + archinstall.arguments['harddrive'].keep_partitions = True + + archinstall.log(f" ** You will now select which partitions to use by selecting mount points (inside the installation). **") + archinstall.log(f" ** The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation). **") + while True: + # Select a partition + partition = archinstall.generic_select(partition_mountpoints.keys(), + "Select a partition by number that you want to set a mount-point for (leave blank when done): ") + if not partition: + break + + # Select a mount-point + mountpoint = input(f"Enter a mount-point for {partition}: ").strip(' ') + if len(mountpoint): + + # Get a valid & supported filesystem for the partition: + while 1: + new_filesystem = input(f"Enter a valid filesystem for {partition} (leave blank for {partition.filesystem}): ").strip(' ') + if len(new_filesystem) <= 0: + if partition.encrypted and partition.filesystem == 'crypto_LUKS': + old_password = archinstall.arguments.get('!encryption-password', None) + if not old_password: + old_password = input(f'Enter the old encryption password for {partition}: ') + + if (autodetected_filesystem := partition.detect_inner_filesystem(old_password)): + new_filesystem = autodetected_filesystem + else: + archinstall.log(f"Could not auto-detect the filesystem inside the encrypted volume.", fg='red') + archinstall.log(f"A filesystem must be defined for the unlocked encrypted partition.") + continue + break + + # Since the potentially new filesystem is new + # we have to check if we support it. We can do this by formatting /dev/null with the partitions filesystem. + # There's a nice wrapper for this on the partition object itself that supports a path-override during .format() + try: + partition.format(new_filesystem, path='/dev/null', log_formating=False, allow_formatting=True) + except archinstall.UnknownFilesystemFormat: + archinstall.log(f"Selected filesystem is not supported yet. If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") + archinstall.log(f"Until then, please enter another supported filesystem.") + continue + except archinstall.SysCallError: + pass # Expected exception since mkfs. can not format /dev/null. + # But that means our .format() function supported it. + break + + # When we've selected all three criteria, + # We can safely mark the partition for formatting and where to mount it. + # TODO: allow_formatting might be redundant since target_mountpoint should only be + # set if we actually want to format it anyway. + partition.allow_formatting = True + partition.target_mountpoint = mountpoint + # Only overwrite the filesystem definition if we selected one: + if len(new_filesystem): + partition.filesystem = new_filesystem + + archinstall.log('Using existing partition table reported above.') + elif option == 'format-all': + archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() + archinstall.arguments['harddrive'].keep_partitions = False + elif archinstall.arguments['harddrive']: + # If the drive doesn't have any partitions, safely mark the disk with keep_partitions = False + # and ask the user for a root filesystem. + archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() + archinstall.arguments['harddrive'].keep_partitions = False + + # Get disk encryption password (or skip if blank) + if archinstall.arguments['harddrive'] and archinstall.arguments.get('!encryption-password', None) is None: + if (passwd := archinstall.get_password(prompt='Enter disk encryption password (leave blank for no encryption): ')): + archinstall.arguments['!encryption-password'] = passwd + archinstall.arguments['harddrive'].encryption_password = archinstall.arguments['!encryption-password'] + + # Get the hostname for the machine + if not archinstall.arguments.get('hostname', None): + archinstall.arguments['hostname'] = input('Desired hostname for the installation: ').strip(' ') + + # Ask for a root password (optional, but triggers requirement for super-user if skipped) + if not archinstall.arguments.get('!root-password', None): + archinstall.arguments['!root-password'] = archinstall.get_password(prompt='Enter root password (Recommendation: leave blank to leave root disabled): ') + + # Ask for additional users (super-user if root pw was not set) + archinstall.arguments['users'] = {} + archinstall.arguments['superusers'] = {} + if not archinstall.arguments.get('!root-password', None): + archinstall.arguments['superusers'] = archinstall.ask_for_superuser_account('Create a required super-user with sudo privileges: ', forced=True) + + users, superusers = archinstall.ask_for_additional_users('Enter a username to create a additional user (leave blank to skip & continue): ') + archinstall.arguments['users'] = users + archinstall.arguments['superusers'] = {**archinstall.arguments['superusers'], **superusers} + + # Ask for archinstall-specific profiles (such as desktop environments etc) + if not archinstall.arguments.get('profile', None): + archinstall.arguments['profile'] = archinstall.select_profile(filter(lambda profile: (Profile(None, profile).is_top_level_profile()), archinstall.list_profiles())) + else: + archinstall.arguments['profile'] = archinstall.list_profiles()[archinstall.arguments['profile']] + + # Check the potentially selected profiles preparations to get early checks if some additional questions are needed. + if archinstall.arguments['profile'] and archinstall.arguments['profile'].has_prep_function(): + with archinstall.arguments['profile'].load_instructions(namespace=f"{archinstall.arguments['profile'].namespace}.py") as imported: + if not imported._prep_function(): + archinstall.log( + ' * Profile\'s preparation requirements was not fulfilled.', + fg='red' + ) + exit(1) + + # Ask about audio server selection if one is not already set + if not archinstall.arguments.get('audio', None): + + # only ask for audio server selection on a desktop profile + if str(archinstall.arguments['profile']) == 'Profile(desktop)': + archinstall.arguments['audio'] = archinstall.ask_for_audio_selection() + else: + # packages installed by a profile may depend on audio and something may get installed anyways, not much we can do about that. + # we will not try to remove packages post-installation to not have audio, as that may cause multiple issues + archinstall.arguments['audio'] = None + + # Ask what kernel user wants: + kernel = input("choose a kernel:\n1. linux\n2. linux-lts\n3. linux-zen") + try: + archinstall.arguments['kernel'] = ['linux', 'linux-lts', 'linux-zen'][int(kernel) - 1] + except: + archinstall.log('invalid kernel selected. defaulting to \'linux\'.') + archinstall.arguments['kernel'] = 'linux' + + + # Additional packages (with some light weight error handling for invalid package names) + if not archinstall.arguments.get('packages', None): + print("Packages not part of the desktop environment are not installed by default.") + print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") + archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] + + if len(archinstall.arguments['packages']): + # Verify packages that were given + try: + archinstall.log(f"Verifying that additional packages exist (this might take a few seconds)") + archinstall.validate_package_list(archinstall.arguments['packages']) + except archinstall.RequirementError as e: + archinstall.log(e, fg='red') + exit(1) + + # Ask or Call the helper function that asks the user to optionally configure a network. + if not archinstall.arguments.get('nic', None): + archinstall.arguments['nic'] = archinstall.ask_to_configure_network() + if not archinstall.arguments['nic']: + archinstall.log(f"No network configuration was selected. Network is going to be unavailable until configured manually!", fg="yellow") + + if not archinstall.arguments.get('timezone', None): + archinstall.arguments['timezone'] = archinstall.ask_for_a_timezone() + + +def perform_installation_steps(): + print() + print('This is your chosen configuration:') + archinstall.log("-- Guided template chosen (with below config) --", level=archinstall.LOG_LEVELS.Debug) + archinstall.log(json.dumps(archinstall.arguments, indent=4, sort_keys=True, cls=archinstall.JSON), level=archinstall.LOG_LEVELS.Info) + print() + + input('Press Enter to continue.') + + """ + Issue a final warning before we continue with something un-revertable. + We mention the drive one last time, and count from 5 to 0. + """ + + if archinstall.arguments.get('harddrive', None): + print(f" ! Formatting {archinstall.arguments['harddrive']} in ", end='') + archinstall.do_countdown() + + """ + Setup the blockdevice, filesystem (and optionally encryption). + Once that's done, we'll hand over to perform_installation() + """ + with archinstall.Filesystem(archinstall.arguments['harddrive'], archinstall.GPT) as fs: + # Wipe the entire drive if the disk flag `keep_partitions`is False. + if archinstall.arguments['harddrive'].keep_partitions is False: + fs.use_entire_disk(root_filesystem_type=archinstall.arguments.get('filesystem', 'btrfs')) + + # Check if encryption is desired and mark the root partition as encrypted. + if archinstall.arguments.get('!encryption-password', None): + root_partition = fs.find_partition('/') + root_partition.encrypted = True + + # After the disk is ready, iterate the partitions and check + # which ones are safe to format, and format those. + for partition in archinstall.arguments['harddrive']: + if partition.safe_to_format(): + # Partition might be marked as encrypted due to the filesystem type crypt_LUKS + # But we might have omitted the encryption password question to skip encryption. + # In which case partition.encrypted will be true, but passwd will be false. + if partition.encrypted and (passwd := archinstall.arguments.get('!encryption-password', None)): + partition.encrypt(password=passwd) + else: + partition.format() + else: + archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=archinstall.LOG_LEVELS.Debug) + + fs.find_partition('/boot').format('vfat') + + if archinstall.arguments.get('!encryption-password', None): + # First encrypt and unlock, then format the desired partition inside the encrypted part. + # archinstall.luks2() encrypts the partition when entering the with context manager, and + # unlocks the drive so that it can be used as a normal block-device within archinstall. + with archinstall.luks2(fs.find_partition('/'), 'luksloop', archinstall.arguments.get('!encryption-password', None)) as unlocked_device: + unlocked_device.format(fs.find_partition('/').filesystem) + unlocked_device.mount('/mnt') + else: + fs.find_partition('/').format(fs.find_partition('/').filesystem) + fs.find_partition('/').mount('/mnt') + + fs.find_partition('/boot').mount('/mnt/boot') + + perform_installation('/mnt') + + +def perform_installation(mountpoint): + """ + Performs the installation steps on a block device. + Only requirement is that the block devices are + formatted and setup prior to entering this function. + """ + with archinstall.Installer(mountpoint, kernel=archinstall.arguments['kernel']) as installation: + ## if len(mirrors): + # Certain services might be running that affects the system during installation. + # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist + # We need to wait for it before we continue since we opted in to use a custom mirror/region. + installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=archinstall.LOG_LEVELS.Info) + while archinstall.service_state('reflector') not in ('dead', 'failed'): + time.sleep(1) + + # Set mirrors used by pacstrap (outside of installation) + if archinstall.arguments.get('mirror-region', None): + archinstall.use_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors for the live medium + + if installation.minimal_installation(): + installation.set_hostname(archinstall.arguments['hostname']) + + # Configure the selected mirrors in the installation + if archinstall.arguments.get('mirror-region', None): + installation.set_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors in the installation medium + + installation.set_keyboard_language(archinstall.arguments['keyboard-language']) + installation.add_bootloader() + + # If user selected to copy the current ISO network configuration + # Perform a copy of the config + if archinstall.arguments.get('nic', {}) == 'Copy ISO network configuration to installation': + installation.copy_ISO_network_config(enable_services=True) # Sources the ISO network configuration to the install medium. + elif archinstall.arguments.get('nic', {}).get('NetworkManager',False): + installation.add_additional_packages("networkmanager") + installation.enable_service('NetworkManager.service') + # Otherwise, if a interface was selected, configure that interface + elif archinstall.arguments.get('nic', {}): + installation.configure_nic(**archinstall.arguments.get('nic', {})) + installation.enable_service('systemd-networkd') + installation.enable_service('systemd-resolved') + + if archinstall.arguments.get('audio', None) != None: + installation.log(f"This audio server will be used: {archinstall.arguments.get('audio', None)}", level=archinstall.LOG_LEVELS.Info) + if archinstall.arguments.get('audio', None) == 'pipewire': + print('Installing pipewire ...') + installation.add_additional_packages(["pipewire", "pipewire-alsa", "pipewire-jack", "pipewire-media-session", "pipewire-pulse", "gst-plugin-pipewire", "libpulse"]) + elif archinstall.arguments.get('audio', None) == 'pulseaudio': + print('Installing pulseaudio ...') + installation.add_additional_packages("pulseaudio") + else: + installation.log("No audio server will be installed.", level=archinstall.LOG_LEVELS.Info) + + if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': + installation.add_additional_packages(archinstall.arguments.get('packages', None)) + + if archinstall.arguments.get('profile', None): + installation.install_profile(archinstall.arguments.get('profile', None)) + + for user, user_info in archinstall.arguments.get('users', {}).items(): + installation.user_create(user, user_info["!password"], sudo=False) + + for superuser, user_info in archinstall.arguments.get('superusers', {}).items(): + installation.user_create(superuser, user_info["!password"], sudo=True) + + if (timezone := archinstall.arguments.get('timezone', None)): + installation.set_timezone(timezone) + + if (root_pw := archinstall.arguments.get('!root-password', None)) and len(root_pw): + installation.user_set_pw('root', root_pw) + + installation.log("For post-installation tips, see https://wiki.archlinux.org/index.php/Installation_guide#Post-installation", fg="yellow") + choice = input("Would you like to chroot into the newly created installation and perform post-installation configuration? [Y/n] ") + if choice.lower() in ("y", ""): + try: + installation.drop_to_shell() + except: + pass + +ask_user_questions() +perform_installation_steps() + -- cgit v1.2.3-54-g00ecf From 8b9f16a0284c5261a29b9818809cbe45a9c0c10b Mon Sep 17 00:00:00 2001 From: Aggam Rahamim Date: Fri, 16 Apr 2021 14:43:17 +0300 Subject: removed new line when ask for kernel --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index f4ab0b70..e6abe872 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -178,7 +178,7 @@ def ask_user_questions(): archinstall.arguments['audio'] = None # Ask what kernel user wants: - kernel = input("\n1. linux\n2. linux-lts\n3. linux-zen\nchoose a kernel of the following: ") + kernel = input("1. linux\n2. linux-lts\n3. linux-zen\nchoose a kernel of the following: ") try: archinstall.arguments['kernel'] = ['linux', 'linux-lts', 'linux-zen'][int(kernel) - 1] except: -- cgit v1.2.3-54-g00ecf From 80a3ca3826d15a8742c60e2a13d6def09768057a Mon Sep 17 00:00:00 2001 From: Malccolm Haak Date: Sat, 17 Apr 2021 14:23:39 +1000 Subject: In guided install Non-UEFI installs need to use grub-install as its the only supported bootloader that doesn't require UEFI --- examples/guided.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 81cc2991..dfc2da07 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -257,12 +257,12 @@ def perform_installation_steps(): # Wipe the entire drive if the disk flag `keep_partitions`is False. if archinstall.arguments['harddrive'].keep_partitions is False: fs.use_entire_disk(root_filesystem_type=archinstall.arguments.get('filesystem', 'btrfs')) - + # Check if encryption is desired and mark the root partition as encrypted. if archinstall.arguments.get('!encryption-password', None): root_partition = fs.find_partition('/') root_partition.encrypted = True - + # After the disk is ready, iterate the partitions and check # which ones are safe to format, and format those. for partition in archinstall.arguments['harddrive']: @@ -314,7 +314,11 @@ def perform_installation(device, boot_partition, language, mirrors): if installation.minimal_installation(): installation.set_mirrors(mirrors) # Set the mirrors in the installation medium installation.set_keyboard_language(language) - installation.add_bootloader() + if hasUEFI(): + installation.add_bootloader() + else: + installation.add_bootloader(bootloder='grub-install') + # If user selected to copy the current ISO network configuration # Perform a copy of the config @@ -338,7 +342,7 @@ def perform_installation(device, boot_partition, language, mirrors): for user, user_info in archinstall.arguments.get('users', {}).items(): installation.user_create(user, user_info["!password"], sudo=False) - + for superuser, user_info in archinstall.arguments.get('superusers', {}).items(): installation.user_create(superuser, user_info["!password"], sudo=True) @@ -359,4 +363,4 @@ def perform_installation(device, boot_partition, language, mirrors): ask_user_questions() perform_installation_steps() - + -- cgit v1.2.3-54-g00ecf From 77894df51c581d26c958f07524e576d3bc118efd Mon Sep 17 00:00:00 2001 From: Malccolm Haak Date: Sat, 17 Apr 2021 14:37:14 +1000 Subject: Whitespace needs to be tabs. Added test for UEFI, if not found add grub-install to pacstrap install --- archinstall/lib/installer.py | 20 +++++++++++--------- examples/guided.py | 8 ++++---- 2 files changed, 15 insertions(+), 13 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index a99bc944..70ff86f2 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -22,7 +22,7 @@ class Installer(): :param partition: Requires a partition as the first argument, this is so that the installer can mount to `mountpoint` and strap packages there. :type partition: class:`archinstall.Partition` - + :param boot_partition: There's two reasons for needing a boot partition argument, The first being so that `mkinitcpio` can place the `vmlinuz` kernel at the right place during the `pacstrap` or `linux` and the base packages for a minimal installation. @@ -33,7 +33,7 @@ class Installer(): :param profile: A profile to install, this is optional and can be called later manually. This just simplifies the process by not having to call :py:func:`~archinstall.Installer.install_profile` later on. :type profile: str, optional - + :param hostname: The given /etc/hostname for the machine. :type hostname: str, optional @@ -118,7 +118,7 @@ class Installer(): if not os.path.isdir(f"{self.mountpoint}/{os.path.dirname(absolute_logfile)}"): os.makedirs(f"{self.mountpoint}/{os.path.dirname(absolute_logfile)}") - + shutil.copy2(absolute_logfile, f"{self.mountpoint}/{absolute_logfile}") return True @@ -126,7 +126,7 @@ class Installer(): def mount(self, partition, mountpoint, create_mountpoint=True): if create_mountpoint and not os.path.isdir(f'{self.mountpoint}{mountpoint}'): os.makedirs(f'{self.mountpoint}{mountpoint}') - + partition.mount(f'{self.mountpoint}{mountpoint}') def post_install_check(self, *args, **kwargs): @@ -149,14 +149,14 @@ class Installer(): def genfstab(self, flags='-pU'): self.log(f"Updating {self.mountpoint}/etc/fstab", level=LOG_LEVELS.Info) - + fstab = sys_command(f'/usr/bin/genfstab {flags} {self.mountpoint}').trace_log with open(f"{self.mountpoint}/etc/fstab", 'ab') as fstab_fh: fstab_fh.write(fstab) if not os.path.isfile(f'{self.mountpoint}/etc/fstab'): raise RequirementError(f'Could not generate fstab, strapping in packages most likely failed (disk out of space?)\n{o}') - + return True def set_hostname(self, hostname=None, *args, **kwargs): @@ -219,7 +219,7 @@ class Installer(): network["DNS"] = dns conf = Networkd(Match={"Name": nic}, Network=network) - + with open(f"{self.mountpoint}/etc/systemd/network/10-{nic}.network", "a") as netconf: netconf.write(str(conf)) @@ -234,7 +234,7 @@ class Installer(): # If we haven't installed the base yet (function called pre-maturely) if self.helper_flags.get('base', False) is False: self.base_packages.append('iwd') - # This function will be called after minimal_installation() + # This function will be called after minimal_installation() # as a hook for post-installs. This hook is only needed if # base is not installed yet. def post_install_enable_iwd_service(*args, **kwargs): @@ -285,6 +285,8 @@ class Installer(): self.base_packages.append('xfsprogs') if self.partition.filesystem == 'f2fs': self.base_packages.append('f2fs-tools') + if not(hasUEFI()): + self.base_packages.append('grub-install') self.pacstrap(self.base_packages) self.helper_flags['base-strapped'] = True #self.genfstab() @@ -353,7 +355,7 @@ class Installer(): f"default {self.init_time}", f"timeout 5" ] - + with open(f'{self.mountpoint}/boot/loader/loader.conf', 'w') as loader: for line in loader_data: if line[:8] == 'default ': diff --git a/examples/guided.py b/examples/guided.py index dfc2da07..38d5d653 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -314,10 +314,10 @@ def perform_installation(device, boot_partition, language, mirrors): if installation.minimal_installation(): installation.set_mirrors(mirrors) # Set the mirrors in the installation medium installation.set_keyboard_language(language) - if hasUEFI(): - installation.add_bootloader() - else: - installation.add_bootloader(bootloder='grub-install') + if hasUEFI(): + installation.add_bootloader() + else: + installation.add_bootloader(bootloder='grub-install') # If user selected to copy the current ISO network configuration -- cgit v1.2.3-54-g00ecf From a316846121caf4b26f96bed8dbe057b649cc409d Mon Sep 17 00:00:00 2001 From: SecondThundeR Date: Sat, 17 Apr 2021 16:35:21 +0300 Subject: Replace input with generic_select where necessary Here are list of changes: > From now on, `generic_select` will be called "Select function", for clarity - Slightly updated select function - Removed options output for some functions, where it's better to do with select function - Added sorting for all lists passed to select function - Replaced `dict.values()` with `dict` as options parameter - Simplified input checking for all functions that use the select function - Added temporary *(for now)* workaround for passing `?` and `help` inputs - Merged fix for `partition.format()` --- archinstall/lib/user_interaction.py | 109 +++++++++++++++--------------------- examples/guided.py | 6 +- profiles/desktop.py | 2 +- profiles/i3.py | 2 +- profiles/xorg.py | 32 +++-------- 5 files changed, 57 insertions(+), 94 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 57558e14..776650b5 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -154,9 +154,13 @@ def ask_to_configure_network(): # Optionally configure one network interface. #while 1: # {MAC: Ifname} - interfaces = {'ISO-CONFIG' : 'Copy ISO network configuration to installation','NetworkManager':'Use NetworkManager to control and manage your internet connection', **list_interfaces()} + interfaces = { + 'ISO-CONFIG' : 'Copy ISO network configuration to installation', + 'NetworkManager':'Use NetworkManager to control and manage your internet connection', + **list_interfaces() + } - nic = generic_select(interfaces.values(), "Select one network interface to configure (leave blank to skip): ") + nic = generic_select(interfaces, "Select one network interface to configure (leave blank to skip): ") if nic and nic != 'Copy ISO network configuration to installation': if nic == 'Use NetworkManager to control and manage your internet connection': return {'nic': nic,'NetworkManager':True} @@ -190,12 +194,12 @@ def ask_to_configure_network(): def ask_for_disk_layout(): options = { - 'keep-existing' : 'Keep existing partition layout and select which ones to use where.', - 'format-all' : 'Format entire drive and setup a basic partition scheme.', - 'abort' : 'Abort the installation.' + 'keep-existing' : 'Keep existing partition layout and select which ones to use where', + 'format-all' : 'Format entire drive and setup a basic partition scheme', + 'abort' : 'Abort the installation' } - value = generic_select(options.values(), "Found partitions on the selected drive, (select by number) what you want to do: ") + value = generic_select(options, "Found partitions on the selected drive, (select by number) what you want to do: ", False) return next((key for key, val in options.items() if val == value), None) def ask_for_main_filesystem_format(): @@ -206,7 +210,7 @@ def ask_for_main_filesystem_format(): 'f2fs' : 'f2fs' } - value = generic_select(options.values(), "Select which filesystem your main partition should use (by number or name): ") + value = generic_select(options, "Select which filesystem your main partition should use (by number or name): ", False) return next((key for key, val in options.items() if val == value), None) def generic_select(options, input_text="Select one of the above by index or absolute value: ", allow_empty_input=True, options_output=True): @@ -215,9 +219,12 @@ def generic_select(options, input_text="Select one of the above by index or abso other than the options and their indexes. As an example: generic_select(["first", "second", "third option"]) - 1: first - 2: second - 3: third option + 0: first + 1: second + 2: third option + + When the user has entered the option correctly, + this function returns an item from list, a string, or None """ # Checking if options are different from `list` or `dict` @@ -226,14 +233,14 @@ def generic_select(options, input_text="Select one of the above by index or abso log(" * Here are the link: https://github.com/archlinux/archinstall/issues * ", fg='yellow') raise RequirementError("generic_select() reqiures list or dictionary as options.") if type(options) == dict: options = sorted(list(options.values())) # To allow only `list` and `dict`, converting values of options and sorting them here. Therefore, now we can only provide the dictionary itself - # if sort: options = sorted(list(options)) # Moved sorting for dictionaries, as some lists are already sorted, when passed here if len(options) == 0: log(" * It looks like there are no options to choose from. Maybe it's time to open an issue on GitHub! * ", fg='red') log(" * Here are the link: https://github.com/archlinux/archinstall/issues * ", fg='yellow') raise RequirementError('generic_select() requires at least one option to operate.') - # Disable the output of options items, if another function displays something different from this + # Added ability to disable the output of options items, + # if another function displays something different from this if options_output: for index, option in enumerate(options): print(f"{index}: {option}") @@ -282,18 +289,10 @@ def select_disk(dict_o_disks): if len(drives) >= 1: for index, drive in enumerate(drives): print(f"{index}: {drive} ({dict_o_disks[drive]['size'], dict_o_disks[drive].device, dict_o_disks[drive]['label']})") - drive = input('Select one of the above disks (by number or full path) or write /mnt to skip partitioning: ') - if drive.strip() == '/mnt': - return None - elif drive.isdigit(): - drive = int(drive) - if drive >= len(drives): - raise DiskError(f'Selected option "{drive}" is out of range') - drive = dict_o_disks[drives[drive]] - elif drive in dict_o_disks: - drive = dict_o_disks[drive] - else: - raise DiskError(f'Selected drive does not exist: "{drive}"') + drive = generic_select(drives, 'Select one of the above disks (by number or full path) or leave blank to skip partitioning: ', True, False) + if not drive: + return drive + drive = dict_o_disks[drive] return drive raise DiskError('select_disk() requires a non-empty dictionary of disks to select from.') @@ -312,24 +311,10 @@ def select_profile(options): profiles = sorted(list(options)) if len(profiles) >= 1: - for index, profile in enumerate(profiles): - print(f"{index}: {profile}") - - print(' -- The above list is a set of pre-programmed profiles. --') + print(' -- The below list is a set of pre-programmed profiles. --') print(' -- They might make it easier to install things like desktop environments. --') - print(' -- (Leave blank and hit enter to skip this step and continue) --') - selected_profile = input('Enter a pre-programmed profile name if you want to install one: ') - - if len(selected_profile.strip()) <= 0: - return None - - if selected_profile.isdigit() and (pos := int(selected_profile)) <= len(profiles)-1: - selected_profile = profiles[pos] - elif selected_profile in options: - selected_profile = options[options.index(selected_profile)] - else: - RequirementError("Selected profile does not exist.") + selected_profile = generic_select(profiles, 'Enter a pre-programmed profile name if you want to install one or leave blank to skip this step: ') return Profile(None, selected_profile) raise RequirementError("Selecting profiles require a least one profile to be given as an option.") @@ -359,12 +344,17 @@ def select_language(options, show_only_country_codes=True): for index, language in enumerate(languages): print(f"{index}: {language}") - print(' -- You can enter ? or help to search for more languages, or skip to use US layout --') - selected_language = input('Select one of the above keyboard languages (by number or full name): ') + # Current workaround for passing `generic_select`, + # if these values are provided as input + languages.extend(['?', 'help']) + languages_length = len(languages) + + print(f' -- You can enter ? ({languages_length - 2}) or help ({languages_length - 1}) to search for more languages, or skip to use US layout --') + selected_language = generic_select(languages, 'Select one of the above keyboard languages (by number or full name): ', True, False) - if len(selected_language.strip()) == 0: + if not selected_language: return DEFAULT_KEYBOARD_LANGUAGE - elif selected_language.lower() in ('?', 'help'): + elif selected_language in ('?', 'help'): while True: filter_string = input('Search for layout containing (example: "sv-"): ') new_options = list(search_keyboard_layout(filter_string)) @@ -375,18 +365,13 @@ def select_language(options, show_only_country_codes=True): return select_language(new_options, show_only_country_codes=False) - elif selected_language.isdigit() and (pos := int(selected_language)) <= len(languages)-1: - selected_language = languages[pos] - return selected_language # I'm leaving "options" on purpose here. # Since languages possibly contains a filtered version of # all possible language layouts, and we might want to write # for instance sv-latin1 (if we know that exists) without having to # go through the search step. - elif selected_language in languages: - return selected_language - else: - raise RequirementError("Selected language does not exist.") + + return selected_language raise RequirementError("Selecting languages require a least one language to be given as an option.") @@ -413,23 +398,17 @@ def select_mirror_regions(mirrors, show_top_mirrors=True): print_large_list(regions, margin_bottom=4) print(' -- You can skip this step by leaving the option blank --') - selected_mirror = input('Select one of the above regions to download packages from (by number or full name): ') - if len(selected_mirror.strip()) == 0: + selected_mirror = generic_select(regions, 'Select one of the above regions to download packages from (by number or full name): ', True, False) + if not selected_mirror: # Returning back empty options which can be both used to # do "if x:" logic as well as do `x.get('mirror', {}).get('sub', None)` chaining return {} - elif selected_mirror.isdigit() and int(selected_mirror) <= len(regions)-1: - # I'm leaving "mirrors" on purpose here. - # Since region possibly contains a known region of - # all possible regions, and we might want to write - # for instance Sweden (if we know that exists) without having to - # go through the search step. - region = regions[int(selected_mirror)] - selected_mirrors[region] = mirrors[region] - elif selected_mirror in mirrors: - selected_mirrors[selected_mirror] = mirrors[selected_mirror] - else: - raise RequirementError("Selected region does not exist.") + # I'm leaving "mirrors" on purpose here. + # Since region possibly contains a known region of + # all possible regions, and we might want to write + # for instance Sweden (if we know that exists) without having to + # go through the search step. + selected_mirrors[selected_mirror] = mirrors[selected_mirror] return selected_mirrors diff --git a/examples/guided.py b/examples/guided.py index c0d22023..89868148 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -76,7 +76,9 @@ def ask_user_questions(): archinstall.log(f" ** The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation). **") while True: # Select a partition - partition = archinstall.generic_select(partition_mountpoints.keys(), + # If we provide keys as options, it's better to convert them to list and sort before passing + mountpoints_list = sorted(list(partition_mountpoints.keys())) + partition = archinstall.generic_select(mountpoints_list, "Select a partition by number that you want to set a mount-point for (leave blank when done): ") if not partition: break @@ -106,7 +108,7 @@ def ask_user_questions(): # we have to check if we support it. We can do this by formatting /dev/null with the partitions filesystem. # There's a nice wrapper for this on the partition object itself that supports a path-override during .format() try: - partition.format(new_filesystem, path='/dev/null', log_formating=False, allow_formatting=True) + partition.format(new_filesystem, path='/dev/null', log_formatting=False, allow_formatting=True) except archinstall.UnknownFilesystemFormat: archinstall.log(f"Selected filesystem is not supported yet. If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") archinstall.log(f"Until then, please enter another supported filesystem.") diff --git a/profiles/desktop.py b/profiles/desktop.py index 846182e2..b46bf6fd 100644 --- a/profiles/desktop.py +++ b/profiles/desktop.py @@ -17,7 +17,7 @@ def _prep_function(*args, **kwargs): """ supported_desktops = ['gnome', 'kde', 'awesome', 'sway', 'cinnamon', 'xfce4', 'lxqt', 'i3', 'budgie', 'mate'] - desktop = archinstall.generic_select(supported_desktops, 'Select your desired desktop environment: ') + desktop = archinstall.generic_select(supported_desktops, 'Select your desired desktop environment: ', False) # Temporarily store the selected desktop profile # in a session-safe location, since this module will get reloaded diff --git a/profiles/i3.py b/profiles/i3.py index 67028b2d..fc427186 100644 --- a/profiles/i3.py +++ b/profiles/i3.py @@ -17,7 +17,7 @@ def _prep_function(*args, **kwargs): """ supported_configurations = ['i3-wm', 'i3-gaps'] - desktop = archinstall.generic_select(supported_configurations, 'Select your desired configuration: ') + desktop = archinstall.generic_select(supported_configurations, 'Select your desired configuration: ', False) # Temporarily store the selected desktop profile # in a session-safe location, since this module will get reloaded diff --git a/profiles/xorg.py b/profiles/xorg.py index e905d533..8c6f686d 100644 --- a/profiles/xorg.py +++ b/profiles/xorg.py @@ -33,10 +33,7 @@ def select_driver(options): drivers = sorted(list(options)) if len(drivers) >= 1: - for index, driver in enumerate(drivers): - print(f"{index}: {driver}") - - print(' -- The above list are supported graphic card drivers. --') + print(' -- The below list are supported graphic card drivers. --') print(' -- You need to select (and read about) which one you need. --') lspci = archinstall.sys_command(f'/usr/bin/lspci') @@ -47,7 +44,7 @@ def select_driver(options): elif b'amd' in line.lower(): print(' ** AMD card detected, suggested driver: AMD / ATI **') - selected_driver = input('Select your graphics card driver: ') + selected_driver = archinstall.generic_select(drivers, 'Select your graphics card driver: ', False) initial_option = selected_driver # Disabled search for now, only a few profiles exist anyway @@ -57,29 +54,14 @@ def select_driver(options): # filter_string = input('Search for layout containing (example: "sv-"): ') # new_options = search_keyboard_layout(filter_string) # return select_language(new_options) - if selected_driver.isdigit() and (pos := int(selected_driver)) <= len(drivers)-1: - selected_driver = options[drivers[pos]] - elif selected_driver in options: - selected_driver = options[options.index(selected_driver)] - elif len(selected_driver) == 0: - raise archinstall.RequirementError("At least one graphics driver is needed to support a graphical environment. Please restart the installer and try again.") - else: - raise archinstall.RequirementError("Selected driver does not exist.") + + selected_driver = options[selected_driver] if type(selected_driver) == dict: driver_options = sorted(list(selected_driver)) - for index, driver_package_group in enumerate(driver_options): - print(f"{index}: {driver_package_group}") - - selected_driver_package_group = input(f'Which driver-type do you want for {initial_option}: ') - if selected_driver_package_group.isdigit() and (pos := int(selected_driver_package_group)) <= len(driver_options)-1: - selected_driver_package_group = selected_driver[driver_options[pos]] - elif selected_driver_package_group in selected_driver: - selected_driver_package_group = selected_driver[selected_driver.index(selected_driver_package_group)] - elif len(selected_driver_package_group) == 0: - raise archinstall.RequirementError(f"At least one driver package is required for a graphical environment using {selected_driver}. Please restart the installer and try again.") - else: - raise archinstall.RequirementError(f"Selected driver-type does not exist for {initial_option}.") + + selected_driver_package_group = archinstall.generic_select(driver_options, f'Which driver-type do you want for {initial_option}: ', False) + selected_driver_package_group = selected_driver[selected_driver_package_group] return selected_driver_package_group -- cgit v1.2.3-54-g00ecf From 7afba65c261057808fae8e3cb22ddd89fed31f2b Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 18:43:19 +0530 Subject: rebase --- archinstall/lib/user_interaction.py | 14 ++++++++++++-- examples/guided.py | 7 +++++-- 2 files changed, 17 insertions(+), 4 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 822f63be..9d09d8f1 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -7,7 +7,7 @@ from .output import log, LOG_LEVELS from .storage import storage from .networking import list_interfaces from .general import sys_command -from .hardware import AVAILABLE_GFX_DRIVERS +from .hardware import AVAILABLE_GFX_DRIVERS, hasUEFI ## TODO: Some inconsistencies between the selection processes. ## Some return the keys from the options, some the values? @@ -143,7 +143,17 @@ def ask_for_a_timezone(): level=LOG_LEVELS.Warning, fg='red' ) - + +def ask_for_bootloader() -> str: + bootloader = "systemd-bootctl" + if hasUEFI==False: + bootloader="grub-install" + else: + bootloader_choice = input("Would you like to use Grub as a bootloader over systemd-boot [y/N] ").lower() + if bootloader_choice == "y": + bootloader="grub-install" + return bootloader + def ask_for_audio_selection(): audio = "pulseaudio" # Default for most desktop environments pipewire_choice = input("Would you like to install pipewire instead of pulseaudio as the default audio server? [Y/n] ").lower() diff --git a/examples/guided.py b/examples/guided.py index c86f2b4b..643e2c94 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -64,6 +64,8 @@ def ask_user_questions(): partition_mountpoints[partition] = None except archinstall.UnknownFilesystemFormat as err: archinstall.log(f" {partition} (Filesystem not supported)", fg='red') + + archinstall.arguments["bootloader"] = archinstall.ask_for_bootloader() # We then ask what to do with the partitions. if (option := archinstall.ask_for_disk_layout()) == 'abort': @@ -190,7 +192,7 @@ def ask_user_questions(): # Additional packages (with some light weight error handling for invalid package names) while True: if not archinstall.arguments.get('packages', None): - print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.") + print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr(in uefi systems) and optional profile packages are installed.") print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] @@ -303,7 +305,8 @@ def perform_installation(mountpoint): # Set mirrors used by pacstrap (outside of installation) if archinstall.arguments.get('mirror-region', None): archinstall.use_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors for the live medium - + if hasUEFI()==False: + installation.base_packages.replace("efibootmgr","")# if we aren't on a uefi system why install efibootmgr if installation.minimal_installation(): installation.set_hostname(archinstall.arguments['hostname']) if archinstall.arguments['mirror-region'].get("mirrors",{})!= None: -- cgit v1.2.3-54-g00ecf From 9c400aa7272fc8eb5c34b19fd65e0f3ed6cb01f5 Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 18:49:02 +0530 Subject: reworked how we handle bootloaders a little --- examples/guided.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 643e2c94..408f377a 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -307,12 +307,14 @@ def perform_installation(mountpoint): archinstall.use_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors for the live medium if hasUEFI()==False: installation.base_packages.replace("efibootmgr","")# if we aren't on a uefi system why install efibootmgr + if archinstall.arguments["bootloader"] == "grub-install": + installation.base_packages = installation.base_packages + " grub" if installation.minimal_installation(): installation.set_hostname(archinstall.arguments['hostname']) if archinstall.arguments['mirror-region'].get("mirrors",{})!= None: installation.set_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors in the installation medium installation.set_keyboard_language(archinstall.arguments['keyboard-language']) - installation.add_bootloader() + installation.add_bootloader(archinstall.arguments["bootloader"]) # If user selected to copy the current ISO network configuration # Perform a copy of the config -- cgit v1.2.3-54-g00ecf From 23704b7908798ff0328daa0fe90d3299806c50e3 Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 18:53:47 +0530 Subject: repharsed some stuff --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 408f377a..7e36f0b2 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -192,7 +192,7 @@ def ask_user_questions(): # Additional packages (with some light weight error handling for invalid package names) while True: if not archinstall.arguments.get('packages', None): - print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr(in uefi systems) and optional profile packages are installed.") + print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr(on uefi systems)/grub(on bios systems) and optional profile packages are installed.") print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] -- cgit v1.2.3-54-g00ecf From 1ea02a7e692af2f3db16308b14be2ccdacdcb761 Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:27:16 +0530 Subject: we should only look for boot on uefi systems --- examples/guided.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 7e36f0b2..df9c9c37 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -268,8 +268,8 @@ def perform_installation_steps(): partition.format() else: archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=archinstall.LOG_LEVELS.Debug) - - fs.find_partition('/boot').format('vfat') + if hasUEFI(): + fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode if archinstall.arguments.get('!encryption-password', None): # First encrypt and unlock, then format the desired partition inside the encrypted part. -- cgit v1.2.3-54-g00ecf From fc8960f2a9a9dd15185f8c4f7d9d98463663637c Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:35:28 +0530 Subject: we should only look for boot on uefi systems --- examples/guided.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index df9c9c37..5007fd33 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -268,8 +268,7 @@ def perform_installation_steps(): partition.format() else: archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=archinstall.LOG_LEVELS.Debug) - if hasUEFI(): - fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode + fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode if archinstall.arguments.get('!encryption-password', None): # First encrypt and unlock, then format the desired partition inside the encrypted part. @@ -281,8 +280,8 @@ def perform_installation_steps(): else: fs.find_partition('/').format(fs.find_partition('/').filesystem) fs.find_partition('/').mount('/mnt') - - fs.find_partition('/boot').mount('/mnt/boot') + if hasUEFI(): + fs.find_partition('/boot').mount('/mnt/boot') perform_installation('/mnt') -- cgit v1.2.3-54-g00ecf From 572ab522fc829a972b6c51774c0e04cc99590fad Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:40:09 +0530 Subject: we should only look for boot on uefi systems --- examples/guided.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 5007fd33..7af77642 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -268,7 +268,8 @@ def perform_installation_steps(): partition.format() else: archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=archinstall.LOG_LEVELS.Debug) - fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode + if hasUEFI(): + fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode if archinstall.arguments.get('!encryption-password', None): # First encrypt and unlock, then format the desired partition inside the encrypted part. -- cgit v1.2.3-54-g00ecf From dbb6d630bdfdb655a3567b8cebc5c6b82bb74459 Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:43:23 +0530 Subject: fixed some issues with adding packages --- examples/guided.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 7af77642..015cc19d 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -306,9 +306,9 @@ def perform_installation(mountpoint): if archinstall.arguments.get('mirror-region', None): archinstall.use_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors for the live medium if hasUEFI()==False: - installation.base_packages.replace("efibootmgr","")# if we aren't on a uefi system why install efibootmgr + installation.base_packages.pop(installation.base_packages.index("efibootmgr"))# if we aren't on a uefi system why install efibootmgr if archinstall.arguments["bootloader"] == "grub-install": - installation.base_packages = installation.base_packages + " grub" + installation.base_packages = installation.base_packages.append("grub") if installation.minimal_installation(): installation.set_hostname(archinstall.arguments['hostname']) if archinstall.arguments['mirror-region'].get("mirrors",{})!= None: -- cgit v1.2.3-54-g00ecf From 47202d9bf94941659946470615a8c6e013e4643e Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:46:22 +0530 Subject: moved some stuff --- examples/guided.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 015cc19d..02a39e8c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -65,7 +65,6 @@ def ask_user_questions(): except archinstall.UnknownFilesystemFormat as err: archinstall.log(f" {partition} (Filesystem not supported)", fg='red') - archinstall.arguments["bootloader"] = archinstall.ask_for_bootloader() # We then ask what to do with the partitions. if (option := archinstall.ask_for_disk_layout()) == 'abort': @@ -143,7 +142,7 @@ def ask_user_questions(): if (passwd := archinstall.get_password(prompt='Enter disk encryption password (leave blank for no encryption): ')): archinstall.arguments['!encryption-password'] = passwd archinstall.arguments['harddrive'].encryption_password = archinstall.arguments['!encryption-password'] - + archinstall.arguments["bootloader"] = archinstall.ask_for_bootloader() # Get the hostname for the machine if not archinstall.arguments.get('hostname', None): archinstall.arguments['hostname'] = input('Desired hostname for the installation: ').strip(' ') -- cgit v1.2.3-54-g00ecf From adeae68123314742dd76e2e231400c5cf6237c1e Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 19:58:23 +0530 Subject: reworked how we remove efimanager and add grub --- archinstall/lib/installer.py | 3 ++- examples/guided.py | 7 ++----- 2 files changed, 4 insertions(+), 6 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 2f90560f..4cf658c1 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -48,7 +48,8 @@ class Installer(): 'base' : False, 'bootloader' : False } - + if hasUEFI() == False: + base_packages.replace(" efibootmgr","") self.base_packages = base_packages.split(' ') if type(base_packages) is str else base_packages self.post_base_install = [] diff --git a/examples/guided.py b/examples/guided.py index 02a39e8c..8308d22c 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -300,18 +300,15 @@ def perform_installation(mountpoint): installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=archinstall.LOG_LEVELS.Info) while archinstall.service_state('reflector') not in ('dead', 'failed'): time.sleep(1) - # Set mirrors used by pacstrap (outside of installation) if archinstall.arguments.get('mirror-region', None): archinstall.use_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors for the live medium - if hasUEFI()==False: - installation.base_packages.pop(installation.base_packages.index("efibootmgr"))# if we aren't on a uefi system why install efibootmgr - if archinstall.arguments["bootloader"] == "grub-install": - installation.base_packages = installation.base_packages.append("grub") if installation.minimal_installation(): installation.set_hostname(archinstall.arguments['hostname']) if archinstall.arguments['mirror-region'].get("mirrors",{})!= None: installation.set_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors in the installation medium + if archinstall.arguments["bootloader"]=="grub-install": + installation.add_additional_packages("grub") installation.set_keyboard_language(archinstall.arguments['keyboard-language']) installation.add_bootloader(archinstall.arguments["bootloader"]) -- cgit v1.2.3-54-g00ecf From 8b723c25e2c487c508d2718b06381ca6c2b7d2a0 Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 20:36:26 +0530 Subject: changed some strings --- archinstall/lib/user_interaction.py | 2 +- examples/guided.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 818590dd..175079ee 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -149,7 +149,7 @@ def ask_for_bootloader() -> str: if hasUEFI()==False: bootloader="grub-install" else: - bootloader_choice = input("Would you like to use Grub as a bootloader over systemd-boot [y/N] ").lower() + bootloader_choice = input("Would you like to use GRUB as a bootloader instead off systemd-boot [y/N] ").lower() if bootloader_choice == "y": bootloader="grub-install" return bootloader diff --git a/examples/guided.py b/examples/guided.py index 8308d22c..3d357e2d 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -191,7 +191,7 @@ def ask_user_questions(): # Additional packages (with some light weight error handling for invalid package names) while True: if not archinstall.arguments.get('packages', None): - print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr(on uefi systems)/grub(on bios systems) and optional profile packages are installed.") + print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr (on UEFI systems)/GRUB (on BIOS systems) and optional profile packages are installed.") print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] -- cgit v1.2.3-54-g00ecf From 85c5275a8f35a7a0c0713d76c68ae0a127f1421c Mon Sep 17 00:00:00 2001 From: advaithm Date: Tue, 20 Apr 2021 21:23:11 +0530 Subject: added return true --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 3d357e2d..878412a9 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -307,7 +307,7 @@ def perform_installation(mountpoint): installation.set_hostname(archinstall.arguments['hostname']) if archinstall.arguments['mirror-region'].get("mirrors",{})!= None: installation.set_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors in the installation medium - if archinstall.arguments["bootloader"]=="grub-install": + if archinstall.arguments["bootloader"]=="grub-install" and hasUEFI()==True: installation.add_additional_packages("grub") installation.set_keyboard_language(archinstall.arguments['keyboard-language']) installation.add_bootloader(archinstall.arguments["bootloader"]) -- cgit v1.2.3-54-g00ecf From 46b872aa61e0f07fd561a4e14083a30a3d039d38 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Wed, 21 Apr 2021 14:37:23 +0200 Subject: Re-working top-level-profile lambda to be a parameter to list_profiles() instead. When skipping a profile, None is returned from somewhere and it causes a glitch. So trying to figure out where and what by cleaning up a bit --- archinstall/lib/profiles.py | 7 ++++++- examples/guided.py | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/profiles.py b/archinstall/lib/profiles.py index 21ec5f6f..95962fd6 100644 --- a/archinstall/lib/profiles.py +++ b/archinstall/lib/profiles.py @@ -15,7 +15,7 @@ def grab_url_data(path): response = urllib.request.urlopen(safe_path, context=ssl_context) return response.read() -def list_profiles(filter_irrelevant_macs=True, subpath=''): +def list_profiles(filter_irrelevant_macs=True, subpath='', filter_top_level_profiles=False): # TODO: Grab from github page as well, not just local static files if filter_irrelevant_macs: local_macs = list_interfaces() @@ -63,6 +63,11 @@ def list_profiles(filter_irrelevant_macs=True, subpath=''): cache[profile[:-3]] = {'path' : os.path.join(storage["UPSTREAM_URL"]+subpath, profile), 'description' : profile_list[profile], 'tailored' : tailored} + if filter_top_level_profiles: + for profile in list(cache.keys()): + if Profile(None, profile).is_top_level_profile() is False: + del(cache[profile]) + return cache class Script(): diff --git a/examples/guided.py b/examples/guided.py index 89868148..ef447abb 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -164,7 +164,7 @@ def ask_user_questions(): # Ask for archinstall-specific profiles (such as desktop environments etc) if not archinstall.arguments.get('profile', None): - archinstall.arguments['profile'] = archinstall.select_profile(filter(lambda profile: (Profile(None, profile).is_top_level_profile()), archinstall.list_profiles())) + archinstall.arguments['profile'] = archinstall.select_profile(archinstall.list_profiles(filter_top_level_profiles=True)) else: archinstall.arguments['profile'] = archinstall.list_profiles()[archinstall.arguments['profile']] -- cgit v1.2.3-54-g00ecf From 81c57560b3f2f0cd10dd8d6b360266f9f4622a41 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Thu, 22 Apr 2021 21:56:52 +0200 Subject: Fixes #324. --- examples/guided.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index ef447abb..09638f0e 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -74,13 +74,14 @@ def ask_user_questions(): archinstall.log(f" ** You will now select which partitions to use by selecting mount points (inside the installation). **") archinstall.log(f" ** The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation). **") + mountpoints_set = [] while True: # Select a partition # If we provide keys as options, it's better to convert them to list and sort before passing mountpoints_list = sorted(list(partition_mountpoints.keys())) partition = archinstall.generic_select(mountpoints_list, "Select a partition by number that you want to set a mount-point for (leave blank when done): ") - if not partition: + if not partition and set(mountpoints_set) & {'/', '/boot'} == {'/', '/boot'}: break # Select a mount-point @@ -122,6 +123,7 @@ def ask_user_questions(): # We can safely mark the partition for formatting and where to mount it. # TODO: allow_formatting might be redundant since target_mountpoint should only be # set if we actually want to format it anyway. + mountpoints_set.append(mountpoint) partition.allow_formatting = True partition.target_mountpoint = mountpoint # Only overwrite the filesystem definition if we selected one: -- cgit v1.2.3-54-g00ecf From 3cf8ec7ad6eccd2899ded1f80ae31c2f835c4d8f Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Thu, 22 Apr 2021 21:58:47 +0200 Subject: Added a continuation if partitions are not set yet. --- examples/guided.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 09638f0e..2bf911fc 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -81,8 +81,11 @@ def ask_user_questions(): mountpoints_list = sorted(list(partition_mountpoints.keys())) partition = archinstall.generic_select(mountpoints_list, "Select a partition by number that you want to set a mount-point for (leave blank when done): ") - if not partition and set(mountpoints_set) & {'/', '/boot'} == {'/', '/boot'}: - break + if not partition: + if set(mountpoints_set) & {'/', '/boot'} == {'/', '/boot'}: + break + + continue # Select a mount-point mountpoint = input(f"Enter a mount-point for {partition}: ").strip(' ') -- cgit v1.2.3-54-g00ecf From 839e945b87ec16129c201f731da8be12bebe6cb8 Mon Sep 17 00:00:00 2001 From: SecondThundeR Date: Fri, 23 Apr 2021 01:03:34 +0300 Subject: Moved output about base installed packages This prevents screen from being cluttered if the user enters the wrong package(or packages), allowing only repetitions of prompt to be displayed --- examples/guided.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 2bf911fc..cc9cf5fc 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -195,10 +195,10 @@ def ask_user_questions(): archinstall.arguments['audio'] = None # Additional packages (with some light weight error handling for invalid package names) + print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.") + print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") while True: if not archinstall.arguments.get('packages', None): - print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.") - print("If you desire a web browser, such as firefox or chromium, you may specify it in the following prompt.") archinstall.arguments['packages'] = [package for package in input('Write additional packages to install (space separated, leave blank to skip): ').split(' ') if len(package)] if len(archinstall.arguments['packages']): -- cgit v1.2.3-54-g00ecf From f5b6e7bafead1f604c27bfb31b84f3f560a682c8 Mon Sep 17 00:00:00 2001 From: SecondThundeR Date: Fri, 23 Apr 2021 01:55:53 +0300 Subject: Update logging for some functions - Unified view of warning (red) and info (yellow) logs - Fixed some PEP8 related issues, like removing redundant f-strings and replacing double quotes to single ones - Removed warning logging level for simple logs - Removed other background color settings for logs to fully close https://github.com/archlinux/archinstall/pull/171 --- archinstall/lib/disk.py | 4 ++-- archinstall/lib/installer.py | 10 +++++----- archinstall/lib/mirrors.py | 2 +- archinstall/lib/output.py | 4 ++-- archinstall/lib/user_interaction.py | 25 +++++++++--------------- examples/guided.py | 39 +++++++++++++++++++------------------ 6 files changed, 39 insertions(+), 45 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/disk.py b/archinstall/lib/disk.py index bada4076..de93556a 100644 --- a/archinstall/lib/disk.py +++ b/archinstall/lib/disk.py @@ -128,7 +128,7 @@ class BlockDevice(): @property def uuid(self): - log(f'BlockDevice().uuid is untested!', level=LOG_LEVELS.Warning, fg='yellow') + log('BlockDevice().uuid is untested!', level=LOG_LEVELS.Warning, fg='yellow') """ Returns the disk UUID as returned by lsblk. This is more reliable than relying on /dev/disk/by-partuuid as @@ -292,7 +292,7 @@ class Partition(): raise DiskError(f"Attempting to encrypt a partition that was not marked for encryption: {self}") if not self.safe_to_format(): - log(f"Partition {self} was marked as protected but encrypt() was called on it!", level=LOG_LEVELS.Error, fg="red") + log(f" * Partition {self} was marked as protected but encrypt() was called on it! * ", level=LOG_LEVELS.Error, fg='red') return False handle = luks2(self, None, None) diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 758033a7..c64079f6 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -79,14 +79,14 @@ class Installer(): self.genfstab() if not (missing_steps := self.post_install_check()): - self.log('Installation completed without any errors. You may now reboot.', bg='black', fg='green', level=LOG_LEVELS.Info) + self.log('Installation completed without any errors. You may now reboot.', fg='green', level=LOG_LEVELS.Info) self.sync_log_to_install_medium() return True else: - self.log('Some required steps were not successfully installed/configured before leaving the installer:', bg='black', fg='red', level=LOG_LEVELS.Warning) + self.log('Some required steps were not successfully installed/configured before leaving the installer:', fg='red', level=LOG_LEVELS.Warning) for step in missing_steps: - self.log(f' - {step}', bg='black', fg='red', level=LOG_LEVELS.Warning) + self.log(f' - {step}', fg='red', level=LOG_LEVELS.Warning) self.log(f"Detailed error logs can be found at: {storage['LOG_PATH']}", level=LOG_LEVELS.Warning) self.log(f"Submit this zip file as an issue to https://github.com/archlinux/archinstall/issues", level=LOG_LEVELS.Warning) @@ -168,7 +168,7 @@ class Installer(): return True else: self.log( - f"Time zone {zone} does not exist, continuing with system default.", + f" * Timezone \"{zone}\" does not exist, continuing with system default * ", level=LOG_LEVELS.Warning, fg='red' ) @@ -460,5 +460,5 @@ class Installer(): vconsole.write(f'KEYMAP={language}\n') vconsole.write(f'FONT=lat9w-16\n') else: - self.log(f'Keyboard language was not changed from default (no language specified).', fg="yellow", level=LOG_LEVELS.Info) + self.log('Keyboard language was not changed from default (no language specified).', fg='yellow', level=LOG_LEVELS.Info) return True diff --git a/archinstall/lib/mirrors.py b/archinstall/lib/mirrors.py index 04f47c0d..57271bf8 100644 --- a/archinstall/lib/mirrors.py +++ b/archinstall/lib/mirrors.py @@ -79,7 +79,7 @@ def list_mirrors(): try: response = urllib.request.urlopen(url) except urllib.error.URLError as err: - log(f'Could not fetch an active mirror-list: {err}', level=LOG_LEVELS.Warning, fg="yellow") + log(f"Could not fetch an active mirror-list: {err}", level=LOG_LEVELS.Warning, fg='yellow') return regions diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py index 6b184b4b..eb23faf4 100644 --- a/archinstall/lib/output.py +++ b/archinstall/lib/output.py @@ -100,12 +100,12 @@ def log(*args, **kwargs): Path(absolute_logfile).parents[0].mkdir(exist_ok=True, parents=True) except PermissionError: # Fallback to creating the log file in the current folder - err_string = f"Not enough permission to place log file at {absolute_logfile}, creating it in {Path('./').absolute()/filename} instead." + err_string = f" * Not enough permission to place log file at {absolute_logfile}, creating it in {Path('./').absolute()/filename} instead * " absolute_logfile = Path('./').absolute()/filename absolute_logfile.parents[0].mkdir(exist_ok=True) absolute_logfile = str(absolute_logfile) storage['LOG_PATH'] = './' - log(err_string, fg="red") + log(err_string, fg='red') Path(absolute_logfile).touch() # Overkill? diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 572acf4f..ec6b6d34 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -22,11 +22,7 @@ def get_longest_option(options): def check_for_correct_username(username): 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=LOG_LEVELS.Warning, - fg='red' - ) + log(' * The username you entered is invalid. Try again * ', fg='red') return False def do_countdown(): @@ -138,8 +134,7 @@ def ask_for_a_timezone(): return timezone else: log( - f"Specified timezone {timezone} does not exist.", - level=LOG_LEVELS.Warning, + f"* Specified timezone {timezone} does not exist * ", fg='red' ) @@ -185,8 +180,7 @@ def ask_to_configure_network(): break except ValueError: log( - "You need to enter a valid IP in IP-config mode.", - level=LOG_LEVELS.Warning, + 'You need to enter a valid IP in IP-config mode', fg='red' ) @@ -201,8 +195,7 @@ def ask_to_configure_network(): break except ValueError: log( - "You need to enter a valid gateway (router) IP address.", - level=LOG_LEVELS.Warning, + 'You need to enter a valid gateway (router) IP address', fg='red' ) @@ -258,15 +251,15 @@ def generic_select(options, input_text="Select one of the above by index or abso # Checking if options are different from `list` or `dict` if type(options) not in [list, dict]: log(f" * Generic select doesn't support ({type(options)}) as type of options * ", fg='red') - log(" * If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues * ", fg='yellow') + log('If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues', fg='yellow') raise RequirementError("generic_select() requires list or dictionary as options.") # To allow only `list` and `dict`, converting values of options here. # Therefore, now we can only provide the dictionary itself if type(options) == dict: options = list(options.values()) if sort: options = sorted(options) # As we pass only list and dict (converted to list), we can skip converting to list if len(options) == 0: - log(f" * Generic select didn't find any options to choose from * ", fg='red') - log(" * If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues * ", fg='yellow') + log(' * Generic select didn\'t find any options to choose from * ', fg='red') + log('If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues', fg='yellow') raise RequirementError('generic_select() requires at least one option to proceed.') @@ -398,7 +391,7 @@ def select_language(options, show_only_country_codes=True): new_options = list(search_keyboard_layout(filter_string)) if len(new_options) <= 0: - log(f"Search string '{filter_string}' yielded no results, please try another search.", fg='yellow') + log(f"Search string '{filter_string}' yielded no results, please try another search", fg='yellow') continue return select_language(new_options, show_only_country_codes=False) @@ -411,7 +404,7 @@ def select_language(options, show_only_country_codes=True): elif verify_keyboard_layout(selected_language): return selected_language else: - log(" * Given language wasn't found * ", fg='red') + log(' * Given language was not found * ', fg='red') raise RequirementError("Selecting languages require a least one language to be given as an option.") diff --git a/examples/guided.py b/examples/guided.py index cc9cf5fc..f89efa45 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -4,7 +4,7 @@ from archinstall.lib.hardware import hasUEFI from archinstall.lib.profiles import Profile if hasUEFI() is False: - archinstall.log("ArchInstall currently only supports machines booted with UEFI.\nMBR & GRUB support is coming in version 2.2.0!", fg="red", level=archinstall.LOG_LEVELS.Error) + archinstall.log(" * ArchInstall currently only supports machines booted with UEFI.\nMBR & GRUB support is coming in version 2.2.0! * ", fg='red', level=archinstall.LOG_LEVELS.Error) exit(1) def ask_user_questions(): @@ -18,8 +18,8 @@ def ask_user_questions(): try: archinstall.arguments['keyboard-language'] = archinstall.select_language(archinstall.list_keyboard_languages()).strip() break - except archinstall.RequirementError as err: - archinstall.log(err, fg="red") + except archinstall.RequirementError as e: + archinstall.log(f" * {e} * ", fg='red') # Before continuing, set the preferred keyboard layout/language in the current terminal. # This will just help the user with the next following questions. @@ -33,7 +33,7 @@ def ask_user_questions(): archinstall.arguments['mirror-region'] = archinstall.select_mirror_regions(archinstall.list_mirrors()) break except archinstall.RequirementError as e: - archinstall.log(e, fg="red") + archinstall.log(f" * {e} * ", fg='red') else: selected_region = archinstall.arguments['mirror-region'] archinstall.arguments['mirror-region'] = {selected_region : archinstall.list_mirrors()[selected_region]} @@ -67,13 +67,13 @@ def ask_user_questions(): # We then ask what to do with the partitions. if (option := archinstall.ask_for_disk_layout()) == 'abort': - archinstall.log(f"Safely aborting the installation. No changes to the disk or system has been made.") + archinstall.log('Safely aborting the installation. No changes to the disk or system has been made', fg='yellow') exit(1) elif option == 'keep-existing': archinstall.arguments['harddrive'].keep_partitions = True - archinstall.log(f" ** You will now select which partitions to use by selecting mount points (inside the installation). **") - archinstall.log(f" ** The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation). **") + archinstall.log(' -- You will now select which partitions to use by selecting mount points (inside the installation) -- ') + archinstall.log(' -- The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation) -- ') mountpoints_set = [] while True: # Select a partition @@ -103,8 +103,8 @@ def ask_user_questions(): if (autodetected_filesystem := partition.detect_inner_filesystem(old_password)): new_filesystem = autodetected_filesystem else: - archinstall.log(f"Could not auto-detect the filesystem inside the encrypted volume.", fg='red') - archinstall.log(f"A filesystem must be defined for the unlocked encrypted partition.") + archinstall.log(' * Could not auto-detect the filesystem inside the encrypted volume * ', fg='red') + archinstall.log('A filesystem must be defined for the unlocked encrypted partition') continue break @@ -114,8 +114,9 @@ def ask_user_questions(): try: partition.format(new_filesystem, path='/dev/null', log_formatting=False, allow_formatting=True) except archinstall.UnknownFilesystemFormat: - archinstall.log(f"Selected filesystem is not supported yet. If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") - archinstall.log(f"Until then, please enter another supported filesystem.") + archinstall.log(' * Selected filesystem is not supported yet * ', fg='red') + archinstall.log(f"If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") + archinstall.log('Until then, please enter another supported filesystem') continue except archinstall.SysCallError: pass # Expected exception since mkfs. can not format /dev/null. @@ -178,7 +179,7 @@ def ask_user_questions(): with archinstall.arguments['profile'].load_instructions(namespace=f"{archinstall.arguments['profile'].namespace}.py") as imported: if not imported._prep_function(): archinstall.log( - ' * Profile\'s preparation requirements was not fulfilled.', + ' * Profile\'s preparation requirements was not fulfilled * ', fg='red' ) exit(1) @@ -204,11 +205,11 @@ def ask_user_questions(): if len(archinstall.arguments['packages']): # Verify packages that were given try: - archinstall.log(f"Verifying that additional packages exist (this might take a few seconds)") + archinstall.log('Verifying that additional packages exist (this might take a few seconds)', fg='yellow') archinstall.validate_package_list(archinstall.arguments['packages']) break except archinstall.RequirementError as e: - archinstall.log(e, fg='red') + archinstall.log(f" * {e} * ", fg='red') archinstall.arguments['packages'] = None # Clear the packages to trigger a new input question else: # no additional packages were selected, which we'll allow @@ -218,7 +219,7 @@ def ask_user_questions(): if not archinstall.arguments.get('nic', None): archinstall.arguments['nic'] = archinstall.ask_to_configure_network() if not archinstall.arguments['nic']: - archinstall.log(f"No network configuration was selected. Network is going to be unavailable until configured manually!", fg="yellow") + archinstall.log('No network configuration was selected. Network is going to be unavailable until configured manually!', fg='yellow') if not archinstall.arguments.get('timezone', None): archinstall.arguments['timezone'] = archinstall.ask_for_a_timezone() @@ -299,7 +300,7 @@ def perform_installation(mountpoint): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist # We need to wait for it before we continue since we opted in to use a custom mirror/region. - installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=archinstall.LOG_LEVELS.Info) + installation.log('Waiting for automatic mirror selection (reflector) to complete...', level=archinstall.LOG_LEVELS.Info) while archinstall.service_state('reflector') not in ('dead', 'failed'): time.sleep(1) @@ -356,9 +357,9 @@ def perform_installation(mountpoint): if (root_pw := archinstall.arguments.get('!root-password', None)) and len(root_pw): installation.user_set_pw('root', root_pw) - installation.log("For post-installation tips, see https://wiki.archlinux.org/index.php/Installation_guide#Post-installation", fg="yellow") - choice = input("Would you like to chroot into the newly created installation and perform post-installation configuration? [Y/n] ") - if choice.lower() in ("y", ""): + installation.log('For post-installation tips, see https://wiki.archlinux.org/index.php/Installation_guide#Post-installation', fg='yellow') + choice = input('Would you like to chroot into the newly created installation and perform post-installation configuration? [Y/n] ') + if choice.lower() in ('y', ''): try: installation.drop_to_shell() except: -- cgit v1.2.3-54-g00ecf From 5c9859d316b8064949370c03745cfd99e0d67670 Mon Sep 17 00:00:00 2001 From: Aggam Rahamim Date: Sun, 25 Apr 2021 14:55:39 +0300 Subject: having ability to use multiple kernels --- archinstall/lib/installer.py | 4 ++-- archinstall/lib/user_interaction.py | 4 +++- examples/guided.py | 19 +++++++++++-------- 3 files changed, 16 insertions(+), 11 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index 7f6311c9..d952a6ed 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -34,8 +34,8 @@ class Installer(): :type hostname: str, optional """ - def __init__(self, target, *, base_packages=' base base-devel linux-firmware efibootmgr', kernel='linux'): - base_packages = kernel + base_packages + def __init__(self, target, *, base_packages='base base-devel linux-firmware efibootmgr ', kernels='linux'): + base_packages = base_packages + kernels.replace(',', ' ') self.target = target self.init_time = time.strftime('%Y-%m-%d_%H-%M-%S') self.milliseconds = int(str(time.time()).split('.')[1]) diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index 99cf6274..3da24684 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -218,6 +218,8 @@ def generic_select(options, input_text="Select one of the above by index or abso 1: first 2: second 3: third option + + it will return the selected text. """ if type(options) == dict: options = list(options) @@ -263,7 +265,7 @@ def select_disk(dict_o_disks): elif drive.isdigit(): drive = int(drive) if drive >= len(drives): - raise DiskError(f'Selected option "{drive}" is out of range') + raise Dis1ror(f'Selected option "{drive}" is out of range') drive = dict_o_disks[drives[drive]] elif drive in dict_o_disks: drive = dict_o_disks[drive] diff --git a/examples/guided.py b/examples/guided.py index e6abe872..ee7b63d9 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -2,6 +2,7 @@ import getpass, time, json, os import archinstall from archinstall.lib.hardware import hasUEFI from archinstall.lib.profiles import Profile +from archinstall.lib.user_interaction import generic_select if hasUEFI() is False: log("ArchInstall currently only supports machines booted with UEFI. MBR & GRUB support is coming in version 2.2.0!", fg="red", level=archinstall.LOG_LEVELS.Error) @@ -168,7 +169,6 @@ def ask_user_questions(): # Ask about audio server selection if one is not already set if not archinstall.arguments.get('audio', None): - # only ask for audio server selection on a desktop profile if str(archinstall.arguments['profile']) == 'Profile(desktop)': archinstall.arguments['audio'] = archinstall.ask_for_audio_selection() @@ -178,12 +178,15 @@ def ask_user_questions(): archinstall.arguments['audio'] = None # Ask what kernel user wants: - kernel = input("1. linux\n2. linux-lts\n3. linux-zen\nchoose a kernel of the following: ") - try: - archinstall.arguments['kernel'] = ['linux', 'linux-lts', 'linux-zen'][int(kernel) - 1] - except: - archinstall.log('invalid kernel selected. defaulting to \'linux\'.') - archinstall.arguments['kernel'] = 'linux' + while True: + kernel = generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:") + if (archinstall.arguments['kernels'] == None or archinstall.arguments['kernels'] == ""): + archinstall.arguments['kernels'] = kernel + else: + if (kernel == "continue"): + break + archinstall.arguments['kernels'] += "," + kernel + # Additional packages (with some light weight error handling for invalid package names) @@ -281,7 +284,7 @@ def perform_installation(mountpoint): Only requirement is that the block devices are formatted and setup prior to entering this function. """ - with archinstall.Installer(mountpoint, kernel=archinstall.arguments['kernel']) as installation: + with archinstall.Installer(mountpoint, kernels=archinstall.arguments['kernels']) as installation: ## if len(mirrors): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist -- cgit v1.2.3-54-g00ecf From fa9a08b86dd902ef5c5277b098fc22031de271df Mon Sep 17 00:00:00 2001 From: Aggam Rahamim Date: Tue, 27 Apr 2021 12:40:05 +0300 Subject: having ability to use multiple kernels - dict fix --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index ddc4d06f..4df1d9de 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -190,7 +190,7 @@ def ask_user_questions(): # Ask what kernel user wants: while True: kernel = generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:") - if (archinstall.arguments['kernels'] == None or archinstall.arguments['kernels'] == ""): + if (archinstall.arguments.get("kernels", None) == None): archinstall.arguments['kernels'] = kernel else: if (kernel == "continue"): -- cgit v1.2.3-54-g00ecf From 1be405aa77f809d847eb6eb8ad58ee8c9574452f Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 27 Apr 2021 12:26:59 +0200 Subject: Corrected indentation (mixed spaces and tabs) --- examples/guided.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 4df1d9de..6177e5ac 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -186,8 +186,8 @@ def ask_user_questions(): # packages installed by a profile may depend on audio and something may get installed anyways, not much we can do about that. # we will not try to remove packages post-installation to not have audio, as that may cause multiple issues archinstall.arguments['audio'] = None - - # Ask what kernel user wants: + + # Ask what kernel user wants: while True: kernel = generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:") if (archinstall.arguments.get("kernels", None) == None): @@ -384,4 +384,4 @@ def perform_installation(mountpoint): pass ask_user_questions() -perform_installation_steps() \ No newline at end of file +perform_installation_steps() -- cgit v1.2.3-54-g00ecf From b6cd5835f19e15f41a41ac8172e5dabb3cb7fa39 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 27 Apr 2021 12:37:16 +0200 Subject: Reduced complexity in guided for the kernel selection process. --- examples/guided.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index f4cf097e..52ee07a6 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -189,16 +189,13 @@ def ask_user_questions(): archinstall.arguments['audio'] = None # Ask what kernel user wants: - while True: - kernel = generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:") - if (archinstall.arguments.get("kernels", None) == None): + if not archinstall.arguments.get("kernels", None): + archinstall.log(f"Here you can choose which kernel to use, leave blank for default which is 'linux'.") + + if (kernel := generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:")): archinstall.arguments['kernels'] = kernel else: - if (kernel == "continue"): - break - archinstall.arguments['kernels'] += "," + kernel - - + archinstall.arguments['kernels'] = 'linux' # Additional packages (with some light weight error handling for invalid package names) while True: -- cgit v1.2.3-54-g00ecf From 2762144e32413ee8d6df433d31bc7b096d11e700 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 27 Apr 2021 12:39:13 +0200 Subject: Added a failsafe for kernels argument to be defaulted to linux, since 'None' could technically end up here. --- examples/guided.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples') diff --git a/examples/guided.py b/examples/guided.py index 52ee07a6..6d8155c7 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -301,7 +301,7 @@ def perform_installation(mountpoint): Only requirement is that the block devices are formatted and setup prior to entering this function. """ - with archinstall.Installer(mountpoint, kernels=archinstall.arguments['kernels']) as installation: + with archinstall.Installer(mountpoint, kernels=archinstall.arguments.get('kernels', 'linux')) as installation: ## if len(mirrors): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist -- cgit v1.2.3-54-g00ecf From 985b7fac3ff400de9954d441480ab795222f4b24 Mon Sep 17 00:00:00 2001 From: SecondThundeR Date: Tue, 27 Apr 2021 15:14:28 +0300 Subject: Revert "Update logging for some functions" This reverts commit f5b6e7bafead1f604c27bfb31b84f3f560a682c8. Reverting commit due to currently redundant change and merge conflict --- archinstall/lib/disk.py | 4 ++-- archinstall/lib/installer.py | 10 +++++----- archinstall/lib/mirrors.py | 2 +- archinstall/lib/output.py | 4 ++-- archinstall/lib/user_interaction.py | 25 +++++++++++++++--------- examples/guided.py | 39 ++++++++++++++++++------------------- 6 files changed, 45 insertions(+), 39 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/disk.py b/archinstall/lib/disk.py index de93556a..bada4076 100644 --- a/archinstall/lib/disk.py +++ b/archinstall/lib/disk.py @@ -128,7 +128,7 @@ class BlockDevice(): @property def uuid(self): - log('BlockDevice().uuid is untested!', level=LOG_LEVELS.Warning, fg='yellow') + log(f'BlockDevice().uuid is untested!', level=LOG_LEVELS.Warning, fg='yellow') """ Returns the disk UUID as returned by lsblk. This is more reliable than relying on /dev/disk/by-partuuid as @@ -292,7 +292,7 @@ class Partition(): raise DiskError(f"Attempting to encrypt a partition that was not marked for encryption: {self}") if not self.safe_to_format(): - log(f" * Partition {self} was marked as protected but encrypt() was called on it! * ", level=LOG_LEVELS.Error, fg='red') + log(f"Partition {self} was marked as protected but encrypt() was called on it!", level=LOG_LEVELS.Error, fg="red") return False handle = luks2(self, None, None) diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index c64079f6..758033a7 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -79,14 +79,14 @@ class Installer(): self.genfstab() if not (missing_steps := self.post_install_check()): - self.log('Installation completed without any errors. You may now reboot.', fg='green', level=LOG_LEVELS.Info) + self.log('Installation completed without any errors. You may now reboot.', bg='black', fg='green', level=LOG_LEVELS.Info) self.sync_log_to_install_medium() return True else: - self.log('Some required steps were not successfully installed/configured before leaving the installer:', fg='red', level=LOG_LEVELS.Warning) + self.log('Some required steps were not successfully installed/configured before leaving the installer:', bg='black', fg='red', level=LOG_LEVELS.Warning) for step in missing_steps: - self.log(f' - {step}', fg='red', level=LOG_LEVELS.Warning) + self.log(f' - {step}', bg='black', fg='red', level=LOG_LEVELS.Warning) self.log(f"Detailed error logs can be found at: {storage['LOG_PATH']}", level=LOG_LEVELS.Warning) self.log(f"Submit this zip file as an issue to https://github.com/archlinux/archinstall/issues", level=LOG_LEVELS.Warning) @@ -168,7 +168,7 @@ class Installer(): return True else: self.log( - f" * Timezone \"{zone}\" does not exist, continuing with system default * ", + f"Time zone {zone} does not exist, continuing with system default.", level=LOG_LEVELS.Warning, fg='red' ) @@ -460,5 +460,5 @@ class Installer(): vconsole.write(f'KEYMAP={language}\n') vconsole.write(f'FONT=lat9w-16\n') else: - self.log('Keyboard language was not changed from default (no language specified).', fg='yellow', level=LOG_LEVELS.Info) + self.log(f'Keyboard language was not changed from default (no language specified).', fg="yellow", level=LOG_LEVELS.Info) return True diff --git a/archinstall/lib/mirrors.py b/archinstall/lib/mirrors.py index 57271bf8..04f47c0d 100644 --- a/archinstall/lib/mirrors.py +++ b/archinstall/lib/mirrors.py @@ -79,7 +79,7 @@ def list_mirrors(): try: response = urllib.request.urlopen(url) except urllib.error.URLError as err: - log(f"Could not fetch an active mirror-list: {err}", level=LOG_LEVELS.Warning, fg='yellow') + log(f'Could not fetch an active mirror-list: {err}', level=LOG_LEVELS.Warning, fg="yellow") return regions diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py index eb23faf4..6b184b4b 100644 --- a/archinstall/lib/output.py +++ b/archinstall/lib/output.py @@ -100,12 +100,12 @@ def log(*args, **kwargs): Path(absolute_logfile).parents[0].mkdir(exist_ok=True, parents=True) except PermissionError: # Fallback to creating the log file in the current folder - err_string = f" * Not enough permission to place log file at {absolute_logfile}, creating it in {Path('./').absolute()/filename} instead * " + err_string = f"Not enough permission to place log file at {absolute_logfile}, creating it in {Path('./').absolute()/filename} instead." absolute_logfile = Path('./').absolute()/filename absolute_logfile.parents[0].mkdir(exist_ok=True) absolute_logfile = str(absolute_logfile) storage['LOG_PATH'] = './' - log(err_string, fg='red') + log(err_string, fg="red") Path(absolute_logfile).touch() # Overkill? diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index ec6b6d34..572acf4f 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -22,7 +22,11 @@ def get_longest_option(options): def check_for_correct_username(username): 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 * ', fg='red') + log( + "The username you entered is invalid. Try again", + level=LOG_LEVELS.Warning, + fg='red' + ) return False def do_countdown(): @@ -134,7 +138,8 @@ def ask_for_a_timezone(): return timezone else: log( - f"* Specified timezone {timezone} does not exist * ", + f"Specified timezone {timezone} does not exist.", + level=LOG_LEVELS.Warning, fg='red' ) @@ -180,7 +185,8 @@ def ask_to_configure_network(): break except ValueError: log( - 'You need to enter a valid IP in IP-config mode', + "You need to enter a valid IP in IP-config mode.", + level=LOG_LEVELS.Warning, fg='red' ) @@ -195,7 +201,8 @@ def ask_to_configure_network(): break except ValueError: log( - 'You need to enter a valid gateway (router) IP address', + "You need to enter a valid gateway (router) IP address.", + level=LOG_LEVELS.Warning, fg='red' ) @@ -251,15 +258,15 @@ def generic_select(options, input_text="Select one of the above by index or abso # Checking if options are different from `list` or `dict` if type(options) not in [list, dict]: log(f" * Generic select doesn't support ({type(options)}) as type of options * ", fg='red') - log('If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues', fg='yellow') + log(" * If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues * ", fg='yellow') raise RequirementError("generic_select() requires list or dictionary as options.") # To allow only `list` and `dict`, converting values of options here. # Therefore, now we can only provide the dictionary itself if type(options) == dict: options = list(options.values()) if sort: options = sorted(options) # As we pass only list and dict (converted to list), we can skip converting to list if len(options) == 0: - log(' * Generic select didn\'t find any options to choose from * ', fg='red') - log('If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues', fg='yellow') + log(f" * Generic select didn't find any options to choose from * ", fg='red') + log(" * If problem persists, please create an issue on https://github.com/archlinux/archinstall/issues * ", fg='yellow') raise RequirementError('generic_select() requires at least one option to proceed.') @@ -391,7 +398,7 @@ def select_language(options, show_only_country_codes=True): new_options = list(search_keyboard_layout(filter_string)) if len(new_options) <= 0: - log(f"Search string '{filter_string}' yielded no results, please try another search", fg='yellow') + log(f"Search string '{filter_string}' yielded no results, please try another search.", fg='yellow') continue return select_language(new_options, show_only_country_codes=False) @@ -404,7 +411,7 @@ def select_language(options, show_only_country_codes=True): elif verify_keyboard_layout(selected_language): return selected_language else: - log(' * Given language was not found * ', fg='red') + log(" * Given language wasn't found * ", fg='red') raise RequirementError("Selecting languages require a least one language to be given as an option.") diff --git a/examples/guided.py b/examples/guided.py index f89efa45..cc9cf5fc 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -4,7 +4,7 @@ from archinstall.lib.hardware import hasUEFI from archinstall.lib.profiles import Profile if hasUEFI() is False: - archinstall.log(" * ArchInstall currently only supports machines booted with UEFI.\nMBR & GRUB support is coming in version 2.2.0! * ", fg='red', level=archinstall.LOG_LEVELS.Error) + archinstall.log("ArchInstall currently only supports machines booted with UEFI.\nMBR & GRUB support is coming in version 2.2.0!", fg="red", level=archinstall.LOG_LEVELS.Error) exit(1) def ask_user_questions(): @@ -18,8 +18,8 @@ def ask_user_questions(): try: archinstall.arguments['keyboard-language'] = archinstall.select_language(archinstall.list_keyboard_languages()).strip() break - except archinstall.RequirementError as e: - archinstall.log(f" * {e} * ", fg='red') + except archinstall.RequirementError as err: + archinstall.log(err, fg="red") # Before continuing, set the preferred keyboard layout/language in the current terminal. # This will just help the user with the next following questions. @@ -33,7 +33,7 @@ def ask_user_questions(): archinstall.arguments['mirror-region'] = archinstall.select_mirror_regions(archinstall.list_mirrors()) break except archinstall.RequirementError as e: - archinstall.log(f" * {e} * ", fg='red') + archinstall.log(e, fg="red") else: selected_region = archinstall.arguments['mirror-region'] archinstall.arguments['mirror-region'] = {selected_region : archinstall.list_mirrors()[selected_region]} @@ -67,13 +67,13 @@ def ask_user_questions(): # We then ask what to do with the partitions. if (option := archinstall.ask_for_disk_layout()) == 'abort': - archinstall.log('Safely aborting the installation. No changes to the disk or system has been made', fg='yellow') + archinstall.log(f"Safely aborting the installation. No changes to the disk or system has been made.") exit(1) elif option == 'keep-existing': archinstall.arguments['harddrive'].keep_partitions = True - archinstall.log(' -- You will now select which partitions to use by selecting mount points (inside the installation) -- ') - archinstall.log(' -- The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation) -- ') + archinstall.log(f" ** You will now select which partitions to use by selecting mount points (inside the installation). **") + archinstall.log(f" ** The root would be a simple / and the boot partition /boot (as all paths are relative inside the installation). **") mountpoints_set = [] while True: # Select a partition @@ -103,8 +103,8 @@ def ask_user_questions(): if (autodetected_filesystem := partition.detect_inner_filesystem(old_password)): new_filesystem = autodetected_filesystem else: - archinstall.log(' * Could not auto-detect the filesystem inside the encrypted volume * ', fg='red') - archinstall.log('A filesystem must be defined for the unlocked encrypted partition') + archinstall.log(f"Could not auto-detect the filesystem inside the encrypted volume.", fg='red') + archinstall.log(f"A filesystem must be defined for the unlocked encrypted partition.") continue break @@ -114,9 +114,8 @@ def ask_user_questions(): try: partition.format(new_filesystem, path='/dev/null', log_formatting=False, allow_formatting=True) except archinstall.UnknownFilesystemFormat: - archinstall.log(' * Selected filesystem is not supported yet * ', fg='red') - archinstall.log(f"If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") - archinstall.log('Until then, please enter another supported filesystem') + archinstall.log(f"Selected filesystem is not supported yet. If you want archinstall to support '{new_filesystem}', please create a issue-ticket suggesting it on github at https://github.com/archlinux/archinstall/issues.") + archinstall.log(f"Until then, please enter another supported filesystem.") continue except archinstall.SysCallError: pass # Expected exception since mkfs. can not format /dev/null. @@ -179,7 +178,7 @@ def ask_user_questions(): with archinstall.arguments['profile'].load_instructions(namespace=f"{archinstall.arguments['profile'].namespace}.py") as imported: if not imported._prep_function(): archinstall.log( - ' * Profile\'s preparation requirements was not fulfilled * ', + ' * Profile\'s preparation requirements was not fulfilled.', fg='red' ) exit(1) @@ -205,11 +204,11 @@ def ask_user_questions(): if len(archinstall.arguments['packages']): # Verify packages that were given try: - archinstall.log('Verifying that additional packages exist (this might take a few seconds)', fg='yellow') + archinstall.log(f"Verifying that additional packages exist (this might take a few seconds)") archinstall.validate_package_list(archinstall.arguments['packages']) break except archinstall.RequirementError as e: - archinstall.log(f" * {e} * ", fg='red') + archinstall.log(e, fg='red') archinstall.arguments['packages'] = None # Clear the packages to trigger a new input question else: # no additional packages were selected, which we'll allow @@ -219,7 +218,7 @@ def ask_user_questions(): if not archinstall.arguments.get('nic', None): archinstall.arguments['nic'] = archinstall.ask_to_configure_network() if not archinstall.arguments['nic']: - archinstall.log('No network configuration was selected. Network is going to be unavailable until configured manually!', fg='yellow') + archinstall.log(f"No network configuration was selected. Network is going to be unavailable until configured manually!", fg="yellow") if not archinstall.arguments.get('timezone', None): archinstall.arguments['timezone'] = archinstall.ask_for_a_timezone() @@ -300,7 +299,7 @@ def perform_installation(mountpoint): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist # We need to wait for it before we continue since we opted in to use a custom mirror/region. - installation.log('Waiting for automatic mirror selection (reflector) to complete...', level=archinstall.LOG_LEVELS.Info) + installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=archinstall.LOG_LEVELS.Info) while archinstall.service_state('reflector') not in ('dead', 'failed'): time.sleep(1) @@ -357,9 +356,9 @@ def perform_installation(mountpoint): if (root_pw := archinstall.arguments.get('!root-password', None)) and len(root_pw): installation.user_set_pw('root', root_pw) - installation.log('For post-installation tips, see https://wiki.archlinux.org/index.php/Installation_guide#Post-installation', fg='yellow') - choice = input('Would you like to chroot into the newly created installation and perform post-installation configuration? [Y/n] ') - if choice.lower() in ('y', ''): + installation.log("For post-installation tips, see https://wiki.archlinux.org/index.php/Installation_guide#Post-installation", fg="yellow") + choice = input("Would you like to chroot into the newly created installation and perform post-installation configuration? [Y/n] ") + if choice.lower() in ("y", ""): try: installation.drop_to_shell() except: -- cgit v1.2.3-54-g00ecf From 090b98b8307fd924882e78b69df9227b4621ec6b Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Tue, 27 Apr 2021 14:43:17 +0000 Subject: Moving away from custom log levels, to something that's well defined. (#360) * Moving away from custom log levels, to something that's well defined. * Added backward compability to log() as well. * Added an option to force log messages out on screen even if the level is below the log level threashold. * Added force log messages when wrong notation is used. * Added some more length to the deprecated message * Swapped all log levels to use logging. instead. Co-authored-by: Anton Hvornum --- archinstall/lib/disk.py | 42 +++++++++++------------ archinstall/lib/general.py | 30 ++++++++--------- archinstall/lib/installer.py | 55 +++++++++++++++--------------- archinstall/lib/luks.py | 11 +++--- archinstall/lib/mirrors.py | 6 ++-- archinstall/lib/output.py | 67 +++++++++++++++++++++++++++---------- archinstall/lib/profiles.py | 6 ++-- archinstall/lib/user_interaction.py | 12 +++---- examples/guided.py | 14 ++++---- 9 files changed, 139 insertions(+), 104 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/disk.py b/archinstall/lib/disk.py index 67c2bdcd..8c7c6818 100644 --- a/archinstall/lib/disk.py +++ b/archinstall/lib/disk.py @@ -1,9 +1,9 @@ import glob, re, os, json, time, hashlib -import pathlib, traceback +import pathlib, traceback, logging from collections import OrderedDict from .exceptions import DiskError from .general import * -from .output import log, LOG_LEVELS +from .output import log from .storage import storage from .hardware import hasUEFI @@ -88,7 +88,7 @@ class BlockDevice(): raise DiskError(f'A crypt device ({self.path}) without a parent kernel device name.') return f"/dev/{self.info['pkname']}" else: - log(f"Unknown blockdevice type for {self.path}: {self.info['type']}", level=LOG_LEVELS.Debug) + log(f"Unknown blockdevice type for {self.path}: {self.info['type']}", level=logging.DEBUG) # if not stat.S_ISBLK(os.stat(full_path).st_mode): # raise DiskError(f'Selected disk "{full_path}" is not a block device.') @@ -129,7 +129,7 @@ class BlockDevice(): @property def uuid(self): - log(f'BlockDevice().uuid is untested!', level=LOG_LEVELS.Warning, fg='yellow') + log(f'BlockDevice().uuid is untested!', level=logging.WARNING, fg='yellow') """ Returns the disk UUID as returned by lsblk. This is more reliable than relying on /dev/disk/by-partuuid as @@ -222,8 +222,8 @@ class Partition(): @encrypted.setter def encrypted(self, value :bool): if value: - log(f'Marking {self} as encrypted: {value}', level=LOG_LEVELS.Debug) - log(f"Callstrack when marking the partition: {''.join(traceback.format_stack())}", level=LOG_LEVELS.Debug) + log(f'Marking {self} as encrypted: {value}', level=logging.DEBUG) + log(f"Callstrack when marking the partition: {''.join(traceback.format_stack())}", level=logging.DEBUG) self._encrypted = value @@ -240,7 +240,7 @@ class Partition(): return self.path def detect_inner_filesystem(self, password): - log(f'Trying to detect inner filesystem format on {self} (This might take a while)', level=LOG_LEVELS.Info) + log(f'Trying to detect inner filesystem format on {self} (This might take a while)', level=logging.INFO) from .luks import luks2 try: @@ -269,16 +269,16 @@ class Partition(): def safe_to_format(self): if self.allow_formatting is False: - log(f"Partition {self} is not marked for formatting.", level=LOG_LEVELS.Debug) + log(f"Partition {self} is not marked for formatting.", level=logging.DEBUG) return False elif self.target_mountpoint == '/boot': try: if self.has_content(): - log(f"Partition {self} is a boot partition and has content inside.", level=LOG_LEVELS.Debug) + log(f"Partition {self} is a boot partition and has content inside.", level=logging.DEBUG) return False except SysCallError as err: - log(err.message, LOG_LEVELS.Debug) - log(f"Partition {self} was identified as /boot but we could not mount to check for content, continuing!", level=LOG_LEVELS.Debug) + log(err.message, logging.DEBUG) + log(f"Partition {self} was identified as /boot but we could not mount to check for content, continuing!", level=logging.DEBUG) pass return True @@ -293,7 +293,7 @@ class Partition(): raise DiskError(f"Attempting to encrypt a partition that was not marked for encryption: {self}") if not self.safe_to_format(): - log(f"Partition {self} was marked as protected but encrypt() was called on it!", level=LOG_LEVELS.Error, fg="red") + log(f"Partition {self} was marked as protected but encrypt() was called on it!", level=logging.ERROR, fg="red") return False handle = luks2(self, None, None) @@ -321,7 +321,7 @@ class Partition(): raise PermissionError(f"{self} is not formatable either because instance is locked ({self.allow_formatting}) or a blocking flag was given ({allow_formatting})") if log_formatting: - log(f'Formatting {path} -> {filesystem}', level=LOG_LEVELS.Info) + log(f'Formatting {path} -> {filesystem}', level=logging.INFO) if filesystem == 'btrfs': o = b''.join(sys_command(f'/usr/bin/mkfs.btrfs -f {path}')) @@ -376,7 +376,7 @@ class Partition(): def mount(self, target, fs=None, options=''): if not self.mountpoint: - log(f'Mounting {self} to {target}', level=LOG_LEVELS.Info) + log(f'Mounting {self} to {target}', level=logging.INFO) if not fs: if not self.filesystem: raise DiskError(f'Need to format (or define) the filesystem on {self} before mounting.') fs = self.filesystem @@ -434,7 +434,7 @@ class Filesystem(): def __enter__(self, *args, **kwargs): if self.blockdevice.keep_partitions is False: - log(f'Wiping {self.blockdevice} by using partition format {self.mode}', level=LOG_LEVELS.Debug) + log(f'Wiping {self.blockdevice} by using partition format {self.mode}', level=logging.DEBUG) if self.mode == GPT: if self.raw_parted(f'{self.blockdevice.device} mklabel gpt').exit_code == 0: self.blockdevice.flush_cache() @@ -451,7 +451,7 @@ class Filesystem(): # TODO: partition_table_type is hardcoded to GPT at the moment. This has to be changed. elif self.mode == self.blockdevice.partition_table_type: - log(f'Kept partition format {self.mode} for {self.blockdevice}', level=LOG_LEVELS.Debug) + log(f'Kept partition format {self.mode} for {self.blockdevice}', level=logging.DEBUG) else: raise DiskError(f'The selected partition table format {self.mode} does not match that of {self.blockdevice}.') @@ -474,7 +474,7 @@ class Filesystem(): def raw_parted(self, string:str): x = sys_command(f'/usr/bin/parted -s {string}') - log(f"'parted -s {string}' returned: {b''.join(x)}", level=LOG_LEVELS.Debug) + log(f"'parted -s {string}' returned: {b''.join(x)}", level=logging.DEBUG) return x def parted(self, string:str): @@ -487,7 +487,7 @@ class Filesystem(): return self.raw_parted(string).exit_code def use_entire_disk(self, root_filesystem_type='ext4'): - log(f"Using and formatting the entire {self.blockdevice}.", level=LOG_LEVELS.Debug) + log(f"Using and formatting the entire {self.blockdevice}.", level=logging.DEBUG) if hasUEFI(): self.add_partition('primary', start='1MiB', end='513MiB', format='fat32') self.set_name(0, 'EFI') @@ -499,7 +499,7 @@ class Filesystem(): self.blockdevice.partition[0].filesystem = 'vfat' self.blockdevice.partition[1].filesystem = root_filesystem_type - log(f"Set the root partition {self.blockdevice.partition[1]} to use filesystem {root_filesystem_type}.", level=LOG_LEVELS.Debug) + log(f"Set the root partition {self.blockdevice.partition[1]} to use filesystem {root_filesystem_type}.", level=logging.DEBUG) self.blockdevice.partition[0].target_mountpoint = '/boot' self.blockdevice.partition[1].target_mountpoint = '/' @@ -510,12 +510,12 @@ class Filesystem(): #we don't need a seprate boot partition it would be a waste of space self.add_partition('primary', start='1MB', end='100%') self.blockdevice.partition[0].filesystem=root_filesystem_type - log(f"Set the root partition {self.blockdevice.partition[0]} to use filesystem {root_filesystem_type}.", level=LOG_LEVELS.Debug) + log(f"Set the root partition {self.blockdevice.partition[0]} to use filesystem {root_filesystem_type}.", level=logging.DEBUG) self.blockdevice.partition[0].target_mountpoint = '/' self.blockdevice.partition[0].allow_formatting = True def add_partition(self, type, start, end, format=None): - log(f'Adding partition to {self.blockdevice}', level=LOG_LEVELS.Info) + log(f'Adding partition to {self.blockdevice}', level=logging.INFO) previous_partitions = self.blockdevice.partitions if self.mode == MBR: diff --git a/archinstall/lib/general.py b/archinstall/lib/general.py index dc0f018a..eb0c5d14 100644 --- a/archinstall/lib/general.py +++ b/archinstall/lib/general.py @@ -1,10 +1,10 @@ import os, json, hashlib, shlex, sys -import time, pty +import time, pty, logging from datetime import datetime, date from subprocess import Popen, STDOUT, PIPE, check_output from select import epoll, EPOLLIN, EPOLLHUP from .exceptions import * -from .output import log, LOG_LEVELS +from .output import log def gen_uid(entropy_length=256): return hashlib.sha512(os.urandom(entropy_length)).hexdigest() @@ -84,7 +84,7 @@ class sys_command():#Thread): self.log = kwargs.get('log', log) if kwargs['emulate']: - self.log(f"Starting command '{cmd}' in emulation mode.", level=LOG_LEVELS.Debug) + self.log(f"Starting command '{cmd}' in emulation mode.", level=logging.DEBUG) if type(cmd) is list: # if we get a list of arguments @@ -204,7 +204,7 @@ class sys_command():#Thread): os.execve(self.cmd[0], self.cmd, {**os.environ, **self.environment_vars}) except FileNotFoundError: self.status = 'done' - self.log(f"{self.cmd[0]} does not exist.", level=LOG_LEVELS.Debug) + self.log(f"{self.cmd[0]} does not exist.", level=logging.DEBUG) self.exit_code = 1 return False @@ -214,8 +214,8 @@ class sys_command():#Thread): poller.register(child_fd, EPOLLIN | EPOLLHUP) if 'events' in self.kwargs and 'debug' in self.kwargs: - self.log(f'[D] Using triggers for command: {self.cmd}', level=LOG_LEVELS.Debug) - self.log(json.dumps(self.kwargs['events']), level=LOG_LEVELS.Debug) + self.log(f'[D] Using triggers for command: {self.cmd}', level=logging.DEBUG) + self.log(json.dumps(self.kwargs['events']), level=logging.DEBUG) alive = True last_trigger_pos = 0 @@ -230,7 +230,7 @@ class sys_command():#Thread): break if 'debug' in self.kwargs and self.kwargs['debug'] and len(output): - self.log(self.cmd, 'gave:', output.decode('UTF-8'), level=LOG_LEVELS.Debug) + self.log(self.cmd, 'gave:', output.decode('UTF-8'), level=logging.DEBUG) if 'on_output' in self.kwargs: self.kwargs['on_output'](self.kwargs['worker'], output) @@ -251,8 +251,8 @@ class sys_command():#Thread): trigger_pos = self.trace_log[last_trigger_pos:].lower().find(trigger.lower()) if 'debug' in self.kwargs and self.kwargs['debug']: - self.log(f"Writing to subprocess {self.cmd[0]}: {self.kwargs['events'][trigger].decode('UTF-8')}", level=LOG_LEVELS.Debug) - self.log(f"Writing to subprocess {self.cmd[0]}: {self.kwargs['events'][trigger].decode('UTF-8')}", level=LOG_LEVELS.Debug) + self.log(f"Writing to subprocess {self.cmd[0]}: {self.kwargs['events'][trigger].decode('UTF-8')}", level=logging.DEBUG) + self.log(f"Writing to subprocess {self.cmd[0]}: {self.kwargs['events'][trigger].decode('UTF-8')}", level=logging.DEBUG) last_trigger_pos = trigger_pos os.write(child_fd, self.kwargs['events'][trigger]) @@ -266,18 +266,18 @@ class sys_command():#Thread): ## Adding a exit trigger: if len(self.kwargs['events']) == 0: if 'debug' in self.kwargs and self.kwargs['debug']: - self.log(f"Waiting for last command {self.cmd[0]} to finish.", level=LOG_LEVELS.Debug) + self.log(f"Waiting for last command {self.cmd[0]} to finish.", level=logging.DEBUG) if bytes(f']$'.lower(), 'UTF-8') in self.trace_log[0-len(f']$')-5:].lower(): if 'debug' in self.kwargs and self.kwargs['debug']: - self.log(f"{self.cmd[0]} has finished.", level=LOG_LEVELS.Debug) + self.log(f"{self.cmd[0]} has finished.", level=logging.DEBUG) alive = False break self.status = 'done' if 'debug' in self.kwargs and self.kwargs['debug']: - self.log(f"{self.cmd[0]} waiting for exit code.", level=LOG_LEVELS.Debug) + self.log(f"{self.cmd[0]} waiting for exit code.", level=logging.DEBUG) if not self.kwargs['emulate']: try: @@ -291,14 +291,14 @@ class sys_command():#Thread): self.exit_code = 0 if 'debug' in self.kwargs and self.kwargs['debug']: - self.log(f"{self.cmd[0]} got exit code: {self.exit_code}", level=LOG_LEVELS.Debug) + self.log(f"{self.cmd[0]} got exit code: {self.exit_code}", level=logging.DEBUG) if 'ignore_errors' in self.kwargs: self.exit_code = 0 if self.exit_code != 0 and not self.kwargs['suppress_errors']: - #self.log(self.trace_log.decode('UTF-8'), level=LOG_LEVELS.Debug) - #self.log(f"'{self.raw_cmd}' did not exit gracefully, exit code {self.exit_code}.", level=LOG_LEVELS.Error) + #self.log(self.trace_log.decode('UTF-8'), level=logging.DEBUG) + #self.log(f"'{self.raw_cmd}' did not exit gracefully, exit code {self.exit_code}.", level=logging.ERROR) raise SysCallError(message=f"{self.trace_log.decode('UTF-8')}\n'{self.raw_cmd}' did not exit gracefully (trace log above), exit code: {self.exit_code}", exit_code=self.exit_code) self.ended = time.time() diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index e2762603..04fe44c8 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -1,4 +1,5 @@ -import os, stat, time, shutil, pathlib, subprocess +import os, stat, time, shutil, pathlib +import subprocess, logging from .exceptions import * from .disk import * @@ -7,7 +8,7 @@ from .user_interaction import * from .profiles import Profile from .mirrors import * from .systemd import Networkd -from .output import log, LOG_LEVELS +from .output import log from .storage import storage from .hardware import * @@ -60,7 +61,7 @@ class Installer(): storage['session'] = self self.partitions = get_partitions_in_use(self.target) - def log(self, *args, level=LOG_LEVELS.Debug, **kwargs): + def log(self, *args, level=logging.DEBUG, **kwargs): """ installer.log() wraps output.log() mainly to set a default log-level for this install session. Any manual override can be done per log() call. @@ -75,8 +76,8 @@ class Installer(): # TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager if len(args) >= 2 and args[1]: - #self.log(self.trace_log.decode('UTF-8'), level=LOG_LEVELS.Debug) - self.log(args[1], level=LOG_LEVELS.Error, fg='red') + #self.log(self.trace_log.decode('UTF-8'), level=logging.DEBUG) + self.log(args[1], level=logging.ERROR, fg='red') self.sync_log_to_install_medium() @@ -89,17 +90,17 @@ class Installer(): self.genfstab() if not (missing_steps := self.post_install_check()): - self.log('Installation completed without any errors. You may now reboot.', bg='black', fg='green', level=LOG_LEVELS.Info) + self.log('Installation completed without any errors. You may now reboot.', bg='black', fg='green', level=logging.INFO) self.sync_log_to_install_medium() return True else: - self.log('Some required steps were not successfully installed/configured before leaving the installer:', bg='black', fg='red', level=LOG_LEVELS.Warning) + self.log('Some required steps were not successfully installed/configured before leaving the installer:', bg='black', fg='red', level=logging.WARNING) for step in missing_steps: - self.log(f' - {step}', bg='black', fg='red', level=LOG_LEVELS.Warning) + self.log(f' - {step}', bg='black', fg='red', level=logging.WARNING) - self.log(f"Detailed error logs can be found at: {storage['LOG_PATH']}", level=LOG_LEVELS.Warning) - self.log(f"Submit this zip file as an issue to https://github.com/archlinux/archinstall/issues", level=LOG_LEVELS.Warning) + self.log(f"Detailed error logs can be found at: {storage['LOG_PATH']}", level=logging.WARNING) + self.log(f"Submit this zip file as an issue to https://github.com/archlinux/archinstall/issues", level=logging.WARNING) self.sync_log_to_install_medium() return False @@ -129,21 +130,21 @@ class Installer(): def pacstrap(self, *packages, **kwargs): if type(packages[0]) in (list, tuple): packages = packages[0] - self.log(f'Installing packages: {packages}', level=LOG_LEVELS.Info) + self.log(f'Installing packages: {packages}', level=logging.INFO) if (sync_mirrors := sys_command('/usr/bin/pacman -Syy')).exit_code == 0: if (pacstrap := sys_command(f'/usr/bin/pacstrap {self.target} {" ".join(packages)}', **kwargs)).exit_code == 0: return True else: - self.log(f'Could not strap in packages: {pacstrap.exit_code}', level=LOG_LEVELS.Info) + self.log(f'Could not strap in packages: {pacstrap.exit_code}', level=logging.INFO) else: - self.log(f'Could not sync mirrors: {sync_mirrors.exit_code}', level=LOG_LEVELS.Info) + self.log(f'Could not sync mirrors: {sync_mirrors.exit_code}', level=logging.INFO) def set_mirrors(self, mirrors): return use_mirrors(mirrors, destination=f'{self.target}/etc/pacman.d/mirrorlist') def genfstab(self, flags='-pU'): - self.log(f"Updating {self.target}/etc/fstab", level=LOG_LEVELS.Info) + self.log(f"Updating {self.target}/etc/fstab", level=logging.INFO) fstab = sys_command(f'/usr/bin/genfstab {flags} {self.target}').trace_log with open(f"{self.target}/etc/fstab", 'ab') as fstab_fh: @@ -179,19 +180,19 @@ class Installer(): else: self.log( f"Time zone {zone} does not exist, continuing with system default.", - level=LOG_LEVELS.Warning, + level=logging.WARNING, fg='red' ) def activate_ntp(self): - self.log(f'Installing and activating NTP.', level=LOG_LEVELS.Info) + self.log(f'Installing and activating NTP.', level=logging.INFO) if self.pacstrap('ntp'): if self.enable_service('ntpd'): return True def enable_service(self, *services): for service in services: - self.log(f'Enabling service {service}', level=LOG_LEVELS.Info) + self.log(f'Enabling service {service}', level=logging.INFO) if (output := self.arch_chroot(f'systemctl enable {service}')).exit_code != 0: raise ServiceException(f"Unable to start service {service}: {output}") @@ -349,7 +350,7 @@ class Installer(): # Run registered post-install hooks for function in self.post_base_install: - self.log(f"Running post-installation hook: {function}", level=LOG_LEVELS.Info) + self.log(f"Running post-installation hook: {function}", level=logging.INFO) function(self) return True @@ -363,7 +364,7 @@ class Installer(): elif partition.mountpoint == self.target: root_partition = partition - self.log(f'Adding bootloader {bootloader} to {boot_partition}', level=LOG_LEVELS.Info) + self.log(f'Adding bootloader {bootloader} to {boot_partition}', level=logging.INFO) if bootloader == 'systemd-bootctl': if not hasUEFI(): @@ -417,10 +418,10 @@ class Installer(): if (real_device := self.detect_encryption(root_partition)): # TODO: We need to detect if the encrypted device is a whole disk encryption, # or simply a partition encryption. Right now we assume it's a partition (and we always have) - log(f"Identifying root partition by PART-UUID on {real_device}: '{real_device.uuid}'.", level=LOG_LEVELS.Debug) + log(f"Identifying root partition by PART-UUID on {real_device}: '{real_device.uuid}'.", level=logging.DEBUG) entry.write(f'options cryptdevice=PARTUUID={real_device.uuid}:luksdev root=/dev/mapper/luksdev rw intel_pstate=no_hwp\n') else: - log(f"Identifying root partition by PART-UUID on {root_partition}, looking for '{root_partition.uuid}'.", level=LOG_LEVELS.Debug) + log(f"Identifying root partition by PART-UUID on {root_partition}, looking for '{root_partition.uuid}'.", level=logging.DEBUG) entry.write(f'options root=PARTUUID={root_partition.uuid} rw intel_pstate=no_hwp\n') self.helper_flags['bootloader'] = bootloader @@ -458,17 +459,17 @@ class Installer(): if type(profile) == str: profile = Profile(self, profile) - self.log(f'Installing network profile {profile}', level=LOG_LEVELS.Info) + self.log(f'Installing network profile {profile}', level=logging.INFO) return profile.install() def enable_sudo(self, entity :str, group=False): - self.log(f'Enabling sudo permissions for {entity}.', level=LOG_LEVELS.Info) + self.log(f'Enabling sudo permissions for {entity}.', level=logging.INFO) with open(f'{self.target}/etc/sudoers', 'a') as sudoers: sudoers.write(f'{"%" if group else ""}{entity} ALL=(ALL) ALL\n') return True def user_create(self, user :str, password=None, groups=[], sudo=False): - self.log(f'Creating user {user}', level=LOG_LEVELS.Info) + self.log(f'Creating user {user}', level=logging.INFO) o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.target} useradd -m -G wheel {user}')) if password: self.user_set_pw(user, password) @@ -481,7 +482,7 @@ class Installer(): self.helper_flags['user'] = True def user_set_pw(self, user, password): - self.log(f'Setting password for {user}', level=LOG_LEVELS.Info) + self.log(f'Setting password for {user}', level=logging.INFO) if user == 'root': # This means the root account isn't locked/disabled with * in /etc/passwd @@ -491,7 +492,7 @@ class Installer(): pass def user_set_shell(self, user, shell): - self.log(f'Setting shell for {user} to {shell}', level=LOG_LEVELS.Info) + self.log(f'Setting shell for {user} to {shell}', level=logging.INFO) o = b''.join(sys_command(f"/usr/bin/arch-chroot {self.target} sh -c \"chsh -s {shell} {user}\"")) pass @@ -502,5 +503,5 @@ class Installer(): vconsole.write(f'KEYMAP={language}\n') vconsole.write(f'FONT=lat9w-16\n') else: - self.log(f'Keyboard language was not changed from default (no language specified).', fg="yellow", level=LOG_LEVELS.Info) + self.log(f'Keyboard language was not changed from default (no language specified).', fg="yellow", level=logging.INFO) return True diff --git a/archinstall/lib/luks.py b/archinstall/lib/luks.py index 894be1c8..7f8485e6 100644 --- a/archinstall/lib/luks.py +++ b/archinstall/lib/luks.py @@ -2,10 +2,11 @@ import os import shlex import time import pathlib +import logging from .exceptions import * from .general import * from .disk import Partition -from .output import log, LOG_LEVELS +from .output import log from .storage import storage class luks2(): @@ -48,7 +49,7 @@ class luks2(): if not self.partition.allow_formatting: raise DiskError(f'Could not encrypt volume {self.partition} due to it having a formatting lock.') - log(f'Encrypting {partition} (This might take a while)', level=LOG_LEVELS.Info) + log(f'Encrypting {partition} (This might take a while)', level=logging.INFO) if not key_file: if self.key_file: @@ -84,7 +85,7 @@ class luks2(): cmd_handle = sys_command(cryptsetup_args) except SysCallError as err: if err.exit_code == 256: - log(f'{partition} is being used, trying to unmount and crypt-close the device and running one more attempt at encrypting the device.', level=LOG_LEVELS.Debug) + log(f'{partition} is being used, trying to unmount and crypt-close the device and running one more attempt at encrypting the device.', level=logging.DEBUG) # Partition was in use, unmount it and try again partition.unmount() @@ -97,11 +98,11 @@ class luks2(): for child in children: # Unmount the child location if child_mountpoint := child.get('mountpoint', None): - log(f'Unmounting {child_mountpoint}', level=LOG_LEVELS.Debug) + log(f'Unmounting {child_mountpoint}', level=logging.DEBUG) sys_command(f"umount -R {child_mountpoint}") # And close it if possible. - log(f"Closing crypt device {child['name']}", level=LOG_LEVELS.Debug) + log(f"Closing crypt device {child['name']}", level=logging.DEBUG) sys_command(f"cryptsetup close {child['name']}") # Then try again to set up the crypt-device diff --git a/archinstall/lib/mirrors.py b/archinstall/lib/mirrors.py index 04f47c0d..ae6c6422 100644 --- a/archinstall/lib/mirrors.py +++ b/archinstall/lib/mirrors.py @@ -1,4 +1,4 @@ -import urllib.request +import urllib.request, logging from .exceptions import * from .general import * @@ -59,7 +59,7 @@ def insert_mirrors(mirrors, *args, **kwargs): return True def use_mirrors(regions :dict, destination='/etc/pacman.d/mirrorlist'): - log(f'A new package mirror-list has been created: {destination}', level=LOG_LEVELS.Info) + log(f'A new package mirror-list has been created: {destination}', level=logging.INFO) for region, mirrors in regions.items(): with open(destination, 'w') as mirrorlist: for mirror in mirrors: @@ -79,7 +79,7 @@ def list_mirrors(): try: response = urllib.request.urlopen(url) except urllib.error.URLError as err: - log(f'Could not fetch an active mirror-list: {err}', level=LOG_LEVELS.Warning, fg="yellow") + log(f'Could not fetch an active mirror-list: {err}', level=logging.WARNING, fg="yellow") return regions diff --git a/archinstall/lib/output.py b/archinstall/lib/output.py index 6b184b4b..73819422 100644 --- a/archinstall/lib/output.py +++ b/archinstall/lib/output.py @@ -17,8 +17,32 @@ class LOG_LEVELS: class journald(dict): @abc.abstractmethod - def log(message, level=LOG_LEVELS.Debug): - import systemd.journal + def log(message, level=logging.DEBUG): + try: + import systemd.journal + except ModuleNotFoundError: + return False + + # For backwards compability, convert old style log-levels + # to logging levels (and warn about deprecated usage) + # There's some code re-usage here but that should be fine. + # TODO: Remove these in a few versions: + if level == LOG_LEVELS.Critical: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + level = logging.CRITICAL + elif level == LOG_LEVELS.Error: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + level = logging.ERROR + elif level == LOG_LEVELS.Warning: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + level = logging.WARNING + elif level == LOG_LEVELS.Info: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + level = logging.INFO + elif level == LOG_LEVELS.Debug: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + level = logging.DEBUG + log_adapter = logging.getLogger('archinstall') log_fmt = logging.Formatter("[%(levelname)s]: %(message)s") log_ch = systemd.journal.JournalHandler() @@ -26,19 +50,7 @@ class journald(dict): log_adapter.addHandler(log_ch) log_adapter.setLevel(logging.DEBUG) - if level == LOG_LEVELS.Critical: - log_adapter.critical(message) - elif level == LOG_LEVELS.Error: - log_adapter.error(message) - elif level == LOG_LEVELS.Warning: - log_adapter.warning(message) - elif level == LOG_LEVELS.Info: - log_adapter.info(message) - elif level == LOG_LEVELS.Debug: - log_adapter.debug(message) - else: - # Fallback logger - log_adapter.debug(message) + log_adapter.log(level, message) # TODO: Replace log() for session based logging. class SessionLogging(): @@ -112,17 +124,38 @@ def log(*args, **kwargs): with open(absolute_logfile, 'a') as log_file: log_file.write(f"{orig_string}\n") + # If we assigned a level, try to log it to systemd's journald. # Unless the level is higher than we've decided to output interactively. # (Remember, log files still get *ALL* the output despite level restrictions) if 'level' in kwargs: - if kwargs['level'] > storage.get('LOG_LEVEL', LOG_LEVELS.Info): + # For backwards compability, convert old style log-levels + # to logging levels (and warn about deprecated usage) + # There's some code re-usage here but that should be fine. + # TODO: Remove these in a few versions: + if kwargs['level'] == LOG_LEVELS.Critical: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + kwargs['level'] = logging.CRITICAL + elif kwargs['level'] == LOG_LEVELS.Error: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + kwargs['level'] = logging.ERROR + elif kwargs['level'] == LOG_LEVELS.Warning: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + kwargs['level'] = logging.WARNING + elif kwargs['level'] == LOG_LEVELS.Info: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + kwargs['level'] = logging.INFO + elif kwargs['level'] == LOG_LEVELS.Debug: + log("Deprecated level detected in log message, please use new logging. instead for the following log message:", fg="red", level=logging.ERROR, force=True) + kwargs['level'] = logging.DEBUG + + if kwargs['level'] > storage.get('LOG_LEVEL', logging.INFO) and not 'force' in kwargs: # Level on log message was Debug, but output level is set to Info. # In that case, we'll drop it. return None try: - journald.log(string, level=kwargs.get('level', LOG_LEVELS.Info)) + journald.log(string, level=kwargs.get('level', logging.INFO)) except ModuleNotFoundError: pass # Ignore writing to journald diff --git a/archinstall/lib/profiles.py b/archinstall/lib/profiles.py index 265ca26a..4988e7ab 100644 --- a/archinstall/lib/profiles.py +++ b/archinstall/lib/profiles.py @@ -1,10 +1,10 @@ import os, urllib.request, urllib.parse, ssl, json, re -import importlib.util, sys, glob, hashlib +import importlib.util, sys, glob, hashlib, logging from collections import OrderedDict from .general import multisplit, sys_command from .exceptions import * from .networking import * -from .output import log, LOG_LEVELS +from .output import log from .storage import storage def grab_url_data(path): @@ -82,7 +82,7 @@ class Script(): self.examples = None self.namespace = os.path.splitext(os.path.basename(self.path))[0] self.original_namespace = self.namespace - log(f"Script {self} has been loaded with namespace '{self.namespace}'", level=LOG_LEVELS.Debug) + log(f"Script {self} has been loaded with namespace '{self.namespace}'", level=logging.DEBUG) def __enter__(self, *args, **kwargs): self.execute() diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index d8640a81..79b0e0b9 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -1,9 +1,9 @@ import getpass, pathlib, os, shutil, re -import sys, time, signal, ipaddress +import sys, time, signal, ipaddress, logging from .exceptions import * from .profiles import Profile from .locale_helpers import list_keyboard_languages, verify_keyboard_layout, search_keyboard_layout -from .output import log, LOG_LEVELS +from .output import log from .storage import storage from .networking import list_interfaces from .general import sys_command @@ -26,7 +26,7 @@ def check_for_correct_username(username): return True log( "The username you entered is invalid. Try again", - level=LOG_LEVELS.Warning, + level=logging.WARNING, fg='red' ) return False @@ -141,7 +141,7 @@ def ask_for_a_timezone(): else: log( f"Specified timezone {timezone} does not exist.", - level=LOG_LEVELS.Warning, + level=logging.WARNING, fg='red' ) @@ -198,7 +198,7 @@ def ask_to_configure_network(): except ValueError: log( "You need to enter a valid IP in IP-config mode.", - level=LOG_LEVELS.Warning, + level=logging.WARNING, fg='red' ) @@ -214,7 +214,7 @@ def ask_to_configure_network(): except ValueError: log( "You need to enter a valid gateway (router) IP address.", - level=LOG_LEVELS.Warning, + level=logging.WARNING, fg='red' ) diff --git a/examples/guided.py b/examples/guided.py index 43aaa788..0e6f2904 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -1,4 +1,4 @@ -import getpass, time, json, os +import getpass, time, json, os, logging import archinstall from archinstall.lib.hardware import hasUEFI from archinstall.lib.profiles import Profile @@ -237,8 +237,8 @@ def ask_user_questions(): def perform_installation_steps(): print() print('This is your chosen configuration:') - archinstall.log("-- Guided template chosen (with below config) --", level=archinstall.LOG_LEVELS.Debug) - archinstall.log(json.dumps(archinstall.arguments, indent=4, sort_keys=True, cls=archinstall.JSON), level=archinstall.LOG_LEVELS.Info) + archinstall.log("-- Guided template chosen (with below config) --", level=logging.DEBUG) + archinstall.log(json.dumps(archinstall.arguments, indent=4, sort_keys=True, cls=archinstall.JSON), level=logging.INFO) print() input('Press Enter to continue.') @@ -282,7 +282,7 @@ def perform_installation_steps(): else: partition.format() else: - archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=archinstall.LOG_LEVELS.Debug) + archinstall.log(f"Did not format {partition} because .safe_to_format() returned False or .allow_formatting was False.", level=logging.DEBUG) if hasUEFI(): fs.find_partition('/boot').format('vfat')# we don't have a boot partition in bios mode @@ -313,7 +313,7 @@ def perform_installation(mountpoint): # Certain services might be running that affects the system during installation. # Currently, only one such service is "reflector.service" which updates /etc/pacman.d/mirrorlist # We need to wait for it before we continue since we opted in to use a custom mirror/region. - installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=archinstall.LOG_LEVELS.Info) + installation.log(f'Waiting for automatic mirror selection (reflector) to complete.', level=logging.INFO) while archinstall.service_state('reflector') not in ('dead', 'failed'): time.sleep(1) # Set mirrors used by pacstrap (outside of installation) @@ -342,7 +342,7 @@ def perform_installation(mountpoint): installation.enable_service('systemd-resolved') if archinstall.arguments.get('audio', None) != None: - installation.log(f"This audio server will be used: {archinstall.arguments.get('audio', None)}", level=archinstall.LOG_LEVELS.Info) + installation.log(f"This audio server will be used: {archinstall.arguments.get('audio', None)}", level=logging.INFO) if archinstall.arguments.get('audio', None) == 'pipewire': print('Installing pipewire ...') @@ -351,7 +351,7 @@ def perform_installation(mountpoint): print('Installing pulseaudio ...') installation.add_additional_packages("pulseaudio") else: - installation.log("No audio server will be installed.", level=archinstall.LOG_LEVELS.Info) + installation.log("No audio server will be installed.", level=logging.INFO) if archinstall.arguments.get('packages', None) and archinstall.arguments.get('packages', None)[0] != '': installation.add_additional_packages(archinstall.arguments.get('packages', None)) -- cgit v1.2.3-54-g00ecf From 6cfaf30718c3c0281553a7afd890fcfca342f2bc Mon Sep 17 00:00:00 2001 From: SecondThundeR Date: Wed, 28 Apr 2021 09:41:47 +0300 Subject: Update kernel select Move select to separate function Remove 'continue' option Add hardened kernel as option --- archinstall/lib/user_interaction.py | 23 +++++++++++++++++++++++ examples/guided.py | 11 +++-------- 2 files changed, 26 insertions(+), 8 deletions(-) (limited to 'examples') diff --git a/archinstall/lib/user_interaction.py b/archinstall/lib/user_interaction.py index cd848136..8d5c9994 100644 --- a/archinstall/lib/user_interaction.py +++ b/archinstall/lib/user_interaction.py @@ -506,3 +506,26 @@ def select_driver(options=AVAILABLE_GFX_DRIVERS): return selected_driver raise RequirementError("Selecting drivers require a least one profile to be given as an option.") + +def select_kernel(options): + """ + Asks the user to select a kernel for system. + + :param options: A `list` with kernel options + :type options: list + + :return: The string as a selected kernel + :rtype: string + """ + + DEFAULT_KERNEL = "linux" + + kernels = sorted(list(options)) + + if kernels: + selected_kernels = generic_select(kernels, "Choose a kernel: ") + if not selected_kernels: + return DEFAULT_KERNEL + return selected_kernels + + raise RequirementError("Selecting kernels require a least one kernel to be given as an option.") diff --git a/examples/guided.py b/examples/guided.py index 1ff84907..2b8a06f5 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -2,7 +2,6 @@ import getpass, time, json, os, logging import archinstall from archinstall.lib.hardware import hasUEFI from archinstall.lib.profiles import Profile -from archinstall.lib.user_interaction import generic_select if archinstall.arguments.get('help'): print("See `man archinstall` for help.") @@ -195,14 +194,10 @@ def ask_user_questions(): # we will not try to remove packages post-installation to not have audio, as that may cause multiple issues archinstall.arguments['audio'] = None - # Ask what kernel user wants: + # Ask for preferred kernel: if not archinstall.arguments.get("kernels", None): - archinstall.log(f"Here you can choose which kernel to use, leave blank for default which is 'linux'.") - - if (kernel := generic_select(["linux", "linux-lts", "linux-zen", "continue"], "choose a kernel:")): - archinstall.arguments['kernels'] = kernel - else: - archinstall.arguments['kernels'] = 'linux' + kernels = ["linux", "linux-lts", "linux-zen", "linux-hardened"] + archinstall.arguments['kernels'] = archinstall.select_kernel(kernels) # Additional packages (with some light weight error handling for invalid package names) print("Only packages such as base, base-devel, linux, linux-firmware, efibootmgr and optional profile packages are installed.") -- cgit v1.2.3-54-g00ecf From 0ebc6be7ae3b153f2baad722a08a2019bb04c905 Mon Sep 17 00:00:00 2001 From: Anton Hvornum Date: Thu, 29 Apr 2021 11:32:21 +0000 Subject: Added a postgresql application profile. (#383) * Added a postgres application profile. Also introducing runas to the arch_chroot of the installation, to run commands as emulated users. This is highly WIP at the moment. * Fixing top-level-listing of profiles. As well as testing some postgres installation steps. * Removed dupe functions. * Added safety check in case a comment mentions the top level profile thing. * Patching namespace corruption. * Avoiding runtime collision due to installation not being initiated yet. * Allow for parameterization of filesystem in guided. Co-authored-by: Anton Hvornum --- archinstall/lib/disk.py | 1 - archinstall/lib/installer.py | 3 +++ archinstall/lib/profiles.py | 53 +++++++------------------------------ examples/guided.py | 6 +++-- profiles/52-54-00-12-34-56.py | 8 +++++- profiles/applications/postgresql.py | 11 ++++++++ 6 files changed, 34 insertions(+), 48 deletions(-) create mode 100644 profiles/applications/postgresql.py (limited to 'examples') diff --git a/archinstall/lib/disk.py b/archinstall/lib/disk.py index ff924f62..49bef1be 100644 --- a/archinstall/lib/disk.py +++ b/archinstall/lib/disk.py @@ -471,7 +471,6 @@ class Filesystem(): def raw_parted(self, string:str): x = sys_command(f'/usr/bin/parted -s {string}') - log(f"'parted -s {string}' returned: {b''.join(x)}", level=logging.DEBUG) return x def parted(self, string:str): diff --git a/archinstall/lib/installer.py b/archinstall/lib/installer.py index dbc6d1b4..a7b36481 100644 --- a/archinstall/lib/installer.py +++ b/archinstall/lib/installer.py @@ -196,6 +196,9 @@ class Installer(): return sys_command(f'/usr/bin/arch-chroot {self.target} {cmd}') def arch_chroot(self, cmd, *args, **kwargs): + if 'runas' in kwargs: + cmd = f"su - {kwargs['runas']} -c \"{cmd}\"" + return self.run_command(cmd) def drop_to_shell(self): diff --git a/archinstall/lib/profiles.py b/archinstall/lib/profiles.py index ad5d3bac..06237c1c 100644 --- a/archinstall/lib/profiles.py +++ b/archinstall/lib/profiles.py @@ -92,6 +92,9 @@ class Script(): if len(args) >= 2 and args[1]: raise args[1] + if self.original_namespace: + self.namespace = self.original_namespace + def localize_path(self, profile_path): if (url := urllib.parse.urlparse(profile_path)).scheme and url.scheme in ('https', 'http'): if not self.converted_path: @@ -202,51 +205,14 @@ class Profile(Script): with open(self.path, 'r') as source: source_data = source.read() - # TODO: I imagine that there is probably a better way to write this. - return 'top_level_profile = True' in source_data - - @property - def packages(self) -> list: - """ - Returns a list of packages baked into the profile definition. - If no package definition has been done, .packages() will return None. - """ - with open(self.path, 'r') as source: - source_data = source.read() - - # Some crude safety checks, make sure the imported profile has - # a __name__ check before importing. - # - # If the requirements are met, import with .py in the namespace to not - # trigger a traditional: - # if __name__ == 'moduleName' - if '__name__' in source_data and '__packages__' in source_data: - with self.load_instructions(namespace=f"{self.namespace}.py") as imported: - if hasattr(imported, '__packages__'): - return imported.__packages__ - return None - - - def has_post_install(self): - with open(self.path, 'r') as source: - source_data = source.read() - - # Some crude safety checks, make sure the imported profile has - # a __name__ check and if so, check if it's got a _prep_function() - # we can call to ask for more user input. - # - # If the requirements are met, import with .py in the namespace to not - # trigger a traditional: - # if __name__ == 'moduleName' - if '__name__' in source_data and '_post_install' in source_data: + if '__name__' in source_data and 'is_top_level_profile' in source_data: with self.load_instructions(namespace=f"{self.namespace}.py") as imported: - if hasattr(imported, '_post_install'): - return True + if hasattr(imported, 'is_top_level_profile'): + return imported.is_top_level_profile - def is_top_level_profile(self): - with open(self.path, 'r') as source: - source_data = source.read() - return 'top_level_profile = True' in source_data + # Default to True if nothing is specified, + # since developers like less code - omitting it should assume they want to present it. + return True @property def packages(self) -> list: @@ -268,7 +234,6 @@ class Profile(Script): if hasattr(imported, '__packages__'): return imported.__packages__ return None - class Application(Profile): def __repr__(self, *args, **kwargs): diff --git a/examples/guided.py b/examples/guided.py index 2b8a06f5..c281d033 100644 --- a/examples/guided.py +++ b/examples/guided.py @@ -136,12 +136,14 @@ def ask_user_questions(): archinstall.log('Using existing partition table reported above.') elif option == 'format-all': - archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() + if not archinstall.arguments.get('filesystem', None): + archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() archinstall.arguments['harddrive'].keep_partitions = False elif archinstall.arguments['harddrive']: # If the drive doesn't have any partitions, safely mark the disk with keep_partitions = False # and ask the user for a root filesystem. - archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() + if not archinstall.arguments.get('filesystem', None): + archinstall.arguments['filesystem'] = archinstall.ask_for_main_filesystem_format() archinstall.arguments['harddrive'].keep_partitions = False # Get disk encryption password (or skip if blank) diff --git a/profiles/52-54-00-12-34-56.py b/profiles/52-54-00-12-34-56.py index 442e053c..a3347760 100644 --- a/profiles/52-54-00-12-34-56.py +++ b/profiles/52-54-00-12-34-56.py @@ -4,6 +4,11 @@ import urllib.request __packages__ = ['nano', 'wget', 'git'] +if __name__ == '52-54-00-12-34-56': + awesome = archinstall.Application(installation, 'postgresql') + awesome.install() + +""" # Unmount and close previous runs (Mainly only used for re-runs, but won't hurt.) archinstall.sys_command(f'umount -R /mnt', suppress_errors=True) archinstall.sys_command(f'cryptsetup close /dev/mapper/luksloop', suppress_errors=True) @@ -51,4 +56,5 @@ with archinstall.Filesystem(harddrive) as fs: try: urllib.request.urlopen(req, timeout=5) except: - pass \ No newline at end of file + pass +""" \ No newline at end of file diff --git a/profiles/applications/postgresql.py b/profiles/applications/postgresql.py new file mode 100644 index 00000000..fcdce824 --- /dev/null +++ b/profiles/applications/postgresql.py @@ -0,0 +1,11 @@ +import archinstall + +# Define the package list in order for lib to source +# which packages will be installed by this profile +__packages__ = ["postgresql"] + +installation.add_additional_packages(__packages__) + +installation.arch_chroot("initdb -D /var/lib/postgres/data", runas='postgres') + +installation.enable_service('postgresql') \ No newline at end of file -- cgit v1.2.3-54-g00ecf