UNPKG

2.45 kBJavaScriptView Raw
1/* eslint no-prototype-builtins: 0 */
2
3'use strict'
4
5const chalk = require('chalk')
6const format = require('stringify-object')
7
8const debug = require('debug')('lint-staged:cfg')
9
10const TEST_DEPRECATED_KEYS = new Map([
11 ['concurrent', key => typeof key === 'boolean'],
12 ['chunkSize', key => typeof key === 'number'],
13 ['globOptions', key => typeof key === 'object'],
14 ['linters', key => typeof key === 'object'],
15 ['ignore', key => Array.isArray(key)],
16 ['subTaskConcurrency', key => typeof key === 'number'],
17 ['renderer', key => typeof key === 'string'],
18 ['relative', key => typeof key === 'boolean']
19])
20
21const formatError = helpMsg => `● Validation Error:
22
23 ${helpMsg}
24
25Please refer to https://github.com/okonet/lint-staged#configuration for more information...`
26
27const createError = (opt, helpMsg, value) =>
28 formatError(`Invalid value for '${chalk.bold(opt)}'.
29
30 ${helpMsg}.
31
32 Configured value is: ${chalk.bold(
33 format(value, { inlineCharacterLimit: Number.POSITIVE_INFINITY })
34 )}`)
35
36/**
37 * Runs config validation. Throws error if the config is not valid.
38 * @param config {Object}
39 * @returns config {Object}
40 */
41module.exports = function validateConfig(config) {
42 debug('Validating config')
43
44 const errors = []
45
46 if (!config || typeof config !== 'object') {
47 errors.push('Configuration should be an object!')
48 } else {
49 const globs = Object.keys(config)
50
51 if (globs.length === 0) {
52 errors.push('Configuration should not be empty!')
53 }
54
55 globs.forEach(key => {
56 if (TEST_DEPRECATED_KEYS.has(key)) {
57 const testFn = TEST_DEPRECATED_KEYS.get(key)
58 if (testFn(config[key])) {
59 errors.push(
60 createError(
61 key,
62 'Advanced configuration has been deprecated. For more info, please visit: https://github.com/okonet/lint-staged',
63 config[key]
64 )
65 )
66 }
67 }
68
69 if (
70 (!Array.isArray(config[key]) ||
71 config[key].some(item => typeof item !== 'string' && typeof item !== 'function')) &&
72 typeof config[key] !== 'string' &&
73 typeof config[key] !== 'function'
74 ) {
75 errors.push(
76 createError(
77 key,
78 'Should be a string, a function, or an array of strings and functions',
79 config[key]
80 )
81 )
82 }
83 })
84 }
85
86 if (errors.length) {
87 throw new Error(errors.join('\n'))
88 }
89
90 return config
91}