lint.js 7.4 KB

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