UNPKG

2.5 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 entries = Object.entries(config)
50
51 if (entries.length === 0) {
52 errors.push('Configuration should not be empty!')
53 }
54
55 entries.forEach(([pattern, task]) => {
56 if (TEST_DEPRECATED_KEYS.has(pattern)) {
57 const testFn = TEST_DEPRECATED_KEYS.get(pattern)
58 if (testFn(task)) {
59 errors.push(
60 createError(
61 pattern,
62 'Advanced configuration has been deprecated. For more info, please visit: https://github.com/okonet/lint-staged',
63 task
64 )
65 )
66 }
67 }
68
69 if (
70 (!Array.isArray(task) ||
71 task.some((item) => typeof item !== 'string' && typeof item !== 'function')) &&
72 typeof task !== 'string' &&
73 typeof task !== 'function'
74 ) {
75 errors.push(
76 createError(
77 pattern,
78 'Should be a string, a function, or an array of strings and functions',
79 task
80 )
81 )
82 }
83 })
84 }
85
86 if (errors.length) {
87 throw new Error(errors.join('\n'))
88 }
89
90 return config
91}
92
93module.exports.createError = createError