cli-engine
Version:
Generic CLI Framework
96 lines (77 loc) • 3.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _cliEngineCommand = require('cli-engine-command');
var _ = require('.');
var _2 = _interopRequireDefault(_);
var _autocomplete = require('../../autocomplete');
var _autocomplete2 = _interopRequireDefault(_autocomplete);
var _plugins = require('../../plugins');
var _plugins2 = _interopRequireDefault(_plugins);
var _cache = require('../../cache');
var _cache2 = _interopRequireDefault(_cache);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class AutocompleteValues extends _2.default {
async run() {
try {
this.errorIfWindows();
// handle missing flags e, not in parser
if (!this.flags.cmd) throw new Error('Missing required value for --cmd');
if (!this.flags.resource) throw new Error('Missing required value for --resource');
// find Command
const plugins = new _plugins2.default(this.out);
await plugins.load();
let Command = await plugins.findCommand(this.flags.cmd);
if (!Command) throw new Error(`Command ${this.flags.cmd} not found`);
// get cache key and options
let cacheKey = 'void';
let cacheCompletion;
if (this.flags.arg) {
let args = Command ? Command.args : [];
let arg = args.find(a => a.name === this.flags.resource);
if (!arg) throw new Error(`Arg ${this.flags.resource} not found`);
cacheKey = arg.name;
cacheCompletion = arg.completion;
} else {
let long = this.flags.resource.replace(/^-+/, '');
let flags = Command ? Command.flags : {};
let flag = flags[long];
if (!flag) throw new Error(`Flag ${long} not found`);
cacheKey = long;
cacheCompletion = flag.completion;
}
// create/fetch cache
if (cacheCompletion && cacheCompletion.options) {
const key = cacheCompletion.cacheKey || cacheKey;
const flagCache = _path2.default.join(this.completionsPath, key);
const duration = cacheCompletion.cacheDuration || 60 * 60 * 24; // 1 day
const cacheFunc = cacheCompletion.options(this.out);
const opts = { cacheFn: () => cacheFunc };
const options = await _cache2.default.fetch(flagCache, duration, opts);
this.out.log((options || []).join('\n'));
}
} catch (err) {
const ac = new _autocomplete2.default(this);
// fail silently
// or autocomplete will use error as options
ac.writeLogFile(err.message);
}
}
}
exports.default = AutocompleteValues;
AutocompleteValues.topic = 'autocomplete';
AutocompleteValues.command = 'values';
AutocompleteValues.description = 'generates autocomplete values';
AutocompleteValues.hidden = true;
AutocompleteValues.flags = {
// don't require cmd or flag
// we want it to run silently
// or autocomplete will use any
// flag errors as options
cmd: _cliEngineCommand.flags.string({ description: '', char: 'c' }),
resource: _cliEngineCommand.flags.string({ description: '', char: 'r' }),
arg: _cliEngineCommand.flags.boolean({ description: '', char: 'a' })
};