type-git 0.6.0 → 0.7.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,566 @@
1
+ import { C as Capabilities, a as CompanionExecutable, E as EnvInheritance, A as AuditConfig, b as ExecutionContext, c as ExecOpts, R as RawResult, d as GitError, G as Git, e as GitOpenOptions, W as WorktreeRepo, B as BareRepo, f as CloneOpts, I as InitOpts, L as LsRemoteOpts, g as LsRemoteResult, h as CommandExecOpts, i as GlobalConfigOperations, j as GlobalLfsOperations } from './git.d-DrhCzWEn.cjs';
2
+
3
+ /**
4
+ * Runtime adapter interfaces for cross-platform support (Node/Deno/Bun)
5
+ *
6
+ * This module defines:
7
+ * - ExecAdapter: Process execution abstraction (#15)
8
+ * - FsAdapter: Filesystem operations abstraction (#16)
9
+ * - Related types and options
10
+ */
11
+
12
+ /**
13
+ * Options for spawning a process
14
+ */
15
+ type SpawnOptions = {
16
+ /** Command and arguments (first element is the command) */
17
+ argv: string[];
18
+ /** UTF-8 text or raw bytes to write to standard input, then close it. */
19
+ stdin?: string | Uint8Array;
20
+ /** Additional environment variables */
21
+ env?: Record<string, string>;
22
+ /**
23
+ * Whether to merge the parent process environment underneath `env`.
24
+ *
25
+ * - `true` (default when omitted): the parent environment is merged underneath `env`,
26
+ * so the child inherits the full parent environment with `env` overrides on top.
27
+ * - `false`: the child receives only the variables in `env` (and nothing from the
28
+ * parent process). This prevents implicit environment variable traversal — used by
29
+ * {@link CliRunner}, which resolves the inherited variables itself.
30
+ */
31
+ inheritEnv?: boolean;
32
+ /** Working directory */
33
+ cwd?: string;
34
+ /** AbortSignal for cancellation */
35
+ signal?: AbortSignal;
36
+ /** Kill signal to use when aborting (default: SIGTERM) */
37
+ killSignal?: 'SIGTERM' | 'SIGKILL';
38
+ };
39
+ /**
40
+ * Result from spawning a process
41
+ */
42
+ type SpawnResult<Output = string> = {
43
+ /** Standard output */
44
+ stdout: Output;
45
+ /** Standard error */
46
+ stderr: string;
47
+ /** Exit code (-1 if unknown) */
48
+ exitCode: number;
49
+ /** Signal that terminated the process (if any) */
50
+ signal?: string;
51
+ /** Whether the process was aborted via AbortSignal */
52
+ aborted: boolean;
53
+ };
54
+ /**
55
+ * Stream handler for incremental output
56
+ *
57
+ * Used for progress tracking and real-time output processing.
58
+ */
59
+ type StreamHandler = {
60
+ /** Called when stdout data is received */
61
+ onStdout?: (chunk: string) => void;
62
+ /** Called when stderr data is received */
63
+ onStderr?: (chunk: string) => void;
64
+ };
65
+ /**
66
+ * Handle to a spawned process
67
+ *
68
+ * Allows streaming output and waiting for completion.
69
+ * Implements AsyncDisposable for use with `await using`.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * // Traditional usage
74
+ * const handle = adapter.spawnStreaming({ argv: ['git', 'fetch'] });
75
+ * try {
76
+ * for await (const line of handle.stdout) { console.log(line); }
77
+ * } finally {
78
+ * handle.kill();
79
+ * }
80
+ *
81
+ * // With await using (recommended)
82
+ * await using handle = adapter.spawnStreaming({ argv: ['git', 'fetch'] });
83
+ * for await (const line of handle.stdout) { console.log(line); }
84
+ * // Automatically disposed when scope exits
85
+ * ```
86
+ */
87
+ interface SpawnHandle extends AsyncDisposable {
88
+ /** Async iterator for stdout lines */
89
+ readonly stdout: AsyncIterable<string>;
90
+ /** Async iterator for stderr lines */
91
+ readonly stderr: AsyncIterable<string>;
92
+ /** Wait for process completion */
93
+ wait(): Promise<SpawnResult>;
94
+ /** Kill the process */
95
+ kill(signal?: 'SIGTERM' | 'SIGKILL'): void;
96
+ }
97
+ /**
98
+ * Adapter interface for process execution
99
+ *
100
+ * Abstracts process spawning across Node.js, Deno, and Bun.
101
+ */
102
+ interface ExecAdapter {
103
+ /**
104
+ * Get the capabilities of this runtime
105
+ */
106
+ getCapabilities(): Capabilities;
107
+ /**
108
+ * Spawn a process and wait for completion
109
+ *
110
+ * @param options - Spawn options
111
+ * @param handlers - Optional stream handlers for real-time output
112
+ * @returns Promise resolving to spawn result
113
+ */
114
+ spawn(options: SpawnOptions, handlers?: StreamHandler): Promise<SpawnResult>;
115
+ /** Capture stdout bytes without text decoding; optional for custom adapters. */
116
+ spawnBytes?(options: SpawnOptions, handlers?: Pick<StreamHandler, 'onStderr'>): Promise<SpawnResult<Uint8Array>>;
117
+ /**
118
+ * Spawn a process with streaming support
119
+ *
120
+ * @param options - Spawn options
121
+ * @returns Handle to the spawned process
122
+ */
123
+ spawnStreaming?(options: SpawnOptions): SpawnHandle;
124
+ }
125
+ /**
126
+ * Options for tailing a file
127
+ */
128
+ type TailOptions = {
129
+ /** Path to the file to tail */
130
+ filePath: string;
131
+ /** AbortSignal for cancellation */
132
+ signal?: AbortSignal;
133
+ /** Callback for each new line */
134
+ onLine: (line: string) => void;
135
+ /** Start offset in bytes (default: 0) */
136
+ startOffset?: number;
137
+ /** Polling interval in milliseconds (default: 100) */
138
+ pollInterval?: number;
139
+ };
140
+ /**
141
+ * Handle to a tail operation
142
+ *
143
+ * Implements AsyncDisposable for use with `await using`.
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * // Traditional usage
148
+ * const handle = adapter.tailStreaming('/path/to/file');
149
+ * try {
150
+ * for await (const line of handle.lines) { console.log(line); }
151
+ * } finally {
152
+ * handle.stop();
153
+ * }
154
+ *
155
+ * // With await using (recommended)
156
+ * await using handle = adapter.tailStreaming('/path/to/file');
157
+ * for await (const line of handle.lines) { console.log(line); }
158
+ * // Automatically stopped when scope exits
159
+ * ```
160
+ */
161
+ interface TailHandle extends AsyncDisposable {
162
+ /** Async iterator for new lines */
163
+ readonly lines: AsyncIterable<string>;
164
+ /** Stop tailing */
165
+ stop(): void;
166
+ }
167
+ /**
168
+ * Adapter interface for filesystem operations
169
+ *
170
+ * Used primarily for LFS progress tracking via GIT_LFS_PROGRESS.
171
+ */
172
+ interface FsAdapter {
173
+ /**
174
+ * Create a temporary file and return its path
175
+ *
176
+ * Calling `deleteFile` with the returned path should release everything this method
177
+ * allocated (built-in adapters also remove the private directory holding the file).
178
+ *
179
+ * @param prefix - Optional prefix for the temp file name
180
+ * @returns Path to the created temporary file
181
+ */
182
+ createTempFile(prefix?: string): Promise<string>;
183
+ /**
184
+ * Create a fresh, empty temporary directory and return its path
185
+ *
186
+ * Callers remove it with {@link FsAdapter.deleteDirectory}.
187
+ *
188
+ * @param prefix - Optional prefix for the temp directory name
189
+ * @returns Path to the created temporary directory
190
+ */
191
+ createTempDirectory?(prefix?: string): Promise<string>;
192
+ /**
193
+ * Start tailing a file (watching for new lines)
194
+ *
195
+ * @param options - Tail options
196
+ * @returns Promise that resolves when tailing stops
197
+ */
198
+ tail(options: TailOptions): Promise<void>;
199
+ /**
200
+ * Start tailing a file with streaming support
201
+ *
202
+ * @param filePath - Path to the file to tail
203
+ * @param options - Optional tail options
204
+ * @returns Handle to the tail operation
205
+ */
206
+ tailStreaming?(filePath: string, options?: {
207
+ signal?: AbortSignal;
208
+ pollInterval?: number;
209
+ }): TailHandle;
210
+ /**
211
+ * Delete a file
212
+ *
213
+ * @param filePath - Path to the file to delete
214
+ */
215
+ deleteFile(filePath: string): Promise<void>;
216
+ /**
217
+ * Delete a directory recursively
218
+ *
219
+ * @param dirPath - Path to the directory to delete
220
+ */
221
+ deleteDirectory(dirPath: string): Promise<void>;
222
+ /**
223
+ * Check if a file exists
224
+ *
225
+ * @param filePath - Path to check
226
+ * @returns Whether the file exists
227
+ */
228
+ exists(filePath: string): Promise<boolean>;
229
+ /**
230
+ * Read a file's contents
231
+ *
232
+ * @param filePath - Path to the file
233
+ * @returns File contents as string
234
+ */
235
+ readFile?(filePath: string): Promise<string>;
236
+ /**
237
+ * Write contents to a file
238
+ *
239
+ * @param filePath - Path to the file
240
+ * @param contents - Contents to write
241
+ */
242
+ writeFile?(filePath: string, contents: string): Promise<void>;
243
+ }
244
+ /**
245
+ * Combined adapters for a runtime
246
+ */
247
+ interface RuntimeAdapters {
248
+ exec: ExecAdapter;
249
+ fs: FsAdapter;
250
+ }
251
+ /**
252
+ * Factory function type for creating runtime adapters
253
+ */
254
+ type AdapterFactory = () => RuntimeAdapters;
255
+
256
+ /**
257
+ * Credential helper configuration
258
+ */
259
+ type CredentialHelperConfig = {
260
+ /** Helper name (e.g., 'store', 'cache', 'manager-core', or custom name) */
261
+ helper?: string;
262
+ /** Path to custom helper binary */
263
+ helperPath?: string;
264
+ };
265
+ /**
266
+ * Options for CliRunner
267
+ */
268
+ type CliRunnerOptions = {
269
+ /** Paths for upstream standalone programs; gitweb defaults to gitweb.cgi on PATH. */
270
+ companionBinaries?: Partial<Record<CompanionExecutable, string>>;
271
+ /** Git binary path (default: 'git') */
272
+ gitBinary?: string;
273
+ /** Additional environment variables */
274
+ env?: Record<string, string>;
275
+ /**
276
+ * Controls how the parent process environment is inherited by spawned Git commands.
277
+ *
278
+ * By default, only a curated allowlist of variables that Git needs to operate is
279
+ * inherited (environment variable traversal prevention); the full parent environment is
280
+ * NOT forwarded. See {@link EnvInheritance} for all options.
281
+ *
282
+ * @default undefined (inherit the default allowlist)
283
+ */
284
+ inheritEnv?: EnvInheritance;
285
+ /** Directories to prepend to PATH */
286
+ pathPrefix?: string[];
287
+ /** Custom HOME directory for git config isolation */
288
+ home?: string;
289
+ /** Credential helper configuration */
290
+ credential?: CredentialHelperConfig;
291
+ /** Audit configuration for command tracking and tracing */
292
+ audit?: AuditConfig;
293
+ };
294
+ /**
295
+ * Per-call options for {@link CliRunner.run} / {@link CliRunner.runOrThrow}.
296
+ *
297
+ * Extends {@link ExecOpts} with an `env` overlay so callers (e.g. the repository
298
+ * implementations) can inject command-specific environment variables — such as
299
+ * `GIT_LFS_SKIP_SMUDGE` for an LFS skip-smudge mode. This keeps `env` out of the
300
+ * public `ExecOpts` / repository operation option types, scoping it to the
301
+ * runner's own `run` / `runOrThrow` entry points.
302
+ */
303
+ type RunOptions = ExecOpts & {
304
+ /** UTF-8 text to write to standard input, then close it. */
305
+ stdin?: string | Uint8Array;
306
+ /**
307
+ * Extra environment variables merged on top of the resolved environment for
308
+ * this single command. Values here take precedence over the configured
309
+ * environment but do not persist across calls.
310
+ */
311
+ env?: Record<string, string>;
312
+ };
313
+ /**
314
+ * CLI Runner for executing Git commands
315
+ *
316
+ * Handles:
317
+ * - Command construction based on execution context
318
+ * - Progress tracking from stderr (Git and LFS)
319
+ * - Abort signal handling
320
+ * - Error mapping
321
+ */
322
+ declare class CliRunner {
323
+ private readonly exec;
324
+ private readonly fs;
325
+ private readonly gitBinary;
326
+ private readonly companionBinaries;
327
+ private readonly baseEnv;
328
+ private readonly inheritEnv;
329
+ private readonly pathPrefix;
330
+ private readonly home;
331
+ private readonly credential;
332
+ private readonly audit;
333
+ constructor(adapters: RuntimeAdapters, options?: CliRunnerOptions);
334
+ /**
335
+ * Create a new CliRunner with additional options merged
336
+ *
337
+ * Used to create a runner for a specific repository with custom environment
338
+ */
339
+ withOptions(options: CliRunnerOptions): CliRunner;
340
+ /**
341
+ * Build command argv based on execution context
342
+ */
343
+ private buildArgv;
344
+ /**
345
+ * Build the effective environment for command execution
346
+ *
347
+ * Seeds the environment from the inherited (allowlisted) parent variables, then layers
348
+ * the configured `env`, home directory, and PATH prefix overrides on top. The parent
349
+ * process environment is never forwarded wholesale unless `inheritEnv: true` is set
350
+ * (environment variable traversal prevention).
351
+ */
352
+ private buildEnv;
353
+ /**
354
+ * Extract directory from a file path
355
+ */
356
+ private extractDirectory;
357
+ /**
358
+ * Run a Git command
359
+ */
360
+ /** Resolve environment-dependent filter constraints before convenience execution. */
361
+ validateFilterOptions(context: ExecutionContext, name: 'clone' | 'submoduleUpdate', options: object | undefined, opts?: RunOptions): Promise<void>;
362
+ /** Resolve mainline narrowing against the executable used by the convenience call. */
363
+ validateMainlineOptions(context: ExecutionContext, name: 'cherryPick' | 'revert', options: object | undefined, opts?: RunOptions): Promise<void>;
364
+ /**
365
+ * Run a probe of a builtin that requires a repository (RUN_SETUP).
366
+ *
367
+ * Global contexts carry no repository, so such probes would otherwise discover one from the
368
+ * process working directory: outside a repository Git dies before parsing options, and inside
369
+ * an unrelated one its configuration leaks in. Run them against a throwaway empty repository.
370
+ */
371
+ private runRepositoryProbe;
372
+ /** Observe atoi using an existing file so clone stops before transport or destination creation. */
373
+ private observeDepthAtoi;
374
+ /** Resolve depth and other native constraints for a convenience fetch call. */
375
+ validateFetchOptions(context: ExecutionContext, options: object | undefined, opts?: RunOptions): Promise<void>;
376
+ /** Check universally invalid input first, then only the native dimensions that affect validity. */
377
+ private validateNativeOptions;
378
+ /** Text execution remains independent of extra command output-mode options. */
379
+ run(context: ExecutionContext, args: string[], opts?: RunOptions): Promise<RawResult>;
380
+ /**
381
+ * Run an internal capability probe.
382
+ *
383
+ * Probes classify Git's own diagnostics, so tracing is stripped from their environment
384
+ * (including GIT_TRACE* variables configured by the caller) and they never reach the
385
+ * user's audit or trace callbacks.
386
+ */
387
+ private probe;
388
+ runBytes(context: ExecutionContext, args: string[], opts?: RunOptions): Promise<RawResult<Uint8Array>>;
389
+ /** Run a standalone upstream program through the shared text execution path. */
390
+ runCompanion(context: ExecutionContext, executable: CompanionExecutable, args: string[], opts?: RunOptions): Promise<RawResult>;
391
+ /** Capture standalone program output without text decoding. */
392
+ runCompanionBytes(context: ExecutionContext, executable: CompanionExecutable, args: string[], opts?: RunOptions): Promise<RawResult<Uint8Array>>;
393
+ /** Validate per-call options, then spawn one Git or companion process and collect its result. */
394
+ private execute;
395
+ /**
396
+ * Process a single line from stderr for progress and trace callbacks
397
+ */
398
+ private processStderrLine;
399
+ /**
400
+ * Map Git result to GitError if needed
401
+ */
402
+ mapError(result: RawResult, context: ExecutionContext, argv: string[]): GitError | null;
403
+ /**
404
+ * Classify error type based on stderr content
405
+ */
406
+ private classifyError;
407
+ /**
408
+ * Extract user-friendly error message from stderr
409
+ */
410
+ private extractErrorMessage;
411
+ /**
412
+ * Run a command and throw on error
413
+ */
414
+ checkResult(context: ExecutionContext, args: string[], result: RawResult): void;
415
+ runOrThrow(context: ExecutionContext, args: string[], opts?: RunOptions): Promise<RawResult>;
416
+ }
417
+
418
+ /**
419
+ * Git implementation - repository-agnostic operations
420
+ */
421
+
422
+ /**
423
+ * Default minimum supported Git version.
424
+ *
425
+ * This is the minimum version required when `useLegacyVersion` is false (the default).
426
+ * Use `useLegacyVersion: true` to allow older Git versions (2.25.0+).
427
+ */
428
+ declare const MIN_GIT_VERSION = "2.30.0";
429
+ /**
430
+ * Legacy minimum Git version
431
+ *
432
+ * When `useLegacyVersion: true` is set, this version is used as the minimum.
433
+ * Git 2.25.0 is the default version on Ubuntu 20.04 LTS.
434
+ */
435
+ declare const LEGACY_GIT_VERSION = "2.25.0";
436
+ /**
437
+ * Options for creating a Git instance
438
+ */
439
+ type CreateGitOptions = CliRunnerOptions & {
440
+ /** Runtime adapters (exec, fs) */
441
+ adapters: RuntimeAdapters;
442
+ /**
443
+ * Controls whether to perform a Git version check during initialization.
444
+ * When true, skips the Git version check. When false (default), throws
445
+ * GitError if Git version is below the minimum required version.
446
+ * @default false
447
+ */
448
+ skipVersionCheck?: boolean;
449
+ /**
450
+ * Allow legacy Git versions (2.25.0+) instead of requiring 2.30.0+.
451
+ *
452
+ * Use this for environments with older Git installations such as
453
+ * Ubuntu 20.04 LTS which ships with Git 2.25.1 by default.
454
+ *
455
+ * @default false
456
+ */
457
+ useLegacyVersion?: boolean;
458
+ };
459
+ /**
460
+ * Create a new Git instance (synchronous, no version check)
461
+ *
462
+ * @param options - Creation options including runtime adapters
463
+ * @returns Git instance
464
+ * @deprecated Use createGit instead for version checking
465
+ */
466
+ declare function createGitSync(options: CreateGitOptions): Git;
467
+ /**
468
+ * Create a new Git instance with optional version check
469
+ *
470
+ * @param options - Creation options including runtime adapters
471
+ * @returns Git instance
472
+ * @throws GitError with kind 'UnsupportedGitVersion' if Git version is below minimum
473
+ */
474
+ declare function createGit(options: CreateGitOptions): Promise<Git>;
475
+
476
+ /** Runtime-independent convenience client. Runtime entrypoints supply the adapters. */
477
+ declare class GitClient implements Git {
478
+ private readonly git;
479
+ constructor(git: Git);
480
+ get open(): (path: string, opts?: GitOpenOptions) => Promise<WorktreeRepo>;
481
+ /**
482
+ * Open an existing bare repository
483
+ *
484
+ * Throws GitError if the repository is not bare.
485
+ *
486
+ * @throws GitError with kind 'NotBareRepo' if the repository is not bare
487
+ */
488
+ get openBare(): (path: string, opts?: GitOpenOptions) => Promise<BareRepo>;
489
+ /**
490
+ * Open an existing repository without type guarantee
491
+ *
492
+ * Returns either WorktreeRepo or BareRepo depending on the repository type.
493
+ * Use this when you don't know the repository type at compile time.
494
+ */
495
+ get openRaw(): (path: string, opts?: GitOpenOptions) => Promise<WorktreeRepo | BareRepo>;
496
+ /**
497
+ * Clone a repository
498
+ *
499
+ * The return type depends on the `bare` or `mirror` option:
500
+ * - `{ bare: true }` or `{ mirror: true }` → `BareRepo`
501
+ * - Otherwise → `WorktreeRepo`
502
+ */
503
+ clone(url: string, path: string, opts: CloneOpts & {
504
+ bare: true;
505
+ } & ExecOpts): Promise<BareRepo>;
506
+ clone(url: string, path: string, opts: CloneOpts & {
507
+ mirror: true;
508
+ } & ExecOpts): Promise<BareRepo>;
509
+ clone(url: string, path: string, opts?: CloneOpts & {
510
+ bare?: false;
511
+ mirror?: false;
512
+ } & ExecOpts): Promise<WorktreeRepo>;
513
+ clone(url: string, path: string, opts?: CloneOpts & ExecOpts): Promise<WorktreeRepo | BareRepo>;
514
+ /**
515
+ * Initialize a new repository
516
+ *
517
+ * The return type depends on the `bare` option:
518
+ * - `{ bare: true }` → `BareRepo`
519
+ * - Otherwise → `WorktreeRepo`
520
+ */
521
+ init(path: string, opts: InitOpts & {
522
+ bare: true;
523
+ } & ExecOpts): Promise<BareRepo>;
524
+ init(path: string, opts?: InitOpts & {
525
+ bare?: false;
526
+ } & ExecOpts): Promise<WorktreeRepo>;
527
+ init(path: string, opts?: InitOpts & ExecOpts): Promise<WorktreeRepo | BareRepo>;
528
+ /**
529
+ * List references in a remote repository
530
+ */
531
+ get lsRemote(): (url: string, opts?: LsRemoteOpts & ExecOpts) => Promise<LsRemoteResult>;
532
+ /**
533
+ * Get git version
534
+ */
535
+ get version(): (opts?: ExecOpts) => Promise<string>;
536
+ /** Execute a raw Git command without typed argument validation. */
537
+ get raw(): (argv: string[], opts?: CommandExecOpts) => Promise<RawResult>;
538
+ /**
539
+ * Global config operations
540
+ *
541
+ * Operates on ~/.gitconfig (user-level configuration).
542
+ * For repository-level config, use repo.config instead.
543
+ */
544
+ get config(): GlobalConfigOperations;
545
+ /**
546
+ * Global LFS operations
547
+ *
548
+ * Operates on ~/.gitconfig (user-level) or /etc/gitconfig (system-level).
549
+ * For repository-level LFS operations, use repo.lfs instead.
550
+ *
551
+ * @example
552
+ * ```typescript
553
+ * // Install LFS globally
554
+ * await git.lfs.install();
555
+ *
556
+ * // Install system-wide
557
+ * await git.lfs.install({ system: true });
558
+ *
559
+ * // Get LFS version
560
+ * const version = await git.lfs.version();
561
+ * ```
562
+ */
563
+ get lfs(): GlobalLfsOperations;
564
+ }
565
+
566
+ export { type AdapterFactory as A, type CreateGitOptions as C, type ExecAdapter as E, type FsAdapter as F, GitClient as G, LEGACY_GIT_VERSION as L, MIN_GIT_VERSION as M, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, createGit as e, createGitSync as f, CliRunner as g, type CliRunnerOptions as h };