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

69 lines
2.4 KiB
JavaScript
Raw Normal View History

2023-12-28 23:41:32 +08:00
'use strict'
// hoisted due to circular dependency on command.
module.exports = argsert
2023-12-18 13:12:25 +08:00
const command = require('./command')()
const YError = require('./yerror')
const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
2023-12-28 23:41:32 +08:00
function argsert (expected, callerArguments, length) {
2023-12-18 13:12:25 +08:00
// TODO: should this eventually raise an exception.
try {
// preface the argument description with "cmd", so
// that we can run it through yargs' command parser.
2023-12-28 23:41:32 +08:00
let position = 0
let parsed = { demanded: [], optional: [] }
2023-12-18 13:12:25 +08:00
if (typeof expected === 'object') {
length = callerArguments
callerArguments = expected
} else {
2023-12-28 23:41:32 +08:00
parsed = command.parseCommand(`cmd ${expected}`)
2023-12-18 13:12:25 +08:00
}
const args = [].slice.call(callerArguments)
while (args.length && args[args.length - 1] === undefined) args.pop()
length = length || args.length
if (length < parsed.demanded.length) {
2023-12-28 23:41:32 +08:00
throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`)
2023-12-18 13:12:25 +08:00
}
const totalCommands = parsed.demanded.length + parsed.optional.length
if (length > totalCommands) {
2023-12-28 23:41:32 +08:00
throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`)
2023-12-18 13:12:25 +08:00
}
2023-12-28 23:41:32 +08:00
parsed.demanded.forEach((demanded) => {
2023-12-18 13:12:25 +08:00
const arg = args.shift()
const observedType = guessType(arg)
2023-12-28 23:41:32 +08:00
const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*')
2023-12-18 13:12:25 +08:00
if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false)
position += 1
})
2023-12-28 23:41:32 +08:00
parsed.optional.forEach((optional) => {
2023-12-18 13:12:25 +08:00
if (args.length === 0) return
const arg = args.shift()
const observedType = guessType(arg)
2023-12-28 23:41:32 +08:00
const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*')
2023-12-18 13:12:25 +08:00
if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true)
position += 1
})
} catch (err) {
console.warn(err.stack)
}
}
function guessType (arg) {
if (Array.isArray(arg)) {
return 'array'
} else if (arg === null) {
return 'null'
}
return typeof arg
}
function argumentTypeError (observedType, allowedTypes, position, optional) {
2023-12-28 23:41:32 +08:00
throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`)
2023-12-18 13:12:25 +08:00
}