Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
@@ -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/<github.base_ref> 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
42 changes: 39 additions & 3 deletions docs/guide/ci-and-github-actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<github.base_ref>` | 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
Expand Down Expand Up @@ -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).
82 changes: 82 additions & 0 deletions scripts/action-comment.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

export const STICKY_MARKER = "<!-- codeint-pr-comment -->";
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();
}
36 changes: 36 additions & 0 deletions scripts/action-comment.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
});