gstatx 0.2.4 → 0.2.6
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/README.md +8 -2
- package/dist/index.js +35 -33
- package/dist/lib.d.ts +1 -0
- package/dist/lib.js +7 -7
- package/dist/utils/config.d.ts +1 -0
- package/dist/utils/git.d.ts +1 -0
- package/dist/utils/repo.d.ts +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -166,6 +166,7 @@ You can create a `.gstatxrc.json` file to set default options and repository pat
|
|
|
166
166
|
"no-commits": false
|
|
167
167
|
},
|
|
168
168
|
"cloneIfNotExists": false,
|
|
169
|
+
"pullIfExists": true,
|
|
169
170
|
"repositories": [
|
|
170
171
|
{
|
|
171
172
|
"path": "../my-repo",
|
|
@@ -179,6 +180,7 @@ You can create a `.gstatxrc.json` file to set default options and repository pat
|
|
|
179
180
|
**Configuration Fields:**
|
|
180
181
|
- `contributors.no-commits` (boolean, optional): Hide commit counts by default
|
|
181
182
|
- `cloneIfNotExists` (boolean, optional): Automatically clone repositories that don't exist locally
|
|
183
|
+
- `pullIfExists` (boolean, optional): Pull latest changes if repository already exists (default: `true`)
|
|
182
184
|
- `repositories` (array, optional): List of repositories to process
|
|
183
185
|
- `path` (string, required): Repository path (relative to config file location)
|
|
184
186
|
- `name` (string, optional): Display name for the repository
|
|
@@ -187,6 +189,7 @@ You can create a `.gstatxrc.json` file to set default options and repository pat
|
|
|
187
189
|
**Important Notes:**
|
|
188
190
|
- Repository paths in the config file are resolved relative to the `.gstatxrc.json` file location, not the current working directory
|
|
189
191
|
- If `cloneIfNotExists: true` and a repository doesn't exist, it will be cloned from the `url`
|
|
192
|
+
- If `pullIfExists: true` (default) and a repository already exists, it will pull the latest changes before processing
|
|
190
193
|
- CLI arguments always override config file values
|
|
191
194
|
- Both `contributors` and `hist` commands can use repositories from the config file
|
|
192
195
|
|
|
@@ -245,13 +248,15 @@ gstatx hist --since "1 month ago" --out report.json
|
|
|
245
248
|
|
|
246
249
|
The tool will automatically use the repositories listed in your config file.
|
|
247
250
|
|
|
248
|
-
### Auto-Cloning Repositories
|
|
251
|
+
### Auto-Cloning and Auto-Updating Repositories
|
|
249
252
|
|
|
250
253
|
When `cloneIfNotExists: true` is set in your config:
|
|
251
254
|
|
|
252
255
|
1. The tool checks if each repository exists at the specified path
|
|
253
256
|
2. If the repository doesn't exist and a `url` is provided, it will be cloned automatically
|
|
254
|
-
3. If the repository already exists
|
|
257
|
+
3. If the repository already exists:
|
|
258
|
+
- If `pullIfExists: true` (default), it will pull the latest changes before processing
|
|
259
|
+
- If `pullIfExists: false`, it will be used as-is without updating
|
|
255
260
|
4. If the path exists but isn't a git repository, an error is shown
|
|
256
261
|
|
|
257
262
|
**Example:**
|
|
@@ -332,6 +337,7 @@ import {
|
|
|
332
337
|
```typescript
|
|
333
338
|
interface ClientOptions {
|
|
334
339
|
cloneIfNotExists?: boolean;
|
|
340
|
+
pullIfExists?: boolean;
|
|
335
341
|
repositories?: RepositoryConfig[];
|
|
336
342
|
configPath?: string;
|
|
337
343
|
contributors?: {
|
package/dist/index.js
CHANGED
|
@@ -1,57 +1,59 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as
|
|
3
|
-
`)}displayWidth(Q){return
|
|
4
|
-
`+" ".repeat(X+
|
|
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
|
|
6
|
-
`)}}function
|
|
2
|
+
import{createRequire as xQ}from"node:module";var AQ=Object.create;var{getPrototypeOf:kQ,defineProperty:o,getOwnPropertyNames:wQ}=Object;var PQ=Object.prototype.hasOwnProperty;var OQ=(Q,X,Y)=>{Y=Q!=null?AQ(kQ(Q)):{};let Z=X||!Q||!Q.__esModule?o(Y,"default",{value:Q,enumerable:!0}):Y;for(let $ of wQ(Q))if(!PQ.call(Z,$))o(Z,$,{get:()=>Q[$],enumerable:!0});return Z};var j=(Q,X)=>()=>(X||Q((X={exports:{}}).exports,X),X.exports);var F=xQ(import.meta.url);var y=j((CQ)=>{class v 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 e extends v{constructor(Q){super(1,"commander.invalidArgument",Q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}CQ.CommanderError=v;CQ.InvalidArgumentError=e});var P=j((gQ)=>{var{InvalidArgumentError:fQ}=y();class QQ{constructor(Q,X){switch(this.description=X||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,Q[0]){case"<":this.required=!0,this._name=Q.slice(1,-1);break;case"[":this.required=!1,this._name=Q.slice(1,-1);break;default:this.required=!0,this._name=Q;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue(Q,X){if(X===this.defaultValue||!Array.isArray(X))return[Q];return X.push(Q),X}default(Q,X){return this.defaultValue=Q,this.defaultValueDescription=X,this}argParser(Q){return this.parseArg=Q,this}choices(Q){return this.argChoices=Q.slice(),this.parseArg=(X,Y)=>{if(!this.argChoices.includes(X))throw new fQ(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(X,Y);return X},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function hQ(Q){let X=Q.name()+(Q.variadic===!0?"...":"");return Q.required?"<"+X+">":"["+X+"]"}gQ.Argument=QQ;gQ.humanReadableArgName=hQ});var f=j((lQ)=>{var{humanReadableArgName:dQ}=P();class XQ{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(Q){this.helpWidth=this.helpWidth??Q.helpWidth??80}visibleCommands(Q){let X=Q.commands.filter((Z)=>!Z._hidden),Y=Q._getHelpCommand();if(Y&&!Y._hidden)X.push(Y);if(this.sortSubcommands)X.sort((Z,$)=>{return Z.name().localeCompare($.name())});return X}compareOptions(Q,X){let Y=(Z)=>{return Z.short?Z.short.replace(/^-/,""):Z.long.replace(/^--/,"")};return Y(Q).localeCompare(Y(X))}visibleOptions(Q){let X=Q.options.filter((Z)=>!Z.hidden),Y=Q._getHelpOption();if(Y&&!Y.hidden){let Z=Y.short&&Q._findOption(Y.short),$=Y.long&&Q._findOption(Y.long);if(!Z&&!$)X.push(Y);else if(Y.long&&!$)X.push(Q.createOption(Y.long,Y.description));else if(Y.short&&!Z)X.push(Q.createOption(Y.short,Y.description))}if(this.sortOptions)X.sort(this.compareOptions);return X}visibleGlobalOptions(Q){if(!this.showGlobalOptions)return[];let X=[];for(let Y=Q.parent;Y;Y=Y.parent){let Z=Y.options.filter(($)=>!$.hidden);X.push(...Z)}if(this.sortOptions)X.sort(this.compareOptions);return X}visibleArguments(Q){if(Q._argsDescription)Q.registeredArguments.forEach((X)=>{X.description=X.description||Q._argsDescription[X.name()]||""});if(Q.registeredArguments.find((X)=>X.description))return Q.registeredArguments;return[]}subcommandTerm(Q){let X=Q.registeredArguments.map((Y)=>dQ(Y)).join(" ");return Q._name+(Q._aliases[0]?"|"+Q._aliases[0]:"")+(Q.options.length?" [options]":"")+(X?" "+X:"")}optionTerm(Q){return Q.flags}argumentTerm(Q){return Q.name()}longestSubcommandTermLength(Q,X){return X.visibleCommands(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleSubcommandTerm(X.subcommandTerm(Z))))},0)}longestOptionTermLength(Q,X){return X.visibleOptions(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleOptionTerm(X.optionTerm(Z))))},0)}longestGlobalOptionTermLength(Q,X){return X.visibleGlobalOptions(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleOptionTerm(X.optionTerm(Z))))},0)}longestArgumentTermLength(Q,X){return X.visibleArguments(Q).reduce((Y,Z)=>{return Math.max(Y,this.displayWidth(X.styleArgumentTerm(X.argumentTerm(Z))))},0)}commandUsage(Q){let X=Q._name;if(Q._aliases[0])X=X+"|"+Q._aliases[0];let Y="";for(let Z=Q.parent;Z;Z=Z.parent)Y=Z.name()+" "+Y;return Y+X+" "+Q.usage()}commandDescription(Q){return Q.description()}subcommandDescription(Q){return Q.summary()||Q.description()}optionDescription(Q){let X=[];if(Q.argChoices)X.push(`choices: ${Q.argChoices.map((Y)=>JSON.stringify(Y)).join(", ")}`);if(Q.defaultValue!==void 0){if(Q.required||Q.optional||Q.isBoolean()&&typeof Q.defaultValue==="boolean")X.push(`default: ${Q.defaultValueDescription||JSON.stringify(Q.defaultValue)}`)}if(Q.presetArg!==void 0&&Q.optional)X.push(`preset: ${JSON.stringify(Q.presetArg)}`);if(Q.envVar!==void 0)X.push(`env: ${Q.envVar}`);if(X.length>0){let Y=`(${X.join(", ")})`;if(Q.description)return`${Q.description} ${Y}`;return Y}return Q.description}argumentDescription(Q){let X=[];if(Q.argChoices)X.push(`choices: ${Q.argChoices.map((Y)=>JSON.stringify(Y)).join(", ")}`);if(Q.defaultValue!==void 0)X.push(`default: ${Q.defaultValueDescription||JSON.stringify(Q.defaultValue)}`);if(X.length>0){let Y=`(${X.join(", ")})`;if(Q.description)return`${Q.description} ${Y}`;return Y}return Q.description}formatItemList(Q,X,Y){if(X.length===0)return[];return[Y.styleTitle(Q),...X,""]}groupItems(Q,X,Y){let Z=new Map;return Q.forEach(($)=>{let q=Y($);if(!Z.has(q))Z.set(q,[])}),X.forEach(($)=>{let q=Y($);if(!Z.has(q))Z.set(q,[]);Z.get(q).push($)}),Z}formatHelp(Q,X){let Y=X.padWidth(Q,X),Z=X.helpWidth??80;function $(G,B){return X.formatItem(G,Y,B,X)}let q=[`${X.styleTitle("Usage:")} ${X.styleUsage(X.commandUsage(Q))}`,""],_=X.commandDescription(Q);if(_.length>0)q=q.concat([X.boxWrap(X.styleCommandDescription(_),Z),""]);let z=X.visibleArguments(Q).map((G)=>{return $(X.styleArgumentTerm(X.argumentTerm(G)),X.styleArgumentDescription(X.argumentDescription(G)))});if(q=q.concat(this.formatItemList("Arguments:",z,X)),this.groupItems(Q.options,X.visibleOptions(Q),(G)=>G.helpGroupHeading??"Options:").forEach((G,B)=>{let R=G.map((U)=>{return $(X.styleOptionTerm(X.optionTerm(U)),X.styleOptionDescription(X.optionDescription(U)))});q=q.concat(this.formatItemList(B,R,X))}),X.showGlobalOptions){let G=X.visibleGlobalOptions(Q).map((B)=>{return $(X.styleOptionTerm(X.optionTerm(B)),X.styleOptionDescription(X.optionDescription(B)))});q=q.concat(this.formatItemList("Global Options:",G,X))}return this.groupItems(Q.commands,X.visibleCommands(Q),(G)=>G.helpGroup()||"Commands:").forEach((G,B)=>{let R=G.map((U)=>{return $(X.styleSubcommandTerm(X.subcommandTerm(U)),X.styleSubcommandDescription(X.subcommandDescription(U)))});q=q.concat(this.formatItemList(B,R,X))}),q.join(`
|
|
3
|
+
`)}displayWidth(Q){return YQ(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()],T=this.displayWidth(z[0]);_.forEach((J)=>{let G=this.displayWidth(J);if(T+G<=X){z.push(J),T+=G;return}$.push(z.join(""));let B=J.trimStart();z=[B],T=this.displayWidth(B)}),$.push(z.join(""))}),$.join(`
|
|
6
|
+
`)}}function YQ(Q){let X=/\x1b\[\d*(;\d*)*m/g;return Q.replace(X,"")}lQ.Help=XQ;lQ.stripColor=YQ});var h=j((nQ)=>{var{InvalidArgumentError:sQ}=y();class $Q{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 ZQ(this.name().replace(/^no-/,""));return ZQ(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 qQ{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 ZQ(Q){return Q.split("-").reduce((X,Y)=>{return X+Y[0].toUpperCase()+Y.slice(1)})}function iQ(Q){let X,Y,Z=/^-[^-]$/,$=/^--[^-]/,q=Q.split(/[ |,]+/).concat("guard");if(Z.test(q[0]))X=q.shift();if($.test(q[0]))Y=q.shift();if(!X&&Z.test(q[0]))X=q.shift();if(!X&&$.test(q[0]))X=Y,Y=q.shift();if(q[0].startsWith("-")){let _=q[0],z=`option creation failed due to '${_}' in option flags '${Q}'`;if(/^-[^-][^-]/.test(_))throw new Error(`${z}
|
|
7
7
|
- a short flag is a single dash and a single character
|
|
8
8
|
- either use a single dash and a single character (for a short flag)
|
|
9
|
-
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(
|
|
10
|
-
- too many short flags`);if($.test(
|
|
11
|
-
- too many long flags`);throw Error(`${
|
|
12
|
-
- unrecognised flag format`)}if(X===void 0&&Y===void 0)throw Error(`option creation failed due to no flags found in '${Q}'.`);return{shortFlag:X,longFlag:Y}}
|
|
9
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);if(Z.test(_))throw new Error(`${z}
|
|
10
|
+
- too many short flags`);if($.test(_))throw new Error(`${z}
|
|
11
|
+
- too many long flags`);throw new Error(`${z}
|
|
12
|
+
- unrecognised flag format`)}if(X===void 0&&Y===void 0)throw new Error(`option creation failed due to no flags found in '${Q}'.`);return{shortFlag:X,longFlag:Y}}nQ.Option=$Q;nQ.DualOptions=qQ});var JQ=j((eQ)=>{function tQ(Q,X){if(Math.abs(Q.length-X.length)>3)return Math.max(Q.length,X.length);let Y=[];for(let Z=0;Z<=Q.length;Z++)Y[Z]=[Z];for(let Z=0;Z<=X.length;Z++)Y[0][Z]=Z;for(let Z=1;Z<=X.length;Z++)for(let $=1;$<=Q.length;$++){let q=1;if(Q[$-1]===X[Z-1])q=0;else q=1;if(Y[$][Z]=Math.min(Y[$-1][Z]+1,Y[$][Z-1]+1,Y[$-1][Z-1]+q),$>1&&Z>1&&Q[$-1]===X[Z-2]&&Q[$-2]===X[Z-1])Y[$][Z]=Math.min(Y[$][Z],Y[$-2][Z-2]+1)}return Y[Q.length][X.length]}function oQ(Q,X){if(!X||X.length===0)return"";X=Array.from(new Set(X));let Y=Q.startsWith("--");if(Y)Q=Q.slice(2),X=X.map((_)=>_.slice(2));let Z=[],$=3,q=0.4;if(X.forEach((_)=>{if(_.length<=1)return;let z=tQ(Q,_),T=Math.max(Q.length,_.length);if((T-z)/T>q){if(z<$)$=z,Z=[_];else if(z===$)Z.push(_)}}),Z.sort((_,z)=>_.localeCompare(z)),Y)Z=Z.map((_)=>`--${_}`);if(Z.length>1)return`
|
|
13
13
|
(Did you mean one of ${Z.join(", ")}?)`;if(Z.length===1)return`
|
|
14
|
-
(Did you mean ${Z[0]}?)`;return""}
|
|
15
|
-
- specify the name in Command constructor or using .name()`);if(X=X||{},X.isDefault)this._defaultCommandName=Q._name;if(X.noHelp||X.hidden)Q._hidden=!0;return this._registerCommand(Q),Q.parent=this,Q._checkForBrokenPassThrough(),this}createArgument(Q,X){return new
|
|
16
|
-
Expecting one of '${Y.join("', '")}'`);if(this._lifeCycleHooks[Q])this._lifeCycleHooks[Q].push(X);else this._lifeCycleHooks[Q]=[X];return this}exitOverride(Q){if(Q)this._exitCallback=Q;else this._exitCallback=(X)=>{if(X.code!=="commander.executeSubCommandAsync")throw X};return this}_exit(Q,X,Y){if(this._exitCallback)this._exitCallback(new
|
|
17
|
-
- already used by option '${X.flags}'`)}this._initOptionGroup(Q),this.options.push(Q)}_registerCommand(Q){let X=(Z)=>{return[Z.name()].concat(Z.aliases())},Y=X(Q).find((Z)=>this._findCommand(Z));if(Y){let Z=X(this._findCommand(Y)).join("|"),$=X(Q).join("|");throw 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,
|
|
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(
|
|
14
|
+
(Did you mean ${Z[0]}?)`;return""}eQ.suggestSimilar=oQ});var TQ=j((_X)=>{var XX=F("node:events").EventEmitter,g=F("node:child_process"),L=F("node:path"),O=F("node:fs"),H=F("node:process"),{Argument:YX,humanReadableArgName:ZX}=P(),{CommanderError:u}=y(),{Help:$X,stripColor:qX}=f(),{Option:_Q,DualOptions:JX}=h(),{suggestSimilar:zQ}=JQ();class d extends XX{constructor(Q){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=Q||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:(X)=>H.stdout.write(X),writeErr:(X)=>H.stderr.write(X),outputError:(X,Y)=>Y(X),getOutHelpWidth:()=>H.stdout.isTTY?H.stdout.columns:void 0,getErrHelpWidth:()=>H.stderr.isTTY?H.stderr.columns:void 0,getOutHasColors:()=>c()??(H.stdout.isTTY&&H.stdout.hasColors?.()),getErrHasColors:()=>c()??(H.stderr.isTTY&&H.stderr.hasColors?.()),stripColor:(X)=>qX(X)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0}copyInheritedSettings(Q){return this._outputConfiguration=Q._outputConfiguration,this._helpOption=Q._helpOption,this._helpCommand=Q._helpCommand,this._helpConfiguration=Q._helpConfiguration,this._exitCallback=Q._exitCallback,this._storeOptionsAsProperties=Q._storeOptionsAsProperties,this._combineFlagAndOptionalValue=Q._combineFlagAndOptionalValue,this._allowExcessArguments=Q._allowExcessArguments,this._enablePositionalOptions=Q._enablePositionalOptions,this._showHelpAfterError=Q._showHelpAfterError,this._showSuggestionAfterError=Q._showSuggestionAfterError,this}_getCommandAndAncestors(){let Q=[];for(let X=this;X;X=X.parent)Q.push(X);return Q}command(Q,X,Y){let Z=X,$=Y;if(typeof Z==="object"&&Z!==null)$=Z,Z=null;$=$||{};let[,q,_]=Q.match(/([^ ]+) *(.*)/),z=this.createCommand(q);if(Z)z.description(Z),z._executableHandler=!0;if($.isDefault)this._defaultCommandName=z._name;if(z._hidden=!!($.noHelp||$.hidden),z._executableFile=$.executableFile||null,_)z.arguments(_);if(this._registerCommand(z),z.parent=this,z.copyInheritedSettings(this),Z)return this;return z}createCommand(Q){return new d(Q)}createHelp(){return Object.assign(new $X,this.configureHelp())}configureHelp(Q){if(Q===void 0)return this._helpConfiguration;return this._helpConfiguration=Q,this}configureOutput(Q){if(Q===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...Q},this}showHelpAfterError(Q=!0){if(typeof Q!=="string")Q=!!Q;return this._showHelpAfterError=Q,this}showSuggestionAfterError(Q=!0){return this._showSuggestionAfterError=!!Q,this}addCommand(Q,X){if(!Q._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
15
|
+
- specify the name in Command constructor or using .name()`);if(X=X||{},X.isDefault)this._defaultCommandName=Q._name;if(X.noHelp||X.hidden)Q._hidden=!0;return this._registerCommand(Q),Q.parent=this,Q._checkForBrokenPassThrough(),this}createArgument(Q,X){return new YX(Q,X)}argument(Q,X,Y,Z){let $=this.createArgument(Q,X);if(typeof Y==="function")$.default(Z).argParser(Y);else $.default(Y);return this.addArgument($),this}arguments(Q){return Q.trim().split(/ +/).forEach((X)=>{this.argument(X)}),this}addArgument(Q){let X=this.registeredArguments.slice(-1)[0];if(X?.variadic)throw new Error(`only the last argument can be variadic '${X.name()}'`);if(Q.required&&Q.defaultValue!==void 0&&Q.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${Q.name()}'`);return this.registeredArguments.push(Q),this}helpCommand(Q,X){if(typeof Q==="boolean"){if(this._addImplicitHelpCommand=Q,Q&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let Y=Q??"help [command]",[,Z,$]=Y.match(/([^ ]+) *(.*)/),q=X??"display help for command",_=this.createCommand(Z);if(_.helpOption(!1),$)_.arguments($);if(q)_.description(q);if(this._addImplicitHelpCommand=!0,this._helpCommand=_,Q||X)this._initCommandGroup(_);return this}addHelpCommand(Q,X){if(typeof Q!=="object")return this.helpCommand(Q,X),this;return this._addImplicitHelpCommand=!0,this._helpCommand=Q,this._initCommandGroup(Q),this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(Q,X){let Y=["preSubcommand","preAction","postAction"];if(!Y.includes(Q))throw new Error(`Unexpected value for event passed to hook : '${Q}'.
|
|
16
|
+
Expecting one of '${Y.join("', '")}'`);if(this._lifeCycleHooks[Q])this._lifeCycleHooks[Q].push(X);else this._lifeCycleHooks[Q]=[X];return this}exitOverride(Q){if(Q)this._exitCallback=Q;else this._exitCallback=(X)=>{if(X.code!=="commander.executeSubCommandAsync")throw X};return this}_exit(Q,X,Y){if(this._exitCallback)this._exitCallback(new u(Q,X,Y));H.exit(Q)}action(Q){let X=(Y)=>{let Z=this.registeredArguments.length,$=Y.slice(0,Z);if(this._storeOptionsAsProperties)$[Z]=this;else $[Z]=this.opts();return $.push(this),Q.apply(this,$)};return this._actionHandler=X,this}createOption(Q,X){return new _Q(Q,X)}_callParseArg(Q,X,Y,Z){try{return Q.parseArg(X,Y)}catch($){if($.code==="commander.invalidArgument"){let q=`${Z} ${$.message}`;this.error(q,{exitCode:$.exitCode,code:$.code})}throw $}}_registerOption(Q){let X=Q.short&&this._findOption(Q.short)||Q.long&&this._findOption(Q.long);if(X){let Y=Q.long&&this._findOption(Q.long)?Q.long:Q.short;throw new Error(`Cannot add option '${Q.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${Y}'
|
|
17
|
+
- already used by option '${X.flags}'`)}this._initOptionGroup(Q),this.options.push(Q)}_registerCommand(Q){let X=(Z)=>{return[Z.name()].concat(Z.aliases())},Y=X(Q).find((Z)=>this._findCommand(Z));if(Y){let Z=X(this._findCommand(Y)).join("|"),$=X(Q).join("|");throw new Error(`cannot add command '${$}' as already have command '${Z}'`)}this._initCommandGroup(Q),this.commands.push(Q)}addOption(Q){this._registerOption(Q);let X=Q.name(),Y=Q.attributeName();if(Q.negate){let $=Q.long.replace(/^--no-/,"--");if(!this._findOption($))this.setOptionValueWithSource(Y,Q.defaultValue===void 0?!0:Q.defaultValue,"default")}else if(Q.defaultValue!==void 0)this.setOptionValueWithSource(Y,Q.defaultValue,"default");let Z=($,q,_)=>{if($==null&&Q.presetArg!==void 0)$=Q.presetArg;let z=this.getOptionValue(Y);if($!==null&&Q.parseArg)$=this._callParseArg(Q,$,z,q);else if($!==null&&Q.variadic)$=Q._collectValue($,z);if($==null)if(Q.negate)$=!1;else if(Q.isBoolean()||Q.optional)$=!0;else $="";this.setOptionValueWithSource(Y,$,_)};if(this.on("option:"+X,($)=>{let q=`error: option '${Q.flags}' argument '${$}' is invalid.`;Z($,q,"cli")}),Q.envVar)this.on("optionEnv:"+X,($)=>{let q=`error: option '${Q.flags}' value '${$}' from env '${Q.envVar}' is invalid.`;Z($,q,"env")});return this}_optionEx(Q,X,Y,Z,$){if(typeof X==="object"&&X instanceof _Q)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,T)=>{let J=_.exec(z);return J?J[0]:T},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(O.existsSync(Q))return;let Z=X?`searched for local subcommand relative to directory '${X}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",$=`'${Q}' does not exist
|
|
19
19
|
- if '${Y}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
20
20
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
21
|
-
- ${Z}`;throw Error($)}_executeSubCommand(Q,X){X=X.slice();let Y=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(J,
|
|
21
|
+
- ${Z}`;throw new Error($)}_executeSubCommand(Q,X){X=X.slice();let Y=!1,Z=[".js",".ts",".tsx",".mjs",".cjs"];function $(J,G){let B=L.resolve(J,G);if(O.existsSync(B))return B;if(Z.includes(L.extname(G)))return;let R=Z.find((U)=>O.existsSync(`${B}${U}`));if(R)return`${B}${R}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let q=Q._executableFile||`${this._name}-${Q._name}`,_=this._executableDir||"";if(this._scriptPath){let J;try{J=O.realpathSync(this._scriptPath)}catch{J=this._scriptPath}_=L.resolve(L.dirname(J),_)}if(_){let J=$(_,q);if(!J&&!Q._executableFile&&this._scriptPath){let G=L.basename(this._scriptPath,L.extname(this._scriptPath));if(G!==this._name)J=$(_,`${G}-${Q._name}`)}q=J||q}Y=Z.includes(L.extname(q));let z;if(H.platform!=="win32")if(Y)X.unshift(q),X=GQ(H.execArgv).concat(X),z=g.spawn(H.argv[0],X,{stdio:"inherit"});else z=g.spawn(q,X,{stdio:"inherit"});else this._checkForMissingExecutable(q,_,Q._name),X.unshift(q),X=GQ(H.execArgv).concat(X),z=g.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 T=this._exitCallback;z.on("close",(J)=>{if(J=J??1,!T)H.exit(J);else T(new u(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(!T)H.exit(1);else{let G=new u(1,"commander.executeSubCommandAsync","(error)");G.nestedError=J,T(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((B)=>B.short).some((B)=>/^-\d$/.test(B)))},_=null,z=null,T=0;while(T<Q.length||z){let J=z??Q[T++];if(z=null,J==="--"){if(Z===Y)Z.push(J);Z.push(...Q.slice(T));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 B=Q[T++];if(B===void 0)this.optionMissingArgument(G);this.emit(`option:${G.name()}`,B)}else if(G.optional){let B=null;if(T<Q.length&&(!$(Q[T])||q(Q[T])))B=Q[T++];this.emit(`option:${G.name()}`,B)}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("="),B=this._findOption(J.slice(0,G));if(B&&(B.required||B.optional)){this.emit(`option:${B.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(T));break}else if(this._getHelpCommand()&&J===this._getHelpCommand().name()){X.push(J,...Q.slice(T));break}else if(this._defaultCommandName){Y.push(J,...Q.slice(T));break}}if(this._passThroughOptions){Z.push(J,...Q.slice(T));break}Z.push(J)}return{operands:X,unknown:Y}}opts(){if(this._storeOptionsAsProperties){let Q={},X=this.options.length;for(let Y=0;Y<X;Y++){let Z=this.options[Y].attributeName();Q[Z]=Z===this._versionOptionName?this._version:this[Z]}return Q}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((Q,X)=>Object.assign(Q,X.opts()),{})}error(Q,X){if(this._outputConfiguration.outputError(`${Q}
|
|
22
22
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
23
23
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
24
|
-
`),this.outputHelp({error:!0});let Y=X||{},Z=Y.exitCode||1,$=Y.code||"commander.error";this._exit(Z,$,Q)}_parseOptionsEnv(){this.options.forEach((Q)=>{if(Q.envVar&&Q.envVar in H.env){let X=Q.attributeName();if(this.getOptionValue(X)===void 0||["default","config","env"].includes(this.getOptionValueSource(X)))if(Q.required||Q.optional)this.emit(`optionEnv:${Q.name()}`,H.env[Q.envVar]);else this.emit(`optionEnv:${Q.name()}`)}})}_parseOptionsImplied(){let Q=new
|
|
25
|
-
`),this._exit(0,"commander.version",Q)}),this}description(Q,X){if(Q===void 0&&X===void 0)return this._description;if(this._description=Q,X)this._argsDescription=X;return this}summary(Q){if(Q===void 0)return this._summary;return this._summary=Q,this}alias(Q){if(Q===void 0)return this._aliases[0];let X=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)X=this.commands[this.commands.length-1];if(Q===X._name)throw Error("Command alias can't be the same as its name");let Y=this.parent?._findCommand(Q);if(Y){let Z=[Y.name()].concat(Y.aliases()).join("|");throw Error(`cannot add alias '${Q}' to command '${this.name()}' as already have command '${Z}'`)}return X._aliases.push(Q),this}aliases(Q){if(Q===void 0)return this._aliases;return Q.forEach((X)=>this.alias(X)),this}usage(Q){if(Q===void 0){if(this._usage)return this._usage;let X=this.registeredArguments.map((Y)=>{return
|
|
24
|
+
`),this.outputHelp({error:!0});let Y=X||{},Z=Y.exitCode||1,$=Y.code||"commander.error";this._exit(Z,$,Q)}_parseOptionsEnv(){this.options.forEach((Q)=>{if(Q.envVar&&Q.envVar in H.env){let X=Q.attributeName();if(this.getOptionValue(X)===void 0||["default","config","env"].includes(this.getOptionValueSource(X)))if(Q.required||Q.optional)this.emit(`optionEnv:${Q.name()}`,H.env[Q.envVar]);else this.emit(`optionEnv:${Q.name()}`)}})}_parseOptionsImplied(){let Q=new JX(this.options),X=(Y)=>{return this.getOptionValue(Y)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(Y))};this.options.filter((Y)=>Y.implied!==void 0&&X(Y.attributeName())&&Q.valueFromOption(this.getOptionValue(Y.attributeName()),Y)).forEach((Y)=>{Object.keys(Y.implied).filter((Z)=>!X(Z)).forEach((Z)=>{this.setOptionValueWithSource(Z,Y.implied[Z],"implied")})})}missingArgument(Q){let X=`error: missing required argument '${Q}'`;this.error(X,{code:"commander.missingArgument"})}optionMissingArgument(Q){let X=`error: option '${Q.flags}' argument missing`;this.error(X,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(Q){let X=`error: required option '${Q.flags}' not specified`;this.error(X,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(Q,X){let Y=(q)=>{let _=q.attributeName(),z=this.getOptionValue(_),T=this.options.find((G)=>G.negate&&_===G.attributeName()),J=this.options.find((G)=>!G.negate&&_===G.attributeName());if(T&&(T.presetArg===void 0&&z===!1||T.presetArg!==void 0&&z===T.presetArg))return T;return J||q},Z=(q)=>{let _=Y(q),z=_.attributeName();if(this.getOptionValueSource(z)==="env")return`environment variable '${_.envVar}'`;return`option '${_.flags}'`},$=`error: ${Z(Q)} cannot be used with ${Z(X)}`;this.error($,{code:"commander.conflictingOption"})}unknownOption(Q){if(this._allowUnknownOption)return;let X="";if(Q.startsWith("--")&&this._showSuggestionAfterError){let Z=[],$=this;do{let q=$.createHelp().visibleOptions($).filter((_)=>_.long).map((_)=>_.long);Z=Z.concat(q),$=$.parent}while($&&!$._enablePositionalOptions);X=zQ(Q,Z)}let Y=`error: unknown option '${Q}'${X}`;this.error(Y,{code:"commander.unknownOption"})}_excessArguments(Q){if(this._allowExcessArguments)return;let X=this.registeredArguments.length,Y=X===1?"":"s",$=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${X} argument${Y} but got ${Q.length}.`;this.error($,{code:"commander.excessArguments"})}unknownCommand(){let Q=this.args[0],X="";if(this._showSuggestionAfterError){let Z=[];this.createHelp().visibleCommands(this).forEach(($)=>{if(Z.push($.name()),$.alias())Z.push($.alias())}),X=zQ(Q,Z)}let Y=`error: unknown command '${Q}'${X}`;this.error(Y,{code:"commander.unknownCommand"})}version(Q,X,Y){if(Q===void 0)return this._version;this._version=Q,X=X||"-V, --version",Y=Y||"output the version number";let Z=this.createOption(X,Y);return this._versionOptionName=Z.attributeName(),this._registerOption(Z),this.on("option:"+Z.name(),()=>{this._outputConfiguration.writeOut(`${Q}
|
|
25
|
+
`),this._exit(0,"commander.version",Q)}),this}description(Q,X){if(Q===void 0&&X===void 0)return this._description;if(this._description=Q,X)this._argsDescription=X;return this}summary(Q){if(Q===void 0)return this._summary;return this._summary=Q,this}alias(Q){if(Q===void 0)return this._aliases[0];let X=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)X=this.commands[this.commands.length-1];if(Q===X._name)throw new Error("Command alias can't be the same as its name");let Y=this.parent?._findCommand(Q);if(Y){let Z=[Y.name()].concat(Y.aliases()).join("|");throw new Error(`cannot add alias '${Q}' to command '${this.name()}' as already have command '${Z}'`)}return X._aliases.push(Q),this}aliases(Q){if(Q===void 0)return this._aliases;return Q.forEach((X)=>this.alias(X)),this}usage(Q){if(Q===void 0){if(this._usage)return this._usage;let X=this.registeredArguments.map((Y)=>{return ZX(Y)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?X:[]).join(" ")}return this._usage=Q,this}name(Q){if(Q===void 0)return this._name;return this._name=Q,this}helpGroup(Q){if(Q===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=Q,this}commandsGroup(Q){if(Q===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=Q,this}optionsGroup(Q){if(Q===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=Q,this}_initOptionGroup(Q){if(this._defaultOptionGroup&&!Q.helpGroupHeading)Q.helpGroup(this._defaultOptionGroup)}_initCommandGroup(Q){if(this._defaultCommandGroup&&!Q.helpGroup())Q.helpGroup(this._defaultCommandGroup)}nameFromFilename(Q){return this._name=L.basename(Q,L.extname(Q)),this}executableDir(Q){if(Q===void 0)return this._executableDir;return this._executableDir=Q,this}helpInformation(Q){let X=this.createHelp(),Y=this._getOutputContext(Q);X.prepareContext({error:Y.error,helpWidth:Y.helpWidth,outputHasColors:Y.hasColors});let Z=X.formatHelp(this,X);if(Y.hasColors)return Z;return this._outputConfiguration.stripColor(Z)}_getOutputContext(Q){Q=Q||{};let X=!!Q.error,Y,Z,$;if(X)Y=(_)=>this._outputConfiguration.writeErr(_),Z=this._outputConfiguration.getErrHasColors(),$=this._outputConfiguration.getErrHelpWidth();else Y=(_)=>this._outputConfiguration.writeOut(_),Z=this._outputConfiguration.getOutHasColors(),$=this._outputConfiguration.getOutHelpWidth();return{error:X,write:(_)=>{if(!Z)_=this._outputConfiguration.stripColor(_);return Y(_)},hasColors:Z,helpWidth:$}}outputHelp(Q){let X;if(typeof Q==="function")X=Q,Q=void 0;let Y=this._getOutputContext(Q),Z={error:Y.error,write:Y.write,command:this};this._getCommandAndAncestors().reverse().forEach((q)=>q.emit("beforeAllHelp",Z)),this.emit("beforeHelp",Z);let $=this.helpInformation({error:Y.error});if(X){if($=X($),typeof $!=="string"&&!Buffer.isBuffer($))throw new Error("outputHelp callback must return a string or a Buffer")}if(Y.write($),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",Z),this._getCommandAndAncestors().forEach((q)=>q.emit("afterAllHelp",Z))}helpOption(Q,X){if(typeof Q==="boolean"){if(Q){if(this._helpOption===null)this._helpOption=void 0;if(this._defaultOptionGroup)this._initOptionGroup(this._getHelpOption())}else this._helpOption=null;return this}if(this._helpOption=this.createOption(Q??"-h, --help",X??"display help for command"),Q||X)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(Q){return this._helpOption=Q,this._initOptionGroup(Q),this}help(Q){this.outputHelp(Q);let X=Number(H.exitCode??0);if(X===0&&Q&&typeof Q!=="function"&&Q.error)X=1;this._exit(X,"commander.help","(outputHelp)")}addHelpText(Q,X){let Y=["beforeAll","before","after","afterAll"];if(!Y.includes(Q))throw new Error(`Unexpected value for position to addHelpText.
|
|
26
26
|
Expecting one of '${Y.join("', '")}'`);let Z=`${Q}Help`;return this.on(Z,($)=>{let q;if(typeof X==="function")q=X({error:$.error,command:$.command});else q=X;if(q)$.write(`${q}
|
|
27
|
-
`)}),this}_outputHelpIfRequested(Q){let X=this._getHelpOption();if(X&&Q.find((Z)=>X.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function
|
|
28
|
-
`);for(let q of $){let
|
|
29
|
-
`);for(let
|
|
30
|
-
`);for(let
|
|
31
|
-
`)[0]||"",
|
|
32
|
-
`).filter((
|
|
33
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${
|
|
34
|
-
\uD83D\uDCE7 Unique email addresses:`),console.log("─".repeat(60)),
|
|
35
|
-
\uD83D\uDCCA Contributors for ${
|
|
36
|
-
❌ \x1B[31mError processing repositories:\x1B[0m \x1B[91m${
|
|
27
|
+
`)}),this}_outputHelpIfRequested(Q){let X=this._getHelpOption();if(X&&Q.find((Z)=>X.is(Z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function GQ(Q){return Q.map((X)=>{if(!X.startsWith("--inspect"))return X;let Y,Z="127.0.0.1",$="9229",q;if((q=X.match(/^(--inspect(-brk)?)$/))!==null)Y=q[1];else if((q=X.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(Y=q[1],/^\d+$/.test(q[3]))$=q[3];else Z=q[3];else if((q=X.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)Y=q[1],Z=q[3],$=q[4];if(Y&&$!=="0")return`${Y}=${Z}:${parseInt($)+1}`;return X})}function c(){if(H.env.NO_COLOR||H.env.FORCE_COLOR==="0"||H.env.FORCE_COLOR==="false")return!1;if(H.env.FORCE_COLOR||H.env.CLICOLOR_FORCE!==void 0)return!0;return}_X.Command=d;_X.useColor=c});var UQ=j((RX)=>{var{Argument:BQ}=P(),{Command:l}=TQ(),{CommanderError:TX,InvalidArgumentError:RQ}=y(),{Help:BX}=f(),{Option:HQ}=h();RX.program=new l;RX.createCommand=(Q)=>new l(Q);RX.createOption=(Q,X)=>new HQ(Q,X);RX.createArgument=(Q,X)=>new BQ(Q,X);RX.Command=l;RX.Option=HQ;RX.Argument=BQ;RX.Help=BX;RX.CommanderError=TX;RX.InvalidArgumentError=RQ;RX.InvalidOptionArgumentError=RQ});import{readFileSync as cX}from"node:fs";import{dirname as dX,join as lX}from"node:path";import{fileURLToPath as mX}from"node:url";var KQ=OQ(UQ(),1),{program:JY,createCommand:_Y,createArgument:zY,createOption:GY,CommanderError:TY,InvalidArgumentError:BY,InvalidOptionArgumentError:RY,Command:WQ,Argument:HY,Option:UY,Help:KY}=KQ.default;import{join as vX}from"node:path";import{existsSync as LQ}from"node:fs";import{readFile as EX}from"node:fs/promises";import{dirname as SQ,join as jQ,resolve as m}from"node:path";var NX=".gstatxrc.json";function p(Q){let Y=Q.replace(/\.git$/,"").split(/[/:]/);return Y[Y.length-1]||"repository"}function FX(Q){let X=m(Q),Y=20,Z=0;while(Z<Y){let $=jQ(X,NX);if(LQ($))return $;let q=SQ(X);if(q===X)break;X=q,Z++}return null}async function A(Q,X=process.cwd()){try{let Y;if(Q){let _=m(Q);if(!LQ(_))return console.error(`Error: Config file not found: ${_}`),null;Y=_}else if(Y=FX(X),!Y)return null;let Z=await EX(Y,"utf-8"),$=JSON.parse(Z),q=SQ(Y);if($.repositories)$.repositories=$.repositories.map((_)=>{if(!_.path&&_.url){let z=p(_.url);return{..._,path:jQ(q,z),name:_.name||z}}if(_.path)return{..._,path:m(q,_.path)};return _});return{config:$,configDir:q}}catch(Y){if(Q)console.error(`Error: Failed to load config file: ${Y}`);return null}}import{exec as yX,execSync as AX}from"node:child_process";import{access as IQ,readFile as kX}from"node:fs/promises";import{join as s}from"node:path";import{promisify as wX}from"node:util";var x=wX(yX);async function VQ(Q){try{return await IQ(s(Q,".mailmap")),!0}catch{return!1}}async function PX(Q){let X=new Map;try{let Y=s(Q,".mailmap"),$=(await kX(Y,"utf-8")).split(`
|
|
28
|
+
`);for(let q of $){let _=q.trim();if(!_||_.startsWith("#"))continue;let z=_.matchAll(/<([^>]+)>/g),T=Array.from(z).map((J)=>J[1]?.trim()).filter((J)=>J!==void 0);if(T.length>=2){let J=T[0];if(J){let G=J.toLowerCase();for(let B=1;B<T.length;B++){let R=T[B];if(R)X.set(R.toLowerCase(),G)}}}}}catch{}return X}async function D(Q){try{return await IQ(s(Q,".git")),!0}catch{return!1}}async function i(Q){try{await MQ(Q);let X=await VQ(Q),Y=new Map;if(X){let $=await PX(Q),{stdout:q}=await x("git log --all --format='%aN|%aE' --use-mailmap",{cwd:Q}),_=new Map,z=q.trim().split(`
|
|
29
|
+
`);for(let T of z){if(!T.trim())continue;let[J,G]=T.split("|");if(!J||!G)continue;let B=G.toLowerCase(),R=$.get(B);if(R)B=R;let U=Y.get(B);if(!_.has(B))_.set(B,new Map);let W=_.get(B);if(W)W.set(J,(W.get(J)||0)+1);if(U)Y.set(B,{...U,commits:U.commits+1});else{let K=R||G;Y.set(B,{name:J,email:K,commits:1,maxIndividualCommits:1})}}for(let[T,J]of _.entries()){let G=Y.get(T);if(G){let B=0,R=G.name;for(let[U,W]of J.entries())if(W>B)B=W,R=U;Y.set(T,{...G,name:R})}}}else{let{stdout:$}=await x("git shortlog -sn --all",{cwd:Q}),q=$.trim().split(`
|
|
30
|
+
`);for(let _ of q){let z=_.match(/^\s*(\d+)\s+(.+)$/);if(z){let T=parseInt(z[1]||"0",10),J=z[2]||"",{stdout:G}=await x(`git log --all --format='%aE' --author="${J.replace(/"/g,"\\\"")}" -1`,{cwd:Q}),B=G.trim().split(`
|
|
31
|
+
`)[0]||"",R=B.toLowerCase(),U=Y.get(R);if(U){let W=U.commits+T;if(T>U.maxIndividualCommits)Y.set(R,{name:J,email:B,commits:W,maxIndividualCommits:T});else Y.set(R,{...U,commits:W})}else Y.set(R,{name:J,email:B,commits:T,maxIndividualCommits:T})}}}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 MQ(Q){try{await x("git fetch --all --prune",{cwd:Q})}catch{}}async function n(Q,X,Y){await MQ(Q);let q=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await VQ(Q)?" --use-mailmap":""}`;if(X)q+=` --since="${X}"`;if(Y)q+=` --until="${Y}"`;let _=AX(q,{encoding:"utf-8",cwd:Q,maxBuffer:10485760}),z=[],T=_.split(`
|
|
32
|
+
`).filter((W)=>W.trim()),J=null,G=0,B=0,R=0,U=[];for(let W of T)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:B,deletions:R,files:U,branches:J.branches||[]});let K=W.split("|");if(K.length>=6){let I=K[0]?.trim(),V=K[1]?.trim(),E=K[2]?.trim(),r=K[3]?.trim(),FQ=K[4]?.trim(),t=K[5]?.trim()||"";if(I&&V&&E&&r){let N=[];if(t){let yQ=t.split(",").map((S)=>S.trim());for(let S of yQ)if(S.startsWith("HEAD ->")){let M=S.match(/HEAD -> (.+)/);if(M?.[1]){let b=M[1].trim().replace(/^(origin|upstream|remote)\//,"");if(b&&!N.includes(b))N.push(b)}}else if(!S.startsWith("tag:")&&!S.startsWith("HEAD")){let M=S.replace(/^(origin|upstream|remote)\//,"");if(M&&!N.includes(M))N.push(M)}}J={hash:I,author:V,email:E,date:r,message:FQ,branches:N},G=0,B=0,R=0,U=[]}}}else{let K=W.trim().split(/\s+/);if(K.length>=2&&K[0]&&K[1]){let I=parseInt(K[0],10)||0,V=parseInt(K[1],10)||0,E=K.slice(2).join(" ");if(E&&!Number.isNaN(I)&&!Number.isNaN(V))G++,B+=I,R+=V,U.push({path:E,insertions:I,deletions:V})}}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:B,deletions:R,files:U,branches:J.branches||[]});return z}import{exec as OX}from"node:child_process";import{existsSync as DQ}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 C=bX(OX);async function a(Q,X=!0){if(!Q.path)return console.error(`Error: Repository ${Q.name||"unknown"} has no path specified`),null;if(DQ(Q.path)&&await D(Q.path)){if(X)try{console.log(`Fetching all remote branches for ${Q.name||Q.path}...`),await C("git fetch --all --prune",{cwd:Q.path}),console.log(`Pulling latest changes for ${Q.name||Q.path}...`),await C("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(DQ(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 C(`git clone "${Q.url}" "${Q.path}"`);try{await C("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 k{config;loadedConfig=null;constructor(Q={}){this.config=Q}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await A(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=p(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(`
|
|
33
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${Y.name||"unknown"} has no path and no URL\x1B[0m`),X.push("");continue}let Z=await a(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 D(Z))throw new Error(`${Z} is not a git repository`);try{let q=await i(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 D(q))throw new Error(`${q} is not a git repository`);try{let z=await n(q,X,Y);$.push({path:q,commits:z})}catch(z){throw new Error(`Failed to get commit history from ${q}: ${z}`)}}return $}}async function EQ(Q,X=!0,Y,Z="text",$=!1){let q=new k({configPath:Y});try{let _=await q.listContributors(Q);if($){let z=new Map;for(let J of _)for(let G of J.contributors){let B=G.email.toLowerCase(),R=z.get(B);if(R){let U=R.commits+G.commits;if(G.commits>R.maxIndividualCommits)z.set(B,{name:G.name,email:G.email,commits:U,maxIndividualCommits:G.commits});else z.set(B,{...R,commits:U})}else z.set(B,{name:G.name,email:G.email,commits:G.commits,maxIndividualCommits:G.commits})}let T=Array.from(z.values()).sort((J,G)=>G.commits-J.commits);if(Z==="json"){let J=T.map((G)=>({name:G.name,email:G.email,...X&&{commits:G.commits}}));console.log(JSON.stringify(J,null,2));return}if(console.log(`
|
|
34
|
+
\uD83D\uDCE7 Unique email addresses:`),console.log("─".repeat(60)),T.length===0)console.log(" No contributors found");else for(let J of T)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((T)=>({path:T.path,contributors:T.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(`
|
|
35
|
+
\uD83D\uDCCA Contributors for ${z.path}:`),console.log("─".repeat(60)),z.contributors.length===0)console.log(" No contributors found");else for(let T of z.contributors)if(X)console.log(` ${T.name} <${T.email}> (${T.commits} commits)`);else console.log(` ${T.name} <${T.email}>`)}catch(_){let z=_ instanceof Error?_.message:String(_);console.error(`
|
|
36
|
+
❌ \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 NQ(Q,X={},Y){let Z=new k({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 T=new Set(z.commits.flatMap((B)=>B.files.map((R)=>R.path))).size,J=z.commits.reduce((B,R)=>B+R.insertions,0),G=z.commits.reduce((B,R)=>B+R.deletions,0);return{path:z.path,commits:z.commits,summary:{totalCommits:z.commits.length,totalFilesChanged:T,totalInsertions:J,totalDeletions:G}}})},_=JSON.stringify(q,null,2);if(X.out){let z=uX(process.cwd(),X.out),T=gX(z);fX(T,{recursive:!0}),hX(z,_,"utf-8"),console.log(`✅ Report saved to: ${z}`),console.log(`
|
|
37
37
|
\uD83D\uDCCA Summary:`);for(let J of q.repositories)console.log(`
|
|
38
|
-
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(
|
|
39
|
-
❌ \x1B[31mError generating history report:\x1B[0m \x1B[91m${q}\x1B[0m`),process.exit(1)}}var
|
|
40
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${
|
|
38
|
+
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(`
|
|
39
|
+
❌ \x1B[31mError generating history report:\x1B[0m \x1B[91m${q}\x1B[0m`),process.exit(1)}}var pX=mX(import.meta.url),sX=dX(pX),iX=lX(sX,"..","package.json"),nX=JSON.parse(cX(iX,"utf-8")),aX=nX.version,w=new WQ;w.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});w.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 A(Z),q=$?.config.contributors?.["no-commits"]??!1,_=!(X.noCommits||q),z=$?.config.contributors?.format||"text",T=X.format||z;if(T!=="json"&&T!=="text")console.error(`
|
|
40
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mInvalid format '${T}'. Must be 'json' or 'text'\x1B[0m`),process.exit(1);let J=Q.length===0?void 0:Q,G=X.uniqueEmails||!1;await EQ(J,_,Z,T,G)}).addHelpText("after",`
|
|
41
41
|
Examples:
|
|
42
42
|
gstatx contributors ./my-repo
|
|
43
43
|
gstatx contributors ./repo1 ./repo2
|
|
44
44
|
gstatx contributors --no-commits ./my-repo
|
|
45
45
|
gstatx contributors --format json ./my-repo
|
|
46
|
-
gstatx contributors --unique-emails ./my-repo`);
|
|
46
|
+
gstatx contributors --unique-emails ./my-repo`);w.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 NQ(q,$,Z)}).addHelpText("after",`
|
|
47
47
|
Examples:
|
|
48
48
|
gstatx hist ./my-repo
|
|
49
49
|
gstatx hist --since "1 month ago" ./my-repo
|
|
50
50
|
gstatx hist --since "2024-01-01" --until "2024-12-31" ./my-repo
|
|
51
|
-
gstatx hist --since "1 month ago" --out report.json ./my-repo`);
|
|
51
|
+
gstatx hist --since "1 month ago" --out report.json ./my-repo`);w.addHelpText("after",`
|
|
52
52
|
Configuration:
|
|
53
53
|
You can create a .gstatxrc.json file to set default options
|
|
54
54
|
and repository paths. CLI arguments override config values.
|
|
55
55
|
Set 'cloneIfNotExists: true' to automatically clone repositories
|
|
56
56
|
that don't exist locally (requires 'url' in repository config).
|
|
57
|
-
|
|
57
|
+
Set 'pullIfExists: true' (default) to pull latest changes for
|
|
58
|
+
existing repositories, or 'pullIfExists: false' to skip updating.
|
|
59
|
+
`);w.parse();
|
package/dist/lib.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { type Commit, type RepoContributor } from "./utils/git";
|
|
|
7
7
|
export type * from "./types";
|
|
8
8
|
export interface ClientOptions extends GstatxConfig {
|
|
9
9
|
cloneIfNotExists?: boolean;
|
|
10
|
+
pullIfExists?: boolean;
|
|
10
11
|
repositories?: RepositoryConfig[];
|
|
11
12
|
configPath?: string;
|
|
12
13
|
}
|
package/dist/lib.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{join as
|
|
2
|
-
`);for(let
|
|
3
|
-
`);for(let
|
|
4
|
-
`);for(let
|
|
5
|
-
`)[0]||"",X
|
|
6
|
-
`).filter((
|
|
7
|
-
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${H.name||"unknown"} has no path and no URL\x1B[0m`),
|
|
1
|
+
import{join as Jq}from"node:path";import{existsSync as C}from"node:fs";import{readFile as m}from"node:fs/promises";import{dirname as g,join as f,resolve as A}from"node:path";var p=".gstatxrc.json";function L(q){let H=q.replace(/\.git$/,"").split(/[/:]/);return H[H.length-1]||"repository"}function s(q){let K=A(q),H=20,Y=0;while(Y<H){let W=f(K,p);if(C(W))return W;let Q=g(K);if(Q===K)break;K=Q,Y++}return null}async function F(q,K=process.cwd()){try{let H;if(q){let V=A(q);if(!C(V))return console.error(`Error: Config file not found: ${V}`),null;H=V}else if(H=s(K),!H)return null;let Y=await m(H,"utf-8"),W=JSON.parse(Y),Q=g(H);if(W.repositories)W.repositories=W.repositories.map((V)=>{if(!V.path&&V.url){let $=L(V.url);return{...V,path:f(Q,$),name:V.name||$}}if(V.path)return{...V,path:A(Q,V.path)};return V});return{config:W,configDir:Q}}catch(H){if(q)console.error(`Error: Failed to load config file: ${H}`);return null}}import{exec as n,execSync as i}from"node:child_process";import{access as d,readFile as a}from"node:fs/promises";import{join as N}from"node:path";import{promisify as t}from"node:util";var R=t(n);async function P(q){try{return await d(N(q,".mailmap")),!0}catch{return!1}}async function o(q){let K=new Map;try{let H=N(q,".mailmap"),W=(await a(H,"utf-8")).split(`
|
|
2
|
+
`);for(let Q of W){let V=Q.trim();if(!V||V.startsWith("#"))continue;let $=V.matchAll(/<([^>]+)>/g),k=Array.from($).map((J)=>J[1]?.trim()).filter((J)=>J!==void 0);if(k.length>=2){let J=k[0];if(J){let T=J.toLowerCase();for(let X=1;X<k.length;X++){let Z=k[X];if(Z)K.set(Z.toLowerCase(),T)}}}}}catch{}return K}async function S(q){try{return await d(N(q,".git")),!0}catch{return!1}}async function y(q){try{await u(q);let K=await P(q),H=new Map;if(K){let W=await o(q),{stdout:Q}=await R("git log --all --format='%aN|%aE' --use-mailmap",{cwd:q}),V=new Map,$=Q.trim().split(`
|
|
3
|
+
`);for(let k of $){if(!k.trim())continue;let[J,T]=k.split("|");if(!J||!T)continue;let X=T.toLowerCase(),Z=W.get(X);if(Z)X=Z;let O=H.get(X);if(!V.has(X))V.set(X,new Map);let G=V.get(X);if(G)G.set(J,(G.get(J)||0)+1);if(O)H.set(X,{...O,commits:O.commits+1});else{let U=Z||T;H.set(X,{name:J,email:U,commits:1,maxIndividualCommits:1})}}for(let[k,J]of V.entries()){let T=H.get(k);if(T){let X=0,Z=T.name;for(let[O,G]of J.entries())if(G>X)X=G,Z=O;H.set(k,{...T,name:Z})}}}else{let{stdout:W}=await R("git shortlog -sn --all",{cwd:q}),Q=W.trim().split(`
|
|
4
|
+
`);for(let V of Q){let $=V.match(/^\s*(\d+)\s+(.+)$/);if($){let k=parseInt($[1]||"0",10),J=$[2]||"",{stdout:T}=await R(`git log --all --format='%aE' --author="${J.replace(/"/g,"\\\"")}" -1`,{cwd:q}),X=T.trim().split(`
|
|
5
|
+
`)[0]||"",Z=X.toLowerCase(),O=H.get(Z);if(O){let G=O.commits+k;if(k>O.maxIndividualCommits)H.set(Z,{name:J,email:X,commits:G,maxIndividualCommits:k});else H.set(Z,{...O,commits:G})}else H.set(Z,{name:J,email:X,commits:k,maxIndividualCommits:k})}}}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 u(q){try{await R("git fetch --all --prune",{cwd:q})}catch{}}async function b(q,K,H){await u(q);let Q=`git log --all --format="%H|%an|%ae|%ad|%s|%D" --date=iso-strict --numstat${await P(q)?" --use-mailmap":""}`;if(K)Q+=` --since="${K}"`;if(H)Q+=` --until="${H}"`;let V=i(Q,{encoding:"utf-8",cwd:q,maxBuffer:10485760}),$=[],k=V.split(`
|
|
6
|
+
`).filter((G)=>G.trim()),J=null,T=0,X=0,Z=0,O=[];for(let G of k)if(G.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:T,insertions:X,deletions:Z,files:O,branches:J.branches||[]});let U=G.split("|");if(U.length>=6){let B=U[0]?.trim(),j=U[1]?.trim(),v=U[2]?.trim(),M=U[3]?.trim(),l=U[4]?.trim(),x=U[5]?.trim()||"";if(B&&j&&v&&M){let I=[];if(x){let c=x.split(",").map((_)=>_.trim());for(let _ of c)if(_.startsWith("HEAD ->")){let w=_.match(/HEAD -> (.+)/);if(w?.[1]){let D=w[1].trim().replace(/^(origin|upstream|remote)\//,"");if(D&&!I.includes(D))I.push(D)}}else if(!_.startsWith("tag:")&&!_.startsWith("HEAD")){let w=_.replace(/^(origin|upstream|remote)\//,"");if(w&&!I.includes(w))I.push(w)}}J={hash:B,author:j,email:v,date:M,message:l,branches:I},T=0,X=0,Z=0,O=[]}}}else{let U=G.trim().split(/\s+/);if(U.length>=2&&U[0]&&U[1]){let B=parseInt(U[0],10)||0,j=parseInt(U[1],10)||0,v=U.slice(2).join(" ");if(v&&!Number.isNaN(B)&&!Number.isNaN(j))T++,X+=B,Z+=j,O.push({path:v,insertions:B,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:T,insertions:X,deletions:Z,files:O,branches:J.branches||[]});return $}import{exec as r}from"node:child_process";import{existsSync as h}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 z=Hq(r);async function E(q,K=!0){if(!q.path)return console.error(`Error: Repository ${q.name||"unknown"} has no path specified`),null;if(h(q.path)&&await S(q.path)){if(K)try{console.log(`Fetching all remote branches for ${q.name||q.path}...`),await z("git fetch --all --prune",{cwd:q.path}),console.log(`Pulling latest changes for ${q.name||q.path}...`),await z("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(h(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 z(`git clone "${q.url}" "${q.path}"`);try{await z("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 F(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=L(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(`
|
|
7
|
+
❌ \x1B[31mError:\x1B[0m \x1B[91mRepository ${H.name||"unknown"} has no path and no URL\x1B[0m`),K.push("");continue}let Y=await E(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 S(Y))throw new Error(`${Y} is not a git repository`);try{let Q=await y(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 S(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{F as loadConfig,S as isGitRepo,y as getContributors,b as getCommits,E as ensureRepository,Kq as Client};
|
package/dist/utils/config.d.ts
CHANGED
package/dist/utils/git.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export interface Commit {
|
|
|
19
19
|
insertions: number;
|
|
20
20
|
deletions: number;
|
|
21
21
|
files: CommitFile[];
|
|
22
|
+
branches: string[];
|
|
22
23
|
}
|
|
23
24
|
export declare function getContributors(repoPath: string): Promise<RepoContributor[]>;
|
|
24
25
|
export declare function getCommits(repoPath: string, since?: string, until?: string): Promise<Commit[]>;
|
package/dist/utils/repo.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { RepositoryConfig } from "./config";
|
|
2
|
-
export declare function ensureRepository(repo: RepositoryConfig): Promise<string | null>;
|
|
2
|
+
export declare function ensureRepository(repo: RepositoryConfig, pullIfExists?: boolean): Promise<string | null>;
|