@leosdc/exploreio 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.
- package/README.md +22 -2
- package/dist/cli.js +12 -3
- package/dist/cli.js.map +1 -1
- package/dist/git/gitService.js +654 -0
- package/dist/git/gitService.js.map +1 -0
- package/dist/git/gitView.js +501 -0
- package/dist/git/gitView.js.map +1 -0
- package/dist/test/exploreio.test.js +42 -0
- package/dist/test/exploreio.test.js.map +1 -1
- package/dist/test/git-panel.test.js +176 -0
- package/dist/test/git-panel.test.js.map +1 -0
- package/dist/tui/app.js +777 -13
- package/dist/tui/app.js.map +1 -1
- package/dist/tui/fullscreenLauncher.js +186 -0
- package/dist/tui/fullscreenLauncher.js.map +1 -0
- package/package.json +2 -2
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exploreio Git & GitHub Service (SPEC-005)
|
|
3
|
+
* Cliente Git local e GitHub CLI (`gh`) seguro usando `execFile` (zero shell interpolation),
|
|
4
|
+
* timeouts explícitos, limites anti-OOM e sanitização anti-ANSI-injection.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import fs from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { promisify } from 'node:util';
|
|
10
|
+
import { stripUnsafeAnsi } from '../tui/ansi.js';
|
|
11
|
+
const execFileAsync = promisify(execFile);
|
|
12
|
+
const GIT_TIMEOUT_MS = 10_000;
|
|
13
|
+
const GIT_NETWORK_TIMEOUT_MS = 25_000;
|
|
14
|
+
const GH_TIMEOUT_MS = 8_000;
|
|
15
|
+
const MAX_EXEC_BUFFER = 1024 * 1024; // 1 MB
|
|
16
|
+
const MAX_PREVIEW_DIFF_LINES = 400;
|
|
17
|
+
async function runBin(bin, args, cwd, timeoutMs = GIT_TIMEOUT_MS) {
|
|
18
|
+
try {
|
|
19
|
+
const { stdout, stderr } = await execFileAsync(bin, [...args], {
|
|
20
|
+
cwd,
|
|
21
|
+
timeout: timeoutMs,
|
|
22
|
+
maxBuffer: MAX_EXEC_BUFFER,
|
|
23
|
+
windowsHide: true,
|
|
24
|
+
env: {
|
|
25
|
+
...process.env,
|
|
26
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
27
|
+
GCM_INTERACTIVE: 'never',
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
return { ok: true, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') };
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
const e = err;
|
|
34
|
+
return {
|
|
35
|
+
ok: false,
|
|
36
|
+
stdout: String(e.stdout ?? ''),
|
|
37
|
+
stderr: String(e.stderr ?? e.message ?? 'Erro ao executar comando'),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Remove credenciais embutidas (user:token@) de URLs remotas antes de exibir na UI. */
|
|
42
|
+
export function sanitizeRemoteUrl(rawUrl) {
|
|
43
|
+
const clean = stripUnsafeAnsi(rawUrl.trim());
|
|
44
|
+
return clean.replace(/(https?:\/\/)([^/@\s]+)@/i, '$1');
|
|
45
|
+
}
|
|
46
|
+
/** Extrai `owner/repo` de URLs remotas do GitHub (HTTPS ou SSH). */
|
|
47
|
+
export function parseGitHubRepoFromUrl(rawUrl) {
|
|
48
|
+
const clean = sanitizeRemoteUrl(rawUrl);
|
|
49
|
+
const httpsMatch = clean.match(/^https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i);
|
|
50
|
+
if (httpsMatch?.[1] && httpsMatch[2]) {
|
|
51
|
+
return `${httpsMatch[1]}/${httpsMatch[2]}`;
|
|
52
|
+
}
|
|
53
|
+
const sshMatch = clean.match(/^(?:ssh:\/\/)?git@github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i);
|
|
54
|
+
if (sshMatch?.[1] && sshMatch[2]) {
|
|
55
|
+
return `${sshMatch[1]}/${sshMatch[2]}`;
|
|
56
|
+
}
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
function statusCodeLabel(code) {
|
|
60
|
+
switch (code) {
|
|
61
|
+
case 'M':
|
|
62
|
+
return 'M';
|
|
63
|
+
case 'A':
|
|
64
|
+
return 'A';
|
|
65
|
+
case 'D':
|
|
66
|
+
return 'D';
|
|
67
|
+
case 'R':
|
|
68
|
+
return 'R';
|
|
69
|
+
case 'C':
|
|
70
|
+
return 'C';
|
|
71
|
+
case 'U':
|
|
72
|
+
return 'U';
|
|
73
|
+
case '?':
|
|
74
|
+
return '?';
|
|
75
|
+
default:
|
|
76
|
+
return code || '·';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Parser puro de `git status --porcelain=v2 --branch`. */
|
|
80
|
+
export function parsePorcelainV2Status(stdout) {
|
|
81
|
+
let branch = '(detached)';
|
|
82
|
+
let upstream = null;
|
|
83
|
+
let ahead = 0;
|
|
84
|
+
let behind = 0;
|
|
85
|
+
const staged = [];
|
|
86
|
+
const unstaged = [];
|
|
87
|
+
const untracked = [];
|
|
88
|
+
const conflicted = [];
|
|
89
|
+
const lines = stdout.split(/\r?\n/);
|
|
90
|
+
for (const line of lines) {
|
|
91
|
+
if (!line)
|
|
92
|
+
continue;
|
|
93
|
+
if (line.startsWith('# branch.head ')) {
|
|
94
|
+
const head = stripUnsafeAnsi(line.slice('# branch.head '.length).trim());
|
|
95
|
+
branch = head === '(detached)' ? 'HEAD (detached)' : head;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (line.startsWith('# branch.upstream ')) {
|
|
99
|
+
upstream = stripUnsafeAnsi(line.slice('# branch.upstream '.length).trim()) || null;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (line.startsWith('# branch.ab ')) {
|
|
103
|
+
const m = line.match(/\+(\d+)\s+-(\d+)/);
|
|
104
|
+
if (m) {
|
|
105
|
+
ahead = Number(m[1] ?? 0);
|
|
106
|
+
behind = Number(m[2] ?? 0);
|
|
107
|
+
}
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (line.startsWith('? ')) {
|
|
111
|
+
const filePath = stripUnsafeAnsi(line.slice(2));
|
|
112
|
+
untracked.push({
|
|
113
|
+
path: filePath,
|
|
114
|
+
indexStatus: '?',
|
|
115
|
+
worktreeStatus: '?',
|
|
116
|
+
section: 'untracked',
|
|
117
|
+
label: '?',
|
|
118
|
+
});
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (line.startsWith('u ')) {
|
|
122
|
+
const parts = line.split(' ');
|
|
123
|
+
const filePath = stripUnsafeAnsi(parts.slice(10).join(' '));
|
|
124
|
+
conflicted.push({
|
|
125
|
+
path: filePath,
|
|
126
|
+
indexStatus: 'U',
|
|
127
|
+
worktreeStatus: 'U',
|
|
128
|
+
section: 'conflicted',
|
|
129
|
+
label: '!',
|
|
130
|
+
});
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
if (line.startsWith('1 ')) {
|
|
134
|
+
const parts = line.split(' ');
|
|
135
|
+
const xy = parts[1] ?? '..';
|
|
136
|
+
const x = xy[0] ?? '.';
|
|
137
|
+
const y = xy[1] ?? '.';
|
|
138
|
+
const filePath = stripUnsafeAnsi(parts.slice(8).join(' '));
|
|
139
|
+
if (x !== '.') {
|
|
140
|
+
staged.push({
|
|
141
|
+
path: filePath,
|
|
142
|
+
indexStatus: x,
|
|
143
|
+
worktreeStatus: y,
|
|
144
|
+
section: 'staged',
|
|
145
|
+
label: statusCodeLabel(x),
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
if (y !== '.') {
|
|
149
|
+
unstaged.push({
|
|
150
|
+
path: filePath,
|
|
151
|
+
indexStatus: x,
|
|
152
|
+
worktreeStatus: y,
|
|
153
|
+
section: 'unstaged',
|
|
154
|
+
label: statusCodeLabel(y),
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (line.startsWith('2 ')) {
|
|
160
|
+
const tabIdx = line.indexOf('\t');
|
|
161
|
+
const left = tabIdx >= 0 ? line.slice(0, tabIdx) : line;
|
|
162
|
+
const origPath = tabIdx >= 0 ? stripUnsafeAnsi(line.slice(tabIdx + 1)) : undefined;
|
|
163
|
+
const parts = left.split(' ');
|
|
164
|
+
const xy = parts[1] ?? '..';
|
|
165
|
+
const x = xy[0] ?? '.';
|
|
166
|
+
const y = xy[1] ?? '.';
|
|
167
|
+
const filePath = stripUnsafeAnsi(parts.slice(9).join(' '));
|
|
168
|
+
if (x !== '.') {
|
|
169
|
+
staged.push({
|
|
170
|
+
path: filePath,
|
|
171
|
+
origPath,
|
|
172
|
+
indexStatus: x,
|
|
173
|
+
worktreeStatus: y,
|
|
174
|
+
section: 'staged',
|
|
175
|
+
label: statusCodeLabel(x),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
if (y !== '.') {
|
|
179
|
+
unstaged.push({
|
|
180
|
+
path: filePath,
|
|
181
|
+
origPath,
|
|
182
|
+
indexStatus: x,
|
|
183
|
+
worktreeStatus: y,
|
|
184
|
+
section: 'unstaged',
|
|
185
|
+
label: statusCodeLabel(y),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
branch,
|
|
192
|
+
upstream,
|
|
193
|
+
ahead,
|
|
194
|
+
behind,
|
|
195
|
+
entries: [...conflicted, ...staged, ...unstaged, ...untracked],
|
|
196
|
+
stagedCount: staged.length,
|
|
197
|
+
unstagedCount: unstaged.length,
|
|
198
|
+
untrackedCount: untracked.length,
|
|
199
|
+
conflictedCount: conflicted.length,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
/** Parser puro da saída de `git log --graph --format=%x1f%h%x1f%H%x1f%D%x1f%an%x1f%ar%x1f%s`. */
|
|
203
|
+
export function parseCommitGraph(stdout, unpushedHashes = new Set()) {
|
|
204
|
+
const rows = [];
|
|
205
|
+
const lines = stdout.split(/\r?\n/);
|
|
206
|
+
for (const rawLine of lines) {
|
|
207
|
+
if (!rawLine.trim())
|
|
208
|
+
continue;
|
|
209
|
+
const sepIdx = rawLine.indexOf('\x1f');
|
|
210
|
+
if (sepIdx === -1) {
|
|
211
|
+
rows.push({
|
|
212
|
+
graphPrefix: stripUnsafeAnsi(rawLine),
|
|
213
|
+
isConnectorOnly: true,
|
|
214
|
+
shortHash: '',
|
|
215
|
+
fullHash: '',
|
|
216
|
+
refs: [],
|
|
217
|
+
author: '',
|
|
218
|
+
relativeDate: '',
|
|
219
|
+
subject: '',
|
|
220
|
+
isUnpushed: false,
|
|
221
|
+
});
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const graphPrefix = stripUnsafeAnsi(rawLine.slice(0, sepIdx));
|
|
225
|
+
const fields = rawLine.slice(sepIdx + 1).split('\x1f');
|
|
226
|
+
const shortHash = stripUnsafeAnsi(fields[0] ?? '');
|
|
227
|
+
const fullHash = stripUnsafeAnsi(fields[1] ?? '');
|
|
228
|
+
const rawRefs = stripUnsafeAnsi(fields[2] ?? '').trim();
|
|
229
|
+
const author = stripUnsafeAnsi(fields[3] ?? '');
|
|
230
|
+
const relativeDate = stripUnsafeAnsi(fields[4] ?? '');
|
|
231
|
+
const subject = stripUnsafeAnsi(fields[5] ?? '');
|
|
232
|
+
const refs = rawRefs
|
|
233
|
+
? rawRefs
|
|
234
|
+
.split(',')
|
|
235
|
+
.map((r) => r.trim())
|
|
236
|
+
.filter(Boolean)
|
|
237
|
+
: [];
|
|
238
|
+
rows.push({
|
|
239
|
+
graphPrefix,
|
|
240
|
+
isConnectorOnly: false,
|
|
241
|
+
shortHash,
|
|
242
|
+
fullHash,
|
|
243
|
+
refs,
|
|
244
|
+
author,
|
|
245
|
+
relativeDate,
|
|
246
|
+
subject,
|
|
247
|
+
isUnpushed: unpushedHashes.has(fullHash) || unpushedHashes.has(shortHash),
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
return rows;
|
|
251
|
+
}
|
|
252
|
+
/** Parser puro de `git branch -a --format=...`. */
|
|
253
|
+
export function parseBranchesOutput(stdout) {
|
|
254
|
+
const branches = [];
|
|
255
|
+
const lines = stdout.split(/\r?\n/);
|
|
256
|
+
for (const line of lines) {
|
|
257
|
+
if (!line.trim())
|
|
258
|
+
continue;
|
|
259
|
+
const parts = line.split('\x1f');
|
|
260
|
+
const headMark = (parts[0] ?? '').trim();
|
|
261
|
+
const name = stripUnsafeAnsi((parts[1] ?? '').trim());
|
|
262
|
+
if (!name || name.endsWith('/HEAD'))
|
|
263
|
+
continue;
|
|
264
|
+
const upstream = stripUnsafeAnsi((parts[2] ?? '').trim());
|
|
265
|
+
const track = stripUnsafeAnsi((parts[3] ?? '').trim());
|
|
266
|
+
const relativeDate = stripUnsafeAnsi((parts[4] ?? '').trim());
|
|
267
|
+
const subject = stripUnsafeAnsi((parts[5] ?? '').trim());
|
|
268
|
+
const isRemote = name.startsWith('origin/') || name.startsWith('upstream/') || name.includes('remotes/');
|
|
269
|
+
branches.push({
|
|
270
|
+
name,
|
|
271
|
+
isCurrent: headMark === '*',
|
|
272
|
+
isRemote,
|
|
273
|
+
upstream,
|
|
274
|
+
track,
|
|
275
|
+
relativeDate,
|
|
276
|
+
subject,
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
return branches;
|
|
280
|
+
}
|
|
281
|
+
/** Resumo ultrarrápido para o badge discreto no cabeçalho do Navegador. */
|
|
282
|
+
export async function getGitSummaryBadge(cwd) {
|
|
283
|
+
const rootRes = await runBin('git', ['rev-parse', '--show-toplevel'], cwd, 3000);
|
|
284
|
+
if (!rootRes.ok)
|
|
285
|
+
return null;
|
|
286
|
+
const repoRoot = rootRes.stdout.trim();
|
|
287
|
+
if (!repoRoot)
|
|
288
|
+
return null;
|
|
289
|
+
const statusRes = await runBin('git', ['status', '--porcelain=v2', '--branch'], repoRoot, 4000);
|
|
290
|
+
if (!statusRes.ok)
|
|
291
|
+
return null;
|
|
292
|
+
const parsed = parsePorcelainV2Status(statusRes.stdout);
|
|
293
|
+
const dirtyCount = parsed.stagedCount + parsed.unstagedCount + parsed.untrackedCount + parsed.conflictedCount;
|
|
294
|
+
return {
|
|
295
|
+
repoRoot,
|
|
296
|
+
branch: parsed.branch,
|
|
297
|
+
upstream: parsed.upstream,
|
|
298
|
+
ahead: parsed.ahead,
|
|
299
|
+
behind: parsed.behind,
|
|
300
|
+
stagedCount: parsed.stagedCount,
|
|
301
|
+
unstagedCount: parsed.unstagedCount,
|
|
302
|
+
untrackedCount: parsed.untrackedCount,
|
|
303
|
+
dirtyCount,
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
/** Carrega snapshot completo local do repositório Git (status, commits parados, árvore e branches). */
|
|
307
|
+
export async function loadGitPanelSnapshot(cwd) {
|
|
308
|
+
const emptyStatus = {
|
|
309
|
+
branch: '',
|
|
310
|
+
upstream: null,
|
|
311
|
+
ahead: 0,
|
|
312
|
+
behind: 0,
|
|
313
|
+
entries: [],
|
|
314
|
+
stagedCount: 0,
|
|
315
|
+
unstagedCount: 0,
|
|
316
|
+
untrackedCount: 0,
|
|
317
|
+
conflictedCount: 0,
|
|
318
|
+
};
|
|
319
|
+
const rootRes = await runBin('git', ['rev-parse', '--show-toplevel'], cwd, 4000);
|
|
320
|
+
if (!rootRes.ok || !rootRes.stdout.trim()) {
|
|
321
|
+
return {
|
|
322
|
+
isGitRepo: false,
|
|
323
|
+
repoRoot: cwd,
|
|
324
|
+
repoName: path.basename(cwd),
|
|
325
|
+
remoteUrl: null,
|
|
326
|
+
githubRepo: null,
|
|
327
|
+
status: emptyStatus,
|
|
328
|
+
unpushedCommits: [],
|
|
329
|
+
commitGraph: [],
|
|
330
|
+
branches: [],
|
|
331
|
+
stashCount: 0,
|
|
332
|
+
error: 'O diretório atual não pertence a um repositório Git.',
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
const repoRoot = rootRes.stdout.trim();
|
|
336
|
+
const repoName = path.basename(repoRoot);
|
|
337
|
+
const [statusRes, remoteRes, graphRes, branchRes, stashRes] = await Promise.all([
|
|
338
|
+
runBin('git', ['status', '--porcelain=v2', '--branch'], repoRoot),
|
|
339
|
+
runBin('git', ['remote', 'get-url', 'origin'], repoRoot),
|
|
340
|
+
runBin('git', [
|
|
341
|
+
'log',
|
|
342
|
+
'--graph',
|
|
343
|
+
'--decorate=short',
|
|
344
|
+
'--all',
|
|
345
|
+
'--color=never',
|
|
346
|
+
'-n',
|
|
347
|
+
'80',
|
|
348
|
+
'--format=%x1f%h%x1f%H%x1f%D%x1f%an%x1f%ar%x1f%s',
|
|
349
|
+
], repoRoot),
|
|
350
|
+
runBin('git', [
|
|
351
|
+
'branch',
|
|
352
|
+
'-a',
|
|
353
|
+
'--sort=-committerdate',
|
|
354
|
+
'--format=%(HEAD)%x1f%(refname:short)%x1f%(upstream:short)%x1f%(upstream:track)%x1f%(committerdate:relative)%x1f%(subject)',
|
|
355
|
+
], repoRoot),
|
|
356
|
+
runBin('git', ['stash', 'list'], repoRoot),
|
|
357
|
+
]);
|
|
358
|
+
const status = statusRes.ok ? parsePorcelainV2Status(statusRes.stdout) : emptyStatus;
|
|
359
|
+
const remoteUrl = remoteRes.ok && remoteRes.stdout.trim() ? sanitizeRemoteUrl(remoteRes.stdout) : null;
|
|
360
|
+
const githubRepo = remoteUrl ? parseGitHubRepoFromUrl(remoteUrl) : null;
|
|
361
|
+
// Commits parados (locais ainda não enviados ao remoto)
|
|
362
|
+
const unpushedArgs = status.upstream
|
|
363
|
+
? ['log', '@{u}..HEAD', '-n', '30', '--format=%h%x1f%H%x1f%ar%x1f%an%x1f%s']
|
|
364
|
+
: ['log', 'HEAD', '--not', '--remotes', '-n', '30', '--format=%h%x1f%H%x1f%ar%x1f%an%x1f%s'];
|
|
365
|
+
const unpushedRes = await runBin('git', unpushedArgs, repoRoot);
|
|
366
|
+
const unpushedCommits = [];
|
|
367
|
+
const unpushedHashes = new Set();
|
|
368
|
+
if (unpushedRes.ok && unpushedRes.stdout.trim()) {
|
|
369
|
+
for (const line of unpushedRes.stdout.split(/\r?\n/)) {
|
|
370
|
+
if (!line.trim())
|
|
371
|
+
continue;
|
|
372
|
+
const [shortHash = '', fullHash = '', relativeDate = '', author = '', subject = ''] = line.split('\x1f');
|
|
373
|
+
if (shortHash) {
|
|
374
|
+
unpushedCommits.push({
|
|
375
|
+
shortHash: stripUnsafeAnsi(shortHash),
|
|
376
|
+
fullHash: stripUnsafeAnsi(fullHash),
|
|
377
|
+
relativeDate: stripUnsafeAnsi(relativeDate),
|
|
378
|
+
author: stripUnsafeAnsi(author),
|
|
379
|
+
subject: stripUnsafeAnsi(subject),
|
|
380
|
+
});
|
|
381
|
+
unpushedHashes.add(shortHash);
|
|
382
|
+
if (fullHash)
|
|
383
|
+
unpushedHashes.add(fullHash);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const commitGraph = graphRes.ok ? parseCommitGraph(graphRes.stdout, unpushedHashes) : [];
|
|
388
|
+
const branches = branchRes.ok ? parseBranchesOutput(branchRes.stdout) : [];
|
|
389
|
+
const stashCount = stashRes.ok
|
|
390
|
+
? stashRes.stdout
|
|
391
|
+
.split(/\r?\n/)
|
|
392
|
+
.map((l) => l.trim())
|
|
393
|
+
.filter(Boolean).length
|
|
394
|
+
: 0;
|
|
395
|
+
return {
|
|
396
|
+
isGitRepo: true,
|
|
397
|
+
repoRoot,
|
|
398
|
+
repoName,
|
|
399
|
+
remoteUrl,
|
|
400
|
+
githubRepo,
|
|
401
|
+
status,
|
|
402
|
+
unpushedCommits,
|
|
403
|
+
commitGraph,
|
|
404
|
+
branches,
|
|
405
|
+
stashCount,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/** Carrega PRs, Issues e Workflow Runs do GitHub via `gh` CLI com degradação graciosa. */
|
|
409
|
+
export async function loadGitHubData(repoRoot, githubRepo) {
|
|
410
|
+
if (!githubRepo) {
|
|
411
|
+
return {
|
|
412
|
+
available: false,
|
|
413
|
+
loading: false,
|
|
414
|
+
repoSlug: null,
|
|
415
|
+
reason: 'Nenhum remote GitHub (origin) detectado neste repositório.',
|
|
416
|
+
pullRequests: [],
|
|
417
|
+
issues: [],
|
|
418
|
+
workflowRuns: [],
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
const authRes = await runBin('gh', ['auth', 'status'], repoRoot, 5000);
|
|
422
|
+
if (!authRes.ok) {
|
|
423
|
+
const missingGh = /ENOENT|not recognized|not found/i.test(authRes.stderr);
|
|
424
|
+
return {
|
|
425
|
+
available: false,
|
|
426
|
+
loading: false,
|
|
427
|
+
repoSlug: githubRepo,
|
|
428
|
+
reason: missingGh
|
|
429
|
+
? 'GitHub CLI (`gh`) não encontrada no PATH. Instale em https://cli.github.com'
|
|
430
|
+
: 'GitHub CLI (`gh`) não autenticada. Execute `gh auth login` no terminal.',
|
|
431
|
+
pullRequests: [],
|
|
432
|
+
issues: [],
|
|
433
|
+
workflowRuns: [],
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
const [prRes, issueRes, runRes] = await Promise.all([
|
|
437
|
+
runBin('gh', [
|
|
438
|
+
'pr',
|
|
439
|
+
'list',
|
|
440
|
+
'--repo',
|
|
441
|
+
githubRepo,
|
|
442
|
+
'--state',
|
|
443
|
+
'open',
|
|
444
|
+
'--limit',
|
|
445
|
+
'15',
|
|
446
|
+
'--json',
|
|
447
|
+
'number,title,author,headRefName,baseRefName,isDraft,reviewDecision,updatedAt,url',
|
|
448
|
+
], repoRoot, GH_TIMEOUT_MS),
|
|
449
|
+
runBin('gh', [
|
|
450
|
+
'issue',
|
|
451
|
+
'list',
|
|
452
|
+
'--repo',
|
|
453
|
+
githubRepo,
|
|
454
|
+
'--state',
|
|
455
|
+
'open',
|
|
456
|
+
'--limit',
|
|
457
|
+
'15',
|
|
458
|
+
'--json',
|
|
459
|
+
'number,title,author,labels,updatedAt,url',
|
|
460
|
+
], repoRoot, GH_TIMEOUT_MS),
|
|
461
|
+
runBin('gh', [
|
|
462
|
+
'run',
|
|
463
|
+
'list',
|
|
464
|
+
'--repo',
|
|
465
|
+
githubRepo,
|
|
466
|
+
'--limit',
|
|
467
|
+
'8',
|
|
468
|
+
'--json',
|
|
469
|
+
'databaseId,displayTitle,workflowName,headBranch,status,conclusion,updatedAt,url',
|
|
470
|
+
], repoRoot, GH_TIMEOUT_MS),
|
|
471
|
+
]);
|
|
472
|
+
const pullRequests = safeParseJsonArray(prRes.ok ? prRes.stdout : '').map((raw) => ({
|
|
473
|
+
number: Number(raw.number ?? 0),
|
|
474
|
+
title: stripUnsafeAnsi(String(raw.title ?? '')),
|
|
475
|
+
author: stripUnsafeAnsi(String(raw.author?.login ?? 'unknown')),
|
|
476
|
+
headRefName: stripUnsafeAnsi(String(raw.headRefName ?? '')),
|
|
477
|
+
baseRefName: stripUnsafeAnsi(String(raw.baseRefName ?? '')),
|
|
478
|
+
isDraft: Boolean(raw.isDraft),
|
|
479
|
+
reviewDecision: stripUnsafeAnsi(String(raw.reviewDecision ?? '')),
|
|
480
|
+
updatedAt: stripUnsafeAnsi(String(raw.updatedAt ?? '')),
|
|
481
|
+
url: stripUnsafeAnsi(String(raw.url ?? '')),
|
|
482
|
+
}));
|
|
483
|
+
const issues = safeParseJsonArray(issueRes.ok ? issueRes.stdout : '').map((raw) => ({
|
|
484
|
+
number: Number(raw.number ?? 0),
|
|
485
|
+
title: stripUnsafeAnsi(String(raw.title ?? '')),
|
|
486
|
+
author: stripUnsafeAnsi(String(raw.author?.login ?? 'unknown')),
|
|
487
|
+
labels: Array.isArray(raw.labels)
|
|
488
|
+
? raw.labels
|
|
489
|
+
.map((l) => stripUnsafeAnsi(String(l?.name ?? '')))
|
|
490
|
+
.filter(Boolean)
|
|
491
|
+
: [],
|
|
492
|
+
updatedAt: stripUnsafeAnsi(String(raw.updatedAt ?? '')),
|
|
493
|
+
url: stripUnsafeAnsi(String(raw.url ?? '')),
|
|
494
|
+
}));
|
|
495
|
+
const workflowRuns = safeParseJsonArray(runRes.ok ? runRes.stdout : '').map((raw) => ({
|
|
496
|
+
id: Number(raw.databaseId ?? 0),
|
|
497
|
+
title: stripUnsafeAnsi(String(raw.displayTitle ?? '')),
|
|
498
|
+
workflowName: stripUnsafeAnsi(String(raw.workflowName ?? '')),
|
|
499
|
+
branch: stripUnsafeAnsi(String(raw.headBranch ?? '')),
|
|
500
|
+
status: stripUnsafeAnsi(String(raw.status ?? '')),
|
|
501
|
+
conclusion: stripUnsafeAnsi(String(raw.conclusion ?? '')),
|
|
502
|
+
updatedAt: stripUnsafeAnsi(String(raw.updatedAt ?? '')),
|
|
503
|
+
url: stripUnsafeAnsi(String(raw.url ?? '')),
|
|
504
|
+
}));
|
|
505
|
+
return {
|
|
506
|
+
available: true,
|
|
507
|
+
loading: false,
|
|
508
|
+
repoSlug: githubRepo,
|
|
509
|
+
pullRequests,
|
|
510
|
+
issues,
|
|
511
|
+
workflowRuns,
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function safeParseJsonArray(raw) {
|
|
515
|
+
if (!raw.trim())
|
|
516
|
+
return [];
|
|
517
|
+
try {
|
|
518
|
+
const parsed = JSON.parse(raw);
|
|
519
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
520
|
+
}
|
|
521
|
+
catch {
|
|
522
|
+
return [];
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/** Carrega diff sanitizado de um arquivo em Status (staged, unstaged ou untracked). */
|
|
526
|
+
export async function loadFileDiff(repoRoot, entry) {
|
|
527
|
+
if (entry.section === 'untracked') {
|
|
528
|
+
const absPath = path.resolve(repoRoot, entry.path);
|
|
529
|
+
try {
|
|
530
|
+
const stat = await fs.stat(absPath);
|
|
531
|
+
if (stat.isDirectory()) {
|
|
532
|
+
return [`[Diretório não rastreado: ${stripUnsafeAnsi(entry.path)}]`];
|
|
533
|
+
}
|
|
534
|
+
if (stat.size > 256 * 1024) {
|
|
535
|
+
return [`[Arquivo novo grande (${Math.round(stat.size / 1024)} KB) — abra no Leitor para inspecionar]`];
|
|
536
|
+
}
|
|
537
|
+
const buf = await fs.readFile(absPath);
|
|
538
|
+
if (buf.subarray(0, 1024).includes(0)) {
|
|
539
|
+
return [`[Arquivo binário não rastreado: ${stripUnsafeAnsi(entry.path)}]`];
|
|
540
|
+
}
|
|
541
|
+
const lines = buf.toString('utf8').split(/\r?\n/).slice(0, MAX_PREVIEW_DIFF_LINES);
|
|
542
|
+
return [
|
|
543
|
+
`--- /dev/null`,
|
|
544
|
+
`+++ b/${stripUnsafeAnsi(entry.path)}`,
|
|
545
|
+
`@@ -0,0 +1,${lines.length} @@ (arquivo novo)`,
|
|
546
|
+
...lines.map((l) => `+${stripUnsafeAnsi(l)}`),
|
|
547
|
+
];
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return [`[Não foi possível ler ${stripUnsafeAnsi(entry.path)}]`];
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
const args = entry.section === 'staged'
|
|
554
|
+
? ['diff', '--cached', '--no-color', '--', entry.path]
|
|
555
|
+
: ['diff', '--no-color', '--', entry.path];
|
|
556
|
+
const res = await runBin('git', args, repoRoot);
|
|
557
|
+
if (!res.ok) {
|
|
558
|
+
return [`Erro ao gerar diff: ${stripUnsafeAnsi(res.stderr.trim())}`];
|
|
559
|
+
}
|
|
560
|
+
if (!res.stdout.trim()) {
|
|
561
|
+
return ['(sem alterações textuais visíveis no diff)'];
|
|
562
|
+
}
|
|
563
|
+
return res.stdout
|
|
564
|
+
.split(/\r?\n/)
|
|
565
|
+
.slice(0, MAX_PREVIEW_DIFF_LINES)
|
|
566
|
+
.map((l) => stripUnsafeAnsi(l));
|
|
567
|
+
}
|
|
568
|
+
/** Carrega detalhes (`git show --stat --patch`) de um commit específico. */
|
|
569
|
+
export async function loadCommitDetails(repoRoot, hash) {
|
|
570
|
+
const safeHash = hash.trim();
|
|
571
|
+
if (!/^[0-9a-fA-F]{4,40}$/.test(safeHash)) {
|
|
572
|
+
return ['Hash de commit inválido.'];
|
|
573
|
+
}
|
|
574
|
+
const res = await runBin('git', ['show', '--stat', '--patch', '--color=never', safeHash], repoRoot);
|
|
575
|
+
if (!res.ok) {
|
|
576
|
+
return [`Erro ao inspecionar commit ${safeHash}: ${stripUnsafeAnsi(res.stderr.trim())}`];
|
|
577
|
+
}
|
|
578
|
+
return res.stdout
|
|
579
|
+
.split(/\r?\n/)
|
|
580
|
+
.slice(0, MAX_PREVIEW_DIFF_LINES)
|
|
581
|
+
.map((l) => stripUnsafeAnsi(l));
|
|
582
|
+
}
|
|
583
|
+
function toCommandResult(res) {
|
|
584
|
+
const errLine = stripUnsafeAnsi((res.stderr || res.stdout).trim().split(/\r?\n/)[0] ?? '');
|
|
585
|
+
return {
|
|
586
|
+
ok: res.ok,
|
|
587
|
+
stdout: stripUnsafeAnsi(res.stdout),
|
|
588
|
+
stderr: stripUnsafeAnsi(res.stderr),
|
|
589
|
+
errorMessage: res.ok ? undefined : errLine || 'Falha ao executar operação Git.',
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
export async function gitStageFile(repoRoot, filePath) {
|
|
593
|
+
return toCommandResult(await runBin('git', ['add', '--', filePath], repoRoot));
|
|
594
|
+
}
|
|
595
|
+
export async function gitUnstageFile(repoRoot, filePath) {
|
|
596
|
+
const res = await runBin('git', ['restore', '--staged', '--', filePath], repoRoot);
|
|
597
|
+
if (res.ok)
|
|
598
|
+
return toCommandResult(res);
|
|
599
|
+
// Fallback para repositórios sem commit inicial (unborn HEAD)
|
|
600
|
+
return toCommandResult(await runBin('git', ['rm', '--cached', '--', filePath], repoRoot));
|
|
601
|
+
}
|
|
602
|
+
export async function gitStageAll(repoRoot) {
|
|
603
|
+
return toCommandResult(await runBin('git', ['add', '-A'], repoRoot));
|
|
604
|
+
}
|
|
605
|
+
export async function gitUnstageAll(repoRoot) {
|
|
606
|
+
return toCommandResult(await runBin('git', ['reset', 'HEAD'], repoRoot));
|
|
607
|
+
}
|
|
608
|
+
export async function gitCommit(repoRoot, message) {
|
|
609
|
+
const cleanMsg = message.trim();
|
|
610
|
+
if (!cleanMsg) {
|
|
611
|
+
return { ok: false, stdout: '', stderr: '', errorMessage: 'Mensagem de commit vazia.' };
|
|
612
|
+
}
|
|
613
|
+
return toCommandResult(await runBin('git', ['commit', '-m', cleanMsg], repoRoot));
|
|
614
|
+
}
|
|
615
|
+
export async function gitPull(repoRoot) {
|
|
616
|
+
return toCommandResult(await runBin('git', ['pull', '--ff-only'], repoRoot, GIT_NETWORK_TIMEOUT_MS));
|
|
617
|
+
}
|
|
618
|
+
export async function gitPush(repoRoot, branchWithoutUpstream) {
|
|
619
|
+
const args = branchWithoutUpstream
|
|
620
|
+
? ['push', '-u', 'origin', branchWithoutUpstream]
|
|
621
|
+
: ['push'];
|
|
622
|
+
return toCommandResult(await runBin('git', args, repoRoot, GIT_NETWORK_TIMEOUT_MS));
|
|
623
|
+
}
|
|
624
|
+
export async function gitFetch(repoRoot) {
|
|
625
|
+
return toCommandResult(await runBin('git', ['fetch', '--all', '--prune'], repoRoot, GIT_NETWORK_TIMEOUT_MS));
|
|
626
|
+
}
|
|
627
|
+
export async function gitCheckoutBranch(repoRoot, branchName) {
|
|
628
|
+
const clean = branchName.trim();
|
|
629
|
+
if (!clean || clean.startsWith('-')) {
|
|
630
|
+
return { ok: false, stdout: '', stderr: '', errorMessage: 'Nome de branch inválido.' };
|
|
631
|
+
}
|
|
632
|
+
const target = clean.startsWith('origin/') ? clean.slice('origin/'.length) : clean;
|
|
633
|
+
return toCommandResult(await runBin('git', ['checkout', target], repoRoot));
|
|
634
|
+
}
|
|
635
|
+
export async function gitCreateBranch(repoRoot, newBranchName) {
|
|
636
|
+
const clean = newBranchName.trim();
|
|
637
|
+
if (!clean || clean.startsWith('-') || /\s/.test(clean)) {
|
|
638
|
+
return { ok: false, stdout: '', stderr: '', errorMessage: 'Nome de branch inválido (sem espaços).' };
|
|
639
|
+
}
|
|
640
|
+
return toCommandResult(await runBin('git', ['checkout', '-b', clean], repoRoot));
|
|
641
|
+
}
|
|
642
|
+
export async function gitStashPush(repoRoot) {
|
|
643
|
+
return toCommandResult(await runBin('git', ['stash', 'push', '-u'], repoRoot));
|
|
644
|
+
}
|
|
645
|
+
export async function gitStashPop(repoRoot) {
|
|
646
|
+
return toCommandResult(await runBin('git', ['stash', 'pop'], repoRoot));
|
|
647
|
+
}
|
|
648
|
+
export async function gitDiscardFile(repoRoot, entry) {
|
|
649
|
+
if (entry.section === 'untracked') {
|
|
650
|
+
return toCommandResult(await runBin('git', ['clean', '-f', '--', entry.path], repoRoot));
|
|
651
|
+
}
|
|
652
|
+
return toCommandResult(await runBin('git', ['checkout', '--', entry.path], repoRoot));
|
|
653
|
+
}
|
|
654
|
+
//# sourceMappingURL=gitService.js.map
|