lint.js 12 KB

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