UNPKG

2.97 kBJavaScriptView Raw
1'use strict'
2
3const dedent = require('dedent')
4const cosmiconfig = require('cosmiconfig')
5const stringifyObject = require('stringify-object')
6const { getConfig, validateConfig } = require('./getConfig')
7const printErrors = require('./printErrors')
8const runAll = require('./runAll')
9
10const debug = require('debug')('lint-staged')
11
12// Force colors for packages that depend on https://www.npmjs.com/package/supports-color
13// but do this only in TTY mode
14if (process.stdout.isTTY) {
15 // istanbul ignore next
16 process.env.FORCE_COLOR = '1'
17}
18
19const errConfigNotFound = new Error('Config could not be found')
20
21function resolveConfig(configPath) {
22 try {
23 return require.resolve(configPath)
24 } catch (ignore) {
25 return configPath
26 }
27}
28
29function 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 * Root lint-staged function that is called from .bin
47 */
48module.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 // result.config is the parsed configuration object
57 // result.filepath is the path to the config file that was found
58 const config = validateConfig(getConfig(result.config, debugMode))
59 if (debugMode) {
60 // Log using logger to be able to test through `consolemock`.
61 logger.log('Running lint-staged with the following config:')
62 logger.log(stringifyObject(config, { indent: ' ' }))
63 } else {
64 // We might not be in debug mode but `DEBUG=lint-staged*` could have
65 // been set.
66 debug('Normalized config:\n%O', config)
67 }
68
69 return runAll(config)
70 .then(() => {
71 debug('linters were executed successfully!')
72 // No errors, exiting with 0
73 })
74 .catch(error => {
75 // Errors detected, printing and exiting with non-zero
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 // It was probably a parsing error
86 logger.error(dedent`
87 Could not parse lint-staged config.
88
89 ${err}
90 `)
91 }
92 logger.error() // empty line
93 // Print helpful message for all errors
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}