lint.js 18 KB

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