lint.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 { getCodeBlocks } = require('@electron/lint-roller/dist/lib/markdown');
  10. const { chunkFilenames, findMatchingFiles } = require('./lib/utils');
  11. const ELECTRON_ROOT = path.normalize(path.dirname(__dirname));
  12. const SOURCE_ROOT = path.resolve(ELECTRON_ROOT, '..');
  13. const DEPOT_TOOLS = path.resolve(SOURCE_ROOT, 'third_party', 'depot_tools');
  14. // Augment the PATH for this script so that we can find executables
  15. // in the depot_tools folder even if folks do not have an instance of
  16. // DEPOT_TOOLS in their path already
  17. process.env.PATH = `${process.env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
  18. const IGNORELIST = new Set([
  19. ['shell', 'browser', 'resources', 'win', 'resource.h'],
  20. ['shell', 'common', 'node_includes.h'],
  21. ['spec', 'fixtures', 'pages', 'jquery-3.6.0.min.js']
  22. ].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
  23. const IS_WINDOWS = process.platform === 'win32';
  24. const CPPLINT_FILTERS = [
  25. // from presubmit_canned_checks.py OFF_BY_DEFAULT_LINT_FILTERS
  26. '-build/include',
  27. '-build/include_order',
  28. '-build/namespaces',
  29. '-readability/casting',
  30. '-runtime/int',
  31. '-whitespace/braces',
  32. // from presubmit_canned_checks.py OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS
  33. '-build/c++11',
  34. '-build/header_guard',
  35. '-readability/todo',
  36. '-runtime/references',
  37. '-whitespace/braces',
  38. '-whitespace/comma',
  39. '-whitespace/end_of_line',
  40. '-whitespace/forcolon',
  41. '-whitespace/indent',
  42. '-whitespace/line_length',
  43. '-whitespace/newline',
  44. '-whitespace/operators',
  45. '-whitespace/parens',
  46. '-whitespace/semicolon',
  47. '-whitespace/tab'
  48. ];
  49. function spawnAndCheckExitCode (cmd, args, opts) {
  50. opts = { stdio: 'inherit', ...opts };
  51. const { error, status, signal } = childProcess.spawnSync(cmd, args, opts);
  52. if (error) {
  53. // the subprocess failed or timed out
  54. console.error(error);
  55. process.exit(1);
  56. }
  57. if (status === null) {
  58. // the subprocess terminated due to a signal
  59. console.error(signal);
  60. process.exit(1);
  61. }
  62. if (status !== 0) {
  63. // `status` is an exit code
  64. process.exit(status);
  65. }
  66. }
  67. function cpplint (args) {
  68. args.unshift(`--root=${SOURCE_ROOT}`);
  69. const result = childProcess.spawnSync(IS_WINDOWS ? 'cpplint.bat' : 'cpplint.py', args, { encoding: 'utf8', shell: true });
  70. // cpplint.py writes EVERYTHING to stderr, including status messages
  71. if (result.stderr) {
  72. for (const line of result.stderr.split(/[\r\n]+/)) {
  73. if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
  74. console.warn(line);
  75. }
  76. }
  77. }
  78. if (result.status !== 0) {
  79. if (result.error) console.error(result.error);
  80. process.exit(result.status || 1);
  81. }
  82. }
  83. function isObjCHeader (filename) {
  84. return /\/(mac|cocoa)\//.test(filename);
  85. }
  86. const LINTERS = [{
  87. key: 'cpp',
  88. roots: ['shell'],
  89. test: filename => filename.endsWith('.cc') || (filename.endsWith('.h') && !isObjCHeader(filename)),
  90. run: (opts, filenames) => {
  91. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  92. for (const chunk of chunkFilenames(filenames)) {
  93. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', ...clangFormatFlags, ...chunk]);
  94. cpplint([`--filter=${CPPLINT_FILTERS.join(',')}`, ...chunk]);
  95. }
  96. }
  97. }, {
  98. key: 'objc',
  99. roots: ['shell'],
  100. test: filename => filename.endsWith('.mm') || (filename.endsWith('.h') && isObjCHeader(filename)),
  101. run: (opts, filenames) => {
  102. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  103. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', ...clangFormatFlags, ...filenames]);
  104. const filter = [...CPPLINT_FILTERS, '-readability/braces'];
  105. cpplint(['--extensions=mm,h', `--filter=${filter.join(',')}`, ...filenames]);
  106. }
  107. }, {
  108. key: 'python',
  109. roots: ['script'],
  110. test: filename => filename.endsWith('.py'),
  111. run: (opts, filenames) => {
  112. const rcfile = path.join(DEPOT_TOOLS, 'pylintrc');
  113. const args = ['--rcfile=' + rcfile, ...filenames];
  114. const env = { PYTHONPATH: path.join(ELECTRON_ROOT, 'script'), ...process.env };
  115. spawnAndCheckExitCode('pylint-2.7', args, { env });
  116. }
  117. }, {
  118. key: 'javascript',
  119. roots: ['build', 'default_app', 'lib', 'npm', 'script', 'spec'],
  120. ignoreRoots: ['spec/node_modules'],
  121. test: filename => filename.endsWith('.js') || filename.endsWith('.ts'),
  122. run: async (opts, filenames) => {
  123. const eslint = new ESLint({
  124. // Do not use the lint cache on CI builds
  125. cache: !process.env.CI,
  126. cacheLocation: `node_modules/.eslintcache.${crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex')}`,
  127. extensions: ['.js', '.ts'],
  128. fix: opts.fix,
  129. overrideConfigFile: path.join(ELECTRON_ROOT, '.eslintrc.json'),
  130. resolvePluginsRelativeTo: ELECTRON_ROOT
  131. });
  132. const formatter = await eslint.loadFormatter();
  133. let successCount = 0;
  134. const results = await eslint.lintFiles(filenames);
  135. for (const result of results) {
  136. successCount += result.errorCount === 0 ? 1 : 0;
  137. if (opts.verbose && result.errorCount === 0 && result.warningCount === 0) {
  138. console.log(`${result.filePath}: no errors or warnings`);
  139. }
  140. }
  141. console.log(formatter.format(results));
  142. if (opts.fix) {
  143. await ESLint.outputFixes(results);
  144. }
  145. if (successCount !== filenames.length) {
  146. console.error('Linting had errors');
  147. process.exit(1);
  148. }
  149. }
  150. }, {
  151. key: 'gn',
  152. roots: ['.'],
  153. test: filename => filename.endsWith('.gn') || filename.endsWith('.gni'),
  154. run: (opts, filenames) => {
  155. const allOk = filenames.map(filename => {
  156. const env = {
  157. CHROMIUM_BUILDTOOLS_PATH: path.resolve(ELECTRON_ROOT, '..', 'buildtools'),
  158. DEPOT_TOOLS_WIN_TOOLCHAIN: '0',
  159. ...process.env
  160. };
  161. // Users may not have depot_tools in PATH.
  162. env.PATH = `${env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
  163. const args = ['format', filename];
  164. if (!opts.fix) args.push('--dry-run');
  165. const result = childProcess.spawnSync('gn', args, { env, stdio: 'inherit', shell: true });
  166. if (result.status === 0) {
  167. return true;
  168. } else if (result.status === 2) {
  169. console.log(`GN format errors in "${filename}". Run 'gn format "${filename}"' or rerun with --fix to fix them.`);
  170. return false;
  171. } else {
  172. console.log(`Error running 'gn format --dry-run "${filename}"': exit code ${result.status}`);
  173. return false;
  174. }
  175. }).every(x => x);
  176. if (!allOk) {
  177. process.exit(1);
  178. }
  179. }
  180. }, {
  181. key: 'patches',
  182. roots: ['patches'],
  183. test: filename => filename.endsWith('.patch'),
  184. run: (opts, filenames) => {
  185. const patchesDir = path.resolve(__dirname, '../patches');
  186. const patchesConfig = path.resolve(patchesDir, 'config.json');
  187. // If the config does not exist, that's a problem
  188. if (!fs.existsSync(patchesConfig)) {
  189. console.error(`Patches config file: "${patchesConfig}" does not exist`);
  190. process.exit(1);
  191. }
  192. for (const target of JSON.parse(fs.readFileSync(patchesConfig, 'utf8'))) {
  193. // The directory the config points to should exist
  194. const targetPatchesDir = path.resolve(__dirname, '../../..', target.patch_dir);
  195. if (!fs.existsSync(targetPatchesDir)) {
  196. console.error(`target patch directory: "${targetPatchesDir}" does not exist`);
  197. process.exit(1);
  198. }
  199. // We need a .patches file
  200. const dotPatchesPath = path.resolve(targetPatchesDir, '.patches');
  201. if (!fs.existsSync(dotPatchesPath)) {
  202. console.error(`.patches file: "${dotPatchesPath}" does not exist`);
  203. process.exit(1);
  204. }
  205. // Read the patch list
  206. const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n');
  207. const patchFileSet = new Set(patchFileList);
  208. patchFileList.reduce((seen, file) => {
  209. if (seen.has(file)) {
  210. console.error(`'${file}' is listed in ${dotPatchesPath} more than once`);
  211. process.exit(1);
  212. }
  213. return seen.add(file);
  214. }, new Set());
  215. if (patchFileList.length !== patchFileSet.size) {
  216. console.error('Each patch file should only be in the .patches file once');
  217. process.exit(1);
  218. }
  219. for (const file of fs.readdirSync(targetPatchesDir)) {
  220. // Ignore the .patches file and READMEs
  221. if (file === '.patches' || file === 'README.md') continue;
  222. if (!patchFileSet.has(file)) {
  223. console.error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`);
  224. process.exit(1);
  225. }
  226. patchFileSet.delete(file);
  227. }
  228. // If anything is left in this set, it means it did not exist on disk
  229. if (patchFileSet.size > 0) {
  230. 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)}`);
  231. process.exit(1);
  232. }
  233. }
  234. const allOk = filenames.length > 0 && filenames.map(f => {
  235. const patchText = fs.readFileSync(f, 'utf8');
  236. const subjectAndDescription = /Subject: (.*?)\n\n([\s\S]*?)\s*(?=diff)/ms.exec(patchText);
  237. if (!subjectAndDescription[2]) {
  238. 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.`);
  239. return false;
  240. }
  241. const trailingWhitespaceLines = patchText.split(/\r?\n/).map((line, index) => [line, index]).filter(([line]) => line.startsWith('+') && /\s+$/.test(line)).map(([, lineNumber]) => lineNumber + 1);
  242. if (trailingWhitespaceLines.length > 0) {
  243. console.warn(`Patch file '${f}' has trailing whitespace on some lines (${trailingWhitespaceLines.join(',')}).`);
  244. return false;
  245. }
  246. return true;
  247. }).every(x => x);
  248. if (!allOk) {
  249. process.exit(1);
  250. }
  251. }
  252. }, {
  253. key: 'md',
  254. roots: ['.'],
  255. ignoreRoots: ['node_modules', 'spec/node_modules'],
  256. test: filename => filename.endsWith('.md'),
  257. run: async (opts, filenames) => {
  258. let errors = false;
  259. // Run markdownlint on all Markdown files
  260. for (const chunk of chunkFilenames(filenames)) {
  261. spawnAndCheckExitCode('electron-markdownlint', chunk);
  262. }
  263. // Run the remaining checks only in docs
  264. const docs = filenames.filter(filename => path.dirname(filename).split(path.sep)[0] === 'docs');
  265. for (const filename of docs) {
  266. const contents = fs.readFileSync(filename, 'utf8');
  267. const codeBlocks = await getCodeBlocks(contents);
  268. for (const codeBlock of codeBlocks) {
  269. const line = codeBlock.position.start.line;
  270. if (codeBlock.lang) {
  271. // Enforce all lowercase language identifiers
  272. if (codeBlock.lang.toLowerCase() !== codeBlock.lang) {
  273. console.log(`${filename}:${line} Code block language identifiers should be all lowercase`);
  274. errors = true;
  275. }
  276. // Prefer js/ts to javascript/typescript as the language identifier
  277. if (codeBlock.lang === 'javascript') {
  278. console.log(`${filename}:${line} Use 'js' as code block language identifier instead of 'javascript'`);
  279. errors = true;
  280. }
  281. if (codeBlock.lang === 'typescript') {
  282. console.log(`${filename}:${line} Use 'typescript' as code block language identifier instead of 'ts'`);
  283. errors = true;
  284. }
  285. // Enforce latest fiddle code block syntax
  286. if (codeBlock.lang === 'javascript' && codeBlock.meta && codeBlock.meta.includes('fiddle=')) {
  287. console.log(`${filename}:${line} Use 'fiddle' as code block language identifier instead of 'javascript fiddle='`);
  288. errors = true;
  289. }
  290. // Ensure non-empty content in fiddle code blocks matches the file content
  291. if (codeBlock.lang === 'fiddle' && codeBlock.value.trim() !== '') {
  292. // This is copied and adapted from the website repo:
  293. // https://github.com/electron/website/blob/62a55ca0dd14f97339e1a361b5418d2f11c34a75/src/transformers/fiddle-embedder.ts#L89C6-L101
  294. const parseFiddleEmbedOptions = (
  295. optStrings
  296. ) => {
  297. // If there are optional parameters, parse them out to pass to the getFiddleAST method.
  298. return optStrings.reduce((opts, option) => {
  299. // Use indexOf to support bizarre combinations like `|key=Myvalue=2` (which will properly
  300. // parse to {'key': 'Myvalue=2'})
  301. const firstEqual = option.indexOf('=');
  302. const key = option.slice(0, firstEqual);
  303. const value = option.slice(firstEqual + 1);
  304. return { ...opts, [key]: value };
  305. }, {});
  306. };
  307. const [dir, ...others] = codeBlock.meta.split('|');
  308. const options = parseFiddleEmbedOptions(others);
  309. const fiddleFilename = path.join(dir, options.focus || 'main.js');
  310. try {
  311. const fiddleContent = fs.readFileSync(fiddleFilename, 'utf8').trim();
  312. if (fiddleContent !== codeBlock.value.trim()) {
  313. console.log(`${filename}:${line} Content for fiddle code block differs from content in ${fiddleFilename}`);
  314. errors = true;
  315. }
  316. } catch (err) {
  317. console.error(`${filename}:${line} Error linting fiddle code block content`);
  318. if (err.stack) {
  319. console.error(err.stack);
  320. }
  321. errors = true;
  322. }
  323. }
  324. }
  325. }
  326. }
  327. if (errors) {
  328. process.exit(1);
  329. }
  330. }
  331. }];
  332. function parseCommandLine () {
  333. let help;
  334. const langs = ['cpp', 'objc', 'javascript', 'python', 'gn', 'patches', 'markdown'];
  335. const langRoots = langs.map(lang => lang + '-roots');
  336. const langIgnoreRoots = langs.map(lang => lang + '-ignore-roots');
  337. const opts = minimist(process.argv.slice(2), {
  338. boolean: [...langs, 'help', 'changed', 'fix', 'verbose', 'only'],
  339. alias: { cpp: ['c++', 'cc', 'cxx'], javascript: ['js', 'es'], python: 'py', markdown: 'md', changed: 'c', help: 'h', verbose: 'v' },
  340. string: [...langRoots, ...langIgnoreRoots],
  341. unknown: () => { help = true; }
  342. });
  343. if (help || opts.help) {
  344. const langFlags = langs.map(lang => `[--${lang}]`).join(' ');
  345. console.log(`Usage: script/lint.js ${langFlags} [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]`);
  346. process.exit(0);
  347. }
  348. return opts;
  349. }
  350. function populateLinterWithArgs (linter, opts) {
  351. const extraRoots = opts[`${linter.key}-roots`];
  352. if (extraRoots) {
  353. linter.roots.push(...extraRoots.split(','));
  354. }
  355. const extraIgnoreRoots = opts[`${linter.key}-ignore-roots`];
  356. if (extraIgnoreRoots) {
  357. const list = extraIgnoreRoots.split(',');
  358. if (linter.ignoreRoots) {
  359. linter.ignoreRoots.push(...list);
  360. } else {
  361. linter.ignoreRoots = list;
  362. }
  363. }
  364. }
  365. async function findChangedFiles (top) {
  366. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
  367. if (result.exitCode !== 0) {
  368. console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
  369. process.exit(1);
  370. }
  371. const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
  372. const absolutePaths = relativePaths.map(x => path.join(top, x));
  373. return new Set(absolutePaths);
  374. }
  375. async function findFiles (args, linter) {
  376. let filenames = [];
  377. let includelist = null;
  378. // build the includelist
  379. if (args.changed) {
  380. includelist = await findChangedFiles(ELECTRON_ROOT);
  381. if (!includelist.size) {
  382. return [];
  383. }
  384. } else if (args.only) {
  385. includelist = new Set(args._.map(p => path.resolve(p)));
  386. }
  387. // accumulate the raw list of files
  388. for (const root of linter.roots) {
  389. const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
  390. filenames.push(...files);
  391. }
  392. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  393. const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
  394. if (!fs.existsSync(ignorePath)) continue;
  395. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
  396. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
  397. }
  398. // remove ignored files
  399. filenames = filenames.filter(x => !IGNORELIST.has(x));
  400. // if a includelist exists, remove anything not in it
  401. if (includelist) {
  402. filenames = filenames.filter(x => includelist.has(x));
  403. }
  404. // it's important that filenames be relative otherwise clang-format will
  405. // produce patches with absolute paths in them, which `git apply` will refuse
  406. // to apply.
  407. return filenames.map(x => path.relative(ELECTRON_ROOT, x));
  408. }
  409. async function main () {
  410. const opts = parseCommandLine();
  411. // no mode specified? run 'em all
  412. if (!opts.cpp && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches && !opts.markdown) {
  413. opts.cpp = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = opts.markdown = true;
  414. }
  415. const linters = LINTERS.filter(x => opts[x.key]);
  416. for (const linter of linters) {
  417. populateLinterWithArgs(linter, opts);
  418. const filenames = await findFiles(opts, linter);
  419. if (filenames.length) {
  420. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
  421. await linter.run(opts, filenames);
  422. }
  423. }
  424. }
  425. if (require.main === module) {
  426. main().catch((error) => {
  427. console.error(error);
  428. process.exit(1);
  429. });
  430. }