gstatx 0.2.7 → 0.2.9
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 +16 -45
- package/dist/lib.js +2 -8
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,55 +1,26 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
3
|
-
`)}displayWidth(Q){return ZQ(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
|
-
`+" ".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()],R=this.displayWidth(z[0]);_.forEach((J)=>{let G=this.displayWidth(J);if(R+G<=X){z.push(J),R+=G;return}$.push(z.join(""));let T=J.trimStart();z=[T],R=this.displayWidth(T)}),$.push(z.join(""))}),$.join(`
|
|
6
|
-
`)}}function ZQ(Q){let X=/\x1b\[\d*(;\d*)*m/g;return Q.replace(X,"")}lQ.Help=YQ;lQ.stripColor=ZQ});var u=M((nQ)=>{var{InvalidArgumentError:sQ}=k();class qQ{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 $Q(this.name().replace(/^no-/,""));return $Q(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 JQ{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 $Q(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}
|
|
2
|
+
import{createRequire as CQ} from"node:module";var kQ=Object.create;var{defineProperty:QQ,getPrototypeOf:wQ,getOwnPropertyNames:PQ}=Object;var OQ=Object.prototype.hasOwnProperty;var xQ=(Q,X,Y)=>{Y=Q!=null?kQ(wQ(Q)):{};const Z=X||!Q||!Q.__esModule?QQ(Y,"default",{value:Q,enumerable:!0}):Y;for(let $ of PQ(Q))if(!OQ.call(Z,$))QQ(Z,$,{get:()=>Q[$],enumerable:!0});return Z};var F=(Q,X)=>()=>(X||Q((X={exports:{}}).exports,X),X.exports);var w=CQ(import.meta.url);var P=F((bQ)=>{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}}bQ.CommanderError=u;bQ.InvalidArgumentError=XQ});var b=F((uQ)=>{var gQ=function(Q){const X=Q.name()+(Q.variadic===!0?"...":"");return Q.required?"<"+X+">":"["+X+"]"},{InvalidArgumentError:hQ}=P();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 hQ(`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}}uQ.Argument=YQ;uQ.humanReadableArgName=gQ});var d=F((mQ)=>{var $Q=function(Q){const X=/\x1b\[\d*(;\d*)*m/g;return Q.replace(X,"")},{humanReadableArgName:lQ}=b();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){const 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){const Y=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return Y(Q).localeCompare(Y(X))}visibleOptions(Q){const X=Q.options.filter((Z)=>!Z.hidden),Y=Q._getHelpOption();if(Y&&!Y.hidden){const 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[];const X=[];for(let Y=Q.parent;Y;Y=Y.parent){const 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){const X=Q.registeredArguments.map((Y)=>lQ(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){const 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){const Y=`(${X.join(", ")})`;if(Q.description)return`${Q.description} ${Y}`;return Y}return Q.description}argumentDescription(Q){const 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){const 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){const Z=new Map;return Q.forEach(($)=>{const q=Y($);if(!Z.has(q))Z.set(q,[])}),X.forEach(($)=>{const q=Y($);if(!Z.has(q))Z.set(q,[]);Z.get(q).push($)}),Z}formatHelp(Q,X){const 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))}`,""];const _=X.commandDescription(Q);if(_.length>0)q=q.concat([X.boxWrap(X.styleCommandDescription(_),Z),""]);const 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)=>{const 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){const 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)=>{const 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("\n")}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){const q=" ".repeat(2);if(!Y)return q+Q;const _=Q.padEnd(X+Q.length-Z.displayWidth(Q)),z=2,J=(this.helpWidth??80)-X-z-2;let G;if(J<this.minWidthToWrap||Z.preformatted(Y))G=Y;else G=Z.boxWrap(Y,J).replace(/\n/g,"\n"+" ".repeat(X+z));return q+_+" ".repeat(z)+G.replace(/\n/g,`\n${q}`)}boxWrap(Q,X){if(X<this.minWidthToWrap)return Q;const Y=Q.split(/\r\n|\n/),Z=/[\s]*[^\s]+/g,$=[];return Y.forEach((q)=>{const _=q.match(Z);if(_===null){$.push("");return}let z=[_.shift()],H=this.displayWidth(z[0]);_.forEach((J)=>{const G=this.displayWidth(J);if(H+G<=X){z.push(J),H+=G;return}$.push(z.join(""));const U=J.trimStart();z=[U],H=this.displayWidth(U)}),$.push(z.join(""))}),$.join("\n")}}mQ.Help=ZQ;mQ.stripColor=$Q});var c=F((aQ)=>{var qQ=function(Q){return Q.split("-").reduce((X,Y)=>{return X+Y[0].toUpperCase()+Y.slice(1)})},nQ=function(Q){let X,Y;const 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("-")){const _=q[0],z=`option creation failed due to '${_}' in option flags '${Q}'`;if(/^-[^-][^-]/.test(_))throw new Error(`${z}
|
|
7
3
|
- a short flag is a single dash and a single character
|
|
8
4
|
- either use a single dash and a single character (for a short flag)
|
|
9
5
|
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(_))throw new Error(`${z}
|
|
10
6
|
- too many short flags`);if($.test(_))throw new Error(`${z}
|
|
11
7
|
- 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.
|
|
13
|
-
(
|
|
14
|
-
|
|
15
|
-
-
|
|
16
|
-
|
|
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 zQ)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,R)=>{let J=_.exec(z);return J?J[0]:R},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(H.versions?.electron)X.from="electron";let Z=H.execArgv??[];if(Z.includes("-e")||Z.includes("--eval")||Z.includes("-p")||Z.includes("--print"))X.from="eval"}if(Q===void 0)Q=H.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(H.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(b.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
|
|
8
|
+
- 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}},{InvalidArgumentError:iQ}=P();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;const Y=nQ(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 iQ(`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){const Y=X.attributeName();if(!this.dualOptions.has(Y))return!0;const Z=this.negativeOptions.get(Y).presetArg,$=Z!==void 0?Z:!1;return X.negate===($===Q)}}aQ.Option=JQ;aQ.DualOptions=_Q});var zQ=F((QX)=>{var oQ=function(Q,X){if(Math.abs(Q.length-X.length)>3)return Math.max(Q.length,X.length);const 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]},eQ=function(Q,X){if(!X||X.length===0)return"";X=Array.from(new Set(X));const Y=Q.startsWith("--");if(Y)Q=Q.slice(2),X=X.map((_)=>_.slice(2));let Z=[],$=3;const q=0.4;if(X.forEach((_)=>{if(_.length<=1)return;const z=oQ(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`\n(Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`\n(Did you mean ${Z[0]}?)`;return""};QX.suggestSimilar=eQ});var TQ=F((zX)=>{var UQ=function(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})},p=function(){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},YX=w("node:events").EventEmitter,l=w("node:child_process"),E=w("node:path"),v=w("node:fs"),B=w("node:process"),{Argument:ZX,humanReadableArgName:$X}=b(),{CommanderError:m}=P(),{Help:qX,stripColor:JX}=d(),{Option:GQ,DualOptions:_X}=c(),{suggestSimilar:HQ}=zQ();class s extends YX{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)=>JX(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(){const 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;$=$||{};const[,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 qX,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
|
|
9
|
+
- 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 ZX(Q,X)}argument(Q,X,Y,Z){const $=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){const 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}const 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){const Y=["preSubcommand","preAction","postAction"];if(!Y.includes(Q))throw new Error(`Unexpected value for event passed to hook : '${Q}'.
|
|
10
|
+
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){const X=(Y)=>{const 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"){const q=`${Z} ${$.message}`;this.error(q,{exitCode:$.exitCode,code:$.code})}throw $}}_registerOption(Q){const X=Q.short&&this._findOption(Q.short)||Q.long&&this._findOption(Q.long);if(X){const 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}'
|
|
11
|
+
- already used by option '${X.flags}'`)}this._initOptionGroup(Q),this.options.push(Q)}_registerCommand(Q){const X=(Z)=>{return[Z.name()].concat(Z.aliases())},Y=X(Q).find((Z)=>this._findCommand(Z));if(Y){const 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);const X=Q.name(),Y=Q.attributeName();if(Q.negate){const $=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");const Z=($,q,_)=>{if($==null&&Q.presetArg!==void 0)$=Q.presetArg;const 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,($)=>{const q=`error: option '${Q.flags}' argument '${$}' is invalid.`;Z($,q,"cli")}),Q.envVar)this.on("optionEnv:"+X,($)=>{const 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()");const q=this.createOption(X,Y);if(q.makeOptionMandatory(!!Q.mandatory),typeof Z==="function")q.default($).argParser(Z);else if(Z instanceof RegExp){const _=Z;Z=(z,H)=>{const 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";const 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();const Y=this._prepareUserArgs(Q,X);return this._parseCommand([],Y),this}async parseAsync(Q,X){this._prepareForParse();const 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.
|
|
12
|
+
- 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(v.existsSync(Q))return;const 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
13
|
- if '${Y}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
14
|
- 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 T=S.resolve(J,G);if(b.existsSync(T))return T;if(Z.includes(S.extname(G)))return;let B=Z.find((U)=>b.existsSync(`${T}${U}`));if(B)return`${T}${B}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let q=Q._executableFile||`${this._name}-${Q._name}`,_=this._executableDir||"";if(this._scriptPath){let J;try{J=b.realpathSync(this._scriptPath)}catch{J=this._scriptPath}_=S.resolve(S.dirname(J),_)}if(_){let J=$(_,q);if(!J&&!Q._executableFile&&this._scriptPath){let G=S.basename(this._scriptPath,S.extname(this._scriptPath));if(G!==this._name)J=$(_,`${G}-${Q._name}`)}q=J||q}Y=Z.includes(S.extname(q));let z;if(H.platform!=="win32")if(Y)X.unshift(q),X=RQ(H.execArgv).concat(X),z=d.spawn(H.argv[0],X,{stdio:"inherit"});else z=d.spawn(q,X,{stdio:"inherit"});else this._checkForMissingExecutable(q,_,Q._name),X.unshift(q),X=RQ(H.execArgv).concat(X),z=d.spawn(H.execPath,X,{stdio:"inherit"});if(!z.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((G)=>{H.on(G,()=>{if(z.killed===!1&&z.exitCode===null)z.kill(G)})});let R=this._exitCallback;z.on("close",(J)=>{if(J=J??1,!R)H.exit(J);else R(new c(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(!R)H.exit(1);else{let G=new c(1,"commander.executeSubCommandAsync","(error)");G.nestedError=J,R(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((T)=>T.short).some((T)=>/^-\d$/.test(T)))},_=null,z=null,R=0;while(R<Q.length||z){let J=z??Q[R++];if(z=null,J==="--"){if(Z===Y)Z.push(J);Z.push(...Q.slice(R));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 T=Q[R++];if(T===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,T)}else if(G.optional){let T=null;if(R<Q.length&&(!$(Q[R])||q(Q[R])))T=Q[R++];this.emit(`option:${G.name()}`,T)}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("="),T=this._findOption(J.slice(0,G));if(T&&(T.required||T.optional)){this.emit(`option:${T.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(R));break}else if(this._getHelpCommand()&&J===this._getHelpCommand().name()){X.push(J,...Q.slice(R));break}else if(this._defaultCommandName){Y.push(J,...Q.slice(R));break}}if(this._passThroughOptions){Z.push(J,...Q.slice(R));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
|
-
|
|
23
|
-
`);else if(this.
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
`);for(let _ of q){let z=_.match(/^\s*(\d+)\s+(.+)$/);if(z){let R=parseInt(z[1]||"0",10),J=z[2]||"",{stdout:G}=await P(`git log --all --format='%aE' --author="${J.replace(/"/g,"\\\"")}" -1`,{cwd:Q}),T=G.trim().split(`
|
|
31
|
-
`)[0]||"",B=T.toLowerCase(),U=Y.get(B);if(U){let K=U.commits+R;if(R>U.maxIndividualCommits)Y.set(B,{name:J,email:T,commits:K,maxIndividualCommits:R});else Y.set(B,{...U,commits:K})}else Y.set(B,{name:J,email:T,commits:R,maxIndividualCommits:R})}}}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 DQ(Q){try{await P("git fetch --all --prune",{cwd:Q})}catch{}}async function r(Q,X,Y){await DQ(Q);let q=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await MQ(Q)?" --use-mailmap":""}`;if(X)q+=` --since="${X}"`;if(Y)q+=` --until="${Y}"`;let _=AX(q,{encoding:"utf-8",cwd:Q,maxBuffer:10485760}),z=[],R=_.split(`
|
|
32
|
-
`).filter((K)=>K.trim()),J=null,G=0,T=0,B=0,U=[];for(let K of R)if(K.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:T,deletions:B,files:U,branches:Array.isArray(J.branches)?J.branches:[]});let W=K.split("|");if(W.length>=5){let L=W[0]?.trim(),j=W[1]?.trim(),I=W[2]?.trim(),F=W[3]?.trim(),D=W[4]?.trim(),o=(W[5]?.trim()||"").trim();if(L&&j&&I&&F){let y=[];if(o){let yQ=o.split(",").map((V)=>V.trim());for(let V of yQ)if(V.startsWith("HEAD ->")){let E=V.match(/HEAD -> (.+)/);if(E?.[1]){let f=E[1].trim().replace(/^(origin|upstream|remote)\//,"");if(f&&!y.includes(f))y.push(f)}}else if(!V.startsWith("tag:")&&!V.startsWith("HEAD")){let E=V.replace(/^(origin|upstream|remote)\//,"");if(E&&!y.includes(E))y.push(E)}}J={hash:L,author:j,email:I,date:F,message:D,branches:y},G=0,T=0,B=0,U=[]}}}else{let W=K.trim().split(/\s+/);if(W.length>=2&&W[0]&&W[1]){let L=parseInt(W[0],10)||0,j=parseInt(W[1],10)||0,I=W.slice(2).join(" ");if(I&&!Number.isNaN(L)&&!Number.isNaN(j))G++,T+=L,B+=j,U.push({path:I,insertions:L,deletions:j})}}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:T,deletions:B,files:U,branches:Array.isArray(J.branches)?J.branches:[]});for(let K of z)if(K.hash)try{let{stdout:W}=await P(`git branch -a --contains ${K.hash}`,{cwd:Q}),L=[],j=W.trim().split(`
|
|
33
|
-
`);for(let F of j){if(!F.trim())continue;let D=F.replace(/^\*\s*/,"").trim().replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(D&&!D.startsWith("HEAD")&&!L.includes(D))L.push(D)}let I=[...new Set([...K.branches,...L])];K.branches=I}catch{}return z}import{exec as OX}from"node:child_process";import{existsSync as EQ}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 v=bX(OX);async function t(Q,X=!0){if(!Q.path)return console.error(`Error: Repository ${Q.name||"unknown"} has no path specified`),null;if(EQ(Q.path)&&await N(Q.path)){if(X)try{console.log(`Fetching all remote branches for ${Q.name||Q.path}...`),await v("git fetch --all --prune",{cwd:Q.path}),console.log(`Pulling latest changes for ${Q.name||Q.path}...`),await v("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(EQ(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 v(`git clone "${Q.url}" "${Q.path}"`);try{await v("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 O{config;loadedConfig=null;constructor(Q={}){this.config=Q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await w(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=i(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(`
|
|
34
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${Y.name||"unknown"} has no path and no URL\x1B[0m`),X.push("");continue}let Z=await t(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 N(Z))throw new Error(`${Z} is not a git repository`);try{let q=await a(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 N(q))throw new Error(`${q} is not a git repository`);try{let z=await r(q,X,Y);$.push({path:q,commits:z})}catch(z){throw new Error(`Failed to get commit history from ${q}: ${z}`)}}return $}}async function NQ(Q,X=!0,Y,Z="text",$=!1){let q=new O({configPath:Y});try{let _=await q.listContributors(Q);if($){let z=new Map;for(let J of _)for(let G of J.contributors){let T=G.email.toLowerCase(),B=z.get(T);if(B){let U=B.commits+G.commits;if(G.commits>B.maxIndividualCommits)z.set(T,{name:G.name,email:G.email,commits:U,maxIndividualCommits:G.commits});else z.set(T,{...B,commits:U})}else z.set(T,{name:G.name,email:G.email,commits:G.commits,maxIndividualCommits:G.commits})}let R=Array.from(z.values()).sort((J,G)=>G.commits-J.commits);if(Z==="json"){let J=R.map((G)=>({name:G.name,email:G.email,...X&&{commits:G.commits}}));console.log(JSON.stringify(J,null,2));return}if(console.log(`
|
|
35
|
-
\uD83D\uDCE7 Unique email addresses:`),console.log("─".repeat(60)),R.length===0)console.log(" No contributors found");else for(let J of R)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((R)=>({path:R.path,contributors:R.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(`
|
|
36
|
-
\uD83D\uDCCA Contributors for ${z.path}:`),console.log("─".repeat(60)),z.contributors.length===0)console.log(" No contributors found");else for(let R of z.contributors)if(X)console.log(` ${R.name} <${R.email}> (${R.commits} commits)`);else console.log(` ${R.name} <${R.email}>`)}catch(_){let z=_ instanceof Error?_.message:String(_);console.error(`
|
|
37
|
-
❌ \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 FQ(Q,X={},Y){let Z=new O({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 R=new Set(z.commits.flatMap((T)=>T.files.map((B)=>B.path))).size,J=z.commits.reduce((T,B)=>T+B.insertions,0),G=z.commits.reduce((T,B)=>T+B.deletions,0);return{path:z.path,commits:z.commits,summary:{totalCommits:z.commits.length,totalFilesChanged:R,totalInsertions:J,totalDeletions:G}}})},_=JSON.stringify(q,null,2);if(X.out){let z=uX(process.cwd(),X.out),R=gX(z);fX(R,{recursive:!0}),hX(z,_,"utf-8"),console.log(`✅ Report saved to: ${z}`),console.log(`
|
|
38
|
-
\uD83D\uDCCA Summary:`);for(let J of q.repositories)console.log(`
|
|
39
|
-
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,x=new LQ;x.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});x.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 w(Z),q=$?.config.contributors?.["no-commits"]??!1,_=!(X.noCommits||q),z=$?.config.contributors?.format||"text",R=X.format||z;if(R!=="json"&&R!=="text")console.error(`
|
|
41
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${R}'. Must be 'json' or 'text'\x1B[0m`),process.exit(1);let J=Q.length===0?void 0:Q,G=X.uniqueEmails||!1;await NQ(J,_,Z,R,G)}).addHelpText("after",`
|
|
42
|
-
Examples:
|
|
43
|
-
gstatx contributors ./my-repo
|
|
44
|
-
gstatx contributors ./repo1 ./repo2
|
|
45
|
-
gstatx contributors --no-commits ./my-repo
|
|
46
|
-
gstatx contributors --format json ./my-repo
|
|
47
|
-
gstatx contributors --unique-emails ./my-repo`);x.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 FQ(q,$,Z)}).addHelpText("after",`
|
|
48
|
-
Examples:
|
|
49
|
-
gstatx hist ./my-repo
|
|
50
|
-
gstatx hist --since "1 month ago" ./my-repo
|
|
51
|
-
gstatx hist --since "2024-01-01" --until "2024-12-31" ./my-repo
|
|
52
|
-
gstatx hist --since "1 month ago" --out report.json ./my-repo`);x.addHelpText("after",`
|
|
15
|
+
- ${Z}`;throw new Error($)}_executeSubCommand(Q,X){X=X.slice();let Y=!1;const Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(J,G){const U=E.resolve(J,G);if(v.existsSync(U))return U;if(Z.includes(E.extname(G)))return;const T=Z.find((R)=>v.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=v.realpathSync(this._scriptPath)}catch{J=this._scriptPath}_=E.resolve(E.dirname(J),_)}if(_){let J=$(_,q);if(!J&&!Q._executableFile&&this._scriptPath){const G=E.basename(this._scriptPath,E.extname(this._scriptPath));if(G!==this._name)J=$(_,`${G}-${Q._name}`)}q=J||q}Y=Z.includes(E.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)})});const 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{const G=new m(1,"commander.executeSubCommandAsync","(error)");G.nestedError=J,H(G)}}),this.runningCommand=z}_dispatchSubcommand(Q,X,Y){const 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();const 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(){const Q=(Y,Z,$)=>{let q=Z;if(Z!==null&&Y.parseArg){const _=`error: command-argument value '${Z}' is invalid for argument '${Y.name()}'.`;q=this._callParseArg(Y,Z,$,_)}return q};this._checkNumberOfArguments();const 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;const 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){const 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();const 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(){const Q=this.options.filter((Y)=>{const 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)=>{const Z=Q.find(($)=>Y.conflictsWith.includes($.attributeName()));if(Z)this._conflictingOption(Y,Z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((Q)=>{Q._checkForConflictingLocalOptions()})}parseOptions(Q){const X=[],Y=[];let Z=X;function $(J){return J.length>1&&J[0]==="-"}const 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)))};let _=null,z=null,H=0;while(H<Q.length||z){const 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)){const G=this._findOption(J);if(G){if(G.required){const 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]!=="-"){const 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)){const 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){const Q={},X=this.options.length;for(let Y=0;Y<X;Y++){const 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}\n`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr("\n"),this.outputHelp({error:!0});const 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){const 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(){const Q=new _X(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){const X=`error: missing required argument '${Q}'`;this.error(X,{code:"commander.missingArgument"})}optionMissingArgument(Q){const X=`error: option '${Q.flags}' argument missing`;this.error(X,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(Q){const X=`error: required option '${Q.flags}' not specified`;this.error(X,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(Q,X){const Y=(q)=>{const _=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)=>{const _=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{const q=$.createHelp().visibleOptions($).filter((_)=>_.long).map((_)=>_.long);Z=Z.concat(q),$=$.parent}while($&&!$._enablePositionalOptions);X=HQ(Q,Z)}const Y=`error: unknown option '${Q}'${X}`;this.error(Y,{code:"commander.unknownOption"})}_excessArguments(Q){if(this._allowExcessArguments)return;const 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(){const Q=this.args[0];let X="";if(this._showSuggestionAfterError){const Z=[];this.createHelp().visibleCommands(this).forEach(($)=>{if(Z.push($.name()),$.alias())Z.push($.alias())}),X=HQ(Q,Z)}const 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";const Z=this.createOption(X,Y);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${Q}\n`),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");const Y=this.parent?._findCommand(Q);if(Y){const 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;const X=this.registeredArguments.map((Y)=>{return $X(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=E.basename(Q,E.extname(Q)),this}executableDir(Q){if(Q===void 0)return this._executableDir;return this._executableDir=Q,this}helpInformation(Q){const X=this.createHelp(),Y=this._getOutputContext(Q);X.prepareContext({error:Y.error,helpWidth:Y.helpWidth,outputHasColors:Y.hasColors});const Z=X.formatHelp(this,X);if(Y.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext(Q){Q=Q||{};const X=!!Q.error;let 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;const 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){const Y=["beforeAll","before","after","afterAll"];if(!Y.includes(Q))throw new Error(`Unexpected value for position to addHelpText.
|
|
16
|
+
Expecting one of '${Y.join("', '")}'`);const 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}\n`)}),this}_outputHelpIfRequested(Q){const X=this._getHelpOption();if(X&&Q.find((Z)=>X.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}zX.Command=s;zX.useColor=p});var WQ=F((BX)=>{var{Argument:BQ}=b(),{Command:i}=TQ(),{CommanderError:UX,InvalidArgumentError:RQ}=P(),{Help:TX}=d(),{Option:KQ}=c();BX.program=new i;BX.createCommand=(Q)=>new i(Q);BX.createOption=(Q,X)=>new KQ(Q,X);BX.createArgument=(Q,X)=>new BQ(Q,X);BX.Command=i;BX.Option=KQ;BX.Argument=BQ;BX.Help=TX;BX.CommanderError=UX;BX.InvalidArgumentError=RQ;BX.InvalidOptionArgumentError=RQ});import{readFileSync as cX} from"node:fs";import{dirname as lX,join as mX} from"node:path";import{fileURLToPath as pX} from"node:url";var LQ=xQ(WQ(),1),{program:_Y,createCommand:zY,createArgument:GY,createOption:HY,CommanderError:UY,InvalidArgumentError:TY,InvalidOptionArgumentError:BY,Command:SQ,Argument:RY,Option:KY,Help:WY}=LQ.default;import{join as fX} from"node:path";import{existsSync as jQ} from"node:fs";import{readFile as NX} from"node:fs/promises";import{dirname as IQ,join as VQ,resolve as n} from"node:path";function a(Q){const Y=Q.replace(/\.git$/,"").split(/[/:]/);return Y[Y.length-1]||"repository"}var yX=function(Q){let X=n(Q);const Y=20;let Z=0;while(Z<Y){const $=VQ(X,FX);if(jQ($))return $;const q=IQ(X);if(q===X)break;X=q,Z++}return null};async function O(Q,X=process.cwd()){try{let Y;if(Q){const _=n(Q);if(!jQ(_))return console.error(`Error: Config file not found: ${_}`),null;Y=_}else if(Y=yX(X),!Y)return null;const Z=await NX(Y,"utf-8"),$=JSON.parse(Z),q=IQ(Y);if($.repositories)$.repositories=$.repositories.map((_)=>{if(!_.path&&_.url){const 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}}var FX=".gstatxrc.json";import{exec as AX,execSync as kX} from"node:child_process";import{access as MQ,readFile as wX} from"node:fs/promises";import{join as t} from"node:path";import{promisify as PX} from"node:util";async function DQ(Q){try{return await MQ(t(Q,".mailmap")),!0}catch{return!1}}async function OX(Q){const X=new Map;try{const Y=t(Q,".mailmap"),$=(await wX(Y,"utf-8")).split("\n");for(let q of $){const _=q.trim();if(!_||_.startsWith("#"))continue;const z=_.matchAll(/<([^>]+)>/g),H=Array.from(z).map((J)=>J[1]?.trim()).filter((J)=>J!==void 0);if(H.length>=2){const J=H[0];if(J){const G=J.toLowerCase();for(let U=1;U<H.length;U++){const T=H[U];if(T)X.set(T.toLowerCase(),G)}}}}}catch{}return X}async function k(Q){try{return await MQ(t(Q,".git")),!0}catch{return!1}}async function r(Q){try{await EQ(Q);const X=await DQ(Q),Y=new Map;if(X){const $=await OX(Q),{stdout:q}=await A("git log --all --format='%aN|%aE' --use-mailmap",{cwd:Q}),_=new Map,z=q.trim().split("\n");for(let H of z){if(!H.trim())continue;const[J,G]=H.split("|");if(!J||!G)continue;let U=G.toLowerCase();const T=$.get(U);if(T)U=T;const R=Y.get(U);if(!_.has(U))_.set(U,new Map);const W=_.get(U);if(W)W.set(J,(W.get(J)||0)+1);if(R)Y.set(U,{...R,commits:R.commits+1});else{const K=T?T.toLowerCase():U;Y.set(U,{name:J,email:K,commits:1,maxIndividualCommits:1})}}for(let[H,J]of _.entries()){const 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{const{stdout:$}=await A("git shortlog -sn --all",{cwd:Q}),q=$.trim().split("\n");for(let _ of q){const z=_.match(/^\s*(\d+)\s+(.+)$/);if(z){const H=parseInt(z[1]||"0",10),J=z[2]||"",{stdout:G}=await A(`git log --all --format='%aE' --author="${J.replace(/"/g,'\\"')}" -1`,{cwd:Q}),T=(G.trim().split("\n")[0]||"").toLowerCase(),R=Y.get(T);if(R){const W=R.commits+H;if(H>R.maxIndividualCommits)Y.set(T,{name:J,email:T,commits:W,maxIndividualCommits:H});else Y.set(T,{...R,commits:W})}else Y.set(T,{name:J,email:T,commits:H,maxIndividualCommits:H})}}}return Array.from(Y.values()).map(($)=>({name:$.name,email:$.email.toLowerCase(),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 A("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}"`;const _=kX(q,{encoding:"utf-8",cwd:Q,maxBuffer:10485760}),z=[],H=_.split("\n").filter((W)=>W.trim());let 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:[]});const K=W.split("|");if(K.length>=5){const V=K[0]?.trim(),D=K[1]?.trim(),M=K[2]?.trim(),L=K[3]?.trim(),S=K[4]?.trim(),j=(K[5]?.trim()||"").trim();if(V&&D&&M&&L){const h=M.toLowerCase(),I=[];if(j){const AQ=j.split(",").map((N)=>N.trim());for(let N of AQ)if(N.startsWith("HEAD ->")){const y=N.match(/HEAD -> (.+)/);if(y?.[1]){const g=y[1].trim().replace(/^(origin|upstream|remote)\//,"");if(g&&!I.includes(g))I.push(g)}}else if(!N.startsWith("tag:")&&!N.startsWith("HEAD")){const y=N.replace(/^(origin|upstream|remote)\//,"");if(y&&!I.includes(y))I.push(y)}}J={hash:V,author:D,email:h,date:L,message:S,branches:I},G=0,U=0,T=0,R=[]}}}else{const K=W.trim().split(/\s+/);if(K.length>=2&&K[0]&&K[1]){const V=parseInt(K[0],10)||0,D=parseInt(K[1],10)||0,M=K.slice(2).join(" ");if(M&&!Number.isNaN(V)&&!Number.isNaN(D))G++,U+=V,T+=D,R.push({path:M,insertions:V,deletions:D})}}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{const{stdout:W}=await A("git branch -a",{cwd:Q}),K=W.trim().split("\n"),V=[],D=new Set;for(let L of K){if(!L.trim())continue;const S=L.replace(/^\*\s*/,"").trim();if(!S||S.startsWith("HEAD"))continue;const j=S.replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(j&&!D.has(j))D.add(j),V.push({ref:S,cleanName:j});else if(j)V.push({ref:S,cleanName:j})}const M=new Map;for(let{ref:L,cleanName:S}of V)try{const{stdout:j}=await A(`git rev-list ${L}`,{cwd:Q}),h=j.trim().split("\n").filter((I)=>I.trim());for(let I of h){if(!M.has(I))M.set(I,new Set);M.get(I)?.add(S)}}catch{}for(let L of z)if(L.hash){const S=M.get(L.hash);if(S&&S.size>0){const j=[...new Set([...L.branches,...Array.from(S)])];L.branches=j}else L.branches=L.branches||[]}}catch{}return z}var A=PX(AX);import{exec as xX} from"node:child_process";import{existsSync as NQ} from"node:fs";import{mkdir as CX} from"node:fs/promises";import{dirname as bX} from"node:path";import{promisify as vX} from"node:util";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 k(Q.path)){if(X)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(`\u2713 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}...`);const Y=bX(Q.path),Z=Q.path.split("/").pop()||"repository";try{await CX(Y,{recursive:!0})}catch($){}await f(`git clone "${Q.url}" "${Q.path}"`);try{await f("git fetch --all --prune",{cwd:Q.path})}catch($){}return console.log(`\u2713 Successfully cloned ${Q.name||Z}`),Q.path}catch(Y){return console.error(`Error: Failed to clone repository: ${Y}`),null}}var f=vX(xX);class x{config;loadedConfig=null;constructor(Q={}){this.config=Q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await O(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){const X=this.loadedConfig?.configDir||process.cwd(),Y=a(Q.url);return{...Q,path:fX(X,Y),name:Q.name||Y}}return Q});if(this.config.cloneIfNotExists&&this.config.repositories){const Q=this.config.pullIfExists??!0,X=[];for(let Y of this.config.repositories){if(!Y.path){console.error(`
|
|
17
|
+
\u274C \x1B[31mError:\x1B[0m \x1B[91mRepository ${Y.name||"unknown"} has no path and no URL\x1B[0m`),X.push("");continue}const 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();const X=this.getRepoPaths(Q);if(X.length===0)throw new Error("No repository paths specified");const Y=[];for(let Z of X){if(!await k(Z))throw new Error(`${Z} is not a git repository`);try{const 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();const Z=this.getRepoPaths(Q);if(Z.length===0)throw new Error("No repository paths specified");const $=[];for(let q of Z){if(!await k(q))throw new Error(`${q} is not a git repository`);try{const 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){const q=new x({configPath:Y});try{const _=await q.listContributors(Q);if($){const z=new Map;for(let J of _)for(let G of J.contributors){const U=G.email.toLowerCase(),T=z.get(U);if(T){const 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})}const H=Array.from(z.values()).sort((J,G)=>G.commits-J.commits);if(Z==="json"){const 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(`
|
|
18
|
+
\uD83D\uDCE7 Unique email addresses:`),console.log("\u2500".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"){const 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(`
|
|
19
|
+
\uD83D\uDCCA Contributors for ${z.path}:`),console.log("\u2500".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(_){const z=_ instanceof Error?_.message:String(_);console.error(`
|
|
20
|
+
\u274C \x1B[31mError processing repositories:\x1B[0m \x1B[91m${z}\x1B[0m`),process.exit(1)}}import{mkdirSync as hX,writeFileSync as gX} from"node:fs";import{dirname as uX,resolve as dX} from"node:path";async function yQ(Q,X={},Y){const Z=new x({configPath:Y});try{const $=await Z.getHistory(Q,X.since,X.until),q={generatedAt:(new Date()).toISOString(),period:{since:X.since,until:X.until},repositories:$.map((z)=>{const 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){const z=dX(process.cwd(),X.out),H=uX(z);hX(H,{recursive:!0}),gX(z,_,"utf-8"),console.log(`\u2705 Report saved to: ${z}`),console.log(`
|
|
21
|
+
\uD83D\uDCCA Summary:`);for(let J of q.repositories)console.log(`\n 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($){const q=$ instanceof Error?$.message:String($);console.error(`
|
|
22
|
+
\u274C \x1B[31mError generating history report:\x1B[0m \x1B[91m${q}\x1B[0m`),process.exit(1)}}var sX=pX(import.meta.url),iX=lX(sX),nX=mX(iX,"..","package.json"),aX=JSON.parse(cX(nX,"utf-8")),tX=aX.version,C=new SQ;C.name("gstatx").description("A CLI tool to export statistics from git repositories").version(tX).option("-c, --config <path>","Specify custom config file path").configureHelp({helpWidth:100});C.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)=>{const Z=Y.parent?.opts().config??".gstatxrc.json",$=await O(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(`
|
|
23
|
+
\u274C \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${H}'. Must be 'json' or 'text'\x1B[0m`),process.exit(1);const J=Q.length===0?void 0:Q,G=X.uniqueEmails||!1;await FQ(J,_,Z,H,G)}).addHelpText("after","\nExamples:\n gstatx contributors ./my-repo\n gstatx contributors ./repo1 ./repo2\n gstatx contributors --no-commits ./my-repo\n gstatx contributors --format json ./my-repo\n gstatx contributors --unique-emails ./my-repo");C.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)=>{const 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",'\nExamples:\n gstatx hist ./my-repo\n gstatx hist --since "1 month ago" ./my-repo\n gstatx hist --since "2024-01-01" --until "2024-12-31" ./my-repo\n gstatx hist --since "1 month ago" --out report.json ./my-repo');C.addHelpText("after",`
|
|
53
24
|
Configuration:
|
|
54
25
|
You can create a .gstatxrc.json file to set default options
|
|
55
26
|
and repository paths. CLI arguments override config values.
|
|
@@ -57,4 +28,4 @@ Configuration:
|
|
|
57
28
|
that don't exist locally (requires 'url' in repository config).
|
|
58
29
|
Set 'pullIfExists: true' (default) to pull latest changes for
|
|
59
30
|
existing repositories, or 'pullIfExists: false' to skip updating.
|
|
60
|
-
`);
|
|
31
|
+
`);C.parse();
|
package/dist/lib.js
CHANGED
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
import{join as
|
|
2
|
-
|
|
3
|
-
`);for(let U of $){if(!U.trim())continue;let[J,G]=U.split("|");if(!J||!G)continue;let X=G.toLowerCase(),k=W.get(X);if(k)X=k;let O=H.get(X);if(!V.has(X))V.set(X,new Map);let Z=V.get(X);if(Z)Z.set(J,(Z.get(J)||0)+1);if(O)H.set(X,{...O,commits:O.commits+1});else{let T=k||G;H.set(X,{name:J,email:T,commits:1,maxIndividualCommits:1})}}for(let[U,J]of V.entries()){let G=H.get(U);if(G){let X=0,k=G.name;for(let[O,Z]of J.entries())if(Z>X)X=Z,k=O;H.set(U,{...G,name:k})}}}else{let{stdout:W}=await D("git shortlog -sn --all",{cwd:q}),Q=W.trim().split(`
|
|
4
|
-
`);for(let V of Q){let $=V.match(/^\s*(\d+)\s+(.+)$/);if($){let U=parseInt($[1]||"0",10),J=$[2]||"",{stdout:G}=await D(`git log --all --format='%aE' --author="${J.replace(/"/g,"\\\"")}" -1`,{cwd:q}),X=G.trim().split(`
|
|
5
|
-
`)[0]||"",k=X.toLowerCase(),O=H.get(k);if(O){let Z=O.commits+U;if(U>O.maxIndividualCommits)H.set(k,{name:J,email:X,commits:Z,maxIndividualCommits:U});else H.set(k,{...O,commits:Z})}else H.set(k,{name:J,email:X,commits:U,maxIndividualCommits:U})}}}return Array.from(H.values()).map((W)=>({name:W.name,email:W.email,commits:W.commits})).sort((W,Q)=>Q.commits-W.commits)}catch(K){throw new Error(`Failed to get contributors from ${q}: ${K}`)}}async function h(q){try{await D("git fetch --all --prune",{cwd:q})}catch{}}async function b(q,K,H){await h(q);let Q=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await u(q)?" --use-mailmap":""}`;if(K)Q+=` --since="${K}"`;if(H)Q+=` --until="${H}"`;let V=i(Q,{encoding:"utf-8",cwd:q,maxBuffer:10485760}),$=[],U=V.split(`
|
|
6
|
-
`).filter((Z)=>Z.trim()),J=null,G=0,X=0,k=0,O=[];for(let Z of U)if(Z.includes("|")){if(J?.hash&&J?.author&&J?.email&&J?.date&&J?.message)$.push({hash:J.hash,author:J.author,email:J.email,date:J.date,message:J.message,filesChanged:G,insertions:X,deletions:k,files:O,branches:Array.isArray(J.branches)?J.branches:[]});let T=Z.split("|");if(T.length>=5){let _=T[0]?.trim(),j=T[1]?.trim(),B=T[2]?.trim(),R=T[3]?.trim(),S=T[4]?.trim(),C=(T[5]?.trim()||"").trim();if(_&&j&&B&&R){let z=[];if(C){let c=C.split(",").map((w)=>w.trim());for(let w of c)if(w.startsWith("HEAD ->")){let v=w.match(/HEAD -> (.+)/);if(v?.[1]){let A=v[1].trim().replace(/^(origin|upstream|remote)\//,"");if(A&&!z.includes(A))z.push(A)}}else if(!w.startsWith("tag:")&&!w.startsWith("HEAD")){let v=w.replace(/^(origin|upstream|remote)\//,"");if(v&&!z.includes(v))z.push(v)}}J={hash:_,author:j,email:B,date:R,message:S,branches:z},G=0,X=0,k=0,O=[]}}}else{let T=Z.trim().split(/\s+/);if(T.length>=2&&T[0]&&T[1]){let _=parseInt(T[0],10)||0,j=parseInt(T[1],10)||0,B=T.slice(2).join(" ");if(B&&!Number.isNaN(_)&&!Number.isNaN(j))G++,X+=_,k+=j,O.push({path:B,insertions:_,deletions:j})}}if(J?.hash&&J?.author&&J?.email&&J?.date&&J?.message)$.push({hash:J.hash,author:J.author,email:J.email,date:J.date,message:J.message,filesChanged:G,insertions:X,deletions:k,files:O,branches:Array.isArray(J.branches)?J.branches:[]});for(let Z of $)if(Z.hash)try{let{stdout:T}=await D(`git branch -a --contains ${Z.hash}`,{cwd:q}),_=[],j=T.trim().split(`
|
|
7
|
-
`);for(let R of j){if(!R.trim())continue;let S=R.replace(/^\*\s*/,"").trim().replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(S&&!S.startsWith("HEAD")&&!_.includes(S))_.push(S)}let B=[...new Set([...Z.branches,..._])];Z.branches=B}catch{}return $}import{exec as r}from"node:child_process";import{existsSync as l}from"node:fs";import{mkdir as e}from"node:fs/promises";import{dirname as qq}from"node:path";import{promisify as Hq}from"node:util";var L=Hq(r);async function x(q,K=!0){if(!q.path)return console.error(`Error: Repository ${q.name||"unknown"} has no path specified`),null;if(l(q.path)&&await I(q.path)){if(K)try{console.log(`Fetching all remote branches for ${q.name||q.path}...`),await L("git fetch --all --prune",{cwd:q.path}),console.log(`Pulling latest changes for ${q.name||q.path}...`),await L("git pull",{cwd:q.path}),console.log(`✓ Successfully updated ${q.name||q.path}`)}catch(H){console.warn(`Warning: Failed to update ${q.path}: ${H}. Continuing with existing code.`)}return q.path}if(l(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 H=qq(q.path),Y=q.path.split("/").pop()||"repository";try{await e(H,{recursive:!0})}catch(W){}await L(`git clone "${q.url}" "${q.path}"`);try{await L("git fetch --all --prune",{cwd:q.path})}catch(W){}return console.log(`✓ Successfully cloned ${q.name||Y}`),q.path}catch(H){return console.error(`Error: Failed to clone repository: ${H}`),null}}class Kq{config;loadedConfig=null;constructor(q={}){this.config=q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await y(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 K=this.loadedConfig?.configDir||process.cwd(),H=N(q.url);return{...q,path:Jq(K,H),name:q.name||H}}return q});if(this.config.cloneIfNotExists&&this.config.repositories){let q=this.config.pullIfExists??!0,K=[];for(let H of this.config.repositories){if(!H.path){console.error(`
|
|
8
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${H.name||"unknown"} has no path and no URL\x1B[0m`),K.push("");continue}let Y=await x(H,q);if(Y)K.push(Y);else K.push(H.path)}this.config.repositories=this.config.repositories.map((H,Y)=>({...H,path:K[Y]||H.path}))}}getRepoPaths(q){if(q&&q.length>0)return q;if(this.config.repositories)return this.config.repositories.map((K)=>K.path).filter((K)=>K!==void 0);return[]}async listContributors(q){await this.initialize();let K=this.getRepoPaths(q);if(K.length===0)throw new Error("No repository paths specified");let H=[];for(let Y of K){if(!await I(Y))throw new Error(`${Y} is not a git repository`);try{let Q=await M(Y);H.push({path:Y,contributors:Q})}catch(Q){throw new Error(`Failed to get contributors from ${Y}: ${Q}`)}}return H}async getHistory(q,K,H){await this.initialize();let Y=this.getRepoPaths(q);if(Y.length===0)throw new Error("No repository paths specified");let W=[];for(let Q of Y){if(!await I(Q))throw new Error(`${Q} is not a git repository`);try{let $=await b(Q,K,H);W.push({path:Q,commits:$})}catch($){throw new Error(`Failed to get commit history from ${Q}: ${$}`)}}return W}}export{y as loadConfig,I as isGitRepo,M as getContributors,b as getCommits,x as ensureRepository,Kq as Client};
|
|
1
|
+
import{join as Qq} from"node:path";import{existsSync as f} from"node:fs";import{readFile as m} from"node:fs/promises";import{dirname as d,join as P,resolve as M} from"node:path";function N(q){const J=q.replace(/\.git$/,"").split(/[/:]/);return J[J.length-1]||"repository"}var n=function(q){let Q=M(q);const J=20;let Y=0;while(Y<J){const X=P(Q,s);if(f(X))return X;const V=d(Q);if(V===Q)break;Q=V,Y++}return null};async function E(q,Q=process.cwd()){try{let J;if(q){const W=M(q);if(!f(W))return console.error(`Error: Config file not found: ${W}`),null;J=W}else if(J=n(Q),!J)return null;const Y=await m(J,"utf-8"),X=JSON.parse(Y),V=d(J);if(X.repositories)X.repositories=X.repositories.map((W)=>{if(!W.path&&W.url){const k=N(W.url);return{...W,path:P(V,k),name:W.name||k}}if(W.path)return{...W,path:M(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}}var s=".gstatxrc.json";import{exec as i,execSync as a} from"node:child_process";import{access as u,readFile as t} from"node:fs/promises";import{join as b} from"node:path";import{promisify as o} from"node:util";async function h(q){try{return await u(b(q,".mailmap")),!0}catch{return!1}}async function r(q){const Q=new Map;try{const J=b(q,".mailmap"),X=(await t(J,"utf-8")).split("\n");for(let V of X){const W=V.trim();if(!W||W.startsWith("#"))continue;const k=W.matchAll(/<([^>]+)>/g),H=Array.from(k).map((K)=>K[1]?.trim()).filter((K)=>K!==void 0);if(H.length>=2){const K=H[0];if(K){const _=K.toLowerCase();for(let Z=1;Z<H.length;Z++){const $=H[Z];if($)Q.set($.toLowerCase(),_)}}}}}catch{}return Q}async function L(q){try{return await u(b(q,".git")),!0}catch{return!1}}async function x(q){try{await l(q);const Q=await h(q),J=new Map;if(Q){const X=await r(q),{stdout:V}=await A("git log --all --format='%aN|%aE' --use-mailmap",{cwd:q}),W=new Map,k=V.trim().split("\n");for(let H of k){if(!H.trim())continue;const[K,_]=H.split("|");if(!K||!_)continue;let Z=_.toLowerCase();const $=X.get(Z);if($)Z=$;const O=J.get(Z);if(!W.has(Z))W.set(Z,new Map);const G=W.get(Z);if(G)G.set(K,(G.get(K)||0)+1);if(O)J.set(Z,{...O,commits:O.commits+1});else{const U=$?$.toLowerCase():Z;J.set(Z,{name:K,email:U,commits:1,maxIndividualCommits:1})}}for(let[H,K]of W.entries()){const _=J.get(H);if(_){let Z=0,$=_.name;for(let[O,G]of K.entries())if(G>Z)Z=G,$=O;J.set(H,{..._,name:$})}}}else{const{stdout:X}=await A("git shortlog -sn --all",{cwd:q}),V=X.trim().split("\n");for(let W of V){const k=W.match(/^\s*(\d+)\s+(.+)$/);if(k){const H=parseInt(k[1]||"0",10),K=k[2]||"",{stdout:_}=await A(`git log --all --format='%aE' --author="${K.replace(/"/g,'\\"')}" -1`,{cwd:q}),$=(_.trim().split("\n")[0]||"").toLowerCase(),O=J.get($);if(O){const G=O.commits+H;if(H>O.maxIndividualCommits)J.set($,{name:K,email:$,commits:G,maxIndividualCommits:H});else J.set($,{...O,commits:G})}else J.set($,{name:K,email:$,commits:H,maxIndividualCommits:H})}}}return Array.from(J.values()).map((X)=>({name:X.name,email:X.email.toLowerCase(),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}"`;const W=a(V,{encoding:"utf-8",cwd:q,maxBuffer:10485760}),k=[],H=W.split("\n").filter((G)=>G.trim());let K=null,_=0,Z=0,$=0,O=[];for(let G of H)if(G.includes("|")){if(K?.hash&&K?.author&&K?.email&&K?.date&&K?.message)k.push({hash:K.hash,author:K.author,email:K.email,date:K.date,message:K.message,filesChanged:_,insertions:Z,deletions:$,files:O,branches:Array.isArray(K.branches)?K.branches:[]});const U=G.split("|");if(U.length>=5){const w=U[0]?.trim(),D=U[1]?.trim(),I=U[2]?.trim(),j=U[3]?.trim(),S=U[4]?.trim(),T=(U[5]?.trim()||"").trim();if(w&&D&&I&&j){const F=I.toLowerCase(),v=[];if(T){const p=T.split(",").map((B)=>B.trim());for(let B of p)if(B.startsWith("HEAD ->")){const z=B.match(/HEAD -> (.+)/);if(z?.[1]){const y=z[1].trim().replace(/^(origin|upstream|remote)\//,"");if(y&&!v.includes(y))v.push(y)}}else if(!B.startsWith("tag:")&&!B.startsWith("HEAD")){const z=B.replace(/^(origin|upstream|remote)\//,"");if(z&&!v.includes(z))v.push(z)}}K={hash:w,author:D,email:F,date:j,message:S,branches:v},_=0,Z=0,$=0,O=[]}}}else{const U=G.trim().split(/\s+/);if(U.length>=2&&U[0]&&U[1]){const w=parseInt(U[0],10)||0,D=parseInt(U[1],10)||0,I=U.slice(2).join(" ");if(I&&!Number.isNaN(w)&&!Number.isNaN(D))_++,Z+=w,$+=D,O.push({path:I,insertions:w,deletions:D})}}if(K?.hash&&K?.author&&K?.email&&K?.date&&K?.message)k.push({hash:K.hash,author:K.author,email:K.email,date:K.date,message:K.message,filesChanged:_,insertions:Z,deletions:$,files:O,branches:Array.isArray(K.branches)?K.branches:[]});try{const{stdout:G}=await A("git branch -a",{cwd:q}),U=G.trim().split("\n"),w=[],D=new Set;for(let j of U){if(!j.trim())continue;const S=j.replace(/^\*\s*/,"").trim();if(!S||S.startsWith("HEAD"))continue;const T=S.replace(/^remotes\//,"").replace(/^(origin|upstream|remote)\//,"");if(T&&!D.has(T))D.add(T),w.push({ref:S,cleanName:T});else if(T)w.push({ref:S,cleanName:T})}const I=new Map;for(let{ref:j,cleanName:S}of w)try{const{stdout:T}=await A(`git rev-list ${j}`,{cwd:q}),F=T.trim().split("\n").filter((v)=>v.trim());for(let v of F){if(!I.has(v))I.set(v,new Set);I.get(v)?.add(S)}}catch{}for(let j of k)if(j.hash){const S=I.get(j.hash);if(S&&S.size>0){const T=[...new Set([...j.branches,...Array.from(S)])];j.branches=T}else j.branches=j.branches||[]}}catch{}return k}var A=o(i);import{exec as e} from"node:child_process";import{existsSync as c} from"node:fs";import{mkdir as qq} from"node:fs/promises";import{dirname as Jq} from"node:path";import{promisify as Kq} from"node:util";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 L(q.path)){if(Q)try{console.log(`Fetching all remote branches for ${q.name||q.path}...`),await R("git fetch --all --prune",{cwd:q.path}),console.log(`Pulling latest changes for ${q.name||q.path}...`),await R("git pull",{cwd:q.path}),console.log(`\u2713 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}...`);const J=Jq(q.path),Y=q.path.split("/").pop()||"repository";try{await qq(J,{recursive:!0})}catch(X){}await R(`git clone "${q.url}" "${q.path}"`);try{await R("git fetch --all --prune",{cwd:q.path})}catch(X){}return console.log(`\u2713 Successfully cloned ${q.name||Y}`),q.path}catch(J){return console.error(`Error: Failed to clone repository: ${J}`),null}}var R=Kq(e);class Vq{config;loadedConfig=null;constructor(q={}){this.config=q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await E(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){const Q=this.loadedConfig?.configDir||process.cwd(),J=N(q.url);return{...q,path:Qq(Q,J),name:q.name||J}}return q});if(this.config.cloneIfNotExists&&this.config.repositories){const q=this.config.pullIfExists??!0,Q=[];for(let J of this.config.repositories){if(!J.path){console.error(`
|
|
2
|
+
\u274C \x1B[31mError:\x1B[0m \x1B[91mRepository ${J.name||"unknown"} has no path and no URL\x1B[0m`),Q.push("");continue}const Y=await g(J,q);if(Y)Q.push(Y);else Q.push(J.path)}this.config.repositories=this.config.repositories.map((J,Y)=>({...J,path:Q[Y]||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();const Q=this.getRepoPaths(q);if(Q.length===0)throw new Error("No repository paths specified");const J=[];for(let Y of Q){if(!await L(Y))throw new Error(`${Y} is not a git repository`);try{const V=await x(Y);J.push({path:Y,contributors:V})}catch(V){throw new Error(`Failed to get contributors from ${Y}: ${V}`)}}return J}async getHistory(q,Q,J){await this.initialize();const Y=this.getRepoPaths(q);if(Y.length===0)throw new Error("No repository paths specified");const X=[];for(let V of Y){if(!await L(V))throw new Error(`${V} is not a git repository`);try{const k=await C(V,Q,J);X.push({path:V,commits:k})}catch(k){throw new Error(`Failed to get commit history from ${V}: ${k}`)}}return X}}export{E as loadConfig,L as isGitRepo,x as getContributors,C as getCommits,g as ensureRepository,Vq as Client};
|