dsh-gufa-code 1.3.201 → 1.3.210
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 +10 -0
- package/client.js +496 -90
- package/host/fs.js +105 -1
- package/host/git.js +163 -74
- package/package.json +1 -1
- package/scripts/selftest-host.mjs +71 -1
- package/src/client/00-core.js +52 -5
- package/src/client/46-gitgraph.js +4 -3
- package/src/client/50-panels.js +243 -49
- package/src/client/85-shortcuts.js +98 -0
- package/src/client/90-app.js +98 -32
package/host/fs.js
CHANGED
|
@@ -10,7 +10,8 @@ import { execFile } from 'node:child_process'
|
|
|
10
10
|
import { promisify } from 'node:util'
|
|
11
11
|
import { constants } from 'node:fs'
|
|
12
12
|
import { tmpdir } from 'node:os'
|
|
13
|
-
import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
13
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
14
|
+
import { fileURLToPath } from 'node:url'
|
|
14
15
|
import { ApiError, badRequest } from './context.js'
|
|
15
16
|
import { registerLsp } from './lsp.js'
|
|
16
17
|
|
|
@@ -85,6 +86,64 @@ export function languageOf(path) {
|
|
|
85
86
|
}
|
|
86
87
|
|
|
87
88
|
/** 项目根内的相对路径解析(拒绝绝对路径、.. 逃逸与符号链接逃逸)。 */
|
|
89
|
+
/** 读取系统剪贴板里的文件/文件夹绝对路径(Finder/资源管理器复制的文件)。 */
|
|
90
|
+
async function readClipboardFilePaths() {
|
|
91
|
+
try {
|
|
92
|
+
if (process.platform === 'darwin') {
|
|
93
|
+
const script = [
|
|
94
|
+
'ObjC.import("AppKit");',
|
|
95
|
+
'var pb = $.NSPasteboard.generalPasteboard;',
|
|
96
|
+
'var urls = pb.readObjectsForClassesOptions($.NSArray.arrayWithObject($.NSURL), $({}));',
|
|
97
|
+
'var out = [];',
|
|
98
|
+
'if (urls) { for (var i = 0; i < urls.count; i++) { var u = urls.objectAtIndex(i); if (u && u.fileURL) out.push(ObjC.unwrap(u.path)); } }',
|
|
99
|
+
'JSON.stringify(out);',
|
|
100
|
+
].join('\n')
|
|
101
|
+
const { stdout } = await runCommand('osascript', ['-l', 'JavaScript', '-e', script], { timeout: 5000, maxBuffer: 2 * 1024 * 1024 })
|
|
102
|
+
return parseClipboardPaths(stdout)
|
|
103
|
+
}
|
|
104
|
+
if (process.platform === 'win32') {
|
|
105
|
+
const script = [
|
|
106
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8;',
|
|
107
|
+
'Add-Type -AssemblyName System.Windows.Forms;',
|
|
108
|
+
'$list = [System.Windows.Forms.Clipboard]::GetFileDropList();',
|
|
109
|
+
'$arr = @(); foreach ($item in $list) { $arr += [string]$item };',
|
|
110
|
+
'ConvertTo-Json -InputObject $arr -Compress',
|
|
111
|
+
].join('\n')
|
|
112
|
+
const { stdout } = await runCommand('powershell', ['-NoProfile', '-NonInteractive', '-Sta', '-Command', script], { timeout: 6000, maxBuffer: 2 * 1024 * 1024 })
|
|
113
|
+
return parseClipboardPaths(stdout)
|
|
114
|
+
}
|
|
115
|
+
for (const candidate of [
|
|
116
|
+
['wl-paste', ['--no-newline', '--type', 'text/uri-list']],
|
|
117
|
+
['xclip', ['-selection', 'clipboard', '-t', 'text/uri-list', '-o']],
|
|
118
|
+
]) {
|
|
119
|
+
try {
|
|
120
|
+
const { stdout } = await runCommand(candidate[0], candidate[1], { timeout: 3000, maxBuffer: 1024 * 1024 })
|
|
121
|
+
const urls = stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.startsWith('file://'))
|
|
122
|
+
if (urls.length > 0) {
|
|
123
|
+
return urls.map((url) => {
|
|
124
|
+
try { return fileURLToPath(url) } catch { return '' }
|
|
125
|
+
}).filter((path) => path !== '')
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
/* 尝试下一个剪贴板命令 */
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return []
|
|
132
|
+
} catch {
|
|
133
|
+
return []
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function parseClipboardPaths(stdout) {
|
|
138
|
+
try {
|
|
139
|
+
const parsed = JSON.parse(String(stdout ?? '').trim() || '[]')
|
|
140
|
+
const rows = Array.isArray(parsed) ? parsed : (typeof parsed === 'string' ? [parsed] : [])
|
|
141
|
+
return rows.filter((item) => typeof item === 'string' && item !== '')
|
|
142
|
+
} catch {
|
|
143
|
+
return []
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
88
147
|
export async function resolveProjectPath(root, raw, { create = false } = {}) {
|
|
89
148
|
if (typeof raw !== 'string') throw badRequest('path must be a string')
|
|
90
149
|
if (isAbsolute(raw)) throw new ApiError('path-invalid', '不允许绝对路径', 400)
|
|
@@ -527,6 +586,51 @@ export function register(router, env) {
|
|
|
527
586
|
return { copied }
|
|
528
587
|
})
|
|
529
588
|
|
|
589
|
+
/** 把系统剪贴板里复制的文件/文件夹粘贴进项目目录(Finder/资源管理器复制,支持多选和文件夹)。 */
|
|
590
|
+
router.method('fs.pasteClipboard', async (body) => {
|
|
591
|
+
const root = await projectOf(env, body)
|
|
592
|
+
const targetDir = await resolveProjectPath(root, typeof body.to === 'string' && body.to !== '' ? body.to : '')
|
|
593
|
+
const targetInfo = await stat(targetDir)
|
|
594
|
+
if (!targetInfo.isDirectory()) throw new ApiError('not-dir', '目标不是目录', 400)
|
|
595
|
+
const sources = await readClipboardFilePaths()
|
|
596
|
+
const copied = []
|
|
597
|
+
const failed = []
|
|
598
|
+
for (const raw of sources) {
|
|
599
|
+
if (typeof raw !== 'string' || raw === '') continue
|
|
600
|
+
const source = resolve(raw)
|
|
601
|
+
const sourceInfo = await stat(source).catch(() => null)
|
|
602
|
+
if (sourceInfo === null) {
|
|
603
|
+
failed.push({ from: raw, error: '文件不存在' })
|
|
604
|
+
continue
|
|
605
|
+
}
|
|
606
|
+
const base = basename(source) || 'item'
|
|
607
|
+
let name = base
|
|
608
|
+
let target = join(targetDir, name)
|
|
609
|
+
let suffix = 1
|
|
610
|
+
while (await stat(target).then(() => true, () => false)) {
|
|
611
|
+
name = suffix === 1 ? `${base} 副本` : `${base} 副本 ${suffix}`
|
|
612
|
+
target = join(targetDir, name)
|
|
613
|
+
suffix += 1
|
|
614
|
+
if (suffix > 200) throw new ApiError('copy-name-failed', '无法生成目标文件名', 500)
|
|
615
|
+
}
|
|
616
|
+
/* 不允许把目标目录本身/其祖先复制进自己里面 */
|
|
617
|
+
if (source === targetDir || (sourceInfo.isDirectory() && target.startsWith(source + sep))) {
|
|
618
|
+
failed.push({ from: raw, error: '不能把文件夹复制到自身内部' })
|
|
619
|
+
continue
|
|
620
|
+
}
|
|
621
|
+
try {
|
|
622
|
+
await cp(source, target, { recursive: true, errorOnExist: true, force: false })
|
|
623
|
+
copied.push({ from: raw, to: relativePath(root, target) })
|
|
624
|
+
} catch (error) {
|
|
625
|
+
failed.push({ from: raw, error: String(error instanceof Error ? error.message : error).slice(0, 200) })
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
if (copied.length === 0 && failed.length === 0) {
|
|
629
|
+
throw new ApiError('clipboard-empty', '系统剪贴板里没有文件或文件夹', 400)
|
|
630
|
+
}
|
|
631
|
+
return { copied, failed }
|
|
632
|
+
})
|
|
633
|
+
|
|
530
634
|
/** 把系统剪贴板里的文件匹配回项目内已有文件(供聊天框「粘贴文件→@引用」使用)。 */
|
|
531
635
|
/** 全项目文本搜索(左侧「搜索」面板用)。返回按文件分组、带上行列号的匹配。 */
|
|
532
636
|
router.method('fs.search', async (body) => {
|
package/host/git.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { execFile } from 'node:child_process'
|
|
6
6
|
import { promisify } from 'node:util'
|
|
7
|
+
import { readdir, rm } from 'node:fs/promises'
|
|
8
|
+
import { basename, isAbsolute, join, resolve, sep } from 'node:path'
|
|
7
9
|
import { ApiError, badRequest } from './context.js'
|
|
8
10
|
|
|
9
11
|
const run = promisify(execFile)
|
|
@@ -31,16 +33,6 @@ async function projectOf(env, body) {
|
|
|
31
33
|
return env.projects.ensure(body.root)
|
|
32
34
|
}
|
|
33
35
|
|
|
34
|
-
/** 打开项目后才 git init 的目录:动态探测并回填 isGit。 */
|
|
35
|
-
async function ensureRepo(env, body) {
|
|
36
|
-
const project = await projectOf(env, body)
|
|
37
|
-
if (project.isGit !== true) {
|
|
38
|
-
const inside = await git(project.root, ['rev-parse', '--is-inside-work-tree']).catch(() => '')
|
|
39
|
-
if (inside.trim() === 'true') project.isGit = true
|
|
40
|
-
}
|
|
41
|
-
return project
|
|
42
|
-
}
|
|
43
|
-
|
|
44
36
|
/** 解析 porcelain=v1 -z 输出(NUL 分隔、路径不转义,正确处理空格/中文/重命名)。 */
|
|
45
37
|
function parseStatusZ(text) {
|
|
46
38
|
const parts = text.split('\u0000')
|
|
@@ -138,26 +130,97 @@ function parseStatus(text) {
|
|
|
138
130
|
return { branch, upstream, hasUpstream: upstream !== '', ahead, behind, changes }
|
|
139
131
|
}
|
|
140
132
|
|
|
133
|
+
/** 查找工作区内所有 Git 仓库(不只看根目录)。跳过依赖/构建目录,限制深度与数量。 */
|
|
134
|
+
const REPO_SKIP_DIRS = new Set([
|
|
135
|
+
'node_modules', 'dist', 'build', 'out', 'target', '.next', '.turbo', '.cache', 'coverage',
|
|
136
|
+
'.venv', 'venv', '__pycache__', 'Pods', 'DerivedData', '.gradle', '.mvn', 'vendor',
|
|
137
|
+
'.idea', '.vscode', '.git',
|
|
138
|
+
])
|
|
139
|
+
|
|
140
|
+
async function findGitRepos(root) {
|
|
141
|
+
const repos = []
|
|
142
|
+
const queue = [{ dir: root, rel: '', depth: 0 }]
|
|
143
|
+
let visited = 0
|
|
144
|
+
while (queue.length > 0 && visited < 4000 && repos.length < 100) {
|
|
145
|
+
const current = queue.shift()
|
|
146
|
+
visited += 1
|
|
147
|
+
let entries = []
|
|
148
|
+
try {
|
|
149
|
+
entries = await readdir(current.dir, { withFileTypes: true })
|
|
150
|
+
} catch {
|
|
151
|
+
continue
|
|
152
|
+
}
|
|
153
|
+
const hasGit = entries.some((entry) => entry.name === '.git')
|
|
154
|
+
if (hasGit) {
|
|
155
|
+
repos.push({
|
|
156
|
+
path: current.dir,
|
|
157
|
+
rel: current.rel,
|
|
158
|
+
name: current.rel === '' ? basename(root) : basename(current.dir),
|
|
159
|
+
isRoot: current.rel === '',
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
/* 只扫工作区根目录 + 直接子目录:用户通常把 Git 项目直接放在工作区下面,
|
|
163
|
+
不再往深处递归,避免大目录扫描变慢。 */
|
|
164
|
+
if (current.depth >= 1) continue
|
|
165
|
+
for (const entry of entries) {
|
|
166
|
+
if (entry.isDirectory() !== true) continue
|
|
167
|
+
if (entry.name.startsWith('.') || REPO_SKIP_DIRS.has(entry.name)) continue
|
|
168
|
+
queue.push({
|
|
169
|
+
dir: join(current.dir, entry.name),
|
|
170
|
+
rel: current.rel === '' ? entry.name : `${current.rel}/${entry.name}`,
|
|
171
|
+
depth: current.depth + 1,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
repos.sort((a, b) => (a.isRoot === b.isRoot ? a.rel.localeCompare(b.rel) : a.isRoot ? -1 : 1))
|
|
176
|
+
return repos
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 解析请求要操作的仓库:默认工作区根目录;body.repo 指向工作区内某个仓库(嵌套仓库)。 */
|
|
180
|
+
async function repoContext(env, body) {
|
|
181
|
+
const project = await projectOf(env, body)
|
|
182
|
+
const base = project.root
|
|
183
|
+
let root = base
|
|
184
|
+
const requested = typeof body?.repo === 'string' ? body.repo.trim() : ''
|
|
185
|
+
if (requested !== '') {
|
|
186
|
+
const candidate = resolve(isAbsolute(requested) ? requested : join(base, requested))
|
|
187
|
+
if (candidate !== base && !candidate.startsWith(base + sep)) throw badRequest('repo 不在当前工作区内')
|
|
188
|
+
const toplevel = (await git(candidate, ['rev-parse', '--show-toplevel']).catch(() => '')).trim()
|
|
189
|
+
root = toplevel !== '' ? resolve(toplevel) : candidate
|
|
190
|
+
if (root !== base && !root.startsWith(base + sep)) throw badRequest('repo 不在当前工作区内')
|
|
191
|
+
}
|
|
192
|
+
const inside = (await git(root, ['rev-parse', '--is-inside-work-tree']).catch(() => '')).trim() === 'true'
|
|
193
|
+
if (inside && root === base) project.isGit = true
|
|
194
|
+
return { project, root, isGit: inside }
|
|
195
|
+
}
|
|
196
|
+
|
|
141
197
|
export function register(router, env) {
|
|
198
|
+
/* 列出工作区内所有 Git 仓库(含子目录里的仓库),供左侧面板逐个操作。 */
|
|
199
|
+
router.method('git.repos', async (body) => {
|
|
200
|
+
const { root } = await repoContext(env, body)
|
|
201
|
+
const repos = await findGitRepos(root)
|
|
202
|
+
return { root: root, repos }
|
|
203
|
+
})
|
|
204
|
+
|
|
142
205
|
router.method('git.status', async (body) => {
|
|
143
|
-
const
|
|
144
|
-
if (!
|
|
145
|
-
const raw = await git(
|
|
206
|
+
const ctx = await repoContext(env, body)
|
|
207
|
+
if (!ctx.isGit) return { isGit: false, branch: '', changes: [], ahead: 0, behind: 0 }
|
|
208
|
+
const raw = await git(ctx.root, ['status', '--porcelain=v1', '-z', '--branch', '--untracked-files=all'])
|
|
146
209
|
const parsed = parseStatusZ(raw)
|
|
147
210
|
if (parsed.changes.length > 0 || parsed.branch !== '') return { isGit: true, ...parsed }
|
|
148
|
-
return { isGit: true, ...parseStatus(await git(
|
|
211
|
+
return { isGit: true, ...parseStatus(await git(ctx.root, ['status', '--porcelain=v1', '--branch', '--untracked-files=all'])) }
|
|
149
212
|
})
|
|
150
213
|
|
|
151
214
|
/* 主动 fetch:git.status 的 behind 只反映本地已知的 remote-tracking ref,
|
|
152
215
|
远端有新提交但没 fetch 时箭头永远是 0。进 Git 面板/点刷新时先 fetch。 */
|
|
153
216
|
router.method('git.fetch', async (body) => {
|
|
154
|
-
const
|
|
155
|
-
if (
|
|
217
|
+
const ctx = await repoContext(env, body)
|
|
218
|
+
if (!ctx.isGit) return { ok: false, reason: 'not-git' }
|
|
156
219
|
try {
|
|
157
|
-
const remotes = (await git(
|
|
220
|
+
const remotes = (await git(ctx.root, ['remote']).catch(() => '')).trim()
|
|
158
221
|
.split('\n').map((line) => line.trim()).filter(Boolean)
|
|
159
222
|
const args = remotes.length > 0 ? ['fetch', '--prune', '--quiet', remotes[0]] : ['fetch', '--prune', '--quiet']
|
|
160
|
-
await git(
|
|
223
|
+
await git(ctx.root, args, 60_000)
|
|
161
224
|
return { ok: true, remote: remotes[0] ?? '' }
|
|
162
225
|
} catch (error) {
|
|
163
226
|
return { ok: false, reason: String(error?.message ?? error).slice(0, 800) }
|
|
@@ -165,34 +228,34 @@ export function register(router, env) {
|
|
|
165
228
|
})
|
|
166
229
|
|
|
167
230
|
router.method('git.stage', async (body) => {
|
|
168
|
-
const
|
|
231
|
+
const { root } = await repoContext(env, body)
|
|
169
232
|
const paths = Array.isArray(body.paths) ? body.paths.filter((item) => typeof item === 'string' && item !== '') : []
|
|
170
233
|
if (paths.length === 0) throw badRequest('paths is required')
|
|
171
|
-
await git(
|
|
234
|
+
await git(root, ['add', '--', ...paths])
|
|
172
235
|
return { ok: true }
|
|
173
236
|
})
|
|
174
237
|
|
|
175
238
|
router.method('git.unstage', async (body) => {
|
|
176
|
-
const
|
|
239
|
+
const { root } = await repoContext(env, body)
|
|
177
240
|
const paths = Array.isArray(body.paths) ? body.paths.filter((item) => typeof item === 'string' && item !== '') : []
|
|
178
241
|
if (paths.length === 0) throw badRequest('paths is required')
|
|
179
242
|
try {
|
|
180
|
-
await git(
|
|
243
|
+
await git(root, ['restore', '--staged', '--', ...paths])
|
|
181
244
|
} catch {
|
|
182
|
-
await git(
|
|
245
|
+
await git(root, ['reset', '-q', 'HEAD', '--', ...paths])
|
|
183
246
|
}
|
|
184
247
|
return { ok: true }
|
|
185
248
|
})
|
|
186
249
|
|
|
187
250
|
router.method('git.commit', async (body) => {
|
|
188
|
-
const
|
|
251
|
+
const { root } = await repoContext(env, body)
|
|
189
252
|
if (typeof body.message !== 'string' || body.message.trim() === '') throw badRequest('提交信息不能为空')
|
|
190
253
|
// 先检查暂存区:git commit 在没有暂存内容时只会把提示写到 stdout,直接透传会变成无意义的 "Command failed"
|
|
191
|
-
const staged = await git(
|
|
254
|
+
const staged = await git(root, ['diff', '--cached', '--name-only'])
|
|
192
255
|
if (staged.trim() === '') {
|
|
193
256
|
throw new ApiError('nothing-staged', '没有已暂存的改动:请先在「未暂存」里点 + 暂存,或点击「全部暂存」后再提交', 400)
|
|
194
257
|
}
|
|
195
|
-
const stdout = await git(
|
|
258
|
+
const stdout = await git(root, ['commit', '-m', body.message])
|
|
196
259
|
return { ok: true, output: stdout.trim().slice(0, 4000) }
|
|
197
260
|
})
|
|
198
261
|
|
|
@@ -213,31 +276,31 @@ export function register(router, env) {
|
|
|
213
276
|
}
|
|
214
277
|
|
|
215
278
|
router.method('git.push', async (body) => {
|
|
216
|
-
const
|
|
217
|
-
const { upstream, remote } = await upstreamOf(
|
|
218
|
-
const args = upstream !== '' ? ['push'] : ['push', '-u', remote, await currentBranch(
|
|
219
|
-
const stdout = await git(
|
|
279
|
+
const { root } = await repoContext(env, body)
|
|
280
|
+
const { upstream, remote } = await upstreamOf(root)
|
|
281
|
+
const args = upstream !== '' ? ['push'] : ['push', '-u', remote, await currentBranch(root)]
|
|
282
|
+
const stdout = await git(root, args, 120_000)
|
|
220
283
|
return { ok: true, output: stdout.trim().slice(0, 4000) }
|
|
221
284
|
})
|
|
222
285
|
|
|
223
286
|
router.method('git.pull', async (body) => {
|
|
224
|
-
const
|
|
225
|
-
const { upstream } = await upstreamOf(
|
|
287
|
+
const { root } = await repoContext(env, body)
|
|
288
|
+
const { upstream } = await upstreamOf(root)
|
|
226
289
|
if (upstream === '') throw new ApiError('no-upstream', '当前分支没有上游分支,请先推送一次建立上游', 400)
|
|
227
|
-
const stdout = await git(
|
|
290
|
+
const stdout = await git(root, ['pull', '--ff-only'], 120_000)
|
|
228
291
|
return { ok: true, output: stdout.trim().slice(0, 4000) }
|
|
229
292
|
})
|
|
230
293
|
|
|
231
294
|
/** 读取某文件在指定版本下的文本内容(供编辑器 diff 使用)。 */
|
|
232
295
|
router.method('git.show', async (body, context = {}) => {
|
|
233
|
-
const
|
|
296
|
+
const { root } = await repoContext(env, body)
|
|
234
297
|
const path = typeof body.path === 'string' ? body.path : ''
|
|
235
298
|
if (path === '' || path.startsWith('/') || path.includes('..')) throw badRequest('path is invalid')
|
|
236
299
|
const rev = body.rev === 'head' ? 'HEAD:' : ':'
|
|
237
300
|
let text = ''
|
|
238
301
|
let missing = false
|
|
239
302
|
try {
|
|
240
|
-
text = await git(
|
|
303
|
+
text = await git(root, ['show', `${rev}${path}`], 30_000)
|
|
241
304
|
} catch {
|
|
242
305
|
missing = true
|
|
243
306
|
text = ''
|
|
@@ -249,27 +312,43 @@ export function register(router, env) {
|
|
|
249
312
|
return { text: binary ? '' : text, missing, binary, tooLarge: false }
|
|
250
313
|
})
|
|
251
314
|
|
|
252
|
-
/**
|
|
315
|
+
/** 撤销指定文件的未暂存改动;未跟踪的新文件没有 HEAD 版本,直接删除文件。 */
|
|
253
316
|
router.method('git.discard', async (body) => {
|
|
254
|
-
const
|
|
317
|
+
const { root } = await repoContext(env, body)
|
|
255
318
|
const paths = Array.isArray(body.paths) ? body.paths.filter((item) => typeof item === 'string' && item !== '' && !item.includes('..') && !item.startsWith('/')) : []
|
|
256
319
|
if (paths.length === 0) throw badRequest('paths is required')
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
await git(
|
|
320
|
+
const removed = []
|
|
321
|
+
const tracked = []
|
|
322
|
+
for (const path of paths) {
|
|
323
|
+
const isTracked = (await git(root, ['ls-files', '--error-unmatch', '--', path]).catch(() => '')).trim() !== ''
|
|
324
|
+
if (isTracked) {
|
|
325
|
+
tracked.push(path)
|
|
326
|
+
continue
|
|
327
|
+
}
|
|
328
|
+
/* 未跟踪文件:git restore/checkout 都会报 pathspec did not match,直接删除工作区文件 */
|
|
329
|
+
const target = resolve(root, path)
|
|
330
|
+
if (target !== root && !target.startsWith(root + sep)) throw badRequest('path is invalid')
|
|
331
|
+
await rm(target, { recursive: true, force: true })
|
|
332
|
+
removed.push(path)
|
|
261
333
|
}
|
|
262
|
-
|
|
334
|
+
if (tracked.length > 0) {
|
|
335
|
+
try {
|
|
336
|
+
await git(root, ['restore', '--worktree', '--', ...tracked], 60_000)
|
|
337
|
+
} catch {
|
|
338
|
+
await git(root, ['checkout', '--', ...tracked], 60_000)
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return { ok: true, removed }
|
|
263
342
|
})
|
|
264
343
|
|
|
265
344
|
/** 撤回上一次提交,改动保留在暂存区(等价 git reset --soft HEAD~1;首个提交用 update-ref)。 */
|
|
266
345
|
router.method('git.undoLastCommit', async (body) => {
|
|
267
|
-
const
|
|
346
|
+
const { root } = await repoContext(env, body)
|
|
268
347
|
try {
|
|
269
|
-
await git(
|
|
348
|
+
await git(root, ['reset', '--soft', 'HEAD~1'], 60_000)
|
|
270
349
|
} catch (error) {
|
|
271
350
|
try {
|
|
272
|
-
await git(
|
|
351
|
+
await git(root, ['update-ref', '-d', 'HEAD'], 60_000)
|
|
273
352
|
} catch {
|
|
274
353
|
throw error
|
|
275
354
|
}
|
|
@@ -277,34 +356,44 @@ export function register(router, env) {
|
|
|
277
356
|
return { ok: true }
|
|
278
357
|
})
|
|
279
358
|
|
|
280
|
-
/**
|
|
359
|
+
/** 撤销所有改动:已跟踪文件还原到 HEAD,未跟踪的新文件从工作区删除。 */
|
|
281
360
|
router.method('git.discardAll', async (body) => {
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
await git(
|
|
286
|
-
|
|
361
|
+
const { root } = await repoContext(env, body)
|
|
362
|
+
/* 先删除未跟踪文件(git restore 对它们无效);--exclude-standard 不会碰 .gitignore 忽略的文件 */
|
|
363
|
+
const removed = []
|
|
364
|
+
const untracked = (await git(root, ['ls-files', '--others', '--exclude-standard', '-z']).catch(() => '')).split('\u0000')
|
|
365
|
+
for (const path of untracked) {
|
|
366
|
+
if (path === '' || path.includes('..') || path.startsWith('/')) continue
|
|
367
|
+
const target = resolve(root, path)
|
|
368
|
+
if (target === root || !target.startsWith(root + sep)) continue
|
|
369
|
+
await rm(target, { recursive: true, force: true })
|
|
370
|
+
removed.push(path)
|
|
371
|
+
}
|
|
372
|
+
const staged = await git(root, ['diff', '--cached', '--name-only']).catch(() => '')
|
|
373
|
+
if (staged.trim() !== '') await git(root, ['restore', '--staged', '--', '.'], 60_000)
|
|
374
|
+
await git(root, ['restore', '--worktree', '--', '.'], 60_000).catch(async () => {
|
|
375
|
+
await git(root, ['checkout', '--', '.'], 60_000)
|
|
287
376
|
})
|
|
288
|
-
return { ok: true }
|
|
377
|
+
return { ok: true, removed }
|
|
289
378
|
})
|
|
290
379
|
|
|
291
380
|
router.method('git.diff', async (body) => {
|
|
292
|
-
const
|
|
381
|
+
const { root } = await repoContext(env, body)
|
|
293
382
|
const args = ['diff', '--no-color', '--unified=3']
|
|
294
383
|
if (body.staged === true) args.push('--cached')
|
|
295
384
|
if (typeof body.path === 'string' && body.path !== '') args.push('--', body.path)
|
|
296
|
-
const patch = await git(
|
|
385
|
+
const patch = await git(root, args)
|
|
297
386
|
return { patch }
|
|
298
387
|
})
|
|
299
388
|
|
|
300
389
|
/** 某次提交的详情:提交信息 + 改动文件列表(name-status)。 */
|
|
301
390
|
router.method('git.commitFiles', async (body) => {
|
|
302
|
-
const
|
|
391
|
+
const { root } = await repoContext(env, body)
|
|
303
392
|
const hash = typeof body.hash === 'string' ? body.hash.trim() : ''
|
|
304
393
|
if (!/^[0-9a-f]{4,64}$/i.test(hash)) throw badRequest('hash is invalid')
|
|
305
|
-
const metaText = await git(
|
|
394
|
+
const metaText = await git(root, ['show', '-s', '--format=%H%x1f%h%x1f%an%x1f%ar%x1f%P%x1f%s', hash], 60_000)
|
|
306
395
|
const meta = metaText.trim().split('\u001f')
|
|
307
|
-
const filesText = await git(
|
|
396
|
+
const filesText = await git(root, ['show', '--name-status', '--format=', '--no-renames', hash], 60_000)
|
|
308
397
|
const files = filesText
|
|
309
398
|
.split('\n')
|
|
310
399
|
.filter((line) => line.trim() !== '')
|
|
@@ -328,7 +417,7 @@ export function register(router, env) {
|
|
|
328
417
|
|
|
329
418
|
/** 读取某文件在指定提交(或其父提交)中的文本内容,供提交 diff 使用。 */
|
|
330
419
|
router.method('git.fileVersion', async (body) => {
|
|
331
|
-
const
|
|
420
|
+
const { root } = await repoContext(env, body)
|
|
332
421
|
const path = typeof body.path === 'string' ? body.path : ''
|
|
333
422
|
const hash = typeof body.hash === 'string' ? body.hash.trim() : ''
|
|
334
423
|
if (path === '' || path.startsWith('/') || path.includes('..')) throw badRequest('path is invalid')
|
|
@@ -337,7 +426,7 @@ export function register(router, env) {
|
|
|
337
426
|
let text = ''
|
|
338
427
|
let missing = false
|
|
339
428
|
try {
|
|
340
|
-
text = await git(
|
|
429
|
+
text = await git(root, ['show', ref], 60_000)
|
|
341
430
|
} catch {
|
|
342
431
|
missing = true
|
|
343
432
|
text = ''
|
|
@@ -351,13 +440,13 @@ export function register(router, env) {
|
|
|
351
440
|
|
|
352
441
|
/** 提交图数据:hash / 父提交 / 作者 / 相对时间 / 引用装饰 / 标题。 */
|
|
353
442
|
router.method('git.graph', async (body) => {
|
|
354
|
-
const
|
|
443
|
+
const { root } = await repoContext(env, body)
|
|
355
444
|
const limit = Number.isInteger(body.limit) && body.limit > 0 ? Math.min(body.limit, 300) : 120
|
|
356
445
|
const args = ['log', `-n${limit}`, '--date=relative', '--format=%H%x1f%h%x1f%P%x1f%an%x1f%ar%x1f%D%x1f%s', '--decorate=short']
|
|
357
446
|
if (body.all !== false) args.push('--all')
|
|
358
447
|
let text = ''
|
|
359
448
|
try {
|
|
360
|
-
text = await git(
|
|
449
|
+
text = await git(root, args, 60_000)
|
|
361
450
|
} catch (error) {
|
|
362
451
|
return { commits: [], branch: '', error: error instanceof Error ? error.message : String(error) }
|
|
363
452
|
}
|
|
@@ -373,15 +462,15 @@ export function register(router, env) {
|
|
|
373
462
|
subject: rest.join('\u001f'),
|
|
374
463
|
}
|
|
375
464
|
})
|
|
376
|
-
const branch = (await git(
|
|
465
|
+
const branch = (await git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).catch(() => '')).trim()
|
|
377
466
|
return { commits, branch, error: '' }
|
|
378
467
|
})
|
|
379
468
|
|
|
380
469
|
router.method('git.log', async (body) => {
|
|
381
|
-
const
|
|
470
|
+
const { root } = await repoContext(env, body)
|
|
382
471
|
const limit = Number.isInteger(body.limit) && body.limit > 0 ? Math.min(body.limit, 100) : 30
|
|
383
472
|
const format = '%H%x1f%h%x1f%an%x1f%ar%x1f%s'
|
|
384
|
-
const stdout = await git(
|
|
473
|
+
const stdout = await git(root, ['log', `-n${limit}`, `--format=${format}`])
|
|
385
474
|
const commits = stdout.split('\n').filter(Boolean).map((line) => {
|
|
386
475
|
const [hash, short, author, when, ...rest] = line.split('\x1f')
|
|
387
476
|
return { hash, short, author, when, subject: rest.join('\x1f') }
|
|
@@ -390,11 +479,11 @@ export function register(router, env) {
|
|
|
390
479
|
})
|
|
391
480
|
|
|
392
481
|
router.method('git.branches', async (body) => {
|
|
393
|
-
const
|
|
482
|
+
const { root } = await repoContext(env, body)
|
|
394
483
|
// 注意:%x1f 是 git log 的转义,ref-filter(branch/for-each-ref 的 --format)不支持,
|
|
395
484
|
// 因此这里用 for-each-ref 拿名字 + rev-parse 判断当前分支,不要拼接格式转义。
|
|
396
|
-
const stdout = await git(
|
|
397
|
-
const current = (await git(
|
|
485
|
+
const stdout = await git(root, ['for-each-ref', '--format=%(refname:short)', 'refs/heads'])
|
|
486
|
+
const current = (await git(root, ['rev-parse', '--abbrev-ref', 'HEAD']).catch(() => '')).trim()
|
|
398
487
|
const branches = stdout
|
|
399
488
|
.split('\n')
|
|
400
489
|
.map((line) => line.trim())
|
|
@@ -405,26 +494,26 @@ export function register(router, env) {
|
|
|
405
494
|
|
|
406
495
|
/** 新建并切换到新分支。 */
|
|
407
496
|
router.method('git.createBranch', async (body) => {
|
|
408
|
-
const
|
|
497
|
+
const { root } = await repoContext(env, body)
|
|
409
498
|
const name = typeof body.name === 'string' ? body.name.trim() : ''
|
|
410
499
|
if (name === '') throw badRequest('分支名不能为空')
|
|
411
|
-
await git(
|
|
500
|
+
await git(root, ['check-ref-format', '--branch', name]).catch(() => {
|
|
412
501
|
throw new ApiError('branch-invalid', `分支名不合法:${name}`, 400)
|
|
413
502
|
})
|
|
414
|
-
const exists = (await git(
|
|
503
|
+
const exists = (await git(root, ['branch', '--list', '--format=%(refname:short)', name]).catch(() => '')).trim()
|
|
415
504
|
if (exists !== '') throw new ApiError('branch-exists', `分支已存在:${name}`, 409)
|
|
416
505
|
try {
|
|
417
|
-
await git(
|
|
506
|
+
await git(root, ['switch', '-c', name], 60_000)
|
|
418
507
|
} catch {
|
|
419
|
-
await git(
|
|
508
|
+
await git(root, ['checkout', '-b', name], 60_000)
|
|
420
509
|
}
|
|
421
510
|
return { ok: true, branch: name }
|
|
422
511
|
})
|
|
423
512
|
|
|
424
513
|
router.method('git.checkout', async (body) => {
|
|
425
|
-
const
|
|
514
|
+
const { root } = await repoContext(env, body)
|
|
426
515
|
if (typeof body.branch !== 'string' || body.branch === '') throw badRequest('branch is required')
|
|
427
|
-
await git(
|
|
516
|
+
await git(root, ['checkout', body.branch])
|
|
428
517
|
return { ok: true }
|
|
429
518
|
})
|
|
430
519
|
|
package/package.json
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* 用法:node scripts/selftest-host.mjs
|
|
6
6
|
*/
|
|
7
7
|
import { execFileSync } from 'node:child_process'
|
|
8
|
-
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
8
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
|
9
9
|
import { tmpdir } from 'node:os'
|
|
10
10
|
import { join } from 'node:path'
|
|
11
11
|
|
|
@@ -270,6 +270,76 @@ try {
|
|
|
270
270
|
const unstagedHead = await call(router, 'git.show', { root, path: 'src/unstaged.ts', rev: 'head' })
|
|
271
271
|
check('unstaged file not in commit', unstagedHead.missing === true)
|
|
272
272
|
|
|
273
|
+
/* 多仓库:工作区根目录仓库 + 子目录仓库分别检测、分别提交 */
|
|
274
|
+
const nestedRepo = join(projectDir, 'nested-lib')
|
|
275
|
+
mkdirSync(nestedRepo, { recursive: true })
|
|
276
|
+
execFileSync('git', ['init', '-q'], { cwd: nestedRepo })
|
|
277
|
+
execFileSync('git', ['config', 'user.email', 'selftest@example.com'], { cwd: nestedRepo })
|
|
278
|
+
execFileSync('git', ['config', 'user.name', 'gufa selftest'], { cwd: nestedRepo })
|
|
279
|
+
writeFileSync(join(nestedRepo, 'index.ts'), 'export const nested = 1\n')
|
|
280
|
+
execFileSync('git', ['add', '.'], { cwd: nestedRepo })
|
|
281
|
+
execFileSync('git', ['commit', '-qm', 'init nested'], { cwd: nestedRepo })
|
|
282
|
+
const repoList = await call(router, 'git.repos', { root })
|
|
283
|
+
check('git.repos lists root repo', repoList.repos.some((repo) => repo.rel === '' && repo.isRoot === true), JSON.stringify(repoList.repos.map((repo) => repo.rel)))
|
|
284
|
+
check('git.repos lists direct child repo', repoList.repos.some((repo) => repo.rel === 'nested-lib'), JSON.stringify(repoList.repos.map((repo) => repo.rel)))
|
|
285
|
+
const nested = repoList.repos.find((repo) => repo.rel === 'nested-lib')
|
|
286
|
+
const nestedStatus = await call(router, 'git.status', { root, repo: nested.path })
|
|
287
|
+
check('nested repo status isolated', nestedStatus.isGit === true && nestedStatus.changes.length === 0, JSON.stringify(nestedStatus.changes))
|
|
288
|
+
writeFileSync(join(nestedRepo, 'index.ts'), 'export const nested = 2\n')
|
|
289
|
+
const nestedDirty = await call(router, 'git.status', { root, repo: nested.path })
|
|
290
|
+
check('nested repo shows own change', nestedDirty.changes.some((change) => change.path === 'index.ts'), JSON.stringify(nestedDirty.changes))
|
|
291
|
+
await call(router, 'git.stage', { root, repo: nested.path, paths: ['index.ts'] })
|
|
292
|
+
await call(router, 'git.commit', { root, repo: nested.path, message: 'nested change' })
|
|
293
|
+
const nestedClean = await call(router, 'git.status', { root, repo: nested.path })
|
|
294
|
+
check('nested repo commits independently', nestedClean.changes.length === 0, JSON.stringify(nestedClean.changes))
|
|
295
|
+
const rootStillDirty = await call(router, 'git.status', { root })
|
|
296
|
+
check('root repo unaffected by nested commit', rootStillDirty.isGit === true && !rootStillDirty.changes.some((change) => change.path === 'nested-lib/index.ts'), JSON.stringify(rootStillDirty.changes))
|
|
297
|
+
let outsideRepoRejected = false
|
|
298
|
+
try {
|
|
299
|
+
await call(router, 'git.status', { root, repo: join(sandbox, 'outside-repo') })
|
|
300
|
+
} catch (error) {
|
|
301
|
+
outsideRepoRejected = error.code === 'bad-request'
|
|
302
|
+
}
|
|
303
|
+
check('git rejects repo outside workspace', outsideRepoRejected)
|
|
304
|
+
|
|
305
|
+
/* 未跟踪新文件:还原 = 删除文件;已跟踪文件:还原 = 恢复 HEAD 内容 */
|
|
306
|
+
await call(router, 'fs.create', { root, path: 'src/temp-untracked.ts', kind: 'file' })
|
|
307
|
+
await call(router, 'fs.write', { root, path: 'src/temp-untracked.ts', content: 'temporary\n' })
|
|
308
|
+
const untrackedBefore = await call(router, 'git.status', { root })
|
|
309
|
+
check('untracked file listed', untrackedBefore.changes.some((change) => change.path === 'src/temp-untracked.ts' && change.untracked === true), JSON.stringify(untrackedBefore.changes))
|
|
310
|
+
const discardedUntracked = await call(router, 'git.discard', { root, paths: ['src/temp-untracked.ts'] })
|
|
311
|
+
check('discard reports removed untracked', Array.isArray(discardedUntracked.removed) && discardedUntracked.removed.includes('src/temp-untracked.ts'), JSON.stringify(discardedUntracked.removed))
|
|
312
|
+
let untrackedGone = false
|
|
313
|
+
try {
|
|
314
|
+
await call(router, 'fs.read', { root, path: 'src/temp-untracked.ts' })
|
|
315
|
+
} catch {
|
|
316
|
+
untrackedGone = true
|
|
317
|
+
}
|
|
318
|
+
const untrackedAfter = await call(router, 'git.status', { root })
|
|
319
|
+
check('discard deletes untracked file', untrackedGone && !untrackedAfter.changes.some((change) => change.path === 'src/temp-untracked.ts'))
|
|
320
|
+
const trackedDoc = await call(router, 'fs.read', { root, path: 'src/main.ts' })
|
|
321
|
+
await call(router, 'fs.write', { root, path: 'src/main.ts', content: 'changed locally\n', expectedRevision: trackedDoc.revision })
|
|
322
|
+
await call(router, 'git.discard', { root, paths: ['src/main.ts'] })
|
|
323
|
+
const restoredDoc = await call(router, 'fs.read', { root, path: 'src/main.ts' })
|
|
324
|
+
check('discard restores tracked file to HEAD', restoredDoc.content === 'const answer = 42\n', JSON.stringify(restoredDoc.content))
|
|
325
|
+
|
|
326
|
+
/* 撤销全部:未跟踪新文件删除 + 已跟踪改动还原 */
|
|
327
|
+
await call(router, 'fs.create', { root, path: 'src/temp-all.ts', kind: 'file' })
|
|
328
|
+
await call(router, 'fs.write', { root, path: 'src/temp-all.ts', content: 'to be removed\n' })
|
|
329
|
+
const allDoc = await call(router, 'fs.read', { root, path: 'src/main.ts' })
|
|
330
|
+
await call(router, 'fs.write', { root, path: 'src/main.ts', content: 'local edit\n', expectedRevision: allDoc.revision })
|
|
331
|
+
const discardedAll = await call(router, 'git.discardAll', { root })
|
|
332
|
+
check('discardAll reports removed untracked', Array.isArray(discardedAll.removed) && discardedAll.removed.includes('src/temp-all.ts'), JSON.stringify(discardedAll.removed))
|
|
333
|
+
let allUntrackedGone = false
|
|
334
|
+
try {
|
|
335
|
+
await call(router, 'fs.read', { root, path: 'src/temp-all.ts' })
|
|
336
|
+
} catch {
|
|
337
|
+
allUntrackedGone = true
|
|
338
|
+
}
|
|
339
|
+
const restoredMain = await call(router, 'fs.read', { root, path: 'src/main.ts' })
|
|
340
|
+
check('discardAll deletes untracked files', allUntrackedGone)
|
|
341
|
+
check('discardAll restores tracked files', restoredMain.content === 'const answer = 42\n', JSON.stringify(restoredMain.content))
|
|
342
|
+
|
|
273
343
|
const gitSearch = await call(router, 'fs.search', { root, query: 'answer' })
|
|
274
344
|
check('search uses git file list', gitSearch.viaGit === true, String(gitSearch.viaGit))
|
|
275
345
|
check('search finds committed file', gitSearch.files.some((file) => file.path === 'src/main.ts'))
|