lint.js 12 KB

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