1 | 'use strict'
|
2 |
|
3 | const dedent = require('dedent')
|
4 | const cosmiconfig = require('cosmiconfig')
|
5 | const stringifyObject = require('stringify-object')
|
6 | const printErrors = require('./printErrors')
|
7 | const runAll = require('./runAll')
|
8 | const validateConfig = require('./validateConfig')
|
9 |
|
10 | const debugLog = require('debug')('lint-staged')
|
11 |
|
12 | const errConfigNotFound = new Error('Config could not be found')
|
13 |
|
14 | function resolveConfig(configPath) {
|
15 | try {
|
16 | return require.resolve(configPath)
|
17 | } catch (ignore) {
|
18 | return configPath
|
19 | }
|
20 | }
|
21 |
|
22 | function loadConfig(configPath) {
|
23 | const explorer = cosmiconfig('lint-staged', {
|
24 | searchPlaces: [
|
25 | 'package.json',
|
26 | '.lintstagedrc',
|
27 | '.lintstagedrc.json',
|
28 | '.lintstagedrc.yaml',
|
29 | '.lintstagedrc.yml',
|
30 | '.lintstagedrc.js',
|
31 | 'lint-staged.config.js'
|
32 | ]
|
33 | })
|
34 |
|
35 | return configPath ? explorer.load(resolveConfig(configPath)) : explorer.search()
|
36 | }
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 | module.exports = function lintStaged(
|
54 | { configPath, shell = false, quiet = false, debug = false } = {},
|
55 | logger = console
|
56 | ) {
|
57 | debugLog('Loading config using `cosmiconfig`')
|
58 |
|
59 | return loadConfig(configPath)
|
60 | .then(result => {
|
61 | if (result == null) throw errConfigNotFound
|
62 |
|
63 | debugLog('Successfully loaded config from `%s`:\n%O', result.filepath, result.config)
|
64 |
|
65 |
|
66 | const config = validateConfig(result.config)
|
67 | if (debug) {
|
68 |
|
69 | logger.log('Running lint-staged with the following config:')
|
70 | logger.log(stringifyObject(config, { indent: ' ' }))
|
71 | } else {
|
72 |
|
73 |
|
74 | debugLog('Normalized config:\n%O', config)
|
75 | }
|
76 |
|
77 | return runAll(config, shell, quiet, debug, logger)
|
78 | .then(() => {
|
79 | debugLog('linters were executed successfully!')
|
80 | return Promise.resolve(true)
|
81 | })
|
82 | .catch(error => {
|
83 | printErrors(error, logger)
|
84 | return Promise.resolve(false)
|
85 | })
|
86 | })
|
87 | .catch(err => {
|
88 | if (err === errConfigNotFound) {
|
89 | logger.error(`${err.message}.`)
|
90 | } else {
|
91 |
|
92 | logger.error(dedent`
|
93 | Could not parse lint-staged config.
|
94 |
|
95 | ${err}
|
96 | `)
|
97 | }
|
98 | logger.error()
|
99 |
|
100 | logger.error(dedent`
|
101 | Please make sure you have created it correctly.
|
102 | See https://github.com/okonet/lint-staged#configuration.
|
103 | `)
|
104 |
|
105 | return Promise.reject(err)
|
106 | })
|
107 | }
|