MCPcopy Create free account
hub / github.com/ChinaSiro/claude-code-sourcemap / _findCommand

Method _findCommand

package/cli.js:7942–7942  ·  view source on GitHub ↗
(q)

Source from the content-addressed store, hash-verified

7940- already used by option '${K.flags}'`)}this.options.push(q)}_registerCommand(q){let K=(z)=>{return[z.name()].concat(z.aliases())},_=K(q).find((z)=>this._findCommand(z));if(_){let z=K(this._findCommand(_)).join("|"),Y=K(q).join("|");throw Error(`cannot add command '${Y}' as already have command '${z}'`)}this.commands.push(q)}addOption(q){this._registerOption(q);let K=q.name(),_=q.attributeName();if(q.negate){let Y=q.long.replace(/^--no-/,"--");if(!this._findOption(Y))this.setOptionValueWithSource(_,q.defaultValue===void 0?!0:q.defaultValue,"default")}else if(q.defaultValue!==void 0)this.setOptionValueWithSource(_,q.defaultValue,"default");let z=(Y,$,A)=>{if(Y==null&&q.presetArg!==void 0)Y=q.presetArg;let O=this.getOptionValue(_);if(Y!==null&&q.parseArg)Y=this._callParseArg(q,Y,O,$);else if(Y!==null&&q.variadic)Y=q._concatValue(Y,O);if(Y==null)if(q.negate)Y=!1;else if(q.isBoolean()||q.optional)Y=!0;else Y="";this.setOptionValueWithSource(_,Y,A)};if(this.on("option:"+K,(Y)=>{let $=`error: option '${q.flags}' argument '${Y}' is invalid.`;z(Y,$,"cli")}),q.envVar)this.on("optionEnv:"+K,(Y)=>{let $=`error: option '${q.flags}' value '${Y}' from env '${q.envVar}' is invalid.`;z(Y,$,"env")});return this}_optionEx(q,K,_,z,Y){if(typeof K==="object"&&K instanceof lFK)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let $=this.createOption(K,_);if($.makeOptionMandatory(!!q.mandatory),typeof z==="function")$.default(Y).argParser(z);else if(z instanceof RegExp){let A=z;z=(O,w)=>{let j=A.exec(O);return j?j[0]:w},$.default(Y).argParser(z)}else $.default(z);return this.addOption($)}option(q,K,_,z){return this._optionEx({},q,K,_,z)}requiredOption(q,K,_,z){return this._optionEx({mandatory:!0},q,K,_,z)}combineFlagAndOptionalValue(q=!0){return this._combineFlagAndOptionalValue=!!q,this}allowUnknownOption(q=!0){return this._allowUnknownOption=!!q,this}allowExcessArguments(q=!0){return this._allowExcessArguments=!!q,this}enablePositionalOptions(q=!0){return this._enablePositionalOptions=!!q,this}passThroughOptions(q=!0){return this._passThroughOptions=!!q,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(q=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!q,this}getOptionValue(q){if(this._storeOptionsAsProperties)return this[q];return this._optionValues[q]}setOptionValue(q,K){return this.setOptionValueWithSource(q,K,void 0)}setOptionValueWithSource(q,K,_){if(this._storeOptionsAsProperties)this[q]=K;else this._optionValues[q]=K;return this._optionValueSources[q]=_,this}getOptionValueSource(q){return this._optionValueSources[q]}getOptionValueSourceWithGlobals(q){let K;return this._getCommandAndAncestors().forEach((_)=>{if(_.getOptionValueSource(q)!==void 0)K=_.getOptionValueSource(q)}),K}_prepareUserArgs(q,K){if(q!==void 0&&!Array.isArray(q))throw Error("first parameter to parse must be array or undefined");if(K=K||{},q===void 0&&K.from===void 0){if(pJ.versions?.electron)K.from="electron";let z=pJ.execArgv??[];if(z.includes("-e")||z.includes("--eval")||z.includes("-p")||z.includes("--print"))K.from="eval"}if(q===void 0)q=pJ.argv;this.rawArgs=q.slice();let _;switch(K.from){case void 0:case"node":this._scriptPath=q[1],_=q.slice(2);break;case"electron":if(pJ.defaultApp)this._scriptPath=q[1],_=q.slice(2);else _=q.slice(1);break;case"user":_=q.slice(0);break;case"eval":_=q.slice(1);break;default:throw Error(`unexpected parse option { from: '${K.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",_}parse(q,K){let _=this._prepareUserArgs(q,K);return this._parseCommand([],_),this}async parseAsync(q,K){let _=this._prepareUserArgs(q,K);return await this._parseCommand([],_),this}_executeSubCommand(q,K){K=K.slice();let _=!1,z=[".js",".ts",".tsx",".mjs",".cjs"];function Y(j,H){let J=hs.resolve(j,H);if(n_7.existsSync(J))return J;if(z.includes(hs.extname(H)))return;let M=z.find((X)=>n_7.existsSync(`${J}${X}`));if(M)return`${J}${M}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let $=q._executableFile||`${this._name}-${q._name}`,A=this._executableDir||"";if(this._scriptPath){let j;try{j=n_7.realpathSync(this._scriptPath)}catch(H){j=this._scriptPath}A=hs.resolve(hs.dirname(j),A)}if(A){let j=Y(A,$);if(!j&&!q._executableFile&&this._scriptPath){let H=hs.basename(this._scriptPath,hs.extname(this._scriptPath));if(H!==this._name)j=Y(A,`${H}-${q._name}`)}$=j||$}_=z.includes(hs.extname($));let O;if(pJ.platform!=="win32")if(_)K.unshift($),K=iFK(pJ.execArgv).concat(K),O=l_7.spawn(pJ.argv[0],K,{stdio:"inherit"});else O=l_7.spawn($,K,{stdio:"inherit"});else K.unshift($),K=iFK(pJ.execArgv).concat(K),O=l_7.spawn(pJ.execPath,K,{stdio:"inherit"});if(!O.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((H)=>{pJ.on(H,()=>{if(O.killed===!1&&O.exitCode===null)O.kill(H)})});let w=this._exitCallback;O.on("close",(j)=>{if(j=j??1,!w)pJ.exit(j);else w(new i_7(j,"commander.executeSubCommandAsync","(close)"))}),O.on("error",(j)=>{if(j.code==="ENOENT"){let H=A?`searched for local subcommand relative to directory '${A}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",J=`'${$}' does not exist
7941 - if '${q._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
7942 - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
7943 - ${H}`;throw Error(J)}else if(j.code==="EACCES")throw Error(`'${$}' not executable`);if(!w)pJ.exit(1);else{let H=new i_7(1,"commander.executeSubCommandAsync","(error)");H.nestedError=j,w(H)}}),this.runningCommand=O}_dispatchSubcommand(q,K,_){let z=this._findCommand(q);if(!z)this.help({error:!0});let Y;return Y=this._chainOrCallSubCommandHook(Y,z,"preSubcommand"),Y=this._chainOrCall(Y,()=>{if(z._executableHandler)this._executeSubCommand(z,K.concat(_));else return z._parseCommand(K,_)}),Y}_dispatchHelpCommand(q){if(!q)this.help();let K=this._findCommand(q);if(K&&!K._executableHandler)K.help();return this._dispatchSubcommand(q,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((q,K)=>{if(q.required&&this.args[K]==null)this.missingArgument(q.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let q=(_,z,Y)=>{let $=z;if(z!==null&&_.parseArg){let A=`error: command-argument value '${z}' is invalid for argument '${_.name()}'.`;$=this._callParseArg(_,z,Y,A)}return $};this._checkNumberOfArguments();let K=[];this.registeredArguments.forEach((_,z)=>{let Y=_.defaultValue;if(_.variadic){if(z<this.args.length){if(Y=this.args.slice(z),_.parseArg)Y=Y.reduce(($,A)=>{return q(_,A,$)},_.defaultValue)}else if(Y===void 0)Y=[]}else if(z<this.args.length){if(Y=this.args[z],_.parseArg)Y=q(_,Y,_.defaultValue)}K[z]=Y}),this.processedArgs=K}_chainOrCall(q,K){if(q&&q.then&&typeof q.then==="function")return q.then(()=>K());return K()}_chainOrCallHooks(q,K){let _=q,z=[];if(this._getCommandAndAncestors().reverse().filter((Y)=>Y._lifeCycleHooks[K]!==void 0).forEach((Y)=>{Y._lifeCycleHooks[K].forEach(($)=>{z.push({hookedCommand:Y,callback:$})})}),K==="postAction")z.reverse();return z.forEach((Y)=>{_=this._chainOrCall(_,()=>{return Y.callback(Y.hookedCommand,this)})}),_}_chainOrCallSubCommandHook(q,K,_){let z=q;if(this._lifeCycleHooks[_]!==void 0)this._lifeCycleHooks[_].forEach((Y)=>{z=this._chainOrCall(z,()=>{return Y(this,K)})});return z}_parseCommand(q,K){let _=this.parseOptions(K);if(this._parseOptionsEnv(),this._parseOptionsImplied(),q=q.concat(_.operands),K=_.unknown,this.args=q.concat(K),q&&this._findCommand(q[0]))return this._dispatchSubcommand(q[0],q.slice(1),K);if(this._getHelpCommand()&&q[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(q[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(K),this._dispatchSubcommand(this._defaultCommandName,q,K);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(_.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=()=>{if(_.unknown.length>0)this.unknownOption(_.unknown[0])},Y=`command:${this.name()}`;if(this._actionHandler){z(),this._processArguments();let $;if($=this._chainOrCallHooks($,"preAction"),$=this._chainOrCall($,()=>this._actionHandler(this.processedArgs)),this.parent)$=this._chainOrCall($,()=>{this.parent.emit(Y,q,K)});return $=this._chainOrCallHooks($,"postAction"),$}if(this.parent&&this.parent.listenerCount(Y))z(),this._processArguments(),this.parent.emit(Y,q,K);else if(q.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",q,K);if(this.listenerCount("command:*"))this.emit("command:*",q,K);else if(this.commands.length)this.unknownCommand();else z(),this._processArguments()}else if(this.commands.length)z(),this.help({error:!0});else z(),this._processArguments()}_findCommand(q){if(!q)return;return this.commands.find((K)=>K._name===q||K._aliases.includes(q))}_findOption(q){return this.options.find((K)=>K.is(q))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((q)=>{q.options.forEach((K)=>{if(K.mandatory&&q.getOptionValue(K.attributeName())===void 0)q.missingMandatoryOptionValue(K)})})}_checkForConflictingLocalOptions(){let q=this.options.filter((_)=>{let z=_.attributeName();if(this.getOptionValue(z)===void 0)return!1;return this.getOptionValueSource(z)!=="default"});q.filter((_)=>_.conflictsWith.length>0).forEach((_)=>{let z=q.find((Y)=>_.conflictsWith.includes(Y.attributeName()));if(z)this._conflictingOption(_,z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((q)=>{q._checkForConflictingLocalOptions()})}parseOptions(q){let K=[],_=[],z=K,Y=q.slice();function $(O){return O.length>1&&O[0]==="-"}let A=null;while(Y.length){let O=Y.shift();if(O==="--"){if(z===_)z.push(O);z.push(...Y);break}if(A&&!$(O)){this.emit(`option:${A.name()}`,O);continue}if(A=null,$(O)){let w=this._findOption(O);if(w){if(w.required){let j=Y.shift();if(j===void 0)this.optionMissingArgument(w);this.emit(`option:${w.name()}`,j)}else if(w.optional){let j=null;if(Y.length>0&&!$(Y[0]))j=Y.shift();this.emit(`option:${w.name()}`,j)}else this.emit(`option:${w.name()}`);A=w.variadic?w:null;continue}}if(O.length>2&&O[0]==="-"&&O[1]!=="-"){let w=this._findOption(`-${O[1]}`);if(w){if(w.required||w.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${w.name()}`,O.slice(2));else this.emit(`option:${w.name()}`),Y.unshift(`-${O.slice(2)}`);continue}}if(/^--[^=]+=/.test(O)){let w=O.indexOf("="),j=this._findOption(O.slice(0,w));if(j&&(j.required||j.optional)){this.emit(`option:${j.name()}`,O.slice(w+1));continue}}if($(O))z=_;if((this._enablePositionalOptions||this._passThroughOptions)&&K.length===0&&_.length===0){if(this._findCommand(O)){if(K.push(O),Y.length>0)_.push(...Y);break}else if(this._getHelpCommand()&&O===this._getHelpCommand().name()){if(K.push(O),Y.length>0)K.push(...Y);break}else if(this._defaultCommandName){if(_.push(O),Y.length>0)_.push(...Y);break}}if(this._passThroughOptions){if(z.push(O),Y.length>0)z.push(...Y);break}z.push(O)}return{operands:K,unknown:_}}opts(){if(this._storeOptionsAsProperties){let q={},K=this.options.length;for(let _=0;_<K;_++){let z=this.options[_].attributeName();q[z]=z===this._versionOptionName?this._version:this[z]}return q}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((q,K)=>Object.assign(q,K.opts()),{})}error(q,K){if(this._outputConfiguration.outputError(`${q}
7944`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
7945`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`

Callers 7

_getHelpCommandMethod · 0.95
_registerCommandMethod · 0.95
_dispatchSubcommandMethod · 0.95
_dispatchHelpCommandMethod · 0.95
_parseCommandMethod · 0.95
parseOptionsMethod · 0.95
aliasMethod · 0.80

Calls 2

includesMethod · 0.80
findMethod · 0.45

Tested by

no test coverage detected