lint.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. ['atom', 'browser', 'mac', 'atom_application.h'],
  12. ['atom', 'browser', 'mac', 'atom_application_delegate.h'],
  13. ['atom', 'browser', 'resources', 'win', 'resource.h'],
  14. ['atom', 'browser', 'notifications', 'mac', 'notification_center_delegate.h'],
  15. ['atom', 'browser', 'ui', 'cocoa', 'atom_menu_controller.h'],
  16. ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window.h'],
  17. ['atom', 'browser', 'ui', 'cocoa', 'atom_ns_window_delegate.h'],
  18. ['atom', 'browser', 'ui', 'cocoa', 'atom_preview_item.h'],
  19. ['atom', 'browser', 'ui', 'cocoa', 'atom_touch_bar.h'],
  20. ['atom', 'browser', 'ui', 'cocoa', 'atom_inspectable_web_contents_view.h'],
  21. ['atom', 'browser', 'ui', 'cocoa', 'event_dispatching_window.h'],
  22. ['atom', 'browser', 'ui', 'cocoa', 'touch_bar_forward_declarations.h'],
  23. ['atom', 'browser', 'ui', 'cocoa', 'NSColor+Hex.h'],
  24. ['atom', 'browser', 'ui', 'cocoa', 'NSString+ANSI.h'],
  25. ['atom', 'common', 'api', 'api_messages.h'],
  26. ['atom', 'common', 'common_message_generator.cc'],
  27. ['atom', 'common', 'common_message_generator.h'],
  28. ['atom', 'common', 'node_includes.h'],
  29. ['spec', 'static', 'jquery-2.0.3.min.js'],
  30. ['spec', 'ts-smoke', 'electron', 'main.ts'],
  31. ['spec', 'ts-smoke', 'electron', 'renderer.ts'],
  32. ['spec', 'ts-smoke', 'runner.js']
  33. ].map(tokens => path.join(SOURCE_ROOT, ...tokens)))
  34. function spawnAndCheckExitCode (cmd, args, opts) {
  35. opts = Object.assign({ stdio: 'inherit' }, opts)
  36. const status = childProcess.spawnSync(cmd, args, opts).status
  37. if (status) process.exit(status)
  38. }
  39. const LINTERS = [ {
  40. key: 'c++',
  41. roots: ['atom'],
  42. test: filename => filename.endsWith('.cc') || filename.endsWith('.h'),
  43. run: (opts, filenames) => {
  44. if (opts.fix) {
  45. spawnAndCheckExitCode('python', ['script/run-clang-format.py', '--fix', ...filenames])
  46. } else {
  47. spawnAndCheckExitCode('python', ['script/run-clang-format.py', ...filenames])
  48. }
  49. const result = childProcess.spawnSync('cpplint.py', filenames, { encoding: 'utf8' })
  50. // cpplint.py writes EVERYTHING to stderr, including status messages
  51. if (result.stderr) {
  52. for (const line of result.stderr.split(/[\r\n]+/)) {
  53. if (line.length && !line.startsWith('Done processing ') && line !== 'Total errors found: 0') {
  54. console.warn(line)
  55. }
  56. }
  57. }
  58. if (result.status) {
  59. process.exit(result.status)
  60. }
  61. }
  62. }, {
  63. key: 'python',
  64. roots: ['script'],
  65. test: filename => filename.endsWith('.py'),
  66. run: (opts, filenames) => {
  67. const rcfile = path.join(DEPOT_TOOLS, 'pylintrc')
  68. const args = ['--rcfile=' + rcfile, ...filenames]
  69. const env = Object.assign({ PYTHONPATH: path.join(SOURCE_ROOT, 'script') }, process.env)
  70. spawnAndCheckExitCode('pylint.py', args, { env })
  71. }
  72. }, {
  73. key: 'javascript',
  74. roots: ['lib', 'spec', 'script', 'default_app'],
  75. ignoreRoots: ['spec/node_modules'],
  76. test: filename => filename.endsWith('.js'),
  77. run: (opts, filenames) => {
  78. const cmd = path.join(SOURCE_ROOT, 'node_modules', '.bin', 'eslint')
  79. const args = [ '--cache', ...filenames ]
  80. if (opts.fix) args.unshift('--fix')
  81. spawnAndCheckExitCode(cmd, args, { cwd: SOURCE_ROOT })
  82. }
  83. }, {
  84. key: 'gn',
  85. roots: ['.'],
  86. test: filename => filename.endsWith('.gn') || filename.endsWith('.gni'),
  87. run: (opts, filenames) => {
  88. const allOk = filenames.map(filename => {
  89. const env = Object.assign({
  90. CHROMIUM_BUILDTOOLS_PATH: path.resolve(SOURCE_ROOT, '..', 'buildtools'),
  91. DEPOT_TOOLS_WIN_TOOLCHAIN: '0'
  92. }, process.env)
  93. // Users may not have depot_tools in PATH.
  94. env.PATH = `${env.PATH}${path.delimiter}${DEPOT_TOOLS}`
  95. const args = ['format', filename]
  96. if (!opts.fix) args.push('--dry-run')
  97. const result = childProcess.spawnSync('gn', args, { env, stdio: 'inherit', shell: true })
  98. if (result.status === 0) {
  99. return true
  100. } else if (result.status === 2) {
  101. console.log(`GN format errors in "${filename}". Run 'gn format "${filename}"' or rerun with --fix to fix them.`)
  102. return false
  103. } else {
  104. console.log(`Error running 'gn format --dry-run "${filename}"': exit code ${result.status}`)
  105. return false
  106. }
  107. }).every(x => x)
  108. if (!allOk) {
  109. process.exit(1)
  110. }
  111. }
  112. }]
  113. function parseCommandLine () {
  114. let help
  115. const opts = minimist(process.argv.slice(2), {
  116. boolean: [ 'c++', 'javascript', 'python', 'gn', 'help', 'changed', 'fix', 'verbose', 'only' ],
  117. alias: { 'c++': ['cc', 'cpp', 'cxx'], javascript: ['js', 'es'], python: 'py', changed: 'c', help: 'h', verbose: 'v' },
  118. unknown: arg => { help = true }
  119. })
  120. if (help || opts.help) {
  121. console.log('Usage: script/lint.js [--cc] [--js] [--py] [-c|--changed] [-h|--help] [-v|--verbose] [--fix] [--only -- file1 file2]')
  122. process.exit(0)
  123. }
  124. return opts
  125. }
  126. async function findChangedFiles (top) {
  127. const result = await GitProcess.exec(['diff', '--name-only', '--cached'], top)
  128. if (result.exitCode !== 0) {
  129. console.log('Failed to find changed files', GitProcess.parseError(result.stderr))
  130. process.exit(1)
  131. }
  132. const relativePaths = result.stdout.split(/\r\n|\r|\n/g)
  133. const absolutePaths = relativePaths.map(x => path.join(top, x))
  134. return new Set(absolutePaths)
  135. }
  136. async function findMatchingFiles (top, test) {
  137. return new Promise((resolve, reject) => {
  138. const matches = []
  139. klaw(top)
  140. .on('end', () => resolve(matches))
  141. .on('data', item => {
  142. if (test(item.path)) {
  143. matches.push(item.path)
  144. }
  145. })
  146. })
  147. }
  148. async function findFiles (args, linter) {
  149. let filenames = []
  150. let whitelist = null
  151. // build the whitelist
  152. if (args.changed) {
  153. whitelist = await findChangedFiles(SOURCE_ROOT)
  154. if (!whitelist.size) {
  155. return []
  156. }
  157. } else if (args.only) {
  158. whitelist = new Set(args._)
  159. }
  160. // accumulate the raw list of files
  161. for (const root of linter.roots) {
  162. const files = await findMatchingFiles(path.join(SOURCE_ROOT, root), linter.test)
  163. filenames.push(...files)
  164. }
  165. for (const ignoreRoot of (linter.ignoreRoots) || []) {
  166. const ignorePath = path.join(SOURCE_ROOT, ignoreRoot)
  167. if (!fs.existsSync(ignorePath)) continue
  168. const ignoreFiles = new Set(await findMatchingFiles(ignorePath, linter.test))
  169. filenames = filenames.filter(fileName => !ignoreFiles.has(fileName))
  170. }
  171. // remove blacklisted files
  172. filenames = filenames.filter(x => !BLACKLIST.has(x))
  173. // if a whitelist exists, remove anything not in it
  174. if (whitelist) {
  175. filenames = filenames.filter(x => whitelist.has(x))
  176. }
  177. // it's important that filenames be relative otherwise clang-format will
  178. // produce patches with absolute paths in them, which `git apply` will refuse
  179. // to apply.
  180. return filenames.map(x => path.relative(SOURCE_ROOT, x))
  181. }
  182. async function main () {
  183. const opts = parseCommandLine()
  184. // no mode specified? run 'em all
  185. if (!opts['c++'] && !opts.javascript && !opts.python && !opts.gn) {
  186. opts['c++'] = opts.javascript = opts.python = opts.gn = true
  187. }
  188. const linters = LINTERS.filter(x => opts[x.key])
  189. for (const linter of linters) {
  190. const filenames = await findFiles(opts, linter)
  191. if (filenames.length) {
  192. if (opts.verbose) { console.log(`linting ${filenames.length} ${linter.key} ${filenames.length === 1 ? 'file' : 'files'}`) }
  193. linter.run(opts, filenames)
  194. }
  195. }
  196. }
  197. if (process.mainModule === module) {
  198. main().catch((error) => {
  199. console.error(error)
  200. process.exit(1)
  201. })
  202. }