lint.js 12 KB

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