diff --git a/.copier-answers.yml b/.copier-answers.yml new file mode 100644 index 0000000..0f99411 --- /dev/null +++ b/.copier-answers.yml @@ -0,0 +1,32 @@ +# Autogenerated. Do not edit this by hand, use `copier update`. +--- +_commit: 0.10.0 +_src_path: gh:salt-extensions/salt-extension-copier +author: NodeRings +author_email: partners@noderings.com +coc_contact: partners@noderings.com +copyright_begin: 2026 +deploy_docs: rolling +docs_url: https://noderings.github.io/saltext-noderings/ +integration_name: NodeRings +license: apache +loaders: + - cloud + - module + - state +max_salt_version: '3008' +no_saltext_namespace: false +os_support: + - Linux +package_name: noderings +project_name: noderings +python_requires: '3.11' +relax_pylint: false +salt_version: '3006' +source_url: https://github.com/noderings/saltext-noderings +ssh_fixtures: false +summary: Salt Extension for ordering servers and managing DNS, firewalls and SSH keys + on the NodeRings cloud marketplace +test_containers: false +tracker_url: https://github.com/noderings/saltext-noderings/issues +url: https://github.com/noderings/saltext-noderings diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..15b41fe --- /dev/null +++ b/.coveragerc @@ -0,0 +1,44 @@ +[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_also = + # 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__.: + if TYPE_CHECKING: + @(abc\.)?abstractmethod + + # Add markers which exclude statements in between. + # Requires coverage>=7.6.0. + no cover: start(?s:.)*?no cover: stop + +omit = + .nox/* + setup.py + +ignore_errors = True + +[paths] +source = + saltext/noderings + src/saltext/noderings +testsuite = + tests/ diff --git a/.github/ISSUE_TEMPLATE/docs.md b/.github/ISSUE_TEMPLATE/docs.md new file mode 100644 index 0000000..59af749 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/docs.md @@ -0,0 +1,23 @@ +--- +name: Docs +about: Issue related to Salt Documentation +title: "[DOCS]" +labels: documentation, needs-triage +assignees: '' + +--- + +**Description** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Suggested Fix** +What did you expect to see in the documentation that is missing or needs updating? + +**Type of documentation** +This could be module documentation or a guide. + +**Location or format of documentation** +Insert page URL if applicable. + +**Additional context** +Add any other context or screenshots here. diff --git a/.github/ISSUE_TEMPLATE/tech-debt.md b/.github/ISSUE_TEMPLATE/tech-debt.md new file mode 100644 index 0000000..5a546c6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/tech-debt.md @@ -0,0 +1,13 @@ +--- +name: Tech Debt +about: Issue is related to tech debt. This includes compatibility changes for newer versions of software and OSes that salt interacts with. +title: "[TECH DEBT]" +labels: tech-debt +assignees: '' + +--- + +### Description of the tech debt to be addressed, include links and screenshots + +### Versions Report +(Provided by running `salt --versions-report`. Please also mention any differences in master/minion versions.) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index b993ec8..d75f2ed 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,9 +1,17 @@ +# Commit messages use Conventional Commits so release-please can sort them. +# Both groups only touch CI and development tools, so they stay out of the +# changelog ("ci" and "build" are hidden sections). version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" + day: "monday" + time: "09:00" + timezone: "Etc/UTC" + commit-message: + prefix: "ci" groups: "github-actions": patterns: @@ -12,6 +20,11 @@ updates: directory: "/" schedule: interval: "weekly" + day: "monday" + time: "09:00" + timezone: "Etc/UTC" + commit-message: + prefix: "build" groups: "pip": patterns: diff --git a/.github/self-hosted-runner.md b/.github/self-hosted-runner.md new file mode 100644 index 0000000..c48bc5f --- /dev/null +++ b/.github/self-hosted-runner.md @@ -0,0 +1,135 @@ +# Running CI on a NodeRings self-hosted runner + +CI runs on GitHub-hosted runners by default. It moves to our own runner when +both of these are true: + +1. A runner with the labels `self-hosted` and `noderings` is online. +2. The repository variable `NODERINGS_RUNNER` is `true`. + +Clear the variable (or set it to anything else) to go back to GitHub-hosted +runners at once, for example while the runner is down. + +These always stay on GitHub-hosted runners, whatever the variable says: + +- pull requests from forks (their code is untrusted) +- the `CI result` summary job +- building and publishing releases (`release.yml`) +- the GitHub Pages deploy job + +## Recommended setup: one dedicated NodeRings VM, repository-level runner + +Use a small Ubuntu 24.04 (x64) virtual machine ordered on NodeRings, used for +nothing else, with the GitHub Actions runner installed as a service. + +Why this option: + +- **A dedicated VM, not the production Kubernetes cluster.** CI runs code from + pull requests. Keep it away from production workloads, cluster credentials + and Argo CD. actions-runner-controller on the prod cluster would put CI + pods next to production. +- **The GitHub Actions runner, not Woodpecker or Forgejo.** The code, pull + requests and branch protection live on GitHub. The native runner reports + ordinary check runs, so branch protection, approvals and logs work + unchanged. Woodpecker or a Forgejo runner would need a separate CI server, + webhooks and mirroring for the same result. +- **Repository-level, not organization-level.** The noderings organization + is on the Free plan, which only has the Default runner group. An + organization runner there would serve every public repository in the + organization. A repository runner only takes jobs from this repository. + Register one per repository (one VM can host several runner services, each + in its own directory and user), or move to an organization runner group + limited to selected repositories once the organization is on a paid plan. + +### 1. Lock down fork pull requests first + +GitHub warns that self-hosted runners on public repositories can run code +from anyone who can open a pull request. A fork can edit the workflow files in +its own pull request, so the `runs-on` guard in our workflows is not enough by +itself. + +- Repository → Settings → Actions → General → *Approval for running fork pull + request workflows from contributors* → **Require approval for all external + contributors**. (This repository already has this setting.) +- Before approving a fork run, read every change under `.github/`. Never + approve a run that changes `runs-on` or adds `self-hosted`. +- Never use `pull_request_target` together with a checkout of the pull + request's code. + +### 2. Prepare the VM + +As root on the new VM: + +```bash +apt-get update +apt-get install -y --no-install-recommends \ + git curl ca-certificates jq make build-essential \ + libenchant-2-2 python3-dev python3-venv +# An unprivileged user for the runner, without sudo. +useradd --create-home --shell /bin/bash runner +# Tool cache for actions/setup-python. +install -d -o runner -g runner /opt/hostedtoolcache +``` + +Keep the VM patched (`unattended-upgrades`), open no inbound ports (the runner +only makes outbound HTTPS connections to GitHub), and do not store other +credentials on it. + +### 3. Register the runner + +1. Open + (Settings → Actions → Runners → **New self-hosted runner**), pick + **Linux** and **x64**. The page shows a registration token that is valid + for one hour. Use it only in the VM's shell. Do not paste it anywhere else. +2. As the `runner` user on the VM: + +```bash +mkdir -p ~/actions-runner && cd ~/actions-runner +curl -fsSLO https://github.com/actions/runner/releases/download/v2.338.2/actions-runner-linux-x64-2.338.2.tar.gz +echo "baebf204307bac6193480852732f0aba2ae97b6c5597c244f4d5558390147c40 actions-runner-linux-x64-2.338.2.tar.gz" | sha256sum -c +tar xzf actions-runner-linux-x64-2.338.2.tar.gz +echo "AGENT_TOOLSDIRECTORY=/opt/hostedtoolcache" >> .env +./config.sh --unattended \ + --url https://github.com/noderings/saltext-noderings \ + --token \ + --name noderings-ci-1 \ + --labels noderings \ + --work _work +``` + + `self-hosted`, `Linux` and `X64` are added automatically. `noderings` is + the label the workflows ask for. +3. Back as root, install and start the service: + +```bash +cd /home/runner/actions-runner +./svc.sh install runner +./svc.sh start +``` + +4. The runner should now show as **Idle** on + . + +### 4. Switch CI over + +Repository → Settings → Secrets and variables → Actions → **Variables** → +New repository variable: `NODERINGS_RUNNER` = `true`. +Then re-run CI on `main` (Actions → CI → Run workflow) and check that the jobs +show the runner name `noderings-ci-1`. + +To switch back, delete the variable or set it to `false`. + +### Optional: live API tests + +Live tests run only when the repository secret `NODERINGS_TOKEN` exists. It +should be a service account token for a separate test organization with a +small credit balance. Fork pull requests never get secrets. Tests that order +billed servers only run from a manual CI run with *billed* ticked. + +### Later: ephemeral runners + +A persistent runner keeps its work directory between jobs. Our workflows clean +up after themselves and only trusted code reaches the runner, so this is +acceptable to start with. To give every job a fresh machine, register with +`--ephemeral`, then re-register after each job. This needs a GitHub App with +the *Administration: write* repository permission so the VM can request +registration tokens itself. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bae8fbe..12cfddd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,11 @@ name: CI -on: +# Runs on GitHub-hosted runners until a NodeRings self-hosted runner exists. +# To switch, register a runner with the labels "self-hosted" and "noderings" +# (see .github/self-hosted-runner.md) and set the repository variable +# NODERINGS_RUNNER=true. Pull requests from forks always stay on +# GitHub-hosted runners: never run untrusted code on our own machines. +"on": push: branches: [main] pull_request: @@ -18,82 +23,149 @@ concurrency: group: ci-${{ github.ref }} cancel-in-progress: true -jobs: - format: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-python@v7 - with: - python-version: "3.12" - - run: pip install "black==26.5.1" "isort==8.0.1" - - run: black --check src tests - - run: isort --check-only src tests +env: + PIP_DISABLE_PIP_VERSION_CHECK: "1" + FORCE_COLOR: "1" - lint: - runs-on: ubuntu-latest +jobs: + pre-commit: + name: Pre-commit + runs-on: ${{ (vars.NODERINGS_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 30 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - run: pip install -e ".[lint,tests]" - - name: Lint the extension - run: pylint --rcfile=.pylintrc src/saltext/noderings - - name: Lint the tests - run: pylint --rcfile=.pylintrc --disable=redefined-outer-name,unused-argument,import-outside-toplevel tests + - run: python -m pip install pre-commit nox uv + - name: Run all hooks (format, docs stubs, bandit, pylint, actionlint) + run: pre-commit run --all-files --show-diff-on-failure --color=always unit: name: Unit (Salt ${{ matrix.salt }}, Python ${{ matrix.python }}) - runs-on: ubuntu-latest + runs-on: ${{ (vars.NODERINGS_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 20 strategy: fail-fast: false matrix: include: - - {salt: "3006.*", python: "3.11"} - - {salt: "3008.*", python: "3.11"} - - {salt: "3008.*", python: "3.12"} + - {salt: "3006", python: "3.11"} + - {salt: "3007", python: "3.12"} + - {salt: "3008", python: "3.12"} + - {salt: "3008", python: "3.13"} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python }} - - run: pip install "salt==${{ matrix.salt }}" -e ".[tests]" - - run: pytest -ra tests/unit + - run: python -m pip install nox uv + - name: Unit tests (nox session from the copier template) + env: + SALT_REQUIREMENT: salt~=${{ matrix.salt }}.0 + run: nox -e "tests-${{ matrix.python }}" -- tests/unit docs: - runs-on: ubuntu-latest + name: Docs + runs-on: ${{ (vars.NODERINGS_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - run: pip install -e ".[docs]" - - run: sphinx-build -W -b html docs docs/_build/html + - name: Check system packages (make, enchant for the spelling extension) + run: | + missing=() + command -v make >/dev/null || missing+=(make) + ldconfig -p | grep -q libenchant-2 || missing+=(libenchant-2-2) + if [ "${#missing[@]}" -gt 0 ]; then + sudo apt-get update -qq && sudo apt-get install -y -qq "${missing[@]}" + fi + - run: python -m pip install nox uv + - name: Build the docs (linkcheck, coverage, HTML; warnings fail) + run: nox -e docs + + package: + name: Package + runs-on: ${{ (vars.NODERINGS_RUNNER == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + - run: python -m pip install build twine + - run: python -m build + - run: python -m twine check --strict dist/* + - name: Install the wheel and check that Salt loads the extension + run: | + python -m venv /tmp/wheel-venv + /tmp/wheel-venv/bin/pip install -q dist/*.whl + /tmp/wheel-venv/bin/python - <<'PY' + from importlib.metadata import entry_points + eps = [ep for ep in entry_points(group="salt.loader") if ep.name == "saltext.noderings"] + assert eps and eps[0].value == "saltext.noderings", eps + import saltext.noderings.clouds.noderings_mod + import saltext.noderings.modules.noderings_mod + import saltext.noderings.states.noderings_mod + print("entry point and modules OK") + PY + mkdir -p /tmp/salt-root + printf 'root_dir: /tmp/salt-root\nfile_client: local\nuser: %s\n' "$(id -un)" > /tmp/salt-root/minion + /tmp/wheel-venv/bin/salt-call -c /tmp/salt-root --local --out=json sys.list_functions noderings | grep -q '"noderings.list_regions"' + /tmp/wheel-venv/bin/salt-call -c /tmp/salt-root --local --out=json sys.list_state_functions noderings | grep -q '"noderings.vm_present"' live: name: Live tests (NodeRings API) needs: [unit] # Only where the secret exists; forks and outside pull requests skip. if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-latest + runs-on: ${{ vars.NODERINGS_RUNNER == 'true' && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 45 env: NODERINGS_TOKEN: ${{ secrets.NODERINGS_TOKEN }} NODERINGS_TEST_BILLED: ${{ inputs.billed && '1' || '' }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - run: pip install "salt==3008.*" -e ".[tests]" + - run: python -m pip install "salt~=3008.0" -e ".[tests]" - name: Functional and integration tests if: env.NODERINGS_TOKEN != '' run: pytest -ra tests/functional tests/integration + - name: Note the skip + if: env.NODERINGS_TOKEN == '' + run: echo "::notice title=Live tests skipped::Add the repository secret NODERINGS_TOKEN (a service account token for a test organization) to run them." + + result: + name: CI result + # The one required status check: it fails if any job above failed. + if: always() + needs: [pre-commit, unit, docs, package, live] + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check the job results + env: + RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + echo "Job results: $RESULTS" + for r in $RESULTS; do + case "$r" in success|skipped) ;; *) exit 1 ;; esac + done diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index a547882..176fd63 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,16 +1,15 @@ -# Publishes the documentation to GitHub Pages on every push to main. -# One-time setup: Settings, Pages, Source "GitHub Actions". +# Publishes the documentation to GitHub Pages on every push to main +# (copier answer deploy_docs: rolling). +# One-time setup: Settings, Pages, Source "GitHub Actions" (done). name: Docs -on: +"on": push: branches: [main] workflow_dispatch: permissions: contents: read - pages: write - id-token: write concurrency: group: pages @@ -18,26 +17,38 @@ concurrency: jobs: build: - runs-on: ubuntu-latest + name: Build docs + runs-on: ${{ vars.NODERINGS_RUNNER == 'true' && fromJSON('["self-hosted","noderings"]') || 'ubuntu-latest' }} + timeout-minutes: 20 steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - run: pip install -e ".[docs]" - - run: sphinx-build -W -b html docs docs/_build/html - - uses: actions/upload-pages-artifact@v5 + - name: Check system packages (enchant for the spelling extension) + run: ldconfig -p | grep -q libenchant-2 || { sudo apt-get update -qq && sudo apt-get install -y -qq libenchant-2-2; } + - run: python -m pip install -e ".[docs]" + - name: Build the HTML docs + working-directory: docs + run: sphinx-build -W -b html . _build/html + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: docs/_build/html deploy: + name: Deploy to GitHub Pages needs: build runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v5 + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml new file mode 100644 index 0000000..0e192dd --- /dev/null +++ b/.github/workflows/release-please.yml @@ -0,0 +1,56 @@ +name: release-please + +# Keeps one open release pull request that collects the Conventional Commits +# merged since the last release into CHANGELOG.md and picks the next version. +# Merging it pushes the vX.Y.Z tag and a draft GitHub release; the tag starts +# release.yml, which builds the package (setuptools_scm reads the version from +# the tag), publishes it to PyPI and then publishes the GitHub release. +# +# Needs the organization's release bot GitHub App, because tags and pull +# requests made with the workflow's own GITHUB_TOKEN do not start other +# workflows: +# variable RELEASE_BOT_APP_ID (or RELEASE_BOT_CLIENT_ID) and +# secret RELEASE_BOT_PRIVATE_KEY. +"on": + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: release-please + cancel-in-progress: false + +jobs: + release-please: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Check the release bot is set up + id: bot + env: + APP_ID: ${{ vars.RELEASE_BOT_APP_ID }} + CLIENT_ID: ${{ vars.RELEASE_BOT_CLIENT_ID }} + HAS_KEY: ${{ secrets.RELEASE_BOT_PRIVATE_KEY != '' }} + run: | + if { [ -n "${APP_ID}" ] || [ -n "${CLIENT_ID}" ]; } && [ "${HAS_KEY}" = "true" ]; then + echo "ready=true" >> "$GITHUB_OUTPUT" + else + echo "::warning title=release-please skipped::Set the variable RELEASE_BOT_APP_ID and secret RELEASE_BOT_PRIVATE_KEY (see CONTRIBUTING.md, Releasing)." + echo "ready=false" >> "$GITHUB_OUTPUT" + fi + - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + if: steps.bot.outputs.ready == 'true' + id: app + with: + # GitHub accepts either the App ID or the Client ID here. + client-id: ${{ vars.RELEASE_BOT_CLIENT_ID || vars.RELEASE_BOT_APP_ID }} + private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }} + - uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0 + if: steps.bot.outputs.ready == 'true' + with: + token: ${{ steps.app.outputs.token }} + config-file: release-please-config.json + manifest-file: .release-please-manifest.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cb7d792..7327f43 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,54 +1,128 @@ -# Publishes a release to PyPI with trusted publishing (no stored token). -# One-time setup on pypi.org: add a pending publisher for project -# "saltext.noderings", owner "noderings", repository "saltext-noderings", -# workflow "release.yml", environment "release". +# Builds and publishes a release when release-please pushes a vX.Y.Z tag. +# +# 1. build: sdist and wheel from the tag (setuptools_scm turns the tag into +# the version) with build provenance attestations. +# 2. pypi: publishes to https://pypi.org/project/saltext.noderings/ with +# trusted publishing (no stored token) from the "pypi" environment. Skipped +# with a warning until the repository variable PYPI_TRUSTED_PUBLISHING is +# "true" (set it once the pending publisher exists on pypi.org, see +# CONTRIBUTING.md, Releasing). +# 3. github-release: uploads the files to the draft release made by +# release-please and publishes it. +# +# Always runs on GitHub-hosted runners: release builds never touch the +# self-hosted runner. name: Release -on: +"on": push: tags: ["v*.*.*"] + workflow_dispatch: # run it from a tag (Use workflow from: Tags) to retry a release permissions: - contents: write + contents: read + +concurrency: + group: release-${{ github.ref_name }} + cancel-in-progress: false + +env: + TAG: ${{ github.ref_name }} jobs: build: + name: Build runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + id-token: write + attestations: write steps: - - uses: actions/checkout@v7 + - name: Check this runs for a version tag + run: | + case "${TAG}" in + v[0-9]*.[0-9]*.[0-9]*) ;; + *) echo "::error::Run this workflow from a vX.Y.Z tag, not ${TAG}."; exit 1 ;; + esac + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - - uses: actions/setup-python@v7 + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: "3.12" - - run: pip install build + - run: python -m pip install build twine - run: python -m build - - uses: actions/upload-artifact@v7 + - run: python -m twine check --strict dist/* + - name: Check the version matches the tag + run: | + want="${TAG#v}" + ls dist + test -f "dist/saltext_noderings-${want}.tar.gz" || test -f "dist/saltext.noderings-${want}.tar.gz" \ + || { echo "::error::The sdist version does not match ${TAG}."; exit 1; } + ls dist/*-"${want}"-py*.whl >/dev/null || { echo "::error::The wheel version does not match ${TAG}."; exit 1; } + - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: dist/* + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: dist path: dist/ + if-no-files-found: error pypi: + name: Publish to PyPI needs: build runs-on: ubuntu-latest - environment: release + timeout-minutes: 10 + environment: + name: pypi + url: https://pypi.org/project/saltext.noderings/ permissions: id-token: write steps: - - uses: actions/download-artifact@v8 + - name: Check PyPI trusted publishing is set up + id: check + env: + ENABLED: ${{ vars.PYPI_TRUSTED_PUBLISHING }} + run: | + if [ "${ENABLED}" = "true" ]; then + echo "publish=true" >> "$GITHUB_OUTPUT" + else + echo "::warning title=PyPI skipped::Add the pending publisher on pypi.org, then set the repository variable PYPI_TRUSTED_PUBLISHING=true (see CONTRIBUTING.md, Releasing). Re-run this workflow from the tag afterwards." + echo "publish=false" >> "$GITHUB_OUTPUT" + fi + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + if: steps.check.outputs.publish == 'true' with: name: dist path: dist/ - - uses: pypa/gh-action-pypi-publish@release/v1 + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + if: steps.check.outputs.publish == 'true' + with: + skip-existing: true github-release: - needs: pypi + name: GitHub release + needs: [build, pypi] + if: always() && needs.build.result == 'success' && needs.pypi.result != 'failure' && needs.pypi.result != 'cancelled' runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write steps: - - uses: actions/download-artifact@v8 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: dist path: dist/ - - env: + - name: Upload the files and publish the release + env: GH_TOKEN: ${{ github.token }} - run: gh release create "$GITHUB_REF_NAME" dist/* --repo "$GITHUB_REPOSITORY" --title "$GITHUB_REF_NAME" --notes "See CHANGELOG.md." + GH_REPO: ${{ github.repository }} + run: | + if ! gh release view "${TAG}" >/dev/null 2>&1; then + gh release create "${TAG}" --verify-tag --draft --title "${TAG}" --notes "See CHANGELOG.md." + fi + gh release upload "${TAG}" dist/* --clobber + gh release edit "${TAG}" --draft=false --latest diff --git a/.gitignore b/.gitignore index a8f9eb4..e3e84e5 100644 --- a/.gitignore +++ b/.gitignore @@ -130,10 +130,10 @@ dmypy.json .pyre/ # Ignore the setuptools_scm auto-generated version module +src/saltext/noderings/version.py # Ignore CI generated artifacts artifacts/ # local test runs .salt-cloud-test/ -src/saltext/noderings/version.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml old mode 100644 new mode 100755 index 1717b70..04b88cd --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,41 +1,146 @@ -# Formatting and checks, as in the salt-extension copier template. -# Install with: pre-commit install +--- +minimum_pre_commit_version: 2.4.0 repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # v6.0.0 hooks: - - id: check-merge-conflict - - id: trailing-whitespace + - id: check-merge-conflict # Check for files that contain merge conflict strings. + args: [--assume-in-merge] + - id: trailing-whitespace # Trim trailing whitespace. args: [--markdown-linebreak-ext=md] - - id: end-of-file-fixer - - id: check-yaml - - id: check-toml - - id: debug-statements + - id: mixed-line-ending # Ensure files use UNIX-style newlines only. + args: [--fix=lf] + - id: end-of-file-fixer # Ensure files end with a newline. + - id: check-ast # Check whether files parse as valid Python. + + # ----- Formatting ----------------------------------------------------------------------------> + - repo: https://github.com/saltstack/pre-commit-remove-import-headers + rev: e79f595c0df31b8cb152c53993ce7c3c64f07cd4 # 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: python + files: ^src/saltext/noderings/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: python + pass_filenames: false + + - repo: https://github.com/saltstack/salt-rewrite + # Automatically rewrite code with known rules + rev: 2401c0faef69b6b846c719d611bcfe358234d5d1 # 2.5.2 + hooks: + - id: salt-rewrite + alias: rewrite-docstrings + name: Salt extensions docstrings auto-fixes + files: ^src/saltext/noderings/.*\.py$ + args: [--silent] + + - repo: https://github.com/saltstack/salt-rewrite + # Automatically rewrite code with known rules + rev: 2401c0faef69b6b846c719d611bcfe358234d5d1 # 2.5.2 + 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: v3.20.0 + rev: 75992aaa40730136014f34227e0135f63fc951b4 # v3.21.2 hooks: - id: pyupgrade - args: [--py311-plus] + name: Rewrite Code to be Py3.11+ + args: [ + --py311-plus, + ] exclude: src/saltext/noderings/version.py - repo: https://github.com/PyCQA/isort - rev: 8.0.1 + rev: a333737ed43df02b18e6c95477ea1b285b3de15a # 8.0.1 hooks: - id: isort - args: [--py, "311"] + args: [ + --py 311, + ] exclude: src/saltext/noderings/(__init__|version).py - repo: https://github.com/psf/black - rev: 26.5.1 + rev: 87928e6d6761a4a6d22250e1fee5601b3998086e # 26.5.1 hooks: - id: black - args: [-l, "100"] + args: [-l 100] + exclude: src/saltext/noderings/version.py + + - repo: https://github.com/adamchainz/blacken-docs + rev: fda77690955e9b63c6687d8806bafd56a526e45f # 1.20.0 + hooks: + - id: blacken-docs + args: [--skip-errors] + files: ^(docs/.*\.rst|src/saltext/noderings/.*\.py)$ + additional_dependencies: + - black==26.5.1 + # <---- Formatting ----------------------------------------------------------------------------- + + # ----- Security ------------------------------------------------------------------------------> + - repo: https://github.com/PyCQA/bandit + rev: 92ae8b82fb422a639f0ed8d99e96cea769594e08 # 1.9.4 + hooks: + - id: bandit + alias: bandit-salt + name: Run bandit against the code base + args: [--silent, -lll, --skip, B701] exclude: src/saltext/noderings/version.py - repo: https://github.com/PyCQA/bandit - rev: 1.8.3 + rev: 92ae8b82fb422a639f0ed8d99e96cea769594e08 # 1.9.4 hooks: - id: bandit + alias: bandit-tests + name: Run bandit against the test suite args: [--silent, -lll, --skip, B701] - exclude: ^tests/ + files: ^tests/.* + # <---- Security ------------------------------------------------------------------------------- + + # ----- Code Analysis -------------------------------------------------------------------------> + + - repo: local + hooks: + - id: nox + alias: lint-src + name: Lint Source Code + language: python + entry: nox -e lint-code-pre-commit -- + files: ^((setup|noxfile)|src/.*)\.py$ + require_serial: true + additional_dependencies: + - nox==2026.4.10 + - uv==0.11.26 # Makes this hook much faster + + - id: nox + alias: lint-tests + name: Lint Tests + language: python + entry: nox -e lint-tests-pre-commit -- + files: ^tests/.*\.py$ + require_serial: true + additional_dependencies: + - nox==2026.4.10 + - uv==0.11.26 # Makes this hook much faster + + - repo: https://github.com/Mateusz-Grzelinski/actionlint-py + rev: 694e2c0dfb4253d51f3c6c54b8f9fec0a16764dc # v1.7.11.24 + hooks: + - id: actionlint + additional_dependencies: + - shellcheck-py==0.11.0.1 + # <---- Code Analysis -------------------------------------------------------------------------- diff --git a/.pre-commit-hooks/check-cli-examples.py b/.pre-commit-hooks/check-cli-examples.py new file mode 100644 index 0000000..0eb1402 --- /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" / "noderings" / "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..e9bcdd1 --- /dev/null +++ b/.pre-commit-hooks/make-autodocs.py @@ -0,0 +1,123 @@ +import ast +import os.path +import subprocess +from pathlib import Path + +repo_path = Path(subprocess.check_output(["git", "rev-parse", "--show-toplevel"]).decode().strip()) +src_dir = repo_path / "src" / "saltext" / "noderings" +doc_dir = repo_path / "docs" + +docs_by_kind = {} +changed_something = False + + +def _find_virtualname(path): + tree = ast.parse(path.read_text()) + for node in ast.walk(tree): + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name) and target.id == "__virtualname__": + if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str): + virtualname = node.value.value + break + else: + continue + break + else: + virtualname = path.with_suffix("").name + return virtualname + + +def write_module(rst_path, path, use_virtualname=True): + if use_virtualname: + virtualname = "``" + _find_virtualname(path) + "``" + else: + virtualname = make_import_path(path) + header_len = len(virtualname) + # The check-merge-conflict pre-commit hook chokes here: + # https://github.com/pre-commit/pre-commit-hooks/issues/100 + if header_len == 7: + header_len += 1 + module_contents = f"""\ +{virtualname} +{'='*header_len} + +.. automodule:: {make_import_path(path)} + :members: +""" + if not rst_path.exists() or rst_path.read_text() != module_contents: + print(rst_path) + rst_path.write_text(module_contents) + return True + return False + + +def write_index(index_rst, import_paths, kind): + if kind == "utils": + header_text = "Utilities" + common_path = os.path.commonpath(tuple(x.replace(".", "/") for x in import_paths)).replace( + "/", "." + ) + if any(x == common_path for x in import_paths): + common_path = common_path[: common_path.rfind(".")] + else: + header_text = ( + "execution modules" if kind.lower() == "modules" else kind.rstrip("s") + " modules" + ) + common_path = import_paths[0][: import_paths[0].rfind(".")] + header = f"{'_'*len(header_text)}\n{header_text.title()}\n{'_'*len(header_text)}" + index_contents = f"""\ +.. all-saltext.noderings.{kind}: + +{header} + +.. currentmodule:: {common_path} + +.. autosummary:: + :toctree: + +{chr(10).join(sorted(' '+p[len(common_path)+1:] for p in import_paths))} +""" + if not index_rst.exists() or index_rst.read_text() != index_contents: + print(index_rst) + index_rst.write_text(index_contents) + return True + return False + + +def make_import_path(path): + if path.name == "__init__.py": + path = path.parent + return ".".join(path.relative_to(repo_path / "src").with_suffix("").parts) + + +for path in src_dir.glob("*/*.py"): + if path.name != "__init__.py": + kind = path.parent.name + if kind != "utils": + docs_by_kind.setdefault(kind, set()).add(path) + +# Utils can have subdirectories, treat them separately +for path in (src_dir / "utils").rglob("*.py"): + if path.name == "__init__.py" and not path.read_text(): + continue + docs_by_kind.setdefault("utils", set()).add(path) + +for kind in docs_by_kind: + kind_path = doc_dir / "ref" / kind + index_rst = kind_path / "index.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 / (import_path + ".rst") + rst_path.parent.mkdir(parents=True, exist_ok=True) + change = write_module(rst_path, path, use_virtualname=kind != "utils") + changed_something = changed_something or change + + write_index(index_rst, import_paths, kind) + + +# Ensure pre-commit realizes we did something +if changed_something: + exit(2) diff --git a/.pylintrc b/.pylintrc old mode 100644 new mode 100755 diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..8d73c7b --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1 @@ +{".": "0.0.0"} diff --git a/CHANGELOG.md b/CHANGELOG.md index d309efb..8a16b28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,3 @@ # Changelog -The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and the project uses [Semantic Versioning](https://semver.org/). - -## 0.1.0 (unreleased) - -### Added - -- Execution module `noderings`: virtual machines (order, start, stop, restart, reinstall, tags, firewall), DNS zones and records with DNSSEC, firewall rulesets with ordered rules, SSH keys, and the marketplace catalog (regions, plans, offers, distros). -- State module `noderings`: `ssh_key_present`/`absent`, `dns_zone_present`/`absent`, `dns_record_present`/`absent`, `firewall_ruleset_present`/`absent`, `vm_present`/`absent`, all with `test=True` support. -- Salt Cloud driver `noderings`: order servers by plan code and city, bootstrap a minion over SSH, list, start, stop, reboot and destroy them. +All notable changes are listed here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and the project uses [Semantic Versioning](https://semver.org/). Entries are generated by release-please from Conventional Commits. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4995144..703b698 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -38,16 +38,51 @@ Optional settings for the live tests: `NODERINGS_TEST_DOMAIN` (parent of the thr Run everything CI runs with nox: ```bash -nox -e tests lint lint-tests docs +nox -e tests-3.12 lint docs +pre-commit run --all-files ``` -## Changelog +## Commit messages -Add a fragment for user-visible changes: `changelog/..md`, where type is `added`, `changed`, `fixed`, `deprecated`, `removed`, `security` or `breaking`. Releases collect them with towncrier. +Use [Conventional Commits](https://www.conventionalcommits.org/). release-please reads them to pick the next version and write `CHANGELOG.md`: + +| Prefix | Changelog section | Version bump (before 1.0) | +|---|---|---| +| `feat:` | Features | minor | +| `fix:` | Bug Fixes | patch | +| `perf:` | Performance | patch | +| `docs:` | Documentation | patch | +| `deps:` | Dependencies | patch | +| `ci:`, `build:`, `chore:`, `test:`, `refactor:` | hidden | none | +| `feat!:` or a `BREAKING CHANGE:` footer | Breaking changes | minor before 1.0, major after | + +The changelog is generated, so there are no towncrier fragments to add (the `changelog/` directory and its towncrier settings come from the copier template and are not used). + +## CI + +`.github/workflows/ci.yml` runs pre-commit, the unit tests on Salt 3006 to 3008, the docs build and a package check. A single **CI result** check is required on `main`. CI runs on GitHub-hosted runners until a NodeRings self-hosted runner exists and the variable `NODERINGS_RUNNER` is `true`. See [.github/self-hosted-runner.md](.github/self-hosted-runner.md). ## Releases -Push a tag such as `v0.2.0`. The release workflow builds the package and publishes it to PyPI with trusted publishing, then publishes the docs. +1. Merge pull requests into `main`. release-please (`.github/workflows/release-please.yml`, using the noderings-release-bot GitHub App) keeps a pull request named `chore: release X.Y.Z` up to date. +2. Merge that pull request when you want to release. release-please pushes the tag `vX.Y.Z` and creates a draft GitHub release. +3. The tag starts `.github/workflows/release.yml`, which: + - builds the sdist and wheel (setuptools_scm reads the version from the tag) and attests their build provenance + - publishes them to PyPI with trusted publishing from the `pypi` environment + - uploads them to the GitHub release and publishes it +4. The docs on GitHub Pages update on every push to `main`. + +Do not create tags or releases by hand. + +### One-time setup + +| Where | What | +|---|---| +| GitHub (done) | Variable `RELEASE_BOT_APP_ID`, secret `RELEASE_BOT_PRIVATE_KEY`, environment `pypi` limited to `v*` tags | +| pypi.org, account `noderings` → *Your account* → *Publishing* → *Add a new pending publisher* (GitHub) | PyPI project name `saltext.noderings`, owner `noderings`, repository `saltext-noderings`, workflow name `release.yml`, environment name `pypi` | +| GitHub → Settings → Secrets and variables → Actions → Variables | `PYPI_TRUSTED_PUBLISHING` = `true` (until then the PyPI step is skipped with a warning) | + +A pending publisher turns into a normal trusted publisher with the first upload, which also creates the project on PyPI. If a release ran before PyPI was ready, open Actions → Release → *Run workflow*, pick the tag under *Use workflow from*, and run it again. Files already on PyPI are skipped. ## Code of conduct diff --git a/LICENSE b/LICENSE index 4daadc0..87d3434 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2023 jeanluc + Copyright 2026 NodeRings Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c590dbd --- /dev/null +++ b/Makefile @@ -0,0 +1,58 @@ +GREEN := $(shell tput -Txterm setaf 2) +YELLOW := $(shell tput -Txterm setaf 3) +BOLD := $(shell tput -Txterm bold) +ULINE := $(shell tput -Txterm smul) +RESET := $(shell tput -Txterm sgr0) + +.DEFAULT_GOAL:=help + + +.PHONY: help +help: + @echo '' + @echo '${ULINE}Usage:${RESET}' + @echo ' ${YELLOW}make${RESET} ${GREEN}${RESET}' + @echo '' + @echo '' + @echo '${ULINE}Targets:${RESET}' + @awk 'BEGIN {FS = ":.*?## "} { \ + if (/^[a-zA-Z_-]+:.*?##.*$$/) {printf " ${BOLD}${GREEN}%-20s${RESET}%s\n", $$1, $$2} \ + else if (/^## .*$$/) {printf "\n ${CYAN}[%s]${RESET}\n", substr($$1,4)} \ + }' $(MAKEFILE_LIST) + +## Lifecycle + +.PHONY: dev +dev: ## Create dev venv, (re-)install project in it + @python tools/initialize.py + +.PHONY: clean +clean: ## Remove: project/nox venvs, built docs + @rm -rf .nox .venv docs/_build + +## Docs + +.PHONY: docs +changelog: dev ## Render changelog. Requires VERSION parameter. + @if [ -z "$(VERSION)" ]; then \ + echo "Missing VERSION parameter. Example: make changelog VERSION=1.0.0" >&2; exit 1; \ + fi; \ + source .venv/bin/activate; \ + towncrier build --yes --version='$(VERSION)' + +.PHONY: docs +docs: dev ## Build docs + @source .venv/bin/activate; \ + nox -e docs --extra-pythons=3.14 --python=3.14 + +.PHONY: docs-dev +docs-dev: dev ## Build docs, serve them and refresh on changes + @source .venv/bin/activate; \ + nox -e docs-dev --extra-pythons=3.14 --python=3.14 + +## Tests + +.PHONY: tests +tests: dev ## Run tests + @source .venv/bin/activate; \ + nox -e tests-3.10 diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..76a2526 --- /dev/null +++ b/NOTICE @@ -0,0 +1,10 @@ +Salt Extension Modules for NodeRings +Copyright 2026 NodeRings + +This product is licensed to you under the Apache 2.0 license (the "License"). +You may not use this product except in compliance with the Apache 2.0 License. + +This product may include a number of subcomponents with separate copyright +notices and license terms. Your use of these subcomponents is subject to the +terms and conditions of the subcomponent's license, as noted in the LICENSE +file. 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/_ext/saltdomain.py b/docs/_ext/saltdomain.py new file mode 100644 index 0000000..7a85489 --- /dev/null +++ b/docs/_ext/saltdomain.py @@ -0,0 +1,18 @@ +""" +Copied/distilled from Salt doc/_ext/saltdomain.py in order to be able +to use Salt's custom doc refs. +""" + + +def setup(app): + app.add_crossref_type( + directivename="conf_master", + rolename="conf_master", + indextemplate="pair: %s; conf/master", + ) + app.add_crossref_type( + directivename="conf_minion", + rolename="conf_minion", + indextemplate="pair: %s; conf/minion", + ) + return {"parallel_read_safe": True, "parallel_write_safe": True} diff --git a/docs/changelog.md b/docs/changelog.md index 66efc0f..2f5367b 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -1,2 +1,12 @@ +# Changelog + +The changelog format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +This project uses [Semantic Versioning](https://semver.org/) - MAJOR.MINOR.PATCH + +```{towncrier-draft-entries} +``` + ```{include} ../CHANGELOG.md +:start-after: '# Changelog' ``` diff --git a/docs/conf.py b/docs/conf.py old mode 100644 new mode 100755 index d75aaa6..9c3be09 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,43 +1,194 @@ -"""Sphinx configuration for saltext-noderings.""" - +# 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 email.policy import os import sys +from pathlib import Path + +try: + from importlib_metadata import distribution +except ImportError: + from importlib.metadata import distribution -sys.path.insert(0, os.path.abspath("../src")) try: - from saltext.noderings import __version__ as release -except ImportError: # pragma: no cover - release = "0.0.0" + 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(".")) + +PROJECT_ROOT_DIR = Path(docs_basepath).parent + +addtl_paths = ( + os.path.join(os.pardir, "src"), # saltext.noderings 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.noderings") + + +# -- Project information ----------------------------------------------------- +this_year = datetime.datetime.today().year +if this_year == 2026: + copyright_year = "2026" +else: + copyright_year = f"2026 - {this_year}" +project = dist.metadata["Summary"] +author = dist.metadata.get("Author") -project = "saltext-noderings" -author = "NodeRings" -copyright = f"2026-{datetime.date.today().year}, {author}" # pylint: disable=redefined-builtin -version = release +if author is None: + # Core metadata is serialized differently with pyproject.toml: + # https://packaging.python.org/en/latest/specifications/pyproject-toml/#authors-maintainers + author_email = dist.metadata["Author-email"] + em = email.message_from_string( + f"To: {author_email}", + policy=email.policy.default, + ) + if em["To"].addresses and em["To"].addresses[0]: + author = em["To"].addresses[0].display_name + author = author or "" +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 --------------------------------------------------- + +linkcheck_ignore = [r"http://localhost:\d+"] + +# 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", - "sphinx_inline_tabs", + "sphinxcontrib.spelling", + "saltdomain", + "sphinxcontrib.towncrier.ext", "myst_parser", + "sphinx_inline_tabs", +] + +myst_enable_extensions = [ + "colon_fence", + "deflist", + "tasklist", +] + +# 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", ] -myst_enable_extensions = ["colon_fence", "deflist"] -source_suffix = {".rst": "restructuredtext", ".md": "markdown"} -master_doc = "index" -exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] +autosummary_generate = False + +# -- 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 = "NodeRings Salt Extension" +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"] -html_show_sourcelink = True -autodoc_default_options = {"members": True, "show-inheritance": False} -autodoc_mock_imports = [] +# 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://docs.pytest.org/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 ----------------------------------------------------------------------------------------------- + +# Towncrier draft config +towncrier_draft_autoversion_mode = "sphinx-release" +towncrier_draft_include_empty = True +towncrier_draft_working_directory = str(PROJECT_ROOT_DIR) + + +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 index f05f5ab..9eef198 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -21,6 +21,7 @@ firewall rulesets, SSH keys and virtual machines in Salt states. ref/modules/index ref/states/index ref/clouds/index + ref/utils/index .. toctree:: :maxdepth: 1 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/ref/clouds/index.rst b/docs/ref/clouds/index.rst index 03256dd..419c313 100644 --- a/docs/ref/clouds/index.rst +++ b/docs/ref/clouds/index.rst @@ -1,5 +1,12 @@ -Salt Cloud driver -================= +.. all-saltext.noderings.clouds: -.. automodule:: saltext.noderings.clouds.noderings_mod - :members: +_____________ +Cloud Modules +_____________ + +.. currentmodule:: saltext.noderings.clouds + +.. autosummary:: + :toctree: + + noderings_mod diff --git a/docs/ref/clouds/saltext.noderings.clouds.noderings_mod.rst b/docs/ref/clouds/saltext.noderings.clouds.noderings_mod.rst new file mode 100644 index 0000000..61690dd --- /dev/null +++ b/docs/ref/clouds/saltext.noderings.clouds.noderings_mod.rst @@ -0,0 +1,5 @@ +``noderings`` +============= + +.. automodule:: saltext.noderings.clouds.noderings_mod + :members: diff --git a/docs/ref/modules/index.rst b/docs/ref/modules/index.rst index 0d7ff4d..ef9e56d 100644 --- a/docs/ref/modules/index.rst +++ b/docs/ref/modules/index.rst @@ -1,5 +1,12 @@ -Execution module -================ +.. all-saltext.noderings.modules: -.. automodule:: saltext.noderings.modules.noderings_mod - :members: +_________________ +Execution Modules +_________________ + +.. currentmodule:: saltext.noderings.modules + +.. autosummary:: + :toctree: + + noderings_mod diff --git a/docs/ref/modules/saltext.noderings.modules.noderings_mod.rst b/docs/ref/modules/saltext.noderings.modules.noderings_mod.rst new file mode 100644 index 0000000..a812c60 --- /dev/null +++ b/docs/ref/modules/saltext.noderings.modules.noderings_mod.rst @@ -0,0 +1,5 @@ +``noderings`` +============= + +.. automodule:: saltext.noderings.modules.noderings_mod + :members: diff --git a/docs/ref/states/index.rst b/docs/ref/states/index.rst index f7dda97..cd81db9 100644 --- a/docs/ref/states/index.rst +++ b/docs/ref/states/index.rst @@ -1,5 +1,12 @@ -State module -============ +.. all-saltext.noderings.states: -.. automodule:: saltext.noderings.states.noderings_mod - :members: +_____________ +State Modules +_____________ + +.. currentmodule:: saltext.noderings.states + +.. autosummary:: + :toctree: + + noderings_mod diff --git a/docs/ref/states/saltext.noderings.states.noderings_mod.rst b/docs/ref/states/saltext.noderings.states.noderings_mod.rst new file mode 100644 index 0000000..62408f1 --- /dev/null +++ b/docs/ref/states/saltext.noderings.states.noderings_mod.rst @@ -0,0 +1,5 @@ +``noderings`` +============= + +.. automodule:: saltext.noderings.states.noderings_mod + :members: diff --git a/docs/ref/utils/index.rst b/docs/ref/utils/index.rst new file mode 100644 index 0000000..0def0b1 --- /dev/null +++ b/docs/ref/utils/index.rst @@ -0,0 +1,16 @@ +.. all-saltext.noderings.utils: + +_________ +Utilities +_________ + +.. currentmodule:: saltext.noderings.utils + +.. autosummary:: + :toctree: + + client + compute + dns + firewall + marketplace diff --git a/docs/ref/utils/saltext.noderings.utils.client.rst b/docs/ref/utils/saltext.noderings.utils.client.rst new file mode 100644 index 0000000..8926986 --- /dev/null +++ b/docs/ref/utils/saltext.noderings.utils.client.rst @@ -0,0 +1,5 @@ +saltext.noderings.utils.client +============================== + +.. automodule:: saltext.noderings.utils.client + :members: diff --git a/docs/ref/utils/saltext.noderings.utils.compute.rst b/docs/ref/utils/saltext.noderings.utils.compute.rst new file mode 100644 index 0000000..25a7a4c --- /dev/null +++ b/docs/ref/utils/saltext.noderings.utils.compute.rst @@ -0,0 +1,5 @@ +saltext.noderings.utils.compute +=============================== + +.. automodule:: saltext.noderings.utils.compute + :members: diff --git a/docs/ref/utils/saltext.noderings.utils.dns.rst b/docs/ref/utils/saltext.noderings.utils.dns.rst new file mode 100644 index 0000000..6e61a3a --- /dev/null +++ b/docs/ref/utils/saltext.noderings.utils.dns.rst @@ -0,0 +1,5 @@ +saltext.noderings.utils.dns +=========================== + +.. automodule:: saltext.noderings.utils.dns + :members: diff --git a/docs/ref/utils/saltext.noderings.utils.firewall.rst b/docs/ref/utils/saltext.noderings.utils.firewall.rst new file mode 100644 index 0000000..8705214 --- /dev/null +++ b/docs/ref/utils/saltext.noderings.utils.firewall.rst @@ -0,0 +1,5 @@ +saltext.noderings.utils.firewall +================================ + +.. automodule:: saltext.noderings.utils.firewall + :members: diff --git a/docs/ref/utils/saltext.noderings.utils.marketplace.rst b/docs/ref/utils/saltext.noderings.utils.marketplace.rst new file mode 100644 index 0000000..d4582d6 --- /dev/null +++ b/docs/ref/utils/saltext.noderings.utils.marketplace.rst @@ -0,0 +1,5 @@ +saltext.noderings.utils.marketplace +=================================== + +.. automodule:: saltext.noderings.utils.marketplace + :members: 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 old mode 100644 new mode 100755 index d2209c5..ea1c5dc --- a/noxfile.py +++ b/noxfile.py @@ -1,53 +1,530 @@ -""" -Development sessions, as in the salt-extension copier template. - - nox -e tests -- tests/unit # unit tests, no account needed - nox -e tests -- tests/functional # live tests, need NODERINGS_TOKEN - nox -e lint lint-tests docs -""" - +import datetime +import json import os +import platform +import shutil +import sys +import tempfile +from importlib import metadata +from pathlib import Path import nox +from nox.command import CommandFailed +from nox.virtualenv import VirtualEnv -nox.options.default_venv_backend = "uv|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 -nox.options.sessions = ["tests", "lint", "lint-tests"] +# Speed up all sessions by using uv if possible +if tuple(map(int, metadata.version("nox").split("."))) >= (2024, 3): + nox.options.default_venv_backend = "uv|virtualenv" + +# Python versions to test against +PYTHON_VERSIONS = ("3", "3.11", "3.12", "3.13", "3.14") +# 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 = os.environ.get("SKIP_REQUIREMENTS_INSTALL", "0") == "1" +EXTRA_REQUIREMENTS_INSTALL = os.environ.get("EXTRA_REQUIREMENTS_INSTALL") + +COVERAGE_REQUIREMENT = os.environ.get("COVERAGE_REQUIREMENT") or "coverage==7.14.3" +SALT_REQUIREMENT = os.environ.get("SALT_REQUIREMENT") or "salt>=3006" +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 = 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, 11): + session.error("Only Python >= 3.11 is supported") + return f"py{version_info[0]}.{version_info[1]}" + + +def _install_requirements( # pylint: disable=unused-argument + session, + *passed_requirements, + install_coverage_requirements=True, + install_test_requirements=True, + install_source=False, + install_salt=True, + install_extras=None, +): + install_extras = install_extras or [] + no_progress = "--progress-bar=off" + if isinstance(session._runner.venv, VirtualEnv) and session._runner.venv.venv_backend == "uv": + no_progress = "--no-progress" + if SKIP_REQUIREMENTS_INSTALL is False: + # Always have the wheel package installed + session.install(no_progress, "wheel", silent=PIP_INSTALL_SILENT) + if install_coverage_requirements: + session.install(no_progress, COVERAGE_REQUIREMENT, silent=PIP_INSTALL_SILENT) + + if install_salt: + # Salt does not publish wheels and setuptools 75.6.0+ breaks requirements inclusion during builds, + # so we need to constrain setuptools in the build environment. uv reads this from + # pyproject.toml, but pip has no equivalent behavior. + # We need delete=False for Windows. delete_on_close would work, but is Python 3.12+ only. + with tempfile.NamedTemporaryFile(delete=False) as constraints_file: + setuptools_constraint = "setuptools<75.6.0" + constraints_file.write(setuptools_constraint.encode()) + env = { + "PIP_CONSTRAINT": constraints_file.name, + } + try: + session.install(no_progress, SALT_REQUIREMENT, silent=PIP_INSTALL_SILENT, env=env) + finally: + os.unlink(constraints_file.name) + + 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 = [no_progress] + install_command += [req.strip() for req in EXTRA_REQUIREMENTS_INSTALL.split()] + session.install(*install_command, silent=PIP_INSTALL_SILENT) -SALT_REQUIREMENT = os.environ.get("SALT_REQUIREMENT", "salt>=3006") -PYTHON_VERSIONS = ["3.11", "3.12", "3.13"] + 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): - """Run the tests. Pass a path to pick a suite; live tests skip without NODERINGS_TOKEN.""" - session.install(SALT_REQUIREMENT, "-e", ".[tests]") - args = session.posargs or ["tests/unit"] - session.run("pytest", "-ra", *args, env={"PYTHONPATH": "."}) + _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: + 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/noderings/*", + ) + # Generate report for tests code coverage + session.run( + "coverage", + "xml", + "-o", + str(COVERAGE_REPORT_TESTS), + "--omit=src/saltext/noderings/*", + "--include=tests/*", + ) + try: + session.run("coverage", "report", "--show-missing", "--include=src/saltext/noderings/*") + # 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/noderings/*,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=["lint", "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} -@nox.session(python="3.12") + 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 + try: + # nox >= 2024.03.02 + # pylint: disable=unexpected-keyword-arg + venv = VirtualEnv( + os.environ["VIRTUAL_ENV"], + interpreter=session._runner.func.python, + reuse_existing=True, + venv_backend="venv", + ) + except TypeError: + # nox < 2024.03.02 + # pylint: disable=unexpected-keyword-arg + venv = VirtualEnv( + os.environ["VIRTUAL_ENV"], + interpreter=session._runner.func.python, + reuse_existing=True, + venv=True, + ) + session._runner.venv = venv + _lint(session, rcfile, flags, paths, tee_output=False) + + +@nox.session(python="3") def lint(session): - """Lint the extension with the template's pylint configuration.""" - session.install(SALT_REQUIREMENT, "-e", ".[lint,tests]") - session.run("pylint", "--rcfile=.pylintrc", "src/saltext/noderings") + """ + 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(name="lint-tests", python="3.12") +@nox.session(python="3", name="lint-tests") def lint_tests(session): - """Lint the tests.""" - session.install(SALT_REQUIREMENT, "-e", ".[lint,tests]") - session.run( - "pylint", - "--rcfile=.pylintrc", - "--disable=redefined-outer-name,unused-argument,import-outside-toplevel", - "tests", - ) + """ + Run PyLint against the test suite. Set PYLINT_REPORT to a path to capture output. + """ + flags = [ + "--disable=I,redefined-outer-name,no-member,missing-module-docstring,missing-function-docstring,missing-class-docstring,attribute-defined-outside-init,inconsistent-return-statements,too-few-public-methods,too-many-public-methods", + ] + 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,no-member,missing-module-docstring,missing-function-docstring,missing-class-docstring,attribute-defined-outside-init,inconsistent-return-statements,too-few-public-methods,too-many-public-methods", + ] + if session.posargs: + paths = session.posargs + else: + paths = ["tests/"] + _lint_pre_commit(session, ".pylintrc", flags, paths) + + +def _get_docs_env(session): + env = {} + if not os.getenv("PYENCHANT_LIBRARY_PATH"): + if sys.platform == "darwin" and platform.processor() == "arm": + try: + # Ensure docs build works on Apple Silicon, where the default + # Homebrew lib path is not autodiscovered. + # Needs `brew install enchant`. + env["PYENCHANT_LIBRARY_PATH"] = str( + next(Path("/opt/homebrew/lib").glob("libenchant*.dylib")) + ) + except StopIteration: + session.warn( + "Failed to autodiscover enchant library. Ensure it's installed (e.g. brew install enchant). " + "If it's installed, set the PYENCHANT_LIBRARY_PATH environment variable to its dylib path." + ) + return env -@nox.session(python="3.12") +@nox.session(python="3") def docs(session): - """Build the HTML documentation into docs/_build/html.""" - session.install(SALT_REQUIREMENT, "-e", ".[docs]") - session.run("sphinx-build", "-W", "-b", "html", "docs", "docs/_build/html") + """ + Build Docs + """ + _install_requirements( + session, + install_coverage_requirements=False, + install_test_requirements=False, + install_source=True, + install_extras=["docs"], + ) + os.chdir("docs/") + env = _get_docs_env(session) + session.run("make", "clean", external=True) + session.run("make", "linkcheck", "SPHINXOPTS=-W", external=True, env=env) + session.run("make", "coverage", "SPHINXOPTS=-W", external=True, env=env) + 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, env=env) + os.chdir(str(REPO_ROOT)) + + +@nox.session(name="docs-dev", python="3") +def docs_dev(session): + """ + 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"], + ) + + build_dir = Path("docs", "_build", "html") + + # Allow specifying sphinx-autobuild options, like --host. + args = ["--watch", "."] + session.posargs + if not any(arg.startswith("--host") for arg in args): + # If the user is overriding the host to something other than localhost, + # it's likely they are rendering on a remote/headless system and don't + # want the browser to open. + args.append("--open-browser") + args += ["docs", str(build_dir)] + + if build_dir.exists(): + shutil.rmtree(build_dir) + + env = _get_docs_env(session) + session.run("sphinx-autobuild", *args, env=env) + + +@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)) diff --git a/pyproject.toml b/pyproject.toml index 1964211..472e7df 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,9 +60,19 @@ dev = [ "nox[uv]>=2024.3,!=2025.05.01", "pre-commit>=2.21.0", ] +# These dependencies are used in automations. It can be helpful +# to have them installed in the dev venv, e.g. for editor integration. +# When initializing the dev env using the included automation, pass +# `--extras` to install them automatically. +dev_extra = [ + "black==26.5.1", + "isort==8.0.1", + "coverage==7.14.3", +] docs = [ "sphinx", "sphinx-prompt", + "sphinxcontrib-spelling", "sphinx-copybutton", "towncrier==26.9.0", "sphinxcontrib-towncrier", @@ -70,6 +80,7 @@ docs = [ "furo", "sphinx-inline-tabs", ] +docsauto = ["sphinx-autobuild"] lint = [ "pylint==4.1.4", ] @@ -84,6 +95,7 @@ tests = [ [tool.uv] # Salt's legacy setup.py requires old setuptools. +# Since uv 0.6.0, it does not fall back to reading requirements from egg-info. build-constraint-dependencies = ["setuptools<69"] [tool.setuptools] @@ -96,11 +108,19 @@ where = ["src"] exclude = ["tests"] [tool.distutils.bdist_wheel] +# Use this option if your package is pure-python universal = 1 +[tool.distutils.sdist] +owner = "root" +group = "root" + +[tool.build_sphinx] +source_dir = "docs" +build_dir = "build/sphinx" + [tool.black] line-length = 100 -target-version = ["py311"] [tool.isort] force_single_line = true @@ -153,16 +173,31 @@ directory = "security" name = "Security" showcontent = true -# Not used for linting (pylint is), but helpful for editors running ruff. +# While we currently don't use ruff for linting, it's helpful to include +# these settings in case a user has setup ruff in their editor environment. [tool.ruff] -line-length = 100 builtins = [ "__opts__", "__salt__", "__pillar__", "__grains__", "__context__", - "__utils__", + "__runner__", + "__ret__", + "__env__", + "__low__", "__states__", + "__utils__", + "__lowstate__", + "__running__", "__active_provider_name__", + "__master_opts__", + "__jid_event__", + "__instance_id__", + "__salt_system_encoding__", + "__proxy__", + "__serializers__", + "__reg__", + "__executors__", + "__events__", ] diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..f2d91fc --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "release-type": "python", + "include-v-in-tag": true, + "include-component-in-tag": false, + "bump-minor-pre-major": true, + "bump-patch-for-minor-pre-major": false, + "draft": true, + "force-tag-creation": true, + "bootstrap-sha": "a521b6d30b39d97d05a2378d0edd4364cad1277d", + "pull-request-title-pattern": "chore: release ${version}", + "changelog-sections": [ + { "type": "feat", "section": "Features" }, + { "type": "fix", "section": "Bug Fixes" }, + { "type": "perf", "section": "Performance" }, + { "type": "deps", "section": "Dependencies" }, + { "type": "docs", "section": "Documentation" }, + { "type": "refactor", "section": "Other", "hidden": true }, + { "type": "chore", "section": "Other", "hidden": true }, + { "type": "ci", "section": "Other", "hidden": true }, + { "type": "test", "section": "Other", "hidden": true }, + { "type": "build", "section": "Other", "hidden": true } + ], + "packages": { + ".": { + "package-name": "saltext.noderings", + "changelog-path": "CHANGELOG.md" + } + } +} diff --git a/setup.py b/setup.py index f999679..56e4bd4 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,4 @@ -# pylint: disable=missing-module-docstring +# pylint: disable=missing-module-docstring,import-error import setuptools if __name__ == "__main__": diff --git a/tests/unit/utils/test_firewall.py b/tests/unit/utils/test_firewall.py index 3a9afb8..71e6d4d 100644 --- a/tests/unit/utils/test_firewall.py +++ b/tests/unit/utils/test_firewall.py @@ -27,7 +27,7 @@ def __init__(self, bodies): self.n = len(bodies) self.ops = [] - def list_firewall_rules(self, rs): + def list_firewall_rules(self, rs): # pylint: disable=unused-argument return [dict(r, position=i) for i, r in enumerate(self.rules)] def update_firewall_rule(self, rid, body): @@ -38,14 +38,16 @@ def delete_firewall_rule(self, rid): self.ops.append(("delete", rid)) self.rules = [r for r in self.rules if r["id"] != rid] - def create_firewall_rule(self, rs, body): + def create_firewall_rule(self, rs, body): # pylint: disable=unused-argument rid = f"r{self.n}" self.n += 1 self.ops.append(("create", rid)) self.rules.insert(0, {"id": rid, "rule": body}) return {"id": rid} - def move_firewall_rule(self, rid, target, position="FIREWALL_RULE_POSITION_BEFORE"): + def move_firewall_rule( # pylint: disable=unused-argument + self, rid, target, position="FIREWALL_RULE_POSITION_BEFORE" + ): self.ops.append(("move", rid)) r = next(x for x in self.rules if x["id"] == rid) self.rules.remove(r) diff --git a/tests/unit/utils/test_marketplace.py b/tests/unit/utils/test_marketplace.py index 3fdd823..4218a9a 100644 --- a/tests/unit/utils/test_marketplace.py +++ b/tests/unit/utils/test_marketplace.py @@ -24,7 +24,7 @@ class FakeMarket: def __init__(self, providers): self.providers = providers - def list_providers(self, code, country, city, billing, ipv6): + def list_providers(self, code, country, city, billing, ipv6): # pylint: disable=unused-argument return self.providers diff --git a/tools/helpers/__init__.py b/tools/helpers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/helpers/cmd.py b/tools/helpers/cmd.py new file mode 100644 index 0000000..25257df --- /dev/null +++ b/tools/helpers/cmd.py @@ -0,0 +1,297 @@ +""" +Polyfill for very basic ``plumbum`` functionality, no external libs required. +Makes scripts that call a lot of CLI commands much more pleasant to write. +""" + +import os +import platform +import shlex +import shutil +import subprocess +from contextlib import contextmanager +from dataclasses import dataclass +from dataclasses import field +from pathlib import Path + + +class CommandNotFound(RuntimeError): + """ + Raised when a command cannot be found in $PATH + """ + + +@dataclass(frozen=True) +class ProcessResult: + """ + The full process result, returned by ``.run`` methods. + The ``__call__`` ones just return stdout. + """ + + retcode: int + stdout: str | bytes + stderr: str | bytes + argv: tuple + + def check(self, retcode=None): + """ + Check if the retcode is expected. retcode can be a list. + """ + if retcode is None: + expected = [0] + elif not isinstance(retcode, (list, tuple)): + expected = [retcode] + if self.retcode not in expected: + raise ProcessExecutionError(self.argv, self.retcode, self.stdout, self.stderr) + + def __str__(self): + msg = [ + "Process execution result:", + f"Command: {shlex.join(self.argv)}", + f"Retcode: {self.retcode}", + "Stdout: |", + ] + msg += [" " * 10 + "| " + line for line in str(self.stdout).splitlines()] + msg.append("Stderr: |") + msg += [" " * 10 + "| " + line for line in str(self.stderr).splitlines()] + return "\n".join(msg) + + +class ProcessExecutionError(OSError): + """ + Raised by ProcessResult.check when an unexpected retcode was returned. + """ + + def __init__(self, argv, retcode, stdout, stderr): + self.argv = argv + self.retcode = retcode + if isinstance(stdout, bytes): + stdout = ascii(stdout) + if isinstance(stderr, bytes): + stderr = ascii(stderr) + self.stdout = stdout + self.stderr = stderr + + def __str__(self): + msg = [ + "Process finished with unexpected exit code", + f"Retcode: {self.retcode}", + f"Command: {shlex.join(self.argv)}", + "Stdout: |", + ] + msg += [" " * 10 + "| " + line for line in str(self.stdout).splitlines()] + msg.append("Stderr: |") + msg += [" " * 10 + "| " + line for line in str(self.stderr).splitlines()] + return "\n".join(msg) + + +class Local: + """ + Glue for command environment defaults. + Should be treated as a singleton. + + Example: + + local = Local() + + some_cmd = local["some_cmd"] + with local.cwd(some_path), local.env(FOO="bar"): + some_cmd("baz") + + # A changed $PATH requires to rediscover commands. + with local.prepend_path(important_path): + local["other_cmd"]() + with local.venv(venv_path): + local["python"]("-m", "pip", "install", "salt") + + """ + + def __init__(self): + # Explicitly cast values to strings to avoid problems on Windows + self._env = {k: str(v) for k, v in os.environ.items()} + + def __getitem__(self, exe): + """ + Return a LocalCommand in this context. + """ + return LocalCommand(exe, _local=self) + + @property + def path(self): + """ + List of paths in the context's $PATH. + """ + return self._env.get("PATH", "").split(os.pathsep) + + def which(self, cmd): + """ + Find `cmd` in $PATH. + """ + res = shutil.which(cmd) + if not res: + raise CommandNotFound(cmd) + return Path(res) + + @contextmanager + def cwd(self, path): + """ + Set the default current working directory for commands inside this context. + """ + prev = Path(os.getcwd()) + new = prev / path + os.cwd(new) + try: + yield + finally: + os.cwd(prev) + + @contextmanager + def env(self, **kwargs): + """ + Override default env vars (sourced from the current process' environment) + for commands inside this context. + """ + prev = self._env.copy() + self._env.update((k, str(v)) for k, v in kwargs.items()) + try: + yield + finally: + self._env = prev + + @contextmanager + def path_prepend(self, *args): + """ + Prepend paths to $PATH for commands inside this context. + + Note: If you have saved a reference to an already requested command, + its $PATH will be updated, but it might not be the command + that would have been returned by a new request. + """ + new_path = [str(arg) for arg in args] + self.path + with self.env(PATH=os.pathsep.join(new_path)): + yield + + @contextmanager + def venv(self, venv_dir): + """ + Enter a Python virtual environment. Effectively prepends its bin dir + to $PATH and sets ``VIRTUAL_ENV``. + """ + venv_dir = Path(venv_dir) + if not venv_dir.is_dir() or not (venv_dir / "pyvenv.cfg").exists(): + raise ValueError(f"Not a virtual environment: {venv_dir}") + venv_bin_dir = venv_dir / "bin" + if platform.system() == "Windows": + venv_bin_dir = venv_dir / "Scripts" + with self.path_prepend(venv_bin_dir), self.env(VIRTUAL_ENV=str(venv_dir)): + yield + + +@dataclass(frozen=True) +class Executable: + """ + Utility class used to avoid repeated command lookups. + """ + + _exe: str + + def __str__(self): + return self._exe + + def __repr__(self): + return f"Executable <{self._exe}>" + + +@dataclass(frozen=True) +class Command: + """ + A command object, can be instantiated directly. Does not follow ``Local``. + """ + + exe: Executable | str + args: tuple[str, ...] = () + + def __post_init__(self): + if not isinstance(self.exe, Executable): + if not (full_exe := self._which(self.exe)): + raise CommandNotFound(self.exe) + object.__setattr__(self, "exe", Executable(full_exe)) + + def _which(self, exe): + return shutil.which(exe) + + def _get_env(self, overrides=None): + base = {k: str(v) for k, v in os.environ.items()} + base.update(overrides or {}) + return base + + def __getitem__(self, arg_or_args): + """ + Returns a subcommand with bound parameters. + + Example: + + git = Command("git")["-c", "commit.gpgsign=0"] + # ... + git("add", ".") + git("commit", "-m", "testcommit") + + """ + if not isinstance(arg_or_args, tuple): + arg_or_args = (arg_or_args,) + return type(self)(self.exe, tuple(*self.args, *arg_or_args), _local=self._local) + + def __call__(self, *args, **kwargs): + """ + Run this command and return stdout. + """ + return self.run(*args, **kwargs).stdout + + def __str__(self): + return shlex.join([self.exe] + list(self.args)) + + def __repr__(self): + return f"Command<{self.exe}, {self.args!r}>" + + def run(self, *args, check=True, env=None, **kwargs): + """ + Run this command and return the full output. + """ + kwargs.setdefault("stdout", subprocess.PIPE) + kwargs.setdefault("stderr", subprocess.PIPE) + kwargs.setdefault("text", True) + argv = [str(self.exe), *self.args, *args] + proc = subprocess.run(argv, check=False, env=self._get_env(env), **kwargs) + ret = ProcessResult( + retcode=proc.returncode, + stdout=proc.stdout, + stderr=proc.stderr, + argv=argv, + ) + if check: + ret.check() + return ret + + +# Should be imported from here. +local = Local() + + +@dataclass(frozen=True) +class LocalCommand(Command): + """ + Command returned by Local()["some_command"]. Follows local contexts. + """ + + _local: Local = field(kw_only=True, repr=False, default=local) + + def _which(self, exe): + return shutil.which(exe, path=self._local._env.get("PATH", "")) + + def _get_env(self, overrides=None): + base = self._local._env.copy() + base.update(overrides or {}) + return base + + +# We must assume git is installed +git = local["git"] diff --git a/tools/helpers/copier.py b/tools/helpers/copier.py new file mode 100644 index 0000000..65ab866 --- /dev/null +++ b/tools/helpers/copier.py @@ -0,0 +1,114 @@ +import os +import sys +from functools import wraps +from pathlib import Path + +from . import prompt + +try: + # In case we have it, use it. + # It's always installed in the Copier environment, so if you ensure you + # call this via ``copier_python``, this will work. + import yaml +except ImportError: + yaml = None + + +if os.environ.get("STAGE"): + # If we're running inside a Copier task/migration, cwd is the target dir. + # We cannot use __file__ because this file is imported from the template clone. + COPIER_ANSWERS = Path(".copier-answers.yml").resolve() +else: + COPIER_ANSWERS = (Path(__file__).parent.parent.parent / ".copier-answers.yml").resolve() + + +if yaml is not None: + + def represent_str(dumper, data): + """ + Represent multiline strings using "|" + """ + if len(data.splitlines()) > 1: + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|") + return dumper.represent_scalar("tag:yaml.org,2002:str", data) + + class OpinionatedYamlDumper(yaml.SafeDumper): + """ + Indent lists by two spaces + """ + + def increase_indent(self, flow=False, indentless=False): + return super().increase_indent(flow=flow, indentless=False) + + OpinionatedYamlDumper.add_representer(str, represent_str) + + +def _needs_answers(func): + @wraps(func) + def _wrapper(*args, **kwargs): + if not COPIER_ANSWERS.exists(): + raise RuntimeError(f"Missing answers file at {COPIER_ANSWERS}") + return func(*args, **kwargs) + + return _wrapper + + +@_needs_answers +def load_answers(): + """ + Load the complete answers file. Depends on PyYAML. + """ + if not yaml: + raise RuntimeError("Missing pyyaml in environment") + with open(COPIER_ANSWERS, encoding="utf-8") as f: + return yaml.safe_load(f) + + +@_needs_answers +def dump_answers(answers): + """ + Write the complete answers file. Depends on PyYAML. + Intended for answers migrations. + """ + if not yaml: + raise RuntimeError("Missing pyyaml in environment") + with open(COPIER_ANSWERS, "w", encoding="utf-8") as f: + yaml.dump( + answers, + f, + Dumper=OpinionatedYamlDumper, + indent=0, + default_flow_style=False, + canonical=False, + ) + + +@_needs_answers +def discover_project_name(): + """ + Specifically discover project name. No dependency. + """ + for line in COPIER_ANSWERS.read_text().splitlines(): + if line.startswith("project_name"): + return line.split(":", maxsplit=1)[1].strip() + raise RuntimeError("Failed discovering project name") + + +def finish_task(msg, success, err_exit=False, extra=None): + """ + Print final conclusion of task (migration) run in Copier. + + We usually want to exit with 0, even when something fails, + because a failing task/migration should not crash Copier. + """ + prompt.pprint("\n", stream=sys.stderr) + if success: + prompt.pprint(f"\n ✓ {msg}", bold=True, bg=prompt.DARKGREEN, stream=sys.stderr) + elif success is None: + prompt.pprint( + f"\n ✓ {msg}", bold=True, fg=prompt.YELLOW, bg=prompt.DARKGREEN, stream=sys.stderr + ) + success = True + else: + prompt.warn(f" ✗ {msg}", extra) + raise SystemExit(int(not success and err_exit)) diff --git a/tools/helpers/git.py b/tools/helpers/git.py new file mode 100644 index 0000000..5336031 --- /dev/null +++ b/tools/helpers/git.py @@ -0,0 +1,30 @@ +from pathlib import Path + +from .cmd import git + + +def ensure_git(): + """ + Ensure the repository has been initialized. + """ + if Path(".git").is_dir(): + return + git("init", "--initial-branch", "main") + + +def list_untracked(): + """ + List untracked files. + """ + for path in git("ls-files", "-z", "-o", "--exclude-standard").split("\x00"): + if path: + yield path + + +def list_conflicted(): + """ + List files with merge conflicts. + """ + for path in git("diff", "-z", "--name-only", "--diff-filter=U", "--relative").split("\x00"): + if path: + yield path diff --git a/tools/helpers/pre_commit.py b/tools/helpers/pre_commit.py new file mode 100644 index 0000000..95cb474 --- /dev/null +++ b/tools/helpers/pre_commit.py @@ -0,0 +1,115 @@ +import re + +from . import prompt +from .cmd import ProcessExecutionError +from .cmd import git +from .cmd import local +from .git import list_untracked + +PRE_COMMIT_TEST_REGEX = re.compile( + r"^(?P[^\n]+?)\.{4,}.*(?PFailed|Passed|Skipped)$" +) +NON_IDEMPOTENT_HOOKS = ( + "trim trailing whitespace", + "mixed line ending", + "fix end of files", + "Remove Python Import Header Comments", + "Check rST doc files exist for modules/states", + "Salt extensions docstrings auto-fixes", + "Rewrite the test suite", + "Rewrite Code to be Py3.", + "isort", + "black", + "blacken-docs", +) + + +def parse_pre_commit(data): + """ + Parse pre-commit output into a list of passing hooks and a mapping of + failing hooks to their output. + """ + passing = [] + failing = {} + cur = None + for line in data.splitlines(): + if match := PRE_COMMIT_TEST_REGEX.match(line): + cur = None + if match.group("resolution") != "Failed": + passing.append(match.group("test")) + continue + cur = match.group("test") + failing[cur] = [] + continue + try: + failing[cur].append(line) + except KeyError: + # in case the parsing logic fails, let's not crash everything + continue + return passing, {test: "\n".join(output).strip() for test, output in failing.items()} + + +def check_pre_commit_rerun(data): + """ + Check if we can expect failing hooks to turn green during a rerun. + """ + _, failing = parse_pre_commit(data) + for hook in failing: + if hook.startswith(NON_IDEMPOTENT_HOOKS): + return True + return False + + +def run_pre_commit(venv, retries=2): + """ + Run pre-commit in a loop until it passes, there is no chance of + autoformatting to make it pass or a maximum number of runs is reached. + + Usually, a maximum of two runs is necessary (if a hook reformats the + output of another later one again). + """ + new_files = set() + + def _run_pre_commit_loop(retries_left): + untracked_files = set(map(str, list_untracked())) + nonlocal new_files + new_files = new_files.union(untracked_files) + # Ensure pre-commit runs on all paths. + # We don't want to git add . because this removes merge conflicts + git("add", "--intent-to-add", *untracked_files) + with local.venv(venv): + try: + local["python"]("-m", "pre_commit", "run", "--all-files") + except ProcessExecutionError as err: + if retries_left > 0 and check_pre_commit_rerun(err.stdout): + return _run_pre_commit_loop(retries_left - 1) + raise + + prompt.status( + "Running pre-commit hooks against all files. This can take a minute, please be patient" + ) + + try: + _run_pre_commit_loop(retries) + return True + except ProcessExecutionError as err: + _, failing = parse_pre_commit(err.stdout) + if failing: + msg = f"Please fix all ({len(failing)}) failing hooks" + else: + msg = f"Output: {err.stderr or err.stdout}" + prompt.warn(f"Pre-commit is failing. {msg}") + for i, failing_hook in enumerate(failing): + prompt.warn(f"✗ Failing hook ({i + 1}): {failing_hook}", failing[failing_hook]) + finally: + if new_files: + try: + # Check if there is at least one commit in the repo, + # otherwise git restore --staged fails. + git("rev-parse", "HEAD") + except ProcessExecutionError: + pass + else: + # Undo git add --intent-to-add to allow RenovateBot to detect new files correctly + git("restore", "--staged", *new_files) + return False diff --git a/tools/helpers/prompt.py b/tools/helpers/prompt.py new file mode 100644 index 0000000..458266a --- /dev/null +++ b/tools/helpers/prompt.py @@ -0,0 +1,54 @@ +import os +import platform +import sys + +DARKGREEN = (0, 100, 0) +DARKRED = (139, 0, 0) +YELLOW = (255, 255, 0) + + +def ensure_utf8(): + """ + On Windows, ensure stdout/stderr output uses UTF-8 encoding. + """ + if platform.system() != "Windows": + return + for stream in (sys.stdout, sys.stderr): + if stream.encoding != "utf-8": + stream.reconfigure(encoding="utf-8") + + +def pprint(msg, bold=False, fg=None, bg=None, stream=None, force_print=False): + """ + Ugly helper for printing a bit more fancy output. + Stand-in for questionary/prompt_toolkit. + """ + if not force_print and os.getenv("TOOLS_SILENT"): + return + out = "" + if bold: + out += "\033[1m" + if fg: + red, green, blue = fg + out += f"\033[38;2;{red};{green};{blue}m" + if bg: + red, green, blue = bg + out += f"\033[48;2;{red};{green};{blue}m" + out += msg + if bold or fg or bg: + out += "\033[0m" + print(out, file=stream or sys.stdout) + + +def status(msg, message=None): + out = f"\n → {msg}" + pprint(out, bold=True, fg=DARKGREEN, stream=sys.stderr) + if message: + pprint(message, stream=sys.stderr) + + +def warn(header, message=None): + out = f"\n{header}" + pprint(out, bold=True, bg=DARKRED, stream=sys.stderr, force_print=True) + if message: + pprint(message, stream=sys.stderr, force_print=True) diff --git a/tools/helpers/venv.py b/tools/helpers/venv.py new file mode 100644 index 0000000..2434ff7 --- /dev/null +++ b/tools/helpers/venv.py @@ -0,0 +1,128 @@ +import tempfile +from pathlib import Path +from shutil import rmtree + +from . import prompt +from .cmd import CommandNotFound +from .cmd import local +from .copier import discover_project_name + +# Should follow the version used for relenv packages, see +# https://github.com/saltstack/salt/blob/master/cicd/shared-gh-workflows-context.yml +RECOMMENDED_PYVER = "3.14" +# For discovery of existing virtual environment, descending priority. +VENV_DIRS = ( + ".venv", + "venv", + ".env", + "env", +) + + +def discover_uv(): + try: + return local["uv"] + except CommandNotFound: + pass + + +def is_venv(path): + if (venv_path := Path(path)).is_dir and (venv_path / "pyvenv.cfg").exists(): + return venv_path + return False + + +def discover_venv(project_root="."): + base = Path(project_root).resolve() + for name in VENV_DIRS: + if found := is_venv(base / name): + return found + raise RuntimeError(f"No venv found in {base}") + + +def venv_pyver(venv): + for line in (venv / "pyvenv.cfg").read_text().splitlines(): + if line.startswith("version =") or line.startswith("version_info ="): + pyver = line.split(" = ")[1].split(".") + return f"{pyver[0]}.{pyver[1]}" + + +def create_venv(project_root=".", directory=None): + base = Path(project_root).resolve() + venv = (base / (directory or VENV_DIRS[0])).resolve() + if is_venv(venv): + raise RuntimeError(f"Venv at {venv} already exists") + prompt.status(f"Creating virtual environment at {venv}") + uv = discover_uv() + if uv is not None: + prompt.status("Found `uv`. Creating venv") + uv( + "venv", + # Install pip/setuptools/wheel for compatibility + "--seed", + "--python", + RECOMMENDED_PYVER, + f"--prompt=saltext-{discover_project_name()}", + ) + else: + prompt.status("Did not find `uv`. Falling back to `venv`") + try: + python = local[f"python{RECOMMENDED_PYVER}"] + except CommandNotFound: + python = local["python3"] + version = python("--version").split(" ")[1] + if not version.startswith(RECOMMENDED_PYVER): + raise RuntimeError( + f"No `python{RECOMMENDED_PYVER}` executable found in $PATH, exiting" + ) + python("-m", "venv", VENV_DIRS[0], f"--prompt=saltext-{discover_project_name()}") + return venv + + +def ensure_project_venv(project_root=".", reinstall=True, install_extras=False): + exists = False + try: + venv = discover_venv(project_root) + prompt.status(f"Found existing virtual environment at {venv}") + + pyver = venv_pyver(venv) + if pyver != RECOMMENDED_PYVER: + prompt.status( + f"Existing venv has Python {pyver}, but recommended is {RECOMMENDED_PYVER}. Recreating." + ) + rmtree(venv) + raise RuntimeError("Existing venv does not use recommended Python version") + + exists = True + except RuntimeError: + venv = create_venv(project_root) + if not reinstall: + return venv + extras = ["dev", "tests", "docs"] + if install_extras: + extras.append("dev_extra") + prompt.status(("Reinstalling" if exists else "Installing") + " project and dependencies") + with local.venv(venv): + uv = discover_uv() + if uv is not None: + uv("pip", "install", "-e", f".[{','.join(extras)}]") + else: + try: + # We install uv into the virtualenv, so it might be available now. + # It speeds up this step a lot. + local["uv"]("pip", "install", "-e", f".[{','.join(extras)}]") + except CommandNotFound: + # Salt does not build correctly with setuptools >= 75.6.0. + # uv reads this constraint from pyproject.toml, but pip needs this workaround. + with tempfile.NamedTemporaryFile(delete=False) as constraints_file: + setuptools_constraint = "setuptools<75.6.0" + constraints_file.write(setuptools_constraint.encode()) + try: + with local.env(PIP_CONSTRAINT=constraints_file.name): + local["python"]("-m", "pip", "install", "-e", f".[{','.join(extras)}]") + finally: + Path(constraints_file.name).unlink() + if not exists or not (Path(project_root) / ".git" / "hooks" / "pre-commit").exists(): + prompt.status("Installing pre-commit hooks") + local["python"]("-m", "pre_commit", "install", "--install-hooks") + return venv diff --git a/tools/initialize.py b/tools/initialize.py new file mode 100644 index 0000000..1eca966 --- /dev/null +++ b/tools/initialize.py @@ -0,0 +1,26 @@ +import sys + +from helpers import prompt +from helpers.copier import finish_task +from helpers.git import ensure_git +from helpers.venv import ensure_project_venv + +if __name__ == "__main__": + args = sys.argv[1:] + try: + prompt.ensure_utf8() + ensure_git() + venv = ensure_project_venv(install_extras="--extras" in args) + except Exception as err: # pylint: disable=broad-except + finish_task( + f"Failed initializing environment: {err}", + False, + True, + extra=( + "No worries, just follow the manual steps documented here: " + "https://salt-extensions.github.io/salt-extension-copier/topics/creation.html#first-steps" + ), + ) + if "--print-venv" in args: + print(venv) + finish_task("Successfully initialized environment", True) diff --git a/tools/version.py b/tools/version.py new file mode 100644 index 0000000..d79b1f7 --- /dev/null +++ b/tools/version.py @@ -0,0 +1,92 @@ +""" +Very simple heuristic to generate the next version number +based on the current changelog news fragments. + +This looks for the most recent version by parsing the +CHANGELOG.md file and increments a specific part, +depending on the fragment types present and their contents. + +Major bumps are caused by: + * files named `.removed.md` + * files named `.breaking.md` + * files containing `BREAKING:` + +Minor bumps are caused by: + * files named `.added.md` + +Otherwise, only the patch version is bumped. +""" + +import re +import sys +from pathlib import Path + +PROJECT_ROOT = Path(".").resolve() +CHANGELOG_DIR = PROJECT_ROOT / "changelog" +CHANGELOG_FILE = PROJECT_ROOT / "CHANGELOG.md" + + +class Version: + def __init__(self, version): + match = re.search(r"v?(?P[0-9]+(?:\.[0-9]+)*)", version) + if not match: + raise ValueError(f"Invalid version: '{version}'") + self.release = tuple(int(i) for i in match.group("release").split(".")) + + @property + def major(self): + return self._ret(0) + + @property + def minor(self): + return self._ret(1) + + @property + def patch(self): + return self._ret(2) + + def __str__(self): + return ".".join(str(i) for i in self.release) + + def _ret(self, cnt): + try: + return self.release[cnt] + except IndexError: + return 0 + + +def last_release(): + for line in CHANGELOG_FILE.read_text(encoding="utf-8").splitlines(): + if line.startswith("## "): + return Version(line.split(" ")[1]) + return Version("0.0.0") + + +def get_next_version(last): + major = minor = False + + for fragment in CHANGELOG_DIR.glob("[!.]*"): + name = fragment.name.lower() + if ".added" in name: + minor = True + elif ".breaking" in name or ".removed" in name: + major = True + break + if "breaking:" in fragment.read_text(encoding="utf-8").lower(): + major = True + break + if major: + return Version(f"{last.major + 1}.0.0") + if minor: + return Version(f"{last.major}.{last.minor + 1}.0") + return Version(f"{last.major}.{last.minor}.{last.patch + 1}") + + +if __name__ == "__main__": + try: + if sys.argv[1] == "next": + print(get_next_version(last_release())) + raise SystemExit(0) + except IndexError: + pass + print(last_release())