webpack/lib/OptionsDefaulter.js

85 lines
1.9 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
2017-11-08 18:32:05 +08:00
const getProperty = (obj, name) => {
name = name.split(".");
2018-02-25 09:00:20 +08:00
for (let i = 0; i < name.length - 1; i++) {
obj = obj[name[i]];
2018-02-25 09:00:20 +08:00
if (typeof obj !== "object" || !obj || Array.isArray(obj)) return;
}
return obj[name.pop()];
2017-11-08 18:32:05 +08:00
};
2017-11-08 18:32:05 +08:00
const setProperty = (obj, name, value) => {
name = name.split(".");
2018-02-25 09:00:20 +08:00
for (let i = 0; i < name.length - 1; i++) {
2018-08-21 08:26:50 +08:00
if (typeof obj[name[i]] !== "object" && obj[name[i]] !== undefined) return;
2018-02-25 09:00:20 +08:00
if (Array.isArray(obj[name[i]])) return;
if (!obj[name[i]]) obj[name[i]] = {};
obj = obj[name[i]];
}
obj[name.pop()] = value;
2017-11-08 18:32:05 +08:00
};
class OptionsDefaulter {
constructor() {
2017-01-11 17:51:58 +08:00
this.defaults = {};
this.config = {};
2016-10-29 17:11:44 +08:00
}
process(options) {
2017-09-14 15:22:29 +08:00
options = Object.assign({}, options);
2018-02-25 09:00:20 +08:00
for (let name in this.defaults) {
switch (this.config[name]) {
case undefined:
if (getProperty(options, name) === undefined) {
setProperty(options, name, this.defaults[name]);
}
break;
case "call":
2018-02-25 09:00:20 +08:00
setProperty(
options,
name,
this.defaults[name].call(this, getProperty(options, name), options)
2018-02-25 09:00:20 +08:00
);
break;
case "make":
if (getProperty(options, name) === undefined) {
2018-03-27 16:19:13 +08:00
setProperty(options, name, this.defaults[name].call(this, options));
}
break;
2018-02-25 09:00:20 +08:00
case "append": {
let oldValue = getProperty(options, name);
if (!Array.isArray(oldValue)) {
oldValue = [];
}
2018-02-25 09:00:20 +08:00
oldValue.push(...this.defaults[name]);
setProperty(options, name, oldValue);
break;
}
default:
2018-02-25 09:00:20 +08:00
throw new Error(
"OptionsDefaulter cannot process " + this.config[name]
);
}
}
2017-09-14 15:22:29 +08:00
return options;
}
set(name, config, def) {
2018-02-25 09:00:20 +08:00
if (def !== undefined) {
this.defaults[name] = def;
this.config[name] = config;
} else {
this.defaults[name] = config;
delete this.config[name];
}
}
}
module.exports = OptionsDefaulter;