Skip to content

Commit

Permalink
Integrated mypy and further clean up of build scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
Rexeh committed Nov 25, 2023
1 parent 263fc84 commit 283cf44
Show file tree
Hide file tree
Showing 11 changed files with 124 additions and 139 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ temp/
/notebooks
/logs/*
/src/joystick_diagrams/logs*
*.egg-info/

# IDE
*.code-workspace
Expand Down
80 changes: 0 additions & 80 deletions build.py

This file was deleted.

58 changes: 28 additions & 30 deletions joystick_diagrams/adaptors/dcs_world.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
"""DCS World Lua Config Parser for use with Joystick Diagrams"""
from ast import Str
import os
import re
from pathlib import Path
import logging
from ply import lex, yacc

from ply import lex, yacc # type: ignore
import joystick_diagrams.adaptors.dcs_world_lex # pylint: disable=unused-import
import joystick_diagrams.adaptors.dcs_world_yacc # pylint: disable=unused-import
import joystick_diagrams.adaptors.joystick_diagram_interface as jdi
Expand Down Expand Up @@ -38,14 +36,14 @@ def __validate_base_directory(self) -> list:
else:
raise FileNotFoundError("DCS: No Config Folder found in DCS Folder.")

def __validate_profiles(self) -> list:
def __validate_profiles(self) -> list[str]:
"""
Validate Profiles Routine
"""
if len(self.base_directory) == 0:
raise FileExistsError("DCS: No profiles exist in Input directory!")

valid_items = list()
valid_items = []
for item in self.base_directory:
valid = self.__validate_profile(item)
if valid:
Expand All @@ -55,7 +53,7 @@ def __validate_profiles(self) -> list:

return valid_items

def __validate_profile(self, item):
def __validate_profile(self, item: str) -> list | bool:
"""
Validate Inidividual Profile
Return Valid Profile
Expand All @@ -68,7 +66,7 @@ def __validate_profile(self, item):

return False

def get_validated_profiles(self):
def get_validated_profiles(self) -> list[str]:
"""Expose Valid Profiles only to UI"""
if self.remove_easy_modes:
return list(
Expand All @@ -85,20 +83,21 @@ def convert_button_format(self, button) -> str:

match len(split):
case 2:
if len(split) == 2:
if split[1][0:3] == "BTN":
return split[1].replace("BTN", "BUTTON_")
elif split[1].isalpha():
return f"AXIS_{split[1]}"
elif split[1][0:6] == "SLIDER":
return f"AXIS_SLIDER_{split[1][6:]}"
else:
return split[1]
## Add default case / better handling
if split[1][0:3] == "BTN":
return f"{split[1].replace('BTN', 'BUTTON_')}"
elif split[1].isalpha():
return f"AXIS_{split[1]}"
elif split[1][0:6] == "SLIDER":
return f"AXIS_SLIDER_{split[1][6:]}"
else:
return f"{split[1]}"
case 4:
return f"{split[1].replace('BTN', 'POV')}_{split[2][3]}_{split[3]}"
case _:
_logger.warning(f"Button format not found for {split}")
return f"{button}"

def process_profiles(self, profile_list: list = None) -> dict:
def process_profiles(self, profile_list: list | None = None) -> dict:
if isinstance(profile_list, list) and len(profile_list) > 0:
self.profiles_to_process = profile_list
else:
Expand All @@ -119,19 +118,20 @@ def process_profiles(self, profile_list: list = None) -> dict:
_logger.info("Skipping as Folder")
else:
try:
_logger.debug(f"Obtaining file data for {joystick_file}")
file_data = (
Path(os.path.join(self.fq_path, joystick_file))
.read_text(encoding="utf-8")
.replace("local diff = ", "")
.replace("return diff", "")
)

except FileNotFoundError:
raise FileExistsError(
"DCS: File {} no longer found - It has been moved/deleted from directory".format(
joystick_file
)
except FileNotFoundError as err:
_logger.error(
f"DCS: File {joystick_file} no longer found - It has been moved/deleted from directory. {err}"
)
raise

else:
parsed_config = self.parse_config(file_data) ##Better handling - decompose

Expand All @@ -143,10 +143,11 @@ def process_profiles(self, profile_list: list = None) -> dict:
self.update_joystick_dictionary(joystick_device, profile, False, button_map)
return self.joystick_dictionary

def parse_config(self, file: Str):
def parse_config(self, file: str):
try:
return self.parse_file(file)
except Exception as error:
_logger.error("There was a parsing issue with the text data, this could mean an unhandled character.")
_logger.error(error)
return None

Expand Down Expand Up @@ -179,7 +180,7 @@ def create_joystick_map(self, data) -> dict:
write_val = False
return button_array

def parse_file(self, file: Str) -> dict:
def parse_file(self, file: str) -> dict:
# pylint: disable=unused-variable
tokens = (
"LCURLY",
Expand Down Expand Up @@ -271,14 +272,11 @@ def p_error(t): # pylint: disable=invalid-name

# Build the lexer
lexer = lex.lex(
debug=False,
optimize=1,
lextab="dcs_world_lex",
reflags=re.UNICODE | re.VERBOSE,
debug=False, optimize=1, lextab="dcs_world_lex", reflags=re.UNICODE | re.VERBOSE, errorlog=_logger
)

# Build the parser
parser = yacc.yacc(debug=False, optimize=1, tabmodule="dcs_world_yacc")
parser = yacc.yacc(debug=False, optimize=1, tabmodule="dcs_world_yacc", errorlog=_logger)

# Parse the data
try:
Expand Down
26 changes: 17 additions & 9 deletions joystick_diagrams/classes/input.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
import logging

_logger = logging.getLogger(__name__)
_devices = {}

print(__name__)


@dataclass
Expand All @@ -39,12 +36,16 @@ def validate(identifier):


class Input:
def __init__(self, identifier: str, style: InputTypes, command: Command, modifiers: list[Modifier] = None) -> None:
# Rework input
# Better naming of the entities
# Change input to non conflciting class

def __init__(self, identifier: str, style: InputTypes, command: Command, modifiers: list[Modifier] = []) -> None:
style.validate(identifier)
self.identifier = identifier
self.style = style
self.command = command
self.modifiers = modifiers = [] if modifiers is None else modifiers
self.modifiers = modifiers

def add_modifier(self, modifier: set, command: Command):
"""
Expand Down Expand Up @@ -75,7 +76,7 @@ class LogicalDevice:
def __init__(self, guid: str, name: str):
self.guid = guid.strip().lower()
self.name = name.strip().lower()
self.inputs = []
self.inputs: list[Input] = []

def create_input(self, input_id: str, style: InputTypes, command: Command) -> None:
existing = self.__check_existing_input(input_id, style)
Expand All @@ -94,7 +95,7 @@ def _get_input(self, input_id: str) -> Input | None:
return x
return None

def get_device_inputs(self) -> dict:
def get_device_inputs(self) -> list[Input]:
return self.inputs

def add_modifier_to_input(self, input_id, modifier: set, command: Command) -> None:
Expand All @@ -109,7 +110,8 @@ def add_modifier_to_input(self, input_id, modifier: set, command: Command) -> No
self.create_input(input_id, InputTypes.BUTTON, "Not Used")
obj = self._get_input(input_id)
_logger.debug(f"Modifier input created now: {obj}")
obj.add_modifier(modifier, command)
else:
obj.add_modifier(modifier, command)

def __check_existing_input(self, input_id: str, style: InputTypes) -> Input | None:
"""
Expand Down Expand Up @@ -149,8 +151,14 @@ def add_device(guid: str, name: str) -> LogicalDevice:


def add_input_modifier(guid: str, input_id: str, modifier: set, command: Command) -> None:
_get_device(guid).add_modifier_to_input(input_id, modifier, command)
try:
_get_device(guid).add_modifier_to_input(input_id, modifier, command)
except:
pass


def add_inputs(guid: str, **kwargs) -> None:
_devices[guid].create_input(**kwargs)


_devices = {}
12 changes: 6 additions & 6 deletions joystick_diagrams/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ def __str__(self):
# -----------------------------------------------------------------------------


class directory_not_valid(JoystickDiagramsException):
def __init__(self, value):
class DirectoryNotValid(JoystickDiagramsException):
def __init__(self, value=""):
super().__init__(value)


class file_not_valid(JoystickDiagramsException):
class FileNotValid(JoystickDiagramsException):
def __init__(self, value=""):
super().__init__(value)

def __str__(self):
return repr("File was invalid: " + self.value)


class file_type_invalid(JoystickDiagramsException):
class FileTypeInvalid(JoystickDiagramsException):
def __init__(self, value="Default"):
super().__init__(value)

Expand All @@ -34,7 +34,7 @@ def __init__(self, value="Default"):
# -----------------------------------------------------------------------------


class plugin_not_valid(JoystickDiagramsException):
class PluginNotValid(JoystickDiagramsException):
def __init__(self, value="", error=""):
super().__init__(value)
self.error = error
Expand All @@ -43,7 +43,7 @@ def __str__(self):
return repr(f"Plugin {self.value} loaded was invalid: {self.error}")


class no_plugins_exist(JoystickDiagramsException):
class NoPluginsExist(JoystickDiagramsException):
def __init__(self, value=""):
super().__init__(value)

Expand Down
8 changes: 4 additions & 4 deletions joystick_diagrams/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@ def __init__(self):
try:
# Try initiate the plugin
self._plugins.append(self.load_plugin(plugin))
except exp.plugin_not_valid as e:
except exp.PluginNotValid as e:
_logger.error(e)
else:
raise exp.no_plugins_exist()
raise exp.NoPluginsExist()

def load_plugin(self, module_path: str) -> ModuleType:
"""Attempt to load the plugin"""
try:
# Todo make nicer the joining of relative pathing...
return import_module("." + module_path + ".main", "joystick_diagrams.plugins").CustomPlugin()
except TypeError as e:
raise exp.plugin_not_valid(error=e) from e
raise exp.PluginNotValid(error=e) from e
except ModuleNotFoundError as e:
raise exp.plugin_not_valid(value=module_path, error=e) from e
raise exp.PluginNotValid(value=module_path, error=e) from e

def find_plugins(self, directory="plugins") -> list:
"""
Expand Down
3 changes: 1 addition & 2 deletions joystick_diagrams/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
Author: Robert Cox
"""
import requests
from dataclasses import dataclass

VERSION = "1.4.1"
VERSION = "1.5"
VERSION_SERVER = "http://localhost:5000/api/v1/version/"


Expand Down
Loading

0 comments on commit 283cf44

Please sign in to comment.