lint.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 klaw = require('klaw');
  8. const minimist = require('minimist');
  9. const path = require('path');
  10. const { chunkFilenames } = 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. ['spec', 'ts-smoke', 'electron', 'main.ts'],
  23. ['spec', 'ts-smoke', 'electron', 'renderer.ts'],
  24. ['spec', 'ts-smoke', 'runner.js']
  25. ].map(tokens => path.join(ELECTRON_ROOT, ...tokens)));
  26. const IS_WINDOWS = process.platform === 'win32';
  27. function spawnAndCheckExitCode (cmd, args, opts) {
  28. opts = { stdio: 'inherit', ...opts };
  29. const { error, status, signal } = childProcess.spawnSync(cmd, args, opts);
  30. if (error) {
  31. // the subprocess failed or timed out
  32. console.error(error);
  33. process.exit(1);
  34. }
  35. if (status === null) {
  36. // the subprocess terminated due to a signal
  37. console.error(signal);
  38. process.exit(1);
  39. }
  40. if (status !== 0) {
  41. // `status` is an exit code
  42. process.exit(status);
  43. }
  44. }
  45. function cpplint (args) {
  46. args.unshift(`--root=${SOURCE_ROOT}`);
  47. const result = childProcess.spawnSync(IS_WINDOWS ? 'cpplint.bat' : 'cpplint.py', args, { encoding: 'utf8', shell: true });
  48. // cpplint.py writes EVERYTHING to stderr, including status messages
  49. if (result.stderr) {
  50. for (const line of result.stderr.split(/[\r\n]+/)) {
  51. if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
  52. console.warn(line);
  53. }
  54. }
  55. }
  56. if (result.status !== 0) {
  57. if (result.error) console.error(result.error);
  58. process.exit(result.status || 1);
  59. }
  60. }
  61. function isObjCHeader (filename) {
  62. return /\/(mac|cocoa)\//.test(filename);
  63. }
  64. const LINTERS = [{
  65. key: 'c++',
  66. roots: ['shell'],
  67. test: filename => filename.endsWith('.cc') || (filename.endsWith('.h') && !isObjCHeader(filename)),
  68. run: (opts, filenames) => {
  69. const clangFormatFlags = opts.fix ? ['--fix'] : [];
  70. for (const chunk of chunkFilenames(filenames)) {
  71. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', ...clangFormatFlags, ...chunk]);
  72. cpplint(chunk);
  73. }
  74. }
  75. }, {
  76. key: 'objc',
  77. roots: ['shell'],
  78. test: filename => filename.endsWith('.mm') || (filename.endsWith('.h') && isObjCHeader(filename)),
  79. run: (opts, filenames) => {
  80. if (opts.fix) {
  81. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', '--fix', ...filenames]);
  82. } else {
  83. spawnAndCheckExitCode('python3', ['script/run-clang-format.py', '-r', ...filenames]);
  84. }
  85. const filter = [
  86. '-readability/braces',
  87. '-readability/casting',
  88. '-whitespace/braces',
  89. '-whitespace/indent',
  90. '-whitespace/parens'
  91. ];
  92. cpplint(['--extensions=mm,h', `--filter=${filter.join(',')}`, ...filenames]);
  93. }
  94. }, {
  95. key: 'python',
  96. roots: ['script'],
  97. test: filename => filename.endsWith('.py'),
  98. run: (opts, filenames) => {
  99. const rcfile = path.join(DEPOT_TOOLS, 'pylintrc');
  100. const args = ['--rcfile=' + rcfile, ...filenames];
  101. const env = { PYTHONPATH: path.join(ELECTRON_ROOT, 'script'), ...process.env };
  102. spawnAndCheckExitCode('pylint-2.7', args, { env });
  103. }
  104. }, {
  105. key: 'javascript',
  106. roots: ['build', 'default_app', 'lib', 'npm', 'script', 'spec'],
  107. ignoreRoots: ['spec/node_modules'],
  108. test: filename => filename.endsWith('.js') || filename.endsWith('.ts'),
  109. run: async (opts, filenames) => {
  110. const eslint = new ESLint({
  111. // Do not use the lint cache on CI builds
  112. cache: !process.env.CI,
  113. cacheLocation: `node_modules/.eslintcache.${crypto.createHash('md5').update(fs.readFileSync(__filename)).digest('hex')}`,
  114. extensions: ['.js', '.ts'],
  115. fix: opts.fix
  116. });
  117. const formatter = await eslint.loadFormatter();
  118. let successCount = 0;
  119. const results = await eslint.lintFiles(filenames);
  120. for (const result of results) {
  121. successCount += result.errorCount === 0 ? 1 : 0;
  122. if (opts.verbose && result.errorCount === 0 && result.warningCount === 0) {
  123. console.log(`${result.filePath}: no errors or warnings`);
  124. }
  125. }
  126. console.log(formatter.format(results));
  127. if (opts.fix) {
  128. await ESLint.outputFixes(results);
  129. }
  130. if (successCount !== filenames.length) {
  131. console.error('Linting had errors');
  132. process.exit(1);
  133. }
  134. }
  135. }, {
  136. key: 'gn',
  137. roots: ['.'],
  138. test: filename => filename.endsWith('.gn') || filename.endsWith('.gni'),
  139. run: (opts, filenames) => {
  140. const allOk = filenames.map(filename => {
  141. const env = {
  142. CHROMIUM_BUILDTOOLS_PATH: path.resolve(ELECTRON_ROOT, '..', 'buildtools'),
  143. DEPOT_TOOLS_WIN_TOOLCHAIN: '0',
  144. ...process.env
  145. };
  146. // Users may not have depot_tools in PATH.
  147. env.PATH = `${env.PATH}${path.delimiter}${DEPOT_TOOLS}`;
  148. const args = ['format', filename];
  149. if (!opts.fix) args.push('--dry-run');
  150. const result = childProcess.spawnSync('gn', args, { env, stdio: 'inherit', shell: true });
  151. if (result.status === 0) {
  152. return true;
  153. } else if (result.status === 2) {
  154. console.log(`GN format errors in "${filename}". Run 'gn format "${filename}"' or rerun with --fix to fix them.`);
  155. return false;
  156. } else {
  157. console.log(`Error running 'gn format --dry-run "${filename}"': exit code ${result.status}`);
  158. return false;
  159. }
  160. }).every(x => x);
  161. if (!allOk) {
  162. process.exit(1);
  163. }
  164. }
  165. }, {
  166. key: 'patches',
  167. roots: ['patches'],
  168. test: filename => filename.endsWith('.patch'),
  169. run: (opts, filenames) => {
  170. const patchesDir = path.resolve(__dirname, '../patches');
  171. const patchesConfig = path.resolve(patchesDir, 'config.json');
  172. // If the config does not exist, that's a problem
  173. if (!fs.existsSync(patchesConfig)) {
  174. process.exit(1);
  175. }
  176. const config = JSON.parse(fs.readFileSync(patchesConfig, 'utf8'));
  177. for (const key of Object.keys(config)) {
  178. // The directory the config points to should exist
  179. const targetPatchesDir = path.resolve(__dirname, '../../..', key);
  180. if (!fs.existsSync(targetPatchesDir)) throw new Error(`target patch directory: "${targetPatchesDir}" does not exist`);
  181. // We need a .patches file
  182. const dotPatchesPath = path.resolve(targetPatchesDir, '.patches');
  183. if (!fs.existsSync(dotPatchesPath)) throw new Error(`.patches file: "${dotPatchesPath}" does not exist`);
  184. // Read the patch list
  185. const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n');
  186. const patchFileSet = new Set(patchFileList);
  187. patchFileList.reduce((seen, file) => {
  188. if (seen.has(file)) {
  189. throw new Error(`'${file}' is listed in ${dotPatchesPath} more than once`);
  190. }
  191. return seen.add(file);
  192. }, new Set());
  193. if (patchFileList.length !== patchFileSet.size) throw new Error('each patch file should only be in the .patches file once');
  194. for (const file of fs.readdirSync(targetPatchesDir)) {
  195. // Ignore the .patches file and READMEs
  196. if (file === '.patches' || file === 'README.md') continue;
  197. if (!patchFileSet.has(file)) {
  198. throw new Error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`);
  199. }
  200. patchFileSet.delete(file);
  201. }
  202. // If anything is left in this set, it means it did not exist on disk
  203. if (patchFileSet.size > 0) {
  204. throw new 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)}`);
  205. }
  206. }
  207. const allOk = filenames.length > 0 && filenames.map(f => {
  208. const patchText = fs.readFileSync(f, 'utf8');
  209. const subjectAndDescription = /Subject: (.*?)\n\n([\s\S]*?)\s*(?=diff)/ms.exec(patchText);
  210. if (!subjectAndDescription[2]) {
  211. 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.`);
  212. return false;
  213. }
  214. const trailingWhitespaceLines = patchText.split(/\r?\n/).map((line, index) => [line, index]).filter(([line]) => line.startsWith('+') && /\s+$/.test(line)).map(([, lineNumber]) => lineNumber + 1);
  215. if (trailingWhitespaceLines.length > 0) {
  216. console.warn(`Patch file '${f}' has trailing whitespace on some lines (${trailingWhitespaceLines.join(',')}).`);
  217. return false;
  218. }
  219. return true;
  220. }).every(x => x);
  221. if (!allOk) {
  222. process.exit(1);
  223. }
  224. }
  225. }];
  226. function parseCommandLine () {
  227. let help;
  228. const opts = minimist(process.argv.slice(2), {
  229. boolean: ['c++', 'objc', 'javascript', 'python', 'gn', 'patches', 'help', 'changed', 'fix', 'verbose', 'only'],
  230. alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
  231. unknown: arg => { help = true; }
  232. });
  233. if (help || opts.help) {
  234. console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]');
  235. process.exit(0);
  236. }
  237. return opts;
  238. }
  239. async function findChangedFiles (top) {
  240. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top);
  241. if (result.exitCode !== 0) {
  242. console.log('Failed to find changed files', GitProcess.parseError(result.stderr));
  243. process.exit(1);
  244. }
  245. const relativePaths = result.stdout.split(/\r\n|\r|\n/g);
  246. const absolutePaths = relativePaths.map(x => path.join(top, x));
  247. return new Set(absolutePaths);
  248. }
  249. async function findMatchingFiles (top, test) {
  250. return new Promise((resolve, reject) => {
  251. const matches = [];
  252. klaw(top, {
  253. filter: f => path.basename(f) !== '.bin'
  254. })
  255. .on('end', () => resolve(matches))
  256. .on('data', item => {
  257. if (test(item.path)) {
  258. matches.push(item.path);
  259. }
  260. });
  261. });
  262. }
  263. async function findFiles (args, linter) {
  264. let filenames = [];
  265. let includelist = null;
  266. // build the includelist
  267. if (args.changed) {
  268. includelist = await findChangedFiles(ELECTRON_ROOT);
  269. if (!includelist.size) {
  270. return [];
  271. }
  272. } else if (args.only) {
  273. includelist = new Set(args._.map(p => path.resolve(p)));
  274. }
  275. // accumulate the raw list of files
  276. for (const root of linter.roots) {
  277. const files = await findMatchingFiles(path.join(ELECTRON_ROOT, root), linter.test);
  278. filenames.push(...files);
  279. }
  280. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  281. const ignorePath = path.join(ELECTRON_ROOT, ignoreRoot);
  282. if (!fs.existsSync(ignorePath)) continue;
  283. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test));
  284. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName));
  285. }
  286. // remove ignored files
  287. filenames = filenames.filter(x => !IGNORELIST.has(x));
  288. // if a includelist exists, remove anything not in it
  289. if (includelist) {
  290. filenames = filenames.filter(x => includelist.has(x));
  291. }
  292. // it's important that filenames be relative otherwise clang-format will
  293. // produce patches with absolute paths in them, which `git apply` will refuse
  294. // to apply.
  295. return filenames.map(x => path.relative(ELECTRON_ROOT, x));
  296. }
  297. async function main () {
  298. const opts = parseCommandLine();
  299. // no mode specified? run 'em all
  300. if (!opts['c++'] && !opts.javascript && !opts.objc && !opts.python && !opts.gn && !opts.patches) {
  301. opts['c++'] = opts.javascript = opts.objc = opts.python = opts.gn = opts.patches = true;
  302. }
  303. const linters = LINTERS.filter(x => opts[x.key]);
  304. for (const linter of linters) {
  305. const filenames = await findFiles(opts, linter);
  306. if (filenames.length) {
  307. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`); }
  308. await linter.run(opts, filenames);
  309. }
  310. }
  311. }
  312. if (process.mainModule === module) {
  313. main().catch((error) => {
  314. console.error(error);
  315. process.exit(1);
  316. });
  317. }