Skip to content

Commit

Permalink
Fix whitespace issues detected by flake8 (#2652)
Browse files Browse the repository at this point in the history
This commit also removes exclusions that are no longer needed.
  • Loading branch information
correctmost authored Aug 28, 2024
1 parent 7b5f1f7 commit 62b4099
Show file tree
Hide file tree
Showing 26 changed files with 141 additions and 127 deletions.
8 changes: 4 additions & 4 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
[flake8]
count = True
# Several of the following could be autofixed or improved by running the code through psf/black
ignore = E123,E126,E128,E203,E227,E231,E261,E302,E402,E722,F541,W191,W292,W293,W503,W504
ignore = E123,E128,E722,F541,W191,W503,W504
max-complexity = 40
max-line-length = 236
max-line-length = 220
show-source = True
statistics = True
builtins = _
per-file-ignores = __init__.py:F401,F403,F405 simple_menu.py:C901,W503 guided.py:C901 network_configuration.py:F821
exclude = .git,__pycache__,docs,actions-runner
per-file-ignores = __init__.py:F401
exclude = .git,__pycache__,build,docs,actions-runner
2 changes: 1 addition & 1 deletion .github/workflows/flake8.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
on: [ push, pull_request ]
name: flake8 linting (15 ignores)
name: flake8 linting (7 ignores)
jobs:
flake8:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ The exceptions to PEP8 are:
* Archinstall uses [tabs instead of spaces](https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) simply to make it
easier for non-IDE developers to navigate the code *(Tab display-width should be equal to 4 spaces)*. Exception to the
rule are comments that need fine-tuned indentation for documentation purposes.
* [Line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) a maximum line length is enforced via flake8 with 236 characters
* [Line length](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) a maximum line length is enforced via flake8 with 220 characters
* [Line breaks before/after binary operator](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)
is not enforced, as long as the style of line breaks is consistent within the same code block.
* Archinstall should always be saved with **Unix-formatted line endings** and no other platform-specific formats.
Expand Down
1 change: 1 addition & 0 deletions archinstall/default_profiles/desktops/cosmic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
if TYPE_CHECKING:
_: Any


class CosmicProfile(XorgProfile):
def __init__(self) -> None:
super().__init__('cosmic-epoch', ProfileType.DesktopEnv, description='', advanced=True)
Expand Down
1 change: 1 addition & 0 deletions archinstall/default_profiles/desktops/plasma.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
if TYPE_CHECKING:
_: Any


class PlasmaProfile(XorgProfile):
def __init__(self) -> None:
super().__init__('KDE Plasma', ProfileType.DesktopEnv, description='')
Expand Down
1 change: 1 addition & 0 deletions archinstall/default_profiles/profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class GreeterType(Enum):
if '--advanced' in sys.argv:
CosmicSession = "cosmic-greeter"


class SelectResult(Enum):
NewSelection = auto()
SameSelection = auto()
Expand Down
2 changes: 1 addition & 1 deletion archinstall/lib/boot.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __enter__(self) -> 'Boot':
storage['active_boot'] = self
return self

def __exit__(self, *args :str, **kwargs :str) -> None:
def __exit__(self, *args: str, **kwargs: str) -> None:
# b''.join(sys_command('sync')) # No need to, since the underlying fs() object will call sync.
# TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager

Expand Down
6 changes: 3 additions & 3 deletions archinstall/lib/disk/device_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,9 @@ def get_uuid_for_path(self, path: Path) -> Optional[str]:
return partition.partuuid if partition else None

def get_btrfs_info(
self,
dev_path: Path,
lsblk_info: Optional[LsblkInfo] = None
self,
dev_path: Path,
lsblk_info: Optional[LsblkInfo] = None
) -> List[_BtrfsSubvolumeInfo]:
if not lsblk_info:
lsblk_info = get_lsblk_info(dev_path)
Expand Down
4 changes: 2 additions & 2 deletions archinstall/lib/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class UnknownFilesystemFormat(Exception):


class SysCallError(Exception):
def __init__(self, message :str, exit_code :Optional[int] = None, worker :Optional['SysCommandWorker'] = None) -> None:
def __init__(self, message: str, exit_code: Optional[int] = None, worker: Optional['SysCommandWorker'] = None) -> None:
super(SysCallError, self).__init__(message)
self.message = message
self.exit_code = exit_code
Expand All @@ -43,4 +43,4 @@ class Deprecated(Exception):
class DownloadTimeout(Exception):
'''
Download timeout exception raised by DownloadTimer.
'''
'''
77 changes: 39 additions & 38 deletions archinstall/lib/general.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@
from .installer import Installer


def generate_password(length :int = 64) -> str:
haystack = string.printable # digits, ascii_letters, punctuation (!"#$[] etc) and whitespace
def generate_password(length: int = 64) -> str:
haystack = string.printable # digits, ascii_letters, punctuation (!"#$[] etc) and whitespace
return ''.join(secrets.choice(haystack) for i in range(length))


def locate_binary(name :str) -> str:
def locate_binary(name: str) -> str:
if path := which(name):
return path
raise RequirementError(f"Binary {name} does not exist.")


def clear_vt100_escape_codes(data :Union[bytes, str]) -> Union[bytes, str]:
def clear_vt100_escape_codes(data: Union[bytes, str]) -> Union[bytes, str]:
# https://stackoverflow.com/a/43627833/929999
vt100_escape_regex = r'\x1B\[[?0-9;]*[a-zA-Z]'
if isinstance(data, bytes):
Expand Down Expand Up @@ -80,6 +80,7 @@ def jsonify(obj: Any, safe: bool = True) -> Any:

return obj


class JSON(json.JSONEncoder, json.JSONDecoder):
"""
A safe JSON encoder that will omit private information in dicts (starting with !)
Expand All @@ -101,13 +102,13 @@ def encode(self, obj: Any) -> str:
class SysCommandWorker:
def __init__(
self,
cmd :Union[str, List[str]],
callbacks :Optional[Dict[str, Any]] = None,
peek_output :Optional[bool] = False,
environment_vars :Optional[Dict[str, Any]] = None,
logfile :Optional[None] = None,
working_directory :Optional[str] = './',
remove_vt100_escape_codes_from_lines :bool = True
cmd: Union[str, List[str]],
callbacks: Optional[Dict[str, Any]] = None,
peek_output: Optional[bool] = False,
environment_vars: Optional[Dict[str, Any]] = None,
logfile: Optional[None] = None,
working_directory: Optional[str] = './',
remove_vt100_escape_codes_from_lines: bool = True
):
callbacks = callbacks or {}
environment_vars = environment_vars or {}
Expand All @@ -116,25 +117,25 @@ def __init__(
cmd = shlex.split(cmd)

if cmd:
if cmd[0][0] != '/' and cmd[0][:2] != './': # pathlib.Path does not work well
if cmd[0][0] != '/' and cmd[0][:2] != './': # pathlib.Path does not work well
cmd[0] = locate_binary(cmd[0])

self.cmd = cmd
self.callbacks = callbacks
self.peek_output = peek_output
# define the standard locale for command outputs. For now the C ascii one. Can be overridden
self.environment_vars = {**storage.get('CMD_LOCALE',{}),**environment_vars}
self.environment_vars = {**storage.get('CMD_LOCALE', {}), **environment_vars}
self.logfile = logfile
self.working_directory = working_directory

self.exit_code :Optional[int] = None
self.exit_code: Optional[int] = None
self._trace_log = b''
self._trace_log_pos = 0
self.poll_object = epoll()
self.child_fd :Optional[int] = None
self.started :Optional[float] = None
self.ended :Optional[float] = None
self.remove_vt100_escape_codes_from_lines :bool = remove_vt100_escape_codes_from_lines
self.child_fd: Optional[int] = None
self.started: Optional[float] = None
self.ended: Optional[float] = None
self.remove_vt100_escape_codes_from_lines: bool = remove_vt100_escape_codes_from_lines

def __contains__(self, key: bytes) -> bool:
"""
Expand All @@ -150,7 +151,7 @@ def __contains__(self, key: bytes) -> bool:

return False

def __iter__(self, *args :str, **kwargs :Dict[str, Any]) -> Iterator[bytes]:
def __iter__(self, *args: str, **kwargs: Dict[str, Any]) -> Iterator[bytes]:
last_line = self._trace_log.rfind(b'\n')
lines = filter(None, self._trace_log[self._trace_log_pos:last_line].splitlines())
for line in lines:
Expand All @@ -174,7 +175,7 @@ def __str__(self) -> str:
def __enter__(self) -> 'SysCommandWorker':
return self

def __exit__(self, *args :str) -> None:
def __exit__(self, *args: str) -> None:
# b''.join(sys_command('sync')) # No need to, since the underlying fs() object will call sync.
# TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager

Expand Down Expand Up @@ -208,7 +209,7 @@ def is_alive(self) -> bool:

return False

def write(self, data: bytes, line_ending :bool = True) -> int:
def write(self, data: bytes, line_ending: bool = True) -> int:
assert isinstance(data, bytes) # TODO: Maybe we can support str as well and encode it

self.make_sure_we_are_executing()
Expand All @@ -228,7 +229,7 @@ def tell(self) -> int:
self.make_sure_we_are_executing()
return self._trace_log_pos

def seek(self, pos :int) -> None:
def seek(self, pos: int) -> None:
self.make_sure_we_are_executing()
# Safety check to ensure 0 < pos < len(tracelog)
self._trace_log_pos = min(max(0, pos), len(self._trace_log))
Expand Down Expand Up @@ -337,19 +338,19 @@ def execute(self) -> bool:

return True

def decode(self, encoding :str = 'UTF-8') -> str:
def decode(self, encoding: str = 'UTF-8') -> str:
return self._trace_log.decode(encoding)


class SysCommand:
def __init__(self,
cmd :Union[str, List[str]],
callbacks :Dict[str, Callable[[Any], Any]] = {},
start_callback :Optional[Callable[[Any], Any]] = None,
peek_output :Optional[bool] = False,
environment_vars :Optional[Dict[str, Any]] = None,
working_directory :Optional[str] = './',
remove_vt100_escape_codes_from_lines :bool = True):
cmd: Union[str, List[str]],
callbacks: Dict[str, Callable[[Any], Any]] = {},
start_callback: Optional[Callable[[Any], Any]] = None,
peek_output: Optional[bool] = False,
environment_vars: Optional[Dict[str, Any]] = None,
working_directory: Optional[str] = './',
remove_vt100_escape_codes_from_lines: bool = True):

self._callbacks = callbacks.copy()
if start_callback:
Expand All @@ -361,25 +362,25 @@ def __init__(self,
self.working_directory = working_directory
self.remove_vt100_escape_codes_from_lines = remove_vt100_escape_codes_from_lines

self.session :Optional[SysCommandWorker] = None
self.session: Optional[SysCommandWorker] = None
self.create_session()

def __enter__(self) -> Optional[SysCommandWorker]:
return self.session

def __exit__(self, *args :str, **kwargs :Dict[str, Any]) -> None:
def __exit__(self, *args: str, **kwargs: Dict[str, Any]) -> None:
# b''.join(sys_command('sync')) # No need to, since the underlying fs() object will call sync.
# TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager

if len(args) >= 2 and args[1]:
error(args[1])

def __iter__(self, *args :List[Any], **kwargs :Dict[str, Any]) -> Iterator[bytes]:
def __iter__(self, *args: List[Any], **kwargs: Dict[str, Any]) -> Iterator[bytes]:
if self.session:
for line in self.session:
yield line

def __getitem__(self, key :slice) -> Optional[bytes]:
def __getitem__(self, key: slice) -> Optional[bytes]:
if not self.session:
raise KeyError(f"SysCommand() does not have an active session.")
elif type(key) is slice:
Expand All @@ -390,7 +391,7 @@ def __getitem__(self, key :slice) -> Optional[bytes]:
else:
raise ValueError("SysCommand() doesn't have key & value pairs, only slices, SysCommand('ls')[:10] as an example.")

def __repr__(self, *args :List[Any], **kwargs :Dict[str, Any]) -> str:
def __repr__(self, *args: List[Any], **kwargs: Dict[str, Any]) -> str:
return self.decode('UTF-8', errors='backslashreplace') or ''

def __json__(self) -> Dict[str, Union[str, bool, List[str], Dict[str, Any], Optional[bool], Optional[Dict[str, Any]]]]:
Expand Down Expand Up @@ -467,7 +468,7 @@ def _pid_exists(pid: int) -> bool:
return False


def run_custom_user_commands(commands :List[str], installation :Installer) -> None:
def run_custom_user_commands(commands: List[str], installation: Installer) -> None:
for index, command in enumerate(commands):
script_path = f"/var/tmp/user-command.{index}.sh"
chroot_path = f"{installation.target}/{script_path}"
Expand All @@ -481,7 +482,7 @@ def run_custom_user_commands(commands :List[str], installation :Installer) -> No
os.unlink(chroot_path)


def json_stream_to_structure(configuration_identifier : str, stream :str, target :dict) -> bool :
def json_stream_to_structure(configuration_identifier: str, stream: str, target: dict) -> bool:
"""
Load a JSON encoded dictionary from a stream and merge it into an existing dictionary.
A stream can be a filepath, a URL or a raw JSON string.
Expand Down Expand Up @@ -520,6 +521,6 @@ def json_stream_to_structure(configuration_identifier : str, stream :str, target
return True


def secret(x :str) -> str:
def secret(x: str) -> str:
""" return * with len equal to to the input string """
return '*' * len(x)
4 changes: 2 additions & 2 deletions archinstall/lib/global_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def setup_selection_menu_options(self) -> None:
self._menu_options['!root-password'] = \
Selector(
_('Root password'),
lambda preset:self._set_root_password(),
lambda preset: self._set_root_password(),
display_func=lambda x: secret(x) if x else '')
self._menu_options['!users'] = \
Selector(
Expand Down Expand Up @@ -178,7 +178,7 @@ def setup_selection_menu_options(self) -> None:
preview_func=self._prev_install_invalid_config,
no_store=True)

self._menu_options['abort'] = Selector(_('Abort'), exec_func=lambda n,v:exit(1))
self._menu_options['abort'] = Selector(_('Abort'), exec_func=lambda n, v: exit(1))

def _missing_configs(self) -> List[str]:
def check(s: str) -> bool:
Expand Down
1 change: 1 addition & 0 deletions archinstall/lib/hardware.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def gfx_packages(self) -> List[GfxPackage]:

return packages


class _SysInfo:
def __init__(self) -> None:
pass
Expand Down
2 changes: 1 addition & 1 deletion archinstall/lib/interactions/general_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def read_packages(p: list[str] = []) -> list[str]:
return packages


def add_number_of_parallel_downloads(input_number :Optional[int] = None) -> Optional[int]:
def add_number_of_parallel_downloads(input_number: Optional[int] = None) -> Optional[int]:
max_recommended = 5
print(_(f"This option enables the number of parallel downloads that can occur during package downloads"))
print(_("Enter the number of parallel downloads to be enabled.\n\nNote:\n"))
Expand Down
8 changes: 4 additions & 4 deletions archinstall/lib/locale/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ def list_x11_keyboard_languages() -> List[str]:
).decode().splitlines()


def verify_keyboard_layout(layout :str) -> bool:
def verify_keyboard_layout(layout: str) -> bool:
for language in list_keyboard_languages():
if layout.lower() == language.lower():
return True
return False


def verify_x11_keyboard_layout(layout :str) -> bool:
def verify_x11_keyboard_layout(layout: str) -> bool:
for language in list_x11_keyboard_languages():
if layout.lower() == language.lower():
return True
Expand All @@ -57,7 +57,7 @@ def get_kb_layout() -> str:
for line in lines:
if "VC Keymap: " in line:
vcline = line

if vcline == "":
return ""

Expand All @@ -68,7 +68,7 @@ def get_kb_layout() -> str:
return layout


def set_kb_layout(locale :str) -> bool:
def set_kb_layout(locale: str) -> bool:
if len(locale.strip()):
if not verify_keyboard_layout(locale):
error(f"Invalid keyboard locale specified: {locale}")
Expand Down
Loading

0 comments on commit 62b4099

Please sign in to comment.