lint.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. const config = JSON.parse(fs.readFileSync(patchesConfig, 'utf8'));
  193. for (const key of Object.keys(config)) {
  194. // The directory the config points to should exist
  195. const targetPatchesDir = path.resolve(__dirname, '../../..', key);
  196. if (!fs.existsSync(targetPatchesDir)) {
  197. console.error(`target patch directory: "${targetPatchesDir}" does not exist`);
  198. process.exit(1);
  199. }
  200. // We need a .patches file
  201. const dotPatchesPath = path.resolve(targetPatchesDir, '.patches');
  202. if (!fs.existsSync(dotPatchesPath)) {
  203. console.error(`.patches file: "${dotPatchesPath}" does not exist`);
  204. process.exit(1);
  205. }
  206. // Read the patch list
  207. const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n');
  208. const patchFileSet = new Set(patchFileList);
  209. patchFileList.reduce((seen, file) => {
  210. if (seen.has(file)) {
  211. console.error(`'${file}' is listed in ${dotPatchesPath} more than once`);
  212. process.exit(1);
  213. }
  214. return seen.add(file);
  215. }, new Set());
  216. if (patchFileList.length !== patchFileSet.size) {
  217. console.error('Each patch file should only be in the .patches file once');
  218. process.exit(1);
  219. }
  220. for (const file of fs.readdirSync(targetPatchesDir)) {
  221. // Ignore the .patches file and READMEs
  222. if (file === '.patches' || file === 'README.md') continue;
  223. if (!patchFileSet.has(file)) {
  224. console.error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`);
  225. process.exit(1);
  226. }
  227. patchFileSet.delete(file);
  228. }
  229. // If anything is left in this set, it means it did not exist on disk
  230. if (patchFileSet.size > 0) {
  231. 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)}`);
  232. process.exit(1);
  233. }
  234. }
  235. const allOk = filenames.length > 0 && filenames.map(f => {
  236. const patchText = fs.readFileSync(f, 'utf8');
  237. const subjectAndDescription = /Subject: (.*?)\n\n([\s\S]*?)\s*(?=diff)/ms.exec(patchText);
  238. if (!subjectAndDescription[2]) {
  239. 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.`);
  240. return false;
  241. }
  242. const trailingWhitespaceLines = patchText.split(/\r?\n/).map((line, index) => [line, index]).filter(([line]) => line.startsWith('+') && /\s+$/.test(line)).map(([, lineNumber]) => lineNumber + 1);
  243. if (trailingWhitespaceLines.length > 0) {
  244. console.warn(`Patch file '${f}' has trailing whitespace on some lines (${trailingWhitespaceLines.join(',')}).`);
  245. return false;
  246. }
  247. return true;
  248. }).every(x => x);
  249. if (!allOk) {
  250. process.exit(1);
  251. }
  252. }
  253. }, {
  254. key: 'md',
  255. roots: ['.'],
  256. ignoreRoots: ['node_modules', 'spec/node_modules'],
  257. test: filename => filename.endsWith('.md'),
  258. run: async (opts, filenames) => {
  259. let errors = false;
  260. // Run markdownlint on all Markdown files
  261. for (const chunk of chunkFilenames(filenames)) {
  262. spawnAndCheckExitCode('electron-markdownlint', chunk);
  263. }
  264. // Run the remaining checks only in docs
  265. const docs = filenames.filter(filename => path.dirname(filename).split(path.sep)[0] === 'docs');
  266. for (const filename of docs) {
  267. const contents = fs.readFileSync(filename, 'utf8');
  268. const codeBlocks = await getCodeBlocks(contents);
  269. for (const codeBlock of codeBlocks) {
  270. const line = codeBlock.position.start.line;
  271. if (codeBlock.lang) {
  272. // Enforce all lowercase language identifiers
  273. if (codeBlock.lang.toLowerCase() !== codeBlock.lang) {
  274. console.log(`${filename}:${line} Code block language identifiers should be all lowercase`);
  275. errors = true;
  276. }
  277. // Prefer js/ts to javascript/typescript as the language identifier
  278. if (codeBlock.lang === 'javascript') {
  279. console.log(`${filename}:${line} Use 'js' as code block language identifier instead of 'javascript'`);
  280. errors = true;
  281. }
  282. if (codeBlock.lang === 'typescript') {
  283. console.log(`${filename}:${line} Use 'typescript' as code block language identifier instead of 'ts'`);
  284. errors = true;
  285. }
  286. // Enforce latest fiddle code block syntax
  287. if (codeBlock.lang === 'javascript' && codeBlock.meta && codeBlock.meta.includes('fiddle=')) {
  288. console.log(`${filename}:${line} Use 'fiddle' as code block language identifier instead of 'javascript fiddle='`);
  289. errors = true;
  290. }
  291. // Ensure non-empty content in fiddle code blocks matches the file content
  292. if (codeBlock.lang === 'fiddle' && codeBlock.value.trim() !== '') {
  293. // This is copied and adapted from the website repo:
  294. // https://github.com/electron/website/blob/62a55ca0dd14f97339e1a361b5418d2f11c34a75/src/transformers/fiddle-embedder.ts#L89C6-L101
  295. const parseFiddleEmbedOptions = (
  296. optStrings
  297. ) => {
  298. // If there are optional parameters, parse them out to pass to the getFiddleAST method.
  299. return optStrings.reduce((opts, option) => {
  300. // Use indexOf to support bizarre combinations like `|key=Myvalue=2` (which will properly
  301. // parse to {'key': 'Myvalue=2'})
  302. const firstEqual = option.indexOf('=');
  303. const key = option.slice(0, firstEqual);
  304. const value = option.slice(firstEqual + 1);
  305. return { ...opts, [key]: value };
  306. }, {});
  307. };
  308. const [dir, ...others] = codeBlock.meta.split('|');
  309. const options = parseFiddleEmbedOptions(others);
  310. const fiddleFilename = path.join(dir, options.focus || 'main.js');
  311. try {
  312. const fiddleContent = fs.readFileSync(fiddleFilename, 'utf8').trim();
  313. if (fiddleContent !== codeBlock.value.trim()) {
  314. console.log(`${filename}:${line} Content for fiddle code block differs from content in ${fiddleFilename}`);
  315. errors = true;
  316. }
  317. } catch (err) {
  318. console.error(`${filename}:${line} Error linting fiddle code block content`);
  319. if (err.stack) {
  320. console.error(err.stack);
  321. }
  322. errors = true;
  323. }
  324. }
  325. }
  326. }
  327. }
  328. if (errors) {
  329. process.exit(1);
  330. }
  331. }
  332. }];
  333. function parseCommandLine () {
  334. let help;
  335. const langs = ['cpp', 'objc', 'javascript', 'python', 'gn', 'patches', 'markdown'];
  336. const langRoots = langs.map(lang => lang + '-roots');
  337. const langIgnoreRoots = langs.map(lang => lang + '-ignore-roots');
  338. const opts = minimist(process.argv.slice(2), {
  339. boolean: [...langs, 'help', 'changed', 'fix', 'verbose', 'only'],
  340. alias: { cpp: ['c++', 'cc', 'cxx'], javascript: ['js', 'es'], python: 'py', markdown: 'md', changed: 'c', help: 'h', verbose: 'v' },
  341. string: [...langRoots, ...langIgnoreRoots],
  342. unknown: () => { help = true; }
  343. });
  344. if (help || opts.help) {
  345. const langFlags = langs.map(lang => `[--${lang}]`).join(' ');
  346. console.log(`Usage: script/lint.js ${langFlags} [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]`);
  347. process.exit(0);
  348. }
  349. return opts;
  350. }
  351. function populateLinterWithArgs (linter, opts) {
  352. const extraRoots = opts[`${linter.key}-roots`];
  353. if (extraRoots) {
  354. linter.roots.push(...extraRoots.split(','));
  355. }
  356. const extraIgnoreRoots = opts[`${linter.key}-ignore-roots`];
  357. if (extraIgnoreRoots) {
  358. const list = extraIgnoreRoots.split(',');
  359. if (linter.ignoreRoots) {
  360. linter.ignoreRoots.push(...list);
  361. } else {
  362. linter.ignoreRoots = list;
  363. }
  364. }
  365. }
  366. async function findChangedFiles (top) {
  367. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
  368. if (result.exitCode !== 0) {
  369. console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
  370. process.exit(1);
  371. }
  372. const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
  373. const absolutePaths = relativePaths.map(x => path.join(top, x));
  374. return new Set(absolutePaths);
  375. }
  376. async function findFiles (args, linter) {
  377. let filenames = [];
  378. let includelist = null;
  379. // build the includelist
  380. if (args.changed) {
  381. includelist = await findChangedFiles(ELECTRON_ROOT);
  382. if (!includelist.size) {
  383. return [];
  384. }
  385. } else if (args.only) {
  386. includelist = new Set(args._.map(p => path.resolve(p)));
  387. }
  388. // accumulate the raw list of files
  389. for (const root of linter.roots) {
  390. const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
  391. filenames.push(...files);
  392. }
  393. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  394. const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
  395. if (!fs.existsSync(ignorePath)) continue;
  396. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
  397. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
  398. }
  399. // remove ignored files
  400. filenames = filenames.filter(x => !IGNORELIST.has(x));
  401. // if a includelist exists, remove anything not in it
  402. if (includelist) {
  403. filenames = filenames.filter(x => includelist.has(x));
  404. }
  405. // it's important that filenames be relative otherwise clang-format will
  406. // produce patches with absolute paths in them, which `git apply` will refuse
  407. // to apply.
  408. return filenames.map(x => path.relative(ELECTRON_ROOT, x));
  409. }
  410. async function main () {
  411. const opts = parseCommandLine();
  412. // no mode specified? run 'em all
  413. if (!opts.cpp && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches && !opts.markdown) {
  414. opts.cpp = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = opts.markdown = true;
  415. }
  416. const linters = LINTERS.filter(x => opts[x.key]);
  417. for (const linter of linters) {
  418. populateLinterWithArgs(linter, opts);
  419. const filenames = await findFiles(opts, linter);
  420. if (filenames.length) {
  421. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
  422. await linter.run(opts, filenames);
  423. }
  424. }
  425. }
  426. if (require.main === module) {
  427. main().catch((error) => {
  428. console.error(error);
  429. process.exit(1);
  430. });
  431. }