UNPKG

2.79 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _parser = require('./parser');
8
9var _parser2 = _interopRequireDefault(_parser);
10
11var _package = require('../package.json');
12
13var _package2 = _interopRequireDefault(_package);
14
15var _cliEngineConfig = require('cli-engine-config');
16
17var _httpCall = require('http-call');
18
19var _httpCall2 = _interopRequireDefault(_httpCall);
20
21var _help = require('./help');
22
23var _help2 = _interopRequireDefault(_help);
24
25function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
26
27// eslint-disable-line
28class Command {
29
30 static get id() {
31 let cmd = [];
32 if (this.topic) cmd.push(this.topic);
33 if (this.command) cmd.push(this.command);
34 return cmd.join(':');
35 }
36
37 /**
38 * instantiate and run the command setting {mock: true} in the config (shorthand method)
39 */
40 static async mock(...argv) {
41 argv.unshift('argv0', 'cmd');
42 return this.run({ argv, mock: true });
43 }
44
45 /**
46 * instantiate and run the command
47 */
48 static async run(config) {
49 const cmd = new this({ config });
50 try {
51 await cmd.init();
52 await cmd.run();
53 await cmd.out.done();
54 } catch (err) {
55 cmd.out.error(err);
56 }
57 return cmd;
58 }
59
60 constructor(options = {}) {
61 this.flags = {};
62 this.args = {};
63
64 this.config = (0, _cliEngineConfig.buildConfig)(options.config);
65 this.argv = this.config.argv;
66 const { cli } = require('cli-ux');
67 this.out = this.cli = cli;
68 this.out.color = require('./color').color;
69 this.http = _httpCall2.default.defaults({
70 headers: {
71 'user-agent': `${this.config.name}/${this.config.version} (${this.config.platform}-${this.config.arch}) node-${process.version}`
72 }
73 });
74 }
75
76 async init() {
77 const parser = new _parser2.default({
78 flags: this.constructor.flags || {},
79 args: this.constructor.args || [],
80 variableArgs: this.constructor.variableArgs,
81 cmd: this
82 });
83 const { argv, flags, args } = await parser.parse({ flags: this.flags, argv: this.argv.slice(2) });
84 this.flags = flags;
85 this.argv = argv;
86 this.args = args;
87 }
88
89 // prevent setting things that need to be static
90
91
92 /**
93 * actual command run code goes here
94 */
95 async run(...rest) {}
96
97 get stdout() {
98 return this.out.stdout.output;
99 }
100
101 get stderr() {
102 return this.out.stderr.output;
103 }
104
105 static buildHelp(config) {
106 let help = new _help2.default(config);
107 return help.command(this);
108 }
109
110 static buildHelpLine(config) {
111 let help = new _help2.default(config);
112 return help.commandLine(this);
113 }
114}
115exports.default = Command;
116Command.aliases = [];
117Command.variableArgs = false;
118Command.args = [];
119Command._version = _package2.default.version;
\No newline at end of file