diff --git a/.github/actions/run-pre-commit/action.yaml b/.github/actions/run-pre-commit/action.yaml new file mode 100644 index 000000000..c18a466a9 --- /dev/null +++ b/.github/actions/run-pre-commit/action.yaml @@ -0,0 +1,85 @@ +name: Run selected pre-commit hooks +description: Run formatting, validation, or unit-test hooks from the shared configuration +inputs: + category: + description: Hook category (formatting, validation, or tests) + required: true + from-ref: + description: Optional base revision for changed-file checks + default: "" + to-ref: + description: Optional head revision for changed-file checks + default: "" +runs: + using: composite + steps: + - name: Install pre-commit + shell: bash + run: python -m pip install pre-commit + + - name: Select and run hooks + shell: bash + env: + HOOK_CATEGORY: ${{ inputs.category }} + FROM_REF: ${{ inputs.from-ref }} + TO_REF: ${{ inputs.to-ref }} + run: | + config=$(mktemp "$RUNNER_TEMP/pre-commit.XXXXXX.yaml") + trap 'rm -f "$config"' EXIT + python - "$config" <<'PY' + import os + import sys + + import yaml + + formatting = { + "trailing-whitespace", "end-of-file-fixer", "mixed-line-ending", + "clang-format", "gersemi", "fix-header-guards", "jsonnet-format", + "markdownlint-cli2", "ruff", "ruff-format", "prettier", + } + tests = {"scripts-unit-tests"} + category = os.environ["HOOK_CATEGORY"] + if category not in {"formatting", "validation", "tests"}: + raise SystemExit(f"Unknown hook category: {category}") + with open(".pre-commit-config.yaml") as source: + config = yaml.safe_load(source) + configured = {hook["id"] for repo in config["repos"] for hook in repo["hooks"]} + missing = (formatting | tests) - configured + if missing: + raise SystemExit(f"Missing configured hooks: {sorted(missing)}") + selected = { + "formatting": formatting, + "validation": configured - formatting - tests, + "tests": tests, + }[category] + repos = [] + for repo in config["repos"]: + hooks = [hook for hook in repo["hooks"] if hook["id"] in selected] + for hook in hooks: + if hook["id"] == "mypy": + hook["args"] = [*hook.get("args", []), "."] + hook["pass_filenames"] = False + hook["always_run"] = True + elif hook["id"] == "scripts-unit-tests": + hook["additional_dependencies"] = [ + *hook.get("additional_dependencies", []), "pytest-cov", + ] + hook["args"] = [ + *hook.get("args", []), + "--cov=scripts", "--cov=ci", "--cov=.devcontainer", + "--cov-report=xml:coverage-scripts.xml", "--cov-report=term-missing", + ] + if hooks: + repos.append({**repo, "hooks": hooks}) + config["repos"] = repos + with open(sys.argv[1], "w") as destination: + yaml.safe_dump(config, destination) + PY + args=(--all-files) + if [[ -n "$FROM_REF" && -n "$TO_REF" ]]; then + args=(--from-ref "$FROM_REF" --to-ref "$TO_REF") + elif [[ -n "$FROM_REF" || -n "$TO_REF" ]]; then + echo "::error::Both from-ref and to-ref are required for changed-file checks" + exit 1 + fi + python -m pre_commit run --config "$config" "${args[@]}" --show-diff-on-failure diff --git a/.github/workflows/actionlint-check.yaml b/.github/workflows/actionlint-check.yaml index 870a5a4a0..80146a1a5 100644 --- a/.github/workflows/actionlint-check.yaml +++ b/.github/workflows/actionlint-check.yaml @@ -60,6 +60,8 @@ jobs: uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 with: include-globs: | + .pre-commit-config.yaml + .github/actionlint.yaml .github/workflows/**/*.yml .github/workflows/**/*.yaml .github/actions/**/*.yml @@ -93,21 +95,19 @@ jobs: needs.setup.outputs.repo }} persist-credentials: false - - name: Announce actionlint check - run: echo "➡️ Running actionlint check..." + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Install pre-commit + run: python -m pip install pre-commit - name: Run actionlint id: lint continue-on-error: true - env: - CHECKOUT_PATH: ${{ needs.setup.outputs.checkout_path }} - ACTIONLINT_IMAGE_URL: "rhysd/actionlint@sha256:7ef0d156288b43c3bd5ee96bac787a28aae53275e88e4f9476a64bc0c19195c9" # v1.7.12 - run: | - docker run --rm \ - -v "$GITHUB_WORKSPACE/${CHECKOUT_PATH}:/work" \ - -w /work \ - "${ACTIONLINT_IMAGE_URL}" \ - -config-file .github/actionlint.yaml + working-directory: ${{ needs.setup.outputs.checkout_path }} + run: python -m pre_commit run actionlint --all-files --show-diff-on-failure - name: Evaluate actionlint result if: always() && steps.lint.outcome != 'skipped' diff --git a/.github/workflows/clang-format-check.yaml b/.github/workflows/clang-format-check.yaml deleted file mode 100644 index e97bb69b5..000000000 --- a/.github/workflows/clang-format-check.yaml +++ /dev/null @@ -1,117 +0,0 @@ -name: Clang-Format Check -run-name: "${{ github.actor }} checking C++ code format" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: cpp - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - clang-format-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Announce clang-format check - run: echo "➡️ Running clang-format check..." - - - name: Run clang-format lint - id: lint - uses: DoozyX/clang-format-lint-action@bcb4eb2cb0d707ee4f3e5cc3b456eb075f12cf73 # v0.20 - with: - source: "./${{ needs.setup.outputs.checkout_path }}" - clangFormatVersion: 20 - extensions: cpp,hpp,cpp.in,hpp.in - continue-on-error: true - - - name: Evaluate clang-format result - if: always() && steps.lint.outcome != 'skipped' - env: - REPO: ${{ needs.setup.outputs.repo }} - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.lint.outcome }}" = 'success' ]; then - echo "✅ clang-format check passed." - else - echo "::error::clang-format check failed. Please review the output above for details." - echo "::error::Comment '@${REPO_NAME}bot format' on the PR to attempt auto-fix." - exit 1 - fi diff --git a/.github/workflows/clang-format-fix.yaml b/.github/workflows/clang-format-fix.yaml deleted file mode 100644 index 7cd320c42..000000000 --- a/.github/workflows/clang-format-fix.yaml +++ /dev/null @@ -1,124 +0,0 @@ -name: Clang-Format Fix -run-name: "${{ github.actor }} fixing C++ code format" - -"on": - issue_comment: - types: - - created - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_formatting.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_formatting.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_formatting.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_formatting.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_formatting.outputs.patch_name }} - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot clang-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_formatting: - runs-on: ubuntu-latest - name: Apply formatting - needs: setup - if: ${{ needs.setup.result == 'success' }} - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - uses: DoozyX/clang-format-lint-action@bcb4eb2cb0d707ee4f3e5cc3b456eb075f12cf73 # v0.20 - with: - source: "./${{ needs.setup.outputs.checkout_path }}" - clangFormatVersion: 20 - inplace: "True" - extensions: cpp,hpp,cpp.in,hpp.in - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: clang-format - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/cmake-format-check.yaml b/.github/workflows/cmake-format-check.yaml deleted file mode 100644 index 86028dcb8..000000000 --- a/.github/workflows/cmake-format-check.yaml +++ /dev/null @@ -1,119 +0,0 @@ -name: CMake Format Check -run-name: "${{ github.actor }} checking CMake format" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: cmake - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - cmake-format-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Install gersemi - run: uv tool install gersemi - - - name: Check CMake formatting - id: lint - env: - CHECKOUT_PATH: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "➡️ Checking CMake file formatting..." - gersemi --check "${CHECKOUT_PATH}" - continue-on-error: true - - - name: Evaluate CMake formatting result - if: always() && steps.lint.outcome != 'skipped' - env: - REPO: ${{ needs.setup.outputs.repo }} - # yamllint disable rule:line-length - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.lint.outcome }}" = 'success' ]; then - echo "✅ All CMake files are properly formatted." - else - echo "::error::Found files with formatting issues." - echo "::error::Run 'gersemi -i ' locally or comment '@${REPO_NAME}bot format' on the PR to auto-fix." - exit 1 - fi - # yamllint enable diff --git a/.github/workflows/cmake-format-fix.yaml b/.github/workflows/cmake-format-fix.yaml deleted file mode 100644 index 954ea0688..000000000 --- a/.github/workflows/cmake-format-fix.yaml +++ /dev/null @@ -1,130 +0,0 @@ -name: CMake Format Fix -run-name: "${{ github.actor }} fixing CMake format" - -"on": - issue_comment: - types: - - created - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_cmake_formatting.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_cmake_formatting.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_cmake_formatting.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_cmake_formatting.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_cmake_formatting.outputs.patch_name }} - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot cmake-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_cmake_formatting: - runs-on: ubuntu-latest - name: Apply CMake formatting - needs: setup - if: needs.setup.result == 'success' - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Install gersemi - run: uv tool install gersemi - - - name: Apply CMake formatting - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "Applying CMake formatting..." - gersemi -i . - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: cmake-format - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/format-all.yaml b/.github/workflows/format-all.yaml deleted file mode 100644 index eb924c761..000000000 --- a/.github/workflows/format-all.yaml +++ /dev/null @@ -1,128 +0,0 @@ -name: Format All -run-name: "${{ github.actor }} fixing all format issues" - -on: - issue_comment: - types: - - created - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - if: > - github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(fromJSON('["OWNER", - "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && startsWith(github.event.comment.body, - format('@{0}bot format', github.event.repository.name)) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - - clang-format: - needs: setup - uses: ./.github/workflows/clang-format-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - cmake-format: - needs: setup - uses: ./.github/workflows/cmake-format-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - header-guards: - needs: setup - uses: ./.github/workflows/header-guards-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - jsonnet-format: - needs: setup - uses: ./.github/workflows/jsonnet-format-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - markdown: - needs: setup - uses: ./.github/workflows/markdown-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - python: - needs: setup - uses: ./.github/workflows/python-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - yaml: - needs: setup - uses: ./.github/workflows/yaml-fix.yaml - with: - ref: ${{ needs.setup.outputs.ref }} - repo: ${{ needs.setup.outputs.repo }} - skip-comment: true - secrets: inherit - - combine-results: - needs: [setup, clang-format, cmake-format, header-guards, jsonnet-format, markdown, python, yaml] - if: always() && needs.setup.result == 'success' - runs-on: ubuntu-latest - steps: - - name: Collect results - id: collect - uses: Framework-R-D/action-collect-format-results@1e3eeee20808b0c8e754955f7633c38ff18a603d # v1 - with: - results-json: | - { - "clang-format": { "result": "${{ needs.clang-format.result }}", "changes": "${{ needs.clang-format.outputs.changes }}", "pushed": "${{ needs.clang-format.outputs.pushed }}", "sha": "${{ needs.clang-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.clang-format.outputs.patch_name }}" }, - "cmake-format": { "result": "${{ needs.cmake-format.result }}", "changes": "${{ needs.cmake-format.outputs.changes }}", "pushed": "${{ needs.cmake-format.outputs.pushed }}", "sha": "${{ needs.cmake-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.cmake-format.outputs.patch_name }}" }, - "header-guards": { "result": "${{ needs.header-guards.result }}", "changes": "${{ needs.header-guards.outputs.changes }}", "pushed": "${{ needs.header-guards.outputs.pushed }}", "sha": "${{ needs.header-guards.outputs.commit_sha_short }}", "patch_name": "${{ needs.header-guards.outputs.patch_name }}" }, - "jsonnetfmt": { "result": "${{ needs.jsonnet-format.result }}", "changes": "${{ needs.jsonnet-format.outputs.changes }}", "pushed": "${{ needs.jsonnet-format.outputs.pushed }}", "sha": "${{ needs.jsonnet-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.jsonnet-format.outputs.patch_name }}" }, - "markdownlint": { "result": "${{ needs.markdown.result }}", "changes": "${{ needs.markdown.outputs.changes }}", "pushed": "${{ needs.markdown.outputs.pushed }}", "sha": "${{ needs.markdown.outputs.commit_sha_short }}", "patch_name": "${{ needs.markdown.outputs.patch_name }}" }, - "ruff": { "result": "${{ needs.python.result }}", "changes": "${{ needs.python.outputs.changes }}", "pushed": "${{ needs.python.outputs.pushed }}", "sha": "${{ needs.python.outputs.commit_sha_short }}", "patch_name": "${{ needs.python.outputs.patch_name }}" }, - "YAML formatter": { "result": "${{ needs.yaml.result }}", "changes": "${{ needs.yaml.outputs.changes }}", "pushed": "${{ needs.yaml.outputs.pushed }}", "sha": "${{ needs.yaml.outputs.commit_sha_short }}", "patch_name": "${{ needs.yaml.outputs.patch_name }}" } - } - - - name: Post combined comment - uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3.0.1 - with: - message: ${{ steps.collect.outputs.message }} - - - name: Update PR comment reactions - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ steps.collect.outputs.has_failures == 'true' && 'failure' || 'success' }} - - - name: Fail on formatter failures - if: steps.collect.outputs.has_failures == 'true' - run: | - echo "One or more formatters failed, were canceled, or were skipped." - exit 1 diff --git a/.github/workflows/header-guards-check.yaml b/.github/workflows/header-guards-check.yaml deleted file mode 100644 index 7c0671fc7..000000000 --- a/.github/workflows/header-guards-check.yaml +++ /dev/null @@ -1,113 +0,0 @@ -name: Header Guards Check -run-name: "${{ github.actor }} checking header guards" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: cpp - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - header-guards-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Set up Python - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - - name: Check header guards - id: check - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - python3 scripts/fix_header_guards.py --check --root . phlex plugins form > check_output.txt 2>&1 || echo "has_issues=true" >> "$GITHUB_OUTPUT" - cat check_output.txt - - - name: Report results - if: always() && steps.check.outputs.has_issues == 'true' - env: - REPO: ${{ needs.setup.outputs.repo }} - run: | - REPO_NAME="${REPO##*/}" - echo "::error::Header guard check failed." - echo "::error::Comment '@${REPO_NAME}bot header-guards-fix' on the PR to auto-fix." - exit 1 diff --git a/.github/workflows/header-guards-fix.yaml b/.github/workflows/header-guards-fix.yaml deleted file mode 100644 index d3df10864..000000000 --- a/.github/workflows/header-guards-fix.yaml +++ /dev/null @@ -1,129 +0,0 @@ -name: Header Guards Fix -run-name: "${{ github.actor }} fixing header guards" - -"on": - issue_comment: - types: - - created - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_fixes.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_fixes.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_fixes.outputs.patch_name }} - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot header-guards-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_fixes: - runs-on: ubuntu-latest - name: Apply fixes - needs: setup - if: needs.setup.result == 'success' - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Set up Python - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version: "3.12" - - - name: Fix header guards - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "Fixing header guards..." - python3 scripts/fix_header_guards.py --root . phlex plugins form || true - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: header-guards - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/jsonnet-format-check.yaml b/.github/workflows/jsonnet-format-check.yaml deleted file mode 100644 index f04b17792..000000000 --- a/.github/workflows/jsonnet-format-check.yaml +++ /dev/null @@ -1,119 +0,0 @@ -name: Jsonnet Format Check -run-name: "${{ github.actor }} checking Jsonnet format" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: jsonnet - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - jsonnet-format-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - path: ${{ needs.setup.outputs.checkout_path }} - persist-credentials: false - - - name: Setup jsonnet - id: setup-jsonnet - uses: zendesk/setup-jsonnet@76fef91403b40b20e4344a88f6c06a85be4f97d4 # v17 - with: - version: v0.22.0 - github_token: ${{ github.token }} - - - name: Check Jsonnet formatting - id: lint - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - find . \( -name "*.jsonnet" -o -name "*.libsonnet" \) -print0 | xargs -0 -r -I {} \ - bash -c 'jsonnetfmt --test "{}" || (echo "FAILED: {}" && diff -u <(jsonnetfmt "{}") "{}" && exit 1)' - continue-on-error: true - - - name: Evaluate Jsonnet formatting result - if: always() && steps.lint.outcome != 'skipped' - env: - REPO: ${{ needs.setup.outputs.repo }} - # yamllint disable rule:line-length - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.lint.outcome }}" = 'success' ]; then - echo "✅ Jsonnet formatting check passed." - else - echo "::error::Jsonnet formatting issues found. Please review the output above for details." - echo "::error::Run 'jsonnetfmt -i ' locally or comment '@${REPO_NAME}bot format' on the PR to auto-fix." - exit 1 - fi - # yamllint enable diff --git a/.github/workflows/jsonnet-format-fix.yaml b/.github/workflows/jsonnet-format-fix.yaml deleted file mode 100644 index 82504b308..000000000 --- a/.github/workflows/jsonnet-format-fix.yaml +++ /dev/null @@ -1,134 +0,0 @@ -name: Jsonnet Format Fix -run-name: "${{ github.actor }} fixing Jsonnet format" - -"on": - issue_comment: - types: - - created - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_jsonnet_formatting.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_jsonnet_formatting.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_jsonnet_formatting.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_jsonnet_formatting.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_jsonnet_formatting.outputs.patch_name }} - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot jsonnet-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_jsonnet_formatting: - runs-on: ubuntu-latest - name: Apply Jsonnet formatting - needs: setup - if: needs.setup.result == 'success' - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Setup jsonnet - id: setup-jsonnet - uses: zendesk/setup-jsonnet@76fef91403b40b20e4344a88f6c06a85be4f97d4 # v17 - with: - version: v0.22.0 - github_token: ${{ github.token }} - - - name: Apply Jsonnet formatting - id: lint - env: - CHECKOUT_PATH: ${{ needs.setup.outputs.checkout_path }} - run: | - find "$CHECKOUT_PATH" \( -name '*.jsonnet' -o -name '*.libsonnet' \) -print0 | xargs -0 -r jsonnetfmt -i - continue-on-error: true - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: jsonnetfmt - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/markdown-check.yaml b/.github/workflows/markdown-check.yaml deleted file mode 100644 index 61aa73232..000000000 --- a/.github/workflows/markdown-check.yaml +++ /dev/null @@ -1,119 +0,0 @@ -name: Markdown Check -run-name: "${{ github.actor }} checking Markdown format" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: md - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - markdown-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Add problem matcher - uses: xt0rted/markdownlint-problem-matcher@1a5fabfb577370cfdf5af944d418e4be3ea06f27 # v3.0.0 - - - name: Run markdownlint - id: lint - uses: DavidAnson/markdownlint-cli2-action@696eb3f2509270d7b882d2aa68347bc676e7af34 # v25.0.0 - with: - globs: | - ${{ needs.setup.outputs.checkout_path }}/**/*.md - !${{ needs.setup.outputs.checkout_path }}/**/CHANGELOG.md - continue-on-error: true - - - name: Evaluate markdownlint result - if: always() && steps.lint.outcome != 'skipped' - env: - REPO: ${{ needs.setup.outputs.repo }} - # yamllint disable rule:line-length - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.lint.outcome }}" = "success" ]; then - echo "✅ Markdown formatting check passed." - else - echo "::error::Markdown formatting check failed." - echo "::error::Comment '@${REPO_NAME}bot format' or '@${REPO_NAME}bot markdown-fix' on the PR to auto-fix." - exit 1 - fi - # yamllint enable diff --git a/.github/workflows/markdown-fix.yaml b/.github/workflows/markdown-fix.yaml deleted file mode 100644 index 430f955a3..000000000 --- a/.github/workflows/markdown-fix.yaml +++ /dev/null @@ -1,136 +0,0 @@ -name: Markdown Fix -run-name: "${{ github.actor }} fixing Markdown format" - -"on": - issue_comment: - types: - - created - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_fixes.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_fixes.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_fixes.outputs.patch_name }} - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot markdown-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_fixes: - runs-on: ubuntu-latest - name: Apply fixes - needs: setup - if: needs.setup.result == 'success' - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Set up Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "26" - package-manager-cache: false - - - name: Install markdownlint-cli2 - run: | - npm update -g npm@^11.10.0 - npm config set min-release-age=3 --location=user - npm install -g markdownlint-cli2 - - - name: Run markdownlint-cli2 fix - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "Fixing Markdown format with markdownlint-cli2..." - markdownlint-cli2 --fix "**/*.md" "!**/CHANGELOG.md" || true - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: markdownlint - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/pre-commit-check.yaml b/.github/workflows/pre-commit-check.yaml new file mode 100644 index 000000000..f0a52eda0 --- /dev/null +++ b/.github/workflows/pre-commit-check.yaml @@ -0,0 +1,34 @@ +name: Formatting Check +run-name: "${{ github.actor }} checking formatting" + +permissions: + contents: read + pull-requests: read + +"on": + pull_request: + workflow_dispatch: + +jobs: + pre-commit: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Check formatting + uses: ./.github/actions/run-pre-commit + with: + category: formatting + from-ref: ${{ github.event.pull_request.base.sha }} + to-ref: ${{ github.event.pull_request.head.sha }} diff --git a/.github/workflows/pre-commit-fix.yaml b/.github/workflows/pre-commit-fix.yaml new file mode 100644 index 000000000..2ead3332a --- /dev/null +++ b/.github/workflows/pre-commit-fix.yaml @@ -0,0 +1,188 @@ +name: Formatting Fix +run-name: "${{ github.actor }} fixing formatting" + +"on": + issue_comment: + types: + - created + +permissions: + contents: read + +jobs: + setup: + runs-on: ubuntu-latest + name: Parse command + permissions: + contents: read + pull-requests: read + if: > + github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(fromJSON('["OWNER", + "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && ( + startsWith(github.event.comment.body, format('@{0}bot pre-commit-fix', github.event.repository.name)) || + startsWith(github.event.comment.body, format('@{0}bot format', github.event.repository.name)) + ) + outputs: + ref: ${{ steps.target.outputs.ref }} + repo: ${{ steps.target.outputs.repo }} + sha: ${{ steps.target.outputs.sha }} + trusted_sha: ${{ steps.target.outputs.trusted_sha }} + steps: + - name: Resolve immutable target + id: target + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: trustedBranch } = await github.rest.repos.getBranch({ + ...context.repo, branch: context.payload.repository.default_branch + }); + core.setOutput('trusted_sha', trustedBranch.commit.sha); + const { data: pr } = await github.rest.pulls.get({ + ...context.repo, pull_number: context.issue.number + }); + if (pr.state !== 'open' || !pr.head.repo) { + throw new Error('The PR must be open and its head repository must exist'); + } + core.setOutput('repo', pr.head.repo.full_name); + core.setOutput('ref', pr.head.ref); + core.setOutput('sha', pr.head.sha); + + apply_fixes: + runs-on: ubuntu-latest + name: Apply fixes + needs: setup + if: needs.setup.result == 'success' + # PR actions and hooks execute here, never with publishing credentials. + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.setup.outputs.sha }} + repository: ${{ needs.setup.outputs.repo }} + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Apply formatting + id: format + continue-on-error: true + uses: ./.github/actions/run-pre-commit + with: + category: formatting + + - name: Verify formatting + uses: ./.github/actions/run-pre-commit + with: + category: formatting + + - name: Export formatting patch + env: + TARGET_SHA: ${{ needs.setup.outputs.sha }} + run: | + git diff --binary --no-ext-diff --no-textconv "$TARGET_SHA" -- > "$RUNNER_TEMP/formatting.patch" + + - name: Upload formatting patch + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: formatting-${{ github.run_id }}-${{ github.run_attempt }}-${{ needs.setup.outputs.sha }} + path: ${{ runner.temp }}/formatting.patch + if-no-files-found: error + retention-days: 1 + + publish: + runs-on: ubuntu-latest + name: Publish validated fixes + needs: [setup, apply_fixes] + permissions: + contents: read + pull-requests: read + steps: + - name: Checkout trusted publishing code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.setup.outputs.trusted_sha }} + path: trusted + persist-credentials: false + + - name: Checkout exact target as data + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.setup.outputs.repo }} + ref: ${{ needs.setup.outputs.sha }} + path: target + persist-credentials: false + + - name: Download formatting patch + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: formatting-${{ github.run_id }}-${{ github.run_attempt }}-${{ needs.setup.outputs.sha }} + path: ${{ runner.temp }}/formatting-artifact + + - name: Reject stale target + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + TARGET_REPO: ${{ needs.setup.outputs.repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + TARGET_SHA: ${{ needs.setup.outputs.sha }} + with: + script: | + const repo = process.env.TARGET_REPO; + const ref = process.env.TARGET_REF; + const sha = process.env.TARGET_SHA; + const { data: pr } = await github.rest.pulls.get({ + ...context.repo, pull_number: context.issue.number + }); + if (pr.state !== 'open' || pr.head.repo?.full_name !== repo || + pr.head.ref !== ref || pr.head.sha !== sha) { + throw new Error('PR target changed during formatting; rerun the command'); + } + + - name: Validate patch and create commit without executing target code + id: commit + env: + TARGET_SHA: ${{ needs.setup.outputs.sha }} + run: | + commit=$(python3 trusted/scripts/prepare_formatting_commit.py target \ + "$RUNNER_TEMP/formatting-artifact/formatting.patch" "$TARGET_SHA") + echo "sha=$commit" >> "$GITHUB_OUTPUT" + + - name: Push fixes + if: steps.commit.outputs.sha != '' + working-directory: target + env: + # Only this trusted step receives the PAT needed to push to contributor forks. + PUSH_TOKEN: ${{ secrets.WORKFLOW_PAT }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + TARGET_SHA: ${{ needs.setup.outputs.sha }} + COMMIT_SHA: ${{ steps.commit.outputs.sha }} + run: | + test -n "$PUSH_TOKEN" + git check-ref-format "refs/heads/$TARGET_REF" + auth=$(printf 'x-access-token:%s' "$PUSH_TOKEN" | base64 -w0) + export GIT_CONFIG_COUNT=1 + export GIT_CONFIG_KEY_0=http.https://github.com/.extraheader + export GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $auth" + current=$(git ls-remote --refs origin "refs/heads/$TARGET_REF") + test "${current%%$'\t'*}" = "$TARGET_SHA" + # The commit has exactly TARGET_SHA as its parent. The explicit lease is an atomic + # compare-and-swap, rejecting even branch deletion or rewind after the stale check. + git -c core.hooksPath=/dev/null push \ + --force-with-lease="refs/heads/$TARGET_REF:$TARGET_SHA" \ + origin "$COMMIT_SHA:refs/heads/$TARGET_REF" + + report: + runs-on: ubuntu-latest + needs: [setup, apply_fixes, publish] + if: always() && needs.setup.result == 'success' && github.event_name == 'issue_comment' + permissions: + issues: write + steps: + - name: Update PR comment reactions + uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + with: + status: ${{ needs.publish.result == 'success' && 'success' || 'failure' }} diff --git a/.github/workflows/pre-commit-validation.yaml b/.github/workflows/pre-commit-validation.yaml new file mode 100644 index 000000000..0b8714b1e --- /dev/null +++ b/.github/workflows/pre-commit-validation.yaml @@ -0,0 +1,70 @@ +name: Repository Validation +run-name: "${{ github.actor }} running analysis and unit tests" + +"on": + pull_request: + push: + branches: ["release/*"] + workflow_dispatch: + +permissions: + contents: read + +jobs: + validation: + name: Static Analysis and Repository Checks + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Run analysis and repository checks + uses: ./.github/actions/run-pre-commit + with: + category: validation + + scripts-test: + name: Scripts, CI, and Devcontainer Unit Tests (${{ matrix.arch }}) + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + steps: + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + + - name: Run unit tests + uses: ./.github/actions/run-pre-commit + with: + category: tests + + - name: Upload scripts coverage to Codecov + if: ${{ hashFiles('coverage-scripts.xml') != '' }} + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + files: coverage-scripts.xml + flags: ${{ matrix.arch }} + name: phlex-scripts-coverage-${{ matrix.arch }} + fail_ci_if_error: false + verbose: true + root_dir: . + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/python-check.yaml b/.github/workflows/python-check.yaml deleted file mode 100644 index 1fbe39759..000000000 --- a/.github/workflows/python-check.yaml +++ /dev/null @@ -1,200 +0,0 @@ -name: Python Check -run-name: "${{ github.actor }} checking Python code" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: | - python - yaml - include-globs: | - scripts/** - ci/** - .devcontainer/** - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - python-check: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Install Python dependencies - run: uv tool install ruff && uv tool install mypy --with types-PyYAML - - - name: Run ruff check - id: ruff - working-directory: ${{ needs.setup.outputs.checkout_path }} - env: - FORCE_COLOR: 1 - run: | - echo "➡️ Checking Python code with ruff..." - ruff check - continue-on-error: true - - - name: Run MyPy check - id: mypy - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "➡️ Checking Python code with MyPy..." - mypy --color-output . - continue-on-error: true - - - name: Evaluate Python checks result - if: always() && (steps.ruff.outcome != 'skipped' || steps.mypy.outcome != 'skipped') - env: - REPO: ${{ needs.setup.outputs.repo }} - # yamllint disable rule:line-length - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.ruff.outcome }}" = 'success' ] && [ "${{ steps.mypy.outcome }}" = 'success' ]; then - echo "✅ Python checks passed." - else - echo "::error::Python checks failed. Comment '@${REPO_NAME}bot python-fix' on the PR to attempt auto-fix." - exit 1 - fi - # yamllint enable - - scripts-test: - needs: setup - if: > - always() && ( - github.event_name == 'workflow_dispatch' || - inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true' - ) - strategy: - fail-fast: false - matrix: - arch: - - amd64 - - arm64 - include: - - arch: amd64 - runner: ubuntu-24.04 - - arch: arm64 - runner: ubuntu-24.04-arm - runs-on: ${{ matrix.runner }} - permissions: - contents: read - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Run scripts unit tests with coverage - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - echo "➡️ Running scripts/ unit tests with coverage..." - uv run --python 3.12 --with pytest --with PyYAML --with pytest-cov \ - pytest scripts/test/ -v \ - --cov=scripts \ - --cov=ci \ - --cov=.devcontainer \ - --cov-report="xml:${GITHUB_WORKSPACE}/coverage-scripts.xml" \ - --cov-report=term-missing - - - name: Upload scripts coverage to Codecov - if: ${{ hashFiles('coverage-scripts.xml') != '' }} - uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 - with: - files: coverage-scripts.xml - flags: ${{ matrix.arch }} - name: phlex-scripts-coverage-${{ matrix.arch }} - fail_ci_if_error: false - verbose: true - root_dir: ${{ needs.setup.outputs.checkout_path || '.' }} - token: ${{ env.CODECOV_TOKEN }} diff --git a/.github/workflows/python-fix.yaml b/.github/workflows/python-fix.yaml deleted file mode 100644 index 4b14bc804..000000000 --- a/.github/workflows/python-fix.yaml +++ /dev/null @@ -1,133 +0,0 @@ -name: Python Fix -run-name: "${{ github.actor }} fixing Python code" - -"on": - issue_comment: - types: - - created - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_fixes.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_fixes.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_fixes.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_fixes.outputs.patch_name }} - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot python-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_fixes: - runs-on: ubuntu-latest - name: Apply fixes - needs: setup - if: needs.setup.result == 'success' - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Install Python dependencies - run: uv tool install ruff - - - name: Run ruff format and fix - working-directory: ${{ needs.setup.outputs.checkout_path }} - env: - FORCE_COLOR: 1 - run: | - echo "Fixing Python format with ruff" - ruff format . || true - echo "Fixing Python linter issues with ruff" - ruff check --fix . || true - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: ruff - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.github/workflows/yaml-check.yaml b/.github/workflows/yaml-check.yaml deleted file mode 100644 index 1c99d4d27..000000000 --- a/.github/workflows/yaml-check.yaml +++ /dev/null @@ -1,111 +0,0 @@ -name: YAML Check -"run-name": "${{ github.actor }} checking YAML files" - -permissions: - contents: read - pull-requests: read - -"on": - pull_request: - push: - branches: ["release/*"] - workflow_dispatch: - inputs: - ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - skip-relevance-check: - description: "Bypass relevance check" - required: false - type: boolean - default: false - pr-base-sha: - description: "Base SHA of the PR for relevance check" - required: false - type: string - pr-head-sha: - description: "Head SHA of the PR for relevance check" - required: false - type: string - ref: - description: "The branch, ref, or SHA to checkout" - required: false - type: string - repo: - description: "The repository to checkout from" - required: false - type: string - -jobs: - setup: - runs-on: ubuntu-latest - outputs: - is_act: ${{ steps.setup.outputs.is_act }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base_sha: ${{ steps.setup.outputs.base_sha }} - pr_number: ${{ steps.setup.outputs.pr_number }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - file-type: yaml - head-ref: ${{ inputs.pr-head-sha }} - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - pr-base-sha: ${{ inputs.pr-base-sha }} - checkout-path: ${{ inputs.checkout-path }} - - yaml-check: - needs: setup - if: > - always() && (github.event_name == 'workflow_dispatch' || inputs.skip-relevance-check || - needs.setup.outputs.has_changes == 'true') - runs-on: ubuntu-latest - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} - persist-credentials: false - - - name: Install uv - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - - - name: Install yamllint - run: uv tool install yamllint - - - name: Run yamllint - id: lint - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: yamllint . - continue-on-error: true - - - name: Evaluate yamllint result - if: always() && steps.lint.outcome != 'skipped' - env: - REPO: ${{ needs.setup.outputs.repo }} - run: | - REPO_NAME="${REPO##*/}" - if [ "${{ steps.lint.outcome }}" = "success" ]; then - echo "✅ YAML check passed." - else - echo "::error::YAML check failed." - echo "::error::Comment '@${REPO_NAME}bot yaml-fix' on the PR to auto-fix." - exit 1 - fi diff --git a/.github/workflows/yaml-fix.yaml b/.github/workflows/yaml-fix.yaml deleted file mode 100644 index 7f2ff324c..000000000 --- a/.github/workflows/yaml-fix.yaml +++ /dev/null @@ -1,136 +0,0 @@ -name: YAML Fix -"run-name": "${{ github.actor }} fixing YAML files" - -"on": - issue_comment: - types: - - created - workflow_dispatch: - inputs: - ref: - description: - "The branch name to checkout and push fixes to (must be a branch, not a commit SHA). Defaults to the - repository's default branch." - required: false - type: string - workflow_call: - inputs: - checkout-path: - description: "Path to check out code to" - required: false - type: string - ref: - description: "The branch name to checkout and push fixes to (must be a branch, not a commit SHA)" - required: true - type: string - repo: - description: "The repository to checkout from" - required: true - type: string - skip-comment: - description: "Skip posting PR comments" - required: false - type: boolean - default: false - outputs: - changes: - description: "Whether any fixes were applied" - value: ${{ jobs.apply_yaml_fixes.outputs.changes }} - pushed: - description: "Whether the fixes were pushed to the remote branch" - value: ${{ jobs.apply_yaml_fixes.outputs.pushed }} - commit_sha: - description: "The full commit SHA of the applied fixes" - value: ${{ jobs.apply_yaml_fixes.outputs.commit_sha }} - commit_sha_short: - description: "The short commit SHA of the applied fixes" - value: ${{ jobs.apply_yaml_fixes.outputs.commit_sha_short }} - patch_name: - description: "Name of the patch file if fixes could not be pushed" - value: ${{ jobs.apply_yaml_fixes.outputs.patch_name }} - -permissions: - pull-requests: write - contents: write - issues: write - -jobs: - setup: - runs-on: ubuntu-latest - name: Parse command - if: > - inputs.ref != '' || github.event_name == 'workflow_dispatch' || ( - github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(fromJSON('["OWNER", "COLLABORATOR", "MEMBER"]'), github.event.comment.author_association) && - startsWith(github.event.comment.body, format('@{0}bot yaml-fix', github.event.repository.name)) - ) - outputs: - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - checkout_path: ${{ steps.setup.outputs.checkout_path }} - steps: - - name: Workflow setup - id: setup - uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 - with: - mode: fix - ref: ${{ inputs.ref }} - repo: ${{ inputs.repo }} - checkout-path: ${{ inputs.checkout-path }} - - apply_yaml_fixes: - runs-on: ubuntu-latest - name: Apply YAML fixes - needs: setup - if: ${{ needs.setup.result == 'success' }} - outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} - - steps: - - name: Checkout code - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} - persist-credentials: false - - - name: Setup Node.js - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: "26" - package-manager-cache: false - - - name: Install prettier - run: | - npm update -g npm@^11.10.0 - npm config set min-release-age=3 --location=user - npm install -g prettier - - - name: Apply YAML formatting - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - prettier --write '**/*.{yaml,yml}' - - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: YAML formatter - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} - - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 - with: - status: ${{ job.status }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 99dd1850f..b9263fdcd 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -24,10 +24,11 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.16.0 hooks: - - id: ruff-format + - id: ruff + args: [--fix] types_or: [python, pyi] language_version: python3.12 - - id: ruff + - id: ruff-format types_or: [python, pyi] language_version: python3.12 - repo: https://github.com/pre-commit/mirrors-clang-format diff --git a/pyproject.toml b/pyproject.toml index d860642a3..cf17160af 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -75,6 +75,7 @@ known-first-party = [ "fix_header_guards", "normalize_coverage_lcov", "normalize_coverage_xml", + "prepare_formatting_commit", "sarif_alerts", ] diff --git a/scripts/check-gating-block.sh b/scripts/check-gating-block.sh index 95266e3e1..1a657ffe1 100755 --- a/scripts/check-gating-block.sh +++ b/scripts/check-gating-block.sh @@ -4,34 +4,20 @@ set -euo pipefail # Verify that the shared if-gating blocks contain the required phrases across # GitHub Actions workflows. Exits 1 if any required phrase is missing. # -# Two gating-block families are checked: +# Relevance gates and workflow-specific event/authorization gates are checked. # -# CHECK-JOB pattern — used by the lint/check job in every *-check workflow: +# CHECK-JOB pattern used by workflows in CHECK_WORKFLOWS: # always() && ( # github.event_name == 'workflow_dispatch' || # inputs.skip-relevance-check || # needs.setup.outputs.has_changes == 'true' # ) -# -# FIX-SETUP pattern — used by the setup job in every *-fix workflow that -# exposes workflow_call (all fix workflows except clang-tidy-fix): -# inputs.ref != '' || -# github.event_name == 'workflow_dispatch' || -# (github.event_name == 'issue_comment' && -# ... author_association gate ...) WORKFLOWS_DIR="${1:-.github/workflows}" # Check workflows whose lint/check job uses the relevance-check if-gate. CHECK_WORKFLOWS=( "actionlint-check.yaml" - "clang-format-check.yaml" - "cmake-format-check.yaml" - "header-guards-check.yaml" - "jsonnet-format-check.yaml" - "markdown-check.yaml" - "python-check.yaml" - "yaml-check.yaml" ) # clang-tidy-check has an issue_comment-aware gating block on its setup job. @@ -39,16 +25,9 @@ TIDY_CHECK_WORKFLOWS=( "clang-tidy-check.yaml" ) -# Fix workflows that expose workflow_call (use inputs.ref != '' as entry point). -# clang-tidy-fix is excluded: it has no workflow_call trigger. -FIX_WORKFLOWS=( - "clang-format-fix.yaml" - "cmake-format-fix.yaml" - "header-guards-fix.yaml" - "jsonnet-format-fix.yaml" - "markdown-fix.yaml" - "python-fix.yaml" - "yaml-fix.yaml" +# Pre-commit fixes accept only authorized PR comment commands. +PRE_COMMIT_FIX_WORKFLOWS=( + "pre-commit-fix.yaml" ) # cmake-build uses the full event-list gating block on its setup job. @@ -85,14 +64,13 @@ TIDY_CHECK_PHRASES=( "github.event.comment.author_association" ) -# Required phrases for fix workflow setup jobs (workflow_call-capable). -FIX_PHRASES=( - "inputs.ref != ''" - "github.event_name == 'workflow_dispatch'" +PRE_COMMIT_FIX_PHRASES=( "github.event_name == 'issue_comment'" "github.event.issue.pull_request" - "fromJSON('[\"OWNER\", \"COLLABORATOR\", \"MEMBER\"]')" - "github.event.comment.author_association" + "contains(fromJSON('[\"OWNER\"," + "\"COLLABORATOR\", \"MEMBER\"]'), github.event.comment.author_association)" + "startsWith(github.event.comment.body, format('@{0}bot pre-commit-fix', github.event.repository.name))" + "startsWith(github.event.comment.body, format('@{0}bot format', github.event.repository.name))" ) # Required phrases for coverage workflow setup job (custom gating). @@ -178,10 +156,10 @@ for wf in "${TIDY_CHECK_WORKFLOWS[@]}"; do done echo "" -echo "Fix workflows (workflow_call-capable, inputs.ref gate)" +echo "Pre-commit fix workflow (authorized PR comment commands)" echo "=======================================================" -for wf in "${FIX_WORKFLOWS[@]}"; do - check_workflow "$WORKFLOWS_DIR/$wf" "$wf" "${FIX_PHRASES[@]}" +for wf in "${PRE_COMMIT_FIX_WORKFLOWS[@]}"; do + check_workflow "$WORKFLOWS_DIR/$wf" "$wf" "${PRE_COMMIT_FIX_PHRASES[@]}" done # Coverage workflow checks diff --git a/scripts/prepare_formatting_commit.py b/scripts/prepare_formatting_commit.py new file mode 100644 index 000000000..23f46fec2 --- /dev/null +++ b/scripts/prepare_formatting_commit.py @@ -0,0 +1,67 @@ +"""Validate an untrusted formatting patch and create a commit without running target code.""" + +from __future__ import annotations + +import os +import re +import subprocess +import sys +from pathlib import Path + + +def prepare_commit(repository: Path, patch: Path, sha: str) -> str: + """Accept only content modifications to existing regular files at the captured SHA.""" + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ValueError("Invalid target SHA") + if patch.is_symlink() or not patch.is_file() or patch.stat().st_size > 10 * 1024 * 1024: + raise ValueError("Expected a regular patch file no larger than 10 MiB") + + def git(*args: str, input_data: bytes | None = None) -> bytes: + return subprocess.run( + ["git", "-c", "core.hooksPath=/dev/null", "-C", str(repository), *args], + input=input_data, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + env={ + **os.environ, + "GIT_AUTHOR_NAME": "github-actions[bot]", + "GIT_AUTHOR_EMAIL": "41898282+github-actions[bot]@users.noreply.github.com", + "GIT_COMMITTER_NAME": "github-actions[bot]", + "GIT_COMMITTER_EMAIL": "41898282+github-actions[bot]@users.noreply.github.com", + }, + ).stdout + + if git("rev-parse", "HEAD").decode().strip() != sha: + raise ValueError("Checkout does not match the captured SHA") + if git("status", "--porcelain"): + raise ValueError("Publishing checkout must be clean") + if patch.stat().st_size == 0: + return "" + # Apply only to the index: no checkout filters, hooks, or patched scripts execute. + git("apply", "--cached", "--check", "--", str(patch.resolve())) + git("apply", "--cached", "--", str(patch.resolve())) + raw_changes = git("diff", "--cached", "--raw", "-z", "--no-renames", sha, "--") + if not raw_changes: + return "" + changes = raw_changes.split(b"\0") + for metadata, _ in zip(changes[0:-1:2], changes[1:-1:2], strict=True): + old_mode, new_mode, _, _, status = metadata.split() + if status != b"M" or old_mode[1:] not in {b"100644", b"100755"}: + raise ValueError("Formatting may only modify existing regular files") + if old_mode[1:] != new_mode: + raise ValueError("Formatting may not change file modes") + tree = git("write-tree").decode().strip() + return ( + git("commit-tree", tree, "-p", sha, input_data=b"style: apply automatic formatting\n") + .decode() + .strip() + ) + + +if __name__ == "__main__": + try: + print(prepare_commit(Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3])) + except (ValueError, subprocess.CalledProcessError) as error: + print(f"Formatting patch rejected: {error}", file=sys.stderr) + sys.exit(1) diff --git a/scripts/test/CMakeLists.txt b/scripts/test/CMakeLists.txt index 633845183..68e3c4234 100644 --- a/scripts/test/CMakeLists.txt +++ b/scripts/test/CMakeLists.txt @@ -29,6 +29,7 @@ endif() set( scripts_test_modules test_check_codeql_alerts + test_check_gating_block test_clang_tidy_check_summary test_clang_tidy_diff_issues test_clang_tidy_fixes_to_problems @@ -36,6 +37,7 @@ set( test_coverage_scripts test_devcontainer_host test_fix_header_guards + test_prepare_formatting_commit test_promote_phlex_dependencies test_sarif_alerts test_upgrade_repos diff --git a/scripts/test/test_check_gating_block.py b/scripts/test/test_check_gating_block.py new file mode 100644 index 000000000..7cfe2cfdf --- /dev/null +++ b/scripts/test/test_check_gating_block.py @@ -0,0 +1,68 @@ +"""Regression tests for the workflow gating checker.""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +SCRIPT = ROOT / "scripts/check-gating-block.sh" +WORKFLOW = "pre-commit-fix.yaml" + + +@pytest.fixture +def workflows(tmp_path): + """Copy workflow data without executing any workflow code.""" + directory = tmp_path / "workflows" + shutil.copytree(ROOT / ".github/workflows", directory) + return directory + + +def check(directory): + """Execute the governance checker against a workflow directory.""" + return subprocess.run( + ["bash", str(SCRIPT), str(directory)], capture_output=True, text=True, check=False + ) + + +def test_current_workflows_pass(workflows): + """The comment-only workflow does not need reusable or manual entry points.""" + result = check(workflows) + assert result.returncode == 0, result.stdout + result.stderr + assert f"PASS: {WORKFLOW}" in result.stdout + + +@pytest.mark.parametrize( + "phrase", + [ + "github.event_name == 'issue_comment'", + "github.event.issue.pull_request", + 'contains(fromJSON(\'["OWNER",', + '"COLLABORATOR", "MEMBER"]\'), github.event.comment.author_association)', + "startsWith(github.event.comment.body, " + + "format('@{0}bot pre-commit-fix', github.event.repository.name))", + "startsWith(github.event.comment.body, " + + "format('@{0}bot format', github.event.repository.name))", + ], +) +def test_rejects_missing_comment_gate_phrase(workflows, phrase): + """Each required authorization and command fragment must remain present.""" + workflow = workflows / WORKFLOW + content = workflow.read_text() + assert phrase in content + workflow.write_text(content.replace(phrase, "REMOVED")) + result = check(workflows) + assert result.returncode == 1, result.stdout + result.stderr + assert f"FAIL: {WORKFLOW}" in result.stdout + assert f"missing: {phrase}" in result.stdout + + +def test_rejects_missing_workflow(workflows): + """Deleting the governed workflow fails rather than silently skipping it.""" + (workflows / WORKFLOW).unlink() + result = check(workflows) + assert result.returncode == 1, result.stdout + result.stderr + assert f"ERROR: {workflows / WORKFLOW} not found" in result.stdout diff --git a/scripts/test/test_prepare_formatting_commit.py b/scripts/test/test_prepare_formatting_commit.py new file mode 100644 index 000000000..f830c0462 --- /dev/null +++ b/scripts/test/test_prepare_formatting_commit.py @@ -0,0 +1,304 @@ +"""Security regression tests for the formatting workflow's publishing boundary.""" + +from __future__ import annotations + +import json +import runpy +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest +import yaml + +from prepare_formatting_commit import prepare_commit + +WORKFLOW = Path(__file__).resolve().parents[2] / ".github/workflows/pre-commit-fix.yaml" + + +def git(repository, *args): + """Run Git in a disposable test repository.""" + return subprocess.check_output(["git", "-C", str(repository), *args]) + + +@pytest.fixture +def repository(tmp_path): + """Create a committed regular file and a clean publishing checkout.""" + repo = tmp_path / "repo" + repo.mkdir() + git(repo, "init") + (repo / "file.py").write_text("x = 1\n") + (repo / "executable.sh").write_text("#!/bin/sh\nexit 0\n") + (repo / "executable.sh").chmod(0o755) + git(repo, "add", ".") + git(repo, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "base") + return repo, git(repo, "rev-parse", "HEAD").decode().strip() + + +def export_patch(repository, tmp_path): + """Export staged changes and restore a clean publishing index and worktree.""" + patch = tmp_path / "formatting.patch" + patch.write_bytes(git(repository, "diff", "--cached", "--binary", "--no-renames")) + git(repository, "restore", "--staged", "--worktree", ".") + # New files restored out of the index remain untracked. + git(repository, "clean", "-fd") + return patch + + +@pytest.mark.parametrize("filename", ["file.py", "executable.sh", "space name.py"]) +def test_creates_commit_without_executing_code(repository, tmp_path, filename): + """Content changes preserve modes and never invoke repository hooks or changed scripts.""" + repo, sha = repository + if filename == "space name.py": + git(repo, "mv", "file.py", filename) + git( + repo, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "-m", + "rename", + ) + sha = git(repo, "rev-parse", "HEAD").decode().strip() + marker = tmp_path / "executed" + hook = repo / ".git/hooks/pre-commit" + hook.write_text(f"#!/bin/sh\ntouch '{marker}'\nexit 1\n") + hook.chmod(0o755) + content = f"#!/bin/sh\ntouch '{marker}'\n" + (repo / filename).write_text(content) + git(repo, "add", filename) + patch = export_patch(repo, tmp_path) + commit = prepare_commit(repo, patch, sha) + assert git(repo, "show", f"{commit}:{filename}").decode() == content + assert git(repo, "rev-parse", f"{commit}^").decode().strip() == sha + assert git(repo, "rev-parse", "HEAD").decode().strip() == sha + assert not marker.exists() + + +@pytest.mark.parametrize("change", ["addition", "deletion", "mode", "symlink", "submodule"]) +def test_rejects_non_content_changes(repository, tmp_path, change): + """Untrusted patches cannot add/delete files or introduce executable plumbing.""" + repo, sha = repository + file = repo / "file.py" + if change == "addition": + (repo / "new.py").write_text("x = 2\n") + git(repo, "add", "new.py") + elif change == "deletion": + git(repo, "rm", "file.py") + elif change == "mode": + git(repo, "update-index", "--chmod=+x", "file.py") + elif change == "symlink": + file.unlink() + file.symlink_to("../outside") + git(repo, "add", "file.py") + else: + git(repo, "update-index", "--add", "--cacheinfo", f"160000,{sha},module") + patch = export_patch(repo, tmp_path) + with pytest.raises(ValueError): + prepare_commit(repo, patch, sha) + assert git(repo, "rev-parse", "HEAD").decode().strip() == sha + + +def test_empty_patch(repository, tmp_path): + """No formatting changes produce no commit.""" + repo, sha = repository + patch = tmp_path / "empty.patch" + patch.write_bytes(b"") + assert prepare_commit(repo, patch, sha) == "" + + +def test_entrypoint_prints_commit(repository, tmp_path, monkeypatch, capsys): + """The publishing command prints the created commit SHA and preserves HEAD.""" + repo, sha = repository + content = "x = 2\n" + (repo / "file.py").write_text(content) + git(repo, "add", "file.py") + patch = export_patch(repo, tmp_path) + script = Path(__file__).resolve().parents[1] / "prepare_formatting_commit.py" + monkeypatch.setattr(sys, "argv", [str(script), str(repo), str(patch), sha]) + + runpy.run_path(str(script), run_name="__main__") + + output = capsys.readouterr() + commit = output.out.strip() + assert len(commit) == 40 + assert output.out == f"{commit}\n" + assert output.err == "" + assert git(repo, "show", f"{commit}:file.py").decode() == content + assert git(repo, "rev-parse", f"{commit}^").decode().strip() == sha + assert git(repo, "rev-parse", "HEAD").decode().strip() == sha + + +def test_entrypoint_rejects_invalid_sha(repository, tmp_path, monkeypatch, capsys): + """The publishing command reports malformed SHAs on stderr and exits with failure.""" + repo, sha = repository + patch = tmp_path / "empty.patch" + patch.write_bytes(b"") + script = Path(__file__).resolve().parents[1] / "prepare_formatting_commit.py" + monkeypatch.setattr(sys, "argv", [str(script), str(repo), str(patch), "not-a-sha"]) + + with pytest.raises(SystemExit) as error: + runpy.run_path(str(script), run_name="__main__") + + assert error.value.code == 1 + output = capsys.readouterr() + assert output.out == "" + assert output.err == "Formatting patch rejected: Invalid target SHA\n" + assert git(repo, "rev-parse", "HEAD").decode().strip() == sha + assert git(repo, "status", "--porcelain") == b"" + + +def test_binary_patch(repository, tmp_path): + """Binary content updates are applied as data without checkout filters.""" + repo, sha = repository + content = b"\x00formatted\xff\n" + (repo / "file.py").write_bytes(content) + git(repo, "add", "file.py") + patch = export_patch(repo, tmp_path) + commit = prepare_commit(repo, patch, sha) + assert git(repo, "show", f"{commit}:file.py") == content + + +@pytest.mark.parametrize("kind", ["sha", "dirty", "symlink", "oversized", "traversal", "git"]) +def test_rejects_invalid_inputs(repository, tmp_path, kind): + """Invalid revisions, artifacts, checkouts, and unsafe paths fail closed.""" + repo, sha = repository + patch = tmp_path / "formatting.patch" + patch.write_bytes(b"") + if kind == "sha": + sha = "0" * 40 + elif kind == "dirty": + (repo / "file.py").write_text("changed\n") + elif kind == "symlink": + patch.unlink() + patch.symlink_to(repo / "file.py") + elif kind == "oversized": + with patch.open("wb") as stream: + stream.truncate(10 * 1024 * 1024 + 1) + else: + path = "../outside" if kind == "traversal" else ".git/config" + patch.write_text( + f"diff --git a/{path} b/{path}\n--- a/{path}\n+++ b/{path}\n@@ -1 +1 @@\n-old\n+new\n" + ) + with pytest.raises((ValueError, subprocess.CalledProcessError)): + prepare_commit(repo, patch, sha) + + +def test_workflow_privilege_boundary(): + """Only trusted publishing steps receive credentials; target execution is SHA-pinned.""" + workflow = yaml.safe_load(WORKFLOW.read_text()) + assert workflow["on"] == {"issue_comment": {"types": ["created"]}} + assert workflow["permissions"] == {"contents": "read"} + jobs = workflow["jobs"] + formatter = jobs["apply_fixes"] + assert formatter["permissions"] == {"contents": "read"} + checkout = formatter["steps"][0]["with"] + assert checkout["ref"] == "${{ needs.setup.outputs.sha }}" + assert checkout["persist-credentials"] is False + assert "secrets." not in str(formatter) + publisher = jobs["publish"] + assert "./.github/actions" not in str(publisher) + assert "pre_commit" not in str(publisher) + push = next(step for step in publisher["steps"] if step["name"] == "Push fixes") + assert push["env"]["PUSH_TOKEN"] == "${{ secrets.WORKFLOW_PAT }}" + assert '--force-with-lease="refs/heads/$TARGET_REF:$TARGET_SHA"' in push["run"] + assert "--force " not in push["run"] + assert 'test "${current%%$\'\\t\'*}" = "$TARGET_SHA"' in push["run"] + stale = next(step for step in publisher["steps"] if step["name"] == "Reject stale target") + assert "pr.head.sha !== sha" in stale["with"]["script"] + assert "pr.head.repo?.full_name !== repo" in stale["with"]["script"] + trusted_checkout = publisher["steps"][0]["with"] + assert trusted_checkout["ref"] == "${{ needs.setup.outputs.trusted_sha }}" + assert "github.event.issue.pull_request" in jobs["setup"]["if"] + assert "github.event.comment.author_association" in jobs["setup"]["if"] + resolver = jobs["setup"]["steps"][0]["with"]["script"] + assert "branch: context.payload.repository.default_branch" in resolver + assert "core.setOutput('trusted_sha', trustedBranch.commit.sha)" in resolver + + +@pytest.mark.parametrize("change", [None, "delete", "rewind", "advance"]) +def test_atomic_push_lease(repository, tmp_path, change): + """The exact-SHA push lease rejects all target changes, including ref deletion.""" + repo, parent = repository + (repo / "file.py").write_text("x = 2\n") + git(repo, "add", "file.py") + git(repo, "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "head") + sha = git(repo, "rev-parse", "HEAD").decode().strip() + remote = tmp_path / "remote.git" + subprocess.run(["git", "init", "--bare", str(remote)], check=True, capture_output=True) + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "origin", f"{sha}:refs/heads/topic") + (repo / "file.py").write_text("x = 3\n") + git(repo, "add", "file.py") + commit = prepare_commit(repo, export_patch(repo, tmp_path), sha) + if change == "delete": + git(remote, "update-ref", "-d", "refs/heads/topic") + elif change == "rewind": + git(remote, "update-ref", "refs/heads/topic", parent) + elif change == "advance": + tree = git(repo, "rev-parse", f"{sha}^{{tree}}").decode().strip() + advanced = ( + git( + repo, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit-tree", + tree, + "-p", + sha, + "-m", + "concurrent update", + ) + .decode() + .strip() + ) + git(repo, "push", "origin", f"{advanced}:refs/heads/topic") + # The changed branch above models an update after the workflow's ls-remote check. + result = subprocess.run( + [ + "git", + "-C", + str(repo), + "push", + f"--force-with-lease=refs/heads/topic:{sha}", + "origin", + f"{commit}:refs/heads/topic", + ], + capture_output=True, + text=True, + ) + assert (result.returncode == 0) == (change is None), result.stderr + + +@pytest.mark.skipif(shutil.which("node") is None, reason="Node.js is required for API mocks") +@pytest.mark.parametrize("change", [None, "sha", "repo", "ref", "closed"]) +def test_stale_target_api_guard(change): + """Execute the actual workflow guard against mocked GitHub responses.""" + jobs = yaml.safe_load(WORKFLOW.read_text())["jobs"] + step = next(step for step in jobs["publish"]["steps"] if step["name"] == "Reject stale target") + pr = { + "state": "open", + "head": {"repo": {"full_name": "owner/repo"}, "ref": "topic", "sha": "a" * 40}, + } + if change == "closed": + pr["state"] = "closed" + elif change == "repo": + pr["head"]["repo"]["full_name"] = "other/repo" + elif change: + pr["head"][change] = "changed" + harness = f""" + const context = {{repo: {{}}, issue: {{number: 440}}}}; + const pr = {json.dumps(pr)}; + process.env.TARGET_REPO = 'owner/repo'; + process.env.TARGET_REF = 'topic'; + process.env.TARGET_SHA = '{"a" * 40}'; + const github = {{rest: {{pulls: {{get: async () => ({{data: pr}})}}}}}}; + (async () => {{ {step["with"]["script"]} }})().catch(() => process.exit(1)); + """ + result = subprocess.run(["node", "-e", harness], capture_output=True, text=True) + assert result.returncode == (0 if change is None else 1), result.stderr diff --git a/scripts/test/test_workflow_cleanup.py b/scripts/test/test_workflow_cleanup.py index b4c92a532..ecdeb7179 100644 --- a/scripts/test/test_workflow_cleanup.py +++ b/scripts/test/test_workflow_cleanup.py @@ -9,6 +9,7 @@ import os import pathlib import subprocess +import sys import pytest import yaml @@ -82,6 +83,72 @@ def test_clang_tidy_marks_completed_only_after_tidy_succeeds(): assert tidy_failure < issues_found < completed_marker +@pytest.mark.parametrize("category", ["formatting", "validation", "tests"]) +def test_pre_commit_coverage_is_ci_only(tmp_path, category): + """Only the CI-generated script test hook collects coverage.""" + repo_dir = WORKFLOWS_DIR.parent.parent + config_path = repo_dir / ".pre-commit-config.yaml" + original_config = config_path.read_text(encoding="utf-8") + action = _load_yaml(repo_dir / ".github" / "actions" / "run-pre-commit" / "action.yaml") + step = next(step for step in action["runs"]["steps"] if step["name"] == "Select and run hooks") + script = step["run"].split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0] + generated_path = tmp_path / "pre-commit.yaml" + result = subprocess.run( + [sys.executable, "-c", script, str(generated_path)], + cwd=repo_dir, + env={**os.environ, "HOOK_CATEGORY": category}, + text=True, + capture_output=True, + ) + assert result.returncode == 0, result.stderr + generated = _load_yaml(generated_path) + hooks = {hook["id"]: hook for repo in generated["repos"] for hook in repo["hooks"]} + if category == "tests": + hook = hooks["scripts-unit-tests"] + assert hook["entry"] == "pytest scripts/test/ -v" + assert hook["additional_dependencies"] == ["pytest", "PyYAML", "pytest-cov"] + assert hook["args"] == [ + "--cov=scripts", + "--cov=ci", + "--cov=.devcontainer", + "--cov-report=xml:coverage-scripts.xml", + "--cov-report=term-missing", + ] + else: + assert "scripts-unit-tests" not in hooks + assert all( + "pytest-cov" not in hook.get("additional_dependencies", []) for hook in hooks.values() + ) + assert config_path.read_text(encoding="utf-8") == original_config + local_config = yaml.safe_load(original_config) + local_hook = next( + hook + for repo in local_config["repos"] + for hook in repo["hooks"] + if hook["id"] == "scripts-unit-tests" + ) + assert "pytest-cov" not in local_hook["additional_dependencies"] + assert not local_hook.get("args") + + +def test_script_coverage_upload_uses_matrix_architecture(): + """Both script-test runners upload their generated report without gating on Codecov.""" + job = _load_yaml(WORKFLOWS_DIR / "pre-commit-validation.yaml")["jobs"]["scripts-test"] + assert {entry["arch"] for entry in job["strategy"]["matrix"]["include"]} == {"amd64", "arm64"} + steps = job["steps"] + test_step = next(step for step in steps if step["name"] == "Run unit tests") + assert test_step["with"]["category"] == "tests" + upload = next(step for step in steps if step["name"] == "Upload scripts coverage to Codecov") + assert steps.index(upload) > steps.index(test_step) + assert upload["if"] == "${{ hashFiles('coverage-scripts.xml') != '' }}" + assert upload["uses"].startswith("codecov/codecov-action@") + assert upload["with"]["files"] == "coverage-scripts.xml" + assert upload["with"]["flags"] == "${{ matrix.arch }}" + assert upload["with"]["name"] == "phlex-scripts-coverage-${{ matrix.arch }}" + assert upload["with"]["token"] == "${{ secrets.CODECOV_TOKEN }}" + assert upload["with"]["fail_ci_if_error"] is False + + @pytest.mark.parametrize( "coverage_result,available,expected_status", [