Perform refactoring to PEP 8 naming conventions

This commit is contained in:
Dylan Taylor 2021-05-15 17:50:28 -04:00
parent 0ac13c0958
commit 1796bbb918
13 changed files with 114 additions and 114 deletions

View File

@ -5,7 +5,7 @@ from collections import OrderedDict
from typing import Optional
from .general import *
from .hardware import hasUEFI
from .hardware import has_uefi
from .output import log
ROOT_DIR_PATTERN = re.compile('^.*?/devices')
@ -77,7 +77,7 @@ class BlockDevice:
raise DiskError(f'Could not locate backplane info for "{self.path}"')
if self.info['type'] == 'loop':
for drive in json.loads(b''.join(sys_command(['losetup', '--json'], hide_from_log=True)).decode('UTF_8'))['loopdevices']:
for drive in json.loads(b''.join(SysCommand(['losetup', '--json'], hide_from_log=True)).decode('UTF_8'))['loopdevices']:
if not drive['name'] == self.path:
continue
@ -99,10 +99,10 @@ class BlockDevice:
@property
def partitions(self):
o = b''.join(sys_command(['partprobe', self.path]))
o = b''.join(SysCommand(['partprobe', self.path]))
# o = b''.join(sys_command('/usr/bin/lsblk -o name -J -b {dev}'.format(dev=dev)))
o = b''.join(sys_command(['/usr/bin/lsblk', '-J', self.path]))
o = b''.join(SysCommand(['/usr/bin/lsblk', '-J', self.path]))
if b'not a block device' in o:
raise DiskError(f'Can not read partitions off something that isn\'t a block device: {self.path}')
@ -116,7 +116,7 @@ class BlockDevice:
for part in r['blockdevices'][0]['children']:
part_id = part['name'][len(os.path.basename(self.path)):]
if part_id not in self.part_cache:
## TODO: Force over-write even if in cache?
# TODO: Force over-write even if in cache?
if part_id not in self.part_cache or self.part_cache[part_id].size != part['size']:
self.part_cache[part_id] = Partition(root_path + part_id, self, part_id=part_id, size=part['size'])
@ -139,7 +139,7 @@ class BlockDevice:
This is more reliable than relying on /dev/disk/by-partuuid as
it doesn't seam to be able to detect md raid partitions.
"""
lsblk = b''.join(sys_command(f'lsblk -J -o+UUID {self.path}'))
lsblk = b''.join(SysCommand(f'lsblk -J -o+UUID {self.path}'))
for partition in json.loads(lsblk.decode('UTF-8'))['blockdevices']:
return partition.get('uuid', None)
@ -216,7 +216,7 @@ class Partition:
This is more reliable than relying on /dev/disk/by-partuuid as
it doesn't seam to be able to detect md raid partitions.
"""
lsblk = b''.join(sys_command(f'lsblk -J -o+PARTUUID {self.path}'))
lsblk = b''.join(SysCommand(f'lsblk -J -o+PARTUUID {self.path}'))
for partition in json.loads(lsblk.decode('UTF-8'))['blockdevices']:
return partition.get('partuuid', None)
return None
@ -236,7 +236,7 @@ class Partition:
@property
def real_device(self):
for blockdevice in json.loads(b''.join(sys_command('lsblk -J')).decode('UTF-8'))['blockdevices']:
for blockdevice in json.loads(b''.join(SysCommand('lsblk -J')).decode('UTF-8'))['blockdevices']:
if parent := self.find_parent_of(blockdevice, os.path.basename(self.path)):
return f"/dev/{parent}"
# raise DiskError(f'Could not find appropriate parent for encrypted partition {self}')
@ -260,11 +260,11 @@ class Partition:
temporary_path = pathlib.Path(temporary_mountpoint)
temporary_path.mkdir(parents=True, exist_ok=True)
if (handle := sys_command(f'/usr/bin/mount {self.path} {temporary_mountpoint}')).exit_code != 0:
if (handle := SysCommand(f'/usr/bin/mount {self.path} {temporary_mountpoint}')).exit_code != 0:
raise DiskError(f'Could not mount and check for content on {self.path} because: {b"".join(handle)}')
files = len(glob.glob(f"{temporary_mountpoint}/*"))
sys_command(f'/usr/bin/umount {temporary_mountpoint}')
SysCommand(f'/usr/bin/umount {temporary_mountpoint}')
temporary_path.rmdir()
@ -327,29 +327,29 @@ class Partition:
log(f'Formatting {path} -> {filesystem}', level=logging.INFO)
if filesystem == 'btrfs':
o = b''.join(sys_command(f'/usr/bin/mkfs.btrfs -f {path}'))
o = b''.join(SysCommand(f'/usr/bin/mkfs.btrfs -f {path}'))
if b'UUID' not in o:
raise DiskError(f'Could not format {path} with {filesystem} because: {o}')
self.filesystem = 'btrfs'
elif filesystem == 'vfat':
o = b''.join(sys_command(f'/usr/bin/mkfs.vfat -F32 {path}'))
o = b''.join(SysCommand(f'/usr/bin/mkfs.vfat -F32 {path}'))
if (b'mkfs.fat' not in o and b'mkfs.vfat' not in o) or b'command not found' in o:
raise DiskError(f'Could not format {path} with {filesystem} because: {o}')
self.filesystem = 'vfat'
elif filesystem == 'ext4':
if (handle := sys_command(f'/usr/bin/mkfs.ext4 -F {path}')).exit_code != 0:
if (handle := SysCommand(f'/usr/bin/mkfs.ext4 -F {path}')).exit_code != 0:
raise DiskError(f'Could not format {path} with {filesystem} because: {b"".join(handle)}')
self.filesystem = 'ext4'
elif filesystem == 'xfs':
if (handle := sys_command(f'/usr/bin/mkfs.xfs -f {path}')).exit_code != 0:
if (handle := SysCommand(f'/usr/bin/mkfs.xfs -f {path}')).exit_code != 0:
raise DiskError(f'Could not format {path} with {filesystem} because: {b"".join(handle)}')
self.filesystem = 'xfs'
elif filesystem == 'f2fs':
if (handle := sys_command(f'/usr/bin/mkfs.f2fs -f {path}')).exit_code != 0:
if (handle := SysCommand(f'/usr/bin/mkfs.f2fs -f {path}')).exit_code != 0:
raise DiskError(f'Could not format {path} with {filesystem} because: {b"".join(handle)}')
self.filesystem = 'f2fs'
@ -389,9 +389,9 @@ class Partition:
try:
if options:
sys_command(f'/usr/bin/mount -o {options} {self.path} {target}')
SysCommand(f'/usr/bin/mount -o {options} {self.path} {target}')
else:
sys_command(f'/usr/bin/mount {self.path} {target}')
SysCommand(f'/usr/bin/mount {self.path} {target}')
except SysCallError as err:
raise err
@ -400,7 +400,7 @@ class Partition:
def unmount(self):
try:
exit_code = sys_command(f'/usr/bin/umount {self.path}').exit_code
exit_code = SysCommand(f'/usr/bin/umount {self.path}').exit_code
except SysCallError as err:
exit_code = err.exit_code
@ -450,7 +450,7 @@ class Filesystem:
else:
raise DiskError('Problem setting the partition format to GPT:', f'/usr/bin/parted -s {self.blockdevice.device} mklabel gpt')
elif self.mode == MBR:
if sys_command(f'/usr/bin/parted -s {self.blockdevice.device} mklabel msdos').exit_code == 0:
if SysCommand(f'/usr/bin/parted -s {self.blockdevice.device} mklabel msdos').exit_code == 0:
return self
else:
raise DiskError('Problem setting the partition format to GPT:', f'/usr/bin/parted -s {self.blockdevice.device} mklabel msdos')
@ -472,7 +472,7 @@ class Filesystem:
# TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager
if len(args) >= 2 and args[1]:
raise args[1]
b''.join(sys_command('sync'))
b''.join(SysCommand('sync'))
return True
def find_partition(self, mountpoint):
@ -481,7 +481,7 @@ class Filesystem:
return partition
def raw_parted(self, string: str):
x = sys_command(f'/usr/bin/parted -s {string}')
x = SysCommand(f'/usr/bin/parted -s {string}')
return x
def parted(self, string: str):
@ -495,7 +495,7 @@ class Filesystem:
def use_entire_disk(self, root_filesystem_type='ext4'):
log(f"Using and formatting the entire {self.blockdevice}.", level=logging.DEBUG)
if hasUEFI():
if has_uefi():
self.add_partition('primary', start='1MiB', end='513MiB', format='fat32')
self.set_name(0, 'EFI')
self.set(0, 'boot on')
@ -572,7 +572,7 @@ def all_disks(*args, **kwargs):
kwargs.setdefault("partitions", False)
drives = OrderedDict()
# for drive in json.loads(sys_command(f'losetup --json', *args, **lkwargs, hide_from_log=True)).decode('UTF_8')['loopdevices']:
for drive in json.loads(b''.join(sys_command('lsblk --json -l -n -o path,size,type,mountpoint,label,pkname,model', *args, **kwargs, hide_from_log=True)).decode('UTF_8'))['blockdevices']:
for drive in json.loads(b''.join(SysCommand('lsblk --json -l -n -o path,size,type,mountpoint,label,pkname,model', *args, **kwargs, hide_from_log=True)).decode('UTF_8'))['blockdevices']:
if not kwargs['partitions'] and drive['type'] == 'part':
continue
@ -605,7 +605,7 @@ def harddrive(size=None, model=None, fuzzy=False):
def get_mount_info(path):
try:
output = b''.join(sys_command(f'/usr/bin/findmnt --json {path}'))
output = b''.join(SysCommand(f'/usr/bin/findmnt --json {path}'))
except SysCallError:
return {}
@ -620,7 +620,7 @@ def get_mount_info(path):
def get_partitions_in_use(mountpoint):
try:
output = b''.join(sys_command(f'/usr/bin/findmnt --json -R {mountpoint}'))
output = b''.join(SysCommand(f'/usr/bin/findmnt --json -R {mountpoint}'))
except SysCallError:
return {}
@ -639,7 +639,7 @@ def get_partitions_in_use(mountpoint):
def get_filesystem_type(path):
try:
handle = sys_command(f"blkid -o value -s TYPE {path}")
handle = SysCommand(f"blkid -o value -s TYPE {path}")
return b''.join(handle).strip().decode('UTF-8')
except SysCallError:
return None
@ -647,7 +647,7 @@ def get_filesystem_type(path):
def disk_layouts():
try:
handle = sys_command("lsblk -f -o+TYPE,SIZE -J")
handle = SysCommand("lsblk -f -o+TYPE,SIZE -J")
return json.loads(b''.join(handle).decode('UTF-8'))
except SysCallError as err:
log(f"Could not return disk layouts: {err}")

View File

@ -42,7 +42,7 @@ def locate_binary(name):
break # Don't recurse
class JSON_Encoder:
class JsonEncoder:
def _encode(obj):
if isinstance(obj, dict):
# We'll need to iterate not just the value that default() usually gets passed
@ -54,12 +54,12 @@ class JSON_Encoder:
# This, is a EXTREMELY ugly hack.. but it's the only quick way I can think of to trigger a encoding of sub-dictionaries.
val = json.loads(json.dumps(val, cls=JSON))
else:
val = JSON_Encoder._encode(val)
val = JsonEncoder._encode(val)
if type(key) == str and key[0] == '!':
copy[JSON_Encoder._encode(key)] = '******'
copy[JsonEncoder._encode(key)] = '******'
else:
copy[JSON_Encoder._encode(key)] = val
copy[JsonEncoder._encode(key)] = val
return copy
elif hasattr(obj, 'json'):
return obj.json()
@ -78,13 +78,13 @@ class JSON_Encoder:
class JSON(json.JSONEncoder, json.JSONDecoder):
def _encode(self, obj):
return JSON_Encoder._encode(obj)
return JsonEncoder._encode(obj)
def encode(self, obj):
return super(JSON, self).encode(self._encode(obj))
class sys_command:
class SysCommand:
"""
Stolen from archinstall_gui
"""
@ -336,4 +336,4 @@ def prerequisite_check():
def reboot():
o = b''.join(sys_command("/usr/bin/reboot"))
o = b''.join(SysCommand("/usr/bin/reboot"))

View File

@ -3,7 +3,7 @@ import os
import subprocess
from typing import Optional
from .general import sys_command
from .general import SysCommand
from .networking import list_interfaces, enrich_iface_types
__packages__ = [
@ -56,48 +56,48 @@ AVAILABLE_GFX_DRIVERS = {
}
def hasWifi() -> bool:
def has_wifi() -> bool:
return 'WIRELESS' in enrich_iface_types(list_interfaces().values()).values()
def hasAMDCPU() -> bool:
def has_amd_cpu() -> bool:
if subprocess.check_output("lscpu | grep AMD", shell=True).strip().decode():
return True
return False
def hasIntelCPU() -> bool:
def has_intel_cpu() -> bool:
if subprocess.check_output("lscpu | grep Intel", shell=True).strip().decode():
return True
return False
def hasUEFI() -> bool:
def has_uefi() -> bool:
return os.path.isdir('/sys/firmware/efi')
def graphicsDevices() -> dict:
def graphics_devices() -> dict:
cards = {}
for line in sys_command("lspci"):
for line in SysCommand("lspci"):
if b' VGA ' in line:
_, identifier = line.split(b': ', 1)
cards[identifier.strip().lower().decode('UTF-8')] = line
return cards
def hasNvidiaGraphics() -> bool:
return any('nvidia' in x for x in graphicsDevices())
def has_nvidia_graphics() -> bool:
return any('nvidia' in x for x in graphics_devices())
def hasAmdGraphics() -> bool:
return any('amd' in x for x in graphicsDevices())
def has_amd_graphics() -> bool:
return any('amd' in x for x in graphics_devices())
def hasIntelGraphics() -> bool:
return any('intel' in x for x in graphicsDevices())
def has_intel_graphics() -> bool:
return any('intel' in x for x in graphics_devices())
def cpuVendor() -> Optional[str]:
def cpu_vendor() -> Optional[str]:
cpu_info = json.loads(subprocess.check_output("lscpu -J", shell=True).decode('utf-8'))['lscpu']
for info in cpu_info:
if info.get('field', None):
@ -106,7 +106,7 @@ def cpuVendor() -> Optional[str]:
return None
def isVM() -> bool:
def is_vm() -> bool:
try:
subprocess.check_call(["systemd-detect-virt"]) # systemd-detect-virt issues a non-zero exit code if it is not on a virtual machine
return True

View File

@ -135,8 +135,8 @@ class Installer:
packages = packages[0]
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:
if (sync_mirrors := SysCommand('/usr/bin/pacman -Syy')).exit_code == 0:
if (pacstrap := SysCommand(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=logging.INFO)
@ -149,7 +149,7 @@ class Installer:
def genfstab(self, flags='-pU'):
self.log(f"Updating {self.target}/etc/fstab", level=logging.INFO)
fstab = sys_command(f'/usr/bin/genfstab {flags} {self.target}').trace_log
fstab = SysCommand(f'/usr/bin/genfstab {flags} {self.target}').trace_log
with open(f"{self.target}/etc/fstab", 'ab') as fstab_fh:
fstab_fh.write(fstab)
@ -171,7 +171,7 @@ class Installer:
with open(f'{self.target}/etc/locale.conf', 'w') as fh:
fh.write(f'LANG={locale}.{encoding}\n')
return True if sys_command(f'/usr/bin/arch-chroot {self.target} locale-gen').exit_code == 0 else False
return True if SysCommand(f'/usr/bin/arch-chroot {self.target} locale-gen').exit_code == 0 else False
def set_timezone(self, zone, *args, **kwargs):
if not zone:
@ -181,7 +181,7 @@ class Installer:
if (pathlib.Path("/usr") / "share" / "zoneinfo" / zone).exists():
(pathlib.Path(self.target) / "etc" / "localtime").unlink(missing_ok=True)
sys_command(f'/usr/bin/arch-chroot {self.target} ln -s /usr/share/zoneinfo/{zone} /etc/localtime')
SysCommand(f'/usr/bin/arch-chroot {self.target} ln -s /usr/share/zoneinfo/{zone} /etc/localtime')
return True
else:
self.log(
@ -203,7 +203,7 @@ class Installer:
raise ServiceException(f"Unable to start service {service}: {output}")
def run_command(self, cmd, *args, **kwargs):
return sys_command(f'/usr/bin/arch-chroot {self.target} {cmd}')
return SysCommand(f'/usr/bin/arch-chroot {self.target} {cmd}')
def arch_chroot(self, cmd, *args, **kwargs):
if 'runas' in kwargs:
@ -232,7 +232,7 @@ class Installer:
with open(f"{self.target}/etc/systemd/network/10-{nic}.network", "a") as netconf:
netconf.write(str(conf))
def copy_ISO_network_config(self, enable_services=False):
def copy_iso_network_config(self, enable_services=False):
# Copy (if any) iwd password and config files
if os.path.isdir('/var/lib/iwd/'):
if psk_files := glob.glob('/var/lib/iwd/*.psk'):
@ -297,13 +297,13 @@ class Installer:
mkinit.write(f"BINARIES=({' '.join(self.BINARIES)})\n")
mkinit.write(f"FILES=({' '.join(self.FILES)})\n")
mkinit.write(f"HOOKS=({' '.join(self.HOOKS)})\n")
sys_command(f'/usr/bin/arch-chroot {self.target} mkinitcpio {" ".join(flags)}')
SysCommand(f'/usr/bin/arch-chroot {self.target} mkinitcpio {" ".join(flags)}')
def minimal_installation(self):
## Add necessary packages if encrypting the drive
## (encrypted partitions default to btrfs for now, so we need btrfs-progs)
## TODO: Perhaps this should be living in the function which dictates
## the partitioning. Leaving here for now.
# Add necessary packages if encrypting the drive
# (encrypted partitions default to btrfs for now, so we need btrfs-progs)
# TODO: Perhaps this should be living in the function which dictates
# the partitioning. Leaving here for now.
for partition in self.partitions:
if partition.filesystem == 'btrfs':
@ -325,11 +325,11 @@ class Installer:
if 'encrypt' not in self.HOOKS:
self.HOOKS.insert(self.HOOKS.index('filesystems'), 'encrypt')
if not hasUEFI():
if not has_uefi():
self.base_packages.append('grub')
if not isVM():
vendor = cpuVendor()
if not is_vm():
vendor = cpu_vendor()
if vendor == "AuthenticAMD":
self.base_packages.append("amd-ucode")
elif vendor == "GenuineIntel":
@ -343,7 +343,7 @@ class Installer:
with open(f"{self.target}/etc/fstab", "a") as fstab:
fstab.write("\ntmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0\n") # Redundant \n at the start? who knows?
## TODO: Support locale and timezone
# TODO: Support locale and timezone
# os.remove(f'{self.target}/etc/localtime')
# sys_command(f'/usr/bin/arch-chroot {self.target} ln -s /usr/share/zoneinfo/{localtime} /etc/localtime')
# sys_command('/usr/bin/arch-chroot /mnt hwclock --hctosys --localtime')
@ -351,7 +351,7 @@ class Installer:
self.set_locale('en_US')
# TODO: Use python functions for this
sys_command(f'/usr/bin/arch-chroot {self.target} chmod 700 /root')
SysCommand(f'/usr/bin/arch-chroot {self.target} chmod 700 /root')
self.mkinitcpio('-P')
@ -378,16 +378,16 @@ class Installer:
if bootloader == 'systemd-bootctl':
self.pacstrap('efibootmgr')
if not hasUEFI():
if not has_uefi():
raise HardwareIncompatibilityError
# TODO: Ideally we would want to check if another config
# points towards the same disk and/or partition.
# And in which case we should do some clean up.
# Install the boot loader
if sys_command(f'/usr/bin/arch-chroot {self.target} bootctl --path=/boot install').exit_code != 0:
if SysCommand(f'/usr/bin/arch-chroot {self.target} bootctl --path=/boot install').exit_code != 0:
# Fallback, try creating the boot loader without touching the EFI variables
sys_command(f'/usr/bin/arch-chroot {self.target} bootctl --no-variables --path=/boot install')
SysCommand(f'/usr/bin/arch-chroot {self.target} bootctl --no-variables --path=/boot install')
# Modify or create a loader.conf
if os.path.isfile(f'{self.target}/boot/loader/loader.conf'):
@ -409,8 +409,8 @@ class Installer:
else:
loader.write(f"{line}\n")
## For some reason, blkid and /dev/disk/by-uuid are not getting along well.
## And blkid is wrong in terms of LUKS.
# For some reason, blkid and /dev/disk/by-uuid are not getting along well.
# And blkid is wrong in terms of LUKS.
# UUID = sys_command('blkid -s PARTUUID -o value {drive}{partition_2}'.format(**args)).decode('UTF-8').strip()
# Setup the loader entry
with open(f'{self.target}/boot/loader/entries/{self.init_time}.conf', 'w') as entry:
@ -418,8 +418,8 @@ class Installer:
entry.write(f'# Created on: {self.init_time}\n')
entry.write('title Arch Linux\n')
entry.write('linux /vmlinuz-linux\n')
if not isVM():
vendor = cpuVendor()
if not is_vm():
vendor = cpu_vendor()
if vendor == "AuthenticAMD":
entry.write("initrd /amd-ucode.img\n")
elif vendor == "GenuineIntel":
@ -427,8 +427,8 @@ class Installer:
else:
self.log("unknow cpu vendor, not adding ucode to systemd-boot config")
entry.write('initrd /initramfs-linux.img\n')
## blkid doesn't trigger on loopback devices really well,
## so we'll use the old manual method until we get that sorted out.
# blkid doesn't trigger on loopback devices really well,
# so we'll use the old manual method until we get that sorted out.
if real_device := self.detect_encryption(root_partition):
# TODO: We need to detect if the encrypted device is a whole disk encryption,
@ -446,17 +446,17 @@ class Installer:
elif bootloader == "grub-install":
self.pacstrap('grub')
if hasUEFI():
if has_uefi():
self.pacstrap('efibootmgr')
o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.target} grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=GRUB'))
sys_command('/usr/bin/arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg')
o = b''.join(SysCommand(f'/usr/bin/arch-chroot {self.target} grub-install --target=x86_64-efi --efi-directory=/boot --bootloader-id=GRUB'))
SysCommand('/usr/bin/arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg')
return True
else:
root_device = subprocess.check_output(f'basename "$(readlink -f /sys/class/block/{root_partition.path.replace("/dev/", "")}/..)"', shell=True).decode().strip()
if root_device == "block":
root_device = f"{root_partition.path}"
o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.target} grub-install --target=i386-pc /dev/{root_device}'))
sys_command('/usr/bin/arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg')
o = b''.join(SysCommand(f'/usr/bin/arch-chroot {self.target} grub-install --target=i386-pc /dev/{root_device}'))
SysCommand('/usr/bin/arch-chroot /mnt grub-mkconfig -o /boot/grub/grub.cfg')
self.helper_flags['bootloader'] = bootloader
return True
else:
@ -484,13 +484,13 @@ class Installer:
if groups is None:
groups = []
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}'))
o = b''.join(SysCommand(f'/usr/bin/arch-chroot {self.target} useradd -m -G wheel {user}'))
if password:
self.user_set_pw(user, password)
if groups:
for group in groups:
o = b''.join(sys_command(f'/usr/bin/arch-chroot {self.target} gpasswd -a {user} {group}'))
o = b''.join(SysCommand(f'/usr/bin/arch-chroot {self.target} gpasswd -a {user} {group}'))
if sudo and self.enable_sudo(user):
self.helper_flags['user'] = True
@ -502,13 +502,13 @@ class Installer:
# This means the root account isn't locked/disabled with * in /etc/passwd
self.helper_flags['user'] = True
o = b''.join(sys_command(f"/usr/bin/arch-chroot {self.target} sh -c \"echo '{user}:{password}' | chpasswd\""))
o = b''.join(SysCommand(f"/usr/bin/arch-chroot {self.target} sh -c \"echo '{user}:{password}' | chpasswd\""))
pass
def user_set_shell(self, user, shell):
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}\""))
o = b''.join(SysCommand(f"/usr/bin/arch-chroot {self.target} sh -c \"chsh -s {shell} {user}\""))
pass
def set_keyboard_language(self, language):

View File

@ -78,7 +78,7 @@ class luks2:
try:
# Try to setup the crypt-device
cmd_handle = sys_command(cryptsetup_args)
cmd_handle = SysCommand(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=logging.DEBUG)
@ -87,7 +87,7 @@ class luks2:
# Get crypt-information about the device by doing a reverse lookup starting with the partition path
# For instance: /dev/sda
devinfo = json.loads(b''.join(sys_command(f"lsblk --fs -J {partition.path}")).decode('UTF-8'))['blockdevices'][0]
devinfo = json.loads(b''.join(SysCommand(f"lsblk --fs -J {partition.path}")).decode('UTF-8'))['blockdevices'][0]
# For each child (sub-partition/sub-device)
if len(children := devinfo.get('children', [])):
@ -95,14 +95,14 @@ class luks2:
# Unmount the child location
if child_mountpoint := child.get('mountpoint', None):
log(f'Unmounting {child_mountpoint}', level=logging.DEBUG)
sys_command(f"umount -R {child_mountpoint}")
SysCommand(f"umount -R {child_mountpoint}")
# And close it if possible.
log(f"Closing crypt device {child['name']}", level=logging.DEBUG)
sys_command(f"cryptsetup close {child['name']}")
SysCommand(f"cryptsetup close {child['name']}")
# Then try again to set up the crypt-device
cmd_handle = sys_command(cryptsetup_args)
cmd_handle = SysCommand(cryptsetup_args)
else:
raise err
@ -128,7 +128,7 @@ class luks2:
while pathlib.Path(partition.path).exists() is False and time.time() - wait_timer < 10:
time.sleep(0.025)
sys_command(f'/usr/bin/cryptsetup open {partition.path} {mountpoint} --key-file {os.path.abspath(key_file)} --type luks2')
SysCommand(f'/usr/bin/cryptsetup open {partition.path} {mountpoint} --key-file {os.path.abspath(key_file)} --type luks2')
if os.path.islink(f'/dev/mapper/{mountpoint}'):
self.mapdev = f'/dev/mapper/{mountpoint}'
unlocked_partition = Partition(self.mapdev, None, encrypted=True, filesystem=get_filesystem_type(self.mapdev), autodetect_filesystem=False)
@ -139,9 +139,9 @@ class luks2:
if not mountpoint:
mountpoint = self.mapdev
sys_command(f'/usr/bin/cryptsetup close {self.mapdev}')
SysCommand(f'/usr/bin/cryptsetup close {self.mapdev}')
return os.path.islink(self.mapdev) is False
def format(self, path):
if (handle := sys_command(f"/usr/bin/cryptsetup -q -v luksErase {path}")).exit_code != 0:
if (handle := SysCommand(f"/usr/bin/cryptsetup -q -v luksErase {path}")).exit_code != 0:
raise DiskError(f'Could not format {path} with {self.filesystem} because: {b"".join(handle)}')

View File

@ -15,9 +15,9 @@ def filter_mirrors_by_region(regions, destination='/etc/pacman.d/mirrorlist', tm
region_list = []
for region in regions.split(','):
region_list.append(f'country={region}')
o = b''.join(sys_command(f"/usr/bin/wget 'https://archlinux.org/mirrorlist/?{'&'.join(region_list)}&protocol=https&ip_version=4&ip_version=6&use_mirror_status=on' -O {tmp_dir}/mirrorlist"))
o = b''.join(sys_command(f"/usr/bin/sed -i 's/#Server/Server/' {tmp_dir}/mirrorlist"))
o = b''.join(sys_command(f"/usr/bin/mv {tmp_dir}/mirrorlist {destination}"))
o = b''.join(SysCommand(f"/usr/bin/wget 'https://archlinux.org/mirrorlist/?{'&'.join(region_list)}&protocol=https&ip_version=4&ip_version=6&use_mirror_status=on' -O {tmp_dir}/mirrorlist"))
o = b''.join(SysCommand(f"/usr/bin/sed -i 's/#Server/Server/' {tmp_dir}/mirrorlist"))
o = b''.join(SysCommand(f"/usr/bin/mv {tmp_dir}/mirrorlist {destination}"))
return True
@ -71,7 +71,7 @@ def use_mirrors(regions: dict, destination='/etc/pacman.d/mirrorlist'):
def re_rank_mirrors(top=10, *positionals, **kwargs):
if sys_command(f'/usr/bin/rankmirrors -n {top} /etc/pacman.d/mirrorlist > /etc/pacman.d/mirrorlist').exit_code == 0:
if SysCommand(f'/usr/bin/rankmirrors -n {top} /etc/pacman.d/mirrorlist > /etc/pacman.d/mirrorlist').exit_code == 0:
return True
return False

View File

@ -5,7 +5,7 @@ import struct
from collections import OrderedDict
from .exceptions import *
from .general import sys_command
from .general import SysCommand
from .storage import storage
@ -53,7 +53,7 @@ def wireless_scan(interface):
if interfaces[interface] != 'WIRELESS':
raise HardwareIncompatibilityError(f"Interface {interface} is not a wireless interface: {interfaces}")
sys_command(f"iwctl station {interface} scan")
SysCommand(f"iwctl station {interface} scan")
if '_WIFI' not in storage:
storage['_WIFI'] = {}
@ -72,5 +72,5 @@ def get_wireless_networks(interface):
wireless_scan(interface)
time.sleep(5)
for line in sys_command(f"iwctl station {interface} get-networks"):
for line in SysCommand(f"iwctl station {interface} get-networks"):
print(line)

View File

@ -18,7 +18,7 @@ class LogLevels:
Debug = 0b111
class journald(dict):
class Journald(dict):
@abc.abstractmethod
def log(message, level=logging.DEBUG):
try:
@ -161,7 +161,7 @@ def log(*args, **kwargs):
return None
try:
journald.log(string, level=kwargs.get('level', logging.INFO))
Journald.log(string, level=kwargs.get('level', logging.INFO))
except ModuleNotFoundError:
pass # Ignore writing to journald

View File

@ -5,6 +5,6 @@ def service_state(service_name: str):
if os.path.splitext(service_name)[1] != '.service':
service_name += '.service' # Just to be safe
state = b''.join(sys_command(f'systemctl show --no-pager -p SubState --value {service_name}', environment_vars={'SYSTEMD_COLORS': '0'}))
state = b''.join(SysCommand(f'systemctl show --no-pager -p SubState --value {service_name}', environment_vars={'SYSTEMD_COLORS': '0'}))
return state.strip().decode('UTF-8')

View File

@ -12,8 +12,8 @@ import time
import tty
from .exceptions import *
from .general import sys_command
from .hardware import AVAILABLE_GFX_DRIVERS, hasUEFI
from .general import SysCommand
from .hardware import AVAILABLE_GFX_DRIVERS, has_uefi
from .locale_helpers import list_keyboard_languages, verify_keyboard_layout, search_keyboard_layout
from .networking import list_interfaces
from .output import log
@ -363,7 +363,7 @@ def ask_for_a_timezone():
def ask_for_bootloader() -> str:
bootloader = "systemd-bootctl"
if not hasUEFI():
if not has_uefi():
bootloader = "grub-install"
else:
bootloader_choice = input("Would you like to use GRUB as a bootloader instead of systemd-boot? [y/N] ").lower()
@ -705,7 +705,7 @@ def select_driver(options=AVAILABLE_GFX_DRIVERS):
default_option = options["All open-source (default)"]
if drivers:
lspci = sys_command('/usr/bin/lspci')
lspci = SysCommand('/usr/bin/lspci')
for line in lspci.trace_log.split(b'\r\n'):
if b' vga ' in line.lower():
if b'nvidia' in line.lower():

View File

@ -8,8 +8,8 @@ sys.path.insert(0, os.path.abspath('..'))
def process_docstring(app, what, name, obj, options, lines):
spaces_pat = re.compile(r"( {8})")
ll = []
for l in lines:
ll.append(spaces_pat.sub(" ", l))
for line in lines:
ll.append(spaces_pat.sub(" ", line))
lines[:] = ll

View File

@ -3,7 +3,7 @@ import logging
import time
import archinstall
from archinstall.lib.hardware import hasUEFI
from archinstall.lib.hardware import has_uefi
if archinstall.arguments.get('help'):
print("See `man archinstall` for help.")
@ -257,7 +257,7 @@ def perform_installation_steps():
Once that's done, we'll hand over to perform_installation()
"""
mode = archinstall.GPT
if hasUEFI() is False:
if has_uefi() is False:
mode = archinstall.MBR
with archinstall.Filesystem(archinstall.arguments['harddrive'], mode) as fs:
@ -294,7 +294,7 @@ def perform_installation_steps():
else:
fs.find_partition('/').mount('/mnt')
if hasUEFI():
if has_uefi():
fs.find_partition('/boot').mount('/mnt/boot')
perform_installation('/mnt')
@ -321,7 +321,7 @@ def perform_installation(mountpoint):
installation.set_hostname(archinstall.arguments['hostname'])
if archinstall.arguments['mirror-region'].get("mirrors", None) is not None:
installation.set_mirrors(archinstall.arguments['mirror-region']) # Set the mirrors in the installation medium
if archinstall.arguments["bootloader"] == "grub-install" and hasUEFI():
if archinstall.arguments["bootloader"] == "grub-install" and has_uefi():
installation.add_additional_packages("grub")
installation.set_keyboard_language(archinstall.arguments['keyboard-language'])
installation.add_bootloader(archinstall.arguments["bootloader"])
@ -329,7 +329,7 @@ def perform_installation(mountpoint):
# 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.
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')

View File

@ -23,7 +23,7 @@ def install_on(mountpoint):
# Optionally enable networking:
if archinstall.arguments.get('network', None):
installation.copy_ISO_network_config(enable_services=True)
installation.copy_iso_network_config(enable_services=True)
installation.add_additional_packages(['nano', 'wget', 'git'])
installation.install_profile('minimal')