From 33c85f4fc7b14d3eed479e65d059201bd7d30743 Mon Sep 17 00:00:00 2001 From: Igor Udot Date: Tue, 31 Dec 2024 20:05:06 +0800 Subject: [PATCH 1/2] ref: removed dependencies and update parser --- .editorconfig | 22 ++ .github/dependabot.yml | 11 + .github/workflows/check-pre-commit.yml | 18 ++ .github/workflows/issue_comment.yml | 20 ++ .github/workflows/new_issues.yml | 20 ++ .github/workflows/new_prs.yml | 25 +++ .github/workflows/publish-pypi.yml | 22 ++ .github/workflows/test-build-docs.yml | 25 +++ .github/workflows/test-esp-bool-parser.yml | 52 +++++ .gitignore | 161 ++++++++++++++ .pre-commit-config.yaml | 49 +++++ .readthedocs.yml | 17 ++ CHANGELOG.md | 10 + CONTRIBUTING.md | 73 +++++++ LICENSE | 202 ++++++++++++++++++ README.md | 51 +++++ esp_bool_parser/__init__.py | 17 ++ .../{if_parser.py => bool_parser.py} | 112 ++++++---- esp_bool_parser/constants.py | 63 +----- esp_bool_parser/soc_header.py | 2 +- esp_bool_parser/utils.py | 6 +- license_header.txt | 2 + pyproject.toml | 18 +- tests/test_bool_parser.py | 89 ++++++++ tests/test_soc_caps.py | 21 ++ 25 files changed, 994 insertions(+), 114 deletions(-) create mode 100644 .editorconfig create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/check-pre-commit.yml create mode 100644 .github/workflows/issue_comment.yml create mode 100644 .github/workflows/new_issues.yml create mode 100644 .github/workflows/new_prs.yml create mode 100644 .github/workflows/publish-pypi.yml create mode 100644 .github/workflows/test-build-docs.yml create mode 100644 .github/workflows/test-esp-bool-parser.yml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .readthedocs.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md rename esp_bool_parser/{if_parser.py => bool_parser.py} (64%) create mode 100644 license_header.txt create mode 100644 tests/test_bool_parser.py create mode 100644 tests/test_soc_caps.py diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..2c286a4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true + +[*.py] +charset = utf-8 +indent_style = space +indent_size = 4 + +[*.rst] +indent_style = space +indent_size = 3 + +[*.md] +indent_style = space +indent_size = 4 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..90e05c4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/check-pre-commit.yml b/.github/workflows/check-pre-commit.yml new file mode 100644 index 0000000..168bd18 --- /dev/null +++ b/.github/workflows/check-pre-commit.yml @@ -0,0 +1,18 @@ +name: pre-commit check + +on: + pull_request: + +jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@v5 + - id: changed-files + uses: tj-actions/changed-files@v45 + - uses: pre-commit/action@v3.0.1 + with: + extra_args: --files ${{ steps.changed-files.outputs.all_changed_files }} diff --git a/.github/workflows/issue_comment.yml b/.github/workflows/issue_comment.yml new file mode 100644 index 0000000..8ee824b --- /dev/null +++ b/.github/workflows/issue_comment.yml @@ -0,0 +1,20 @@ +name: Sync issue comments to JIRA + +# This workflow will be triggered when new issue comment is created (including PR comments) +on: issue_comment + +jobs: + sync_issue_comments_to_jira: + name: Sync Issue Comments to Jira + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + - name: Sync issue comments to JIRA + uses: espressif/github-actions/sync_issues_to_jira@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + JIRA_PASS: ${{ secrets.JIRA_PASS }} + JIRA_PROJECT: RDT + JIRA_COMPONENT: idf-build-apps + JIRA_URL: ${{ secrets.JIRA_URL }} + JIRA_USER: ${{ secrets.JIRA_USER }} diff --git a/.github/workflows/new_issues.yml b/.github/workflows/new_issues.yml new file mode 100644 index 0000000..aa5d226 --- /dev/null +++ b/.github/workflows/new_issues.yml @@ -0,0 +1,20 @@ +name: Sync issues to Jira + +# This workflow will be triggered when a new issue is opened +on: issues + +jobs: + sync_issues_to_jira: + name: Sync issues to Jira + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + - name: Sync GitHub issues to Jira project + uses: espressif/github-actions/sync_issues_to_jira@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + JIRA_PASS: ${{ secrets.JIRA_PASS }} + JIRA_PROJECT: RDT + JIRA_COMPONENT: idf-build-apps + JIRA_URL: ${{ secrets.JIRA_URL }} + JIRA_USER: ${{ secrets.JIRA_USER }} diff --git a/.github/workflows/new_prs.yml b/.github/workflows/new_prs.yml new file mode 100644 index 0000000..a8a6667 --- /dev/null +++ b/.github/workflows/new_prs.yml @@ -0,0 +1,25 @@ +name: Sync remain PRs to Jira + +# This workflow will be triggered every hour, to sync remaining PRs (i.e. PRs with zero comment) to Jira project +# Note that, PRs can also get synced when new PR comment is created +on: + schedule: + - cron: "0 * * * *" + +jobs: + sync_prs_to_jira: + name: Sync PRs to Jira + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@master + - name: Sync PRs to Jira project + uses: espressif/github-actions/sync_issues_to_jira@master + with: + cron_job: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + JIRA_PASS: ${{ secrets.JIRA_PASS }} + JIRA_PROJECT: RDT + JIRA_COMPONENT: idf-build-apps + JIRA_URL: ${{ secrets.JIRA_URL }} + JIRA_USER: ${{ secrets.JIRA_USER }} diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml new file mode 100644 index 0000000..eb02481 --- /dev/null +++ b/.github/workflows/publish-pypi.yml @@ -0,0 +1,22 @@ +name: Publish PyPI + +on: + push: + tags: + - 'v*' + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.7' + - name: Publish packages + env: + FLIT_USERNAME: __token__ + FLIT_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} + run: | + pip install flit + flit publish --setup-py diff --git a/.github/workflows/test-build-docs.yml b/.github/workflows/test-build-docs.yml new file mode 100644 index 0000000..0b81fa9 --- /dev/null +++ b/.github/workflows/test-build-docs.yml @@ -0,0 +1,25 @@ +name: Test Build Docs + +on: + pull_request: + +jobs: + build-docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.7' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flit + flit install -s + - name: Build the docs + run: | + cd docs + pushd en && make html && popd + - name: markdown-link-check + uses: gaurav-nelson/github-action-markdown-link-check@1.0.15 diff --git a/.github/workflows/test-esp-bool-parser.yml b/.github/workflows/test-esp-bool-parser.yml new file mode 100644 index 0000000..71f6d6e --- /dev/null +++ b/.github/workflows/test-esp-bool-parser.yml @@ -0,0 +1,52 @@ +name: Test ESP bool parser + +on: + pull_request: + paths: + - 'esp_bool_parser/**' + push: + branches: + - main + +env: + IDF_PATH: /opt/esp/idf + +defaults: + run: + shell: bash + +jobs: + build-python-packages: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.7' + - run: | + pip install -U pip + pip install flit + flit build + - name: Upload built python packages + uses: actions/upload-artifact@v4 + with: + name: wheel + path: dist/esp_bool_parser-*.whl + + + basic-testest: + runs-on: ubuntu-latest + env: + FLIT_ROOT_INSTALL: 1 + steps: + - uses: actions/checkout@v4 + - name: Build the Apps + run: | + pip install flit + flit install -s + pytest --cov esp_bool_parser --cov-report term-missing:skip-covered --junit-xml pytest.xml | tee pytest-coverage.txt + - name: Pytest coverage comment + uses: MishaKav/pytest-coverage-comment@main + with: + pytest-coverage-path: pytest-coverage.txt + junitxml-path: pytest.xml diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9fa2499 --- /dev/null +++ b/.gitignore @@ -0,0 +1,161 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/*/_build/ +docs/en/references/api/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e132d3e --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,49 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v5.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: mixed-line-ending + args: [ '-f=lf' ] + - repo: https://github.com/Lucas-C/pre-commit-hooks + rev: v1.5.5 + hooks: + - id: insert-license + files: \.py$ + args: + - --license-filepath + - license_header.txt # defaults to: LICENSE.txt + - --use-current-year + exclude: 'idf_build_apps/vendors/' + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: 'v0.8.0' + hooks: + - id: ruff + args: ['--fix'] + - id: ruff-format + - repo: https://github.com/pre-commit/mirrors-mypy + rev: 'v1.13.0' + hooks: + - id: mypy + args: ['--warn-unused-ignores'] + additional_dependencies: + - pydantic<2.6 + - pydantic-settings + - packaging + - toml + - pyparsing + - types-PyYAML + - types-toml + - pytest + - argcomplete>=3 + - repo: https://github.com/hfudev/rstfmt + rev: v0.1.4 + hooks: + - id: rstfmt + args: ['-w', '-1'] + files: "docs\/.+rst$" + additional_dependencies: + - sphinx-argparse + - sphinx-tabs + - sphinxcontrib-mermaid diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000..1656076 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,17 @@ +# .readthedocs.yaml +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +version: 2 + +build: + os: ubuntu-22.04 + tools: + python: "3.7" + +python: + install: + - method: pip + path: . + extra_requirements: + - doc diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..12a5b24 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## v0.1.0 (2025-01-02) + +### Added + +- **`parse_bool_expr`**: A method for handling complex boolean expressions, supporting logical operators like `and` and `or`. +- **`register_addition_attribute`**: A method for dynamically registering additional attributes with the `ChipAttr` class, enabling custom attribute handling for targets and configurations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..3b5a3ff --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,73 @@ +# Contributions Guide + +Hi! We're glad that you're interested in contributing to `esp-bool-parser`. This document would guide you through the process of setting up the development environment, running tests, and building documentation. + +## Supported ESP-IDF Versions + +Here's a table shows the supported ESP-IDF versions and the corresponding Python versions. + +| ESP-IDF Version | ESP-IDF Supported Python Versions | esp-bool-parser Releases | +|-----------------|-----------------------------------|--------------------------| +| 5.0 | 3.7+ | main (0.x) | +| 5.1 | 3.7+ | main (0.x) | +| 5.2 | 3.7+ | main (0.x) | +| 5.3 | 3.8+ | main (0.x) | +| 5.4 | 3.8+ | main (0.x) | +| master (5.5) | 3.9+ | main (0.x) | + +## Setup the Dev Environment + +1. Create virtual environment + + ```shell + python -m venv venv + ``` + +2. Activate the virtual environment + + ```shell + . ./venv/bin/activate + ``` + +3. Install [flit][flit] + + We use [flit][flit] to build the package and install the dependencies. + + ```shell + pip install flit + ``` + +4. Install all dependencies + + All dependencies would be installed, and our package `esp-bool-parser` would be installed with editable mode. + + ```shell + flit install -s + ``` + +## Run Testing + +We use [pytest][pytest] for testing. + +```shell +pytest +``` + +## Build Documentation + +We use [sphinx][sphinx] and [autodoc][autodoc] for generating documentation and API references. Besides, we treat warnings as errors while building the documentation. Please fix them before your commits got merged. + +```shell +cd docs && make html +``` + +For documentation preview, you may use any browser you prefer. The executable has to be searchable in `PATH`. For example we're using firefox here. + +```shell +firefox _build/html/index.html +``` + +[flit]: https://flit.pypa.io/en/stable/index.html +[pytest]: https://docs.pytest.org/en/stable/contents.html +[sphinx]: https://www.sphinx-doc.org/en/master/ +[autodoc]: https://www.sphinx-doc.org/en/master/usage/quickstart.html#autodoc diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + 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 + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..76c6a57 --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +# esp-bool-parser + +`esp-bool-parser` is a package that provides a way to process boolean statements based on `soc_caps` files in the ESP-IDF. + +It helps you locate `soc_headers` files in the ESP-IDF, parse them, and store the parsed values as constants, which are then used in `ChipAttr`. + +When you import `esp_bool_parser`, you will gain access to the following functions: + +### Key Functions + +#### `parse_bool_expr(stmt: str)` + +Parses a boolean expression. + +- **Parameters:** + - `stmt` (str): A string containing the boolean expression. + +- **Returns:** + - A parsed representation of the boolean expression. + +- **Usage Example:** + + ```python + stmt_string = 'IDF_TARGET == "esp32"' + stmt = parse_bool_expr(stmt_string) + result = stmt.get_value("esp32", "config_name") + ``` + +#### `register_addition_attribute(attr: str, action: t.Callable[..., t.Any]) -> None` + +Registers an additional attribute for `ChipAttr`. + +You can extend the functionality of `ChipAttr` by adding custom handlers for new attributes. +Use the `register_addition_attribute` function to register additional attributes. +When these attributes are encountered, the associated handler function will be called. +Additionally, you can override existing attributes, as the newly registered handler will take priority over the original ones. + +- **Parameters:** + - `attr` (str): The name of the additional attribute. + - `action` (Callable): A callable that processes `**kwargs`. The `target` and `config_name` parameters will be passed as `kwargs` when the attribute is detected. + +- **Usage Example:** + + ```python + def my_action(target, config_name, **kwargs): + # Custom logic to handle the attribute + print(f"Processing {target} with {config_name}") + return target + + register_addition_attribute("CUSTOM_ATTR", my_action) + ``` diff --git a/esp_bool_parser/__init__.py b/esp_bool_parser/__init__.py index e69de29..1ea1c39 100644 --- a/esp_bool_parser/__init__.py +++ b/esp_bool_parser/__init__.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +""" +Tools for building ESP-IDF related apps. +""" + +# ruff: noqa: E402 + +__version__ = '0.1.0' + +from .bool_parser import parse_bool_expr, register_addition_attribute + +__all__ = [ + 'parse_bool_expr', + 'register_addition_attribute', +] diff --git a/esp_bool_parser/if_parser.py b/esp_bool_parser/bool_parser.py similarity index 64% rename from esp_bool_parser/if_parser.py rename to esp_bool_parser/bool_parser.py index 8c75d60..0df368e 100644 --- a/esp_bool_parser/if_parser.py +++ b/esp_bool_parser/bool_parser.py @@ -1,13 +1,11 @@ -# SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD +# SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD # SPDX-License-Identifier: Apache-2.0 import operator import os +import typing as t from ast import ( literal_eval, ) -from typing import ( - Any, -) from packaging.version import ( Version, @@ -15,7 +13,6 @@ from pyparsing import ( Keyword, Literal, - MatchFirst, ParseResults, QuotedString, Suppress, @@ -34,14 +31,13 @@ IDF_VERSION_MINOR, IDF_VERSION_PATCH, ) -from utils import ( - InvalidIfClause, +from .soc_header import ( + SOC_HEADERS, +) +from .utils import ( InvalidInput, to_version, ) -from soc_header import ( - SOC_HEADERS, -) class Stmt: @@ -49,7 +45,7 @@ class Stmt: Statement """ - def get_value(self, target: str, config_name: str) -> Any: + def get_value(self, target: str, config_name: str) -> t.Any: """ Lazy calculated. All subclasses of `Stmt` should implement this function. @@ -74,18 +70,18 @@ class ChipAttr(Stmt): - CONFIG_NAME: config name defined in the config rules """ + addition_attr: t.Dict[str, t.Callable] = {} + def __init__(self, t: ParseResults): self.attr: str = t[0] - def get_value(self, target: str, config_name: str) -> Any: - from .manifest import FolderRule # lazy-load + def get_value(self, target: str, config_name: str) -> t.Any: + if self.attr in self.addition_attr: + return self.addition_attr[self.attr](target=target, config_name=config_name) if self.attr == 'IDF_TARGET': return target - if self.attr == 'INCLUDE_DEFAULT': - return 1 if target in FolderRule.DEFAULT_BUILD_TARGETS else 0 - if self.attr == 'IDF_VERSION': return IDF_VERSION @@ -115,7 +111,7 @@ class Integer(Stmt): def __init__(self, t: ParseResults): self.expr: str = t[0] - def get_value(self, target: str, config_name: str) -> Any: # noqa: ARG002 + def get_value(self, target: str, config_name: str) -> t.Any: # noqa: ARG002 return literal_eval(self.expr) @@ -123,7 +119,7 @@ class String(Stmt): def __init__(self, t: ParseResults): self.expr: str = t[0] - def get_value(self, target: str, config_name: str) -> Any: # noqa: ARG002 + def get_value(self, target: str, config_name: str) -> t.Any: # noqa: ARG002 return literal_eval(f'"{self.expr}"') # double quotes is swallowed by QuotedString @@ -131,7 +127,7 @@ class List_(Stmt): def __init__(self, t: ParseResults): self.expr = t - def get_value(self, target: str, config_name: str) -> Any: + def get_value(self, target: str, config_name: str) -> t.Any: return [item.get_value(target, config_name) for item in self.expr] @@ -152,7 +148,7 @@ def __init__(self, t: ParseResults): self.comparison: str = t[1] self.right: Stmt = t[2] - def get_value(self, target: str, config_name: str) -> Any: + def get_value(self, target: str, config_name: str) -> t.Any: _l = self.left.get_value(target, config_name) _r = self.right.get_value(target, config_name) @@ -186,23 +182,32 @@ def _or(_l, _r): return _l or _r -class BoolOrAnd(BoolExpr): - def __init__(self, t: ParseResults): - if len(t[0]) > 3: - raise InvalidIfClause( - 'Chaining "and"/"or" is not allowed. Please use paratheses instead. ' - 'For example: "a and b and c" should be "(a and b) and c".' - ) - self.left: BoolStmt = t[0][0] - self.right: BoolStmt = t[0][2] +class BoolOr(BoolExpr): + def __init__(self, res: ParseResults): + self.bool_stmts: t.List[BoolStmt] = [] + for stmt in res[0]: + if stmt != 'or': + self.bool_stmts.append(stmt) + + def get_value(self, target: str, config_name: str) -> t.Any: + for stmt in self.bool_stmts: + if stmt.get_value(target, config_name): + return True + return False - if t[0][1] == 'and': - self.operation = _and - if t[0][1] == 'or': - self.operation = _or - def get_value(self, target: str, config_name: str) -> Any: - return self.operation(self.left.get_value(target, config_name), self.right.get_value(target, config_name)) +class BoolAnd(BoolExpr): + def __init__(self, res: ParseResults): + self.bool_stmts: t.List[BoolStmt] = [] + for stmt in res[0]: + if stmt != 'and': + self.bool_stmts.append(stmt) + + def get_value(self, target: str, config_name: str) -> t.Any: + for stmt in self.bool_stmts: + if not stmt.get_value(target, config_name): + return False + return True CAP_WORD = Word(alphas.upper(), nums + alphas.upper() + '_').setParseAction(ChipAttr) @@ -235,6 +240,41 @@ def get_value(self, target: str, config_name: str) -> Any: BOOL_EXPR = infixNotation( BOOL_STMT, [ - (MatchFirst((AND, OR)), 2, opAssoc.LEFT, BoolOrAnd), + (AND, 2, opAssoc.LEFT, BoolAnd), + (OR, 2, opAssoc.LEFT, BoolOr), ], ) + + +def register_addition_attribute(attr: str, action: t.Callable[..., t.Any]) -> None: + """ + Register an additional attribute for ChipAttr. + + :param attr: The name of the additional attribute (string). + :param action: A callable that processes **kwargs. The `target` and `config_name` + parameters will be passed as kwargs when the attribute is detected. + """ + ChipAttr.addition_attr[attr] = action + + +def parse_bool_expr(stmt: str) -> BoolStmt: + """ + Parse a boolean expression. + + :param stmt: A string containing the boolean expression. + :return: A `BoolStmt` object representing the parsed expression. + + .. note:: + + You can use this function to parse a boolean expression and evaluate its value based on the given context. + For example: + + .. code:: python + + stmt_string = 'IDF_TARGET == "esp32"' + stmt: BoolStmt = parse_bool_expr(stmt_string) + value = stmt.get_value("esp32", "config_name") + print(value) + # Output: True + """ + return BOOL_EXPR.parseString(stmt)[0] diff --git a/esp_bool_parser/constants.py b/esp_bool_parser/constants.py index 5c97431..dc4b9b4 100644 --- a/esp_bool_parser/constants.py +++ b/esp_bool_parser/constants.py @@ -1,7 +1,6 @@ -# SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD +# SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD # SPDX-License-Identifier: Apache-2.0 -import enum import importlib import logging import os @@ -20,10 +19,6 @@ LOGGER.warning('IDF_PATH environment variable is not set. Entering test mode...') LOGGER.warning('- Setting IDF_PATH to current directory...') IDF_PATH = os.path.abspath(_idf_env) -IDF_PY = os.path.join(IDF_PATH, 'tools', 'idf.py') -IDF_SIZE_PY = os.path.join(IDF_PATH, 'tools', 'idf_size.py') -PROJECT_DESCRIPTION_JSON = 'project_description.json' -DEFAULT_SDKCONFIG = 'sdkconfig.defaults' _idf_py_actions = os.path.join(IDF_PATH, 'tools', 'idf_py_actions') @@ -63,60 +58,4 @@ def _idf_version_from_cmake() -> t.Tuple[int, int, int]: IDF_VERSION_MAJOR, IDF_VERSION_MINOR, IDF_VERSION_PATCH = _idf_version_from_cmake() - IDF_VERSION = to_version(f'{IDF_VERSION_MAJOR}.{IDF_VERSION_MINOR}.{IDF_VERSION_PATCH}') - - -class BuildStatus(str, enum.Enum): - UNKNOWN = 'unknown' - DISABLED = 'disabled' - SKIPPED = 'skipped' - SHOULD_BE_BUILT = 'should be built' - FAILED = 'build failed' - SUCCESS = 'build success' - - -class BuildStage(str, enum.Enum): - DRY_RUN = 'Dry Run' - PRE_BUILD = 'Pre Build' - BUILD = 'Build' - POST_BUILD = 'Post Build' - - @classmethod - def max_length(cls) -> int: - return max(len(v.value) for v in cls.__members__.values()) - - -completion_instructions = """ -With the `--activate` option, detect your shell type and add the appropriate commands to your shell's config file -so that it runs on startup. You will likely have to restart. -or re-login for the autocompletion to start working. - -You can also specify your shell using the `--shell` option. - -If you do not want automatic modification of your shell configuration file -You can manually add the commands provided below to activate autocompletion. -or run them in your current terminal session for one-time activation. - -Once again, you will likely have to restart -or re-login for the autocompletion to start working. - -bash: - eval "$(register-python-argcomplete idf-build-apps)" - -zsh: - To activate completions in zsh, first make sure compinit is marked for - autoload and run autoload: - - autoload -U compinit - compinit - - Afterwards you can enable completions for idf-build-apps: - - eval "$(register-python-argcomplete idf-build-apps)" - -fish: - # Not required to be in the config file, only run once - register-python-argcomplete --shell fish idf-build-apps >~/.config/fish/completions/idf-build-apps.fish -""" -IDF_BUILD_APPS_TOML_FN = '.idf_build_apps.toml' diff --git a/esp_bool_parser/soc_header.py b/esp_bool_parser/soc_header.py index bf52242..a20c7f9 100644 --- a/esp_bool_parser/soc_header.py +++ b/esp_bool_parser/soc_header.py @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2022-2024 Espressif Systems (Shanghai) CO LTD +# SPDX-FileCopyrightText: 2022-2025 Espressif Systems (Shanghai) CO LTD # SPDX-License-Identifier: Apache-2.0 import logging import os.path diff --git a/esp_bool_parser/utils.py b/esp_bool_parser/utils.py index 1690b67..ff49e5e 100644 --- a/esp_bool_parser/utils.py +++ b/esp_bool_parser/utils.py @@ -1,8 +1,12 @@ +# SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +import typing as t from packaging.version import ( Version, ) -import typing as t + class InvalidInput(SystemExit): """Invalid input from user""" diff --git a/license_header.txt b/license_header.txt new file mode 100644 index 0000000..9926cc0 --- /dev/null +++ b/license_header.txt @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD +SPDX-License-Identifier: Apache-2.0 diff --git a/pyproject.toml b/pyproject.toml index ec156f3..478f161 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,11 +24,7 @@ requires-python = ">=3.7" dependencies = [ "pyparsing", - "pyyaml", "packaging", - "toml; python_version < '3.11'", - "argcomplete>=3", - "typing-extensions; python_version < '3.11'", ] [project.optional-dependencies] @@ -50,19 +46,16 @@ doc = [ [project.urls] homepage = "https://github.com/espressif/esp-bool-parser" -repository = "https://github.com/espressif/esp-bool-parser +repository = "https://github.com/espressif/esp-bool-parser" documentation = "https://docs.espressif.com/projects/esp-bool-parser" -changelog = "https://github.com/espressif/esp-bool-parsers/blob/master/CHANGELOG.md" - -[project.scripts] -idf-build-apps = "idf_build_apps:main.main" +changelog = "https://github.com/espressif/esp-bool-parsers/blob/main/CHANGELOG.md" [tool.commitizen] name = "cz_conventional_commits" -version = "2.5.3" +version = "0.1.0" tag_format = "v$version" version_files = [ - "idf_build_apps/__init__.py", + "esp_bool_parser/__init__.py", ] [tool.pytest.ini_options] @@ -146,9 +139,6 @@ ignore = [ # `open` and `read` should be replaced by `Path(f).read_text()` 'FURB101', ] -typing-modules = [ - "idf_build_apps.utils" -] [tool.ruff.format] quote-style = "single" diff --git a/tests/test_bool_parser.py b/tests/test_bool_parser.py new file mode 100644 index 0000000..7328cf5 --- /dev/null +++ b/tests/test_bool_parser.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from esp_bool_parser.bool_parser import parse_bool_expr, register_addition_attribute + + +@pytest.mark.parametrize( + 's, res', + [ + ('1 == 1', True), + ('"a" == "a"', True), + ('1 == 2', False), + ('"a" == "b"', False), + ], +) +def test_simple_parse(s, res): + stmt = parse_bool_expr(s) + result = stmt.get_value('', '') + assert result == res + + +@pytest.mark.parametrize( + 's, res', + [ + ('SOMETHING == 2', True), + ('SOMETHING == 1', False), + ], +) +def test_extend_attr(s, res): + stmt = parse_bool_expr(s) + + def _process_attr(**kwargs): + return kwargs.get('target') * 2 + + register_addition_attribute('SOMETHING', _process_attr) + result = stmt.get_value(1, '') + assert result == res + + +@pytest.mark.parametrize( + 's, res', + [ + ('1 == 0 or 2 == 0 or 3 == 3', True), + ('1 == 0 and 3 == 3', False), + ('1 == 1 and 2 == 2 or 3 == 0', True), + ('1 == 1 and 2 == 0 or 3 == 0', False), + ('1 == 1 and 2 == 2 and 3 == 1', False), + ('1 == 1 and 2 == 2 and 3 == 3', True), + ('1 == 1 and 2 == 2 or 3 == 0 and 4 == 0', True), + ('1 == 1 and 2 == 0 or 3 == 0 and 4 == 0', False), + ('1 == 1 and 2 == 0 or 3 == 3 and 4 == 4', True), + ('1 == 1 and 2 == 2 and 3 == 0 or 4 == 4', True), + ('(1 == 1 and 2 == 2) or 3 == 0', True), + ('1 == 1 and (2 == 2 or 3 == 3)', True), + ('1 == 1 and (2 == 0 or 3 == 3)', True), + ('(1 == 1 and 2 == 2) and (3 == 3 or 4 == 0)', True), + ('(1 == 1 and 2 == 0) or (3 == 3 and 4 == 4)', True), + ('(1 == 1 and 2 == 2) or (3 == 3 and 4 == 4)', True), + ('1 == 1 and (2 == 2 or 3 == 0) and 4 == 4', True), + ('(1 == 1 or 2 == 0) and (3 == 3 or 4 == 0)', True), + ('1 == 1 and (2 == 0 or 3 == 3) and (4 == 4 or 5 == 5)', True), + ('(1 == 1 and 2 == 0) or (3 == 3 and (4 == 4 or 5 == 5))', True), + ('(1 == 1 and (2 == 2 or 3 == 3)) or (4 == 4 and 5 == 5)', True), + ('1 == 1 or (2 == 0 and (3 == 3 or 4 == 4))', True), + ('(1 == 1 or 2 == 2) and (3 == 3 or (4 == 4 and 5 == 5))', True), + ('1 == 1 or (2 == 2 and (3 == 3 or 4 == 0))', True), + ('(1 == 1 and (2 == 2 or 3 == 0)) or (4 == 4 and 5 == 5)', True), + ('(1 == 1 and (2 == 2 or (3 == 3 and 4 == 4))) or 5 == 5', True), + ('(1 == 1 and 2 == 2) or (3 == 0 and 4 == 4)', True), + ('1 == 1 and (2 == 2 or 3 == 0) and 4 == 0', False), + ('(1 == 0 or 2 == 0) and (3 == 0 or 4 == 0)', False), + ('1 == 0 and (2 == 0 or 3 == 3) and (4 == 4 or 5 == 5)', False), + ('(1 == 1 and 2 == 2) and (3 == 3 and 4 == 0)', False), + ('(1 == 1 and 2 == 0) or (3 == 3 and (4 == 0 or 5 == 1))', False), + ('(1 == 0 and (2 == 2 or 3 == 3)) or (4 == 4 and 5 == 0)', False), + ('1 == 0 or (2 == 0 and (3 == 3 or 4 == 4))', False), + ('(1 == 0 or 2 == 0) and (3 == 3 or (4 == 4 and 5 == 5))', False), + ('1 == 0 or (2 == 0 and (3 == 0 or 4 == 0))', False), + ('(1 == 0 and (2 == 2 or (3 == 3 and 4 == 4))) or 5 == 0', False), + ('(1 == 1 and (2 == 0 or (3 == 3 and 4 == 5))) or 5 == 0', False), + ('(1 == 1 and 2 == 0) or (3 == 0 and (4 == 0 or 5 == 0))', False), + ], +) +def test_chain_rule(s, res): + stmt = parse_bool_expr(s) + result = stmt.get_value('', '') + assert result == res diff --git a/tests/test_soc_caps.py b/tests/test_soc_caps.py new file mode 100644 index 0000000..c2f1f87 --- /dev/null +++ b/tests/test_soc_caps.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +import pytest + +from esp_bool_parser.soc_header import parse_define + + +@pytest.mark.parametrize( + 's, res', + [ + ('#define SOC_FOO (4)', '4'), + ('#define SOC_FOO (-4)', '-4'), + ('#define SOC_FOO 4', '4'), + ('#define SOC_FOO -4', '-4'), + ], +) +def test_parse_define_int(s, res): + parse_result = parse_define(s) + assert parse_result['name'] == 'SOC_FOO' + assert parse_result['int_value'] == res From 09e21732864d8204fd68d485c7c698e52fb2da60 Mon Sep 17 00:00:00 2001 From: "igor.udot" Date: Thu, 2 Jan 2025 16:06:29 +0800 Subject: [PATCH 2/2] docs: initialized documentation --- CONTRIBUTING.md | 2 +- docs/_apidoc_templates/module.rst_t | 8 +++ docs/_apidoc_templates/package.rst_t | 49 ++++++++++++++++++ docs/_apidoc_templates/toc.rst_t | 7 +++ docs/_static/espressif-logo.svg | 77 ++++++++++++++++++++++++++++ docs/_static/theme_overrides.css | 55 ++++++++++++++++++++ docs/_templates/layout.html | 7 +++ docs/conf_common.py | 53 +++++++++++++++++++ docs/en/Makefile | 20 ++++++++ docs/en/conf.py | 11 ++++ docs/en/index.rst | 52 +++++++++++++++++++ docs/en/others/CHANGELOG.md | 2 + docs/en/others/CONTRIBUTING.md | 2 + 13 files changed, 344 insertions(+), 1 deletion(-) create mode 100644 docs/_apidoc_templates/module.rst_t create mode 100644 docs/_apidoc_templates/package.rst_t create mode 100644 docs/_apidoc_templates/toc.rst_t create mode 100644 docs/_static/espressif-logo.svg create mode 100644 docs/_static/theme_overrides.css create mode 100644 docs/_templates/layout.html create mode 100644 docs/conf_common.py create mode 100644 docs/en/Makefile create mode 100644 docs/en/conf.py create mode 100644 docs/en/index.rst create mode 100644 docs/en/others/CHANGELOG.md create mode 100644 docs/en/others/CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3b5a3ff..ff528b0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -58,7 +58,7 @@ pytest We use [sphinx][sphinx] and [autodoc][autodoc] for generating documentation and API references. Besides, we treat warnings as errors while building the documentation. Please fix them before your commits got merged. ```shell -cd docs && make html +cd docs/en && make html ``` For documentation preview, you may use any browser you prefer. The executable has to be searchable in `PATH`. For example we're using firefox here. diff --git a/docs/_apidoc_templates/module.rst_t b/docs/_apidoc_templates/module.rst_t new file mode 100644 index 0000000..49cca84 --- /dev/null +++ b/docs/_apidoc_templates/module.rst_t @@ -0,0 +1,8 @@ +{%- if show_headings %} +{{- [basename, "module"] | join(' ') | e | heading }} + +{% endif -%} +.. automodule:: {{ qualname }} +{%- for option in automodule_options %} + :{{ option }}: +{%- endfor %} diff --git a/docs/_apidoc_templates/package.rst_t b/docs/_apidoc_templates/package.rst_t new file mode 100644 index 0000000..44cbce9 --- /dev/null +++ b/docs/_apidoc_templates/package.rst_t @@ -0,0 +1,49 @@ +{%- macro automodule(modname, options) -%} +.. automodule:: {{ modname }} +{%- for option in options %} + :{{ option }}: +{%- endfor %} +{%- endmacro %} + +{%- macro toctree(docnames) -%} +.. toctree:: + :maxdepth: {{ maxdepth }} +{% for docname in docnames %} + {{ docname }} +{%- endfor %} +{%- endmacro %} + +{%- if is_namespace %} +{{- [pkgname, "namespace"] | join(" ") | e | heading }} +{% else %} +{{- [pkgname, "package"] | join(" ") | e | heading }} +{% endif %} + +{%- if is_namespace %} +.. py:module:: {{ pkgname }} +{% endif %} + +{%- if modulefirst and not is_namespace %} +{{ automodule(pkgname, automodule_options) }} +{% endif %} + +{%- if subpackages %} +{{ toctree(subpackages) }} +{% endif %} + +{%- if submodules %} +{% if separatemodules %} +{{ toctree(submodules) }} +{% else %} +{%- for submodule in submodules %} +{% if show_headings %} +{{- [submodule, "module"] | join(" ") | e | heading(2) }} +{% endif %} +{{ automodule(submodule, automodule_options) }} +{% endfor %} +{%- endif %} +{%- endif %} + +{%- if not modulefirst and not is_namespace %} +{{ automodule(pkgname, automodule_options) }} +{% endif %} diff --git a/docs/_apidoc_templates/toc.rst_t b/docs/_apidoc_templates/toc.rst_t new file mode 100644 index 0000000..878540c --- /dev/null +++ b/docs/_apidoc_templates/toc.rst_t @@ -0,0 +1,7 @@ +{{ header | heading }} + +.. toctree:: + :maxdepth: {{ maxdepth }} +{% for docname in docnames %} + {{ docname }} +{%- endfor %} diff --git a/docs/_static/espressif-logo.svg b/docs/_static/espressif-logo.svg new file mode 100644 index 0000000..1725310 --- /dev/null +++ b/docs/_static/espressif-logo.svg @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/_static/theme_overrides.css b/docs/_static/theme_overrides.css new file mode 100644 index 0000000..a88100a --- /dev/null +++ b/docs/_static/theme_overrides.css @@ -0,0 +1,55 @@ +/* override table width restrictions */ +@media screen and (min-width: 767px) { + + .wy-table-responsive table td { + /* !important prevents the common CSS stylesheets from overriding + this as on RTD they are loaded after this stylesheet */ + white-space: normal !important; + } + + .wy-table-responsive { + overflow: visible !important; + } + } + + .wy-side-nav-search { + background-color: #e3e3e3 !important; + } + + .wy-side-nav-search input[type=text] { + border-radius: 0px !important; + border-color: #333333 !important; + } + + .icon-home { + color: #333333 !important; + } + + .icon-home:hover { + background-color: #d6d6d6 !important; + } + + .version { + color: #000000 !important; + } + + a:hover { + color: #bd2c2a !important; + } + + .logo { + width: 240px !important; + } + + .highlight .c1 { + color: #008080; + } + + .bolditalics { + font-weight: bold; + font-style: italic; + } + +pre { + white-space: pre-wrap !important; +} diff --git a/docs/_templates/layout.html b/docs/_templates/layout.html new file mode 100644 index 0000000..631d13d --- /dev/null +++ b/docs/_templates/layout.html @@ -0,0 +1,7 @@ +{% extends "!layout.html" %} + +{% block document %} + + {{ super() }} + +{% endblock %} diff --git a/docs/conf_common.py b/docs/conf_common.py new file mode 100644 index 0000000..b5b97a3 --- /dev/null +++ b/docs/conf_common.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: 2023-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + + +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html +from datetime import datetime + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = 'esp-bool-parser' +project_homepage = 'https://github.com/espressif/esp-bool-parser' +copyright = f'2024-{datetime.now().year}, Espressif Systems (Shanghai) Co., Ltd.' # noqa: A001 +author = 'Fu Hanxi' +languages = ['en'] +version = '0.x' + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx_copybutton', + 'myst_parser', + 'sphinxcontrib.mermaid', + 'sphinxarg.ext', + 'sphinx_tabs.tabs', +] + +templates_path = ['_templates'] +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_css_files = ['theme_overrides.css'] +html_logo = '../_static/espressif-logo.svg' +html_static_path = ['../_static'] +html_theme = 'sphinx_rtd_theme' + +# mermaid 10.2.0 will show syntax error +# use fixed version instead +mermaid_version = '10.6.1' + +autodoc_default_options = { + 'members': True, + 'member-order': 'bysource', + 'show-inheritance': True, + 'exclude-members': 'model_computed_fields,model_config,model_fields,model_post_init', +} diff --git a/docs/en/Makefile b/docs/en/Makefile new file mode 100644 index 0000000..b50c24d --- /dev/null +++ b/docs/en/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= -W +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/en/conf.py b/docs/en/conf.py new file mode 100644 index 0000000..f30436d --- /dev/null +++ b/docs/en/conf.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD +# SPDX-License-Identifier: Apache-2.0 + +import os +import sys + +language = 'en' + +sys.path.insert(0, os.path.abspath('../')) + +from conf_common import * # noqa diff --git a/docs/en/index.rst b/docs/en/index.rst new file mode 100644 index 0000000..3239f4e --- /dev/null +++ b/docs/en/index.rst @@ -0,0 +1,52 @@ +######################################### + esp-bool-parser |version| Documentation +######################################### + +This documentation is for esp-bool-parser. esp-bool-parser is a package which help process boolean statements based on `soc_caps` files in the ESP-IDF. + +***************** + esp-bool-parser +***************** + +`esp-bool-parser` is a package that provides a way to process boolean statements based on `soc_caps` files in the ESP-IDF. + +It helps you locate `soc_headers` files in the ESP-IDF, parse them, and store the parsed values as constants, which are then used in `ChipAttr`. + +When you import `esp_bool_parser`, you will gain access to **`parse_bool_expr`**. + +*************** + Usage Example +*************** + +.. code:: python + + stmt_string = 'IDF_TARGET == "esp32"' + stmt: BoolStmt = parse_bool_expr(stmt_string) + result = stmt.get_value("esp32", "config_name") + +*************** + Extendability +*************** + +You can extend the functionality of `ChipAttr` by adding custom handlers for new attributes. Use the `register_addition_attribute` function to register additional attributes. When these attributes are encountered, the associated handler function will be called. Additionally, you can override existing attributes, as the newly registered handler will take priority over the original ones. + +Example: + +.. code:: python + + def custom_handler(target: str, config_name: str, **kwargs) -> Any: + # Custom logic to handle the attribute + return "custom_value" + + register_addition_attribute("CUSTOM_ATTR", custom_handler) + +.. caution:: + + Always add ``**kwargs`` to keep forward-compatibility. + +.. toctree:: + :maxdepth: 1 + :caption: Others + :glob: + + others/* diff --git a/docs/en/others/CHANGELOG.md b/docs/en/others/CHANGELOG.md new file mode 100644 index 0000000..14e66a7 --- /dev/null +++ b/docs/en/others/CHANGELOG.md @@ -0,0 +1,2 @@ +```{include} ../../../CHANGELOG.md +``` diff --git a/docs/en/others/CONTRIBUTING.md b/docs/en/others/CONTRIBUTING.md new file mode 100644 index 0000000..004f419 --- /dev/null +++ b/docs/en/others/CONTRIBUTING.md @@ -0,0 +1,2 @@ +```{include} ../../../CONTRIBUTING.md +```