lint.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #!/usr/bin/env node
  2. const crypto = require('node:crypto');
  3. const { GitProcess } = require('dugite');
  4. const childProcess = require('node:child_process');
  5. const { ESLint } = require('eslint');
  6. const fs = require('node:fs');
  7. const minimist = require('minimist');
  8. const path = require('node:path');
  9. const { chunkFilenames, findMatchingFiles } = require('./lib/utils');
  10. const ELECTRON_ROOT = path.normalize(path.dirname(__dirname));
  11. const SOURCE_ROOT = path.resolve(ELECTRON_ROOT, '..');
  12. const DEPOT_TOOLS = path.resolve(SOURCE_ROOT, 'third_party', 'depot_tools');
  13. // Augment the PATH for this script so that we can find executables
  14. // in the depot_tools folder even if folks do not have an instance of
  15. // DEPOT_TOOLS in their path already
  16. process.env.PATH = `${process.env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
  17. const IGNORELIST = new Set([
  18. ['shell', 'browser', 'resources', 'win', 'resource.h'],
  19. ['shell', 'common', 'node_includes.h'],
  20. ['spec', 'fixtures', 'pages', 'jquery-3.6.0.min.js']
  21. ].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
  22. const IS_WINDOWS = process.platform === 'win32';
  23. const CPPLINT_FILTERS = [
  24. // from presubmit_canned_checks.py OFF_BY_DEFAULT_LINT_FILTERS
  25. '-build/include',
  26. '-build/include_order',
  27. '-build/namespaces',
  28. '-readability/casting',
  29. '-runtime/int',
  30. '-whitespace/braces',
  31. // from presubmit_canned_checks.py OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS
  32. '-build/c++11',
  33. '-build/header_guard',
  34. '-readability/todo',
  35. '-runtime/references',
  36. '-whitespace/braces',
  37. '-whitespace/comma',
  38. '-whitespace/end_of_line',
  39. '-whitespace/forcolon',
  40. '-whitespace/indent',
  41. '-whitespace/line_length',
  42. '-whitespace/newline',
  43. '-whitespace/operators',
  44. '-whitespace/parens',
  45. '-whitespace/semicolon',
  46. '-whitespace/tab'
  47. ];
  48. function spawnAndCheckExitCode (cmd, args, opts) {
  49. opts = { stdio: 'inherit', ...opts };
  50. const { error, status, signal } = childProcess.spawnSync(cmd, args, opts);
  51. if (error) {
  52. // the subprocess failed or timed out
  53. console.error(error);
  54. process.exit(1);
  55. }
  56. if (status === null) {
  57. // the subprocess terminated due to a signal
  58. console.error(signal);
  59. process.exit(1);
  60. }
  61. if (status !== 0) {
  62. // `status` is an exit code
  63. process.exit(status);
  64. }
  65. }
  66. function cpplint (args) {
  67. args.unshift(`--root=${SOURCE_ROOT}`);
  68. const result = childProcess.spawnSync(IS_WINDOWS ? 'cpplint.bat' : 'cpplint.py', args, { encoding: 'utf8', shell: true });
  69. // cpplint.py writes EVERYTHING to stderr, including status messages
  70. if (result.stderr) {
  71. for (const line of result.stderr.split(/[\r\n]+/)) {
  72. if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
  73. console.warn(line);
  74. }
  75. }
  76. }
  77. if (result.status !== 0) {
  78. if (result.error) console.error(result.error);
  79. process.exit(result.status || 1);
  80. }
  81. }
  82. function isObjCHeader (filename) {
  83. return /\/(mac|cocoa)\//.test(filename);
  84. }
  85. const LINTERS = [{
  86. key: 'c++',
  87. roots: ['shell'],
  88. test: filename => filename.endsWith('.cc') || (filename.endsWith('.h') && !isObjCHeader(filename)),
  89. run: (opts, filenames) => {
  90. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  91. for (const chunk of chunkFilenames(filenames)) {
  92. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', ...clangFormatFlags, ...chunk]);
  93. cpplint([`--filter=${CPPLINT_FILTERS.join(',')}`, ...chunk]);
  94. }
  95. }
  96. }, {
  97. key: 'objc',
  98. roots: ['shell'],
  99. test: filename => filename.endsWith('.mm') || (filename.endsWith('.h') && isObjCHeader(filename)),
  100. run: (opts, filenames) => {
  101. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  102. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', ...clangFormatFlags, ...filenames]);
  103. const filter = [...CPPLINT_FILTERS, '-readability/braces'];
  104. cpplint(['--extensions=mm,h', `--filter=${filter.join(',')}`, ...filenames]);
  105. }
  106. }, {
  107. key: 'python',
  108. roots: ['script'],
  109. test: filename => filename.endsWith('.py'),
  110. run: (opts, filenames) => {
  111. const rcfile = path.join(DEPOT_TOOLS, 'pylintrc');
  112. const args = ['--rcfile=' + rcfile, ...filenames];
  113. const env = { PYTHONPATH: path.join(ELECTRON_ROOT, 'script'), ...process.env };
  114. spawnAndCheckExitCode('pylint-2.7', args, { env });
  115. }
  116. }, {
  117. key: 'javascript',
  118. roots: ['build', 'default_app', 'lib', 'npm', 'script', 'spec'],
  119. ignoreRoots: ['spec/node_modules'],
  120. test: filename => filename.endsWith('.js') || filename.endsWith('.ts'),
  121. run: async (opts, filenames) => {
  122. const eslint = new ESLint({
  123. // Do not use the lint cache on CI builds
  124. cache: !process.env.CI,
  125. cacheLocation: `node_modules/.eslintcache.${crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex')}`,
  126. extensions: ['.js', '.ts'],
  127. fix: opts.fix
  128. });
  129. const formatter = await eslint.loadFormatter();
  130. let successCount = 0;
  131. const results = await eslint.lintFiles(filenames);
  132. for (const result of results) {
  133. successCount += result.errorCount === 0 ? 1 : 0;
  134. if (opts.verbose && result.errorCount === 0 && result.warningCount === 0) {
  135. console.log(`${result.filePath}: no errors or warnings`);
  136. }
  137. }
  138. console.log(formatter.format(results));
  139. if (opts.fix) {
  140. await ESLint.outputFixes(results);
  141. }
  142. if (successCount !== filenames.length) {
  143. console.error('Linting had errors');
  144. process.exit(1);
  145. }
  146. }
  147. }, {
  148. key: 'gn',
  149. roots: ['.'],
  150. test: filename => filename.endsWith('.gn') || filename.endsWith('.gni'),
  151. run: (opts, filenames) => {
  152. const allOk = filenames.map(filename => {
  153. const env = {
  154. CHROMIUM_BUILDTOOLS_PATH: path.resolve(ELECTRON_ROOT, '..', 'buildtools'),
  155. DEPOT_TOOLS_WIN_TOOLCHAIN: '0',
  156. ...process.env
  157. };
  158. // Users may not have depot_tools in PATH.
  159. env.PATH = `${env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
  160. const args = ['format', filename];
  161. if (!opts.fix) args.push('--dry-run');
  162. const result = childProcess.spawnSync('gn', args, { env, stdio: 'inherit', shell: true });
  163. if (result.status === 0) {
  164. return true;
  165. } else if (result.status === 2) {
  166. console.log(`GN format errors in "${filename}". Run 'gn format "${filename}"' or rerun with --fix to fix them.`);
  167. return false;
  168. } else {
  169. console.log(`Error running 'gn format --dry-run "${filename}"': exit code ${result.status}`);
  170. return false;
  171. }
  172. }).every(x => x);
  173. if (!allOk) {
  174. process.exit(1);
  175. }
  176. }
  177. }, {
  178. key: 'patches',
  179. roots: ['patches'],
  180. test: filename => filename.endsWith('.patch'),
  181. run: (opts, filenames) => {
  182. const patchesDir = path.resolve(__dirname, '../patches');
  183. const patchesConfig = path.resolve(patchesDir, 'config.json');
  184. // If the config does not exist, that's a problem
  185. if (!fs.existsSync(patchesConfig)) {
  186. console.error(`Patches config file: "${patchesConfig}" does not exist`);
  187. process.exit(1);
  188. }
  189. const config = JSON.parse(fs.readFileSync(patchesConfig, 'utf8'));
  190. for (const key of Object.keys(config)) {
  191. // The directory the config points to should exist
  192. const targetPatchesDir = path.resolve(__dirname, '../../..', key);
  193. if (!fs.existsSync(targetPatchesDir)) {
  194. console.error(`target patch directory: "${targetPatchesDir}" does not exist`);
  195. process.exit(1);
  196. }
  197. // We need a .patches file
  198. const dotPatchesPath = path.resolve(targetPatchesDir, '.patches');
  199. if (!fs.existsSync(dotPatchesPath)) {
  200. console.error(`.patches file: "${dotPatchesPath}" does not exist`);
  201. process.exit(1);
  202. }
  203. // Read the patch list
  204. const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n');
  205. const patchFileSet = new Set(patchFileList);
  206. patchFileList.reduce((seen, file) => {
  207. if (seen.has(file)) {
  208. console.error(`'${file}' is listed in ${dotPatchesPath} more than once`);
  209. process.exit(1);
  210. }
  211. return seen.add(file);
  212. }, new Set());
  213. if (patchFileList.length !== patchFileSet.size) {
  214. console.error('Each patch file should only be in the .patches file once');
  215. process.exit(1);
  216. }
  217. for (const file of fs.readdirSync(targetPatchesDir)) {
  218. // Ignore the .patches file and READMEs
  219. if (file === '.patches' || file === 'README.md') continue;
  220. if (!patchFileSet.has(file)) {
  221. console.error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`);
  222. process.exit(1);
  223. }
  224. patchFileSet.delete(file);
  225. }
  226. // If anything is left in this set, it means it did not exist on disk
  227. if (patchFileSet.size > 0) {
  228. 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)}`);
  229. process.exit(1);
  230. }
  231. }
  232. const allOk = filenames.length > 0 && filenames.map(f => {
  233. const patchText = fs.readFileSync(f, 'utf8');
  234. const subjectAndDescription = /Subject: (.*?)\n\n([\s\S]*?)\s*(?=diff)/ms.exec(patchText);
  235. if (!subjectAndDescription[2]) {
  236. 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.`);
  237. return false;
  238. }
  239. const trailingWhitespaceLines = patchText.split(/\r?\n/).map((line, index) => [line, index]).filter(([line]) => line.startsWith('+') && /\s+$/.test(line)).map(([, lineNumber]) => lineNumber + 1);
  240. if (trailingWhitespaceLines.length > 0) {
  241. console.warn(`Patch file '${f}' has trailing whitespace on some lines (${trailingWhitespaceLines.join(',')}).`);
  242. return false;
  243. }
  244. return true;
  245. }).every(x => x);
  246. if (!allOk) {
  247. process.exit(1);
  248. }
  249. }
  250. }];
  251. function parseCommandLine () {
  252. let help;
  253. const opts = minimist(process.argv.slice(2), {
  254. boolean: ['c++', 'objc', 'javascript', 'python', 'gn', 'patches', 'help', 'changed', 'fix', 'verbose', 'only'],
  255. alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
  256. unknown: () => { help = true; }
  257. });
  258. if (help || opts.help) {
  259. console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]');
  260. process.exit(0);
  261. }
  262. return opts;
  263. }
  264. async function findChangedFiles (top) {
  265. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
  266. if (result.exitCode !== 0) {
  267. console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
  268. process.exit(1);
  269. }
  270. const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
  271. const absolutePaths = relativePaths.map(x => path.join(top, x));
  272. return new Set(absolutePaths);
  273. }
  274. async function findFiles (args, linter) {
  275. let filenames = [];
  276. let includelist = null;
  277. // build the includelist
  278. if (args.changed) {
  279. includelist = await findChangedFiles(ELECTRON_ROOT);
  280. if (!includelist.size) {
  281. return [];
  282. }
  283. } else if (args.only) {
  284. includelist = new Set(args._.map(p => path.resolve(p)));
  285. }
  286. // accumulate the raw list of files
  287. for (const root of linter.roots) {
  288. const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
  289. filenames.push(...files);
  290. }
  291. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  292. const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
  293. if (!fs.existsSync(ignorePath)) continue;
  294. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
  295. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
  296. }
  297. // remove ignored files
  298. filenames = filenames.filter(x => !IGNORELIST.has(x));
  299. // if a includelist exists, remove anything not in it
  300. if (includelist) {
  301. filenames = filenames.filter(x => includelist.has(x));
  302. }
  303. // it's important that filenames be relative otherwise clang-format will
  304. // produce patches with absolute paths in them, which `git apply` will refuse
  305. // to apply.
  306. return filenames.map(x => path.relative(ELECTRON_ROOT, x));
  307. }
  308. async function main () {
  309. const opts = parseCommandLine();
  310. // no mode specified? run 'em all
  311. if (!opts['c++'] && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches) {
  312. opts['c++'] = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = true;
  313. }
  314. const linters = LINTERS.filter(x => opts[x.key]);
  315. for (const linter of linters) {
  316. const filenames = await findFiles(opts, linter);
  317. if (filenames.length) {
  318. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
  319. await linter.run(opts, filenames);
  320. }
  321. }
  322. }
  323. if (require.main === module) {
  324. main().catch((error) => {
  325. console.error(error);
  326. process.exit(1);
  327. });
  328. }