deepseek-harness-git 0.0.0-stage → 1.0.1
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/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +257 -2
- package/client.js +2991 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +10 -0
- package/index.js +1523 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +74 -4
package/index.js
ADDED
|
@@ -0,0 +1,1523 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git — host half.
|
|
3
|
+
*
|
|
4
|
+
* Runs the local `git` executable for one registered Workspace at a time and
|
|
5
|
+
* publishes the result over one authenticated exact Fetch route on Connection's
|
|
6
|
+
* shared `/api` channel. The browser half (`./client`) owns the panel; this half
|
|
7
|
+
* owns argument construction, path admission, and output parsing.
|
|
8
|
+
*
|
|
9
|
+
* Design notes:
|
|
10
|
+
* - Every request names its Workspace directory. `admit()` only accepts the
|
|
11
|
+
* exact canonical paths the Workspace registry (or the default working
|
|
12
|
+
* directory) publishes, so the route cannot be used as an arbitrary-cwd shell.
|
|
13
|
+
* - Commands are spawned with `execFile` and an argv array — never a shell — and
|
|
14
|
+
* every user-supplied path travels after `--`.
|
|
15
|
+
* - Reads use `GIT_OPTIONAL_LOCKS=0`; network verbs get a longer bound and
|
|
16
|
+
* `GIT_TERMINAL_PROMPT=0` so a missing credential fails instead of hanging.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { execFile } from 'node:child_process'
|
|
20
|
+
import { promises as fs } from 'node:fs'
|
|
21
|
+
import path from 'node:path'
|
|
22
|
+
|
|
23
|
+
/** Exact route the browser half calls. Connection owns the `/api` prefix. */
|
|
24
|
+
const ROUTE_PATH = '/api/dsh-git'
|
|
25
|
+
/** Bound for a read-only git verb. */
|
|
26
|
+
const READ_TIMEOUT_MS = 60_000
|
|
27
|
+
/** Bound for a verb that may talk to a remote. */
|
|
28
|
+
const NETWORK_TIMEOUT_MS = 120_000
|
|
29
|
+
/** Upper bound for one patch handed to the browser. */
|
|
30
|
+
const MAX_DIFF_LINES = 6_000
|
|
31
|
+
/** A larger untracked file is reported as binary instead of read. */
|
|
32
|
+
const MAX_FILE_BYTES = 1024 * 1024
|
|
33
|
+
/** Truncated command output kept for a notice or an error. */
|
|
34
|
+
const MAX_MESSAGE_CHARS = 4_000
|
|
35
|
+
/** Guards the number of pathspecs one request may carry. */
|
|
36
|
+
const MAX_PATHS = 200
|
|
37
|
+
/** Bound for one AI commit-message request. */
|
|
38
|
+
const MESSAGE_TIMEOUT_MS = 90_000
|
|
39
|
+
/** Character budget for the prompt input. */
|
|
40
|
+
const MESSAGE_MAX_INPUT_CHARS = 24_000
|
|
41
|
+
/** Output cap for one commit message. */
|
|
42
|
+
const MESSAGE_MAX_OUTPUT_TOKENS = 320
|
|
43
|
+
/** Untracked files quoted to the model when no diff exists. */
|
|
44
|
+
const MESSAGE_MAX_UNTRACKED_FILES = 5
|
|
45
|
+
/** Bytes quoted from one untracked file. */
|
|
46
|
+
const MESSAGE_MAX_UNTRACKED_BYTES = 4_096
|
|
47
|
+
|
|
48
|
+
const NO_STORE = { 'cache-control': 'no-store' }
|
|
49
|
+
|
|
50
|
+
/** A failure the browser half can show verbatim. */
|
|
51
|
+
export class GitPanelError extends Error {
|
|
52
|
+
constructor(code, message) {
|
|
53
|
+
super(message)
|
|
54
|
+
this.name = 'GitPanelError'
|
|
55
|
+
this.code = code
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Collapse command output to one bounded, trimmed message. */
|
|
60
|
+
function clean(value) {
|
|
61
|
+
return String(value ?? '')
|
|
62
|
+
.replace(/\r\n/g, '\n')
|
|
63
|
+
.replace(/^\n+|\n+$/g, '')
|
|
64
|
+
.slice(0, MAX_MESSAGE_CHARS)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isWindows() {
|
|
68
|
+
return process.platform === 'win32'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Compare two absolute paths with the platform's case rules. */
|
|
72
|
+
function samePath(left, right) {
|
|
73
|
+
const a = path.resolve(String(left))
|
|
74
|
+
const b = path.resolve(String(right))
|
|
75
|
+
return isWindows() ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Validate one repository-relative path.
|
|
80
|
+
*
|
|
81
|
+
* Git pathspecs are relative to the repository root. Rejecting absolute paths
|
|
82
|
+
* and `..` segments keeps a request inside the admitted Workspace even though
|
|
83
|
+
* git itself would accept a wider pathspec.
|
|
84
|
+
*/
|
|
85
|
+
function normalizeRelPath(input) {
|
|
86
|
+
if (typeof input !== 'string' || input.trim() === '') {
|
|
87
|
+
throw new GitPanelError('git/bad-path', 'A file path is required.')
|
|
88
|
+
}
|
|
89
|
+
const raw = input.replace(/\\/g, '/')
|
|
90
|
+
if (raw.startsWith('/') || /^[A-Za-z]:\//.test(raw)) {
|
|
91
|
+
throw new GitPanelError('git/bad-path', 'File paths must be relative to the repository root.')
|
|
92
|
+
}
|
|
93
|
+
const parts = raw.split('/').filter((part) => part !== '' && part !== '.')
|
|
94
|
+
if (parts.length === 0 || parts.includes('..')) {
|
|
95
|
+
throw new GitPanelError('git/bad-path', 'File paths must stay inside the repository.')
|
|
96
|
+
}
|
|
97
|
+
return parts.join('/')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function normalizePaths(input) {
|
|
101
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
102
|
+
throw new GitPanelError('git/bad-path', 'At least one file path is required.')
|
|
103
|
+
}
|
|
104
|
+
return [...new Set(input.map(normalizeRelPath))].slice(0, MAX_PATHS)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Validate one remote name before it reaches argv. */
|
|
108
|
+
function normalizeRemote(input) {
|
|
109
|
+
if (typeof input !== 'string') {
|
|
110
|
+
throw new GitPanelError('git/bad-remote', 'A remote name is required.')
|
|
111
|
+
}
|
|
112
|
+
const name = input.trim()
|
|
113
|
+
if (
|
|
114
|
+
name === ''
|
|
115
|
+
|| name.startsWith('-')
|
|
116
|
+
|| name.includes('..')
|
|
117
|
+
|| /[\s~^:?*[\\\x00-\x1f\x7f]/.test(name)
|
|
118
|
+
) {
|
|
119
|
+
throw new GitPanelError('git/bad-remote', 'That is not a valid remote name.')
|
|
120
|
+
}
|
|
121
|
+
return name
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Validate one remote URL before it reaches argv. */
|
|
125
|
+
function normalizeRemoteUrl(input) {
|
|
126
|
+
if (typeof input !== 'string') {
|
|
127
|
+
throw new GitPanelError('git/bad-remote-url', 'A remote URL is required.')
|
|
128
|
+
}
|
|
129
|
+
const url = input.trim()
|
|
130
|
+
if (
|
|
131
|
+
url === ''
|
|
132
|
+
|| url.length > 2048
|
|
133
|
+
|| url.startsWith('-')
|
|
134
|
+
|| /[\x00-\x1f\x7f]/.test(url)
|
|
135
|
+
) {
|
|
136
|
+
throw new GitPanelError('git/bad-remote-url', 'That is not a valid remote URL.')
|
|
137
|
+
}
|
|
138
|
+
return url
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Validate one local branch name before it reaches argv. */
|
|
142
|
+
function normalizeBranch(input) {
|
|
143
|
+
if (typeof input !== 'string') {
|
|
144
|
+
throw new GitPanelError('git/bad-branch', 'A branch name is required.')
|
|
145
|
+
}
|
|
146
|
+
const name = input.trim()
|
|
147
|
+
if (
|
|
148
|
+
name === ''
|
|
149
|
+
|| name.startsWith('-')
|
|
150
|
+
|| name.startsWith('/')
|
|
151
|
+
|| name.endsWith('/')
|
|
152
|
+
|| name.endsWith('.')
|
|
153
|
+
|| name.includes('..')
|
|
154
|
+
|| name.includes('@{')
|
|
155
|
+
|| name.includes('//')
|
|
156
|
+
|| /[\s~^:?*[\\\x00-\x1f\x7f]/.test(name)
|
|
157
|
+
|| name.split('/').some((part) => part === '' || part === '.' || part === '..' || part.endsWith('.lock'))
|
|
158
|
+
) {
|
|
159
|
+
throw new GitPanelError('git/bad-branch', 'That is not a valid branch name.')
|
|
160
|
+
}
|
|
161
|
+
return name
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Run one git command without a shell.
|
|
166
|
+
*
|
|
167
|
+
* @returns `{ ok: true, stdout, stderr }` or a classified failure.
|
|
168
|
+
*/
|
|
169
|
+
function runGit(gitPath, cwd, args, timeoutMs = READ_TIMEOUT_MS) {
|
|
170
|
+
return new Promise((resolve) => {
|
|
171
|
+
let settled = false
|
|
172
|
+
const finish = (result) => {
|
|
173
|
+
if (settled) return
|
|
174
|
+
settled = true
|
|
175
|
+
resolve(result)
|
|
176
|
+
}
|
|
177
|
+
const command = ['--no-pager', '-c', 'core.quotepath=false', '-c', 'color.ui=false', ...args]
|
|
178
|
+
try {
|
|
179
|
+
const child = execFile(gitPath, command, {
|
|
180
|
+
cwd,
|
|
181
|
+
timeout: timeoutMs,
|
|
182
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
183
|
+
windowsHide: true,
|
|
184
|
+
encoding: 'utf8',
|
|
185
|
+
env: {
|
|
186
|
+
...process.env,
|
|
187
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
188
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
189
|
+
GIT_PAGER: 'cat',
|
|
190
|
+
PAGER: 'cat',
|
|
191
|
+
GIT_EDITOR: 'true',
|
|
192
|
+
EDITOR: 'true',
|
|
193
|
+
},
|
|
194
|
+
}, (error, stdout, stderr) => {
|
|
195
|
+
if (error) {
|
|
196
|
+
const missing = error.code === 'ENOENT' || /ENOENT/.test(String(error.message))
|
|
197
|
+
const killed = Boolean(error.killed || error.signal)
|
|
198
|
+
const message = missing
|
|
199
|
+
? 'Git was not found. Install Git and make sure it is on PATH.'
|
|
200
|
+
: killed
|
|
201
|
+
? `Git did not finish within ${Math.round(timeoutMs / 1000)} seconds.`
|
|
202
|
+
: clean(stderr) || clean(error.message) || 'Git failed.'
|
|
203
|
+
finish({
|
|
204
|
+
ok: false,
|
|
205
|
+
missing,
|
|
206
|
+
message,
|
|
207
|
+
stdout: String(stdout ?? ''),
|
|
208
|
+
stderr: String(stderr ?? ''),
|
|
209
|
+
})
|
|
210
|
+
return
|
|
211
|
+
}
|
|
212
|
+
finish({ ok: true, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
|
|
213
|
+
})
|
|
214
|
+
child.on('error', (error) => {
|
|
215
|
+
finish({
|
|
216
|
+
ok: false,
|
|
217
|
+
missing: error.code === 'ENOENT',
|
|
218
|
+
message: clean(error.message),
|
|
219
|
+
stdout: '',
|
|
220
|
+
stderr: '',
|
|
221
|
+
})
|
|
222
|
+
})
|
|
223
|
+
} catch (error) {
|
|
224
|
+
finish({ ok: false, missing: false, message: clean(error?.message ?? error), stdout: '', stderr: '' })
|
|
225
|
+
}
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async function mustGit(gitPath, cwd, args, timeoutMs) {
|
|
230
|
+
const result = await runGit(gitPath, cwd, args, timeoutMs)
|
|
231
|
+
if (!result.ok) {
|
|
232
|
+
throw new GitPanelError(result.missing ? 'git/missing' : 'git/command-failed', result.message)
|
|
233
|
+
}
|
|
234
|
+
return result.stdout
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The repository root containing `cwd`, or null when it is not a work tree. */
|
|
238
|
+
async function repoRoot(gitPath, cwd) {
|
|
239
|
+
const inside = await runGit(gitPath, cwd, ['rev-parse', '--is-inside-work-tree'])
|
|
240
|
+
if (!inside.ok || inside.stdout.trim() !== 'true') return null
|
|
241
|
+
const top = await mustGit(gitPath, cwd, ['rev-parse', '--show-toplevel'])
|
|
242
|
+
return path.resolve(top.trim())
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function mustRepoRoot(gitPath, cwd) {
|
|
246
|
+
const root = await repoRoot(gitPath, cwd)
|
|
247
|
+
if (root === null) {
|
|
248
|
+
throw new GitPanelError('git/no-repository', 'This folder is not inside a Git repository.')
|
|
249
|
+
}
|
|
250
|
+
return root
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Parse `git status --porcelain=v1 -z --branch`.
|
|
255
|
+
*
|
|
256
|
+
* The first record is the branch header; `-z` terminates every path with NUL and
|
|
257
|
+
* emits a rename's original path as the record after its new path.
|
|
258
|
+
*/
|
|
259
|
+
export function parseStatus(text) {
|
|
260
|
+
const tokens = String(text ?? '').split('\0')
|
|
261
|
+
const head = {
|
|
262
|
+
branch: null,
|
|
263
|
+
upstream: null,
|
|
264
|
+
ahead: 0,
|
|
265
|
+
behind: 0,
|
|
266
|
+
detached: false,
|
|
267
|
+
unborn: false,
|
|
268
|
+
}
|
|
269
|
+
const staged = []
|
|
270
|
+
const unstaged = []
|
|
271
|
+
const conflicts = []
|
|
272
|
+
|
|
273
|
+
for (let index = 0; index < tokens.length; index += 1) {
|
|
274
|
+
const record = tokens[index]
|
|
275
|
+
if (record === '') continue
|
|
276
|
+
if (record.startsWith('## ')) {
|
|
277
|
+
Object.assign(head, parseBranchHeader(record.slice(3)))
|
|
278
|
+
continue
|
|
279
|
+
}
|
|
280
|
+
if (record.length < 4) continue
|
|
281
|
+
const x = record[0]
|
|
282
|
+
const y = record[1]
|
|
283
|
+
const filePath = record.slice(3)
|
|
284
|
+
let originalPath = null
|
|
285
|
+
if (x === 'R' || x === 'C' || y === 'R' || y === 'C') {
|
|
286
|
+
originalPath = tokens[index + 1] ?? null
|
|
287
|
+
index += 1
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (x === '?' && y === '?') {
|
|
291
|
+
unstaged.push({ path: filePath, originalPath: null, status: 'U', untracked: true })
|
|
292
|
+
continue
|
|
293
|
+
}
|
|
294
|
+
if (x === '!' && y === '!') continue
|
|
295
|
+
|
|
296
|
+
const conflicted = isConflict(x, y)
|
|
297
|
+
if (conflicted) {
|
|
298
|
+
conflicts.push({ path: filePath, originalPath, status: '!', untracked: false, conflicted: true })
|
|
299
|
+
continue
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const indexStatus = stagedStatus(x)
|
|
303
|
+
if (indexStatus !== null) {
|
|
304
|
+
staged.push({ path: filePath, originalPath, status: indexStatus, untracked: false })
|
|
305
|
+
}
|
|
306
|
+
const worktreeStatus = worktreeStatusOf(y)
|
|
307
|
+
if (worktreeStatus !== null) {
|
|
308
|
+
unstaged.push({ path: filePath, originalPath, status: worktreeStatus, untracked: false })
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return { head, staged, unstaged, conflicts }
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function isConflict(x, y) {
|
|
316
|
+
if (x === 'U' || y === 'U') return true
|
|
317
|
+
return (x === 'A' && y === 'A') || (x === 'D' && y === 'D')
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function stagedStatus(x) {
|
|
321
|
+
switch (x) {
|
|
322
|
+
case 'M': return 'M'
|
|
323
|
+
case 'A': return 'A'
|
|
324
|
+
case 'D': return 'D'
|
|
325
|
+
case 'R': return 'R'
|
|
326
|
+
case 'C': return 'C'
|
|
327
|
+
case 'T': return 'T'
|
|
328
|
+
default: return null
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
function worktreeStatusOf(y) {
|
|
333
|
+
switch (y) {
|
|
334
|
+
case 'M': return 'M'
|
|
335
|
+
case 'D': return 'D'
|
|
336
|
+
case 'T': return 'T'
|
|
337
|
+
case 'A': return 'A'
|
|
338
|
+
case 'R': return 'R'
|
|
339
|
+
case 'C': return 'C'
|
|
340
|
+
default: return null
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Parse the text after `## ` in a porcelain v1 status header. */
|
|
345
|
+
export function parseBranchHeader(header) {
|
|
346
|
+
const result = {
|
|
347
|
+
branch: null,
|
|
348
|
+
upstream: null,
|
|
349
|
+
ahead: 0,
|
|
350
|
+
behind: 0,
|
|
351
|
+
detached: false,
|
|
352
|
+
unborn: false,
|
|
353
|
+
}
|
|
354
|
+
if (header.startsWith('No commits yet on ')) {
|
|
355
|
+
result.branch = header.slice('No commits yet on '.length).trim()
|
|
356
|
+
result.unborn = true
|
|
357
|
+
return result
|
|
358
|
+
}
|
|
359
|
+
if (header === 'HEAD (no branch)') {
|
|
360
|
+
result.detached = true
|
|
361
|
+
return result
|
|
362
|
+
}
|
|
363
|
+
const bracket = header.match(/^(.*?)(?:\s+\[(.+)\])?$/)
|
|
364
|
+
if (!bracket) return result
|
|
365
|
+
const body = bracket[1] ?? ''
|
|
366
|
+
const counts = bracket[2] ?? ''
|
|
367
|
+
const separator = body.indexOf('...')
|
|
368
|
+
if (separator === -1) {
|
|
369
|
+
result.branch = body.trim() || null
|
|
370
|
+
} else {
|
|
371
|
+
result.branch = body.slice(0, separator).trim() || null
|
|
372
|
+
result.upstream = body.slice(separator + 3).trim() || null
|
|
373
|
+
}
|
|
374
|
+
for (const part of counts.split(',')) {
|
|
375
|
+
const value = part.trim()
|
|
376
|
+
const ahead = value.match(/^ahead (\d+)$/)
|
|
377
|
+
const behind = value.match(/^behind (\d+)$/)
|
|
378
|
+
if (ahead) result.ahead = Number(ahead[1])
|
|
379
|
+
if (behind) result.behind = Number(behind[1])
|
|
380
|
+
}
|
|
381
|
+
return result
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** List configured remotes with their fetch URL. */
|
|
385
|
+
async function listRemotes(gitPath, root) {
|
|
386
|
+
const result = await runGit(gitPath, root, ['remote', '-v'])
|
|
387
|
+
if (!result.ok) return []
|
|
388
|
+
const seen = new Map()
|
|
389
|
+
for (const line of result.stdout.split('\n')) {
|
|
390
|
+
const match = line.match(/^(\S+)\s+(\S+)\s+\((fetch|push)\)$/)
|
|
391
|
+
if (match === null) continue
|
|
392
|
+
const [, name, url] = match
|
|
393
|
+
if (!seen.has(name)) seen.set(name, { name, url })
|
|
394
|
+
}
|
|
395
|
+
return [...seen.values()]
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export async function addRemote(gitPath, cwd, payload = {}) {
|
|
399
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
400
|
+
const name = normalizeRemote(payload.name)
|
|
401
|
+
const url = normalizeRemoteUrl(payload.url)
|
|
402
|
+
const remotes = await listRemotes(gitPath, root)
|
|
403
|
+
if (remotes.some((entry) => entry.name === name)) {
|
|
404
|
+
throw new GitPanelError('git/remote-exists', `Remote ${JSON.stringify(name)} already exists.`)
|
|
405
|
+
}
|
|
406
|
+
try {
|
|
407
|
+
await mustGit(gitPath, root, ['remote', 'add', '--', name, url])
|
|
408
|
+
} catch (error) {
|
|
409
|
+
throw new GitPanelError('git/remote-add-failed', clean(error?.message ?? error) || 'Could not add the remote.')
|
|
410
|
+
}
|
|
411
|
+
return { remote: { name, url } }
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
export async function removeRemote(gitPath, cwd, payload = {}) {
|
|
415
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
416
|
+
const name = normalizeRemote(payload.name)
|
|
417
|
+
const remotes = await listRemotes(gitPath, root)
|
|
418
|
+
if (!remotes.some((entry) => entry.name === name)) {
|
|
419
|
+
throw new GitPanelError('git/remote-not-found', `Unknown remote ${JSON.stringify(name)}.`)
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
await mustGit(gitPath, root, ['remote', 'remove', name])
|
|
423
|
+
} catch (error) {
|
|
424
|
+
throw new GitPanelError('git/remote-remove-failed', clean(error?.message ?? error) || 'Could not remove the remote.')
|
|
425
|
+
}
|
|
426
|
+
return { name }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Read branches, newest commit first; an unborn HEAD yields an empty list. */
|
|
430
|
+
async function readBranches(gitPath, root) {
|
|
431
|
+
const result = await runGit(gitPath, root, [
|
|
432
|
+
'for-each-ref',
|
|
433
|
+
'--sort=-committerdate',
|
|
434
|
+
'refs/heads',
|
|
435
|
+
'--format=%(refname:short)%1f%(HEAD)%1f%(upstream:short)%1f%(committerdate:iso-strict)%1f%(subject)',
|
|
436
|
+
])
|
|
437
|
+
if (!result.ok) return []
|
|
438
|
+
return result.stdout
|
|
439
|
+
.split('\n')
|
|
440
|
+
.filter((line) => line !== '')
|
|
441
|
+
.slice(0, 200)
|
|
442
|
+
.map((line) => {
|
|
443
|
+
const [name = '', head = '', upstream = '', date = '', subject = ''] = line.split('\x1f')
|
|
444
|
+
return {
|
|
445
|
+
name,
|
|
446
|
+
current: head === '*',
|
|
447
|
+
upstream: upstream === '' ? null : upstream,
|
|
448
|
+
date: date === '' ? null : date,
|
|
449
|
+
subject,
|
|
450
|
+
}
|
|
451
|
+
})
|
|
452
|
+
.filter((branch) => branch.name !== '')
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Read the most recent commits; an unborn HEAD yields an empty list. */
|
|
456
|
+
async function readCommits(gitPath, root) {
|
|
457
|
+
const result = await runGit(gitPath, root, [
|
|
458
|
+
'log',
|
|
459
|
+
'-n',
|
|
460
|
+
'40',
|
|
461
|
+
'--date=iso-strict',
|
|
462
|
+
'--pretty=format:%H%x1f%h%x1f%an%x1f%ae%x1f%ad%x1f%s%x1e',
|
|
463
|
+
])
|
|
464
|
+
if (!result.ok) return []
|
|
465
|
+
return result.stdout
|
|
466
|
+
.split('\x1e')
|
|
467
|
+
.map((record) => record.replace(/^\n+/, ''))
|
|
468
|
+
.filter((record) => record !== '')
|
|
469
|
+
.slice(0, 40)
|
|
470
|
+
.map((record) => {
|
|
471
|
+
const [hash = '', short = '', author = '', email = '', date = '', subject = ''] = record.split('\x1f')
|
|
472
|
+
return { hash, short, author, email, date, subject }
|
|
473
|
+
})
|
|
474
|
+
.filter((commit) => commit.hash !== '')
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Strip the `a/` or `b/` prefix from a patch header path. */
|
|
478
|
+
function stripDiffPath(value) {
|
|
479
|
+
let text = String(value ?? '').trim()
|
|
480
|
+
if (text === '/dev/null') return ''
|
|
481
|
+
if (text.startsWith('"') && text.endsWith('"')) {
|
|
482
|
+
text = text.slice(1, -1).replace(/\\(.)/g, '$1')
|
|
483
|
+
}
|
|
484
|
+
if (text.startsWith('a/') || text.startsWith('b/')) return text.slice(2)
|
|
485
|
+
return text
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/**
|
|
489
|
+
* Parse one unified patch into renderable files.
|
|
490
|
+
*
|
|
491
|
+
* Headers (`---`/`+++`) are only recognised outside a hunk so a deleted line
|
|
492
|
+
* whose content begins with `--` cannot be mistaken for a file header.
|
|
493
|
+
*/
|
|
494
|
+
export function parsePatch(text) {
|
|
495
|
+
const lines = String(text ?? '').replace(/\r\n/g, '\n').split('\n')
|
|
496
|
+
const files = []
|
|
497
|
+
let file = null
|
|
498
|
+
let oldLine = 0
|
|
499
|
+
let newLine = 0
|
|
500
|
+
let inHunk = false
|
|
501
|
+
let total = 0
|
|
502
|
+
let truncated = false
|
|
503
|
+
|
|
504
|
+
const ensureFile = () => {
|
|
505
|
+
if (file === null) {
|
|
506
|
+
file = { header: '', path: '', originalPath: null, binary: false, combined: false, lines: [] }
|
|
507
|
+
files.push(file)
|
|
508
|
+
}
|
|
509
|
+
return file
|
|
510
|
+
}
|
|
511
|
+
const push = (line) => {
|
|
512
|
+
ensureFile().lines.push(line)
|
|
513
|
+
total += 1
|
|
514
|
+
if (total >= MAX_DIFF_LINES) truncated = true
|
|
515
|
+
return !truncated
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
for (const raw of lines) {
|
|
519
|
+
if (truncated) break
|
|
520
|
+
if (raw.startsWith('diff --git ') || raw.startsWith('diff --cc ') || raw.startsWith('diff --combined ')) {
|
|
521
|
+
const combined = raw.startsWith('diff --cc ') || raw.startsWith('diff --combined ')
|
|
522
|
+
file = { header: raw, path: '', originalPath: null, binary: false, combined, lines: [] }
|
|
523
|
+
files.push(file)
|
|
524
|
+
inHunk = false
|
|
525
|
+
total += 1
|
|
526
|
+
if (total >= MAX_DIFF_LINES) truncated = true
|
|
527
|
+
continue
|
|
528
|
+
}
|
|
529
|
+
if (raw === '') continue
|
|
530
|
+
if (file === null) {
|
|
531
|
+
file = { header: '', path: '', originalPath: null, binary: false, combined: false, lines: [] }
|
|
532
|
+
files.push(file)
|
|
533
|
+
}
|
|
534
|
+
if (!inHunk && raw.startsWith('rename from ')) {
|
|
535
|
+
file.originalPath = raw.slice('rename from '.length)
|
|
536
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
537
|
+
continue
|
|
538
|
+
}
|
|
539
|
+
if (!inHunk && raw.startsWith('rename to ')) {
|
|
540
|
+
file.path = raw.slice('rename to '.length)
|
|
541
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
542
|
+
continue
|
|
543
|
+
}
|
|
544
|
+
if (!inHunk && raw.startsWith('Binary files ')) {
|
|
545
|
+
file.binary = true
|
|
546
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
547
|
+
continue
|
|
548
|
+
}
|
|
549
|
+
if (!inHunk && raw.startsWith('--- ')) {
|
|
550
|
+
const value = stripDiffPath(raw.slice(4))
|
|
551
|
+
if (value !== '') file.originalPath = value
|
|
552
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
553
|
+
continue
|
|
554
|
+
}
|
|
555
|
+
if (!inHunk && raw.startsWith('+++ ')) {
|
|
556
|
+
const value = stripDiffPath(raw.slice(4))
|
|
557
|
+
if (value !== '') file.path = value
|
|
558
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
559
|
+
continue
|
|
560
|
+
}
|
|
561
|
+
const combinedHunk = raw.match(/^@@@ -(\d+)(?:,\d+)? -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@@/)
|
|
562
|
+
if (combinedHunk) {
|
|
563
|
+
inHunk = true
|
|
564
|
+
file.combined = true
|
|
565
|
+
oldLine = Number(combinedHunk[1])
|
|
566
|
+
newLine = Number(combinedHunk[3])
|
|
567
|
+
if (!push({ kind: 'hunk', text: raw, oldLine, newLine })) break
|
|
568
|
+
continue
|
|
569
|
+
}
|
|
570
|
+
const hunk = raw.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/)
|
|
571
|
+
if (hunk) {
|
|
572
|
+
inHunk = true
|
|
573
|
+
oldLine = Number(hunk[1])
|
|
574
|
+
newLine = Number(hunk[2])
|
|
575
|
+
if (!push({ kind: 'hunk', text: raw, oldLine, newLine })) break
|
|
576
|
+
continue
|
|
577
|
+
}
|
|
578
|
+
if (inHunk && file.combined) {
|
|
579
|
+
// A combined diff (`diff --cc`) carries one status column per parent.
|
|
580
|
+
// A plus in either column is an addition, a minus in either is a removal;
|
|
581
|
+
// the two columns themselves are not part of the content.
|
|
582
|
+
const marker = raw.slice(0, 2)
|
|
583
|
+
const content = raw.slice(2)
|
|
584
|
+
if (marker === ' ') {
|
|
585
|
+
if (!push({ kind: 'ctx', text: content, oldLine, newLine })) break
|
|
586
|
+
oldLine += 1
|
|
587
|
+
newLine += 1
|
|
588
|
+
continue
|
|
589
|
+
}
|
|
590
|
+
if (marker[0] === '+' || marker[1] === '+') {
|
|
591
|
+
if (!push({ kind: 'add', text: content, newLine })) break
|
|
592
|
+
newLine += 1
|
|
593
|
+
continue
|
|
594
|
+
}
|
|
595
|
+
if (marker[0] === '-' || marker[1] === '-') {
|
|
596
|
+
if (!push({ kind: 'del', text: content, oldLine })) break
|
|
597
|
+
oldLine += 1
|
|
598
|
+
continue
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (inHunk && raw.startsWith('+')) {
|
|
602
|
+
if (!push({ kind: 'add', text: raw.slice(1), newLine })) break
|
|
603
|
+
newLine += 1
|
|
604
|
+
continue
|
|
605
|
+
}
|
|
606
|
+
if (inHunk && raw.startsWith('-')) {
|
|
607
|
+
if (!push({ kind: 'del', text: raw.slice(1), oldLine })) break
|
|
608
|
+
oldLine += 1
|
|
609
|
+
continue
|
|
610
|
+
}
|
|
611
|
+
if (inHunk && raw.startsWith(' ')) {
|
|
612
|
+
if (!push({ kind: 'ctx', text: raw.slice(1), oldLine, newLine })) break
|
|
613
|
+
oldLine += 1
|
|
614
|
+
newLine += 1
|
|
615
|
+
continue
|
|
616
|
+
}
|
|
617
|
+
if (raw.startsWith('\\')) {
|
|
618
|
+
if (!push({ kind: 'note', text: raw })) break
|
|
619
|
+
continue
|
|
620
|
+
}
|
|
621
|
+
if (!push({ kind: 'meta', text: raw })) break
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
for (const entry of files) {
|
|
625
|
+
if (entry.path === '') entry.path = entry.originalPath ?? guessPatchPath(entry.header)
|
|
626
|
+
if (entry.path === '' && entry.originalPath !== null) entry.path = entry.originalPath
|
|
627
|
+
}
|
|
628
|
+
return { files, truncated }
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function guessPatchPath(header) {
|
|
632
|
+
if (header.startsWith('diff --cc ')) return header.slice('diff --cc '.length)
|
|
633
|
+
if (header.startsWith('diff --combined ')) return header.slice('diff --combined '.length)
|
|
634
|
+
const match = /^diff --git a\/(.+) b\/(.+)$/.exec(header)
|
|
635
|
+
if (!match) return ''
|
|
636
|
+
return match[2] ?? match[1] ?? ''
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Build a synthetic patch for an untracked text file. */
|
|
640
|
+
async function untrackedDiff(root, relativePath) {
|
|
641
|
+
const absolute = path.join(root, relativePath)
|
|
642
|
+
const stat = await fs.stat(absolute).catch(() => null)
|
|
643
|
+
if (stat === null || !stat.isFile()) return ''
|
|
644
|
+
if (stat.size > MAX_FILE_BYTES) {
|
|
645
|
+
return `diff --git a/${relativePath} b/${relativePath}\nBinary files a/${relativePath} and b/${relativePath} differ\n`
|
|
646
|
+
}
|
|
647
|
+
const buffer = await fs.readFile(absolute)
|
|
648
|
+
if (buffer.includes(0)) {
|
|
649
|
+
return `diff --git a/${relativePath} b/${relativePath}\nBinary files a/${relativePath} and b/${relativePath} differ\n`
|
|
650
|
+
}
|
|
651
|
+
const content = buffer.toString('utf8').replace(/\r\n/g, '\n')
|
|
652
|
+
const lines = content.split('\n')
|
|
653
|
+
if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
|
|
654
|
+
const body = lines.map((line) => `+${line}`).join('\n')
|
|
655
|
+
return [
|
|
656
|
+
`diff --git a/${relativePath} b/${relativePath}`,
|
|
657
|
+
'new file mode 100644',
|
|
658
|
+
'--- /dev/null',
|
|
659
|
+
`+++ b/${relativePath}`,
|
|
660
|
+
`@@ -0,0 +1,${lines.length} @@`,
|
|
661
|
+
body,
|
|
662
|
+
'',
|
|
663
|
+
].join('\n')
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/** Full repository snapshot for one admitted Workspace. */
|
|
667
|
+
export async function readState(gitPath, cwd) {
|
|
668
|
+
const root = await repoRoot(gitPath, cwd)
|
|
669
|
+
const generatedAt = new Date().toISOString()
|
|
670
|
+
if (root === null) {
|
|
671
|
+
return { repo: null, staged: [], unstaged: [], conflicts: [], branches: [], commits: [], remotes: [], generatedAt }
|
|
672
|
+
}
|
|
673
|
+
const statusOut = await mustGit(gitPath, root, [
|
|
674
|
+
'status',
|
|
675
|
+
'--porcelain=v1',
|
|
676
|
+
'-z',
|
|
677
|
+
'--branch',
|
|
678
|
+
'--untracked-files=all',
|
|
679
|
+
])
|
|
680
|
+
const parsed = parseStatus(statusOut)
|
|
681
|
+
const [branches, commits, remotes] = await Promise.all([
|
|
682
|
+
readBranches(gitPath, root),
|
|
683
|
+
readCommits(gitPath, root),
|
|
684
|
+
listRemotes(gitPath, root),
|
|
685
|
+
])
|
|
686
|
+
return {
|
|
687
|
+
repo: { root, name: path.basename(root) || root, ...parsed.head },
|
|
688
|
+
staged: parsed.staged,
|
|
689
|
+
unstaged: parsed.unstaged,
|
|
690
|
+
conflicts: parsed.conflicts,
|
|
691
|
+
branches,
|
|
692
|
+
commits,
|
|
693
|
+
remotes,
|
|
694
|
+
generatedAt,
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
/** One file's patch in the selected group. */
|
|
699
|
+
export async function readDiff(gitPath, cwd, payload = {}) {
|
|
700
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
701
|
+
const relativePath = normalizeRelPath(payload.path)
|
|
702
|
+
const group = payload.group === 'staged' ? 'staged' : 'unstaged'
|
|
703
|
+
// A pathspec limited to the new name hides the old name, so git cannot
|
|
704
|
+
// recognise a rename. Include the original path when the browser knows it.
|
|
705
|
+
const originalPath = typeof payload.originalPath === 'string' && payload.originalPath !== ''
|
|
706
|
+
? normalizeRelPath(payload.originalPath)
|
|
707
|
+
: null
|
|
708
|
+
const pathspec = originalPath !== null && originalPath !== relativePath
|
|
709
|
+
? [relativePath, originalPath]
|
|
710
|
+
: [relativePath]
|
|
711
|
+
let text = group === 'staged'
|
|
712
|
+
? await mustGit(gitPath, root, [
|
|
713
|
+
'diff', '--cached', '--no-color', '--no-ext-diff', '--find-renames', '-U3', '--', ...pathspec,
|
|
714
|
+
])
|
|
715
|
+
: await mustGit(gitPath, root, [
|
|
716
|
+
'diff', '--no-color', '--no-ext-diff', '--find-renames', '-U3', '--', ...pathspec,
|
|
717
|
+
])
|
|
718
|
+
let untracked = false
|
|
719
|
+
if (group === 'unstaged' && text.trim() === '') {
|
|
720
|
+
const statusOut = await mustGit(gitPath, root, ['status', '--porcelain=v1', '-z', '--', relativePath])
|
|
721
|
+
if (statusOut.startsWith('??')) {
|
|
722
|
+
untracked = true
|
|
723
|
+
text = await untrackedDiff(root, relativePath)
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const parsed = parsePatch(text)
|
|
727
|
+
return { path: relativePath, group, untracked, files: parsed.files, truncated: parsed.truncated }
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** One commit's metadata and patch. */
|
|
731
|
+
export async function readShow(gitPath, cwd, payload = {}) {
|
|
732
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
733
|
+
const hash = String(payload.hash ?? '')
|
|
734
|
+
if (!/^[0-9a-fA-F]{4,40}$/.test(hash)) {
|
|
735
|
+
throw new GitPanelError('git/bad-revision', 'That is not a valid commit id.')
|
|
736
|
+
}
|
|
737
|
+
const meta = await mustGit(gitPath, root, [
|
|
738
|
+
'show', '-s', '--date=iso-strict',
|
|
739
|
+
'--format=%H%x1f%h%x1f%an%x1f%ae%x1f%ad%x1f%s%x1e',
|
|
740
|
+
hash,
|
|
741
|
+
])
|
|
742
|
+
const [hashFull = '', short = '', author = '', email = '', date = '', subject = ''] =
|
|
743
|
+
meta.split('\x1e')[0].split('\x1f')
|
|
744
|
+
const patch = await mustGit(gitPath, root, [
|
|
745
|
+
'show', '--pretty=format:', '--patch', '--no-color', '--no-ext-diff', '--find-renames', '-U3', hash,
|
|
746
|
+
])
|
|
747
|
+
const parsed = parsePatch(patch)
|
|
748
|
+
return {
|
|
749
|
+
commit: { hash: hashFull, short, author, email, date, subject },
|
|
750
|
+
files: parsed.files,
|
|
751
|
+
truncated: parsed.truncated,
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export async function stage(gitPath, cwd, payload = {}) {
|
|
756
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
757
|
+
if (payload.all === true) {
|
|
758
|
+
await mustGit(gitPath, root, ['add', '-A'])
|
|
759
|
+
return { staged: 'all' }
|
|
760
|
+
}
|
|
761
|
+
const paths = normalizePaths(payload.paths)
|
|
762
|
+
await mustGit(gitPath, root, ['add', '--', ...paths])
|
|
763
|
+
return { staged: paths.length }
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
export async function unstage(gitPath, cwd, payload = {}) {
|
|
767
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
768
|
+
const paths = payload.all === true ? ['.'] : normalizePaths(payload.paths)
|
|
769
|
+
const result = await runGit(gitPath, root, ['restore', '--staged', '--', ...paths])
|
|
770
|
+
if (!result.ok) {
|
|
771
|
+
// An unborn HEAD has no tree for `restore` to read; the index itself is the
|
|
772
|
+
// only record, so remove the entries directly.
|
|
773
|
+
await mustGit(gitPath, root, ['rm', '--cached', '--quiet', '-r', '--', ...paths])
|
|
774
|
+
}
|
|
775
|
+
return { unstaged: paths.length }
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
export async function discard(gitPath, cwd, payload = {}) {
|
|
779
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
780
|
+
const paths = normalizePaths(payload.paths)
|
|
781
|
+
const statusOut = await mustGit(gitPath, root, ['status', '--porcelain=v1', '-z', '--', ...paths])
|
|
782
|
+
const untracked = new Set()
|
|
783
|
+
for (const token of statusOut.split('\0')) {
|
|
784
|
+
if (token.startsWith('?? ')) untracked.add(token.slice(3))
|
|
785
|
+
}
|
|
786
|
+
const tracked = paths.filter((entry) => !untracked.has(entry))
|
|
787
|
+
if (tracked.length > 0) {
|
|
788
|
+
await mustGit(gitPath, root, ['restore', '--', ...tracked])
|
|
789
|
+
}
|
|
790
|
+
for (const entry of untracked) {
|
|
791
|
+
await fs.rm(path.join(root, entry), { force: true })
|
|
792
|
+
}
|
|
793
|
+
return { discarded: paths.length }
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
export async function commit(gitPath, cwd, payload = {}) {
|
|
797
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
798
|
+
const message = String(payload.message ?? '').trim()
|
|
799
|
+
if (message === '') {
|
|
800
|
+
throw new GitPanelError('git/empty-message', 'Enter a commit message.')
|
|
801
|
+
}
|
|
802
|
+
if (payload.stageAll === true) {
|
|
803
|
+
await mustGit(gitPath, root, ['add', '-A'])
|
|
804
|
+
}
|
|
805
|
+
const args = ['commit', '-m', message]
|
|
806
|
+
if (payload.amend === true) args.push('--amend')
|
|
807
|
+
const result = await runGit(gitPath, root, args)
|
|
808
|
+
if (!result.ok) {
|
|
809
|
+
throw new GitPanelError('git/commit-failed', result.message)
|
|
810
|
+
}
|
|
811
|
+
const head = await runGit(gitPath, root, ['rev-parse', '--short', 'HEAD'])
|
|
812
|
+
return { hash: head.ok ? head.stdout.trim() : '', output: clean(result.stdout) }
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
export async function checkout(gitPath, cwd, payload = {}) {
|
|
816
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
817
|
+
const branch = normalizeBranch(payload.branch)
|
|
818
|
+
await mustGit(gitPath, root, ['switch', branch])
|
|
819
|
+
return { branch }
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
export async function createBranch(gitPath, cwd, payload = {}) {
|
|
823
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
824
|
+
const branch = normalizeBranch(payload.branch)
|
|
825
|
+
await mustGit(gitPath, root, ['switch', '-c', branch])
|
|
826
|
+
return { branch }
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
export async function deleteBranch(gitPath, cwd, payload = {}) {
|
|
830
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
831
|
+
const branch = normalizeBranch(payload.branch)
|
|
832
|
+
const statusOut = await mustGit(gitPath, root, ['status', '--porcelain=v1', '-z', '--branch'])
|
|
833
|
+
const { head } = parseStatus(statusOut)
|
|
834
|
+
if (head.branch === branch) {
|
|
835
|
+
throw new GitPanelError('git/branch-current', 'Switch away from the branch before deleting it.')
|
|
836
|
+
}
|
|
837
|
+
try {
|
|
838
|
+
await mustGit(gitPath, root, ['branch', '-d', branch])
|
|
839
|
+
} catch (error) {
|
|
840
|
+
throw new GitPanelError('git/branch-delete-failed', clean(error?.message ?? error) || 'Could not delete the branch.')
|
|
841
|
+
}
|
|
842
|
+
return { branch }
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
export async function fetchRemote(gitPath, cwd) {
|
|
846
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
847
|
+
const result = await runGit(gitPath, root, ['fetch', '--all', '--prune'], NETWORK_TIMEOUT_MS)
|
|
848
|
+
if (!result.ok) throw new GitPanelError('git/fetch-failed', result.message)
|
|
849
|
+
return { output: clean(result.stderr || result.stdout) }
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
export async function pull(gitPath, cwd) {
|
|
853
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
854
|
+
const result = await runGit(gitPath, root, ['pull', '--no-edit'], NETWORK_TIMEOUT_MS)
|
|
855
|
+
if (!result.ok) throw new GitPanelError('git/pull-failed', result.message)
|
|
856
|
+
return { output: clean(result.stdout || result.stderr) }
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
export async function push(gitPath, cwd) {
|
|
860
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
861
|
+
const statusOut = await mustGit(gitPath, root, ['status', '--porcelain=v1', '-z', '--branch'])
|
|
862
|
+
const { head } = parseStatus(statusOut)
|
|
863
|
+
let args = ['push']
|
|
864
|
+
if (head.branch !== null && head.upstream === null) {
|
|
865
|
+
const remotes = (await mustGit(gitPath, root, ['remote']))
|
|
866
|
+
.split('\n')
|
|
867
|
+
.map((entry) => entry.trim())
|
|
868
|
+
.filter((entry) => entry !== '')
|
|
869
|
+
const remote = remotes.includes('origin') ? 'origin' : remotes.length === 1 ? remotes[0] : null
|
|
870
|
+
if (remote === null) {
|
|
871
|
+
throw new GitPanelError(
|
|
872
|
+
'git/push-failed',
|
|
873
|
+
'This branch has no upstream and no unambiguous remote. Set one with git push --set-upstream <remote> <branch>.',
|
|
874
|
+
)
|
|
875
|
+
}
|
|
876
|
+
args = ['push', '--set-upstream', remote, head.branch]
|
|
877
|
+
}
|
|
878
|
+
const result = await runGit(gitPath, root, args, NETWORK_TIMEOUT_MS)
|
|
879
|
+
if (!result.ok) throw new GitPanelError('git/push-failed', result.message)
|
|
880
|
+
return { output: clean(result.stderr || result.stdout) }
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/** List the fetched branches of one remote, without the remote prefix. */
|
|
884
|
+
export async function readRemoteBranches(gitPath, cwd, payload = {}) {
|
|
885
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
886
|
+
const remote = normalizeRemote(payload.remote)
|
|
887
|
+
const remotes = await listRemotes(gitPath, root)
|
|
888
|
+
if (!remotes.some((entry) => entry.name === remote)) {
|
|
889
|
+
throw new GitPanelError('git/remote-not-found', `Unknown remote ${JSON.stringify(remote)}.`)
|
|
890
|
+
}
|
|
891
|
+
const result = await runGit(gitPath, root, [
|
|
892
|
+
'for-each-ref',
|
|
893
|
+
'--sort=refname',
|
|
894
|
+
`refs/remotes/${remote}`,
|
|
895
|
+
'--format=%(refname:short)',
|
|
896
|
+
])
|
|
897
|
+
if (!result.ok) throw new GitPanelError('git/branch-list-failed', result.message)
|
|
898
|
+
const prefix = `${remote}/`
|
|
899
|
+
const branches = result.stdout
|
|
900
|
+
.split('\n')
|
|
901
|
+
.map((line) => line.trim())
|
|
902
|
+
.filter((line) => line.startsWith(prefix) && line !== `${prefix}HEAD`)
|
|
903
|
+
.map((line) => line.slice(prefix.length))
|
|
904
|
+
.filter((name) => name !== '')
|
|
905
|
+
.slice(0, 500)
|
|
906
|
+
return { remote, branches }
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Point one local branch at a remote-tracking branch. */
|
|
910
|
+
export async function setUpstream(gitPath, cwd, payload = {}) {
|
|
911
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
912
|
+
const branch = normalizeBranch(payload.branch)
|
|
913
|
+
const remote = normalizeRemote(payload.remote)
|
|
914
|
+
const remoteBranch = normalizeBranch(payload.remoteBranch)
|
|
915
|
+
const remotes = await listRemotes(gitPath, root)
|
|
916
|
+
if (!remotes.some((entry) => entry.name === remote)) {
|
|
917
|
+
throw new GitPanelError('git/remote-not-found', `Unknown remote ${JSON.stringify(remote)}.`)
|
|
918
|
+
}
|
|
919
|
+
const upstream = `${remote}/${remoteBranch}`
|
|
920
|
+
try {
|
|
921
|
+
await mustGit(gitPath, root, ['branch', `--set-upstream-to=${upstream}`, branch])
|
|
922
|
+
} catch (error) {
|
|
923
|
+
throw new GitPanelError('git/upstream-failed', clean(error?.message ?? error) || 'Could not set the upstream branch.')
|
|
924
|
+
}
|
|
925
|
+
return { branch, upstream }
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
export async function init(gitPath, cwd) {
|
|
929
|
+
const result = await runGit(gitPath, cwd, ['init', '-b', 'main'])
|
|
930
|
+
if (!result.ok) {
|
|
931
|
+
const fallback = await runGit(gitPath, cwd, ['init'])
|
|
932
|
+
if (!fallback.ok) throw new GitPanelError('git/init-failed', fallback.message)
|
|
933
|
+
}
|
|
934
|
+
return { initialized: true }
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* Build the bounded prompt input for one commit message.
|
|
939
|
+
*
|
|
940
|
+
* The staged diff is the source when anything is staged, because that is what
|
|
941
|
+
* a plain commit would record. Otherwise the working-tree diff is used, and an
|
|
942
|
+
* untracked-only change is quoted from the files themselves.
|
|
943
|
+
*/
|
|
944
|
+
async function readMessageInput(gitPath, root, parsed) {
|
|
945
|
+
const lines = []
|
|
946
|
+
lines.push(`Repository: ${path.basename(root) || root}`)
|
|
947
|
+
lines.push(`Branch: ${parsed.head.branch ?? (parsed.head.detached ? 'detached HEAD' : 'unknown')}`)
|
|
948
|
+
const changed = []
|
|
949
|
+
for (const entry of parsed.conflicts) changed.push(`! ${entry.path}`)
|
|
950
|
+
for (const entry of parsed.staged) {
|
|
951
|
+
changed.push(`${entry.status} ${entry.path}${entry.originalPath ? ` (from ${entry.originalPath})` : ''}`)
|
|
952
|
+
}
|
|
953
|
+
for (const entry of parsed.unstaged) {
|
|
954
|
+
changed.push(`${entry.untracked ? '??' : entry.status} ${entry.path}${entry.originalPath ? ` (from ${entry.originalPath})` : ''}`)
|
|
955
|
+
}
|
|
956
|
+
lines.push('Changed files:')
|
|
957
|
+
lines.push(...changed.slice(0, 100))
|
|
958
|
+
if (changed.length > 100) lines.push(`… ${changed.length - 100} more files`)
|
|
959
|
+
lines.push('')
|
|
960
|
+
|
|
961
|
+
const staged = parsed.staged.length > 0
|
|
962
|
+
const diff = await mustGit(gitPath, root, [
|
|
963
|
+
'diff',
|
|
964
|
+
...(staged ? ['--cached'] : []),
|
|
965
|
+
'--no-color',
|
|
966
|
+
'--no-ext-diff',
|
|
967
|
+
'--find-renames',
|
|
968
|
+
'-U1',
|
|
969
|
+
])
|
|
970
|
+
let body = diff
|
|
971
|
+
if (body.trim() === '' && parsed.unstaged.some((entry) => entry.untracked)) {
|
|
972
|
+
const chunks = []
|
|
973
|
+
for (const entry of parsed.unstaged.filter((item) => item.untracked).slice(0, MESSAGE_MAX_UNTRACKED_FILES)) {
|
|
974
|
+
const absolute = path.join(root, entry.path)
|
|
975
|
+
const stat = await fs.stat(absolute).catch(() => null)
|
|
976
|
+
if (stat === null || !stat.isFile()) continue
|
|
977
|
+
if (stat.size > MESSAGE_MAX_UNTRACKED_BYTES * 8) {
|
|
978
|
+
chunks.push(`New file ${entry.path} (too large to quote)`)
|
|
979
|
+
continue
|
|
980
|
+
}
|
|
981
|
+
const buffer = await fs.readFile(absolute).catch(() => null)
|
|
982
|
+
if (buffer === null || buffer.includes(0)) {
|
|
983
|
+
chunks.push(`New file ${entry.path} (binary)`)
|
|
984
|
+
continue
|
|
985
|
+
}
|
|
986
|
+
const content = buffer.toString('utf8').slice(0, MESSAGE_MAX_UNTRACKED_BYTES)
|
|
987
|
+
chunks.push(`New file ${entry.path}:\n${content}${buffer.length > MESSAGE_MAX_UNTRACKED_BYTES ? '\n…' : ''}`)
|
|
988
|
+
}
|
|
989
|
+
if (chunks.length > 0) body = chunks.join('\n\n')
|
|
990
|
+
}
|
|
991
|
+
if (body.trim() !== '') {
|
|
992
|
+
lines.push(staged ? 'Staged diff:' : 'Working tree diff:')
|
|
993
|
+
lines.push(body)
|
|
994
|
+
} else if (parsed.conflicts.length > 0) {
|
|
995
|
+
lines.push('The working tree has unresolved merge conflicts.')
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
let input = lines.join('\n')
|
|
999
|
+
let truncated = false
|
|
1000
|
+
if (input.length > MESSAGE_MAX_INPUT_CHARS) {
|
|
1001
|
+
input = `${input.slice(0, MESSAGE_MAX_INPUT_CHARS)}\n… (diff truncated)`
|
|
1002
|
+
truncated = true
|
|
1003
|
+
}
|
|
1004
|
+
return { input, truncated, files: changed.length }
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/** Strip fences, labels, quotes, and whole-line emphasis from model output. */
|
|
1008
|
+
export function cleanCommitMessage(text) {
|
|
1009
|
+
let value = String(text ?? '').replace(/\r\n/g, '\n').trim()
|
|
1010
|
+
value = value.replace(/^```[a-zA-Z0-9_-]*\s*\n?/u, '').replace(/\n?```$/u, '').trim()
|
|
1011
|
+
value = value.replace(/^(?:commit message|message|提交信息|提交说明|提交消息)\s*[::]\s*/iu, '').trim()
|
|
1012
|
+
if (value.length >= 2) {
|
|
1013
|
+
const first = value[0]
|
|
1014
|
+
const last = value[value.length - 1]
|
|
1015
|
+
if ((first === '"' && last === '"') || (first === "'" && last === "'") || (first === '“' && last === '”')) {
|
|
1016
|
+
value = value.slice(1, -1).trim()
|
|
1017
|
+
}
|
|
1018
|
+
}
|
|
1019
|
+
const [subject = '', ...rest] = value.split('\n')
|
|
1020
|
+
const cleanedSubject = subject
|
|
1021
|
+
.replace(/^\*\*(.+)\*\*$/u, '$1')
|
|
1022
|
+
.replace(/^`(.+)`$/u, '$1')
|
|
1023
|
+
.trim()
|
|
1024
|
+
return [cleanedSubject, ...rest].join('\n').trim()
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
/** System instruction for the message model, in the UI's language. */
|
|
1028
|
+
function messageSystemPrompt(locale) {
|
|
1029
|
+
const chinese = typeof locale === 'string' && locale.toLowerCase().startsWith('zh')
|
|
1030
|
+
return [
|
|
1031
|
+
'You write Git commit messages for a source-control panel.',
|
|
1032
|
+
'Return only the final commit message in plain text: no Markdown fences, no surrounding quotes, no explanation, and no preamble.',
|
|
1033
|
+
'Use an imperative subject line of at most 72 characters.',
|
|
1034
|
+
'Add a blank line and a short body (wrapped at 72 columns) only when the change is substantial.',
|
|
1035
|
+
'Describe only what the supplied changed-file list and diff show. Do not invent files, tests, issue numbers, or behaviour.',
|
|
1036
|
+
chinese ? 'Write the message in Simplified Chinese.' : 'Write the message in English.',
|
|
1037
|
+
].join('\n')
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* Read the profile's new-session default model, when one is configured.
|
|
1042
|
+
*
|
|
1043
|
+
* The panel offers that selection as "Default"; the host also uses it when the
|
|
1044
|
+
* request carries no explicit model.
|
|
1045
|
+
*/
|
|
1046
|
+
function readDefaultSelection(ctx) {
|
|
1047
|
+
try {
|
|
1048
|
+
const selection = safeGet(ctx, 'agentDefaultModel')?.currentSelection?.() ?? null
|
|
1049
|
+
if (selection === null || typeof selection !== 'object') return null
|
|
1050
|
+
if (typeof selection.provider !== 'string' || selection.provider === '') return null
|
|
1051
|
+
if (typeof selection.model !== 'string' || selection.model === '') return null
|
|
1052
|
+
return {
|
|
1053
|
+
provider: selection.provider,
|
|
1054
|
+
model: selection.model,
|
|
1055
|
+
...(typeof selection.reasoningEffort === 'string' && selection.reasoningEffort !== ''
|
|
1056
|
+
? { reasoningEffort: selection.reasoningEffort }
|
|
1057
|
+
: {}),
|
|
1058
|
+
}
|
|
1059
|
+
} catch {
|
|
1060
|
+
return null
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
/** Read a model chosen in the panel; null means "use the default". */
|
|
1065
|
+
function readMessageSelection(payload) {
|
|
1066
|
+
const provider = typeof payload?.provider === 'string' ? payload.provider.trim() : ''
|
|
1067
|
+
const model = typeof payload?.model === 'string' ? payload.model.trim() : ''
|
|
1068
|
+
if (provider === '' && model === '') return null
|
|
1069
|
+
if (provider === '' || model === '' || provider.length > 200 || model.length > 300) {
|
|
1070
|
+
throw new GitPanelError('git/model-invalid', 'The selected model is invalid.')
|
|
1071
|
+
}
|
|
1072
|
+
return { provider, model }
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/**
|
|
1076
|
+
* List the model catalog offered by the profile's adapters, plus the
|
|
1077
|
+
* new-session default. The panel uses this for its model picker; one adapter
|
|
1078
|
+
* failing to list models contributes an error instead of failing the page.
|
|
1079
|
+
*/
|
|
1080
|
+
async function listMessageModels(ctx) {
|
|
1081
|
+
const defaultSelection = readDefaultSelection(ctx)
|
|
1082
|
+
const llm = safeGet(ctx, 'llm')
|
|
1083
|
+
if (llm === undefined || typeof llm.listProviders !== 'function') {
|
|
1084
|
+
return {
|
|
1085
|
+
default: defaultSelection,
|
|
1086
|
+
providers: [],
|
|
1087
|
+
models: [],
|
|
1088
|
+
errors: [{ provider: '*', message: 'The LLM service is unavailable in this profile.' }],
|
|
1089
|
+
truncated: false,
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
let rawProviders
|
|
1093
|
+
try {
|
|
1094
|
+
rawProviders = llm.listProviders()
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
return {
|
|
1097
|
+
default: defaultSelection,
|
|
1098
|
+
providers: [],
|
|
1099
|
+
models: [],
|
|
1100
|
+
errors: [{ provider: '*', message: clean(error?.message ?? error) }],
|
|
1101
|
+
truncated: false,
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
if (!Array.isArray(rawProviders)) rawProviders = []
|
|
1105
|
+
const seen = new Set()
|
|
1106
|
+
const providers = []
|
|
1107
|
+
for (const provider of rawProviders) {
|
|
1108
|
+
if (provider === null || typeof provider !== 'object') continue
|
|
1109
|
+
if (typeof provider.id !== 'string' || provider.id === '' || seen.has(provider.id)) continue
|
|
1110
|
+
seen.add(provider.id)
|
|
1111
|
+
providers.push({
|
|
1112
|
+
id: provider.id,
|
|
1113
|
+
name: typeof provider.name === 'string' && provider.name !== '' ? provider.name : provider.id,
|
|
1114
|
+
})
|
|
1115
|
+
}
|
|
1116
|
+
const boundedProviders = providers.slice(0, 24)
|
|
1117
|
+
const models = []
|
|
1118
|
+
const errors = []
|
|
1119
|
+
const maxModels = 500
|
|
1120
|
+
await Promise.all(boundedProviders.map(async (provider) => {
|
|
1121
|
+
if (typeof llm.listModels !== 'function') {
|
|
1122
|
+
errors.push({ provider: provider.id, message: 'Model listing is unavailable.' })
|
|
1123
|
+
return
|
|
1124
|
+
}
|
|
1125
|
+
try {
|
|
1126
|
+
const list = await llm.listModels(provider.id)
|
|
1127
|
+
if (!Array.isArray(list)) return
|
|
1128
|
+
for (const model of list) {
|
|
1129
|
+
if (models.length >= maxModels) return
|
|
1130
|
+
if (model === null || typeof model !== 'object') continue
|
|
1131
|
+
if (typeof model.id !== 'string' || model.id === '') continue
|
|
1132
|
+
models.push({
|
|
1133
|
+
provider: provider.id,
|
|
1134
|
+
model: model.id,
|
|
1135
|
+
name: typeof model.name === 'string' && model.name !== '' ? model.name : model.id,
|
|
1136
|
+
...(typeof model.description === 'string' && model.description !== ''
|
|
1137
|
+
? { description: model.description }
|
|
1138
|
+
: {}),
|
|
1139
|
+
})
|
|
1140
|
+
}
|
|
1141
|
+
} catch (error) {
|
|
1142
|
+
errors.push({ provider: provider.id, message: clean(error?.message ?? error) })
|
|
1143
|
+
}
|
|
1144
|
+
}))
|
|
1145
|
+
models.sort((left, right) => {
|
|
1146
|
+
if (left.provider !== right.provider) return left.provider.localeCompare(right.provider)
|
|
1147
|
+
return left.name.localeCompare(right.name)
|
|
1148
|
+
})
|
|
1149
|
+
return {
|
|
1150
|
+
default: defaultSelection,
|
|
1151
|
+
providers: boundedProviders,
|
|
1152
|
+
models,
|
|
1153
|
+
errors,
|
|
1154
|
+
truncated: providers.length > boundedProviders.length || models.length >= maxModels,
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/**
|
|
1159
|
+
* Ask a model for a commit message.
|
|
1160
|
+
*
|
|
1161
|
+
* The call goes through `ctx.llm.prepareCall` so capability validation and
|
|
1162
|
+
* adapter defaults apply, then the stream is accumulated locally; the panel
|
|
1163
|
+
* only needs text, not the full block assembler.
|
|
1164
|
+
*/
|
|
1165
|
+
async function generateCommitMessage(ctx, cwd, payload, gitPath, options = {}) {
|
|
1166
|
+
const root = await mustRepoRoot(gitPath, cwd)
|
|
1167
|
+
const statusOut = await mustGit(gitPath, root, [
|
|
1168
|
+
'status', '--porcelain=v1', '-z', '--branch', '--untracked-files=all',
|
|
1169
|
+
])
|
|
1170
|
+
const parsed = parseStatus(statusOut)
|
|
1171
|
+
if (parsed.staged.length === 0 && parsed.unstaged.length === 0 && parsed.conflicts.length === 0) {
|
|
1172
|
+
throw new GitPanelError('git/no-changes', 'There are no changes to describe.')
|
|
1173
|
+
}
|
|
1174
|
+
const built = await readMessageInput(gitPath, root, parsed)
|
|
1175
|
+
|
|
1176
|
+
const llm = safeGet(ctx, 'llm')
|
|
1177
|
+
if (llm === undefined || typeof llm.prepareCall !== 'function') {
|
|
1178
|
+
throw new GitPanelError('git/llm-unavailable', 'The LLM service is unavailable in this profile.')
|
|
1179
|
+
}
|
|
1180
|
+
let selection = readMessageSelection(payload)
|
|
1181
|
+
?? (typeof options.messageProvider === 'string' && options.messageProvider !== ''
|
|
1182
|
+
? { provider: options.messageProvider, model: options.messageModel }
|
|
1183
|
+
: null)
|
|
1184
|
+
?? readDefaultSelection(ctx)
|
|
1185
|
+
const provider = selection?.provider
|
|
1186
|
+
const model = selection?.model
|
|
1187
|
+
if (typeof provider !== 'string' || provider === '' || typeof model !== 'string' || model === '') {
|
|
1188
|
+
throw new GitPanelError('git/no-model', 'No model is configured. Pick one in the commit box or Settings, Models.')
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
const signal = AbortSignal.timeout(MESSAGE_TIMEOUT_MS)
|
|
1192
|
+
let call
|
|
1193
|
+
try {
|
|
1194
|
+
call = await llm.prepareCall(
|
|
1195
|
+
{ provider, model, maxTokens: MESSAGE_MAX_OUTPUT_TOKENS },
|
|
1196
|
+
signal,
|
|
1197
|
+
(controls, modelInfo) => {
|
|
1198
|
+
const efforts = Array.isArray(modelInfo?.reasoning?.efforts) ? modelInfo.reasoning.efforts : []
|
|
1199
|
+
const preferred = typeof selection?.reasoningEffort === 'string'
|
|
1200
|
+
&& efforts.some((effort) => effort.id === selection.reasoningEffort)
|
|
1201
|
+
? selection.reasoningEffort
|
|
1202
|
+
: modelInfo?.reasoning?.defaultEffort ?? efforts[0]?.id
|
|
1203
|
+
return preferred === undefined ? controls : { ...controls, reasoningEffort: preferred }
|
|
1204
|
+
},
|
|
1205
|
+
)
|
|
1206
|
+
} catch (error) {
|
|
1207
|
+
throw new GitPanelError('git/message-failed', clean(error?.message ?? error) || 'The model could not be prepared.')
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
const textByIndex = new Map()
|
|
1211
|
+
let finish = null
|
|
1212
|
+
try {
|
|
1213
|
+
const stream = call.stream({
|
|
1214
|
+
...call.config,
|
|
1215
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: built.input }] }],
|
|
1216
|
+
system: messageSystemPrompt(payload.locale),
|
|
1217
|
+
signal,
|
|
1218
|
+
})
|
|
1219
|
+
for await (const chunk of stream) {
|
|
1220
|
+
signal.throwIfAborted()
|
|
1221
|
+
if (chunk.type === 'text-delta') {
|
|
1222
|
+
textByIndex.set(chunk.index, (textByIndex.get(chunk.index) ?? '') + chunk.text)
|
|
1223
|
+
} else if (chunk.type === 'block-end' && chunk.block?.type === 'text') {
|
|
1224
|
+
textByIndex.set(chunk.index, chunk.block.text)
|
|
1225
|
+
} else if (chunk.type === 'finish') {
|
|
1226
|
+
finish = chunk.reason
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
} catch (error) {
|
|
1230
|
+
if (error?.name === 'AbortError' || signal.aborted) {
|
|
1231
|
+
throw new GitPanelError('git/message-timeout', 'The model did not answer in time.')
|
|
1232
|
+
}
|
|
1233
|
+
throw new GitPanelError('git/message-failed', clean(error?.message ?? error) || 'The model request failed.')
|
|
1234
|
+
}
|
|
1235
|
+
if (finish !== null && (finish.kind === 'error' || finish.kind === 'aborted')) {
|
|
1236
|
+
throw new GitPanelError('git/message-failed', clean(finish.failure?.message) || 'The model request failed.')
|
|
1237
|
+
}
|
|
1238
|
+
if (finish !== null && finish.kind === 'tool-calls') {
|
|
1239
|
+
throw new GitPanelError('git/message-failed', 'The model returned a tool call instead of a commit message.')
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
const message = cleanCommitMessage(
|
|
1243
|
+
[...textByIndex.entries()]
|
|
1244
|
+
.sort((left, right) => left[0] - right[0])
|
|
1245
|
+
.map(([, value]) => value)
|
|
1246
|
+
.join(''),
|
|
1247
|
+
)
|
|
1248
|
+
if (message === '') {
|
|
1249
|
+
throw new GitPanelError('git/message-empty', 'The model returned an empty commit message.')
|
|
1250
|
+
}
|
|
1251
|
+
return { message, model: { provider, model }, files: built.files, truncated: built.truncated }
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/** Read the Workspaces this profile may operate on. */
|
|
1255
|
+
function listWorkspaces(ctx) {
|
|
1256
|
+
const workspaces = []
|
|
1257
|
+
const registry = safeGet(ctx, 'workspaceRegistry')
|
|
1258
|
+
if (registry !== undefined && typeof registry.list === 'function') {
|
|
1259
|
+
for (const workspace of registry.list()) {
|
|
1260
|
+
if (workspace === null || typeof workspace !== 'object') continue
|
|
1261
|
+
if (typeof workspace.path !== 'string' || workspace.path === '') continue
|
|
1262
|
+
workspaces.push({
|
|
1263
|
+
id: String(workspace.id ?? workspace.path),
|
|
1264
|
+
title: typeof workspace.title === 'string' && workspace.title !== ''
|
|
1265
|
+
? workspace.title
|
|
1266
|
+
: (path.basename(workspace.path) || workspace.path),
|
|
1267
|
+
path: workspace.path,
|
|
1268
|
+
})
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
const workingDirectory = safeGet(ctx, 'workingDirectory')
|
|
1272
|
+
const fallback = workingDirectory !== undefined && typeof workingDirectory.defaultDirectory === 'string'
|
|
1273
|
+
? workingDirectory.defaultDirectory
|
|
1274
|
+
: null
|
|
1275
|
+
if (fallback !== null && !workspaces.some((workspace) => samePath(workspace.path, fallback))) {
|
|
1276
|
+
workspaces.push({ id: 'default', title: path.basename(fallback) || fallback, path: fallback })
|
|
1277
|
+
}
|
|
1278
|
+
return workspaces
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
function safeGet(ctx, name) {
|
|
1282
|
+
try {
|
|
1283
|
+
return ctx.get(name)
|
|
1284
|
+
} catch {
|
|
1285
|
+
return undefined
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/** True when `target` is `root` itself or a descendant of it. */
|
|
1290
|
+
function isInside(root, target) {
|
|
1291
|
+
const relative = path.relative(root, target)
|
|
1292
|
+
return relative === ''
|
|
1293
|
+
|| (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
/** Admit one request's directory: a Workspace root or a repository inside it. */
|
|
1297
|
+
async function admitPath(ctx, cwd) {
|
|
1298
|
+
if (typeof cwd !== 'string' || cwd.trim() === '' || !path.isAbsolute(cwd)) {
|
|
1299
|
+
throw new GitPanelError('git/not-workspace', 'A Workspace directory is required.')
|
|
1300
|
+
}
|
|
1301
|
+
const target = path.resolve(cwd)
|
|
1302
|
+
const owner = listWorkspaces(ctx).find((workspace) => isInside(workspace.path, target))
|
|
1303
|
+
if (owner === undefined) {
|
|
1304
|
+
throw new GitPanelError('git/not-workspace', 'That directory is not inside a registered Workspace.')
|
|
1305
|
+
}
|
|
1306
|
+
// Resolve symlinks on both sides so a link cannot walk out of the Workspace.
|
|
1307
|
+
const [realTarget, realOwner] = await Promise.all([
|
|
1308
|
+
fs.realpath(target).catch(() => null),
|
|
1309
|
+
fs.realpath(owner.path).catch(() => owner.path),
|
|
1310
|
+
])
|
|
1311
|
+
if (realTarget === null || !isInside(realOwner, realTarget)) {
|
|
1312
|
+
throw new GitPanelError('git/not-workspace', 'That directory resolves outside its Workspace.')
|
|
1313
|
+
}
|
|
1314
|
+
return realTarget
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
/** Directory names a repository scan never descends into. */
|
|
1318
|
+
const SCAN_SKIP = new Set([
|
|
1319
|
+
'.git', 'node_modules', 'vendor', 'dist', 'build', 'out', 'target',
|
|
1320
|
+
'.next', '.nuxt', '.cache', 'coverage', '.venv', 'venv', '__pycache__',
|
|
1321
|
+
'bin', 'obj', '.idea', '.vscode', '.turbo', '.gradle', '.mvn',
|
|
1322
|
+
])
|
|
1323
|
+
/** Depth below the Workspace root the scan walks. */
|
|
1324
|
+
const SCAN_MAX_DEPTH = 4
|
|
1325
|
+
/** Directory budget for one scan. */
|
|
1326
|
+
const SCAN_MAX_DIRS = 2000
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Discover Git repositories inside one admitted Workspace.
|
|
1330
|
+
*
|
|
1331
|
+
* The walk is filesystem-only (no `git` process per candidate), bounded by
|
|
1332
|
+
* depth and directory count, skips symlinks and heavy build directories, and
|
|
1333
|
+
* reports a repository as soon as a `.git` directory or file is present.
|
|
1334
|
+
*/
|
|
1335
|
+
export async function scanRepositories(root) {
|
|
1336
|
+
const repos = []
|
|
1337
|
+
const queue = [{ dir: root, depth: 0 }]
|
|
1338
|
+
let visited = 0
|
|
1339
|
+
let truncated = false
|
|
1340
|
+
|
|
1341
|
+
while (queue.length > 0) {
|
|
1342
|
+
if (visited >= SCAN_MAX_DIRS) {
|
|
1343
|
+
truncated = true
|
|
1344
|
+
break
|
|
1345
|
+
}
|
|
1346
|
+
const { dir, depth } = queue.shift()
|
|
1347
|
+
visited += 1
|
|
1348
|
+
let entries
|
|
1349
|
+
try {
|
|
1350
|
+
entries = await fs.readdir(dir, { withFileTypes: true })
|
|
1351
|
+
} catch {
|
|
1352
|
+
continue
|
|
1353
|
+
}
|
|
1354
|
+
const hasGit = entries.some((entry) => (
|
|
1355
|
+
entry.name === '.git' && (entry.isDirectory() || entry.isFile())
|
|
1356
|
+
))
|
|
1357
|
+
if (hasGit) {
|
|
1358
|
+
const relative = path.relative(root, dir).split(path.sep).join('/')
|
|
1359
|
+
repos.push({
|
|
1360
|
+
path: dir,
|
|
1361
|
+
relativePath: relative === '' ? '.' : relative,
|
|
1362
|
+
name: path.basename(dir) || dir,
|
|
1363
|
+
})
|
|
1364
|
+
}
|
|
1365
|
+
if (depth >= SCAN_MAX_DEPTH) continue
|
|
1366
|
+
for (const entry of entries) {
|
|
1367
|
+
if (!entry.isDirectory()) continue
|
|
1368
|
+
if (entry.name.startsWith('.') || SCAN_SKIP.has(entry.name)) continue
|
|
1369
|
+
queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 })
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
repos.sort((left, right) => {
|
|
1374
|
+
if (left.relativePath === '.') return -1
|
|
1375
|
+
if (right.relativePath === '.') return 1
|
|
1376
|
+
return left.relativePath.localeCompare(right.relativePath)
|
|
1377
|
+
})
|
|
1378
|
+
return { workspace: root, repos, truncated }
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/** Build the request-facing service; tests can call the low-level exports. */
|
|
1382
|
+
export function createGitService(options = {}) {
|
|
1383
|
+
const gitPath = typeof options.gitPath === 'string' && options.gitPath.trim() !== ''
|
|
1384
|
+
? options.gitPath.trim()
|
|
1385
|
+
: 'git'
|
|
1386
|
+
const messageProvider = typeof options.messageProvider === 'string' && options.messageProvider.trim() !== ''
|
|
1387
|
+
? options.messageProvider.trim()
|
|
1388
|
+
: null
|
|
1389
|
+
const messageModel = typeof options.messageModel === 'string' && options.messageModel.trim() !== ''
|
|
1390
|
+
? options.messageModel.trim()
|
|
1391
|
+
: null
|
|
1392
|
+
if ((messageProvider === null) !== (messageModel === null)) {
|
|
1393
|
+
throw new Error('dsh-git: messageProvider and messageModel must be supplied together')
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
return {
|
|
1397
|
+
async repos(ctx) {
|
|
1398
|
+
return { workspaces: listWorkspaces(ctx) }
|
|
1399
|
+
},
|
|
1400
|
+
async scan(ctx, payload) {
|
|
1401
|
+
return scanRepositories(await admitPath(ctx, payload.cwd))
|
|
1402
|
+
},
|
|
1403
|
+
async models(ctx) {
|
|
1404
|
+
return listMessageModels(ctx)
|
|
1405
|
+
},
|
|
1406
|
+
async message(ctx, payload) {
|
|
1407
|
+
return generateCommitMessage(
|
|
1408
|
+
ctx,
|
|
1409
|
+
await admitPath(ctx, payload.cwd),
|
|
1410
|
+
payload,
|
|
1411
|
+
gitPath,
|
|
1412
|
+
{ messageProvider, messageModel },
|
|
1413
|
+
)
|
|
1414
|
+
},
|
|
1415
|
+
async state(ctx, payload) {
|
|
1416
|
+
return readState(gitPath, await admitPath(ctx, payload.cwd))
|
|
1417
|
+
},
|
|
1418
|
+
async diff(ctx, payload) {
|
|
1419
|
+
return readDiff(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1420
|
+
},
|
|
1421
|
+
async show(ctx, payload) {
|
|
1422
|
+
return readShow(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1423
|
+
},
|
|
1424
|
+
async stage(ctx, payload) {
|
|
1425
|
+
return stage(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1426
|
+
},
|
|
1427
|
+
async unstage(ctx, payload) {
|
|
1428
|
+
return unstage(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1429
|
+
},
|
|
1430
|
+
async discard(ctx, payload) {
|
|
1431
|
+
return discard(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1432
|
+
},
|
|
1433
|
+
async commit(ctx, payload) {
|
|
1434
|
+
return commit(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1435
|
+
},
|
|
1436
|
+
async checkout(ctx, payload) {
|
|
1437
|
+
return checkout(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1438
|
+
},
|
|
1439
|
+
async createBranch(ctx, payload) {
|
|
1440
|
+
return createBranch(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1441
|
+
},
|
|
1442
|
+
async deleteBranch(ctx, payload) {
|
|
1443
|
+
return deleteBranch(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1444
|
+
},
|
|
1445
|
+
async remoteBranches(ctx, payload) {
|
|
1446
|
+
return readRemoteBranches(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1447
|
+
},
|
|
1448
|
+
async setUpstream(ctx, payload) {
|
|
1449
|
+
return setUpstream(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1450
|
+
},
|
|
1451
|
+
async addRemote(ctx, payload) {
|
|
1452
|
+
return addRemote(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1453
|
+
},
|
|
1454
|
+
async removeRemote(ctx, payload) {
|
|
1455
|
+
return removeRemote(gitPath, await admitPath(ctx, payload.cwd), payload)
|
|
1456
|
+
},
|
|
1457
|
+
async fetch(ctx, payload) {
|
|
1458
|
+
return fetchRemote(gitPath, await admitPath(ctx, payload.cwd))
|
|
1459
|
+
},
|
|
1460
|
+
async pull(ctx, payload) {
|
|
1461
|
+
return pull(gitPath, await admitPath(ctx, payload.cwd))
|
|
1462
|
+
},
|
|
1463
|
+
async push(ctx, payload) {
|
|
1464
|
+
return push(gitPath, await admitPath(ctx, payload.cwd))
|
|
1465
|
+
},
|
|
1466
|
+
async init(ctx, payload) {
|
|
1467
|
+
return init(gitPath, await admitPath(ctx, payload.cwd))
|
|
1468
|
+
},
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
const ACTIONS = new Set([
|
|
1473
|
+
'repos', 'scan', 'models', 'message', 'state', 'diff', 'show', 'stage', 'unstage', 'discard',
|
|
1474
|
+
'commit', 'checkout', 'createBranch', 'deleteBranch', 'remoteBranches', 'setUpstream',
|
|
1475
|
+
'addRemote', 'removeRemote',
|
|
1476
|
+
'fetch', 'pull', 'push', 'init',
|
|
1477
|
+
])
|
|
1478
|
+
|
|
1479
|
+
async function dispatch(service, ctx, endpoint, payload) {
|
|
1480
|
+
try {
|
|
1481
|
+
if (!ACTIONS.has(endpoint)) {
|
|
1482
|
+
throw new GitPanelError('git/unknown-action', `Unknown action ${JSON.stringify(endpoint)}.`)
|
|
1483
|
+
}
|
|
1484
|
+
const value = await service[endpoint](ctx, payload !== null && typeof payload === 'object' ? payload : {})
|
|
1485
|
+
return { ok: true, value }
|
|
1486
|
+
} catch (error) {
|
|
1487
|
+
if (error instanceof GitPanelError) {
|
|
1488
|
+
return { ok: false, error: { code: error.code, message: error.message } }
|
|
1489
|
+
}
|
|
1490
|
+
return { ok: false, error: { code: 'git/failed', message: clean(error?.message ?? error) } }
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
/**
|
|
1495
|
+
* Host half entry point.
|
|
1496
|
+
*
|
|
1497
|
+
* The route is registered inside `ctx.inject(['connection'])` so a profile
|
|
1498
|
+
* without the browser carrier simply leaves the plugin inactive.
|
|
1499
|
+
*/
|
|
1500
|
+
export function apply(ctx, config = {}) {
|
|
1501
|
+
const service = createGitService(config)
|
|
1502
|
+
ctx.inject(['connection'], (connectionCtx) => {
|
|
1503
|
+
const dispose = connectionCtx.connection.fetch.register({
|
|
1504
|
+
path: ROUTE_PATH,
|
|
1505
|
+
methods: ['POST'],
|
|
1506
|
+
requestBody: 'buffered',
|
|
1507
|
+
fetch: async (request) => {
|
|
1508
|
+
let body
|
|
1509
|
+
try {
|
|
1510
|
+
body = await request.json()
|
|
1511
|
+
} catch {
|
|
1512
|
+
return Response.json(
|
|
1513
|
+
{ ok: false, error: { code: 'git/bad-request', message: 'The request body must be JSON.' } },
|
|
1514
|
+
{ status: 400, headers: NO_STORE },
|
|
1515
|
+
)
|
|
1516
|
+
}
|
|
1517
|
+
const result = await dispatch(service, ctx, String(body?.endpoint ?? ''), body?.payload)
|
|
1518
|
+
return Response.json(result, { headers: NO_STORE })
|
|
1519
|
+
},
|
|
1520
|
+
})
|
|
1521
|
+
return dispose
|
|
1522
|
+
})
|
|
1523
|
+
}
|