name: WordPress Theme Check on: pull_request: types: [opened, labeled, synchronize] # One run per PR. A new push cancels the run still in flight for the same PR, # rather than queueing a second Playground run behind it. concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number }} cancel-in-progress: true env: SECEX_EGRESS_RULES: registry.npmjs.org,nodejs.org,api.github.com,github.com,codeload.github.com,objects.githubusercontent.com,release-assets.githubusercontent.com,raw.githubusercontent.com,api.wordpress.org,downloads.wordpress.org,wordpress.org,downloads.w.org,playground.wordpress.net permissions: contents: read pull-requests: write jobs: theme-check: # Theme Check runs on WordPress Playground (PHP-WASM in Node), so this job no # longer needs Docker. runs-on: [self-hosted, secex, gha-runner-2cpu-4gb] steps: - name: Checkout code uses: actions/checkout@a37ce9120846195fa4ece8f58b268e6043cb2f26 # v3.7.0 # Pinned to 20 deliberately. @wp-playground/cli pulls a native dependency # (fs-ext-extra-prebuilt) that fails to build on Node 26 — npm install dies with a # node-gyp error, and npx fails silently with exit 1 and no output. - name: Setup Node.js uses: actions/setup-node@3235b876344d2a9aa001b8d1453c930bba69e610 # v3.9.1 with: node-version: '20' - name: Install @wp-playground/cli run: npm install -g @wp-playground/cli - name: Get changed root folders uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1 with: script: | const fs = require('fs'); const path = require('path'); const { owner, repo, number } = context.issue; let allFiles = []; let page = 1; while (true) { const { data: files } = await github.rest.pulls.listFiles({ owner, repo, pull_number: number, per_page: 100, page: page }); allFiles = allFiles.concat(files); if (files.length < 100) break; page++; } console.log('files', allFiles.map(file => file.filename)); const rootFolders = new Set(); for (const file of allFiles) { const parts = file.filename.split('/'); if (parts.length > 1 && !parts[0].startsWith('.')) { rootFolders.add(parts[0]); } } // Keep only directories that still exist and actually are themes. A PR can // touch common/ or delete a theme outright, and `theme-check run ` errors // out on anything that isn't a theme WordPress can see. const themeFolders = Array.from(rootFolders).filter(folder => { if (!/^[A-Za-z0-9_-]+$/.test(folder)) return false; return fs.existsSync(path.join(process.env.GITHUB_WORKSPACE, folder, 'style.css')); }); core.exportVariable('THEME_FOLDERS', themeFolders.join(',')); console.log(`Changed theme folders: ${themeFolders.join(', ')}`); // A theme that isn't on the base branch yet is a new theme. New themes go // through the /theme-review skill, which reports Theme Check's warnings and // recommendations, so the comment below lists only their REQUIRED items. const baseRef = context.payload.pull_request.base.ref; const newThemeFolders = []; for (const folder of themeFolders) { try { await github.rest.repos.getContent({ owner, repo, path: `${folder}/style.css`, ref: baseRef }); } catch (error) { if (error.status !== 404) throw error; newThemeFolders.push(folder); } } core.exportVariable('NEW_THEME_FOLDERS', newThemeFolders.join(',')); console.log(`New theme folders: ${newThemeFolders.join(', ')}`); - name: Debug THEME_FOLDERS run: echo "THEME_FOLDERS is ${{ env.THEME_FOLDERS }}" - name: Run Theme Check for each folder if: env.THEME_FOLDERS != '' run: | OUT_DIR="$RUNNER_TEMP/theme-check-out" RUNNER_DIR="$RUNNER_TEMP/theme-check-runner" mkdir -p "$OUT_DIR" "$RUNNER_DIR" echo "THEME_CHECK_OUT_DIR=$OUT_DIR" >> $GITHUB_ENV # `wp theme-check run` exits 1 whenever it finds a REQUIRED item, which would abort # the Blueprint. Capture the result in PHP instead and always write it to a file. cat > "$RUNNER_DIR/one.php" <<'PHP' 'all', 'exit_error' => false, 'launch' => false, ) ); file_put_contents( '/output/' . $slug . '.json', json_encode( array( 'slug' => $slug, 'exit_code' => $result->return_code, 'messages' => json_decode( $result->stdout, true ), 'stderr' => $result->stderr, ) ) ); PHP # Each theme gets its own `wp-cli` step. Theme Check accumulates results in a global # ($themechecks) that it never resets, so checking several themes in one PHP process # leaks the first theme's findings into every later theme's report. A separate step # is a separate PHP process, which keeps the runs independent. STEPS="" MOUNTS=() MOUNTED=" " IFS=',' read -ra FOLDERS <<< "${{ env.THEME_FOLDERS }}" for THEME_FOLDER in "${FOLDERS[@]}"; do echo "Queueing theme folder: $THEME_FOLDER" # A PR that changes a parent theme and its children mounts the parent twice: # once as an earlier child's parent, once as a folder in its own right. Playground # rejects the second mount and aborts the whole run, so every theme comes back # without a result. if [[ "$MOUNTED" != *" $THEME_FOLDER "* ]]; then MOUNTS+=("--mount=$GITHUB_WORKSPACE/$THEME_FOLDER:/wordpress/wp-content/themes/$THEME_FOLDER") MOUNTED="$MOUNTED$THEME_FOLDER " fi # Child themes only resolve if the parent is mounted alongside them. The value # comes from the PR's own style.css, so hold it to the same charset as the slugs # above before it reaches a mount path. PARENT=$(sed -n 's/^[[:space:]]*Template:[[:space:]]*//p' "$GITHUB_WORKSPACE/$THEME_FOLDER/style.css" | head -1 | tr -d '\r' | xargs || true) if [ -n "$PARENT" ] && [[ "$PARENT" =~ ^[A-Za-z0-9_-]+$ ]] && [ -d "$GITHUB_WORKSPACE/$PARENT" ] && [[ "$MOUNTED" != *" $PARENT "* ]]; then echo " parent theme: $PARENT" MOUNTS+=("--mount=$GITHUB_WORKSPACE/$PARENT:/wordpress/wp-content/themes/$PARENT") MOUNTED="$MOUNTED$PARENT " fi STEPS="$STEPS{\"step\":\"wp-cli\",\"command\":\"wp eval-file /runner/one.php $THEME_FOLDER\"}," done cat > "$RUNNER_TEMP/blueprint.json" <> $GITHUB_ENV set -e ls -la "$OUT_DIR" - name: Find and delete previous comment uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1 with: github-token: ${{secrets.GITHUB_TOKEN}} script: | const { owner, repo, number } = context.issue; const { data: comments } = await github.rest.issues.listComments({ owner, repo, issue_number: number, }); const botComment = comments.find(comment => comment.user.type === 'Bot' && comment.body.includes('Theme-Check results') ); if (botComment) { await github.rest.issues.deleteComment({ owner, repo, comment_id: botComment.id, }); } - name: Comment PR if: env.THEME_FOLDERS != '' uses: actions/github-script@d7906e4ad0b1822421a7e6a35d5ca353c962f410 # v6.4.1 with: github-token: ${{secrets.GITHUB_TOKEN}} script: | const fs = require('fs'); const path = require('path'); const outDir = process.env.THEME_CHECK_OUT_DIR; let fullComment = ''; const folders = process.env.THEME_FOLDERS.split(','); const newFolders = (process.env.NEW_THEME_FOLDERS || '').split(',').filter(Boolean); let hasErrors = false; let hasThemeSections = false; const emojis = { 'REQUIRED': '❎', 'WARNING': '⚠️', 'RECOMMENDED': '💡', 'INFO': 'ℹ️', }; fullComment += 'Theme-Check results\n'; fullComment += '--- \n'; for (const folder of folders) { const resultFile = path.join(outDir, `${folder}.json`); if (!fs.existsSync(resultFile)) { console.log(`No Theme Check result written for ${folder}`); fullComment += `### ${folder}: Theme Check did not run ❌.\n`; fullComment += 'Playground did not produce a result for this theme. See the workflow log.\n'; fullComment += '--- \n'; hasErrors = true; continue; } const result = JSON.parse(fs.readFileSync(resultFile, 'utf8')); const comments = result.messages; const themeCheckExitCode = result.exit_code; console.log(`Theme Check Result for ${folder}: ${JSON.stringify(comments)}`); console.log(`Theme Check Exit Code for ${folder}: ${themeCheckExitCode}`); if (themeCheckExitCode !== 0) { hasErrors = true; } if (!Array.isArray(comments)) { console.log(`Theme Check stderr for ${folder}: ${result.stderr}`); fullComment += `### ${folder}: Theme Check did not run ❌.\n`; fullComment += 'Theme Check returned no parsable output. See the workflow log.\n'; fullComment += '--- \n'; hasErrors = true; continue; } // A new theme with no REQUIRED items gets no section: /theme-review reports its // warnings and recommendations. const isNewTheme = newFolders.includes(folder); if (isNewTheme && themeCheckExitCode === 0) { continue; } hasThemeSections = true; if (themeCheckExitCode !== 0) { fullComment += `### ${folder}: There are required changes on the theme ❌.\n`; } else { fullComment += `### ${folder}: No changes required ✅.\n`; } const groupedComments = {}; for (const check of comments) { if (!groupedComments[check.type]) { groupedComments[check.type] = []; } groupedComments[check.type].push(check.value); } // Add REQUIRED comments to the main body for (const type of ['REQUIRED']) { if (groupedComments[type]) { fullComment += `**${emojis[type]} ${type}**\n`; groupedComments[type].forEach(value => { fullComment += `- ${value}\n`; }); fullComment += '\n'; } } for (const [type, groupComments] of Object.entries(groupedComments)) { if (type !== 'REQUIRED' && type !== 'INFO' && !isNewTheme) { fullComment += `
\n${emojis[type]} ${type} (${groupComments.length})\n\n`; groupComments.forEach(value => { fullComment += `- ${value}\n`; }); fullComment += '\n
\n\n'; } } fullComment += '--- \n'; } // A Playground failure (as opposed to Theme Check reporting problems) would // otherwise pass silently in the case where every theme still has a result file. if (process.env.PLAYGROUND_EXIT_CODE !== '0') { fullComment += `Playground exited with code ${process.env.PLAYGROUND_EXIT_CODE}. See the workflow log.\n`; hasErrors = true; } // Skip the comment when every changed theme is new and has no REQUIRED items. if (!hasThemeSections && !hasErrors) { return; } // Post message. This could be optional in the future when theme-check 'fails' on all the REQUIRED change. // Example issue that needs to be fixed: https://github.com/WordPress/theme-check/issues/465 github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: fullComment }); if (hasErrors) { core.setFailed('One or more themes have required changes. Please review the comments and make necessary updates.'); }