juisy 2.0.0-beta.0 → 2.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +661 -0
  2. package/bin/cli/cli.js +6 -4
  3. package/bin/cli/cmds/index.js +10 -10
  4. package/bin/cli/cmds/private/docs/generate-api.js +31 -0
  5. package/bin/cli/cmds/{docs → private/docs}/index.js +4 -6
  6. package/bin/cli/cmds/{print-globals.js → public/print-globals.js} +0 -1
  7. package/bin/cli/index.js +1 -1
  8. package/bin/scripts/prepare.js +22 -0
  9. package/dist/DataExporter.d.ts +6 -0
  10. package/dist/cli/CLIFactory.d.ts +48 -11
  11. package/dist/cli/Command.d.ts +23 -13
  12. package/dist/cli/GlobalSettings.schema.json +1 -0
  13. package/dist/cli/InterfaceUtils.d.ts +8 -2
  14. package/dist/cli/OutputUtils.d.ts +3 -3
  15. package/dist/cli/Plugin.d.ts +21 -0
  16. package/dist/cli/extract-usage.d.ts +7 -1
  17. package/dist/cli/index.d.ts +18 -6
  18. package/dist/cli/index.js +1252 -129
  19. package/dist/cli/plugins/command-handler-injections/augment.d.ts +29 -0
  20. package/dist/cli/{command-visitors → plugins/command-handler-injections/command-visitors}/command-handler-injections.d.ts +1 -1
  21. package/dist/cli/plugins/command-handler-injections/index.d.ts +3 -0
  22. package/dist/cli/plugins/command-meta/augment.d.ts +23 -0
  23. package/dist/cli/{command-visitors/get-command-meta.d.ts → plugins/command-meta/command-visitors/command-meta.d.ts} +1 -1
  24. package/dist/cli/plugins/command-meta/index.d.ts +3 -0
  25. package/dist/cli/plugins/default-command-fallbacks/augment.d.ts +3 -0
  26. package/dist/cli/plugins/default-command-fallbacks/command-visitors/default-command-fallbacks.d.ts +10 -0
  27. package/dist/cli/plugins/default-command-fallbacks/index.d.ts +3 -0
  28. package/dist/cli/plugins/load-env-file/augment.d.ts +9 -0
  29. package/dist/cli/plugins/load-env-file/index.d.ts +3 -0
  30. package/dist/cli/plugins/private-commands/augment.d.ts +6 -0
  31. package/dist/cli/{command-visitors → plugins/private-commands/command-visitors}/private-command.d.ts +1 -1
  32. package/dist/cli/plugins/private-commands/index.d.ts +3 -0
  33. package/dist/cli/plugins/register-bump-version-command/cmds/index.d.ts +3 -0
  34. package/dist/cli/plugins/register-bump-version-command/index.d.ts +3 -0
  35. package/dist/cli/plugins/register-changelog-command/augment.d.ts +110 -0
  36. package/dist/cli/plugins/register-changelog-command/cmds/index.d.ts +3 -0
  37. package/dist/cli/plugins/register-changelog-command/index.d.ts +3 -0
  38. package/dist/cli/plugins/register-docs-commands/augment.d.ts +18 -0
  39. package/dist/cli/plugins/register-docs-commands/cmds/generate-api.d.ts +3 -0
  40. package/dist/cli/plugins/register-docs-commands/cmds/generate-cli.d.ts +3 -0
  41. package/dist/cli/plugins/register-docs-commands/cmds/generate-readme.d.ts +3 -0
  42. package/dist/cli/plugins/register-docs-commands/cmds/index.d.ts +3 -0
  43. package/dist/cli/plugins/register-docs-commands/index.d.ts +3 -0
  44. package/dist/cli/plugins/register-git-hooks-commands/augment.d.ts +40 -0
  45. package/dist/cli/plugins/register-git-hooks-commands/cmds/index.d.ts +3 -0
  46. package/dist/cli/plugins/register-git-hooks-commands/cmds/reset.d.ts +3 -0
  47. package/dist/cli/plugins/register-git-hooks-commands/cmds/sync.d.ts +3 -0
  48. package/dist/cli/plugins/register-git-hooks-commands/index.d.ts +3 -0
  49. package/dist/cli/plugins/register-lint-commands/augment.d.ts +39 -0
  50. package/dist/cli/plugins/register-lint-commands/cmds/commit.d.ts +3 -0
  51. package/dist/cli/plugins/register-lint-commands/cmds/default.d.ts +3 -0
  52. package/dist/cli/plugins/register-lint-commands/cmds/markdown.d.ts +3 -0
  53. package/dist/cli/plugins/register-lint-commands/cmds/staged.d.ts +3 -0
  54. package/dist/cli/plugins/register-lint-commands/index.d.ts +3 -0
  55. package/dist/cli/plugins/register-lint-commands/settings.d.ts +11 -0
  56. package/dist/cli/plugins/register-lint-commands/types.d.ts +26 -0
  57. package/dist/cli/plugins/register-release-command/augment.d.ts +9 -0
  58. package/dist/cli/plugins/register-release-command/cmds/index.d.ts +3 -0
  59. package/dist/cli/plugins/register-release-command/index.d.ts +3 -0
  60. package/dist/cli/plugins/register-test-command/cmds/index.d.ts +3 -0
  61. package/dist/cli/plugins/register-test-command/index.d.ts +3 -0
  62. package/dist/cli/types.d.ts +73 -44
  63. package/dist/cli/utils.d.ts +3 -3
  64. package/dist/eject.d.ts +11 -4
  65. package/dist/index.d.ts +8 -2
  66. package/dist/index.js +80 -76
  67. package/dist/project-globals.d.ts +9 -0
  68. package/dist/templater/index.d.ts +6 -1
  69. package/dist/templater/index.js +18 -31
  70. package/dist/templater/markdown-templater/ReadmeTemplater.d.ts +28 -28
  71. package/dist/templater/markdown-templater/index.d.ts +3 -0
  72. package/dist/templater/types.d.ts +6 -0
  73. package/dist/utils/misc.d.ts +1 -1
  74. package/package.json +201 -179
  75. package/README.md +0 -211
  76. package/bin/cli/cmds/changelog.js +0 -41
  77. package/bin/cli/cmds/docs/generate-api.js +0 -22
  78. package/bin/cli/cmds/docs/generate-cli.js +0 -11
  79. package/bin/cli/cmds/docs/generate-readme.js +0 -11
  80. package/bin/cli/cmds/docs/lint.js +0 -42
  81. package/bin/cli/cmds/eject.js +0 -28
  82. package/bin/cli/cmds/git-hooks/index.js +0 -20
  83. package/bin/cli/cmds/git-hooks/reset.js +0 -48
  84. package/bin/cli/cmds/git-hooks/sync.js +0 -19
  85. package/bin/cli/cmds/release.js +0 -231
  86. package/bin/cli/lib/docs/generate-api-doc.js +0 -78
  87. package/bin/cli/lib/version/update-version.js +0 -52
  88. package/bin/scripts/commit-msg.js +0 -32
  89. package/bin/scripts/pre-commit.js +0 -24
  90. package/dist/cli/command-visitors/index.d.ts +0 -9
  91. package/src/index.js +0 -507
  92. package/template/CHANGELOG.md +0 -0
  93. package/template/bin/cli/cli.js +0 -27
  94. package/template/bin/cli/cmds/changelog.js +0 -71
  95. package/template/bin/cli/cmds/docs.js +0 -30
  96. package/template/bin/cli/cmds/docs_cmds/generate-api.js +0 -75
  97. package/template/bin/cli/cmds/docs_cmds/generate-readme.js +0 -51
  98. package/template/bin/cli/cmds/git-hooks.js +0 -30
  99. package/template/bin/cli/cmds/git_hooks_cmds/reset.js +0 -76
  100. package/template/bin/cli/cmds/git_hooks_cmds/sync.js +0 -44
  101. package/template/bin/cli/cmds/release.js +0 -219
  102. package/template/bin/cli/index.js +0 -7
  103. package/template/bin/cli/lib/docs/generate-api-doc.js +0 -33
  104. package/template/bin/cli/lib/release/generate-release-note.js +0 -3
  105. package/template/bin/cli/lib/version/update-version.js +0 -51
  106. package/template/bin/scripts/commit-msg.js +0 -42
  107. package/template/bin/scripts/pre-commit.js +0 -32
  108. package/template/docs/api/docs.config.js +0 -10
  109. package/template/docs/readme/config.js +0 -22
  110. package/template/docs/readme/readme.js +0 -70
  111. package/template/docs/readme/template.md +0 -53
  112. /package/bin/cli/cmds/{test.js → private/test.js} +0 -0
  113. /package/bin/cli/cmds/{squeeze.js → public/squeeze.js} +0 -0
@@ -1,78 +0,0 @@
1
- // import fs from 'fs-extra'
2
- // import jsdoc2md from 'jsdoc-to-markdown'
3
- import path from 'path'
4
- import { InterfaceUtils, OutputUtils } from '#juisy/cli'
5
-
6
- // utils
7
- const { rootDir } = InterfaceUtils
8
- const {
9
- $style,
10
- log,
11
- step,
12
- substep
13
- } = OutputUtils
14
-
15
- // Default config
16
- const defaultConfig = {
17
- outputDir: 'documentation',
18
- jsdoc: {
19
- configPath: undefined
20
- },
21
- jsdoc2md: {
22
- partial: []
23
- }
24
- }
25
-
26
- /**
27
- * Generate API doc function
28
- * @param {object} [options = {}] - The options object
29
- * @returns {void}
30
- */
31
- export default async function generateApiDoc (options = {}) {
32
- // Process options
33
- options = merge(defaultConfig, options)
34
-
35
- const docs = {
36
- API: {
37
- sourcePath: path.resolve(rootDir, './src/index.js'),
38
- destPath: path.resolve(rootDir, './documentation/api.md')
39
- },
40
- Utils: {
41
- sourcePath: path.resolve(rootDir, './src/utils/index.js'),
42
- destPath: path.resolve(rootDir, './documentation/utils.md')
43
- }
44
- }
45
-
46
- /**
47
- * Generate doc
48
- */
49
- step('Generate doc')
50
-
51
- // // Loop on docs
52
- // for (const name in docs) {
53
- // const sourcePath = docs[name].sourcePath
54
- // const destPath = docs[name].destPath
55
-
56
- // let genResult
57
- // await wait(`Generating "${name}"`, async () => {
58
- // genResult = await jsdoc2md.render({
59
- // 'no-cache': Boolean(options.jsdoc.configPath),
60
- // files: sourcePath,
61
- // template: `# ${name} documentation\n\n{{>main}}`,
62
- // partial: options.jsdoc2md.partial,
63
- // configure: options.jsdoc.configPath
64
- // })
65
- // })
66
- // // f*cking windows compat:
67
- // // jsdoc2md will generate CR (\r) character for @example blocks content line endings
68
- // genResult = genResult.replace(/\r(\n)?/g, '\n')
69
- // // Write output
70
- // await wait(`Writing file "${path.basename(destPath)}"`, async () => {
71
- // await fs.writeFile(destPath, genResult, { encoding: 'utf8' })
72
- // })
73
- // substep(`File "${path.basename(destPath)}" successfuly generated`)
74
- // }
75
-
76
- substep($style.green('✔ Success'), { last: true })
77
- log() // Blank line
78
- }
@@ -1,52 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const juisy = require('../../../../src')
4
-
5
- const {
6
- $style,
7
- error,
8
- step,
9
- substep,
10
- run,
11
- wait
12
- } = juisy.utils
13
-
14
- const rootDir = path.resolve(__dirname, '../../../../')
15
-
16
- // File paths
17
- const filePaths = {
18
- packageJson: path.resolve(rootDir, './package.json')
19
- }
20
- // Get package.json content
21
- const packageJson = require(filePaths.packageJson)
22
-
23
- /**
24
- * Update version in necessary files
25
- * @param {string} version - The version
26
- * @return {void}
27
- */
28
- module.exports = async function updateVersion (version) {
29
- // Update version for each file
30
- packageJson.version = version
31
-
32
- /**
33
- * Update files
34
- */
35
- step('Updating version in necessary files')
36
- // Update package.json
37
- try {
38
- fs.writeFileSync(filePaths.packageJson, JSON.stringify(packageJson, null, 4), 'utf8')
39
- } catch (e) {
40
- error('Unable to update package.json file', e)
41
- }
42
- substep($style.green('✔ package.json successfuly updated'))
43
- // Updating package-lock
44
- await wait('Updating package-lock.json', async () => {
45
- try {
46
- await run('npm', [ 'install', '--prefer-offline' ], { stdio: 'pipe', cwd: rootDir })
47
- } catch (e) {
48
- error('Unable to update package-lock.json file', e)
49
- }
50
- })
51
- substep($style.green('✔ package-lock.json successfuly updated'), { last: true })
52
- }
@@ -1,32 +0,0 @@
1
- import run from 'execa'
2
- /**
3
- * commit-msg git hook
4
- */
5
- ;(async function () {
6
- console.log('Git hook: commit-msg')
7
-
8
- // Get git commit msg path from args
9
- const args = process.argv.slice(2)
10
- const gitMsgPath = args[0]
11
-
12
- try {
13
- // original is: npx --no -- commitlint --edit ${1}
14
- // we replace "${1}" by gitMsgPath arg
15
- await run('npx', [
16
- '--no',
17
- '--',
18
- 'commitlint',
19
- '--edit',
20
- gitMsgPath
21
- ])
22
- } catch (e) {
23
- console.error('❌ Git hook: "commit-msg" failed. Please check ./COMMIT_CONVENTION.md for more informations.', e)
24
- console.log() // blank line
25
- process.exit(1) // Abort with error
26
- }
27
-
28
- // Everything is okay
29
- console.log('✔ Git hook: "commit-msg" passed')
30
-
31
- console.log() // blank line
32
- })()
@@ -1,24 +0,0 @@
1
- import run from 'execa'
2
-
3
- /**
4
- * Pre commit git hook
5
- */
6
- ;(async function () {
7
- console.log('Git hook: pre-commit')
8
-
9
- try {
10
- // npx lint-staged
11
- await run('npx', [
12
- 'lint-staged'
13
- ], { stdio: 'pipe' })
14
- } catch (e) {
15
- console.error('Git hook: "commit-msg" error: ', e)
16
- console.log() // blank line
17
- process.exit(1)
18
- }
19
-
20
- // Everything is okay
21
- console.log('✔ Git hook: "pre-commit" passed')
22
-
23
- console.log() // blank line
24
- })()
@@ -1,9 +0,0 @@
1
- import * as commandHandlerInjections from './command-handler-injections';
2
- import * as getCommandMeta from './get-command-meta';
3
- import * as privateCommand from './private-command';
4
- declare const _default: {
5
- commandHandlerInjections: typeof commandHandlerInjections;
6
- getCommandMeta: typeof getCommandMeta;
7
- privateCommand: typeof privateCommand;
8
- };
9
- export default _default;
package/src/index.js DELETED
@@ -1,507 +0,0 @@
1
- /**
2
- * @file Entry point
3
- * @description @hperchec/juisy [/src/index.js]
4
- * @author Hervé Perchec
5
- */
6
-
7
- /**
8
- * @module juisy
9
- * @type {object}
10
- * @typicalname juisy
11
- * @description
12
- * From: @hperchec/juisy@{{{{VERSION}}}}
13
- * @example
14
- * const juisy = require('@hperchec/juisy')
15
- */
16
-
17
- const getCallerFile = require('get-caller-file')
18
- const Yargs = require('yargs/yargs')
19
- const utils = require('./utils')
20
-
21
- /**
22
- * @param {Function} builder - The CLI builder function
23
- * @returns {Function} A function that takes optional argv as first parameter and returns {@link CLI CLI}
24
- * @description
25
- * Creates a CLI (yargs instance) factory
26
- * @example
27
- * const { createCli } = require('@hperchec/juisy')
28
- *
29
- * const cli = createCli(cli => cli
30
- * .scriptName('my-juicy-cli')
31
- * .usage('Usage: $0 <command> [<options>]')
32
- * )
33
- *
34
- * const argv = process.argv.slice(2)
35
- *
36
- * // Parse argv
37
- * cli().parse(argv)
38
- */
39
- exports.createCli = function (builder) {
40
- return function (argv) {
41
- const cli = initYargs(Yargs(argv))
42
- return builder(cli)
43
- }
44
- }
45
-
46
- /**
47
- * @typedef {object} CommandDoclet
48
- * @category types
49
- * @description
50
- * Command documentation object returned by {@link module:juisy.cliTools.extractUsage extractUsage} tool.
51
- * @property {string} command - The command
52
- * @property {string[]} args - The command args
53
- * @property {object} aliases - The yargs instance `aliasMap` reference
54
- * @property {object} deprecated - If command is deprecated
55
- * @property {module:juisy~ExtractedUsage} extractedUsage - The extracted usage object from yargs usage instance
56
- * @property {string} rawUsage - The usage output as string (as if `--help` option passed)
57
- * @property {?object} [children] - The child commands
58
- */
59
-
60
- /**
61
- * @typedef {object} ExtractedUsage
62
- * @category types
63
- * @description
64
- * Type of {@link module:juisy~CommandDoclet CommandDoclet} `extractedUsage` property
65
- * @property {object} demandedCommands - Same as yargs instance `getDemandedCommands` method
66
- * @property {object} demandedOptions - Same as yargs instance `getDemandedOptions` method
67
- * @property {object} deprecatedOptions - Same as yargs instance `getDeprecatedOptions` method
68
- * @property {object} groups - Same as yargs instance `getGroups` method
69
- * @property {object} options - Same as yargs instance `getOptions` method
70
- * @property {string[]} usages - Same as yargs usage instance `getUsage` method
71
- * @property {object} commands - The result of yargs usage instance `getCommands` method as object.
72
- * While the UsageInstance commands items are defined as follow: `[cmd, description, isDefault, aliases, deprecated]`,
73
- * we cast it to an object like: `{cmd, description, isDefault, aliases, deprecated}`.
74
- */
75
-
76
- /**
77
- * @alias module:juisy.cliTools
78
- * @type {object}
79
- * @description
80
- * CLI tools
81
- */
82
- const cliTools = exports.cliTools = {
83
- /**
84
- * @async
85
- * @param {Function} cliFactory - The cli factory function returned by createCli method
86
- * @param {boolean} [recursive = false] - Recursive mode (parse child commands)
87
- * @param {string[]} [args = [""]] - The base args to pass as parseAsync first parameter
88
- * @param {string} [locale = en] - The locale
89
- * @returns {Promise<module:juisy~CommandDoclet>} The extracted command doclet
90
- * @fulfil {module:juisy~CommandDoclet}
91
- * @description
92
- * Extract usage object from CLI (Yargs) instance factory
93
- * @example
94
- * **Note**: don't call `cli()`, pass the factory.
95
- *
96
- * ```js
97
- * const { createCli, cliTools } = require('@hperchec/juisy')
98
- *
99
- * const cli = createCli(cli => cli
100
- * // ...
101
- * )
102
- *
103
- * cliTools.extractUsage(cli)
104
- * ```
105
- *
106
- * Recursively extract usage:
107
- *
108
- * ```js
109
- * await cliTools.extractUsage(cli, true)
110
- * ```
111
- * With base args:
112
- *
113
- * ```js
114
- * await cliTools.extractUsage(cli, false, [ 'my-command' ])
115
- * ```
116
- *
117
- * Change locale:
118
- *
119
- * ```js
120
- * await cliTools.extractUsage(cli, undefined, undefined, 'fr')
121
- * ```
122
- */
123
- async extractUsage (cliFactory, recursive = false, args = [ '' ], locale = 'en') {
124
- const innerYargs = cliFactory([ '' ]) // empty argv
125
- // Set locale
126
- innerYargs.locale(locale)
127
-
128
- // Init doclet object extracted usage object
129
- const doclet = {
130
- command: undefined,
131
- args: undefined,
132
- aliases: undefined,
133
- // deprecated: false,
134
- extractedUsage: undefined,
135
- rawUsage: undefined,
136
- children: recursive ? {} : undefined
137
- }
138
-
139
- const parseCallback = function (err, argv, output) {
140
- if (err) throw err
141
- // this is the yargs instance with temporary parse state
142
- const self = this
143
- // Set doclet args
144
- doclet.args = argv._
145
- // Set doclet command
146
- doclet.command = argv._[argv._.length - 1] // is there a better way?
147
- // Set rawUsage
148
- doclet.rawUsage = output
149
- // Extracted usage
150
- const extractedUsage = doclet.extractedUsage = {}
151
-
152
- extractedUsage.demandedCommands = self.getDemandedCommands()
153
- extractedUsage.demandedOptions = self.getDemandedOptions()
154
- extractedUsage.deprecatedOptions = self.getDeprecatedOptions()
155
- extractedUsage.groups = self.getGroups()
156
- extractedUsage.options = self.getOptions()
157
- // extractedUsage.examples = examples // @todo: No API for UsageInstance examples?
158
-
159
- const internalMethods = self.getInternalMethods()
160
- const usageInstance = internalMethods.getUsageInstance()
161
-
162
- extractedUsage.usages = usageInstance.getUsage()
163
-
164
- const commandInstance = internalMethods.getCommandInstance()
165
-
166
- // Set doclet aliases
167
- doclet.aliases = commandInstance.aliasMap
168
-
169
- const childCommandsFromHandlers = commandInstance.handlers
170
- const childCommandsFromUsage = usageInstance.getCommands()
171
-
172
- extractedUsage.commands = Object.keys(childCommandsFromHandlers).reduce((accumulator, handlerKey) => {
173
- // the UsageInstance commands item is like: [cmd, description, isDefault, aliases, deprecated]
174
- const [ cmd, description, isDefault, aliases, deprecated ] = childCommandsFromUsage.find((command) => {
175
- return command[0] === childCommandsFromHandlers[handlerKey].original
176
- })
177
- accumulator[handlerKey] = { cmd, description, isDefault, aliases, deprecated }
178
- return accumulator
179
- }, {})
180
- }
181
-
182
- // Parse async command
183
- const parsed = await innerYargs.parseAsync(args, { help: true }, parseCallback) // eslint-disable-line no-unused-vars
184
-
185
- // If recursive, loop on child commands
186
- if (recursive) {
187
- for (const childCommand in doclet.extractedUsage.commands) {
188
- // Recursively call extractUsage method
189
- doclet.children[childCommand] = await cliTools.extractUsage(
190
- cliFactory,
191
- true,
192
- [ ...(args.filter(a => a !== '')), childCommand ],
193
- locale
194
- )
195
- }
196
- }
197
-
198
- return doclet
199
- }
200
- }
201
-
202
- /**
203
- * @type {object}
204
- * @description
205
- * Juisy utils. See [utils](./utils.md) documentation.
206
- */
207
- exports.utils = utils
208
-
209
- /**
210
- * @ignore
211
- * @param {Yargs} yargs - The yargs instance
212
- * @returns {CLI} The initialized yargs as CLI
213
- */
214
- function initYargs (yargs) {
215
- // Private properties
216
- yargs._isPrivate = false
217
- yargs._globalCommandVisitors = {}
218
- yargs._globalCommandVisitorsEnabled = new Set([])
219
- yargs._meta = {}
220
-
221
- // Methods
222
- const originalCommandDirMethod = yargs.commandDir
223
- yargs.originalCommandDir = originalCommandDirMethod
224
- yargs.commandDir = commandDir
225
- yargs.globalCommandVisitor = globalCommandVisitor
226
- yargs.globalCommandVisitorOptions = globalCommandVisitorOptions
227
- yargs.hasGlobalCommandVisitor = hasGlobalCommandVisitor
228
- yargs.disableGlobalCommandVisitors = disableGlobalCommandVisitors
229
- yargs.enableGlobalCommandVisitors = enableGlobalCommandVisitors
230
- yargs.isPrivate = isPrivate
231
- yargs.getMeta = getMeta
232
-
233
- return yargs
234
- .globalCommandVisitor('private-command-visitor', privateCommandVisitor, privateCommandVisitor.options)
235
- .globalCommandVisitor('get-meta-command-visitor', getMetaCommandVisitor, getMetaCommandVisitor.options)
236
- .strict() // disallow unknow command
237
- .help() // Enable help
238
- }
239
-
240
- /**
241
- * @typedef {Yargs} CLI
242
- * @typicalname cli
243
- * @category types
244
- * @description
245
- * CLI object returned by cli factory from {@link module:juisy.createCli createCli} method.
246
- *
247
- * It has all inherited properties and methods from [yargs](https://github.com/yargs/yargs) instance plus the following:
248
- */
249
-
250
- /**
251
- * @alias module:juisy~CLI#commandDir
252
- * @param {string} dir - Same as yargs `commandDir` argument
253
- * @param {object} [options] - Same as yargs `commandDir` options
254
- * @returns {CLI} Returns the CLI (yargs) instance
255
- * @description
256
- * See [yargs.commandDir](https://yargs.js.org/docs/#api-reference-commanddirdirectory-opts) documentation.
257
- */
258
- function commandDir (dir, options = {}) {
259
- const self = this // this is yargs instance
260
- // Is options.visit set?
261
- const visitor = options.visit || (cmdObj => cmdObj)
262
-
263
- // Add directory with wrapped visit option
264
- self.getInternalMethods().getCommandInstance().addDirectory(dir, require, getCallerFile(), {
265
- ...options,
266
- visit: function (commandObject, pathToFile, filename) {
267
- let failOnFalsyReturn
268
- // Loop on enabled global command visitors
269
- for (const name of self._globalCommandVisitorsEnabled) {
270
- const globalVisitor = self._globalCommandVisitors[name]
271
- // Call global visitor: fail on falsy returned value
272
- if (!globalVisitor(commandObject, pathToFile, filename, self, globalVisitor.options)) {
273
- failOnFalsyReturn = true
274
- }
275
- }
276
-
277
- // Then custom visitor
278
- const customVisitorResult = visitor(commandObject, pathToFile, filename, self)
279
-
280
- return failOnFalsyReturn ? false : customVisitorResult
281
- }
282
- })
283
- return self
284
- }
285
-
286
- /**
287
- * @callback module:juisy~CLI~globalCommandVisitorCallback
288
- * @category callback
289
- * @param {object} commandObject - The command object
290
- * @param {string} pathToFile - The path to file
291
- * @param {string} filename - The filename
292
- * @param {CLI} yargs - The current CLI instance
293
- * @param {object} options - The default options to set
294
- * @description
295
- * Custom global command visitor callback.
296
- *
297
- * Takes same parameters as original yargs commandDir "visit" option, plus yargs itself and visitor options.
298
- */
299
-
300
- /**
301
- * @alias module:juisy~CLI#globalCommandVisitor
302
- * @param {string} name - The visitor unique name
303
- * @param {module:juisy~CLI~globalCommandVisitorCallback} visitor - The visitor function
304
- * @param {object} defaultOptions - The default visitor options object
305
- * @returns {CLI} Returns the CLI (yargs) instance
306
- * @description
307
- * Set a global command visitor function
308
- * @example
309
- * const visitor = function (commandObject, pathToFile, filename, yargs, options) {
310
- * const { foo } = options
311
- * console.log('The "foo" option : ', foo)
312
- * return commandObject
313
- * }
314
- *
315
- * cli.globalCommandVisitor('my-custom-visitor', visitor, { foo: 'bar' })
316
- * .commandDir('cmds_dir')
317
- * // => will console log foo option for each command visited
318
- */
319
- function globalCommandVisitor (name, visitor, defaultOptions = {}) {
320
- this._globalCommandVisitors[name] = visitor
321
- return this.enableGlobalCommandVisitors([ name ])
322
- .globalCommandVisitorOptions(name, defaultOptions)
323
- }
324
-
325
- /**
326
- * @alias module:juisy~CLI#globalCommandVisitorOptions
327
- * @param {string} name - The visitor unique name
328
- * @param {object} options - The visitor options object
329
- * @returns {CLI} Returns the CLI (yargs) instance
330
- * @description
331
- * Set global command visitor options
332
- * @example
333
- * // Overrides default options for 'my-custom-visitor'
334
- * // defined via globalCommandVisitor method
335
- * cli.globalCommandVisitorOptions('my-custom-visitor', { foo: 'baz' })
336
- */
337
- function globalCommandVisitorOptions (name, options) {
338
- this._globalCommandVisitors[name].options = {
339
- ...this._globalCommandVisitors[name].options,
340
- ...options
341
- }
342
- return this
343
- }
344
-
345
- /**
346
- * @alias module:juisy~CLI#hasGlobalCommandVisitor
347
- * @param {string} name - The visitor name
348
- * @returns {boolean} True if global command visitor is defined
349
- * @description
350
- * Check if global command visitor is defined
351
- * @example
352
- * cli.hasGlobalCommandVisitor('my-custom-visitor')
353
- */
354
- function hasGlobalCommandVisitor (name) {
355
- return Object.keys(this._globalCommandVisitors).includes(name)
356
- }
357
-
358
- /**
359
- * @alias module:juisy~CLI#disableGlobalCommandVisitors
360
- * @param {string[]} visitors - The visitor names
361
- * @returns {CLI} Returns the CLI (yargs) instance
362
- * @description
363
- * Disables global command visitors
364
- * @example
365
- * // Disables the "my-disabled-visitor" global command visitor
366
- * cli.disableGlobalCommandVisitors(['my-disabled-visitor'])
367
- */
368
- function disableGlobalCommandVisitors (visitors = []) {
369
- for (const name of visitors) {
370
- // If visitor exists
371
- if (this.hasGlobalCommandVisitor(name)) {
372
- // Enable
373
- this._globalCommandVisitorsEnabled.delete(name)
374
- } else {
375
- throw new Error('Global command visitor: "' + name + '" not defined.')
376
- }
377
- }
378
- return this
379
- }
380
-
381
- /**
382
- * @alias module:juisy~CLI#enableGlobalCommandVisitors
383
- * @param {string[]} visitors - The visitor names
384
- * @returns {CLI} Returns the CLI (yargs) instance
385
- * @description
386
- * Enables global command visitors
387
- * @example
388
- * // Enables the "my-custom-visitor" and "my-awesome-visitor"
389
- * // global command visitors
390
- * cli.enableGlobalCommandVisitors(['my-custom-visitor', 'my-awesome-visitor'])
391
- */
392
- function enableGlobalCommandVisitors (visitors = []) {
393
- for (const name of visitors) {
394
- // If visitor exists
395
- if (this.hasGlobalCommandVisitor(name)) {
396
- // Enable
397
- this._globalCommandVisitorsEnabled.add(name)
398
- } else {
399
- throw new Error('Global command visitor: "' + name + '" not defined.')
400
- }
401
- }
402
- return this
403
- }
404
-
405
- /**
406
- * @alias module:juisy~CLI#isPrivate
407
- * @returns {boolean} True if command is private
408
- * @description
409
- * Get command private status
410
- */
411
- function isPrivate () {
412
- return this._isPrivate
413
- }
414
-
415
- /**
416
- * @alias module:juisy~CLI#getMeta
417
- * @returns {object} The command meta
418
- * @description
419
- * Get the CLI instance meta
420
- * @example
421
- * cli.getMeta()
422
- */
423
- function getMeta () {
424
- return this._meta
425
- }
426
-
427
- /**
428
- * @ignore
429
- * @param {?Function} target - The target builder
430
- * @param {Function} builder - The wrap
431
- * @description
432
- * Wrap command builder (target) with builder passed as second parameter
433
- * that will be called before target. Target can be undefined
434
- */
435
- function wrapBuilder (target, builder) {
436
- // Is target set?
437
- const _target = target || (yargs => yargs)
438
- // Return wrapped builder
439
- return function (yargs) {
440
- return _target(builder(yargs))
441
- }
442
- }
443
-
444
- /**
445
- * @ignore
446
- * @param {object} commandObject - Same as yargs.commandDir "visit" option
447
- * @param {string} pathToFile - Same as yargs.commandDir "visit" option
448
- * @param {string} filename - Same as yargs.commandDir "visit" option
449
- * @param {CLI} cli - The CLI (yargs) instance
450
- * @param {object} options - The global command visitor defined options
451
- * @returns {object|boolean} False if command is private and env key is set to "private".
452
- * Otherwise, returns the commandObject with wrapped builder to tag CLI instance as private.
453
- * @description
454
- * Global command visitor to auto-set command private status
455
- */
456
- function privateCommandVisitor (commandObject, pathToFile, filename, cli, options) {
457
- const { cmdObjectProp, envKey } = options
458
- if (commandObject[cmdObjectProp]) {
459
- // Check if env key is set to 'private'
460
- if (process.env[envKey] === 'private') {
461
- // Wrap builder
462
- commandObject.builder = wrapBuilder(commandObject.builder, function (yargs) {
463
- yargs._isPrivate = true
464
- return yargs
465
- })
466
- } else {
467
- // Else, don't return command object
468
- return false
469
- }
470
- }
471
- return commandObject
472
- }
473
-
474
- privateCommandVisitor.options = {
475
- cmdObjectProp: 'private',
476
- envKey: 'CLI_ENV'
477
- }
478
-
479
- /**
480
- * @ignore
481
- * @param {object} commandObject - Same as yargs.commandDir "visit" option
482
- * @param {string} pathToFile - Same as yargs.commandDir "visit" option
483
- * @param {string} filename - Same as yargs.commandDir "visit" option
484
- * @param {CLI} cli - The CLI (yargs) instance
485
- * @param {object} options - The global command visitor defined options
486
- * @returns {object} The commandObject with wrapped builder to inject CLI instance meta.
487
- * @description
488
- * Global command visitor to auto-set command meta
489
- */
490
- function getMetaCommandVisitor (commandObject, pathToFile, filename, cli, options) {
491
- const { cmdObjectProp } = options
492
- // if prop is defined (default: "meta")
493
- if (commandObject[cmdObjectProp]) {
494
- const commandMeta = commandObject[cmdObjectProp]
495
- // Wrap builder
496
- commandObject.builder = wrapBuilder(commandObject.builder, function (yargs) {
497
- // Deep merge the meta objects with parent
498
- yargs._meta = utils.merge(yargs._meta, commandMeta)
499
- return yargs
500
- })
501
- }
502
- return commandObject
503
- }
504
-
505
- getMetaCommandVisitor.options = {
506
- cmdObjectProp: 'meta'
507
- }
File without changes