-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgit.ts
More file actions
495 lines (437 loc) · 13.3 KB
/
git.ts
File metadata and controls
495 lines (437 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/**
* Git utilities for baseline comparison
* Handles worktree creation, ref validation, and cleanup
*/
import { spawn } from 'node:child_process';
import { join } from 'node:path';
import { access, rm, mkdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { debugLog, debugError } from './debug.js';
/**
* Result from creating a git worktree
*/
export interface GitWorktreeResult {
/** Path to the created worktree */
worktreePath: string;
/** The resolved commit hash */
commitHash: string;
/** The original ref that was requested */
ref: string;
}
/**
* Options for git operations
*/
export interface GitOptions {
/** Working directory for git commands (default: process.cwd()) */
cwd?: string;
/** Timeout in milliseconds (default: 30000) */
timeout?: number;
}
/**
* Execute a git command and return stdout
* Uses spawn instead of exec for better security (no shell interpretation)
* @throws Error if git command fails
*/
async function execGit(
args: string[],
options: GitOptions = {}
): Promise<string> {
const cwd = options.cwd ?? process.cwd();
const timeout = options.timeout ?? 30000;
const command = `git ${args.join(' ')}`;
debugLog('git', `Executing: ${command}`, { cwd });
return new Promise((resolve, reject) => {
const child = spawn('git', args, {
cwd,
timeout,
stdio: ['ignore', 'pipe', 'pipe'],
});
let stdout = '';
let stderr = '';
// TypeScript needs explicit type assertion for stdio pipes
if (child.stdout) {
child.stdout.on('data', (data: Buffer) => {
stdout += data.toString();
});
}
if (child.stderr) {
child.stderr.on('data', (data: Buffer) => {
stderr += data.toString();
});
}
child.on('error', (error: Error) => {
debugError('git', 'execGit spawn error', {
command,
cwd,
message: error.message,
});
reject(new Error(`Git command failed: ${error.message}`));
});
child.on('close', (code: number | null) => {
if (code === 0) {
if (stderr && !stderr.includes('Preparing worktree')) {
// Some git commands output to stderr even on success
debugLog('git', `stderr: ${stderr.trim()}`);
}
resolve(stdout.trim());
} else {
debugError('git', 'execGit', {
command,
cwd,
code,
stderr: stderr.trim(),
});
const errorMessage = stderr.trim() || `Command failed with exit code ${code}`;
reject(new Error(`Git command failed: ${errorMessage}`));
}
});
});
}
/**
* Check if a directory is inside a git repository
*/
export async function isGitRepo(options: GitOptions = {}): Promise<boolean> {
try {
await execGit(['rev-parse', '--git-dir'], options);
return true;
} catch {
return false;
}
}
/**
* Get the root directory of the git repository
*/
export async function getGitRoot(options: GitOptions = {}): Promise<string> {
const root = await execGit(['rev-parse', '--show-toplevel'], options);
return root;
}
/**
* Check if git worktrees are supported (git >= 2.5)
*/
export async function supportsWorktrees(options: GitOptions = {}): Promise<boolean> {
try {
// Try to list worktrees - will fail if not supported
await execGit(['worktree', 'list'], options);
return true;
} catch {
return false;
}
}
/**
* Resolve a git ref to its commit hash
* Validates that the ref exists
*
* @param ref - Git ref (branch, tag, commit, HEAD, HEAD~1, etc.)
* @returns The resolved commit hash
* @throws Error if ref doesn't exist
*/
export async function resolveGitRef(
ref: string,
options: GitOptions = {}
): Promise<string> {
try {
const hash = await execGit(['rev-parse', '--verify', ref], options);
return hash;
} catch (error) {
throw new Error(`Invalid git ref "${ref}": ref does not exist`);
}
}
/**
* Get a short description of a git ref (for display)
* Returns branch name, tag name, or short commit hash
*/
export async function describeGitRef(
ref: string,
options: GitOptions = {}
): Promise<string> {
try {
// Try to get a symbolic name first
const symbolic = await execGit(
['rev-parse', '--abbrev-ref', ref],
options
);
if (symbolic && symbolic !== 'HEAD') {
return symbolic;
}
} catch {
// Ignore - fall through to short hash
}
try {
// Fall back to short commit hash
const shortHash = await execGit(['rev-parse', '--short', ref], options);
return shortHash;
} catch {
return ref; // Return original if all else fails
}
}
/**
* Create a git worktree at a specific ref
*
* @param ref - Git ref to checkout (branch, tag, commit, etc.)
* @param targetDir - Directory to create the worktree in (optional, will create temp if not provided)
* @returns GitWorktreeResult with worktree path and commit info
* @throws Error if worktree creation fails
*/
export async function createWorktree(
ref: string,
targetDir?: string,
options: GitOptions = {}
): Promise<GitWorktreeResult> {
// Validate we're in a git repo
if (!(await isGitRepo(options))) {
throw new Error('Not a git repository');
}
// Check worktree support
if (!(await supportsWorktrees(options))) {
throw new Error('Git worktrees not supported (requires git >= 2.5)');
}
// Resolve the ref to a commit hash
const commitHash = await resolveGitRef(ref, options);
// Generate worktree path if not provided
const worktreePath = targetDir ?? join(
tmpdir(),
`logicstamp-worktree-${Date.now()}-${commitHash.substring(0, 8)}`
);
debugLog('git', `Creating worktree at ${worktreePath} for ref ${ref}`, {
commitHash,
});
try {
// Create parent directory if needed
await mkdir(worktreePath, { recursive: true });
// Remove the directory we just created (git worktree add needs it to not exist)
await rm(worktreePath, { recursive: true, force: true });
// Create the worktree in detached HEAD mode
await execGit(
['worktree', 'add', '--detach', worktreePath, commitHash],
options
);
debugLog('git', `Worktree created successfully at ${worktreePath}`);
return {
worktreePath,
commitHash,
ref,
};
} catch (error) {
// Clean up on failure
try {
await rm(worktreePath, { recursive: true, force: true });
} catch {
// Ignore cleanup errors
}
const err = error as Error;
debugError('git', 'createWorktree', {
ref,
targetDir: worktreePath,
message: err.message,
});
throw new Error(`Failed to create worktree for "${ref}": ${err.message}`);
}
}
/**
* Remove a git worktree and clean up its directory
*
* @param worktreePath - Path to the worktree to remove
*/
export async function removeWorktree(
worktreePath: string,
options: GitOptions = {}
): Promise<void> {
debugLog('git', `Removing worktree at ${worktreePath}`);
try {
// First, try to remove via git worktree command
await execGit(['worktree', 'remove', '--force', worktreePath], options);
} catch (error) {
// If git worktree remove fails, try manual cleanup
debugLog('git', `git worktree remove failed, trying manual cleanup`);
try {
// Remove the directory
await rm(worktreePath, { recursive: true, force: true });
// Prune stale worktree entries
await execGit(['worktree', 'prune'], options);
} catch (cleanupError) {
debugError('git', 'removeWorktree', {
worktreePath,
message: (cleanupError as Error).message,
});
// Don't throw - best effort cleanup
}
}
debugLog('git', `Worktree removed: ${worktreePath}`);
}
/**
* Check if there are uncommitted changes in the working directory
*/
export async function hasUncommittedChanges(options: GitOptions = {}): Promise<boolean> {
try {
const status = await execGit(['status', '--porcelain'], options);
return status.length > 0;
} catch {
return false;
}
}
/**
* Get the current branch name (or "HEAD" if detached)
*/
export async function getCurrentBranch(options: GitOptions = {}): Promise<string> {
try {
const branch = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], options);
return branch;
} catch {
return 'HEAD';
}
}
/**
* Parse a baseline string into ref and type
*
* @param baseline - Baseline string (e.g., "git:main", "git:HEAD", "git:v1.0.0")
* @returns Parsed baseline info or null if not a git baseline
*/
export function parseGitBaseline(baseline: string): { ref: string } | null {
if (!baseline.startsWith('git:')) {
return null;
}
const ref = baseline.substring(4); // Remove "git:" prefix
if (!ref) {
return null;
}
return { ref };
}
/**
* Directory paths used for git baseline comparison
*/
export interface GitBaselinePaths {
/** Root temp directory for this comparison */
tempRoot: string;
/** Directory for baseline context (generated from git ref) */
baselineDir: string;
/** Directory for current context (generated from working tree) */
currentDir: string;
/** Directory for git worktree (source code at git ref) */
worktreeDir: string;
}
/**
* Create directory structure for git baseline comparison
* Uses .logicstamp/compare/ for context files
*/
export async function createBaselinePaths(
projectRoot: string,
ref: string
): Promise<GitBaselinePaths> {
const timestamp = Date.now();
const safeRef = ref.replace(/[^a-zA-Z0-9_-]/g, '_').substring(0, 20);
// Context files go in .logicstamp/compare/
const compareRoot = join(projectRoot, '.logicstamp', 'compare');
const baselineDir = join(compareRoot, 'baseline');
const currentDir = join(compareRoot, 'current');
// Worktree goes in system temp (it's large)
const worktreeDir = join(
tmpdir(),
`logicstamp-worktree-${safeRef}-${timestamp}`
);
// Create directories
await mkdir(baselineDir, { recursive: true });
await mkdir(currentDir, { recursive: true });
return {
tempRoot: compareRoot,
baselineDir,
currentDir,
worktreeDir,
};
}
/**
* Check if a file is git-ignored
* @param filePath - File path relative to git root or absolute path
* @param options - Git options
* @returns true if the file is git-ignored, false otherwise
*/
export async function isGitIgnored(
filePath: string,
options: GitOptions = {}
): Promise<boolean> {
try {
// git check-ignore --quiet returns exit code 0 if file is ignored, 1 if not ignored
// execGit throws on non-zero exit codes, so if it succeeds, file is ignored
await execGit(['check-ignore', '--quiet', filePath], options);
return true; // Command succeeded, file is ignored
} catch {
// Command failed (exit code 1), file is not ignored
return false;
}
}
/**
* Filter out git-ignored files from an array of file paths
* @param filePaths - Array of file paths to filter (may be normalized basenames in git baseline mode)
* @param projectRoot - Project root directory (for resolving relative paths)
* @param options - Git options
* @returns Array of file paths that are NOT git-ignored
*/
export async function filterGitIgnoredFiles(
filePaths: string[],
projectRoot: string,
options: GitOptions = {}
): Promise<string[]> {
const { relative } = await import('node:path');
const filtered: string[] = [];
for (const filePath of filePaths) {
let isIgnored = false;
// If the path contains a slash, it's a full relative path
if (filePath.includes('/')) {
// Convert to relative path from project root if needed
let relativePath: string;
if (filePath.startsWith('/') || filePath.match(/^[A-Z]:/)) {
// Absolute path - convert to relative
relativePath = relative(projectRoot, filePath).replace(/\\/g, '/');
} else {
relativePath = filePath;
}
// Check if file is git-ignored
isIgnored = await isGitIgnored(relativePath, { ...options, cwd: projectRoot });
} else {
// It's just a basename (normalized in git baseline mode)
// Check if the basename itself is git-ignored (works for root-level files like next-env.d.ts)
isIgnored = await isGitIgnored(filePath, { ...options, cwd: projectRoot });
// Also check common patterns that might match this basename
if (!isIgnored) {
// Check common git-ignore patterns that might match
const patternsToCheck = [
`**/${filePath}`,
`*/${filePath}`,
];
for (const pattern of patternsToCheck) {
if (await isGitIgnored(pattern, { ...options, cwd: projectRoot })) {
isIgnored = true;
break;
}
}
}
}
if (!isIgnored) {
filtered.push(filePath);
}
}
return filtered;
}
/**
* Clean up git baseline comparison directories
*/
export async function cleanupBaselinePaths(
paths: GitBaselinePaths,
options: GitOptions = {}
): Promise<void> {
debugLog('git', 'Cleaning up baseline paths', { ...paths });
// Remove worktree first (via git)
try {
await removeWorktree(paths.worktreeDir, options);
} catch {
// Best effort - worktree might already be removed
}
// Remove context directories
try {
await rm(paths.tempRoot, { recursive: true, force: true });
} catch (error) {
debugError('git', 'cleanupBaselinePaths', {
tempRoot: paths.tempRoot,
message: (error as Error).message,
});
}
}