From a6b01990776fb308a331048ecd2e7760cd0b3e61 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 15:38:03 +0100 Subject: [PATCH 1/9] feat: add SPDX header check action Signed-off-by: Simon Scatton --- .github/workflows/test.yml | 26 +++++++ README.md | 41 ++++++++++ spdx-check/action.yml | 13 ++++ spdx-check/files.mjs | 22 ++++++ spdx-check/header.mjs | 13 ++++ spdx-check/index.mjs | 61 +++++++++++++++ spdx-check/test/files.test.mjs | 96 ++++++++++++++++++++++++ spdx-check/test/header.test.mjs | 102 +++++++++++++++++++++++++ spdx-check/test/index.test.mjs | 129 ++++++++++++++++++++++++++++++++ 9 files changed, 503 insertions(+) create mode 100644 .github/workflows/test.yml create mode 100644 spdx-check/action.yml create mode 100644 spdx-check/files.mjs create mode 100644 spdx-check/header.mjs create mode 100644 spdx-check/index.mjs create mode 100644 spdx-check/test/files.test.mjs create mode 100644 spdx-check/test/header.test.mjs create mode 100644 spdx-check/test/index.test.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..2ddd16a --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,26 @@ +name: test + +on: + push: + pull_request: + +jobs: + unit: + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 + with: + node-version: 24 + - run: node --test "spdx-check/test/*.test.mjs" + + dogfood: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: ./spdx-check + with: + include: "*.mjs" diff --git a/README.md b/README.md index ae44eeb..4b2cd02 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,44 @@ # workflows Reusable GitHub Actions workflows for the ai-openshell organization. + +## spdx-check + +Fails the job if a tracked file lacks `SPDX-License-Identifier: Apache-2.0` +in its first 10 lines. It's a JavaScript action with no dependencies, so it +runs as a step in a job you already have, with no setup step. + +```yaml +- uses: actions/checkout@v7 +- uses: ai-openshell/workflows/spdx-check@main + with: + include: "*.py *.rs *.go Dockerfile* */Dockerfile* scripts/bin/*" + exclude: "third_party/* *_pb2.py" +``` + +### Inputs + +- `include` (required): which files to check. +- `exclude` (optional): which of those files to skip. + +Both are [git pathspecs](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec), +separated by spaces or newlines. Only tracked files are checked, so gitignored +paths like `node_modules/` never show up. Under git's default pathspec rules, +`*` also matches `/`: + +- `*.py` matches Python files at any depth. +- `Dockerfile*` matches only root-level Dockerfiles. Add `*/Dockerfile*` for + nested ones. +- `scripts/bin/*` matches everything under `scripts/bin/`. + +### Rules + +- The license must be exactly `Apache-2.0`. The check rejects + `Apache-2.0-only` and `Apache-2.0 OR MIT`. +- Empty files pass. +- For files that can't hold a comment, such as JSON, put the header in a + [REUSE](https://reuse.software/spec/) sidecar named `.license`. When a + sidecar exists, the check reads it instead of the file. + +Each failing file gets an error annotation on line 1, and the job summary lists +all of them. diff --git a/spdx-check/action.yml b/spdx-check/action.yml new file mode 100644 index 0000000..2975128 --- /dev/null +++ b/spdx-check/action.yml @@ -0,0 +1,13 @@ +name: SPDX check +description: Check that source files declare SPDX-License-Identifier Apache-2.0 in their first 10 lines. +inputs: + include: + description: Git pathspec patterns of files to check, separated by whitespace or newlines. + required: true + exclude: + description: Git pathspec patterns of files to skip, separated by whitespace or newlines. + required: false + default: "" +runs: + using: node24 + main: index.mjs diff --git a/spdx-check/files.mjs b/spdx-check/files.mjs new file mode 100644 index 0000000..3032504 --- /dev/null +++ b/spdx-check/files.mjs @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; + +export function listFiles({ include, exclude = [], cwd }) { + const excludes = exclude.map((pattern) => `:(exclude)${pattern}`); + const args = ["ls-files", "-z", "--", ...include, ...excludes]; + // TODO: report git's error clearly (not a repo, invalid pathspec). + const stdout = execFileSync("git", args, { + cwd, + encoding: "utf8", + maxBuffer: 64 * 1024 * 1024, + }); + return stdout.split("\0").filter(Boolean); +} + +export function headerSource(path, cwd) { + const sidecar = `${path}.license`; + return existsSync(join(cwd, sidecar)) ? sidecar : path; +} diff --git a/spdx-check/header.mjs b/spdx-check/header.mjs new file mode 100644 index 0000000..0c7519d --- /dev/null +++ b/spdx-check/header.mjs @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Rejects suffixes (-only, +) and compound expressions (OR/AND/WITH). +const SPDX = + /SPDX-License-Identifier:[ \t]*Apache-2\.0(?![A-Za-z0-9.+-]|[ \t]+(?:OR|AND|WITH)\b)/; + +export function hasSpdxHeader(buf) { + // An empty file has no content to license. + if (buf.length === 0) return true; + // latin1 maps every byte to a char, so binary or non-UTF-8 input never throws. + const lines = buf.toString("latin1").split("\n", 10); + return lines.some((line) => SPDX.test(line)); +} diff --git a/spdx-check/index.mjs b/spdx-check/index.mjs new file mode 100644 index 0000000..c4d5854 --- /dev/null +++ b/spdx-check/index.mjs @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { appendFileSync, closeSync, openSync, readSync } from "node:fs"; +import { join } from "node:path"; +import { headerSource, listFiles } from "./files.mjs"; +import { hasSpdxHeader } from "./header.mjs"; + +const LICENSE = "SPDX-License-Identifier: Apache-2.0"; +const head = Buffer.alloc(8192); + +function patterns(value = "") { + return value.split(/\s+/).filter(Boolean); +} + +function readHead(path) { + // TODO: handle unreadable entries (submodules, dangling symlinks, deleted files). + const fd = openSync(path, "r"); + const bytesRead = readSync(fd, head, 0, head.length, 0); + closeSync(fd); + return head.subarray(0, bytesRead); +} + +function findFailures(files, cwd) { + const failures = []; + for (const file of files) { + const src = headerSource(file, cwd); + if (!hasSpdxHeader(readHead(join(cwd, src)))) failures.push(src); + } + return failures.sort(); +} + +function writeSummary(path, total, failures) { + const lines = [ + "### SPDX check", + "", + `Checked ${total} files, ${failures.length} missing \`${LICENSE}\`.`, + "", + ...failures.map((failure) => `- \`${failure}\``), + ]; + appendFileSync(path, lines.join("\n") + "\n"); +} + +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 files = listFiles({ include, exclude, cwd }); + const failures = findFailures(files, cwd); + for (const src of failures) { + console.log(`::error file=${src},line=1::Missing ${LICENSE}`); + } + console.log( + `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`, + ); + const summaryPath = process.env.GITHUB_STEP_SUMMARY; + if (summaryPath) writeSummary(summaryPath, files.length, failures); + if (failures.length > 0) process.exitCode = 1; +} + +main(); diff --git a/spdx-check/test/files.test.mjs b/spdx-check/test/files.test.mjs new file mode 100644 index 0000000..c071ede --- /dev/null +++ b/spdx-check/test/files.test.mjs @@ -0,0 +1,96 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { test, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { headerSource, listFiles } from '../files.mjs'; + +const tempDirs = []; +after(() => { + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); +}); + +function writeFiles(root, paths) { + for (const path of paths) { + const full = join(root, ...path.split('/')); + mkdirSync(dirname(full), { recursive: true }); + writeFileSync(full, ''); + } +} + +function makeRepo(paths) { + const root = mkdtempSync(join(tmpdir(), 'spdx-files-')); + tempDirs.push(root); + execFileSync('git', ['init', '-q'], { cwd: root }); + writeFiles(root, paths); + execFileSync('git', ['add', '-A'], { cwd: root }); + return root; +} + +function sorted(list) { + return [...list].sort(); +} + +test('*.py matches at root and at depth', () => { + const cwd = makeRepo(['a.py', 'pkg/b.py', 'pkg/sub/c.py', 'README.md']); + const files = listFiles({ include: ['*.py'], cwd }); + assert.deepEqual(sorted(files), ['a.py', 'pkg/b.py', 'pkg/sub/c.py']); +}); + +test('Dockerfile* matches root-level files only', () => { + const cwd = makeRepo(['Dockerfile', 'Dockerfile.dev', 'deploy/Dockerfile']); + const files = listFiles({ include: ['Dockerfile*'], cwd }); + assert.deepEqual(sorted(files), ['Dockerfile', 'Dockerfile.dev']); +}); + +test('*/Dockerfile* matches nested files only', () => { + const cwd = makeRepo(['Dockerfile', 'deploy/Dockerfile', 'deploy/Dockerfile.prod']); + const files = listFiles({ include: ['*/Dockerfile*'], cwd }); + assert.deepEqual(sorted(files), ['deploy/Dockerfile', 'deploy/Dockerfile.prod']); +}); + +test('scripts/bin/* matches an extensionless file', () => { + const cwd = makeRepo(['scripts/bin/run', 'scripts/other']); + const files = listFiles({ include: ['scripts/bin/*'], cwd }); + assert.deepEqual(files, ['scripts/bin/run']); +}); + +test('excludes remove matching files', () => { + const cwd = makeRepo(['a.py', 'third_party/x.py', 'proto/m_pb2.py']); + const files = listFiles({ + include: ['*.py'], + exclude: ['third_party/*', '*_pb2.py'], + cwd, + }); + assert.deepEqual(files, ['a.py']); +}); + +test('untracked files are ignored', () => { + const cwd = makeRepo(['a.py']); + writeFiles(cwd, ['b.py']); + assert.deepEqual(listFiles({ include: ['*.py'], cwd }), ['a.py']); +}); + +test('multiple include patterns combine', () => { + const cwd = makeRepo(['a.py', 'b.mjs', 'c.md']); + const files = listFiles({ include: ['*.py', '*.mjs'], cwd }); + assert.deepEqual(sorted(files), ['a.py', 'b.mjs']); +}); + +test('headerSource returns the sidecar when it exists', () => { + const cwd = makeRepo(['x.json', 'x.json.license']); + assert.equal(headerSource('x.json', cwd), 'x.json.license'); +}); + +test('headerSource returns the path when there is no sidecar', () => { + const cwd = makeRepo(['y.json']); + assert.equal(headerSource('y.json', cwd), 'y.json'); +}); + +test('headerSource works for nested paths', () => { + const cwd = makeRepo(['conf/x.json', 'conf/x.json.license']); + assert.equal(headerSource('conf/x.json', cwd), 'conf/x.json.license'); +}); diff --git a/spdx-check/test/header.test.mjs b/spdx-check/test/header.test.mjs new file mode 100644 index 0000000..07ab61c --- /dev/null +++ b/spdx-check/test/header.test.mjs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { hasSpdxHeader } from '../header.mjs'; + +const ID = 'SPDX-License-Identifier: Apache-2.0'; + +function check(text) { + return hasSpdxHeader(Buffer.from(text)); +} + +function filler(n) { + return 'x\n'.repeat(n); +} + +test('empty buffer passes', () => { + assert.equal(hasSpdxHeader(Buffer.alloc(0)), true); +}); + +test('hash comment passes', () => { + assert.equal(check(`# ${ID}\nprint("hi")\n`), true); +}); + +test('double-slash comment passes', () => { + assert.equal(check(`// ${ID}\nconsole.log(1);\n`), true); +}); + +test('multi-line block comment passes', () => { + assert.equal(check(`/*\n * Copyright Foo\n * ${ID}\n */\nint x;\n`), true); +}); + +test('single-line block comment passes', () => { + assert.equal(check(`/* ${ID} */\nint x;\n`), true); +}); + +test('html comment passes', () => { + assert.equal(check(`\n

hi

\n`), true); +}); + +test('shebang then header passes', () => { + assert.equal(check(`#!/usr/bin/env python3\n# ${ID}\n`), true); +}); + +test('header on line 10 passes', () => { + assert.equal(check(`${filler(9)}# ${ID}\n`), true); +}); + +test('header on line 11 fails', () => { + assert.equal(check(`${filler(10)}# ${ID}\n`), false); +}); + +test('CRLF file passes', () => { + assert.equal(check(`#!/bin/sh\r\n# ${ID}\r\necho hi\r\n`), true); +}); + +test('file without header fails', () => { + assert.equal(check('print("hi")\n'), false); +}); + +test('MIT fails', () => { + assert.equal(check('# SPDX-License-Identifier: MIT\n'), false); +}); + +test('Apache-2.0-only is rejected', () => { + assert.equal(check(`# ${ID}-only\n`), false); +}); + +test('Apache-2.0 OR MIT is rejected', () => { + assert.equal(check(`# ${ID} OR MIT\n`), false); +}); + +test('Apache-2.0 AND MIT is rejected', () => { + assert.equal(check(`# ${ID} AND MIT\n`), false); +}); + +test('Apache-2.0 WITH an exception is rejected', () => { + assert.equal(check(`# ${ID} WITH LLVM-exception\n`), false); +}); + +test('UTF-16 BOM bytes before header still pass', () => { + const buf = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`# ${ID}\n`)]); + assert.equal(hasSpdxHeader(buf), true); +}); + +test('Latin-1 byte before header still passes', () => { + const buf = Buffer.concat([ + Buffer.from('# Caf'), + Buffer.from([0xe9]), + Buffer.from(`\n# ${ID}\n`), + ]); + assert.equal(hasSpdxHeader(buf), true); +}); + +test('NUL bytes around header still pass', () => { + const buf = Buffer.concat([ + Buffer.from([0x00, 0x00, 0x0a]), + Buffer.from(`# ${ID}\n`), + Buffer.from([0x00, 0xff]), + ]); + assert.equal(hasSpdxHeader(buf), true); +}); diff --git a/spdx-check/test/index.test.mjs b/spdx-check/test/index.test.mjs new file mode 100644 index 0000000..df17762 --- /dev/null +++ b/spdx-check/test/index.test.mjs @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { test, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const INDEX = fileURLToPath(new URL('../index.mjs', import.meta.url)); +const HEADER = '# SPDX-License-Identifier: Apache-2.0\n'; + +const tempDirs = []; +after(() => { + for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); +}); + +function tempDir() { + const dir = mkdtempSync(join(tmpdir(), 'spdx-index-')); + tempDirs.push(dir); + return dir; +} + +function makeRepo(files) { + const root = tempDir(); + execFileSync('git', ['init', '-q'], { cwd: root }); + for (const [path, content] of Object.entries(files)) { + const full = join(root, ...path.split('/')); + mkdirSync(dirname(full), { recursive: true }); + writeFileSync(full, content); + } + execFileSync('git', ['add', '-A'], { cwd: root }); + return root; +} + +// Under GitHub Actions the parent env carries the real job's INPUT_* and +// GITHUB_* (step summary, outputs); the child must never see them. +function childEnv(vars) { + const env = {}; + for (const [key, value] of Object.entries(process.env)) { + const upper = key.toUpperCase(); + if (upper.startsWith('INPUT_') || upper.startsWith('GITHUB_')) continue; + env[key] = value; + } + return { ...env, ...vars }; +} + +function run(cwd, vars) { + const result = spawnSync(process.execPath, [INDEX], { + cwd, + env: childEnv(vars), + encoding: 'utf8', + }); + const errors = result.stdout.split(/\r?\n/).filter((l) => l.startsWith('::error')); + return { status: result.status, errors, stderr: result.stderr }; +} + +function annotation(path) { + return `::error file=${path},line=1::Missing SPDX-License-Identifier: Apache-2.0`; +} + +test('all files with headers pass', () => { + const cwd = makeRepo({ 'a.py': `${HEADER}print(1)\n`, 'pkg/b.py': HEADER }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, []); + assert.equal(status, 0, stderr); +}); + +test('failures are annotated in sorted order', () => { + const cwd = makeRepo({ 'z.py': 'x\n', 'a.py': 'x\n', 'm/b.py': 'x\n', 'ok.py': HEADER }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, [annotation('a.py'), annotation('m/b.py'), annotation('z.py')]); + assert.equal(status, 1); +}); + +// git lists x.json before x.json.d/y.py, but x.json is reported as +// x.json.license, which sorts after x.json.d/y.py. +test('sidecar paths are sorted by their reported name', () => { + const cwd = makeRepo({ + 'x.json': '{}\n', + 'x.json.license': 'nothing\n', + 'x.json.d/y.py': 'x\n', + }); + const { errors } = run(cwd, { INPUT_INCLUDE: '*.json *.py' }); + assert.deepEqual(errors, [annotation('x.json.d/y.py'), annotation('x.json.license')]); +}); + +test('sidecar with header makes the file pass', () => { + const cwd = makeRepo({ 'cfg.json': '{}\n', 'cfg.json.license': HEADER }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.json' }); + assert.deepEqual(errors, []); + assert.equal(status, 0, stderr); +}); + +test('sidecar without header is annotated by its own path', () => { + const cwd = makeRepo({ 'cfg.json': '{}\n', 'cfg.json.license': 'nothing\n' }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.json' }); + assert.deepEqual(errors, [annotation('cfg.json.license')]); + assert.equal(status, 1); +}); + +test('newline-separated include patterns all apply', () => { + const cwd = makeRepo({ 'a.py': 'x\n', 'b.sh': 'x\n', 'c.md': 'x\n' }); + const { errors } = run(cwd, { INPUT_INCLUDE: ' *.py\n *.sh\n' }); + assert.deepEqual(errors, [annotation('a.py'), annotation('b.sh')]); +}); + +test('exclude patterns are honoured', () => { + const cwd = makeRepo({ 'a.py': HEADER, 'third_party/x.py': 'x\n', 'm_pb2.py': 'x\n' }); + const { status, errors, stderr } = run(cwd, { + INPUT_INCLUDE: '*.py', + INPUT_EXCLUDE: 'third_party/*\n*_pb2.py\n', + }); + assert.deepEqual(errors, []); + assert.equal(status, 0, stderr); +}); + +test('step summary is appended with failing paths', () => { + const cwd = makeRepo({ 'a.py': 'x\n', 'm/b.py': 'x\n' }); + const summary = join(tempDir(), 'summary.md'); + writeFileSync(summary, 'existing\n'); + const { status } = run(cwd, { INPUT_INCLUDE: '*.py', GITHUB_STEP_SUMMARY: summary }); + const text = readFileSync(summary, 'utf8'); + assert.ok(text.startsWith('existing\n'), text); + assert.ok(text.includes('a.py'), text); + assert.ok(text.includes('m/b.py'), text); + assert.equal(status, 1); +}); From 845b5d2de9b7f747527cd2aa1577ab2e24e190e8 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 15:42:19 +0100 Subject: [PATCH 2/9] chore: add Apache-2.0 license Signed-off-by: Simon Scatton --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 24e57f3e87f24af46868bd813bf98357bb0f7975 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 15:42:19 +0100 Subject: [PATCH 3/9] docs: move spdx-check usage to its own README Signed-off-by: Simon Scatton --- README.md | 42 +++--------------------------------------- spdx-check/README.md | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 39 deletions(-) create mode 100644 spdx-check/README.md diff --git a/README.md b/README.md index 4b2cd02..6a1e80a 100644 --- a/README.md +++ b/README.md @@ -2,43 +2,7 @@ Reusable GitHub Actions workflows for the ai-openshell organization. -## spdx-check +## Actions -Fails the job if a tracked file lacks `SPDX-License-Identifier: Apache-2.0` -in its first 10 lines. It's a JavaScript action with no dependencies, so it -runs as a step in a job you already have, with no setup step. - -```yaml -- uses: actions/checkout@v7 -- uses: ai-openshell/workflows/spdx-check@main - with: - include: "*.py *.rs *.go Dockerfile* */Dockerfile* scripts/bin/*" - exclude: "third_party/* *_pb2.py" -``` - -### Inputs - -- `include` (required): which files to check. -- `exclude` (optional): which of those files to skip. - -Both are [git pathspecs](https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec), -separated by spaces or newlines. Only tracked files are checked, so gitignored -paths like `node_modules/` never show up. Under git's default pathspec rules, -`*` also matches `/`: - -- `*.py` matches Python files at any depth. -- `Dockerfile*` matches only root-level Dockerfiles. Add `*/Dockerfile*` for - nested ones. -- `scripts/bin/*` matches everything under `scripts/bin/`. - -### Rules - -- The license must be exactly `Apache-2.0`. The check rejects - `Apache-2.0-only` and `Apache-2.0 OR MIT`. -- Empty files pass. -- For files that can't hold a comment, such as JSON, put the header in a - [REUSE](https://reuse.software/spec/) sidecar named `.license`. When a - sidecar exists, the check reads it instead of the file. - -Each failing file gets an error annotation on line 1, and the job summary lists -all of them. +- [`spdx-check`](spdx-check/): fails the job if source files lack an + `SPDX-License-Identifier: Apache-2.0` header. diff --git a/spdx-check/README.md b/spdx-check/README.md new file mode 100644 index 0000000..71550b2 --- /dev/null +++ b/spdx-check/README.md @@ -0,0 +1,41 @@ +# spdx-check + +Fails the job if a tracked file lacks `SPDX-License-Identifier: Apache-2.0` +in its first 10 lines. It's a JavaScript action with no dependencies, so it +runs as a step in a job you already have, with no setup step. + +```yaml +- uses: actions/checkout@v7 +- uses: ai-openshell/workflows/spdx-check@main + with: + include: "*.py *.rs *.go Dockerfile* */Dockerfile* scripts/bin/*" + exclude: "third_party/* *_pb2.py" +``` + +## Inputs + +- `include` (required): which files to check. +- `exclude` (optional): which of those files to skip. + +Both are +[git pathspecs](https://git-scm.com/docs/gitglossary#def_pathspec), +separated by spaces or newlines. Only tracked files are checked, so gitignored +paths like `node_modules/` never show up. Under git's default pathspec rules, +`*` also matches `/`: + +- `*.py` matches Python files at any depth. +- `Dockerfile*` matches only root-level Dockerfiles. Add `*/Dockerfile*` for + nested ones. +- `scripts/bin/*` matches everything under `scripts/bin/`. + +## Rules + +- The license must be exactly `Apache-2.0`. The check rejects + `Apache-2.0-only` and `Apache-2.0 OR MIT`. +- Empty files pass. +- For files that can't hold a comment, such as JSON, put the header in a + [REUSE](https://reuse.software/spec/) sidecar named `.license`. When a + sidecar exists, the check reads it instead of the file. + +Each failing file gets an error annotation on line 1, and the job summary lists +all of them. From c042698392e7bf1e8ef685fcc1d325acc1959ea4 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 15:49:35 +0100 Subject: [PATCH 4/9] ci: drop macos from test matrix Signed-off-by: Simon Scatton --- .github/workflows/test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2ddd16a..65a791b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,7 +8,7 @@ jobs: unit: strategy: matrix: - os: [ubuntu-latest, windows-latest, macos-latest] + os: [ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v7 From 61979f12e7d2db402dbc027bc2951d9fae4f8113 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 16:37:39 +0100 Subject: [PATCH 5/9] fix(spdx-check): merge exclude pathspec magic Signed-off-by: Simon Scatton --- spdx-check/files.mjs | 10 +++++++++- spdx-check/test/files.test.mjs | 6 ++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/spdx-check/files.mjs b/spdx-check/files.mjs index 3032504..2f4e8d8 100644 --- a/spdx-check/files.mjs +++ b/spdx-check/files.mjs @@ -4,8 +4,16 @@ import { execFileSync } from "node:child_process"; import { existsSync } from "node:fs"; import { join } from "node:path"; +// Git reads a second ":(...)" prefix as literal text, so long-form magic +// must be merged into the exclude prefix. +function excludeSpec(pattern) { + return pattern.startsWith(":(") + ? `:(exclude,${pattern.slice(2)}` + : `:(exclude)${pattern}`; +} + export function listFiles({ include, exclude = [], cwd }) { - const excludes = exclude.map((pattern) => `:(exclude)${pattern}`); + const excludes = exclude.map(excludeSpec); const args = ["ls-files", "-z", "--", ...include, ...excludes]; // TODO: report git's error clearly (not a repo, invalid pathspec). const stdout = execFileSync("git", args, { diff --git a/spdx-check/test/files.test.mjs b/spdx-check/test/files.test.mjs index c071ede..ab763a2 100644 --- a/spdx-check/test/files.test.mjs +++ b/spdx-check/test/files.test.mjs @@ -68,6 +68,12 @@ test('excludes remove matching files', () => { assert.deepEqual(files, ['a.py']); }); +test('exclude patterns keep their own pathspec magic', () => { + const cwd = makeRepo(['src/z.go', 'vendor/y.go', 'vendor/a/x.go']); + const files = listFiles({ include: ['*.go'], exclude: [':(glob)vendor/**'], cwd }); + assert.deepEqual(files, ['src/z.go']); +}); + test('untracked files are ignored', () => { const cwd = makeRepo(['a.py']); writeFiles(cwd, ['b.py']); From 0c720bf1ae0c8e0bad3b126bbc5c609dcb4e8947 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 16:37:55 +0100 Subject: [PATCH 6/9] fix(spdx-check): escape file names in annotations Signed-off-by: Simon Scatton --- spdx-check/index.mjs | 12 +++++++++++- spdx-check/test/index.test.mjs | 19 +++++++++++++++++-- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/spdx-check/index.mjs b/spdx-check/index.mjs index c4d5854..6ea7e52 100644 --- a/spdx-check/index.mjs +++ b/spdx-check/index.mjs @@ -20,6 +20,16 @@ function readHead(path) { return head.subarray(0, bytesRead); } +// GitHub's escaping rules for workflow command property values. +function escapeProperty(value) { + return value + .replaceAll("%", "%25") + .replaceAll("\r", "%0D") + .replaceAll("\n", "%0A") + .replaceAll(":", "%3A") + .replaceAll(",", "%2C"); +} + function findFailures(files, cwd) { const failures = []; for (const file of files) { @@ -48,7 +58,7 @@ function main() { const files = listFiles({ include, exclude, cwd }); const failures = findFailures(files, cwd); for (const src of failures) { - console.log(`::error file=${src},line=1::Missing ${LICENSE}`); + console.log(`::error file=${escapeProperty(src)},line=1::Missing ${LICENSE}`); } console.log( `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`, diff --git a/spdx-check/test/index.test.mjs b/spdx-check/test/index.test.mjs index df17762..966e56a 100644 --- a/spdx-check/test/index.test.mjs +++ b/spdx-check/test/index.test.mjs @@ -52,8 +52,9 @@ function run(cwd, vars) { env: childEnv(vars), encoding: 'utf8', }); - const errors = result.stdout.split(/\r?\n/).filter((l) => l.startsWith('::error')); - return { status: result.status, errors, stderr: result.stderr }; + const lines = result.stdout.split(/\r?\n/); + const errors = lines.filter((l) => l.startsWith('::error')); + return { status: result.status, lines, errors, stderr: result.stderr }; } function annotation(path) { @@ -116,6 +117,20 @@ test('exclude patterns are honoured', () => { assert.equal(status, 0, stderr); }); +test('annotation file property is escaped', () => { + const cwd = makeRepo({ 'a,b%.py': 'x\n' }); + const { errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, [annotation('a%2Cb%25.py')]); +}); + +// Windows forbids newlines and colons in filenames. +test('a filename cannot inject a workflow command', { skip: process.platform === 'win32' }, () => { + const cwd = makeRepo({ 'x\n::add-mask::DUMMY\n.py': 'x\n' }); + const { lines, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, [annotation('x%0A%3A%3Aadd-mask%3A%3ADUMMY%0A.py')]); + assert.ok(!lines.some((l) => l.startsWith('::add-mask')), lines.join('\n')); +}); + test('step summary is appended with failing paths', () => { const cwd = makeRepo({ 'a.py': 'x\n', 'm/b.py': 'x\n' }); const summary = join(tempDir(), 'summary.md'); From 0b9c4e65604f3887413bafadfa6fb16f94ea3c98 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 16:38:13 +0100 Subject: [PATCH 7/9] fix(spdx-check): read complete header lines Signed-off-by: Simon Scatton --- spdx-check/header.mjs | 12 +++++++++++- spdx-check/index.mjs | 13 ++++++++++--- spdx-check/test/header.test.mjs | 8 +++++++- spdx-check/test/index.test.mjs | 16 ++++++++++++++++ 4 files changed, 44 insertions(+), 5 deletions(-) diff --git a/spdx-check/header.mjs b/spdx-check/header.mjs index 0c7519d..dcf2da4 100644 --- a/spdx-check/header.mjs +++ b/spdx-check/header.mjs @@ -1,13 +1,23 @@ // SPDX-License-Identifier: Apache-2.0 +const LINES = 10; // Rejects suffixes (-only, +) and compound expressions (OR/AND/WITH). const SPDX = /SPDX-License-Identifier:[ \t]*Apache-2\.0(?![A-Za-z0-9.+-]|[ \t]+(?:OR|AND|WITH)\b)/; +export function hasHeaderLines(buf) { + let at = -1; + for (let line = 0; line < LINES; line++) { + at = buf.indexOf(0x0a, at + 1); + if (at === -1) return false; + } + return true; +} + export function hasSpdxHeader(buf) { // An empty file has no content to license. if (buf.length === 0) return true; // latin1 maps every byte to a char, so binary or non-UTF-8 input never throws. - const lines = buf.toString("latin1").split("\n", 10); + const lines = buf.toString("latin1").split("\n", LINES); return lines.some((line) => SPDX.test(line)); } diff --git a/spdx-check/index.mjs b/spdx-check/index.mjs index 6ea7e52..8ee0630 100644 --- a/spdx-check/index.mjs +++ b/spdx-check/index.mjs @@ -3,7 +3,7 @@ import { appendFileSync, closeSync, openSync, readSync } from "node:fs"; import { join } from "node:path"; import { headerSource, listFiles } from "./files.mjs"; -import { hasSpdxHeader } from "./header.mjs"; +import { hasHeaderLines, hasSpdxHeader } from "./header.mjs"; const LICENSE = "SPDX-License-Identifier: Apache-2.0"; const head = Buffer.alloc(8192); @@ -12,12 +12,19 @@ function patterns(value = "") { return value.split(/\s+/).filter(Boolean); } +// Grows past 8 KiB only until the header lines are complete, so a long line +// can't hide the header or cut a license expression short. function readHead(path) { // TODO: handle unreadable entries (submodules, dangling symlinks, deleted files). const fd = openSync(path, "r"); - const bytesRead = readSync(fd, head, 0, head.length, 0); + let buf = head; + let size = readSync(fd, buf, 0, buf.length, 0); + while (size === buf.length && !hasHeaderLines(buf)) { + buf = Buffer.concat([buf], buf.length * 2); + size += readSync(fd, buf, size, buf.length - size, size); + } closeSync(fd); - return head.subarray(0, bytesRead); + return buf.subarray(0, size); } // GitHub's escaping rules for workflow command property values. diff --git a/spdx-check/test/header.test.mjs b/spdx-check/test/header.test.mjs index 07ab61c..401c673 100644 --- a/spdx-check/test/header.test.mjs +++ b/spdx-check/test/header.test.mjs @@ -2,7 +2,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { hasSpdxHeader } from '../header.mjs'; +import { hasHeaderLines, hasSpdxHeader } from '../header.mjs'; const ID = 'SPDX-License-Identifier: Apache-2.0'; @@ -100,3 +100,9 @@ test('NUL bytes around header still pass', () => { ]); assert.equal(hasSpdxHeader(buf), true); }); + +test('header lines are complete only after the tenth newline', () => { + assert.equal(hasHeaderLines(Buffer.from(filler(9))), false); + assert.equal(hasHeaderLines(Buffer.from(`${filler(9)}x`)), false); + assert.equal(hasHeaderLines(Buffer.from(filler(10))), true); +}); diff --git a/spdx-check/test/index.test.mjs b/spdx-check/test/index.test.mjs index 966e56a..5bcfea3 100644 --- a/spdx-check/test/index.test.mjs +++ b/spdx-check/test/index.test.mjs @@ -131,6 +131,22 @@ test('a filename cannot inject a workflow command', { skip: process.platform === assert.ok(!lines.some((l) => l.startsWith('::add-mask')), lines.join('\n')); }); +test('a long first line does not hide a header on line 2', () => { + const cwd = makeRepo({ 'a.py': `#${'x'.repeat(10000)}\n${HEADER}` }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, []); + assert.equal(status, 0, stderr); +}); + +// Line 1 is 8155 bytes, so "Apache-2.0" on line 2 ends exactly at byte 8192. +test('a license expression cut at 8 KiB is not accepted', () => { + const line1 = `#${'x'.repeat(8153)}\n`; + const cwd = makeRepo({ 'a.py': `${line1}# SPDX-License-Identifier: Apache-2.0 OR MIT\n` }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); + assert.deepEqual(errors, [annotation('a.py')]); + assert.equal(status, 1); +}); + test('step summary is appended with failing paths', () => { const cwd = makeRepo({ 'a.py': 'x\n', 'm/b.py': 'x\n' }); const summary = join(tempDir(), 'summary.md'); From 1e6c84849d530b6e6f67c6f0f5c16527898ea010 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 16:38:21 +0100 Subject: [PATCH 8/9] refactor(spdx-check): tidy glue and test helpers Signed-off-by: Simon Scatton --- spdx-check/index.mjs | 57 +++++++++++++++------------------- spdx-check/test/files.test.mjs | 54 ++++++++++---------------------- spdx-check/test/index.test.mjs | 33 +++----------------- spdx-check/test/repo.mjs | 37 ++++++++++++++++++++++ 4 files changed, 84 insertions(+), 97 deletions(-) create mode 100644 spdx-check/test/repo.mjs diff --git a/spdx-check/index.mjs b/spdx-check/index.mjs index 8ee0630..7ad0fd8 100644 --- a/spdx-check/index.mjs +++ b/spdx-check/index.mjs @@ -6,6 +6,13 @@ import { headerSource, listFiles } from "./files.mjs"; import { hasHeaderLines, hasSpdxHeader } from "./header.mjs"; const LICENSE = "SPDX-License-Identifier: Apache-2.0"; +const ESCAPES = { + "%": "%25", + "\r": "%0D", + "\n": "%0A", + ":": "%3A", + ",": "%2C", +}; const head = Buffer.alloc(8192); function patterns(value = "") { @@ -27,34 +34,22 @@ function readHead(path) { return buf.subarray(0, size); } -// GitHub's escaping rules for workflow command property values. -function escapeProperty(value) { - return value - .replaceAll("%", "%25") - .replaceAll("\r", "%0D") - .replaceAll("\n", "%0A") - .replaceAll(":", "%3A") - .replaceAll(",", "%2C"); +function findFailures(files, cwd) { + return files + .map((file) => headerSource(file, cwd)) + .filter((src) => !hasSpdxHeader(readHead(join(cwd, src)))) + .sort(); } -function findFailures(files, cwd) { - const failures = []; - for (const file of files) { - const src = headerSource(file, cwd); - if (!hasSpdxHeader(readHead(join(cwd, src)))) failures.push(src); - } - return failures.sort(); +// Escaped so a file name can't break out of the workflow command. +function annotation(src) { + const file = src.replace(/[%\r\n:,]/g, (char) => ESCAPES[char]); + return `::error file=${file},line=1::Missing ${LICENSE}`; } -function writeSummary(path, total, failures) { - const lines = [ - "### SPDX check", - "", - `Checked ${total} files, ${failures.length} missing \`${LICENSE}\`.`, - "", - ...failures.map((failure) => `- \`${failure}\``), - ]; - appendFileSync(path, lines.join("\n") + "\n"); +function writeSummary(path, result, failures) { + const list = failures.map((src) => `- \`${src}\`\n`).join(""); + appendFileSync(path, `### SPDX check\n\n${result}\n\n${list}`); } function main() { @@ -64,14 +59,12 @@ function main() { const exclude = patterns(process.env.INPUT_EXCLUDE); const files = listFiles({ include, exclude, cwd }); const failures = findFailures(files, cwd); - for (const src of failures) { - console.log(`::error file=${escapeProperty(src)},line=1::Missing ${LICENSE}`); - } - console.log( - `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`, - ); - const summaryPath = process.env.GITHUB_STEP_SUMMARY; - if (summaryPath) writeSummary(summaryPath, files.length, failures); + const result = + `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`; + failures.forEach((src) => console.log(annotation(src))); + console.log(result); + const summary = process.env.GITHUB_STEP_SUMMARY; + if (summary) writeSummary(summary, result, failures); if (failures.length > 0) process.exitCode = 1; } diff --git a/spdx-check/test/files.test.mjs b/spdx-check/test/files.test.mjs index ab763a2..edef29e 100644 --- a/spdx-check/test/files.test.mjs +++ b/spdx-check/test/files.test.mjs @@ -1,33 +1,13 @@ // SPDX-License-Identifier: Apache-2.0 -import { test, after } from 'node:test'; +import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { execFileSync } from 'node:child_process'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; import { headerSource, listFiles } from '../files.mjs'; +import { makeRepo, writeFiles } from './repo.mjs'; -const tempDirs = []; -after(() => { - for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); -}); - -function writeFiles(root, paths) { - for (const path of paths) { - const full = join(root, ...path.split('/')); - mkdirSync(dirname(full), { recursive: true }); - writeFileSync(full, ''); - } -} - -function makeRepo(paths) { - const root = mkdtempSync(join(tmpdir(), 'spdx-files-')); - tempDirs.push(root); - execFileSync('git', ['init', '-q'], { cwd: root }); - writeFiles(root, paths); - execFileSync('git', ['add', '-A'], { cwd: root }); - return root; +// Listing only looks at paths, so every file can be empty. +function repo(paths) { + return makeRepo(Object.fromEntries(paths.map((path) => [path, '']))); } function sorted(list) { @@ -35,31 +15,31 @@ function sorted(list) { } test('*.py matches at root and at depth', () => { - const cwd = makeRepo(['a.py', 'pkg/b.py', 'pkg/sub/c.py', 'README.md']); + const cwd = repo(['a.py', 'pkg/b.py', 'pkg/sub/c.py', 'README.md']); const files = listFiles({ include: ['*.py'], cwd }); assert.deepEqual(sorted(files), ['a.py', 'pkg/b.py', 'pkg/sub/c.py']); }); test('Dockerfile* matches root-level files only', () => { - const cwd = makeRepo(['Dockerfile', 'Dockerfile.dev', 'deploy/Dockerfile']); + const cwd = repo(['Dockerfile', 'Dockerfile.dev', 'deploy/Dockerfile']); const files = listFiles({ include: ['Dockerfile*'], cwd }); assert.deepEqual(sorted(files), ['Dockerfile', 'Dockerfile.dev']); }); test('*/Dockerfile* matches nested files only', () => { - const cwd = makeRepo(['Dockerfile', 'deploy/Dockerfile', 'deploy/Dockerfile.prod']); + const cwd = repo(['Dockerfile', 'deploy/Dockerfile', 'deploy/Dockerfile.prod']); const files = listFiles({ include: ['*/Dockerfile*'], cwd }); assert.deepEqual(sorted(files), ['deploy/Dockerfile', 'deploy/Dockerfile.prod']); }); test('scripts/bin/* matches an extensionless file', () => { - const cwd = makeRepo(['scripts/bin/run', 'scripts/other']); + const cwd = repo(['scripts/bin/run', 'scripts/other']); const files = listFiles({ include: ['scripts/bin/*'], cwd }); assert.deepEqual(files, ['scripts/bin/run']); }); test('excludes remove matching files', () => { - const cwd = makeRepo(['a.py', 'third_party/x.py', 'proto/m_pb2.py']); + const cwd = repo(['a.py', 'third_party/x.py', 'proto/m_pb2.py']); const files = listFiles({ include: ['*.py'], exclude: ['third_party/*', '*_pb2.py'], @@ -69,34 +49,34 @@ test('excludes remove matching files', () => { }); test('exclude patterns keep their own pathspec magic', () => { - const cwd = makeRepo(['src/z.go', 'vendor/y.go', 'vendor/a/x.go']); + const cwd = repo(['src/z.go', 'vendor/y.go', 'vendor/a/x.go']); const files = listFiles({ include: ['*.go'], exclude: [':(glob)vendor/**'], cwd }); assert.deepEqual(files, ['src/z.go']); }); test('untracked files are ignored', () => { - const cwd = makeRepo(['a.py']); - writeFiles(cwd, ['b.py']); + const cwd = repo(['a.py']); + writeFiles(cwd, { 'b.py': '' }); assert.deepEqual(listFiles({ include: ['*.py'], cwd }), ['a.py']); }); test('multiple include patterns combine', () => { - const cwd = makeRepo(['a.py', 'b.mjs', 'c.md']); + const cwd = repo(['a.py', 'b.mjs', 'c.md']); const files = listFiles({ include: ['*.py', '*.mjs'], cwd }); assert.deepEqual(sorted(files), ['a.py', 'b.mjs']); }); test('headerSource returns the sidecar when it exists', () => { - const cwd = makeRepo(['x.json', 'x.json.license']); + const cwd = repo(['x.json', 'x.json.license']); assert.equal(headerSource('x.json', cwd), 'x.json.license'); }); test('headerSource returns the path when there is no sidecar', () => { - const cwd = makeRepo(['y.json']); + const cwd = repo(['y.json']); assert.equal(headerSource('y.json', cwd), 'y.json'); }); test('headerSource works for nested paths', () => { - const cwd = makeRepo(['conf/x.json', 'conf/x.json.license']); + const cwd = repo(['conf/x.json', 'conf/x.json.license']); assert.equal(headerSource('conf/x.json', cwd), 'conf/x.json.license'); }); diff --git a/spdx-check/test/index.test.mjs b/spdx-check/test/index.test.mjs index 5bcfea3..c581c1a 100644 --- a/spdx-check/test/index.test.mjs +++ b/spdx-check/test/index.test.mjs @@ -1,39 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 -import { test, after } from 'node:test'; +import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { execFileSync, spawnSync } from 'node:child_process'; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { makeRepo, tempDir } from './repo.mjs'; const INDEX = fileURLToPath(new URL('../index.mjs', import.meta.url)); const HEADER = '# SPDX-License-Identifier: Apache-2.0\n'; -const tempDirs = []; -after(() => { - for (const dir of tempDirs) rmSync(dir, { recursive: true, force: true }); -}); - -function tempDir() { - const dir = mkdtempSync(join(tmpdir(), 'spdx-index-')); - tempDirs.push(dir); - return dir; -} - -function makeRepo(files) { - const root = tempDir(); - execFileSync('git', ['init', '-q'], { cwd: root }); - for (const [path, content] of Object.entries(files)) { - const full = join(root, ...path.split('/')); - mkdirSync(dirname(full), { recursive: true }); - writeFileSync(full, content); - } - execFileSync('git', ['add', '-A'], { cwd: root }); - return root; -} - // Under GitHub Actions the parent env carries the real job's INPUT_* and // GITHUB_* (step summary, outputs); the child must never see them. function childEnv(vars) { diff --git a/spdx-check/test/repo.mjs b/spdx-check/test/repo.mjs new file mode 100644 index 0000000..d293ac7 --- /dev/null +++ b/spdx-check/test/repo.mjs @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { after } from 'node:test'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; + +const dirs = []; +after(() => { + for (const dir of dirs) rmSync(dir, { recursive: true, force: true }); +}); + +export function tempDir() { + const dir = mkdtempSync(join(tmpdir(), 'spdx-')); + dirs.push(dir); + return dir; +} + +// `files` maps a /-separated path to its content. +export function writeFiles(root, files) { + for (const [path, content] of Object.entries(files)) { + const full = join(root, ...path.split('/')); + mkdirSync(dirname(full), { recursive: true }); + writeFileSync(full, content); + } +} + +// Files are staged but never committed: git ls-files lists the index, and +// skipping commits avoids needing a git identity on CI. +export function makeRepo(files) { + const root = tempDir(); + execFileSync('git', ['init', '-q'], { cwd: root }); + writeFiles(root, files); + execFileSync('git', ['add', '-A'], { cwd: root }); + return root; +} From 6be314651c7f6c83584d66acf538979be6d5f2e5 Mon Sep 17 00:00:00 2001 From: Simon Scatton Date: Tue, 10 Nov 2026 16:38:46 +0100 Subject: [PATCH 9/9] style: format with prettier Signed-off-by: Simon Scatton --- spdx-check/index.mjs | 3 +- spdx-check/test/files.test.mjs | 105 +++++++++++--------- spdx-check/test/header.test.mjs | 59 ++++++------ spdx-check/test/index.test.mjs | 163 +++++++++++++++++++------------- spdx-check/test/repo.mjs | 18 ++-- 5 files changed, 194 insertions(+), 154 deletions(-) diff --git a/spdx-check/index.mjs b/spdx-check/index.mjs index 7ad0fd8..7a9571d 100644 --- a/spdx-check/index.mjs +++ b/spdx-check/index.mjs @@ -59,8 +59,7 @@ function main() { const exclude = patterns(process.env.INPUT_EXCLUDE); const files = listFiles({ include, exclude, cwd }); const failures = findFailures(files, cwd); - const result = - `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`; + const result = `Checked ${files.length} files, ${failures.length} missing ${LICENSE}`; failures.forEach((src) => console.log(annotation(src))); console.log(result); const summary = process.env.GITHUB_STEP_SUMMARY; diff --git a/spdx-check/test/files.test.mjs b/spdx-check/test/files.test.mjs index edef29e..a604cbd 100644 --- a/spdx-check/test/files.test.mjs +++ b/spdx-check/test/files.test.mjs @@ -1,82 +1,93 @@ // SPDX-License-Identifier: Apache-2.0 -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import { headerSource, listFiles } from '../files.mjs'; -import { makeRepo, writeFiles } from './repo.mjs'; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { headerSource, listFiles } from "../files.mjs"; +import { makeRepo, writeFiles } from "./repo.mjs"; // Listing only looks at paths, so every file can be empty. function repo(paths) { - return makeRepo(Object.fromEntries(paths.map((path) => [path, '']))); + return makeRepo(Object.fromEntries(paths.map((path) => [path, ""]))); } function sorted(list) { return [...list].sort(); } -test('*.py matches at root and at depth', () => { - const cwd = repo(['a.py', 'pkg/b.py', 'pkg/sub/c.py', 'README.md']); - const files = listFiles({ include: ['*.py'], cwd }); - assert.deepEqual(sorted(files), ['a.py', 'pkg/b.py', 'pkg/sub/c.py']); +test("*.py matches at root and at depth", () => { + const cwd = repo(["a.py", "pkg/b.py", "pkg/sub/c.py", "README.md"]); + const files = listFiles({ include: ["*.py"], cwd }); + assert.deepEqual(sorted(files), ["a.py", "pkg/b.py", "pkg/sub/c.py"]); }); -test('Dockerfile* matches root-level files only', () => { - const cwd = repo(['Dockerfile', 'Dockerfile.dev', 'deploy/Dockerfile']); - const files = listFiles({ include: ['Dockerfile*'], cwd }); - assert.deepEqual(sorted(files), ['Dockerfile', 'Dockerfile.dev']); +test("Dockerfile* matches root-level files only", () => { + const cwd = repo(["Dockerfile", "Dockerfile.dev", "deploy/Dockerfile"]); + const files = listFiles({ include: ["Dockerfile*"], cwd }); + assert.deepEqual(sorted(files), ["Dockerfile", "Dockerfile.dev"]); }); -test('*/Dockerfile* matches nested files only', () => { - const cwd = repo(['Dockerfile', 'deploy/Dockerfile', 'deploy/Dockerfile.prod']); - const files = listFiles({ include: ['*/Dockerfile*'], cwd }); - assert.deepEqual(sorted(files), ['deploy/Dockerfile', 'deploy/Dockerfile.prod']); +test("*/Dockerfile* matches nested files only", () => { + const cwd = repo([ + "Dockerfile", + "deploy/Dockerfile", + "deploy/Dockerfile.prod", + ]); + const files = listFiles({ include: ["*/Dockerfile*"], cwd }); + assert.deepEqual(sorted(files), [ + "deploy/Dockerfile", + "deploy/Dockerfile.prod", + ]); }); -test('scripts/bin/* matches an extensionless file', () => { - const cwd = repo(['scripts/bin/run', 'scripts/other']); - const files = listFiles({ include: ['scripts/bin/*'], cwd }); - assert.deepEqual(files, ['scripts/bin/run']); +test("scripts/bin/* matches an extensionless file", () => { + const cwd = repo(["scripts/bin/run", "scripts/other"]); + const files = listFiles({ include: ["scripts/bin/*"], cwd }); + assert.deepEqual(files, ["scripts/bin/run"]); }); -test('excludes remove matching files', () => { - const cwd = repo(['a.py', 'third_party/x.py', 'proto/m_pb2.py']); +test("excludes remove matching files", () => { + const cwd = repo(["a.py", "third_party/x.py", "proto/m_pb2.py"]); const files = listFiles({ - include: ['*.py'], - exclude: ['third_party/*', '*_pb2.py'], + include: ["*.py"], + exclude: ["third_party/*", "*_pb2.py"], cwd, }); - assert.deepEqual(files, ['a.py']); + assert.deepEqual(files, ["a.py"]); }); -test('exclude patterns keep their own pathspec magic', () => { - const cwd = repo(['src/z.go', 'vendor/y.go', 'vendor/a/x.go']); - const files = listFiles({ include: ['*.go'], exclude: [':(glob)vendor/**'], cwd }); - assert.deepEqual(files, ['src/z.go']); +test("exclude patterns keep their own pathspec magic", () => { + const cwd = repo(["src/z.go", "vendor/y.go", "vendor/a/x.go"]); + const files = listFiles({ + include: ["*.go"], + exclude: [":(glob)vendor/**"], + cwd, + }); + assert.deepEqual(files, ["src/z.go"]); }); -test('untracked files are ignored', () => { - const cwd = repo(['a.py']); - writeFiles(cwd, { 'b.py': '' }); - assert.deepEqual(listFiles({ include: ['*.py'], cwd }), ['a.py']); +test("untracked files are ignored", () => { + const cwd = repo(["a.py"]); + writeFiles(cwd, { "b.py": "" }); + assert.deepEqual(listFiles({ include: ["*.py"], cwd }), ["a.py"]); }); -test('multiple include patterns combine', () => { - const cwd = repo(['a.py', 'b.mjs', 'c.md']); - const files = listFiles({ include: ['*.py', '*.mjs'], cwd }); - assert.deepEqual(sorted(files), ['a.py', 'b.mjs']); +test("multiple include patterns combine", () => { + const cwd = repo(["a.py", "b.mjs", "c.md"]); + const files = listFiles({ include: ["*.py", "*.mjs"], cwd }); + assert.deepEqual(sorted(files), ["a.py", "b.mjs"]); }); -test('headerSource returns the sidecar when it exists', () => { - const cwd = repo(['x.json', 'x.json.license']); - assert.equal(headerSource('x.json', cwd), 'x.json.license'); +test("headerSource returns the sidecar when it exists", () => { + const cwd = repo(["x.json", "x.json.license"]); + assert.equal(headerSource("x.json", cwd), "x.json.license"); }); -test('headerSource returns the path when there is no sidecar', () => { - const cwd = repo(['y.json']); - assert.equal(headerSource('y.json', cwd), 'y.json'); +test("headerSource returns the path when there is no sidecar", () => { + const cwd = repo(["y.json"]); + assert.equal(headerSource("y.json", cwd), "y.json"); }); -test('headerSource works for nested paths', () => { - const cwd = repo(['conf/x.json', 'conf/x.json.license']); - assert.equal(headerSource('conf/x.json', cwd), 'conf/x.json.license'); +test("headerSource works for nested paths", () => { + const cwd = repo(["conf/x.json", "conf/x.json.license"]); + assert.equal(headerSource("conf/x.json", cwd), "conf/x.json.license"); }); diff --git a/spdx-check/test/header.test.mjs b/spdx-check/test/header.test.mjs index 401c673..bf040df 100644 --- a/spdx-check/test/header.test.mjs +++ b/spdx-check/test/header.test.mjs @@ -1,98 +1,101 @@ // SPDX-License-Identifier: Apache-2.0 -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import { hasHeaderLines, hasSpdxHeader } from '../header.mjs'; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { hasHeaderLines, hasSpdxHeader } from "../header.mjs"; -const ID = 'SPDX-License-Identifier: Apache-2.0'; +const ID = "SPDX-License-Identifier: Apache-2.0"; function check(text) { return hasSpdxHeader(Buffer.from(text)); } function filler(n) { - return 'x\n'.repeat(n); + return "x\n".repeat(n); } -test('empty buffer passes', () => { +test("empty buffer passes", () => { assert.equal(hasSpdxHeader(Buffer.alloc(0)), true); }); -test('hash comment passes', () => { +test("hash comment passes", () => { assert.equal(check(`# ${ID}\nprint("hi")\n`), true); }); -test('double-slash comment passes', () => { +test("double-slash comment passes", () => { assert.equal(check(`// ${ID}\nconsole.log(1);\n`), true); }); -test('multi-line block comment passes', () => { +test("multi-line block comment passes", () => { assert.equal(check(`/*\n * Copyright Foo\n * ${ID}\n */\nint x;\n`), true); }); -test('single-line block comment passes', () => { +test("single-line block comment passes", () => { assert.equal(check(`/* ${ID} */\nint x;\n`), true); }); -test('html comment passes', () => { +test("html comment passes", () => { assert.equal(check(`\n

hi

\n`), true); }); -test('shebang then header passes', () => { +test("shebang then header passes", () => { assert.equal(check(`#!/usr/bin/env python3\n# ${ID}\n`), true); }); -test('header on line 10 passes', () => { +test("header on line 10 passes", () => { assert.equal(check(`${filler(9)}# ${ID}\n`), true); }); -test('header on line 11 fails', () => { +test("header on line 11 fails", () => { assert.equal(check(`${filler(10)}# ${ID}\n`), false); }); -test('CRLF file passes', () => { +test("CRLF file passes", () => { assert.equal(check(`#!/bin/sh\r\n# ${ID}\r\necho hi\r\n`), true); }); -test('file without header fails', () => { +test("file without header fails", () => { assert.equal(check('print("hi")\n'), false); }); -test('MIT fails', () => { - assert.equal(check('# SPDX-License-Identifier: MIT\n'), false); +test("MIT fails", () => { + assert.equal(check("# SPDX-License-Identifier: MIT\n"), false); }); -test('Apache-2.0-only is rejected', () => { +test("Apache-2.0-only is rejected", () => { assert.equal(check(`# ${ID}-only\n`), false); }); -test('Apache-2.0 OR MIT is rejected', () => { +test("Apache-2.0 OR MIT is rejected", () => { assert.equal(check(`# ${ID} OR MIT\n`), false); }); -test('Apache-2.0 AND MIT is rejected', () => { +test("Apache-2.0 AND MIT is rejected", () => { assert.equal(check(`# ${ID} AND MIT\n`), false); }); -test('Apache-2.0 WITH an exception is rejected', () => { +test("Apache-2.0 WITH an exception is rejected", () => { assert.equal(check(`# ${ID} WITH LLVM-exception\n`), false); }); -test('UTF-16 BOM bytes before header still pass', () => { - const buf = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(`# ${ID}\n`)]); +test("UTF-16 BOM bytes before header still pass", () => { + const buf = Buffer.concat([ + Buffer.from([0xff, 0xfe]), + Buffer.from(`# ${ID}\n`), + ]); assert.equal(hasSpdxHeader(buf), true); }); -test('Latin-1 byte before header still passes', () => { +test("Latin-1 byte before header still passes", () => { const buf = Buffer.concat([ - Buffer.from('# Caf'), + Buffer.from("# Caf"), Buffer.from([0xe9]), Buffer.from(`\n# ${ID}\n`), ]); assert.equal(hasSpdxHeader(buf), true); }); -test('NUL bytes around header still pass', () => { +test("NUL bytes around header still pass", () => { const buf = Buffer.concat([ Buffer.from([0x00, 0x00, 0x0a]), Buffer.from(`# ${ID}\n`), @@ -101,7 +104,7 @@ test('NUL bytes around header still pass', () => { assert.equal(hasSpdxHeader(buf), true); }); -test('header lines are complete only after the tenth newline', () => { +test("header lines are complete only after the tenth newline", () => { assert.equal(hasHeaderLines(Buffer.from(filler(9))), false); assert.equal(hasHeaderLines(Buffer.from(`${filler(9)}x`)), false); assert.equal(hasHeaderLines(Buffer.from(filler(10))), true); diff --git a/spdx-check/test/index.test.mjs b/spdx-check/test/index.test.mjs index c581c1a..182bbd4 100644 --- a/spdx-check/test/index.test.mjs +++ b/spdx-check/test/index.test.mjs @@ -1,15 +1,15 @@ // SPDX-License-Identifier: Apache-2.0 -import { test } from 'node:test'; -import assert from 'node:assert/strict'; -import { spawnSync } from 'node:child_process'; -import { readFileSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { makeRepo, tempDir } from './repo.mjs'; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { makeRepo, tempDir } from "./repo.mjs"; -const INDEX = fileURLToPath(new URL('../index.mjs', import.meta.url)); -const HEADER = '# SPDX-License-Identifier: Apache-2.0\n'; +const INDEX = fileURLToPath(new URL("../index.mjs", import.meta.url)); +const HEADER = "# SPDX-License-Identifier: Apache-2.0\n"; // Under GitHub Actions the parent env carries the real job's INPUT_* and // GITHUB_* (step summary, outputs); the child must never see them. @@ -17,7 +17,7 @@ function childEnv(vars) { const env = {}; for (const [key, value] of Object.entries(process.env)) { const upper = key.toUpperCase(); - if (upper.startsWith('INPUT_') || upper.startsWith('GITHUB_')) continue; + if (upper.startsWith("INPUT_") || upper.startsWith("GITHUB_")) continue; env[key] = value; } return { ...env, ...vars }; @@ -27,10 +27,10 @@ function run(cwd, vars) { const result = spawnSync(process.execPath, [INDEX], { cwd, env: childEnv(vars), - encoding: 'utf8', + encoding: "utf8", }); const lines = result.stdout.split(/\r?\n/); - const errors = lines.filter((l) => l.startsWith('::error')); + const errors = lines.filter((l) => l.startsWith("::error")); return { status: result.status, lines, errors, stderr: result.stderr }; } @@ -38,100 +38,127 @@ function annotation(path) { return `::error file=${path},line=1::Missing SPDX-License-Identifier: Apache-2.0`; } -test('all files with headers pass', () => { - const cwd = makeRepo({ 'a.py': `${HEADER}print(1)\n`, 'pkg/b.py': HEADER }); - const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.py' }); +test("all files with headers pass", () => { + const cwd = makeRepo({ "a.py": `${HEADER}print(1)\n`, "pkg/b.py": HEADER }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: "*.py" }); assert.deepEqual(errors, []); assert.equal(status, 0, stderr); }); -test('failures are annotated in sorted order', () => { - const cwd = makeRepo({ 'z.py': 'x\n', 'a.py': 'x\n', 'm/b.py': 'x\n', 'ok.py': HEADER }); - const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); - assert.deepEqual(errors, [annotation('a.py'), annotation('m/b.py'), annotation('z.py')]); +test("failures are annotated in sorted order", () => { + const cwd = makeRepo({ + "z.py": "x\n", + "a.py": "x\n", + "m/b.py": "x\n", + "ok.py": HEADER, + }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: "*.py" }); + assert.deepEqual(errors, [ + annotation("a.py"), + annotation("m/b.py"), + annotation("z.py"), + ]); assert.equal(status, 1); }); // git lists x.json before x.json.d/y.py, but x.json is reported as // x.json.license, which sorts after x.json.d/y.py. -test('sidecar paths are sorted by their reported name', () => { +test("sidecar paths are sorted by their reported name", () => { const cwd = makeRepo({ - 'x.json': '{}\n', - 'x.json.license': 'nothing\n', - 'x.json.d/y.py': 'x\n', + "x.json": "{}\n", + "x.json.license": "nothing\n", + "x.json.d/y.py": "x\n", }); - const { errors } = run(cwd, { INPUT_INCLUDE: '*.json *.py' }); - assert.deepEqual(errors, [annotation('x.json.d/y.py'), annotation('x.json.license')]); + const { errors } = run(cwd, { INPUT_INCLUDE: "*.json *.py" }); + assert.deepEqual(errors, [ + annotation("x.json.d/y.py"), + annotation("x.json.license"), + ]); }); -test('sidecar with header makes the file pass', () => { - const cwd = makeRepo({ 'cfg.json': '{}\n', 'cfg.json.license': HEADER }); - const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.json' }); +test("sidecar with header makes the file pass", () => { + const cwd = makeRepo({ "cfg.json": "{}\n", "cfg.json.license": HEADER }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: "*.json" }); assert.deepEqual(errors, []); assert.equal(status, 0, stderr); }); -test('sidecar without header is annotated by its own path', () => { - const cwd = makeRepo({ 'cfg.json': '{}\n', 'cfg.json.license': 'nothing\n' }); - const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.json' }); - assert.deepEqual(errors, [annotation('cfg.json.license')]); +test("sidecar without header is annotated by its own path", () => { + const cwd = makeRepo({ "cfg.json": "{}\n", "cfg.json.license": "nothing\n" }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: "*.json" }); + assert.deepEqual(errors, [annotation("cfg.json.license")]); assert.equal(status, 1); }); -test('newline-separated include patterns all apply', () => { - const cwd = makeRepo({ 'a.py': 'x\n', 'b.sh': 'x\n', 'c.md': 'x\n' }); - const { errors } = run(cwd, { INPUT_INCLUDE: ' *.py\n *.sh\n' }); - assert.deepEqual(errors, [annotation('a.py'), annotation('b.sh')]); +test("newline-separated include patterns all apply", () => { + const cwd = makeRepo({ "a.py": "x\n", "b.sh": "x\n", "c.md": "x\n" }); + const { errors } = run(cwd, { INPUT_INCLUDE: " *.py\n *.sh\n" }); + assert.deepEqual(errors, [annotation("a.py"), annotation("b.sh")]); }); -test('exclude patterns are honoured', () => { - const cwd = makeRepo({ 'a.py': HEADER, 'third_party/x.py': 'x\n', 'm_pb2.py': 'x\n' }); +test("exclude patterns are honoured", () => { + const cwd = makeRepo({ + "a.py": HEADER, + "third_party/x.py": "x\n", + "m_pb2.py": "x\n", + }); const { status, errors, stderr } = run(cwd, { - INPUT_INCLUDE: '*.py', - INPUT_EXCLUDE: 'third_party/*\n*_pb2.py\n', + INPUT_INCLUDE: "*.py", + INPUT_EXCLUDE: "third_party/*\n*_pb2.py\n", }); assert.deepEqual(errors, []); assert.equal(status, 0, stderr); }); -test('annotation file property is escaped', () => { - const cwd = makeRepo({ 'a,b%.py': 'x\n' }); - const { errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); - assert.deepEqual(errors, [annotation('a%2Cb%25.py')]); +test("annotation file property is escaped", () => { + const cwd = makeRepo({ "a,b%.py": "x\n" }); + const { errors } = run(cwd, { INPUT_INCLUDE: "*.py" }); + assert.deepEqual(errors, [annotation("a%2Cb%25.py")]); }); // Windows forbids newlines and colons in filenames. -test('a filename cannot inject a workflow command', { skip: process.platform === 'win32' }, () => { - const cwd = makeRepo({ 'x\n::add-mask::DUMMY\n.py': 'x\n' }); - const { lines, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); - assert.deepEqual(errors, [annotation('x%0A%3A%3Aadd-mask%3A%3ADUMMY%0A.py')]); - assert.ok(!lines.some((l) => l.startsWith('::add-mask')), lines.join('\n')); -}); - -test('a long first line does not hide a header on line 2', () => { - const cwd = makeRepo({ 'a.py': `#${'x'.repeat(10000)}\n${HEADER}` }); - const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: '*.py' }); +test( + "a filename cannot inject a workflow command", + { skip: process.platform === "win32" }, + () => { + const cwd = makeRepo({ "x\n::add-mask::DUMMY\n.py": "x\n" }); + const { lines, errors } = run(cwd, { INPUT_INCLUDE: "*.py" }); + assert.deepEqual(errors, [ + annotation("x%0A%3A%3Aadd-mask%3A%3ADUMMY%0A.py"), + ]); + assert.ok(!lines.some((l) => l.startsWith("::add-mask")), lines.join("\n")); + }, +); + +test("a long first line does not hide a header on line 2", () => { + const cwd = makeRepo({ "a.py": `#${"x".repeat(10000)}\n${HEADER}` }); + const { status, errors, stderr } = run(cwd, { INPUT_INCLUDE: "*.py" }); assert.deepEqual(errors, []); assert.equal(status, 0, stderr); }); // Line 1 is 8155 bytes, so "Apache-2.0" on line 2 ends exactly at byte 8192. -test('a license expression cut at 8 KiB is not accepted', () => { - const line1 = `#${'x'.repeat(8153)}\n`; - const cwd = makeRepo({ 'a.py': `${line1}# SPDX-License-Identifier: Apache-2.0 OR MIT\n` }); - const { status, errors } = run(cwd, { INPUT_INCLUDE: '*.py' }); - assert.deepEqual(errors, [annotation('a.py')]); +test("a license expression cut at 8 KiB is not accepted", () => { + const line1 = `#${"x".repeat(8153)}\n`; + const cwd = makeRepo({ + "a.py": `${line1}# SPDX-License-Identifier: Apache-2.0 OR MIT\n`, + }); + const { status, errors } = run(cwd, { INPUT_INCLUDE: "*.py" }); + assert.deepEqual(errors, [annotation("a.py")]); assert.equal(status, 1); }); -test('step summary is appended with failing paths', () => { - const cwd = makeRepo({ 'a.py': 'x\n', 'm/b.py': 'x\n' }); - const summary = join(tempDir(), 'summary.md'); - writeFileSync(summary, 'existing\n'); - const { status } = run(cwd, { INPUT_INCLUDE: '*.py', GITHUB_STEP_SUMMARY: summary }); - const text = readFileSync(summary, 'utf8'); - assert.ok(text.startsWith('existing\n'), text); - assert.ok(text.includes('a.py'), text); - assert.ok(text.includes('m/b.py'), text); +test("step summary is appended with failing paths", () => { + const cwd = makeRepo({ "a.py": "x\n", "m/b.py": "x\n" }); + const summary = join(tempDir(), "summary.md"); + writeFileSync(summary, "existing\n"); + const { status } = run(cwd, { + INPUT_INCLUDE: "*.py", + GITHUB_STEP_SUMMARY: summary, + }); + const text = readFileSync(summary, "utf8"); + assert.ok(text.startsWith("existing\n"), text); + assert.ok(text.includes("a.py"), text); + assert.ok(text.includes("m/b.py"), text); assert.equal(status, 1); }); diff --git a/spdx-check/test/repo.mjs b/spdx-check/test/repo.mjs index d293ac7..c3d9e6e 100644 --- a/spdx-check/test/repo.mjs +++ b/spdx-check/test/repo.mjs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 -import { after } from 'node:test'; -import { execFileSync } from 'node:child_process'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; +import { after } from "node:test"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; const dirs = []; after(() => { @@ -12,7 +12,7 @@ after(() => { }); export function tempDir() { - const dir = mkdtempSync(join(tmpdir(), 'spdx-')); + const dir = mkdtempSync(join(tmpdir(), "spdx-")); dirs.push(dir); return dir; } @@ -20,7 +20,7 @@ export function tempDir() { // `files` maps a /-separated path to its content. export function writeFiles(root, files) { for (const [path, content] of Object.entries(files)) { - const full = join(root, ...path.split('/')); + const full = join(root, ...path.split("/")); mkdirSync(dirname(full), { recursive: true }); writeFileSync(full, content); } @@ -30,8 +30,8 @@ export function writeFiles(root, files) { // skipping commits avoids needing a git identity on CI. export function makeRepo(files) { const root = tempDir(); - execFileSync('git', ['init', '-q'], { cwd: root }); + execFileSync("git", ["init", "-q"], { cwd: root }); writeFiles(root, files); - execFileSync('git', ['add', '-A'], { cwd: root }); + execFileSync("git", ["add", "-A"], { cwd: root }); return root; }