From d2fca3b557bb90208cd4fc07a88191e5df5bccf9 Mon Sep 17 00:00:00 2001 From: Wee Bit Date: Sat, 5 Aug 2023 16:15:54 +0300 Subject: [PATCH] Move declared command-argument parsing to constructor --- lib/command.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/command.js b/lib/command.js index 590a271dd..a8f51bef2 100644 --- a/lib/command.js +++ b/lib/command.js @@ -21,6 +21,15 @@ class Command extends EventEmitter { constructor(name) { super(); + const nameMatchResult = name?.match(/([^ ]+) *(.*)/); + /** @type {string} */ + this._name = nameMatchResult?.[1] ?? ''; + /** @type {Argument[]} */ + this._args = []; + if (nameMatchResult?.[2]) { + this.arguments(nameMatchResult[2]); + } + /** @type {Command[]} */ this.commands = []; /** @type {Option[]} */ @@ -28,14 +37,11 @@ class Command extends EventEmitter { this.parent = null; this._allowUnknownOption = false; this._allowExcessArguments = true; - /** @type {Argument[]} */ - this._args = []; /** @type {string[]} */ this.args = []; // cli args with options removed this.rawArgs = []; this.processedArgs = []; // like .args but after custom processing and collecting variadic this._scriptPath = null; - this._name = name || ''; this._optionValues = {}; this._optionValueSources = {}; // default, env, cli etc this._storeOptionsAsProperties = false; @@ -142,9 +148,8 @@ class Command extends EventEmitter { desc = null; } opts = opts || {}; - const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); - const cmd = this.createCommand(name); + const cmd = this.createCommand(nameAndArgs); if (desc) { cmd.description(desc); cmd._executableHandler = true; @@ -152,7 +157,7 @@ class Command extends EventEmitter { if (opts.isDefault) this._defaultCommandName = cmd._name; cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - if (args) cmd.arguments(args); + this.commands.push(cmd); cmd.parent = this; cmd.copyInheritedSettings(this);