Skip to content

Commit 7b74afd

Browse files
committed
IMPROVEMENT: activated most of ruff linting rules
ruff check --fix is awsome!
1 parent 4c58fd1 commit 7b74afd

File tree

55 files changed

+723
-484
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

55 files changed

+723
-484
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
repos:
22
- repo: https://github.com/astral-sh/ruff-pre-commit
3-
rev: v0.7.3
3+
rev: v0.8.0
44
hooks:
55
- id: ruff
66
args: [ --fix ]

MethodicConfigurator/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Python package initialization file. Loads translations and declares version information.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>

MethodicConfigurator/annotate_params.py

Lines changed: 111 additions & 62 deletions
Large diffs are not rendered by default.

MethodicConfigurator/ardupilot_methodic_configurator.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#!/usr/bin/env python3
22

33
"""
4+
The main application file. calls four sub-applications.
5+
46
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
57
68
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>
@@ -15,6 +17,7 @@
1517
from logging import getLevelName as logging_getLevelName
1618
from logging import info as logging_info
1719
from sys import exit as sys_exit
20+
from typing import Union
1821
from webbrowser import open as webbrowser_open
1922

2023
from MethodicConfigurator import _, __version__
@@ -38,6 +41,7 @@ def argument_parser() -> argparse.Namespace:
3841
3942
Returns:
4043
argparse.Namespace: An object containing the parsed arguments.
44+
4145
"""
4246
parser = argparse.ArgumentParser(
4347
description=_(
@@ -60,7 +64,7 @@ def argument_parser() -> argparse.Namespace:
6064
return add_common_arguments_and_parse(parser)
6165

6266

63-
def connect_to_fc_and_read_parameters(args) -> tuple[FlightController, str]:
67+
def connect_to_fc_and_read_parameters(args: argparse.Namespace) -> tuple[FlightController, str]:
6468
flight_controller = FlightController(args.reboot_time)
6569

6670
error_str = flight_controller.connect(args.device, log_errors=False)
@@ -86,7 +90,7 @@ def component_editor(
8690
flight_controller: FlightController,
8791
vehicle_type: str,
8892
local_filesystem: LocalFilesystem,
89-
vehicle_dir_window,
93+
vehicle_dir_window: Union[None, VehicleDirectorySelectionWindow],
9094
) -> None:
9195
component_editor_window = ComponentEditorWindow(__version__, local_filesystem)
9296
if (

MethodicConfigurator/argparse_check_range.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Check the range of an Argparse parameter.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Dmitriy Kovalev
@@ -11,15 +11,15 @@
1111
"""
1212

1313
from argparse import Action, ArgumentError, ArgumentParser, Namespace
14+
from collections.abc import Sequence
1415
from operator import ge, gt, le, lt
16+
from typing import Any, Union
1517

1618
from MethodicConfigurator import _
1719

1820

1921
class CheckRange(Action):
20-
"""
21-
Check if the Argparse argument value is within the specified range
22-
"""
22+
"""Check if the Argparse argument value is within the specified range."""
2323

2424
def __init__(self, *args, **kwargs) -> None:
2525
if "min" in kwargs and "inf" in kwargs:
@@ -52,7 +52,13 @@ def interval(self) -> str:
5252
msg = _("valid range: {_lo}, {_up}")
5353
return msg.format(**locals())
5454

55-
def __call__(self, parser: ArgumentParser, namespace: Namespace, values, option_string=None) -> None:
55+
def __call__(
56+
self,
57+
parser: ArgumentParser, # noqa: ARG002
58+
namespace: Namespace,
59+
values: Union[str, Sequence[Any], None],
60+
option_string: Union[None, str] = None, # noqa: ARG002
61+
) -> None:
5662
if not isinstance(values, (int, float)):
5763
raise ArgumentError(self, _("Value must be a number."))
5864

MethodicConfigurator/backend_filesystem.py

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Filesystem operations.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>
@@ -54,14 +54,15 @@ def is_within_tolerance(x: float, y: float, atol: float = 1e-08, rtol: float = 1
5454
the sum of the absolute tolerance (`atol`) and the product of the relative tolerance (`rtol`)
5555
and the absolute value of `y`.
5656
57-
Parameters:
58-
- x (float): The first number to compare.
59-
- y (float): The second number to compare.
60-
- atol (float, optional): The absolute tolerance. Defaults to 1e-08.
61-
- rtol (float, optional): The relative tolerance. Defaults to 1e-03.
57+
Args:
58+
x (float): The first number to compare.
59+
y (float): The second number to compare.
60+
atol (float, optional): The absolute tolerance. Defaults to 1e-08.
61+
rtol (float, optional): The relative tolerance. Defaults to 1e-03.
6262
6363
Returns:
64-
- bool: True if the difference is within the tolerance, False otherwise.
64+
bool: True if the difference is within the tolerance, False otherwise.
65+
6566
"""
6667
return abs(x - y) <= atol + (rtol * abs(y))
6768

@@ -74,12 +75,13 @@ class LocalFilesystem(VehicleComponents, ConfigurationSteps, ProgramSettings):
7475
reading parameters from files, and handling configuration steps. It is designed to simplify
7576
the interaction with the local filesystem for managing ArduPilot configuration files.
7677
77-
Attributes:
78+
Args:
7879
vehicle_dir (str): The directory path where the vehicle configuration files are stored.
7980
vehicle_type (str): The type of the vehicle (e.g., "ArduCopter", "Rover").
8081
file_parameters (dict): A dictionary of parameters read from intermediate parameter files.
8182
param_default_dict (dict): A dictionary of default parameter values.
8283
doc_dict (dict): A dictionary containing documentation for each parameter.
84+
8385
"""
8486

8587
def __init__(self, vehicle_dir: str, vehicle_type: str, fw_version: str, allow_editing_template_files: bool) -> None:
@@ -227,6 +229,7 @@ def read_params_from_files(self) -> dict[str, dict[str, "Par"]]:
227229
Returns:
228230
- Dict[str, Dict[str, 'Par']]: A dictionary with filenames as keys and as values
229231
a dictionary with (parameter names, values) pairs.
232+
230233
"""
231234
parameters: dict[str, dict[str, Par]] = {}
232235
if os_path.isdir(self.vehicle_dir):
@@ -243,18 +246,19 @@ def read_params_from_files(self) -> dict[str, dict[str, "Par"]]:
243246
return parameters
244247

245248
@staticmethod
246-
def str_to_bool(s) -> Optional[bool]:
249+
def str_to_bool(s: str) -> Optional[bool]:
247250
"""
248251
Converts a string representation of a boolean value to a boolean.
249252
250253
This function interprets the string 'true', 'yes', '1' as True, and 'false', 'no', '0' as False.
251254
Any other input will return None.
252255
253-
Parameters:
254-
- s (str): The string to convert.
256+
Args:
257+
s (str): The string to convert.
255258
256259
Returns:
257-
- Optional[bool]: True, False, or None if the string does not match any known boolean representation.
260+
Optional[bool]: True, False, or None if the string does not match any known boolean representation.
261+
258262
"""
259263
if s.lower() == "true" or s.lower() == "yes" or s.lower() == "1":
260264
return True
@@ -269,10 +273,11 @@ def export_to_param(self, params: dict[str, "Par"], filename_out: str, annotate_
269273
This function formats the provided parameters into a string suitable for a .param file,
270274
writes the string to the specified output file, and optionally updates the parameter documentation.
271275
272-
Parameters:
273-
- params (Dict[str, 'Par']): A dictionary of parameters to export.
274-
- filename_out (str): The name of the output file.
275-
- annotate_doc (bool, optional): Whether to update the parameter documentation. Defaults to True.
276+
Args:
277+
params (Dict[str, 'Par']): A dictionary of parameters to export.
278+
filename_out (str): The name of the output file.
279+
annotate_doc (bool, optional): Whether to update the parameter documentation. Defaults to True.
280+
276281
"""
277282
Par.export_to_param(Par.format_params(params), os_path.join(self.vehicle_dir, filename_out))
278283
if annotate_doc:
@@ -284,11 +289,12 @@ def vehicle_configuration_file_exists(self, filename: str) -> bool:
284289
"""
285290
Check if a vehicle configuration file exists in the vehicle directory.
286291
287-
Parameters:
288-
- filename (str): The name of the file to check.
292+
Args:
293+
filename (str): The name of the file to check.
289294
290295
Returns:
291-
- bool: True if the file exists and is a file (not a directory), False otherwise.
296+
bool: True if the file exists and is a file (not a directory), False otherwise.
297+
292298
"""
293299
return os_path.exists(os_path.join(self.vehicle_dir, filename)) and os_path.isfile(
294300
os_path.join(self.vehicle_dir, filename)
@@ -304,6 +310,7 @@ def __all_intermediate_parameter_file_comments(self) -> dict[str, str]:
304310
305311
Returns:
306312
- Dict[str, str]: A dictionary mapping parameter names to their comments.
313+
307314
"""
308315
ret = {}
309316
for params in self.file_parameters.values():
@@ -320,11 +327,12 @@ def annotate_intermediate_comments_to_param_dict(self, param_dict: dict[str, flo
320327
intermediate parameter files to create a new dictionary where each parameter is represented
321328
by a 'Par' object containing both the value and the comment.
322329
323-
Parameters:
324-
- param_dict (Dict[str, float]): A dictionary of parameters with only values.
330+
Args:
331+
param_dict (Dict[str, float]): A dictionary of parameters with only values.
325332
326333
Returns:
327-
- Dict[str, 'Par']: A dictionary of parameters with intermediate parameter file comments.
334+
Dict[str, 'Par']: A dictionary of parameters with intermediate parameter file comments.
335+
328336
"""
329337
ret = {}
330338
ip_comments = self.__all_intermediate_parameter_file_comments()
@@ -341,12 +349,13 @@ def categorize_parameters(self, param: dict[str, "Par"]) -> tuple[dict[str, "Par
341349
- Non-default, writable calibrations
342350
- Non-default, writable non-calibrations
343351
344-
Parameters:
345-
- param (Dict[str, 'Par']): A dictionary mapping parameter names to their 'Par' objects.
352+
Args:
353+
param (Dict[str, 'Par']): A dictionary mapping parameter names to their 'Par' objects.
346354
347355
Returns:
348-
- Tuple[Dict[str, "Par"], Dict[str, "Par"], Dict[str, "Par"]]: A tuple of three dictionaries.
356+
Tuple[Dict[str, "Par"], Dict[str, "Par"], Dict[str, "Par"]]: A tuple of three dictionaries.
349357
Each dictionary represents one of the categories mentioned above.
358+
350359
"""
351360
non_default__read_only_params = {}
352361
non_default__writable_calibrations = {}
@@ -374,9 +383,7 @@ def get_directory_name_from_full_path(full_path: str) -> str:
374383
normalized_path = os_path.normpath(full_path)
375384

376385
# Split the path into head and tail, then get the basename of the tail
377-
directory_name = os_path.basename(os_path.split(normalized_path)[1])
378-
379-
return directory_name
386+
return os_path.basename(os_path.split(normalized_path)[1])
380387

381388
# Extract the vehicle name from the directory path
382389
def get_vehicle_directory_name(self) -> str:
@@ -390,7 +397,7 @@ def zip_file_exists(self) -> bool:
390397
zip_file_path = self.zip_file_path()
391398
return os_path.exists(zip_file_path) and os_path.isfile(zip_file_path)
392399

393-
def add_configuration_file_to_zip(self, zipf, filename) -> None:
400+
def add_configuration_file_to_zip(self, zipf: ZipFile, filename: str) -> None:
394401
if self.vehicle_configuration_file_exists(filename):
395402
zipf.write(os_path.join(self.vehicle_dir, filename), arcname=filename)
396403

@@ -403,9 +410,10 @@ def zip_files(self, files_to_zip: list[tuple[bool, str]]) -> None:
403410
intermediate parameter files. The method checks for the existence of each file before
404411
attempting to add it to the zip archive.
405412
406-
Parameters:
407-
- files_to_zip (List[Tuple[bool, str]]): A list of tuples, where each tuple contains a boolean
413+
Args:
414+
files_to_zip (List[Tuple[bool, str]]): A list of tuples, where each tuple contains a boolean
408415
indicating if the file was written and a string for the filename.
416+
409417
"""
410418
zip_file_path = self.zip_file_path()
411419
with ZipFile(zip_file_path, "w") as zipf:

MethodicConfigurator/backend_filesystem_configuration_steps.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Manages configuration steps at the filesystem level.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>
@@ -32,6 +32,7 @@ class ConfigurationSteps:
3232
Attributes:
3333
configuration_steps_filename (str): The name of the file containing documentation for the configuration files.
3434
configuration_steps (dict): A dictionary containing the configuration steps.
35+
3536
"""
3637

3738
def __init__(self, _vehicle_dir: str, vehicle_type: str) -> None:

MethodicConfigurator/backend_filesystem_program_settings.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Manages program settings at the filesystem level.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>
@@ -79,11 +79,12 @@ def valid_directory_name(dir_name: str) -> bool:
7979
invalid for directory names in many operating systems. It does not guarantee that the name
8080
is valid in all contexts or operating systems, as directory name validity can vary.
8181
82-
Parameters:
83-
- dir_name (str): The directory name to check.
82+
Args:
83+
dir_name (str): The directory name to check.
8484
8585
Returns:
86-
- bool: True if the directory name matches the allowed pattern, False otherwise.
86+
bool: True if the directory name matches the allowed pattern, False otherwise.
87+
8788
"""
8889
# Include os.sep in the pattern
8990
pattern = r"^[\w" + re_escape(os_sep) + "-]+$"
@@ -100,7 +101,7 @@ def __user_config_dir() -> str:
100101
error_msg = _("The path '{user_config_directory}' is not a directory.")
101102
raise NotADirectoryError(error_msg.format(**locals()))
102103

103-
return user_config_directory # type: ignore[no-any-return] # workaround a mypy bug
104+
return user_config_directory
104105

105106
@staticmethod
106107
def __site_config_dir() -> str:
@@ -115,7 +116,7 @@ def __site_config_dir() -> str:
115116
error_msg = _("The path '{site_config_directory}' is not a directory.")
116117
raise NotADirectoryError(error_msg.format(**locals()))
117118

118-
return site_config_directory # type: ignore[no-any-return] # workaround a mypy bug
119+
return site_config_directory
119120

120121
@staticmethod
121122
def __get_settings_as_dict() -> dict[str, Any]:
@@ -151,7 +152,7 @@ def __get_settings_as_dict() -> dict[str, Any]:
151152
return settings
152153

153154
@staticmethod
154-
def __set_settings_from_dict(settings) -> None:
155+
def __set_settings_from_dict(settings: dict) -> None:
155156
settings_path = os_path.join(ProgramSettings.__user_config_dir(), "settings.json")
156157

157158
with open(settings_path, "w", encoding="utf-8") as settings_file:

MethodicConfigurator/backend_filesystem_vehicle_components.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
#!/usr/bin/env python3
2-
31
"""
2+
Manages vehicle components at the filesystem level.
3+
44
This file is part of Ardupilot methodic configurator. https://github.com/ArduPilot/MethodicConfigurator
55
66
SPDX-FileCopyrightText: 2024 Amilcar do Carmo Lucas <[email protected]>
@@ -52,7 +52,7 @@ def load_vehicle_components_json_data(self, vehicle_dir: str) -> dict[Any, Any]:
5252
self.vehicle_components = data
5353
return data
5454

55-
def save_vehicle_components_json_data(self, data, vehicle_dir: str) -> bool:
55+
def save_vehicle_components_json_data(self, data: dict, vehicle_dir: str) -> bool:
5656
filepath = os_path.join(vehicle_dir, self.vehicle_components_json_filename)
5757
try:
5858
with open(filepath, "w", encoding="utf-8") as file:

0 commit comments

Comments
 (0)