build: ESLint rule to check/add license headers (#11716)

This commit is contained in:
richestrinh 2024-01-26 21:25:39 -08:00 committed by GitHub
parent d085127bba
commit 96b7af5988
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 84 additions and 0 deletions

View File

@ -149,6 +149,8 @@ module.exports = {
'rulesdir/prettier-comments': 'error',
// Enforces consistent file extension
'rulesdir/extensions': 'error',
// Enforces license headers on files
'rulesdir/check-license': 'warn',
},
overrides: [
{

View File

@ -0,0 +1,82 @@
/**
* @license
* Copyright 2024 Google Inc.
* SPDX-License-Identifier: Apache-2.0
*/
import type {TSESTree} from '@typescript-eslint/utils';
import {ESLintUtils} from '@typescript-eslint/utils';
const createRule = ESLintUtils.RuleCreator(name => {
return `https://github.com/puppeteer/puppeteer/tree/main/tools/eslint/${name}.ts`;
});
const copyrightPattern = /Copyright ([0-9]{4}) Google Inc\./;
const currentYear = new Date().getFullYear;
const licenseHeader = `/**
* @license
* Copyright ${currentYear} Google Inc.
* SPDX-License-Identifier: Apache-2.0
*/`;
const enforceLicenseRule = createRule<[], 'licenseRule'>({
name: 'check-license',
meta: {
type: 'layout',
docs: {
description: 'Validate existence of license header',
requiresTypeChecking: false,
},
fixable: 'code',
schema: [],
messages: {
licenseRule: 'Add license header.',
},
},
defaultOptions: [],
create(context) {
const sourceCode = context.sourceCode;
const comments = sourceCode.getAllComments();
const header =
comments[0]?.type === 'Block' && isHeaderComment(comments[0])
? comments[0]
: null;
function isHeaderComment(comment: TSESTree.Comment) {
if (comment && comment.range[0] >= 0 && comment.range[1] <= 88) {
return true;
} else {
return false;
}
}
return {
Program(node) {
if (
header &&
header.value.includes('@license') &&
header.value.includes('SPDX-License-Identifier: Apache-2.0') &&
copyrightPattern.test(header.value)
) {
return;
}
// Add header license
if (!header || !header.value.includes('@license')) {
const startLoc: [number, number] = [0, 88];
context.report({
node: node,
messageId: 'licenseRule',
fix(fixer) {
return fixer.insertTextBeforeRange(startLoc, licenseHeader);
},
});
}
},
};
},
});
export = enforceLicenseRule;