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