implement explicit Optional type hints for =None parameters

Thanks https://github.com/hauntsaninja/no_implicit_optional
This commit is contained in:
InsanePrawn 2022-11-09 15:22:06 +01:00
parent 669c82a10b
commit 82a87e7ea9
15 changed files with 34 additions and 27 deletions

View file

@ -36,7 +36,7 @@ class AbstractChroot(Protocol):
copy_base: bool, copy_base: bool,
extra_repos: Mapping[str, RepoInfo], extra_repos: Mapping[str, RepoInfo],
base_packages: list[str], base_packages: list[str],
path_override: str = None, path_override: Optional[str] = None,
): ):
pass pass
@ -87,10 +87,10 @@ class Chroot(AbstractChroot):
self, self,
name: str, name: str,
arch: Arch, arch: Arch,
copy_base: bool = None, copy_base: Optional[bool] = None,
extra_repos: Mapping[str, RepoInfo] = {}, extra_repos: Mapping[str, RepoInfo] = {},
base_packages: list[str] = ['base', 'base-devel', 'git'], base_packages: list[str] = ['base', 'base-devel', 'git'],
path_override: str = None, path_override: Optional[str] = None,
): ):
self.uuid = uuid4() self.uuid = uuid4()
if copy_base is None: if copy_base is None:
@ -138,7 +138,7 @@ class Chroot(AbstractChroot):
absolute_source: str, absolute_source: str,
relative_destination: str, relative_destination: str,
options=['bind'], options=['bind'],
fs_type: str = None, fs_type: Optional[str] = None,
fail_if_mounted: bool = True, fail_if_mounted: bool = True,
mkdir: bool = True, mkdir: bool = True,
strict_cache_consistency: bool = False, strict_cache_consistency: bool = False,
@ -294,7 +294,7 @@ class Chroot(AbstractChroot):
root_write_file(makepkg_conf_path, makepkg_cross_conf) root_write_file(makepkg_conf_path, makepkg_cross_conf)
return makepkg_conf_path_relative return makepkg_conf_path_relative
def write_pacman_conf(self, check_space: Optional[bool] = None, in_chroot: bool = True, absolute_path: str = None): def write_pacman_conf(self, check_space: Optional[bool] = None, in_chroot: bool = True, absolute_path: Optional[str] = None):
user = None user = None
group = None group = None
if check_space is None: if check_space is None:

View file

@ -2,6 +2,8 @@ import click
import logging import logging
import os import os
from typing import Optional
from config.state import config from config.state import config
from wrapper import enforce_wrap from wrapper import enforce_wrap
from devices.device import get_profile_device from devices.device import get_profile_device
@ -21,7 +23,7 @@ CHROOT_TYPES = ['base', 'build', 'rootfs']
default=None, default=None,
) )
@click.pass_context @click.pass_context
def cmd_chroot(ctx: click.Context, type: str = 'build', name: str = None, enable_crossdirect=True): def cmd_chroot(ctx: click.Context, type: str = 'build', name: Optional[str] = None, enable_crossdirect=True):
"""Open a shell in a chroot. For rootfs NAME is a profile name, for others the architecture (e.g. aarch64).""" """Open a shell in a chroot. For rootfs NAME is a profile name, for others the architecture (e.g. aarch64)."""
if type not in CHROOT_TYPES: if type not in CHROOT_TYPES:

View file

@ -30,7 +30,7 @@ class DeviceChroot(BuildChroot):
clss.create_rootfs(self, reset, pacman_conf_target, active_previously) clss.create_rootfs(self, reset, pacman_conf_target, active_previously)
def mount_rootfs(self, source_path: str, fs_type: str = None, options: list[str] = [], allow_overlay: bool = False): def mount_rootfs(self, source_path: str, fs_type: Optional[str] = None, options: list[str] = [], allow_overlay: bool = False):
if self.active: if self.active:
raise Exception(f'{self.name}: Chroot is marked as active, not mounting a rootfs over it.') raise Exception(f'{self.name}: Chroot is marked as active, not mounting a rootfs over it.')
if not os.path.exists(source_path): if not os.path.exists(source_path):

View file

@ -61,7 +61,7 @@ def make_abs_path(path: str) -> str:
return '/' + path.lstrip('/') return '/' + path.lstrip('/')
def get_chroot_path(chroot_name, override_basepath: str = None) -> str: def get_chroot_path(chroot_name, override_basepath: Optional[str] = None) -> str:
base_path = config.get_path('chroots') if not override_basepath else override_basepath base_path = config.get_path('chroots') if not override_basepath else override_basepath
return os.path.join(base_path, chroot_name) return os.path.join(base_path, chroot_name)

View file

@ -1,6 +1,7 @@
import logging import logging
from copy import deepcopy from copy import deepcopy
from typing import Optional
from .scheme import Profile, SparseProfile from .scheme import Profile, SparseProfile
@ -23,7 +24,7 @@ PROFILE_EMPTY: Profile = {key: None for key in PROFILE_DEFAULTS.keys()} # type:
def resolve_profile( def resolve_profile(
name: str, name: str,
sparse_profiles: dict[str, SparseProfile], sparse_profiles: dict[str, SparseProfile],
resolved: dict[str, Profile] = None, resolved: Optional[dict[str, Profile]] = None,
_visited=None, _visited=None,
) -> dict[str, Profile]: ) -> dict[str, Profile]:
""" """

View file

@ -174,7 +174,7 @@ def parse_file(config_file: str, base: dict = CONFIG_DEFAULTS) -> dict:
class ConfigLoadException(Exception): class ConfigLoadException(Exception):
inner = None inner = None
def __init__(self, extra_msg='', inner_exception: Exception = None): def __init__(self, extra_msg='', inner_exception: Optional[Exception] = None):
msg: list[str] = ['Config load failed!'] msg: list[str] = ['Config load failed!']
if extra_msg: if extra_msg:
msg.append(extra_msg) msg.append(extra_msg)

View file

@ -22,7 +22,7 @@ class BinaryPackage(PackageInfo):
name: str, name: str,
version: str, version: str,
filename: str, filename: str,
resolved_url: str = None, resolved_url: Optional[str] = None,
): ):
self.name = name self.name = name
self.version = version self.version = version

View file

@ -3,6 +3,8 @@ import os
import pwd import pwd
import subprocess import subprocess
from typing import Optional
from .cmd import run_cmd, run_root_cmd, generate_cmd_su from .cmd import run_cmd, run_root_cmd, generate_cmd_su
@ -10,7 +12,7 @@ def get_username(id: int):
return pwd.getpwuid(id).pw_name return pwd.getpwuid(id).pw_name
def run_func(f, expected_user: str = None, **kwargs): def run_func(f, expected_user: Optional[str] = None, **kwargs):
current_uid = os.getuid() current_uid = os.getuid()
current_username = get_username(current_uid) current_username = get_username(current_uid)
target_uid = current_uid target_uid = current_uid

View file

@ -1,8 +1,10 @@
from typing import Optional
from constants import Arch, CFLAGS_ARCHES, CFLAGS_GENERAL, COMPILE_ARCHES, GCC_HOSTSPECS from constants import Arch, CFLAGS_ARCHES, CFLAGS_GENERAL, COMPILE_ARCHES, GCC_HOSTSPECS
from config.state import config from config.state import config
def generate_makepkg_conf(arch: Arch, cross: bool = False, chroot: str = None) -> str: def generate_makepkg_conf(arch: Arch, cross: bool = False, chroot: Optional[str] = None) -> str:
""" """
Generate a makepkg.conf. For use with crosscompiling, specify `cross=True` and pass as `chroot` Generate a makepkg.conf. For use with crosscompiling, specify `cross=True` and pass as `chroot`
the relative path inside the native chroot where the foreign chroot will be mounted. the relative path inside the native chroot where the foreign chroot will be mounted.

View file

@ -362,11 +362,11 @@ def cmd_image():
is_flag=True, is_flag=True,
default=False, default=False,
help='Skip creating image files for the partitions and directly work on the target block device.') help='Skip creating image files for the partitions and directly work on the target block device.')
def cmd_build(profile_name: str = None, def cmd_build(profile_name: Optional[str] = None,
local_repos: bool = True, local_repos: bool = True,
build_pkgs: bool = True, build_pkgs: bool = True,
no_download_pkgs=False, no_download_pkgs=False,
block_target: str = None, block_target: Optional[str] = None,
skip_part_images: bool = False): skip_part_images: bool = False):
""" """
Build a device image. Build a device image.
@ -454,7 +454,7 @@ def cmd_build(profile_name: str = None,
@cmd_image.command(name='inspect') @cmd_image.command(name='inspect')
@click.option('--shell', '-s', is_flag=True) @click.option('--shell', '-s', is_flag=True)
@click.argument('profile', required=False) @click.argument('profile', required=False)
def cmd_inspect(profile: str = None, shell: bool = False): def cmd_inspect(profile: Optional[str] = None, shell: bool = False):
"""Open a shell in a device image""" """Open a shell in a device image"""
config.enforce_profile_device_set() config.enforce_profile_device_set()
config.enforce_profile_flavour_set() config.enforce_profile_flavour_set()

View file

@ -24,7 +24,7 @@ from image.cli import cmd_image
@verbose_option @verbose_option
@config_option @config_option
@nowrapper_option @nowrapper_option
def cli(verbose: bool = False, config_file: str = None, wrapper_override: Optional[bool] = None, error_shell: bool = False): def cli(verbose: bool = False, config_file: Optional[str] = None, wrapper_override: Optional[bool] = None, error_shell: bool = False):
setup_logging(verbose) setup_logging(verbose)
config.runtime.verbose = verbose config.runtime.verbose = verbose
config.runtime.no_wrap = wrapper_override is False config.runtime.no_wrap = wrapper_override is False

View file

@ -51,7 +51,7 @@ def run_ssh_command(cmd: list[str] = [],
return run_cmd(full_cmd) return run_cmd(full_cmd)
def scp_put_files(src: list[str], dst: str, user: str = None, host: str = SSH_DEFAULT_HOST, port: int = SSH_DEFAULT_PORT): def scp_put_files(src: list[str], dst: str, user: Optional[str] = None, host: str = SSH_DEFAULT_HOST, port: int = SSH_DEFAULT_PORT):
check_programs_wrap(['scp']) check_programs_wrap(['scp'])
if not user: if not user:
user = config.get_profile()['username'] user = config.get_profile()['username']

View file

@ -449,7 +449,7 @@ def setup_sources(package: Pkgbuild, lazy: bool = True):
def build_package( def build_package(
package: Pkgbuild, package: Pkgbuild,
arch: Arch, arch: Arch,
repo_dir: str = None, repo_dir: Optional[str] = None,
enable_crosscompile: bool = True, enable_crosscompile: bool = True,
enable_crossdirect: bool = True, enable_crossdirect: bool = True,
enable_ccache: bool = True, enable_ccache: bool = True,

View file

@ -1,7 +1,7 @@
import click import click
import logging import logging
from typing import Sequence, Union from typing import Optional, Sequence, Union
from config.state import config from config.state import config
from constants import Arch from constants import Arch
@ -14,21 +14,21 @@ wrapper_impls: dict[str, Wrapper] = {
} }
def get_wrapper_type(wrapper_type: str = None): def get_wrapper_type(wrapper_type: Optional[str] = None):
return wrapper_type or config.file.wrapper.type return wrapper_type or config.file.wrapper.type
def get_wrapper_impl(wrapper_type: str = None) -> Wrapper: def get_wrapper_impl(wrapper_type: Optional[str] = None) -> Wrapper:
return wrapper_impls[get_wrapper_type(wrapper_type)] return wrapper_impls[get_wrapper_type(wrapper_type)]
def wrap(wrapper_type: str = None): def wrap(wrapper_type: Optional[str] = None):
wrapper_type = get_wrapper_type(wrapper_type) wrapper_type = get_wrapper_type(wrapper_type)
if wrapper_type != 'none': if wrapper_type != 'none':
get_wrapper_impl(wrapper_type).wrap() get_wrapper_impl(wrapper_type).wrap()
def is_wrapped(wrapper_type: str = None): def is_wrapped(wrapper_type: Optional[str] = None):
wrapper_type = get_wrapper_type(wrapper_type) wrapper_type = get_wrapper_type(wrapper_type)
return wrapper_type != 'none' and get_wrapper_impl(wrapper_type).is_wrapped() return wrapper_type != 'none' and get_wrapper_impl(wrapper_type).is_wrapped()

View file

@ -3,7 +3,7 @@ import os
import uuid import uuid
import pathlib import pathlib
from typing import Protocol from typing import Optional, Protocol
from config.state import config from config.state import config
from config.state import dump_file as dump_config_file from config.state import dump_file as dump_config_file
@ -37,7 +37,7 @@ class BaseWrapper(Wrapper):
type: str type: str
wrapped_config_path: str wrapped_config_path: str
def __init__(self, random_id: str = None, name: str = None): def __init__(self, random_id: Optional[str] = None, name: Optional[str] = None):
self.uuid = str(random_id or uuid.uuid4()) self.uuid = str(random_id or uuid.uuid4())
self.identifier = name or f'kupferbootstrap-{self.uuid}' self.identifier = name or f'kupferbootstrap-{self.uuid}'
@ -98,7 +98,7 @@ class BaseWrapper(Wrapper):
def is_wrapped(self): def is_wrapped(self):
return os.getenv(WRAPPER_ENV_VAR) == self.type.upper() return os.getenv(WRAPPER_ENV_VAR) == self.type.upper()
def get_bind_mounts_default(self, wrapped_config_path: str = None, ssh_dir: str = None, target_home: str = '/root'): def get_bind_mounts_default(self, wrapped_config_path: Optional[str] = None, ssh_dir: Optional[str] = None, target_home: str = '/root'):
wrapped_config_path = wrapped_config_path or self.wrapped_config_path wrapped_config_path = wrapped_config_path or self.wrapped_config_path
ssh_dir = ssh_dir or os.path.join(pathlib.Path.home(), '.ssh') ssh_dir = ssh_dir or os.path.join(pathlib.Path.home(), '.ssh')
assert (wrapped_config_path) assert (wrapped_config_path)