kit.program/argv/CliCmdLine.js

78 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2024-02-27 08:54:41 +00:00
module.exports = class CliCmdLine {
/**
* 带值的命令格式
* @param parser 解析器
* @param cmdLine 命令描述格式
* @param flags 标记
* @param params 参数
* @param position 位置参数
*/
constructor(parser, cmdLine, flags, params, position) {
this.parser = parser
this.cmdline = cmdLine
this.flags = new Set([])
this.params = {}
let i = 0;
for ( let pname in cmdLine.params ) {
let param = cmdLine.params[pname];
if ( param.isFlag ) {
if ( param.needValue ){
if ( params[pname] ) {
this.params[pname] = params[pname]
} else {
if ( ! param.isOptional ) {
throw "命令解析错误,缺少必填标记参数。" + pname
}
}
} else {
if ( flags.has(pname) ) {
this.flags.add( pname )
} else {
if ( ! param.isOptional ) {
throw "命令解析错误,缺少必填标记。" + pname
}
}
}
} else {
if ( i < position.length ) {
this.params[ pname ] = position[ i++ ] ;
} else {
if ( ! param.isOptional ) {
throw "命令解析错误,缺少必填位置参数。" + pname;
}
}
}
}
}
/**
* 是否已经绑定了回调函数
*/
canEval(){
return this.parser.canEval( this )
}
async eval(params){
return this.parser.eval( this )
}
getParamValue(name, def){
if ( name.startsWith("--") ) {
name = name.substring(2);
}
let v = this.params[ name ];
if ( null == v ) {
return def
} else {
return v;
}
}
hasFlag(name){
return this.flags.has(name)
}
}