Skip to content

Commit

Permalink
FIX: more ruff and mypy linting
Browse files Browse the repository at this point in the history
  • Loading branch information
amilcarlucas committed Nov 18, 2024
1 parent eecb837 commit 54c531c
Show file tree
Hide file tree
Showing 45 changed files with 423 additions and 408 deletions.
10 changes: 5 additions & 5 deletions MethodicConfigurator/annotate_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class Par:
comment (Optional[str]): An optional comment associated with the parameter.
"""

def __init__(self, value: float, comment: Optional[str] = None):
def __init__(self, value: float, comment: Optional[str] = None) -> None:
self.value = value
self.comment = comment

Expand Down Expand Up @@ -184,7 +184,7 @@ def load_param_file_into_dict(param_file: str) -> dict[str, "Par"]:
return parameter_dict

@staticmethod
def validate_parameter(param_file, parameter_dict, i, original_line, comment, parameter, value): # pylint: disable=too-many-arguments
def validate_parameter(param_file, parameter_dict, i, original_line, comment, parameter, value) -> None: # pylint: disable=too-many-arguments
if len(parameter) > PARAM_NAME_MAX_LEN:
raise SystemExit(f"Too long parameter name: {parameter} in {param_file} line {i}")
if not re.match(PARAM_NAME_REGEX, parameter):
Expand Down Expand Up @@ -646,7 +646,7 @@ def update_parameter_documentation_file( # pylint: disable=too-many-locals, too
param_file,
lines,
delete_documentation_annotations: bool,
):
) -> None:
new_lines = []
if os_path.basename(param_file).endswith("16_pid_adjustment.param"):
new_lines.extend(lines[0:5]) # copy the first 6 lines verbatim
Expand Down Expand Up @@ -703,7 +703,7 @@ def update_parameter_documentation_file( # pylint: disable=too-many-locals, too
file.writelines(new_lines)


def print_read_only_params(doc):
def print_read_only_params(doc) -> None:
"""
Print the names of read-only parameters.
Expand Down Expand Up @@ -751,7 +751,7 @@ def parse_parameter_metadata(
return create_doc_dict(xml_root, vehicle_type, max_line_length)


def main():
def main() -> None:
args = arg_parser()
try:
xml_url = get_xml_url(args.vehicle_type, args.firmware_version)
Expand Down
6 changes: 3 additions & 3 deletions MethodicConfigurator/argparse_check_range.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
https://gist.github.com/dmitriykovalev/2ab1aa33a8099ef2d514925d84aa89e7
"""

from argparse import Action, ArgumentError
from argparse import Action, ArgumentError, ArgumentParser, Namespace
from operator import ge, gt, le, lt

from MethodicConfigurator import _
Expand All @@ -21,7 +21,7 @@ class CheckRange(Action):
Check if the Argparse argument value is within the specified range
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
if "min" in kwargs and "inf" in kwargs:
raise ValueError(_("either min or inf, but not both"))
if "max" in kwargs and "sup" in kwargs:
Expand Down Expand Up @@ -52,7 +52,7 @@ def interval(self):
msg = _("valid range: {_lo}, {_up}")
return msg.format(**locals())

def __call__(self, parser, namespace, values, option_string=None):
def __call__(self, parser: ArgumentParser, namespace: Namespace, values, option_string=None) -> None:
if not isinstance(values, (int, float)):
raise ArgumentError(self, _("Value must be a number."))

Expand Down
31 changes: 17 additions & 14 deletions MethodicConfigurator/backend_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

# from sys import exit as sys_exit
from argparse import ArgumentParser
from logging import debug as logging_debug
from logging import error as logging_error
from logging import info as logging_info
Expand All @@ -21,7 +22,7 @@
from re import compile as re_compile
from shutil import copy2 as shutil_copy2
from shutil import copytree as shutil_copytree
from typing import Any
from typing import Any, Optional
from zipfile import ZipFile

from requests import get as requests_get # type: ignore[import-untyped]
Expand Down Expand Up @@ -81,7 +82,7 @@ class LocalFilesystem(VehicleComponents, ConfigurationSteps, ProgramSettings):
doc_dict (dict): A dictionary containing documentation for each parameter.
"""

def __init__(self, vehicle_dir: str, vehicle_type: str, fw_version: str, allow_editing_template_files: bool):
def __init__(self, vehicle_dir: str, vehicle_type: str, fw_version: str, allow_editing_template_files: bool) -> None:
self.file_parameters: dict[str, dict[str, Par]] = {}
VehicleComponents.__init__(self)
ConfigurationSteps.__init__(self, vehicle_dir, vehicle_type)
Expand All @@ -95,7 +96,7 @@ def __init__(self, vehicle_dir: str, vehicle_type: str, fw_version: str, allow_e
if vehicle_dir is not None:
self.re_init(vehicle_dir, vehicle_type)

def re_init(self, vehicle_dir: str, vehicle_type: str):
def re_init(self, vehicle_dir: str, vehicle_type: str) -> None:
self.vehicle_dir = vehicle_dir
self.doc_dict = {}

Expand Down Expand Up @@ -149,7 +150,7 @@ def vehicle_configuration_files_exist(self, vehicle_dir: str) -> bool:
return True
return False

def rename_parameter_files(self):
def rename_parameter_files(self) -> None:
if self.vehicle_dir is None or self.configuration_steps is None:
return
# Rename parameter files if some new files got added to the vehicle directory
Expand All @@ -170,7 +171,7 @@ def rename_parameter_files(self):
os_rename(old_filename_path, new_filename_path)
logging_info("Renamed %s to %s", old_filename, new_filename)

def __extend_and_reformat_parameter_documentation_metadata(self): # pylint: disable=too-many-branches
def __extend_and_reformat_parameter_documentation_metadata(self) -> None: # pylint: disable=too-many-branches
for param_name, param_info in self.doc_dict.items():
if "fields" in param_info:
param_fields = param_info["fields"]
Expand Down Expand Up @@ -242,7 +243,7 @@ def read_params_from_files(self) -> dict[str, dict[str, "Par"]]:
return parameters

@staticmethod
def str_to_bool(s):
def str_to_bool(s) -> Optional[bool]:
"""
Converts a string representation of a boolean value to a boolean.
Expand Down Expand Up @@ -389,11 +390,11 @@ def zip_file_exists(self):
zip_file_path = self.zip_file_path()
return os_path.exists(zip_file_path) and os_path.isfile(zip_file_path)

def add_configuration_file_to_zip(self, zipf, filename):
def add_configuration_file_to_zip(self, zipf, filename) -> None:
if self.vehicle_configuration_file_exists(filename):
zipf.write(os_path.join(self.vehicle_dir, filename), arcname=filename)

def zip_files(self, files_to_zip: list[tuple[bool, str]]):
def zip_files(self, files_to_zip: list[tuple[bool, str]]) -> None:
"""
Zips the intermediate parameter files that were written to, including specific summary files.
Expand Down Expand Up @@ -442,14 +443,14 @@ def vehicle_image_exists(self):
return os_path.exists(self.vehicle_image_filepath()) and os_path.isfile(self.vehicle_image_filepath())

@staticmethod
def new_vehicle_dir(base_dir: str, new_dir: str):
def new_vehicle_dir(base_dir: str, new_dir: str) -> str:
return os_path.join(base_dir, new_dir)

@staticmethod
def directory_exists(directory: str) -> bool:
return os_path.exists(directory) and os_path.isdir(directory)

def copy_template_files_to_new_vehicle_dir(self, template_dir: str, new_vehicle_dir: str):
def copy_template_files_to_new_vehicle_dir(self, template_dir: str, new_vehicle_dir: str) -> None:
# Copy the template files to the new vehicle directory
for item in os_listdir(template_dir):
if item in {"apm.pdef.xml", "vehicle.jpg", "last_uploaded_filename.txt", "tempcal_acc.png", "tempcal_gyro.png"}:
Expand All @@ -462,7 +463,7 @@ def copy_template_files_to_new_vehicle_dir(self, template_dir: str, new_vehicle_
shutil_copy2(s, d)

@staticmethod
def getcwd():
def getcwd() -> str:
return os_getcwd()

def tempcal_imu_result_param_tuple(self):
Expand All @@ -480,7 +481,7 @@ def copy_fc_values_to_file(self, selected_file: str, params: dict[str, float]):
logging_warning(_("Parameter %s not found in the current parameter file"), param)
return ret

def write_last_uploaded_filename(self, current_file: str):
def write_last_uploaded_filename(self, current_file: str) -> None:
try:
with open(os_path.join(self.vehicle_dir, "last_uploaded_filename.txt"), "w", encoding="utf-8") as file:
file.write(current_file)
Expand Down Expand Up @@ -577,7 +578,9 @@ def write_param_default_values(self, param_default_values: dict[str, "Par"]) ->
return True
return False

def write_param_default_values_to_file(self, param_default_values: dict[str, "Par"], filename: str = "00_default.param"):
def write_param_default_values_to_file(
self, param_default_values: dict[str, "Par"], filename: str = "00_default.param"
) -> None:
if self.write_param_default_values(param_default_values):
Par.export_to_param(Par.format_params(self.param_default_dict), os_path.join(self.vehicle_dir, filename))

Expand Down Expand Up @@ -622,7 +625,7 @@ def download_file_from_url(url: str, local_filename: str, timeout: int = 5) -> b
return False

@staticmethod
def add_argparse_arguments(parser):
def add_argparse_arguments(parser: ArgumentParser) -> ArgumentParser:
parser.add_argument(
"-t",
"--vehicle-type",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ class ConfigurationSteps:
configuration_steps (dict): A dictionary containing the configuration steps.
"""

def __init__(self, _vehicle_dir: str, vehicle_type: str):
def __init__(self, _vehicle_dir: str, vehicle_type: str) -> None:
self.configuration_steps_filename = "configuration_steps_" + vehicle_type + ".json"
self.configuration_steps: dict[str, dict] = {}
self.forced_parameters: dict[str, dict] = {}
self.derived_parameters: dict[str, dict] = {}
self.log_loaded_file = False

def re_init(self, vehicle_dir: str, vehicle_type: str):
def re_init(self, vehicle_dir: str, vehicle_type: str) -> None:
if vehicle_type == "":
return
self.configuration_steps_filename = "configuration_steps_" + vehicle_type + ".json"
Expand Down
30 changes: 15 additions & 15 deletions MethodicConfigurator/backend_filesystem_program_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,21 @@ class ProgramSettings:
validation of directory names according to specific rules.
"""

def __init__(self):
def __init__(self) -> None:
pass

@staticmethod
def application_icon_filepath():
def application_icon_filepath() -> str:
script_dir = os_path.dirname(os_path.abspath(__file__))
return os_path.join(script_dir, "ArduPilot_icon.png")

@staticmethod
def application_logo_filepath():
def application_logo_filepath() -> str:
script_dir = os_path.dirname(os_path.abspath(__file__))
return os_path.join(script_dir, "ArduPilot_logo.png")

@staticmethod
def create_new_vehicle_dir(new_vehicle_dir: str):
def create_new_vehicle_dir(new_vehicle_dir: str) -> str:
# Check if the new vehicle directory already exists
if os_path.exists(new_vehicle_dir):
return _("Directory already exists, choose a different one")
Expand All @@ -64,7 +64,7 @@ def create_new_vehicle_dir(new_vehicle_dir: str):
return ""

@staticmethod
def valid_directory_name(dir_name: str):
def valid_directory_name(dir_name: str) -> bool:
"""
Check if a given directory name contains only alphanumeric characters, underscores, hyphens,
and the OS directory separator.
Expand All @@ -84,7 +84,7 @@ def valid_directory_name(dir_name: str):
return re_match(pattern, dir_name) is not None

@staticmethod
def __user_config_dir():
def __user_config_dir() -> str:
user_config_directory = user_config_dir(".ardupilot_methodic_configurator", False, roaming=True, ensure_exists=True)

if not os_path.exists(user_config_directory):
Expand All @@ -97,7 +97,7 @@ def __user_config_dir():
return user_config_directory

@staticmethod
def __site_config_dir():
def __site_config_dir() -> str:
site_config_directory = site_config_dir(
".ardupilot_methodic_configurator", False, version=None, multipath=False, ensure_exists=True
)
Expand Down Expand Up @@ -140,14 +140,14 @@ def __get_settings_as_dict() -> dict[str, Any]:
return settings

@staticmethod
def __set_settings_from_dict(settings):
def __set_settings_from_dict(settings) -> None:
settings_path = os_path.join(ProgramSettings.__user_config_dir(), "settings.json")

with open(settings_path, "w", encoding="utf-8") as settings_file:
json_dump(settings, settings_file, indent=4)

@staticmethod
def __get_settings_config():
def __get_settings_config() -> tuple[dict[str, Any], str, str]:
settings = ProgramSettings.__get_settings_as_dict()

# Regular expression pattern to match single backslashes
Expand All @@ -158,7 +158,7 @@ def __get_settings_config():
return settings, pattern, replacement

@staticmethod
def store_recently_used_template_dirs(template_dir: str, new_base_dir: str):
def store_recently_used_template_dirs(template_dir: str, new_base_dir: str) -> None:
settings, pattern, replacement = ProgramSettings.__get_settings_config()

# Update the settings with the new values
Expand All @@ -172,7 +172,7 @@ def store_recently_used_template_dirs(template_dir: str, new_base_dir: str):
ProgramSettings.__set_settings_from_dict(settings)

@staticmethod
def store_template_dir(relative_template_dir: str):
def store_template_dir(relative_template_dir: str) -> None:
settings, pattern, replacement = ProgramSettings.__get_settings_config()

template_dir = os_path.join(ProgramSettings.get_templates_base_dir(), relative_template_dir)
Expand All @@ -183,7 +183,7 @@ def store_template_dir(relative_template_dir: str):
ProgramSettings.__set_settings_from_dict(settings)

@staticmethod
def store_recently_used_vehicle_dir(vehicle_dir: str):
def store_recently_used_vehicle_dir(vehicle_dir: str) -> None:
settings, pattern, replacement = ProgramSettings.__get_settings_config()

# Update the settings with the new values
Expand All @@ -192,7 +192,7 @@ def store_recently_used_vehicle_dir(vehicle_dir: str):
ProgramSettings.__set_settings_from_dict(settings)

@staticmethod
def get_templates_base_dir():
def get_templates_base_dir() -> str:
current_dir = os_path.dirname(os_path.abspath(__file__))
if platform_system() == "Windows":
site_directory = ProgramSettings.__site_config_dir()
Expand All @@ -209,7 +209,7 @@ def get_templates_base_dir():
return os_path.join(site_directory, "vehicle_templates")

@staticmethod
def get_recently_used_dirs():
def get_recently_used_dirs() -> tuple[str, str, str]:
template_default_dir = os_path.join(
ProgramSettings.get_templates_base_dir(), "ArduCopter", "diatone_taycan_mxc", "4.5.x-params"
)
Expand All @@ -232,7 +232,7 @@ def display_usage_popup(ptype: str) -> bool:
return bool(display_usage_popup_settings.get(ptype, True))

@staticmethod
def set_display_usage_popup(ptype: str, value: bool):
def set_display_usage_popup(ptype: str, value: bool) -> None:
if ptype in {"component_editor", "parameter_editor"}:
settings, _, _ = ProgramSettings.__get_settings_config()
settings["display_usage_popup"][ptype] = value
Expand Down
6 changes: 3 additions & 3 deletions MethodicConfigurator/backend_filesystem_vehicle_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class VehicleComponents:
vehicle components configurations from a JSON file.
"""

def __init__(self):
def __init__(self) -> None:
self.vehicle_components_json_filename = "vehicle_components.json"
self.vehicle_components = None

Expand Down Expand Up @@ -89,11 +89,11 @@ def get_fc_fw_version_from_vehicle_components_json(self) -> str:
return ""

@staticmethod
def supported_vehicles():
def supported_vehicles() -> list[str]:
return ["AP_Periph", "AntennaTracker", "ArduCopter", "ArduPlane", "ArduSub", "Blimp", "Heli", "Rover", "SITL"]

@staticmethod
def get_vehicle_components_overviews():
def get_vehicle_components_overviews() -> dict[str, TemplateOverview]:
"""
Finds all subdirectories of base_dir containing a "vehicle_components.json" file,
creates a dictionary where the keys are the subdirectory names (relative to base_dir)
Expand Down
Loading

0 comments on commit 54c531c

Please sign in to comment.