lint.js 12 KB

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