-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
87 lines (76 loc) · 2.1 KB
/
index.js
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
const yaml = require('js-yaml');
const fs = require('fs');
const path = require('path');
const colors = require('colors');
const yargs = require('yargs');
const callsite = require('callsite');
const Joi = require('joi');
const {
registerCommands,
registerOptions,
registerAutocomplete
} = require('./lib/init-yargs');
const {
settingsSchema,
commandsSchema,
optionsSchema
} = require('./joi-schemas/schemas');
class CliIfy {
constructor(configPath) {
this._commands;
this._options;
this._settings;
this._yargs = yargs;
this._manifestSchema = Joi.compile({
settings: settingsSchema,
commands: commandsSchema,
options: optionsSchema
});
}
init({ manifest, dependencies }) {
try {
const execDir = this._getExecDir();
const {
commands,
options,
settings
} = this._loadConfig(execDir, manifest);
this._commands = commands;
this._options = options;
this._settings = settings;
registerCommands(this._commands, this._yargs, this._settings, execDir, dependencies);
registerOptions(this._options, this._yargs, this._settings);
registerAutocomplete(this._commands, this._settings);
this._yargs.argv;
} catch (e) {
if (e.name && e.name === 'YAMLException') {
return console.log(colors.red(`${e.name} : ${e.message}`));
}
if (e.name && e.name === 'ManifestException') {
return console.log(colors.red(e));
}
return console.log(e);
}
}
_loadConfig(execDir, manifest) {
const configs = yaml.safeLoad(
fs.readFileSync(path.resolve(execDir, manifest), 'utf8')
);
return this._validateSchema(configs);
}
_validateSchema(configs) {
const result = this._manifestSchema.validate(configs);
if (result.error) {
const err = new Error(result.error.details[0].message);
err.name = 'ManifestException';
throw err;
}
return result.value;
}
_getExecDir() {
const stack = callsite();
const requester = stack[2].getFileName();
return path.dirname(requester);
}
};
module.exports = CliIfy;