├── qgispluginci ├── __init__.py ├── translation_clients │ ├── __init__.py │ ├── baseclient.py │ └── transifex.py ├── __main__.py ├── exceptions.py ├── version_note.py ├── plugins.xml.template ├── utils.py ├── translation.py ├── changelog.py ├── cli.py ├── parameters.py └── release.py ├── requirements ├── translation.txt ├── development.txt ├── documentation.txt └── base.txt ├── requirements.txt ├── docs ├── development │ ├── history.md │ ├── contribute.md │ ├── environment.md │ ├── testing.md │ └── documentation.md ├── robots.txt ├── misc │ ├── credits.md │ └── faq.md ├── configuration │ ├── exclude.md │ ├── submodules.md │ ├── translation.md │ ├── plugin_path.md │ └── options.md ├── usage │ ├── cli_translation.md │ ├── ci_docker.md │ ├── ci_gitlab.md │ ├── ci_travis.md │ ├── ci_github.md │ ├── cli_changelog.md │ ├── cli_package.md │ └── cli_release.md ├── conf.py └── index.md ├── nose2.cfg ├── test ├── __init__.py ├── fixtures │ ├── setup.cfg │ ├── pyproject.toml │ ├── .qgis-plugin-ci-test-changelog.yaml │ ├── .qgis-plugin-ci │ └── CHANGELOG.md ├── utils.py ├── plugins.xml.expected ├── test_parameters.py ├── test_utils.py ├── test_translation.py ├── test_changelog.py └── test_release.py ├── qgis_plugin_CI_testing ├── icons │ └── opengisch.png ├── resources.qrc ├── metadata.txt ├── __init__.py ├── qgis_plugin_ci_testing_plugin.py └── ui │ └── config.ui ├── .gitmodules ├── .github ├── dependabot.yml ├── release.yml └── workflows │ ├── wheel.yml │ ├── test.yml │ ├── release.yml │ └── docs_builder.yml ├── .qgis-plugin-ci ├── .gitignore ├── CONTRIBUTING.md ├── .pre-commit-config.yaml ├── setup.cfg ├── pyproject.toml ├── README.md ├── CHANGELOG.md └── LICENSE /qgispluginci/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements/translation.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /qgispluginci/translation_clients/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -r requirements/base.txt 2 | -------------------------------------------------------------------------------- /docs/development/history.md: -------------------------------------------------------------------------------- 1 | ```{include} ../../CHANGELOG.md 2 | ``` 3 | -------------------------------------------------------------------------------- /docs/development/contribute.md: -------------------------------------------------------------------------------- 1 | ```{include} ../../CONTRIBUTING.md 2 | ``` 3 | -------------------------------------------------------------------------------- /docs/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | 3 | Sitemap: https://opengisch.github.io/qgis-plugin-ci/sitemap.xml 4 | -------------------------------------------------------------------------------- /qgispluginci/__main__.py: -------------------------------------------------------------------------------- 1 | from qgispluginci.cli import cli 2 | 3 | if __name__ == "__main__": 4 | cli() 5 | -------------------------------------------------------------------------------- /nose2.cfg: -------------------------------------------------------------------------------- 1 | [unittest] 2 | start-dir = test 3 | code-directories = .. 4 | 5 | [log-capture] 6 | always-on = True 7 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | 4 | logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) 5 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/icons/opengisch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opengisch/qgis-plugin-ci/HEAD/qgis_plugin_CI_testing/icons/opengisch.png -------------------------------------------------------------------------------- /test/fixtures/setup.cfg: -------------------------------------------------------------------------------- 1 | [qgis-plugin-ci] 2 | plugin_path = qgis_plugin_CI_testing 3 | github_organization_slug = opengisch 4 | project_slug = qgis_plugin_ci_testing 5 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/resources.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | icons/opengisch.png 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "qgis_plugin_ci_testing/qgissettingmanager"] 2 | path = qgis_plugin_CI_testing/qgissettingmanager 3 | url = https://github.com/opengisch/qgissettingmanager.git 4 | -------------------------------------------------------------------------------- /test/fixtures/pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.qgis-plugin-ci] 2 | plugin_path = "qgis_plugin_CI_testing" 3 | github_organization_slug = "opengisch" 4 | project_slug = "qgis_plugin_ci_testing" 5 | -------------------------------------------------------------------------------- /test/fixtures/.qgis-plugin-ci-test-changelog.yaml: -------------------------------------------------------------------------------- 1 | plugin_path: qgis_plugin_CI_testing 2 | github_organization_slug: opengisch 3 | project_slug: qgis-plugin-ci-changelog 4 | create_date: 1985-07-21 5 | -------------------------------------------------------------------------------- /docs/misc/credits.md: -------------------------------------------------------------------------------- 1 | # Credits 2 | 3 | - [Python 3](https://www.python.org/) 4 | 5 | ## Dependencies 6 | 7 | > Generated with [pip-licenses](https://pypi.org/project/pip-licenses/) 8 | 9 | ```{include} licenses.md 10 | 11 | ``` 12 | -------------------------------------------------------------------------------- /requirements/development.txt: -------------------------------------------------------------------------------- 1 | # Develoment dependencies 2 | # ----------------------- 3 | 4 | # tooling 5 | flake8-builtins>=1.5 6 | flake8-print>=5 7 | pre-commit>=3,<5 8 | ruff>=0.11.7,<0.14 9 | 10 | # for testing 11 | nose2>=0.15.1,<0.16 12 | -------------------------------------------------------------------------------- /requirements/documentation.txt: -------------------------------------------------------------------------------- 1 | # Documentation 2 | 3 | furo>=2024 4 | myst-parser[linkify]>=4 5 | sphinx-autobuild>=2024 6 | sphinx-copybutton>=0.5 7 | sphinx-design>=0.6.0 8 | sphinx-sitemap>=2.4 9 | tomli >= 2.2; python_full_version < '3.11' 10 | -------------------------------------------------------------------------------- /docs/configuration/exclude.md: -------------------------------------------------------------------------------- 1 | # Exclude files in the plugin archive 2 | 3 | If you want to avoid some files to be shipped with your plugin, create a `.gitattributes` file in which you can specify the files to ignore. For instance: 4 | 5 | ```gitignore 6 | resources.qrc export-ignore 7 | ``` 8 | -------------------------------------------------------------------------------- /requirements/base.txt: -------------------------------------------------------------------------------- 1 | # Project dependencies 2 | # ----------------------- 3 | 4 | GitPython>=3.1,<3.2 5 | PyGithub>=2,<2.9 6 | PyQt5>=5.15,<5.16 7 | pyqt5ac>=1.2,<1.3 8 | python-slugify>=4.0,<8.1 9 | pyyaml>=5.4,<6.1 10 | six>=1.16.0 11 | transifex-python>=3.2,<4.0 12 | tomli >= 2.2; python_full_version < '3.11' 13 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/requirements" 5 | schedule: 6 | interval: "cron" 7 | cronjob: "0 6 5 */3 *" 8 | 9 | - package-ecosystem: "github-actions" 10 | directory: "/" 11 | schedule: 12 | interval: "cron" 13 | cronjob: "0 6 5 */3 *" 14 | -------------------------------------------------------------------------------- /.qgis-plugin-ci: -------------------------------------------------------------------------------- 1 | plugin_path: qgis_plugin_CI_testing 2 | github_organization_slug: opengisch 3 | project_slug: qgis-plugin-ci 4 | transifex_coordinator: geoninja 5 | transifex_organization: pytransifex 6 | translation_languages: 7 | - fr 8 | - it 9 | - de 10 | create_date: 1985-07-21 11 | 12 | repository_url: https://github.com/opengisch/qgis-plugin-ci/ 13 | 14 | #lrelease_path: /usr/local/opt/qt5/bin/lrelease 15 | -------------------------------------------------------------------------------- /test/fixtures/.qgis-plugin-ci: -------------------------------------------------------------------------------- 1 | plugin_path: qgis_plugin_CI_testing 2 | github_organization_slug: opengisch 3 | project_slug: qgis-plugin-ci 4 | transifex_coordinator: geoninja 5 | transifex_organization: pytransifex 6 | translation_languages: 7 | - fr 8 | - it 9 | - de 10 | create_date: 1985-07-21 11 | 12 | repository_url: https://github.com/opengisch/qgis-plugin-ci/ 13 | 14 | #lrelease_path: /usr/local/opt/qt5/bin/lrelease 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Sphinx documentation 2 | docs/_apidoc/ 3 | docs/_build/ 4 | docs/_autosummary/ 5 | build/ 6 | dist/ 7 | *.egg-info 8 | Pipfile 9 | Pipfile.lock 10 | 11 | *.orig 12 | 13 | __pycache__/ 14 | *.pyc 15 | *.tar 16 | *.zip 17 | 18 | qgis_plugin_CI_testing/i18n 19 | qgis_plugin_CI_testing/resources_rc.py 20 | 21 | .tokens 22 | 23 | .idea 24 | .DS_Store 25 | .venv 26 | .vscode/settings.json 27 | dev_precommit_black.log 28 | 29 | htmlcov 30 | junit 31 | .coverage 32 | coverage.xml 33 | -------------------------------------------------------------------------------- /docs/development/environment.md: -------------------------------------------------------------------------------- 1 | # Development 2 | 3 | ## Environment setup 4 | 5 | Typically on Ubuntu: 6 | 7 | ```bash 8 | # create virtual environment linking to system packages (for pyqgis) 9 | python3 -m venv .venv 10 | 11 | # bump dependencies inside venv 12 | python -m pip install -U pip setuptools wheel 13 | python -m pip install -U -r requirements.txt 14 | 15 | # install git hooks 16 | pre-commit install 17 | 18 | # install project as editable 19 | python -m pip install -e . 20 | ``` 21 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | authors: 4 | - dependabot 5 | - pre-commit-ci 6 | categories: 7 | - title: Bugs fixes 🐛 8 | labels: 9 | - bug 10 | - title: Features and enhancements 🎉 11 | labels: 12 | - enhancement 13 | - title: Tooling 🔧 14 | labels: 15 | - github_actions 16 | - title: Documentation 📖 17 | labels: 18 | - documentation 19 | - title: Other Changes 20 | labels: 21 | - "*" 22 | -------------------------------------------------------------------------------- /docs/configuration/submodules.md: -------------------------------------------------------------------------------- 1 | # Handle submodules SSH 2 | 3 | If you have any submodule configured using ssh and not https, you need to change the connection url. For example, on Travis: 4 | 5 | ````yaml 6 | git: 7 | submodules: false 8 | 9 | before_install: 10 | # cannot use SSH to fetch submodule 11 | - sed -i 's#git@github.com:#https://github.com/#' .gitmodules 12 | - git submodule update --init --recursive 13 | ```` 14 | 15 | When packaging the plugin, it's possible to not update the submodule using CLI options. 16 | -------------------------------------------------------------------------------- /docs/development/testing.md: -------------------------------------------------------------------------------- 1 | # Tests 2 | 3 | ## System requirements 4 | 5 | ```bash 6 | sudo apt-get update 7 | sudo apt-get install qt5-default qttools5-dev-tools 8 | ``` 9 | 10 | ## Environment variables 11 | 12 | ```bash 13 | export github_token={CHANGE_WITH_A_REAL_GITHUB_TOKEN} 14 | export transifex_token={CHANGE_WITH_A_REAL_TRANSIFEX_TOKEN} 15 | ``` 16 | 17 | ## Run tests 18 | 19 | Run all tests: 20 | 21 | ```bash 22 | nose2 -v 23 | ``` 24 | 25 | Run a specific test: 26 | 27 | ```bash 28 | python -m unittest test.test_changelog 29 | ``` 30 | -------------------------------------------------------------------------------- /docs/configuration/translation.md: -------------------------------------------------------------------------------- 1 | # Using Transifex to translate your plugin 2 | 3 | ```yaml 4 | jobs: 5 | include: 6 | - stage: push-translation 7 | if: branch = master 8 | script: qgis-plugin-ci push-translation ${TX_TOKEN} 9 | 10 | - stage: deploy 11 | if: tag IS present 12 | script: 13 | - > 14 | qgis-plugin-ci release ${TRAVIS_TAG} 15 | --transifex-token ${TX_TOKEN} 16 | --github-token ${GH_TOKEN} 17 | --osgeo-username ${OSGEO_USERNAME} 18 | --osgeo-password ${OSGEO_PASSWORD} 19 | ``` 20 | -------------------------------------------------------------------------------- /docs/configuration/plugin_path.md: -------------------------------------------------------------------------------- 1 | # Plugin source path 2 | 3 | The plugin path should be named in a distinctive form for the plugin 4 | as it will be used in QGIS for the plugin folder name. 5 | For instance, `my_super_transformer` for _My Super Transformer_ plugin. 6 | 7 | Also, [`use_project_slug_as_plugin_directory`](/_apidoc/qgispluginci.parameters) can be used to alter this behavior. 8 | If the source directory is not at the top level, the [`project_slug`](/_apidoc/qgispluginci.parameters) 9 | will automatically be used in any case. 10 | 11 | Side note, the plugin path shouldn't contain any dash character. 12 | -------------------------------------------------------------------------------- /qgispluginci/exceptions.py: -------------------------------------------------------------------------------- 1 | class BuiltResourceInSources(Exception): 2 | pass 3 | 4 | 5 | class ConfigurationNotFound(Exception): 6 | pass 7 | 8 | 9 | class GithubReleaseCouldNotUploadAsset(Exception): 10 | pass 11 | 12 | 13 | class GithubReleaseNotFound(Exception): 14 | pass 15 | 16 | 17 | class MissingChangelog(Exception): 18 | pass 19 | 20 | 21 | class TransifexManyResources(Warning): 22 | pass 23 | 24 | 25 | class TransifexNoResource(Exception): 26 | pass 27 | 28 | 29 | class TranslationFailed(Exception): 30 | pass 31 | 32 | 33 | class UncommitedChanges(Exception): 34 | pass 35 | -------------------------------------------------------------------------------- /docs/usage/cli_translation.md: -------------------------------------------------------------------------------- 1 | # Commands related to the translation 2 | 3 | ## Pull translations 4 | 5 | ```bash 6 | usage: qgis-plugin-ci pull-translation [-h] [--compile] transifex_token 7 | 8 | positional arguments: 9 | transifex_token The Transifex API token 10 | 11 | optional arguments: 12 | -h, --help show this help message and exit 13 | --compile Will compile TS files into QM files 14 | ``` 15 | 16 | ## Push translations 17 | 18 | ```bash 19 | usage: qgis-plugin-ci push-translation [-h] transifex_token 20 | 21 | positional arguments: 22 | transifex_token The Transifex API token 23 | 24 | optional arguments: 25 | -h, --help show this help message and exit 26 | ``` 27 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/metadata.txt: -------------------------------------------------------------------------------- 1 | 2 | [general] 3 | name=QGIS Plugin CI Testing 4 | qgisMinimumVersion=3.2 5 | description=This is a testing plugin for QGIS Plugin CI 6 | about=Downloading would be useless 7 | version=dev 8 | author=Denis Rouzaud 9 | email=denis@opengis.ch 10 | changelog=changelog 11 | 12 | # Tags are comma separated with spaces allowed 13 | tags= 14 | 15 | tracker=https://github.com/opengisch/qgis-plugin-ci/issues 16 | homepage=https://github.com/opengisch/qgis-plugin-ci 17 | repository=https://github.com/opengisch/qgis-plugin-ci 18 | 19 | category=plugins 20 | 21 | # experimental flag 22 | experimental=True 23 | 24 | # change icon... 25 | icon=icons/opengisch.png 26 | 27 | [tool:qgis-plugin-ci] 28 | commitNumber= 29 | -------------------------------------------------------------------------------- /docs/usage/ci_docker.md: -------------------------------------------------------------------------------- 1 | # Docker 2 | 3 | 3Liz is maintaining a small docker image of this package available on [GitHub](https://github.com/3liz/docker-qgis-plugin-ci) 4 | and [Docker Hub](https://hub.docker.com/r/3liz/qgis-plugin-ci). 5 | 6 | This is an example with GitLab-CI running with the Docker image from Docker Hub : 7 | 8 | ```yaml 9 | package: 10 | stage: package 11 | only: 12 | - tags 13 | image: 3liz/qgis-plugin-ci:latest 14 | script: 15 | - > 16 | qgis-plugin-ci 17 | package ${CI_COMMIT_REF_NAME} 18 | --plugin-repo-url https://custom.server.url/ 19 | artifacts: 20 | expose_as: 'QGIS package' 21 | paths: 22 | - ${PLUGIN_NAME}.${CI_COMMIT_REF_NAME}.zip 23 | - plugins.xml 24 | ``` 25 | -------------------------------------------------------------------------------- /docs/development/documentation.md: -------------------------------------------------------------------------------- 1 | # Documentation 2 | 3 | Project uses Sphinx to generate documentation from docstrings (documentation in-code) and custom pages written in Markdown (through the [MyST parser](https://myst-parser.readthedocs.io/en/latest/)). 4 | 5 | ## Build documentation website 6 | 7 | To build it: 8 | 9 | ```bash 10 | # install additional dependencies 11 | python -m pip install -U -r requirements/documentation.txt 12 | # build it 13 | sphinx-build -b html docs docs/_build/html 14 | ``` 15 | 16 | Open `docs/_build/index.html` in a web browser. 17 | 18 | ## Write documentation using live render 19 | 20 | ```bash 21 | sphinx-autobuild -b html docs/ docs/_build/html 22 | ``` 23 | 24 | Open in a web browser to see the HTML render updated when a file is saved. 25 | -------------------------------------------------------------------------------- /test/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def can_skip_test_github(): 5 | """Check when the Transifex test can run.""" 6 | is_ci = os.getenv("CI") == "true" 7 | is_main_repo = os.getenv("GITHUB_REPOSITORY") == "opengisch/qgis-plugin-ci" 8 | 9 | if is_ci and is_main_repo: 10 | return False 11 | 12 | if not os.getenv("github_token"): 13 | return True 14 | 15 | return False 16 | 17 | 18 | def can_skip_test_transifex(): 19 | """Check when the Transifex test can run.""" 20 | is_ci = os.getenv("CI") == "true" 21 | is_main_repo = os.getenv("GITHUB_REPOSITORY") == "opengisch/qgis-plugin-ci" 22 | is_dependabot = os.getenv("GITHUB_ACTOR") == "dependabot[bot]" 23 | 24 | if is_ci and is_main_repo and not is_dependabot: 25 | # Always run the test on CI 26 | return False 27 | 28 | if not os.getenv("tx_api_token"): 29 | return True 30 | 31 | return False 32 | -------------------------------------------------------------------------------- /qgispluginci/version_note.py: -------------------------------------------------------------------------------- 1 | from typing import NamedTuple 2 | 3 | 4 | class VersionNote(NamedTuple): 5 | major: str = None 6 | minor: str = None 7 | patch: str = None 8 | url: str = None 9 | prerelease: str = None 10 | separator: str = None 11 | date: str = None 12 | text_raw: str = None 13 | 14 | @property 15 | def text(self) -> str: 16 | """Remove many \n at the start and end of the string.""" 17 | return self.text_raw.strip() 18 | 19 | @property 20 | def is_prerelease(self) -> bool: 21 | if self.prerelease and len(self.prerelease): 22 | return True 23 | else: 24 | return False 25 | 26 | @property 27 | def version(self) -> str: 28 | if self.prerelease: 29 | return f"{self.major}.{self.minor}.{self.patch}-{self.prerelease}" 30 | else: 31 | return f"{self.major}.{self.minor}.{self.patch}" 32 | -------------------------------------------------------------------------------- /qgispluginci/plugins.xml.template: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | __RELEASE_VERSION__ 6 | __QGIS_MIN_VERSION__ 7 | __HOMEPAGE__ 8 | __PLUGINZIP__ 9 | __ICON__ 10 | __AUTHOR__ 11 | __DOWNLOAD_URL__ 12 | __OSGEO_USERNAME__ 13 | __CREATE_DATE__ 14 | __RELEASE_DATE__ 15 | __EXPERIMENTAL__ 16 | __DEPRECATED__ 17 | __ISSUE_TRACKER__ 18 | __REPO_URL__ 19 | __TAGS__ 20 | 21 | 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | First off, thanks for considering to contribute to this project! :tada::+1: 4 | 5 | These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | ## Git hooks 8 | 9 | We use git hooks through [pre-commit](https://pre-commit.com/) to enforce and automatically check some "rules". Please install it before to push any commit. 10 | 11 | See the relevant configuration file: `.pre-commit-config.yaml`. 12 | 13 | ## Code Style 14 | 15 | Make sure your code *roughly* follows [PEP-8](https://www.python.org/dev/peps/pep-0008/) and keeps things consistent with the rest of the code: 16 | 17 | - docstrings: [sphinx-style](https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html#the-sphinx-docstring-format) is used to write technical documentation. 18 | - formatting: [ruff](https://docs.astral.sh/ruff/formatter/) is used to automatically format the code without debate. 19 | - static analisis: [flake8](https://flake8.pycqa.org/en/latest/) is used to catch some dizziness and keep the source code healthy. 20 | -------------------------------------------------------------------------------- /test/plugins.xml.expected: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 0.1.2 6 | 3.2 7 | https://github.com/opengisch/qgis-plugin-ci 8 | qgis_plugin_CI_testing.0.1.2.zip 9 | icons/opengisch.png 10 | Denis Rouzaud 11 | https://github.com/opengisch/qgis-plugin-ci/releases/download/0.1.2/qgis_plugin_CI_testing.0.1.2.zip 12 | Denis Rouzaud 13 | 1985-07-21 14 | __TODAY__ 15 | True 16 | False 17 | https://github.com/opengisch/qgis-plugin-ci/issues 18 | https://github.com/opengisch/qgis-plugin-ci 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /docs/misc/faq.md: -------------------------------------------------------------------------------- 1 | # Frequently Asked Questions 2 | 3 | ## Unknown error 4 | 5 | If you get this message: 6 | 7 | ```log 8 | A fault occurred 9 | Fault code: 1 10 | Fault string: Unknown error, [' File "/usr/local/lib/python3.7/site-packages/rpc4django/xmlrpcdispatcher.py", line 84, in dispatch\n response = self._dispatch(method, params, **kwargs)\n', ' File "/usr/local/lib/python3.7/site-packages/rpc4django/xmlrpcdispatcher.py", line 121, in _dispatch\n return func(*params, **kwargs)\n', ' File "./plugins/api.py", line 121, in plugin_upload\n raise Fault(1, e.message)\n'] 11 | ``` 12 | 13 | Try to upload manually the plugin through the web UI on and follow the error message. 14 | 15 | It occurs for many reasons: 16 | 17 | - the plugin name is not matching the previous plugin versions 18 | 19 | ## How can I merge many XML files into one ? 20 | 21 | QGIS-Plugin-CI can generate the `plugins.xml` file, per plugin. 22 | If you want to merge many XML files into one to have a single QGIS plugin repository providing many plugins, 23 | you should check [QGIS-Plugin-Repo](https://github.com/3liz/qgis-plugin-repo). 24 | It's designed to run on CI after QGIS-Plugin-CI. 25 | -------------------------------------------------------------------------------- /test/fixtures/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## Unreleased 9 | 10 | * Not released yet 11 | 12 | ## 10.1.0-beta1 - 2021/02/08 13 | 14 | - This is the latest documented version in this changelog 15 | - The changelog module is tested against these lines 16 | - Be careful modifying this file 17 | 18 | ## 10.1.0-alpha1 - 2021/01/10 19 | 20 | - This is a version with a prerelease in this changelog 21 | - The changelog module is tested against these lines 22 | - Be careful modifying this file 23 | 24 | ### Fixed 25 | 26 | - trying with a subsection in a version note 27 | 28 | ## 10.0.1 - 2020/12/31 29 | 30 | - End of year version 31 | 32 | ## 10.0.0 - 11/04/2020 33 | 34 | - A 35 | - B 36 | - C 37 | 38 | ## [9.10.1] - 2019-09-11 39 | 40 | - D 41 | - E 42 | - F 43 | 44 | ## v0.1.1 - 2017-07-22 45 | 46 | * Tag with a "v" prefix to check the regular expression 47 | * Previous version 48 | 49 | ## 0.1.0 - 2017-07-21 50 | 51 | * Very old version 52 | -------------------------------------------------------------------------------- /.github/workflows/wheel.yml: -------------------------------------------------------------------------------- 1 | name: "🐍 Python Wheel" 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | workflow_dispatch: 11 | workflow_call: 12 | 13 | 14 | jobs: 15 | tests: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Get source code 19 | uses: actions/checkout@v5 20 | 21 | - name: Set up Python 22 | uses: actions/setup-python@v6 23 | with: 24 | python-version: "3.9" 25 | cache: "pip" 26 | cache-dependency-path: "requirements/*.txt" 27 | 28 | - name: Install project requirements 29 | run: | 30 | python -m pip install -U pip setuptools wheel 31 | python -m pip install -U -r requirements/base.txt 32 | python -m pip install -U build 33 | 34 | - name: Install project as a package 35 | run: python -m pip install -e . 36 | 37 | - name: Build a binary wheel and a source tarball 38 | run: >- 39 | python -m build --sdist --wheel --outdir dist/ . 40 | 41 | - uses: actions/upload-artifact@v4 42 | with: 43 | name: python_wheel 44 | path: dist/* 45 | if-no-files-found: error 46 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: ".venv|tests/dev/|tests/fixtures/" 2 | fail_fast: false 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v6.0.0 6 | hooks: 7 | - id: check-added-large-files 8 | args: 9 | - --maxkb=500 10 | - id: check-case-conflict 11 | - id: check-toml 12 | - id: check-xml 13 | - id: check-yaml 14 | - id: detect-private-key 15 | - id: end-of-file-fixer 16 | - id: fix-byte-order-marker 17 | - id: trailing-whitespace 18 | args: 19 | - --markdown-linebreak-ext=md 20 | 21 | - repo: https://github.com/asottile/pyupgrade 22 | rev: v3.20.0 23 | hooks: 24 | - id: pyupgrade 25 | args: 26 | - --py39-plus 27 | 28 | - repo: https://github.com/astral-sh/ruff-pre-commit 29 | rev: "v0.13.3" 30 | hooks: 31 | - id: ruff 32 | args: 33 | - --fix 34 | - --target-version=py39 35 | types_or: 36 | - python 37 | - pyi 38 | - id: ruff-format 39 | args: 40 | - --line-length=88 41 | - --target-version=py39 42 | types_or: 43 | - python 44 | - pyi 45 | 46 | ci: 47 | autofix_prs: true 48 | autoupdate_schedule: quarterly 49 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description_file = README.md 3 | 4 | # -- Code quality ------------------------------------ 5 | [flake8] 6 | count = True 7 | exclude = 8 | # No need to traverse our git directory 9 | .git, 10 | # There's no value in checking cache directories 11 | __pycache__, 12 | # The conf file is mostly autogenerated, ignore it 13 | docs/conf.py, 14 | # The old directory contains Flake8 2.0 15 | old, 16 | # This contains our built documentation 17 | build, 18 | # This contains builds of flake8 that we don't want to check 19 | dist, 20 | # This contains local virtual environments 21 | .venv*, 22 | venv*, 23 | # do not watch on tests 24 | tests, 25 | # do not consider external packages 26 | */external/*, 27 | ext_libs/*, 28 | qgis_plugin_CI_testing/* 29 | ignore = E121,E123,E126,E203,E226,E24,E704,W503,W504 30 | max-complexity = 15 31 | max-doc-length = 130 32 | max-line-length = 100 33 | output-file = dev_flake8_report.txt 34 | statistics = True 35 | tee = True 36 | 37 | [isort] 38 | ensure_newline_before_comments = True 39 | force_grid_wrap = 0 40 | include_trailing_comma = True 41 | line_length = 88 42 | multi_line_output = 3 43 | profile = black 44 | use_parentheses = True 45 | skip= 46 | qgis_plugin_CI_testing/, 47 | .venv, 48 | venv, 49 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: 🧪 Run tests 2 | 3 | concurrency: testing_environment 4 | 5 | on: 6 | pull_request: 7 | branches: 8 | - master 9 | push: 10 | branches: 11 | - master 12 | workflow_dispatch: 13 | workflow_call: 14 | 15 | 16 | jobs: 17 | tests: 18 | runs-on: ubuntu-latest 19 | steps: 20 | # Not using strategy.matrix to create multiple jobs 21 | # as we do NOT want to test with any form of concurrency 22 | # to avoid 'race conditions' against Transifex 23 | 24 | - name: Check out repository code 25 | uses: actions/checkout@v5 26 | 27 | - uses: actions/setup-python@v6 28 | with: 29 | python-version: "3.9" 30 | cache: "pip" 31 | cache-dependency-path: "requirements/*.txt" 32 | 33 | - name: install 34 | run: | 35 | python -m pip install -U -r requirements/development.txt 36 | python -m pip install -e . 37 | 38 | - name: Simple cli test 39 | run: qgis-plugin-ci --help 40 | 41 | - name: Install system requirements 42 | run: | 43 | sudo apt-get update 44 | sudo apt-get install qtbase5-dev qttools5-dev-tools 45 | 46 | - name: Tests 47 | env: 48 | tx_api_token: ${{ secrets.TRANSIFEX_TOKEN }} 49 | github_token: ${{ secrets.GITHUB_TOKEN }} 50 | run: nose2 -v 51 | -------------------------------------------------------------------------------- /test/test_parameters.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | # standard 4 | import unittest 5 | from pathlib import Path 6 | 7 | # Project 8 | from qgispluginci.exceptions import ConfigurationNotFound 9 | from qgispluginci.parameters import Parameters 10 | 11 | 12 | class TestParameters(unittest.TestCase): 13 | def test_changelog_parameters(self): 14 | """Test parameters for changelog command.""" 15 | # For the changelog command, the configuration file is optional. 16 | # It mustn't raise an exception 17 | parameters = Parameters.make_from(args={}, optional_configuration=True) 18 | self.assertIsNone(parameters.plugin_path) 19 | self.assertEqual("CHANGELOG.md", parameters.changelog_path) 20 | 21 | def test_global_parameters(self): 22 | """Test global parameters.""" 23 | # A configuration file must exist. 24 | with self.assertRaises(ConfigurationNotFound): 25 | Parameters.make_from( 26 | args={}, path_to_config_file=Path("does-not-exist.yml") 27 | ) 28 | 29 | # Existing configuration file 30 | parameters = Parameters.make_from( 31 | args={}, path_to_config_file=Path("test/fixtures/pyproject.toml") 32 | ) 33 | self.assertEqual("qgis_plugin_CI_testing", parameters.plugin_path) 34 | self.assertEqual("CHANGELOG.md", parameters.changelog_path) 35 | -------------------------------------------------------------------------------- /docs/usage/ci_gitlab.md: -------------------------------------------------------------------------------- 1 | # GitLab CI 2 | 3 | qgis-plugin-ci integrates nicely with GitLab CI. The following example automatically uploads plugins to the plugin repository when a new tag is created on GitLab. 4 | 5 | All you need to do is adding `OSGEO_USER_NAME` and `OSGEO_USER_PASSWORD` to the CI/CD variables in the repository settings. 6 | 7 | Save this file as `.gitlab-ci.yml`: 8 | 9 | ```yaml 10 | stages: 11 | - 🚀 deploy 12 | 13 | deploy:qgis-repository: 14 | stage: 🚀 deploy 15 | image: python:3.11 16 | rules: 17 | - if: '$CI_COMMIT_TAG' 18 | before_script: 19 | - apt update 20 | - apt install -y git 21 | # Uncomment if plugin use translations 22 | # - apt install -y qt5-qmake qttools5-dev-tools 23 | # - python -m pip install -U pyqt5-tools 24 | - python -m pip install -U qgis-plugin-ci 25 | script: 26 | - echo "Deploying the version ${CI_COMMIT_TAG} plugin to QGIS Plugins Repository with the user ${OSGEO_USER_NAME}" 27 | # Uncomment if plugin use translations 28 | # # Amend gitignore to include translation files with qgis-plugin-ci 29 | # - sed -i "s|^*.qm.*| |" .gitignore 30 | # # git tracks new files 31 | # - git add $PROJECT_FOLDER/resources/i18n/*.qm 32 | - qgis-plugin-ci release ${CI_COMMIT_TAG} 33 | --osgeo-username $OSGEO_USER_NAME 34 | --osgeo-password $OSGEO_USER_PASSWORD 35 | --allow-uncommitted-changes 36 | ``` 37 | -------------------------------------------------------------------------------- /docs/usage/ci_travis.md: -------------------------------------------------------------------------------- 1 | # TravisCI 2 | 3 | ## Basic configuration 4 | 5 | **Notes**: 6 | 7 | - Python 3.7 is required. Check on Travis that you are using at least Python 3.7. 8 | - `qgis-plugin-ci` must find an existing GitHub release for the tag. Either you create the release from GitHub, which will trigger Travis or you can use Travis/GitHub Actions to create the release automatically. 9 | 10 | One can easily set up a deployment using Travis. 11 | 12 | 1. Add `qgis-plugin-ci` to `requirements.txt` or have `pip install qgis-plugin-ci` in `install` step. 13 | 2. Specify the environment variables required to connect to the different platforms (Osgeo, Github, Transifex). You can add them either using the Travis CLI with `travis encrypt` or use the web interface to add the variables. 14 | 3. Add a deploy step to release the plugin: 15 | 16 | ```yaml 17 | deploy: 18 | - provider: script 19 | script: qgis-plugin-ci release ${TRAVIS_TAG} --github-token ${GH_TOKEN} --osgeo-username ${OSGEO_USERNAME} --osgeo-password {OSGEO_PASSWORD} 20 | on: 21 | tags: true 22 | ``` 23 | 24 | This assumes that you have an existing GitHub release. 25 | Alternatively, Travis can create the release by adding a `releases` provider before the `script` provider: 26 | 27 | ```yaml 28 | - provider: releases 29 | name: Title of the release ${TRAVIS_TAG} 30 | api_key: ${GH_TOKEN} 31 | on: 32 | tags: true 33 | ``` 34 | -------------------------------------------------------------------------------- /docs/usage/ci_github.md: -------------------------------------------------------------------------------- 1 | # GitHub workflows 2 | 3 | qgis-plugin-ci integrates nicely with github workflows. The following example automatically uploads plugins to releases and to the plugin repository when a new release is created on github. 4 | 5 | All you need to do is adding `OSGEO_PASSWORD` to the secrets in the repository settings. Note that the `GITHUB_TOKEN` is available automatically without any configuration. 6 | 7 | Save this file as `.github/workflows/release.yaml`: 8 | 9 | ```yaml 10 | on: 11 | release: 12 | types: published 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | 21 | - name: Set up Python 22 | uses: actions/setup-python@v1 23 | with: 24 | python-version: 3.12 25 | 26 | # Needed if the plugin is using Transifex, to have the lrelease command 27 | # - name: Install Qt lrelease 28 | # run: | 29 | # sudo apt-get update 30 | # sudo apt-get install qt5-make qttools5-dev-tools 31 | 32 | - name: Install qgis-plugin-ci 33 | run: pip3 install qgis-plugin-ci 34 | 35 | - name: Deploy plugin 36 | run: >- 37 | qgis-plugin-ci 38 | release ${GITHUB_REF/refs\/tags\//} 39 | --github-token ${{ secrets.GITHUB_TOKEN }} 40 | --osgeo-username ${{ secrets.OSGEO_USER }} 41 | --osgeo-password ${{ secrets.OSGEO_PASSWORD }} 42 | ``` 43 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | /*************************************************************************** 3 | 4 | QgisLocator 5 | 6 | ------------------- 7 | begin : 2018-05-03 8 | copyright : (C) 2018 by Denis Rouzaud 9 | email : denis@opengis.ch 10 | git sha : $Format:%H$ 11 | ***************************************************************************/ 12 | 13 | /*************************************************************************** 14 | * * 15 | * This program is free software; you can redistribute it and/or modify * 16 | * it under the terms of the GNU General Public License as published by * 17 | * the Free Software Foundation; either version 2 of the License, or * 18 | * (at your option) any later version. * 19 | * * 20 | ***************************************************************************/ 21 | """ 22 | 23 | 24 | def classFactory(iface): 25 | """Load plugin. 26 | 27 | :param iface: A QGIS interface instance. 28 | :type iface: QgsInterface 29 | """ 30 | # 31 | from .qgis_plugin_ci_testing_plugin import QgisPluginCiTesting 32 | 33 | return QgisPluginCiTesting(iface) 34 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/qgis_plugin_ci_testing_plugin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | /*************************************************************************** 4 | 5 | QGIS Plugin CI Testing 6 | Copyright (C) 2019 Denis Rouzaud 7 | 8 | ***************************************************************************/ 9 | 10 | /*************************************************************************** 11 | * * 12 | * This program is free software; you can redistribute it and/or modify * 13 | * it under the terms of the GNU General Public License as published by * 14 | * the Free Software Foundation; either version 2 of the License, or * 15 | * (at your option) any later version. * 16 | * * 17 | ***************************************************************************/ 18 | """ 19 | 20 | import os 21 | 22 | from PyQt5.QtCore import QCoreApplication, QLocale, QSettings, QTranslator 23 | from qgis.gui import QgisInterface 24 | 25 | DEBUG = False 26 | 27 | 28 | class QgisPluginCiTesting: 29 | def __init__(self, iface: QgisInterface): 30 | self.iface = iface 31 | 32 | # initialize translation 33 | qgis_locale = QLocale(QSettings().value("locale/userLocale")) 34 | locale_path = os.path.join(os.path.dirname(__file__), "i18n") 35 | self.translator = QTranslator() 36 | self.translator.load(qgis_locale, "swiss_locator", "_", locale_path) 37 | QCoreApplication.installTranslator(self.translator) 38 | 39 | self.trUtf8("some UTF-8 translation: un épilogue où l'on marche sur des œufs") 40 | 41 | def initGui(self): 42 | pass 43 | 44 | def unload(self): 45 | pass 46 | -------------------------------------------------------------------------------- /docs/usage/cli_changelog.md: -------------------------------------------------------------------------------- 1 | # Changelog (CLI) 2 | 3 | Manipulate `CHANGELOG.md` file, extracting relevant information. 4 | Used within the [package](cli_package) and [release](cli_release) commands to populate the `metadata.txt` and the GitHub Release description. 5 | 6 | By default, the script will look for a file `CHANGELOG.md` in the root folder. 7 | But you can specify a specific file path with `changelog_path` in the configuration file. 8 | For instance: 9 | 10 | ```ini 11 | changelog_path=CHANGELOG-3.4.md 12 | ``` 13 | 14 | or 15 | 16 | ```ini 17 | changelog_path=subfolder/CHANGELOG.md 18 | ``` 19 | 20 | ## Command help 21 | 22 | ```bash 23 | usage: qgis-plugin-ci changelog [-h] release_version 24 | 25 | positional arguments: 26 | release_version The version to be released. If nothing is speficied, the latest 27 | version specified into the changelog is used. 28 | 29 | optional arguments: 30 | -h, --help show this help message and exit 31 | ``` 32 | 33 | ## Requirements 34 | 35 | The `CHANGELOG.md` file must follow the convention [Keep A Changelog](https://keepachangelog.com/). For example, see this [repository changelog](https://github.com/opengisch/qgis-plugin-ci/blob/master/CHANGELOG.md). 36 | 37 | > **NOTE** 38 | > Currently the "Unreleased" section and subsections (e.g. "Fixed" etc) are not supported, see [#56](https://github.com/opengisch/qgis-plugin-ci/issues/56). 39 | 40 | ## Use cases 41 | 42 | - Extract the `CHANGELOG.md` content and copy it into the `changelog` section within plugin `metadata.txt` 43 | - Extract the `n` latest versions from `CHANGELOG.md` into `metadata.txt` 44 | - Get the latest version release note 45 | 46 | ## Examples 47 | 48 | ### Extract changelog for latest version 49 | 50 | ```bash 51 | $ qgis-plugin-ci changelog latest 52 | - Separate python files and UI files in the temporary PRO file (#29) 53 | ``` 54 | -------------------------------------------------------------------------------- /test/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from qgispluginci.utils import parse_tag 4 | from qgispluginci.version_note import VersionNote 5 | 6 | 7 | class TestUtils(unittest.TestCase): 8 | def test_version_note_from_tag(self): 9 | """Test to parse a tag and check the version note.""" 10 | 11 | version = parse_tag("10.1.0-beta1") 12 | self.assertIsInstance(version, VersionNote) 13 | self.assertEqual("10", version.major) 14 | self.assertEqual("1", version.minor) 15 | self.assertEqual("0", version.patch) 16 | self.assertEqual("beta1", version.prerelease) 17 | self.assertTrue(version.is_prerelease) 18 | 19 | version = parse_tag("3.4.0-rc.2") 20 | self.assertIsInstance(version, VersionNote) 21 | self.assertEqual("3", version.major) 22 | self.assertEqual("4", version.minor) 23 | self.assertEqual("0", version.patch) 24 | self.assertEqual("rc.2", version.prerelease) 25 | self.assertTrue(version.is_prerelease) 26 | 27 | version = parse_tag("10.1.0") 28 | self.assertIsInstance(version, VersionNote) 29 | self.assertEqual("10", version.major) 30 | self.assertEqual("1", version.minor) 31 | self.assertEqual("0", version.patch) 32 | self.assertIsNone(version.prerelease) 33 | self.assertFalse(version.is_prerelease) 34 | 35 | version = parse_tag("v10.1.0") 36 | self.assertIsInstance(version, VersionNote) 37 | self.assertEqual("v10", version.major) 38 | self.assertEqual("1", version.minor) 39 | self.assertEqual("0", version.patch) 40 | self.assertIsNone(version.prerelease) 41 | self.assertFalse(version.is_prerelease) 42 | 43 | # Not following https://semver.org/, we can't guess 44 | version = parse_tag("10.1") 45 | self.assertIsInstance(version, VersionNote) 46 | self.assertIsNone(version.major) 47 | self.assertIsNone(version.minor) 48 | self.assertIsNone(version.patch) 49 | self.assertIsNone(version.prerelease) 50 | self.assertFalse(version.is_prerelease) 51 | 52 | 53 | if __name__ == "__main__": 54 | unittest.main() 55 | -------------------------------------------------------------------------------- /qgispluginci/translation_clients/baseclient.py: -------------------------------------------------------------------------------- 1 | from typing import NamedTuple 2 | 3 | 4 | class TranslationConfig(NamedTuple): 5 | api_token: str 6 | organization_name: str 7 | project_slug: str 8 | resource_file_path: str 9 | resource_slug: str 10 | 11 | private: bool = False 12 | project_name: str = None 13 | i18n_type: str = "QT" 14 | repository_url: str = None 15 | source_language_code: str = "en" 16 | 17 | 18 | class BaseClient: 19 | def __init__( 20 | self, config: TranslationConfig, update_string_fcn, create_project: bool = True 21 | ): 22 | """ 23 | Parameters 24 | ---------- 25 | config: 26 | The config for the Translation platform 27 | 28 | create_project: 29 | if True, it will create the project, resource and language on Transifex 30 | 31 | """ 32 | self.config = config 33 | self.login() 34 | self.project = self.get_project() 35 | if not self.project and create_project: 36 | self.project = self.create_project() 37 | update_string_fcn() 38 | self.create_resource() 39 | 40 | def login(self): 41 | raise NotImplementedError 42 | 43 | def get_project(self): 44 | raise NotImplementedError 45 | 46 | def project_exists(self): 47 | raise NotImplementedError 48 | 49 | def create_project(self): 50 | raise NotImplementedError 51 | 52 | def delete_project(self): 53 | raise NotImplementedError 54 | 55 | def create_resource(self): 56 | raise NotImplementedError 57 | 58 | def list_resources(self): 59 | raise NotImplementedError 60 | 61 | def get_resource(self): 62 | raise NotImplementedError 63 | 64 | def list_languages(self): 65 | raise NotImplementedError 66 | 67 | def create_language(self, language_code: str): 68 | raise NotImplementedError 69 | 70 | def update_source_translation(self): 71 | raise NotImplementedError 72 | 73 | def get_translation( 74 | self, 75 | language_code: str, 76 | path_to_output_file: str, 77 | ) -> str: 78 | raise NotImplementedError 79 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: 📦 Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | env: 9 | PROJECT_FOLDER: "qgispluginci" 10 | PYTHON_VERSION_RELEASE: "3.9" 11 | QGISPLUGINCI_VERSION: ${{ github.ref_name }} 12 | 13 | jobs: 14 | tests: 15 | name: "Tests" 16 | uses: ./.github/workflows/test.yml 17 | secrets: inherit 18 | 19 | build-python-wheel: 20 | name: "🐍 Python Wheel" 21 | uses: ./.github/workflows/wheel.yml 22 | secrets: inherit 23 | 24 | release-gh: 25 | name: "Release on tag 🚀" 26 | runs-on: ubuntu-latest 27 | needs: [build-python-wheel, tests] 28 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 29 | 30 | steps: 31 | - name: Retrieve artifact from Python build 32 | uses: actions/download-artifact@v5 33 | with: 34 | name: python_wheel 35 | path: dist/ 36 | 37 | - name: Create/update release on GitHub 38 | uses: ncipollo/release-action@v1.20.0 39 | with: 40 | allowUpdates: true 41 | artifacts: "builds**/*" 42 | generateReleaseNotes: true 43 | omitNameDuringUpdate: true 44 | token: ${{ secrets.GITHUB_TOKEN }} 45 | 46 | release-pypi: 47 | name: "🐍 Release on PyPI" 48 | runs-on: ubuntu-latest 49 | needs: [build-python-wheel, tests] 50 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 51 | 52 | steps: 53 | - name: Retrieve artifact from Python build 54 | uses: actions/download-artifact@v5 55 | with: 56 | name: python_wheel 57 | path: dist/ 58 | 59 | # -- FROM HERE, A TAG IS REQUIRED --- 60 | - name: Deploy to PyPI 61 | uses: pypa/gh-action-pypi-publish@release/v1 62 | 63 | with: 64 | user: __token__ 65 | password: ${{ secrets.PYPI_API_TOKEN }} 66 | 67 | - name: Create/update release on GitHub 68 | uses: ncipollo/release-action@v1.20.0 69 | with: 70 | allowUpdates: true 71 | artifacts: "dist/*.tar.gz" 72 | generateReleaseNotes: true 73 | omitNameDuringUpdate: true 74 | token: ${{ secrets.GITHUB_TOKEN }} 75 | -------------------------------------------------------------------------------- /docs/usage/cli_package.md: -------------------------------------------------------------------------------- 1 | # Package 2 | 3 | This command is not specific to the hosting platform (GitLab, GitHub…) 4 | 5 | ```bash 6 | usage: qgis-plugin-ci package [-h] 7 | [--transifex-token TRANSIFEX_TOKEN] 8 | [--plugin-repo-url PLUGIN_REPO_URL] 9 | [--allow-uncommitted-changes] 10 | release_version 11 | 12 | positional arguments: 13 | release_version The version to be released 14 | 15 | optional arguments: 16 | -h, --help show this help message and exit 17 | --transifex-token TRANSIFEX_TOKEN 18 | The Transifex API token. If specified translations 19 | will be pulled and compiled. 20 | -u --plugin-repo-url PLUGIN_REPO_URL 21 | If specified, a XML repository file will be created in the current directory, the zip URL will use this parameter. 22 | -c --allow-uncommitted-changes 23 | If omitted, uncommitted changes are not allowed before 24 | packaging. If specified and some changes are detected, 25 | a hard reset on a stash create will be used to revert 26 | changes made by qgis-plugin-ci. 27 | -d --disable-submodule-update 28 | If omitted, a git submodule is updated. If specified, git submodules will not be updated/initialized before packaging. 29 | -a ASSET_PATH, --asset-path ASSET_PATH 30 | An additional asset path to add. Can be specified multiple times. 31 | ``` 32 | 33 | ## Additional metadata 34 | 35 | When packaging the plugin, some extra metadata information can be added if these keys are present in the `metadata.txt`: 36 | 37 | * `commitNumber=` : the commit number in the branch otherwise 1 on a tag 38 | * `commitSha1=` : the commit ID 39 | * `dateTime=` : the date time in UTC format when the packaging is done 40 | 41 | :::{tip} 42 | These extra parameters are specific to QGIS Plugin CI, so it's strongly recommended storing them below a dedicated section: 43 | 44 | ```ini 45 | [tool:qgis-plugin-ci] 46 | commitNumber= 47 | commitSha1= 48 | dateTime= 49 | ``` 50 | 51 | ::: 52 | -------------------------------------------------------------------------------- /docs/configuration/options.md: -------------------------------------------------------------------------------- 1 | # Configuration 2 | 3 | ## Settings 4 | 5 | The plugin must have a configuration, located at the top directory; it can be either: 6 | 7 | - a YAML file named `.qgis-plugin-ci` 8 | - an INI file named `setup.cfg` with a `[qgis-plugin-ci]` section 9 | - a TOML file (= your actual `pyproject.toml` file) with a `[tool.qgis-plugin-ci]` section. 10 | 11 | In the configuration, you should at least provide the following configuration: 12 | 13 | - `plugin_path`, the folder where the source code is located under the git repository. See 14 | 15 | You can find a template `.qgis-plugin-ci` in this repository. 16 | You can read the docstring of the [Parameters module](/_apidoc/qgispluginci.parameters) 17 | to know parameters which are available in the file. 18 | 19 | ## Conventions 20 | 21 | QGIS-Plugin-CI is best served if you use these two conventions : 22 | 23 | * [Semantic versioning](https://semver.org/) 24 | * [Keep A Changelog](https://keepachangelog.com) 25 | 26 | ## Options 27 | 28 | | Name | Required | Description | Example | 29 | | :--- | :------: | :---------- | :------ | 30 | | `github_organization_slug` | no | The *organization* slug on SCM host (e.g. Github) and translation platform (e.g. Transifex).
Not required when running on Travis since deduced from `$TRAVIS_REPO_SLUG`environment variable. | | 31 | | `plugin_path` | **yes** | The folder where the source code is located. Shouldn't have any dash character. Defaults to: `slugify(plugin_name)`. | qgis_plugin_CI_testing | 32 | | `project_slug` | no | The *project* slug on SCM host (e.g. Github) and translation platform (e.g. Transifex).
Not required when running on Travis since deduced from `$TRAVIS_REPO_SLUG`environment variable. | | 33 | 34 | ## Examples 35 | 36 | ### Using YAML file `.qgis-plugin-ci` 37 | 38 | ```yaml 39 | plugin_path: qgis_plugin_ci_testing 40 | github_organization_slug: opengisch 41 | project_slug: qgis-plugin-ci 42 | ``` 43 | 44 | ### Using INI file `setup.cfg` 45 | 46 | ```ini 47 | [qgis-plugin-ci] 48 | plugin_path = QuickOSM 49 | github_organization_slug = 3liz 50 | project_slug = QuickOSM 51 | ``` 52 | ### Using TOML file `pyproject.toml` 53 | 54 | ```toml 55 | [tool.qgis-plugin-ci] 56 | plugin_path = "qgis_plugin_ci_testing" 57 | github_organization_slug = "opengisch" 58 | project_slug = "qgis-plugin-ci" 59 | ``` 60 | -------------------------------------------------------------------------------- /test/test_translation.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | # standard library 4 | import logging 5 | import os 6 | import unittest 7 | 8 | # 3rd party 9 | import yaml 10 | 11 | # project 12 | from qgispluginci.parameters import Parameters 13 | from qgispluginci.translation import Translation 14 | 15 | # Tests 16 | from .utils import can_skip_test_transifex 17 | 18 | # Logging 19 | logger = logging.getLogger(__name__) 20 | 21 | # Ensuring proper ordering for tests sensitive to state 22 | unittest.TestLoader.sortTestMethodsUsing = None 23 | 24 | 25 | @unittest.skipIf(can_skip_test_transifex(), "Missing tx_api_token") 26 | class TestTranslation(unittest.TestCase): 27 | @classmethod 28 | def setUpClass(cls): 29 | """Initialize the test case""" 30 | with open(".qgis-plugin-ci") as f: 31 | arg_dict = yaml.safe_load(f) 32 | cls.parameters = Parameters(arg_dict) 33 | cls.tx_api_token = os.getenv("tx_api_token") 34 | assert cls.tx_api_token 35 | 36 | def setUp(self): 37 | """Initialize the next test method (run before every test method)""" 38 | self.t = Translation(self.parameters, tx_api_token=self.tx_api_token) 39 | 40 | def tearDown(self): 41 | self.t.tx_client.delete_project() 42 | """ 43 | try: 44 | self.t.tx_client.delete_team(f"{self.parameters.project_slug}-team") 45 | except PyTransifexException as error: 46 | logger.debug(error) 47 | """ 48 | 49 | def test_creation(self): 50 | """ 51 | Translation initialized from setUp, so we 'fake' a new test 52 | by tearing it down 53 | """ 54 | self.t = Translation(self.parameters, tx_api_token=self.tx_api_token) 55 | self.t.tx_client.delete_project() 56 | self.assertFalse(self.t.tx_client.project_exists(self.parameters.project_slug)) 57 | self.t = Translation(self.parameters, tx_api_token=self.tx_api_token) 58 | self.assertTrue(self.t.tx_client.project_exists(self.parameters.project_slug)) 59 | self.assertEqual(len(self.t.tx_client.list_resources()), 1) 60 | 61 | def test_push(self): 62 | self.t.update_strings() 63 | self.t.push() 64 | 65 | def test_pull(self): 66 | self.t.pull() 67 | self.t.compile_strings() 68 | 69 | 70 | if __name__ == "__main__": 71 | unittest.main() 72 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0", "setuptools-scm", "wheel", "setuptools-git-versioning"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "qgis-plugin-ci" 7 | dynamic = ["version", "readme", "dependencies", "optional-dependencies"] 8 | authors = [ 9 | {name = "Denis Rouzaud", email = "denis@opengis.ch"}, 10 | {name = "Etienne Trimaille", email = "etienne.trimaille@gmail.com"}, 11 | {name = "Julien Moura", email = "dev@ingeoveritas.com"}, 12 | ] 13 | description = "Let qgis-plugin-ci package and release your QGIS plugins for you. Have a tea or go hiking meanwhile. Contains scripts to perform automated testing and deployment for QGIS plugins. These scripts are written for and tested on GitHub Actions, GitLab CI, Travis-CI, and Transifex." 14 | requires-python = ">=3.9" 15 | keywords = ["QGIS", "CI", "changelog", "plugin"] 16 | license = {text = "GPLv3"} 17 | classifiers = [ 18 | "Development Status :: 5 - Production/Stable", 19 | "Intended Audience :: System Administrators", 20 | "Intended Audience :: Developers", 21 | "Intended Audience :: Information Technology", 22 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 23 | "Operating System :: OS Independent", 24 | "Programming Language :: Python :: 3", 25 | "Programming Language :: Python :: 3.9", 26 | "Programming Language :: Python :: 3.10", 27 | "Programming Language :: Python :: 3.11", 28 | "Programming Language :: Python :: 3.12", 29 | "Programming Language :: Python :: 3.13", 30 | "Programming Language :: Python :: Implementation :: CPython", 31 | "Topic :: Scientific/Engineering :: GIS", 32 | ] 33 | 34 | [project.scripts] 35 | qgis-plugin-ci = "qgispluginci.cli:cli" 36 | 37 | [project.urls] 38 | homepage = "https://opengisch.github.io/qgis-plugin-ci/" 39 | documentation = "https://opengisch.github.io/qgis-plugin-ci/" 40 | repository = "https://github.com/opengisch/qgis-plugin-ci/" 41 | tracker = "https://github.com/opengisch/qgis-plugin-ci/issues" 42 | 43 | [tool.setuptools] 44 | packages = ["qgispluginci", "qgispluginci.translation_clients"] 45 | 46 | [tool.setuptools-git-versioning] 47 | enabled = true 48 | 49 | [tool.setuptools.dynamic] 50 | readme = {file = ["README.md"], content-type = "text/markdown"} 51 | dependencies = {file = ["requirements/base.txt"]} 52 | optional-dependencies.dev = {file = ["requirements/development.txt"]} 53 | -------------------------------------------------------------------------------- /qgispluginci/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import re 4 | from math import floor 5 | from math import log as math_log 6 | from math import pow 7 | from typing import Union 8 | 9 | from qgispluginci.version_note import VersionNote 10 | 11 | # GLOBALS 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def replace_in_file(file_path: str, pattern, new: str, encoding: str = "utf8"): 16 | with open(file_path, encoding=encoding) as f: 17 | content = f.read() 18 | content = re.sub(pattern, new, content, flags=re.M) 19 | with open(file_path, "w", encoding=encoding) as f: 20 | f.write(content) 21 | 22 | 23 | def configure_file(source_file: str, dest_file: str, replace: dict): 24 | with open(source_file, encoding="utf-8") as f: 25 | content = f.read() 26 | for pattern, new in replace.items(): 27 | content = re.sub(pattern, new, content, flags=re.M) 28 | with open(dest_file, "w", encoding="utf-8") as f: 29 | f.write(content) 30 | 31 | 32 | def convert_octets(octets: int) -> str: 33 | """Convert a mount of octets in readable size. 34 | 35 | :param int octets: mount of octets to convert 36 | 37 | :Example: 38 | 39 | .. code-block:: python 40 | 41 | >>> convert_octets(1024) 42 | "1ko" 43 | """ 44 | # check zero 45 | if octets == 0: 46 | return "0 octet" 47 | 48 | # conversion 49 | size_name = ("octets", "Ko", "Mo", "Go", "To", "Po") 50 | i = int(floor(math_log(octets, 1024))) 51 | p = pow(1024, i) 52 | s = round(octets / p, 2) 53 | 54 | return f"{s} {size_name[i]}" 55 | 56 | 57 | def touch_file(path, update_time: bool = False, create_dir: bool = True): 58 | basedir = os.path.dirname(path) 59 | if create_dir and not os.path.exists(basedir): 60 | os.makedirs(basedir) 61 | with open(path, "a"): 62 | if update_time: 63 | os.utime(path, None) 64 | else: 65 | pass 66 | 67 | 68 | def parse_tag(version_tag: str) -> Union[VersionNote, None]: 69 | """Parse a tag and determine the semantic version.""" 70 | components = version_tag.split("-") 71 | items = components[0].split(".") 72 | 73 | try: 74 | if len(components) == 2: 75 | return VersionNote( 76 | major=items[0], minor=items[1], patch=items[2], prerelease=components[1] 77 | ) 78 | else: 79 | return VersionNote(major=items[0], minor=items[1], patch=items[2]) 80 | except IndexError: 81 | return VersionNote() 82 | -------------------------------------------------------------------------------- /.github/workflows/docs_builder.yml: -------------------------------------------------------------------------------- 1 | name: "📚 Documentation Builder" 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | paths: 7 | - 'docs/**/*' 8 | - '.github/workflows/docs_builder.yml' 9 | - 'qgispluginci/**/*.py' 10 | - 'requirements/documentation.txt' 11 | tags: 12 | - "*" 13 | 14 | pull_request: 15 | branches: [master] 16 | paths: 17 | - ".github/workflows/docs_builder.yml" 18 | - docs/**/* 19 | - requirements/documentation.txt 20 | 21 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 22 | permissions: 23 | contents: read 24 | pages: write 25 | id-token: write 26 | 27 | # Allow one concurrent deployment 28 | concurrency: 29 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 30 | cancel-in-progress: true 31 | 32 | env: 33 | PYTHON_VERSION: 3.11 34 | 35 | jobs: 36 | build-docs: 37 | 38 | runs-on: ubuntu-latest 39 | 40 | steps: 41 | - name: Get source code 42 | uses: actions/checkout@v5 43 | 44 | - name: Set up Python 45 | uses: actions/setup-python@v6 46 | with: 47 | python-version: ${{ env.PYTHON_VERSION }} 48 | cache: "pip" 49 | cache-dependency-path: "requirements/*.txt" 50 | 51 | - name: Install project requirements 52 | run: | 53 | python -m pip install -U pip setuptools wheel 54 | python -m pip install -U -r requirements.txt 55 | 56 | - name: Install project as a package 57 | run: python -m pip install -e . 58 | 59 | # this job must run before installing other dependencies to avoid listing everything 60 | - name: Generates licenses page with pip-licences 61 | run: | 62 | python -m pip install -U "pip-licenses>=4,<5" 63 | pip-licenses --format=markdown --with-authors --with-description --with-urls --ignore-packages qgis-plugin-ci --output-file=docs/misc/licenses.md 64 | 65 | - name: Install documentation requirements 66 | run: | 67 | python -m pip install -U -r requirements/documentation.txt 68 | 69 | - name: Build doc using Sphinx 70 | run: sphinx-build -b html -j auto -d docs/_build/cache -q docs docs/_build/html 71 | 72 | - name: Save build doc as artifact 73 | uses: actions/upload-artifact@v4 74 | with: 75 | name: documentation 76 | path: docs/_build/html/* 77 | if-no-files-found: error 78 | retention-days: 30 79 | 80 | - name: Setup Pages 81 | uses: actions/configure-pages@v5 82 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && !contains(github.ref, 'beta') 83 | 84 | - name: Upload artifact 85 | uses: actions/upload-pages-artifact@v4 86 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && !contains(github.ref, 'beta') 87 | with: 88 | # Upload entire repository 89 | path: docs/_build/html/ 90 | 91 | - name: Deploy to GitHub Pages 92 | id: deployment 93 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && !contains(github.ref, 'beta') 94 | uses: actions/deploy-pages@v4 95 | -------------------------------------------------------------------------------- /docs/usage/cli_release.md: -------------------------------------------------------------------------------- 1 | # Release 2 | 3 | This command is specific for plugins hosted on GitHub. 4 | 5 | ```bash 6 | usage: qgis-plugin-ci release [-h] [--release-tag RELEASE_TAG] 7 | [--transifex-token TRANSIFEX_TOKEN] 8 | [--github-token GITHUB_TOKEN] [-r] [-c] [-d] 9 | [--alternative-repo-url ALTERNATIVE_REPO_URL] 10 | [--osgeo-username OSGEO_USERNAME] 11 | [--osgeo-password OSGEO_PASSWORD] 12 | release_version 13 | 14 | positional arguments: 15 | release_version The version to be released (x.y.z). 16 | 17 | options: 18 | -h, --help show this help message and exit 19 | --release-tag RELEASE_TAG 20 | The release tag, if different from the version (e.g. vx.y.z). 21 | --transifex-token TRANSIFEX_TOKEN 22 | The Transifex API token. If specified translations will be pulled and 23 | compiled. 24 | --github-token GITHUB_TOKEN 25 | The Github API token. If specified, the archive will be pushed to an 26 | already existing release. 27 | -r, --create-plugin-repo 28 | Will create a XML repo as a Github release asset. Github token is 29 | required. 30 | -c, --allow-uncommitted-changes 31 | If omitted, uncommitted changes are not allowed before releasing. If 32 | specified and some changes are detected, a hard reset on a stash 33 | create will be used to revert changes made by qgis-plugin-ci. 34 | -d, --disable-submodule-update 35 | If omitted, a git submodule is updated. If specified, git submodules 36 | will not be updated/initialized before packaging. 37 | --alternative-repo-url ALTERNATIVE_REPO_URL 38 | The URL of the endpoint to publish the plugin (defaults to 39 | plugins.qgis.org) 40 | -a ASSET_PATH, --asset-path ASSET_PATH 41 | An additional asset path to add. Can be specified multiple times. 42 | --osgeo-username OSGEO_USERNAME 43 | The Osgeo user name to publish the plugin. 44 | --osgeo-password OSGEO_PASSWORD 45 | The Osgeo password to publish the plugin. 46 | ``` 47 | 48 | If the exit code is `2`, it means the upload to the QGIS server has failed. 49 | 50 | ## Additional metadata 51 | 52 | When packaging the plugin, some extra metadata information can be added if these keys are present in the `metadata.txt`: 53 | 54 | * `commitNumber=` : the commit number in the branch otherwise 1 on a tag 55 | * `commitSha1=` : the commit ID 56 | * `dateTime=` : the date time in UTC format when the packaging is done 57 | 58 | :::{tip} 59 | These extra parameters are specific to QGIS Plugin CI, so it's strongly recommended storing them below a dedicated section: 60 | 61 | ```ini 62 | [tool:qgis-plugin-ci] 63 | commitNumber= 64 | commitSha1= 65 | dateTime= 66 | ``` 67 | 68 | ::: 69 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | 3 | """ 4 | Configuration for project documentation using Sphinx. 5 | """ 6 | 7 | # standard 8 | import sys 9 | from datetime import date, datetime 10 | from importlib.metadata import version 11 | from os import environ, path 12 | 13 | if sys.version_info >= (3, 11): 14 | import tomllib 15 | else: 16 | import tomli as tomllib 17 | 18 | __version__ = version("qgis-plugin-ci") 19 | 20 | with open("../pyproject.toml", "rb") as f: 21 | pyproject = tomllib.load(f) 22 | 23 | # -- Build environment ----------------------------------------------------- 24 | on_rtd = environ.get("READTHEDOCS", None) == "True" 25 | 26 | # -- Project information ----------------------------------------------------- 27 | author = ", ".join([a["name"] for a in pyproject["project"]["authors"]]) 28 | __copyright__ = f"2019 - {date.today().year}, {author}" 29 | project = "QGIS Plugin CI" 30 | version = release = __version__ 31 | 32 | 33 | # -- General configuration --------------------------------------------------- 34 | 35 | # Add any Sphinx extension module names here, as strings. They can be 36 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 37 | # ones. 38 | extensions = [ 39 | # Sphinx included 40 | "sphinx.ext.autodoc", 41 | "sphinx.ext.autosectionlabel", 42 | "sphinx.ext.githubpages", 43 | "sphinx.ext.intersphinx", 44 | "sphinx.ext.extlinks", 45 | # 3rd party 46 | "myst_parser", 47 | "sphinx_copybutton", 48 | "sphinx_design", 49 | "sphinx_sitemap", 50 | ] 51 | 52 | 53 | # The suffix(es) of source filenames. 54 | # You can specify multiple suffix as a list of string: 55 | # 56 | source_suffix = {".md": "markdown", ".rst": "restructuredtext"} 57 | autosectionlabel_prefix_document = True 58 | # The master toctree document. 59 | master_doc = "index" 60 | 61 | # The language for content autogenerated by Sphinx. Refer to documentation 62 | # for a list of supported languages. 63 | # 64 | # This is also used if you do content translation via gettext catalogs. 65 | # Usually you set "language" from the command line for these cases. 66 | language = "en" 67 | 68 | # List of patterns, relative to source directory, that match files and 69 | # directories to ignore when looking for source files. 70 | # This pattern also affects html_static_path and html_extra_path . 71 | exclude_patterns = ["_build", ".venv", "Thumbs.db", ".DS_Store", "_output", "ext_libs"] 72 | 73 | # The name of the Pygments (syntax highlighting) style to use. 74 | pygments_style = "sphinx" 75 | 76 | 77 | # -- Options for HTML output ------------------------------------------------- 78 | 79 | # -- Theme 80 | 81 | # final URL 82 | html_baseurl = pyproject["project"]["urls"]["homepage"] 83 | 84 | # Add any paths that contain custom static files (such as style sheets) here, 85 | # relative to this directory. They are copied after the builtin static files, 86 | # so a file named "default.css" will overwrite the builtin "default.css". 87 | # html_static_path = ["static"] 88 | html_extra_path = ["robots.txt"] 89 | 90 | # theme 91 | html_theme = "furo" 92 | html_theme_options = { 93 | "navigation_with_keys": True, 94 | "source_repository": pyproject["project"]["urls"]["repository"], 95 | "source_branch": "main", 96 | "source_directory": "docs/", 97 | } 98 | 99 | 100 | # -- EXTENSIONS -------------------------------------------------------- 101 | 102 | myst_enable_extensions = [ 103 | "colon_fence", 104 | "deflist", 105 | "html_image", 106 | "linkify", 107 | "replacements", 108 | "smartquotes", 109 | "substitution", 110 | ] 111 | 112 | myst_heading_anchors = 3 113 | 114 | # replacement variables 115 | myst_substitutions = { 116 | "author": author, 117 | "date_update": datetime.now().strftime("%d %B %Y"), 118 | "description": pyproject["project"]["description"], 119 | "repo_url": pyproject["project"]["urls"]["homepage"], 120 | "title": project, 121 | "version": version, 122 | } 123 | 124 | myst_url_schemes = ("http", "https", "mailto") 125 | 126 | # Configuration for intersphinx (refer to others docs). 127 | intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)} 128 | 129 | # sitemap 130 | sitemap_url_scheme = "{link}" 131 | 132 | # -- Options for Sphinx API doc ---------------------------------------------- 133 | 134 | 135 | # run api doc 136 | def run_apidoc(_): 137 | from sphinx.ext.apidoc import main 138 | 139 | cur_dir = path.normpath(path.dirname(__file__)) 140 | output_path = path.join(cur_dir, "_apidoc") 141 | modules = path.normpath(path.join(cur_dir, "../qgispluginci")) 142 | exclusions = ["../.venv", "../scripts", "../server", "../tests"] 143 | main(["-e", "-f", "-M", "-o", output_path, modules] + exclusions) 144 | 145 | 146 | # launch setup 147 | def setup(app): 148 | app.connect("builder-inited", run_apidoc) 149 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # QGIS Plugin CI 2 | 3 | [![PyPi version badge](https://badgen.net/pypi/v/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 4 | [![PyPI - Downloads](https://img.shields.io/pypi/dm/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 5 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 6 | 7 | [![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) 8 | [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit) 9 | [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/opengisch/qgis-plugin-ci/master.svg)](https://results.pre-commit.ci/latest/github/opengisch/qgis-plugin-ci/master) 10 | 11 | Contains scripts to perform automated testing and deployment for QGIS plugins. 12 | These scripts are written for and tested on GitHub, Travis-CI, github workflows and Transifex. 13 | 14 | - Deploy plugin releases on QGIS official plugin repository 15 | - Publish plugin in Github releases, option to deploy a custom repository 16 | - Easily integrated in Travis-CI or github workflows 17 | - Completely handle translations with Transifex: 18 | - create the project and the languages 19 | - pull and push translations 20 | - all TS/QM files can be managed on the CI, the `i18n` folder can be omitted from the Git repository 21 | - `changelog` section in the metadata.txt can be populated if the CHANGELOG.md is present 22 | - set the `experimental` flag according to the tag if needed 23 | 24 | :book: For further information, see [the documentation](https://opengisch.github.io/qgis-plugin-ci/). 25 | 26 | QGIS-Plugin-CI is best served if you use these two conventions : 27 | 28 | - [Semantic versioning](https://semver.org/) 29 | - [Keep A Changelog](https://keepachangelog.com) 30 | 31 | ## Command line 32 | 33 | ```commandline 34 | usage: qgis-plugin-ci [-h] [-v] 35 | {package,changelog,release,pull-translation,push-translation} 36 | ... 37 | 38 | optional arguments: 39 | -h, --help show this help message and exit 40 | -v, --version print the version and exit 41 | 42 | commands: 43 | qgis-plugin-ci command 44 | 45 | {package,changelog,release,pull-translation,push-translation} 46 | package creates an archive of the plugin 47 | changelog gets the changelog content 48 | release release the plugin 49 | pull-translation pull translations from Transifex 50 | push-translation update strings and push translations 51 | ``` 52 | 53 | ## Requirements 54 | 55 | - The code is under a **git** repository (`git archive` is used to bundle the plugin). 56 | - There is no uncommitted changes when doing a package/release (althought there is an option to bypass this requirement). 57 | - A configuration at the top directory either in `.qgis-plugin-ci` or in `setup.cfg` or `pyproject.toml` with a `[qgis-plugin-ci]` section (see `docs/configuration/options.md` for details). 58 | - The source files of the plugin are within a sub-directory with a `metadata.txt` file with the following fields: 59 | - description 60 | - qgisMinimumVersion 61 | - repository 62 | - tracker 63 | 64 | See `parameters.py` for more parameters and details. Notice that the name of this directory will be used for the zip file. 65 | 66 | ## QRC and UI files 67 | 68 | - Any .qrc file in the source top directory (plugin_path) will be compiled and output as filename_rc.py. You can then import it using `import plugin_path.resources_rc` 69 | - Currently, qgis-plugin-ci does not compile any .ui file. 70 | 71 | ## Publishing plugins 72 | 73 | When releasing, you can publish the plugin : 74 | 75 | 1. In the official QGIS plugin repository. You need to provide user name and password for your Osgeo account. 76 | 2. As a custom repository in Github releases and which can be added later in QGIS. The address will be: https://github.com/__ORG__/__REPO__/releases/latest/download/plugins.xml 77 | 78 | Both can be achieved in the same process. 79 | 80 | ## Pre-release and experimental 81 | 82 | In the case of a pre-release (either from the tag name according to [Semantic Versioning](https://semver.org/) or from the GitHub release), the plugin will be flagged as experimental. 83 | 84 | The tool will recognise any label use as a suffix to flag it as pre-release : 85 | 86 | - `10.1.0-beta1` 87 | - `3.4.0-rc.2` 88 | 89 | ## Debug 90 | 91 | In any Python module, you can have a global variable as `DEBUG = True`, which will be changed to `False` when packaging the plugin. 92 | 93 | ## Other tools 94 | 95 | ### QGIS-Plugin-Repo 96 | 97 | QGIS-Plugin-CI can generate the `plugins.xml` file, per plugin. 98 | If you want to merge many XML files into one to have a single QGIS plugin repository providing many plugins, 99 | you should check [QGIS-Plugin-Repo](https://github.com/3liz/qgis-plugin-repo). 100 | It's designed to run on CI after QGIS-Plugin-CI. 101 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # {{ title }} - Documentation 2 | 3 | > **Description:** {{ description }} 4 | > **Author and contributors:** {{ author }} 5 | > **Version:** {{ version }} 6 | > **Source code:** {{ repo_url }} 7 | > **Last documentation build:** {{ date_update }} 8 | 9 | [![PyPi version badge](https://badgen.net/pypi/v/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 10 | [![PyPI - Downloads](https://img.shields.io/pypi/dm/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 11 | [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/qgis-plugin-ci)](https://pypi.org/project/qgis-plugin-ci/) 12 | 13 | [![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) 14 | [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://github.com/pre-commit/pre-commit) 15 | [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/opengisch/qgis-plugin-ci/master.svg)](https://results.pre-commit.ci/latest/github/opengisch/qgis-plugin-ci/master) 16 | 17 | ## Installation 18 | 19 | Package is available on [PyPi](https://pypi.org/project/qgis-plugin-ci/): 20 | 21 | ```bash 22 | pip install qgis-plugin-ci 23 | ``` 24 | 25 | ```{toctree} 26 | --- 27 | caption: Configuration 28 | maxdepth: 1 29 | --- 30 | configuration/options 31 | configuration/plugin_path 32 | configuration/exclude 33 | configuration/submodules 34 | configuration/translation 35 | ``` 36 | 37 | ```{toctree} 38 | --- 39 | caption: Use the CLI 40 | maxdepth: 1 41 | --- 42 | usage/cli_changelog 43 | usage/cli_package 44 | usage/cli_release 45 | usage/cli_translation 46 | ``` 47 | 48 | ```{toctree} 49 | --- 50 | caption: Use in CI/CD platforms 51 | maxdepth: 1 52 | --- 53 | usage/ci_github 54 | usage/ci_gitlab 55 | usage/ci_docker 56 | usage/ci_travis 57 | ``` 58 | 59 | ```{toctree} 60 | --- 61 | caption: Miscellaneous 62 | maxdepth: 1 63 | --- 64 | misc/credits 65 | misc/faq 66 | ``` 67 | 68 | ```{toctree} 69 | --- 70 | caption: Contribution guide 71 | maxdepth: 1 72 | --- 73 | Code documentation <_apidoc/modules> 74 | development/contribute 75 | development/environment 76 | development/documentation 77 | development/testing 78 | development/history 79 | ``` 80 | 81 | ---- 82 | 83 | ## Plugins published using qgis-plugin-ci 84 | 85 | 86 | 87 | :::::{grid} 2 88 | 89 | :::{card} 90 | :link: https://github.com/opengisch/qgis_server_render_geojson/ 91 | 92 | Render GeoJSON (server) 93 | ^^^^^^^^^^^^^^^^^^^^^^^ 94 | 95 | * deployment on GitHub Releases and plugin repository 96 | * works on GitHub workflows 97 | * barebone implementation, no bells and whistles 98 | ::: 99 | 100 | :::{card} 101 | :link: https://github.com/3liz/lizmap-plugin/ 102 | 103 | Lizmap 104 | ^^^^^^ 105 | 106 | * using a `setup.cfg` file 107 | * metadata populated automatically from CHANGELOG.md file 108 | * GitHub release created automatically from Travis 109 | * released on official repository 110 | * translations are committed from Travis to the repository after the release process 111 | * GitLab-CI with Docker is used as well 112 | ::: 113 | 114 | :::{card} 115 | :link: https://github.com/opengisch/qgis_geomapfish_locator/ 116 | 117 | GeoMapFish Locator 118 | ^^^^^^^^^^^^^^^^^^ 119 | 120 | * translated on Transifex 121 | * released on official repo 122 | ::: 123 | 124 | :::{card} 125 | :link: https://github.com/VeriVD/qgis_VeriVD/ 126 | 127 | VeriVD 128 | ^^^^^^ 129 | 130 | * released on custom repo as GitHub release 131 | ::: 132 | 133 | :::{card} 134 | :link: https://github.com/3liz/qgis-pgmetadata-plugin/ 135 | 136 | pgMetadata 137 | ^^^^^^ 138 | 139 | * Released using GitHub Actions and Transifex 140 | 141 | ::: 142 | 143 | :::{card} 144 | :link: https://github.com/geotribu/qtribu/ 145 | 146 | QTribu 147 | ^^^^^^ 148 | 149 | * GitHub Actions 150 | * using a `setup.cfg` file 151 | * Used to on custom plugins repository as GitHub release 152 | 153 | ::: 154 | 155 | :::{card} 156 | :link: https://gitlab.com/Oslandia/qgis/landsurveycodesimport/ 157 | 158 | Land Survey Codes Import 159 | ^^^^^^^^^^^^^^^^^^^^^^^^ 160 | 161 | * Release using **GitLab CI** 162 | * Local translations 163 | * using a `setup.cfg` file 164 | 165 | ::: 166 | 167 | :::{card} 168 | :link: https://gitlab.com/Oslandia/qgis/french_locator_filter/ 169 | 170 | French Locator Filter 171 | ^^^^^^^^^^^^^^^^^^^^^ 172 | 173 | * Release using **GitLab CI** 174 | * Local translations (no transifex) 175 | * Configured using a `setup.cfg` file 176 | * Both deployed on custom repository on GitLab Pages (on master) on official repository (on git tag) 177 | 178 | ::: 179 | 180 | :::{card} 181 | :link: https://gitlab.com/Oslandia/qgis/thyrsis/ 182 | 183 | Thyrsis 184 | ^^^^^^^ 185 | 186 | * Packaged and release using **GitLab CI** 187 | * Embed some built external dependencies 188 | * Local translations (no transifex) 189 | * Configured using a `setup.cfg` file 190 | * Both deployed on custom repository on GitLab Pages (on master) on official repository (on git tag) 191 | 192 | ::: 193 | 194 | ::::: 195 | 196 | 197 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). 6 | 7 | 8 | 9 | ## Unreleased 10 | 11 | ## 2.5.3 - 2023-02-10 12 | 13 | 14 | 15 | ### Bugs fixes 🐛 16 | 17 | * Bump git hooks to fix pre-commit fail because of isort by @Guts in 18 | 19 | ### Features and enhancements 🎉 20 | 21 | * Add missing aliases to release subcommand by @Guts in 22 | * Python - Use Python fstrings everywhere by @Gustry in 23 | * Add option to use a custom plugin server by @towa in 24 | 25 | ### Documentation 📖 26 | 27 | * Complete latest releases notes to changelog by @Guts in 28 | 29 | ### Other Changes 30 | 31 | * Avoid duplicated dependencies listing by loading dependencies from requirements files by @Guts in 32 | 33 | ### New Contributors 34 | 35 | * @towa made their first contribution in 36 | 37 | ## 2.5.2 - 2022-09-26 38 | 39 | * Align xmlrpc verbosity on CLI option by @Guts in 40 | 41 | ## 2.5.1 - 2022-09-22 42 | 43 | * Fix 159: Add missing parameters and set a default value by @Guts in 44 | 45 | ## 2.5.0 - 2022-09-22 46 | 47 | * fix Experimental flag is not correct for a pre-release tag in the XML by @3nids in 48 | * Fix regression in 2.4 where zip was not compressed by @ivanlonel in 49 | * Use built-in version argument by @Guts in 50 | * use concurrency to avoid multiple workflow running at once by @3nids in 51 | * Do not run pyqt5ac if there is no qrc file by @Guts in 52 | * Feature: add verbosity option and improve log by @Guts in 53 | * Handle missing changelog when latest is passed by @Guts in 54 | * Improve release workflow enabling auto changelog by @Guts in 55 | * Update and clean git hooks by @Guts in 56 | 57 | ## 2.4.0 - 2022-08-25 58 | 59 | * Keep files permissions when creating zip file by @jmkerloch #129 60 | * Update dependencies 61 | * Documentation improvements 62 | 63 | ## 2.3.0 - 2022-03-17 64 | 65 | * Add some metadata in the `metadata.txt` when packaging such as commit number, commit SHA1 and date if these keys are presents 66 | 67 | ## 2.2.0 - 2022-03-17 68 | 69 | * Allow to release a version (1.2.3) which is different from the release tag (v1.2.3) (#120) 70 | 71 | ## 2.1.2 - 2022-02-15 72 | 73 | * Raise an error if a built resource is present in source and the names conflicts by @3nids 74 | 75 | ## 2.1.1 - 2022-01-20 76 | 77 | * Fix a regression from 2.1.0 when the changelog command is used without a configuration file 78 | 79 | ## 2.1.0 - 2022-01-10 80 | 81 | * Add the possibility to choose the changelog filepath in the configuration file with `changelog_path` 82 | * Add some aliases in the command line for some parameters 83 | * Update the documentation 84 | 85 | ## 2.0.1 - 2021-05-11 86 | 87 | * Fix an issue when packaging this project on 88 | 89 | ## 2.0.0 - 2021-05-06 90 | 91 | * Add a dedicated website for the documentation 92 | * Improve the changelog parser : 93 | * The `changelog_regexp` parameter has been removed 94 | * The CHANGELOG.md must follow [semantic versioning](https://semver.org/) and [Keep A Changelog](https://keepachangelog.com/) 95 | * The `experimental` flag is determined automatically if the package name is following the semantic versioning 96 | * Add a special keyword `latest` to package the latest version described in a CHANGELOG.md file 97 | * Possible to install the repository using pip install with the GIT URL 98 | 99 | ## 1.8.4 - 2020-09-07 100 | 101 | * Separate python files and UI files in the temporary PRO file (#29) 102 | 103 | ## 1.8.3 - 2020-08-25 104 | 105 | * Keep the plugin path when creating the ZIP 106 | * Rename qgis_plugin_ci_testing to qgis_plugin_CI_testing to have a capital letter 107 | * Update readme about plugin_path 108 | 109 | ## 1.8.2 - 2020-08-05 110 | 111 | * Run travis on tags too (#24) 112 | 113 | ## 1.8.1 - 2020-08-05 114 | 115 | * better support of spaces in plugin name 116 | * Use underscore instead of hyphen for plugin name #22 (#23) 117 | 118 | ## 1.8.0 - 2020-07-16 119 | 120 | * Create temporary .pro file to make pylupdate5 work with unicode char (#19) 121 | 122 | ## 0.1.2 - 2017-07-23 123 | 124 | (This version note is used in unit-tests) 125 | 126 | * Tag without "v" prefix 127 | * Add a CHANGELOG.md file for testing 128 | -------------------------------------------------------------------------------- /qgispluginci/translation_clients/transifex.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from pathlib import Path 3 | 4 | import requests 5 | from transifex.api import transifex_api as tx_api 6 | from transifex.api.jsonapi.exceptions import DoesNotExist 7 | 8 | from qgispluginci.translation_clients.baseclient import BaseClient, TranslationConfig 9 | 10 | # GLOBALS 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class TransifexClient(BaseClient): 15 | def __init__( 16 | self, config: TranslationConfig, update_string_fcn, create_project: bool = True 17 | ): 18 | super().__init__(config, update_string_fcn, create_project) 19 | 20 | def login(self): 21 | tx_api.setup(auth=self.config.api_token) 22 | self.organization = self.get_organization() 23 | logger.info(f"Logged in as organization: {self.config.organization_name}") 24 | 25 | def get_organization(self): 26 | return tx_api.Organization.get(slug=self.config.organization_name) 27 | 28 | def get_project(self): 29 | try: 30 | return ( 31 | self.get_organization() 32 | .fetch("projects") 33 | .get(slug=self.config.project_slug) 34 | ) 35 | except DoesNotExist: 36 | return None 37 | 38 | def project_exists(self, project_slug: str) -> bool: 39 | """Check if the project exists in the remote Transifex repository""" 40 | try: 41 | if self.get_project(): 42 | return True 43 | return False 44 | except DoesNotExist: 45 | return False 46 | 47 | def create_project(self): 48 | source_language = tx_api.Language.get(code=self.config.source_language_code) 49 | project_name = self.config.project_name or self.config.project_slug 50 | 51 | if self.config.private: 52 | tx_api.Project.create( 53 | name=project_name, 54 | slug=self.config.project_slug, 55 | source_language=source_language, 56 | private=self.config.private, 57 | organization=self.get_organization(), 58 | ) 59 | else: 60 | tx_api.Project.create( 61 | name=project_name, 62 | slug=self.config.project_slug, 63 | source_language=source_language, 64 | private=self.config.private, 65 | organization=self.get_organization(), 66 | repository_url=self.config.repository_url, 67 | ) 68 | 69 | return self.get_project() 70 | 71 | def delete_project(self): 72 | project = self.get_project() 73 | if project: 74 | project.delete() 75 | 76 | def create_resource(self): 77 | resource = tx_api.Resource.create( 78 | project=self.get_project(), 79 | name=self.config.resource_slug, 80 | slug=self.config.resource_slug, 81 | i18n_format=tx_api.I18nFormat(id=self.config.i18n_type), 82 | ) 83 | 84 | with open(self.config.resource_file_path) as fh: 85 | content = fh.read() 86 | 87 | tx_api.ResourceStringsAsyncUpload.upload(content, resource=resource) 88 | logger.info(f"Resource created: {self.config.resource_slug}") 89 | 90 | def get_resource(self): 91 | resources = self.get_project().fetch("resources") 92 | if not resources: 93 | return None 94 | return resources.get(slug=self.config.resource_slug) 95 | 96 | def list_resources(self): 97 | if resources := self.get_project().fetch("resources"): 98 | return list(resources.all()) 99 | else: 100 | return [] 101 | 102 | def list_languages(self): 103 | languages = self.get_project().fetch("languages").all() 104 | return [lang.code for lang in languages] 105 | 106 | def create_language(self, language_code: str, coordinators): 107 | if language := tx_api.Language.get(code=language_code): 108 | logger.debug(f"Adding {language.code} to {self.config.project_slug}") 109 | self.get_project().add("languages", [language]) 110 | 111 | # if coordinators: 112 | # self.get_project().add("coordinators", coordinators) 113 | 114 | def update_source_translation(self): 115 | with open(self.config.resource_file_path) as fh: 116 | content = fh.read() 117 | 118 | tx_api.ResourceStringsAsyncUpload.upload(content, resource=self.get_resource()) 119 | logger.info(f"Source updated for resource: {self.config.resource_slug}") 120 | 121 | def get_translation( 122 | self, 123 | language_code: str, 124 | path_to_output_file: str, 125 | ) -> str: 126 | """Fetch the translation resource matching the given language""" 127 | path_to_parent = Path(path_to_output_file).parent 128 | 129 | Path.mkdir(path_to_parent, parents=True, exist_ok=True) 130 | language = tx_api.Language.get(code=language_code) 131 | 132 | url = tx_api.ResourceTranslationsAsyncDownload.download( 133 | resource=self.get_resource(), language=language 134 | ) 135 | 136 | r = requests.get(url) 137 | # Transifex returns None encoding and the apparent_encoding is Windows-1254 what leads to malformed 138 | # result strings. 139 | # So we set the encoding hardcoded to utf-8. 140 | if not r.encoding: 141 | r.encoding = "utf-8" 142 | translated_content = r.text 143 | with open(path_to_output_file, "w") as fh: 144 | fh.write(translated_content) 145 | 146 | logger.info(f"Translations '{language_code}' downloaded") 147 | return str(path_to_output_file) 148 | -------------------------------------------------------------------------------- /qgispluginci/translation.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import logging 3 | import subprocess 4 | import sys 5 | from pathlib import Path 6 | 7 | from qgispluginci.exceptions import ( 8 | TranslationFailed, 9 | ) 10 | from qgispluginci.parameters import Parameters 11 | from qgispluginci.translation_clients.baseclient import TranslationConfig 12 | from qgispluginci.translation_clients.transifex import TransifexClient 13 | from qgispluginci.utils import touch_file 14 | 15 | # GLOBALS 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | class Translation: 20 | def __init__( 21 | self, parameters: Parameters, tx_api_token: str, create_project: bool = True 22 | ): 23 | """ 24 | Parameters 25 | ---------- 26 | parameters: 27 | 28 | tx_api_token: 29 | Transifex API token 30 | 31 | create_project: 32 | if True, it will create the project, resource and language on Transifex 33 | 34 | """ 35 | self.parameters = parameters 36 | 37 | plugin_path = self.parameters.plugin_path 38 | tx = self.parameters.transifex_resource 39 | lang = self.parameters.translation_source_language 40 | self.ts_file = f"{plugin_path}/i18n/{tx}_{lang}.ts" 41 | 42 | tx_config = TranslationConfig( 43 | api_token=tx_api_token, 44 | organization_name=parameters.transifex_organization, 45 | project_slug=parameters.transifex_project, 46 | repository_url=parameters.repository_url, 47 | source_language_code=parameters.translation_source_language, 48 | resource_file_path=self.ts_file, 49 | resource_slug=self.parameters.transifex_resource, 50 | ) 51 | self.tx_client = TransifexClient(tx_config, self.update_strings, create_project) 52 | 53 | def update_strings(self): 54 | """ 55 | Update TS files from plugin source strings 56 | """ 57 | source_py_files = [] 58 | source_ui_files = [] 59 | relative_path = f"./{self.parameters.plugin_path}" 60 | for ext in ("py", "ui"): 61 | for file in glob.glob( 62 | f"{self.parameters.plugin_path}/**/*.{ext}", 63 | recursive=True, 64 | ): 65 | file_path = str(Path(file).relative_to(relative_path)) 66 | if ext == "py": 67 | source_py_files.append(file_path) 68 | else: 69 | source_ui_files.append(file_path) 70 | 71 | touch_file(self.ts_file) 72 | 73 | project_file = Path(self.parameters.plugin_path).joinpath( 74 | self.parameters.plugin_name + ".pro" 75 | ) 76 | 77 | with open(project_file, "w") as f: 78 | source_py_files = " ".join(source_py_files) 79 | source_ui_files = " ".join(source_ui_files) 80 | assert f.write("CODECFORTR = UTF-8\n") 81 | assert f.write(f"SOURCES = {source_py_files}\n") 82 | assert f.write(f"FORMS = {source_ui_files}\n") 83 | assert f.write( 84 | f"TRANSLATIONS = {Path(self.ts_file).relative_to(relative_path)}\n" 85 | ) 86 | f.flush() 87 | f.close() 88 | 89 | cmd = [self.parameters.pylupdate5_path, "-noobsolete", str(project_file)] 90 | 91 | output = subprocess.run(cmd, capture_output=True, text=True) 92 | 93 | project_file.unlink() 94 | 95 | if output.returncode != 0: 96 | logger.error( 97 | f"Translation failed: {output.stderr}", exc_info=TranslationFailed() 98 | ) 99 | sys.exit(1) 100 | else: 101 | logger.info(f"Successfully run pylupdate5: {output.stdout}") 102 | 103 | def compile_strings(self): 104 | """ 105 | Compile TS file into QM files 106 | """ 107 | cmd = [self.parameters.lrelease_path] 108 | for file in glob.glob(f"{self.parameters.plugin_path}/i18n/*.ts"): 109 | cmd.append(file) 110 | output = subprocess.run(cmd, capture_output=True, text=True) 111 | if output.returncode != 0: 112 | logger.error( 113 | f"Translation failed: {output.stderr}", exc_info=TranslationFailed() 114 | ) 115 | sys.exit(1) 116 | else: 117 | logger.info(f"Successfully run lrelease: {output.stdout}") 118 | 119 | def pull(self): 120 | """ 121 | Pull TS files from Transifex 122 | """ 123 | resource = self.tx_client.get_resource() 124 | existing_langs = self.tx_client.list_languages() 125 | logger.info( 126 | f"{len(existing_langs)} languages found for resource {resource}:" 127 | f" ({existing_langs})" 128 | ) 129 | for lang in self.parameters.translation_languages: 130 | if lang not in existing_langs: 131 | logger.debug(f"Creating missing language: {lang}") 132 | self.tx_client.create_language( 133 | language_code=lang, 134 | coordinators=[self.parameters.transifex_coordinator], 135 | ) 136 | existing_langs.append(lang) 137 | for lang in existing_langs: 138 | ts_file = f"{self.parameters.plugin_path}/i18n/{self.parameters.transifex_resource}_{lang}.ts" 139 | logger.debug(f"Downloading translation file: {ts_file}") 140 | self.tx_client.get_translation( 141 | language_code=lang, 142 | path_to_output_file=ts_file, 143 | ) 144 | 145 | def push(self): 146 | self.tx_client.get_resource() 147 | logger.debug( 148 | f"Pushing resource: {self.parameters.transifex_resource} " 149 | f"with file {self.ts_file}" 150 | ) 151 | self.tx_client.update_source_translation() 152 | -------------------------------------------------------------------------------- /qgispluginci/changelog.py: -------------------------------------------------------------------------------- 1 | #! python3 # noqa E265 2 | 3 | """ 4 | Changelog parser. Following . 5 | """ 6 | 7 | # ############################################################################ 8 | # ########## Libraries ############# 9 | # ################################## 10 | 11 | # standard library 12 | import logging 13 | import re 14 | import sys 15 | from pathlib import Path 16 | from typing import Union 17 | 18 | from qgispluginci.version_note import VersionNote 19 | 20 | # ############################################################################ 21 | # ########## Globals ############# 22 | # ################################ 23 | 24 | # see: https://regex101.com/r/8JROUv/1 25 | CHANGELOG_REGEXP = r"(?<=##)\s*\[*(v?0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)\]?(\(.*\))?(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?\]*\s-\s*([\d\-/]{10})(.*?)(?=##|\Z)" 26 | logger = logging.getLogger(__name__) 27 | 28 | # ############################################################################ 29 | # ########## Classes ############# 30 | # ################################ 31 | 32 | 33 | class ChangelogParser: 34 | CHANGELOG_FILEPATH: Union[Path, None] = None 35 | 36 | @classmethod 37 | def has_changelog( 38 | cls, parent_folder: Union[Path, str] = Path("."), changelog_path="CHANGELOG.md" 39 | ) -> bool: 40 | """Check if a changelog file exists within the parent folder. If it does, \ 41 | it returns True and the file path is stored as class attribute. If not, it \ 42 | returns False and the class attribute is reset to None. 43 | 44 | Args: 45 | parent_folder (Union[Path, str], optional): parent folder where to look \ 46 | for a `CHANGELOG.md` file. Defaults to Path("."). 47 | 48 | changelog_path str: Path relative to parent_folder. Defaults to CHANGELOG.md. 49 | 50 | Raises: 51 | FileExistsError: if the parent_folder path doesn't exist 52 | TypeError: if the path is not a folder but a path 53 | 54 | Returns: 55 | bool: True if a CHANGELOG.md exists within the parent_folder 56 | """ 57 | # reset stored path as class attribute 58 | cls.CHANGELOG_FILEPATH = None 59 | 60 | # ensure using pathlib.Path 61 | if isinstance(parent_folder, str): 62 | parent_folder = Path(parent_folder) 63 | 64 | # check if the folder exists 65 | if not parent_folder.exists(): 66 | logger.error( 67 | f"Parent folder doesn't exist: {parent_folder.resolve()}", 68 | exc_info=FileExistsError(), 69 | ) 70 | sys.exit(1) 71 | # check if path is a folder 72 | if not parent_folder.is_dir(): 73 | logger.error( 74 | f"Path is not a folder: {parent_folder.resolve()}", exc_info=TypeError() 75 | ) 76 | sys.exit(1) 77 | 78 | # build, check and store the changelog path 79 | cls.CHANGELOG_FILEPATH = parent_folder / changelog_path 80 | if cls.CHANGELOG_FILEPATH.is_file(): 81 | logger.info(f"Changelog file used: {cls.CHANGELOG_FILEPATH.resolve()}") 82 | return True 83 | else: 84 | logger.warning( 85 | f"Changelog file doesn't exist: {cls.CHANGELOG_FILEPATH.resolve()}" 86 | ) 87 | cls.CHANGELOG_FILEPATH = None 88 | return False 89 | 90 | def __init__( 91 | self, 92 | parent_folder: Union[Path, str] = Path("."), 93 | changelog_path: str = "CHANGELOG.md", 94 | ): 95 | self.has_changelog(parent_folder=parent_folder, changelog_path=changelog_path) 96 | 97 | def _parse(self): 98 | if not self.CHANGELOG_FILEPATH: 99 | return None 100 | 101 | with self.CHANGELOG_FILEPATH.open(mode="r", encoding="UTF8") as f: 102 | content = f.read() 103 | 104 | return re.findall( 105 | pattern=CHANGELOG_REGEXP, string=content, flags=re.MULTILINE | re.DOTALL 106 | ) 107 | 108 | def last_items(self, count: int) -> str: 109 | """Content to add in the metadata.txt. 110 | 111 | Args: 112 | count (int): Maximum number of tags to include in the file. 113 | 114 | Returns: 115 | str: changelog extraction ready to be added to metadata.txt 116 | """ 117 | changelog_content = self._parse() 118 | if not changelog_content: 119 | return "" 120 | 121 | count = int(count) 122 | output = "\n" 123 | 124 | for version in changelog_content[0:count]: 125 | version_note = VersionNote(*version) 126 | output += f" Version {version_note.version}:\n" 127 | for item in version_note.text.split("\n"): 128 | if item: 129 | output += f" {item}\n" 130 | output += "\n" 131 | return output 132 | 133 | def _version_note(self, tag: str) -> Union[VersionNote, None]: 134 | """Get the tuple for a given version.""" 135 | changelog_content = self._parse() 136 | if not len(changelog_content): 137 | logger.error( 138 | f"Parsing the changelog ({self.CHANGELOG_FILEPATH.resolve()}) " 139 | "returned an empty content." 140 | ) 141 | return None 142 | 143 | if tag == "latest": 144 | return VersionNote(*changelog_content[0]) 145 | 146 | for version in changelog_content: 147 | version_note = VersionNote(*version) 148 | if version_note.version == tag: 149 | return version_note 150 | 151 | def latest_version(self) -> str: 152 | """Return the latest tag described in the changelog file.""" 153 | latest = self._version_note("latest") 154 | logger.debug( 155 | "Latest version retrieved from changelog " 156 | f"({self.CHANGELOG_FILEPATH.resolve()}): {latest.version}" 157 | ) 158 | return latest.version 159 | 160 | def content(self, tag: str) -> Union[str, None]: 161 | """Get a version content to add in a release according to the version name.""" 162 | version_note = self._version_note(tag) 163 | if not version_note: 164 | return None 165 | 166 | return version_note.text 167 | 168 | 169 | # ############################################################################ 170 | # ####### Stand-alone run ######## 171 | # ################################ 172 | if __name__ == "__main__": 173 | pass 174 | -------------------------------------------------------------------------------- /test/test_changelog.py: -------------------------------------------------------------------------------- 1 | #! python3 # noqa E265 2 | 3 | """ 4 | Usage from the repo root folder: 5 | 6 | .. code-block:: bash 7 | # for whole tests 8 | python -m unittest test.test_changelog 9 | # for specific test 10 | python -m unittest test.test_changelog.TestChangelog.test_has_changelog 11 | """ 12 | 13 | # standard library 14 | import tempfile 15 | import unittest 16 | from pathlib import Path 17 | 18 | # project 19 | from qgispluginci.changelog import ChangelogParser 20 | from qgispluginci.version_note import VersionNote 21 | 22 | # ############################################################################ 23 | # ########## Classes ############# 24 | # ################################ 25 | 26 | 27 | class TestChangelog(unittest.TestCase): 28 | def test_has_changelog(self): 29 | """Test changelog path logic.""" 30 | # using this repository as parent folder 31 | self.assertTrue(ChangelogParser.has_changelog()) 32 | self.assertIsInstance(ChangelogParser.CHANGELOG_FILEPATH, Path) 33 | 34 | # using the fixture subfolder as string 35 | self.assertTrue(ChangelogParser.has_changelog(parent_folder="test/fixtures")) 36 | self.assertIsInstance(ChangelogParser.CHANGELOG_FILEPATH, Path) 37 | 38 | # using the fixture subfolder as pathlib.Path 39 | self.assertTrue( 40 | ChangelogParser.has_changelog(parent_folder=Path("test/fixtures")) 41 | ) 42 | self.assertIsInstance(ChangelogParser.CHANGELOG_FILEPATH, Path) 43 | 44 | # with a path to a file, must raise a type error 45 | with self.assertRaises(SystemExit): 46 | ChangelogParser.has_changelog(parent_folder=Path(__file__)) 47 | self.assertIsNone(ChangelogParser.CHANGELOG_FILEPATH, None) 48 | 49 | # with a path to a folder which doesn't exist, must raise a file exists error 50 | with self.assertRaises(SystemExit): 51 | ChangelogParser.has_changelog(parent_folder=Path("imaginary_path")) 52 | 53 | def test_changelog_content(self): 54 | """Test version content from changelog.""" 55 | # parser 56 | parser = ChangelogParser(parent_folder="test/fixtures") 57 | self.assertIsInstance(parser.CHANGELOG_FILEPATH, Path) 58 | 59 | # Unreleased doesn't count 60 | self.assertEqual(7, len(parser._parse())) 61 | 62 | # This version doesn't exist 63 | self.assertIsNone(parser.content("0.0.0")) 64 | 65 | expected_checks = { 66 | "10.1.0-beta1": ( 67 | "- This is the latest documented version in this changelog\n" 68 | "- The changelog module is tested against these lines\n" 69 | "- Be careful modifying this file" 70 | ), 71 | "10.1.0-alpha1": ( 72 | "- This is a version with a prerelease in this changelog\n" 73 | "- The changelog module is tested against these lines\n" 74 | "- Be careful modifying this file" 75 | # "\n" TODO Fixed section is missing 76 | # "- trying with a subsection in a version note" 77 | ), 78 | "10.0.1": "- End of year version", 79 | "10.0.0": "- A\n- B\n- C", 80 | "9.10.1": "- D\n- E\n- F", 81 | "v0.1.1": ( 82 | '* Tag with a "v" prefix to check the regular expression\n' 83 | "* Previous version" 84 | ), 85 | "0.1.0": "* Very old version", 86 | } 87 | for version, expected in expected_checks.items(): 88 | with self.subTest(i=version): 89 | self.assertEqual(parser.content(version), expected) 90 | 91 | def test_changelog_content_latest(self): 92 | """Test against the latest special option value. \ 93 | See: https://github.com/opengisch/qgis-plugin-ci/pull/33 94 | """ 95 | # expected result 96 | expected_latest = ( 97 | "- This is the latest documented version in this changelog\n" 98 | "- The changelog module is tested against these lines\n" 99 | "- Be careful modifying this file" 100 | ) 101 | 102 | # get latest 103 | parser = ChangelogParser(parent_folder="test/fixtures") 104 | self.assertEqual(expected_latest, parser.content("latest")) 105 | 106 | self.assertEqual("10.1.0-beta1", parser.latest_version()) 107 | 108 | def test_changelog_content_ci_fake(self): 109 | """Test specific fake version used in tests.""" 110 | parser = ChangelogParser() 111 | fake_version_content = parser.content(tag="0.1.2") 112 | 113 | # expected result 114 | expected = ( 115 | "(This version note is used in unit-tests)\n\n" 116 | '* Tag without "v" prefix\n' 117 | "* Add a CHANGELOG.md file for testing" 118 | ) 119 | 120 | self.assertIsInstance(fake_version_content, str) 121 | self.assertEqual(expected, fake_version_content) 122 | 123 | def test_different_changelog_file(self): 124 | """Test against a different changelog filename.""" 125 | old = Path("test/fixtures/CHANGELOG.md") 126 | new_folder = Path(tempfile.mkdtemp()) 127 | new_path = new_folder / Path("CHANGELOG-branch-X.md") 128 | self.assertFalse(new_path.exists()) 129 | 130 | new_path.write_text(old.read_text()) 131 | 132 | self.assertTrue( 133 | ChangelogParser.has_changelog( 134 | parent_folder=new_folder, 135 | changelog_path=new_path, 136 | ) 137 | ) 138 | 139 | def test_changelog_last_items(self): 140 | """Test last items from changelog.""" 141 | # on fixture changelog 142 | parser = ChangelogParser(parent_folder="test/fixtures") 143 | last_items = parser.last_items(3) 144 | self.assertIsInstance(last_items, str) 145 | 146 | # on repository changelog 147 | parser = ChangelogParser() 148 | last_items = parser.last_items(3) 149 | self.assertIsInstance(last_items, str) 150 | 151 | def test_changelog_version_note(self): 152 | """Test version note named tuple structure and mechanisms.""" 153 | # parser 154 | parser = ChangelogParser(parent_folder="test/fixtures") 155 | self.assertIsInstance(parser.CHANGELOG_FILEPATH, Path) 156 | 157 | # content parsed 158 | changelog_content = parser._parse() 159 | self.assertEqual(len(changelog_content), 7) 160 | 161 | # loop on versions 162 | for version in changelog_content: 163 | version_note = VersionNote(*version) 164 | self.assertIsInstance(version_note.date, str) 165 | self.assertTrue(hasattr(version_note, "is_prerelease")) 166 | self.assertTrue(hasattr(version_note, "version")) 167 | if len(version_note.prerelease): 168 | self.assertEqual(version_note.is_prerelease, True) 169 | 170 | def test_version_note_tuple(self): 171 | """Test the version note tuple.""" 172 | parser = ChangelogParser(parent_folder="test/fixtures") 173 | 174 | version = parser._version_note("0.0.0") 175 | self.assertIsNone(version) 176 | 177 | version = parser._version_note("10.1.0-beta1") 178 | self.assertEqual("10", version.major) 179 | self.assertEqual("1", version.minor) 180 | self.assertEqual("0", version.patch) 181 | self.assertEqual("", version.url) 182 | self.assertEqual("beta1", version.prerelease) 183 | self.assertTrue(version.is_prerelease) 184 | self.assertEqual("", version.separator) # Not sure what is the separator 185 | self.assertEqual("2021/02/08", version.date) 186 | self.assertEqual( 187 | ( 188 | "- This is the latest documented version in this changelog\n" 189 | "- The changelog module is tested against these lines\n" 190 | "- Be careful modifying this file" 191 | ), 192 | version.text, 193 | ) 194 | 195 | version = parser._version_note("10.0.1") 196 | self.assertEqual("", version.prerelease) 197 | self.assertFalse(version.is_prerelease) 198 | 199 | 200 | # ############################################################################ 201 | # ####### Stand-alone run ######## 202 | # ################################ 203 | if __name__ == "__main__": 204 | unittest.main() 205 | -------------------------------------------------------------------------------- /qgispluginci/cli.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import argparse 3 | import logging 4 | from importlib.metadata import version 5 | 6 | from qgispluginci.changelog import ChangelogParser 7 | from qgispluginci.parameters import Parameters 8 | from qgispluginci.release import release 9 | from qgispluginci.translation import Translation 10 | 11 | __version__ = version("qgis-plugin-ci") 12 | __title__ = "QGISPluginCI" 13 | 14 | 15 | def cli(): 16 | # create the top-level parser 17 | parser = argparse.ArgumentParser( 18 | formatter_class=argparse.ArgumentDefaultsHelpFormatter 19 | ) 20 | 21 | # Optional verbosity counter (eg. -v, -vv, -vvv, etc.) 22 | parser.add_argument( 23 | "-v", 24 | "--verbose", 25 | action="count", 26 | default=1, 27 | dest="verbosity", 28 | help="Verbosity level: None = WARNING, -v = INFO, -vv = DEBUG", 29 | ) 30 | 31 | parser.add_argument( 32 | "--version", 33 | action="version", 34 | version=__version__, 35 | ) 36 | 37 | parser.add_argument( 38 | "--no-validation", 39 | action="store_true", 40 | help="Turn off validation of the version to be released or packaged", 41 | ) 42 | 43 | subparsers = parser.add_subparsers( 44 | title="commands", description="qgis-plugin-ci command", dest="command" 45 | ) 46 | 47 | # package 48 | package_parser = subparsers.add_parser( 49 | "package", help="creates an archive of the plugin" 50 | ) 51 | package_parser.add_argument("release_version", help="The version to be released") 52 | package_parser.add_argument( 53 | "--transifex-token", 54 | help="The Transifex API token. If specified translations will be pulled and compiled.", 55 | ) 56 | package_parser.add_argument( 57 | "-u", 58 | "--plugin-repo-url", 59 | help="If specified, a XML repository file will be created in the current directory, the zip URL will use this parameter.", 60 | ) 61 | package_parser.add_argument( 62 | "-c", 63 | "--allow-uncommitted-changes", 64 | action="store_true", 65 | help="If omitted, uncommitted changes are not allowed before packaging. If specified and some changes are " 66 | "detected, a hard reset on a stash create will be used to revert changes made by qgis-plugin-ci.", 67 | ) 68 | package_parser.add_argument( 69 | "-d", 70 | "--disable-submodule-update", 71 | action="store_true", 72 | help="If omitted, a git submodule is updated. If specified, git submodules will not be updated/initialized before packaging.", 73 | ) 74 | package_parser.add_argument( 75 | "-a", 76 | "--asset-path", 77 | action="append", 78 | help="An additional asset path to add. Can be specified multiple times.", 79 | ) 80 | 81 | # changelog 82 | changelog_parser = subparsers.add_parser( 83 | "changelog", help="gets the changelog content" 84 | ) 85 | changelog_parser.add_argument( 86 | "release_version", 87 | help=( 88 | "The version to be released. If nothing is specified, the latest version specified into the changelog is " 89 | "used." 90 | ), 91 | default="latest", 92 | ) 93 | 94 | # release 95 | release_parser = subparsers.add_parser("release", help="release the plugin") 96 | release_parser.add_argument( 97 | "release_version", help="The version to be released (x.y.z)." 98 | ) 99 | release_parser.add_argument( 100 | "--release-tag", 101 | help="The release tag, if different from the version (e.g. vx.y.z).", 102 | ) 103 | release_parser.add_argument( 104 | "--transifex-token", 105 | help="The Transifex API token. If specified translations will be pulled and compiled.", 106 | ) 107 | release_parser.add_argument( 108 | "--github-token", 109 | help="The Github API token. If specified, the archive will be pushed to an already existing release.", 110 | ) 111 | release_parser.add_argument( 112 | "-r", 113 | "--create-plugin-repo", 114 | action="store_true", 115 | help="Will create a XML repo as a Github release asset. Github token is required.", 116 | ) 117 | release_parser.add_argument( 118 | "-c", 119 | "--allow-uncommitted-changes", 120 | action="store_true", 121 | help="If omitted, uncommitted changes are not allowed before releasing. If specified and some changes are " 122 | "detected, a hard reset on a stash create will be used to revert changes made by qgis-plugin-ci.", 123 | ) 124 | release_parser.add_argument( 125 | "-d", 126 | "--disable-submodule-update", 127 | action="store_true", 128 | help="If omitted, a git submodule is updated. If specified, git submodules will not be updated/initialized before packaging.", 129 | ) 130 | release_parser.add_argument( 131 | "-a", 132 | "--asset-path", 133 | action="append", 134 | help="An additional asset path to add. Can be specified multiple times.", 135 | ) 136 | release_parser.add_argument( 137 | "--alternative-repo-url", 138 | help="The URL of the endpoint to publish the plugin (defaults to plugins.qgis.org)", 139 | ) 140 | release_parser.add_argument( 141 | "--osgeo-username", help="The Osgeo user name to publish the plugin." 142 | ) 143 | release_parser.add_argument( 144 | "--osgeo-password", help="The Osgeo password to publish the plugin." 145 | ) 146 | 147 | # pull-translation 148 | pull_tr_parser = subparsers.add_parser( 149 | "pull-translation", help="pull translations from Transifex" 150 | ) 151 | pull_tr_parser.add_argument("transifex_token", help="The Transifex API token") 152 | pull_tr_parser.add_argument( 153 | "--compile", action="store_true", help="Will compile TS files into QM files" 154 | ) 155 | 156 | # push-translation 157 | push_tr_parser = subparsers.add_parser( 158 | "push-translation", help="update strings and push translations" 159 | ) 160 | push_tr_parser.add_argument("transifex_token", help="The Transifex API token") 161 | 162 | args = parser.parse_args() 163 | Parameters.validate_args(args) 164 | 165 | # set log level depending on verbosity argument 166 | args.verbosity = 40 - (10 * args.verbosity) if args.verbosity > 0 else 0 167 | logging.basicConfig( 168 | level=args.verbosity, 169 | format="%(asctime)s||%(levelname)s||%(module)s||%(message)s", 170 | datefmt="%Y-%m-%d %H:%M:%S", 171 | ) 172 | 173 | console = logging.StreamHandler() 174 | console.setLevel(args.verbosity) 175 | 176 | # add the handler to the root logger 177 | logger = logging.getLogger(__title__) 178 | logger.debug(f"Log level set: {logging}") 179 | 180 | # if no command is passed, print the help and exit 181 | if not args.command: 182 | parser.print_help() 183 | parser.exit() 184 | 185 | exit_val = 0 186 | 187 | # CHANGELOG 188 | if args.command == "changelog": 189 | try: 190 | # Initialize Parameters 191 | # Configuration file is optional at this stage 192 | parameters = Parameters.make_from(args=args, optional_configuration=True) 193 | c = ChangelogParser( 194 | changelog_path=parameters.changelog_path, 195 | ) 196 | content = c.content(args.release_version) 197 | if content: 198 | print(content) # noqa: T2 199 | except Exception as exc: 200 | logger.error("Something went wrong reading the changelog.", exc_info=exc) 201 | exit_val = 1 202 | 203 | return exit_val 204 | 205 | # Initialize Parameters 206 | # Configuration file is now required 207 | parameters = Parameters.make_from(args=args) 208 | 209 | # PACKAGE 210 | if args.command == "package": 211 | release( 212 | parameters, 213 | release_version=args.release_version, 214 | tx_api_token=args.transifex_token, 215 | allow_uncommitted_changes=args.allow_uncommitted_changes, 216 | plugin_repo_url=args.plugin_repo_url, 217 | disable_submodule_update=args.disable_submodule_update, 218 | asset_paths=args.asset_path, 219 | ) 220 | 221 | # RELEASE 222 | elif args.command == "release": 223 | release( 224 | parameters, 225 | release_version=args.release_version, 226 | release_tag=args.release_tag, 227 | tx_api_token=args.transifex_token, 228 | github_token=args.github_token, 229 | upload_plugin_repo_github=args.create_plugin_repo, 230 | alternative_repo_url=args.alternative_repo_url, 231 | osgeo_username=args.osgeo_username, 232 | osgeo_password=args.osgeo_password, 233 | allow_uncommitted_changes=args.allow_uncommitted_changes, 234 | disable_submodule_update=args.disable_submodule_update, 235 | asset_paths=args.asset_path, 236 | ) 237 | 238 | # TRANSLATION PULL 239 | elif args.command == "pull-translation": 240 | t = Translation(parameters, args.transifex_token) 241 | t.pull() 242 | if args.compile: 243 | t.compile_strings() 244 | 245 | # TRANSLATION PUSH 246 | elif args.command == "push-translation": 247 | t = Translation(parameters, args.transifex_token) 248 | t.update_strings() 249 | t.push() 250 | 251 | else: 252 | logger.error(f"Unsupported command {args.command}") 253 | exit_val = 1 254 | 255 | return exit_val 256 | -------------------------------------------------------------------------------- /test/test_release.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | # standard 4 | import argparse 5 | import filecmp 6 | import os 7 | import re 8 | import unittest 9 | import urllib.request 10 | from itertools import product 11 | from pathlib import Path 12 | from tempfile import mkstemp 13 | from zipfile import ZipFile 14 | 15 | # 3rd party 16 | import yaml 17 | from github import Github, GithubException 18 | 19 | # Tests 20 | from utils import can_skip_test_github 21 | 22 | # Project 23 | from qgispluginci.changelog import ChangelogParser 24 | from qgispluginci.exceptions import GithubReleaseNotFound 25 | from qgispluginci.parameters import DASH_WARNING, Parameters 26 | from qgispluginci.release import release 27 | from qgispluginci.translation import Translation 28 | from qgispluginci.utils import replace_in_file 29 | 30 | # If changed, also update CHANGELOG.md 31 | RELEASE_VERSION_TEST = "0.1.2" 32 | 33 | 34 | class TestRelease(unittest.TestCase): 35 | def setUp(self): 36 | self.setup_params = Parameters.make_from( 37 | path_to_config_file=Path("test/fixtures/setup.cfg") 38 | ) 39 | self.qgis_plugin_config_params = Parameters.make_from( 40 | path_to_config_file=Path("test/fixtures/.qgis-plugin-ci") 41 | ) 42 | self.pyproject_params = Parameters.make_from( 43 | path_to_config_file=Path("test/fixtures/pyproject.toml") 44 | ) 45 | self.tx_api_token = os.getenv("tx_api_token") 46 | self.github_token = os.getenv("github_token") 47 | self.repo = None 48 | self.t = None 49 | if self.github_token: 50 | print("init Github") 51 | self.repo = Github(self.github_token).get_repo("opengisch/qgis-plugin-ci") 52 | self.clean_assets() 53 | 54 | def tearDown(self): 55 | self.clean_assets() 56 | 57 | def clean_assets(self): 58 | if self.repo: 59 | rel = None 60 | try: 61 | rel = self.repo.get_release(id=RELEASE_VERSION_TEST) 62 | except GithubException: 63 | raise GithubReleaseNotFound(f"Release {RELEASE_VERSION_TEST} not found") 64 | if rel: 65 | print("deleting release assets") 66 | for asset in rel.get_assets(): 67 | print(f" delete {asset.name}") 68 | asset.delete_asset() 69 | if self.t: 70 | self.t._t.delete_project(self.qgis_plugin_config_params.project_slug) 71 | 72 | def test_dict_from_config(self): 73 | with self.subTest(): 74 | self.assertTrue(dict(self.qgis_plugin_config_params)) 75 | self.assertTrue(dict(self.pyproject_params)) 76 | self.assertTrue(dict(self.setup_params)) 77 | 78 | def test_release_from_dot_qgis_plugin_ci(self): 79 | release(self.qgis_plugin_config_params, RELEASE_VERSION_TEST) 80 | 81 | def test_release_from_pyproject(self): 82 | print(self.pyproject_params) 83 | release(self.pyproject_params, RELEASE_VERSION_TEST) 84 | 85 | def test_release_with_empty_tx_token(self): 86 | release( 87 | self.qgis_plugin_config_params, 88 | RELEASE_VERSION_TEST, 89 | tx_api_token="", 90 | ) 91 | 92 | @unittest.skipIf(can_skip_test_github(), "Missing tx_api_token") 93 | def test_release_with_transifex(self): 94 | Translation(self.qgis_plugin_config_params, tx_api_token=self.tx_api_token) 95 | release( 96 | self.qgis_plugin_config_params, 97 | RELEASE_VERSION_TEST, 98 | tx_api_token=self.tx_api_token, 99 | ) 100 | 101 | def test_zipname(self): 102 | """Tests about the zipname for the QGIS plugin manager. 103 | 104 | See #22 about dash 105 | and also capital letters 106 | """ 107 | self.assertEqual( 108 | "my_plugin.0.0.0.zip", 109 | Parameters.archive_name("my_plugin", "0.0.0"), 110 | ) 111 | 112 | with self.assertLogs( 113 | logger="qgispluginci.parameters", level="WARNING" 114 | ) as captured: 115 | Parameters.archive_name("my-plugin", "0.0.0") 116 | self.assertEqual( 117 | len(captured.records), 1 118 | ) # check that there is only one log message 119 | self.assertEqual(captured.records[0].getMessage(), DASH_WARNING) 120 | 121 | @unittest.skipIf(can_skip_test_github(), "Missing github_token") 122 | def test_release_upload_github(self): 123 | release( 124 | self.qgis_plugin_config_params, 125 | RELEASE_VERSION_TEST, 126 | github_token=self.github_token, 127 | upload_plugin_repo_github=True, 128 | ) 129 | 130 | # check the custom plugin repo 131 | _, xml_repo = mkstemp(suffix=".xml") 132 | url = f"https://github.com/opengisch/qgis-plugin-ci/releases/download/{RELEASE_VERSION_TEST}/plugins.xml" 133 | print(f"retrieve repo from {url}") 134 | urllib.request.urlretrieve(url, xml_repo) 135 | replace_in_file( 136 | xml_repo, 137 | r"[\w-]+<\/update_date>", 138 | "__TODAY__", 139 | ) 140 | if not filecmp.cmp("test/plugins.xml.expected", xml_repo, shallow=False): 141 | import difflib 142 | 143 | with open("test/plugins.xml.expected") as f: 144 | text1 = f.readlines() 145 | with open(xml_repo) as f: 146 | text2 = f.readlines() 147 | self.assertFalse(True, "\n".join(difflib.unified_diff(text1, text2))) 148 | 149 | # compare archive file size 150 | gh_release = self.repo.get_release(id=RELEASE_VERSION_TEST) 151 | archive_name = self.qgis_plugin_config_params.archive_name( 152 | self.qgis_plugin_config_params.plugin_path, RELEASE_VERSION_TEST 153 | ) 154 | fs = os.path.getsize(archive_name) 155 | print("size: ", fs) 156 | self.assertGreater(fs, 0, "archive file size must be > 0") 157 | found = False 158 | for a in gh_release.get_assets(): 159 | if a.name == archive_name: 160 | found = True 161 | self.assertEqual(fs, a.size, "asset size doesn't march archive size.") 162 | break 163 | self.assertTrue(found, "asset not found") 164 | 165 | def test_release_changelog(self): 166 | """Test if changelog in metadata.txt inside zipped plugin after release command.""" 167 | # variables 168 | cli_config_changelog = Path("test/fixtures/.qgis-plugin-ci-test-changelog.yaml") 169 | version_to_release = "0.1.2" 170 | 171 | # load specific parameters 172 | with cli_config_changelog.open() as in_cfg: 173 | arg_dict = yaml.safe_load(in_cfg) 174 | parameters = Parameters(arg_dict) 175 | self.assertIsInstance(parameters, Parameters) 176 | 177 | # get output zip path 178 | archive_name = parameters.archive_name( 179 | plugin_name=parameters.plugin_path, release_version=version_to_release 180 | ) 181 | 182 | # extract last items from changelog 183 | parser = ChangelogParser() 184 | self.assertTrue(parser.has_changelog()) 185 | changelog_lastitems = parser.last_items( 186 | count=parameters.changelog_number_of_entries 187 | ) 188 | 189 | # Include a changelog 190 | release( 191 | parameters=parameters, 192 | release_version=version_to_release, 193 | allow_uncommitted_changes=True, 194 | ) 195 | 196 | # open archive and compare 197 | with ZipFile(archive_name, "r") as zip_file: 198 | data = zip_file.read(f"{parameters.plugin_path}/metadata.txt") 199 | license_data = zip_file.read(f"{parameters.plugin_path}/LICENSE") 200 | 201 | # Changelog 202 | self.assertGreater( 203 | data.find(bytes(changelog_lastitems, "utf8")), 204 | 0, 205 | f"changelog detection failed in release: {data}", 206 | ) 207 | 208 | # License 209 | self.assertGreater( 210 | license_data.find(bytes("GNU GENERAL PUBLIC LICENSE", "utf8")), 211 | 0, 212 | "license file content mismatch", 213 | ) 214 | 215 | # Commit number 216 | self.assertEqual(1, len(re.findall(r"commitNumber=\d+", str(data)))) 217 | 218 | # Commit sha1 not in the metadata.txt 219 | self.assertEqual(0, len(re.findall(r"commitSha1=\d+", str(data)))) 220 | 221 | def test_release_version_valid_invalid(self): 222 | valid_tags = [ 223 | "v1.1.1", 224 | "v1.1", 225 | "1.0.1", 226 | "1.1", 227 | "1.0.0-alpha", 228 | "1.0.0-dev", 229 | "latest", 230 | ] 231 | invalid_tags = ["1", "v1", ".", ".1"] 232 | expected_valid_results = { 233 | "v1.1.1": ["v3"], 234 | "v1.1": ["v2"], 235 | "1.0.1": ["double", "semver"], 236 | "1.1": ["simple"], 237 | "1.0.0-alpha": ["semver"], 238 | "1.0.0-dev": ["semver"], 239 | "latest": ["latest"], 240 | } 241 | valid_results = {tag: [] for tag in valid_tags} 242 | patterns = Parameters.get_release_version_patterns() 243 | for key, cand in product(patterns, valid_results): 244 | if re.match(patterns[key], cand): 245 | valid_results[cand].append(key) 246 | self.assertEqual(valid_results, expected_valid_results) 247 | 248 | invalid_results = {tag: [] for tag in invalid_tags} 249 | for key, cand in product(patterns, invalid_results): 250 | if re.match(patterns[key], cand): 251 | invalid_results[cand].append(key) 252 | self.assertFalse(any(invalid_results.values())) 253 | 254 | def test_release_version_validation_on(self): 255 | parser = argparse.ArgumentParser() 256 | subparsers = parser.add_subparsers( 257 | title="commands", description="qgis-plugin-ci command", dest="command" 258 | ) 259 | sub_parser = subparsers.add_parser("package") 260 | sub_parser.add_argument("release_version") 261 | sub_parser.add_argument("--no-validation", action="store_true") 262 | args = parser.parse_args(["package", "v1"]) 263 | with self.assertRaises(ValueError): 264 | Parameters.validate_args(args) 265 | 266 | def test_release_version_validation_off(self): 267 | parser = argparse.ArgumentParser() 268 | subparsers = parser.add_subparsers( 269 | title="commands", description="qgis-plugin-ci command", dest="command" 270 | ) 271 | sub_parser = subparsers.add_parser("package") 272 | sub_parser.add_argument("release_version") 273 | sub_parser.add_argument("--no-validation", action="store_true") 274 | args = parser.parse_args(["package", "v1", "--no-validation"]) 275 | Parameters.validate_args(args) 276 | 277 | 278 | if __name__ == "__main__": 279 | unittest.main() 280 | -------------------------------------------------------------------------------- /qgis_plugin_CI_testing/ui/config.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | Config 4 | 5 | 6 | 7 | 0 8 | 0 9 | 606 10 | 453 11 | 12 | 13 | 14 | Swiss locator filter configuration 15 | 16 | 17 | 18 | 19 | 20 | Language 21 | 22 | 23 | 24 | 25 | 26 | 27 | Coordinates system 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | Qt::Horizontal 41 | 42 | 43 | QDialogButtonBox::Cancel|QDialogButtonBox::Ok 44 | 45 | 46 | 47 | 48 | 49 | 50 | Qt::Horizontal 51 | 52 | 53 | 54 | 40 55 | 20 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 0 64 | 65 | 66 | 67 | Locations 68 | 69 | 70 | 71 | 72 | 73 | Filter priority 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | Maximum number of results 87 | 88 | 89 | 90 | 91 | 92 | 93 | Qt::Vertical 94 | 95 | 96 | 97 | 20 98 | 40 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | Qt::Horizontal 107 | 108 | 109 | 110 | 40 111 | 20 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | Feature search 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | Maximum number of results 133 | 134 | 135 | 136 | 137 | 138 | 139 | Filter priority 140 | 141 | 142 | 143 | 144 | 145 | 146 | Qt::Horizontal 147 | 148 | 149 | 150 | 40 151 | 20 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | Restrict feature search to specific layers 160 | 161 | 162 | true 163 | 164 | 165 | true 166 | 167 | 168 | 169 | 170 | 171 | true 172 | 173 | 174 | true 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | true 185 | 186 | 187 | select all 188 | 189 | 190 | 191 | 192 | 193 | 194 | true 195 | 196 | 197 | unselect all 198 | 199 | 200 | 201 | 202 | 203 | 204 | Qt::Horizontal 205 | 206 | 207 | 208 | 40 209 | 20 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | true 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | WMS layers 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | Qt::Vertical 241 | 242 | 243 | 244 | 20 245 | 40 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | Maximum number of results 254 | 255 | 256 | 257 | 258 | 259 | 260 | Qt::Horizontal 261 | 262 | 263 | 264 | 40 265 | 20 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | Filter priority 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | Show map tip on the map whenever possible 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | QgsFilterLineEdit 293 | QLineEdit 294 |
qgsfilterlineedit.h
295 |
296 |
297 | 298 | 299 | 300 | buttonBox 301 | accepted() 302 | Config 303 | accept() 304 | 305 | 306 | 254 307 | 419 308 | 309 | 310 | 157 311 | 274 312 | 313 | 314 | 315 | 316 | buttonBox 317 | rejected() 318 | Config 319 | reject() 320 | 321 | 322 | 322 323 | 419 324 | 325 | 326 | 286 327 | 274 328 | 329 | 330 | 331 | 332 |
333 | -------------------------------------------------------------------------------- /qgispluginci/parameters.py: -------------------------------------------------------------------------------- 1 | #! python3 # noqa E265 2 | 3 | """ 4 | Parameters management. 5 | """ 6 | 7 | # ############################################################################ 8 | # ########## Libraries ############# 9 | # ################################## 10 | 11 | import configparser 12 | import datetime 13 | import logging 14 | import os 15 | import re 16 | import sys 17 | 18 | # standard library 19 | from argparse import Namespace 20 | from collections.abc import Iterator 21 | from pathlib import Path 22 | from typing import Any, Callable, Optional 23 | 24 | 25 | if sys.version_info >= (3, 11): 26 | import tomllib 27 | else: 28 | import tomli as tomllib 29 | 30 | 31 | import yaml 32 | 33 | # 3rd party 34 | from slugify import slugify 35 | 36 | from qgispluginci.exceptions import ConfigurationNotFound 37 | 38 | # ############################################################################ 39 | # ########## Globals ############# 40 | # ################################ 41 | 42 | 43 | DASH_WARNING = "Dash in the plugin name is causing issues with QGIS plugin manager" 44 | 45 | logger = logging.getLogger(__name__) 46 | 47 | 48 | # ############################################################################ 49 | # ########## Classes ############# 50 | # ################################ 51 | 52 | 53 | class Parameters: 54 | """ 55 | Attributes 56 | ---------- 57 | plugin_path: str 58 | The directory of the source code in the repository. 59 | Defaults to: `slugify(plugin_name)` 60 | 61 | github_organization_slug: str 62 | The organization slug on SCM host (e.g. Github) and translation platform (e.g. Transifex). 63 | Not required when running on Travis since deduced from `$TRAVIS_REPO_SLUG`environment variable. 64 | 65 | project_slug: str 66 | The project slug on SCM host (e.g. Github) and translation platform (e.g. Transifex). 67 | Not required when running on Travis since deduced from `$TRAVIS_REPO_SLUG`environment variable. 68 | 69 | transifex_coordinator: str 70 | The username of the coordinator in Transifex. 71 | Required to create new languages. 72 | 73 | transifex_organization: str 74 | The organization name in Transifex 75 | Defaults to: the GitHub organization slug 76 | 77 | transifex_project: str 78 | The project on Transifex, which can be different from the one on GitHub. 79 | Defaults to: the project_slug 80 | 81 | transifex_resource: str 82 | The resource name in transifex 83 | Defaults to: the project_slug 84 | 85 | translation_source_language: 86 | The source language for translations. 87 | Defaults to: 'en' 88 | 89 | translation_languages: 90 | List of languages. 91 | 92 | changelog_include: 93 | If the changelog must be added when releasing a version AND if there is a CHANGELOG.md file 94 | Defaults to True 95 | 96 | changelog_path: 97 | Path to the CHANGELOG.md relative to the configuration file. Defaults to CHANGELOG.md 98 | 99 | changelog_number_of_entries: 100 | Number of changelog entries to add in the metdata.txt 101 | Defaults to 3 102 | 103 | create_date: datetime.date 104 | The date of creation of the plugin. 105 | The would be used in the custom repository XML. 106 | Format: YYYY-MM-DD 107 | 108 | lrelease_path: str 109 | The path of lrelease executable 110 | 111 | pylupdate5_path: str 112 | The path of pylupdate executable 113 | 114 | use_project_slug_as_plugin_directory: bool 115 | If True, the `project_slug` is used for the plugin directory name in the installation. 116 | Defaults to False 117 | 118 | """ 119 | 120 | @classmethod 121 | def make_from( 122 | cls, 123 | *, 124 | args: Optional[Any] = None, 125 | path_to_config_file: Optional[Path] = None, 126 | optional_configuration: bool = False, 127 | ) -> "Parameters": 128 | """ 129 | Instantiate from a config file or by exploring the filesystem 130 | Accepts an argparse Namespace for backward compatibility. 131 | """ 132 | supported_config_file_names = { 133 | "setup.cfg", 134 | ".qgis-plugin-ci", 135 | "pyproject.toml", 136 | } 137 | configuration_not_found = ConfigurationNotFound( 138 | ".qgis-plugin-ci or setup.cfg or pyproject.toml with a 'qgis-plugin-ci' section have not been found." 139 | ) 140 | 141 | def load_config(path_to_config_file: Path, file_name: str) -> dict[str, Any]: 142 | if file_name == "setup.cfg": 143 | config = configparser.ConfigParser() 144 | config.read(path_to_config_file) 145 | arg_dict = dict(config.items("qgis-plugin-ci")) 146 | else: 147 | if file_name == ".qgis-plugin-ci": 148 | with open(path_to_config_file) as fh: 149 | arg_dict = yaml.safe_load(fh) 150 | elif file_name == "pyproject.toml": 151 | with open(path_to_config_file, "rb") as fh: 152 | contents = tomllib.load(fh) 153 | arg_dict = contents["tool"]["qgis-plugin-ci"] 154 | else: 155 | raise configuration_not_found 156 | return arg_dict 157 | 158 | def explore_config() -> dict[str, Any]: 159 | for file_name in supported_config_file_names: 160 | path_to_file = Path(file_name) 161 | if path_to_file.is_file(): 162 | try: 163 | return load_config(path_to_file, path_to_file.name) 164 | except ( 165 | ConfigurationNotFound, 166 | configparser.NoSectionError, 167 | KeyError, 168 | ): 169 | pass 170 | raise configuration_not_found 171 | 172 | if optional_configuration and not path_to_config_file: 173 | return cls({}) 174 | 175 | if path_to_config_file: 176 | file_name = path_to_config_file.name 177 | 178 | if not ( 179 | path_to_config_file.is_file() 180 | and file_name in supported_config_file_names 181 | ): 182 | raise configuration_not_found 183 | config_dict = load_config(path_to_config_file, file_name) 184 | else: 185 | config_dict = explore_config() 186 | return cls(config_dict) 187 | 188 | def __init__(self, definition: dict[str, Any]): 189 | self.plugin_path = definition.get("plugin_path") 190 | self.changelog_path = definition.get("changelog_path", "CHANGELOG.md") 191 | 192 | if not self.plugin_path: 193 | # This tool can be used outside of a QGIS plugin to read a changelog file 194 | return 195 | 196 | get_metadata = self.collect_metadata() 197 | self.plugin_name = get_metadata("name") 198 | self.plugin_slug = slugify(self.plugin_name, separator="_") 199 | 200 | # fix directory in zip file 201 | self.use_project_slug_as_plugin_directory = definition.get( 202 | "use_project_slug_as_plugin_directory", False 203 | ) 204 | # if not top level: force to use project slug 205 | if self.plugin_path.count("/") > 0: 206 | self.plugin_zip_directory = self.plugin_slug 207 | # otherwise use setting 208 | elif self.use_project_slug_as_plugin_directory: 209 | self.plugin_zip_directory = self.plugin_slug 210 | # we cannot force to use project_slug as it would be a breaking change for existing plugins 211 | # as this would lead to have 2 versions of the plugin (1 with the old directory name, 1 with the old one) 212 | else: 213 | self.plugin_zip_directory = self.plugin_path 214 | 215 | self.project_slug = definition.get( 216 | "project_slug", 217 | os.environ.get("TRAVIS_REPO_SLUG", f".../{self.plugin_slug}").split("/")[1], 218 | ) 219 | self.github_organization_slug = definition.get( 220 | "github_organization_slug", 221 | os.environ.get("TRAVIS_REPO_SLUG", "").split("/")[0], 222 | ) 223 | self.transifex_coordinator = definition.get("transifex_coordinator", "") 224 | self.transifex_organization = definition.get( 225 | "transifex_organization", self.github_organization_slug 226 | ) 227 | self.translation_source_language = definition.get( 228 | "translation_source_language", "en" 229 | ) 230 | self.translation_languages = definition.get("translation_languages", {}) 231 | self.transifex_project = definition.get("transifex_project", self.project_slug) 232 | self.transifex_resource = definition.get( 233 | "transifex_resource", self.project_slug 234 | ) 235 | self.create_date = datetime.datetime.strptime( 236 | str(definition.get("create_date", datetime.date.today())), "%Y-%m-%d" 237 | ) 238 | self.lrelease_path = definition.get("lrelease_path", "lrelease") 239 | self.pylupdate5_path = definition.get("pylupdate5_path", "pylupdate5") 240 | changelog_include = definition.get("changelog_include", True) 241 | if isinstance(changelog_include, str): 242 | self.changelog_include = changelog_include.lower() in [ 243 | "true", 244 | "1", 245 | "t", 246 | "y", 247 | ] 248 | else: 249 | self.changelog_include = changelog_include 250 | self.changelog_number_of_entries = definition.get( 251 | "changelog_number_of_entries", 3 252 | ) 253 | 254 | # read from metadata 255 | self.author = get_metadata("author", "") 256 | self.description = get_metadata("description") 257 | self.qgis_minimum_version = get_metadata("qgisMinimumVersion") 258 | self.icon = get_metadata("icon", "") 259 | self.tags = get_metadata("tags", "") 260 | self.experimental = get_metadata("experimental", False) 261 | self.deprecated = get_metadata("deprecated", False) 262 | self.issue_tracker = get_metadata("tracker") 263 | self.homepage = get_metadata("homepage", "") 264 | if self.homepage == "": 265 | logger.warning( 266 | "Homepage is not given in the metadata. " 267 | "It is a mandatory information to publish " 268 | "the plugin on the QGIS official repository." 269 | ) 270 | self.repository_url = get_metadata("repository") 271 | 272 | # check if slugs have not trailing slash 273 | if any( 274 | ( 275 | isinstance(self.plugin_slug, str) and self.plugin_slug.endswith("/"), 276 | isinstance(self.project_slug, str) and self.project_slug.endswith("/"), 277 | isinstance(self.github_organization_slug, str) 278 | and self.github_organization_slug.endswith("/"), 279 | ) 280 | ): 281 | logger.error( 282 | ValueError( 283 | "The plugin, project or organization slugs must not have a trailing slash." 284 | ) 285 | ) 286 | 287 | @staticmethod 288 | def get_release_version_patterns() -> dict[str, re.Pattern]: 289 | return { 290 | "simple": r"\d+\.\d+$", 291 | "double": r"\d+\.\d+\.\d+$", 292 | "v2": r"^v\d+\.\d+$", 293 | "v3": r"^v\d+\.\d+\.\d+$", 294 | # See https://github.com/semver/semver/blob/master/semver.md#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string 295 | "semver": r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$", 296 | "latest": r"^latest$", 297 | } 298 | 299 | @staticmethod 300 | def validate_args(args: Namespace): 301 | """ 302 | Raise an exception just in case: 303 | - the user didn't opt-out of validation using the `--no-validation` flag; and 304 | - the value of `release_version` matches no supported pattern. 305 | """ 306 | if not hasattr(args, "release_version") or not args.release_version: 307 | return 308 | 309 | if args.no_validation: 310 | logging.warning("Disabled release version validation.") 311 | return 312 | 313 | patterns = Parameters.get_release_version_patterns() 314 | semver_compliance = re.match(patterns.pop("semver"), args.release_version) 315 | 316 | if not semver_compliance: 317 | logging.warning( 318 | f"Be aware that '{args.release_version}' is not a semver-compliant " 319 | "version. It might still comply with acceptable practices." 320 | ) 321 | 322 | if semver_compliance or any( 323 | re.match(other_pattern, args.release_version) 324 | for other_pattern in patterns.values() 325 | ): 326 | return 327 | 328 | raise ValueError( 329 | f""" 330 | Unable to validate the release version '{args.release_version}'. 331 | Please use a release version identifier such as '1.0.1' (recommended, semantic versioning), 'v1.1.1', 'v1.1', or '1.1'. 332 | Otherwise you can disable validation by running this command again with an extra '--no-validation' flag. 333 | Semantic versioning (semvar) identifiers are recommended. 334 | Take a look at https://en.wikipedia.org/wiki/Software_versioning#Semantic_versioning for a refresher." 335 | """ 336 | ) 337 | 338 | @staticmethod 339 | def archive_name(plugin_name, release_version: str) -> str: 340 | """ 341 | Returns the archive file name 342 | """ 343 | # zipname: use dot before version number 344 | # and not dash since it's causing issues #22 345 | if "-" in plugin_name: 346 | logger.warning(DASH_WARNING) 347 | 348 | return f"{plugin_name}.{release_version}.zip" 349 | 350 | def collect_metadata(self) -> Callable[[str, Optional[Any]], Any]: 351 | """ 352 | Returns a closure capturing a Dict of metadata, allowing to retrieve one 353 | value after the other while also iterating over the file once. 354 | """ 355 | metadata_file = f"{self.plugin_path}/metadata.txt" 356 | metadata = {} 357 | with open(metadata_file) as fh: 358 | for line in fh: 359 | split = line.strip().split("=", 1) 360 | if len(split) == 2: 361 | metadata[split[0]] = split[1] 362 | 363 | def get_metadata(key: str, default_value: Optional[Any] = None) -> Any: 364 | if not self.plugin_path: 365 | return "" 366 | 367 | value = metadata.get(key, None) 368 | if value: 369 | return value 370 | elif default_value is not None: 371 | return default_value 372 | else: 373 | logger.error(f"Mandatory key is missing in metadata: {key}") 374 | sys.exit(1) 375 | 376 | return get_metadata 377 | 378 | def __iter__(self) -> Iterator[tuple[str, Any]]: 379 | """Allows to represent attributes as dict, list, etc.""" 380 | for k in vars(self): 381 | yield k, self.__getattribute__(k) 382 | 383 | def __str__(self) -> str: 384 | """Allows to represent instances as a string.""" 385 | return str(dict(self)) 386 | 387 | 388 | # ############################################################################ 389 | # ####### Stand-alone run ######## 390 | # ################################ 391 | if __name__ == "__main__": 392 | pass 393 | -------------------------------------------------------------------------------- /qgispluginci/release.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import base64 4 | import logging 5 | import os 6 | import re 7 | import shutil 8 | import sys 9 | import tarfile 10 | import xmlrpc.client 11 | import zipfile 12 | from glob import glob 13 | from pathlib import Path 14 | from tempfile import mkstemp 15 | from typing import TYPE_CHECKING 16 | 17 | import git 18 | from github import Github, GithubException 19 | 20 | try: 21 | import importlib.resources as importlib_resources 22 | except ImportError: 23 | # In Py<3.7 fall-back to backported `importlib_resources`. 24 | import importlib_resources 25 | 26 | import datetime 27 | 28 | import pyqt5ac 29 | 30 | from qgispluginci.changelog import ChangelogParser 31 | from qgispluginci.exceptions import ( 32 | BuiltResourceInSources, 33 | GithubReleaseCouldNotUploadAsset, 34 | GithubReleaseNotFound, 35 | UncommitedChanges, 36 | ) 37 | from qgispluginci.parameters import Parameters 38 | from qgispluginci.translation import Translation 39 | from qgispluginci.utils import ( 40 | configure_file, 41 | convert_octets, 42 | parse_tag, 43 | replace_in_file, 44 | ) 45 | 46 | if TYPE_CHECKING: 47 | from github.Repository import Repository 48 | 49 | # GLOBALS 50 | logger = logging.getLogger(__name__) 51 | 52 | 53 | def create_archive( 54 | parameters: Parameters, 55 | release_version: str, 56 | archive_name: str, 57 | add_translations: bool = False, 58 | allow_uncommitted_changes: bool = False, 59 | is_prerelease: bool = False, 60 | raise_min_version: str = None, 61 | disable_submodule_update: bool = False, 62 | asset_paths: tuple[str] = (), 63 | ): 64 | repo = git.Repo() 65 | 66 | top_tar_handle, top_tar_file = mkstemp(suffix=".tar") 67 | 68 | # keep track of current state 69 | initial_stash = None 70 | diff = repo.index.diff(None) 71 | if diff: 72 | logger.info("There are uncommitted changes:") 73 | for diff in diff: 74 | logger.info(diff) 75 | if not allow_uncommitted_changes: 76 | err_msg = ( 77 | "You have uncommitted changes. " 78 | "Stash or commit them or use -c / --allow-uncommitted-changes option." 79 | ) 80 | logger.error(err_msg, exc_info=UncommitedChanges()) 81 | sys.exit(1) 82 | else: 83 | initial_stash = repo.git.stash("create") 84 | 85 | # changelog 86 | if parameters.changelog_include: 87 | parser = ChangelogParser( 88 | parent_folder=Path(parameters.plugin_path).resolve().parent, 89 | changelog_path=parameters.changelog_path, 90 | ) 91 | if parser.has_changelog(): 92 | try: 93 | content = parser.last_items( 94 | count=parameters.changelog_number_of_entries 95 | ) 96 | if content: 97 | replace_in_file( 98 | f"{parameters.plugin_path}/metadata.txt", 99 | r"^changelog=.*$", 100 | f"changelog={content}", 101 | ) 102 | except Exception as exc: 103 | # Do not fail the release process if something is wrong when parsing the changelog 104 | replace_in_file( 105 | f"{parameters.plugin_path}/metadata.txt", 106 | r"^changelog=.*$", 107 | "", 108 | ) 109 | logger.warning( 110 | f"An exception occurred while parsing the changelog file: {exc}", 111 | exc_info=exc, 112 | ) 113 | else: 114 | # Remove the changelog line 115 | replace_in_file(f"{parameters.plugin_path}/metadata.txt", r"^changelog=.*$", "") 116 | 117 | # set version in metadata 118 | replace_in_file( 119 | f"{parameters.plugin_path}/metadata.txt", 120 | r"^version=.*$", 121 | f"version={release_version}", 122 | ) 123 | 124 | # Commit number 125 | replace_in_file( 126 | f"{parameters.plugin_path}/metadata.txt", 127 | r"^commitNumber=.*$", 128 | f"commitNumber={len(list(repo.iter_commits()))}", 129 | ) 130 | 131 | # Git SHA1 132 | replace_in_file( 133 | f"{parameters.plugin_path}/metadata.txt", 134 | r"^commitSha1=.*$", 135 | f"commitSha1={repo.head.object.hexsha}", 136 | ) 137 | 138 | # Date/time in UTC 139 | date_time = datetime.datetime.now(datetime.timezone.utc).strftime( 140 | "%Y-%m-%dT%H:%M:%SZ" 141 | ) 142 | replace_in_file( 143 | f"{parameters.plugin_path}/metadata.txt", 144 | r"^dateTime=.*$", 145 | f"dateTime={date_time}", 146 | ) 147 | 148 | # set the plugin as experimental on a pre-release 149 | if is_prerelease: 150 | replace_in_file( 151 | f"{parameters.plugin_path}/metadata.txt", 152 | r"^experimental=.*$", 153 | f"experimental={True if is_prerelease else False}", 154 | ) 155 | 156 | if raise_min_version: 157 | replace_in_file( 158 | f"{parameters.plugin_path}/metadata.txt", 159 | r"^qgisMinimumVersion=.*$", 160 | f"qgisMinimumVersion={raise_min_version}", 161 | ) 162 | 163 | # replace any DEBUG=False in all Python files 164 | if not is_prerelease: 165 | for file in glob(f"{parameters.plugin_path}/**/*.py", recursive=True): 166 | replace_in_file(file, r"^DEBUG\s*=\s*True", "DEBUG = False") 167 | 168 | # keep track of current state 169 | try: 170 | stash = repo.git.stash("create") 171 | except git.exc.GitCommandError: 172 | stash = "HEAD" 173 | if stash == "" or stash is None: 174 | stash = "HEAD" 175 | # create TAR archive 176 | logger.debug(f"Git archive plugin with stash: {stash}") 177 | repo.git.archive(stash, "-o", top_tar_file, parameters.plugin_path) 178 | # adding submodules 179 | for submodule in repo.submodules: 180 | _, sub_tar_file = mkstemp(suffix=".tar") 181 | if submodule.path.split("/")[0] != parameters.plugin_path: 182 | logger.debug( 183 | f"Skipping submodule not in plugin source directory: {submodule.name}" 184 | ) 185 | continue 186 | if not disable_submodule_update: 187 | submodule.update(init=True) 188 | sub_repo = submodule.module() 189 | logger.info("Git archive submodule: {sub_repo}") 190 | sub_repo.git.archive( 191 | "HEAD", "--prefix", f"{submodule.path}/", "-o", sub_tar_file 192 | ) 193 | with tarfile.open(top_tar_file, mode="a") as tt: 194 | with tarfile.open(sub_tar_file, mode="r:") as st: 195 | for m in st.getmembers(): 196 | if not m.isfile(): 197 | continue 198 | tt.add(m.name) 199 | 200 | # add LICENSE if not already in plugin path but available in its parent 201 | parent_folder_license_copied = False 202 | if not Path(f"{parameters.plugin_path}/LICENSE").is_file(): 203 | parent_license = Path(f"{parameters.plugin_path}/../LICENSE") 204 | if parent_license.is_file(): 205 | shutil.copy(parent_license, f"{parameters.plugin_path}/LICENSE") 206 | parent_folder_license_copied = True 207 | with tarfile.open(top_tar_file, mode="a") as tt: 208 | tt.add(f"{parameters.plugin_path}/LICENSE") 209 | 210 | # add translation files 211 | if add_translations: 212 | with tarfile.open(top_tar_file, mode="a") as tt: 213 | logger.debug("Adding translations") 214 | for file in glob(f"{parameters.plugin_path}/i18n/*.qm"): 215 | logger.debug(f" adding translation: {os.path.basename(file)}") 216 | # https://stackoverflow.com/a/48462950/1548052 217 | tt.add(file) 218 | 219 | # compile qrc files 220 | if list(Path(parameters.plugin_path).glob("*.qrc")): 221 | pyqt5ac.main( 222 | ioPaths=[ 223 | [ 224 | f"{parameters.plugin_path}/*.qrc", 225 | f"{parameters.plugin_path}/%%FILENAME%%_rc.py", 226 | ] 227 | ] 228 | ) 229 | for file in glob(f"{parameters.plugin_path}/*_rc.py"): 230 | with tarfile.open(top_tar_file, mode="r:") as tt: 231 | for n in tt.getnames(): 232 | if n == file: 233 | err_msg = ( 234 | f"The file {file} is present in the sources and its name " 235 | "conflicts with a just built resource. " 236 | "You might want to remove it from the sources or " 237 | "setting export-ignore in .gitattributes config file." 238 | ) 239 | logger.error(err_msg, exc_info=BuiltResourceInSources()) 240 | sys.exit(1) 241 | with tarfile.open(top_tar_file, mode="a") as tt: 242 | logger.debug(f"\tAdding resource: {file}") 243 | # https://stackoverflow.com/a/48462950/1548052 244 | tt.add(file) 245 | # Add assets 246 | if asset_paths: 247 | with tarfile.open(top_tar_file, mode="a") as tt: 248 | for asset_path in asset_paths: 249 | tt.add(asset_path) 250 | 251 | # converting to ZIP 252 | # why using TAR before? because it provides the prefix and makes things easier 253 | with zipfile.ZipFile( 254 | file=archive_name, mode="w", compression=zipfile.ZIP_DEFLATED 255 | ) as zf: 256 | # adding the content of TAR archive 257 | with tarfile.open(top_tar_file, mode="r:") as tt: 258 | for m in tt.getmembers(): 259 | if m.isdir(): 260 | continue 261 | f = tt.extractfile(m) 262 | fl = f.read() 263 | fn = m.name 264 | # Get permissions and add it to ZipInfo 265 | st = os.stat(fn) 266 | 267 | # fix directory structure if plugin path is not top level 268 | # or if the plugin source directory is not distinctive (src, plugin, etc.) 269 | # e.g. plugin/some_dir/metadata.txt => my_plugin/metadata.txt 270 | fixed_path = fn.replace( 271 | parameters.plugin_path, parameters.plugin_zip_directory 272 | ) 273 | info = zipfile.ZipInfo(fixed_path) 274 | 275 | # Using flags as defined in python zipfile module 276 | # code : https://github.com/python/cpython/blob/b885b8f4be9c74ef1ce7923dbf055c31e7f47735/Lib/zipfile.py#L545 277 | # see https://stackoverflow.com/questions/434641/how-do-i-set-permissions-attributes-on-a-file-in-a-zip-file-using-pythons-zip/53008127#53008127 278 | info.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes 279 | info.compress_type = zf.compression 280 | zf.writestr(info, fl) 281 | 282 | if parent_folder_license_copied: 283 | Path(f"{parameters.plugin_path}/LICENSE").unlink() 284 | 285 | logger.debug("-" * 40) 286 | logger.debug(f"Files in ZIP archive ({archive_name}):") 287 | with zipfile.ZipFile(file=archive_name, mode="r") as zf: 288 | for f in zf.namelist(): 289 | logger.debug(f) 290 | logger.debug("-" * 40) 291 | 292 | # checkout to reset changes 293 | if initial_stash: 294 | repo.git.reset("--hard", initial_stash) 295 | repo.git.reset("HEAD^") 296 | else: 297 | repo.git.checkout("--", ".") 298 | 299 | # print the result 300 | print( # noqa: T2 301 | f"Plugin archive created: {archive_name} " 302 | f"({convert_octets(Path(archive_name).stat().st_size)})" 303 | ) 304 | 305 | 306 | def upload_asset_to_github_release( 307 | parameters: Parameters, 308 | asset_path: str, 309 | release_tag: str, 310 | github_token: str, 311 | asset_name: str = None, 312 | ): 313 | slug = f"{parameters.github_organization_slug}/{parameters.project_slug}" 314 | repo = Github(github_token).get_repo(slug) 315 | try: 316 | logger.debug( 317 | f"Getting release on {parameters.github_organization_slug}" 318 | f"/{parameters.project_slug}" 319 | ) 320 | gh_release = repo.get_release(id=release_tag) 321 | logger.debug( 322 | f"Release retrieved from GitHub: {gh_release}, " 323 | f"{gh_release.tag_name}, " 324 | f"{gh_release.upload_url}" 325 | ) 326 | except GithubException as exc: 327 | logger.error( 328 | f"Release {release_tag} not found for {slug}", 329 | exc_info=GithubReleaseNotFound(exc), 330 | ) 331 | sys.exit(1) 332 | try: 333 | assert os.path.exists(asset_path) 334 | if asset_name: 335 | logger.debug(f"Uploading asset: {asset_path} as {asset_name}") 336 | 337 | uploaded_asset = gh_release.upload_asset( 338 | path=asset_path, label=asset_name, name=asset_name 339 | ) 340 | else: 341 | logger.debug(f"Uploading asset: {asset_path}") 342 | uploaded_asset = gh_release.upload_asset(asset_path) 343 | logger.info(f"Asset successfully uploaded: {uploaded_asset.url}") 344 | except GithubException as exc: 345 | logger.error( 346 | f"Could not upload asset for release {release_tag} on {slug}. " 347 | "Are you sure the user for the given token can upload asset to this repo?", 348 | exc_info=GithubReleaseCouldNotUploadAsset(exc), 349 | ) 350 | sys.exit(1) 351 | 352 | 353 | def release_is_prerelease( 354 | parameters: Parameters, 355 | release_tag: str, 356 | github_token: str, 357 | ) -> bool: 358 | """Check the tag name or the GitHub release if the version must be experimental or not.""" 359 | 360 | if parse_tag(release_tag).is_prerelease: 361 | # The tag itself is a pre-release according to https://semver.org/ 362 | return True 363 | 364 | if not github_token: 365 | return False 366 | 367 | slug = f"{parameters.github_organization_slug}/{parameters.project_slug}" 368 | 369 | try: 370 | logger.debug(f"Getting GitHub repository: {slug}") 371 | gh_client: Github = Github(login_or_token=github_token) 372 | repo: Repository = gh_client.get_repo(slug) 373 | except GithubException as exc: 374 | logger.error( 375 | f"Could not get repository details: {slug}. " 376 | "Are you sure the user for the given token can access this repo?", 377 | exc_info=exc, 378 | ) 379 | sys.exit(1) 380 | try: 381 | logger.debug( 382 | f"Getting release on {parameters.github_organization_slug}" 383 | f"/{parameters.project_slug}" 384 | ) 385 | gh_release = repo.get_release(id=release_tag) 386 | logger.debug( 387 | f"Release retrieved from GitHub: {gh_release}, " 388 | f"{gh_release.tag_name}, " 389 | f"{gh_release.upload_url}" 390 | ) 391 | except GithubException as exc: 392 | logger.error( 393 | f"Release {release_tag} not found. Trace: {exc}", 394 | exc_info=GithubReleaseNotFound(), 395 | ) 396 | sys.exit(1) 397 | return gh_release.prerelease 398 | 399 | 400 | def create_plugin_repo( 401 | parameters: Parameters, 402 | release_version: str, 403 | release_tag: str, 404 | archive: str, 405 | osgeo_username: str, 406 | is_prerelease: bool = False, 407 | plugin_repo_url: str = None, 408 | ) -> str: 409 | """ 410 | Creates the plugin repo as an XML file 411 | """ 412 | replace_dict = { 413 | "__RELEASE_VERSION__": release_version, 414 | "__RELEASE_TAG__": release_tag or release_version, 415 | "__PLUGIN_NAME__": parameters.plugin_name, 416 | "__RELEASE_DATE__": datetime.date.today().strftime("%Y-%m-%d"), 417 | "__CREATE_DATE__": parameters.create_date.strftime("%Y-%m-%d"), 418 | "__ORG__": parameters.github_organization_slug, 419 | "__REPO__": parameters.project_slug, 420 | "__PLUGINZIP__": archive, 421 | "__OSGEO_USERNAME__": osgeo_username or parameters.author, 422 | "__DEPRECATED__": str(parameters.deprecated), 423 | "__EXPERIMENTAL__": str(is_prerelease or parameters.experimental), 424 | "__TAGS__": parameters.tags, 425 | "__ICON__": parameters.icon, 426 | "__AUTHOR__": parameters.author, 427 | "__QGIS_MIN_VERSION__": parameters.qgis_minimum_version, 428 | "__DESCRIPTION__": parameters.description, 429 | "__ISSUE_TRACKER__": parameters.issue_tracker, 430 | "__HOMEPAGE__": parameters.homepage, 431 | "__REPO_URL__": parameters.repository_url, 432 | } 433 | if not plugin_repo_url: 434 | orgs = replace_dict["__ORG__"] 435 | repo = replace_dict["__REPO__"] 436 | tag = replace_dict["__RELEASE_TAG__"] 437 | plugin_zip = replace_dict["__PLUGINZIP__"] 438 | download_url = ( 439 | f"https://github.com/{orgs}/{repo}/releases/download/{tag}/{plugin_zip}" 440 | ) 441 | _, xml_repo = mkstemp(suffix=".xml") 442 | else: 443 | download_url = f"{plugin_repo_url}{replace_dict['__PLUGINZIP__']}" 444 | xml_repo = "./plugins.xml" 445 | replace_dict["__DOWNLOAD_URL__"] = download_url 446 | with importlib_resources.path( 447 | "qgispluginci", "plugins.xml.template" 448 | ) as xml_template: 449 | configure_file(xml_template, xml_repo, replace_dict) 450 | return xml_repo 451 | 452 | 453 | def upload_plugin_to_osgeo( 454 | username: str, password: str, archive: str, server_url: str = None 455 | ): 456 | """ 457 | Upload the plugin to QGIS repository 458 | 459 | Parameters 460 | ---------- 461 | server_url 462 | The plugin server URL (defaults to plugins.qgis.org) 463 | username 464 | The username 465 | password 466 | The password 467 | archive 468 | The plugin archive file path to be uploaded 469 | """ 470 | if not server_url: 471 | server_url = "https://plugins.qgis.org:443/plugins/RPC2/" 472 | 473 | encoded_auth_string = base64.b64encode(f"{username}:{password}".encode()).decode( 474 | "utf-8" 475 | ) 476 | 477 | server = xmlrpc.client.ServerProxy( 478 | server_url, 479 | verbose=(logger.getEffectiveLevel() <= 10), 480 | headers=[("Authorization", f"Basic {encoded_auth_string}")], 481 | ) 482 | 483 | try: 484 | logger.debug(f"Start uploading {archive} to QGIS plugins repository.") 485 | with open(archive, "rb") as handle: 486 | plugin_id, version_id = server.plugin.upload( 487 | xmlrpc.client.Binary(handle.read()) 488 | ) 489 | logger.debug(f"Plugin ID: {plugin_id}") 490 | logger.debug(f"Version ID: {version_id}") 491 | except xmlrpc.client.ProtocolError as err: 492 | url = re.sub(r":[^/].*@", ":******@", err.url) 493 | err_msg = ( 494 | "=== A protocol error occurred ===\n" 495 | f"URL: {url}\n" 496 | f"HTTP/HTTPS headers: {err.headers}\n" 497 | f"Error code: {err.errcode}\n" 498 | f"Error message: {err.errmsg}\n" 499 | f"Plugin path: {archive}" 500 | ) 501 | logger.error(err_msg) 502 | sys.exit(2) 503 | except xmlrpc.client.Fault as err: 504 | err_msg = ( 505 | "=== A fault occurred occurred ===\n" 506 | f"Fault code: {err.faultCode}\n" 507 | f"Fault string: {err.faultString}\n" 508 | f"Plugin path: {archive}" 509 | ) 510 | logger.error(err_msg) 511 | sys.exit(2) 512 | 513 | 514 | def release( 515 | parameters: Parameters, 516 | release_version: str, 517 | release_tag: str = None, 518 | github_token: str = None, 519 | upload_plugin_repo_github: bool = False, 520 | tx_api_token: str = None, 521 | alternative_repo_url: str = None, 522 | osgeo_username: str = None, 523 | osgeo_password: str = None, 524 | allow_uncommitted_changes: bool = False, 525 | plugin_repo_url: str = None, 526 | disable_submodule_update: bool = False, 527 | asset_paths: list[str] = [], 528 | ): 529 | """ 530 | 531 | Parameters 532 | ---------- 533 | parameters 534 | The configuration parameters 535 | release_version: 536 | The release version (x.y.z) 537 | release_tag: 538 | The release tag (vx.y.z). 539 | If not given, the release version will be used 540 | github_token 541 | The Github token 542 | upload_plugin_repo_github 543 | If true, a custom repo will be created as a release asset on Github and could later be used in QGIS as a custom plugin repository. 544 | plugin_repo_url 545 | If set, this URL will be used to create the ZIP URL in the XML file 546 | tx_api_token 547 | The Transifex token 548 | alternative_repo_url 549 | URL of the endpoint to upload the plugin to 550 | osgeo_username 551 | osgeo username to upload the plugin to official QGIS repository 552 | osgeo_password 553 | osgeo password to upload the plugin to official QGIS repository 554 | allow_uncommitted_changes 555 | If False, uncommitted changes are not allowed before packaging/releasing. 556 | If True and some changes are detected, a hard reset on a stash create will be used to revert changes made by qgis-plugin-ci. 557 | disable_submodule_update 558 | If omitted, a git submodule is updated. If specified, git submodules will not be updated/initialized before packaging. 559 | """ 560 | 561 | if release_version == "latest": 562 | parser = ChangelogParser( 563 | parent_folder=Path(parameters.plugin_path).resolve().parent, 564 | changelog_path=parameters.changelog_path, 565 | ) 566 | if parser.has_changelog(): 567 | release_version = parser.latest_version() 568 | else: 569 | release_version = "latest" 570 | 571 | release_tag = release_tag or release_version 572 | 573 | if tx_api_token: 574 | tr = Translation(parameters, create_project=False, tx_api_token=tx_api_token) 575 | tr.pull() 576 | tr.compile_strings() 577 | 578 | archive_name = parameters.archive_name(parameters.plugin_path, release_version) 579 | 580 | # check if the GitHub release is a regular or pre-release 581 | is_prerelease = release_is_prerelease( 582 | parameters, release_tag=release_tag, github_token=github_token 583 | ) 584 | 585 | if is_prerelease: 586 | logger.info(f"{release_tag} is a pre-release.") 587 | else: 588 | logger.info(f"{release_tag} is a regular release.") 589 | 590 | create_archive( 591 | parameters, 592 | release_version, 593 | archive_name, 594 | add_translations=bool(tx_api_token), 595 | allow_uncommitted_changes=allow_uncommitted_changes, 596 | is_prerelease=is_prerelease, 597 | disable_submodule_update=disable_submodule_update, 598 | asset_paths=asset_paths, 599 | ) 600 | 601 | if github_token is not None: 602 | upload_asset_to_github_release( 603 | parameters, 604 | asset_path=archive_name, 605 | release_tag=release_tag, 606 | github_token=github_token, 607 | ) 608 | if upload_plugin_repo_github: 609 | xml_repo = create_plugin_repo( 610 | parameters=parameters, 611 | release_version=release_version, 612 | release_tag=release_tag, 613 | is_prerelease=is_prerelease, 614 | archive=archive_name, 615 | osgeo_username=osgeo_username, 616 | ) 617 | upload_asset_to_github_release( 618 | parameters, 619 | asset_path=xml_repo, 620 | release_tag=release_tag, 621 | github_token=github_token, 622 | asset_name="plugins.xml", 623 | ) 624 | 625 | if plugin_repo_url: 626 | xml_repo = create_plugin_repo( 627 | parameters=parameters, 628 | release_version=release_version, 629 | release_tag=release_tag, 630 | archive=archive_name, 631 | is_prerelease=is_prerelease, 632 | osgeo_username=osgeo_username, 633 | plugin_repo_url=plugin_repo_url, 634 | ) 635 | logger.info(f"Local XML repo file created : {xml_repo}") 636 | 637 | if osgeo_username is not None: 638 | assert osgeo_password is not None 639 | upload_plugin_to_osgeo( 640 | username=osgeo_username, 641 | password=osgeo_password, 642 | archive=archive_name, 643 | server_url=alternative_repo_url, 644 | ) 645 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------