Skip to content

Commit

Permalink
Removal of py2 code
Browse files Browse the repository at this point in the history
* Remove packages future and attrs
* Fixup spacing on all copyright texts (black will change that)
* Ordered all imports (with isort)
* Remove object usage
* Replace call unicode instances with str, long with int
* Replace raise_from with raise ... from
* Remove all usages of OrderedDict. Ordinary dict guarantees order
* Replace execfile with exec
* Combine nosis/pickler.py and nosis/xtoy.py into nosis.py
* Added tests for nosis.py
* Raise NotImplementedError on node BE_to_LE() and LE_to_BE() as they might not work properly in py3. Missing test suits for them to verify.
  • Loading branch information
sveinse committed Jan 28, 2024
1 parent 5c559e2 commit 917b532
Show file tree
Hide file tree
Showing 25 changed files with 682 additions and 699 deletions.
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
#'Programming Language :: Python :: 3 :: Only',
],

Expand Down Expand Up @@ -142,7 +143,6 @@
# For an analysis of "install_requires" vs pip's requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[ # Optional
'future',
'jsonschema',
'colorama',
'deepdiff',
Expand All @@ -160,7 +160,7 @@
extras_require={ # Optional
'dist': ['build'],
'lint': ['pylint', 'flake8', 'mypy'],
'test': ['pytest', 'coverage', 'pytest-cov', 'pytest-mock', 'attrs'],
'test': ['pytest', 'coverage', 'pytest-cov', 'pytest-mock'],
},

# If there are data files included in your packages that need to be
Expand Down
31 changes: 16 additions & 15 deletions src/objdictgen/__init__.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
"""Object Dictionary tool for Canfestival, a CanOpen stack."""
#
# Copyright (C) 2022-2023 Svein Seldal, Laerdal Medical AS
# Copyright (C) 2022-2024 Svein Seldal, Laerdal Medical AS
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

import os

from objdictgen.node import Node, ImportProfile, Find
from objdictgen.nodemanager import NodeManager
from objdictgen.maps import OD
from objdictgen.node import Find, ImportProfile, Node
from objdictgen.nodemanager import NodeManager

# Shortcuts
LoadFile = Node.LoadFile
Expand Down
57 changes: 26 additions & 31 deletions src/objdictgen/__main__.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
"""Main entry point for objdictgen"""
#
# Copyright (C) 2022-2023 Svein Seldal, Laerdal Medical AS
# Copyright (C) 2022-2024 Svein Seldal, Laerdal Medical AS
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

from __future__ import absolute_import
from pprint import pformat
import sys
import getopt
import argparse
import functools
import getopt
import logging
import attr
from colorama import init, Fore, Style
import sys
from dataclasses import dataclass, field
from pprint import pformat

from colorama import Fore, Style, init

import objdictgen
from objdictgen import jsonod
Expand All @@ -38,10 +39,10 @@
log.addHandler(logging.StreamHandler(sys.stdout))


@attr.s
class DebugOpts(object):
@dataclass
class DebugOpts:
''' Options for main to control the debug_wrapper '''
show_debug = attr.ib(default=False)
show_debug: bool = field(default=False)

def set_debug(self, dbg):
self.show_debug = dbg
Expand Down Expand Up @@ -129,10 +130,9 @@ def main(debugopts, args=None):

# FIXME: New options: new file, add parameter, delete parameter, copy parameter

kw = dict(required=True) if sys.version_info[0] >= 3 else {}
subparser = parser.add_subparsers(title="command", dest="command", metavar="command", help='''
Commands
''', **kw)
''', required=True)


# -- COMMON --
Expand All @@ -149,10 +149,9 @@ def main(debugopts, args=None):
subp.add_argument('-D', '--debug', **opt_debug)

# -- CONVERT --
kw = dict(aliases=['gen', 'conv']) if sys.version_info[0] >= 3 else {}
subp = subparser.add_parser('convert', help='''
Generate
''', **kw)
''', aliases=['gen', 'conv'])
subp.add_argument('od', **opt_od)
subp.add_argument('out', default=None, help="Output file")
subp.add_argument('-i', '--index', action="append", help="OD Index to include. Filter out the rest.")
Expand All @@ -167,10 +166,9 @@ def main(debugopts, args=None):
subp.add_argument('-D', '--debug', **opt_debug)

# -- DIFF --
kw = dict(aliases=['compare']) if sys.version_info[0] >= 3 else {}
subp = subparser.add_parser('diff', help='''
Compare OD files
''', **kw)
''', aliases=['compare'])
subp.add_argument('od1', **opt_od)
subp.add_argument('od2', **opt_od)
subp.add_argument('--internal', action="store_true", help="Diff internal object")
Expand Down Expand Up @@ -279,9 +277,6 @@ def main(debugopts, args=None):

# -- DIFF command --
elif opts.command in ("diff", "compare"):
if sys.version_info[0] < 3:
parser.error("diff does not work with python 2")

od1 = open_od(opts.od1, validate=not opts.novalidate)
od2 = open_od(opts.od2, validate=not opts.novalidate)

Expand Down
59 changes: 22 additions & 37 deletions src/objdictgen/eds_utils.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,30 @@
# -*- coding: utf-8 -*-
"""Handler for EDS files, a standard file format in CANopen."""
#
# This file is based on objdictgen from CanFestival
# Copyright (C) 2022-2024 Svein Seldal, Laerdal Medical AS
# Copyright (C): Edouard TISSERANT, Francis DUPIN and Laurent BESSARD
#
# Copyright (C) 2022-2023 Svein Seldal, Laerdal Medical AS
# Copyright (C): Edouard TISSERANT, Francis DUPIN and Laurent BESSARD
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

from __future__ import print_function
from __future__ import absolute_import
from builtins import range
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

import os
import re
import sys
from time import localtime, strftime
from past.builtins import long # type: ignore
from future.utils import raise_from

import objdictgen
from objdictgen.maps import OD

if sys.version_info[0] >= 3:
unicode = str # pylint: disable=invalid-name
INT_TYPES = int # pylint: disable=invalid-name
else:
INT_TYPES = (int, long)

# Regular expression for finding index section names
RE_INDEX = re.compile(r'([0-9A-F]{1,4}$)')
# Regular expression for finding subindex section names
Expand All @@ -62,7 +47,7 @@

# Function for verifying data values
is_integer = lambda x: isinstance(x, int) # noqa: E731
is_string = lambda x: isinstance(x, (str, unicode)) # 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
Expand Down Expand Up @@ -188,7 +173,7 @@ def ParseCPJFile(filepath):
try:
computed_value = int(value, 16)
except ValueError:
raise_from(ValueError("'%s' is not a valid value for attribute '%s' of section '[%s]'" % (value, keyname, section_name)), None)
raise ValueError("'%s' is not a valid value for attribute '%s' of section '[%s]'" % (value, keyname, section_name)) from None
elif value.isdigit() or value.startswith("-") and value[1:].isdigit():
# Second case, value is a number and starts with "0" or "-0", then it's an octal value
if value.startswith("0") or value.startswith("-0"):
Expand Down Expand Up @@ -348,13 +333,13 @@ def ParseEDSFile(filepath):
_ = int(value.upper().replace("$NODEID+", ""), 16)
computed_value = '"%s"' % value
except ValueError:
raise_from(ValueError("'%s' is not a valid formula for attribute '%s' of section '[%s]'" % (value, keyname, section_name)), None)
raise ValueError("'%s' is not a valid formula for attribute '%s' of section '[%s]'" % (value, keyname, section_name)) from None
# Second case, value starts with "0x", then it's an hexadecimal value
elif value.startswith("0x") or value.startswith("-0x"):
try:
computed_value = int(value, 16)
except ValueError:
raise_from(ValueError("'%s' is not a valid value for attribute '%s' of section '[%s]'" % (value, keyname, section_name)), None)
raise ValueError("'%s' is not a valid value for attribute '%s' of section '[%s]'" % (value, keyname, section_name)) from None
elif value.isdigit() or value.startswith("-") and value[1:].isdigit():
# Third case, value is a number and starts with "0", then it's an octal value
if value.startswith("0") or value.startswith("-0"):
Expand Down Expand Up @@ -428,10 +413,10 @@ def VerifyValue(values, section_name, param):
values[uparam] = float(values[uparam])
elif values["DATATYPE"] == 0x01:
values[uparam] = {0: False, 1: True}[values[uparam]]
elif not isinstance(values[uparam], INT_TYPES) and "$NODEID" not in values[uparam].upper():
raise ValueError()
elif not isinstance(values[uparam], int) and "$NODEID" not in values[uparam].upper():
raise ValueError() # FIXME: Should this get something more specific?
except ValueError:
raise_from(ValueError("Error on section '[%s]': '%s' incompatible with DataType" % (section_name, param)), None)
raise ValueError("Error on section '[%s]': '%s' incompatible with DataType" % (section_name, param)) from None


# Function that generate the EDS file content for the current node in the manager
Expand Down
39 changes: 17 additions & 22 deletions src/objdictgen/gen_cfile.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,25 @@
# -*- coding: utf-8 -*-
"""Generate C file from a object dictionary node for canfestival."""
#
# This file is based on objdictgen from CanFestival
# Copyright (C) 2022-2024 Svein Seldal, Laerdal Medical AS
# Copyright (C): Edouard TISSERANT, Francis DUPIN
#
# Copyright (C) 2022-2023 Svein Seldal, Laerdal Medical AS
# Copyright (C): Edouard TISSERANT, Francis DUPIN
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

from __future__ import absolute_import
from builtins import range
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA

import re
import os
import re

from objdictgen.maps import OD

Expand All @@ -42,7 +37,7 @@
FILE_HEADER = """\n/* File generated by gen_cfile.py. Should not be modified. */\n"""


class CFileContext(object):
class CFileContext:
def __init__(self):
self.internal_types = {}
self.default_string_size = 10
Expand Down
Loading

0 comments on commit 917b532

Please sign in to comment.