name: "Check whether nix files are parseable v2"

permissions:
  pull-requests: read
  contents: read

on:
  # avoids approving first time contributors
  pull_request_target:
    branches-ignore:
      - 'release-**'

jobs:
  tests:
    name: nix-files-parseable-check
    runs-on: ubuntu-latest
    if: "github.repository_owner == 'NixOS' && !contains(github.event.pull_request.title, '[skip treewide]')"
    steps:
    - name: Get list of changed files from PR
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        gh api \
          repos/NixOS/nixpkgs/pulls/${{github.event.number}}/files --paginate \
          | jq --raw-output '.[] | select(.status != "removed" and (.filename | endswith(".nix"))) | .filename' \
          > "$HOME/changed_files"
        if [[ -s "$HOME/changed_files" ]]; then
          echo "CHANGED_FILES=$HOME/changed_files" > "$GITHUB_ENV"
        fi
    - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
      with:
        # pull_request_target checks out the base branch by default
        ref: refs/pull/${{ github.event.pull_request.number }}/merge
      if: ${{ env.CHANGED_FILES && env.CHANGED_FILES != '' }}
    - uses: cachix/install-nix-action@08dcb3a5e62fa31e2da3d490afc4176ef55ecd72 # v30
      with:
        nix_path: nixpkgs=channel:nixpkgs-unstable
    - name: Parse all changed or added nix files
      run: |
        ret=0
        while IFS= read -r file; do
          out="$(nix-instantiate --parse "$file")" || { echo "$out" && ret=1; }
        done < "$HOME/changed_files"
        exit "$ret"
      if: ${{ env.CHANGED_FILES && env.CHANGED_FILES != '' }}
