type-git 0.4.0 → 0.6.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.
@@ -0,0 +1,392 @@
1
+ import {
2
+ GitClient,
3
+ createGit,
4
+ createGitSync,
5
+ createTailPolling,
6
+ joinBytes,
7
+ runTailPolling
8
+ } from "./chunk-IYOGHATP.js";
9
+
10
+ // src/adapters/node/exec.ts
11
+ import { spawn } from "child_process";
12
+ function resolveChildEnv(env, inheritEnv) {
13
+ if (inheritEnv === false) {
14
+ return env ?? {};
15
+ }
16
+ return env ? { ...process.env, ...env } : process.env;
17
+ }
18
+ async function* streamToAsyncIterable(stream) {
19
+ let buffer = "";
20
+ for await (const chunk of stream) {
21
+ buffer += chunk;
22
+ const lines = buffer.split("\n");
23
+ buffer = lines.pop() ?? "";
24
+ for (const line of lines) {
25
+ yield line;
26
+ }
27
+ }
28
+ if (buffer) {
29
+ yield buffer;
30
+ }
31
+ }
32
+ var NodeExecAdapter = class {
33
+ windowsHide;
34
+ /**
35
+ * @param options - Vetted spawn options; see {@link NodeExecAdapterOptions}.
36
+ * @throws TypeError if `windowsHide` is present but not a boolean.
37
+ */
38
+ constructor(options) {
39
+ const windowsHide = options?.windowsHide;
40
+ if (windowsHide !== void 0 && typeof windowsHide !== "boolean") {
41
+ throw new TypeError("windowsHide must be a boolean");
42
+ }
43
+ this.windowsHide = windowsHide;
44
+ }
45
+ getCapabilities() {
46
+ return {
47
+ canSpawnProcess: true,
48
+ canReadEnv: true,
49
+ canWriteTemp: true,
50
+ supportsAbortSignal: true,
51
+ supportsKillSignal: true,
52
+ runtime: "node"
53
+ };
54
+ }
55
+ async spawn(options, handlers) {
56
+ return await this.spawnResult(options, handlers, false);
57
+ }
58
+ async spawnBytes(options, handlers) {
59
+ return await this.spawnResult(options, handlers, true);
60
+ }
61
+ /**
62
+ * Run a process to completion and collect its output as text, or as bytes when `binary` is
63
+ * true. Applies the configured `windowsHide` option.
64
+ */
65
+ async spawnResult(options, handlers, binary) {
66
+ const { argv, env, inheritEnv, cwd, signal } = options;
67
+ const command = argv[0];
68
+ if (command === void 0) {
69
+ throw new Error("argv must not be empty");
70
+ }
71
+ const args = argv.slice(1);
72
+ if (signal?.aborted) {
73
+ return Promise.resolve({
74
+ stdout: binary ? new Uint8Array(0) : "",
75
+ stderr: "",
76
+ exitCode: -1,
77
+ aborted: true
78
+ });
79
+ }
80
+ return new Promise((resolve, reject) => {
81
+ const child = spawn(command, args, {
82
+ cwd,
83
+ env: resolveChildEnv(env, inheritEnv),
84
+ stdio: [options.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"],
85
+ ...this.windowsHide === void 0 ? {} : { windowsHide: this.windowsHide }
86
+ });
87
+ if (!binary) {
88
+ child.stdout?.setEncoding("utf8");
89
+ }
90
+ child.stderr?.setEncoding("utf8");
91
+ let stdout = "";
92
+ const stdoutChunks = [];
93
+ let stderr = "";
94
+ let aborted = false;
95
+ let exitSignal;
96
+ const abortHandler = () => {
97
+ aborted = true;
98
+ child.kill("SIGTERM");
99
+ };
100
+ if (signal) {
101
+ if (signal.aborted) {
102
+ child.kill("SIGTERM");
103
+ aborted = true;
104
+ } else {
105
+ signal.addEventListener("abort", abortHandler, { once: true });
106
+ }
107
+ }
108
+ child.stdout?.on("data", (chunk) => {
109
+ if (typeof chunk === "string") {
110
+ stdout += chunk;
111
+ handlers?.onStdout?.(chunk);
112
+ } else {
113
+ stdoutChunks.push(chunk);
114
+ }
115
+ });
116
+ child.stderr?.on("data", (chunk) => {
117
+ const text = chunk;
118
+ stderr += text;
119
+ handlers?.onStderr?.(text);
120
+ });
121
+ child.stdin?.on("error", (error) => {
122
+ if (error.code !== "EPIPE" && error.code !== "EOF") {
123
+ reject(error);
124
+ }
125
+ });
126
+ child.stdin?.end(options.stdin);
127
+ child.on("error", (error) => {
128
+ signal?.removeEventListener("abort", abortHandler);
129
+ reject(error);
130
+ });
131
+ child.on("close", (code, sig) => {
132
+ signal?.removeEventListener("abort", abortHandler);
133
+ if (sig) {
134
+ exitSignal = sig;
135
+ }
136
+ resolve({
137
+ stdout: binary ? joinBytes(stdoutChunks) : stdout,
138
+ stderr,
139
+ exitCode: code ?? -1,
140
+ signal: exitSignal,
141
+ aborted
142
+ });
143
+ });
144
+ });
145
+ }
146
+ /**
147
+ * Start a process and return a handle that streams its stdout lines. Applies the configured
148
+ * `windowsHide` option.
149
+ */
150
+ spawnStreaming(options) {
151
+ const { argv, env, inheritEnv, cwd, signal } = options;
152
+ const command = argv[0];
153
+ if (command === void 0) {
154
+ throw new Error("argv must not be empty");
155
+ }
156
+ const args = argv.slice(1);
157
+ const child = spawn(command, args, {
158
+ cwd,
159
+ env: resolveChildEnv(env, inheritEnv),
160
+ stdio: [options.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"],
161
+ ...this.windowsHide === void 0 ? {} : { windowsHide: this.windowsHide }
162
+ });
163
+ let aborted = false;
164
+ let exitSignal;
165
+ const abortHandler = () => {
166
+ aborted = true;
167
+ child.kill("SIGTERM");
168
+ };
169
+ if (signal) {
170
+ if (signal.aborted) {
171
+ child.kill("SIGTERM");
172
+ aborted = true;
173
+ } else {
174
+ signal.addEventListener("abort", abortHandler, { once: true });
175
+ }
176
+ }
177
+ const waitPromise = new Promise((resolve, reject) => {
178
+ child.stdout?.setEncoding("utf8");
179
+ child.stderr?.setEncoding("utf8");
180
+ let stdout = "";
181
+ let stderr = "";
182
+ child.stdout?.on("data", (chunk) => {
183
+ stdout += chunk;
184
+ });
185
+ child.stderr?.on("data", (chunk) => {
186
+ stderr += chunk;
187
+ });
188
+ child.stdin?.on("error", (error) => {
189
+ if (error.code !== "EPIPE" && error.code !== "EOF") {
190
+ reject(error);
191
+ }
192
+ });
193
+ child.stdin?.end(options.stdin);
194
+ child.on("error", (error) => {
195
+ signal?.removeEventListener("abort", abortHandler);
196
+ reject(error);
197
+ });
198
+ child.on("close", (code, sig) => {
199
+ signal?.removeEventListener("abort", abortHandler);
200
+ if (sig) {
201
+ exitSignal = sig;
202
+ }
203
+ resolve({
204
+ stdout,
205
+ stderr,
206
+ exitCode: code ?? -1,
207
+ signal: exitSignal,
208
+ aborted
209
+ });
210
+ });
211
+ });
212
+ const stdoutStream = child.stdout;
213
+ const stderrStream = child.stderr;
214
+ if (!(stdoutStream && stderrStream)) {
215
+ throw new Error("Failed to create stdio streams");
216
+ }
217
+ return {
218
+ stdout: streamToAsyncIterable(stdoutStream),
219
+ stderr: streamToAsyncIterable(stderrStream),
220
+ wait: () => waitPromise,
221
+ kill: (sig) => {
222
+ child.kill(sig ?? "SIGTERM");
223
+ },
224
+ [Symbol.asyncDispose]: async () => {
225
+ if (child.exitCode === null) {
226
+ child.kill("SIGTERM");
227
+ }
228
+ await waitPromise.catch(() => {
229
+ });
230
+ }
231
+ };
232
+ }
233
+ };
234
+
235
+ // src/adapters/node/fs.ts
236
+ import { access, mkdtemp, open, readFile, rm, writeFile } from "fs/promises";
237
+ import { tmpdir } from "os";
238
+ import { join } from "path";
239
+ var NodeFsAdapter = class {
240
+ /** Private directories created by createTempFile, keyed by the returned file path. */
241
+ tempFileDirs = /* @__PURE__ */ new Map();
242
+ async createTempFile(prefix = "type-git-") {
243
+ const dir = await mkdtemp(join(tmpdir(), prefix));
244
+ const filePath = join(dir, "temp");
245
+ this.tempFileDirs.set(filePath, dir);
246
+ return filePath;
247
+ }
248
+ async createTempDirectory(prefix = "type-git-") {
249
+ return await mkdtemp(join(tmpdir(), prefix));
250
+ }
251
+ async tail(options) {
252
+ const { filePath, signal, onLine, pollInterval = 100 } = options;
253
+ const state = { file: null };
254
+ const decoder = new TextDecoder();
255
+ const adapter = {
256
+ readChunk: async (position) => {
257
+ try {
258
+ if (!state.file) {
259
+ state.file = await open(filePath, "r");
260
+ }
261
+ const { bytesRead, buffer: chunk } = await state.file.read({
262
+ buffer: Buffer.alloc(4096),
263
+ position
264
+ });
265
+ return {
266
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
267
+ newPosition: position + bytesRead
268
+ };
269
+ } catch {
270
+ return null;
271
+ }
272
+ },
273
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
274
+ };
275
+ try {
276
+ await runTailPolling({ adapter, signal, pollInterval, onLine });
277
+ } finally {
278
+ if (state.file) {
279
+ await state.file.close();
280
+ }
281
+ }
282
+ }
283
+ async deleteFile(filePath) {
284
+ const tempDir = this.tempFileDirs.get(filePath);
285
+ if (tempDir !== void 0) {
286
+ await rm(tempDir, { force: true, recursive: true });
287
+ this.tempFileDirs.delete(filePath);
288
+ return;
289
+ }
290
+ await rm(filePath, { force: true });
291
+ }
292
+ async deleteDirectory(dirPath) {
293
+ await rm(dirPath, { force: true, recursive: true });
294
+ }
295
+ async exists(filePath) {
296
+ try {
297
+ await access(filePath);
298
+ return true;
299
+ } catch {
300
+ return false;
301
+ }
302
+ }
303
+ async readFile(filePath) {
304
+ return await readFile(filePath, "utf8");
305
+ }
306
+ async writeFile(filePath, contents) {
307
+ await writeFile(filePath, contents, "utf8");
308
+ }
309
+ tailStreaming(filePath, options) {
310
+ const { signal, pollInterval = 100 } = options ?? {};
311
+ const state = { file: null };
312
+ const decoder = new TextDecoder();
313
+ const adapter = {
314
+ readChunk: async (position) => {
315
+ try {
316
+ if (!state.file) {
317
+ state.file = await open(filePath, "r");
318
+ }
319
+ const { bytesRead, buffer: chunk } = await state.file.read({
320
+ buffer: Buffer.alloc(4096),
321
+ position
322
+ });
323
+ return {
324
+ data: decoder.decode(chunk.subarray(0, bytesRead), { stream: true }),
325
+ newPosition: position + bytesRead
326
+ };
327
+ } catch {
328
+ return null;
329
+ }
330
+ },
331
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
332
+ };
333
+ const polling = createTailPolling({ adapter, signal, pollInterval });
334
+ const closeFileHandle = async () => {
335
+ if (state.file) {
336
+ await state.file.close().catch(() => {
337
+ });
338
+ state.file = null;
339
+ }
340
+ };
341
+ const originalStop = polling.stop;
342
+ const enhancedStop = () => {
343
+ originalStop();
344
+ void closeFileHandle();
345
+ };
346
+ return {
347
+ lines: polling.lines,
348
+ stop: enhancedStop,
349
+ [Symbol.asyncDispose]: async () => {
350
+ await polling[Symbol.asyncDispose]();
351
+ await closeFileHandle();
352
+ }
353
+ };
354
+ }
355
+ };
356
+
357
+ // src/adapters/node/index.ts
358
+ function createNodeAdapters(options) {
359
+ return {
360
+ exec: new NodeExecAdapter(options),
361
+ fs: new NodeFsAdapter()
362
+ };
363
+ }
364
+ function splitOptions(options) {
365
+ const { windowsHide, ...gitOptions } = options ?? {};
366
+ return {
367
+ ...gitOptions,
368
+ adapters: createNodeAdapters(windowsHide === void 0 ? void 0 : { windowsHide })
369
+ };
370
+ }
371
+ var TypeGit = class _TypeGit extends GitClient {
372
+ /**
373
+ * Create a client after checking the installed Git version. Node adapter options such as
374
+ * `windowsHide` are passed to the execution adapter.
375
+ */
376
+ static async create(options) {
377
+ return new _TypeGit(await createGit(splitOptions(options)));
378
+ }
379
+ /** Wrap an existing Git instance, or create one from options without the version check. */
380
+ constructor(optionsOrGit) {
381
+ super(
382
+ optionsOrGit && "open" in optionsOrGit ? optionsOrGit : createGitSync(splitOptions(optionsOrGit))
383
+ );
384
+ }
385
+ };
386
+
387
+ export {
388
+ NodeExecAdapter,
389
+ NodeFsAdapter,
390
+ createNodeAdapters,
391
+ TypeGit
392
+ };