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