diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..65a791b --- /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] + 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/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. diff --git a/README.md b/README.md index ae44eeb..6a1e80a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ # workflows Reusable GitHub Actions workflows for the ai-openshell organization. + +## Actions + +- [`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. 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..2f4e8d8 --- /dev/null +++ b/spdx-check/files.mjs @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: Apache-2.0 + +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(excludeSpec); + 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..dcf2da4 --- /dev/null +++ b/spdx-check/header.mjs @@ -0,0 +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", LINES); + 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..7a9571d --- /dev/null +++ b/spdx-check/index.mjs @@ -0,0 +1,70 @@ +// 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 { 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 = "") { + 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"); + 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 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) { + const file = src.replace(/[%\r\n:,]/g, (char) => ESCAPES[char]); + return `::error file=${file},line=1::Missing ${LICENSE}`; +} + +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() { + 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); + 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; +} + +main(); diff --git a/spdx-check/test/files.test.mjs b/spdx-check/test/files.test.mjs new file mode 100644 index 0000000..a604cbd --- /dev/null +++ b/spdx-check/test/files.test.mjs @@ -0,0 +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"; + +// 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) { + 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("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("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"]); + const files = listFiles({ + include: ["*.py"], + exclude: ["third_party/*", "*_pb2.py"], + cwd, + }); + 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("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("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 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 new file mode 100644 index 0000000..bf040df --- /dev/null +++ b/spdx-check/test/header.test.mjs @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: Apache-2.0 + +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"; + +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); +}); + +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 new file mode 100644 index 0000000..182bbd4 --- /dev/null +++ b/spdx-check/test/index.test.mjs @@ -0,0 +1,164 @@ +// 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"; + +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. +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 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) { + 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("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" }); + 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"); + 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 new file mode 100644 index 0000000..c3d9e6e --- /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; +}