-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit.ts
More file actions
540 lines (465 loc) · 15.2 KB
/
git.ts
File metadata and controls
540 lines (465 loc) · 15.2 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import { execFile, execFileSync, spawn } from "child_process";
import { promises as fs } from "fs";
import * as path from "path";
interface GitRunOptions {
cwd: string;
gitPath: string;
args: string[];
}
let debugEnabled = false;
export function setGitDebug(enabled: boolean): void {
debugEnabled = enabled;
}
function log(message: string, ...args: unknown[]): void {
if (!debugEnabled) return;
console.debug(`[auto-git] ${message}`, ...args);
}
function logCmd(args: string[]): void {
if (!debugEnabled) return;
console.debug(`[auto-git] > git ${args.join(" ")}`);
}
function buildGitEnv(): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
if (process.platform === "darwin") {
const extraPaths = [
"/usr/local/bin",
"/opt/homebrew/bin",
"/usr/local/sbin",
"/opt/homebrew/sbin",
];
const currentPath = env.PATH ?? "";
const parts = currentPath.split(path.delimiter).filter(Boolean);
const partsNormalized = parts.map((p) => p.replace(/\/+$/, ""));
const missing = extraPaths.filter((p) => !partsNormalized.includes(p));
if (missing.length > 0) {
env.PATH = [...parts, ...missing].join(path.delimiter);
}
}
return env;
}
let cachedGitEnv: NodeJS.ProcessEnv | null = null;
function getGitEnv(): NodeJS.ProcessEnv {
if (!cachedGitEnv) {
cachedGitEnv = buildGitEnv();
}
return cachedGitEnv;
}
function runGitSync({ cwd, gitPath, args }: GitRunOptions): string {
logCmd(args);
try {
const result = execFileSync(gitPath, args, {
cwd,
windowsHide: true,
env: getGitEnv(),
encoding: "utf8",
});
log("ok");
return result;
} catch (e) {
log("error:", (e as Error).message);
throw e;
}
}
function runGit({ cwd, gitPath, args }: GitRunOptions): Promise<string> {
logCmd(args);
return new Promise((resolve, reject) => {
execFile(
gitPath,
args,
{
cwd,
windowsHide: true,
env: getGitEnv(),
},
(err, stdout, stderr) => {
if (err) {
log("error:", stderr?.trim() || err.message);
reject(new Error(stderr?.trim() || err.message));
return;
}
log("ok");
resolve(stdout);
}
);
});
}
async function ensureGitignore(cwd: string, ignoreDir?: string): Promise<void> {
if (!ignoreDir) return;
const gitignorePath = path.join(cwd, ".gitignore");
const ignorePattern = ignoreDir.endsWith("/") ? ignoreDir : `${ignoreDir}/`;
let content = "";
try {
content = await fs.readFile(gitignorePath, "utf8");
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
}
const lines = content.split(/\r?\n/);
if (lines.some((line) => line.trim() === ignorePattern)) return;
const eol = content.includes("\r\n") ? "\r\n" : "\n";
const prefix = content.length > 0 && !content.endsWith("\n") ? eol : "";
await fs.writeFile(gitignorePath, `${content}${prefix}${ignorePattern}${eol}`, "utf8");
}
// Repo state detection
export type RepoState =
| "not-a-repo"
| "empty-repo"
| "local-only"
| "remote-no-upstream"
| "ready";
export async function detectRepoState(cwd: string, gitPath: string): Promise<RepoState> {
// Check if it's a git repo
if (!(await isGitRepo(cwd, gitPath))) {
return "not-a-repo";
}
// Check if there are any commits
try {
await runGit({ cwd, gitPath, args: ["rev-parse", "HEAD"] });
} catch {
return "empty-repo";
}
// Check if remote is configured
const remoteUrl = await getRemoteUrl(cwd, gitPath);
if (!remoteUrl) {
return "local-only";
}
// Check if upstream is set
try {
await runGit({ cwd, gitPath, args: ["rev-parse", "--abbrev-ref", "@{u}"] });
return "ready";
} catch {
return "remote-no-upstream";
}
}
export async function getChangedFiles(cwd: string, gitPath: string): Promise<string[]> {
const stdout = await runGit({ cwd, gitPath, args: ["status", "--porcelain=v1", "-z"] });
if (!stdout) return [];
const parts = stdout.split("\0").filter(Boolean);
const files: string[] = [];
for (let i = 0; i < parts.length; i++) {
const entry = parts[i];
const statusCode = entry.slice(0, 2);
const filePath = entry.slice(3);
// Handle rename/copy entries (have additional NUL-separated path for new name)
if (statusCode.startsWith("R") || statusCode.startsWith("C")) {
const newPath = parts[++i];
if (newPath) files.push(newPath);
continue;
}
if (filePath) files.push(filePath);
}
return [...new Set(files)];
}
export async function getChangedFileDiff(cwd: string, gitPath: string, filePath: string): Promise<string> {
const stdout = await runGit({ cwd, gitPath, args: ["diff", "--", filePath] });
if (!stdout) return "";
return stdout;
}
export async function commitAll(cwd: string, gitPath: string, message: string): Promise<void> {
await runGit({ cwd, gitPath, args: ["add", "-A"] });
try {
await runGit({ cwd, gitPath, args: ["commit", "-m", message] });
} catch (e) {
const msg = (e as Error).message;
if (msg.includes("nothing to commit") || msg.includes("no changes added")) {
return;
}
throw e;
}
}
export async function push(cwd: string, gitPath: string): Promise<void> {
const branch = await getCurrentBranch(cwd, gitPath);
await runGit({ cwd, gitPath, args: ["push", "-u", "origin", branch] });
}
export interface PullResult {
success: boolean;
hasConflicts: boolean;
message: string;
notReady?: boolean;
}
export async function pull(cwd: string, gitPath: string): Promise<PullResult> {
// Check repo state first
const state = await detectRepoState(cwd, gitPath);
if (state !== "ready") {
return {
success: false,
hasConflicts: false,
message: `Repository not ready: ${state}`,
notReady: true
};
}
try {
// Try to use upstream first
try {
const stdout = await runGit({ cwd, gitPath, args: ["pull"] });
return { success: true, hasConflicts: false, message: stdout };
} catch {
// Fallback to explicit origin/branch
const branch = await getCurrentBranch(cwd, gitPath);
const stdout = await runGit({ cwd, gitPath, args: ["pull", "origin", branch] });
return { success: true, hasConflicts: false, message: stdout };
}
} catch (e) {
const msg = (e as Error).message;
if (msg.includes("CONFLICT") || msg.includes("Merge conflict")) {
return { success: false, hasConflicts: true, message: msg };
}
throw e;
}
}
export async function getConflictFiles(cwd: string, gitPath: string): Promise<string[]> {
try {
const stdout = await runGit({ cwd, gitPath, args: ["diff", "--name-only", "--diff-filter=U"] });
return stdout.split("\n").map(f => f.trim()).filter(Boolean);
} catch {
return [];
}
}
export async function hasConflicts(cwd: string, gitPath: string): Promise<boolean> {
const files = await getConflictFiles(cwd, gitPath);
return files.length > 0;
}
export async function markConflictsResolved(cwd: string, gitPath: string): Promise<void> {
await runGit({ cwd, gitPath, args: ["add", "-A"] });
}
export async function isGitRepo(cwd: string, gitPath: string): Promise<boolean> {
try {
await runGit({ cwd, gitPath, args: ["rev-parse", "--git-dir"] });
return true;
} catch {
return false;
}
}
export async function initRepo(cwd: string, gitPath: string, ignoreDir?: string): Promise<void> {
await runGit({ cwd, gitPath, args: ["init"] });
await ensureGitignore(cwd, ignoreDir);
}
export async function getRemoteUrl(cwd: string, gitPath: string): Promise<string> {
try {
const stdout = await runGit({ cwd, gitPath, args: ["remote", "get-url", "origin"] });
return stdout.trim();
} catch {
return "";
}
}
export async function setRemoteUrl(cwd: string, gitPath: string, url: string): Promise<void> {
const currentUrl = await getRemoteUrl(cwd, gitPath);
if (currentUrl) {
await runGit({ cwd, gitPath, args: ["remote", "set-url", "origin", url] });
} else {
await runGit({ cwd, gitPath, args: ["remote", "add", "origin", url] });
}
}
export async function revertAll(cwd: string, gitPath: string): Promise<void> {
await runGit({ cwd, gitPath, args: ["checkout", "--", "."] });
await runGit({ cwd, gitPath, args: ["clean", "-fd"] });
}
export async function revertFile(cwd: string, gitPath: string, filePath: string): Promise<void> {
try {
// Try checkout first (for modified files)
await runGit({ cwd, gitPath, args: ["checkout", "--", filePath] });
} catch {
// If checkout fails, it might be an untracked file - remove it
await runGit({ cwd, gitPath, args: ["clean", "-f", "--", filePath] });
}
}
export type FileStatus = "M" | "A" | "R" | "U" | "";
function parsePorcelainV1Z(stdout: string): Map<string, FileStatus> {
const statusMap = new Map<string, FileStatus>();
if (!stdout) return statusMap;
const parts = stdout.split("\0").filter(Boolean);
for (let i = 0; i < parts.length; i++) {
const entry = parts[i];
const xy = entry.slice(0, 2);
let filePath = entry.slice(3);
if (xy.includes("R") || xy.includes("C")) {
const newPath = parts[++i];
if (newPath) filePath = newPath;
}
let status: FileStatus = "";
if (xy.includes("U")) {
status = "U";
} else if (xy === "??") {
status = "A";
} else if (xy.includes("A")) {
status = "A";
} else if (xy.includes("M")) {
status = "M";
} else if (xy.includes("R") || xy.includes("C")) {
status = "R";
}
if (filePath && status) {
statusMap.set(filePath, status);
}
}
return statusMap;
}
export async function getFileStatuses(cwd: string, gitPath: string): Promise<Map<string, FileStatus>> {
try {
const stdout = await runGit({ cwd, gitPath, args: ["status", "--porcelain=v1", "-z"] });
return parsePorcelainV1Z(stdout);
} catch {
return new Map<string, FileStatus>();
}
}
export async function getTrackedFiles(cwd: string, gitPath: string): Promise<Set<string>> {
const tracked = new Set<string>();
try {
const stdout = await runGit({ cwd, gitPath, args: ["ls-files", "-z"] });
if (stdout) {
stdout.split("\0").filter(Boolean).forEach((p) => tracked.add(p));
}
} catch {
// Ignore
}
return tracked;
}
// Get remote default branch (main/master)
export async function getRemoteDefaultBranch(cwd: string, gitPath: string): Promise<string | null> {
try {
// Try to get from remote HEAD
const stdout = await runGit({ cwd, gitPath, args: ["remote", "show", "origin"] });
const match = stdout.match(/HEAD branch:\s*(\S+)/);
if (match && match[1] !== "(unknown)") return match[1];
} catch {
// Fallback: try common branch names
}
// Try to find main or master in remote refs
try {
const refs = await runGit({ cwd, gitPath, args: ["ls-remote", "--heads", "origin"] });
if (!refs.trim()) return null; // Empty remote
if (refs.includes("refs/heads/main")) return "main";
if (refs.includes("refs/heads/master")) return "master";
// Return first branch found
const match = refs.match(/refs\/heads\/(\S+)/);
if (match) return match[1];
} catch {
// Ignore
}
return null; // Remote is empty or unreachable
}
// Initialize repo with first commit and push to empty remote
export async function initAndPush(cwd: string, gitPath: string, url: string, branch: string = "main", ignoreDir?: string): Promise<void> {
// Initialize with branch name
await runGit({ cwd, gitPath, args: ["init", "-b", branch] });
// Ensure .gitignore excludes config dir if specified
await ensureGitignore(cwd, ignoreDir);
// Add all files
await runGit({ cwd, gitPath, args: ["add", "-A"] });
// Create initial commit
await runGit({ cwd, gitPath, args: ["commit", "-m", "Initial commit"] });
// Add remote
await runGit({ cwd, gitPath, args: ["remote", "add", "origin", url] });
// Push with upstream
await runGit({ cwd, gitPath, args: ["push", "-u", "origin", branch] });
}
// Connect to existing remote repo (fetch and checkout)
export async function connectToRemote(cwd: string, gitPath: string, url: string, ignoreDir?: string): Promise<{ branch: string }> {
// Initialize if needed
if (!(await isGitRepo(cwd, gitPath))) {
await runGit({ cwd, gitPath, args: ["init", "-b", "main"] });
}
// Add remote
const currentUrl = await getRemoteUrl(cwd, gitPath);
if (!currentUrl) {
await runGit({ cwd, gitPath, args: ["remote", "add", "origin", url] });
} else if (currentUrl !== url) {
await runGit({ cwd, gitPath, args: ["remote", "set-url", "origin", url] });
}
// Fetch remote
await runGit({ cwd, gitPath, args: ["fetch", "origin"] });
// Get remote default branch (null if remote is empty)
const remoteBranch = await getRemoteDefaultBranch(cwd, gitPath);
if (!remoteBranch) {
// Remote is empty - create initial commit and push
await ensureGitignore(cwd, ignoreDir);
await runGit({ cwd, gitPath, args: ["add", "-A"] });
try {
await runGit({ cwd, gitPath, args: ["commit", "-m", "Initial commit"] });
} catch (e) {
// Might fail if no files to commit, that's ok
const msg = (e as Error).message;
if (!msg.includes("nothing to commit")) {
throw e;
}
}
await runGit({ cwd, gitPath, args: ["push", "-u", "origin", "main"] });
return { branch: "main" };
}
// Remote has content - check if we have local commits
let hasLocalCommits = false;
try {
await runGit({ cwd, gitPath, args: ["rev-parse", "HEAD"] });
hasLocalCommits = true;
} catch {
hasLocalCommits = false;
}
if (!hasLocalCommits) {
// No local commits: checkout remote branch directly
await runGit({ cwd, gitPath, args: ["checkout", "-b", remoteBranch, `origin/${remoteBranch}`] });
} else {
// Has local commits: rename branch and set upstream
try {
await runGit({ cwd, gitPath, args: ["branch", `-M`, remoteBranch] });
} catch {
// Branch might already be named correctly
}
await runGit({ cwd, gitPath, args: ["branch", `--set-upstream-to=origin/${remoteBranch}`, remoteBranch] });
}
return { branch: remoteBranch };
}
// Set upstream for current branch
export async function setUpstream(cwd: string, gitPath: string): Promise<void> {
const branch = await getCurrentBranch(cwd, gitPath);
await runGit({ cwd, gitPath, args: ["push", "-u", "origin", branch] });
}
// Get current branch name
async function getCurrentBranch(cwd: string, gitPath: string): Promise<string> {
const stdout = await runGit({ cwd, gitPath, args: ["rev-parse", "--abbrev-ref", "HEAD"] });
return stdout.trim();
}
// Synchronous version for use during app close
export function getChangedFilesSync(cwd: string, gitPath: string): string[] {
try {
const stdout = runGitSync({ cwd, gitPath, args: ["status", "--porcelain=v1", "-z"] });
if (!stdout) return [];
const parts = stdout.split("\0").filter(Boolean);
const files: string[] = [];
for (let i = 0; i < parts.length; i++) {
const entry = parts[i];
const statusCode = entry.slice(0, 2);
const filePath = entry.slice(3);
if (statusCode.startsWith("R") || statusCode.startsWith("C")) {
const newPath = parts[++i];
if (newPath) files.push(newPath);
continue;
}
if (filePath) files.push(filePath);
}
return [...new Set(files)];
} catch {
return [];
}
}
// Sync commit only, then spawn detached push process
export function commitSyncAndPushDetached(cwd: string, gitPath: string, message: string): void {
try {
runGitSync({ cwd, gitPath, args: ["add", "-A"] });
runGitSync({ cwd, gitPath, args: ["commit", "-m", message] });
} catch {
// Commit failed or nothing to commit
return;
}
// Spawn detached push process that continues after parent exits
try {
const child = spawn(gitPath, ["push"], {
cwd,
detached: true,
stdio: "ignore",
windowsHide: true,
env: getGitEnv(),
});
child.unref();
} catch {
// Ignore spawn errors
}
}