lint.js 12 KB

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