Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions archinstall/default_profiles/desktops/awesome.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,21 +36,20 @@ def install(self, install_session: Installer) -> None:
super().install(install_session)

# TODO: Copy a full configuration to ~/.config/awesome/rc.lua instead.
with open(f'{install_session.target}/etc/xdg/awesome/rc.lua') as fh:
awesome_lua = fh.read()
rc_lua = install_session.target / 'etc/xdg/awesome/rc.lua'
awesome_lua = rc_lua.read_text()

# Replace xterm with alacritty for a smoother experience.
awesome_lua = awesome_lua.replace('"xterm"', '"alacritty"')

with open(f'{install_session.target}/etc/xdg/awesome/rc.lua', 'w') as fh:
fh.write(awesome_lua)
rc_lua.write_text(awesome_lua)

# TODO: Configure the right-click-menu to contain the above packages that were installed. (as a user config)

# TODO: check if we selected a greeter,
# but for now, awesome is intended to run without one.
with open(f'{install_session.target}/etc/X11/xinit/xinitrc') as xinitrc:
xinitrc_data = xinitrc.read()
xinitrc = install_session.target / 'etc/X11/xinit/xinitrc'
xinitrc_data = xinitrc.read_text()

for line in xinitrc_data.split('\n'):
if 'twm &' in line:
Expand All @@ -63,5 +62,4 @@ def install(self, install_session: Installer) -> None:
xinitrc_data += '\n'
xinitrc_data += 'exec awesome\n'

with open(f'{install_session.target}/etc/X11/xinit/xinitrc', 'w') as xinitrc:
xinitrc.write(xinitrc_data)
xinitrc.write_text(xinitrc_data)
2 changes: 1 addition & 1 deletion archinstall/lib/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def poll(self) -> None:
def execute(self) -> bool:
import pty

if (old_dir := os.getcwd()) != self.working_directory:
if (old_dir := os.getcwd()) != self.working_directory: # noqa: PTH109
os.chdir(str(self.working_directory))

# Note: If for any reason, we get a Python exception between here
Expand Down
3 changes: 1 addition & 2 deletions archinstall/lib/disk/device_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,8 +616,7 @@ def _wipe(self, dev_path: Path) -> None:
@param dev_path: Device path of the partition to be wiped.
@type dev_path: str
"""
with open(dev_path, 'wb') as p:
p.write(bytearray(1024))
dev_path.write_bytes(bytearray(1024))

def wipe_dev(self, block_device: BDevice) -> None:
"""
Expand Down
2 changes: 1 addition & 1 deletion archinstall/lib/disk/luks.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def _crypttab(
) -> None:
debug(f'Adding crypttab entry for key {key_file}')

with open(crypttab_path, 'a') as crypttab:
with crypttab_path.open('a') as crypttab:
opt = ','.join(options)
uuid = self._get_luks_uuid()
row = f'{self.mapper_name} UUID={uuid} {key_file} {opt}\n'
Expand Down
16 changes: 7 additions & 9 deletions archinstall/lib/hardware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import os
from dataclasses import dataclass
from enum import Enum, StrEnum
from functools import cached_property
Expand All @@ -10,6 +9,8 @@
from archinstall.lib.networking import enrich_iface_types, list_interfaces
from archinstall.lib.translationhandler import tr

_VIRTUAL_DMI_ID = Path('/sys/devices/virtual/dmi/id')


class CPUVendor(StrEnum):
AMD = 'AuthenticAMD'
Expand Down Expand Up @@ -146,9 +147,8 @@ def __init__(self) -> None:
def has_battery(self) -> bool:
for type_path in Path('/sys/class/power_supply/').glob('*/type'):
try:
with open(type_path) as f:
if f.read().strip() == 'Battery':
return True
if type_path.read_text().rstrip() == 'Battery':
return True
except OSError:
continue

Expand Down Expand Up @@ -213,7 +213,7 @@ def has_wifi() -> bool:

@staticmethod
def has_uefi() -> bool:
return os.path.isdir('/sys/firmware/efi')
return Path('/sys/firmware/efi').is_dir()

@staticmethod
def _graphics_devices() -> dict[str, str]:
Expand Down Expand Up @@ -248,16 +248,14 @@ def cpu_model() -> str | None:
@staticmethod
def sys_vendor() -> str | None:
try:
with open('/sys/devices/virtual/dmi/id/sys_vendor') as vendor:
return vendor.read().strip()
return (_VIRTUAL_DMI_ID / 'sys_vendor').read_text().rstrip()
except FileNotFoundError:
return None

@staticmethod
def product_name() -> str | None:
try:
with open('/sys/devices/virtual/dmi/id/product_name') as product:
return product.read().strip()
return (_VIRTUAL_DMI_ID / 'product_name').read_text().rstrip()
except FileNotFoundError:
return None

Expand Down
40 changes: 22 additions & 18 deletions archinstall/lib/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ def set_mirrors(
if repositories_config:
debug(f'Pacman config: {repositories_config}')

with open(pacman_config, 'a') as fp:
with pacman_config.open('a') as fp:
fp.write(repositories_config)

regions_config = mirror_config.regions_config(mirror_list_handler, speed_sort=True)
Expand All @@ -616,7 +616,7 @@ def genfstab(self, flags: str = '-pU') -> None:
except SysCallError as err:
raise RequirementError(f'Could not generate fstab, strapping in packages most likely failed (disk out of space?)\n Error: {err}')

with open(fstab_path, 'ab') as fp:
with fstab_path.open('ab') as fp:
fp.write(gen_fstab)

if not fstab_path.is_file():
Expand All @@ -627,7 +627,7 @@ def genfstab(self, flags: str = '-pU') -> None:
if plugin.on_genfstab(self) is True:
break

with open(fstab_path, 'a') as fp:
with fstab_path.open('a') as fp:
for entry in self._fstab_entries:
fp.write(f'{entry}\n')

Expand Down Expand Up @@ -770,7 +770,7 @@ def configure_nic(self, nic: Nic) -> None:
or conf
)

with open(f'{self.target}/etc/systemd/network/10-{nic.iface}.network', 'a') as netconf:
with (self.target / f'etc/systemd/network/10-{nic.iface}.network').open('a') as netconf:
netconf.write(str(conf))

def systemd_resolved_stub_mode(self) -> None:
Expand Down Expand Up @@ -833,7 +833,7 @@ def mkinitcpio(self, flags: list[str]) -> bool:
if plugin.on_mkinitcpio(self):
return True

with open(f'{self.target}/etc/mkinitcpio.conf', 'r+') as mkinit:
with (self.target / 'etc/mkinitcpio.conf').open('r+') as mkinit:
content = mkinit.read()
content = re.sub('\nMODULES=(.*)', f'\nMODULES=({" ".join(self._modules)})', content)
content = re.sub('\nBINARIES=(.*)', f'\nBINARIES=({" ".join(self._binaries)})', content)
Expand Down Expand Up @@ -1026,9 +1026,14 @@ def setup_swap(self, algo: ZramAlgorithm = ZramAlgorithm.ZSTD) -> None:

info(f'Zram compression algorithm: {algo.value}')

with open(f'{self.target}/etc/systemd/zram-generator.conf', 'w') as zram_conf:
zram_conf.write('[zram0]\n')
zram_conf.write(f'compression-algorithm = {algo.value}\n')
(self.target / 'etc/systemd/zram-generator.conf').write_text(
textwrap.dedent(
f"""\
[zram0]
compression-algorithm = {algo.value}
""",
)
)

self.enable_service('systemd-zram-setup@zram0.service')

Expand Down Expand Up @@ -1504,11 +1509,11 @@ def _add_limine_bootloader(

if not bootloader_removable:
# Create EFI boot menu entry for Limine.
fw_platform_size = Path('/sys/firmware/efi/fw_platform_size')
try:
with open('/sys/firmware/efi/fw_platform_size') as fw_platform_size:
efi_bitness = fw_platform_size.read().strip()
efi_bitness = fw_platform_size.read_text().rstrip()
except Exception as err:
raise OSError(f'Could not open or read /sys/firmware/efi/fw_platform_size to determine EFI bitness: {err}')
raise OSError(f'Could not open or read {fw_platform_size} to determine EFI bitness: {err}')

if efi_bitness == '64':
loader_path = f'\\EFI\\arch-limine\\{"BOOTAA64.EFI" if platform.machine() == "aarch64" else "BOOTX64.EFI"}'
Expand Down Expand Up @@ -1790,9 +1795,8 @@ def _config_uki(
raise ValueError(f'Could not detect ESP at mountpoint {self.target}')

# Set up kernel command line
with open(self.target / 'etc/kernel/cmdline', 'w') as cmdline:
kernel_parameters = self._get_kernel_params(root)
cmdline.write(' '.join(kernel_parameters) + '\n')
kernel_parameters = self._get_kernel_params(root)
(self.target / 'etc/kernel/cmdline').write_text(' '.join(kernel_parameters) + '\n')

diff_mountpoint = None

Expand Down Expand Up @@ -1920,11 +1924,11 @@ def enable_sudo(self, user: User, group: bool = False) -> None:
# Guarantees sudoer confs directory recommended perms
sudoers_dir.chmod(0o440)
# Appends a reference to the sudoers file, because if we are here sudoers.d did not exist yet
with open(self.target / 'etc/sudoers', 'a') as sudoers:
with (self.target / 'etc/sudoers').open('a') as sudoers:
sudoers.write('@includedir /etc/sudoers.d\n')

# We count how many files are there already so we know which number to prefix the file with
num_of_rules_already = len(os.listdir(sudoers_dir))
num_of_rules_already = len(os.listdir(sudoers_dir)) # noqa: PTH208
file_num_str = f'{num_of_rules_already:02d}' # We want 00_user1, 01_user2, etc

# Guarantees that username str does not contain invalid characters for a linux file name:
Expand Down Expand Up @@ -2098,7 +2102,7 @@ def set_x11_keyboard_language(self, language: str) -> bool:
return True

def _service_started(self, service_name: str) -> str | None:
if os.path.splitext(service_name)[1] not in ('.service', '.target', '.timer'):
if Path(service_name).suffix not in ('.service', '.target', '.timer'):
service_name += '.service' # Just to be safe

last_execution_time = (
Expand All @@ -2116,7 +2120,7 @@ def _service_started(self, service_name: str) -> str | None:
return last_execution_time

def _service_state(self, service_name: str) -> str:
if os.path.splitext(service_name)[1] not in ('.service', '.target', '.timer'):
if Path(service_name).suffix not in ('.service', '.target', '.timer'):
service_name += '.service' # Just to be safe

return SysCommand(
Expand Down
2 changes: 1 addition & 1 deletion archinstall/lib/locale/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def list_keyboard_languages() -> list[str]:
def list_locales() -> list[str]:
locales = []

with open('/usr/share/i18n/SUPPORTED') as file:
with Path('/usr/share/i18n/SUPPORTED').open() as file:
for line in file:
if line != 'C.UTF-8 UTF-8\n':
locales.append(line.rstrip())
Expand Down
5 changes: 2 additions & 3 deletions archinstall/lib/plugins.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import importlib.util
import os
import sys
from importlib import metadata
from pathlib import Path
Expand Down Expand Up @@ -34,7 +33,7 @@ def plugin(f: Any, *_args: Any, **_kwargs: Any) -> None:

def _import_via_path(path: Path, namespace: str | None = None) -> str:
if not namespace:
namespace = os.path.basename(path)
namespace = path.name

if namespace == '__init__.py':
namespace = path.parent.name
Expand Down Expand Up @@ -65,7 +64,7 @@ def load_plugin(path: Path) -> None:
namespace: str | None = None
info(f'Loading plugin from {path}')

if os.path.isfile(path):
if path.is_file():
namespace = _import_via_path(path)

if namespace and namespace in sys.modules:
Expand Down
8 changes: 3 additions & 5 deletions archinstall/lib/profile/profiles_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,11 @@ def install_greeter(self, install_session: Installer, greeter: GreeterType) -> N
# slick-greeter requires a config change
if greeter == GreeterType.LightdmSlick:
path = install_session.target.joinpath('etc/lightdm/lightdm.conf')
with open(path) as file:
filedata = file.read()
filedata = path.read_text()

filedata = filedata.replace('#greeter-session=example-gtk-gnome', 'greeter-session=lightdm-slick-greeter')

with open(path, 'w') as file:
file.write(filedata)
path.write_text(filedata)

if greeter == GreeterType.GreetdDms:
greetd_config = install_session.target / 'etc/greetd/config.toml'
Expand Down Expand Up @@ -306,7 +304,7 @@ def _is_legacy(self, file: Path) -> bool:
Check if the provided profile file contains a
legacy profile definition
"""
with open(file) as fp:
with file.open() as fp:
for line in fp.readlines():
if '__packages__' in line:
return True
Expand Down
2 changes: 1 addition & 1 deletion archinstall/lib/translationhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def _provided_translations(self) -> list[str]:
Get a list of all known languages
"""
translation_files = []
for filename in os.listdir(self._locales_dir):
for filename in os.listdir(self._locales_dir): # noqa: PTH208
if len(filename) == 2 or filename in ['pt_BR', 'zh-CN', 'zh-TW']:
translation_files.append(filename)

Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
if TYPE_CHECKING:
from sphinx.application import Sphinx

sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('..')) # noqa: PTH100


def process_docstring(
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ select = [
"PLC", # Pylint conventions
"PLE", # Pylint errors
"PLW", # Pylint warnings
"PTH", # flake8-use-pathlib
"PYI", # flake8-pyi
"RET", # flake8-return
"RSE", # flake8-raise
Expand Down
2 changes: 1 addition & 1 deletion test_tooling/qemu/qemu.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ def poll(self) -> None:
def execute(self) -> bool:
import pty

if (old_dir := os.getcwd()) != self.working_directory:
if (old_dir := os.getcwd()) != self.working_directory: # noqa: PTH109
os.chdir(str(self.working_directory))

# Note: If for any reason, we get a Python exception between here
Expand Down
Loading