From 644aaa0c1e4ff266022fed27ad82e3da1f1d7955 Mon Sep 17 00:00:00 2001 From: snelzing <39928924+snelzing@users.noreply.github.com> Date: Mon, 18 Dec 2023 19:17:20 -0500 Subject: [PATCH] "Initial commit of extension framework" --- .coveragerc | 42 ++ .github/workflows/test.yml | 417 +++++++++++++++ .gitignore | 135 +++++ .pre-commit-config.yaml | 281 ++++++++++ .pre-commit-hooks/check-cli-examples.py | 64 +++ .pre-commit-hooks/make-autodocs.py | 59 ++ .pylintrc | 681 ++++++++++++++++++++++++ LICENSE | 201 +++++++ README.md | 33 ++ docs/Makefile | 20 + docs/_static/.gitkeep | 0 docs/all.rst | 16 + docs/conf.py | 162 ++++++ docs/index.rst | 15 + docs/make.bat | 35 ++ docs/ref/.gitkeep | 0 docs/sitevars.rst | 0 noxfile.py | 527 ++++++++++++++++++ pyproject.toml | 10 + requirements/base.txt | 1 + requirements/changelog.txt | 0 requirements/dev.txt | 0 requirements/docs-auto.txt | 0 requirements/docs.in | 5 + requirements/docs.txt | 0 requirements/lint.in | 2 + requirements/lint.txt | 0 requirements/py3.5/docs.txt | 0 requirements/py3.5/lint.txt | 0 requirements/py3.5/tests.txt | 0 requirements/py3.6/docs.txt | 89 ++++ requirements/py3.6/lint.txt | 41 ++ requirements/py3.6/tests.txt | 67 +++ requirements/py3.7/docs.txt | 87 +++ requirements/py3.7/lint.txt | 41 ++ requirements/py3.7/tests.txt | 63 +++ requirements/py3.8/docs.txt | 84 +++ requirements/py3.8/lint.txt | 34 ++ requirements/py3.8/tests.txt | 51 ++ requirements/py3.9/docs.txt | 87 +++ requirements/py3.9/lint.txt | 34 ++ requirements/py3.9/tests.txt | 51 ++ requirements/tests.in | 2 + requirements/tests.txt | 0 setup.cfg | 79 +++ setup.py | 5 + src/saltext/consul/__init__.py | 28 + src/saltext/consul/loader.py | 5 + tests/__init__.py | 0 tests/conftest.py | 39 ++ tests/integration/__init__.py | 0 tests/integration/conftest.py | 28 + tests/unit/__init__.py | 0 53 files changed, 3621 insertions(+) create mode 100644 .coveragerc create mode 100644 .github/workflows/test.yml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .pre-commit-hooks/check-cli-examples.py create mode 100644 .pre-commit-hooks/make-autodocs.py create mode 100644 .pylintrc create mode 100644 LICENSE create mode 100644 README.md create mode 100644 docs/Makefile create mode 100644 docs/_static/.gitkeep create mode 100644 docs/all.rst create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat create mode 100644 docs/ref/.gitkeep create mode 100644 docs/sitevars.rst create mode 100644 noxfile.py create mode 100644 pyproject.toml create mode 100644 requirements/base.txt create mode 100644 requirements/changelog.txt create mode 100644 requirements/dev.txt create mode 100644 requirements/docs-auto.txt create mode 100644 requirements/docs.in create mode 100644 requirements/docs.txt create mode 100644 requirements/lint.in create mode 100644 requirements/lint.txt create mode 100644 requirements/py3.5/docs.txt create mode 100644 requirements/py3.5/lint.txt create mode 100644 requirements/py3.5/tests.txt create mode 100644 requirements/py3.6/docs.txt create mode 100644 requirements/py3.6/lint.txt create mode 100644 requirements/py3.6/tests.txt create mode 100644 requirements/py3.7/docs.txt create mode 100644 requirements/py3.7/lint.txt create mode 100644 requirements/py3.7/tests.txt create mode 100644 requirements/py3.8/docs.txt create mode 100644 requirements/py3.8/lint.txt create mode 100644 requirements/py3.8/tests.txt create mode 100644 requirements/py3.9/docs.txt create mode 100644 requirements/py3.9/lint.txt create mode 100644 requirements/py3.9/tests.txt create mode 100644 requirements/tests.in create mode 100644 requirements/tests.txt create mode 100644 setup.cfg create mode 100644 setup.py create mode 100644 src/saltext/consul/__init__.py create mode 100644 src/saltext/consul/loader.py create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/integration/__init__.py create mode 100644 tests/integration/conftest.py create mode 100644 tests/unit/__init__.py diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..811f136 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,42 @@ +[run] +branch = True +cover_pylib = False +relative_files = True +parallel = True +concurrency = multiprocessing + +omit = + .nox/* + setup.py + +[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__ + + # 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 False: + if __name__ == .__main__.: + +omit = + .nox/* + setup.py + + +ignore_errors = True + +[paths] +source = + saltext/consul + src/saltext/consul +testsuite = + tests/ diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..6e535cb --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,417 @@ + +name: Testing + +on: [push, pull_request] + +jobs: + Pre-Commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v1 + with: + python-version: 3.7 + - name: Set Cache Key + run: echo "PY=$(python --version --version | sha256sum | cut -d' ' -f1)" >> $GITHUB_ENV + - name: Install System Deps + run: | + sudo apt-get update + sudo apt-get install -y libxml2 libxml2-dev libxslt-dev + - uses: actions/cache@v1 + with: + path: ~/.cache/pre-commit + key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }} + - uses: pre-commit/action@v1.0.1 + + Docs: + runs-on: ubuntu-latest + needs: Pre-Commit + + timeout-minutes: 10 + + steps: + - uses: actions/checkout@v2 + + - name: Set up Python 3.7 For Nox + uses: actions/setup-python@v1 + with: + python-version: 3.7 + + - name: Install Nox + run: | + python -m pip install --upgrade pip + pip install nox + + - name: Install Doc Requirements + run: | + nox --force-color -e docs --install-only + + - name: Build Docs + env: + SKIP_REQUIREMENTS_INSTALL: YES + run: | + nox --force-color -e docs + + Linux: + runs-on: ubuntu-latest + needs: Pre-Commit + + timeout-minutes: 15 + + strategy: + fail-fast: false + max-parallel: 4 + matrix: + python-version: + - 3.6 + - 3.7 + - 3.8 + salt-version: + - 3003 + + steps: + - uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Nox + run: | + python -m pip install --upgrade pip + pip install nox + + - name: Install Test Requirements + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + run: | + nox --force-color -e tests-3 --install-only + + - name: Test + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + SKIP_REQUIREMENTS_INSTALL: YES + run: | + nox --force-color -e tests-3 -- -vv tests/ + + - name: Create CodeCov Flags + if: always() + id: codecov-flags + run: | + echo ::set-output name=flags::$(python -c "import sys; print('{},{},salt_{}'.format('${{ runner.os }}'.replace('-latest', ''), 'py{}{}'.format(*sys.version_info), '_'.join(str(v) for v in '${{ matrix.salt-version }}'.replace('==', '_').split('.'))))") + + - name: Upload Project Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},project + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-project + REPORT_PATH: artifacts/coverage-project.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Tests Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},tests + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-tests + REPORT_PATH: artifacts/coverage-tests.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Logs + if: always() + uses: actions/upload-artifact@main + with: + name: runtests-${{ runner.os }}-py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}.log + path: artifacts/runtests-*.log + + Windows: + runs-on: windows-latest + needs: Pre-Commit + + timeout-minutes: 40 + + strategy: + fail-fast: false + max-parallel: 3 + matrix: + python-version: + - 3.6 + - 3.7 + salt-version: + - 3003 + + steps: + - uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Nox + run: | + python -m pip install --upgrade pip + pip install nox + + - name: Install Test Requirements + shell: bash + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + EXTRA_REQUIREMENTS_INSTALL: Cython + run: | + export PATH="/C/Program Files (x86)/Windows Kits/10/bin/10.0.18362.0/x64;$PATH" + nox --force-color -e tests-3 --install-only + + - name: Test + shell: bash + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + SKIP_REQUIREMENTS_INSTALL: YES + run: | + export PATH="/C/Program Files (x86)/Windows Kits/10/bin/10.0.18362.0/x64;$PATH" + nox --force-color -e tests-3 -- -vv tests/ + + - name: Create CodeCov Flags + if: always() + id: codecov-flags + run: | + echo ::set-output name=flags::$(python -c "import sys; print('{},{},salt_{}'.format('${{ runner.os }}'.replace('-latest', ''), 'py{}{}'.format(*sys.version_info), '_'.join(str(v) for v in '${{ matrix.salt-version }}'.replace('==', '_').split('.'))))") + + - name: Upload Project Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},project + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-project + REPORT_PATH: artifacts/coverage-project.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Tests Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},tests + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-tests + REPORT_PATH: artifacts/coverage-tests.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Logs + if: always() + uses: actions/upload-artifact@main + with: + name: runtests-${{ runner.os }}-py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}.log + path: artifacts/runtests-*.log + + macOS: + runs-on: macOS-latest + needs: Pre-Commit + + timeout-minutes: 40 + + strategy: + fail-fast: false + max-parallel: 3 + matrix: + python-version: + - 3.6 + - 3.7 + salt-version: + - 3003 + + steps: + - uses: actions/checkout@v2 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Nox + run: | + python -m pip install --upgrade pip + pip install nox + + - name: Install Test Requirements + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + run: | + nox --force-color -e tests-3 --install-only + + - name: Test + env: + SALT_REQUIREMENT: salt==${{ matrix.salt-version }} + SKIP_REQUIREMENTS_INSTALL: YES + run: | + nox --force-color -e tests-3 -- -vv tests/ + + - name: Create CodeCov Flags + if: always() + id: codecov-flags + run: | + echo ::set-output name=flags::$(python -c "import sys; print('{},{},salt_{}'.format('${{ runner.os }}'.replace('-latest', ''), 'py{}{}'.format(*sys.version_info), '_'.join(str(v) for v in '${{ matrix.salt-version }}'.replace('==', '_').split('.'))))") + + - name: Upload Project Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},project + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-project + REPORT_PATH: artifacts/coverage-project.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Tests Code Coverage + if: always() + shell: bash + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + REPORT_FLAGS: ${{ steps.codecov-flags.outputs.flags }},tests + REPORT_NAME: ${{ runner.os }}-Py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}-tests + REPORT_PATH: artifacts/coverage-tests.xml + run: | + if [ ! -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if curl --max-time 30 -L https://codecov.io/bash --output codecov.sh; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + if [ -f codecov.sh ]; then + n=0 + until [ "$n" -ge 5 ] + do + if bash codecov.sh -R $(pwd) -n "${REPORT_NAME}" -f "${REPORT_PATH}" -F "${REPORT_FLAGS}"; then + break + fi + n=$((n+1)) + sleep 15 + done + fi + + - name: Upload Logs + if: always() + uses: actions/upload-artifact@main + with: + name: runtests-${{ runner.os }}-py${{ matrix.python-version }}-Salt${{ matrix.salt-version }}.log + path: artifacts/runtests-*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..74da6da --- /dev/null +++ b/.gitignore @@ -0,0 +1,135 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Ignore the setuptools_scm auto-generated version module +src/saltext/consul/version.py + +# Ignore CI generated artifacts +artifacts/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..561a985 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,281 @@ +--- +minimum_pre_commit_version: 2.4.0 +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.0.1 + hooks: + - id: check-merge-conflict # Check for files that contain merge conflict strings. + - id: trailing-whitespace # Trims trailing whitespace. + args: [--markdown-linebreak-ext=md] + - id: mixed-line-ending # Replaces or checks mixed line ending. + args: [--fix=lf] + - id: end-of-file-fixer # Makes sure files end in a newline and only a newline. + - id: check-merge-conflict # Check for files that contain merge conflict strings. + - id: check-ast # Simply check whether files parse as valid python. + + # ----- Formatting ----------------------------------------------------------------------------> + - repo: https://github.com/saltstack/pre-commit-remove-import-headers + rev: 1.1.0 + hooks: + - id: remove-import-headers + + - repo: local + hooks: + - id: check-cli-examples + name: Check CLI examples on execution modules + entry: python .pre-commit-hooks/check-cli-examples.py + language: system + files: ^src/saltext/consul/modules/.*\.py$ + + - repo: local + hooks: + - id: check-docs + name: Check rST doc files exist for modules/states + entry: python .pre-commit-hooks/make-autodocs.py + language: system + pass_filenames: false + + - repo: https://github.com/s0undt3ch/salt-rewrite + # Automatically rewrite code with known rules + rev: 1.3.3 + hooks: + - id: salt-rewrite + alias: rewrite-docstrings + name: Salt extensions docstrings auto-fixes + files: ^src/saltext/consul/.*\.py$ + args: [--silent] + + - repo: https://github.com/s0undt3ch/salt-rewrite + # Automatically rewrite code with known rules + rev: 1.3.3 + hooks: + - id: salt-rewrite + alias: rewrite-tests + name: Rewrite the test suite + files: ^tests/.*\.py$ + args: [--silent, -E, fix_docstrings] + + - repo: https://github.com/asottile/pyupgrade + rev: v2.37.2 + hooks: + - id: pyupgrade + name: Rewrite Code to be Py3.6+ + args: [ + --py36-plus + ] + exclude: src/saltext/consul/version.py + + - repo: https://github.com/asottile/reorder_python_imports + rev: v2.6.0 + hooks: + - id: reorder-python-imports + args: [ + --py3-plus, + ] + exclude: src/saltext/consul/version.py + + - repo: https://github.com/psf/black + rev: 22.6.0 + hooks: + - id: black + args: [-l 100] + exclude: src/saltext/consul/version.py + additional_dependencies: + - click<8.1.0 + + - repo: https://github.com/asottile/blacken-docs + rev: v1.12.1 + hooks: + - id: blacken-docs + args: [--skip-errors] + files: ^(docs/.*\.rst|src/saltext/consul/.*\.py)$ + additional_dependencies: + - black==22.6.0 + - click<8.1.0 + # <---- Formatting ----------------------------------------------------------------------------- + + # ----- Security ------------------------------------------------------------------------------> + - repo: https://github.com/PyCQA/bandit + rev: "1.7.0" + hooks: + - id: bandit + alias: bandit-salt + name: Run bandit against the code base + args: [--silent, -lll, --skip, B701] + exclude: src/saltext/consul/version.py + - repo: https://github.com/PyCQA/bandit + rev: "1.7.0" + hooks: + - id: bandit + alias: bandit-tests + name: Run bandit against the test suite + args: [--silent, -lll, --skip, B701] + files: ^tests/.* + # <---- Security ------------------------------------------------------------------------------- + + # ----- Code Analysis -------------------------------------------------------------------------> + - repo: https://github.com/saltstack/mirrors-nox + rev: v2021.6.12 + hooks: + - id: nox + alias: lint-src + name: Lint Source Code + files: ^((setup|noxfile)|src/.*)\.py$ + args: + - -e + - lint-code-pre-commit + - -- + + - repo: https://github.com/saltstack/mirrors-nox + rev: v2021.6.12 + hooks: + - id: nox + alias: lint-tests + name: Lint Tests + files: ^tests/.*\.py$ + args: + - -e + - lint-tests-pre-commit + - -- + # <---- Code Analysis -------------------------------------------------------------------------- + + # ----- Static Test Requirements --------------------------------------------------------------> + - repo: https://github.com/saltstack/pip-tools-compile-impersonate + rev: '4.1' + hooks: + - id: pip-tools-compile + alias: compile-3.6-test-requirements + name: Py3.6 Test Requirements + files: ^requirements/tests.in$ + pass_filenames: false + args: + - -v + - --py-version=3.6 + - --platform=linux + - requirements/tests.in + + - id: pip-tools-compile + alias: compile-3.7-test-requirements + name: Py3.7 Test Requirements + files: ^requirements/tests.in$ + pass_filenames: false + args: + - -v + - --py-version=3.7 + - --platform=linux + - requirements/tests.in + + - id: pip-tools-compile + alias: compile-3.8-test-requirements + name: Py3.8 Test Requirements + files: ^requirements/tests.in$ + pass_filenames: false + args: + - -v + - --py-version=3.8 + - --platform=linux + - requirements/tests.in + + - id: pip-tools-compile + alias: compile-3.9-test-requirements + name: Py3.9 Test Requirements + files: ^requirements/tests.in$ + pass_filenames: false + args: + - -v + - --py-version=3.9 + - --platform=linux + - requirements/tests.in + # <---- Static Test Requirements --------------------------------------------------------------- + + # ----- Static Lint Requirements --------------------------------------------------------------> + - id: pip-tools-compile + alias: compile-3.6-test-requirements + name: Py3.6 Lint Requirements + files: ^requirements/lint.in$ + pass_filenames: false + args: + - -v + - --py-version=3.6 + - --platform=linux + - requirements/lint.in + + - id: pip-tools-compile + alias: compile-3.7-test-requirements + name: Py3.7 Lint Requirements + files: ^requirements/lint.in$ + pass_filenames: false + args: + - -v + - --py-version=3.7 + - --platform=linux + - requirements/lint.in + + - id: pip-tools-compile + alias: compile-3.8-test-requirements + name: Py3.8 Lint Requirements + files: ^requirements/lint.in$ + pass_filenames: false + args: + - -v + - --py-version=3.8 + - --platform=linux + - requirements/lint.in + + - id: pip-tools-compile + alias: compile-3.9-test-requirements + name: Py3.9 Lint Requirements + files: ^requirements/lint.in$ + pass_filenames: false + args: + - -v + - --py-version=3.9 + - --platform=linux + - requirements/lint.in + # <---- Static Lint Requirements --------------------------------------------------------------- + + # ----- Static Docs Requirements --------------------------------------------------------------> + - id: pip-tools-compile + alias: compile-3.6-test-requirements + name: Py3.6 Docs Requirements + files: ^requirements/docs.in$ + pass_filenames: false + args: + - -v + - --py-version=3.6 + - --platform=linux + - requirements/docs.in + + - id: pip-tools-compile + alias: compile-3.7-test-requirements + name: Py3.7 Docs Requirements + files: ^requirements/docs.in$ + pass_filenames: false + args: + - -v + - --py-version=3.7 + - --platform=linux + - requirements/docs.in + + - id: pip-tools-compile + alias: compile-3.8-test-requirements + name: Py3.8 Docs Requirements + files: ^requirements/docs.in$ + pass_filenames: false + args: + - -v + - --py-version=3.8 + - --platform=linux + - requirements/docs.in + + - id: pip-tools-compile + alias: compile-3.9-test-requirements + name: Py3.9 Docs Requirements + files: ^requirements/docs.in$ + pass_filenames: false + args: + - -v + - --py-version=3.9 + - --platform=linux + - requirements/docs.in + # <---- Static Docs Requirements --------------------------------------------------------------- diff --git a/.pre-commit-hooks/check-cli-examples.py b/.pre-commit-hooks/check-cli-examples.py new file mode 100644 index 0000000..b34d329 --- /dev/null +++ b/.pre-commit-hooks/check-cli-examples.py @@ -0,0 +1,64 @@ +import ast +import pathlib +import re +import sys + +CODE_ROOT = pathlib.Path(__file__).resolve().parent.parent +EXECUTION_MODULES_PATH = CODE_ROOT / "src" / "saltext" / " consul" / "modules" + + +def check_cli_examples(files): + """ + Check that every function on every execution module provides a CLI example + """ + errors = 0 + for file in files: + path = pathlib.Path(file).resolve() + try: + relpath = path.relative_to(EXECUTION_MODULES_PATH) + if str(relpath.parent) != ".": + # We don't want to check nested packages + continue + except ValueError: + # We're only interested in execution modules + continue + module = ast.parse(path.read_text(), filename=str(path)) + for funcdef in [node for node in module.body if isinstance(node, ast.FunctionDef)]: + if funcdef.name.startswith("_"): + # We're not interested in internal functions + continue + + docstring = ast.get_docstring(funcdef, clean=False) + if not docstring: + errors += 1 + print( + "The function {!r} on '{}' does not have a docstring".format( + funcdef.name, + path.relative_to(CODE_ROOT), + ), + file=sys.stderr, + ) + continue + + if _check_cli_example_present(docstring) is False: + errors += 1 + print( + "The function {!r} on '{}' does not have a 'CLI Example:' in it's docstring".format( + funcdef.name, + path.relative_to(CODE_ROOT), + ), + file=sys.stderr, + ) + continue + sys.exit(errors) + + +CLI_EXAMPLE_PRESENT_RE = re.compile(r"CLI Example(?:s)?:") + + +def _check_cli_example_present(docstring): + return CLI_EXAMPLE_PRESENT_RE.search(docstring) is not None + + +if __name__ == "__main__": + check_cli_examples(sys.argv[1:]) diff --git a/.pre-commit-hooks/make-autodocs.py b/.pre-commit-hooks/make-autodocs.py new file mode 100644 index 0000000..700af6f --- /dev/null +++ b/.pre-commit-hooks/make-autodocs.py @@ -0,0 +1,59 @@ +import subprocess +import sys +from enum import IntEnum +from pathlib import Path + + +repo_path = Path(subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip()) +src_dir = repo_path / "src" / " saltext" / "consul" +doc_dir = repo_path / "docs" + +docs_by_kind = {} + + +def make_import_path(path): + return ".".join(path.with_suffix("").parts[-4:]) + + +for path in Path(__file__).parent.parent.joinpath("src/saltext/consul/").glob("*/*.py"): + if path.name != "__init__.py": + kind = path.parent.name + docs_by_kind.setdefault(kind, set()).add(path) + +for kind in docs_by_kind: + kind_path = doc_dir / "ref" / kind + all_rst = kind_path / "all.rst" + import_paths = [] + for path in sorted(docs_by_kind[kind]): + import_path = make_import_path(path) + import_paths.append(import_path) + rst_path = kind_path.joinpath(import_path).with_suffix(".rst") + print(rst_path) + rst_path.parent.mkdir(parents=True, exist_ok=True) + rst_path.write_text( + f""" +{import_path} +{'='*len(import_path)} + +.. automodule:: {import_path} + :members: +""" + ) + + header_text = ( + "execution modules" if kind.lower() == "modules" else kind.rstrip("s") + " modules" + ) + header = f"{'_'*len(header_text)}\n{header_text.title()}\n{'_'*len(header_text)}" + + all_rst.write_text( + f""" +.. all-saltext.consul.{kind}: + +{header} + +.. autosummary:: + :toctree: + +{chr(10).join(sorted(' '+p for p in import_paths))} +""" + ) diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..7fb0a22 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,681 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Clear in-memory caches upon conclusion of linting. Useful if running pylint +# in a server-like mode. +clear-cache-post-run=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold under which the program will exit with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regular expressions patterns to the +# ignore-list. The regex matches against paths and can be in Posix or Windows +# format. Because '\\' represents the directory delimiter on Windows systems, +# it can't be used as an escape character. +ignore-paths= + +# Files or directories matching the regular expression patterns are skipped. +# The regex matches against base names, not paths. The default value ignores +# Emacs file locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.10 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# Add paths to the list of the source roots. Supports globbing patterns. The +# source root is an absolute path or a path relative to the current working +# directory used to determine a package namespace for modules located under the +# source root. +source-roots= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type alias names. If left empty, type +# alias names will be checked with the set naming style. +#typealias-rgx= + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + asyncSetUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=15 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=25 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=builtins.BaseException,builtins.Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=2000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow explicit reexports by alias from a package __init__. +allow-reexport-from-package=no + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=R, + locally-disabled, + file-ignored, + unexpected-special-method-signature, + import-error, + no-member, + unsubscriptable-object, + blacklisted-name, + invalid-name, + missing-docstring, + empty-docstring, + unidiomatic-typecheck, + wrong-import-order, + ungrouped-imports, + wrong-import-position, + bad-mcs-method-argument, + bad-mcs-classmethod-argument, + line-too-long, + too-many-lines, + bad-continuation, + exec-used, + attribute-defined-outside-init, + protected-access, + reimported, + fixme, + global-statement, + unused-variable, + unused-argument, + redefined-outer-name, + redefined-builtin, + undefined-loop-variable, + logging-format-interpolation, + invalid-format-index, + line-too-long, + import-outside-toplevel, + deprecated-method, + keyword-arg-before-vararg, + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[METHOD_ARGS] + +# List of qualified names (i.e., library.method) which require a timeout +# parameter e.g. 'requests.api.get,requests.api.post' +timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. No available dictionaries : You need to install the +# system dependency for enchant to work.. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins=__opts__, + __salt__, + __pillar__, + __grains__, + __context__, + __runner__, + __ret__, + __env__, + __low__, + __states__, + __lowstate__, + __running__, + __active_provider_name__, + __master_opts__, + __jid_event__, + __instance_id__, + __salt_system_encoding__, + __proxy__, + __serializers__, + __reg__, + __executors__, + __events__ + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a92dcb5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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 EITR Technologies + + 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..b276b66 --- /dev/null +++ b/README.md @@ -0,0 +1,33 @@ +# consul + +Salt Extension for interacting with Consul + +## Quickstart + +To get started with your new project: + + # Create a new venv + python3 -m venv env --prompt consul + source env/bin/activate + + # On mac, you may need to upgrade pip + python -m pip install --upgrade pip + + # On WSL or some flavors of linux you may need to install the `enchant` + # library in order to build the docs + sudo apt-get install -y enchant + + # Install extension + test/dev/doc dependencies into your environment + python -m pip install -e .[tests,dev,docs] + + # Run tests! + python -m nox -e tests-3 + + # skip requirements install for next time + export SKIP_REQUIREMENTS_INSTALL=1 + + # Build the docs, serve, and view in your web browser: + python -m nox -e docs && (cd docs/_build/html; python -m webbrowser localhost:8000; python -m http.server; cd -) + + # Run the example function + salt-call --local consul.example_function text="Happy Hacking!" diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d4bb2cb --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/_static/.gitkeep b/docs/_static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/all.rst b/docs/all.rst new file mode 100644 index 0000000..3cacbfc --- /dev/null +++ b/docs/all.rst @@ -0,0 +1,16 @@ +.. _all the states/modules: + +Complete List of consul +======================= + + +.. toctree:: + :maxdepth: 2 + + ref/modules.rst + + +.. toctree:: + :maxdepth: 2 + + ref/states.rst diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..16f122d --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,162 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html +# -- Path setup -------------------------------------------------------------- +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import datetime +import os +import sys + +try: + from importlib_metadata import distribution +except ImportError: + from importlib.metadata import distribution + + +try: + docs_basepath = os.path.abspath(os.path.dirname(__file__)) +except NameError: + # sphinx-intl and six execute some code which will raise this NameError + # assume we're in the doc/ directory + docs_basepath = os.path.abspath(os.path.dirname(".")) + +addtl_paths = ( + os.path.join(os.pardir, "src"), # saltext.consul itself (for autodoc) + "_ext", # custom Sphinx extensions +) + +for addtl_path in addtl_paths: + sys.path.insert(0, os.path.abspath(os.path.join(docs_basepath, addtl_path))) + +dist = distribution("saltext.consul") + + +# -- Project information ----------------------------------------------------- +this_year = datetime.datetime.today().year +if this_year == 2021: + copyright_year = 2021 +else: + copyright_year = f"2021 - {this_year}" +project = dist.metadata["Summary"] +author = dist.metadata["Author"] +copyright = f"{copyright_year}, {author}" + +# The full version, including alpha/beta/rc tags +release = dist.version + + +# Variables to pass into the docs from sitevars.rst for rst substitution +with open("sitevars.rst") as site_vars_file: + site_vars = site_vars_file.read().splitlines() + +rst_prolog = """ +{} +""".format( + "\n".join(site_vars[:]) +) + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.napoleon", + "sphinx.ext.intersphinx", + "sphinx.ext.viewcode", + "sphinx.ext.todo", + "sphinx.ext.coverage", + "sphinx_copybutton", + "sphinxcontrib.spelling", +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [ + "_build", + "Thumbs.db", + ".DS_Store", + ".vscode", + ".venv", + ".git", + ".gitlab-ci", + ".gitignore", + "sitevars.rst", +] + +autosummary_generate = True + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "furo" +html_title = project + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +html_logo = "" + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. Favicons can be up to at least 228x228. PNG +# format is supported as well, not just .ico' +html_favicon = "" + +# Sphinx Napoleon Config +napoleon_google_docstring = True +napoleon_numpy_docstring = False +napoleon_include_init_with_doc = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True + +# ----- Intersphinx Config ----------------------------------------------------------------------------------------> +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "pytest": ("https://pytest.readthedocs.io/en/stable", None), + "salt": ("https://docs.saltproject.io/en/latest", None), +} +# <---- Intersphinx Config ----------------------------------------------------------------------------------------- + +# ----- Autodoc Config ----------------------------------------------------------------------------------------------> +autodoc_default_options = {"member-order": "bysource"} +autodoc_mock_imports = ["salt"] +# <---- Autodoc Config ----------------------------------------------------------------------------------------------- + + +def setup(app): + app.add_crossref_type( + directivename="fixture", + rolename="fixture", + indextemplate="pair: %s; fixture", + ) + # Allow linking to pytest's confvals. + app.add_object_type( + "confval", + "pytest-confval", + objname="configuration value", + indextemplate="pair: %s; configuration value", + ) diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..004c647 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,15 @@ +Welcome to consul Documentation! +================================ + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + all.rst + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..922152e --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/ref/.gitkeep b/docs/ref/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/docs/sitevars.rst b/docs/sitevars.rst new file mode 100644 index 0000000..e69de29 diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 0000000..6c7bafe --- /dev/null +++ b/noxfile.py @@ -0,0 +1,527 @@ +# pylint: disable=missing-module-docstring,import-error,protected-access,missing-function-docstring +import datetime +import json +import os +import pathlib +import shutil +import sys +import tempfile +from pathlib import Path + +import nox +from nox.command import CommandFailed +from nox.virtualenv import VirtualEnv + +# Nox options +# Reuse existing virtualenvs +nox.options.reuse_existing_virtualenvs = True +# Don't fail on missing interpreters +nox.options.error_on_missing_interpreters = False + +# Python versions to test against +PYTHON_VERSIONS = ("3", "3.5", "3.6", "3.7", "3.8", "3.9", "3.10") +# Be verbose when running under a CI context +CI_RUN = ( + os.environ.get("JENKINS_URL") or os.environ.get("CI") or os.environ.get("DRONE") is not None +) +PIP_INSTALL_SILENT = CI_RUN is False +SKIP_REQUIREMENTS_INSTALL = "SKIP_REQUIREMENTS_INSTALL" in os.environ +EXTRA_REQUIREMENTS_INSTALL = os.environ.get("EXTRA_REQUIREMENTS_INSTALL") + +COVERAGE_VERSION_REQUIREMENT = "coverage==5.2" +SALT_REQUIREMENT = os.environ.get("SALT_REQUIREMENT") or "salt>=3003" +if SALT_REQUIREMENT == "salt==master": + SALT_REQUIREMENT = "git+https://github.com/saltstack/salt.git@master" + +# Prevent Python from writing bytecode +os.environ["PYTHONDONTWRITEBYTECODE"] = "1" + +# Global Path Definitions +REPO_ROOT = pathlib.Path(__file__).resolve().parent +# Change current directory to REPO_ROOT +os.chdir(str(REPO_ROOT)) + +ARTIFACTS_DIR = REPO_ROOT / "artifacts" +# Make sure the artifacts directory exists +ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True) +CUR_TIME = datetime.datetime.now().strftime("%Y%m%d%H%M%S.%f") +RUNTESTS_LOGFILE = ARTIFACTS_DIR / f"runtests-{CUR_TIME}.log" +COVERAGE_REPORT_DB = REPO_ROOT / ".coverage" +COVERAGE_REPORT_PROJECT = ARTIFACTS_DIR.relative_to(REPO_ROOT) / "coverage-project.xml" +COVERAGE_REPORT_TESTS = ARTIFACTS_DIR.relative_to(REPO_ROOT) / "coverage-tests.xml" +JUNIT_REPORT = ARTIFACTS_DIR.relative_to(REPO_ROOT) / "junit-report.xml" + + +def _get_session_python_version_info(session): + try: + version_info = session._runner._real_python_version_info + except AttributeError: + session_py_version = session.run_always( + "python", + "-c", + 'import sys; sys.stdout.write("{}.{}.{}".format(*sys.version_info))', + silent=True, + log=False, + ) + version_info = tuple(int(part) for part in session_py_version.split(".") if part.isdigit()) + session._runner._real_python_version_info = version_info + return version_info + + +def _get_pydir(session): + version_info = _get_session_python_version_info(session) + if version_info < (3, 5): + session.error("Only Python >= 3.5 is supported") + return f"py{version_info[0]}.{version_info[1]}" + + +def _install_requirements( + session, + *passed_requirements, # pylint: disable=unused-argument + install_coverage_requirements=True, + install_test_requirements=True, + install_source=False, + install_salt=True, + install_extras=None, +): + install_extras = install_extras or [] + if SKIP_REQUIREMENTS_INSTALL is False: + # Always have the wheel package installed + session.install("--progress-bar=off", "wheel", silent=PIP_INSTALL_SILENT) + if install_coverage_requirements: + session.install( + "--progress-bar=off", COVERAGE_VERSION_REQUIREMENT, silent=PIP_INSTALL_SILENT + ) + + if install_salt: + session.install("--progress-bar=off", SALT_REQUIREMENT, silent=PIP_INSTALL_SILENT) + + if install_test_requirements: + install_extras.append("tests") + + if EXTRA_REQUIREMENTS_INSTALL: + session.log( + "Installing the following extra requirements because the " + "EXTRA_REQUIREMENTS_INSTALL environment variable was set: " + "EXTRA_REQUIREMENTS_INSTALL='%s'", + EXTRA_REQUIREMENTS_INSTALL, + ) + install_command = ["--progress-bar=off"] + install_command += [req.strip() for req in EXTRA_REQUIREMENTS_INSTALL.split()] + session.install(*install_command, silent=PIP_INSTALL_SILENT) + + if install_source: + pkg = "." + if install_extras: + pkg += f"[{','.join(install_extras)}]" + session.install("-e", pkg, silent=PIP_INSTALL_SILENT) + elif install_extras: + pkg = f".[{','.join(install_extras)}]" + session.install(pkg, silent=PIP_INSTALL_SILENT) + + +@nox.session(python=PYTHON_VERSIONS) +def tests(session): + _install_requirements(session, install_source=True) + + sitecustomize_dir = session.run("salt-factories", "--coverage", silent=True, log=False) + python_path_env_var = os.environ.get("PYTHONPATH") or None + if python_path_env_var is None: + python_path_env_var = sitecustomize_dir + else: + python_path_entries = python_path_env_var.split(os.pathsep) + if sitecustomize_dir in python_path_entries: + python_path_entries.remove(sitecustomize_dir) + python_path_entries.insert(0, sitecustomize_dir) + python_path_env_var = os.pathsep.join(python_path_entries) + + env = { + # The updated python path so that sitecustomize is importable + "PYTHONPATH": python_path_env_var, + # The full path to the .coverage data file. Makes sure we always write + # them to the same directory + "COVERAGE_FILE": str(COVERAGE_REPORT_DB), + # Instruct sub processes to also run under coverage + "COVERAGE_PROCESS_START": str(REPO_ROOT / ".coveragerc"), + } + + session.run("coverage", "erase") + args = [ + "--rootdir", + str(REPO_ROOT), + f"--log-file={RUNTESTS_LOGFILE.relative_to(REPO_ROOT)}", + "--log-file-level=debug", + "--show-capture=no", + f"--junitxml={JUNIT_REPORT}", + "--showlocals", + "-ra", + "-s", + ] + if session._runner.global_config.forcecolor: + args.append("--color=yes") + if not session.posargs: + args.append("tests/") + else: + for arg in session.posargs: + if arg.startswith("--color") and args[0].startswith("--color"): + args.pop(0) + args.append(arg) + for arg in session.posargs: + if arg.startswith("-"): + continue + if arg.startswith(f"tests{os.sep}"): + break + try: + pathlib.Path(arg).resolve().relative_to(REPO_ROOT / "tests") + break + except ValueError: + continue + else: + args.append("tests/") + try: + session.run("coverage", "run", "-m", "pytest", *args, env=env) + finally: + # Always combine and generate the XML coverage report + try: + session.run("coverage", "combine") + except CommandFailed: + # Sometimes some of the coverage files are corrupt which would + # trigger a CommandFailed exception + pass + # Generate report for salt code coverage + session.run( + "coverage", + "xml", + "-o", + str(COVERAGE_REPORT_PROJECT), + "--omit=tests/*", + "--include=src/saltext/consul/*", + ) + # Generate report for tests code coverage + session.run( + "coverage", + "xml", + "-o", + str(COVERAGE_REPORT_TESTS), + "--omit=src/saltext/consul/*", + "--include=tests/*", + ) + try: + session.run("coverage", "report", "--show-missing", "--include=src/saltext/consul/*") + # If you also want to display the code coverage report on the CLI + # for the tests, comment the call above and uncomment the line below + # session.run( + # "coverage", "report", "--show-missing", + # "--include=src/saltext/consul/*,tests/*" + # ) + finally: + # Move the coverage DB to artifacts/coverage in order for it to be archived by CI + if COVERAGE_REPORT_DB.exists(): + shutil.move(str(COVERAGE_REPORT_DB), str(ARTIFACTS_DIR / COVERAGE_REPORT_DB.name)) + + +class Tee: + """ + Python class to mimic linux tee behaviour + """ + + def __init__(self, first, second): + self._first = first + self._second = second + + def write(self, buf): + wrote = self._first.write(buf) + self._first.flush() + self._second.write(buf) + self._second.flush() + return wrote + + def fileno(self): + return self._first.fileno() + + +def _lint(session, rcfile, flags, paths, tee_output=True): + _install_requirements( + session, + install_salt=False, + install_coverage_requirements=False, + install_test_requirements=False, + install_extras=["dev", "tests"], + ) + + if tee_output: + session.run("pylint", "--version") + pylint_report_path = os.environ.get("PYLINT_REPORT") + + cmd_args = ["pylint", f"--rcfile={rcfile}"] + list(flags) + list(paths) + + src_path = str(REPO_ROOT / "src") + python_path_env_var = os.environ.get("PYTHONPATH") or None + if python_path_env_var is None: + python_path_env_var = src_path + else: + python_path_entries = python_path_env_var.split(os.pathsep) + if src_path in python_path_entries: + python_path_entries.remove(src_path) + python_path_entries.insert(0, src_path) + python_path_env_var = os.pathsep.join(python_path_entries) + + env = { + # The updated python path so that the project is importable without installing it + "PYTHONPATH": python_path_env_var, + "PYTHONUNBUFFERED": "1", + } + + cmd_kwargs = {"env": env} + + if tee_output: + stdout = tempfile.TemporaryFile(mode="w+b") + cmd_kwargs["stdout"] = Tee(stdout, sys.__stdout__) + + try: + session.run(*cmd_args, **cmd_kwargs) + finally: + if tee_output: + stdout.seek(0) + contents = stdout.read() + if contents: + contents = contents.decode("utf-8") + sys.stdout.write(contents) + sys.stdout.flush() + if pylint_report_path: + # Write report + with open(pylint_report_path, "w", encoding="utf-8") as wfh: + wfh.write(contents) + session.log("Report file written to %r", pylint_report_path) + stdout.close() + + +def _lint_pre_commit(session, rcfile, flags, paths): + if "VIRTUAL_ENV" not in os.environ: + session.error( + "This should be running from within a virtualenv and " + "'VIRTUAL_ENV' was not found as an environment variable." + ) + if "pre-commit" not in os.environ["VIRTUAL_ENV"]: + session.error( + "This should be running from within a pre-commit virtualenv and " + f"'VIRTUAL_ENV'({os.environ['VIRTUAL_ENV']}) does not appear to be a pre-commit virtualenv." + ) + + # Let's patch nox to make it run inside the pre-commit virtualenv + session._runner.venv = VirtualEnv( + os.environ["VIRTUAL_ENV"], + interpreter=session._runner.func.python, + reuse_existing=True, + venv=True, + ) + _lint(session, rcfile, flags, paths, tee_output=False) + + +@nox.session(python="3") +def lint(session): + """ + Run PyLint against the code and the test suite. Set PYLINT_REPORT to a path to capture output. + """ + session.notify(f"lint-code-{session.python}") + session.notify(f"lint-tests-{session.python}") + + +@nox.session(python="3", name="lint-code") +def lint_code(session): + """ + Run PyLint against the code. Set PYLINT_REPORT to a path to capture output. + """ + flags = ["--disable=I"] + if session.posargs: + paths = session.posargs + else: + paths = ["setup.py", "noxfile.py", "src/"] + _lint(session, ".pylintrc", flags, paths) + + +@nox.session(python="3", name="lint-tests") +def lint_tests(session): + """ + Run PyLint against the test suite. Set PYLINT_REPORT to a path to capture output. + """ + flags = [ + "--disable=I,redefined-outer-name,missing-function-docstring,no-member,missing-module-docstring" + ] + if session.posargs: + paths = session.posargs + else: + paths = ["tests/"] + _lint(session, ".pylintrc", flags, paths) + + +@nox.session(python=False, name="lint-code-pre-commit") +def lint_code_pre_commit(session): + """ + Run PyLint against the code. Set PYLINT_REPORT to a path to capture output. + """ + flags = ["--disable=I"] + if session.posargs: + paths = session.posargs + else: + paths = ["setup.py", "noxfile.py", "src/"] + _lint_pre_commit(session, ".pylintrc", flags, paths) + + +@nox.session(python=False, name="lint-tests-pre-commit") +def lint_tests_pre_commit(session): + """ + Run PyLint against the code and the test suite. Set PYLINT_REPORT to a path to capture output. + """ + flags = [ + "--disable=I,redefined-outer-name,missing-function-docstring,no-member,missing-module-docstring", + ] + if session.posargs: + paths = session.posargs + else: + paths = ["tests/"] + _lint_pre_commit(session, ".pylintrc", flags, paths) + + +@nox.session(python="3") +def docs(session): + """ + Build Docs + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs"], + ) + os.chdir("docs/") + session.run("make", "clean", external=True) + session.run("make", "linkcheck", "SPHINXOPTS=-W", external=True) + session.run("make", "coverage", "SPHINXOPTS=-W", external=True) + docs_coverage_file = os.path.join("_build", "html", "python.txt") + if os.path.exists(docs_coverage_file): + with open(docs_coverage_file) as rfh: # pylint: disable=unspecified-encoding + contents = rfh.readlines()[2:] + if contents: + session.error("\n" + "".join(contents)) + session.run("make", "html", "SPHINXOPTS=-W", external=True) + os.chdir(str(REPO_ROOT)) + + +@nox.session(name="docs-html", python="3") +@nox.parametrize("clean", [False, True]) +@nox.parametrize("include_api_docs", [False, True]) +def docs_html(session, clean, include_api_docs): + """ + Build Sphinx HTML Documentation + + TODO: Add option for `make linkcheck` and `make coverage` + calls via Sphinx. Ran into problems with two when + using Furo theme and latest Sphinx. + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs"], + ) + if include_api_docs: + gen_api_docs(session) + build_dir = Path("docs", "_build", "html") + sphinxopts = "-Wn" + if clean: + sphinxopts += "E" + args = [sphinxopts, "--keep-going", "docs", str(build_dir)] + session.run("sphinx-build", *args, external=True) + + +@nox.session(name="docs-dev", python="3") +@nox.parametrize("clean", [False, True]) +def docs_dev(session, clean) -> None: + """ + Build and serve the Sphinx HTML documentation, with live reloading on file changes, via sphinx-autobuild. + + Note: Only use this in INTERACTIVE DEVELOPMENT MODE. This SHOULD NOT be called + in CI/CD pipelines, as it will hang. + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs", "docsauto"], + ) + + # Launching LIVE reloading Sphinx session + build_dir = Path("docs", "_build", "html") + args = ["--watch", ".", "--open-browser", "docs", str(build_dir)] + if clean and build_dir.exists(): + shutil.rmtree(build_dir) + + session.run("sphinx-autobuild", *args) + + +@nox.session(name="docs-crosslink-info", python="3") +def docs_crosslink_info(session): + """ + Report intersphinx cross links information + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs"], + ) + os.chdir("docs/") + intersphinx_mapping = json.loads( + session.run( + "python", + "-c", + "import json; import conf; print(json.dumps(conf.intersphinx_mapping))", + silent=True, + log=False, + ) + ) + intersphinx_mapping_list = ", ".join(list(intersphinx_mapping)) + try: + mapping_entry = intersphinx_mapping[session.posargs[0]] + except IndexError: + session.error( + f"You need to pass at least one argument whose value must be one of: {intersphinx_mapping_list}" + ) + except KeyError: + session.error(f"Only acceptable values for first argument are: {intersphinx_mapping_list}") + session.run( + "python", "-m", "sphinx.ext.intersphinx", mapping_entry[0].rstrip("/") + "/objects.inv" + ) + os.chdir(str(REPO_ROOT)) + + +@nox.session(name="gen-api-docs", python="3") +def gen_api_docs(session): + """ + Generate API Docs + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs"], + ) + try: + shutil.rmtree("docs/ref") + except FileNotFoundError: + pass + session.run( + "sphinx-apidoc", + "--implicit-namespaces", + "--module-first", + "-o", + "docs/ref/", + "src/saltext", + "src/saltext/consul/config/schemas", + ) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6ea51a2 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,10 @@ +[build-system] +requires = ["setuptools>=50.3.2", "wheel", "setuptools-declarative-requirements", "setuptools_scm[toml]>=3.4"] +build-backend = "setuptools.build_meta" + +[tool.setuptools_scm] +write_to = "src/saltext/consul/version.py" +write_to_template = "__version__ = \"{version}\"" + +[tool.black] +line-length = 100 diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000..bcd4f13 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1 @@ +salt>=3003 diff --git a/requirements/changelog.txt b/requirements/changelog.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/dev.txt b/requirements/dev.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/docs-auto.txt b/requirements/docs-auto.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/docs.in b/requirements/docs.in new file mode 100644 index 0000000..1542731 --- /dev/null +++ b/requirements/docs.in @@ -0,0 +1,5 @@ +sphinx +sphinx-material-saltstack +sphinx-prompt +sphinxcontrib-spelling +importlib_metadata; python_version < "3.8" diff --git a/requirements/docs.txt b/requirements/docs.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/lint.in b/requirements/lint.in new file mode 100644 index 0000000..911de93 --- /dev/null +++ b/requirements/lint.in @@ -0,0 +1,2 @@ +pylint +saltpylint diff --git a/requirements/lint.txt b/requirements/lint.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/py3.5/docs.txt b/requirements/py3.5/docs.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/py3.5/lint.txt b/requirements/py3.5/lint.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/py3.5/tests.txt b/requirements/py3.5/tests.txt new file mode 100644 index 0000000..e69de29 diff --git a/requirements/py3.6/docs.txt b/requirements/py3.6/docs.txt new file mode 100644 index 0000000..273b81d --- /dev/null +++ b/requirements/py3.6/docs.txt @@ -0,0 +1,89 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.6/docs.txt requirements/docs.in +# +alabaster==0.7.13 + # via sphinx +babel==2.11.0 + # via sphinx +beautifulsoup4==4.9.1 + # via sphinx-material-saltstack +certifi==2023.11.17 + # via requests +charset-normalizer==2.0.12 + # via requests +css-html-js-minify==2.5.5 + # via sphinx-material-saltstack +docutils==0.18.1 + # via sphinx +idna==3.6 + # via requests +imagesize==1.4.1 + # via sphinx +importlib-metadata==4.8.3 ; python_version < "3.8" + # via + # -r requirements/docs.in + # sphinx + # sphinxcontrib-spelling +jinja2==3.0.3 + # via sphinx +lxml==4.5.2 + # via sphinx-material-saltstack +markupsafe==2.0.1 + # via jinja2 +packaging==21.3 + # via sphinx +pyenchant==3.2.2 + # via sphinxcontrib-spelling +pygments==2.14.0 + # via + # sphinx + # sphinx-prompt +pyparsing==3.0.7 + # via packaging +python-slugify[unidecode]==4.0.1 + # via sphinx-material-saltstack +pytz==2023.3.post1 + # via babel +requests==2.27.1 + # via sphinx +snowballstemmer==2.2.0 + # via sphinx +soupsieve==2.3.2.post1 + # via beautifulsoup4 +sphinx-material-saltstack==1.0.5 + # via -r requirements/docs.in +sphinx-prompt==1.5.0 + # via -r requirements/docs.in +sphinx==5.3.0 + # via + # -r requirements/docs.in + # sphinx-material-saltstack + # sphinx-prompt + # sphinxcontrib-spelling +sphinxcontrib-applehelp==1.0.2 + # via sphinx +sphinxcontrib-devhelp==1.0.2 + # via sphinx +sphinxcontrib-htmlhelp==2.0.0 + # via sphinx +sphinxcontrib-jsmath==1.0.1 + # via sphinx +sphinxcontrib-qthelp==1.0.3 + # via sphinx +sphinxcontrib-serializinghtml==1.1.5 + # via sphinx +sphinxcontrib-spelling==7.7.0 + # via -r requirements/docs.in +text-unidecode==1.3 + # via python-slugify +typing-extensions==4.1.1 + # via importlib-metadata +unidecode==1.3.7 + # via python-slugify +urllib3==1.26.18 + # via requests +zipp==3.6.0 + # via importlib-metadata diff --git a/requirements/py3.6/lint.txt b/requirements/py3.6/lint.txt new file mode 100644 index 0000000..4ae2428 --- /dev/null +++ b/requirements/py3.6/lint.txt @@ -0,0 +1,41 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.6/lint.txt requirements/lint.in +# +astroid==2.11.7 + # via pylint +dill==0.3.4 + # via pylint +isort==5.10.1 + # via pylint +lazy-object-proxy==1.7.1 + # via astroid +mccabe==0.7.0 + # via pylint +modernize==0.5 + # via saltpylint +platformdirs==2.4.0 + # via pylint +pycodestyle==2.10.0 + # via saltpylint +pylint==2.13.9 + # via + # -r requirements/lint.in + # saltpylint +saltpylint==2023.8.3 + # via -r requirements/lint.in +tomli==1.2.3 + # via pylint +typed-ast==1.5.5 + # via astroid +typing-extensions==4.1.1 + # via + # astroid + # pylint +wrapt==1.16.0 + # via astroid + +# The following packages are considered to be unsafe in a requirements file: +# setuptools diff --git a/requirements/py3.6/tests.txt b/requirements/py3.6/tests.txt new file mode 100644 index 0000000..705ae90 --- /dev/null +++ b/requirements/py3.6/tests.txt @@ -0,0 +1,67 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.6/tests.txt requirements/tests.in +# +attrs==22.2.0 + # via + # pytest + # pytest-salt-factories + # pytest-skip-markers +distlib==0.3.8 + # via virtualenv +distro==1.8.0 + # via pytest-skip-markers +filelock==3.4.1 + # via virtualenv +importlib-metadata==4.8.3 + # via + # pluggy + # pytest + # virtualenv +importlib-resources==5.4.0 + # via virtualenv +iniconfig==1.1.1 + # via pytest +msgpack==1.0.5 + # via pytest-salt-factories +packaging==21.3 + # via pytest +platformdirs==2.4.0 + # via virtualenv +pluggy==1.0.0 + # via pytest +psutil==5.9.7 + # via pytest-salt-factories +py==1.11.0 + # via pytest +pyparsing==3.0.7 + # via packaging +pytest-helpers-namespace==2021.12.29 + # via pytest-salt-factories +pytest-salt-factories==0.912.2 + # via -r requirements/tests.in +pytest-skip-markers==1.3.0 + # via pytest-salt-factories +pytest-tempdir==2019.10.12 + # via pytest-salt-factories +pytest==7.0.1 + # via + # -r requirements/tests.in + # pytest-helpers-namespace + # pytest-salt-factories + # pytest-skip-markers + # pytest-tempdir +pyzmq==25.1.2 + # via pytest-salt-factories +tomli==1.2.3 + # via pytest +typing-extensions==4.1.1 + # via importlib-metadata +virtualenv==20.17.1 + # via pytest-salt-factories +zipp==3.6.0 + # via + # importlib-metadata + # importlib-resources diff --git a/requirements/py3.7/docs.txt b/requirements/py3.7/docs.txt new file mode 100644 index 0000000..eb87713 --- /dev/null +++ b/requirements/py3.7/docs.txt @@ -0,0 +1,87 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.7/docs.txt requirements/docs.in +# +alabaster==0.7.13 + # via sphinx +babel==2.14.0 + # via sphinx +beautifulsoup4==4.9.1 + # via sphinx-material-saltstack +certifi==2023.11.17 + # via requests +charset-normalizer==3.3.2 + # via requests +css-html-js-minify==2.5.5 + # via sphinx-material-saltstack +docutils==0.19 + # via sphinx +idna==3.6 + # via requests +imagesize==1.4.1 + # via sphinx +importlib-metadata==6.7.0 ; python_version < "3.8" + # via + # -r requirements/docs.in + # sphinx + # sphinxcontrib-spelling +jinja2==3.1.2 + # via sphinx +lxml==4.5.2 + # via sphinx-material-saltstack +markupsafe==2.1.3 + # via jinja2 +packaging==23.2 + # via sphinx +pyenchant==3.2.2 + # via sphinxcontrib-spelling +pygments==2.17.2 + # via + # sphinx + # sphinx-prompt +python-slugify[unidecode]==4.0.1 + # via sphinx-material-saltstack +pytz==2023.3.post1 + # via babel +requests==2.31.0 + # via sphinx +snowballstemmer==2.2.0 + # via sphinx +soupsieve==2.4.1 + # via beautifulsoup4 +sphinx-material-saltstack==1.0.5 + # via -r requirements/docs.in +sphinx-prompt==1.5.0 + # via -r requirements/docs.in +sphinx==5.3.0 + # via + # -r requirements/docs.in + # sphinx-material-saltstack + # sphinx-prompt + # sphinxcontrib-spelling +sphinxcontrib-applehelp==1.0.2 + # via sphinx +sphinxcontrib-devhelp==1.0.2 + # via sphinx +sphinxcontrib-htmlhelp==2.0.0 + # via sphinx +sphinxcontrib-jsmath==1.0.1 + # via sphinx +sphinxcontrib-qthelp==1.0.3 + # via sphinx +sphinxcontrib-serializinghtml==1.1.5 + # via sphinx +sphinxcontrib-spelling==8.0.0 + # via -r requirements/docs.in +text-unidecode==1.3 + # via python-slugify +typing-extensions==4.7.1 + # via importlib-metadata +unidecode==1.3.7 + # via python-slugify +urllib3==2.0.7 + # via requests +zipp==3.15.0 + # via importlib-metadata diff --git a/requirements/py3.7/lint.txt b/requirements/py3.7/lint.txt new file mode 100644 index 0000000..4eda0b4 --- /dev/null +++ b/requirements/py3.7/lint.txt @@ -0,0 +1,41 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.7/lint.txt requirements/lint.in +# +astroid==2.15.8 + # via pylint +dill==0.3.7 + # via pylint +isort==5.11.5 + # via pylint +lazy-object-proxy==1.9.0 + # via astroid +mccabe==0.7.0 + # via pylint +modernize==0.5 + # via saltpylint +platformdirs==4.0.0 + # via pylint +pycodestyle==2.10.0 + # via saltpylint +pylint==2.17.7 + # via + # -r requirements/lint.in + # saltpylint +saltpylint==2023.8.3 + # via -r requirements/lint.in +tomli==2.0.1 + # via pylint +tomlkit==0.12.3 + # via pylint +typed-ast==1.5.5 + # via astroid +typing-extensions==4.7.1 + # via + # astroid + # platformdirs + # pylint +wrapt==1.16.0 + # via astroid diff --git a/requirements/py3.7/tests.txt b/requirements/py3.7/tests.txt new file mode 100644 index 0000000..1945552 --- /dev/null +++ b/requirements/py3.7/tests.txt @@ -0,0 +1,63 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.7/tests.txt requirements/tests.in +# +attrs==23.1.0 + # via + # pytest-salt-factories + # pytest-skip-markers +distlib==0.3.8 + # via virtualenv +distro==1.8.0 + # via pytest-skip-markers +exceptiongroup==1.2.0 + # via pytest +filelock==3.12.2 + # via virtualenv +importlib-metadata==6.7.0 + # via + # attrs + # pluggy + # pytest + # virtualenv +iniconfig==2.0.0 + # via pytest +msgpack==1.0.5 + # via pytest-salt-factories +packaging==23.2 + # via pytest +platformdirs==4.0.0 + # via virtualenv +pluggy==1.2.0 + # via pytest +psutil==5.9.7 + # via pytest-salt-factories +pytest-helpers-namespace==2021.12.29 + # via pytest-salt-factories +pytest-salt-factories==0.912.2 + # via -r requirements/tests.in +pytest-skip-markers==1.5.0 + # via pytest-salt-factories +pytest-tempdir==2019.10.12 + # via pytest-salt-factories +pytest==7.4.3 + # via + # -r requirements/tests.in + # pytest-helpers-namespace + # pytest-salt-factories + # pytest-skip-markers + # pytest-tempdir +pyzmq==25.1.2 + # via pytest-salt-factories +tomli==2.0.1 + # via pytest +typing-extensions==4.7.1 + # via + # importlib-metadata + # platformdirs +virtualenv==20.25.0 + # via pytest-salt-factories +zipp==3.15.0 + # via importlib-metadata diff --git a/requirements/py3.8/docs.txt b/requirements/py3.8/docs.txt new file mode 100644 index 0000000..0cc6eed --- /dev/null +++ b/requirements/py3.8/docs.txt @@ -0,0 +1,84 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.8/docs.txt requirements/docs.in +# +alabaster==0.7.13 + # via sphinx +babel==2.14.0 + # via sphinx +beautifulsoup4==4.9.1 + # via sphinx-material-saltstack +certifi==2023.11.17 + # via requests +charset-normalizer==3.3.2 + # via requests +css-html-js-minify==2.5.5 + # via sphinx-material-saltstack +docutils==0.20.1 + # via + # sphinx + # sphinx-prompt +idna==3.6 + # via requests +imagesize==1.4.1 + # via sphinx +importlib-metadata==7.0.0 + # via sphinx +jinja2==3.1.2 + # via sphinx +lxml==4.5.2 + # via sphinx-material-saltstack +markupsafe==2.1.3 + # via jinja2 +packaging==23.2 + # via sphinx +pyenchant==3.2.2 + # via sphinxcontrib-spelling +pygments==2.17.2 + # via + # sphinx + # sphinx-prompt +python-slugify[unidecode]==4.0.1 + # via sphinx-material-saltstack +pytz==2023.3.post1 + # via babel +requests==2.31.0 + # via sphinx +snowballstemmer==2.2.0 + # via sphinx +soupsieve==2.5 + # via beautifulsoup4 +sphinx-material-saltstack==1.0.5 + # via -r requirements/docs.in +sphinx-prompt==1.7.0 + # via -r requirements/docs.in +sphinx==7.1.2 + # via + # -r requirements/docs.in + # sphinx-material-saltstack + # sphinx-prompt + # sphinxcontrib-spelling +sphinxcontrib-applehelp==1.0.4 + # via sphinx +sphinxcontrib-devhelp==1.0.2 + # via sphinx +sphinxcontrib-htmlhelp==2.0.1 + # via sphinx +sphinxcontrib-jsmath==1.0.1 + # via sphinx +sphinxcontrib-qthelp==1.0.3 + # via sphinx +sphinxcontrib-serializinghtml==1.1.5 + # via sphinx +sphinxcontrib-spelling==8.0.0 + # via -r requirements/docs.in +text-unidecode==1.3 + # via python-slugify +unidecode==1.3.7 + # via python-slugify +urllib3==2.1.0 + # via requests +zipp==3.17.0 + # via importlib-metadata diff --git a/requirements/py3.8/lint.txt b/requirements/py3.8/lint.txt new file mode 100644 index 0000000..d4f1496 --- /dev/null +++ b/requirements/py3.8/lint.txt @@ -0,0 +1,34 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.8/lint.txt requirements/lint.in +# +astroid==3.0.2 + # via pylint +dill==0.3.7 + # via pylint +isort==5.13.2 + # via pylint +mccabe==0.7.0 + # via pylint +modernize==0.5 + # via saltpylint +platformdirs==4.1.0 + # via pylint +pycodestyle==2.11.1 + # via saltpylint +pylint==3.0.3 + # via + # -r requirements/lint.in + # saltpylint +saltpylint==2023.8.3 + # via -r requirements/lint.in +tomli==2.0.1 + # via pylint +tomlkit==0.12.3 + # via pylint +typing-extensions==4.9.0 + # via + # astroid + # pylint diff --git a/requirements/py3.8/tests.txt b/requirements/py3.8/tests.txt new file mode 100644 index 0000000..2282e3d --- /dev/null +++ b/requirements/py3.8/tests.txt @@ -0,0 +1,51 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.8/tests.txt requirements/tests.in +# +attrs==23.1.0 + # via + # pytest-salt-factories + # pytest-skip-markers +distlib==0.3.8 + # via virtualenv +distro==1.8.0 + # via pytest-skip-markers +exceptiongroup==1.2.0 + # via pytest +filelock==3.13.1 + # via virtualenv +iniconfig==2.0.0 + # via pytest +msgpack==1.0.7 + # via pytest-salt-factories +packaging==23.2 + # via pytest +platformdirs==4.1.0 + # via virtualenv +pluggy==1.3.0 + # via pytest +psutil==5.9.7 + # via pytest-salt-factories +pytest-helpers-namespace==2021.12.29 + # via pytest-salt-factories +pytest-salt-factories==0.912.2 + # via -r requirements/tests.in +pytest-skip-markers==1.5.0 + # via pytest-salt-factories +pytest-tempdir==2019.10.12 + # via pytest-salt-factories +pytest==7.4.3 + # via + # -r requirements/tests.in + # pytest-helpers-namespace + # pytest-salt-factories + # pytest-skip-markers + # pytest-tempdir +pyzmq==25.1.2 + # via pytest-salt-factories +tomli==2.0.1 + # via pytest +virtualenv==20.25.0 + # via pytest-salt-factories diff --git a/requirements/py3.9/docs.txt b/requirements/py3.9/docs.txt new file mode 100644 index 0000000..8aab136 --- /dev/null +++ b/requirements/py3.9/docs.txt @@ -0,0 +1,87 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.9/docs.txt requirements/docs.in +# +alabaster==0.7.13 + # via sphinx +babel==2.14.0 + # via sphinx +beautifulsoup4==4.9.1 + # via sphinx-material-saltstack +certifi==2023.11.17 + # via requests +charset-normalizer==3.3.2 + # via requests +css-html-js-minify==2.5.5 + # via sphinx-material-saltstack +docutils==0.20.1 + # via + # sphinx + # sphinx-prompt +idna==3.6 + # via requests +imagesize==1.4.1 + # via sphinx +importlib-metadata==7.0.0 + # via sphinx +jinja2==3.1.2 + # via sphinx +lxml==4.5.2 + # via sphinx-material-saltstack +markupsafe==2.1.3 + # via jinja2 +packaging==23.2 + # via sphinx +pyenchant==3.2.2 + # via sphinxcontrib-spelling +pygments==2.17.2 + # via + # sphinx + # sphinx-prompt +python-slugify[unidecode]==4.0.1 + # via sphinx-material-saltstack +requests==2.31.0 + # via sphinx +snowballstemmer==2.2.0 + # via sphinx +soupsieve==2.5 + # via beautifulsoup4 +sphinx-material-saltstack==1.0.5 + # via -r requirements/docs.in +sphinx-prompt==1.8.0 + # via -r requirements/docs.in +sphinx==7.2.6 + # via + # -r requirements/docs.in + # sphinx-material-saltstack + # sphinx-prompt + # sphinxcontrib-applehelp + # sphinxcontrib-devhelp + # sphinxcontrib-htmlhelp + # sphinxcontrib-qthelp + # sphinxcontrib-serializinghtml + # sphinxcontrib-spelling +sphinxcontrib-applehelp==1.0.7 + # via sphinx +sphinxcontrib-devhelp==1.0.5 + # via sphinx +sphinxcontrib-htmlhelp==2.0.4 + # via sphinx +sphinxcontrib-jsmath==1.0.1 + # via sphinx +sphinxcontrib-qthelp==1.0.6 + # via sphinx +sphinxcontrib-serializinghtml==1.1.9 + # via sphinx +sphinxcontrib-spelling==8.0.0 + # via -r requirements/docs.in +text-unidecode==1.3 + # via python-slugify +unidecode==1.3.7 + # via python-slugify +urllib3==2.1.0 + # via requests +zipp==3.17.0 + # via importlib-metadata diff --git a/requirements/py3.9/lint.txt b/requirements/py3.9/lint.txt new file mode 100644 index 0000000..5cfdc7c --- /dev/null +++ b/requirements/py3.9/lint.txt @@ -0,0 +1,34 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.9/lint.txt requirements/lint.in +# +astroid==3.0.2 + # via pylint +dill==0.3.7 + # via pylint +isort==5.13.2 + # via pylint +mccabe==0.7.0 + # via pylint +modernize==0.5 + # via saltpylint +platformdirs==4.1.0 + # via pylint +pycodestyle==2.11.1 + # via saltpylint +pylint==3.0.3 + # via + # -r requirements/lint.in + # saltpylint +saltpylint==2023.8.3 + # via -r requirements/lint.in +tomli==2.0.1 + # via pylint +tomlkit==0.12.3 + # via pylint +typing-extensions==4.9.0 + # via + # astroid + # pylint diff --git a/requirements/py3.9/tests.txt b/requirements/py3.9/tests.txt new file mode 100644 index 0000000..c9bc9b5 --- /dev/null +++ b/requirements/py3.9/tests.txt @@ -0,0 +1,51 @@ +# +# This file is autogenerated by pip-compile +# To update, run: +# +# pip-compile --output-file=requirements/py3.9/tests.txt requirements/tests.in +# +attrs==23.1.0 + # via + # pytest-salt-factories + # pytest-skip-markers +distlib==0.3.8 + # via virtualenv +distro==1.8.0 + # via pytest-skip-markers +exceptiongroup==1.2.0 + # via pytest +filelock==3.13.1 + # via virtualenv +iniconfig==2.0.0 + # via pytest +msgpack==1.0.7 + # via pytest-salt-factories +packaging==23.2 + # via pytest +platformdirs==4.1.0 + # via virtualenv +pluggy==1.3.0 + # via pytest +psutil==5.9.7 + # via pytest-salt-factories +pytest-helpers-namespace==2021.12.29 + # via pytest-salt-factories +pytest-salt-factories==0.912.2 + # via -r requirements/tests.in +pytest-skip-markers==1.5.0 + # via pytest-salt-factories +pytest-tempdir==2019.10.12 + # via pytest-salt-factories +pytest==7.4.3 + # via + # -r requirements/tests.in + # pytest-helpers-namespace + # pytest-salt-factories + # pytest-skip-markers + # pytest-tempdir +pyzmq==25.1.2 + # via pytest-salt-factories +tomli==2.0.1 + # via pytest +virtualenv==20.25.0 + # via pytest-salt-factories diff --git a/requirements/tests.in b/requirements/tests.in new file mode 100644 index 0000000..9f29215 --- /dev/null +++ b/requirements/tests.in @@ -0,0 +1,2 @@ +pytest >= 6.1.0 +pytest-salt-factories >= 0.130.0 diff --git a/requirements/tests.txt b/requirements/tests.txt new file mode 100644 index 0000000..e69de29 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..6b9a92f --- /dev/null +++ b/setup.cfg @@ -0,0 +1,79 @@ +[metadata] +name = saltext.consul +description = Salt Extension for interacting with Consul +long_description = file: README.md +long_description_content_type = text/markdown +author = EITR Technologies +author_email = devops@eitr.tech +keywords = salt-extension +url = https://github.com/salt-extensions/saltext-consul +project_urls = + Source=https://github.com/salt-extensions/saltext-consul + Tracker=https://github.com/salt-extensions/saltext-consul/issues +license = Apache Software License +classifiers = + Programming Language :: Python + Programming Language :: Cython + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Development Status :: 4 - Beta + Intended Audience :: Developers + License :: OSI Approved :: Apache Software License +platforms = any + +[options] +zip_safe = False +include_package_data = True +package_dir = + =src +packages = find_namespace: +python_requires = >= 3.5 +setup_requires = + wheel + setuptools>=50.3.2 + setuptools_scm[toml]>=3.4 + setuptools-declarative-requirements +install_requires = + salt>=3003 + # Add other module install requirements above this line + +[options.packages.find] +where = src +exclude = + tests + +# When targetting Salt < 3003, you can remove the other 'options.entry_points' section and use this one +#[options.entry_points] +#salt.loader= +# + +[options.entry_points] +salt.loader= + saltext.consul = saltext.consul + +[requirements-files] +install_requires = requirements/base.txt +tests_require = requirements/tests.txt +extras_require = + dev = requirements/dev.txt + tests = requirements/tests.txt + docs = requirements/docs.txt + docsauto = requirements/docs-auto.txt + changelog = requirements/changelog.txt + +[bdist_wheel] +# Use this option if your package is pure-python +universal = 1 + +[build_sphinx] +source_dir = docs +build_dir = build/sphinx + +[sdist] +owner = root +group = root diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..f999679 --- /dev/null +++ b/setup.py @@ -0,0 +1,5 @@ +# pylint: disable=missing-module-docstring +import setuptools + +if __name__ == "__main__": + setuptools.setup(use_scm_version=True) diff --git a/src/saltext/consul/__init__.py b/src/saltext/consul/__init__.py new file mode 100644 index 0000000..a3a83f6 --- /dev/null +++ b/src/saltext/consul/__init__.py @@ -0,0 +1,28 @@ +# pylint: disable=missing-module-docstring +import pathlib + +PACKAGE_ROOT = pathlib.Path(__file__).resolve().parent +try: + from .version import __version__ +except ImportError: # pragma: no cover + __version__ = "0.0.0.not-installed" + try: + from importlib.metadata import version, PackageNotFoundError + + try: + __version__ = version(__name__) + except PackageNotFoundError: + # package is not installed + pass + except ImportError: + try: + from pkg_resources import get_distribution, DistributionNotFound + + try: + __version__ = get_distribution(__name__).version + except DistributionNotFound: + # package is not installed + pass + except ImportError: + # pkg resources isn't even available?! + pass diff --git a/src/saltext/consul/loader.py b/src/saltext/consul/loader.py new file mode 100644 index 0000000..5d2e0b6 --- /dev/null +++ b/src/saltext/consul/loader.py @@ -0,0 +1,5 @@ +""" +Define the required entry-points functions in order for Salt to know +what and from where it should load this extension's loaders +""" +from . import PACKAGE_ROOT # pylint: disable=unused-import diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..d0e315f --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,39 @@ +import logging +import os + +import pytest +from saltext.consul import PACKAGE_ROOT +from saltfactories.utils import random_string + + +# Reset the root logger to its default level(because salt changed it) +logging.root.setLevel(logging.WARNING) + + +# This swallows all logging to stdout. +# To show select logs, set --log-cli-level= +for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + handler.close() + + +@pytest.fixture(scope="session") +def salt_factories_config(): + """ + Return a dictionary with the keyword arguments for FactoriesManager + """ + return { + "code_dir": str(PACKAGE_ROOT), + "inject_sitecustomize": "COVERAGE_PROCESS_START" in os.environ, + "start_timeout": 120 if os.environ.get("CI") else 60, + } + + +@pytest.fixture(scope="package") +def master(salt_factories): + return salt_factories.salt_master_daemon(random_string("master-")) + + +@pytest.fixture(scope="package") +def minion(master): + return master.salt_minion_daemon(random_string("minion-")) diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py new file mode 100644 index 0000000..9bd9458 --- /dev/null +++ b/tests/integration/conftest.py @@ -0,0 +1,28 @@ +import pytest + + +@pytest.fixture(scope="package") +def master(master): + with master.started(): + yield master + + +@pytest.fixture(scope="package") +def minion(minion): + with minion.started(): + yield minion + + +@pytest.fixture +def salt_run_cli(master): + return master.salt_run_cli() + + +@pytest.fixture +def salt_cli(master): + return master.salt_cli() + + +@pytest.fixture +def salt_call_cli(minion): + return minion.salt_call_cli() diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29