1 | #!/usr/bin/env node
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | const fs = require('fs');
|
6 | const path = require('path');
|
7 | const forEachProperty = require('for-each-property');
|
8 | const inspectProperty = require('inspect-property');
|
9 | const cliss = require('cliss');
|
10 | const findUp = require('find-up');
|
11 |
|
12 | function requireMainModule(currentPath) {
|
13 | let packageJson = path.resolve(path.join(currentPath, '/package.json'));
|
14 |
|
15 | if (!fs.existsSync(packageJson)) {
|
16 | packageJson = findUp.sync('package.json', {
|
17 | cwd: packageJson
|
18 | });
|
19 | }
|
20 |
|
21 | const modulePath = path.dirname(packageJson);
|
22 | return {
|
23 | moduleRef: require(modulePath),
|
24 | packageJson: require(packageJson)
|
25 | };
|
26 | }
|
27 |
|
28 | function magicli({ commands = {}, validateRequiredParameters = false, help = {}, version = {}, pipe = {}, enumerability = 'enumerable', subcommandDelimiter = '-', modulePath } = {}) {
|
29 | const { moduleRef, packageJson } = requireMainModule(modulePath || require.main.filename);
|
30 | const moduleName = packageJson.name;
|
31 | const moduleVersion = packageJson.version;
|
32 | const moduleDescription = packageJson.description;
|
33 | const moduleApi = inspectProperty(moduleRef, null, { enumerability, delimiter: subcommandDelimiter, inspectProperties: true });
|
34 |
|
35 |
|
36 | const cliSpec = { name: moduleName, version: moduleVersion, description: moduleDescription };
|
37 |
|
38 |
|
39 | if (moduleApi.type === 'function') {
|
40 | cliSpec.action = moduleApi.functionInspection.fn;
|
41 |
|
42 | if (commands[moduleName]) {
|
43 | Object.assign(cliSpec, commands[moduleName]);
|
44 | }
|
45 | }
|
46 |
|
47 |
|
48 | forEachProperty(moduleApi.properties, (value, key) => {
|
49 | if (value.type !== 'function' || value.isClass) {
|
50 | return;
|
51 | }
|
52 |
|
53 | cliSpec.commands = cliSpec.commands || [];
|
54 | const subcommand = {
|
55 | name: key,
|
56 | action: value.functionInspection.fn
|
57 | };
|
58 |
|
59 | if (commands[subcommand.name]) {
|
60 | Object.assign(subcommand, commands[subcommand.name]);
|
61 | }
|
62 |
|
63 | cliSpec.commands.push(subcommand);
|
64 | });
|
65 |
|
66 | cliss(cliSpec, { options: { validateRequiredParameters }, help, version, pipe });
|
67 | }
|
68 |
|
69 | module.exports = magicli; |
\ | No newline at end of file |