gstatx 0.1.0 → 0.1.2

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 CHANGED
@@ -1,15 +1,205 @@
1
1
  # gstatx
2
2
 
3
- To install dependencies:
3
+ 📊 Export statistics from git repositories
4
+
5
+ A CLI tool to analyze and export statistics from one or multiple git repositories.
6
+
7
+ ## Installation
4
8
 
5
9
  ```bash
6
- bun install
10
+ npm install -g gstatx
7
11
  ```
8
12
 
9
- To run:
13
+ Or using npm:
10
14
 
11
15
  ```bash
12
- bun run src/index.ts
16
+ npm install -g gstatx
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```bash
22
+ # List contributors for a repository
23
+ gstatx contributors ./my-repo
24
+
25
+ # List contributors for multiple repositories
26
+ gstatx contributors ./repo1 ./repo2 ./repo3
27
+
28
+ # Hide commit counts
29
+ gstatx contributors --no-commits ./my-repo
13
30
  ```
14
31
 
15
- This project was created using `bun init` in bun v1.2.14. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.
32
+ ## User Guide
33
+
34
+ ### Commands
35
+
36
+ #### `contributors`
37
+
38
+ List contributors for specified git repositories.
39
+
40
+ **Usage:**
41
+ ```bash
42
+ gstatx contributors [options] <repo-path> [repo-path2 ...]
43
+ ```
44
+
45
+ **Options:**
46
+ - `--no-commits` - Hide commit counts in contributor list
47
+ - `--help, -h` - Show help message
48
+
49
+ **Examples:**
50
+ ```bash
51
+ # List contributors with commit counts
52
+ gstatx contributors ./my-repo
53
+
54
+ # List contributors without commit counts
55
+ gstatx contributors --no-commits ./my-repo
56
+
57
+ # List contributors for multiple repositories
58
+ gstatx contributors ./repo1 ./repo2 ./repo3
59
+ ```
60
+
61
+ ### Configuration File
62
+
63
+ You can create a `.gstatxrc.json` file to set default options and repository paths. The config file is automatically searched in the current directory and parent directories.
64
+
65
+ **Config File Location:**
66
+ - Default: `.gstatxrc.json` (searched from current directory up to root)
67
+ - Custom: Use `--config` or `-c` flag to specify a custom path
68
+
69
+ **Configuration Options:**
70
+
71
+ ```json
72
+ {
73
+ "contributors": {
74
+ "no-commits": false
75
+ },
76
+ "cloneIfNotExists": false,
77
+ "repositories": [
78
+ {
79
+ "path": "../my-repo",
80
+ "name": "My Repository",
81
+ "url": "git@github.com:user/repo.git"
82
+ }
83
+ ]
84
+ }
85
+ ```
86
+
87
+ **Configuration Fields:**
88
+
89
+ - `contributors.no-commits` (boolean, optional): Hide commit counts by default
90
+ - `cloneIfNotExists` (boolean, optional): Automatically clone repositories that don't exist locally
91
+ - `repositories` (array, optional): List of repositories to process
92
+ - `path` (string, required): Repository path (relative to config file location)
93
+ - `name` (string, optional): Display name for the repository
94
+ - `url` (string, optional): Git URL for cloning (required if `cloneIfNotExists: true`)
95
+
96
+ **Important Notes:**
97
+ - Repository paths in the config file are resolved relative to the `.gstatxrc.json` file location, not the current working directory
98
+ - If `cloneIfNotExists: true` and a repository doesn't exist, it will be cloned from the `url`
99
+ - CLI arguments always override config file values
100
+
101
+ **Example Config File:**
102
+
103
+ ```json
104
+ {
105
+ "contributors": {
106
+ "no-commits": false
107
+ },
108
+ "cloneIfNotExists": true,
109
+ "repositories": [
110
+ {
111
+ "path": "../project-a",
112
+ "name": "Project A",
113
+ "url": "git@github.com:user/project-a.git"
114
+ },
115
+ {
116
+ "path": "../project-b",
117
+ "name": "Project B",
118
+ "url": "git@github.com:user/project-b.git"
119
+ }
120
+ ]
121
+ }
122
+ ```
123
+
124
+ ### Global Options
125
+
126
+ - `--help, -h` - Show help message
127
+ - `--config, -c <path>` - Specify custom config file path
128
+
129
+ **Examples:**
130
+ ```bash
131
+ # Use custom config file
132
+ gstatx --config ./custom-config.json contributors
133
+
134
+ # Short form
135
+ gstatx -c ./custom-config.json contributors
136
+ ```
137
+
138
+ ### Using Config File Repositories
139
+
140
+ If you have repositories defined in your config file, you can run commands without specifying paths:
141
+
142
+ ```bash
143
+ # Uses repositories from .gstatxrc.json
144
+ gstatx contributors
145
+ ```
146
+
147
+ The tool will automatically use the repositories listed in your config file.
148
+
149
+ ### Auto-Cloning Repositories
150
+
151
+ When `cloneIfNotExists: true` is set in your config:
152
+
153
+ 1. The tool checks if each repository exists at the specified path
154
+ 2. If the repository doesn't exist and a `url` is provided, it will be cloned automatically
155
+ 3. If the repository already exists, it will be used as-is
156
+ 4. If the path exists but isn't a git repository, an error is shown
157
+
158
+ **Example:**
159
+ ```json
160
+ {
161
+ "cloneIfNotExists": true,
162
+ "repositories": [
163
+ {
164
+ "path": "../new-repo",
165
+ "name": "New Repository",
166
+ "url": "git@github.com:user/repo.git"
167
+ }
168
+ ]
169
+ }
170
+ ```
171
+
172
+ Running `gstatx contributors` will automatically clone the repository if it doesn't exist.
173
+
174
+ ## Development
175
+
176
+ ### Prerequisites
177
+
178
+ - Node.js >= 18.0.0
179
+ - Bun (for development)
180
+
181
+ ### Setup
182
+
183
+ ```bash
184
+ # Install dependencies
185
+ bun install
186
+
187
+ # Build the project
188
+ bun run build
189
+
190
+ # Run locally
191
+ bun run src/index.ts contributors ./my-repo
192
+ ```
193
+
194
+ ### Scripts
195
+
196
+ - `bun run build` - Build the project
197
+ - `bun run start` - Run the CLI locally
198
+ - `bun run check` - Check code quality
199
+ - `bun run check:fix` - Fix code quality issues
200
+ - `bun run lint` - Lint the code
201
+ - `bun run format` - Format the code
202
+
203
+ ## License
204
+
205
+ MIT
@@ -0,0 +1,8 @@
1
+ export interface RepoContributor {
2
+ name: string;
3
+ email: string;
4
+ commits: number;
5
+ }
6
+ export declare function getContributors(repoPath: string): Promise<RepoContributor[]>;
7
+ export declare function showHelp(): void;
8
+ export declare function listContributors(repoPaths: string[], showCommits?: boolean, configPath?: string): Promise<void>;
package/dist/index.js CHANGED
@@ -1,2 +1,48 @@
1
1
  #!/usr/bin/env node
2
- async function c(){let b=process.argv.slice(2);if(b.length===0)console.log("Usage: gstatx <repo-path> [repo-path2 ...]"),console.log(" Export statistics for one or more git repositories"),process.exit(1);console.log("Repositories to analyze:",b)}c().catch(console.error);
2
+ import{createRequire as S1}from"node:module";var B1=Object.create;var{getPrototypeOf:U1,defineProperty:g,getOwnPropertyNames:G1}=Object;var L1=Object.prototype.hasOwnProperty;var M1=($,q,J)=>{J=$!=null?B1(U1($)):{};let z=q||!$||!$.__esModule?g(J,"default",{value:$,enumerable:!0}):J;for(let Q of G1($))if(!L1.call(z,Q))g(z,Q,{get:()=>$[Q],enumerable:!0});return z};var M=($,q)=>()=>(q||$((q={exports:{}}).exports,q),q.exports);var I=S1(import.meta.url);var E=M((K1)=>{class w extends Error{constructor($,q,J){super(J);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=q,this.exitCode=$,this.nestedError=void 0}}class l extends w{constructor($){super(1,"commander.invalidArgument",$);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}K1.CommanderError=w;K1.InvalidArgumentError=l});var y=M((V1)=>{var{InvalidArgumentError:I1}=E();class c{constructor($,q){switch(this.description=q||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,$[0]){case"<":this.required=!0,this._name=$.slice(1,-1);break;case"[":this.required=!1,this._name=$.slice(1,-1);break;default:this.required=!0,this._name=$;break}if(this._name.endsWith("..."))this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_collectValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.push($),q}default($,q){return this.defaultValue=$,this.defaultValueDescription=q,this}argParser($){return this.parseArg=$,this}choices($){return this.argChoices=$.slice(),this.parseArg=(q,J)=>{if(!this.argChoices.includes(q))throw new I1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,J);return q},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function E1($){let q=$.name()+($.variadic===!0?"...":"");return $.required?"<"+q+">":"["+q+"]"}V1.Argument=c;V1.humanReadableArgName=E1});var A=M((F1)=>{var{humanReadableArgName:y1}=y();class m{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext($){this.helpWidth=this.helpWidth??$.helpWidth??80}visibleCommands($){let q=$.commands.filter((z)=>!z._hidden),J=$._getHelpCommand();if(J&&!J._hidden)q.push(J);if(this.sortSubcommands)q.sort((z,Q)=>{return z.name().localeCompare(Q.name())});return q}compareOptions($,q){let J=(z)=>{return z.short?z.short.replace(/^-/,""):z.long.replace(/^--/,"")};return J($).localeCompare(J(q))}visibleOptions($){let q=$.options.filter((z)=>!z.hidden),J=$._getHelpOption();if(J&&!J.hidden){let z=J.short&&$._findOption(J.short),Q=J.long&&$._findOption(J.long);if(!z&&!Q)q.push(J);else if(J.long&&!Q)q.push($.createOption(J.long,J.description));else if(J.short&&!z)q.push($.createOption(J.short,J.description))}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleGlobalOptions($){if(!this.showGlobalOptions)return[];let q=[];for(let J=$.parent;J;J=J.parent){let z=J.options.filter((Q)=>!Q.hidden);q.push(...z)}if(this.sortOptions)q.sort(this.compareOptions);return q}visibleArguments($){if($._argsDescription)$.registeredArguments.forEach((q)=>{q.description=q.description||$._argsDescription[q.name()]||""});if($.registeredArguments.find((q)=>q.description))return $.registeredArguments;return[]}subcommandTerm($){let q=$.registeredArguments.map((J)=>y1(J)).join(" ");return $._name+($._aliases[0]?"|"+$._aliases[0]:"")+($.options.length?" [options]":"")+(q?" "+q:"")}optionTerm($){return $.flags}argumentTerm($){return $.name()}longestSubcommandTermLength($,q){return q.visibleCommands($).reduce((J,z)=>{return Math.max(J,this.displayWidth(q.styleSubcommandTerm(q.subcommandTerm(z))))},0)}longestOptionTermLength($,q){return q.visibleOptions($).reduce((J,z)=>{return Math.max(J,this.displayWidth(q.styleOptionTerm(q.optionTerm(z))))},0)}longestGlobalOptionTermLength($,q){return q.visibleGlobalOptions($).reduce((J,z)=>{return Math.max(J,this.displayWidth(q.styleOptionTerm(q.optionTerm(z))))},0)}longestArgumentTermLength($,q){return q.visibleArguments($).reduce((J,z)=>{return Math.max(J,this.displayWidth(q.styleArgumentTerm(q.argumentTerm(z))))},0)}commandUsage($){let q=$._name;if($._aliases[0])q=q+"|"+$._aliases[0];let J="";for(let z=$.parent;z;z=z.parent)J=z.name()+" "+J;return J+q+" "+$.usage()}commandDescription($){return $.description()}subcommandDescription($){return $.summary()||$.description()}optionDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0){if($.required||$.optional||$.isBoolean()&&typeof $.defaultValue==="boolean")q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`)}if($.presetArg!==void 0&&$.optional)q.push(`preset: ${JSON.stringify($.presetArg)}`);if($.envVar!==void 0)q.push(`env: ${$.envVar}`);if(q.length>0){let J=`(${q.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}argumentDescription($){let q=[];if($.argChoices)q.push(`choices: ${$.argChoices.map((J)=>JSON.stringify(J)).join(", ")}`);if($.defaultValue!==void 0)q.push(`default: ${$.defaultValueDescription||JSON.stringify($.defaultValue)}`);if(q.length>0){let J=`(${q.join(", ")})`;if($.description)return`${$.description} ${J}`;return J}return $.description}formatItemList($,q,J){if(q.length===0)return[];return[J.styleTitle($),...q,""]}groupItems($,q,J){let z=new Map;return $.forEach((Q)=>{let X=J(Q);if(!z.has(X))z.set(X,[])}),q.forEach((Q)=>{let X=J(Q);if(!z.has(X))z.set(X,[]);z.get(X).push(Q)}),z}formatHelp($,q){let J=q.padWidth($,q),z=q.helpWidth??80;function Q(H,T){return q.formatItem(H,J,T,q)}let X=[`${q.styleTitle("Usage:")} ${q.styleUsage(q.commandUsage($))}`,""],Z=q.commandDescription($);if(Z.length>0)X=X.concat([q.boxWrap(q.styleCommandDescription(Z),z),""]);let Y=q.visibleArguments($).map((H)=>{return Q(q.styleArgumentTerm(q.argumentTerm(H)),q.styleArgumentDescription(q.argumentDescription(H)))});if(X=X.concat(this.formatItemList("Arguments:",Y,q)),this.groupItems($.options,q.visibleOptions($),(H)=>H.helpGroupHeading??"Options:").forEach((H,T)=>{let U=H.map((G)=>{return Q(q.styleOptionTerm(q.optionTerm(G)),q.styleOptionDescription(q.optionDescription(G)))});X=X.concat(this.formatItemList(T,U,q))}),q.showGlobalOptions){let H=q.visibleGlobalOptions($).map((T)=>{return Q(q.styleOptionTerm(q.optionTerm(T)),q.styleOptionDescription(q.optionDescription(T)))});X=X.concat(this.formatItemList("Global Options:",H,q))}return this.groupItems($.commands,q.visibleCommands($),(H)=>H.helpGroup()||"Commands:").forEach((H,T)=>{let U=H.map((G)=>{return Q(q.styleSubcommandTerm(q.subcommandTerm(G)),q.styleSubcommandDescription(q.subcommandDescription(G)))});X=X.concat(this.formatItemList(T,U,q))}),X.join(`
3
+ `)}displayWidth($){return d($).length}styleTitle($){return $}styleUsage($){return $.split(" ").map((q)=>{if(q==="[options]")return this.styleOptionText(q);if(q==="[command]")return this.styleSubcommandText(q);if(q[0]==="["||q[0]==="<")return this.styleArgumentText(q);return this.styleCommandText(q)}).join(" ")}styleCommandDescription($){return this.styleDescriptionText($)}styleOptionDescription($){return this.styleDescriptionText($)}styleSubcommandDescription($){return this.styleDescriptionText($)}styleArgumentDescription($){return this.styleDescriptionText($)}styleDescriptionText($){return $}styleOptionTerm($){return this.styleOptionText($)}styleSubcommandTerm($){return $.split(" ").map((q)=>{if(q==="[options]")return this.styleOptionText(q);if(q[0]==="["||q[0]==="<")return this.styleArgumentText(q);return this.styleSubcommandText(q)}).join(" ")}styleArgumentTerm($){return this.styleArgumentText($)}styleOptionText($){return $}styleArgumentText($){return $}styleSubcommandText($){return $}styleCommandText($){return $}padWidth($,q){return Math.max(q.longestOptionTermLength($,q),q.longestGlobalOptionTermLength($,q),q.longestSubcommandTermLength($,q),q.longestArgumentTermLength($,q))}preformatted($){return/\n[^\S\r\n]/.test($)}formatItem($,q,J,z){let X=" ".repeat(2);if(!J)return X+$;let Z=$.padEnd(q+$.length-z.displayWidth($)),Y=2,R=(this.helpWidth??80)-q-Y-2,H;if(R<this.minWidthToWrap||z.preformatted(J))H=J;else H=z.boxWrap(J,R).replace(/\n/g,`
4
+ `+" ".repeat(q+Y));return X+Z+" ".repeat(Y)+H.replace(/\n/g,`
5
+ ${X}`)}boxWrap($,q){if(q<this.minWidthToWrap)return $;let J=$.split(/\r\n|\n/),z=/[\s]*[^\s]+/g,Q=[];return J.forEach((X)=>{let Z=X.match(z);if(Z===null){Q.push("");return}let Y=[Z.shift()],_=this.displayWidth(Y[0]);Z.forEach((R)=>{let H=this.displayWidth(R);if(_+H<=q){Y.push(R),_+=H;return}Q.push(Y.join(""));let T=R.trimStart();Y=[T],_=this.displayWidth(T)}),Q.push(Y.join(""))}),Q.join(`
6
+ `)}}function d($){let q=/\x1b\[\d*(;\d*)*m/g;return $.replace(q,"")}F1.Help=m;F1.stripColor=d});var P=M((O1)=>{var{InvalidArgumentError:P1}=E();class s{constructor($,q){this.flags=$,this.description=q||"",this.required=$.includes("<"),this.optional=$.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test($),this.mandatory=!1;let J=k1($);if(this.short=J.shortFlag,this.long=J.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){return this.defaultValue=$,this.defaultValueDescription=q,this}preset($){return this.presetArg=$,this}conflicts($){return this.conflictsWith=this.conflictsWith.concat($),this}implies($){let q=$;if(typeof $==="string")q={[$]:!0};return this.implied=Object.assign(this.implied||{},q),this}env($){return this.envVar=$,this}argParser($){return this.parseArg=$,this}makeOptionMandatory($=!0){return this.mandatory=!!$,this}hideHelp($=!0){return this.hidden=!!$,this}_collectValue($,q){if(q===this.defaultValue||!Array.isArray(q))return[$];return q.push($),q}choices($){return this.argChoices=$.slice(),this.parseArg=(q,J)=>{if(!this.argChoices.includes(q))throw new P1(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._collectValue(q,J);return q},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){if(this.negate)return p(this.name().replace(/^no-/,""));return p(this.name())}helpGroup($){return this.helpGroupHeading=$,this}is($){return this.short===$||this.long===$}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class i{constructor($){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,$.forEach((q)=>{if(q.negate)this.negativeOptions.set(q.attributeName(),q);else this.positiveOptions.set(q.attributeName(),q)}),this.negativeOptions.forEach((q,J)=>{if(this.positiveOptions.has(J))this.dualOptions.add(J)})}valueFromOption($,q){let J=q.attributeName();if(!this.dualOptions.has(J))return!0;let z=this.negativeOptions.get(J).presetArg,Q=z!==void 0?z:!1;return q.negate===(Q===$)}}function p($){return $.split("-").reduce((q,J)=>{return q+J[0].toUpperCase()+J.slice(1)})}function k1($){let q,J,z=/^-[^-]$/,Q=/^--[^-]/,X=$.split(/[ |,]+/).concat("guard");if(z.test(X[0]))q=X.shift();if(Q.test(X[0]))J=X.shift();if(!q&&z.test(X[0]))q=X.shift();if(!q&&Q.test(X[0]))q=J,J=X.shift();if(X[0].startsWith("-")){let Z=X[0],Y=`option creation failed due to '${Z}' in option flags '${$}'`;if(/^-[^-][^-]/.test(Z))throw new Error(`${Y}
7
+ - a short flag is a single dash and a single character
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(Z))throw new Error(`${Y}
10
+ - too many short flags`);if(Q.test(Z))throw new Error(`${Y}
11
+ - too many long flags`);throw new Error(`${Y}
12
+ - unrecognised flag format`)}if(q===void 0&&J===void 0)throw new Error(`option creation failed due to no flags found in '${$}'.`);return{shortFlag:q,longFlag:J}}O1.Option=s;O1.DualOptions=i});var t=M((v1)=>{function C1($,q){if(Math.abs($.length-q.length)>3)return Math.max($.length,q.length);let J=[];for(let z=0;z<=$.length;z++)J[z]=[z];for(let z=0;z<=q.length;z++)J[0][z]=z;for(let z=1;z<=q.length;z++)for(let Q=1;Q<=$.length;Q++){let X=1;if($[Q-1]===q[z-1])X=0;else X=1;if(J[Q][z]=Math.min(J[Q-1][z]+1,J[Q][z-1]+1,J[Q-1][z-1]+X),Q>1&&z>1&&$[Q-1]===q[z-2]&&$[Q-2]===q[z-1])J[Q][z]=Math.min(J[Q][z],J[Q-2][z-2]+1)}return J[$.length][q.length]}function f1($,q){if(!q||q.length===0)return"";q=Array.from(new Set(q));let J=$.startsWith("--");if(J)$=$.slice(2),q=q.map((Z)=>Z.slice(2));let z=[],Q=3,X=0.4;if(q.forEach((Z)=>{if(Z.length<=1)return;let Y=C1($,Z),_=Math.max($.length,Z.length);if((_-Y)/_>X){if(Y<Q)Q=Y,z=[Z];else if(Y===Q)z.push(Z)}}),z.sort((Z,Y)=>Z.localeCompare(Y)),J)z=z.map((Z)=>`--${Z}`);if(z.length>1)return`
13
+ (Did you mean one of ${z.join(", ")}?)`;if(z.length===1)return`
14
+ (Did you mean ${z[0]}?)`;return""}v1.suggestSimilar=f1});var o=M((p1)=>{var u1=I("node:events").EventEmitter,k=I("node:child_process"),L=I("node:path"),F=I("node:fs"),B=I("node:process"),{Argument:g1,humanReadableArgName:l1}=y(),{CommanderError:O}=E(),{Help:c1,stripColor:m1}=A(),{Option:n,DualOptions:d1}=P(),{suggestSimilar:r}=t();class b extends u1{constructor($){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=$||"",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:(q)=>B.stdout.write(q),writeErr:(q)=>B.stderr.write(q),outputError:(q,J)=>J(q),getOutHelpWidth:()=>B.stdout.isTTY?B.stdout.columns:void 0,getErrHelpWidth:()=>B.stderr.isTTY?B.stderr.columns:void 0,getOutHasColors:()=>x()??(B.stdout.isTTY&&B.stdout.hasColors?.()),getErrHasColors:()=>x()??(B.stderr.isTTY&&B.stderr.hasColors?.()),stripColor:(q)=>m1(q)},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($){return this._outputConfiguration=$._outputConfiguration,this._helpOption=$._helpOption,this._helpCommand=$._helpCommand,this._helpConfiguration=$._helpConfiguration,this._exitCallback=$._exitCallback,this._storeOptionsAsProperties=$._storeOptionsAsProperties,this._combineFlagAndOptionalValue=$._combineFlagAndOptionalValue,this._allowExcessArguments=$._allowExcessArguments,this._enablePositionalOptions=$._enablePositionalOptions,this._showHelpAfterError=$._showHelpAfterError,this._showSuggestionAfterError=$._showSuggestionAfterError,this}_getCommandAndAncestors(){let $=[];for(let q=this;q;q=q.parent)$.push(q);return $}command($,q,J){let z=q,Q=J;if(typeof z==="object"&&z!==null)Q=z,z=null;Q=Q||{};let[,X,Z]=$.match(/([^ ]+) *(.*)/),Y=this.createCommand(X);if(z)Y.description(z),Y._executableHandler=!0;if(Q.isDefault)this._defaultCommandName=Y._name;if(Y._hidden=!!(Q.noHelp||Q.hidden),Y._executableFile=Q.executableFile||null,Z)Y.arguments(Z);if(this._registerCommand(Y),Y.parent=this,Y.copyInheritedSettings(this),z)return this;return Y}createCommand($){return new b($)}createHelp(){return Object.assign(new c1,this.configureHelp())}configureHelp($){if($===void 0)return this._helpConfiguration;return this._helpConfiguration=$,this}configureOutput($){if($===void 0)return this._outputConfiguration;return this._outputConfiguration={...this._outputConfiguration,...$},this}showHelpAfterError($=!0){if(typeof $!=="string")$=!!$;return this._showHelpAfterError=$,this}showSuggestionAfterError($=!0){return this._showSuggestionAfterError=!!$,this}addCommand($,q){if(!$._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);if(q=q||{},q.isDefault)this._defaultCommandName=$._name;if(q.noHelp||q.hidden)$._hidden=!0;return this._registerCommand($),$.parent=this,$._checkForBrokenPassThrough(),this}createArgument($,q){return new g1($,q)}argument($,q,J,z){let Q=this.createArgument($,q);if(typeof J==="function")Q.default(z).argParser(J);else Q.default(J);return this.addArgument(Q),this}arguments($){return $.trim().split(/ +/).forEach((q)=>{this.argument(q)}),this}addArgument($){let q=this.registeredArguments.slice(-1)[0];if(q?.variadic)throw new Error(`only the last argument can be variadic '${q.name()}'`);if($.required&&$.defaultValue!==void 0&&$.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${$.name()}'`);return this.registeredArguments.push($),this}helpCommand($,q){if(typeof $==="boolean"){if(this._addImplicitHelpCommand=$,$&&this._defaultCommandGroup)this._initCommandGroup(this._getHelpCommand());return this}let J=$??"help [command]",[,z,Q]=J.match(/([^ ]+) *(.*)/),X=q??"display help for command",Z=this.createCommand(z);if(Z.helpOption(!1),Q)Z.arguments(Q);if(X)Z.description(X);if(this._addImplicitHelpCommand=!0,this._helpCommand=Z,$||q)this._initCommandGroup(Z);return this}addHelpCommand($,q){if(typeof $!=="object")return this.helpCommand($,q),this;return this._addImplicitHelpCommand=!0,this._helpCommand=$,this._initCommandGroup($),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){let J=["preSubcommand","preAction","postAction"];if(!J.includes($))throw new Error(`Unexpected value for event passed to hook : '${$}'.
16
+ Expecting one of '${J.join("', '")}'`);if(this._lifeCycleHooks[$])this._lifeCycleHooks[$].push(q);else this._lifeCycleHooks[$]=[q];return this}exitOverride($){if($)this._exitCallback=$;else this._exitCallback=(q)=>{if(q.code!=="commander.executeSubCommandAsync")throw q};return this}_exit($,q,J){if(this._exitCallback)this._exitCallback(new O($,q,J));B.exit($)}action($){let q=(J)=>{let z=this.registeredArguments.length,Q=J.slice(0,z);if(this._storeOptionsAsProperties)Q[z]=this;else Q[z]=this.opts();return Q.push(this),$.apply(this,Q)};return this._actionHandler=q,this}createOption($,q){return new n($,q)}_callParseArg($,q,J,z){try{return $.parseArg(q,J)}catch(Q){if(Q.code==="commander.invalidArgument"){let X=`${z} ${Q.message}`;this.error(X,{exitCode:Q.exitCode,code:Q.code})}throw Q}}_registerOption($){let q=$.short&&this._findOption($.short)||$.long&&this._findOption($.long);if(q){let J=$.long&&this._findOption($.long)?$.long:$.short;throw new Error(`Cannot add option '${$.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${J}'
17
+ - already used by option '${q.flags}'`)}this._initOptionGroup($),this.options.push($)}_registerCommand($){let q=(z)=>{return[z.name()].concat(z.aliases())},J=q($).find((z)=>this._findCommand(z));if(J){let z=q(this._findCommand(J)).join("|"),Q=q($).join("|");throw new Error(`cannot add command '${Q}' as already have command '${z}'`)}this._initCommandGroup($),this.commands.push($)}addOption($){this._registerOption($);let q=$.name(),J=$.attributeName();if($.negate){let Q=$.long.replace(/^--no-/,"--");if(!this._findOption(Q))this.setOptionValueWithSource(J,$.defaultValue===void 0?!0:$.defaultValue,"default")}else if($.defaultValue!==void 0)this.setOptionValueWithSource(J,$.defaultValue,"default");let z=(Q,X,Z)=>{if(Q==null&&$.presetArg!==void 0)Q=$.presetArg;let Y=this.getOptionValue(J);if(Q!==null&&$.parseArg)Q=this._callParseArg($,Q,Y,X);else if(Q!==null&&$.variadic)Q=$._collectValue(Q,Y);if(Q==null)if($.negate)Q=!1;else if($.isBoolean()||$.optional)Q=!0;else Q="";this.setOptionValueWithSource(J,Q,Z)};if(this.on("option:"+q,(Q)=>{let X=`error: option '${$.flags}' argument '${Q}' is invalid.`;z(Q,X,"cli")}),$.envVar)this.on("optionEnv:"+q,(Q)=>{let X=`error: option '${$.flags}' value '${Q}' from env '${$.envVar}' is invalid.`;z(Q,X,"env")});return this}_optionEx($,q,J,z,Q){if(typeof q==="object"&&q instanceof n)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let X=this.createOption(q,J);if(X.makeOptionMandatory(!!$.mandatory),typeof z==="function")X.default(Q).argParser(z);else if(z instanceof RegExp){let Z=z;z=(Y,_)=>{let R=Z.exec(Y);return R?R[0]:_},X.default(Q).argParser(z)}else X.default(z);return this.addOption(X)}option($,q,J,z){return this._optionEx({},$,q,J,z)}requiredOption($,q,J,z){return this._optionEx({mandatory:!0},$,q,J,z)}combineFlagAndOptionalValue($=!0){return this._combineFlagAndOptionalValue=!!$,this}allowUnknownOption($=!0){return this._allowUnknownOption=!!$,this}allowExcessArguments($=!0){return this._allowExcessArguments=!!$,this}enablePositionalOptions($=!0){return this._enablePositionalOptions=!!$,this}passThroughOptions($=!0){return this._passThroughOptions=!!$,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($=!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=!!$,this}getOptionValue($){if(this._storeOptionsAsProperties)return this[$];return this._optionValues[$]}setOptionValue($,q){return this.setOptionValueWithSource($,q,void 0)}setOptionValueWithSource($,q,J){if(this._storeOptionsAsProperties)this[$]=q;else this._optionValues[$]=q;return this._optionValueSources[$]=J,this}getOptionValueSource($){return this._optionValueSources[$]}getOptionValueSourceWithGlobals($){let q;return this._getCommandAndAncestors().forEach((J)=>{if(J.getOptionValueSource($)!==void 0)q=J.getOptionValueSource($)}),q}_prepareUserArgs($,q){if($!==void 0&&!Array.isArray($))throw new Error("first parameter to parse must be array or undefined");if(q=q||{},$===void 0&&q.from===void 0){if(B.versions?.electron)q.from="electron";let z=B.execArgv??[];if(z.includes("-e")||z.includes("--eval")||z.includes("-p")||z.includes("--print"))q.from="eval"}if($===void 0)$=B.argv;this.rawArgs=$.slice();let J;switch(q.from){case void 0:case"node":this._scriptPath=$[1],J=$.slice(2);break;case"electron":if(B.defaultApp)this._scriptPath=$[1],J=$.slice(2);else J=$.slice(1);break;case"user":J=$.slice(0);break;case"eval":J=$.slice(1);break;default:throw new Error(`unexpected parse option { from: '${q.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",J}parse($,q){this._prepareForParse();let J=this._prepareUserArgs($,q);return this._parseCommand([],J),this}async parseAsync($,q){this._prepareForParse();let J=this._prepareUserArgs($,q);return await this._parseCommand([],J),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,J){if(F.existsSync($))return;let z=q?`searched for local subcommand relative to directory '${q}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",Q=`'${$}' does not exist
19
+ - if '${J}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
+ - ${z}`;throw new Error(Q)}_executeSubCommand($,q){q=q.slice();let J=!1,z=[".js",".ts",".tsx",".mjs",".cjs"];function Q(R,H){let T=L.resolve(R,H);if(F.existsSync(T))return T;if(z.includes(L.extname(H)))return;let U=z.find((G)=>F.existsSync(`${T}${G}`));if(U)return`${T}${U}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let X=$._executableFile||`${this._name}-${$._name}`,Z=this._executableDir||"";if(this._scriptPath){let R;try{R=F.realpathSync(this._scriptPath)}catch{R=this._scriptPath}Z=L.resolve(L.dirname(R),Z)}if(Z){let R=Q(Z,X);if(!R&&!$._executableFile&&this._scriptPath){let H=L.basename(this._scriptPath,L.extname(this._scriptPath));if(H!==this._name)R=Q(Z,`${H}-${$._name}`)}X=R||X}J=z.includes(L.extname(X));let Y;if(B.platform!=="win32")if(J)q.unshift(X),q=a(B.execArgv).concat(q),Y=k.spawn(B.argv[0],q,{stdio:"inherit"});else Y=k.spawn(X,q,{stdio:"inherit"});else this._checkForMissingExecutable(X,Z,$._name),q.unshift(X),q=a(B.execArgv).concat(q),Y=k.spawn(B.execPath,q,{stdio:"inherit"});if(!Y.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((H)=>{B.on(H,()=>{if(Y.killed===!1&&Y.exitCode===null)Y.kill(H)})});let _=this._exitCallback;Y.on("close",(R)=>{if(R=R??1,!_)B.exit(R);else _(new O(R,"commander.executeSubCommandAsync","(close)"))}),Y.on("error",(R)=>{if(R.code==="ENOENT")this._checkForMissingExecutable(X,Z,$._name);else if(R.code==="EACCES")throw new Error(`'${X}' not executable`);if(!_)B.exit(1);else{let H=new O(1,"commander.executeSubCommandAsync","(error)");H.nestedError=R,_(H)}}),this.runningCommand=Y}_dispatchSubcommand($,q,J){let z=this._findCommand($);if(!z)this.help({error:!0});z._prepareForParse();let Q;return Q=this._chainOrCallSubCommandHook(Q,z,"preSubcommand"),Q=this._chainOrCall(Q,()=>{if(z._executableHandler)this._executeSubCommand(z,q.concat(J));else return z._parseCommand(q,J)}),Q}_dispatchHelpCommand($){if(!$)this.help();let q=this._findCommand($);if(q&&!q._executableHandler)q.help();return this._dispatchSubcommand($,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach(($,q)=>{if($.required&&this.args[q]==null)this.missingArgument($.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 $=(J,z,Q)=>{let X=z;if(z!==null&&J.parseArg){let Z=`error: command-argument value '${z}' is invalid for argument '${J.name()}'.`;X=this._callParseArg(J,z,Q,Z)}return X};this._checkNumberOfArguments();let q=[];this.registeredArguments.forEach((J,z)=>{let Q=J.defaultValue;if(J.variadic){if(z<this.args.length){if(Q=this.args.slice(z),J.parseArg)Q=Q.reduce((X,Z)=>{return $(J,Z,X)},J.defaultValue)}else if(Q===void 0)Q=[]}else if(z<this.args.length){if(Q=this.args[z],J.parseArg)Q=$(J,Q,J.defaultValue)}q[z]=Q}),this.processedArgs=q}_chainOrCall($,q){if($?.then&&typeof $.then==="function")return $.then(()=>q());return q()}_chainOrCallHooks($,q){let J=$,z=[];if(this._getCommandAndAncestors().reverse().filter((Q)=>Q._lifeCycleHooks[q]!==void 0).forEach((Q)=>{Q._lifeCycleHooks[q].forEach((X)=>{z.push({hookedCommand:Q,callback:X})})}),q==="postAction")z.reverse();return z.forEach((Q)=>{J=this._chainOrCall(J,()=>{return Q.callback(Q.hookedCommand,this)})}),J}_chainOrCallSubCommandHook($,q,J){let z=$;if(this._lifeCycleHooks[J]!==void 0)this._lifeCycleHooks[J].forEach((Q)=>{z=this._chainOrCall(z,()=>{return Q(this,q)})});return z}_parseCommand($,q){let J=this.parseOptions(q);if(this._parseOptionsEnv(),this._parseOptionsImplied(),$=$.concat(J.operands),q=J.unknown,this.args=$.concat(q),$&&this._findCommand($[0]))return this._dispatchSubcommand($[0],$.slice(1),q);if(this._getHelpCommand()&&$[0]===this._getHelpCommand().name())return this._dispatchHelpCommand($[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(q),this._dispatchSubcommand(this._defaultCommandName,$,q);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(J.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let z=()=>{if(J.unknown.length>0)this.unknownOption(J.unknown[0])},Q=`command:${this.name()}`;if(this._actionHandler){z(),this._processArguments();let X;if(X=this._chainOrCallHooks(X,"preAction"),X=this._chainOrCall(X,()=>this._actionHandler(this.processedArgs)),this.parent)X=this._chainOrCall(X,()=>{this.parent.emit(Q,$,q)});return X=this._chainOrCallHooks(X,"postAction"),X}if(this.parent?.listenerCount(Q))z(),this._processArguments(),this.parent.emit(Q,$,q);else if($.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",$,q);if(this.listenerCount("command:*"))this.emit("command:*",$,q);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($){if(!$)return;return this.commands.find((q)=>q._name===$||q._aliases.includes($))}_findOption($){return this.options.find((q)=>q.is($))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(($)=>{$.options.forEach((q)=>{if(q.mandatory&&$.getOptionValue(q.attributeName())===void 0)$.missingMandatoryOptionValue(q)})})}_checkForConflictingLocalOptions(){let $=this.options.filter((J)=>{let z=J.attributeName();if(this.getOptionValue(z)===void 0)return!1;return this.getOptionValueSource(z)!=="default"});$.filter((J)=>J.conflictsWith.length>0).forEach((J)=>{let z=$.find((Q)=>J.conflictsWith.includes(Q.attributeName()));if(z)this._conflictingOption(J,z)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(($)=>{$._checkForConflictingLocalOptions()})}parseOptions($){let q=[],J=[],z=q;function Q(R){return R.length>1&&R[0]==="-"}let X=(R)=>{if(!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(R))return!1;return!this._getCommandAndAncestors().some((H)=>H.options.map((T)=>T.short).some((T)=>/^-\d$/.test(T)))},Z=null,Y=null,_=0;while(_<$.length||Y){let R=Y??$[_++];if(Y=null,R==="--"){if(z===J)z.push(R);z.push(...$.slice(_));break}if(Z&&(!Q(R)||X(R))){this.emit(`option:${Z.name()}`,R);continue}if(Z=null,Q(R)){let H=this._findOption(R);if(H){if(H.required){let T=$[_++];if(T===void 0)this.optionMissingArgument(H);this.emit(`option:${H.name()}`,T)}else if(H.optional){let T=null;if(_<$.length&&(!Q($[_])||X($[_])))T=$[_++];this.emit(`option:${H.name()}`,T)}else this.emit(`option:${H.name()}`);Z=H.variadic?H:null;continue}}if(R.length>2&&R[0]==="-"&&R[1]!=="-"){let H=this._findOption(`-${R[1]}`);if(H){if(H.required||H.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${H.name()}`,R.slice(2));else this.emit(`option:${H.name()}`),Y=`-${R.slice(2)}`;continue}}if(/^--[^=]+=/.test(R)){let H=R.indexOf("="),T=this._findOption(R.slice(0,H));if(T&&(T.required||T.optional)){this.emit(`option:${T.name()}`,R.slice(H+1));continue}}if(z===q&&Q(R)&&!(this.commands.length===0&&X(R)))z=J;if((this._enablePositionalOptions||this._passThroughOptions)&&q.length===0&&J.length===0){if(this._findCommand(R)){q.push(R),J.push(...$.slice(_));break}else if(this._getHelpCommand()&&R===this._getHelpCommand().name()){q.push(R,...$.slice(_));break}else if(this._defaultCommandName){J.push(R,...$.slice(_));break}}if(this._passThroughOptions){z.push(R,...$.slice(_));break}z.push(R)}return{operands:q,unknown:J}}opts(){if(this._storeOptionsAsProperties){let $={},q=this.options.length;for(let J=0;J<q;J++){let z=this.options[J].attributeName();$[z]=z===this._versionOptionName?this._version:this[z]}return $}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(($,q)=>Object.assign($,q.opts()),{})}error($,q){if(this._outputConfiguration.outputError(`${$}
22
+ `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
+ `);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
24
+ `),this.outputHelp({error:!0});let J=q||{},z=J.exitCode||1,Q=J.code||"commander.error";this._exit(z,Q,$)}_parseOptionsEnv(){this.options.forEach(($)=>{if($.envVar&&$.envVar in B.env){let q=$.attributeName();if(this.getOptionValue(q)===void 0||["default","config","env"].includes(this.getOptionValueSource(q)))if($.required||$.optional)this.emit(`optionEnv:${$.name()}`,B.env[$.envVar]);else this.emit(`optionEnv:${$.name()}`)}})}_parseOptionsImplied(){let $=new d1(this.options),q=(J)=>{return this.getOptionValue(J)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(J))};this.options.filter((J)=>J.implied!==void 0&&q(J.attributeName())&&$.valueFromOption(this.getOptionValue(J.attributeName()),J)).forEach((J)=>{Object.keys(J.implied).filter((z)=>!q(z)).forEach((z)=>{this.setOptionValueWithSource(z,J.implied[z],"implied")})})}missingArgument($){let q=`error: missing required argument '${$}'`;this.error(q,{code:"commander.missingArgument"})}optionMissingArgument($){let q=`error: option '${$.flags}' argument missing`;this.error(q,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue($){let q=`error: required option '${$.flags}' not specified`;this.error(q,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption($,q){let J=(X)=>{let Z=X.attributeName(),Y=this.getOptionValue(Z),_=this.options.find((H)=>H.negate&&Z===H.attributeName()),R=this.options.find((H)=>!H.negate&&Z===H.attributeName());if(_&&(_.presetArg===void 0&&Y===!1||_.presetArg!==void 0&&Y===_.presetArg))return _;return R||X},z=(X)=>{let Z=J(X),Y=Z.attributeName();if(this.getOptionValueSource(Y)==="env")return`environment variable '${Z.envVar}'`;return`option '${Z.flags}'`},Q=`error: ${z($)} cannot be used with ${z(q)}`;this.error(Q,{code:"commander.conflictingOption"})}unknownOption($){if(this._allowUnknownOption)return;let q="";if($.startsWith("--")&&this._showSuggestionAfterError){let z=[],Q=this;do{let X=Q.createHelp().visibleOptions(Q).filter((Z)=>Z.long).map((Z)=>Z.long);z=z.concat(X),Q=Q.parent}while(Q&&!Q._enablePositionalOptions);q=r($,z)}let J=`error: unknown option '${$}'${q}`;this.error(J,{code:"commander.unknownOption"})}_excessArguments($){if(this._allowExcessArguments)return;let q=this.registeredArguments.length,J=q===1?"":"s",Q=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${q} argument${J} but got ${$.length}.`;this.error(Q,{code:"commander.excessArguments"})}unknownCommand(){let $=this.args[0],q="";if(this._showSuggestionAfterError){let z=[];this.createHelp().visibleCommands(this).forEach((Q)=>{if(z.push(Q.name()),Q.alias())z.push(Q.alias())}),q=r($,z)}let J=`error: unknown command '${$}'${q}`;this.error(J,{code:"commander.unknownCommand"})}version($,q,J){if($===void 0)return this._version;this._version=$,q=q||"-V, --version",J=J||"output the version number";let z=this.createOption(q,J);return this._versionOptionName=z.attributeName(),this._registerOption(z),this.on("option:"+z.name(),()=>{this._outputConfiguration.writeOut(`${$}
25
+ `),this._exit(0,"commander.version",$)}),this}description($,q){if($===void 0&&q===void 0)return this._description;if(this._description=$,q)this._argsDescription=q;return this}summary($){if($===void 0)return this._summary;return this._summary=$,this}alias($){if($===void 0)return this._aliases[0];let q=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)q=this.commands[this.commands.length-1];if($===q._name)throw new Error("Command alias can't be the same as its name");let J=this.parent?._findCommand($);if(J){let z=[J.name()].concat(J.aliases()).join("|");throw new Error(`cannot add alias '${$}' to command '${this.name()}' as already have command '${z}'`)}return q._aliases.push($),this}aliases($){if($===void 0)return this._aliases;return $.forEach((q)=>this.alias(q)),this}usage($){if($===void 0){if(this._usage)return this._usage;let q=this.registeredArguments.map((J)=>{return l1(J)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?q:[]).join(" ")}return this._usage=$,this}name($){if($===void 0)return this._name;return this._name=$,this}helpGroup($){if($===void 0)return this._helpGroupHeading??"";return this._helpGroupHeading=$,this}commandsGroup($){if($===void 0)return this._defaultCommandGroup??"";return this._defaultCommandGroup=$,this}optionsGroup($){if($===void 0)return this._defaultOptionGroup??"";return this._defaultOptionGroup=$,this}_initOptionGroup($){if(this._defaultOptionGroup&&!$.helpGroupHeading)$.helpGroup(this._defaultOptionGroup)}_initCommandGroup($){if(this._defaultCommandGroup&&!$.helpGroup())$.helpGroup(this._defaultCommandGroup)}nameFromFilename($){return this._name=L.basename($,L.extname($)),this}executableDir($){if($===void 0)return this._executableDir;return this._executableDir=$,this}helpInformation($){let q=this.createHelp(),J=this._getOutputContext($);q.prepareContext({error:J.error,helpWidth:J.helpWidth,outputHasColors:J.hasColors});let z=q.formatHelp(this,q);if(J.hasColors)return z;return this._outputConfiguration.stripColor(z)}_getOutputContext($){$=$||{};let q=!!$.error,J,z,Q;if(q)J=(Z)=>this._outputConfiguration.writeErr(Z),z=this._outputConfiguration.getErrHasColors(),Q=this._outputConfiguration.getErrHelpWidth();else J=(Z)=>this._outputConfiguration.writeOut(Z),z=this._outputConfiguration.getOutHasColors(),Q=this._outputConfiguration.getOutHelpWidth();return{error:q,write:(Z)=>{if(!z)Z=this._outputConfiguration.stripColor(Z);return J(Z)},hasColors:z,helpWidth:Q}}outputHelp($){let q;if(typeof $==="function")q=$,$=void 0;let J=this._getOutputContext($),z={error:J.error,write:J.write,command:this};this._getCommandAndAncestors().reverse().forEach((X)=>X.emit("beforeAllHelp",z)),this.emit("beforeHelp",z);let Q=this.helpInformation({error:J.error});if(q){if(Q=q(Q),typeof Q!=="string"&&!Buffer.isBuffer(Q))throw new Error("outputHelp callback must return a string or a Buffer")}if(J.write(Q),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",z),this._getCommandAndAncestors().forEach((X)=>X.emit("afterAllHelp",z))}helpOption($,q){if(typeof $==="boolean"){if($){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($??"-h, --help",q??"display help for command"),$||q)this._initOptionGroup(this._helpOption);return this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption($){return this._helpOption=$,this._initOptionGroup($),this}help($){this.outputHelp($);let q=Number(B.exitCode??0);if(q===0&&$&&typeof $!=="function"&&$.error)q=1;this._exit(q,"commander.help","(outputHelp)")}addHelpText($,q){let J=["beforeAll","before","after","afterAll"];if(!J.includes($))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${J.join("', '")}'`);let z=`${$}Help`;return this.on(z,(Q)=>{let X;if(typeof q==="function")X=q({error:Q.error,command:Q.command});else X=q;if(X)Q.write(`${X}
27
+ `)}),this}_outputHelpIfRequested($){let q=this._getHelpOption();if(q&&$.find((z)=>q.is(z)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function a($){return $.map((q)=>{if(!q.startsWith("--inspect"))return q;let J,z="127.0.0.1",Q="9229",X;if((X=q.match(/^(--inspect(-brk)?)$/))!==null)J=X[1];else if((X=q.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(J=X[1],/^\d+$/.test(X[3]))Q=X[3];else z=X[3];else if((X=q.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)J=X[1],z=X[3],Q=X[4];if(J&&Q!=="0")return`${J}=${z}:${parseInt(Q)+1}`;return q})}function x(){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}p1.Command=b;p1.useColor=x});var J1=M((r1)=>{var{Argument:e}=y(),{Command:C}=o(),{CommanderError:t1,InvalidArgumentError:$1}=E(),{Help:n1}=A(),{Option:q1}=P();r1.program=new C;r1.createCommand=($)=>new C($);r1.createOption=($,q)=>new q1($,q);r1.createArgument=($,q)=>new e($,q);r1.Command=C;r1.Option=q1;r1.Argument=e;r1.Help=n1;r1.CommanderError=t1;r1.InvalidArgumentError=$1;r1.InvalidOptionArgumentError=$1});var z1=M1(J1(),1),{program:x2,createCommand:b2,createArgument:C2,createOption:f2,CommanderError:v2,InvalidArgumentError:h2,InvalidOptionArgumentError:u2,Command:Q1,Argument:g2,Option:l2,Help:c2}=z1.default;import{existsSync as X1}from"node:fs";import{readFile as R2}from"node:fs/promises";import{dirname as Y1,join as H2,resolve as f}from"node:path";var _2=".gstatxrc.json";function T2($){let q=f($),J=20,z=0;while(z<J){let Q=H2(q,_2);if(X1(Q))return Q;let X=Y1(q);if(X===q)break;q=X,z++}return null}async function V($,q=process.cwd()){try{let J;if($){let Z=f($);if(!X1(Z))return console.error(`Error: Config file not found: ${Z}`),null;J=Z}else if(J=T2(q),!J)return null;let z=await R2(J,"utf-8"),Q=JSON.parse(z),X=Y1(J);if(Q.repositories)Q.repositories=Q.repositories.map((Z)=>({...Z,path:f(X,Z.path)}));return{config:Q,configDir:X}}catch(J){if($)console.error(`Error: Failed to load config file: ${J}`);return null}}import{exec as B2,execSync as U2}from"node:child_process";import{access as G2}from"node:fs/promises";import{join as L2}from"node:path";import{promisify as M2}from"node:util";var Z1=M2(B2);async function W($){try{return await G2(L2($,".git")),!0}catch{return!1}}async function v($){try{let{stdout:q}=await Z1("git shortlog -sn --all",{cwd:$}),J=[],z=q.trim().split(`
28
+ `);for(let Q of z){let X=Q.match(/^\s*(\d+)\s+(.+)$/);if(X){let Z=parseInt(X[1]||"0",10),Y=X[2]||"",{stdout:_}=await Z1(`git log --format='%aE' --author="${Y.replace(/"/g,"\\\"")}" -1`,{cwd:$}),R=_.trim().split(`
29
+ `)[0]||"";J.push({name:Y,email:R,commits:Z})}}return J.sort((Q,X)=>X.commits-Q.commits)}catch(q){throw new Error(`Failed to get contributors from ${$}: ${q}`)}}function h($,q,J){let z='git log --format="%H|%an|%ae|%ad|%s" --date=iso-strict --numstat';if(q)z+=` --since="${q}"`;if(J)z+=` --until="${J}"`;let Q=U2(z,{encoding:"utf-8",cwd:$,maxBuffer:10485760}),X=[],Z=Q.split(`
30
+ `).filter((U)=>U.trim()),Y=null,_=0,R=0,H=0,T=[];for(let U of Z)if(U.includes("|")){if(Y?.hash&&Y?.author&&Y?.email&&Y?.date&&Y?.message)X.push({hash:Y.hash,author:Y.author,email:Y.email,date:Y.date,message:Y.message,filesChanged:_,insertions:R,deletions:H,files:T});let[G,S,K,j,...T1]=U.split("|");if(G&&S&&K&&j)Y={hash:G.trim(),author:S.trim(),email:K.trim(),date:j.trim(),message:T1.join("|").trim()},_=0,R=0,H=0,T=[]}else{let G=U.trim().split(/\s+/);if(G.length>=2&&G[0]&&G[1]){let S=parseInt(G[0],10)||0,K=parseInt(G[1],10)||0,j=G.slice(2).join(" ");if(j&&!Number.isNaN(S)&&!Number.isNaN(K))_++,R+=S,H+=K,T.push({path:j,insertions:S,deletions:K})}}if(Y?.hash&&Y?.author&&Y?.email&&Y?.date&&Y?.message)X.push({hash:Y.hash,author:Y.author,email:Y.email,date:Y.date,message:Y.message,filesChanged:_,insertions:R,deletions:H,files:T});return X}import{exec as S2}from"node:child_process";import{existsSync as R1}from"node:fs";import{mkdir as K2}from"node:fs/promises";import{dirname as W2}from"node:path";import{promisify as j2}from"node:util";var I2=j2(S2);async function u($){if(R1($.path)&&await W($.path))return $.path;if(R1($.path))return console.error(`Error: Path exists but is not a git repository: ${$.path}`),null;if(!$.url)return console.error(`Error: Repository not found at ${$.path} and no URL provided for cloning`),null;try{console.log(`Cloning repository from ${$.url} to ${$.path}...`);let q=W2($.path),J=$.path.split("/").pop()||"repository";try{await K2(q,{recursive:!0})}catch(z){}return await I2(`git clone "${$.url}" "${$.path}"`),console.log(`✓ Successfully cloned ${$.name||J}`),$.path}catch(q){return console.error(`Error: Failed to clone repository: ${q}`),null}}class N{config;loadedConfig=null;constructor($={}){this.config=$}async initialize(){if(!this.config.repositories){if(this.loadedConfig=await V(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.cloneIfNotExists&&this.config.repositories){let $=[];for(let q of this.config.repositories){let J=await u(q);if(J)$.push(J)}this.config.repositories=this.config.repositories.map((q,J)=>({...q,path:$[J]||q.path}))}}getRepoPaths($){if($&&$.length>0)return $;if(this.config.repositories)return this.config.repositories.map((q)=>q.path);return[]}async listContributors($){await this.initialize();let q=this.getRepoPaths($);if(q.length===0)throw new Error("No repository paths specified");let J=[];for(let z of q){if(!await W(z))throw new Error(`${z} is not a git repository`);try{let X=await v(z);J.push({path:z,contributors:X})}catch(X){throw new Error(`Failed to get contributors from ${z}: ${X}`)}}return J}async getHistory($,q,J){await this.initialize();let z=this.getRepoPaths($);if(z.length===0)throw new Error("No repository paths specified");let Q=[];for(let X of z){if(!await W(X))throw new Error(`${X} is not a git repository`);try{let Y=h(X,q,J);Q.push({path:X,commits:Y})}catch(Y){throw new Error(`Failed to get commit history from ${X}: ${Y}`)}}return Q}}async function H1($,q=!0,J){let z=new N({configPath:J});try{let Q=await z.listContributors($);for(let X of Q)if(console.log(`
31
+ \uD83D\uDCCA Contributors for ${X.path}:`),console.log("─".repeat(60)),X.contributors.length===0)console.log(" No contributors found");else for(let Z of X.contributors)if(q)console.log(` ${Z.name} <${Z.email}> (${Z.commits} commits)`);else console.log(` ${Z.name} <${Z.email}>`)}catch(Q){console.error("Error processing repositories:",Q)}}import{writeFileSync as E2}from"node:fs";import{resolve as V2}from"node:path";async function _1($,q={},J){let z=new N({configPath:J});try{let Q=await z.getHistory($,q.since,q.until),X={generatedAt:new Date().toISOString(),period:{since:q.since,until:q.until},repositories:Q.map((Y)=>{let _=new Set(Y.commits.flatMap((T)=>T.files.map((U)=>U.path))).size,R=Y.commits.reduce((T,U)=>T+U.insertions,0),H=Y.commits.reduce((T,U)=>T+U.deletions,0);return{path:Y.path,commits:Y.commits,summary:{totalCommits:Y.commits.length,totalFilesChanged:_,totalInsertions:R,totalDeletions:H}}})},Z=JSON.stringify(X,null,2);if(q.out){let Y=V2(process.cwd(),q.out);E2(Y,Z,"utf-8"),console.log(`✅ Report saved to: ${Y}`),console.log(`
32
+ \uD83D\uDCCA Summary:`);for(let _ of X.repositories)console.log(`
33
+ Repository: ${_.path}`),console.log(` Commits: ${_.summary.totalCommits}`),console.log(` Files Changed: ${_.summary.totalFilesChanged}`),console.log(` Lines Added: ${_.summary.totalInsertions.toLocaleString()}`),console.log(` Lines Removed: ${_.summary.totalDeletions.toLocaleString()}`)}else console.log(Z)}catch(Q){throw console.error("Error generating history report:",Q),Q}}var D=new Q1;D.name("gstatx").description("A CLI tool to export statistics from git repositories").version("0.1.1").option("-c, --config <path>","Specify custom config file path").configureHelp({helpWidth:100});D.command("contributors").description("List contributors for specified repositories").option("--no-commits","Hide commit counts in contributor list").argument("[repo-paths...]","Repository paths").action(async($,q,J)=>{let z=J.parent?.opts().config,X=(await V(z))?.config.contributors?.["no-commits"]??!1,Z=!(q.noCommits||X),Y=$.length===0?void 0:$;await H1(Y,Z,z)}).addHelpText("after",`
34
+ Examples:
35
+ gstatx contributors ./my-repo
36
+ gstatx contributors ./repo1 ./repo2
37
+ gstatx contributors --no-commits ./my-repo`);D.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")').option("-o, --out <file>","Output file path (defaults to stdout)").argument("[repo-paths...]","Repository paths").action(async($,q,J)=>{let z=J.parent?.opts().config,Q={since:q.since,until:q.until,out:q.out},X=$.length===0?void 0:$;await _1(X,Q,z)}).addHelpText("after",`
38
+ Examples:
39
+ gstatx hist ./my-repo
40
+ gstatx hist --since "1 month ago" ./my-repo
41
+ gstatx hist --since "2024-01-01" --until "2024-12-31" ./my-repo
42
+ gstatx hist --since "1 month ago" --out report.json ./my-repo`);D.addHelpText("after",`
43
+ Configuration:
44
+ You can create a .gstatxrc.json file to set default options
45
+ and repository paths. CLI arguments override config values.
46
+ Set 'cloneIfNotExists: true' to automatically clone repositories
47
+ that don't exist locally (requires 'url' in repository config).
48
+ `);D.parse();
package/dist/lib.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * gstatx - Library API
3
+ * Export stats of a repo or list of repos
4
+ */
5
+ import { type GstatxConfig, type RepositoryConfig } from "./utils/config";
6
+ import { type Commit, type RepoContributor } from "./utils/git";
7
+ export type * from "./types";
8
+ export interface ClientOptions extends GstatxConfig {
9
+ cloneIfNotExists?: boolean;
10
+ repositories?: RepositoryConfig[];
11
+ configPath?: string;
12
+ }
13
+ export declare class Client {
14
+ private config;
15
+ private loadedConfig;
16
+ constructor(options?: ClientOptions);
17
+ /**
18
+ * Initialize the client by loading config file if needed
19
+ */
20
+ private initialize;
21
+ /**
22
+ * Get repository paths to use
23
+ */
24
+ private getRepoPaths;
25
+ /**
26
+ * List contributors for specified repositories
27
+ * @param repoPaths Optional array of repository paths. If not provided, uses repositories from config.
28
+ * @returns Array of contributors grouped by repository
29
+ */
30
+ listContributors(repoPaths?: string[]): Promise<Array<{
31
+ path: string;
32
+ contributors: RepoContributor[];
33
+ }>>;
34
+ /**
35
+ * Get commit history for specified repositories
36
+ * @param repoPaths Optional array of repository paths. If not provided, uses repositories from config.
37
+ * @param since Optional start date for the history (e.g., "2024-01-01", "1 month ago")
38
+ * @param until Optional end date for the history (e.g., "2024-12-31", "now")
39
+ * @returns Array of commit history grouped by repository
40
+ */
41
+ getHistory(repoPaths?: string[], since?: string, until?: string): Promise<Array<{
42
+ path: string;
43
+ commits: Commit[];
44
+ }>>;
45
+ }
46
+ export { loadConfig } from "./utils/config";
47
+ export { type Commit, getCommits, getContributors, isGitRepo, } from "./utils/git";
48
+ export { ensureRepository } from "./utils/repo";
package/dist/lib.js ADDED
@@ -0,0 +1,4 @@
1
+ import{existsSync as G}from"node:fs";import{readFile as I}from"node:fs/promises";import{dirname as R,join as S,resolve as j}from"node:path";var v=".gstatxrc.json";function D(q){let w=j(q),B=20,J=0;while(J<B){let K=S(w,v);if(G(K))return K;let H=R(w);if(H===w)break;w=H,J++}return null}async function O(q,w=process.cwd()){try{let B;if(q){let Q=j(q);if(!G(Q))return console.error(`Error: Config file not found: ${Q}`),null;B=Q}else if(B=D(w),!B)return null;let J=await I(B,"utf-8"),K=JSON.parse(J),H=R(B);if(K.repositories)K.repositories=K.repositories.map((Q)=>({...Q,path:j(H,Q.path)}));return{config:K,configDir:H}}catch(B){if(q)console.error(`Error: Failed to load config file: ${B}`);return null}}import{exec as F,execSync as x}from"node:child_process";import{access as y}from"node:fs/promises";import{join as f}from"node:path";import{promisify as C}from"node:util";var _=C(F);async function Y(q){try{return await y(f(q,".git")),!0}catch{return!1}}async function E(q){try{let{stdout:w}=await _("git shortlog -sn --all",{cwd:q}),B=[],J=w.trim().split(`
2
+ `);for(let K of J){let H=K.match(/^\s*(\d+)\s+(.+)$/);if(H){let Q=parseInt(H[1]||"0",10),z=H[2]||"",{stdout:U}=await _(`git log --format='%aE' --author="${z.replace(/"/g,"\\\"")}" -1`,{cwd:q}),V=U.trim().split(`
3
+ `)[0]||"";B.push({name:z,email:V,commits:Q})}}return B.sort((K,H)=>H.commits-K.commits)}catch(w){throw new Error(`Failed to get contributors from ${q}: ${w}`)}}function N(q,w,B){let J='git log --format="%H|%an|%ae|%ad|%s" --date=iso-strict --numstat';if(w)J+=` --since="${w}"`;if(B)J+=` --until="${B}"`;let K=x(J,{encoding:"utf-8",cwd:q,maxBuffer:10485760}),H=[],Q=K.split(`
4
+ `).filter((Z)=>Z.trim()),z=null,U=0,V=0,k=0,M=[];for(let Z of Q)if(Z.includes("|")){if(z?.hash&&z?.author&&z?.email&&z?.date&&z?.message)H.push({hash:z.hash,author:z.author,email:z.email,date:z.date,message:z.message,filesChanged:U,insertions:V,deletions:k,files:M});let[T,W,X,$,...b]=Z.split("|");if(T&&W&&X&&$)z={hash:T.trim(),author:W.trim(),email:X.trim(),date:$.trim(),message:b.join("|").trim()},U=0,V=0,k=0,M=[]}else{let T=Z.trim().split(/\s+/);if(T.length>=2&&T[0]&&T[1]){let W=parseInt(T[0],10)||0,X=parseInt(T[1],10)||0,$=T.slice(2).join(" ");if($&&!Number.isNaN(W)&&!Number.isNaN(X))U++,V+=W,k+=X,M.push({path:$,insertions:W,deletions:X})}}if(z?.hash&&z?.author&&z?.email&&z?.date&&z?.message)H.push({hash:z.hash,author:z.author,email:z.email,date:z.date,message:z.message,filesChanged:U,insertions:V,deletions:k,files:M});return H}import{exec as g}from"node:child_process";import{existsSync as L}from"node:fs";import{mkdir as d}from"node:fs/promises";import{dirname as P}from"node:path";import{promisify as l}from"node:util";var u=l(g);async function A(q){if(L(q.path)&&await Y(q.path))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 w=P(q.path),B=q.path.split("/").pop()||"repository";try{await d(w,{recursive:!0})}catch(J){}return await u(`git clone "${q.url}" "${q.path}"`),console.log(`✓ Successfully cloned ${q.name||B}`),q.path}catch(w){return console.error(`Error: Failed to clone repository: ${w}`),null}}class h{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.cloneIfNotExists&&this.config.repositories){let q=[];for(let w of this.config.repositories){let B=await A(w);if(B)q.push(B)}this.config.repositories=this.config.repositories.map((w,B)=>({...w,path:q[B]||w.path}))}}getRepoPaths(q){if(q&&q.length>0)return q;if(this.config.repositories)return this.config.repositories.map((w)=>w.path);return[]}async listContributors(q){await this.initialize();let w=this.getRepoPaths(q);if(w.length===0)throw new Error("No repository paths specified");let B=[];for(let J of w){if(!await Y(J))throw new Error(`${J} is not a git repository`);try{let H=await E(J);B.push({path:J,contributors:H})}catch(H){throw new Error(`Failed to get contributors from ${J}: ${H}`)}}return B}async getHistory(q,w,B){await this.initialize();let J=this.getRepoPaths(q);if(J.length===0)throw new Error("No repository paths specified");let K=[];for(let H of J){if(!await Y(H))throw new Error(`${H} is not a git repository`);try{let z=N(H,w,B);K.push({path:H,commits:z})}catch(z){throw new Error(`Failed to get commit history from ${H}: ${z}`)}}return K}}export{O as loadConfig,Y as isGitRepo,E as getContributors,N as getCommits,A as ensureRepository,h as Client};
@@ -0,0 +1,2 @@
1
+ export type { ContributorsConfig, GstatxConfig, LoadedConfig, RepositoryConfig, } from "./utils/config";
2
+ export type { RepoContributor } from "./utils/git";
@@ -0,0 +1,18 @@
1
+ export interface RepositoryConfig {
2
+ path: string;
3
+ name?: string;
4
+ url?: string;
5
+ }
6
+ export interface ContributorsConfig {
7
+ "no-commits"?: boolean;
8
+ }
9
+ export interface GstatxConfig {
10
+ contributors?: ContributorsConfig;
11
+ repositories?: RepositoryConfig[];
12
+ cloneIfNotExists?: boolean;
13
+ }
14
+ export interface LoadedConfig {
15
+ config: GstatxConfig;
16
+ configDir: string;
17
+ }
18
+ export declare function loadConfig(customPath?: string, startPath?: string): Promise<LoadedConfig | null>;
@@ -0,0 +1,24 @@
1
+ export interface RepoContributor {
2
+ name: string;
3
+ email: string;
4
+ commits: number;
5
+ }
6
+ export declare function isGitRepo(path: string): Promise<boolean>;
7
+ export interface CommitFile {
8
+ path: string;
9
+ insertions: number;
10
+ deletions: number;
11
+ }
12
+ export interface Commit {
13
+ hash: string;
14
+ author: string;
15
+ email: string;
16
+ date: string;
17
+ message: string;
18
+ filesChanged: number;
19
+ insertions: number;
20
+ deletions: number;
21
+ files: CommitFile[];
22
+ }
23
+ export declare function getContributors(repoPath: string): Promise<RepoContributor[]>;
24
+ export declare function getCommits(repoPath: string, since?: string, until?: string): Commit[];
@@ -0,0 +1,2 @@
1
+ import type { RepositoryConfig } from "./config";
2
+ export declare function ensureRepository(repo: RepositoryConfig): Promise<string | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gstatx",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Export stats of a repo or list of repos",
5
5
  "type": "module",
6
6
  "engines": {
@@ -9,12 +9,20 @@
9
9
  "bin": {
10
10
  "gstatx": "dist/index.js"
11
11
  },
12
- "main": "dist/index.js",
12
+ "main": "dist/lib.js",
13
+ "types": "dist/lib.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/lib.d.ts",
17
+ "import": "./dist/lib.js",
18
+ "default": "./dist/lib.js"
19
+ }
20
+ },
13
21
  "files": [
14
22
  "dist"
15
23
  ],
16
24
  "scripts": {
17
- "build": "bun build src/index.ts --outdir dist --target node --minify",
25
+ "build": "bun build src/index.ts --outdir dist --target node --minify && bun build src/lib.ts --outdir dist --target node --minify && tsc -p tsconfig.build.json",
18
26
  "prepack": "bun run build",
19
27
  "start": "bun run src/index.ts",
20
28
  "lint": "biome lint .",
@@ -38,5 +46,8 @@
38
46
  },
39
47
  "peerDependencies": {
40
48
  "typescript": "^5"
49
+ },
50
+ "dependencies": {
51
+ "commander": "^14.0.2"
41
52
  }
42
53
  }