diff --git a/cli.js b/cli.js index fa38372e8..76b3d3ec6 100644 --- a/cli.js +++ b/cli.js @@ -1,5 +1,6 @@ const path = require('path'); const config = require('config'); +const { version } = require('./package.json'); function load(command = 'help') { const file = path.join(__dirname, 'lib', `${command}.js`); @@ -14,8 +15,10 @@ function load(command = 'help') { } module.exports = function(cmd, args, opts = {}) { + if (opts.version && !cmd) return Promise.resolve(version); + try { - const command = load(cmd); + const command = load(opts.help ? 'help' : cmd); return command.run({ args, opts }); } catch(e) { return Promise.reject(e); diff --git a/rdme.js b/rdme.js index 6c5855122..f76a99f2f 100755 --- a/rdme.js +++ b/rdme.js @@ -1,6 +1,17 @@ #! /usr/bin/env node require('colors'); -const parseArgs = require('minimist')(process.argv.slice(2)); + +const parseArgs = require('minimist')(process.argv.slice(2), { + alias: { + // Allows --version, -v, -V + v: 'version', + V: 'version', + + // // Allows --help, -h, -H + h: 'help', + H: 'help', + } +}); require('./cli')(parseArgs._[0], parseArgs._.slice(1), parseArgs) .then(() => process.exit()) diff --git a/test/cli.test.js b/test/cli.test.js index 3863adc69..9a65c1887 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -1,22 +1,33 @@ const assert = require('assert'); +const minimist = require('minimist'); const cli = require('../cli'); +const { version } = require('../package.json'); describe('cli', () => { - let error; - beforeAll(() => { - error = { console }; - }); - - afterAll(() => { - console.error = error; - }); - it('command not found', done => cli('notARealCommand').catch(e => { assert.equal(e.message.includes('Command not found'), true) return done(); })); + describe('--version', () => { + it('should return version from package.json', () => + cli('', [], minimist(['--version'])).then(v => assert.equal(v, version))); + + // This is necessary because we use --version for other commands like `docs` + it('should only return version if no command', () => + cli('no-such-command', [], minimist(['--version'])).then(() => { + throw new Error('Should not get here'); + }).catch(() => { + // This can be ignored as it's just going to be + // a command not found error + })); + }); + + describe('--help', () => { + it('should print help and not error', () => + cli('', [], minimist(['--help'])) + ); }); });