From ccb71791360d4a14c399f528b2f2a934ecdcbaa0 Mon Sep 17 00:00:00 2001 From: Niko Aarnio Date: Wed, 11 Sep 2024 10:53:43 +0300 Subject: [PATCH] Initial commit Project created with the Cookiecutter QGIS Plugin Template. --- .editorconfig | 19 + .flake8 | 3 + .github/ISSUE_TEMPLATE/bug_report.md | 33 ++ .github/ISSUE_TEMPLATE/feature_request.md | 20 + .github/workflows/code-style.yml | 14 + .github/workflows/release.yml | 31 ++ .github/workflows/test-and-pre-release.yml | 118 ++++ .gitignore | 7 + .gitmodules | 3 + .pre-commit-config.yaml | 22 + .qgis-plugin-ci | 5 + CHANGELOG.md | 5 + LICENSE | 339 +++++++++++ README.md | 53 ++ arho-feature-template.code-workspace | 63 +++ arho_feature_template/.gitattributes | 3 + arho_feature_template/__init__.py | 21 + .../__init__.py | 0 .../processing_algorithm.py | 195 +++++++ .../provider.py | 44 ++ arho_feature_template/build.py | 30 + arho_feature_template/metadata.txt | 16 + arho_feature_template/plugin.py | 125 +++++ arho_feature_template/qgis_plugin_tools | 1 + arho_feature_template/resources/.gitignore | 0 .../resources/i18n/.gitignore | 0 .../resources/icons/.gitignore | 0 arho_feature_template/resources/ui/.gitignore | 0 create_qgis_venv.py | 445 +++++++++++++++ docs/development.md | 173 ++++++ docs/push_translations.yml | 26 + pyproject.toml | 27 + requirements-dev.in | 20 + requirements-dev.txt | 0 ruff_defaults.toml | 527 ++++++++++++++++++ tests/__init__.py | 0 tests/conftest.py | 15 + tests/test_plugin.py | 5 + 38 files changed, 2408 insertions(+) create mode 100644 .editorconfig create mode 100644 .flake8 create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/workflows/code-style.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/test-and-pre-release.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 .pre-commit-config.yaml create mode 100644 .qgis-plugin-ci create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 arho-feature-template.code-workspace create mode 100644 arho_feature_template/.gitattributes create mode 100644 arho_feature_template/__init__.py create mode 100644 arho_feature_template/arho_feature_template_processing/__init__.py create mode 100644 arho_feature_template/arho_feature_template_processing/processing_algorithm.py create mode 100644 arho_feature_template/arho_feature_template_processing/provider.py create mode 100755 arho_feature_template/build.py create mode 100644 arho_feature_template/metadata.txt create mode 100644 arho_feature_template/plugin.py create mode 160000 arho_feature_template/qgis_plugin_tools create mode 100644 arho_feature_template/resources/.gitignore create mode 100644 arho_feature_template/resources/i18n/.gitignore create mode 100644 arho_feature_template/resources/icons/.gitignore create mode 100644 arho_feature_template/resources/ui/.gitignore create mode 100644 create_qgis_venv.py create mode 100644 docs/development.md create mode 100644 docs/push_translations.yml create mode 100644 pyproject.toml create mode 100644 requirements-dev.in create mode 100644 requirements-dev.txt create mode 100644 ruff_defaults.toml create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_plugin.py diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a436084 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,19 @@ +root = true + +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.py] +indent_style = space +indent_size = 4 + +[*.ui] +indent_style = space +indent_size = 2 +max_line_length = 100000 + +[*.md] +trim_trailing_whitespace = false diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..ec7cedf --- /dev/null +++ b/.flake8 @@ -0,0 +1,3 @@ +[flake8] +# Flake8 is used only for QGIS rules. Ruff is used for all other rules. +select = QGS diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..be6f4e0 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - Plugin: [e.g. 1.0] + - QGIS [e.g. 3.14] + - Python: [e.g. 3.8] + - OS: [e.g. Windows 10, Fedora 32] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..3d2e74c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Expected behaviour** +A clear and concise description of what you'd like to happen if you do x. + +**Current behaviour** +A clear and concise description of the current behaviour when you do x. If completely new feature, leave empty. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. If relevant please also provide version of the plugin and information on the system you are running it on. diff --git a/.github/workflows/code-style.yml b/.github/workflows/code-style.yml new file mode 100644 index 0000000..7da22cd --- /dev/null +++ b/.github/workflows/code-style.yml @@ -0,0 +1,14 @@ +name: code-style + +on: + pull_request: + push: + branches: [master, main] + +jobs: + code-style: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - uses: pre-commit/action@v2.0.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..fe56209 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,31 @@ +name: Release + +on: + release: + types: released + +jobs: + plugin_dst: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Set up Python 3.8 + uses: actions/setup-python@v1 + with: + python-version: 3.8 + + # Needed if the plugin is using Transifex, to have the lrelease command + # - name: Install Qt lrelease + # run: sudo apt-get update && sudo apt-get install qt5-default qttools5-dev-tools + + - name: Install qgis-plugin-ci + run: pip3 install qgis-plugin-ci + + # When osgeo upload is wanted: --osgeo-username usrname --osgeo-password ${{ secrets.OSGEO_PASSWORD }} + # When Transifex is wanted: --transifex-token ${{ secrets.TRANSIFEX_TOKEN }} + - name: Deploy plugin + run: qgis-plugin-ci release ${GITHUB_REF/refs\/tags\//} --github-token ${{ secrets.GITHUB_TOKEN }} --disable-submodule-update diff --git a/.github/workflows/test-and-pre-release.yml b/.github/workflows/test-and-pre-release.yml new file mode 100644 index 0000000..fc89ee0 --- /dev/null +++ b/.github/workflows/test-and-pre-release.yml @@ -0,0 +1,118 @@ +# workflow name +name: Tests + +# Controls when the action will run. Triggers the workflow on push or pull request +# events but only for the wanted branches +on: + pull_request: + push: + branches: [master, main] + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + linux_tests: + # The type of runner that the job will run on + runs-on: ubuntu-latest + strategy: + matrix: + # Remove unsupported versions and add more versions. Use LTR version in the cov_tests job + docker_tags: [release-3_10, release-3_16, latest] + fail-fast: false + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Pull qgis + run: docker pull qgis/qgis:${{ matrix.docker_tags }} + + # Runs all tests + - name: Run tests + run: > + docker run --rm --net=host --volume `pwd`:/app -w=/app -e QGIS_PLUGIN_IN_CI=1 qgis/qgis:${{ matrix.docker_tags }} sh -c + "pip3 install -qr requirements-dev.txt && xvfb-run -s '+extension GLX -screen 0 1024x768x24' + pytest -v --cov=arho_feature_template --cov-report=xml" + + # Upload coverage report. Will not work if the repo is private + - name: Upload coverage to Codecov + if: ${{ matrix.docker_tags == 'latest' && !github.event.repository.private }} + uses: codecov/codecov-action@v1 + with: + file: ./coverage.xml + flags: unittests + fail_ci_if_error: false # set to true when upload is working + verbose: false + + windows_tests: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Choco install qgis + uses: crazy-max/ghaction-chocolatey@v1 + with: + args: install qgis-ltr -y + + - name: Run tests + shell: pwsh + run: | + $env:PATH="C:\Program Files\QGIS 3.16\bin;$env:PATH" + $env:QGIS_PLUGIN_IN_CI=1 + python-qgis-ltr.bat -m pip install -qr requirements-dev.txt + python-qgis-ltr.bat -m pytest -v + + pre-release: + name: "Pre Release" + runs-on: "ubuntu-latest" + needs: [linux_tests, windows_tests] + + steps: + - uses: hmarr/debug-action@v2 + + - uses: "marvinpinto/action-automatic-releases@latest" + if: ${{ github.event.pull_request }} + with: + repo_token: "${{ secrets.GITHUB_TOKEN }}" + automatic_release_tag: "dev-pr" + prerelease: true + title: "Development Build made for PR #${{ github.event.number }}" + + - uses: "marvinpinto/action-automatic-releases@latest" + if: ${{ github.event.after != github.event.before }} + with: + repo_token: "${{ secrets.GITHUB_TOKEN }}" + automatic_release_tag: "dev" + prerelease: true + title: "Development Build made for master branch" + + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Set up Python 3.8 + uses: actions/setup-python@v1 + with: + python-version: 3.8 + + # Needed if the plugin is using Transifex, to have the lrelease command + # - name: Install Qt lrelease + # run: sudo apt-get update && sudo apt-get install qt5-default qttools5-dev-tools + + - name: Install qgis-plugin-ci + run: pip3 install qgis-plugin-ci + + # When Transifex is wanted: --transifex-token ${{ secrets.TRANSIFEX_TOKEN }} + - name: Deploy plugin + if: ${{ github.event.pull_request }} + run: qgis-plugin-ci release dev-pr --github-token ${{ secrets.GITHUB_TOKEN }} --disable-submodule-update + + # When Transifex is wanted: --transifex-token ${{ secrets.TRANSIFEX_TOKEN }} + - name: Deploy plugin + if: ${{ github.event.after != github.event.before }} + run: qgis-plugin-ci release dev --github-token ${{ secrets.GITHUB_TOKEN }} --disable-submodule-update diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..87041a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +arho-feature-template/i18n +venv/ +.venv/ +start_ide.bat +.vscode +*/.pytest_cache +__pycache__ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..02a707e --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "arho_feature_template/qgis_plugin_tools"] + path = arho_feature_template/qgis_plugin_tools + url = https://github.com/GispoCoding/qgis_plugin_tools diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..e63b6ba --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,22 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-added-large-files + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.8.0 + hooks: + - id: mypy + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.1.11 + hooks: + # Run the linter. + - id: ruff + args: ["--extend-fixable=F841,F401"] + # Run the formatter. + - id: ruff-format diff --git a/.qgis-plugin-ci b/.qgis-plugin-ci new file mode 100644 index 0000000..33a47bf --- /dev/null +++ b/.qgis-plugin-ci @@ -0,0 +1,5 @@ +plugin_path: arho_feature_template +github_organization_slug: GispoCoding +project_slug: arho-feature-template +transifex_coordinator: replace-me +transifex_organization: replace-me diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e305f95 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# CHANGELOG + + + +### diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3b640e7 --- /dev/null +++ b/README.md @@ -0,0 +1,53 @@ +# ARHO feature template +![tests](https://github.com/GispoCoding/arho-feature-template/workflows/Tests/badge.svg) +[![codecov.io](https://codecov.io/github/GispoCoding/arho-feature-template/coverage.svg?branch=main)](https://codecov.io/github/GispoCoding/arho-feature-template?branch=main) +![release](https://github.com/GispoCoding/arho-feature-template/workflows/Release/badge.svg) + +[![GPLv2 license](https://img.shields.io/badge/License-GPLv2-blue.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) +[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) +[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit) + +## Development + +Create a virtual environment activate it and install needed dependencies with the following commands: +```console +python create_qgis_venv.py +.venv\Scripts\activate # On Linux and macOS run `source .venv\bin\activate` +pip install -r requirements-dev.txt +``` + +For more detailed development instructions see [development](docs/development.md). + +### Testing the plugin on QGIS + +A symbolic link / directory junction should be made to the directory containing the installed plugins pointing to the dev plugin package. + +On Windows Command promt +```console +mklink /J %AppData%\QGIS\QGIS3\profiles\default\python\plugins\arho_feature_template .\arho_feature_template +``` + +On Windows PowerShell +```console +New-Item -ItemType SymbolicLink -Path ${env:APPDATA}\QGIS\QGIS3\profiles\default\python\plugins\arho_feature_template -Value ${pwd}\arho_feature_template +``` + +On Linux +```console +ln -s arho_feature_template/ ~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/arho_feature_template +``` + +After that you should be able to enable the plugin in the QGIS Plugin Manager. + +### VsCode setup + +On VS Code use the workspace [arho-feature-template.code-workspace](arho-feature-template.code-workspace). +The workspace contains all the settings and extensions needed for development. + +Select the Python interpreter with Command Palette (Ctrl+Shift+P). Select `Python: Select Interpreter` and choose +the one with the path `.venv\Scripts\python.exe`. + +## License +This plugin is distributed under the terms of the [GNU General Public License, version 2](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) license. + +See [LICENSE](LICENSE) for more information. diff --git a/arho-feature-template.code-workspace b/arho-feature-template.code-workspace new file mode 100644 index 0000000..6d62132 --- /dev/null +++ b/arho-feature-template.code-workspace @@ -0,0 +1,63 @@ +{ + "folders": [ + { + "path": "." + } + ], + "settings": { + "editor.formatOnSave": true, + "[python]": { + "editor.defaultFormatter": "charliermarsh.ruff", + "editor.codeActionsOnSave": { + "source.organizeImports": "explicit", + "source.fixAll": "explicit" + } + }, + "python.testing.pytestEnabled": true, + "python.testing.pytestArgs": [ + "test" + ], + "python.testing.unittestEnabled": false + }, + "extensions": { + "recommendations": [ + "ms-python.python", + "ms-python.flake8", + "ms-python.mypy-type-checker", + "charliermarsh.ruff", + "editorconfig.editorconfig" + ] + }, + "launch": { + "configurations": [ + { + "name": "QGIS debugpy", + "type": "debugpy", + "request": "attach", + "connect": { + "host": "localhost", + "port": 5678 + }, + "pathMappings": [ + { + "localRoot": "${workspaceFolder}/arho_feature_template", + "remoteRoot": "${env:APPDATA}/QGIS/QGIS3/profiles/default/python/plugins/arho_feature_template" + } + ] + }, + { + "name": "Debug Tests", + "type": "debugpy", + "request": "launch", + "purpose": [ + "debug-test" + ], + "console": "integratedTerminal", + "justMyCode": false, + "env": { + "PYTEST_ADDOPTS": "--no-cov" + } + } + ], + } +} diff --git a/arho_feature_template/.gitattributes b/arho_feature_template/.gitattributes new file mode 100644 index 0000000..9dad0d8 --- /dev/null +++ b/arho_feature_template/.gitattributes @@ -0,0 +1,3 @@ +.gitattributes export-ignore +.editorconfig export-ignore +test export-ignore diff --git a/arho_feature_template/__init__.py b/arho_feature_template/__init__.py new file mode 100644 index 0000000..20b518a --- /dev/null +++ b/arho_feature_template/__init__.py @@ -0,0 +1,21 @@ +import os +from typing import TYPE_CHECKING + +from arho_feature_template.qgis_plugin_tools.infrastructure.debugging import ( + setup_debugpy, # noqa F401 + setup_ptvsd, # noqa F401 + setup_pydevd, # noqa F401 +) + +if TYPE_CHECKING: + from qgis.gui import QgisInterface + +debugger = os.environ.get("QGIS_PLUGIN_USE_DEBUGGER", "").lower() +if debugger in {"debugpy", "ptvsd", "pydevd"}: + locals()["setup_" + debugger]() + + +def classFactory(iface: "QgisInterface"): # noqa N802 + from arho_feature_template.plugin import Plugin + + return Plugin() diff --git a/arho_feature_template/arho_feature_template_processing/__init__.py b/arho_feature_template/arho_feature_template_processing/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/arho_feature_template/arho_feature_template_processing/processing_algorithm.py b/arho_feature_template/arho_feature_template_processing/processing_algorithm.py new file mode 100644 index 0000000..acb5683 --- /dev/null +++ b/arho_feature_template/arho_feature_template_processing/processing_algorithm.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +from typing import Any + +from qgis import processing # noqa: TCH002 +from qgis.core import ( + QgsFeatureSink, + QgsProcessing, + QgsProcessingAlgorithm, + QgsProcessingContext, + QgsProcessingFeedback, + QgsProcessingParameterFeatureSink, + QgsProcessingParameterFeatureSource, +) +from qgis.PyQt.QtCore import QCoreApplication + + +class ProcessingAlgorithm(QgsProcessingAlgorithm): + """ + This is an example algorithm that takes a vector layer and + creates a new identical one. + + It is meant to be used as an example of how to create your own + algorithms and explain methods and variables used to do it. An + algorithm like this will be available in all elements, and there + is not need for additional work. + + All Processing algorithms should extend the QgsProcessingAlgorithm + class. + """ + + # Constants used to refer to parameters and outputs. They will be + # used when calling the algorithm from another algorithm, or when + # calling from the QGIS console. + + INPUT = "INPUT" + OUTPUT = "OUTPUT" + + def __init__(self) -> None: + super().__init__() + + self._name = "myprocessingalgorithm" + self._display_name = "My Processing Algorithm" + self._group_id = "" + self._group = "" + self._short_help_string = "" + + def tr(self, string) -> str: + """ + Returns a translatable string with the self.tr() function. + """ + return QCoreApplication.translate("Processing", string) + + def createInstance(self): # noqa N802 + return ProcessingAlgorithm() + + def name(self) -> str: + """ + Returns the algorithm name, used for identifying the algorithm. This + string should be fixed for the algorithm, and must not be localised. + The name should be unique within each provider. Names should contain + lowercase alphanumeric characters only and no spaces or other + formatting characters. + """ + return self._name + + def displayName(self) -> str: # noqa N802 + """ + Returns the translated algorithm name, which should be used for any + user-visible display of the algorithm name. + """ + return self.tr(self._display_name) + + def groupId(self) -> str: # noqa N802 + """ + Returns the unique ID of the group this algorithm belongs to. This + string should be fixed for the algorithm, and must not be localised. + The group id should be unique within each provider. Group id should + contain lowercase alphanumeric characters only and no spaces or other + formatting characters. + """ + return self._group_id + + def group(self) -> str: + """ + Returns the name of the group this algorithm belongs to. This string + should be localised. + """ + return self.tr(self._group) + + def shortHelpString(self) -> str: # noqa N802 + """ + Returns a localised short helper string for the algorithm. This string + should provide a basic description about what the algorithm does and the + parameters and outputs associated with it.. + """ + return self.tr(self._short_help_string) + + def initAlgorithm(self, config=None): # noqa N802 + """ + Here we define the inputs and output of the algorithm, along + with some other properties. + """ + + # We add the input vector features source. It can have any kind of + # geometry. + self.addParameter( + QgsProcessingParameterFeatureSource( + self.INPUT, + self.tr("Input layer"), + [QgsProcessing.TypeVectorAnyGeometry], + ) + ) + + # We add a feature sink in which to store our processed features (this + # usually takes the form of a newly created vector layer when the + # algorithm is run in QGIS). + self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT, self.tr("Output layer"))) + + def processAlgorithm( # noqa N802 + self, + parameters: dict[str, Any], + context: QgsProcessingContext, + feedback: QgsProcessingFeedback, + ) -> dict: + """ + Here is where the processing itself takes place. + """ + + # Initialize feedback if it is None + if feedback is None: + feedback = QgsProcessingFeedback() + + # Retrieve the feature source and sink. The 'dest_id' variable is used + # to uniquely identify the feature sink, and must be included in the + # dictionary returned by the processAlgorithm function. + source = self.parameterAsSource(parameters, self.INPUT, context) + + (sink, dest_id) = self.parameterAsSink( + parameters, + self.OUTPUT, + context, + source.fields(), + source.wkbType(), + source.sourceCrs(), + ) + + # Send some information to the user + feedback.pushInfo(f"CRS is {source.sourceCrs().authid()}") + + # Compute the number of steps to display within the progress bar and + # get features from source + total = 100.0 / source.featureCount() if source.featureCount() else 0 + features = source.getFeatures() + + for current, feature in enumerate(features): + # Stop the algorithm if cancel button has been clicked + if feedback.isCanceled(): + break + + # Add a feature in the sink + sink.addFeature(feature, QgsFeatureSink.FastInsert) + + # Update the progress bar + feedback.setProgress(int(current * total)) + + # To run another Processing algorithm as part of this algorithm, you can use + # processing.run(...). Make sure you pass the current context and feedback + # to processing.run to ensure that all temporary layer outputs are available + # to the executed algorithm, and that the executed algorithm can send feedback + # reports to the user (and correctly handle cancellation and progress reports!) + if False: + _buffered_layer = processing.run( + "native:buffer", + { + "INPUT": dest_id, + "DISTANCE": 1.5, + "SEGMENTS": 5, + "END_CAP_STYLE": 0, + "JOIN_STYLE": 0, + "MITER_LIMIT": 2, + "DISSOLVE": False, + "OUTPUT": "memory:", + }, + context=context, + feedback=feedback, + )["OUTPUT"] + + # Return the results of the algorithm. In this case our only result is + # the feature sink which contains the processed features, but some + # algorithms may return multiple feature sinks, calculated numeric + # statistics, etc. These should all be included in the returned + # dictionary, with keys matching the feature corresponding parameter + # or output names. + return {self.OUTPUT: dest_id} diff --git a/arho_feature_template/arho_feature_template_processing/provider.py b/arho_feature_template/arho_feature_template_processing/provider.py new file mode 100644 index 0000000..422ab7d --- /dev/null +++ b/arho_feature_template/arho_feature_template_processing/provider.py @@ -0,0 +1,44 @@ +from qgis.core import QgsProcessingProvider + +from arho_feature_template.arho_feature_template_processing.processing_algorithm import ProcessingAlgorithm + + +class Provider(QgsProcessingProvider): + def __init__(self) -> None: + super().__init__() + + self._id = "myprovider" + self._name = "My provider" + + def id(self) -> str: + """The ID of your plugin, used to identify the provider. + + This string should be a unique, short, character only string, + eg "qgis" or "gdal". This string should not be localised. + """ + return self._id + + def name(self) -> str: + """ + The display name of your plugin in Processing. + + This string should be as short as possible and localised. + """ + return self._name + + def load(self) -> bool: + self.refreshAlgorithms() + return True + + def icon(self): + """ + Returns a QIcon which is used for your provider inside the Processing toolbox. + """ + return QgsProcessingProvider.icon(self) + + def loadAlgorithms(self) -> None: # noqa N802 + """ + Adds individual processing algorithms to the provider. + """ + alg = ProcessingAlgorithm() + self.addAlgorithm(alg) diff --git a/arho_feature_template/build.py b/arho_feature_template/build.py new file mode 100755 index 0000000..7e79ff4 --- /dev/null +++ b/arho_feature_template/build.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python +from __future__ import annotations + +import glob + +from qgis_plugin_tools.infrastructure.plugin_maker import PluginMaker + +""" +################################################# +# Edit the following to match the plugin +################################################# +""" + +py_files = [fil for fil in glob.glob("**/*.py", recursive=True) if "test/" not in fil and "test\\" not in fil] +locales = ["fi"] +profile = "default" +ui_files = list(glob.glob("**/*.ui", recursive=True)) +resources = list(glob.glob("**/*.qrc", recursive=True)) +extra_dirs = ["resources"] +compiled_resources: list[str] = [] + +PluginMaker( + py_files=py_files, + ui_files=ui_files, + resources=resources, + extra_dirs=extra_dirs, + compiled_resources=compiled_resources, + locales=locales, + profile=profile, +) diff --git a/arho_feature_template/metadata.txt b/arho_feature_template/metadata.txt new file mode 100644 index 0000000..4ea1ece --- /dev/null +++ b/arho_feature_template/metadata.txt @@ -0,0 +1,16 @@ +[general] +name=ARHO feature template +description= +about= +version=0.1.0 +qgisMinimumVersion=3.16 +author= +email= +changelog= +tags= +repository=https://github.com/GispoCoding/arho-feature-template +tracker=https://github.com/GispoCoding/arho-feature-template/issues +homepage=https://github.com/GispoCoding/arho-feature-template +category=Plugins +experimental=True +deprecated=False diff --git a/arho_feature_template/plugin.py b/arho_feature_template/plugin.py new file mode 100644 index 0000000..85f87c2 --- /dev/null +++ b/arho_feature_template/plugin.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from typing import Callable + +from qgis.PyQt.QtCore import QCoreApplication, QTranslator +from qgis.PyQt.QtGui import QIcon +from qgis.PyQt.QtWidgets import QAction, QWidget +from qgis.utils import iface + +from arho_feature_template.qgis_plugin_tools.tools.custom_logging import setup_logger, teardown_logger +from arho_feature_template.qgis_plugin_tools.tools.i18n import setup_translation +from arho_feature_template.qgis_plugin_tools.tools.resources import plugin_name + + +class Plugin: + """QGIS Plugin Implementation.""" + + name = plugin_name() + + def __init__(self) -> None: + setup_logger(Plugin.name) + + # initialize locale + locale, file_path = setup_translation() + if file_path: + self.translator = QTranslator() + self.translator.load(file_path) + # noinspection PyCallByClass + QCoreApplication.installTranslator(self.translator) + else: + pass + + self.actions: list[QAction] = [] + self.menu = Plugin.name + + def add_action( + self, + icon_path: str, + text: str, + callback: Callable, + *, + enabled_flag: bool = True, + add_to_menu: bool = True, + add_to_toolbar: bool = True, + status_tip: str | None = None, + whats_this: str | None = None, + parent: QWidget | None = None, + ) -> QAction: + """Add a toolbar icon to the toolbar. + + :param icon_path: Path to the icon for this action. Can be a resource + path (e.g. ':/plugins/foo/bar.png') or a normal file system path. + + :param text: Text that should be shown in menu items for this action. + + :param callback: Function to be called when the action is triggered. + + :param enabled_flag: A flag indicating if the action should be enabled + by default. Defaults to True. + + :param add_to_menu: Flag indicating whether the action should also + be added to the menu. Defaults to True. + + :param add_to_toolbar: Flag indicating whether the action should also + be added to the toolbar. Defaults to True. + + :param status_tip: Optional text to show in a popup when mouse pointer + hovers over the action. + + :param parent: Parent widget for the new action. Defaults None. + + :param whats_this: Optional text to show in the status bar when the + mouse pointer hovers over the action. + + :returns: The action that was created. Note that the action is also + added to self.actions list. + :rtype: QAction + """ + + icon = QIcon(icon_path) + action = QAction(icon, text, parent) + # noinspection PyUnresolvedReferences + action.triggered.connect(callback) + action.setEnabled(enabled_flag) + + if status_tip is not None: + action.setStatusTip(status_tip) + + if whats_this is not None: + action.setWhatsThis(whats_this) + + if add_to_toolbar: + # Adds plugin icon to Plugins toolbar + iface.addToolBarIcon(action) + + if add_to_menu: + iface.addPluginToMenu(self.menu, action) + + self.actions.append(action) + + return action + + def initGui(self) -> None: # noqa N802 + """Create the menu entries and toolbar icons inside the QGIS GUI.""" + self.add_action( + "", + text=Plugin.name, + callback=self.run, + parent=iface.mainWindow(), + add_to_toolbar=False, + ) + + def onClosePlugin(self) -> None: # noqa N802 + """Cleanup necessary items here when plugin dockwidget is closed""" + + def unload(self) -> None: + """Removes the plugin menu item and icon from QGIS GUI.""" + for action in self.actions: + iface.removePluginMenu(Plugin.name, action) + iface.removeToolBarIcon(action) + teardown_logger(Plugin.name) + + def run(self) -> None: + """Run method that performs all the real work""" + print("Hello QGIS plugin") # noqa: T201 diff --git a/arho_feature_template/qgis_plugin_tools b/arho_feature_template/qgis_plugin_tools new file mode 160000 index 0000000..fd8650d --- /dev/null +++ b/arho_feature_template/qgis_plugin_tools @@ -0,0 +1 @@ +Subproject commit fd8650d041ee4eb8e19ab5ab87ff68861aad7550 diff --git a/arho_feature_template/resources/.gitignore b/arho_feature_template/resources/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/arho_feature_template/resources/i18n/.gitignore b/arho_feature_template/resources/i18n/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/arho_feature_template/resources/icons/.gitignore b/arho_feature_template/resources/icons/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/arho_feature_template/resources/ui/.gitignore b/arho_feature_template/resources/ui/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/create_qgis_venv.py b/create_qgis_venv.py new file mode 100644 index 0000000..8f9916f --- /dev/null +++ b/create_qgis_venv.py @@ -0,0 +1,445 @@ +# SPDX-FileCopyrightText: 2024 Gispo Ltd. +# +# SPDX-License-Identifier: MIT + +# ruff: noqa: T201 + +""" +This is a tool for creating a virtual environment for QGIS plugin development. + +Originated from https://github.com/GispoCoding/qgis-venv-creator + +Usage: +python create_qgis_venv.py [--help] [--venv-parent ] [--venv-name ] +""" + +from __future__ import annotations + +import argparse +import logging +import os +import platform +import shutil +import subprocess +import sys +from abc import ABC, abstractmethod +from pathlib import Path +from typing import TYPE_CHECKING, Any, Generator, Protocol, TypedDict, cast + +if TYPE_CHECKING: + + class CliArgsType(TypedDict, total=False): + qgis_installation: Path | None + qgis_installation_search_path_pattern: str | None + venv_parent: Path | None + venv_name: str | None + python_executable: Path | None + debug: bool + + class SupportsVenvCreation(Protocol): + @classmethod + def create_venv(cls, *args: Any, **kwargs: Any) -> Path: ... + + @staticmethod + def cli_arguments() -> list[CliArg]: ... + + +__version__ = "0.1.0" + +cli_args: CliArgsType = {} + + +class CliArg: + """Command line argument definition to be passed to argparse.ArgumentParser.add_argument() + + ```py + import argparse + + parser = argparse.ArgumentParser() + + cli_arg = CliArg("--foo", help="Foo") + parser.add_argument(*cli_arg.args, **cli_arg.kwargs) + + args = parser.parse_args(["--foo", "bar"]) + assert args.foo == "bar" + ``` + """ + + def __init__(self, *args: str, **kwargs: Any): + self.args = args + self.kwargs = kwargs + + +logger = logging.getLogger(__name__) + + +class VenvCreationError(RuntimeError): + def __init__(self): + super().__init__("Failed to create virtual environment") + + +class InvalidPythonExecutableError(RuntimeError): + def __init__(self, executable_path: Path | None): + super().__init__(f"{executable_path} is not a valid Python executable.") + + +class InvalidQgisPathError(RuntimeError): + def __init__(self, qgis_installation: Path | None): + super().__init__(f"{qgis_installation} is not a valid QGIS path.") + + +class VenvParentDirectoryNotExistsError(RuntimeError): + def __init__(self, venv_directory: Path): + super().__init__(f"Virtual environment directory {venv_directory} does not exist.") + + +class GlobPatternError(ValueError): + def __init__(self, pattern: str): + super().__init__(f"Invalid glob pattern: {pattern}. Wildcard in the first directory part is not supported.") + + +class UnsupportedPlatformError(RuntimeError): + def __init__(self, platform: str): + super().__init__(f"Unsupported platform: {platform}.") + + +def _is_valid_python_executable(python_executable: Path | None) -> bool: + """Check if the given path is a valid Python executable.""" + + return python_executable is not None and python_executable.exists() and os.access(python_executable, os.X_OK) + + +def _create_venv(python_executable: Path | None, venv_parent: Path | None = None, venv_name: str | None = None) -> Path: + """Create a virtual environment for a QGIS plugin project.""" + + if python_executable is None or not python_executable.exists() or not os.access(python_executable, os.X_OK): + raise InvalidPythonExecutableError(python_executable) + + venv_parent = venv_parent or Path.cwd() + if not venv_parent.exists(): + raise VenvParentDirectoryNotExistsError(venv_parent) + + venv_name = venv_name or ".venv" + + venv_directory = venv_parent / venv_name + logger.debug("Creating virtual environment to '%s' using '%s'", venv_directory, python_executable) + try: + subprocess.run( + [ + python_executable, + "-m", + "venv", + "--system-site-packages", + venv_directory, + ], + check=True, + ) + except subprocess.CalledProcessError as e: + logger.debug("Failed to create virtual environment. %s", e) + raise VenvCreationError from e + + return venv_directory + + +def _create_glob_generator_from_pattern(pattern: str) -> Generator[Path, None, None]: + """Create a glob generator from a pattern. + + The Path.glob() method does not support absolute paths. This is to overcome that limitation. + """ + + glob_parts: list[str] = [] + part_iterator = iter(Path(pattern).parts) + root_part = next(part_iterator) + if "*" in root_part: + raise GlobPatternError(pattern) + path = Path(root_part) + for part in part_iterator: + if not glob_parts and "*" not in part: + path /= part + else: + glob_parts.append(part) + + return path.glob(os.sep.join(glob_parts)) + + +class Platform(ABC): + @classmethod + @abstractmethod + def create_venv(cls, *args: Any, **kwargs: Any) -> Path: + """Create a virtual environment for plugin project.""" + + @staticmethod + def cli_arguments() -> list[CliArg]: + """Returns environment specific command line arguments to be passed to argparse.ArgumentParser.add_argument()""" + + return [] + + +class MultiQgisPlatform(Platform): + @staticmethod + @abstractmethod + def _find_qgis_installations(qgis_installation_search_path_pattern: str | None = None) -> list[Path]: + """Find all QGIS installations from the system.""" + raise NotImplementedError + + @staticmethod + @abstractmethod + def _is_valid_qgis_path(qgis_path: Path) -> bool: + """Validate that the given path is a valid QGIS installation.""" + raise NotImplementedError + + @staticmethod + @abstractmethod + def _find_qgis_python_executable(qgis_install_directory: Path) -> Path | None: + """Find the Python executable for the QGIS installation.""" + raise NotImplementedError + + @classmethod + @abstractmethod + def create_venv( + cls, + python_executable: Path | None, + qgis_installation: Path | None, + venv_parent: Path, + venv_name: str, + qgis_installation_search_path_pattern: str | None = None, + ) -> Path: + raise NotImplementedError + + @classmethod + def select_qgis_install(cls, custom_search_path_pattern: str | None = None) -> Path: + """Prompts the user to select a QGIS installation from the system.""" + + custom_search_path_pattern = custom_search_path_pattern or os.environ.get( + "QGIS_INSTALLATION_SEARCH_PATH_PATTERN" + ) + qgis_installations = list(cls._find_qgis_installations(custom_search_path_pattern)) + + print("Found following QGIS installations from the system. Which one to use for development?") + for i, path in enumerate(qgis_installations): + print(f" {i+1} - {path}") + custom_selection_index = len(qgis_installations) + 1 + print(f" {custom_selection_index} - Custom") + choose_prompt = f"Choose from [{'/'.join(str(i+1) for i in range(custom_selection_index))}]" + while True: + try: + selection = int(input(f" {choose_prompt}: ")) + except ValueError: + print("Invalid selection.") + continue + + if selection == custom_selection_index: + while True: + custom_qgis_path = Path(input(" Give path to QGIS installation: ")) + if not cls._is_valid_qgis_path(custom_qgis_path): + print("Invalid qgis installation path") + continue + return custom_qgis_path + else: + try: + return qgis_installations[selection - 1] + except IndexError: + print("Invalid selection") + continue + + @staticmethod + def cli_arguments() -> list[CliArg]: + return [ + CliArg( + "--qgis-installation", + help=( + "Path to the QGIS installation to use for development. " + "Installations made with official msi and Osgeo4W instellers are supported. " + "Give the path to the 'qgis' directory inside the 'apps' directory. " + "If not given, the user is prompted to select one." + ), + type=Path, + ), + CliArg( + "--qgis-installation-search-path-pattern", + help=( + "Custom glob pattern for QGIS installations to be selected. " + "Can be set also with QGIS_INSTALLATION_SEARCH_PATH_PATTERN environment variable." + ), + type=str, + ), + CliArg( + "--python-executable", + help=( + "Path to the Python executable used by the QGIS installation. " + "If not given, the Python executable is searched from the QGIS installation." + ), + type=Path, + ), + ] + + +class Windows(MultiQgisPlatform): + @classmethod + def _find_qgis_installations(cls, custom_search_path_pattern: str | None = None) -> list[Path]: + """Find all QGIS installations from the Windows system.""" + + possible_qgis_installation_generators = [ + Path("C:/Program Files").glob("QGIS*/apps/qgis*/"), + Path("C:/OSGeo4W/apps").glob("qgis*/"), + Path("C:/OSGeo4W64/apps").glob("qgis*/"), + ] + + if custom_search_path_pattern is not None: + if not custom_search_path_pattern.endswith(os.sep) or ( + os.altsep is not None and not custom_search_path_pattern.endswith(os.altsep) + ): + custom_search_path_pattern += os.sep + possible_qgis_installation_generators.append( + _create_glob_generator_from_pattern(custom_search_path_pattern) + ) + + return [ + qgis_installation + for possible_qgis_installation_glob in possible_qgis_installation_generators + for qgis_installation in possible_qgis_installation_glob + if cls._is_valid_qgis_path(qgis_installation) + ] + + @staticmethod + def _is_valid_qgis_path(qgis_installation: Path) -> bool: + root = qgis_installation.parent.parent + bin_directory = root / "bin" + qgis_bin_directory = qgis_installation / "bin" + qt5_bin_directory = root / "apps" / "Qt5" / "bin" + python_path = Windows._find_qgis_python_executable(qgis_installation) + if not python_path: + return False + return all(d.exists() for d in (bin_directory, qgis_bin_directory, qt5_bin_directory, python_path)) + + @staticmethod + def _find_qgis_python_executable(qgis_install_directory: Path) -> Path | None: + """Find the Python executable for the QGIS installation.""" + + apps_directory = qgis_install_directory.parent + python_install_directory = next(apps_directory.glob("Python*"), None) + if not python_install_directory: + return None + return python_install_directory / "python.exe" + + @staticmethod + def _create_sitecustomize_file(venv_directory: Path, qgis_installation: Path) -> None: + root = qgis_installation.parent.parent + bin_directory = root / "bin" + qgis_bin_directory = qgis_installation / "bin" + qt5_bin_directory = root / "apps" / "Qt5" / "bin" + + content = ( + "import os\n" + "\n" + f"os.add_dll_directory('{bin_directory.as_posix()}')\n" + f"os.add_dll_directory('{qgis_bin_directory.as_posix()}')\n" + f"os.add_dll_directory('{qt5_bin_directory.as_posix()}')\n" + ) + sitecustomize_file_path = venv_directory / "Lib" / "site-packages" / "sitecustomize.py" + logger.debug("Writing site customize file to '%s'", sitecustomize_file_path) + sitecustomize_file_path.write_text(content, encoding="utf-8") + + @staticmethod + def _create_path_configuration_file(venv_directory: Path, qgis_installation: Path) -> None: + content = (qgis_installation / "python").as_posix() + "\n" + + path_file_path = venv_directory / "qgis.pth" + logger.debug("Writing qgis path configuration to '%s'", path_file_path) + path_file_path.write_text(content, encoding="utf-8") + + @staticmethod + def _patch_venv(venv_directory: Path, qgis_installation: Path) -> None: + Windows._create_path_configuration_file(venv_directory, qgis_installation) + Windows._create_sitecustomize_file(venv_directory, qgis_installation) + + @classmethod + def create_venv( + cls, + python_executable: Path | None, + qgis_installation: Path | None, + venv_parent: Path, + venv_name: str, + qgis_installation_search_path_pattern: str | None = None, + ) -> Path: + qgis_installation = qgis_installation or cls.select_qgis_install(qgis_installation_search_path_pattern) + if not cls._is_valid_qgis_path(qgis_installation): + raise InvalidQgisPathError(qgis_installation) + python_executable = python_executable or cls._find_qgis_python_executable(qgis_installation) + if not _is_valid_python_executable(python_executable): + raise InvalidPythonExecutableError(python_executable) + venv_directory = _create_venv(python_executable, venv_parent, venv_name=venv_name) + + cls._patch_venv(venv_directory, qgis_installation) + + return venv_directory + + +class Linux(Platform): + @classmethod + def create_venv( + cls, python_executable: Path | None = None, venv_parent: Path | None = None, venv_name: str | None = None + ) -> Path: + if python_executable is None: + python3_command = Path("python3") + python3_executable = shutil.which(python3_command) + if python3_executable is None: + raise InvalidPythonExecutableError(python3_command) + python_executable = Path(python3_executable) + + return _create_venv(python_executable, venv_parent, venv_name=venv_name) + + +def cli() -> None: + """Create a virtual environment for a QGIS plugin project.""" + + environments: dict[str, SupportsVenvCreation] = { + "Windows": Windows, + "Linux": Linux, + # "Darwin": MacOs, TODO: Implement MacOs support + } + environment = environments.get(platform.system()) + if environment is None: + raise UnsupportedPlatformError(platform.system()) + + parser = argparse.ArgumentParser() + parser.add_argument( + "--venv-parent", + help=( + "Path to the parent directory of the virtual environment to be created. " + "Most likely your project directory. Default current directory." + ), + type=Path, + default=Path.cwd(), + ) + parser.add_argument("--venv-name", help="Name of the virtual environment", default=".venv") + for cli_arg in environment.cli_arguments(): + parser.add_argument(*cli_arg.args, **cli_arg.kwargs) + parser.add_argument("--debug", action="store_true", help="Enable debug logging") + + args = cast("CliArgsType", vars(parser.parse_args())) + cli_args.update(args) + + if args.pop("debug"): + logging.basicConfig(level=logging.DEBUG) + + try: + environment.create_venv(**args) + except VenvCreationError: + print("Virtual environment creation failed", file=sys.stderr) + sys.exit(1) + except (InvalidPythonExecutableError, InvalidQgisPathError) as e: + print(str(e), file=sys.stderr) + sys.exit(1) + + +def main() -> None: + try: + cli() + except KeyboardInterrupt: + print("Virtual environment creation cancelled", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..8e08573 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,173 @@ +Development of arho-feature-template plugin +=========================== + +This project uses [qgis_plugin_tools](https://github.com/GispoCoding/qgis_plugin_tools) submodule, +so set git setting value: `git config --global submodule.recurse true`. + +When cloning use `--recurse-submodules` like so: +`git clone --recurse-submodules https://github.com/GispoCoding/arho-feature-template.git` + +When pulling from existing repo: +```sh +git submodule init +git submodule update +``` + + +The code for the plugin is in the [arho_feature_template](../arho-feature-template) folder. Make sure you have required tools, such as +Qt with Qt Editor and Qt Linquist installed by following this +[tutorial](https://www.qgistutorials.com/en/docs/3/building_a_python_plugin.html#get-the-tools). + +For building the plugin use platform independent [build.py](../arho-feature-template/build.py) script. + +## Setting up development environment + +To get started with the development, follow these steps: + +1. Go to the [arho_feature_template](../arho-feature-template) directory with a terminal +1. Create a new Python virtual environment with pre-commit using Python aware of QGIS libraries: + ```shell + python build.py venv + ``` + In Windows it would be best to use python-qgis.bat or python-qgis-ltr.bat: + ```shell + C:\OSGeo4W64\bin\python-qgis.bat build.py venv + ``` +1. **Note: This part is only for developers that are using QGIS < 3.16.8.** If you want to use IDE for development, it is best to start it with the + following way on Windows: + ```shell + :: Check out the arguments with python build.py start_ide -h + set QGIS_DEV_IDE= + set QGIS_DEV_OSGEO4W_ROOT=C:\OSGeo4W64 + set QGIS_DEV_PREFIX_PATH=C:\OSGeo4W64\apps\qgis-ltr + C:\OSGeo4W64\bin\python-qgis.bat build.py start_ide + :: If you want to create a bat script for starting the ide, you can do it with: + C:\OSGeo4W64\bin\python-qgis.bat build.py start_ide --save_to_disk + ``` + +Now the development environment should be all-set. + +If you want to edit or disable some quite strict pre-commit scripts, edit .pre-commit-config.yaml. +For example to disable typing, remove mypy hook and flake8-annotations from the file. + +## Keeping dependencies up to date + +1. Activate the virtual environment. +2. `pip install pip-tools` +3. `pip-compile --upgrade requirements-dev.in` +4. `pip install -r requirements-dev.txt` or `pip-sync requirements-dev.txt` + +## Adding or editing source files + +If you create or edit source files make sure that: + +* they contain absolute imports: + ```python + from arho_feature_template.utils.exceptions import TestException # Good + + from ..utils.exceptions import TestException # Bad + + ``` +* they will be found by [build.py](../arho_feature_template/build.py) script (`py_files` and `ui_files` values) + +* you consider adding test files for the new functionality +## Deployment + +Edit [build.py](../arho_feature_template/build.py) to contain working values for *profile*, *lrelease* and *pyrcc*. If you are +running on Windows, make sure the value *QGIS_INSTALLATION_DIR* points to right folder + +Run the deployment with: + +```shell script +python build.py deploy +``` + +After deploying and restarting QGIS you should see the plugin in the QGIS installed plugins where you have to activate +it. + + +## Testing + +Install python packages listed in [requirements-dev.txt](../requirements-dev.txt) to the virtual environment +and run tests with: + +```shell script +pytest +``` + +## Translating + +### Translating with Transifex + +Fill in `transifex_coordinator` (Transifex username) and `transifex_organization` +in [.qgis-plugin-ci](../.qgis-plugin-ci) to use Transifex translation. + +If you want to see the translations during development, add `i18n` to the `extra_dirs` in `build.py`: + +```python +extra_dirs = ["resources", "i18n"] +``` + +#### Pushing / creating new translations + +For step-by-step instructions, read the [translation tutorial](./translation_tutorial.md#Tutorial). + +* First, install [Transifex CLI](https://docs.transifex.com/client/installing-the-client) and + [qgis-plugin-ci](https://github.com/opengisch/qgis-plugin-ci) +* Make sure command `pylupdate5` works. Otherwise install it with `pip install pyqt5` +* Run `qgis-plugin-ci push-translation ` +* Go to your Transifex site, add some languages and start translating +* Copy [push_translations.yml](push_translations.yml) file to [workflows](../.github/workflows) folder to enable + automatic pushing after commits to master +* Add this badge ![](https://github.com/GispoCoding/arho-feature-template/workflows/Translations/badge.svg) to + the [README](../README.md) + +##### Pulling + +There is no need to pull if you configure `--transifex-token` into your +[release](../.github/workflows/release.yml) workflow (remember to use Github Secrets). Remember to uncomment the +lrelease section as well. You can however pull manually to test the process. + +* Run `qgis-plugin-ci pull-translation --compile `#### Translating with QT Linguistic (if Transifex not available) + +The translation files are in [i18n](../arho-feature-template/resources/i18n) folder. Translatable content in python files is +code such as `tr(u"Hello World")`. + +To update language *.ts* files to contain newest lines to translate, run + +```shell script +python build.py transup +``` + +You can then open the *.ts* files you wish to translate with Qt Linguist and make the changes. + +Compile the translations to *.qm* files with: + +```shell script +python build.py transcompile +``` + + +### Github Release + +Follow these steps to create a release + +* Add changelog information to [CHANGELOG.md](../CHANGELOG.md) using this + [format](https://raw.githubusercontent.com/opengisch/qgis-plugin-ci/master/CHANGELOG.md) +* Make a new commit. (`git add -A && git commit -m "Release 0.1.0"`) +* Create new tag for it (`git tag -a 0.1.0 -m "Version 0.1.0"`) +* Push tag to Github using `git push --follow-tags` +* Create Github release +* [qgis-plugin-ci](https://github.com/opengisch/qgis-plugin-ci) adds release zip automatically as an asset + +Modify [release](../.github/workflows/release.yml) workflow according to its comments if you want to upload the +plugin to QGIS plugin repository. + +### Local release + +For local release install [qgis-plugin-ci](https://github.com/opengisch/qgis-plugin-ci) (possibly to different venv +to avoid Qt related problems on some environments) and follow these steps: +```shell +cd arho-feature-template +qgis-plugin-ci package --disable-submodule-update 0.1.0 +``` diff --git a/docs/push_translations.yml b/docs/push_translations.yml new file mode 100644 index 0000000..325c665 --- /dev/null +++ b/docs/push_translations.yml @@ -0,0 +1,26 @@ +name: Translations + +on: + push: + branches: + - master + +jobs: + push_translations: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + submodules: true + + - name: Set up Python 3.8 + uses: actions/setup-python@v1 + with: + python-version: 3.8 + + - name: Install qgis-plugin-ci + run: pip3 install qgis-plugin-ci + + - name: Push translations + run: qgis-plugin-ci push-translation ${{ secrets.TRANSIFEX_TOKEN }} diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..7d62774 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[tool.pytest.ini_options] +addopts = "-v" + +[tool.coverage.report] +omit = ["arho_feature_template/qgis_plugin_tools/*"] + +[tool.ruff] +target-version = "py38" +extend = "ruff_defaults.toml" + + +exclude = ["arho_feature_template/qgis_plugin_tools"] + +[tool.ruff.lint] + +unfixable = [ + "F401", # unused imports + "F841", # unused variables +] + +[[tool.mypy.overrides]] +module = "arho_feature_template.qgis_plugin_tools.*" +ignore_errors = true + +[[tool.mypy.overrides]] +module = ["qgis.*", "osgeo.*"] +ignore_missing_imports = true diff --git a/requirements-dev.in b/requirements-dev.in new file mode 100644 index 0000000..42e975a --- /dev/null +++ b/requirements-dev.in @@ -0,0 +1,20 @@ +# Debugging +debugpy + +# Dependency maintenance +pip-tools + +# Testing +pytest +pytest-cov +pytest-qgis + +# Linting and formatting +pre-commit +mypy +ruff +flake8 +flake8-qgis + +# Stubs +PyQt5-stubs diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..e69de29 diff --git a/ruff_defaults.toml b/ruff_defaults.toml new file mode 100644 index 0000000..8b6d10f --- /dev/null +++ b/ruff_defaults.toml @@ -0,0 +1,527 @@ +line-length = 120 + +[format] +docstring-code-format = true +docstring-code-line-length = 80 + +[lint] +select = [ + "A001", + "A002", + "A003", + "ARG001", + "ARG002", + "ARG003", + "ARG004", + "ARG005", + "ASYNC210", + "ASYNC220", + "ASYNC221", + "ASYNC230", + "ASYNC251", + "B002", + "B003", + "B004", + "B005", + "B006", + "B007", + "B008", + "B009", + "B010", + "B011", + "B012", + "B013", + "B014", + "B015", + "B016", + "B017", + "B018", + "B019", + "B020", + "B021", + "B022", + "B023", + "B024", + "B025", + "B026", + "B028", + "B029", + "B030", + "B031", + "B032", + "B033", + "B034", + "B904", + "B905", + "BLE001", + "C400", + "C401", + "C402", + "C403", + "C404", + "C405", + "C406", + "C408", + "C409", + "C410", + "C411", + "C413", + "C414", + "C415", + "C416", + "C417", + "C418", + "C419", + "COM818", + "DTZ001", + "DTZ002", + "DTZ003", + "DTZ004", + "DTZ005", + "DTZ006", + "DTZ007", + "DTZ011", + "DTZ012", + "E101", + "E401", + "E402", + "E501", + "E701", + "E702", + "E703", + "E711", + "E712", + "E713", + "E714", + "E721", + "E722", + "E731", + "E741", + "E742", + "E743", + "E902", + "E999", + "EM101", + "EM102", + "EM103", + "EXE001", + "EXE002", + "EXE003", + "EXE004", + "EXE005", + "F401", + "F402", + "F403", + "F404", + "F405", + "F406", + "F407", + "F501", + "F502", + "F503", + "F504", + "F505", + "F506", + "F507", + "F508", + "F509", + "F521", + "F522", + "F523", + "F524", + "F525", + "F541", + "F601", + "F602", + "F621", + "F622", + "F631", + "F632", + "F633", + "F634", + "F701", + "F702", + "F704", + "F706", + "F707", + "F722", + "F811", + "F821", + "F822", + "F823", + "F841", + "F842", + "F901", + "FA100", + "FA102", + "FBT001", + "FBT002", + "FLY002", + "G001", + "G002", + "G003", + "G004", + "G010", + "G101", + "G201", + "G202", + "I001", + "I002", + "ICN001", + "ICN002", + "ICN003", + "INP001", + "INT001", + "INT002", + "INT003", + "ISC003", + "N801", + "N802", + "N803", + "N804", + "N805", + "N806", + "N807", + "N811", + "N812", + "N813", + "N814", + "N815", + "N816", + "N817", + "N818", + "N999", + "PERF101", + "PERF102", + "PERF401", + "PERF402", + "PGH001", + "PGH002", + "PGH005", + "PIE790", + "PIE794", + "PIE796", + "PIE800", + "PIE804", + "PIE807", + "PIE808", + "PIE810", + "PLC0105", + "PLC0131", + "PLC0132", + "PLC0205", + "PLC0208", + "PLC0414", + "PLC3002", + "PLE0100", + "PLE0101", + "PLE0116", + "PLE0117", + "PLE0118", + "PLE0241", + "PLE0302", + "PLE0307", + "PLE0604", + "PLE0605", + "PLE1142", + "PLE1205", + "PLE1206", + "PLE1300", + "PLE1307", + "PLE1310", + "PLE1507", + "PLE1700", + "PLE2502", + "PLE2510", + "PLE2512", + "PLE2513", + "PLE2514", + "PLE2515", + "PLR0124", + "PLR0133", + "PLR0206", + "PLR0402", + "PLR1701", + "PLR1711", + "PLR1714", + "PLR1722", + "PLR2004", + "PLR5501", + "PLW0120", + "PLW0127", + "PLW0129", + "PLW0131", + "PLW0406", + "PLW0602", + "PLW0603", + "PLW0711", + "PLW1508", + "PLW1509", + "PLW1510", + "PLW2901", + "PLW3301", + "PT001", + "PT002", + "PT003", + "PT006", + "PT007", + "PT008", + "PT009", + "PT010", + "PT011", + "PT012", + "PT013", + "PT014", + "PT015", + "PT016", + "PT017", + "PT018", + "PT019", + "PT020", + "PT021", + "PT022", + "PT023", + "PT024", + "PT025", + "PT026", + "PT027", + "PYI001", + "PYI002", + "PYI003", + "PYI004", + "PYI005", + "PYI006", + "PYI007", + "PYI008", + "PYI009", + "PYI010", + "PYI011", + "PYI012", + "PYI013", + "PYI014", + "PYI015", + "PYI016", + "PYI017", + "PYI018", + "PYI019", + "PYI020", + "PYI021", + "PYI024", + "PYI025", + "PYI026", + "PYI029", + "PYI030", + "PYI032", + "PYI033", + "PYI034", + "PYI035", + "PYI036", + "PYI041", + "PYI042", + "PYI043", + "PYI044", + "PYI045", + "PYI046", + "PYI047", + "PYI048", + "PYI049", + "PYI050", + "PYI051", + "PYI052", + "PYI053", + "PYI054", + "PYI055", + "PYI056", + "RET503", + "RET504", + "RET505", + "RET506", + "RET507", + "RET508", + "RSE102", + "RUF001", + "RUF002", + "RUF003", + "RUF005", + "RUF006", + "RUF007", + "RUF008", + "RUF009", + "RUF010", + "RUF011", + "RUF012", + "RUF013", + "RUF015", + "RUF016", + "RUF100", + "RUF200", + "S101", + "S102", + "S103", + "S104", + "S105", + "S106", + "S107", + "S108", + "S110", + "S112", + "S113", + "S301", + "S302", + "S303", + "S304", + "S305", + "S306", + "S307", + "S308", + "S310", + "S311", + "S312", + "S313", + "S314", + "S315", + "S316", + "S317", + "S318", + "S319", + "S320", + "S321", + "S323", + "S324", + "S501", + "S506", + "S508", + "S509", + "S601", + "S602", + "S604", + "S605", + "S606", + "S607", + "S608", + "S609", + "S612", + "S701", + "SIM101", + "SIM102", + "SIM103", + "SIM105", + "SIM107", + "SIM108", + "SIM109", + "SIM110", + "SIM112", + "SIM114", + "SIM115", + "SIM116", + "SIM117", + "SIM118", + "SIM201", + "SIM202", + "SIM208", + "SIM210", + "SIM211", + "SIM212", + "SIM220", + "SIM221", + "SIM222", + "SIM223", + "SIM300", + "SIM910", + "SLF001", + "SLOT000", + "SLOT001", + "SLOT002", + "T100", + "T201", + "T203", + "TCH001", + "TCH002", + "TCH003", + "TCH004", + "TCH005", + "TD004", + "TD005", + "TD006", + "TD007", + "TID251", + "TID252", + "TID253", + "TRY002", + "TRY003", + "TRY004", + "TRY200", + "TRY201", + "TRY300", + "TRY301", + "TRY302", + "TRY400", + "TRY401", + "UP001", + "UP003", + "UP004", + "UP005", + "UP006", + "UP007", + "UP008", + "UP009", + "UP010", + "UP011", + "UP012", + "UP013", + "UP014", + "UP015", + "UP017", + "UP018", + "UP019", + "UP020", + "UP021", + "UP022", + "UP023", + "UP024", + "UP025", + "UP026", + "UP027", + "UP028", + "UP029", + "UP030", + "UP031", + "UP032", + "UP033", + "UP034", + "UP035", + "UP036", + "UP037", + "UP038", + "UP039", + "UP040", + "W291", + "W292", + "W293", + "W505", + "W605", + "YTT101", + "YTT102", + "YTT103", + "YTT201", + "YTT202", + "YTT203", + "YTT204", + "YTT301", + "YTT302", + "YTT303", +] + +[lint.per-file-ignores] +"**/scripts/*" = ["INP001", "T201"] +"**/tests/**/*" = ["PLC1901", "PLR2004", "PLR6301", "S", "TID252"] + +[lint.flake8-tidy-imports] +ban-relative-imports = "all" + +[lint.isort] +known-first-party = ["arho_feature_template"] + +[lint.flake8-pytest-style] +fixture-parentheses = false +mark-parentheses = false diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..f420bbf --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,15 @@ +""" +This class contains fixtures and common helper function to keep the test files +shorter. + +pytest-qgis (https://pypi.org/project/pytest-qgis) contains the following helpful +fixtures: + +* qgis_app initializes and returns fully configured QgsApplication. + This fixture is called automatically on the start of pytest session. +* qgis_canvas initializes and returns QgsMapCanvas +* qgis_iface returns mocked QgsInterface +* new_project makes sure that all the map layers and configurations are removed. + This should be used with tests that add stuff to QgsProject. + +""" diff --git a/tests/test_plugin.py b/tests/test_plugin.py new file mode 100644 index 0000000..8a5941e --- /dev/null +++ b/tests/test_plugin.py @@ -0,0 +1,5 @@ +from arho_feature_template.qgis_plugin_tools.tools.resources import plugin_name + + +def test_plugin_name(): + assert plugin_name() == "ARHOfeaturetemplate"