forked from op7418/CodePilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.ts
More file actions
385 lines (340 loc) · 11.1 KB
/
service.ts
File metadata and controls
385 lines (340 loc) · 11.1 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
import { execFile } from 'child_process';
import path from 'path';
import type { GitStatus, GitChangedFile, GitBranch, GitLogEntry, GitCommitDetail, GitWorktree } from '@/types';
function runGit(args: string[], opts: { cwd: string; timeoutMs?: number }): Promise<string> {
if (!path.isAbsolute(opts.cwd)) {
return Promise.reject(new Error(`cwd must be absolute: ${opts.cwd}`));
}
return new Promise((resolve, reject) => {
execFile('git', args, {
cwd: opts.cwd,
timeout: opts.timeoutMs ?? 10000,
maxBuffer: 10 * 1024 * 1024,
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
}, (err, stdout, stderr) => {
if (err) {
const msg = stderr?.trim() || err.message;
reject(new Error(msg));
} else {
resolve(stdout);
}
});
});
}
export async function isGitRepo(cwd: string): Promise<boolean> {
try {
await runGit(['rev-parse', '--is-inside-work-tree'], { cwd, timeoutMs: 5000 });
return true;
} catch {
return false;
}
}
export async function getRepoRoot(cwd: string): Promise<string> {
const result = await runGit(['rev-parse', '--show-toplevel'], { cwd, timeoutMs: 5000 });
return result.trim();
}
export async function getStatus(cwd: string): Promise<GitStatus> {
const isRepo = await isGitRepo(cwd);
if (!isRepo) {
return {
isRepo: false,
repoRoot: '',
branch: '',
upstream: '',
ahead: 0,
behind: 0,
dirty: false,
changedFiles: [],
};
}
const repoRoot = await getRepoRoot(cwd);
// Get branch info
let branch = '';
try {
branch = (await runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, timeoutMs: 5000 })).trim();
} catch {
branch = '';
}
// Get upstream
let upstream = '';
let ahead = 0;
let behind = 0;
try {
upstream = (await runGit(['rev-parse', '--abbrev-ref', '@{upstream}'], { cwd, timeoutMs: 5000 })).trim();
const countOutput = (await runGit(['rev-list', '--left-right', '--count', `${upstream}...HEAD`], { cwd, timeoutMs: 5000 })).trim();
const parts = countOutput.split(/\s+/);
behind = parseInt(parts[0] || '0', 10);
ahead = parseInt(parts[1] || '0', 10);
} catch {
// no upstream
}
// Get changed files using porcelain v2
const changedFiles: GitChangedFile[] = [];
try {
const statusOutput = await runGit(['status', '--porcelain=v2', '--untracked-files=normal'], { cwd });
for (const line of statusOutput.split('\n')) {
if (!line) continue;
if (line.startsWith('1 ') || line.startsWith('2 ')) {
// Changed entry
const xy = line.substring(2, 4);
const pathPart = line.startsWith('2 ')
? line.split('\t')[1] || line.split(' ').pop() || ''
: line.substring(line.lastIndexOf(' ') + 1);
const indexStatus = xy[0];
const worktreeStatus = xy[1];
if (indexStatus !== '.' && indexStatus !== '?') {
changedFiles.push({
path: pathPart.trim(),
status: parseStatusChar(indexStatus),
staged: true,
});
}
if (worktreeStatus !== '.' && worktreeStatus !== '?') {
changedFiles.push({
path: pathPart.trim(),
status: parseStatusChar(worktreeStatus),
staged: false,
});
}
} else if (line.startsWith('? ')) {
// Untracked
const filePath = line.substring(2);
changedFiles.push({
path: filePath.trim(),
status: 'untracked',
staged: false,
});
}
}
} catch {
// status failed
}
return {
isRepo: true,
repoRoot,
branch,
upstream,
ahead,
behind,
dirty: changedFiles.length > 0,
changedFiles,
};
}
function parseStatusChar(c: string): GitChangedFile['status'] {
switch (c) {
case 'M': return 'modified';
case 'A': return 'added';
case 'D': return 'deleted';
case 'R': return 'renamed';
case 'C': return 'copied';
default: return 'modified';
}
}
export async function getBranches(cwd: string): Promise<GitBranch[]> {
const output = await runGit(
['branch', '-a', '--format=%(refname:short)\t%(upstream:short)\t%(worktreepath)'],
{ cwd }
);
// Get the list of local-only branch names so we can distinguish them from remotes
let localNames: Set<string>;
try {
const localOutput = await runGit(['branch', '--format=%(refname:short)'], { cwd });
localNames = new Set(localOutput.split('\n').map(l => l.trim()).filter(Boolean));
} catch {
localNames = new Set();
}
const branches: GitBranch[] = [];
for (const line of output.split('\n')) {
if (!line.trim()) continue;
const [name, upstream, worktreePath] = line.split('\t');
const trimmedName = name.trim();
// A branch is remote only if it starts with "origin/" (or other remote prefix)
// AND is NOT in the local branch list
const isRemote = !localNames.has(trimmedName) && (trimmedName.startsWith('origin/') || trimmedName.includes('/'));
branches.push({
name: trimmedName,
isRemote,
upstream: upstream?.trim() || '',
worktreePath: worktreePath?.trim() || '',
});
}
return branches;
}
export async function checkout(cwd: string, branch: string): Promise<void> {
// Validate branch name — reject suspicious characters
if (!/^[\w.\-/]+$/.test(branch)) {
throw new Error(`Invalid branch name: ${branch}`);
}
// Check for dirty worktree
const status = await getStatus(cwd);
if (status.dirty) {
throw new Error('Cannot checkout: dirty working tree. Commit or stash changes first.');
}
await runGit(['checkout', branch], { cwd, timeoutMs: 15000 });
}
export async function getLog(cwd: string, limit = 50): Promise<GitLogEntry[]> {
const SEP = '|||';
const format = `%H${SEP}%an${SEP}%ae${SEP}%aI${SEP}%s`;
const output = await runGit(
['log', `--pretty=format:${format}`, `-${limit}`],
{ cwd }
);
const entries: GitLogEntry[] = [];
for (const line of output.split('\n')) {
if (!line.trim()) continue;
const parts = line.split(SEP);
if (parts.length < 5) continue;
entries.push({
sha: parts[0],
authorName: parts[1],
authorEmail: parts[2],
timestamp: parts[3],
message: parts[4],
});
}
return entries;
}
export async function commit(cwd: string, message: string): Promise<string> {
// Stage all changes
await runGit(['add', '-A'], { cwd, timeoutMs: 15000 });
// Check if there are staged changes.
// `git diff --cached --quiet` exits 0 = clean, exits 1 = has staged changes.
// runGit rejects on any non-zero exit. We treat rejection as "has changes".
// If there's a real error (corrupt index, etc.), the subsequent git commit
// will fail with a proper message, so it's safe to proceed optimistically.
try {
await runGit(['diff', '--cached', '--quiet'], { cwd, timeoutMs: 10000 });
// Exit 0 = nothing staged
throw new Error('Nothing to commit');
} catch (err) {
if (err instanceof Error && err.message === 'Nothing to commit') {
throw err;
}
// Exit 1 (has changes) or real error — proceed to commit either way
}
const commitMsg = message.trim() || 'Update';
const output = await runGit(['commit', '-m', commitMsg], { cwd, timeoutMs: 30000 });
// Extract SHA from output
const match = output.match(/\[[\w/.-]+ ([0-9a-f]+)\]/);
return match?.[1] || '';
}
export async function push(cwd: string): Promise<void> {
// Try regular push first
try {
await runGit(['push'], { cwd, timeoutMs: 30000 });
} catch (err) {
// If no upstream, set it
if (err instanceof Error && (err.message.includes('no upstream') || err.message.includes('has no upstream'))) {
const branch = (await runGit(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd, timeoutMs: 5000 })).trim();
await runGit(['push', '-u', 'origin', branch], { cwd, timeoutMs: 30000 });
} else {
throw err;
}
}
}
export async function getCommitDetail(cwd: string, sha: string): Promise<GitCommitDetail> {
// Validate SHA
if (!/^[0-9a-f]{7,40}$/.test(sha)) {
throw new Error(`Invalid SHA: ${sha}`);
}
const SEP = '|||';
const format = `%H${SEP}%an${SEP}%ae${SEP}%aI${SEP}%s`;
const output = await runGit(['show', `--pretty=format:${format}`, '--stat', sha], { cwd });
const lines = output.split('\n');
const headerLine = lines[0];
const parts = headerLine.split(SEP);
// Stats are everything after the header until the diff
const statsLines: string[] = [];
const diffLines: string[] = [];
let inDiff = false;
for (let i = 1; i < lines.length; i++) {
if (lines[i].startsWith('diff --git')) {
inDiff = true;
}
if (inDiff) {
diffLines.push(lines[i]);
} else {
statsLines.push(lines[i]);
}
}
// Get the full diff separately
let diff = '';
try {
diff = await runGit(['show', '--format=', sha], { cwd });
} catch {
diff = diffLines.join('\n');
}
return {
sha: parts[0] || sha,
authorName: parts[1] || '',
authorEmail: parts[2] || '',
timestamp: parts[3] || '',
message: parts[4] || '',
stats: statsLines.join('\n').trim(),
diff,
};
}
export async function getWorktrees(cwd: string): Promise<GitWorktree[]> {
const output = await runGit(['worktree', 'list', '--porcelain'], { cwd });
const worktrees: GitWorktree[] = [];
let current: Partial<GitWorktree> = {};
for (const line of output.split('\n')) {
if (line.startsWith('worktree ')) {
if (current.path) {
worktrees.push({
path: current.path,
head: current.head || '',
branch: current.branch || '',
bare: current.bare || false,
dirty: false, // filled below
});
}
current = { path: line.substring(9) };
} else if (line.startsWith('HEAD ')) {
current.head = line.substring(5);
} else if (line.startsWith('branch ')) {
// Strip refs/heads/ prefix
current.branch = line.substring(7).replace('refs/heads/', '');
} else if (line === 'bare') {
current.bare = true;
}
}
// Don't forget the last entry
if (current.path) {
worktrees.push({
path: current.path,
head: current.head || '',
branch: current.branch || '',
bare: current.bare || false,
dirty: false,
});
}
// Check dirty status for each non-bare worktree
await Promise.all(
worktrees.map(async (wt) => {
if (wt.bare) return;
try {
const statusOutput = await runGit(
['status', '--porcelain', '--untracked-files=no'],
{ cwd: wt.path, timeoutMs: 5000 }
);
wt.dirty = statusOutput.trim().length > 0;
} catch {
// If we can't check, leave as false
}
})
);
return worktrees;
}
export function sanitizeBranchForPath(branch: string): string {
return branch.replace(/[^a-zA-Z0-9._-]/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
}
export async function deriveWorktree(cwd: string, branch: string, targetPath: string): Promise<string> {
// Validate branch name
if (!/^[\w.\-/]+$/.test(branch)) {
throw new Error(`Invalid branch name: ${branch}`);
}
// Create the worktree
await runGit(['worktree', 'add', '-b', branch, targetPath], { cwd, timeoutMs: 30000 });
return targetPath;
}