1
0
Fork 0
management/front/dkha-web-sz-main/node_modules/yargs/lib/validation.js

342 lines
9.8 KiB
JavaScript
Raw Normal View History

2023-12-28 23:41:32 +08:00
'use strict'
const argsert = require('./argsert')
2023-12-18 13:12:25 +08:00
const objFilter = require('./obj-filter')
2023-12-28 23:41:32 +08:00
const specialKeys = ['$0', '--', '_']
2023-12-18 13:12:25 +08:00
// validation-type-stuff, missing params,
// bad implications, custom checks.
2023-12-28 23:41:32 +08:00
module.exports = function validation (yargs, usage, y18n) {
2023-12-18 13:12:25 +08:00
const __ = y18n.__
const __n = y18n.__n
const self = {}
// validate appropriate # of non-option
// arguments were provided, i.e., '_'.
2023-12-28 23:41:32 +08:00
self.nonOptionCount = function nonOptionCount (argv) {
2023-12-18 13:12:25 +08:00
const demandedCommands = yargs.getDemandedCommands()
// don't count currently executing commands
const _s = argv._.length - yargs.getContext().commands.length
if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
if (_s < demandedCommands._.min) {
if (demandedCommands._.minMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null
)
} else {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min)
)
}
} else if (_s > demandedCommands._.max) {
if (demandedCommands._.maxMsg !== undefined) {
usage.fail(
// replace $0 with observed, $1 with expected.
demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null
)
} else {
usage.fail(
2023-12-28 23:41:32 +08:00
__('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max)
2023-12-18 13:12:25 +08:00
)
}
}
}
}
// validate the appropriate # of <required>
// positional arguments were provided:
2023-12-28 23:41:32 +08:00
self.positionalCount = function positionalCount (required, observed) {
2023-12-18 13:12:25 +08:00
if (observed < required) {
usage.fail(
__('Not enough non-option arguments: got %s, need at least %s', observed, required)
)
}
}
// make sure all the required arguments are present.
2023-12-28 23:41:32 +08:00
self.requiredArguments = function requiredArguments (argv) {
2023-12-18 13:12:25 +08:00
const demandedOptions = yargs.getDemandedOptions()
2023-12-28 23:41:32 +08:00
let missing = null
2023-12-18 13:12:25 +08:00
2023-12-28 23:41:32 +08:00
Object.keys(demandedOptions).forEach((key) => {
2023-12-18 13:12:25 +08:00
if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') {
missing = missing || {}
missing[key] = demandedOptions[key]
}
})
if (missing) {
const customMsgs = []
2023-12-28 23:41:32 +08:00
Object.keys(missing).forEach((key) => {
2023-12-18 13:12:25 +08:00
const msg = missing[key]
if (msg && customMsgs.indexOf(msg) < 0) {
customMsgs.push(msg)
}
})
2023-12-28 23:41:32 +08:00
const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''
2023-12-18 13:12:25 +08:00
usage.fail(__n(
'Missing required argument: %s',
'Missing required arguments: %s',
Object.keys(missing).length,
Object.keys(missing).join(', ') + customMsg
))
}
}
// check for unknown arguments (strict-mode).
2023-12-28 23:41:32 +08:00
self.unknownArguments = function unknownArguments (argv, aliases, positionalMap) {
2023-12-18 13:12:25 +08:00
const commandKeys = yargs.getCommandInstance().getCommands()
const unknown = []
const currentContext = yargs.getContext()
2023-12-28 23:41:32 +08:00
Object.keys(argv).forEach((key) => {
if (specialKeys.indexOf(key) === -1 &&
2023-12-18 13:12:25 +08:00
!positionalMap.hasOwnProperty(key) &&
!yargs._getParseContext().hasOwnProperty(key) &&
2023-12-28 23:41:32 +08:00
!aliases.hasOwnProperty(key)
) {
2023-12-18 13:12:25 +08:00
unknown.push(key)
}
})
if (commandKeys.length > 0) {
2023-12-28 23:41:32 +08:00
argv._.slice(currentContext.commands.length).forEach((key) => {
2023-12-18 13:12:25 +08:00
if (commandKeys.indexOf(key) === -1) {
unknown.push(key)
}
})
}
if (unknown.length > 0) {
usage.fail(__n(
'Unknown argument: %s',
'Unknown arguments: %s',
unknown.length,
unknown.join(', ')
))
}
}
// validate arguments limited to enumerated choices
2023-12-28 23:41:32 +08:00
self.limitedChoices = function limitedChoices (argv) {
2023-12-18 13:12:25 +08:00
const options = yargs.getOptions()
const invalid = {}
if (!Object.keys(options.choices).length) return
2023-12-28 23:41:32 +08:00
Object.keys(argv).forEach((key) => {
if (specialKeys.indexOf(key) === -1 &&
2023-12-18 13:12:25 +08:00
options.choices.hasOwnProperty(key)) {
2023-12-28 23:41:32 +08:00
[].concat(argv[key]).forEach((value) => {
2023-12-18 13:12:25 +08:00
// TODO case-insensitive configurability
2023-12-28 23:41:32 +08:00
if (options.choices[key].indexOf(value) === -1 &&
value !== undefined) {
2023-12-18 13:12:25 +08:00
invalid[key] = (invalid[key] || []).concat(value)
}
})
}
})
const invalidKeys = Object.keys(invalid)
if (!invalidKeys.length) return
2023-12-28 23:41:32 +08:00
let msg = __('Invalid values:')
invalidKeys.forEach((key) => {
msg += `\n ${__(
2023-12-18 13:12:25 +08:00
'Argument: %s, Given: %s, Choices: %s',
key,
usage.stringifiedValues(invalid[key]),
usage.stringifiedValues(options.choices[key])
2023-12-28 23:41:32 +08:00
)}`
2023-12-18 13:12:25 +08:00
})
usage.fail(msg)
}
// custom checks, added using the `check` option on yargs.
2023-12-28 23:41:32 +08:00
let checks = []
self.check = function check (f, global) {
2023-12-18 13:12:25 +08:00
checks.push({
func: f,
2023-12-28 23:41:32 +08:00
global
2023-12-18 13:12:25 +08:00
})
}
2023-12-28 23:41:32 +08:00
self.customChecks = function customChecks (argv, aliases) {
for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
const func = f.func
let result = null
2023-12-18 13:12:25 +08:00
try {
result = func(argv, aliases)
} catch (err) {
usage.fail(err.message ? err.message : err, err)
continue
}
if (!result) {
usage.fail(__('Argument check failed: %s', func.toString()))
} else if (typeof result === 'string' || result instanceof Error) {
usage.fail(result.toString(), result)
}
}
}
// check implications, argument foo implies => argument bar.
2023-12-28 23:41:32 +08:00
let implied = {}
self.implies = function implies (key, value) {
argsert('<string|object> [array|number|string]', [key, value], arguments.length)
2023-12-18 13:12:25 +08:00
if (typeof key === 'object') {
2023-12-28 23:41:32 +08:00
Object.keys(key).forEach((k) => {
2023-12-18 13:12:25 +08:00
self.implies(k, key[k])
})
} else {
yargs.global(key)
2023-12-28 23:41:32 +08:00
if (!implied[key]) {
implied[key] = []
}
if (Array.isArray(value)) {
value.forEach((i) => self.implies(key, i))
} else {
implied[key].push(value)
}
2023-12-18 13:12:25 +08:00
}
}
2023-12-28 23:41:32 +08:00
self.getImplied = function getImplied () {
2023-12-18 13:12:25 +08:00
return implied
}
2023-12-28 23:41:32 +08:00
self.implications = function implications (argv) {
2023-12-18 13:12:25 +08:00
const implyFail = []
2023-12-28 23:41:32 +08:00
Object.keys(implied).forEach((key) => {
2023-12-18 13:12:25 +08:00
const origKey = key
2023-12-28 23:41:32 +08:00
;(implied[key] || []).forEach((value) => {
let num
let key = origKey
const origValue = value
// convert string '1' to number 1
num = Number(key)
key = isNaN(num) ? key : num
if (typeof key === 'number') {
// check length of argv._
key = argv._.length >= key
} else if (key.match(/^--no-.+/)) {
// check if key doesn't exist
key = key.match(/^--no-(.+)/)[1]
key = !argv[key]
} else {
// check if key exists
key = argv[key]
}
2023-12-18 13:12:25 +08:00
2023-12-28 23:41:32 +08:00
num = Number(value)
value = isNaN(num) ? value : num
2023-12-18 13:12:25 +08:00
2023-12-28 23:41:32 +08:00
if (typeof value === 'number') {
value = argv._.length >= value
} else if (value.match(/^--no-.+/)) {
value = value.match(/^--no-(.+)/)[1]
value = !argv[value]
} else {
value = argv[value]
}
if (key && !value) {
implyFail.push(` ${origKey} -> ${origValue}`)
}
})
2023-12-18 13:12:25 +08:00
})
if (implyFail.length) {
2023-12-28 23:41:32 +08:00
let msg = `${__('Implications failed:')}\n`
2023-12-18 13:12:25 +08:00
2023-12-28 23:41:32 +08:00
implyFail.forEach((value) => {
msg += (value)
2023-12-18 13:12:25 +08:00
})
usage.fail(msg)
}
}
2023-12-28 23:41:32 +08:00
let conflicting = {}
self.conflicts = function conflicts (key, value) {
argsert('<string|object> [array|string]', [key, value], arguments.length)
2023-12-18 13:12:25 +08:00
if (typeof key === 'object') {
2023-12-28 23:41:32 +08:00
Object.keys(key).forEach((k) => {
2023-12-18 13:12:25 +08:00
self.conflicts(k, key[k])
})
} else {
yargs.global(key)
2023-12-28 23:41:32 +08:00
if (!conflicting[key]) {
conflicting[key] = []
}
if (Array.isArray(value)) {
value.forEach((i) => self.conflicts(key, i))
} else {
conflicting[key].push(value)
}
2023-12-18 13:12:25 +08:00
}
}
2023-12-28 23:41:32 +08:00
self.getConflicting = () => conflicting
self.conflicting = function conflictingFn (argv) {
Object.keys(argv).forEach((key) => {
if (conflicting[key]) {
conflicting[key].forEach((value) => {
// we default keys to 'undefined' that have been configured, we should not
// apply conflicting check unless they are a value other than 'undefined'.
if (value && argv[key] !== undefined && argv[value] !== undefined) {
usage.fail(__('Arguments %s and %s are mutually exclusive', key, value))
}
})
2023-12-18 13:12:25 +08:00
}
})
}
2023-12-28 23:41:32 +08:00
self.recommendCommands = function recommendCommands (cmd, potentialCommands) {
2023-12-18 13:12:25 +08:00
const distance = require('./levenshtein')
const threshold = 3 // if it takes more than three edits, let's move on.
2023-12-28 23:41:32 +08:00
potentialCommands = potentialCommands.sort((a, b) => b.length - a.length)
2023-12-18 13:12:25 +08:00
2023-12-28 23:41:32 +08:00
let recommended = null
let bestDistance = Infinity
for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
const d = distance(cmd, candidate)
2023-12-18 13:12:25 +08:00
if (d <= threshold && d < bestDistance) {
bestDistance = d
recommended = candidate
}
}
if (recommended) usage.fail(__('Did you mean %s?', recommended))
}
2023-12-28 23:41:32 +08:00
self.reset = function reset (localLookup) {
implied = objFilter(implied, (k, v) => !localLookup[k])
conflicting = objFilter(conflicting, (k, v) => !localLookup[k])
checks = checks.filter(c => c.global)
2023-12-18 13:12:25 +08:00
return self
}
2023-12-28 23:41:32 +08:00
let frozen
self.freeze = function freeze () {
2023-12-18 13:12:25 +08:00
frozen = {}
frozen.implied = implied
frozen.checks = checks
frozen.conflicting = conflicting
}
2023-12-28 23:41:32 +08:00
self.unfreeze = function unfreeze () {
2023-12-18 13:12:25 +08:00
implied = frozen.implied
checks = frozen.checks
conflicting = frozen.conflicting
frozen = undefined
}
return self
}