lint.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #!/usr/bin/env node
  2. const crypto = require('crypto');
  3. const { GitProcess } = require('dugite');
  4. const childProcess = require('child_process');
  5. const { ESLint } = require('eslint');
  6. const fs = require('fs');
  7. const minimist = require('minimist');
  8. const path = require('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. ['spec', 'ts-smoke', 'electron', 'main.ts'],
  22. ['spec', 'ts-smoke', 'electron', 'renderer.ts'],
  23. ['spec', 'ts-smoke', 'runner.js']
  24. ].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
  25. const IS_WINDOWS = process.platform === 'win32';
  26. const CPPLINT_FILTERS = [
  27. // from presubmit_canned_checks.py OFF_BY_DEFAULT_LINT_FILTERS
  28. '-build/include',
  29. '-build/include_order',
  30. '-build/namespaces',
  31. '-readability/casting',
  32. '-runtime/int',
  33. '-whitespace/braces',
  34. // from presubmit_canned_checks.py OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS
  35. '-build/c++11',
  36. '-build/header_guard',
  37. '-readability/todo',
  38. '-runtime/references',
  39. '-whitespace/braces',
  40. '-whitespace/comma',
  41. '-whitespace/end_of_line',
  42. '-whitespace/forcolon',
  43. '-whitespace/indent',
  44. '-whitespace/line_length',
  45. '-whitespace/newline',
  46. '-whitespace/operators',
  47. '-whitespace/parens',
  48. '-whitespace/semicolon',
  49. '-whitespace/tab'
  50. ];
  51. function spawnAndCheckExitCode (cmd, args, opts) {
  52. opts = { stdio: 'inherit', ...opts };
  53. const { error, status, signal } = childProcess.spawnSync(cmd, args, opts);
  54. if (error) {
  55. // the subprocess failed or timed out
  56. console.error(error);
  57. process.exit(1);
  58. }
  59. if (status === null) {
  60. // the subprocess terminated due to a signal
  61. console.error(signal);
  62. process.exit(1);
  63. }
  64. if (status !== 0) {
  65. // `status` is an exit code
  66. process.exit(status);
  67. }
  68. }
  69. function cpplint (args) {
  70. args.unshift(`--root=${SOURCE_ROOT}`);
  71. const result = childProcess.spawnSync(IS_WINDOWS ? 'cpplint.bat' : 'cpplint.py', args, { encoding: 'utf8', shell: true });
  72. // cpplint.py writes EVERYTHING to stderr, including status messages
  73. if (result.stderr) {
  74. for (const line of result.stderr.split(/[\r\n]+/)) {
  75. if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
  76. console.warn(line);
  77. }
  78. }
  79. }
  80. if (result.status !== 0) {
  81. if (result.error) console.error(result.error);
  82. process.exit(result.status || 1);
  83. }
  84. }
  85. function isObjCHeader (filename) {
  86. return /\/(mac|cocoa)\//.test(filename);
  87. }
  88. const LINTERS = [{
  89. key: 'c++',
  90. roots: ['shell'],
  91. test: filename => filename.endsWith('.cc') || (filename.endsWith('.h') && !isObjCHeader(filename)),
  92. run: (opts, filenames) => {
  93. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  94. for (const chunk of chunkFilenames(filenames)) {
  95. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', ...clangFormatFlags, ...chunk]);
  96. cpplint([`--filter=${CPPLINT_FILTERS.join(',')}`, ...chunk]);
  97. }
  98. }
  99. }, {
  100. key: 'objc',
  101. roots: ['shell'],
  102. test: filename => filename.endsWith('.mm') || (filename.endsWith('.h') && isObjCHeader(filename)),
  103. run: (opts, filenames) => {
  104. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  105. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', ...clangFormatFlags, ...filenames]);
  106. const filter = [...CPPLINT_FILTERS, '-readability/braces'];
  107. cpplint(['--extensions=mm,h', `--filter=${filter.join(',')}`, ...filenames]);
  108. }
  109. }, {
  110. key: 'python',
  111. roots: ['script'],
  112. test: filename => filename.endsWith('.py'),
  113. run: (opts, filenames) => {
  114. const rcfile = path.join(DEPOT_TOOLS, 'pylintrc');
  115. const args = ['--rcfile=' + rcfile, ...filenames];
  116. const env = { PYTHONPATH: path.join(ELECTRON_ROOT, 'script'), ...process.env };
  117. spawnAndCheckExitCode('pylint-2.7', args, { env });
  118. }
  119. }, {
  120. key: 'javascript',
  121. roots: ['build', 'default_app', 'lib', 'npm', 'script', 'spec'],
  122. ignoreRoots: ['spec/node_modules'],
  123. test: filename => filename.endsWith('.js') || filename.endsWith('.ts'),
  124. run: async (opts, filenames) => {
  125. const eslint = new ESLint({
  126. // Do not use the lint cache on CI builds
  127. cache: !process.env.CI,
  128. cacheLocation: `node_modules/.eslintcache.${crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex')}`,
  129. extensions: ['.js', '.ts'],
  130. fix: opts.fix
  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. function parseCommandLine () {
  255. let help;
  256. const opts = minimist(process.argv.slice(2), {
  257. boolean: ['c++', 'objc', 'javascript', 'python', 'gn', 'patches', 'help', 'changed', 'fix', 'verbose', 'only'],
  258. alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
  259. unknown: arg => { help = true; }
  260. });
  261. if (help || opts.help) {
  262. console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]');
  263. process.exit(0);
  264. }
  265. return opts;
  266. }
  267. async function findChangedFiles (top) {
  268. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
  269. if (result.exitCode !== 0) {
  270. console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
  271. process.exit(1);
  272. }
  273. const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
  274. const absolutePaths = relativePaths.map(x => path.join(top, x));
  275. return new Set(absolutePaths);
  276. }
  277. async function findFiles (args, linter) {
  278. let filenames = [];
  279. let includelist = null;
  280. // build the includelist
  281. if (args.changed) {
  282. includelist = await findChangedFiles(ELECTRON_ROOT);
  283. if (!includelist.size) {
  284. return [];
  285. }
  286. } else if (args.only) {
  287. includelist = new Set(args._.map(p => path.resolve(p)));
  288. }
  289. // accumulate the raw list of files
  290. for (const root of linter.roots) {
  291. const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
  292. filenames.push(...files);
  293. }
  294. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  295. const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
  296. if (!fs.existsSync(ignorePath)) continue;
  297. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
  298. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
  299. }
  300. // remove ignored files
  301. filenames = filenames.filter(x => !IGNORELIST.has(x));
  302. // if a includelist exists, remove anything not in it
  303. if (includelist) {
  304. filenames = filenames.filter(x => includelist.has(x));
  305. }
  306. // it's important that filenames be relative otherwise clang-format will
  307. // produce patches with absolute paths in them, which `git apply` will refuse
  308. // to apply.
  309. return filenames.map(x => path.relative(ELECTRON_ROOT, x));
  310. }
  311. async function main () {
  312. const opts = parseCommandLine();
  313. // no mode specified? run 'em all
  314. if (!opts['c++'] && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches) {
  315. opts['c++'] = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = true;
  316. }
  317. const linters = LINTERS.filter(x => opts[x.key]);
  318. for (const linter of linters) {
  319. const filenames = await findFiles(opts, linter);
  320. if (filenames.length) {
  321. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
  322. await linter.run(opts, filenames);
  323. }
  324. }
  325. }
  326. if (process.mainModule === module) {
  327. main().catch((error) => {
  328. console.error(error);
  329. process.exit(1);
  330. });
  331. }