Skip to content

Commit a6b0199

Browse files
committed
feat: add SPDX header check action
Signed-off-by: Simon Scatton <sscatton@nvidia.com>
1 parent f53e2fd commit a6b0199

9 files changed

Lines changed: 503 additions & 0 deletions

File tree

‎.github/workflows/test.yml‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
name: test
2+
3+
on:
4+
push:
5+
pull_request:
6+
7+
jobs:
8+
unit:
9+
strategy:
10+
matrix:
11+
os: [ubuntu-latest, windows-latest, macos-latest]
12+
runs-on: ${{ matrix.os }}
13+
steps:
14+
- uses: actions/checkout@v7
15+
- uses: actions/setup-node@v7
16+
with:
17+
node-version: 24
18+
- run: node --test "spdx-check/test/*.test.mjs"
19+
20+
dogfood:
21+
runs-on: ubuntu-latest
22+
steps:
23+
- uses: actions/checkout@v7
24+
- uses: ./spdx-check
25+
with:
26+
include: "*.mjs"

‎README.md‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
11
# workflows
22

33
Reusable GitHub Actions workflows for the ai-openshell organization.
4+
5+
## spdx-check
6+
7+
Fails the job if a tracked file lacks `SPDX-License-Identifier: Apache-2.0`
8+
in its first 10 lines. It's a JavaScript action with no dependencies, so it
9+
runs as a step in a job you already have, with no setup step.
10+
11+
```yaml
12+
- uses: actions/checkout@v7
13+
- uses: ai-openshell/workflows/spdx-check@main
14+
with:
15+
include: "*.py *.rs *.go Dockerfile* */Dockerfile* scripts/bin/*"
16+
exclude: "third_party/* *_pb2.py"
17+
```
18+
19+
### Inputs
20+
21+
- `include` (required): which files to check.
22+
- `exclude` (optional): which of those files to skip.
23+
24+
Both are [git pathspecs](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec),
25+
separated by spaces or newlines. Only tracked files are checked, so gitignored
26+
paths like `node_modules/` never show up. Under git's default pathspec rules,
27+
`*` also matches `/`:
28+
29+
- `*.py` matches Python files at any depth.
30+
- `Dockerfile*` matches only root-level Dockerfiles. Add `*/Dockerfile*` for
31+
nested ones.
32+
- `scripts/bin/*` matches everything under `scripts/bin/`.
33+
34+
### Rules
35+
36+
- The license must be exactly `Apache-2.0`. The check rejects
37+
`Apache-2.0-only` and `Apache-2.0 OR MIT`.
38+
- Empty files pass.
39+
- For files that can't hold a comment, such as JSON, put the header in a
40+
[REUSE](https://reuse.software/spec/) sidecar named `<file>.license`. When a
41+
sidecar exists, the check reads it instead of the file.
42+
43+
Each failing file gets an error annotation on line 1, and the job summary lists
44+
all of them.

‎spdx-check/action.yml‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
name: SPDX check
2+
description: Check that source files declare SPDX-License-Identifier Apache-2.0 in their first 10 lines.
3+
inputs:
4+
include:
5+
description: Git pathspec patterns of files to check, separated by whitespace or newlines.
6+
required: true
7+
exclude:
8+
description: Git pathspec patterns of files to skip, separated by whitespace or newlines.
9+
required: false
10+
default: ""
11+
runs:
12+
using: node24
13+
main: index.mjs

‎spdx-check/files.mjs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
import { execFileSync } from "node:child_process";
4+
import { existsSync } from "node:fs";
5+
import { join } from "node:path";
6+
7+
export function listFiles({ include, exclude = [], cwd }) {
8+
const excludes = exclude.map((pattern) => `:(exclude)${pattern}`);
9+
const args = ["ls-files", "-z", "--", ...include, ...excludes];
10+
// TODO: report git's error clearly (not a repo, invalid pathspec).
11+
const stdout = execFileSync("git", args, {
12+
cwd,
13+
encoding: "utf8",
14+
maxBuffer: 64 * 1024 * 1024,
15+
});
16+
return stdout.split("\0").filter(Boolean);
17+
}
18+
19+
export function headerSource(path, cwd) {
20+
const sidecar = `${path}.license`;
21+
return existsSync(join(cwd, sidecar)) ? sidecar : path;
22+
}

‎spdx-check/header.mjs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
// Rejects suffixes (-only, +) and compound expressions (OR/AND/WITH).
4+
const SPDX =
5+
/SPDX-License-Identifier:[ \t]*Apache-2\.0(?![A-Za-z0-9.+-]|[ \t]+(?:OR|AND|WITH)\b)/;
6+
7+
export function hasSpdxHeader(buf) {
8+
// An empty file has no content to license.
9+
if (buf.length === 0) return true;
10+
// latin1 maps every byte to a char, so binary or non-UTF-8 input never throws.
11+
const lines = buf.toString("latin1").split("\n", 10);
12+
return lines.some((line) => SPDX.test(line));
13+
}

‎spdx-check/index.mjs‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
import { appendFileSync, closeSync, openSync, readSync } from "node:fs";
4+
import { join } from "node:path";
5+
import { headerSource, listFiles } from "./files.mjs";
6+
import { hasSpdxHeader } from "./header.mjs";
7+
8+
const LICENSE = "SPDX-License-Identifier: Apache-2.0";
9+
const head = Buffer.alloc(8192);
10+
11+
function patterns(value = "") {
12+
return value.split(/\s+/).filter(Boolean);
13+
}
14+
15+
function readHead(path) {
16+
// TODO: handle unreadable entries (submodules, dangling symlinks, deleted files).
17+
const fd = openSync(path, "r");
18+
const bytesRead = readSync(fd, head, 0, head.length, 0);
19+
closeSync(fd);
20+
return head.subarray(0, bytesRead);
21+
}
22+
23+
function findFailures(files, cwd) {
24+
const failures = [];
25+
for (const file of files) {
26+
const src = headerSource(file, cwd);
27+
if (!hasSpdxHeader(readHead(join(cwd, src)))) failures.push(src);
28+
}
29+
return failures.sort();
30+
}
31+
32+
function writeSummary(path, total, failures) {
33+
const lines = [
34+
"### SPDX check",
35+
"",
36+
`Checked ${total} files, ${failures.length} missing \`${LICENSE}\`.`,
37+
"",
38+
...failures.map((failure) => `- \`${failure}\``),
39+
];
40+
appendFileSync(path, lines.join("\n") + "\n");
41+
}
42+
43+
function main() {
44+
const cwd = process.cwd();
45+
// TODO: reject an empty include; git ls-files with no pathspec lists every file.
46+
const include = patterns(process.env.INPUT_INCLUDE);
47+
const exclude = patterns(process.env.INPUT_EXCLUDE);
48+
const files = listFiles({ include, exclude, cwd });
49+
const failures = findFailures(files, cwd);
50+
for (const src of failures) {
51+
console.log(`::error file=${src},line=1::Missing ${LICENSE}`);
52+
}
53+
console.log(
54+
`Checked ${files.length} files, ${failures.length} missing ${LICENSE}`,
55+
);
56+
const summaryPath = process.env.GITHUB_STEP_SUMMARY;
57+
if (summaryPath) writeSummary(summaryPath, files.length, failures);
58+
if (failures.length > 0) process.exitCode = 1;
59+
}
60+
61+
main();

‎spdx-check/test/files.test.mjs‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
import { test, after } from 'node:test';
4+
import assert from 'node:assert/strict';
5+
import { execFileSync } from 'node:child_process';
6+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
7+
import { tmpdir } from 'node:os';
8+
import { dirname, join } from 'node:path';
9+
import { headerSource, listFiles } from '../files.mjs';
10+
11+
const tempDirs = [];
12+
after(() => {
13+
for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true });
14+
});
15+
16+
function writeFiles(root, paths) {
17+
for (const path of paths) {
18+
const full = join(root, ...path.split('/'));
19+
mkdirSync(dirname(full), { recursive: true });
20+
writeFileSync(full, '');
21+
}
22+
}
23+
24+
function makeRepo(paths) {
25+
const root = mkdtempSync(join(tmpdir(), 'spdx-files-'));
26+
tempDirs.push(root);
27+
execFileSync('git', ['init', '-q'], { cwd: root });
28+
writeFiles(root, paths);
29+
execFileSync('git', ['add', '-A'], { cwd: root });
30+
return root;
31+
}
32+
33+
function sorted(list) {
34+
return [...list].sort();
35+
}
36+
37+
test('*.py matches at root and at depth', () => {
38+
const cwd = makeRepo(['a.py', 'pkg/b.py', 'pkg/sub/c.py', 'README.md']);
39+
const files = listFiles({ include: ['*.py'], cwd });
40+
assert.deepEqual(sorted(files), ['a.py', 'pkg/b.py', 'pkg/sub/c.py']);
41+
});
42+
43+
test('Dockerfile* matches root-level files only', () => {
44+
const cwd = makeRepo(['Dockerfile', 'Dockerfile.dev', 'deploy/Dockerfile']);
45+
const files = listFiles({ include: ['Dockerfile*'], cwd });
46+
assert.deepEqual(sorted(files), ['Dockerfile', 'Dockerfile.dev']);
47+
});
48+
49+
test('*/Dockerfile* matches nested files only', () => {
50+
const cwd = makeRepo(['Dockerfile', 'deploy/Dockerfile', 'deploy/Dockerfile.prod']);
51+
const files = listFiles({ include: ['*/Dockerfile*'], cwd });
52+
assert.deepEqual(sorted(files), ['deploy/Dockerfile', 'deploy/Dockerfile.prod']);
53+
});
54+
55+
test('scripts/bin/* matches an extensionless file', () => {
56+
const cwd = makeRepo(['scripts/bin/run', 'scripts/other']);
57+
const files = listFiles({ include: ['scripts/bin/*'], cwd });
58+
assert.deepEqual(files, ['scripts/bin/run']);
59+
});
60+
61+
test('excludes remove matching files', () => {
62+
const cwd = makeRepo(['a.py', 'third_party/x.py', 'proto/m_pb2.py']);
63+
const files = listFiles({
64+
include: ['*.py'],
65+
exclude: ['third_party/*', '*_pb2.py'],
66+
cwd,
67+
});
68+
assert.deepEqual(files, ['a.py']);
69+
});
70+
71+
test('untracked files are ignored', () => {
72+
const cwd = makeRepo(['a.py']);
73+
writeFiles(cwd, ['b.py']);
74+
assert.deepEqual(listFiles({ include: ['*.py'], cwd }), ['a.py']);
75+
});
76+
77+
test('multiple include patterns combine', () => {
78+
const cwd = makeRepo(['a.py', 'b.mjs', 'c.md']);
79+
const files = listFiles({ include: ['*.py', '*.mjs'], cwd });
80+
assert.deepEqual(sorted(files), ['a.py', 'b.mjs']);
81+
});
82+
83+
test('headerSource returns the sidecar when it exists', () => {
84+
const cwd = makeRepo(['x.json', 'x.json.license']);
85+
assert.equal(headerSource('x.json', cwd), 'x.json.license');
86+
});
87+
88+
test('headerSource returns the path when there is no sidecar', () => {
89+
const cwd = makeRepo(['y.json']);
90+
assert.equal(headerSource('y.json', cwd), 'y.json');
91+
});
92+
93+
test('headerSource works for nested paths', () => {
94+
const cwd = makeRepo(['conf/x.json', 'conf/x.json.license']);
95+
assert.equal(headerSource('conf/x.json', cwd), 'conf/x.json.license');
96+
});

‎spdx-check/test/header.test.mjs‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
3+
import { test } from 'node:test';
4+
import assert from 'node:assert/strict';
5+
import { hasSpdxHeader } from '../header.mjs';
6+
7+
const ID = 'SPDX-License-Identifier: Apache-2.0';
8+
9+
function check(text) {
10+
return hasSpdxHeader(Buffer.from(text));
11+
}
12+
13+
function filler(n) {
14+
return 'x\n'.repeat(n);
15+
}
16+
17+
test('empty buffer passes', () => {
18+
assert.equal(hasSpdxHeader(Buffer.alloc(0)), true);
19+
});
20+
21+
test('hash comment passes', () => {
22+
assert.equal(check(`# ${ID}\nprint("hi")\n`), true);
23+
});
24+
25+
test('double-slash comment passes', () => {
26+
assert.equal(check(`// ${ID}\nconsole.log(1);\n`), true);
27+
});
28+
29+
test('multi-line block comment passes', () => {
30+
assert.equal(check(`/*\n * Copyright Foo\n * ${ID}\n */\nint x;\n`), true);
31+
});
32+
33+
test('single-line block comment passes', () => {
34+
assert.equal(check(`/* ${ID} */\nint x;\n`), true);
35+
});
36+
37+
test('html comment passes', () => {
38+
assert.equal(check(`<!-- ${ID} -->\n<p>hi</p>\n`), true);
39+
});
40+
41+
test('shebang then header passes', () => {
42+
assert.equal(check(`#!/usr/bin/env python3\n# ${ID}\n`), true);
43+
});
44+
45+
test('header on line 10 passes', () => {
46+
assert.equal(check(`${filler(9)}# ${ID}\n`), true);
47+
});
48+
49+
test('header on line 11 fails', () => {
50+
assert.equal(check(`${filler(10)}# ${ID}\n`), false);
51+
});
52+
53+
test('CRLF file passes', () => {
54+
assert.equal(check(`#!/bin/sh\r\n# ${ID}\r\necho hi\r\n`), true);
55+
});
56+
57+
test('file without header fails', () => {
58+
assert.equal(check('print("hi")\n'), false);
59+
});
60+
61+
test('MIT fails', () => {
62+
assert.equal(check('# SPDX-License-Identifier: MIT\n'), false);
63+
});
64+
65+
test('Apache-2.0-only is rejected', () => {
66+
assert.equal(check(`# ${ID}-only\n`), false);
67+
});
68+
69+
test('Apache-2.0 OR MIT is rejected', () => {
70+
assert.equal(check(`# ${ID} OR MIT\n`), false);
71+
});
72+
73+
test('Apache-2.0 AND MIT is rejected', () => {
74+
assert.equal(check(`# ${ID} AND MIT\n`), false);
75+
});
76+
77+
test('Apache-2.0 WITH an exception is rejected', () => {
78+
assert.equal(check(`# ${ID} WITH LLVM-exception\n`), false);
79+
});
80+
81+
test('UTF-16 BOM bytes before header still pass', () => {
82+
const buf = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`# ${ID}\n`)]);
83+
assert.equal(hasSpdxHeader(buf), true);
84+
});
85+
86+
test('Latin-1 byte before header still passes', () => {
87+
const buf = Buffer.concat([
88+
Buffer.from('# Caf'),
89+
Buffer.from([0xe9]),
90+
Buffer.from(`\n# ${ID}\n`),
91+
]);
92+
assert.equal(hasSpdxHeader(buf), true);
93+
});
94+
95+
test('NUL bytes around header still pass', () => {
96+
const buf = Buffer.concat([
97+
Buffer.from([0x00, 0x00, 0x0a]),
98+
Buffer.from(`# ${ID}\n`),
99+
Buffer.from([0x00, 0xff]),
100+
]);
101+
assert.equal(hasSpdxHeader(buf), true);
102+
});

0 commit comments

Comments
 (0)