lint.js 13 KB

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