lint.js 11 KB

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