Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,14 @@ filterwarnings = "ignore::DeprecationWarning"

[tool.ruff]
line-length = 120
exclude = [
"tests/od/**",
]

[tool.ruff.lint.per-file-ignores]
"tests/*" = [
"S101", # Allow use of assert statements in tests
]
"tests/test_imports.py" = [
"F401", # Allow unused imports in this file
]
16 changes: 6 additions & 10 deletions src/objdictgen/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def inner(*args, **kw):
opts = DebugOpts()
try:
return fn(opts, *args, **kw)
except Exception as exc: # pylint: disable=broad-except
except Exception as exc:
if opts.show_debug:
raise
print(f"{ODG_PROGRAM}: {exc.__class__.__name__}: {exc}")
Expand Down Expand Up @@ -212,8 +212,8 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
if opts.command == "help":
if opts.subcommand:
for subparsers_action in (
a for a in parser._actions # pylint: disable=protected-access
if isinstance(a, argparse._SubParsersAction) # pylint: disable=protected-access
a for a in parser._actions
if isinstance(a, argparse._SubParsersAction)
):
for choice, subparser in subparsers_action.choices.items():
if choice != opts.subcommand:
Expand Down Expand Up @@ -294,8 +294,7 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
elif opts.command == "edit":

# Import here to prevent including optional UI components for cmd-line use
from .ui.objdictedit import \
uimain # pylint: disable=import-outside-toplevel
from .ui.objdictedit import uimain
uimain(opts.od)


Expand All @@ -322,17 +321,15 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):
elif opts.command == "network":

# Import here to prevent including optional UI components for cmd-line use
from .ui.networkedit import \
uimain # pylint: disable=import-outside-toplevel
from .ui.networkedit import uimain
uimain(opts.dir)


# -- NODELIST command --
elif opts.command == "nodelist":

# Import here to prevent including optional UI components for cmd-line use
from .nodelist import \
main as _main # pylint: disable=import-outside-toplevel
from .nodelist import main as _main
_main(opts.dir)


Expand All @@ -342,5 +339,4 @@ def main(debugopts: DebugOpts, args: Sequence[str]|None = None):

# To support -m objdictgen
if __name__ == '__main__':
# pylint: disable=no-value-for-parameter
main()
7 changes: 3 additions & 4 deletions src/objdictgen/eds_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@
}

# Function for verifying data values
is_integer = lambda x: isinstance(x, int) # pylint: disable=unnecessary-lambda-assignment
is_string = lambda x: isinstance(x, str) # pylint: disable=unnecessary-lambda-assignment
is_boolean = lambda x: x in (0, 1) # pylint: disable=unnecessary-lambda-assignment
is_integer = lambda x: isinstance(x, int) # noqa: E731
is_string = lambda x: isinstance(x, str) # noqa: E731
is_boolean = lambda x: x in (0, 1) # noqa: E731

# Define checking of value for each attribute
ENTRY_ATTRIBUTES: dict[str, Callable[[Any], bool]] = {
Expand Down Expand Up @@ -505,7 +505,6 @@ def generate_eds_content(node: Node, filepath: TPath):
entries = list(node)

# FIXME: Too many camelCase vars in here
# pylint: disable=invalid-name

try:
value = node.GetEntry(0x1018)
Expand Down
3 changes: 1 addition & 2 deletions src/objdictgen/gen_cfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def text(self, s: str = "") -> Text:
# FIXME: Delete this method when everything is converted to f-strings
def ftext(self, s: str) -> Text:
"""Format a text string."""
return Text(self, "").__imod__(s) # pylint: disable=unnecessary-dunder-call
return Text(self, "").__imod__(s)

def get_valid_type_infos(self, typename: str, items=None) -> TypeInfos:
"""Get valid type infos from a typename.
Expand Down Expand Up @@ -191,7 +191,6 @@ def generate_file_content(node: NodeProtocol, headerfile: str, pointers_dict=Non
"""

# FIXME: Too many camelCase vars in here
# pylint: disable=invalid-name

# Setup the main context to store the data
ctx = CFileContext()
Expand Down
26 changes: 18 additions & 8 deletions src/objdictgen/jsonod.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,25 @@
import jsonschema

import objdictgen

# Accessed by node.py, so we need to import node as module to avoid circular references
from objdictgen import maps
from objdictgen import node as nodelib
from objdictgen.maps import OD, ODMapping, ODMappingList
from objdictgen.typing import (TDiffNodes, TIndexEntry, TODJson, TODObj,
TODObjJson, TODSubObj, TODSubObjJson, TODValue,
TParamEntry, TPath, TProfileMenu)
from objdictgen.utils import (copy_in_order, exc_amend, maybe_number,
str_to_int, strip_brackets)
from objdictgen.typing import (
TDiffNodes,
TIndexEntry,
TODJson,
TODObj,
TODObjJson,
TODSubObj,
TODSubObjJson,
TODValue,
TParamEntry,
TPath,
TProfileMenu,
)
from objdictgen.utils import copy_in_order, exc_amend, maybe_number, str_to_int, strip_brackets

T = TypeVar('T')
M = TypeVar('M', bound=Mapping)
Expand Down Expand Up @@ -352,10 +362,10 @@ def generate_jsonc(node: Node, compact=False, sort=False, internal=False,

if jsonc:
# In jsonc the field is converted to "<field>, // <comment>"
repl = lambda m: m[1].replace('\\"', '"') + m[3] + m[2]
repl = lambda m: m[1].replace('\\"', '"') + m[3] + m[2] # noqa: E731
else:
# In json the field is converted to "<field>,"
repl = lambda m: m[1].replace('\\"', '"') + m[3]
repl = lambda m: m[1].replace('\\"', '"') + m[3] # noqa: E731

# Convert the special @@ fields to jsonc comments
# Syntax: "@@<field>, // <comment>@@"
Expand Down Expand Up @@ -396,7 +406,7 @@ def generate_node(contents: str|TODJson, validate: bool = True) -> Node:
# validate_fromdict() is better at giving useful errors
# than the json validator. However the type checking of the json
# validator is better.
global SCHEMA # pylint: disable=global-statement
global SCHEMA
if not SCHEMA:
with open(objdictgen.JSON_SCHEMA, 'r', encoding="utf-8") as f:
SCHEMA = json.loads(remove_jsonc(f.read()))
Expand Down
10 changes: 4 additions & 6 deletions src/objdictgen/maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@
from typing import TYPE_CHECKING, Any, Callable, Generator, TypeVar

import objdictgen
from objdictgen.typing import (TODObj, TODSubObj, TODValue, TParamEntry, TPath,
TProfileMenu)
from objdictgen.typing import TODObj, TODSubObj, TODValue, TParamEntry, TPath, TProfileMenu

T = TypeVar('T')

Expand Down Expand Up @@ -327,15 +326,14 @@ def import_profile(profilename: TPath) -> tuple["ODMapping", TProfileMenu]:

# Mapping and AddMenuEntries are expected to be defined by the execfile
# The profiles requires some vars to be set
# pylint: disable=unused-variable
try:
with open(profilepath, "r", encoding="utf-8") as f:
log.debug("EXECFILE %s", profilepath)
code = compile(f.read(), profilepath, 'exec')
exec(code, globals(), locals()) # FIXME: Using exec is unsafe
# pylint: disable=undefined-variable
return Mapping, AddMenuEntries # type: ignore[name-defined] # due to the exec() magic
except Exception as exc: # pylint: disable=broad-except
# NOTE: These seem missing due to the exec() magic
return Mapping, AddMenuEntries # type: ignore[name-defined] # noqa: F821
except Exception as exc:
log.debug("EXECFILE FAILED: %s", exc)
log.debug(traceback.format_exc())
raise ValueError(f"Loading profile '{profilepath}' failed: {exc}") from exc
Expand Down
6 changes: 3 additions & 3 deletions src/objdictgen/nodelist.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def SaveMasterNode(self, netname: str = ""):
masterpath = self.Root / "master.od"
try:
self.Manager.SaveCurrentInFile(masterpath)
except Exception as exc: # pylint: disable=broad-except
except Exception as exc:
raise ValueError(f"Fail to save master node in '{masterpath}'") from exc

def LoadSlaveNodes(self, netname: str = ""):
Expand All @@ -174,7 +174,7 @@ def LoadSlaveNodes(self, netname: str = ""):
self.LoadEDS(node["DCFName"])
self.AddSlaveNode(node["Name"], nodeid, node["DCFName"])
self.Changed = False
except Exception as exc: # pylint: disable=broad-except
except Exception as exc:
raise ValueError(f"Unable to load CPJ file '{cpjpath}'") from exc

def SaveNodeList(self, netname: str = ""):
Expand All @@ -188,7 +188,7 @@ def SaveNodeList(self, netname: str = ""):
with open(cpjpath, mode=mode, encoding="utf-8") as f:
f.write(content)
self.Changed = False
except Exception as exc: # pylint: disable=broad-except
except Exception as exc:
raise ValueError(f"Fail to save node list in '{cpjpath}'") from exc

def GetOrderNumber(self, nodeid: int) -> int:
Expand Down
2 changes: 1 addition & 1 deletion src/objdictgen/nodemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@

# Returns a new id
def get_new_id():
global CURRENTID # pylint: disable=global-statement
global CURRENTID
CURRENTID += 1
return CURRENTID

Expand Down
7 changes: 3 additions & 4 deletions src/objdictgen/nosis.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def xmldump(filehandle: io.TextIOWrapper|None, py_obj: object,
omit = omit or ()

# Store the ref id to the pickling object (if not deepcopying)
global VISITED # pylint: disable=global-statement
global VISITED
objid = id(py_obj)
VISITED = {
objid: py_obj
Expand Down Expand Up @@ -316,7 +316,7 @@ def xmlload(filehandle: SupportsRead[str|bytes]|bytes|str) -> Any:
elif isinstance(filehandle, bytes):
fh = io.BytesIO(filehandle)

global VISITED # pylint: disable=global-statement
global VISITED
VISITED = {} # Reset the visited collection

return _thing_from_dom(minidom.parse(fh), None)
Expand Down Expand Up @@ -511,7 +511,7 @@ def _thing_from_dom(dom_node: minidom.Element|minidom.Document, container: Any =
# a value= attribute. ie. pickler can place it in either
# place (based on user preference) and unpickler doesn't care
node_valuetext = ""
if 'value' in node._attrs: # type: ignore[attr-defined] # pylint: disable=protected-access
if 'value' in node._attrs:
# text in tag
ttext = node.getAttribute('value')
node_valuetext = unsafe_string(ttext, isattr=True)
Expand Down Expand Up @@ -557,7 +557,6 @@ def _thing_from_dom(dom_node: minidom.Element|minidom.Document, container: Any =
# clearer to show all cases being handled (easier to see the pattern
# when doing later maintenance).

# pylint: disable=self-assigning-variable
if node_type == 'None':
node_val = None
elif node_type == 'numeric':
Expand Down
2 changes: 0 additions & 2 deletions src/objdictgen/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,6 @@
class NodeProtocol(Protocol):
"""Protocol for the Node class."""

# pylint: disable=unnecessary-ellipsis

Name: str
"""Name of the node."""

Expand Down
24 changes: 8 additions & 16 deletions src/objdictgen/ui/commondialogs.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@
from objdictgen import maps
from objdictgen.maps import OD
from objdictgen.typing import TGetValues
from objdictgen.ui.exception import (display_error_dialog,
display_exception_dialog)
from objdictgen.ui.exception import display_error_dialog, display_exception_dialog

log = logging.getLogger('objdictgen')

Expand All @@ -50,7 +49,6 @@

class CommunicationDialog(wx.Dialog):
"""Edit Communication Profile Dialog."""
# pylint: disable=attribute-defined-outside-init

IndexDictionary: dict[int, tuple[str, bool]]
CurrentList: list[int]
Expand Down Expand Up @@ -249,7 +247,6 @@ def UnselectCurrent(self):

class MapVariableDialog(wx.Dialog):
"""Create Map Variable Dialog."""
# pylint: disable=attribute-defined-outside-init

def _init_coll_flexGridSizer1_Items(self, parent):
parent.Add(self.MainSizer, 0, border=20,
Expand Down Expand Up @@ -383,7 +380,7 @@ def __init__(self, parent):
def SetIndex(self, index):
self.Index.SetValue(f"0x{index:04X}")

def OnOK(self, event): # pylint: disable=unused-argument
def OnOK(self, event):
error = []
try:
int(self.Index.GetValue(), 16)
Expand Down Expand Up @@ -459,7 +456,6 @@ def EnableNumberTyping(self, enable):

class UserTypeDialog(wx.Dialog):
"""Create User Type Dialog."""
# pylint: disable=attribute-defined-outside-init

# Helpers for typing
RightBoxSizer: wx.StaticBoxSizer
Expand Down Expand Up @@ -592,7 +588,7 @@ def __init__(self, parent):

self.TypeDictionary: dict[str, tuple[int, int]] = {}

def OnOK(self, event): # pylint: disable=unused-argument
def OnOK(self, event):
error = []
message = None
name = self.Type.GetStringSelection()
Expand Down Expand Up @@ -711,7 +707,6 @@ def GetValues(self):

class NodeInfosDialog(wx.Dialog):
"""Dialog for editing node infos."""
# pylint: disable=attribute-defined-outside-init

def _init_coll_flexGridSizer1_Items(self, parent):
parent.Add(self.MainSizer, 0, border=20,
Expand Down Expand Up @@ -821,7 +816,7 @@ def __init__(self, parent):
for node_type in NODE_TYPES:
self.Type.Append(node_type)

def OnOK(self, event): # pylint: disable=unused-argument
def OnOK(self, event):
name = self.NodeName.GetValue()
message = ""
if name:
Expand Down Expand Up @@ -883,7 +878,7 @@ def GetValues(self):

class CreateNodeDialog(wx.Dialog):
"""Dialog for creating new node."""
# pylint: disable=attribute-defined-outside-init


def _init_coll_flexGridSizer1_Items(self, parent):
parent.Add(self.MainSizer, 0, border=20,
Expand Down Expand Up @@ -1123,7 +1118,7 @@ def __init__(self, parent, buttons=wx.OK | wx.CANCEL):
self.Profile.SetStringSelection("None")
self.NodeName.SetFocus()

def OnOK(self, event): # pylint: disable=unused-argument
def OnOK(self, event):
name = self.NodeName.GetValue()
message = ""
if name:
Expand Down Expand Up @@ -1217,7 +1212,6 @@ def OnProfileChoice(self, event):

class AddSlaveDialog(wx.Dialog):
"""UI for adding a slave to the nodelist."""
# pylint: disable=attribute-defined-outside-init

def _init_coll_flexGridSizer1_Items(self, parent):
parent.Add(self.MainSizer, 0, border=20,
Expand Down Expand Up @@ -1314,7 +1308,7 @@ def __init__(self, parent):

self.SlaveNodeID.SetValue("0x00")

def OnOK(self, event): # pylint: disable=unused-argument
def OnOK(self, event):
error = []
if not self.SlaveName.GetValue():
error.append("Slave Name")
Expand Down Expand Up @@ -1369,7 +1363,7 @@ def OnImportEDSButton(self, event):
if dialog.ShowModal() == wx.ID_YES:
try:
self.NodeList.ImportEDSFile(filepath)
except Exception: # pylint: disable=broad-except
except Exception:
display_exception_dialog(self)

self.RefreshEDSFile()
Expand Down Expand Up @@ -1407,7 +1401,6 @@ def GetValues(self) -> TGetValues:


class DCFEntryValuesTable(wx.grid.GridTableBase):
# pylint: disable=attribute-defined-outside-init

"""
A custom wxGrid Table using user supplied data
Expand Down Expand Up @@ -1531,7 +1524,6 @@ def Empty(self):

class DCFEntryValuesDialog(wx.Dialog):
"""Dialog to edit DCF Entry values."""
# pylint: disable=attribute-defined-outside-init

def _init_coll_MainSizer_Items(self, parent):
parent.Add(self.staticText1, 0, border=20,
Expand Down
Loading
Loading