lint.js 11 KB

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