electron/script/lint.js

345 lines
12 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
2020-12-10 18:57:06 +00:00
const crypto = require('crypto');
2020-03-20 20:28:31 +00:00
const { GitProcess } = require('dugite');
const childProcess = require('child_process');
const { ESLint } = require('eslint');
2020-03-20 20:28:31 +00:00
const fs = require('fs');
const minimist = require('minimist');
const path = require('path');
const { chunkFilenames, findMatchingFiles } = require('./lib/utils');
const ELECTRON_ROOT = path.normalize(path.dirname(__dirname));
const SOURCE_ROOT = path.resolve(ELECTRON_ROOT, '..');
const DEPOT_TOOLS = path.resolve(SOURCE_ROOT, 'third_party', 'depot_tools');
// Augment the PATH for this script so that we can find executables
// in the depot_tools folder even if folks do not have an instance of
// DEPOT_TOOLS in their path already
process.env.PATH = `${process.env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
const IGNORELIST = new Set([
2019-06-19 20:56:58 +00:00
['shell', 'browser', 'resources', 'win', 'resource.h'],
['shell', 'common', 'node_includes.h'],
['spec', 'fixtures', 'pages', 'jquery-3.6.0.min.js'],
['spec', 'ts-smoke', 'electron', 'main.ts'],
['spec', 'ts-smoke', 'electron', 'renderer.ts'],
['spec', 'ts-smoke', 'runner.js']
].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
const IS_WINDOWS = process.platform === 'win32';
function spawnAndCheckExitCode (cmd, args, opts) {
opts = { stdio: 'inherit', ...opts };
const { error, status, signal } = childProcess.spawnSync(cmd, args, opts);
if (error) {
2022-07-05 15:49:56 +00:00
// the subprocess failed or timed out
console.error(error);
process.exit(1);
}
if (status === null) {
// the subprocess terminated due to a signal
console.error(signal);
process.exit(1);
}
if (status !== 0) {
// `status` is an exit code
process.exit(status);
}
}
function cpplint (args) {
args.unshift(`--root=${SOURCE_ROOT}`);
const result = childProcess.spawnSync(IS_WINDOWS ? 'cpplint.bat' : 'cpplint.py', args, { encoding: 'utf8', shell: true });
// cpplint.py writes EVERYTHING to stderr, including status messages
if (result.stderr) {
for (const line of result.stderr.split(/[\r\n]+/)) {
if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
2020-03-20 20:28:31 +00:00
console.warn(line);
}
}
}
if (result.status !== 0) {
if (result.error) console.error(result.error);
process.exit(result.status || 1);
}
}
function isObjCHeader (filename) {
2020-03-20 20:28:31 +00:00
return /\/(mac|cocoa)\//.test(filename);
}
const LINTERS = [{
key: 'c++',
roots: ['shell'],
test: filename => filename.endsWith('.cc') || (filename.endsWith('.h') && !isObjCHeader(filename)),
run: (opts, filenames) => {
const clangFormatFlags = opts.fix ? ['--fix'] : [];
for (const chunk of chunkFilenames(filenames)) {
spawnAndCheckExitCode('python3', ['script/run-clang-format.py', ...clangFormatFlags, ...chunk]);
cpplint(chunk);
}
}
}, {
key: 'objc',
2019-06-19 20:56:58 +00:00
roots: ['shell'],
test: filename => filename.endsWith('.mm') || (filename.endsWith('.h') && isObjCHeader(filename)),
run: (opts, filenames) => {
const clangFormatFlags = opts.fix ? ['--fix'] : [];
spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', ...clangFormatFlags, ...filenames]);
const filter = [
'-readability/braces',
'-readability/casting',
'-whitespace/braces',
'-whitespace/indent',
'-whitespace/parens'
2020-03-20 20:28:31 +00:00
];
cpplint(['--extensions=mm,h', `--filter=${filter.join(',')}`, ...filenames]);
}
}, {
key: 'python',
roots: ['script'],
test: filename => filename.endsWith('.py'),
run: (opts, filenames) => {
2020-03-20 20:28:31 +00:00
const rcfile = path.join(DEPOT_TOOLS, 'pylintrc');
const args = ['--rcfile=' + rcfile, ...filenames];
const env = { PYTHONPATH: path.join(ELECTRON_ROOT, 'script'), ...process.env };
spawnAndCheckExitCode('pylint-2.7', args, { env });
}
}, {
key: 'javascript',
roots: ['build', 'default_app', 'lib', 'npm', 'script', 'spec'],
ignoreRoots: ['spec/node_modules'],
test: filename => filename.endsWith('.js') || filename.endsWith('.ts'),
run: async (opts, filenames) => {
const eslint = new ESLint({
2020-12-10 18:57:06 +00:00
// Do not use the lint cache on CI builds
cache: !process.env.CI,
cacheLocation: `node_modules/.eslintcache.${crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex')}`,
extensions: ['.js', '.ts'],
fix: opts.fix
});
const formatter = await eslint.loadFormatter();
let successCount = 0;
2020-12-10 18:57:06 +00:00
const results = await eslint.lintFiles(filenames);
for (const result of results) {
successCount += result.errorCount === 0 ? 1 : 0;
2020-12-10 18:57:06 +00:00
if (opts.verbose && result.errorCount === 0 && result.warningCount === 0) {
console.log(`${result.filePath}: no errors or warnings`);
}
}
2020-12-10 18:57:06 +00:00
console.log(formatter.format(results));
if (opts.fix) {
await ESLint.outputFixes(results);
}
if (successCount !== filenames.length) {
console.error('Linting had errors');
process.exit(1);
}
}
}, {
key: 'gn',
roots: ['.'],
test: filename => filename.endsWith('.gn') || filename.endsWith('.gni'),
run: (opts, filenames) => {
const allOk = filenames.map(filename => {
const env = {
CHROMIUM_BUILDTOOLS_PATH: path.resolve(ELECTRON_ROOT, '..', 'buildtools'),
DEPOT_TOOLS_WIN_TOOLCHAIN: '0',
...process.env
};
// Users may not have depot_tools in PATH.
2020-03-20 20:28:31 +00:00
env.PATH = `${env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
const args = ['format', filename];
if (!opts.fix) args.push('--dry-run');
const result = childProcess.spawnSync('gn', args, { env, stdio: 'inherit', shell: true });
if (result.status === 0) {
2020-03-20 20:28:31 +00:00
return true;
} else if (result.status === 2) {
2020-03-20 20:28:31 +00:00
console.log(`GN format errors in "${filename}". Run 'gn format "${filename}"' or rerun with --fix to fix them.`);
return false;
} else {
2020-03-20 20:28:31 +00:00
console.log(`Error running 'gn format --dry-run "${filename}"': exit code ${result.status}`);
return false;
}
2020-03-20 20:28:31 +00:00
}).every(x => x);
if (!allOk) {
2020-03-20 20:28:31 +00:00
process.exit(1);
}
}
}, {
key: 'patches',
roots: ['patches'],
2020-11-30 07:49:01 +00:00
test: filename => filename.endsWith('.patch'),
run: (opts, filenames) => {
2020-03-20 20:28:31 +00:00
const patchesDir = path.resolve(__dirname, '../patches');
2020-11-30 07:49:01 +00:00
const patchesConfig = path.resolve(patchesDir, 'config.json');
// If the config does not exist, that's a problem
2020-11-30 07:49:01 +00:00
if (!fs.existsSync(patchesConfig)) {
console.error(`Patches config file: "${patchesConfig}" does not exist`);
2020-11-30 07:49:01 +00:00
process.exit(1);
}
2020-11-30 07:49:01 +00:00
const config = JSON.parse(fs.readFileSync(patchesConfig, 'utf8'));
for (const key of Object.keys(config)) {
// The directory the config points to should exist
const targetPatchesDir = path.resolve(__dirname, '../../..', key);
if (!fs.existsSync(targetPatchesDir)) {
console.error(`target patch directory: "${targetPatchesDir}" does not exist`);
process.exit(1);
}
2020-11-30 07:49:01 +00:00
// We need a .patches file
const dotPatchesPath = path.resolve(targetPatchesDir, '.patches');
if (!fs.existsSync(dotPatchesPath)) {
console.error(`.patches file: "${dotPatchesPath}" does not exist`);
process.exit(1);
}
2020-11-30 07:49:01 +00:00
// Read the patch list
const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n');
const patchFileSet = new Set(patchFileList);
patchFileList.reduce((seen, file) => {
if (seen.has(file)) {
console.error(`'${file}' is listed in ${dotPatchesPath} more than once`);
process.exit(1);
}
2020-11-30 07:49:01 +00:00
return seen.add(file);
}, new Set());
if (patchFileList.length !== patchFileSet.size) {
console.error('Each patch file should only be in the .patches file once');
process.exit(1);
}
2020-11-30 07:49:01 +00:00
for (const file of fs.readdirSync(targetPatchesDir)) {
// Ignore the .patches file and READMEs
if (file === '.patches' || file === 'README.md') continue;
2020-11-30 07:49:01 +00:00
if (!patchFileSet.has(file)) {
console.error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`);
process.exit(1);
}
2020-11-30 07:49:01 +00:00
patchFileSet.delete(file);
}
// If anything is left in this set, it means it did not exist on disk
if (patchFileSet.size > 0) {
console.error(`Expected all the patch files listed in the .patches file at "${dotPatchesPath}" to exist but some did not:\n${JSON.stringify([...patchFileSet.values()], null, 2)}`);
process.exit(1);
}
}
2020-11-30 07:49:01 +00:00
const allOk = filenames.length > 0 && filenames.map(f => {
2020-03-20 20:28:31 +00:00
const patchText = fs.readFileSync(f, 'utf8');
2020-11-30 07:49:01 +00:00
const subjectAndDescription = /Subject: (.*?)\n\n([\s\S]*?)\s*(?=diff)/ms.exec(patchText);
if (!subjectAndDescription[2]) {
2020-03-20 20:28:31 +00:00
console.warn(`Patch file '${f}' has no description. Every patch must contain a justification for why the patch exists and the plan for its removal.`);
2020-11-30 07:49:01 +00:00
return false;
}
const trailingWhitespaceLines = patchText.split(/\r?\n/).map((line, index) => [line, index]).filter(([line]) => line.startsWith('+') && /\s+$/.test(line)).map(([, lineNumber]) => lineNumber + 1);
if (trailingWhitespaceLines.length > 0) {
console.warn(`Patch file '${f}' has trailing whitespace on some lines (${trailingWhitespaceLines.join(',')}).`);
2020-11-30 07:49:01 +00:00
return false;
}
2020-11-30 07:49:01 +00:00
return true;
}).every(x => x);
if (!allOk) {
2020-03-20 20:28:31 +00:00
process.exit(1);
}
}
2020-03-20 20:28:31 +00:00
}];
function parseCommandLine () {
2020-03-20 20:28:31 +00:00
let help;
const opts = minimist(process.argv.slice(2), {
boolean: ['c++', 'objc', 'javascript', 'python', 'gn', 'patches', 'help', 'changed', 'fix', 'verbose', 'only'],
alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
2020-03-20 20:28:31 +00:00
unknown: arg => { help = true; }
});
if (help || opts.help) {
2020-03-20 20:28:31 +00:00
console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]');
process.exit(0);
}
2020-03-20 20:28:31 +00:00
return opts;
}
async function findChangedFiles (top) {
2020-03-20 20:28:31 +00:00
const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
if (result.exitCode !== 0) {
2020-03-20 20:28:31 +00:00
console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
process.exit(1);
}
2020-03-20 20:28:31 +00:00
const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
const absolutePaths = relativePaths.map(x => path.join(top, x));
return new Set(absolutePaths);
}
async function findFiles (args, linter) {
2020-03-20 20:28:31 +00:00
let filenames = [];
let includelist = null;
// build the includelist
if (args.changed) {
includelist = await findChangedFiles(ELECTRON_ROOT);
if (!includelist.size) {
2020-03-20 20:28:31 +00:00
return [];
}
} else if (args.only) {
includelist = new Set(args._.map(p => path.resolve(p)));
}
// accumulate the raw list of files
for (const root of linter.roots) {
const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
2020-03-20 20:28:31 +00:00
filenames.push(...files);
}
for (const ignoreRoot of (linter.ignoreRoots) || []) {
const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
2020-03-20 20:28:31 +00:00
if (!fs.existsSync(ignorePath)) continue;
2020-03-20 20:28:31 +00:00
const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
}
// remove ignored files
filenames = filenames.filter(x => !IGNORELIST.has(x));
// if a includelist exists, remove anything not in it
if (includelist) {
filenames = filenames.filter(x => includelist.has(x));
}
// it's important that filenames be relative otherwise clang-format will
// produce patches with absolute paths in them, which `git apply` will refuse
// to apply.
return filenames.map(x => path.relative(ELECTRON_ROOT, x));
}
async function main () {
2020-03-20 20:28:31 +00:00
const opts = parseCommandLine();
// no mode specified? run 'em all
if (!opts['c++'] && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches) {
2020-03-20 20:28:31 +00:00
opts['c++'] = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = true;
}
2020-03-20 20:28:31 +00:00
const linters = LINTERS.filter(x => opts[x.key]);
for (const linter of linters) {
2020-03-20 20:28:31 +00:00
const filenames = await findFiles(opts, linter);
if (filenames.length) {
2020-03-20 20:28:31 +00:00
if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
await linter.run(opts, filenames);
}
}
}
if (process.mainModule === module) {
main().catch((error) => {
2020-03-20 20:28:31 +00:00
console.error(error);
process.exit(1);
});
}