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
3 changes: 3 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: ./spdx-check
with:
include: "*.mjs"
base: ${{ github.event.pull_request.base.sha }}
17 changes: 17 additions & 0 deletions spdx-check/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ runs as a step in a job you already have, with no setup step.

- `include` (required): which files to check.
- `exclude` (optional): which of those files to skip.
- `base` (optional): a git revision, usually the pull request's base commit.
When set, the check also fails if a checked file's header has lost an
`SPDX-FileCopyrightText` notice that it had at `base`. The revision must be
in the checkout, so use `fetch-depth: 0`.

Both are
[git pathspecs](https://git-scm.com/docs/gitglossary#def_pathspec),
Expand All @@ -37,5 +41,18 @@ paths like `node_modules/` never show up. Under git's default pathspec rules,
[REUSE](https://reuse.software/spec/) sidecar named `<file>.license`. When a
sidecar exists, the check reads it instead of the file.

- A notice may move between comment styles and stay within the first 10
lines. Deleted files and notices below line 10 at `base` are not tracked.

Each failing file gets an error annotation on line 1, and the job summary lists
all of them.

```yaml
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: ai-openshell/workflows/spdx-check@main
with:
include: "*.py *.rs"
base: ${{ github.event.pull_request.base.sha }}
```
4 changes: 4 additions & 0 deletions spdx-check/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ inputs:
description: Git pathspec patterns of files to skip, separated by whitespace or newlines.
required: false
default: ""
base:
description: Git revision to compare against. When set, also fail if a checked file's header has lost an SPDX-FileCopyrightText notice it had at this revision.
required: false
default: ""
runs:
using: node24
main: index.mjs
63 changes: 63 additions & 0 deletions spdx-check/copyright.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: Apache-2.0

import { execFileSync } from "node:child_process";

const MARKER = "SPDX-FileCopyrightText:";
const LINES = 10;

// Drops comment syntax so a notice can move between comment styles.
function notice(line) {
const text = line.slice(line.indexOf(MARKER)).trim();
return text.replace(/(?:-->|\*\/)$/, "").trimEnd();
}

export function headerNotices(buf) {
return buf
.toString("latin1")
.split("\n", LINES)
.filter((line) => line.includes(MARKER))
.map(notice);
}

// Maps each source to the notices in its first 10 lines at base.
function baseNotices(base, sources, cwd) {
const args = ["grep", "-I", "-n", "-z", "-F", "-e", MARKER];
let stdout;
try {
stdout = execFileSync("git", [...args, "--end-of-options", base, "--"], {
cwd,
maxBuffer: 64 * 1024 * 1024,
stdio: ["ignore", "pipe", "pipe"],
});
} catch (err) {
if (err.status === 1) return new Map();
const reason = err.stderr?.toString().trim() || err.message;
throw new Error(
`Cannot read base ${base} (${reason}). Fetch it, for example with fetch-depth: 0.`,
);
}

const wanted = new Set(sources);
const prefix = `${base}:`;
const found = new Map();
for (const record of stdout.toString("latin1").split("\n")) {
if (!record) continue;
const [location, lineno, line] = record.split("\0");
const src = location.slice(prefix.length);
if (Number(lineno) > LINES || !wanted.has(src)) continue;
found.set(src, [...(found.get(src) ?? []), notice(line)]);
}
return found;
}

// Lists notices in a source's header at base that its header now lacks.
export function findRemoved(base, sources, cwd, readHeader) {
const removed = [];
for (const [src, notices] of baseNotices(base, sources, cwd)) {
const kept = new Set(headerNotices(readHeader(src)));
for (const text of notices) {
if (!kept.has(text)) removed.push({ src, notice: text });
}
}
return removed.sort((a, b) => (a.src < b.src ? -1 : a.src > b.src ? 1 : 0));
}
54 changes: 36 additions & 18 deletions spdx-check/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { appendFileSync, closeSync, openSync, readSync } from "node:fs";
import { join } from "node:path";
import { findRemoved } from "./copyright.mjs";
import { headerSource, listFiles } from "./files.mjs";
import { hasHeaderLines, hasSpdxHeader } from "./header.mjs";

Expand Down Expand Up @@ -34,37 +35,54 @@ function readHead(path) {
return buf.subarray(0, size);
}

function findFailures(files, cwd) {
return files
.map((file) => headerSource(file, cwd))
.filter((src) => !hasSpdxHeader(readHead(join(cwd, src))))
.sort();
}

// Escaped so a file name can't break out of the workflow command.
function annotation(src) {
// Escaped so a file name or notice can't break out of the workflow command.
function annotation(src, message) {
const file = src.replace(/[%\r\n:,]/g, (char) => ESCAPES[char]);
return `::error file=${file},line=1::Missing ${LICENSE}`;
const text = message.replace(/[%\r\n]/g, (char) => ESCAPES[char]);
return `::error file=${file},line=1::${text}`;
}

function writeSummary(path, result, failures) {
const list = failures.map((src) => `- \`${src}\`\n`).join("");
appendFileSync(path, `### SPDX check\n\n${result}\n\n${list}`);
function writeSummary(path, result, failures, removed) {
const missing = failures.map((src) => `- \`${src}\`\n`).join("");
const lost = removed
.map(({ src, notice }) => `- \`${src}\`: ${notice}\n`)
.join("");
appendFileSync(path, `### SPDX check\n\n${result}\n\n${missing}${lost}`);
}

function main() {
const cwd = process.cwd();
// TODO: reject an empty include; git ls-files with no pathspec lists every file.
const include = patterns(process.env.INPUT_INCLUDE);
const exclude = patterns(process.env.INPUT_EXCLUDE);
const base = process.env.INPUT_BASE?.trim();
const files = listFiles({ include, exclude, cwd });
const failures = findFailures(files, cwd);
const result = `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`;
failures.forEach((src) => console.log(annotation(src)));
const sources = files.map((file) => headerSource(file, cwd));
const readHeader = (src) => readHead(join(cwd, src));
const failures = sources.filter((src) => !hasSpdxHeader(readHeader(src)));
failures.sort();
let removed = [];
try {
if (base) removed = findRemoved(base, sources, cwd, readHeader);
} catch (err) {
console.log(
`::error::${err.message.replace(/[%\r\n]/g, (c) => ESCAPES[c])}`,
);
process.exitCode = 1;
return;
}

let result = `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`;
if (base)
result += `, ${removed.length} copyright notices removed since ${base}`;
failures.forEach((src) => console.log(annotation(src, `Missing ${LICENSE}`)));
removed.forEach(({ src, notice }) =>
console.log(annotation(src, `Removed ${notice}`)),
);
console.log(result);
const summary = process.env.GITHUB_STEP_SUMMARY;
if (summary) writeSummary(summary, result, failures);
if (failures.length > 0) process.exitCode = 1;
if (summary) writeSummary(summary, result, failures, removed);
if (failures.length > 0 || removed.length > 0) process.exitCode = 1;
}

main();
152 changes: 149 additions & 3 deletions spdx-check/test/index.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import { test } from "node:test";
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { readFileSync, writeFileSync } from "node:fs";
import { execFileSync, spawnSync } from "node:child_process";
import { readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { makeRepo, tempDir } from "./repo.mjs";
import { commit, makeRepo, tempDir, writeFiles } from "./repo.mjs";

const INDEX = fileURLToPath(new URL("../index.mjs", import.meta.url));
const HEADER = "# SPDX-License-Identifier: Apache-2.0\n";
Expand Down Expand Up @@ -162,3 +162,149 @@ test("step summary is appended with failing paths", () => {
assert.ok(text.includes("m/b.py"), text);
assert.equal(status, 1);
});

const COPYRIGHT = "SPDX-FileCopyrightText: Copyright (c) 2025 Example Corp";
const LICENSED = `# ${COPYRIGHT}\n${HEADER}x\n`;

function removed(path, notice = COPYRIGHT) {
return `::error file=${path},line=1::Removed ${notice}`;
}

// Commits `files` as the base, then applies `changes`; null deletes a file.
function repoWithBase(files, changes) {
const cwd = makeRepo(files);
const base = commit(cwd);
for (const [path, content] of Object.entries(changes)) {
if (content === null) rmSync(join(cwd, path));
else writeFiles(cwd, { [path]: content });
}
return { cwd, base };
}

test("a kept copyright notice passes", () => {
const { cwd, base } = repoWithBase(
{ "a.py": LICENSED },
{ "a.py": `${LICENSED}y\n` },
);
const { status, errors, stderr } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: base,
});
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("a removed copyright notice is annotated", () => {
const { cwd, base } = repoWithBase(
{ "a.py": LICENSED },
{ "a.py": `${HEADER}x\n` },
);
const { status, errors } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: base,
});
assert.deepEqual(errors, [removed("a.py")]);
assert.equal(status, 1);
});

test("a removed notice passes without a base", () => {
const { cwd } = repoWithBase(
{ "a.py": LICENSED },
{ "a.py": `${HEADER}x\n` },
);
const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: "*.py" });
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("a notice may change comment style", () => {
const { cwd, base } = repoWithBase(
{ "a.css": `/* ${COPYRIGHT} */\n/* ${HEADER.slice(2, -1)} */\n` },
{ "a.css": `/*\n * ${COPYRIGHT}\n * ${HEADER.slice(2)} */\n` },
);
const { status, errors, stderr } = run(cwd, {
INPUT_INCLUDE: "*.css",
INPUT_BASE: base,
});
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("a deleted file is not reported", () => {
const { cwd, base } = repoWithBase(
{ "a.py": LICENSED, "b.py": HEADER },
{ "a.py": null },
);
execFileSync("git", ["add", "-A"], { cwd });
const { status, errors, stderr } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: base,
});
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("a notice removed from a sidecar is annotated on the sidecar", () => {
const { cwd, base } = repoWithBase(
{ "c.json": "{}\n", "c.json.license": `${COPYRIGHT}\n${HEADER.slice(2)}` },
{ "c.json.license": HEADER.slice(2) },
);
const { status, errors } = run(cwd, {
INPUT_INCLUDE: "*.json",
INPUT_BASE: base,
});
assert.deepEqual(errors, [removed("c.json.license")]);
assert.equal(status, 1);
});

test("notices below line 10 at the base are not tracked", () => {
const body = `${HEADER}${"x\n".repeat(10)}# ${COPYRIGHT}\n`;
const { cwd, base } = repoWithBase({ "a.py": body }, { "a.py": HEADER });
const { status, errors, stderr } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: base,
});
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("excluded files are not checked for removed notices", () => {
const { cwd, base } = repoWithBase(
{ "vendor/a.py": LICENSED },
{ "vendor/a.py": "x\n" },
);
const { status, errors, stderr } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_EXCLUDE: "vendor/*",
INPUT_BASE: base,
});
assert.deepEqual(errors, []);
assert.equal(status, 0, stderr);
});

test("an unknown base fails the step", () => {
const cwd = makeRepo({ "a.py": HEADER });
commit(cwd);
const { status, errors } = run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: "0".repeat(40),
});
assert.equal(errors.length, 1);
assert.match(errors[0], /^::error::Cannot read base 0{40}/);
assert.equal(status, 1);
});

test("summary lists removed notices", () => {
const { cwd, base } = repoWithBase(
{ "a.py": LICENSED },
{ "a.py": `${HEADER}x\n` },
);
const summary = join(tempDir(), "summary.md");
run(cwd, {
INPUT_INCLUDE: "*.py",
INPUT_BASE: base,
GITHUB_STEP_SUMMARY: summary,
});
const text = readFileSync(summary, "utf8");
assert.ok(text.includes(`\`a.py\`: ${COPYRIGHT}`), text);
});
12 changes: 12 additions & 0 deletions spdx-check/test/repo.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,15 @@ export function makeRepo(files) {
execFileSync("git", ["add", "-A"], { cwd: root });
return root;
}

// Commits the index with a throwaway identity and returns the commit id.
export function commit(root) {
const identity = ["-c", "user.name=t", "-c", "user.email=t@example.com"];
execFileSync("git", [...identity, "commit", "-q", "-m", "base"], {
cwd: root,
});
return execFileSync("git", ["rev-parse", "HEAD"], {
cwd: root,
encoding: "utf8",
}).trim();
}