Migrating Beau's CLI from commander to OCLIF.

This commit is contained in:
David Diaz 2018-04-29 16:58:11 -06:00
parent 92142c148b
commit 25635c907f
6 changed files with 2191 additions and 2020 deletions

189
bin/beau
View File

@ -1,188 +1,5 @@
#!/usr/bin/env node #!/usr/bin/env node
const program = require('commander');
const process = require('process');
const Beau = require('../src/beau');
const yaml = require('js-yaml');
const fs = require('fs');
const { Line, Spinner } = require('clui');
const clc = require('cli-color');
const jsome = require('jsome');
const dotenv = require('dotenv');
const updateNotifier = require('update-notifier');
const package = require('../package.json'); require('@oclif/command')
.run()
updateNotifier({ pkg: package }).notify(); .catch(require('@oclif/errors/handle'));
program.version(package.version);
program
.command('request <alias>')
.option(
'-c --config <config>',
'Specify your request config file. Defaults to beau.yml in the current directory.',
'beau.yml'
)
.option(
'--verbose',
'Show all the information available on the current request.',
false
)
.option('--no-format', 'Return the text without any special formatting.')
.action(async (alias, { config, format, verbose }) => {
const beau = loadConfig(config);
let spinner;
if (format) {
spinner = new Spinner(clc.yellow(`Requesting: ${alias}`));
spinner.start();
}
try {
let res = await beau.requests.execByAlias(alias);
let { status, headers, body } = res.response;
let { endpoint } = res.request;
if (format) {
spinner.stop();
status = status.toString().startsWith(2)
? clc.green(status)
: clc.red(status);
new Line()
.padding(2)
.column('Status', 20, [clc.cyan])
.column('Endpoint', 20, [clc.cyan])
.output();
new Line()
.padding(2)
.column(status, 20)
.column(endpoint)
.output();
new Line().output();
if (verbose) {
jsome(res);
} else {
jsome(body);
}
} else {
console.log(status);
console.log(endpoint);
console.log(JSON.stringify(headers));
console.log(JSON.stringify(body));
}
process.exit(0);
} catch (err) {
new Line().output();
console.error(err.message);
process.exit(1);
}
});
program
.command('list')
.option(
'-c --config <config>',
'Specify your request config file. Defaults to beau.yml in the current directory.',
'beau.yml'
)
.option('--no-format', 'Return the text without any special formatting.')
.action(({ config, format }) => {
const beau = loadConfig(config);
if (format) {
new Line()
.padding(2)
.column('HTTP Verb', 20, [clc.cyan])
.column('Alias', 30, [clc.cyan])
.column('Endpoint', 20, [clc.cyan])
.output();
beau.requests.list.forEach(({ VERB, ALIAS, ENDPOINT, PATH }) =>
new Line()
.padding(2)
.column(VERB, 20, [clc.yellow])
.column(ALIAS, 30, [clc.yellow])
.column(ENDPOINT.replace(/\/$/, '') + '/' + PATH.replace(/^\//, ''))
.output()
);
new Line().output();
} else {
beau.requests.list.forEach(({ VERB, ALIAS, ENDPOINT, PATH }) => {
console.log(`${VERB}\t${ALIAS}\t${ENDPOINT.replace(/\/$/, '')}/${PATH.replace(/^\//, '')}`);
});
}
});
program
.command('init')
.option(
'-e --endpoint <endpoint>',
'Allows you to set the default endpoint',
null
)
.action(({ endpoint }) => {
const newFile = `# Beau.yml
version: 1${
endpoint === null
? `
# endpoint: http://example.com
`
: `
endpoint: ${endpoint}
`
}
# defaults:
# params:
# userId: 25
# GET /profile: profile
# GET /posts:
# alias: posts
# params:
# order: ASC
# POST /profile:
# alias: save-profile
# headers:
# authentication: Bearer token
# payload:
# name: David
# lastname: Diaz
`;
if (!fs.existsSync('beau.yml')) {
fs.writeFileSync('beau.yml', newFile);
console.info('beau.yml created!');
} else {
console.error('beau.yml already exists.');
}
});
program.parse(process.argv);
if (!program.args.length) {
program.help();
}
function loadConfig(configFile) {
if (!fs.existsSync(configFile)) {
console.error(`The config file, ${configFile} was not found.`);
process.exit(1);
}
const config = yaml.safeLoad(fs.readFileSync(configFile, 'utf-8'));
const env = dotenv.config().parsed || {};
return new Beau(config, env);
}

37
bin/cli/base.js Normal file
View File

@ -0,0 +1,37 @@
const yaml = require('js-yaml');
const fs = require('fs');
const dotenv = require('dotenv');
const { Command, flags } = require('@oclif/command');
const Beau = require('../../src/beau');
class Base extends Command {
loadConfig(configFile) {
if (!fs.existsSync(configFile)) {
this.error(`The config file, ${configFile} was not found.`);
this.exit(1);
}
const config = yaml.safeLoad(fs.readFileSync(configFile, 'utf-8'));
const env = dotenv.config().parsed || {};
return new Beau(config, env);
}
}
Base.flags = {
config: flags.string({
char: 'c',
description: 'The configuration file to be used.',
default: 'beau.yml'
}),
verbose: flags.boolean({
char: 'V',
description: 'Show all additional information available for a command.'
}),
'no-format': flags.boolean({
description: `Disables color formatting for usage on external tools.`
})
};
module.exports = Base;

52
bin/cli/commands/list.js Normal file
View File

@ -0,0 +1,52 @@
const clc = require('cli-color');
const { Line } = require('clui');
const { flags } = require('@oclif/command');
const Base = require('../base');
class ListCommand extends Base {
async run() {
const { flags } = this.parse(ListCommand);
const Beau = this.loadConfig(flags.config);
if (flags.format === false) {
return Beau.requests.list.forEach(
({ VERB, ALIAS, ENDPOINT, PATH }) =>
this.log(
VERB +
`\t` +
ALIAS +
`\t` +
ENDPOINT.replace(/\/$/, '') +
`/` +
PATH.replace(/^\//, '')
)
);
}
new Line()
.padding(2)
.column('HTTP Verb', 20, [clc.cyan])
.column('Alias', 30, [clc.cyan])
.column('Endpoint', 20, [clc.cyan])
.output();
Beau.requests.list.forEach(({ VERB, ALIAS, ENDPOINT, PATH }) =>
new Line()
.padding(2)
.column(VERB, 20, [clc.yellow])
.column(ALIAS, 30, [clc.yellow])
.column(
ENDPOINT.replace(/\/$/, '') + '/' + PATH.replace(/^\//, '')
)
.output()
);
new Line().output();
}
}
ListCommand.description = `Lists all available requests in the config file.`;
ListCommand.flags = { ...Base.flags };
module.exports = ListCommand;

View File

@ -0,0 +1,83 @@
const clc = require('cli-color');
const jsome = require('jsome');
const { Line, Spinner } = require('clui');
const { flags } = require('@oclif/command');
const Base = require('../base');
class RequestCommand extends Base {
prettyOutput(res, verbose = false) {
let { status, body } = res.response;
this.spinner.stop();
status = status.toString().startsWith(2)
? clc.green(status)
: clc.red(status);
new Line()
.padding(2)
.column('Status', 20, [clc.cyan])
.column('Endpoint', 20, [clc.cyan])
.output();
new Line()
.padding(2)
.column(status, 20)
.column(res.request.endpoint)
.output();
new Line().output();
jsome(verbose ? res : body);
}
async run() {
const { flags, args } = this.parse(RequestCommand);
const Beau = this.loadConfig(flags.config);
this.spinner = new Spinner(clc.yellow(`Requesting: ${args.alias}`), [
'⣾',
'⣽',
'⣻',
'⢿',
'⡿',
'⣟',
'⣯',
'⣷'
]);
try {
if (!flags['no-format']) {
this.spinner.start();
}
let res = await Beau.requests.execByAlias(args.alias);
if (flags['no-format']) {
this.log(res.response.status);
this.log(res.request.endpoint);
this.log(JSON.stringify(res.response.headers));
this.log(JSON.stringify(res.response.body));
} else {
this.prettyOutput(res, flags.verbose);
}
} catch (err) {
new Line().output();
this.spinner.stop();
this.error(err.message);
}
}
}
RequestCommand.description = `Executes a request by name.`;
RequestCommand.flags = { ...Base.flags };
RequestCommand.args = [
{
name: 'alias',
required: true,
description: `The alias of the request to execute.`
}
];
module.exports = RequestCommand;

3833
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -11,22 +11,33 @@
"test:coverage": "jest --coverage" "test:coverage": "jest --coverage"
}, },
"dependencies": { "dependencies": {
"@oclif/command": "^1.4.16",
"@oclif/config": "^1.6.13",
"@oclif/plugin-help": "^1.2.5",
"@oclif/plugin-warn-if-update-available": "^1.3.6",
"cli-color": "^1.1.0", "cli-color": "^1.1.0",
"clui": "^0.3.1", "clui": "^0.3.1",
"commander": "^2.15.1",
"deepmerge": "^2.1.0", "deepmerge": "^2.1.0",
"dotenv": "^5.0.1", "dotenv": "^5.0.1",
"globby": "^8.0.1",
"js-yaml": "^3.11.0", "js-yaml": "^3.11.0",
"jsome": "^2.5.0", "jsome": "^2.5.0",
"request": "^2.85.0", "request": "^2.85.0",
"request-promise-native": "^1.0.5", "request-promise-native": "^1.0.5",
"requireg": "^0.1.6", "requireg": "^0.1.6"
"update-notifier": "^2.5.0"
}, },
"repository": "git@github.com:Seich/Beau.git", "repository": "git@github.com:Seich/Beau.git",
"devDependencies": { "devDependencies": {
"jest": "^22.4.0" "jest": "^22.4.0"
}, },
"oclif": {
"commands": "./bin/cli/commands",
"bin": "beau",
"plugins": [
"@oclif/plugin-help",
"@oclif/plugin-warn-if-update-available"
]
},
"jest": { "jest": {
"testEnvironment": "node", "testEnvironment": "node",
"notify": true "notify": true