@yukiakai/actions-git 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Yuki Akai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,226 @@
1
+ # @yukiakai/actions-git
2
+
3
+ > Lightweight Git client for GitHub Actions and CI workflows.
4
+
5
+ A small, promise-based wrapper around `git` built for automation workflows such as:
6
+
7
+ - Deploy actions
8
+ - Artifact publishing
9
+ - Docs deployment
10
+ - CI synchronization
11
+ - Temporary repository workflows
12
+
13
+ Designed to be:
14
+ - Minimal
15
+ - Predictable
16
+ - CI-friendly
17
+ - Easy to test
18
+
19
+ ---
20
+
21
+ ## Features
22
+
23
+ - Shallow clone with automatic fallback
24
+ - Branch existence detection
25
+ - Orphan branch support
26
+ - Workspace wipe utilities
27
+ - Simple commit/push workflow
28
+ - Promise-based API
29
+ - TypeScript support
30
+ - Designed for GitHub Actions
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ npm install @yukiakai/actions-git
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Example
43
+
44
+ ```ts
45
+ import { GitClient } from '@yukiakai/actions-git';
46
+
47
+ const git = new GitClient({
48
+ repo: 'owner/repo',
49
+ token: process.env.GITHUB_TOKEN!,
50
+ branch: 'gh-pages',
51
+ cwd: './.deploy',
52
+ });
53
+
54
+ await git.clone();
55
+
56
+ await git.setup();
57
+
58
+ await git.checkout();
59
+
60
+ await git.wipe(['.']);
61
+
62
+ await git.add(['dist']);
63
+
64
+ if (await git.hasChanges()) {
65
+ await git.commit('deploy: update docs');
66
+
67
+ await git.push();
68
+ }
69
+ ```
70
+
71
+ ---
72
+
73
+ ## API
74
+
75
+ ### `new GitClient(options)`
76
+
77
+ Creates a new Git client instance.
78
+
79
+ ```ts
80
+ type GitOptions = {
81
+ repo: string;
82
+ token: string;
83
+ branch: string;
84
+ cwd: string;
85
+ };
86
+ ```
87
+
88
+ ---
89
+
90
+ # Methods
91
+
92
+ ## `clone()`
93
+
94
+ Clone the repository into the target working directory.
95
+
96
+ Attempts shallow clone first:
97
+
98
+ ```bash
99
+ git clone --depth=1 --branch <branch>
100
+ ```
101
+
102
+ Falls back to full clone if shallow clone fails.
103
+
104
+ ---
105
+
106
+ ## `setup()`
107
+
108
+ Configure git identity for CI environments.
109
+
110
+ Sets:
111
+
112
+ ```bash
113
+ user.name = github-actions[bot]
114
+ user.email = github-actions[bot]@users.noreply.github.com
115
+ ```
116
+
117
+ ---
118
+
119
+ ## `checkout()`
120
+
121
+ Checkout the target branch.
122
+
123
+ Behavior:
124
+
125
+ - If the branch exists:
126
+ - `git checkout <branch>`
127
+
128
+ - If the branch does not exist:
129
+ - creates orphan branch
130
+ - wipes working tree
131
+
132
+ ---
133
+
134
+ ## `wipe(patterns)`
135
+
136
+ Remove tracked and untracked files from the working tree.
137
+
138
+ ```ts
139
+ await git.wipe(['.']);
140
+ ```
141
+
142
+ Internally runs:
143
+
144
+ ```bash
145
+ git rm -r -f --ignore-unmatch
146
+ git clean -fdx
147
+ ```
148
+
149
+ Useful for deployment workflows where the workspace must be fully reset.
150
+
151
+ ---
152
+
153
+ ## `pullRebase()`
154
+
155
+ Run:
156
+
157
+ ```bash
158
+ git pull --rebase origin <branch>
159
+ ```
160
+
161
+ ---
162
+
163
+ ## `add(patterns)`
164
+
165
+ Stage files.
166
+
167
+ ```ts
168
+ await git.add(['dist', 'package.json']);
169
+ ```
170
+
171
+ ---
172
+
173
+ ## `commit(message)`
174
+
175
+ Create a commit.
176
+
177
+ ```ts
178
+ await git.commit('deploy: update docs');
179
+ ```
180
+
181
+ ---
182
+
183
+ ## `push()`
184
+
185
+ Push the current branch to origin.
186
+
187
+ ```ts
188
+ await git.push();
189
+ ```
190
+
191
+ ---
192
+
193
+ ## `hasChanges()`
194
+
195
+ Check whether staged changes exist.
196
+
197
+ ```ts
198
+ const changed = await git.hasChanges();
199
+ ```
200
+
201
+ Uses:
202
+
203
+ ```bash
204
+ git diff --cached --quiet
205
+ ```
206
+
207
+ Returns:
208
+ - `true` → changes exist
209
+ - `false` → no changes
210
+
211
+ ---
212
+
213
+ ## Use Cases
214
+
215
+ - GitHub Actions
216
+ - Documentation deployment
217
+ - Artifact deployment
218
+ - Monorepo publishing
219
+ - Static site deployment
220
+ - CI repository sync
221
+
222
+ ---
223
+
224
+ ## License
225
+
226
+ MIT Yuki Akai
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var H=Object.create;var y=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var B=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var M=(o,e)=>{for(var t in e)y(o,t,{get:e[t],enumerable:!0})},A=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of V(e))!q.call(o,r)&&r!==t&&y(o,r,{get:()=>e[r],enumerable:!(i=Q(e,r))||i.enumerable});return o};var p=(o,e,t)=>(t=o!=null?H(B(o)):{},A(e||!o||!o.__esModule?y(t,"default",{value:o,enumerable:!0}):t,o)),X=o=>A(y({},"__esModule",{value:!0}),o);var le={};M(le,{GitClient:()=>G});module.exports=X(le);var x=p(require("os"),1),$=p(require("events"),1),I=p(require("child_process"),1),F=p(require("path"),1);var h=p(require("path"),1);var v=p(require("fs"),1),f=p(require("path"),1),T=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})},{chmod:Y,copyFile:z,lstat:K,mkdir:Z,open:de,readdir:k,rename:J,rm:ee,rmdir:ue,stat:g,symlink:te,unlink:ie}=v.promises,m=process.platform==="win32";var he=v.constants.O_RDONLY;function C(o){return T(this,void 0,void 0,function*(){try{yield g(o)}catch(e){if(e.code==="ENOENT")return!1;throw e}return!0})}function E(o){if(o=re(o),!o)throw new Error('isRooted() parameter "p" cannot be empty');return m?o.startsWith("\\")||/^[A-Z]:/i.test(o):o.startsWith("/")}function S(o,e){return T(this,void 0,void 0,function*(){let t;try{t=yield g(o)}catch(r){r.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${o}': ${r}`)}if(t&&t.isFile()){if(m){let r=f.extname(o).toUpperCase();if(e.some(s=>s.toUpperCase()===r))return o}else if(R(t))return o}let i=o;for(let r of e){o=i+r,t=void 0;try{t=yield g(o)}catch(s){s.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${o}': ${s}`)}if(t&&t.isFile()){if(m){try{let s=f.dirname(o),n=f.basename(o).toUpperCase();for(let a of yield k(s))if(n===a.toUpperCase()){o=f.join(s,a);break}}catch(s){console.log(`Unexpected error attempting to determine the actual case of the file '${o}': ${s}`)}return o}else if(R(t))return o}}return""})}function re(o){return o=o||"",m?(o=o.replace(/\//g,"\\"),o.replace(/\\\\+/g,"\\")):o.replace(/\/\/+/g,"/")}function R(o){return(o.mode&1)>0||(o.mode&8)>0&&process.getgid!==void 0&&o.gid===process.getgid()||(o.mode&64)>0&&process.getuid!==void 0&&o.uid===process.getuid()}var D=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})};function O(o,e){return D(this,void 0,void 0,function*(){if(!o)throw new Error("parameter 'tool' is required");if(e){let i=yield O(o,!1);if(!i)throw m?new Error(`Unable to locate executable file: ${o}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`):new Error(`Unable to locate executable file: ${o}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);return i}let t=yield oe(o);return t&&t.length>0?t[0]:""})}function oe(o){return D(this,void 0,void 0,function*(){if(!o)throw new Error("parameter 'tool' is required");let e=[];if(m&&process.env.PATHEXT)for(let r of process.env.PATHEXT.split(h.delimiter))r&&e.push(r);if(E(o)){let r=yield S(o,e);return r?[r]:[]}if(o.includes(h.sep))return[];let t=[];if(process.env.PATH)for(let r of process.env.PATH.split(h.delimiter))r&&t.push(r);let i=[];for(let r of t){let s=yield S(h.join(r,o),e);s&&i.push(s)}return i})}var W=require("timers"),N=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})},b=process.platform==="win32",_=class extends $.EventEmitter{constructor(e,t,i){if(super(),!e)throw new Error("Parameter 'toolPath' cannot be null or empty.");this.toolPath=e,this.args=t||[],this.options=i||{}}_debug(e){this.options.listeners&&this.options.listeners.debug&&this.options.listeners.debug(e)}_getCommandString(e,t){let i=this._getSpawnFileName(),r=this._getSpawnArgs(e),s=t?"":"[command]";if(b)if(this._isCmdFile()){s+=i;for(let n of r)s+=` ${n}`}else if(e.windowsVerbatimArguments){s+=`"${i}"`;for(let n of r)s+=` ${n}`}else{s+=this._windowsQuoteCmdArg(i);for(let n of r)s+=` ${this._windowsQuoteCmdArg(n)}`}else{s+=i;for(let n of r)s+=` ${n}`}return s}_processLineBuffer(e,t,i){try{let r=t+e.toString(),s=r.indexOf(x.EOL);for(;s>-1;){let n=r.substring(0,s);i(n),r=r.substring(s+x.EOL.length),s=r.indexOf(x.EOL)}return r}catch(r){return this._debug(`error processing line. Failed with error ${r}`),""}}_getSpawnFileName(){return b&&this._isCmdFile()?process.env.COMSPEC||"cmd.exe":this.toolPath}_getSpawnArgs(e){if(b&&this._isCmdFile()){let t=`/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;for(let i of this.args)t+=" ",t+=e.windowsVerbatimArguments?i:this._windowsQuoteCmdArg(i);return t+='"',[t]}return this.args}_endsWith(e,t){return e.endsWith(t)}_isCmdFile(){let e=this.toolPath.toUpperCase();return this._endsWith(e,".CMD")||this._endsWith(e,".BAT")}_windowsQuoteCmdArg(e){if(!this._isCmdFile())return this._uvQuoteCmdArg(e);if(!e)return'""';let t=[" "," ","&","(",")","[","]","{","}","^","=",";","!","'","+",",","`","~","|","<",">",'"'],i=!1;for(let n of e)if(t.some(a=>a===n)){i=!0;break}if(!i)return e;let r='"',s=!0;for(let n=e.length;n>0;n--)r+=e[n-1],s&&e[n-1]==="\\"?r+="\\":e[n-1]==='"'?(s=!0,r+='"'):s=!1;return r+='"',r.split("").reverse().join("")}_uvQuoteCmdArg(e){if(!e)return'""';if(!e.includes(" ")&&!e.includes(" ")&&!e.includes('"'))return e;if(!e.includes('"')&&!e.includes("\\"))return`"${e}"`;let t='"',i=!0;for(let r=e.length;r>0;r--)t+=e[r-1],i&&e[r-1]==="\\"?t+="\\":e[r-1]==='"'?(i=!0,t+="\\"):i=!1;return t+='"',t.split("").reverse().join("")}_cloneExecOptions(e){e=e||{};let t={cwd:e.cwd||process.cwd(),env:e.env||process.env,silent:e.silent||!1,windowsVerbatimArguments:e.windowsVerbatimArguments||!1,failOnStdErr:e.failOnStdErr||!1,ignoreReturnCode:e.ignoreReturnCode||!1,delay:e.delay||1e4};return t.outStream=e.outStream||process.stdout,t.errStream=e.errStream||process.stderr,t}_getSpawnOptions(e,t){e=e||{};let i={};return i.cwd=e.cwd,i.env=e.env,i.windowsVerbatimArguments=e.windowsVerbatimArguments||this._isCmdFile(),e.windowsVerbatimArguments&&(i.argv0=`"${t}"`),i}exec(){return N(this,void 0,void 0,function*(){return!E(this.toolPath)&&(this.toolPath.includes("/")||b&&this.toolPath.includes("\\"))&&(this.toolPath=F.resolve(process.cwd(),this.options.cwd||process.cwd(),this.toolPath)),this.toolPath=yield O(this.toolPath,!0),new Promise((e,t)=>N(this,void 0,void 0,function*(){this._debug(`exec tool: ${this.toolPath}`),this._debug("arguments:");for(let l of this.args)this._debug(` ${l}`);let i=this._cloneExecOptions(this.options);!i.silent&&i.outStream&&i.outStream.write(this._getCommandString(i)+x.EOL);let r=new U(i,this.toolPath);if(r.on("debug",l=>{this._debug(l)}),this.options.cwd&&!(yield C(this.options.cwd)))return t(new Error(`The cwd: ${this.options.cwd} does not exist!`));let s=this._getSpawnFileName(),n=I.spawn(s,this._getSpawnArgs(i),this._getSpawnOptions(this.options,s)),a="";n.stdout&&n.stdout.on("data",l=>{this.options.listeners&&this.options.listeners.stdout&&this.options.listeners.stdout(l),!i.silent&&i.outStream&&i.outStream.write(l),a=this._processLineBuffer(l,a,c=>{this.options.listeners&&this.options.listeners.stdline&&this.options.listeners.stdline(c)})});let u="";if(n.stderr&&n.stderr.on("data",l=>{r.processStderr=!0,this.options.listeners&&this.options.listeners.stderr&&this.options.listeners.stderr(l),!i.silent&&i.errStream&&i.outStream&&(i.failOnStdErr?i.errStream:i.outStream).write(l),u=this._processLineBuffer(l,u,c=>{this.options.listeners&&this.options.listeners.errline&&this.options.listeners.errline(c)})}),n.on("error",l=>{r.processError=l.message,r.processExited=!0,r.processClosed=!0,r.CheckComplete()}),n.on("exit",l=>{r.processExitCode=l,r.processExited=!0,this._debug(`Exit code ${l} received from tool '${this.toolPath}'`),r.CheckComplete()}),n.on("close",l=>{r.processExitCode=l,r.processExited=!0,r.processClosed=!0,this._debug(`STDIO streams have closed for tool '${this.toolPath}'`),r.CheckComplete()}),r.on("done",(l,c)=>{a.length>0&&this.emit("stdline",a),u.length>0&&this.emit("errline",u),n.removeAllListeners(),l?t(l):e(c)}),this.options.input){if(!n.stdin)throw new Error("child process missing stdin");n.stdin.end(this.options.input)}}))})}};function L(o){let e=[],t=!1,i=!1,r="";function s(n){i&&n!=='"'&&(r+="\\"),r+=n,i=!1}for(let n=0;n<o.length;n++){let a=o.charAt(n);if(a==='"'){i?s(a):t=!t;continue}if(a==="\\"&&i){s(a);continue}if(a==="\\"&&t){i=!0;continue}if(a===" "&&!t){r.length>0&&(e.push(r),r="");continue}s(a)}return r.length>0&&e.push(r.trim()),e}var U=class o extends $.EventEmitter{constructor(e,t){if(super(),this.processClosed=!1,this.processError="",this.processExitCode=0,this.processExited=!1,this.processStderr=!1,this.delay=1e4,this.done=!1,this.timeout=null,!t)throw new Error("toolPath must not be empty");this.options=e,this.toolPath=t,e.delay&&(this.delay=e.delay)}CheckComplete(){this.done||(this.processClosed?this._setResult():this.processExited&&(this.timeout=(0,W.setTimeout)(o.HandleTimeout,this.delay,this)))}_debug(e){this.emit("debug",e)}_setResult(){let e;this.processExited&&(this.processError?e=new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`):this.processExitCode!==0&&!this.options.ignoreReturnCode?e=new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`):this.processStderr&&this.options.failOnStdErr&&(e=new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`))),this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.done=!0,this.emit("done",e,this.processExitCode)}static HandleTimeout(e){if(!e.done){if(!e.processClosed&&e.processExited){let t=`The STDIO streams did not close within ${e.delay/1e3} seconds of the exit event from process '${e.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;e._debug(t)}e._setResult()}}};var ce=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})};function j(o,e,t){return ce(this,void 0,void 0,function*(){let i=L(o);if(i.length===0)throw new Error("Parameter 'commandLine' cannot be null or empty.");let r=i[0];return e=i.slice(1).concat(e||[]),new _(r,e,t).exec()})}var G=class{constructor(e){this.options=e}get repoUrl(){let{repo:e,token:t}=this.options;return`https://x-access-token:${t}@github.com/${e}.git`}async execGitRaw(e,t){return{exitCode:await j("git",e,t)}}async execGit(e,t){return await this.execGitRaw(e,{cwd:this.options.cwd,...t})}async execGitInspectable(e,t){return await this.execGit(e,{...t,ignoreReturnCode:!0})}async clone(){let{branch:e,cwd:t}=this.options;(await this.execGitRaw(["clone","--depth=1","--branch",e,this.repoUrl,t],{ignoreReturnCode:!0})).exitCode!==0&&await this.execGitRaw(["clone",this.repoUrl,t])}async wipe(e){await this.execGit(["rm","-r","-f","--ignore-unmatch",...e]),await this.execGit(["clean","-fdx"])}async setup(){await this.execGit(["config","user.name","github-actions[bot]"]),await this.execGit(["config","user.email","github-actions[bot]@users.noreply.github.com"])}async checkout(){let{branch:e}=this.options;await this.branchExists(e)?await this.execGit(["checkout",e]):(await this.execGit(["checkout","--orphan",e]),await this.wipe(["."]))}async pullRebase(){let{branch:e}=this.options;await this.execGit(["pull","--rebase","origin",e])}async commit(e){await this.execGit(["commit","-m",e])}async add(e){await this.execGit(["add",...e])}async push(){let{branch:e}=this.options;await this.execGit(["push","origin",e])}async hasChanges(){let e=await this.execGitInspectable(["diff","--cached","--quiet"]);if(e.exitCode===0)return!1;if(e.exitCode===1)return!0;throw new Error(`git diff failed with exit code ${e.exitCode}`)}async branchExists(e){let t=await this.execGitInspectable(["ls-remote","--exit-code","--heads","origin",e]);if(t.exitCode===0)return!0;if(t.exitCode===2)return!1;throw new Error(`Failed to check remote branch "${e}" (exit code ${t.exitCode})`)}};0&&(module.exports={GitClient});
@@ -0,0 +1,34 @@
1
+ import { ExecOptions } from '@actions/exec';
2
+
3
+ type GitExecOptions = Omit<ExecOptions, 'cwd'>;
4
+ type GitInspectableOptions = Omit<GitExecOptions, 'ignoreReturnCode'>;
5
+ interface GitExecResult {
6
+ exitCode: number;
7
+ }
8
+ interface GitOptions {
9
+ cwd: string;
10
+ repo: string;
11
+ branch: string;
12
+ token: string;
13
+ }
14
+
15
+ declare class GitClient {
16
+ private options;
17
+ constructor(options: GitOptions);
18
+ private get repoUrl();
19
+ protected execGitRaw(args: string[], options?: ExecOptions): Promise<GitExecResult>;
20
+ private execGit;
21
+ private execGitInspectable;
22
+ clone(): Promise<void>;
23
+ wipe(pattern: string[]): Promise<void>;
24
+ setup(): Promise<void>;
25
+ checkout(): Promise<void>;
26
+ pullRebase(): Promise<void>;
27
+ commit(message: string): Promise<void>;
28
+ add(pattern: string[]): Promise<void>;
29
+ push(): Promise<void>;
30
+ hasChanges(): Promise<boolean>;
31
+ private branchExists;
32
+ }
33
+
34
+ export { GitClient, type GitExecOptions, type GitExecResult, type GitInspectableOptions, type GitOptions };
@@ -0,0 +1,34 @@
1
+ import { ExecOptions } from '@actions/exec';
2
+
3
+ type GitExecOptions = Omit<ExecOptions, 'cwd'>;
4
+ type GitInspectableOptions = Omit<GitExecOptions, 'ignoreReturnCode'>;
5
+ interface GitExecResult {
6
+ exitCode: number;
7
+ }
8
+ interface GitOptions {
9
+ cwd: string;
10
+ repo: string;
11
+ branch: string;
12
+ token: string;
13
+ }
14
+
15
+ declare class GitClient {
16
+ private options;
17
+ constructor(options: GitOptions);
18
+ private get repoUrl();
19
+ protected execGitRaw(args: string[], options?: ExecOptions): Promise<GitExecResult>;
20
+ private execGit;
21
+ private execGitInspectable;
22
+ clone(): Promise<void>;
23
+ wipe(pattern: string[]): Promise<void>;
24
+ setup(): Promise<void>;
25
+ checkout(): Promise<void>;
26
+ pullRebase(): Promise<void>;
27
+ commit(message: string): Promise<void>;
28
+ add(pattern: string[]): Promise<void>;
29
+ push(): Promise<void>;
30
+ hasChanges(): Promise<boolean>;
31
+ private branchExists;
32
+ }
33
+
34
+ export { GitClient, type GitExecOptions, type GitExecResult, type GitInspectableOptions, type GitOptions };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import*as x from"os";import*as U from"events";import*as P from"child_process";import*as D from"path";import*as h from"path";import*as g from"fs";import*as f from"path";var G=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})},{chmod:W,copyFile:L,lstat:j,mkdir:H,open:J,readdir:A,rename:Q,rm:V,rmdir:ee,stat:y,symlink:B,unlink:q}=g.promises,p=process.platform==="win32";var te=g.constants.O_RDONLY;function _(o){return G(this,void 0,void 0,function*(){try{yield y(o)}catch(e){if(e.code==="ENOENT")return!1;throw e}return!0})}function v(o){if(o=M(o),!o)throw new Error('isRooted() parameter "p" cannot be empty');return p?o.startsWith("\\")||/^[A-Z]:/i.test(o):o.startsWith("/")}function C(o,e){return G(this,void 0,void 0,function*(){let t;try{t=yield y(o)}catch(r){r.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${o}': ${r}`)}if(t&&t.isFile()){if(p){let r=f.extname(o).toUpperCase();if(e.some(s=>s.toUpperCase()===r))return o}else if($(t))return o}let i=o;for(let r of e){o=i+r,t=void 0;try{t=yield y(o)}catch(s){s.code!=="ENOENT"&&console.log(`Unexpected error attempting to determine if executable file exists '${o}': ${s}`)}if(t&&t.isFile()){if(p){try{let s=f.dirname(o),n=f.basename(o).toUpperCase();for(let a of yield A(s))if(n===a.toUpperCase()){o=f.join(s,a);break}}catch(s){console.log(`Unexpected error attempting to determine the actual case of the file '${o}': ${s}`)}return o}else if($(t))return o}}return""})}function M(o){return o=o||"",p?(o=o.replace(/\//g,"\\"),o.replace(/\\\\+/g,"\\")):o.replace(/\/\/+/g,"/")}function $(o){return(o.mode&1)>0||(o.mode&8)>0&&process.getgid!==void 0&&o.gid===process.getgid()||(o.mode&64)>0&&process.getuid!==void 0&&o.uid===process.getuid()}var T=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})};function S(o,e){return T(this,void 0,void 0,function*(){if(!o)throw new Error("parameter 'tool' is required");if(e){let i=yield S(o,!1);if(!i)throw p?new Error(`Unable to locate executable file: ${o}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`):new Error(`Unable to locate executable file: ${o}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);return i}let t=yield X(o);return t&&t.length>0?t[0]:""})}function X(o){return T(this,void 0,void 0,function*(){if(!o)throw new Error("parameter 'tool' is required");let e=[];if(p&&process.env.PATHEXT)for(let r of process.env.PATHEXT.split(h.delimiter))r&&e.push(r);if(v(o)){let r=yield C(o,e);return r?[r]:[]}if(o.includes(h.sep))return[];let t=[];if(process.env.PATH)for(let r of process.env.PATH.split(h.delimiter))r&&t.push(r);let i=[];for(let r of t){let s=yield C(h.join(r,o),e);s&&i.push(s)}return i})}import{setTimeout as z}from"timers";var k=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})},E=process.platform==="win32",b=class extends U.EventEmitter{constructor(e,t,i){if(super(),!e)throw new Error("Parameter 'toolPath' cannot be null or empty.");this.toolPath=e,this.args=t||[],this.options=i||{}}_debug(e){this.options.listeners&&this.options.listeners.debug&&this.options.listeners.debug(e)}_getCommandString(e,t){let i=this._getSpawnFileName(),r=this._getSpawnArgs(e),s=t?"":"[command]";if(E)if(this._isCmdFile()){s+=i;for(let n of r)s+=` ${n}`}else if(e.windowsVerbatimArguments){s+=`"${i}"`;for(let n of r)s+=` ${n}`}else{s+=this._windowsQuoteCmdArg(i);for(let n of r)s+=` ${this._windowsQuoteCmdArg(n)}`}else{s+=i;for(let n of r)s+=` ${n}`}return s}_processLineBuffer(e,t,i){try{let r=t+e.toString(),s=r.indexOf(x.EOL);for(;s>-1;){let n=r.substring(0,s);i(n),r=r.substring(s+x.EOL.length),s=r.indexOf(x.EOL)}return r}catch(r){return this._debug(`error processing line. Failed with error ${r}`),""}}_getSpawnFileName(){return E&&this._isCmdFile()?process.env.COMSPEC||"cmd.exe":this.toolPath}_getSpawnArgs(e){if(E&&this._isCmdFile()){let t=`/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`;for(let i of this.args)t+=" ",t+=e.windowsVerbatimArguments?i:this._windowsQuoteCmdArg(i);return t+='"',[t]}return this.args}_endsWith(e,t){return e.endsWith(t)}_isCmdFile(){let e=this.toolPath.toUpperCase();return this._endsWith(e,".CMD")||this._endsWith(e,".BAT")}_windowsQuoteCmdArg(e){if(!this._isCmdFile())return this._uvQuoteCmdArg(e);if(!e)return'""';let t=[" "," ","&","(",")","[","]","{","}","^","=",";","!","'","+",",","`","~","|","<",">",'"'],i=!1;for(let n of e)if(t.some(a=>a===n)){i=!0;break}if(!i)return e;let r='"',s=!0;for(let n=e.length;n>0;n--)r+=e[n-1],s&&e[n-1]==="\\"?r+="\\":e[n-1]==='"'?(s=!0,r+='"'):s=!1;return r+='"',r.split("").reverse().join("")}_uvQuoteCmdArg(e){if(!e)return'""';if(!e.includes(" ")&&!e.includes(" ")&&!e.includes('"'))return e;if(!e.includes('"')&&!e.includes("\\"))return`"${e}"`;let t='"',i=!0;for(let r=e.length;r>0;r--)t+=e[r-1],i&&e[r-1]==="\\"?t+="\\":e[r-1]==='"'?(i=!0,t+="\\"):i=!1;return t+='"',t.split("").reverse().join("")}_cloneExecOptions(e){e=e||{};let t={cwd:e.cwd||process.cwd(),env:e.env||process.env,silent:e.silent||!1,windowsVerbatimArguments:e.windowsVerbatimArguments||!1,failOnStdErr:e.failOnStdErr||!1,ignoreReturnCode:e.ignoreReturnCode||!1,delay:e.delay||1e4};return t.outStream=e.outStream||process.stdout,t.errStream=e.errStream||process.stderr,t}_getSpawnOptions(e,t){e=e||{};let i={};return i.cwd=e.cwd,i.env=e.env,i.windowsVerbatimArguments=e.windowsVerbatimArguments||this._isCmdFile(),e.windowsVerbatimArguments&&(i.argv0=`"${t}"`),i}exec(){return k(this,void 0,void 0,function*(){return!v(this.toolPath)&&(this.toolPath.includes("/")||E&&this.toolPath.includes("\\"))&&(this.toolPath=D.resolve(process.cwd(),this.options.cwd||process.cwd(),this.toolPath)),this.toolPath=yield S(this.toolPath,!0),new Promise((e,t)=>k(this,void 0,void 0,function*(){this._debug(`exec tool: ${this.toolPath}`),this._debug("arguments:");for(let l of this.args)this._debug(` ${l}`);let i=this._cloneExecOptions(this.options);!i.silent&&i.outStream&&i.outStream.write(this._getCommandString(i)+x.EOL);let r=new O(i,this.toolPath);if(r.on("debug",l=>{this._debug(l)}),this.options.cwd&&!(yield _(this.options.cwd)))return t(new Error(`The cwd: ${this.options.cwd} does not exist!`));let s=this._getSpawnFileName(),n=P.spawn(s,this._getSpawnArgs(i),this._getSpawnOptions(this.options,s)),a="";n.stdout&&n.stdout.on("data",l=>{this.options.listeners&&this.options.listeners.stdout&&this.options.listeners.stdout(l),!i.silent&&i.outStream&&i.outStream.write(l),a=this._processLineBuffer(l,a,c=>{this.options.listeners&&this.options.listeners.stdline&&this.options.listeners.stdline(c)})});let u="";if(n.stderr&&n.stderr.on("data",l=>{r.processStderr=!0,this.options.listeners&&this.options.listeners.stderr&&this.options.listeners.stderr(l),!i.silent&&i.errStream&&i.outStream&&(i.failOnStdErr?i.errStream:i.outStream).write(l),u=this._processLineBuffer(l,u,c=>{this.options.listeners&&this.options.listeners.errline&&this.options.listeners.errline(c)})}),n.on("error",l=>{r.processError=l.message,r.processExited=!0,r.processClosed=!0,r.CheckComplete()}),n.on("exit",l=>{r.processExitCode=l,r.processExited=!0,this._debug(`Exit code ${l} received from tool '${this.toolPath}'`),r.CheckComplete()}),n.on("close",l=>{r.processExitCode=l,r.processExited=!0,r.processClosed=!0,this._debug(`STDIO streams have closed for tool '${this.toolPath}'`),r.CheckComplete()}),r.on("done",(l,c)=>{a.length>0&&this.emit("stdline",a),u.length>0&&this.emit("errline",u),n.removeAllListeners(),l?t(l):e(c)}),this.options.input){if(!n.stdin)throw new Error("child process missing stdin");n.stdin.end(this.options.input)}}))})}};function N(o){let e=[],t=!1,i=!1,r="";function s(n){i&&n!=='"'&&(r+="\\"),r+=n,i=!1}for(let n=0;n<o.length;n++){let a=o.charAt(n);if(a==='"'){i?s(a):t=!t;continue}if(a==="\\"&&i){s(a);continue}if(a==="\\"&&t){i=!0;continue}if(a===" "&&!t){r.length>0&&(e.push(r),r="");continue}s(a)}return r.length>0&&e.push(r.trim()),e}var O=class o extends U.EventEmitter{constructor(e,t){if(super(),this.processClosed=!1,this.processError="",this.processExitCode=0,this.processExited=!1,this.processStderr=!1,this.delay=1e4,this.done=!1,this.timeout=null,!t)throw new Error("toolPath must not be empty");this.options=e,this.toolPath=t,e.delay&&(this.delay=e.delay)}CheckComplete(){this.done||(this.processClosed?this._setResult():this.processExited&&(this.timeout=z(o.HandleTimeout,this.delay,this)))}_debug(e){this.emit("debug",e)}_setResult(){let e;this.processExited&&(this.processError?e=new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`):this.processExitCode!==0&&!this.options.ignoreReturnCode?e=new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`):this.processStderr&&this.options.failOnStdErr&&(e=new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`))),this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.done=!0,this.emit("done",e,this.processExitCode)}static HandleTimeout(e){if(!e.done){if(!e.processClosed&&e.processExited){let t=`The STDIO streams did not close within ${e.delay/1e3} seconds of the exit event from process '${e.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;e._debug(t)}e._setResult()}}};var Z=function(o,e,t,i){function r(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function a(c){try{l(i.next(c))}catch(d){n(d)}}function u(c){try{l(i.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):r(c.value).then(a,u)}l((i=i.apply(o,e||[])).next())})};function I(o,e,t){return Z(this,void 0,void 0,function*(){let i=N(o);if(i.length===0)throw new Error("Parameter 'commandLine' cannot be null or empty.");let r=i[0];return e=i.slice(1).concat(e||[]),new b(r,e,t).exec()})}var F=class{constructor(e){this.options=e}get repoUrl(){let{repo:e,token:t}=this.options;return`https://x-access-token:${t}@github.com/${e}.git`}async execGitRaw(e,t){return{exitCode:await I("git",e,t)}}async execGit(e,t){return await this.execGitRaw(e,{cwd:this.options.cwd,...t})}async execGitInspectable(e,t){return await this.execGit(e,{...t,ignoreReturnCode:!0})}async clone(){let{branch:e,cwd:t}=this.options;(await this.execGitRaw(["clone","--depth=1","--branch",e,this.repoUrl,t],{ignoreReturnCode:!0})).exitCode!==0&&await this.execGitRaw(["clone",this.repoUrl,t])}async wipe(e){await this.execGit(["rm","-r","-f","--ignore-unmatch",...e]),await this.execGit(["clean","-fdx"])}async setup(){await this.execGit(["config","user.name","github-actions[bot]"]),await this.execGit(["config","user.email","github-actions[bot]@users.noreply.github.com"])}async checkout(){let{branch:e}=this.options;await this.branchExists(e)?await this.execGit(["checkout",e]):(await this.execGit(["checkout","--orphan",e]),await this.wipe(["."]))}async pullRebase(){let{branch:e}=this.options;await this.execGit(["pull","--rebase","origin",e])}async commit(e){await this.execGit(["commit","-m",e])}async add(e){await this.execGit(["add",...e])}async push(){let{branch:e}=this.options;await this.execGit(["push","origin",e])}async hasChanges(){let e=await this.execGitInspectable(["diff","--cached","--quiet"]);if(e.exitCode===0)return!1;if(e.exitCode===1)return!0;throw new Error(`git diff failed with exit code ${e.exitCode}`)}async branchExists(e){let t=await this.execGitInspectable(["ls-remote","--exit-code","--heads","origin",e]);if(t.exitCode===0)return!0;if(t.exitCode===2)return!1;throw new Error(`Failed to check remote branch "${e}" (exit code ${t.exitCode})`)}};export{F as GitClient};
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@yukiakai/actions-git",
3
+ "version": "1.0.0",
4
+ "description": "Lightweight Git client for GitHub Actions and CI workflows.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js",
11
+ "require": "./dist/index.cjs"
12
+ },
13
+ "scripts": {
14
+ "test": "npm run build && npx vitest run --reporter verbose --coverage",
15
+ "format": "prettier --write **/*.{js,ts}",
16
+ "format:check": "prettier --check **/*.{js,ts}",
17
+ "lint": "eslint src/**/*.ts",
18
+ "build": "npx tsup",
19
+ "docs": "npx typedoc",
20
+ "prepare": "is-ci || husky"
21
+ },
22
+ "files": [
23
+ "dist/*",
24
+ "CHANGELOG.md"
25
+ ],
26
+ "keywords": [
27
+ "actions",
28
+ "git",
29
+ "CI",
30
+ "typescript"
31
+ ],
32
+ "author": "Yuki_akai",
33
+ "homepage": "https://github.com/yukiakai212/actions-git.js",
34
+ "funding": "https://github.com/sponsors/yukiakai212",
35
+ "engines": {
36
+ "node": ">= 16"
37
+ },
38
+ "maintainers": [
39
+ {
40
+ "name": "Yuki_akai",
41
+ "homepage": "https://github.com/yukiakai212"
42
+ }
43
+ ],
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "git+https://github.com/yukiakai212/actions-git.js.git"
47
+ },
48
+ "bugs": {
49
+ "url": "https://github.com/yukiakai212/actions-git.js/issues"
50
+ },
51
+ "license": "MIT",
52
+ "devDependencies": {
53
+ "@changesets/cli": "^2.29.8",
54
+ "@eslint/js": "^9.30.1",
55
+ "@types/node": "^24.0.10",
56
+ "@vitest/coverage-v8": "^4.0.15",
57
+ "dotenv": "^17.0.1",
58
+ "eslint": "^9.30.0",
59
+ "husky": "^9.1.7",
60
+ "is-ci": "^4.1.0",
61
+ "prettier": "^3.6.2",
62
+ "tsup": "^8.5.1",
63
+ "tsx": "^4.20.3",
64
+ "typedoc": "^0.28.9",
65
+ "typescript": "^5.8.3",
66
+ "typescript-eslint": "^8.35.1",
67
+ "vitest": "^4.0.15"
68
+ },
69
+ "dependencies": {
70
+ "@actions/exec": "^3.0.0"
71
+ }
72
+ }