From a9e6d14be622548f72aa2dadcb4c900227579cb4 Mon Sep 17 00:00:00 2001 From: pthierry Date: Thu, 11 Jul 2024 16:48:07 +0200 Subject: [PATCH] publishing initial release v0.1.6 --- .github/workflows/main.yml | 29 ++++++ .github/workflows/publish.yml | 43 +++++++++ .github/workflows/reuse.yml | 15 +++ .gitignore | 12 +++ CODEOWNERS | 7 ++ LICENSE | 177 ++++++++++++++++++++++++++++++++++ LICENSES/Apache-2.0.txt | 177 ++++++++++++++++++++++++++++++++++ README.md | 98 +++++++++++++++++++ pyproject.toml | 65 +++++++++++++ src/svd2json/__init__.py | 20 ++++ src/svd2json/__version__.py | 7 ++ src/svd2json/py.typed | 4 + src/svd2json/svd2json.py | 158 ++++++++++++++++++++++++++++++ tests/test_svd2json.py | 12 +++ tox.ini | 63 ++++++++++++ 15 files changed, 887 insertions(+) create mode 100644 .github/workflows/main.yml create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/reuse.yml create mode 100644 .gitignore create mode 100644 CODEOWNERS create mode 100644 LICENSE create mode 100644 LICENSES/Apache-2.0.txt create mode 100644 README.md create mode 100644 pyproject.toml create mode 100644 src/svd2json/__init__.py create mode 100644 src/svd2json/__version__.py create mode 100644 src/svd2json/py.typed create mode 100644 src/svd2json/svd2json.py create mode 100644 tests/test_svd2json.py create mode 100644 tox.ini diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..b69a0e2 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# +# SPDX-License-Identifier: Apache-2.0 + +on: + push: + pull_request: + branches: + - main + +jobs: + ut: + strategy: + matrix: + version: ['3.10', '3.11', '3.12'] + uses: outpost-os/pipeline-python/.github/workflows/unittest.yml@v1 + with: + python-version: ${{ matrix.version }} + secrets: inherit + doc: + uses: outpost-os/pipeline-python/.github/workflows/doc.yml@v1 + with: + python-version: '3.11' + lint: + needs: [ ut, doc ] + if: ${{ github.event_name == 'pull_request' }} + uses: outpost-os/pipeline-python/.github/workflows/lint.yml@v1 + with: + python-version: '3.10' diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..cb47458 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# +# SPDX-License-Identifier: Apache-2.0 + +name: Upload Python Package + +on: + release: + types: [released] + +jobs: + deploy: + runs-on: ubuntu-latest + environment: release + + permissions: + id-token: write + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Set up Python 3.10 + uses: actions/setup-python@v5 + with: + python-version: '3.10' + + - name: Install twine + run: | + pip install twine + + - name: Mint token + id: mint + uses: tschm/token-mint-action@v1.0.3 + + - name: Build n check python package + run: | + python -m build + twine check dist/*.whl + + - name: Publish package to registry + run: | + twine upload --disable-progress-bar -u __token__ -p '${{ steps.mint.outputs.api-token }}' dist diff --git a/.github/workflows/reuse.yml b/.github/workflows/reuse.yml new file mode 100644 index 0000000..fc7302e --- /dev/null +++ b/.github/workflows/reuse.yml @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# +# SPDX-License-Identifier: Apache-2.0 + +name: REUSE Compliance Check + +on: [push, pull_request] + +jobs: + reuse: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: REUSE Compliance Check + uses: fsfe/reuse-action@v4 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fddebbd --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 + +reports +build +dist +*.egg-info +**__pycache__ +.eggs/ +.tox +.coverage +*.pyc diff --git a/CODEOWNERS b/CODEOWNERS new file mode 100644 index 0000000..bffa653 --- /dev/null +++ b/CODEOWNERS @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 +# +# These owners will be the default owners for everything in +# the repo. Unless a later match takes precedence. + +* @florent-valette @philippe-thierry diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 0000000..d8edcea --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ + + +[![REUSE status](https://api.reuse.software/badge/github.com/outpost-os/python-svd2json)](https://api.reuse.software/info/github.com/outpost-os/python-Rsvd2json) + +![PyPI - Version](https://img.shields.io/pypi/v/svd2json) +![PyPI - License](https://img.shields.io/pypi/l/svd2json) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/svd2json) + +![build](https://github.com/outpost-os/python-svd2json/actions/workflows/main.yml/badge.svg) + + +# Python svd2json package + +This package converts a [CMSIS SVD (System View Description)](https://arm-software.github.io/CMSIS_5/SVD/html/index.html) file into a more friendly JSon format than raw XML to JSon conversion. +The aim of this package is to ease code generation from SVD file. We state that JSon format is the +best suitable for this purpose. For instance, it can be used as-is in Jinja2 template processing. + +## JSon format + +The resulting JSon `root` node is the `device` node in SVD. +XML values are converted to equivalent JSon ones. + +> **_NOTE:_** Some SVD files might be inconsistent in peripherals and/or registers naming convention across devices or in a single SVD file. E.g. only few registers are prefixed by peripheral name but no others, you can optionally trim this prefix in order to keep code generation as simple as possible and reusable among a wide range of devices/mcu. !!ADD REF!! + +An Additional `interrupts` is added in the resulting JSon which collects all interrupts declared across all peripherals. This can ease, for instance, `VTOR` table generation, one only has to walk through this array. + +## Script +This package exports the following script: +### svd2json +```console +$ svd2json --help +usage: svd2json [-h] -s SVD output + +convert svd file to json + +positional arguments: + output output filename + +options: + -h, --help show this help message and exit + -s SVD, --svd SVD SVD file to convert +``` + +## How to ... +This package follows PEP517/518/621 for its build system using a single `pyproject.toml` file and `setuptools` with dynamic versioning as build-backend. Unit testing, linting etc. are done with `tox`. +The minimal python version is Python 3.10. + +#### Build +One can use any python build front-end. E.g. with [PyPA `build` front-end](https://github.com/pypa/build) : + +```console +python -m build +``` + +#### Lint +This package is linted by [`black`](https://black.readthedocs.io/en/stable/) and [`flake8`](https://flake8.pycqa.org/en/latest/). In case of conflict between those two linter, we choose to follow `black` rules by default as it is closer to `PEP8` than `flake8`. + +```console +tox -e lint +``` + +#### Type check +Type checking is done with [mypy](https://mypy-lang.org/) with a python 3.10+ syntax. + +```console +tox -e type +``` + +#### License check +Package license(s) can be checked using [reuse](https://reuse.software/). + +``` +tox -e licenses +``` + +#### Doc +Documentation is generated using [`Sphinx`](https://www.sphinx-doc.org/en/master/index.html) and using +the [numpy style](https://numpydoc.readthedocs.io/en/latest/format.html) for pythondoc with [napoleon extension](https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html). + +```console +tox -e docs +``` + +#### Unit tests +Package Unit tests are based on `pytest` with coverage support. + +```console +tox -e unittests +tox -e htmlcov +``` + +## License +Licensed under Apache-2.0 + +> see [LICENSE](LICENSES/Apache-2.0.txt) file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..fea2b53 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: 2023 - 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 + +[build-system] +requires = ["setuptools>=64", "setuptools_scm>=8"] +build-backend = "setuptools.build_meta" + +[project] +name = "svd2json" +description = "Convert SVD file to json" +dynamic = ["version"] +requires-python = ">= 3.10" +readme = "README.md" +authors = [ + {email = "Ledger SAS "}, +] +license = {file = "LICENSES/Apache-2.0.txt"} +dependencies = [] +classifiers = [ + "Development Status :: 4 - Beta", + + "Intended Audience :: Developers", + + "Topic :: Software Development :: Build Tools", + + "License :: OSI Approved :: Apache Software License", + + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] + +[project.scripts] +svd2json = "svd2json:run" + +[project.optional-dependencies] +devel = [ + "coverage>=0.4", + "pytest>=4.6", + "pytest-cov>=5.0.0", + "cachetools>=5.3", +] +lint = [ + "black>=24.2,<25.0", + "flake8>=7.0,<8.0", + "flake8-html>=0.4.3", +] +type = [ + "mypy>=1.8.0", + "lxml>=4.8.0", +] +doc = [ + "Sphinx>=7.2.0", + "sphinx-rtd-theme>=2.0.0", + "sphinx-simplepdf>=1.6.0", + # "sphinx-autoapi", +] +license = [ + "reuse>=3.0.0", +] + +[tool.setuptools_scm] +# intentionally blank diff --git a/src/svd2json/__init__.py b/src/svd2json/__init__.py new file mode 100644 index 0000000..14b9ebf --- /dev/null +++ b/src/svd2json/__init__.py @@ -0,0 +1,20 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Copyright 2023 Ledger SAS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .__version__ import __version__ +from .svd2json import Svd2Json, run + +__all__ = ["__version__", "Svd2Json", "run"] diff --git a/src/svd2json/__version__.py b/src/svd2json/__version__.py new file mode 100644 index 0000000..83e6839 --- /dev/null +++ b/src/svd2json/__version__.py @@ -0,0 +1,7 @@ +# SPDX-FileCopyrightText: 2023-2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 + + +from importlib import metadata + +__version__ = metadata.version("svd2json") diff --git a/src/svd2json/py.typed b/src/svd2json/py.typed new file mode 100644 index 0000000..8491236 --- /dev/null +++ b/src/svd2json/py.typed @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 +# +# Marker file for PEP 561 diff --git a/src/svd2json/svd2json.py b/src/svd2json/svd2json.py new file mode 100644 index 0000000..fd188d5 --- /dev/null +++ b/src/svd2json/svd2json.py @@ -0,0 +1,158 @@ +# SPDX-License-Identifier: Apache-2.0 +# +# Copyright 2023 Ledger SAS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +from xml.etree import ElementTree +import json + + +class Svd2Json: + class interrupt: + pass + + TagValueType = { + "cpu": dict, + "device": dict, + "name": str, + "endian": str, + "revision": str, + "mpuPresent": bool, + "fpuPresent": bool, + "fpuDP": bool, + "dspPresent": bool, + "icachePresent": bool, + "dcachePresent": bool, + "itcmPresent": bool, + "dtcmPresent": bool, + "vtorPresent": bool, + "nvicPrioBits": int, + "deviceNumInterrupts": int, + "sauNumRegions": int, + "version": str, + "description": str, + "peripherals": list, + "peripheral": dict, + "fields": list, + "field": dict, + "baseAddress": int, + "addressOffset": int, + "size": int, + "bitOffset": int, + "bitWidth": int, + "access": str, + "registers": list, + "register": dict, + "interrupt": interrupt, + "value": int, + "groupName": str, + } + + def __init__(self): + self._out = dict() + self._interrupts = list() + + def parse(self, root): + self._out = self._parse(root) + self._peripheral_name_fixup() + self._interrupts.sort(key=lambda x: x["value"]) + self._out["interrupts"] = self._interrupts + return self._out + + def _parse(self, node: ElementTree.Element) -> list | dict | str | int | None: + try: + value_type = self.TagValueType[node.tag] + return getattr(self, f"_parse_{value_type.__name__}")(node) + except KeyError: + return None + + def _parse_dict(self, node: ElementTree.Element) -> dict: + out = dict() + for child in node: + ret = self._parse(child) + if ret is not None: + out[child.tag] = ret + + return out + + def _parse_str(self, node: ElementTree.Element) -> str: + return node.text if node.text is not None else str("") + + def _parse_bool(self, node: ElementTree.Element) -> bool: + return True if node.text == "true" or node.text == "1" else False + + def _parse_int(self, node: ElementTree.Element) -> int | None: + # If the field is empty, skip it + if node.text is None: + return None + str_val = node.text + if str_val.lower().startswith("0x"): + return int(str_val, 16) + else: + return int(str_val) + + def _parse_list(self, node: ElementTree.Element) -> list: + out = list() + for child in node: + ret = self._parse(child) + if ret is not None: + out.append(ret) + + return out + + def _parse_interrupt(self, node: ElementTree.Element) -> None: + interrupt = dict() + for elem in node: + ret = self._parse(elem) + if ret is not None: + interrupt[elem.tag] = ret + # Some irq are shared so, do not insert twice an interrupt with same name + exist = next((irq for irq in self._interrupts if irq["name"] == interrupt["name"]), None) + if not exist: + self._interrupts.append(interrupt) + return None + + def _peripheral_name_fixup(self) -> None: + """ + Some SVD may have the peripheral's name as prefix for register's name + As this is not consistent **AND** there is already such a concatenation + in peripherals layout template, we can trim this + """ + for p in self._out["peripherals"]: + if "groupName" in p.keys() and "registers" in p.keys(): + for r in p["registers"]: + r["name"] = r["name"].removeprefix((p["groupName"] + "_").upper()) + + +def svd2json(svd_path: str) -> dict: + svd_tree = ElementTree.parse(svd_path) + out = Svd2Json().parse(svd_tree.getroot()) + return out + + +def run(): + parser = argparse.ArgumentParser(prog="svd2json", description="convert svd file to json") + + parser.add_argument("output", default="out.json", help="output filename") + parser.add_argument("-s", "--svd", required=True, action="store", help="SVD file to convert") + args = parser.parse_args() + + try: + svd_json = json.dumps(svd2json(args.svd), indent=2) + with open(args.output, "w") as outfile: + outfile.write(svd_json) + except FileNotFoundError as e: + print(e) + exit(e.errno) diff --git a/tests/test_svd2json.py b/tests/test_svd2json.py new file mode 100644 index 0000000..38a0b20 --- /dev/null +++ b/tests/test_svd2json.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 + +# coding: utf-8 + +# import pytest +from svd2json import Svd2Json + + +def test_internals(): + converter = Svd2Json() + assert isinstance(converter._interrupts, list) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..8de5d8f --- /dev/null +++ b/tox.ini @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: 2023 - 2024 Ledger SAS +# SPDX-License-Identifier: Apache-2.0 + +[tox] +min_version = 4.0 +env_list = + lint + license + type + unittests + htmlcov + # docs +isolated_build = true + +[tox:.package] +basepython = python3 + +[testenv] +# extras = devel + +[testenv:unittests] +extras = devel +commands = + pytest --cov=svd2json --tb=long -v {posargs} + coverage report -m + coverage xml + +[testenv:htmlcov] +extras = devel +commands = + coverage run --parallel-mode -m pytest {posargs} + coverage combine + coverage report + coverage html --directory=reports/testcov + +[testenv:lint] +extras = lint +commands = + black --line-length 100 --check --diff . + +[testenv:type] +extras = type +commands = + mypy -p svd2json --html-report reports/mypycov + +[testenv:licenses] +extras = license +commands = reuse lint + +# [testenv:docs] + +[flake8] +select = C, E, F, W, B, B9 + +# XXX: +# Some flake8 rules conflicts with Black and/or aren't PEP8 compliant, in case of conflit we +# choose the Black way of doing. +# - E203: is not PEP8 compliant and conflit with blake, must be disabled +# - E704: complain about collapse impl. for ellided func/method/class which is allowed by PEP8 +# Black will ensure that this is the only case in which one should write a oneliner. +ignore = E203, E704 +max-line-length = 100 +exclude = .git, .github, __pycache__, build, dist, .eggs, .tox, venv, venv*, .venv, .venv*, reports, .mypy_cache