lint.js 18 KB

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