@auttam/easycli
Version:
A quick and easy way of creating cli for your npm package.
80 lines (79 loc) • 3.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OptionCollection = exports.Option = void 0;
const base_config_1 = require("./base-config");
const collection_1 = require("./collection");
const config_error_1 = require("../errors/config-error");
class Option extends base_config_1.Config {
constructor(config) {
super(config);
this.acceptOnly = [];
this.aliases = [];
if (config.value) {
this.value = config.value;
}
this.acceptOnly = Array.isArray(config.acceptOnly) ? config.acceptOnly : [];
this.aliases = config.aliases && Array.isArray(config.aliases) ? config.aliases : [];
this.acceptOnly = this.acceptOnly.filter((value, index, self) => self.indexOf(value) === index);
this.aliases = this.aliases.filter((value, index, self) => self.indexOf(value) === index);
if (this.aliases.indexOf(this.name) > -1) {
this.aliases = this.aliases.filter(item => item != this.name);
}
}
}
exports.Option = Option;
class OptionCollection extends collection_1.Collection {
constructor() {
super(...arguments);
this._propNames = {};
this._names = '';
}
add(config) {
if (!config)
throw new config_error_1.ConfigurationError('Option configuration cannot be null or undefined');
if (super.hasKey(config.name)) {
var option = super.get(config.name);
option.merge(config);
super.update(option.name, option);
}
else {
var option = new Option(config);
super.append(option.name, option);
}
}
addList(configs) {
if (!configs || !configs.length)
return;
configs.forEach(config => this.add(config));
}
addByAny(config) {
this.add({
name: config.name || '',
help: config.help,
value: config.value,
acceptOnly: config.acceptOnly,
aliases: config.aliases,
propName: config.name
});
}
validate(item) {
if (this._propNames[item.propName] && this._propNames[item.propName] != item.name) {
throw new config_error_1.ConfigurationError('Unable to add option, option has a property name that is already used', item);
}
var self = this;
var matched = item.aliases.some(name => {
return self._names.indexOf(' ' + name + ' ') > -1;
});
if (matched) {
throw new config_error_1.ConfigurationError('Unable to add option, option has a name that is already used', item);
}
}
itemAdded(item) {
if (this._names.indexOf(item.name) == -1) {
this._names += item.name + ' ' + item.aliases.join(' ') + ' ';
}
this._propNames[item.propName] = item.name;
}
verify() { }
}
exports.OptionCollection = OptionCollection;