From 0dc9dc0689d30ecc7b34f474f919cc771daf3c4e Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Sun, 22 Nov 2026 23:26:23 +0800 Subject: [PATCH] feat: add reusable GitHub Action with sticky PR summary comment --- action.yml | 129 ++++++++++++++++++++++++++++ docs/guide/ci-and-github-actions.md | 42 ++++++++- scripts/action-comment.mjs | 82 ++++++++++++++++++ scripts/action-comment.test.mjs | 36 ++++++++ 4 files changed, 286 insertions(+), 3 deletions(-) create mode 100644 action.yml create mode 100644 scripts/action-comment.mjs create mode 100644 scripts/action-comment.test.mjs diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..dd1f219 --- /dev/null +++ b/action.yml @@ -0,0 +1,129 @@ +name: codeint +description: Measure Software entropy, gate pull requests on Regressions, post a sticky PR summary comment, and optionally upload SARIF. + +branding: + icon: activity + color: green + +inputs: + base-ref: + description: Base Git ref to diff against (defaults to origin/ on pull requests). + required: false + default: "" + path: + description: Directory to measure inside the repository. + required: false + default: "." + version: + description: Release tag to install (for example v0.4.0) or latest. + required: false + default: "latest" + comment: + description: Post or update a sticky pull-request summary comment. + required: false + default: "true" + upload-sarif: + description: Upload codeint.sarif to GitHub code scanning (requires security-events write permission). + required: false + default: "false" + fail-on-regression: + description: Fail the workflow step when codeint diff exits 1 on a Budget or Regression failure. + required: false + default: "true" + token: + description: GitHub token used to post or update the sticky pull-request comment. + required: false + default: ${{ github.token }} + +outputs: + exit-code: + description: Exit code returned by codeint diff. + value: ${{ steps.diff.outputs.exit-code }} + sarif-file: + description: Path to the generated SARIF report when upload-sarif is enabled. + value: ${{ steps.diff.outputs.sarif-file }} + markdown-file: + description: Path to the generated Markdown report. + value: ${{ steps.diff.outputs.markdown-file }} + +runs: + using: composite + steps: + - name: Install codeint + shell: bash + env: + INPUT_VERSION: ${{ inputs.version }} + run: | + set -euo pipefail + if [ "$INPUT_VERSION" = "latest" ]; then + URL="https://github.com/avidianity/codeint/releases/latest/download/install.sh" + else + URL="https://github.com/avidianity/codeint/releases/download/${INPUT_VERSION}/install.sh" + fi + curl -fsSL "$URL" | bash + echo "$HOME/.local/bin" >> "$GITHUB_PATH" + + - name: Run codeint diff + id: diff + shell: bash + env: + INPUT_BASE_REF: ${{ inputs.base-ref }} + INPUT_PATH: ${{ inputs.path }} + INPUT_UPLOAD_SARIF: ${{ inputs.upload-sarif }} + GITHUB_BASE_REF: ${{ github.base_ref }} + run: | + set -euo pipefail + BASE="$INPUT_BASE_REF" + if [ -z "$BASE" ]; then + if [ -n "$GITHUB_BASE_REF" ]; then + BASE="origin/$GITHUB_BASE_REF" + else + BASE="HEAD~1" + fi + fi + MD_FILE="codeint-report.md" + SARIF_FILE="codeint.sarif" + set +e + codeint diff "$BASE" "$INPUT_PATH" --format markdown --output "$MD_FILE" + EXIT_CODE=$? + set -e + echo "exit-code=$EXIT_CODE" >> "$GITHUB_OUTPUT" + echo "markdown-file=$MD_FILE" >> "$GITHUB_OUTPUT" + if [ "$INPUT_UPLOAD_SARIF" = "true" ]; then + set +e + codeint diff "$BASE" "$INPUT_PATH" --format sarif --output "$SARIF_FILE" + set -e + echo "sarif-file=$SARIF_FILE" >> "$GITHUB_OUTPUT" + fi + + - name: Post or update sticky pull-request comment + if: inputs.comment == 'true' && github.event_name == 'pull_request' + shell: bash + env: + GITHUB_TOKEN: ${{ inputs.token }} + GITHUB_REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPORT_FILE: ${{ steps.diff.outputs.markdown-file }} + DIFF_EXIT_CODE: ${{ steps.diff.outputs.exit-code }} + ACTION_PATH: ${{ github.action_path }} + run: node "$ACTION_PATH/scripts/action-comment.mjs" + + - name: Upload SARIF + if: inputs.upload-sarif == 'true' && hashFiles('codeint.sarif') != '' + uses: github/codeql-action/upload-sarif@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea + with: + sarif_file: codeint.sarif + + - name: Enforce exit code + shell: bash + env: + DIFF_EXIT_CODE: ${{ steps.diff.outputs.exit-code }} + FAIL_ON_REGRESSION: ${{ inputs.fail-on-regression }} + run: | + set -euo pipefail + if [ "$DIFF_EXIT_CODE" = "2" ]; then + exit 2 + fi + if [ "$DIFF_EXIT_CODE" = "1" ] && [ "$FAIL_ON_REGRESSION" = "true" ]; then + exit 1 + fi diff --git a/docs/guide/ci-and-github-actions.md b/docs/guide/ci-and-github-actions.md index 3801412..8a4fd8c 100644 --- a/docs/guide/ci-and-github-actions.md +++ b/docs/guide/ci-and-github-actions.md @@ -2,9 +2,45 @@ Run `codeint diff` on every pull request so Software entropy Regressions are caught before merge. -## GitHub Actions workflow +## One-line GitHub Action (recommended) -Add `.github/workflows/codeint.yml` to diff against the pull request base branch and upload SARIF findings to GitHub code scanning: +Use the reusable `avidianity/codeint` action to install codeint, diff against the pull-request base, and maintain one updating sticky pull-request summary comment: + +```yaml +name: codeint + +on: + pull_request: + +permissions: + contents: read + pull-requests: write + +jobs: + codeint: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + fetch-depth: 0 + - uses: avidianity/codeint@main +``` + +### Action inputs + +| Input | Default | Description | +| ----- | ------- | ----------- | +| `base-ref` | `origin/` | Base Git ref to diff against. | +| `path` | `.` | Directory to measure inside the repository. | +| `version` | `latest` | Release tag (for example `v0.4.0`) or `latest`. | +| `comment` | `true` | Post or update one sticky pull-request summary comment. | +| `upload-sarif` | `false` | Upload `codeint.sarif` to GitHub code scanning (requires `security-events: write`). | +| `fail-on-regression` | `true` | Fail the step when `codeint diff` exits `1`. | +| `token` | `${{ github.token }}` | Token used to post or update the pull-request comment. | + +## Manual workflow with SARIF upload + +If you prefer calling the CLI directly without the composite action: ```yaml name: codeint @@ -41,5 +77,5 @@ jobs: ## Notes - `fetch-depth: 0` fetches full branch history so `codeint diff` can compute the Git merge-base. -- `if: always() && hashFiles('codeint.sarif') != ''` ensures SARIF annotations still upload when `codeint diff` exits `1` on a Budget or Regression failure. +- Grant `pull-requests: write` for sticky pull-request comments, and `security-events: write` when `upload-sarif: true`. - To tune Budgets or Regression tolerances, edit `codeint.json`; see [Configuration](./configuration.md). diff --git a/scripts/action-comment.mjs b/scripts/action-comment.mjs new file mode 100644 index 0000000..bbaa48a --- /dev/null +++ b/scripts/action-comment.mjs @@ -0,0 +1,82 @@ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const STICKY_MARKER = ""; +const MAX_BODY_CHARS = 60000; + +export function buildCommentBody(markdown, exitCode) { + const status = + exitCode === 0 + ? "Passed (no Budget or Regression failures)" + : exitCode === 1 + ? "Failed (Budget or Regression exceeded)" + : `Error (exit code ${exitCode})`; + const trimmed = markdown.trim(); + const content = + trimmed.length > MAX_BODY_CHARS + ? `${trimmed.slice(0, MAX_BODY_CHARS)}\n\n_(Report truncated to fit GitHub comment size limits.)_` + : trimmed; + return `${STICKY_MARKER}\n## codeint Software entropy diff\n\n**Status:** ${status}\n\n${content}\n`; +} + +export function findStickyCommentId(comments) { + const existing = comments.find( + (item) => typeof item?.body === "string" && item.body.includes(STICKY_MARKER) + ); + return existing ? existing.id : null; +} + +async function githubRequest(url, token, options = {}) { + const response = await fetch(url, { + ...options, + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${token}`, + "User-Agent": "codeint-action", + "X-GitHub-Api-Version": "2022-11-28", + ...options.headers, + }, + }); + if (!response.ok) { + throw new Error(`GitHub API ${response.status} for ${url}`); + } + return response.json(); +} + +async function runFromEnv() { + const token = process.env.GITHUB_TOKEN; + const repo = process.env.GITHUB_REPOSITORY; + const prNumber = process.env.PR_NUMBER; + const reportFile = process.env.REPORT_FILE; + const exitCode = Number(process.env.DIFF_EXIT_CODE ?? "0"); + if (!token || !repo || !prNumber || !reportFile || !fs.existsSync(reportFile)) { + return; + } + const markdown = fs.readFileSync(reportFile, "utf8"); + const body = buildCommentBody(markdown, exitCode); + const apiBase = process.env.GITHUB_API_URL || "https://api.github.com"; + const listUrl = `${apiBase}/repos/${repo}/issues/${prNumber}/comments?per_page=100`; + const comments = await githubRequest(listUrl, token); + const existingId = findStickyCommentId(comments); + if (existingId) { + await githubRequest(`${apiBase}/repos/${repo}/issues/comments/${existingId}`, token, { + method: "PATCH", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ body }), + }); + } else { + await githubRequest(`${apiBase}/repos/${repo}/issues/${prNumber}/comments`, token, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ body }), + }); + } +} + +const isEntrypoint = + process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); + +if (isEntrypoint) { + await runFromEnv(); +} diff --git a/scripts/action-comment.test.mjs b/scripts/action-comment.test.mjs new file mode 100644 index 0000000..3821441 --- /dev/null +++ b/scripts/action-comment.test.mjs @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + STICKY_MARKER, + buildCommentBody, + findStickyCommentId, +} from "./action-comment.mjs"; + +test("buildCommentBody includes sticky marker and status", () => { + const ok = buildCommentBody("| Metric | Base | Head |", 0); + assert.ok(ok.startsWith(STICKY_MARKER)); + assert.ok(ok.includes("Passed (no Budget or Regression failures)")); + assert.ok(ok.includes("| Metric | Base | Head |")); + + const failed = buildCommentBody("regression details", 1); + assert.ok(failed.includes("Failed (Budget or Regression exceeded)")); +}); + +test("buildCommentBody truncates oversized reports cleanly", () => { + const huge = "x".repeat(70000); + const body = buildCommentBody(huge, 0); + assert.ok(body.length < 61000); + assert.ok(body.includes("Report truncated")); +}); + +test("findStickyCommentId finds existing marker or returns null", () => { + assert.equal( + findStickyCommentId([ + { id: 10, body: "unrelated comment" }, + { id: 42, body: `${STICKY_MARKER}\nold report` }, + ]), + 42 + ); + assert.equal(findStickyCommentId([{ id: 10, body: "plain" }]), null); +});