gstatx 0.2.7 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +29 -28
- package/dist/lib.js +9 -8
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,55 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as xQ}from"node:module";var AQ=Object.create;var{getPrototypeOf:kQ,defineProperty:
|
|
3
|
-
`)}displayWidth(Q){return
|
|
2
|
+
import{createRequire as xQ}from"node:module";var AQ=Object.create;var{getPrototypeOf:kQ,defineProperty:QQ,getOwnPropertyNames:wQ}=Object;var PQ=Object.prototype.hasOwnProperty;var OQ=(Q,X,Y)=>{Y=Q!=null?AQ(kQ(Q)):{};let Z=X||!Q||!Q.__esModule?QQ(Y,"default",{value:Q,enumerable:!0}):Y;for(let $ of wQ(Q))if(!PQ.call(Z,$))QQ(Z,$,{get:()=>Q[$],enumerable:!0});return Z};var y=(Q,X)=>()=>(X||Q((X={exports:{}}).exports,X),X.exports);var P=xQ(import.meta.url);var O=y((CQ)=>{class u extends Error{constructor(Q,X,Y){super(Y);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=X,this.exitCode=Q,this.nestedError=void 0}}class XQ extends u{constructor(Q){super(1,"commander.invalidArgument",Q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}CQ.CommanderError=u;CQ.InvalidArgumentError=XQ});var v=y((gQ)=>{var{InvalidArgumentError:fQ}=O();class YQ{constructor(Q,X){switch(this.description=X||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,Q[0]){case"<":this.required=!0,this._name=Q.slice(1,-1);break;case"[":this.required=!1,this._name=Q.slice(1,-1);break;default:this.required=!0,this._name=Q;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(Q,X){if(X===this.defaultValue||!Array.isArray(X))return[Q];return X.push(Q),X}default(Q,X){return this.defaultValue=Q,this.defaultValueDescription=X,this}argParser(Q){return this.parseArg=Q,this}choices(Q){return this.argChoices=Q.slice(),this.parseArg=(X,Y)=>{if(!this.argChoices.includes(X))throw new fQ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(X,Y);return X},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function hQ(Q){let X=Q.name()+(Q.variadic===!0?"...":"");return Q.required?"<"+X+">":"["+X+"]"}gQ.Argument=YQ;gQ.humanReadableArgName=hQ});var d=y((lQ)=>{var{humanReadableArgName:cQ}=v();class ZQ{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(Q){this.helpWidth=this.helpWidth??Q.helpWidth??80}visibleCommands(Q){let X=Q.commands.filter((Z)=>!Z._hidden),Y=Q._getHelpCommand();if(Y&&!Y._hidden)X.push(Y);if(this.sortSubcommands)X.sort((Z,$)=>{return Z.name().localeCompare($.name())});return X}compareOptions(Q,X){let Y=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return Y(Q).localeCompare(Y(X))}visibleOptions(Q){let X=Q.options.filter((Z)=>!Z.hidden),Y=Q._getHelpOption();if(Y&&!Y.hidden){let Z=Y.short&&Q._findOption(Y.short),$=Y.long&&Q._findOption(Y.long);if(!Z&&!$)X.push(Y);else if(Y.long&&!$)X.push(Q.createOption(Y.long,Y.description));else if(Y.short&&!Z)X.push(Q.createOption(Y.short,Y.description))}if(this.sortOptions)X.sort(this.compareOptions);return X}visibleGlobalOptions(Q){if(!this.showGlobalOptions)return[];let X=[];for(let Y=Q.parent;Y;Y=Y.parent){let Z=Y.options.filter(($)=>!$.hidden);X.push(...Z)}if(this.sortOptions)X.sort(this.compareOptions);return X}visibleArguments(Q){if(Q._argsDescription)Q.registeredArguments.forEach((X)=>{X.description=X.description||Q._argsDescription[X.name()]||""});if(Q.registeredArguments.find((X)=>X.description))return Q.registeredArguments;return[]}subcommandTerm(Q){let X=Q.registeredArguments.map((Y)=>cQ(Y)).join(" ");return Q._name+(Q._aliases[0]?"|"+Q._aliases[0]:"")+(Q.options.length?" [options]":"")+(X?" "+X:"")}optionTerm(Q){return Q.flags}argumentTerm(Q){return Q.name()}longestSubcommandTermLength(Q,X){return X.visibleCommands(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleSubcommandTerm(X.subcommandTerm(Z))))},0)}longestOptionTermLength(Q,X){return X.visibleOptions(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleOptionTerm(X.optionTerm(Z))))},0)}longestGlobalOptionTermLength(Q,X){return X.visibleGlobalOptions(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleOptionTerm(X.optionTerm(Z))))},0)}longestArgumentTermLength(Q,X){return X.visibleArguments(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleArgumentTerm(X.argumentTerm(Z))))},0)}commandUsage(Q){let X=Q._name;if(Q._aliases[0])X=X+"|"+Q._aliases[0];let Y="";for(let Z=Q.parent;Z;Z=Z.parent)Y=Z.name()+" "+Y;return Y+X+" "+Q.usage()}commandDescription(Q){return Q.description()}subcommandDescription(Q){return Q.summary()||Q.description()}optionDescription(Q){let X=[];if(Q.argChoices)X.push(`choices: ${Q.argChoices.map((Y)=>JSON.stringify(Y)).join(", ")}`);if(Q.defaultValue!==void 0){if(Q.required||Q.optional||Q.isBoolean()&&typeof Q.defaultValue==="boolean")X.push(`default: ${Q.defaultValueDescription||JSON.stringify(Q.defaultValue)}`)}if(Q.presetArg!==void 0&&Q.optional)X.push(`preset: ${JSON.stringify(Q.presetArg)}`);if(Q.envVar!==void 0)X.push(`env: ${Q.envVar}`);if(X.length>0){let Y=`(${X.join(", ")})`;if(Q.description)return`${Q.description} ${Y}`;return Y}return Q.description}argumentDescription(Q){let X=[];if(Q.argChoices)X.push(`choices: ${Q.argChoices.map((Y)=>JSON.stringify(Y)).join(", ")}`);if(Q.defaultValue!==void 0)X.push(`default: ${Q.defaultValueDescription||JSON.stringify(Q.defaultValue)}`);if(X.length>0){let Y=`(${X.join(", ")})`;if(Q.description)return`${Q.description} ${Y}`;return Y}return Q.description}formatItemList(Q,X,Y){if(X.length===0)return[];return[Y.styleTitle(Q),...X,""]}groupItems(Q,X,Y){let Z=new Map;return Q.forEach(($)=>{let q=Y($);if(!Z.has(q))Z.set(q,[])}),X.forEach(($)=>{let q=Y($);if(!Z.has(q))Z.set(q,[]);Z.get(q).push($)}),Z}formatHelp(Q,X){let Y=X.padWidth(Q,X),Z=X.helpWidth??80;function $(G,U){return X.formatItem(G,Y,U,X)}let q=[`${X.styleTitle("Usage:")} ${X.styleUsage(X.commandUsage(Q))}`,""],_=X.commandDescription(Q);if(_.length>0)q=q.concat([X.boxWrap(X.styleCommandDescription(_),Z),""]);let z=X.visibleArguments(Q).map((G)=>{return $(X.styleArgumentTerm(X.argumentTerm(G)),X.styleArgumentDescription(X.argumentDescription(G)))});if(q=q.concat(this.formatItemList("Arguments:",z,X)),this.groupItems(Q.options,X.visibleOptions(Q),(G)=>G.helpGroupHeading??"Options:").forEach((G,U)=>{let T=G.map((R)=>{return $(X.styleOptionTerm(X.optionTerm(R)),X.styleOptionDescription(X.optionDescription(R)))});q=q.concat(this.formatItemList(U,T,X))}),X.showGlobalOptions){let G=X.visibleGlobalOptions(Q).map((U)=>{return $(X.styleOptionTerm(X.optionTerm(U)),X.styleOptionDescription(X.optionDescription(U)))});q=q.concat(this.formatItemList("Global Options:",G,X))}return this.groupItems(Q.commands,X.visibleCommands(Q),(G)=>G.helpGroup()||"Commands:").forEach((G,U)=>{let T=G.map((R)=>{return $(X.styleSubcommandTerm(X.subcommandTerm(R)),X.styleSubcommandDescription(X.subcommandDescription(R)))});q=q.concat(this.formatItemList(U,T,X))}),q.join(`
|
|
3
|
+
`)}displayWidth(Q){return $Q(Q).length}styleTitle(Q){return Q}styleUsage(Q){return Q.split(" ").map((X)=>{if(X==="[options]")return this.styleOptionText(X);if(X==="[command]")return this.styleSubcommandText(X);if(X[0]==="["||X[0]==="<")return this.styleArgumentText(X);return this.styleCommandText(X)}).join(" ")}styleCommandDescription(Q){return this.styleDescriptionText(Q)}styleOptionDescription(Q){return this.styleDescriptionText(Q)}styleSubcommandDescription(Q){return this.styleDescriptionText(Q)}styleArgumentDescription(Q){return this.styleDescriptionText(Q)}styleDescriptionText(Q){return Q}styleOptionTerm(Q){return this.styleOptionText(Q)}styleSubcommandTerm(Q){return Q.split(" ").map((X)=>{if(X==="[options]")return this.styleOptionText(X);if(X[0]==="["||X[0]==="<")return this.styleArgumentText(X);return this.styleSubcommandText(X)}).join(" ")}styleArgumentTerm(Q){return this.styleArgumentText(Q)}styleOptionText(Q){return Q}styleArgumentText(Q){return Q}styleSubcommandText(Q){return Q}styleCommandText(Q){return Q}padWidth(Q,X){return Math.max(X.longestOptionTermLength(Q,X),X.longestGlobalOptionTermLength(Q,X),X.longestSubcommandTermLength(Q,X),X.longestArgumentTermLength(Q,X))}preformatted(Q){return/\n[^\S\r\n]/.test(Q)}formatItem(Q,X,Y,Z){let q=" ".repeat(2);if(!Y)return q+Q;let _=Q.padEnd(X+Q.length-Z.displayWidth(Q)),z=2,J=(this.helpWidth??80)-X-z-2,G;if(J<this.minWidthToWrap||Z.preformatted(Y))G=Y;else G=Z.boxWrap(Y,J).replace(/\n/g,`
|
|
4
4
|
`+" ".repeat(X+z));return q+_+" ".repeat(z)+G.replace(/\n/g,`
|
|
5
|
-
${q}`)}boxWrap(Q,X){if(X<this.minWidthToWrap)return Q;let Y=Q.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,$=[];return Y.forEach((q)=>{let _=q.match(Z);if(_===null){$.push("");return}let z=[_.shift()],
|
|
6
|
-
`)}}function
|
|
5
|
+
${q}`)}boxWrap(Q,X){if(X<this.minWidthToWrap)return Q;let Y=Q.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,$=[];return Y.forEach((q)=>{let _=q.match(Z);if(_===null){$.push("");return}let z=[_.shift()],H=this.displayWidth(z[0]);_.forEach((J)=>{let G=this.displayWidth(J);if(H+G<=X){z.push(J),H+=G;return}$.push(z.join(""));let U=J.trimStart();z=[U],H=this.displayWidth(U)}),$.push(z.join(""))}),$.join(`
|
|
6
|
+
`)}}function $Q(Q){let X=/\x1b\[\d*(;\d*)*m/g;return Q.replace(X,"")}lQ.Help=ZQ;lQ.stripColor=$Q});var c=y((nQ)=>{var{InvalidArgumentError:sQ}=O();class JQ{constructor(Q,X){this.flags=Q,this.description=X||"",this.required=Q.includes("<"),this.optional=Q.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(Q),this.mandatory=!1;let Y=iQ(Q);if(this.short=Y.shortFlag,this.long=Y.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(Q,X){return this.defaultValue=Q,this.defaultValueDescription=X,this}preset(Q){return this.presetArg=Q,this}conflicts(Q){return this.conflictsWith=this.conflictsWith.concat(Q),this}implies(Q){let X=Q;if(typeof Q==="string")X={[Q]:!0};return this.implied=Object.assign(this.implied||{},X),this}env(Q){return this.envVar=Q,this}argParser(Q){return this.parseArg=Q,this}makeOptionMandatory(Q=!0){return this.mandatory=!!Q,this}hideHelp(Q=!0){return this.hidden=!!Q,this}_collectValue(Q,X){if(X===this.defaultValue||!Array.isArray(X))return[Q];return X.push(Q),X}choices(Q){return this.argChoices=Q.slice(),this.parseArg=(X,Y)=>{if(!this.argChoices.includes(X))throw new sQ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(X,Y);return X},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return qQ(this.name().replace(/^no-/,""));return qQ(this.name())}helpGroup(Q){return this.helpGroupHeading=Q,this}is(Q){return this.short===Q||this.long===Q}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class _Q{constructor(Q){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,Q.forEach((X)=>{if(X.negate)this.negativeOptions.set(X.attributeName(),X);else this.positiveOptions.set(X.attributeName(),X)}),this.negativeOptions.forEach((X,Y)=>{if(this.positiveOptions.has(Y))this.dualOptions.add(Y)})}valueFromOption(Q,X){let Y=X.attributeName();if(!this.dualOptions.has(Y))return!0;let Z=this.negativeOptions.get(Y).presetArg,$=Z!==void 0?Z:!1;return X.negate===($===Q)}}function qQ(Q){return Q.split("-").reduce((X,Y)=>{return X+Y[0].toUpperCase()+Y.slice(1)})}function iQ(Q){let X,Y,Z=/^-[^-]$/,$=/^--[^-]/,q=Q.split(/[ |,]+/).concat("guard");if(Z.test(q[0]))X=q.shift();if($.test(q[0]))Y=q.shift();if(!X&&Z.test(q[0]))X=q.shift();if(!X&&$.test(q[0]))X=Y,Y=q.shift();if(q[0].startsWith("-")){let _=q[0],z=`option creation failed due to '${_}' in option flags '${Q}'`;if(/^-[^-][^-]/.test(_))throw new Error(`${z}
|
|
7
7
|
- a short flag is a single dash and a single character
|
|
8
8
|
- either use a single dash and a single character (for a short flag)
|
|
9
9
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(_))throw new Error(`${z}
|
|
10
10
|
- too many short flags`);if($.test(_))throw new Error(`${z}
|
|
11
11
|
- too many long flags`);throw new Error(`${z}
|
|
12
|
-
- unrecognised flag format`)}if(X===void 0&&Y===void 0)throw new Error(`option creation failed due to no flags found in '${Q}'.`);return{shortFlag:X,longFlag:Y}}nQ.Option=
|
|
12
|
+
- unrecognised flag format`)}if(X===void 0&&Y===void 0)throw new Error(`option creation failed due to no flags found in '${Q}'.`);return{shortFlag:X,longFlag:Y}}nQ.Option=JQ;nQ.DualOptions=_Q});var zQ=y((eQ)=>{function rQ(Q,X){if(Math.abs(Q.length-X.length)>3)return Math.max(Q.length,X.length);let Y=[];for(let Z=0;Z<=Q.length;Z++)Y[Z]=[Z];for(let Z=0;Z<=X.length;Z++)Y[0][Z]=Z;for(let Z=1;Z<=X.length;Z++)for(let $=1;$<=Q.length;$++){let q=1;if(Q[$-1]===X[Z-1])q=0;else q=1;if(Y[$][Z]=Math.min(Y[$-1][Z]+1,Y[$][Z-1]+1,Y[$-1][Z-1]+q),$>1&&Z>1&&Q[$-1]===X[Z-2]&&Q[$-2]===X[Z-1])Y[$][Z]=Math.min(Y[$][Z],Y[$-2][Z-2]+1)}return Y[Q.length][X.length]}function oQ(Q,X){if(!X||X.length===0)return"";X=Array.from(new Set(X));let Y=Q.startsWith("--");if(Y)Q=Q.slice(2),X=X.map((_)=>_.slice(2));let Z=[],$=3,q=0.4;if(X.forEach((_)=>{if(_.length<=1)return;let z=rQ(Q,_),H=Math.max(Q.length,_.length);if((H-z)/H>q){if(z<$)$=z,Z=[_];else if(z===$)Z.push(_)}}),Z.sort((_,z)=>_.localeCompare(z)),Y)Z=Z.map((_)=>`--${_}`);if(Z.length>1)return`
|
|
13
13
|
(Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
|
|
14
|
-
(Did you mean ${Z[0]}?)`;return""}eQ.suggestSimilar=oQ});var TQ=
|
|
14
|
+
(Did you mean ${Z[0]}?)`;return""}eQ.suggestSimilar=oQ});var TQ=y((_X)=>{var XX=P("node:events").EventEmitter,l=P("node:child_process"),D=P("node:path"),f=P("node:fs"),B=P("node:process"),{Argument:YX,humanReadableArgName:ZX}=v(),{CommanderError:m}=O(),{Help:$X,stripColor:qX}=d(),{Option:GQ,DualOptions:JX}=c(),{suggestSimilar:HQ}=zQ();class s extends XX{constructor(Q){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=Q||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(X)=>B.stdout.write(X),writeErr:(X)=>B.stderr.write(X),outputError:(X,Y)=>Y(X),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>p()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>p()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:(X)=>qX(X)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(Q){return this._outputConfiguration=Q._outputConfiguration,this._helpOption=Q._helpOption,this._helpCommand=Q._helpCommand,this._helpConfiguration=Q._helpConfiguration,this._exitCallback=Q._exitCallback,this._storeOptionsAsProperties=Q._storeOptionsAsProperties,this._combineFlagAndOptionalValue=Q._combineFlagAndOptionalValue,this._allowExcessArguments=Q._allowExcessArguments,this._enablePositionalOptions=Q._enablePositionalOptions,this._showHelpAfterError=Q._showHelpAfterError,this._showSuggestionAfterError=Q._showSuggestionAfterError,this}_getCommandAndAncestors(){let Q=[];for(let X=this;X;X=X.parent)Q.push(X);return Q}command(Q,X,Y){let Z=X,$=Y;if(typeof Z==="object"&&Z!==null)$=Z,Z=null;$=$||{};let[,q,_]=Q.match(/([^ ]+) *(.*)/),z=this.createCommand(q);if(Z)z.description(Z),z._executableHandler=!0;if($.isDefault)this._defaultCommandName=z._name;if(z._hidden=!!($.noHelp||$.hidden),z._executableFile=$.executableFile||null,_)z.arguments(_);if(this._registerCommand(z),z.parent=this,z.copyInheritedSettings(this),Z)return this;return z}createCommand(Q){return new s(Q)}createHelp(){return Object.assign(new $X,this.configureHelp())}configureHelp(Q){if(Q===void 0)return this._helpConfiguration;return this._helpConfiguration=Q,this}configureOutput(Q){if(Q===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...Q},this}showHelpAfterError(Q=!0){if(typeof Q!=="string")Q=!!Q;return this._showHelpAfterError=Q,this}showSuggestionAfterError(Q=!0){return this._showSuggestionAfterError=!!Q,this}addCommand(Q,X){if(!Q._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
15
|
- specify the name in Command constructor or using .name()`);if(X=X||{},X.isDefault)this._defaultCommandName=Q._name;if(X.noHelp||X.hidden)Q._hidden=!0;return this._registerCommand(Q),Q.parent=this,Q._checkForBrokenPassThrough(),this}createArgument(Q,X){return new YX(Q,X)}argument(Q,X,Y,Z){let $=this.createArgument(Q,X);if(typeof Y==="function")$.default(Z).argParser(Y);else $.default(Y);return this.addArgument($),this}arguments(Q){return Q.trim().split(/ +/).forEach((X)=>{this.argument(X)}),this}addArgument(Q){let X=this.registeredArguments.slice(-1)[0];if(X?.variadic)throw new Error(`only the last argument can be variadic '${X.name()}'`);if(Q.required&&Q.defaultValue!==void 0&&Q.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${Q.name()}'`);return this.registeredArguments.push(Q),this}helpCommand(Q,X){if(typeof Q==="boolean"){if(this._addImplicitHelpCommand=Q,Q&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Y=Q??"help [command]",[,Z,$]=Y.match(/([^ ]+) *(.*)/),q=X??"display help for command",_=this.createCommand(Z);if(_.helpOption(!1),$)_.arguments($);if(q)_.description(q);if(this._addImplicitHelpCommand=!0,this._helpCommand=_,Q||X)this._initCommandGroup(_);return this}addHelpCommand(Q,X){if(typeof Q!=="object")return this.helpCommand(Q,X),this;return this._addImplicitHelpCommand=!0,this._helpCommand=Q,this._initCommandGroup(Q),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(Q,X){let Y=["preSubcommand","preAction","postAction"];if(!Y.includes(Q))throw new Error(`Unexpected value for event passed to hook : '${Q}'.
|
|
16
|
-
Expecting one of '${Y.join("', '")}'`);if(this._lifeCycleHooks[Q])this._lifeCycleHooks[Q].push(X);else this._lifeCycleHooks[Q]=[X];return this}exitOverride(Q){if(Q)this._exitCallback=Q;else this._exitCallback=(X)=>{if(X.code!=="commander.executeSubCommandAsync")throw X};return this}_exit(Q,X,Y){if(this._exitCallback)this._exitCallback(new
|
|
17
|
-
- already used by option '${X.flags}'`)}this._initOptionGroup(Q),this.options.push(Q)}_registerCommand(Q){let X=(Z)=>{return[Z.name()].concat(Z.aliases())},Y=X(Q).find((Z)=>this._findCommand(Z));if(Y){let Z=X(this._findCommand(Y)).join("|"),$=X(Q).join("|");throw new Error(`cannot add command '${$}' as already have command '${Z}'`)}this._initCommandGroup(Q),this.commands.push(Q)}addOption(Q){this._registerOption(Q);let X=Q.name(),Y=Q.attributeName();if(Q.negate){let $=Q.long.replace(/^--no-/,"--");if(!this._findOption($))this.setOptionValueWithSource(Y,Q.defaultValue===void 0?!0:Q.defaultValue,"default")}else if(Q.defaultValue!==void 0)this.setOptionValueWithSource(Y,Q.defaultValue,"default");let Z=($,q,_)=>{if($==null&&Q.presetArg!==void 0)$=Q.presetArg;let z=this.getOptionValue(Y);if($!==null&&Q.parseArg)$=this._callParseArg(Q,$,z,q);else if($!==null&&Q.variadic)$=Q._collectValue($,z);if($==null)if(Q.negate)$=!1;else if(Q.isBoolean()||Q.optional)$=!0;else $="";this.setOptionValueWithSource(Y,$,_)};if(this.on("option:"+X,($)=>{let q=`error: option '${Q.flags}' argument '${$}' is invalid.`;Z($,q,"cli")}),Q.envVar)this.on("optionEnv:"+X,($)=>{let q=`error: option '${Q.flags}' value '${$}' from env '${Q.envVar}' is invalid.`;Z($,q,"env")});return this}_optionEx(Q,X,Y,Z,$){if(typeof X==="object"&&X instanceof
|
|
18
|
-
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(Q,X,Y){if(
|
|
16
|
+
Expecting one of '${Y.join("', '")}'`);if(this._lifeCycleHooks[Q])this._lifeCycleHooks[Q].push(X);else this._lifeCycleHooks[Q]=[X];return this}exitOverride(Q){if(Q)this._exitCallback=Q;else this._exitCallback=(X)=>{if(X.code!=="commander.executeSubCommandAsync")throw X};return this}_exit(Q,X,Y){if(this._exitCallback)this._exitCallback(new m(Q,X,Y));B.exit(Q)}action(Q){let X=(Y)=>{let Z=this.registeredArguments.length,$=Y.slice(0,Z);if(this._storeOptionsAsProperties)$[Z]=this;else $[Z]=this.opts();return $.push(this),Q.apply(this,$)};return this._actionHandler=X,this}createOption(Q,X){return new GQ(Q,X)}_callParseArg(Q,X,Y,Z){try{return Q.parseArg(X,Y)}catch($){if($.code==="commander.invalidArgument"){let q=`${Z} ${$.message}`;this.error(q,{exitCode:$.exitCode,code:$.code})}throw $}}_registerOption(Q){let X=Q.short&&this._findOption(Q.short)||Q.long&&this._findOption(Q.long);if(X){let Y=Q.long&&this._findOption(Q.long)?Q.long:Q.short;throw new Error(`Cannot add option '${Q.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Y}'
|
|
17
|
+
- already used by option '${X.flags}'`)}this._initOptionGroup(Q),this.options.push(Q)}_registerCommand(Q){let X=(Z)=>{return[Z.name()].concat(Z.aliases())},Y=X(Q).find((Z)=>this._findCommand(Z));if(Y){let Z=X(this._findCommand(Y)).join("|"),$=X(Q).join("|");throw new Error(`cannot add command '${$}' as already have command '${Z}'`)}this._initCommandGroup(Q),this.commands.push(Q)}addOption(Q){this._registerOption(Q);let X=Q.name(),Y=Q.attributeName();if(Q.negate){let $=Q.long.replace(/^--no-/,"--");if(!this._findOption($))this.setOptionValueWithSource(Y,Q.defaultValue===void 0?!0:Q.defaultValue,"default")}else if(Q.defaultValue!==void 0)this.setOptionValueWithSource(Y,Q.defaultValue,"default");let Z=($,q,_)=>{if($==null&&Q.presetArg!==void 0)$=Q.presetArg;let z=this.getOptionValue(Y);if($!==null&&Q.parseArg)$=this._callParseArg(Q,$,z,q);else if($!==null&&Q.variadic)$=Q._collectValue($,z);if($==null)if(Q.negate)$=!1;else if(Q.isBoolean()||Q.optional)$=!0;else $="";this.setOptionValueWithSource(Y,$,_)};if(this.on("option:"+X,($)=>{let q=`error: option '${Q.flags}' argument '${$}' is invalid.`;Z($,q,"cli")}),Q.envVar)this.on("optionEnv:"+X,($)=>{let q=`error: option '${Q.flags}' value '${$}' from env '${Q.envVar}' is invalid.`;Z($,q,"env")});return this}_optionEx(Q,X,Y,Z,$){if(typeof X==="object"&&X instanceof GQ)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let q=this.createOption(X,Y);if(q.makeOptionMandatory(!!Q.mandatory),typeof Z==="function")q.default($).argParser(Z);else if(Z instanceof RegExp){let _=Z;Z=(z,H)=>{let J=_.exec(z);return J?J[0]:H},q.default($).argParser(Z)}else q.default(Z);return this.addOption(q)}option(Q,X,Y,Z){return this._optionEx({},Q,X,Y,Z)}requiredOption(Q,X,Y,Z){return this._optionEx({mandatory:!0},Q,X,Y,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 new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(Q=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new 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,X){return this.setOptionValueWithSource(Q,X,void 0)}setOptionValueWithSource(Q,X,Y){if(this._storeOptionsAsProperties)this[Q]=X;else this._optionValues[Q]=X;return this._optionValueSources[Q]=Y,this}getOptionValueSource(Q){return this._optionValueSources[Q]}getOptionValueSourceWithGlobals(Q){let X;return this._getCommandAndAncestors().forEach((Y)=>{if(Y.getOptionValueSource(Q)!==void 0)X=Y.getOptionValueSource(Q)}),X}_prepareUserArgs(Q,X){if(Q!==void 0&&!Array.isArray(Q))throw new Error("first parameter to parse must be array or undefined");if(X=X||{},Q===void 0&&X.from===void 0){if(B.versions?.electron)X.from="electron";let Z=B.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))X.from="eval"}if(Q===void 0)Q=B.argv;this.rawArgs=Q.slice();let Y;switch(X.from){case void 0:case"node":this._scriptPath=Q[1],Y=Q.slice(2);break;case"electron":if(B.defaultApp)this._scriptPath=Q[1],Y=Q.slice(2);else Y=Q.slice(1);break;case"user":Y=Q.slice(0);break;case"eval":Y=Q.slice(1);break;default:throw new Error(`unexpected parse option { from: '${X.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",Y}parse(Q,X){this._prepareForParse();let Y=this._prepareUserArgs(Q,X);return this._parseCommand([],Y),this}async parseAsync(Q,X){this._prepareForParse();let Y=this._prepareUserArgs(Q,X);return await this._parseCommand([],Y),this}_prepareForParse(){if(this._savedState===null)this.saveStateBeforeParse();else this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
18
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[]}_checkForMissingExecutable(Q,X,Y){if(f.existsSync(Q))return;let Z=X?`searched for local subcommand relative to directory '${X}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",$=`'${Q}' does not exist
|
|
19
19
|
- if '${Y}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
20
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${Z}`;throw new Error($)}_executeSubCommand(Q,X){X=X.slice();let Y=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(J,G){let
|
|
21
|
+
- ${Z}`;throw new Error($)}_executeSubCommand(Q,X){X=X.slice();let Y=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(J,G){let U=D.resolve(J,G);if(f.existsSync(U))return U;if(Z.includes(D.extname(G)))return;let T=Z.find((R)=>f.existsSync(`${U}${R}`));if(T)return`${U}${T}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let q=Q._executableFile||`${this._name}-${Q._name}`,_=this._executableDir||"";if(this._scriptPath){let J;try{J=f.realpathSync(this._scriptPath)}catch{J=this._scriptPath}_=D.resolve(D.dirname(J),_)}if(_){let J=$(_,q);if(!J&&!Q._executableFile&&this._scriptPath){let G=D.basename(this._scriptPath,D.extname(this._scriptPath));if(G!==this._name)J=$(_,`${G}-${Q._name}`)}q=J||q}Y=Z.includes(D.extname(q));let z;if(B.platform!=="win32")if(Y)X.unshift(q),X=UQ(B.execArgv).concat(X),z=l.spawn(B.argv[0],X,{stdio:"inherit"});else z=l.spawn(q,X,{stdio:"inherit"});else this._checkForMissingExecutable(q,_,Q._name),X.unshift(q),X=UQ(B.execArgv).concat(X),z=l.spawn(B.execPath,X,{stdio:"inherit"});if(!z.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((G)=>{B.on(G,()=>{if(z.killed===!1&&z.exitCode===null)z.kill(G)})});let H=this._exitCallback;z.on("close",(J)=>{if(J=J??1,!H)B.exit(J);else H(new m(J,"commander.executeSubCommandAsync","(close)"))}),z.on("error",(J)=>{if(J.code==="ENOENT")this._checkForMissingExecutable(q,_,Q._name);else if(J.code==="EACCES")throw new Error(`'${q}' not executable`);if(!H)B.exit(1);else{let G=new m(1,"commander.executeSubCommandAsync","(error)");G.nestedError=J,H(G)}}),this.runningCommand=z}_dispatchSubcommand(Q,X,Y){let Z=this._findCommand(Q);if(!Z)this.help({error:!0});Z._prepareForParse();let $;return $=this._chainOrCallSubCommandHook($,Z,"preSubcommand"),$=this._chainOrCall($,()=>{if(Z._executableHandler)this._executeSubCommand(Z,X.concat(Y));else return Z._parseCommand(X,Y)}),$}_dispatchHelpCommand(Q){if(!Q)this.help();let X=this._findCommand(Q);if(X&&!X._executableHandler)X.help();return this._dispatchSubcommand(Q,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((Q,X)=>{if(Q.required&&this.args[X]==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=(Y,Z,$)=>{let q=Z;if(Z!==null&&Y.parseArg){let _=`error: command-argument value '${Z}' is invalid for argument '${Y.name()}'.`;q=this._callParseArg(Y,Z,$,_)}return q};this._checkNumberOfArguments();let X=[];this.registeredArguments.forEach((Y,Z)=>{let $=Y.defaultValue;if(Y.variadic){if(Z<this.args.length){if($=this.args.slice(Z),Y.parseArg)$=$.reduce((q,_)=>{return Q(Y,_,q)},Y.defaultValue)}else if($===void 0)$=[]}else if(Z<this.args.length){if($=this.args[Z],Y.parseArg)$=Q(Y,$,Y.defaultValue)}X[Z]=$}),this.processedArgs=X}_chainOrCall(Q,X){if(Q?.then&&typeof Q.then==="function")return Q.then(()=>X());return X()}_chainOrCallHooks(Q,X){let Y=Q,Z=[];if(this._getCommandAndAncestors().reverse().filter(($)=>$._lifeCycleHooks[X]!==void 0).forEach(($)=>{$._lifeCycleHooks[X].forEach((q)=>{Z.push({hookedCommand:$,callback:q})})}),X==="postAction")Z.reverse();return Z.forEach(($)=>{Y=this._chainOrCall(Y,()=>{return $.callback($.hookedCommand,this)})}),Y}_chainOrCallSubCommandHook(Q,X,Y){let Z=Q;if(this._lifeCycleHooks[Y]!==void 0)this._lifeCycleHooks[Y].forEach(($)=>{Z=this._chainOrCall(Z,()=>{return $(this,X)})});return Z}_parseCommand(Q,X){let Y=this.parseOptions(X);if(this._parseOptionsEnv(),this._parseOptionsImplied(),Q=Q.concat(Y.operands),X=Y.unknown,this.args=Q.concat(X),Q&&this._findCommand(Q[0]))return this._dispatchSubcommand(Q[0],Q.slice(1),X);if(this._getHelpCommand()&&Q[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(Q[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(X),this._dispatchSubcommand(this._defaultCommandName,Q,X);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(Y.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let Z=()=>{if(Y.unknown.length>0)this.unknownOption(Y.unknown[0])},$=`command:${this.name()}`;if(this._actionHandler){Z(),this._processArguments();let q;if(q=this._chainOrCallHooks(q,"preAction"),q=this._chainOrCall(q,()=>this._actionHandler(this.processedArgs)),this.parent)q=this._chainOrCall(q,()=>{this.parent.emit($,Q,X)});return q=this._chainOrCallHooks(q,"postAction"),q}if(this.parent?.listenerCount($))Z(),this._processArguments(),this.parent.emit($,Q,X);else if(Q.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",Q,X);if(this.listenerCount("command:*"))this.emit("command:*",Q,X);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((X)=>X._name===Q||X._aliases.includes(Q))}_findOption(Q){return this.options.find((X)=>X.is(Q))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((Q)=>{Q.options.forEach((X)=>{if(X.mandatory&&Q.getOptionValue(X.attributeName())===void 0)Q.missingMandatoryOptionValue(X)})})}_checkForConflictingLocalOptions(){let Q=this.options.filter((Y)=>{let Z=Y.attributeName();if(this.getOptionValue(Z)===void 0)return!1;return this.getOptionValueSource(Z)!=="default"});Q.filter((Y)=>Y.conflictsWith.length>0).forEach((Y)=>{let Z=Q.find(($)=>Y.conflictsWith.includes($.attributeName()));if(Z)this._conflictingOption(Y,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((Q)=>{Q._checkForConflictingLocalOptions()})}parseOptions(Q){let X=[],Y=[],Z=X;function $(J){return J.length>1&&J[0]==="-"}let q=(J)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(J))return!1;return!this._getCommandAndAncestors().some((G)=>G.options.map((U)=>U.short).some((U)=>/^-\d$/.test(U)))},_=null,z=null,H=0;while(H<Q.length||z){let J=z??Q[H++];if(z=null,J==="--"){if(Z===Y)Z.push(J);Z.push(...Q.slice(H));break}if(_&&(!$(J)||q(J))){this.emit(`option:${_.name()}`,J);continue}if(_=null,$(J)){let G=this._findOption(J);if(G){if(G.required){let U=Q[H++];if(U===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,U)}else if(G.optional){let U=null;if(H<Q.length&&(!$(Q[H])||q(Q[H])))U=Q[H++];this.emit(`option:${G.name()}`,U)}else this.emit(`option:${G.name()}`);_=G.variadic?G:null;continue}}if(J.length>2&&J[0]==="-"&&J[1]!=="-"){let G=this._findOption(`-${J[1]}`);if(G){if(G.required||G.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${G.name()}`,J.slice(2));else this.emit(`option:${G.name()}`),z=`-${J.slice(2)}`;continue}}if(/^--[^=]+=/.test(J)){let G=J.indexOf("="),U=this._findOption(J.slice(0,G));if(U&&(U.required||U.optional)){this.emit(`option:${U.name()}`,J.slice(G+1));continue}}if(Z===X&&$(J)&&!(this.commands.length===0&&q(J)))Z=Y;if((this._enablePositionalOptions||this._passThroughOptions)&&X.length===0&&Y.length===0){if(this._findCommand(J)){X.push(J),Y.push(...Q.slice(H));break}else if(this._getHelpCommand()&&J===this._getHelpCommand().name()){X.push(J,...Q.slice(H));break}else if(this._defaultCommandName){Y.push(J,...Q.slice(H));break}}if(this._passThroughOptions){Z.push(J,...Q.slice(H));break}Z.push(J)}return{operands:X,unknown:Y}}opts(){if(this._storeOptionsAsProperties){let Q={},X=this.options.length;for(let Y=0;Y<X;Y++){let Z=this.options[Y].attributeName();Q[Z]=Z===this._versionOptionName?this._version:this[Z]}return Q}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((Q,X)=>Object.assign(Q,X.opts()),{})}error(Q,X){if(this._outputConfiguration.outputError(`${Q}
|
|
22
22
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
23
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0});let Y=X||{},Z=Y.exitCode||1,$=Y.code||"commander.error";this._exit(Z,$,Q)}_parseOptionsEnv(){this.options.forEach((Q)=>{if(Q.envVar&&Q.envVar in
|
|
25
|
-
`),this._exit(0,"commander.version",Q)}),this}description(Q,X){if(Q===void 0&&X===void 0)return this._description;if(this._description=Q,X)this._argsDescription=X;return this}summary(Q){if(Q===void 0)return this._summary;return this._summary=Q,this}alias(Q){if(Q===void 0)return this._aliases[0];let X=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)X=this.commands[this.commands.length-1];if(Q===X._name)throw new Error("Command alias can't be the same as its name");let Y=this.parent?._findCommand(Q);if(Y){let Z=[Y.name()].concat(Y.aliases()).join("|");throw new Error(`cannot add alias '${Q}' to command '${this.name()}' as already have command '${Z}'`)}return X._aliases.push(Q),this}aliases(Q){if(Q===void 0)return this._aliases;return Q.forEach((X)=>this.alias(X)),this}usage(Q){if(Q===void 0){if(this._usage)return this._usage;let X=this.registeredArguments.map((Y)=>{return ZX(Y)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?X:[]).join(" ")}return this._usage=Q,this}name(Q){if(Q===void 0)return this._name;return this._name=Q,this}helpGroup(Q){if(Q===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=Q,this}commandsGroup(Q){if(Q===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=Q,this}optionsGroup(Q){if(Q===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=Q,this}_initOptionGroup(Q){if(this._defaultOptionGroup&&!Q.helpGroupHeading)Q.helpGroup(this._defaultOptionGroup)}_initCommandGroup(Q){if(this._defaultCommandGroup&&!Q.helpGroup())Q.helpGroup(this._defaultCommandGroup)}nameFromFilename(Q){return this._name=
|
|
24
|
+
`),this.outputHelp({error:!0});let Y=X||{},Z=Y.exitCode||1,$=Y.code||"commander.error";this._exit(Z,$,Q)}_parseOptionsEnv(){this.options.forEach((Q)=>{if(Q.envVar&&Q.envVar in B.env){let X=Q.attributeName();if(this.getOptionValue(X)===void 0||["default","config","env"].includes(this.getOptionValueSource(X)))if(Q.required||Q.optional)this.emit(`optionEnv:${Q.name()}`,B.env[Q.envVar]);else this.emit(`optionEnv:${Q.name()}`)}})}_parseOptionsImplied(){let Q=new JX(this.options),X=(Y)=>{return this.getOptionValue(Y)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Y))};this.options.filter((Y)=>Y.implied!==void 0&&X(Y.attributeName())&&Q.valueFromOption(this.getOptionValue(Y.attributeName()),Y)).forEach((Y)=>{Object.keys(Y.implied).filter((Z)=>!X(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,Y.implied[Z],"implied")})})}missingArgument(Q){let X=`error: missing required argument '${Q}'`;this.error(X,{code:"commander.missingArgument"})}optionMissingArgument(Q){let X=`error: option '${Q.flags}' argument missing`;this.error(X,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(Q){let X=`error: required option '${Q.flags}' not specified`;this.error(X,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(Q,X){let Y=(q)=>{let _=q.attributeName(),z=this.getOptionValue(_),H=this.options.find((G)=>G.negate&&_===G.attributeName()),J=this.options.find((G)=>!G.negate&&_===G.attributeName());if(H&&(H.presetArg===void 0&&z===!1||H.presetArg!==void 0&&z===H.presetArg))return H;return J||q},Z=(q)=>{let _=Y(q),z=_.attributeName();if(this.getOptionValueSource(z)==="env")return`environment variable '${_.envVar}'`;return`option '${_.flags}'`},$=`error: ${Z(Q)} cannot be used with ${Z(X)}`;this.error($,{code:"commander.conflictingOption"})}unknownOption(Q){if(this._allowUnknownOption)return;let X="";if(Q.startsWith("--")&&this._showSuggestionAfterError){let Z=[],$=this;do{let q=$.createHelp().visibleOptions($).filter((_)=>_.long).map((_)=>_.long);Z=Z.concat(q),$=$.parent}while($&&!$._enablePositionalOptions);X=HQ(Q,Z)}let Y=`error: unknown option '${Q}'${X}`;this.error(Y,{code:"commander.unknownOption"})}_excessArguments(Q){if(this._allowExcessArguments)return;let X=this.registeredArguments.length,Y=X===1?"":"s",$=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${X} argument${Y} but got ${Q.length}.`;this.error($,{code:"commander.excessArguments"})}unknownCommand(){let Q=this.args[0],X="";if(this._showSuggestionAfterError){let Z=[];this.createHelp().visibleCommands(this).forEach(($)=>{if(Z.push($.name()),$.alias())Z.push($.alias())}),X=HQ(Q,Z)}let Y=`error: unknown command '${Q}'${X}`;this.error(Y,{code:"commander.unknownCommand"})}version(Q,X,Y){if(Q===void 0)return this._version;this._version=Q,X=X||"-V, --version",Y=Y||"output the version number";let Z=this.createOption(X,Y);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${Q}
|
|
25
|
+
`),this._exit(0,"commander.version",Q)}),this}description(Q,X){if(Q===void 0&&X===void 0)return this._description;if(this._description=Q,X)this._argsDescription=X;return this}summary(Q){if(Q===void 0)return this._summary;return this._summary=Q,this}alias(Q){if(Q===void 0)return this._aliases[0];let X=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)X=this.commands[this.commands.length-1];if(Q===X._name)throw new Error("Command alias can't be the same as its name");let Y=this.parent?._findCommand(Q);if(Y){let Z=[Y.name()].concat(Y.aliases()).join("|");throw new Error(`cannot add alias '${Q}' to command '${this.name()}' as already have command '${Z}'`)}return X._aliases.push(Q),this}aliases(Q){if(Q===void 0)return this._aliases;return Q.forEach((X)=>this.alias(X)),this}usage(Q){if(Q===void 0){if(this._usage)return this._usage;let X=this.registeredArguments.map((Y)=>{return ZX(Y)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?X:[]).join(" ")}return this._usage=Q,this}name(Q){if(Q===void 0)return this._name;return this._name=Q,this}helpGroup(Q){if(Q===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=Q,this}commandsGroup(Q){if(Q===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=Q,this}optionsGroup(Q){if(Q===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=Q,this}_initOptionGroup(Q){if(this._defaultOptionGroup&&!Q.helpGroupHeading)Q.helpGroup(this._defaultOptionGroup)}_initCommandGroup(Q){if(this._defaultCommandGroup&&!Q.helpGroup())Q.helpGroup(this._defaultCommandGroup)}nameFromFilename(Q){return this._name=D.basename(Q,D.extname(Q)),this}executableDir(Q){if(Q===void 0)return this._executableDir;return this._executableDir=Q,this}helpInformation(Q){let X=this.createHelp(),Y=this._getOutputContext(Q);X.prepareContext({error:Y.error,helpWidth:Y.helpWidth,outputHasColors:Y.hasColors});let Z=X.formatHelp(this,X);if(Y.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext(Q){Q=Q||{};let X=!!Q.error,Y,Z,$;if(X)Y=(_)=>this._outputConfiguration.writeErr(_),Z=this._outputConfiguration.getErrHasColors(),$=this._outputConfiguration.getErrHelpWidth();else Y=(_)=>this._outputConfiguration.writeOut(_),Z=this._outputConfiguration.getOutHasColors(),$=this._outputConfiguration.getOutHelpWidth();return{error:X,write:(_)=>{if(!Z)_=this._outputConfiguration.stripColor(_);return Y(_)},hasColors:Z,helpWidth:$}}outputHelp(Q){let X;if(typeof Q==="function")X=Q,Q=void 0;let Y=this._getOutputContext(Q),Z={error:Y.error,write:Y.write,command:this};this._getCommandAndAncestors().reverse().forEach((q)=>q.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let $=this.helpInformation({error:Y.error});if(X){if($=X($),typeof $!=="string"&&!Buffer.isBuffer($))throw new Error("outputHelp callback must return a string or a Buffer")}if(Y.write($),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Z),this._getCommandAndAncestors().forEach((q)=>q.emit("afterAllHelp",Z))}helpOption(Q,X){if(typeof Q==="boolean"){if(Q){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(Q??"-h, --help",X??"display help for command"),Q||X)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(Q){return this._helpOption=Q,this._initOptionGroup(Q),this}help(Q){this.outputHelp(Q);let X=Number(B.exitCode??0);if(X===0&&Q&&typeof Q!=="function"&&Q.error)X=1;this._exit(X,"commander.help","(outputHelp)")}addHelpText(Q,X){let Y=["beforeAll","before","after","afterAll"];if(!Y.includes(Q))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${Y.join("', '")}'`);let Z=`${Q}Help`;return this.on(Z,($)=>{let q;if(typeof X==="function")q=X({error:$.error,command:$.command});else q=X;if(q)$.write(`${q}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(Q){let X=this._getHelpOption();if(X&&Q.find((Z)=>X.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function
|
|
28
|
-
`);for(let q of $){let _=q.trim();if(!_||_.startsWith("#"))continue;let z=_.matchAll(/<([^>]+)>/g),
|
|
29
|
-
`);for(let
|
|
30
|
-
`);for(let _ of q){let z=_.match(/^\s*(\d+)\s+(.+)$/);if(z){let
|
|
31
|
-
`)[0]||"",
|
|
32
|
-
`).filter((
|
|
33
|
-
`);for(let
|
|
34
|
-
|
|
35
|
-
\
|
|
36
|
-
\uD83D\
|
|
37
|
-
|
|
27
|
+
`)}),this}_outputHelpIfRequested(Q){let X=this._getHelpOption();if(X&&Q.find((Z)=>X.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function UQ(Q){return Q.map((X)=>{if(!X.startsWith("--inspect"))return X;let Y,Z="127.0.0.1",$="9229",q;if((q=X.match(/^(--inspect(-brk)?)$/))!==null)Y=q[1];else if((q=X.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Y=q[1],/^\d+$/.test(q[3]))$=q[3];else Z=q[3];else if((q=X.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Y=q[1],Z=q[3],$=q[4];if(Y&&$!=="0")return`${Y}=${Z}:${parseInt($)+1}`;return X})}function p(){if(B.env.NO_COLOR||B.env.FORCE_COLOR==="0"||B.env.FORCE_COLOR==="false")return!1;if(B.env.FORCE_COLOR||B.env.CLICOLOR_FORCE!==void 0)return!0;return}_X.Command=s;_X.useColor=p});var WQ=y((TX)=>{var{Argument:BQ}=v(),{Command:i}=TQ(),{CommanderError:HX,InvalidArgumentError:RQ}=O(),{Help:UX}=d(),{Option:KQ}=c();TX.program=new i;TX.createCommand=(Q)=>new i(Q);TX.createOption=(Q,X)=>new KQ(Q,X);TX.createArgument=(Q,X)=>new BQ(Q,X);TX.Command=i;TX.Option=KQ;TX.Argument=BQ;TX.Help=UX;TX.CommanderError=HX;TX.InvalidArgumentError=RQ;TX.InvalidOptionArgumentError=RQ});import{readFileSync as dX}from"node:fs";import{dirname as cX,join as lX}from"node:path";import{fileURLToPath as mX}from"node:url";var LQ=OQ(WQ(),1),{program:JY,createCommand:_Y,createArgument:zY,createOption:GY,CommanderError:HY,InvalidArgumentError:UY,InvalidOptionArgumentError:TY,Command:SQ,Argument:BY,Option:RY,Help:KY}=LQ.default;import{join as vX}from"node:path";import{existsSync as jQ}from"node:fs";import{readFile as EX}from"node:fs/promises";import{dirname as IQ,join as VQ,resolve as n}from"node:path";var NX=".gstatxrc.json";function a(Q){let Y=Q.replace(/\.git$/,"").split(/[/:]/);return Y[Y.length-1]||"repository"}function FX(Q){let X=n(Q),Y=20,Z=0;while(Z<Y){let $=VQ(X,NX);if(jQ($))return $;let q=IQ(X);if(q===X)break;X=q,Z++}return null}async function x(Q,X=process.cwd()){try{let Y;if(Q){let _=n(Q);if(!jQ(_))return console.error(`Error: Config file not found: ${_}`),null;Y=_}else if(Y=FX(X),!Y)return null;let Z=await EX(Y,"utf-8"),$=JSON.parse(Z),q=IQ(Y);if($.repositories)$.repositories=$.repositories.map((_)=>{if(!_.path&&_.url){let z=a(_.url);return{..._,path:VQ(q,z),name:_.name||z}}if(_.path)return{..._,path:n(q,_.path)};return _});return{config:$,configDir:q}}catch(Y){if(Q)console.error(`Error: Failed to load config file: ${Y}`);return null}}import{exec as yX,execSync as AX}from"node:child_process";import{access as MQ,readFile as kX}from"node:fs/promises";import{join as t}from"node:path";import{promisify as wX}from"node:util";var k=wX(yX);async function DQ(Q){try{return await MQ(t(Q,".mailmap")),!0}catch{return!1}}async function PX(Q){let X=new Map;try{let Y=t(Q,".mailmap"),$=(await kX(Y,"utf-8")).split(`
|
|
28
|
+
`);for(let q of $){let _=q.trim();if(!_||_.startsWith("#"))continue;let z=_.matchAll(/<([^>]+)>/g),H=Array.from(z).map((J)=>J[1]?.trim()).filter((J)=>J!==void 0);if(H.length>=2){let J=H[0];if(J){let G=J.toLowerCase();for(let U=1;U<H.length;U++){let T=H[U];if(T)X.set(T.toLowerCase(),G)}}}}}catch{}return X}async function w(Q){try{return await MQ(t(Q,".git")),!0}catch{return!1}}async function r(Q){try{await EQ(Q);let X=await DQ(Q),Y=new Map;if(X){let $=await PX(Q),{stdout:q}=await k("git log --all --format='%aN|%aE' --use-mailmap",{cwd:Q}),_=new Map,z=q.trim().split(`
|
|
29
|
+
`);for(let H of z){if(!H.trim())continue;let[J,G]=H.split("|");if(!J||!G)continue;let U=G.toLowerCase(),T=$.get(U);if(T)U=T;let R=Y.get(U);if(!_.has(U))_.set(U,new Map);let W=_.get(U);if(W)W.set(J,(W.get(J)||0)+1);if(R)Y.set(U,{...R,commits:R.commits+1});else{let K=T||G;Y.set(U,{name:J,email:K,commits:1,maxIndividualCommits:1})}}for(let[H,J]of _.entries()){let G=Y.get(H);if(G){let U=0,T=G.name;for(let[R,W]of J.entries())if(W>U)U=W,T=R;Y.set(H,{...G,name:T})}}}else{let{stdout:$}=await k("git shortlog -sn --all",{cwd:Q}),q=$.trim().split(`
|
|
30
|
+
`);for(let _ of q){let z=_.match(/^\s*(\d+)\s+(.+)$/);if(z){let H=parseInt(z[1]||"0",10),J=z[2]||"",{stdout:G}=await k(`git log --all --format='%aE' --author="${J.replace(/"/g,"\\\"")}" -1`,{cwd:Q}),U=G.trim().split(`
|
|
31
|
+
`)[0]||"",T=U.toLowerCase(),R=Y.get(T);if(R){let W=R.commits+H;if(H>R.maxIndividualCommits)Y.set(T,{name:J,email:U,commits:W,maxIndividualCommits:H});else Y.set(T,{...R,commits:W})}else Y.set(T,{name:J,email:U,commits:H,maxIndividualCommits:H})}}}return Array.from(Y.values()).map(($)=>({name:$.name,email:$.email,commits:$.commits})).sort(($,q)=>q.commits-$.commits)}catch(X){throw new Error(`Failed to get contributors from ${Q}: ${X}`)}}async function EQ(Q){try{await k("git fetch --all --prune",{cwd:Q})}catch{}}async function o(Q,X,Y){await EQ(Q);let q=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await DQ(Q)?" --use-mailmap":""}`;if(X)q+=` --since="${X}"`;if(Y)q+=` --until="${Y}"`;let _=AX(q,{encoding:"utf-8",cwd:Q,maxBuffer:10485760}),z=[],H=_.split(`
|
|
32
|
+
`).filter((W)=>W.trim()),J=null,G=0,U=0,T=0,R=[];for(let W of H)if(W.includes("|")){if(J?.hash&&J?.author&&J?.email&&J?.date&&J?.message)z.push({hash:J.hash,author:J.author,email:J.email,date:J.date,message:J.message,filesChanged:G,insertions:U,deletions:T,files:R,branches:Array.isArray(J.branches)?J.branches:[]});let K=W.split("|");if(K.length>=5){let I=K[0]?.trim(),M=K[1]?.trim(),V=K[2]?.trim(),L=K[3]?.trim(),S=K[4]?.trim(),j=(K[5]?.trim()||"").trim();if(I&&M&&V&&L){let E=[];if(j){let N=j.split(",").map((F)=>F.trim());for(let F of N)if(F.startsWith("HEAD ->")){let A=F.match(/HEAD -> (.+)/);if(A?.[1]){let g=A[1].trim().replace(/^(origin|upstream|remote)\//,"");if(g&&!E.includes(g))E.push(g)}}else if(!F.startsWith("tag:")&&!F.startsWith("HEAD")){let A=F.replace(/^(origin|upstream|remote)\//,"");if(A&&!E.includes(A))E.push(A)}}J={hash:I,author:M,email:V,date:L,message:S,branches:E},G=0,U=0,T=0,R=[]}}}else{let K=W.trim().split(/\s+/);if(K.length>=2&&K[0]&&K[1]){let I=parseInt(K[0],10)||0,M=parseInt(K[1],10)||0,V=K.slice(2).join(" ");if(V&&!Number.isNaN(I)&&!Number.isNaN(M))G++,U+=I,T+=M,R.push({path:V,insertions:I,deletions:M})}}if(J?.hash&&J?.author&&J?.email&&J?.date&&J?.message)z.push({hash:J.hash,author:J.author,email:J.email,date:J.date,message:J.message,filesChanged:G,insertions:U,deletions:T,files:R,branches:Array.isArray(J.branches)?J.branches:[]});try{let{stdout:W}=await k("git branch -a",{cwd:Q}),K=W.trim().split(`
|
|
33
|
+
`),I=[],M=new Set;for(let L of K){if(!L.trim())continue;let S=L.replace(/^\*\s*/,"").trim();if(!S||S.startsWith("HEAD"))continue;let j=S.replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(j&&!M.has(j))M.add(j),I.push({ref:S,cleanName:j});else if(j)I.push({ref:S,cleanName:j})}let V=new Map;for(let{ref:L,cleanName:S}of I)try{let{stdout:j}=await k(`git rev-list ${L}`,{cwd:Q}),E=j.trim().split(`
|
|
34
|
+
`).filter((N)=>N.trim());for(let N of E){if(!V.has(N))V.set(N,new Set);V.get(N)?.add(S)}}catch{}for(let L of z)if(L.hash){let S=V.get(L.hash);if(S&&S.size>0){let j=[...new Set([...L.branches,...Array.from(S)])];L.branches=j}else L.branches=L.branches||[]}}catch{}return z}import{exec as OX}from"node:child_process";import{existsSync as NQ}from"node:fs";import{mkdir as xX}from"node:fs/promises";import{dirname as CX}from"node:path";import{promisify as bX}from"node:util";var h=bX(OX);async function e(Q,X=!0){if(!Q.path)return console.error(`Error: Repository ${Q.name||"unknown"} has no path specified`),null;if(NQ(Q.path)&&await w(Q.path)){if(X)try{console.log(`Fetching all remote branches for ${Q.name||Q.path}...`),await h("git fetch --all --prune",{cwd:Q.path}),console.log(`Pulling latest changes for ${Q.name||Q.path}...`),await h("git pull",{cwd:Q.path}),console.log(`✓ Successfully updated ${Q.name||Q.path}`)}catch(Y){console.warn(`Warning: Failed to update ${Q.path}: ${Y}. Continuing with existing code.`)}return Q.path}if(NQ(Q.path))return console.error(`Error: Path exists but is not a git repository: ${Q.path}`),null;if(!Q.url)return console.error(`Error: Repository not found at ${Q.path} and no URL provided for cloning`),null;try{console.log(`Cloning repository from ${Q.url} to ${Q.path}...`);let Y=CX(Q.path),Z=Q.path.split("/").pop()||"repository";try{await xX(Y,{recursive:!0})}catch($){}await h(`git clone "${Q.url}" "${Q.path}"`);try{await h("git fetch --all --prune",{cwd:Q.path})}catch($){}return console.log(`✓ Successfully cloned ${Q.name||Z}`),Q.path}catch(Y){return console.error(`Error: Failed to clone repository: ${Y}`),null}}class C{config;loadedConfig=null;constructor(Q={}){this.config=Q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await x(this.config.configPath),this.loadedConfig?.config.repositories)this.config.repositories=this.loadedConfig.config.repositories;if(this.loadedConfig?.config)this.config={...this.loadedConfig.config,...this.config,repositories:this.config.repositories||this.loadedConfig.config.repositories}}if(this.config.repositories)this.config.repositories=this.config.repositories.map((Q)=>{if(!Q.path&&Q.url){let X=this.loadedConfig?.configDir||process.cwd(),Y=a(Q.url);return{...Q,path:vX(X,Y),name:Q.name||Y}}return Q});if(this.config.cloneIfNotExists&&this.config.repositories){let Q=this.config.pullIfExists??!0,X=[];for(let Y of this.config.repositories){if(!Y.path){console.error(`
|
|
35
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${Y.name||"unknown"} has no path and no URL\x1B[0m`),X.push("");continue}let Z=await e(Y,Q);if(Z)X.push(Z);else X.push(Y.path)}this.config.repositories=this.config.repositories.map((Y,Z)=>({...Y,path:X[Z]||Y.path}))}}getRepoPaths(Q){if(Q&&Q.length>0)return Q;if(this.config.repositories)return this.config.repositories.map((X)=>X.path).filter((X)=>X!==void 0);return[]}async listContributors(Q){await this.initialize();let X=this.getRepoPaths(Q);if(X.length===0)throw new Error("No repository paths specified");let Y=[];for(let Z of X){if(!await w(Z))throw new Error(`${Z} is not a git repository`);try{let q=await r(Z);Y.push({path:Z,contributors:q})}catch(q){throw new Error(`Failed to get contributors from ${Z}: ${q}`)}}return Y}async getHistory(Q,X,Y){await this.initialize();let Z=this.getRepoPaths(Q);if(Z.length===0)throw new Error("No repository paths specified");let $=[];for(let q of Z){if(!await w(q))throw new Error(`${q} is not a git repository`);try{let z=await o(q,X,Y);$.push({path:q,commits:z})}catch(z){throw new Error(`Failed to get commit history from ${q}: ${z}`)}}return $}}async function FQ(Q,X=!0,Y,Z="text",$=!1){let q=new C({configPath:Y});try{let _=await q.listContributors(Q);if($){let z=new Map;for(let J of _)for(let G of J.contributors){let U=G.email.toLowerCase(),T=z.get(U);if(T){let R=T.commits+G.commits;if(G.commits>T.maxIndividualCommits)z.set(U,{name:G.name,email:G.email,commits:R,maxIndividualCommits:G.commits});else z.set(U,{...T,commits:R})}else z.set(U,{name:G.name,email:G.email,commits:G.commits,maxIndividualCommits:G.commits})}let H=Array.from(z.values()).sort((J,G)=>G.commits-J.commits);if(Z==="json"){let J=H.map((G)=>({name:G.name,email:G.email,...X&&{commits:G.commits}}));console.log(JSON.stringify(J,null,2));return}if(console.log(`
|
|
36
|
+
\uD83D\uDCE7 Unique email addresses:`),console.log("─".repeat(60)),H.length===0)console.log(" No contributors found");else for(let J of H)if(X)console.log(` ${J.name} <${J.email}> (${J.commits} commits)`);else console.log(` ${J.name} <${J.email}>`);return}if(Z==="json"){let z=_.map((H)=>({path:H.path,contributors:H.contributors.map((J)=>({name:J.name,email:J.email,...X&&{commits:J.commits}}))}));console.log(JSON.stringify(z,null,2));return}for(let z of _)if(console.log(`
|
|
37
|
+
\uD83D\uDCCA Contributors for ${z.path}:`),console.log("─".repeat(60)),z.contributors.length===0)console.log(" No contributors found");else for(let H of z.contributors)if(X)console.log(` ${H.name} <${H.email}> (${H.commits} commits)`);else console.log(` ${H.name} <${H.email}>`)}catch(_){let z=_ instanceof Error?_.message:String(_);console.error(`
|
|
38
|
+
❌ \x1B[31mError processing repositories:\x1B[0m \x1B[91m${z}\x1B[0m`),process.exit(1)}}import{mkdirSync as fX,writeFileSync as hX}from"node:fs";import{dirname as gX,resolve as uX}from"node:path";async function yQ(Q,X={},Y){let Z=new C({configPath:Y});try{let $=await Z.getHistory(Q,X.since,X.until),q={generatedAt:new Date().toISOString(),period:{since:X.since,until:X.until},repositories:$.map((z)=>{let H=new Set(z.commits.flatMap((U)=>U.files.map((T)=>T.path))).size,J=z.commits.reduce((U,T)=>U+T.insertions,0),G=z.commits.reduce((U,T)=>U+T.deletions,0);return{path:z.path,commits:z.commits,summary:{totalCommits:z.commits.length,totalFilesChanged:H,totalInsertions:J,totalDeletions:G}}})},_=JSON.stringify(q,null,2);if(X.out){let z=uX(process.cwd(),X.out),H=gX(z);fX(H,{recursive:!0}),hX(z,_,"utf-8"),console.log(`✅ Report saved to: ${z}`),console.log(`
|
|
38
39
|
\uD83D\uDCCA Summary:`);for(let J of q.repositories)console.log(`
|
|
39
40
|
Repository: ${J.path}`),console.log(` Commits: ${J.summary.totalCommits}`),console.log(` Files Changed: ${J.summary.totalFilesChanged}`),console.log(` Lines Added: ${J.summary.totalInsertions.toLocaleString()}`),console.log(` Lines Removed: ${J.summary.totalDeletions.toLocaleString()}`)}else console.log(_)}catch($){let q=$ instanceof Error?$.message:String($);console.error(`
|
|
40
|
-
❌ \x1B[31mError generating history report:\x1B[0m \x1B[91m${q}\x1B[0m`),process.exit(1)}}var pX=mX(import.meta.url),sX=cX(pX),iX=lX(sX,"..","package.json"),nX=JSON.parse(dX(iX,"utf-8")),aX=nX.version,
|
|
41
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${
|
|
41
|
+
❌ \x1B[31mError generating history report:\x1B[0m \x1B[91m${q}\x1B[0m`),process.exit(1)}}var pX=mX(import.meta.url),sX=cX(pX),iX=lX(sX,"..","package.json"),nX=JSON.parse(dX(iX,"utf-8")),aX=nX.version,b=new SQ;b.name("gstatx").description("A CLI tool to export statistics from git repositories").version(aX).option("-c, --config <path>","Specify custom config file path").configureHelp({helpWidth:100});b.command("contributors").description("List contributors for specified repositories").option("--no-commits","Hide commit counts in contributor list").option("-f, --format <format>","Output format: 'json' or 'text' (default: 'text')").option("-u, --unique-emails","List unique email addresses only (deduplicates by email)").argument("[repo-paths...]","Repository paths").action(async(Q,X,Y)=>{let Z=Y.parent?.opts().config??".gstatxrc.json",$=await x(Z),q=$?.config.contributors?.["no-commits"]??!1,_=!(X.noCommits||q),z=$?.config.contributors?.format||"text",H=X.format||z;if(H!=="json"&&H!=="text")console.error(`
|
|
42
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${H}'. Must be 'json' or 'text'\x1B[0m`),process.exit(1);let J=Q.length===0?void 0:Q,G=X.uniqueEmails||!1;await FQ(J,_,Z,H,G)}).addHelpText("after",`
|
|
42
43
|
Examples:
|
|
43
44
|
gstatx contributors ./my-repo
|
|
44
45
|
gstatx contributors ./repo1 ./repo2
|
|
45
46
|
gstatx contributors --no-commits ./my-repo
|
|
46
47
|
gstatx contributors --format json ./my-repo
|
|
47
|
-
gstatx contributors --unique-emails ./my-repo`);
|
|
48
|
+
gstatx contributors --unique-emails ./my-repo`);b.command("hist").description("Generate commit history report").option("-s, --since <date>",'Start date for the report (e.g., "2024-01-01", "1 month ago")').option("-u, --until <date>",'End date for the report (e.g., "2024-12-31", "now") (default: "now")').option("-o, --out <file>","Output file path (defaults to stdout)").argument("[repo-paths...]","Repository paths").action(async(Q,X,Y)=>{let Z=Y.parent?.opts().config??".gstatxrc.json",$={since:X.since,until:X.until??"now",out:X.out},q=Q.length===0?void 0:Q;await yQ(q,$,Z)}).addHelpText("after",`
|
|
48
49
|
Examples:
|
|
49
50
|
gstatx hist ./my-repo
|
|
50
51
|
gstatx hist --since "1 month ago" ./my-repo
|
|
51
52
|
gstatx hist --since "2024-01-01" --until "2024-12-31" ./my-repo
|
|
52
|
-
gstatx hist --since "1 month ago" --out report.json ./my-repo`);
|
|
53
|
+
gstatx hist --since "1 month ago" --out report.json ./my-repo`);b.addHelpText("after",`
|
|
53
54
|
Configuration:
|
|
54
55
|
You can create a .gstatxrc.json file to set default options
|
|
55
56
|
and repository paths. CLI arguments override config values.
|
|
@@ -57,4 +58,4 @@ Configuration:
|
|
|
57
58
|
that don't exist locally (requires 'url' in repository config).
|
|
58
59
|
Set 'pullIfExists: true' (default) to pull latest changes for
|
|
59
60
|
existing repositories, or 'pullIfExists: false' to skip updating.
|
|
60
|
-
`);
|
|
61
|
+
`);b.parse();
|
package/dist/lib.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import{join as
|
|
2
|
-
`);for(let
|
|
3
|
-
`);for(let
|
|
4
|
-
`);for(let
|
|
5
|
-
`)[0]||"",k=
|
|
6
|
-
`).filter((
|
|
7
|
-
`);for(let
|
|
8
|
-
|
|
1
|
+
import{join as Kq}from"node:path";import{existsSync as f}from"node:fs";import{readFile as p}from"node:fs/promises";import{dirname as d,join as P,resolve as E}from"node:path";var m=".gstatxrc.json";function M(q){let J=q.replace(/\.git$/,"").split(/[/:]/);return J[J.length-1]||"repository"}function s(q){let Q=E(q),J=20,Z=0;while(Z<J){let X=P(Q,m);if(f(X))return X;let V=d(Q);if(V===Q)break;Q=V,Z++}return null}async function N(q,Q=process.cwd()){try{let J;if(q){let W=E(q);if(!f(W))return console.error(`Error: Config file not found: ${W}`),null;J=W}else if(J=s(Q),!J)return null;let Z=await p(J,"utf-8"),X=JSON.parse(Z),V=d(J);if(X.repositories)X.repositories=X.repositories.map((W)=>{if(!W.path&&W.url){let $=M(W.url);return{...W,path:P(V,$),name:W.name||$}}if(W.path)return{...W,path:E(V,W.path)};return W});return{config:X,configDir:V}}catch(J){if(q)console.error(`Error: Failed to load config file: ${J}`);return null}}import{exec as n,execSync as i}from"node:child_process";import{access as u,readFile as a}from"node:fs/promises";import{join as b}from"node:path";import{promisify as t}from"node:util";var A=t(n);async function h(q){try{return await u(b(q,".mailmap")),!0}catch{return!1}}async function o(q){let Q=new Map;try{let J=b(q,".mailmap"),X=(await a(J,"utf-8")).split(`
|
|
2
|
+
`);for(let V of X){let W=V.trim();if(!W||W.startsWith("#"))continue;let $=W.matchAll(/<([^>]+)>/g),H=Array.from($).map((K)=>K[1]?.trim()).filter((K)=>K!==void 0);if(H.length>=2){let K=H[0];if(K){let _=K.toLowerCase();for(let Y=1;Y<H.length;Y++){let k=H[Y];if(k)Q.set(k.toLowerCase(),_)}}}}}catch{}return Q}async function R(q){try{return await u(b(q,".git")),!0}catch{return!1}}async function x(q){try{await l(q);let Q=await h(q),J=new Map;if(Q){let X=await o(q),{stdout:V}=await A("git log --all --format='%aN|%aE' --use-mailmap",{cwd:q}),W=new Map,$=V.trim().split(`
|
|
3
|
+
`);for(let H of $){if(!H.trim())continue;let[K,_]=H.split("|");if(!K||!_)continue;let Y=_.toLowerCase(),k=X.get(Y);if(k)Y=k;let O=J.get(Y);if(!W.has(Y))W.set(Y,new Map);let G=W.get(Y);if(G)G.set(K,(G.get(K)||0)+1);if(O)J.set(Y,{...O,commits:O.commits+1});else{let U=k||_;J.set(Y,{name:K,email:U,commits:1,maxIndividualCommits:1})}}for(let[H,K]of W.entries()){let _=J.get(H);if(_){let Y=0,k=_.name;for(let[O,G]of K.entries())if(G>Y)Y=G,k=O;J.set(H,{..._,name:k})}}}else{let{stdout:X}=await A("git shortlog -sn --all",{cwd:q}),V=X.trim().split(`
|
|
4
|
+
`);for(let W of V){let $=W.match(/^\s*(\d+)\s+(.+)$/);if($){let H=parseInt($[1]||"0",10),K=$[2]||"",{stdout:_}=await A(`git log --all --format='%aE' --author="${K.replace(/"/g,"\\\"")}" -1`,{cwd:q}),Y=_.trim().split(`
|
|
5
|
+
`)[0]||"",k=Y.toLowerCase(),O=J.get(k);if(O){let G=O.commits+H;if(H>O.maxIndividualCommits)J.set(k,{name:K,email:Y,commits:G,maxIndividualCommits:H});else J.set(k,{...O,commits:G})}else J.set(k,{name:K,email:Y,commits:H,maxIndividualCommits:H})}}}return Array.from(J.values()).map((X)=>({name:X.name,email:X.email,commits:X.commits})).sort((X,V)=>V.commits-X.commits)}catch(Q){throw new Error(`Failed to get contributors from ${q}: ${Q}`)}}async function l(q){try{await A("git fetch --all --prune",{cwd:q})}catch{}}async function C(q,Q,J){await l(q);let V=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await h(q)?" --use-mailmap":""}`;if(Q)V+=` --since="${Q}"`;if(J)V+=` --until="${J}"`;let W=i(V,{encoding:"utf-8",cwd:q,maxBuffer:10485760}),$=[],H=W.split(`
|
|
6
|
+
`).filter((G)=>G.trim()),K=null,_=0,Y=0,k=0,O=[];for(let G of H)if(G.includes("|")){if(K?.hash&&K?.author&&K?.email&&K?.date&&K?.message)$.push({hash:K.hash,author:K.author,email:K.email,date:K.date,message:K.message,filesChanged:_,insertions:Y,deletions:k,files:O,branches:Array.isArray(K.branches)?K.branches:[]});let U=G.split("|");if(U.length>=5){let T=U[0]?.trim(),I=U[1]?.trim(),v=U[2]?.trim(),j=U[3]?.trim(),w=U[4]?.trim(),S=(U[5]?.trim()||"").trim();if(T&&I&&v&&j){let z=[];if(S){let D=S.split(",").map((B)=>B.trim());for(let B of D)if(B.startsWith("HEAD ->")){let L=B.match(/HEAD -> (.+)/);if(L?.[1]){let y=L[1].trim().replace(/^(origin|upstream|remote)\//,"");if(y&&!z.includes(y))z.push(y)}}else if(!B.startsWith("tag:")&&!B.startsWith("HEAD")){let L=B.replace(/^(origin|upstream|remote)\//,"");if(L&&!z.includes(L))z.push(L)}}K={hash:T,author:I,email:v,date:j,message:w,branches:z},_=0,Y=0,k=0,O=[]}}}else{let U=G.trim().split(/\s+/);if(U.length>=2&&U[0]&&U[1]){let T=parseInt(U[0],10)||0,I=parseInt(U[1],10)||0,v=U.slice(2).join(" ");if(v&&!Number.isNaN(T)&&!Number.isNaN(I))_++,Y+=T,k+=I,O.push({path:v,insertions:T,deletions:I})}}if(K?.hash&&K?.author&&K?.email&&K?.date&&K?.message)$.push({hash:K.hash,author:K.author,email:K.email,date:K.date,message:K.message,filesChanged:_,insertions:Y,deletions:k,files:O,branches:Array.isArray(K.branches)?K.branches:[]});try{let{stdout:G}=await A("git branch -a",{cwd:q}),U=G.trim().split(`
|
|
7
|
+
`),T=[],I=new Set;for(let j of U){if(!j.trim())continue;let w=j.replace(/^\*\s*/,"").trim();if(!w||w.startsWith("HEAD"))continue;let S=w.replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(S&&!I.has(S))I.add(S),T.push({ref:w,cleanName:S});else if(S)T.push({ref:w,cleanName:S})}let v=new Map;for(let{ref:j,cleanName:w}of T)try{let{stdout:S}=await A(`git rev-list ${j}`,{cwd:q}),z=S.trim().split(`
|
|
8
|
+
`).filter((D)=>D.trim());for(let D of z){if(!v.has(D))v.set(D,new Set);v.get(D)?.add(w)}}catch{}for(let j of $)if(j.hash){let w=v.get(j.hash);if(w&&w.size>0){let S=[...new Set([...j.branches,...Array.from(w)])];j.branches=S}else j.branches=j.branches||[]}}catch{}return $}import{exec as r}from"node:child_process";import{existsSync as c}from"node:fs";import{mkdir as e}from"node:fs/promises";import{dirname as qq}from"node:path";import{promisify as Jq}from"node:util";var F=Jq(r);async function g(q,Q=!0){if(!q.path)return console.error(`Error: Repository ${q.name||"unknown"} has no path specified`),null;if(c(q.path)&&await R(q.path)){if(Q)try{console.log(`Fetching all remote branches for ${q.name||q.path}...`),await F("git fetch --all --prune",{cwd:q.path}),console.log(`Pulling latest changes for ${q.name||q.path}...`),await F("git pull",{cwd:q.path}),console.log(`✓ Successfully updated ${q.name||q.path}`)}catch(J){console.warn(`Warning: Failed to update ${q.path}: ${J}. Continuing with existing code.`)}return q.path}if(c(q.path))return console.error(`Error: Path exists but is not a git repository: ${q.path}`),null;if(!q.url)return console.error(`Error: Repository not found at ${q.path} and no URL provided for cloning`),null;try{console.log(`Cloning repository from ${q.url} to ${q.path}...`);let J=qq(q.path),Z=q.path.split("/").pop()||"repository";try{await e(J,{recursive:!0})}catch(X){}await F(`git clone "${q.url}" "${q.path}"`);try{await F("git fetch --all --prune",{cwd:q.path})}catch(X){}return console.log(`✓ Successfully cloned ${q.name||Z}`),q.path}catch(J){return console.error(`Error: Failed to clone repository: ${J}`),null}}class Qq{config;loadedConfig=null;constructor(q={}){this.config=q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await N(this.config.configPath),this.loadedConfig?.config.repositories)this.config.repositories=this.loadedConfig.config.repositories;if(this.loadedConfig?.config)this.config={...this.loadedConfig.config,...this.config,repositories:this.config.repositories||this.loadedConfig.config.repositories}}if(this.config.repositories)this.config.repositories=this.config.repositories.map((q)=>{if(!q.path&&q.url){let Q=this.loadedConfig?.configDir||process.cwd(),J=M(q.url);return{...q,path:Kq(Q,J),name:q.name||J}}return q});if(this.config.cloneIfNotExists&&this.config.repositories){let q=this.config.pullIfExists??!0,Q=[];for(let J of this.config.repositories){if(!J.path){console.error(`
|
|
9
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${J.name||"unknown"} has no path and no URL\x1B[0m`),Q.push("");continue}let Z=await g(J,q);if(Z)Q.push(Z);else Q.push(J.path)}this.config.repositories=this.config.repositories.map((J,Z)=>({...J,path:Q[Z]||J.path}))}}getRepoPaths(q){if(q&&q.length>0)return q;if(this.config.repositories)return this.config.repositories.map((Q)=>Q.path).filter((Q)=>Q!==void 0);return[]}async listContributors(q){await this.initialize();let Q=this.getRepoPaths(q);if(Q.length===0)throw new Error("No repository paths specified");let J=[];for(let Z of Q){if(!await R(Z))throw new Error(`${Z} is not a git repository`);try{let V=await x(Z);J.push({path:Z,contributors:V})}catch(V){throw new Error(`Failed to get contributors from ${Z}: ${V}`)}}return J}async getHistory(q,Q,J){await this.initialize();let Z=this.getRepoPaths(q);if(Z.length===0)throw new Error("No repository paths specified");let X=[];for(let V of Z){if(!await R(V))throw new Error(`${V} is not a git repository`);try{let $=await C(V,Q,J);X.push({path:V,commits:$})}catch($){throw new Error(`Failed to get commit history from ${V}: ${$}`)}}return X}}export{N as loadConfig,R as isGitRepo,x as getContributors,C as getCommits,g as ensureRepository,Qq as Client};
|