#!/usr/bin/env node // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /** * Checks that every tracked source file under packages/, native/ and scripts/ * carries the Apache-2.0 license header. * * node scripts/check-license-headers.mjs # report and exit 1 on misses * node scripts/check-license-headers.mjs --fix # insert the header where missing * * Checked extensions: .ts, .tsx, .mts, .cts, .js, .mjs, .cjs, .kt, .kts, .dart and * .swift (`//` header), and .sh, .bash and .py (`#` header). Other file types * (for example .lua, .pro, .sql and .html) are not checked. tasks/, test-apps/, * .github/ and root config files are out of scope; files there that carry a * header got it by hand. * * A file passes when, within its first HEADER_SCAN_LINES lines (counted after an * optional shebang or `// swift-tools-version` line), a comment line reads * exactly `SPDX-License-Identifier: Apache-2.0` and an Amazon copyright comment * line sits above it. The older long-form Apache-2.0 notice, kept in * native/kotlin/plugin/build.gradle.kts, also passes. Files are enumerated with * `git ls-files`, so untracked and gitignored build output is never scanned. */ import { execFileSync } from 'node:child_process'; import { readFileSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..'); /** Top-level trees that are scanned. tasks/, test-apps/, .github/ and root config files are not published, so they are out of scope. */ const ROOTS = ['packages/', 'native/', 'scripts/']; /** File extensions that take a `#` comment header. */ const HASH_EXTENSIONS = new Set(['sh', 'bash', 'py']); /** File extensions that must carry a header. */ export const EXTENSIONS = new Set([ 'ts', 'tsx', 'mts', 'cts', 'js', 'mjs', 'cjs', 'kt', 'kts', 'dart', 'swift', ...HASH_EXTENSIONS, ]); /** * Paths that are deliberately left without a header. Each entry is a RegExp * tested against the repo-relative path, with the reason next to it. */ export const EXCLUSIONS = [ // Scaffolds copied into a user's new project; the user owns that code. [/^packages\/create-blocks-app\/templates\//, 'user project scaffolds'], // Codegen goldens mirror the code generated into user projects, which // carries no header. Only the numbered fixture dirs hold goldens; the // scripts next to them are hand-written and keep their header. [/^native\/codegen-fixtures\/\d{2}-[^/]+\//, 'codegen golden outputs'], // Written by Next.js on every build; a header would be overwritten. [/^packages\/admin-ui\/next-env\.d\.ts$/, 'generated by Next.js'], // Written by the build_version builder, which has no header option. CI // regenerates it and fails on any diff, so a hand-added header cannot stay. [/^native\/dart\/packages\/blocks_runtime\/lib\/src\/version\.dart$/, 'generated by build_version'], // Written by Mockito's build_runner builder ("Do not manually edit"); the // next regeneration would drop a hand-added header. [/\.mocks\.dart$/, 'generated by Mockito'], ]; /** How many lines (after a shebang / swift-tools-version line) are searched. */ const HEADER_SCAN_LINES = 6; const SPDX_MARKER = 'SPDX-License-Identifier: Apache-2.0'; /** * The header forms that pass. Each needs its license line within the scan * window and one of its copyright lines somewhere above it. Every line must be * a comment (`//`, ` *` or `#`), so a string literal never counts. */ const HEADER_FORMS = [ { license: /^\s*(\/\/|\*|#)\s*SPDX-License-Identifier: Apache-2\.0\s*$/, copyright: [ /^\s*(\/\/|\*|#)\s*Copyright Amazon\.com, Inc\. or its affiliates\. All Rights Reserved\.\s*$/, // The Swift form, enforced by native/swift/.swiftformat. /^\s*(\/\/|\*|#)\s*Copyright Amazon\.com Inc\. or its affiliates\.\s*$/, ], }, { // The older long-form notice in native/kotlin/plugin/build.gradle.kts. license: /^\s*\*\s*Licensed under the Apache License, Version 2\.0 \(the "License"\)\.\s*$/, copyright: [/^\s*\*\s*Copyright \d{4} Amazon\.com, Inc\. or its affiliates\. All Rights Reserved\.\s*$/], }, ]; const HASH_HEADER = [ '# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.', '# SPDX-License-Identifier: Apache-2.0', ]; const SLASH_HEADER = [ '// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.', '// SPDX-License-Identifier: Apache-2.0', ]; /** Matches the header enforced by native/swift/.swiftformat. */ const SWIFT_HEADER = [ '//', '// Copyright Amazon.com Inc. or its affiliates.', '// All Rights Reserved.', '//', '// SPDX-License-Identifier: Apache-2.0', '//', ]; export function extensionOf(path) { const dot = path.lastIndexOf('.'); return dot === -1 ? '' : path.slice(dot + 1); } export function excludedBy(path) { return EXCLUSIONS.find(([pattern]) => pattern.test(path)); } /** Number of leading lines that must stay above the header (0 or 1). */ function preambleLength(lines) { const first = lines[0] ?? ''; if (first.startsWith('#!') || first.startsWith('// swift-tools-version')) return 1; return 0; } export function hasHeader(text) { const lines = text.replace(/^\uFEFF/, '').split('\n'); const start = preambleLength(lines); const window = lines.slice(start, start + HEADER_SCAN_LINES); return HEADER_FORMS.some(({ license, copyright }) => { const at = window.findIndex((line) => license.test(line)); return at > 0 && window.slice(0, at).some((line) => copyright.some((pattern) => pattern.test(line))); }); } /** The header lines for a file, picked by its extension. */ function headerFor(path) { const ext = extensionOf(path); if (ext === 'swift') return SWIFT_HEADER; if (HASH_EXTENSIONS.has(ext)) return HASH_HEADER; return SLASH_HEADER; } export function withHeader(text, path) { // A file that already passes is returned unchanged, so a second run is a no-op. if (hasHeader(text)) return text; // Keep a leading byte-order mark at the very front, above the header. const bom = text.startsWith('\uFEFF') ? '\uFEFF' : ''; if (bom) text = text.slice(1); const eol = text.includes('\r\n') ? '\r\n' : '\n'; const lines = text.split(/\r?\n/); const start = preambleLength(lines); const header = headerFor(path); const before = lines.slice(0, start); let rest = lines.slice(start); // Collapse leading blank lines so exactly one separates header and code. while (rest.length > 1 && rest[0].trim() === '') rest = rest.slice(1); const body = rest.length === 1 && rest[0] === '' ? [''] : ['', ...rest]; return bom + [...before, ...header, ...body].join(eol); } function trackedFiles() { const out = execFileSync('git', ['ls-files', '-z', '--', ...ROOTS], { cwd: repoRoot, encoding: 'utf8' }); return out.split('\0').filter(Boolean); } function main() { const fix = process.argv.includes('--fix'); const missing = []; for (const path of trackedFiles()) { if (!EXTENSIONS.has(extensionOf(path))) continue; if (excludedBy(path)) continue; const abs = join(repoRoot, path); let text; try { text = readFileSync(abs, 'utf8'); } catch { // Deleted in the working tree but still in the index. continue; } if (hasHeader(text)) continue; if (fix) writeFileSync(abs, withHeader(text, path)); missing.push(path); } if (missing.length === 0) { console.log('All tracked source files carry the Apache-2.0 license header.'); return; } if (fix) { console.log(`Added the license header to ${missing.length} file(s):`); for (const path of missing) console.log(` ${path}`); return; } console.error(`${missing.length} file(s) are missing the license header (${SPDX_MARKER}):`); for (const path of missing) console.error(` ${path}`); console.error('\nRun `node scripts/check-license-headers.mjs --fix` to add it.'); process.exitCode = 1; } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();