File size: 9,743 Bytes
4a51346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
/**
 * @fileoverview Create configurations for a rule
 * @author Ian VanSchooten
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const builtInRules = require("../rules");

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Wrap all of the elements of an array into arrays.
 * @param   {*[]}     xs Any array.
 * @returns {Array[]}    An array of arrays.
 */
function explodeArray(xs) {
    return xs.reduce((accumulator, x) => {
        accumulator.push([x]);
        return accumulator;
    }, []);
}

/**
 * Mix two arrays such that each element of the second array is concatenated
 * onto each element of the first array.
 *
 * For example:
 * combineArrays([a, [b, c]], [x, y]); // -> [[a, x], [a, y], [b, c, x], [b, c, y]]
 * @param   {Array} arr1 The first array to combine.
 * @param   {Array} arr2 The second array to combine.
 * @returns {Array}      A mixture of the elements of the first and second arrays.
 */
function combineArrays(arr1, arr2) {
    const res = [];

    if (arr1.length === 0) {
        return explodeArray(arr2);
    }
    if (arr2.length === 0) {
        return explodeArray(arr1);
    }
    arr1.forEach(x1 => {
        arr2.forEach(x2 => {
            res.push([].concat(x1, x2));
        });
    });
    return res;
}

/**
 * Group together valid rule configurations based on object properties
 *
 * e.g.:
 * groupByProperty([
 *     {before: true},
 *     {before: false},
 *     {after: true},
 *     {after: false}
 * ]);
 *
 * will return:
 * [
 *     [{before: true}, {before: false}],
 *     [{after: true}, {after: false}]
 * ]
 * @param   {Object[]} objects Array of objects, each with one property/value pair
 * @returns {Array[]}          Array of arrays of objects grouped by property
 */
function groupByProperty(objects) {
    const groupedObj = objects.reduce((accumulator, obj) => {
        const prop = Object.keys(obj)[0];

        accumulator[prop] = accumulator[prop] ? accumulator[prop].concat(obj) : [obj];
        return accumulator;
    }, {});

    return Object.keys(groupedObj).map(prop => groupedObj[prop]);
}


//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------

/**
 * Configuration settings for a rule.
 *
 * A configuration can be a single number (severity), or an array where the first
 * element in the array is the severity, and is the only required element.
 * Configs may also have one or more additional elements to specify rule
 * configuration or options.
 * @typedef {Array|number} ruleConfig
 * @param {number}  0  The rule's severity (0, 1, 2).
 */

/**
 * Object whose keys are rule names and values are arrays of valid ruleConfig items
 * which should be linted against the target source code to determine error counts.
 * (a ruleConfigSet.ruleConfigs).
 *
 * e.g. rulesConfig = {
 *     "comma-dangle": [2, [2, "always"], [2, "always-multiline"], [2, "never"]],
 *     "no-console": [2]
 * }
 * @typedef rulesConfig
 */


/**
 * Create valid rule configurations by combining two arrays,
 * with each array containing multiple objects each with a
 * single property/value pair and matching properties.
 *
 * e.g.:
 * combinePropertyObjects(
 *     [{before: true}, {before: false}],
 *     [{after: true}, {after: false}]
 * );
 *
 * will return:
 * [
 *     {before: true, after: true},
 *     {before: true, after: false},
 *     {before: false, after: true},
 *     {before: false, after: false}
 * ]
 * @param   {Object[]} objArr1 Single key/value objects, all with the same key
 * @param   {Object[]} objArr2 Single key/value objects, all with another key
 * @returns {Object[]}         Combined objects for each combination of input properties and values
 */
function combinePropertyObjects(objArr1, objArr2) {
    const res = [];

    if (objArr1.length === 0) {
        return objArr2;
    }
    if (objArr2.length === 0) {
        return objArr1;
    }
    objArr1.forEach(obj1 => {
        objArr2.forEach(obj2 => {
            const combinedObj = {};
            const obj1Props = Object.keys(obj1);
            const obj2Props = Object.keys(obj2);

            obj1Props.forEach(prop1 => {
                combinedObj[prop1] = obj1[prop1];
            });
            obj2Props.forEach(prop2 => {
                combinedObj[prop2] = obj2[prop2];
            });
            res.push(combinedObj);
        });
    });
    return res;
}

/**
 * Creates a new instance of a rule configuration set
 *
 * A rule configuration set is an array of configurations that are valid for a
 * given rule.  For example, the configuration set for the "semi" rule could be:
 *
 * ruleConfigSet.ruleConfigs // -> [[2], [2, "always"], [2, "never"]]
 *
 * Rule configuration set class
 */
class RuleConfigSet {

    // eslint-disable-next-line jsdoc/require-description
    /**
     * @param {ruleConfig[]} configs Valid rule configurations
     */
    constructor(configs) {

        /**
         * Stored valid rule configurations for this instance
         * @type {Array}
         */
        this.ruleConfigs = configs || [];
    }

    /**
     * Add a severity level to the front of all configs in the instance.
     * This should only be called after all configs have been added to the instance.
     * @returns {void}
     */
    addErrorSeverity() {
        const severity = 2;

        this.ruleConfigs = this.ruleConfigs.map(config => {
            config.unshift(severity);
            return config;
        });

        // Add a single config at the beginning consisting of only the severity
        this.ruleConfigs.unshift(severity);
    }

    /**
     * Add rule configs from an array of strings (schema enums)
     * @param  {string[]} enums Array of valid rule options (e.g. ["always", "never"])
     * @returns {void}
     */
    addEnums(enums) {
        this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, enums));
    }

    /**
     * Add rule configurations from a schema object
     * @param  {Object} obj Schema item with type === "object"
     * @returns {boolean} true if at least one schema for the object could be generated, false otherwise
     */
    addObject(obj) {
        const objectConfigSet = {
            objectConfigs: [],
            add(property, values) {
                for (let idx = 0; idx < values.length; idx++) {
                    const optionObj = {};

                    optionObj[property] = values[idx];
                    this.objectConfigs.push(optionObj);
                }
            },

            combine() {
                this.objectConfigs = groupByProperty(this.objectConfigs).reduce((accumulator, objArr) => combinePropertyObjects(accumulator, objArr), []);
            }
        };

        /*
         * The object schema could have multiple independent properties.
         * If any contain enums or booleans, they can be added and then combined
         */
        Object.keys(obj.properties).forEach(prop => {
            if (obj.properties[prop].enum) {
                objectConfigSet.add(prop, obj.properties[prop].enum);
            }
            if (obj.properties[prop].type && obj.properties[prop].type === "boolean") {
                objectConfigSet.add(prop, [true, false]);
            }
        });
        objectConfigSet.combine();

        if (objectConfigSet.objectConfigs.length > 0) {
            this.ruleConfigs = this.ruleConfigs.concat(combineArrays(this.ruleConfigs, objectConfigSet.objectConfigs));
            return true;
        }

        return false;
    }
}

/**
 * Generate valid rule configurations based on a schema object
 * @param   {Object} schema  A rule's schema object
 * @returns {Array[]}        Valid rule configurations
 */
function generateConfigsFromSchema(schema) {
    const configSet = new RuleConfigSet();

    if (Array.isArray(schema)) {
        for (const opt of schema) {
            if (opt.enum) {
                configSet.addEnums(opt.enum);
            } else if (opt.type && opt.type === "object") {
                if (!configSet.addObject(opt)) {
                    break;
                }

            // TODO (IanVS): support oneOf
            } else {

                // If we don't know how to fill in this option, don't fill in any of the following options.
                break;
            }
        }
    }
    configSet.addErrorSeverity();
    return configSet.ruleConfigs;
}

/**
 * Generate possible rule configurations for all of the core rules
 * @param {boolean} noDeprecated Indicates whether ignores deprecated rules or not.
 * @returns {rulesConfig} Hash of rule names and arrays of possible configurations
 */
function createCoreRuleConfigs(noDeprecated = false) {
    return Array.from(builtInRules).reduce((accumulator, [id, rule]) => {
        const schema = (typeof rule === "function") ? rule.schema : rule.meta.schema;
        const isDeprecated = (typeof rule === "function") ? rule.deprecated : rule.meta.deprecated;

        if (noDeprecated && isDeprecated) {
            return accumulator;
        }

        accumulator[id] = generateConfigsFromSchema(schema);
        return accumulator;
    }, {});
}


//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------

module.exports = {
    generateConfigsFromSchema,
    createCoreRuleConfigs
};