From c7204ed80e7b82eb3e1c4899478965c7816883ed Mon Sep 17 00:00:00 2001 From: Ben Morse <96morse@gmail.com> Date: Sat, 16 Dec 2023 15:34:39 +0000 Subject: [PATCH] init --- .coveragerc | 24 +++ .editorconfig | 24 +++ .../scripts/report_nightly_build_failure.py | 26 +++ .github/workflows/nightly.yml | 35 +++ .github/workflows/publish.yml | 51 +++++ .github/workflows/test.yml | 83 +++++++ .gitignore | 16 ++ .pre-commit-config.yaml | 44 ++++ CHANGELOG.md | 42 ++++ CONTRIBUTING.md | 1 + LICENSE | 202 ++++++++++++++++++ README.md | 81 +++++++ SECURITY.md | 5 + pyproject.toml | 63 ++++++ setup.cfg | 14 ++ testmanage.py | 66 ++++++ tox.ini | 62 ++++++ wagtail_defender/__init__.py | 5 + wagtail_defender/apps.py | 7 + wagtail_defender/migrations/__init__.py | 0 wagtail_defender/models.py | 0 wagtail_defender/test/__init__.py | 1 + wagtail_defender/test/apps.py | 7 + wagtail_defender/test/settings.py | 161 ++++++++++++++ wagtail_defender/test/tests/__init__.py | 0 wagtail_defender/test/urls.py | 13 ++ wagtail_defender/wagtail_hooks.py | 26 +++ 27 files changed, 1059 insertions(+) create mode 100644 .coveragerc create mode 100644 .editorconfig create mode 100644 .github/scripts/report_nightly_build_failure.py create mode 100644 .github/workflows/nightly.yml create mode 100644 .github/workflows/publish.yml create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 pyproject.toml create mode 100644 setup.cfg create mode 100644 testmanage.py create mode 100644 tox.ini create mode 100644 wagtail_defender/__init__.py create mode 100644 wagtail_defender/apps.py create mode 100644 wagtail_defender/migrations/__init__.py create mode 100644 wagtail_defender/models.py create mode 100644 wagtail_defender/test/__init__.py create mode 100644 wagtail_defender/test/apps.py create mode 100644 wagtail_defender/test/settings.py create mode 100644 wagtail_defender/test/tests/__init__.py create mode 100644 wagtail_defender/test/urls.py create mode 100644 wagtail_defender/wagtail_hooks.py diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..acf83d7 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,24 @@ +[run] +branch = True +include = wagtail_defender/* +omit = */migrations/*,*/tests/* + +[report] +# Regexes for lines to exclude from consideration +exclude_lines = + # Have to re-enable the standard pragma + pragma: no cover + + # Don't complain about missing debug-only code: + def __repr__ + if self\.debug + + # Don't complain if tests don't hit defensive assertion code: + raise AssertionError + raise NotImplementedError + + # Don't complain if non-runnable code isn't run: + if 0: + if __name__ == .__main__.: + +ignore_errors = True diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..5b2c9b9 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,24 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf + +[Makefile] +indent_style = tab + +[*.py] +max_line_length = 88 + +[*.{html,rst,md}] +indent_size = 4 + +[*.{js,ts,tsx,json,yml,yaml,css,scss}] +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/.github/scripts/report_nightly_build_failure.py b/.github/scripts/report_nightly_build_failure.py new file mode 100644 index 0000000..f2e0e7e --- /dev/null +++ b/.github/scripts/report_nightly_build_failure.py @@ -0,0 +1,26 @@ +""" +Called by GH Actions when the nightly build fails. + +This reports an error to the #nightly-build-failures Slack channel. +""" +import os + +import requests + + +if "SLACK_WEBHOOK_URL" in os.environ: + print("Reporting to #nightly-build-failures slack channel") + response = requests.post( + os.environ["SLACK_WEBHOOK_URL"], + json={ + "text": "A Nightly build failed. See https://github.com/Morsey187/wagtail-defender/actions/runs/" + + os.environ["GITHUB_RUN_ID"], + }, + ) + + print("Slack responded with:", response) + +else: + print( + "Unable to report to #nightly-build-failures slack channel because SLACK_WEBHOOK_URL is not set" + ) diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000..c41a845 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,35 @@ +name: Nightly Wagtail Test + +on: + schedule: + - cron: '0 1 * * *' + # At 01:00, daily + workflow_dispatch: + +jobs: + nightly-wagtail-test: + runs-on: ubuntu-latest + env: + WEBHOOK_EXISTS: ${{ secrets.SLACK_WEBHOOK_URL != '' }} + + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: '3.11' + + - run: git clone https://github.com/wagtail/wagtail.git + + - run: python -m pip install flit + - run: flit install --deps production --extras testing + - run: python -m pip install ./wagtail + + - run: python testmanage.py test + + - name: Report failure + run: | + python -m pip install requests + python ./.github/scripts/report_nightly_build_failure.py + if: ${{ failure() && env.WEBHOOK_EXISTS == 'true' }} + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..422d322 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,51 @@ +# See https://packaging.python.org/en/latest/guides/publishing-package-distribution-releases-using-github-actions-ci-cd-workflows/ +# for a detailed guide +name: Publish to PyPI + +on: + release: + types: [published] + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read # to fetch code (actions/checkout) + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up Python 3.11 + uses: actions/setup-python@v4 + with: + python-version: '3.11' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install flit + python -m flit install --symlink + + - name: Build + run: python -m flit build + + - uses: actions/upload-artifact@v3 + with: + path: ./dist + + publish: + needs: build + runs-on: ubuntu-latest + permissions: + contents: none + id-token: write # required for trusted publishing + environment: publish + steps: + - uses: actions/download-artifact@v3 + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: artifact/ + print-hash: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..48facc6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,83 @@ +name: defender CI + +on: + push: + branches: + - main + - 'stable/**' + + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read # to fetch code (actions/checkout) + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + - name: Set up Python 3.8 + uses: actions/setup-python@v4 + with: + python-version: '3.8' + - uses: pre-commit/action@v3.0.0 + + test-sqlite: + runs-on: ubuntu-latest + needs: lint + strategy: + matrix: + python: ['3.8', '3.9', '3.10', '3.11', '3.12'] + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + - name: Install + run: | + python -m pip install --upgrade pip setuptools wheel + python -m pip install .[ci] + - name: Test + run: tox + env: + DB: sqlite + + test-postgres: + runs-on: ubuntu-latest + needs: lint + strategy: + matrix: + python: ['3.8', '3.9', '3.10', '3.11', '3.12'] + + services: + postgres: + image: ${{ matrix.postgres || 'postgres:11' }} + env: + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 + + steps: + - uses: actions/checkout@v3 + - name: Set up Python ${{ matrix.python }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python }} + - name: Install + run: | + python -m pip install --upgrade pip setuptools wheel + python -m pip install .[ci] + - name: Test + run: tox + env: + DATABASE_URL: postgres://postgres:postgres@localhost:5432/wagtail_defender + DB: postgres diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90c8bc1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +__pycache__/ +*.py[co] +/build +/dist +/wagtail_defender.egg-info +/.coverage +/htmlcov +/.tox +/.venv +/venv +/.vscode +/site +/test_wagtail_defender.db +/node_modules +/test-static +/test-media diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..a9d4c77 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,44 @@ +ci: + autofix_prs: false + +default_language_version: + python: python3 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-added-large-files + - id: check-case-conflict + - id: check-json + - id: check-merge-conflict + - id: check-symlinks + - id: check-toml + - id: check-yaml + args: ['--unsafe'] + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/psf/black + rev: 23.9.1 + hooks: + - id: black + language_version: python3 + args: ['--target-version', 'py38'] + - repo: https://github.com/adamchainz/blacken-docs + rev: 1.16.0 + hooks: + - id: blacken-docs + additional_dependencies: [black==23.9.1] + - repo: https://github.com/pycqa/isort + # isort config is in setup.cfg + rev: 5.12.0 + hooks: + - id: isort + - repo: https://github.com/pycqa/flake8 + # flake8 config is in setup.cfg + rev: 6.1.0 + hooks: + - id: flake8 + additional_dependencies: + - flake8-bugbear + - flake8-comprehensions diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5366f82 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,42 @@ +# defender Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.1.0] - 2023-12-16 + +### Added + +- ... + +### Changed + +- ... + +### Removed + +- ... + + + diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..63f8952 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +# Contributing to defender diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..eab94ce --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2023, Ben Morse + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b7f248e --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# Wagtail defender + +django-defender configured for Wagtail + +[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![PyPI version](https://badge.fury.io/py/wagtail-defender.svg)](https://badge.fury.io/py/wagtail-defender) +[![defender CI](https://github.com/Morsey187/wagtail-defender/actions/workflows/test.yml/badge.svg)](https://github.com/Morsey187/wagtail-defender/actions/workflows/test.yml) + +## Links + +- [Documentation](https://github.com/Morsey187/wagtail-defender/blob/main/README.md) +- [Changelog](https://github.com/Morsey187/wagtail-defender/blob/main/CHANGELOG.md) +- [Contributing](https://github.com/Morsey187/wagtail-defender/blob/main/CONTRIBUTING.md) +- [Discussions](https://github.com/Morsey187/wagtail-defender/discussions) +- [Security](https://github.com/Morsey187/wagtail-defender/security) + +## Supported versions + +- Python ... +- Django ... +- Wagtail ... + +## Installation + +- `python -m pip install wagtail-defender` +- ... + +## Contributing + +### Install + +To make changes to this project, first clone this repository: + +```sh +git clone https://github.com/Morsey187/wagtail-defender.git +cd wagtail-defender +``` + +With your preferred virtualenv activated, install testing dependencies: + +#### Using pip + +```sh +python -m pip install --upgrade pip>=21.3 +python -m pip install -e '.[testing]' -U +``` + +#### Using flit + +```sh +python -m pip install flit +flit install +``` + +### pre-commit + +Note that this project uses [pre-commit](https://github.com/pre-commit/pre-commit). +It is included in the project testing requirements. To set up locally: + +```shell +# go to the project directory +$ cd wagtail-defender +# initialize pre-commit +$ pre-commit install + +# Optional, run all checks once for this, then the checks will run only on the changed files +$ git ls-files --others --cached --exclude-standard | xargs pre-commit run --files +``` + +### How to run tests + +Now you can run tests as shown below: + +```sh +tox +``` + +or, you can run them for a specific environment `tox -e python3.11-django4.2-wagtail5.1` or specific test +`tox -e python3.11-django4.2-wagtail5.1-sqlite wagtail-defender.tests.test_file.TestClass.test_method` + +To run the test app interactively, use `tox -e interactive`, visit `http://127.0.0.1:8020/admin/` and log in with `admin`/`changeme`. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..c696f97 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security + +We take the security of Wagtail, and related packages we maintain, seriously. If you have found a security issue with any of our projects please email us at security@wagtail.org so we can work together to find and patch the issue. We appreciate responsible disclosure with any security related issues, so please contact us first before creating a Github issue. + +If you want to send an encrypted email (optional), the public key ID for security@wagtail.org is 0xbed227b4daf93ff9, and this public key is available from most commonly-used keyservers. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..1141074 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,63 @@ +[build-system] +requires = ["flit_core >=3.2,<4"] +build-backend = "flit_core.buildapi" + +[project] +name = "wagtail-defender" +authors = [{name = "Ben Morse", email = "96morse@gmail.com"}] +description = "django-defender configured for Wagtail" +readme = "README.md" +license = {file = "LICENSE"} +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Framework :: Django", + "Framework :: Django :: 3.2", + "Framework :: Django :: 4.2", + "Framework :: Wagtail", + "Framework :: Wagtail :: 4", + "Framework :: Wagtail :: 5", +] +requires-python = ">=3.8" +dynamic = ["version"] +dependencies = [ + "Django>=3.2", + "Wagtail>=4.1" +] +[project.optional-dependencies] +testing = [ + "dj-database-url==2.1.0", + "pre-commit==3.4.0" +] +ci = [ + "tox==4.11.3", + "tox-gh-actions==3.1.3" +] + +[project.urls] +Home = "https://github.com/Morsey187/wagtail-defender" + +[tool.flit.module] +name = "wagtail_defender" + +[tool.flit.sdist] +exclude = [ + "wagtail_defender/static_src", + "wagtail_defender/test", + "wagtail_defender/static/wagtail_defender/js/.gitignore", + "testmanage.py", + ".*", + "*.js", + "*.json", + "*.ini", + "*.yml" +] diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..b18b701 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,14 @@ +[flake8] +max-line-length=88 +exclude=migrations,dist,build,venv,node_modules,.tox,venv,.venv,.git +# E501: Line too long +# W503: line break before binary operator (superseded by W504 line break after binary operator) +ignore = E501,W503 + +[isort] +known_first_party=wagtail_defender +skip=migrations,.git,__pycache__,LC_MESSAGES,locale,build,dist,.github,.tox,venv,.venv,node_modules +blocked_extensions=rst,html,js,svg,txt,css,scss,png,snap,tsx,ts,sh +lines_between_types=1 +lines_after_imports=2 +profile=black diff --git a/testmanage.py b/testmanage.py new file mode 100644 index 0000000..a3f59b5 --- /dev/null +++ b/testmanage.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +import argparse +import os +import shutil +import sys +import warnings + +from django.core.management import execute_from_command_line + + +os.environ["DJANGO_SETTINGS_MODULE"] = "wagtail_defender.test.settings" + + +def make_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--deprecation", + choices=["all", "pending", "imminent", "none"], + default="imminent", + ) + return parser + + +def parse_args(args=None): + return make_parser().parse_known_args(args) + + +def runtests(): + args, rest = parse_args() + + only_wagtail = r"^wagtail(\.|$)" + if args.deprecation == "all": + # Show all deprecation warnings from all packages + warnings.simplefilter("default", DeprecationWarning) + warnings.simplefilter("default", PendingDeprecationWarning) + elif args.deprecation == "pending": + # Show all deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + warnings.filterwarnings( + "default", category=PendingDeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "imminent": + # Show only imminent deprecation warnings from wagtail + warnings.filterwarnings( + "default", category=DeprecationWarning, module=only_wagtail + ) + elif args.deprecation == "none": + # Deprecation warnings are ignored by default + pass + + argv = [sys.argv[0]] + rest + + try: + execute_from_command_line(argv) + finally: + from wagtail.test.settings import MEDIA_ROOT, STATIC_ROOT + + shutil.rmtree(STATIC_ROOT, ignore_errors=True) + shutil.rmtree(MEDIA_ROOT, ignore_errors=True) + + +if __name__ == "__main__": + runtests() diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..89c10db --- /dev/null +++ b/tox.ini @@ -0,0 +1,62 @@ +[tox] +skipsdist = True +usedevelop = True + +envlist = + python{3.8,3.9,3.10,3.11}-django{3.2}-wagtail{4.1}-{sqlite,postgres} + python{3.8,3.9,3.10,3.11}-django{3.2,4.2}-wagtail{5.1,5.2}-{sqlite,postgres} + python{3.12}-django{4.2}-wagtail{5.2}-{sqlite,postgres} + +[gh-actions] +python = + 3.8: python3.8 + 3.9: python3.9 + 3.10: python3.10 + 3.11: python3.11 + 3.12: python3.12 + +[gh-actions:env] +DB = + sqlite: sqlite + postgres: postgres + +[testenv] +install_command = pip install -e ".[testing]" -U {opts} {packages} +commands = coverage run testmanage.py test --deprecation all {posargs: -v 2} + +basepython = + python3.8: python3.8 + python3.9: python3.9 + python3.10: python3.10 + python3.11: python3.11 + python3.12: python3.12 + +deps = + coverage + + django3.2: Django>=3.2,<4.0 + django4.2: Django>=4.2,<4.3 + + wagtail4.1: wagtail>=4.1,<4.2 + wagtail5.1: wagtail>=5.1,<5.2 + wagtail5.2: wagtail>=5.2,<5.3 + + postgres: psycopg2>=2.6 + +setenv = + postgres: DATABASE_URL={env:DATABASE_URL:postgres:///wagtail_defender} + +[testenv:interactive] +basepython = python3.10 + +commands_pre = + python {toxinidir}/testmanage.py makemigrations + python {toxinidir}/testmanage.py migrate + python {toxinidir}/testmanage.py shell -c "from django.contrib.auth.models import User;(not User.objects.filter(username='admin').exists()) and User.objects.create_superuser('admin', 'super@example.com', 'changeme')" + python {toxinidir}/testmanage.py createcachetable + +commands = + {posargs:python testmanage.py runserver 0.0.0.0:8020} + +setenv = + INTERACTIVE = 1 diff --git a/wagtail_defender/__init__.py b/wagtail_defender/__init__.py new file mode 100644 index 0000000..c6361e5 --- /dev/null +++ b/wagtail_defender/__init__.py @@ -0,0 +1,5 @@ +default_app_config = "wagtail_defender.apps.WagtailDefenderAppConfig" + + +VERSION = (0, 1, 0) +__version__ = ".".join(map(str, VERSION)) diff --git a/wagtail_defender/apps.py b/wagtail_defender/apps.py new file mode 100644 index 0000000..228cc9b --- /dev/null +++ b/wagtail_defender/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class WagtailDefenderAppConfig(AppConfig): + label = "wagtail_defender" + name = "wagtail_defender" + verbose_name = "Wagtail defender" diff --git a/wagtail_defender/migrations/__init__.py b/wagtail_defender/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/wagtail_defender/models.py b/wagtail_defender/models.py new file mode 100644 index 0000000..e69de29 diff --git a/wagtail_defender/test/__init__.py b/wagtail_defender/test/__init__.py new file mode 100644 index 0000000..f6064bd --- /dev/null +++ b/wagtail_defender/test/__init__.py @@ -0,0 +1 @@ +default_app_config = "wagtail_defender.test.apps.WagtailDefenderTestAppConfig" diff --git a/wagtail_defender/test/apps.py b/wagtail_defender/test/apps.py new file mode 100644 index 0000000..64a0640 --- /dev/null +++ b/wagtail_defender/test/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig + + +class WagtailDefenderTestAppConfig(AppConfig): + label = "wagtail_defender_test" + name = "wagtail_defender.test" + verbose_name = "Wagtail defender tests" diff --git a/wagtail_defender/test/settings.py b/wagtail_defender/test/settings.py new file mode 100644 index 0000000..d99d92a --- /dev/null +++ b/wagtail_defender/test/settings.py @@ -0,0 +1,161 @@ +""" +Django settings for temp project. + +For more information on this file, see +https://docs.djangoproject.com/en/stable/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/stable/ref/settings/ +""" + +import os + +import dj_database_url + + +# Build paths inside the project like this: os.path.join(PROJECT_DIR, ...) +PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BASE_DIR = os.path.dirname(PROJECT_DIR) + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/stable/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "c6u0-9c!7nilj_ysatsda0(f@e_2mws2f!6m0n^o*4#*q#kzp)" + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["localhost", "testserver"] + + +# Application definition + +INSTALLED_APPS = [ + "wagtail_defender", + "wagtail_defender.test", + "wagtail.contrib.search_promotions", + "wagtail.contrib.forms", + "wagtail.contrib.redirects", + "wagtail.embeds", + "wagtail.users", + "wagtail.snippets", + "wagtail.documents", + "wagtail.images", + "wagtail.search", + "wagtail.admin", + "wagtail.api.v2", + "wagtail.contrib.routable_page", + "wagtail.contrib.styleguide", + "wagtail.sites", + "wagtail", + "taggit", + "rest_framework", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "django.contrib.sitemaps", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", + "wagtail.contrib.redirects.middleware.RedirectMiddleware", +] + +ROOT_URLCONF = "wagtail_defender.test.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ] + }, + } +] + + +# Using DatabaseCache to make sure that the cache is cleared between tests. +# This prevents false-positives in some wagtail core tests where we are +# changing the 'wagtail_root_paths' key which may cause future tests to fail. +CACHES = { + "default": { + "BACKEND": "django.core.cache.backends.db.DatabaseCache", + "LOCATION": "cache", + } +} + + +# don't use the intentionally slow default password hasher +PASSWORD_HASHERS = ("django.contrib.auth.hashers.MD5PasswordHasher",) + + +# Database +# https://docs.djangoproject.com/en/stable/ref/settings/#databases + +DATABASES = { + "default": dj_database_url.config(default="sqlite:///test_wagtail_defender.db"), +} + + +# Password validation +# https://docs.djangoproject.com/en/stable/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + }, + {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, + {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, + {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, +] + + +# Internationalization +# https://docs.djangoproject.com/en/stable/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "UTC" + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/stable/howto/static-files/ + +STATICFILES_FINDERS = [ + "django.contrib.staticfiles.finders.FileSystemFinder", + "django.contrib.staticfiles.finders.AppDirectoriesFinder", +] + +STATICFILES_DIRS = [os.path.join(PROJECT_DIR, "static")] + +STATIC_ROOT = os.path.join(BASE_DIR, "test-static") +STATIC_URL = "/static/" + +MEDIA_ROOT = os.path.join(BASE_DIR, "test-media") + + +# Wagtail settings + +WAGTAIL_SITE_NAME = "Wagtail defender test site" diff --git a/wagtail_defender/test/tests/__init__.py b/wagtail_defender/test/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/wagtail_defender/test/urls.py b/wagtail_defender/test/urls.py new file mode 100644 index 0000000..5348aaf --- /dev/null +++ b/wagtail_defender/test/urls.py @@ -0,0 +1,13 @@ +from django.contrib import admin +from django.urls import include, path +from wagtail import urls as wagtail_urls +from wagtail.admin import urls as wagtailadmin_urls +from wagtail.documents import urls as wagtaildocs_urls + + +urlpatterns = [ + path("django-admin/", admin.site.urls), + path("admin/", include(wagtailadmin_urls)), + path("documents/", include(wagtaildocs_urls)), + path("", include(wagtail_urls)), +] diff --git a/wagtail_defender/wagtail_hooks.py b/wagtail_defender/wagtail_hooks.py new file mode 100644 index 0000000..cedf4b2 --- /dev/null +++ b/wagtail_defender/wagtail_hooks.py @@ -0,0 +1,26 @@ +from django.urls import include, path +from django.views.i18n import JavaScriptCatalog +from wagtail import hooks + + +@hooks.register("register_admin_urls") +def register_admin_urls(): + urls = [ + path( + "jsi18n/", + JavaScriptCatalog.as_view(packages=["wagtail_defender"]), + name="javascript_catalog", + ), + # Add your other URLs here, and they will appear under `/admin/defender/` + # Note: you do not need to check for authentication in views added here, Wagtail does this for you! + ] + + return [ + path( + "defender/", + include( + (urls, "wagtail_defender"), + namespace="wagtail_defender", + ), + ) + ]