UNPKG

2.44 kBJavaScriptView Raw
1'use strict'
2
3const debug = require('debug')('elint:main')
4const co = require('co')
5const _ = require('lodash')
6const walker = require('./walker')
7const report = require('./utils/report')
8const isGitHooks = require('./utils/is-git-hooks')
9const eslint = require('./workers/eslint')
10const stylelint = require('./workers/stylelint')
11const notifier = require('./notifier')
12
13/**
14 * @typedef ELintOptions
15 * @property {stirng} type lint 类型
16 * @property {boolean} fix 是否自动修复问题
17 * @property {boolean} forceFix 是否强制自动修复问题
18 */
19
20/**
21 * 主函数
22 *
23 * @param {string[]} files 待执行 lint 的文件
24 * @param {ELintOptions} options options
25 * @returns {void}
26 */
27function elint (files, options) {
28 co(function * () {
29 const fileList = yield walker(files, options)
30
31 // 没有匹配到任何文件,直接退出
32 if (!fileList.es.length && !fileList.style.length) {
33 process.exit()
34 }
35
36 // linters 对象,方便后续操作
37 const linters = {
38 es: eslint,
39 style: stylelint
40 }
41
42 // 处理 fix 和 forceFix
43 const isGit = yield isGitHooks()
44
45 if (isGit) {
46 options.fix = false
47 }
48 if (options.forceFix) {
49 options.fix = true
50 }
51
52 debug('parsed options: %o', options)
53
54 const { type } = options
55 const argus = JSON.stringify(options)
56 let workers = []
57
58 if (type) {
59 // 明确指定 type,例如 elint lint es "*.js"
60 workers.push(linters[type](argus, ...fileList[type]))
61 } else {
62 /**
63 * 没有明确指定 type,根据文件类型判断支持哪些 linter
64 * 使用 _.toPairs 兼容 node v6
65 */
66 _.toPairs(linters).forEach(([linterType, linter]) => {
67 if (!fileList[linterType].length) {
68 return
69 }
70
71 workers.push(linter(argus, ...fileList[linterType]))
72 })
73 }
74
75 // 添加 notifier
76 workers.push(notifier.notify())
77
78 Promise.all(workers).then(results => {
79 const notifierResult = results.pop()
80 const lintResults = results
81
82 const outputs = []
83 let success = true
84
85 lintResults.forEach(result => {
86 const output = JSON.parse(result.stdout)
87 outputs.push(output)
88 success = success && output.success
89 })
90
91 console.log(report(outputs))
92
93 if (notifierResult) {
94 console.log(notifierResult)
95 }
96
97 process.exit(success ? 0 : 1)
98 })
99 })
100}
101
102module.exports = elint