dsh-dock 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -2
- package/client.js +1843 -126
- package/features/dshtools/host.js +13 -0
- package/features/git/host.js +884 -0
- package/features/git/rpc.js +156 -0
- package/features/git/view.jsx +1946 -0
- package/index.js +3 -0
- package/package.json +3 -3
- package/src/client.jsx +17 -1
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
// dsh-dock · 功能模块【Git 管理】· 宿主半部
|
|
2
|
+
//
|
|
3
|
+
// 定位:一个只依赖 git 命令行的本地仓库工作台。面板能看历史、看工作区、
|
|
4
|
+
// 看差异、暂存与提交、推送——全部走 `git` 子进程,不引入任何 git 库依赖。
|
|
5
|
+
//
|
|
6
|
+
// RPC(webServer HTTP 路由,前缀 /dsh-dock/git):
|
|
7
|
+
// GET /info → { defaultDir, home, platform, gitVersion, available }
|
|
8
|
+
// POST /repos { dir, depth?, includeSubdirs? } → { root, repos:[...] }
|
|
9
|
+
// POST /refs { repo } → { head, branch, branches:{local,remote}, tags, remotes }
|
|
10
|
+
// POST /resolve { path } → { repo, repoName, relPath, isDirectory }(右键入口用,无需选目录)
|
|
11
|
+
// POST /commits { repo|repos, limit?, skip?, search?, author?, branch?, path? } → { results }
|
|
12
|
+
// POST /commit { repo, sha } → { commit }(含 diff 与文件清单)
|
|
13
|
+
// POST /status { repo } → { staged, unstaged, untracked, branch, ahead, behind }
|
|
14
|
+
// POST /diff { repo, sha?|staged?|untracked?, path? } → { files:[...] }
|
|
15
|
+
// POST /file { repo, path, sha? } → { path, content, truncated }
|
|
16
|
+
// POST /stage { repo, paths, unstage?, confirm:true }
|
|
17
|
+
// POST /create-commit { repo, message, paths?, confirm:true } → { commit }
|
|
18
|
+
// POST /push { repo, remote?, branch?, confirm:true } → { output }
|
|
19
|
+
//
|
|
20
|
+
// 安全约定:
|
|
21
|
+
// - 只接受绝对路径,拒绝含 NUL 的串;路径必须真实存在且是目录。
|
|
22
|
+
// - 一律 execFile('git', [...]) 传参数组,绝不拼 shell 字符串,也不经 shell 执行。
|
|
23
|
+
// - 仓库发现有条数与深度上限,避免误选家目录时把整盘扫一遍。
|
|
24
|
+
// - 写操作(stage / create-commit / push)额外要求 confirm: true,防止误触。
|
|
25
|
+
// - 路由挂在 /dsh-dock/git 前缀下,注册处显式 auth: 'required' 并把 peer 透传给信任栅栏。
|
|
26
|
+
import { execFile } from 'node:child_process'
|
|
27
|
+
import { promises as fsp } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { basename, isAbsolute, join, relative, sep } from 'node:path'
|
|
30
|
+
import { readBody, rejectUntrustedRequest, sendJson } from '../../src/host-core.js'
|
|
31
|
+
|
|
32
|
+
/** 普通 git 命令超时(毫秒)。 */
|
|
33
|
+
const GIT_TIMEOUT_MS = 15000
|
|
34
|
+
|
|
35
|
+
/** push 可能走网络,单独给更长的超时。 */
|
|
36
|
+
const GIT_PUSH_TIMEOUT_MS = 120000
|
|
37
|
+
|
|
38
|
+
/** 单条 git 命令输出上限(字节)。 */
|
|
39
|
+
const GIT_MAX_BUFFER = 32 * 1024 * 1024
|
|
40
|
+
|
|
41
|
+
/** 仓库发现:最大深度与最多返回条数(防止选中家目录时把整盘扫穿)。 */
|
|
42
|
+
const SCAN_MAX_DEPTH = 4
|
|
43
|
+
const SCAN_MAX_REPOS = 200
|
|
44
|
+
|
|
45
|
+
/** 发现时跳过的目录名:构建产物、依赖与 VCS 内部目录,进去也没有独立仓库。 */
|
|
46
|
+
const SKIP_DIRS = new Set([
|
|
47
|
+
'node_modules', '.git', 'dist', 'build', 'out', 'target', 'vendor',
|
|
48
|
+
'.next', '.nuxt', '.cache', '.venv', 'venv', '__pycache__', '.idea', '.vscode',
|
|
49
|
+
'Pods', 'DerivedData', '.gradle', '.m2', 'coverage', '.pnpm-store', '.yarn',
|
|
50
|
+
])
|
|
51
|
+
|
|
52
|
+
/** 提交列表默认条数 / 上限。 */
|
|
53
|
+
const DEFAULT_LIMIT = 100
|
|
54
|
+
const MAX_LIMIT = 500
|
|
55
|
+
|
|
56
|
+
/** 一次 diff 最多回多少行(防止超大提交把面板卡死)。 */
|
|
57
|
+
const MAX_DIFF_LINES = 4000
|
|
58
|
+
|
|
59
|
+
/** 单文件预览最多回多少字节。 */
|
|
60
|
+
const MAX_FILE_BYTES = 512 * 1024
|
|
61
|
+
|
|
62
|
+
/** 提交列表字段分隔符(RS/US,正文里不会出现)。 */
|
|
63
|
+
const RS = '\u001e'
|
|
64
|
+
const US = '\u001f'
|
|
65
|
+
|
|
66
|
+
/** 提交列表的 pretty 格式:哈希 / 短哈希 / 作者 / 邮箱 / 作者时间 / 提交者 / 提交者时间 / 父提交 / 引用 / 标题 / 正文。 */
|
|
67
|
+
const LOG_FORMAT = ['%H', '%h', '%an', '%ae', '%aI', '%cn', '%cI', '%P', '%D', '%s', '%b'].join('%x1f') + '%x1e'
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 跑一条 git 命令。
|
|
71
|
+
* @param {string} cwd 仓库目录(作为 -C 的目标)
|
|
72
|
+
* @param {string[]} args git 子命令与参数
|
|
73
|
+
* @param {{ timeout?: number, allowFail?: boolean }} [options]
|
|
74
|
+
* @returns {Promise<string>} 标准输出(已去尾空白)
|
|
75
|
+
*/
|
|
76
|
+
function git(cwd, args, options = {}) {
|
|
77
|
+
const timeout = Number(options.timeout) > 0 ? Number(options.timeout) : GIT_TIMEOUT_MS
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
execFile(
|
|
80
|
+
'git',
|
|
81
|
+
['-C', cwd, '--no-pager', ...args],
|
|
82
|
+
{
|
|
83
|
+
timeout,
|
|
84
|
+
maxBuffer: GIT_MAX_BUFFER,
|
|
85
|
+
windowsHide: true,
|
|
86
|
+
env: {
|
|
87
|
+
...process.env,
|
|
88
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
89
|
+
GIT_PAGER: 'cat',
|
|
90
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
91
|
+
LC_ALL: 'C',
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
(error, stdout, stderr) => {
|
|
95
|
+
if (error) {
|
|
96
|
+
// 有些命令(git diff --no-index / diff --quiet)用退出码表达「有差异」,
|
|
97
|
+
// 调用方显式 allowFail 时照常返回 stdout。
|
|
98
|
+
if (options.allowFail) {
|
|
99
|
+
resolve(String(stdout || ''))
|
|
100
|
+
return
|
|
101
|
+
}
|
|
102
|
+
const detail = String(stderr || '').trim() || (error && error.message) || String(error)
|
|
103
|
+
reject(new Error(detail))
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
resolve(String(stdout || ''))
|
|
107
|
+
},
|
|
108
|
+
)
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 路径是否可当作仓库目录使用:绝对路径、无 NUL、真实存在且是目录。 */
|
|
113
|
+
async function assertDirectory(path, label) {
|
|
114
|
+
if (typeof path !== 'string' || path.length === 0) throw new Error((label || '路径') + '不能为空')
|
|
115
|
+
if (path.includes('\0')) throw new Error((label || '路径') + '含非法字符')
|
|
116
|
+
if (!isAbsolute(path)) throw new Error((label || '路径') + '必须是绝对路径:' + path)
|
|
117
|
+
let info
|
|
118
|
+
try {
|
|
119
|
+
info = await fsp.stat(path)
|
|
120
|
+
} catch {
|
|
121
|
+
throw new Error((label || '路径') + '不存在或不可读:' + path)
|
|
122
|
+
}
|
|
123
|
+
if (!info.isDirectory()) throw new Error((label || '路径') + '不是目录:' + path)
|
|
124
|
+
return path
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 校验仓库路径并确认它确实是 git 仓库(有 .git 或处于工作树内)。 */
|
|
128
|
+
async function assertRepo(path) {
|
|
129
|
+
await assertDirectory(path, '仓库目录')
|
|
130
|
+
try {
|
|
131
|
+
const top = (await git(path, ['rev-parse', '--show-toplevel'])).trim()
|
|
132
|
+
return top.length > 0 ? top : path
|
|
133
|
+
} catch (error) {
|
|
134
|
+
throw new Error('不是 Git 仓库:' + path + '(' + ((error && error.message) || String(error)) + ')')
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 校验仓库内的相对路径:不许绝对路径、不许 .. 逃逸。 */
|
|
139
|
+
function assertRepoPath(path) {
|
|
140
|
+
if (typeof path !== 'string' || path.length === 0) throw new Error('文件路径不能为空')
|
|
141
|
+
if (path.includes('\0')) throw new Error('文件路径含非法字符')
|
|
142
|
+
if (isAbsolute(path)) throw new Error('文件路径必须是仓库内的相对路径:' + path)
|
|
143
|
+
const parts = path.split(/[\\/]+/)
|
|
144
|
+
if (parts.some((p) => p === '..')) throw new Error('文件路径不允许跳出仓库:' + path)
|
|
145
|
+
return path
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 该目录自身是否是 git 仓库工作树(有 .git 文件或目录)。 */
|
|
149
|
+
async function isRepoRoot(dir) {
|
|
150
|
+
try {
|
|
151
|
+
const info = await fsp.stat(join(dir, '.git'))
|
|
152
|
+
return info.isDirectory() || info.isFile()
|
|
153
|
+
} catch {
|
|
154
|
+
return false
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 相对路径转成用 / 分隔的展示串(Windows 反斜杠统一)。 */
|
|
159
|
+
function posixRel(from, to) {
|
|
160
|
+
const rel = relative(from, to)
|
|
161
|
+
if (rel === '') return '.'
|
|
162
|
+
return rel.split(sep).join('/')
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 读一个仓库的摘要:当前分支、HEAD、工作区是否干净、最近一条提交。
|
|
167
|
+
* 不是仓库(或 git 报错)时返回 null,调用方按「不是仓库」处理。
|
|
168
|
+
*/
|
|
169
|
+
async function repoSummary(dir) {
|
|
170
|
+
let branch = ''
|
|
171
|
+
let head = ''
|
|
172
|
+
let dirty = 0
|
|
173
|
+
let last = null
|
|
174
|
+
try {
|
|
175
|
+
branch = (await git(dir, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
|
|
176
|
+
} catch {
|
|
177
|
+
return null
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
head = (await git(dir, ['rev-parse', '--short', 'HEAD'])).trim()
|
|
181
|
+
} catch {
|
|
182
|
+
head = ''
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
const status = await git(dir, ['status', '--porcelain'])
|
|
186
|
+
dirty = status.split('\n').filter((line) => line.trim().length > 0).length
|
|
187
|
+
} catch {
|
|
188
|
+
dirty = 0
|
|
189
|
+
}
|
|
190
|
+
if (head) {
|
|
191
|
+
try {
|
|
192
|
+
const raw = await git(dir, ['log', '-1', '--pretty=format:%h' + US + '%aI' + US + '%an' + US + '%s'])
|
|
193
|
+
const parts = raw.split(US)
|
|
194
|
+
if (parts.length >= 4) {
|
|
195
|
+
last = { sha: parts[0], date: parts[1], author: parts[2], subject: parts[3] }
|
|
196
|
+
}
|
|
197
|
+
} catch {
|
|
198
|
+
last = null
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return { branch, head, dirty, last }
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* 在 root 下发现仓库:root 自身 + 指定深度内的子目录仓库。
|
|
206
|
+
* 每个候选目录先判 .git 存在,再问 git 拿摘要,避免把普通目录当仓库。
|
|
207
|
+
*/
|
|
208
|
+
async function discoverRepos(root, depth, includeSubdirs) {
|
|
209
|
+
const found = []
|
|
210
|
+
const seen = new Set()
|
|
211
|
+
const maxDepth = Math.min(Math.max(Number(depth) || 0, 0), SCAN_MAX_DEPTH)
|
|
212
|
+
|
|
213
|
+
async function consider(dir) {
|
|
214
|
+
if (found.length >= SCAN_MAX_REPOS) return
|
|
215
|
+
if (seen.has(dir)) return
|
|
216
|
+
seen.add(dir)
|
|
217
|
+
if (!(await isRepoRoot(dir))) return
|
|
218
|
+
const summary = await repoSummary(dir)
|
|
219
|
+
if (summary === null) return
|
|
220
|
+
found.push(Object.assign({
|
|
221
|
+
path: dir,
|
|
222
|
+
name: basename(dir) || dir,
|
|
223
|
+
relPath: posixRel(root, dir),
|
|
224
|
+
isRoot: dir === root,
|
|
225
|
+
}, summary))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
await consider(root)
|
|
229
|
+
if (!includeSubdirs || maxDepth === 0) return found
|
|
230
|
+
|
|
231
|
+
async function walk(dir, level) {
|
|
232
|
+
if (level > maxDepth || found.length >= SCAN_MAX_REPOS) return
|
|
233
|
+
let entries
|
|
234
|
+
try {
|
|
235
|
+
entries = await fsp.readdir(dir, { withFileTypes: true })
|
|
236
|
+
} catch {
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
for (const entry of entries) {
|
|
240
|
+
if (found.length >= SCAN_MAX_REPOS) return
|
|
241
|
+
if (!entry.isDirectory()) continue
|
|
242
|
+
if (SKIP_DIRS.has(entry.name)) continue
|
|
243
|
+
if (entry.name.startsWith('.')) continue
|
|
244
|
+
const child = join(dir, entry.name)
|
|
245
|
+
await consider(child)
|
|
246
|
+
await walk(child, level + 1)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
await walk(root, 1)
|
|
251
|
+
return found
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 把 git log 的原始输出解析成提交对象数组。 */
|
|
255
|
+
function parseLog(raw) {
|
|
256
|
+
const commits = []
|
|
257
|
+
for (const record of String(raw || '').split(RS)) {
|
|
258
|
+
const text = record.replace(/^\n/, '')
|
|
259
|
+
if (text.trim().length === 0) continue
|
|
260
|
+
const parts = text.split(US)
|
|
261
|
+
if (parts.length < 10) continue
|
|
262
|
+
const body = parts.length > 10 ? parts.slice(10).join(US) : ''
|
|
263
|
+
commits.push({
|
|
264
|
+
sha: parts[0],
|
|
265
|
+
shortSha: parts[1],
|
|
266
|
+
author: parts[2],
|
|
267
|
+
authorEmail: parts[3],
|
|
268
|
+
authorDate: parts[4],
|
|
269
|
+
committer: parts[5],
|
|
270
|
+
committerDate: parts[6],
|
|
271
|
+
parents: parts[7] ? parts[7].split(' ').filter(Boolean) : [],
|
|
272
|
+
refs: parts[8] ? parts[8].split(',').map((x) => x.trim()).filter(Boolean) : [],
|
|
273
|
+
subject: parts[9],
|
|
274
|
+
body: body.trim(),
|
|
275
|
+
})
|
|
276
|
+
}
|
|
277
|
+
return commits
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** 把 YYYY-MM-DD 或 ISO 时间转成 git 认识的 --since/--until 值;无效返回空串。 */
|
|
281
|
+
function normalizeDate(value) {
|
|
282
|
+
const text = typeof value === 'string' ? value.trim() : ''
|
|
283
|
+
if (!text) return ''
|
|
284
|
+
// 只接受日期与常见 ISO 形式,避免把任意字符串塞给 git
|
|
285
|
+
if (!/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2})?)?/.test(text)) return ''
|
|
286
|
+
return text
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* 读一个仓库的提交记录。
|
|
291
|
+
* @param {string} repo 仓库目录
|
|
292
|
+
* @param {{ limit?: number, skip?: number, search?: string, searchIn?: string, author?: string, branch?: string, path?: string, since?: string, until?: string }} options
|
|
293
|
+
* searchIn: 'message'(只搜说明,默认)| 'all'(说明 + 作者 + 哈希)
|
|
294
|
+
*/
|
|
295
|
+
async function readCommits(repo, options) {
|
|
296
|
+
await assertDirectory(repo, '仓库目录')
|
|
297
|
+
const limit = Math.min(Math.max(Number(options.limit) || DEFAULT_LIMIT, 1), MAX_LIMIT)
|
|
298
|
+
const skip = Math.max(Number(options.skip) || 0, 0)
|
|
299
|
+
const args = ['log', '--no-color', '--pretty=format:' + LOG_FORMAT, '-n', String(limit)]
|
|
300
|
+
if (skip > 0) args.push('--skip', String(skip))
|
|
301
|
+
const search = typeof options.search === 'string' ? options.search.trim() : ''
|
|
302
|
+
if (search) {
|
|
303
|
+
if (options.searchIn === 'all') {
|
|
304
|
+
// 同时匹配说明/正文/作者/哈希:--grep 与 --author 是「或」关系,用 --all-match 会变「且」,
|
|
305
|
+
// 所以这里分开取两次再按顺序合并会打乱时间线——改用 pickaxe 风格的组合不可靠,
|
|
306
|
+
// 直接在一次 log 里用多个 --grep(默认就是「或」)。
|
|
307
|
+
args.push('--grep', search, '-i', '--author', search)
|
|
308
|
+
} else {
|
|
309
|
+
args.push('--grep', search, '-i')
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
const author = typeof options.author === 'string' ? options.author.trim() : ''
|
|
313
|
+
// searchIn=all 时 author 已作为关键词参与匹配,再叠一次会变成「且」,跳过
|
|
314
|
+
if (author && options.searchIn !== 'all') args.push('--author', author)
|
|
315
|
+
const since = normalizeDate(options.since)
|
|
316
|
+
if (since) args.push('--since', since)
|
|
317
|
+
const until = normalizeDate(options.until)
|
|
318
|
+
if (until) args.push('--until', until)
|
|
319
|
+
const branch = typeof options.branch === 'string' ? options.branch.trim() : ''
|
|
320
|
+
args.push(branch || 'HEAD')
|
|
321
|
+
// 路径过滤放在 -- 之后,避免和分支名混淆
|
|
322
|
+
const path = typeof options.path === 'string' ? options.path.trim() : ''
|
|
323
|
+
if (path) args.push('--', assertRepoPath(path))
|
|
324
|
+
const raw = await git(repo, args)
|
|
325
|
+
return parseLog(raw)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 把统一 diff 文本按文件切块并解析出每个 hunk 的行。 */
|
|
329
|
+
function parseDiff(raw) {
|
|
330
|
+
const files = []
|
|
331
|
+
let current = null
|
|
332
|
+
let hunk = null
|
|
333
|
+
const lines = String(raw || '').split('\n')
|
|
334
|
+
for (const line of lines) {
|
|
335
|
+
if (line.startsWith('diff --git ')) {
|
|
336
|
+
if (current) files.push(current)
|
|
337
|
+
const m = /^diff --git a\/(.*) b\/(.*)$/.exec(line)
|
|
338
|
+
current = {
|
|
339
|
+
path: m ? m[2] : '',
|
|
340
|
+
oldPath: m ? m[1] : '',
|
|
341
|
+
status: 'modified',
|
|
342
|
+
binary: false,
|
|
343
|
+
additions: 0,
|
|
344
|
+
deletions: 0,
|
|
345
|
+
hunks: [],
|
|
346
|
+
}
|
|
347
|
+
hunk = null
|
|
348
|
+
continue
|
|
349
|
+
}
|
|
350
|
+
if (current === null) continue
|
|
351
|
+
if (line.startsWith('new file mode')) { current.status = 'added'; continue }
|
|
352
|
+
if (line.startsWith('deleted file mode')) { current.status = 'deleted'; continue }
|
|
353
|
+
if (line.startsWith('rename from ')) { current.oldPath = line.slice(12); current.status = 'renamed'; continue }
|
|
354
|
+
if (line.startsWith('rename to ')) { current.path = line.slice(10); continue }
|
|
355
|
+
if (line.startsWith('Binary files ') || line === 'GIT binary patch') { current.binary = true; continue }
|
|
356
|
+
if (line.startsWith('@@')) {
|
|
357
|
+
const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
|
|
358
|
+
hunk = {
|
|
359
|
+
header: line,
|
|
360
|
+
oldStart: m ? Number(m[1]) : 0,
|
|
361
|
+
newStart: m ? Number(m[3]) : 0,
|
|
362
|
+
lines: [],
|
|
363
|
+
}
|
|
364
|
+
current.hunks.push(hunk)
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
if (line.startsWith('--- ') || line.startsWith('+++ ') || line.startsWith('index ')) continue
|
|
368
|
+
if (hunk === null) continue
|
|
369
|
+
const kind = line.startsWith('+') ? '+' : line.startsWith('-') ? '-' : line.startsWith('\\') ? '\\' : ' '
|
|
370
|
+
if (kind === '+') current.additions += 1
|
|
371
|
+
else if (kind === '-') current.deletions += 1
|
|
372
|
+
hunk.lines.push({ kind, text: line.slice(1) })
|
|
373
|
+
}
|
|
374
|
+
if (current) files.push(current)
|
|
375
|
+
// 超大 diff 截断:保留前面的文件,标记 truncated
|
|
376
|
+
let total = 0
|
|
377
|
+
const kept = []
|
|
378
|
+
for (const f of files) {
|
|
379
|
+
let lines2 = 0
|
|
380
|
+
for (const h of f.hunks) lines2 += h.lines.length
|
|
381
|
+
if (total + lines2 > MAX_DIFF_LINES) {
|
|
382
|
+
f.truncated = true
|
|
383
|
+
kept.push(f)
|
|
384
|
+
return { files: kept, truncated: true }
|
|
385
|
+
}
|
|
386
|
+
total += lines2
|
|
387
|
+
kept.push(f)
|
|
388
|
+
}
|
|
389
|
+
return { files: kept, truncated: false }
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 读一条提交的详情:说明、作者/提交者、变更文件与增删行数、完整 diff。 */
|
|
393
|
+
async function readCommit(repo, sha) {
|
|
394
|
+
await assertDirectory(repo, '仓库目录')
|
|
395
|
+
if (typeof sha !== 'string' || !/^[0-9a-fA-F]{4,64}$/.test(sha)) throw new Error('提交哈希不合法:' + sha)
|
|
396
|
+
const meta = await git(repo, ['show', '-s', '--no-color', '--pretty=format:%H' + US + '%h' + US + '%an' + US + '%ae' + US + '%aI' + US + '%cn' + US + '%ce' + US + '%cI' + US + '%P' + US + '%D' + US + '%s' + US + '%b', sha])
|
|
397
|
+
const parts = meta.split(US)
|
|
398
|
+
if (parts.length < 11) throw new Error('无法解析提交信息:' + sha)
|
|
399
|
+
const numstat = await git(repo, ['show', '--no-color', '--numstat', '--format=', sha])
|
|
400
|
+
const files = []
|
|
401
|
+
let additions = 0
|
|
402
|
+
let deletions = 0
|
|
403
|
+
for (const line of numstat.split('\n')) {
|
|
404
|
+
if (line.trim().length === 0) continue
|
|
405
|
+
const cols = line.split('\t')
|
|
406
|
+
if (cols.length < 3) continue
|
|
407
|
+
const added = cols[0] === '-' ? 0 : Number(cols[0]) || 0
|
|
408
|
+
const removed = cols[1] === '-' ? 0 : Number(cols[1]) || 0
|
|
409
|
+
additions += added
|
|
410
|
+
deletions += removed
|
|
411
|
+
files.push({ path: cols.slice(2).join('\t'), additions: added, deletions: removed })
|
|
412
|
+
}
|
|
413
|
+
let diff = { files: [], truncated: false }
|
|
414
|
+
try {
|
|
415
|
+
// 合并提交默认不展开 diff;--first-parent 取与第一个父提交的差异,正是用户想看的
|
|
416
|
+
const raw = await git(repo, ['show', '--no-color', '--format=', '--patch', '--first-parent', sha])
|
|
417
|
+
diff = parseDiff(raw)
|
|
418
|
+
} catch {
|
|
419
|
+
diff = { files: [], truncated: false }
|
|
420
|
+
}
|
|
421
|
+
return {
|
|
422
|
+
sha: parts[0],
|
|
423
|
+
shortSha: parts[1],
|
|
424
|
+
author: parts[2],
|
|
425
|
+
authorEmail: parts[3],
|
|
426
|
+
authorDate: parts[4],
|
|
427
|
+
committer: parts[5],
|
|
428
|
+
committerEmail: parts[6],
|
|
429
|
+
committerDate: parts[7],
|
|
430
|
+
parents: parts[8] ? parts[8].split(' ').filter(Boolean) : [],
|
|
431
|
+
refs: parts[9] ? parts[9].split(',').map((x) => x.trim()).filter(Boolean) : [],
|
|
432
|
+
subject: parts[10],
|
|
433
|
+
body: parts.slice(11).join(US).trim(),
|
|
434
|
+
additions,
|
|
435
|
+
deletions,
|
|
436
|
+
files,
|
|
437
|
+
diff,
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* 把任意路径解析成「所在仓库 + 仓库内相对路径」。
|
|
444
|
+
* 用于右键「查看 Git 历史」:不需要选目录弹窗,服务器上没有原生对话框也能用。
|
|
445
|
+
* @param {string} target 绝对路径(目录或文件)
|
|
446
|
+
*/
|
|
447
|
+
async function resolveRepoForPath(target) {
|
|
448
|
+
if (typeof target !== 'string' || target.length === 0) throw new Error('路径不能为空')
|
|
449
|
+
if (target.includes('\0')) throw new Error('路径含非法字符')
|
|
450
|
+
if (!isAbsolute(target)) throw new Error('路径必须是绝对路径:' + target)
|
|
451
|
+
let info
|
|
452
|
+
try {
|
|
453
|
+
info = await fsp.stat(target)
|
|
454
|
+
} catch {
|
|
455
|
+
throw new Error('路径不存在或不可读:' + target)
|
|
456
|
+
}
|
|
457
|
+
// 文件就取它所在的目录
|
|
458
|
+
const dir = info.isDirectory() ? target : join(target, '..')
|
|
459
|
+
let top = ''
|
|
460
|
+
try {
|
|
461
|
+
top = (await git(dir, ['rev-parse', '--show-toplevel'])).trim()
|
|
462
|
+
} catch (error) {
|
|
463
|
+
throw new Error('该路径不在任何 Git 仓库内:' + target + '(' + ((error && error.message) || String(error)) + ')')
|
|
464
|
+
}
|
|
465
|
+
if (!top) throw new Error('该路径不在任何 Git 仓库内:' + target)
|
|
466
|
+
// git 返回的是**真实路径**(macOS 的 /var 是 /private/var 的符号链接)。
|
|
467
|
+
// 直接用入参算相对路径会得到一串 ../,所以两边都先 realpath 再比。
|
|
468
|
+
let realTarget = target
|
|
469
|
+
let realTop = top
|
|
470
|
+
try { realTarget = await fsp.realpath(target) } catch { /* 保持原值 */ }
|
|
471
|
+
try { realTop = await fsp.realpath(top) } catch { /* 保持原值 */ }
|
|
472
|
+
const rel = posixRel(realTop, realTarget)
|
|
473
|
+
return {
|
|
474
|
+
repo: top,
|
|
475
|
+
repoName: basename(top) || top,
|
|
476
|
+
// 相对仓库根的路径;'..' 表示目标在仓库之上(理论上不会发生)
|
|
477
|
+
relPath: rel,
|
|
478
|
+
isDirectory: info.isDirectory(),
|
|
479
|
+
exists: true,
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** 读引用:当前分支、本地/远端分支、标签、远端。 */
|
|
484
|
+
async function readRefs(repo) {
|
|
485
|
+
await assertDirectory(repo, '仓库目录')
|
|
486
|
+
let head = ''
|
|
487
|
+
let branch = ''
|
|
488
|
+
let detached = false
|
|
489
|
+
try {
|
|
490
|
+
branch = (await git(repo, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
|
|
491
|
+
detached = branch === 'HEAD'
|
|
492
|
+
} catch {
|
|
493
|
+
branch = ''
|
|
494
|
+
}
|
|
495
|
+
try {
|
|
496
|
+
head = (await git(repo, ['rev-parse', '--short', 'HEAD'])).trim()
|
|
497
|
+
} catch {
|
|
498
|
+
head = ''
|
|
499
|
+
}
|
|
500
|
+
const out = { head, branch, detached, local: [], remote: [], tags: [], remotes: [], upstream: '', ahead: 0, behind: 0 }
|
|
501
|
+
try {
|
|
502
|
+
const raw = await git(repo, ['for-each-ref', '--format=%(refname)' + US + '%(refname:short)' + US + '%(objectname:short)' + US + '%(committerdate:iso-strict)' + US + '%(subject)', 'refs/heads', 'refs/remotes', 'refs/tags'])
|
|
503
|
+
for (const line of raw.split('\n')) {
|
|
504
|
+
if (!line.trim()) continue
|
|
505
|
+
const p = line.split(US)
|
|
506
|
+
if (p.length < 5) continue
|
|
507
|
+
const [full, short, sha, date, subject] = p
|
|
508
|
+
const row = { name: short, full, sha, date, subject }
|
|
509
|
+
if (full.startsWith('refs/heads/')) out.local.push(row)
|
|
510
|
+
else if (full.startsWith('refs/remotes/')) out.remote.push(row)
|
|
511
|
+
else if (full.startsWith('refs/tags/')) out.tags.push(row)
|
|
512
|
+
}
|
|
513
|
+
} catch { /* 空仓库:没有任何引用 */ }
|
|
514
|
+
try {
|
|
515
|
+
const list = await git(repo, ['remote'])
|
|
516
|
+
out.remotes = list.split('\n').map((x) => x.trim()).filter(Boolean)
|
|
517
|
+
} catch { out.remotes = [] }
|
|
518
|
+
try {
|
|
519
|
+
const up = (await git(repo, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])).trim()
|
|
520
|
+
out.upstream = up
|
|
521
|
+
const counts = await git(repo, ['rev-list', '--left-right', '--count', up + '...HEAD'])
|
|
522
|
+
const m = counts.trim().split(/\s+/)
|
|
523
|
+
out.behind = Number(m[0]) || 0
|
|
524
|
+
out.ahead = Number(m[1]) || 0
|
|
525
|
+
} catch { out.upstream = '' }
|
|
526
|
+
return out
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** 解析 git status --porcelain=v1 -z 的输出。 */
|
|
530
|
+
function parseStatus(raw) {
|
|
531
|
+
const entries = []
|
|
532
|
+
const parts = String(raw || '').split('\0')
|
|
533
|
+
for (let i = 0; i < parts.length; i++) {
|
|
534
|
+
const item = parts[i]
|
|
535
|
+
if (!item || item.length < 4) continue
|
|
536
|
+
const x = item[0]
|
|
537
|
+
const y = item[1]
|
|
538
|
+
const path = item.slice(3)
|
|
539
|
+
// 重命名/复制:下一个 NUL 段是原路径
|
|
540
|
+
let origPath = ''
|
|
541
|
+
if (x === 'R' || x === 'C' || y === 'R' || y === 'C') {
|
|
542
|
+
origPath = parts[i + 1] || ''
|
|
543
|
+
i += 1
|
|
544
|
+
}
|
|
545
|
+
entries.push({
|
|
546
|
+
path,
|
|
547
|
+
origPath,
|
|
548
|
+
index: x,
|
|
549
|
+
worktree: y,
|
|
550
|
+
staged: x !== ' ' && x !== '?',
|
|
551
|
+
untracked: x === '?',
|
|
552
|
+
conflicted: x === 'U' || y === 'U' || (x === 'A' && y === 'A') || (x === 'D' && y === 'D'),
|
|
553
|
+
})
|
|
554
|
+
}
|
|
555
|
+
return entries
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** 工作区状态:分支、领先落后、暂存区与未暂存改动。 */
|
|
559
|
+
async function readStatus(repo) {
|
|
560
|
+
await assertRepo(repo)
|
|
561
|
+
const refs = await readRefs(repo)
|
|
562
|
+
const raw = await git(repo, ['status', '--porcelain=v1', '-z', '--untracked-files=all'])
|
|
563
|
+
const entries = parseStatus(raw)
|
|
564
|
+
return {
|
|
565
|
+
branch: refs.branch,
|
|
566
|
+
head: refs.head,
|
|
567
|
+
detached: refs.detached,
|
|
568
|
+
upstream: refs.upstream,
|
|
569
|
+
ahead: refs.ahead,
|
|
570
|
+
behind: refs.behind,
|
|
571
|
+
entries,
|
|
572
|
+
stagedCount: entries.filter((e) => e.staged).length,
|
|
573
|
+
unstagedCount: entries.filter((e) => !e.staged && !e.untracked).length,
|
|
574
|
+
untrackedCount: entries.filter((e) => e.untracked).length,
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* 读差异:三种来源之一——某条提交(sha)、暂存区(staged)、工作区(默认)。
|
|
580
|
+
* path 给定时只看该文件。
|
|
581
|
+
*/
|
|
582
|
+
async function readDiff(repo, options) {
|
|
583
|
+
await assertRepo(repo)
|
|
584
|
+
const args = ['diff', '--no-color', '--no-ext-diff', '--patch']
|
|
585
|
+
const sha = typeof options.sha === 'string' ? options.sha.trim() : ''
|
|
586
|
+
const staged = options.staged === true
|
|
587
|
+
const untracked = options.untracked === true
|
|
588
|
+
let target = ''
|
|
589
|
+
if (sha) {
|
|
590
|
+
if (!/^[0-9a-fA-F]{4,64}$/.test(sha)) throw new Error('提交哈希不合法:' + sha)
|
|
591
|
+
// 提交 → 与第一个父提交比较;根提交用 --root
|
|
592
|
+
args.push('--first-parent', sha + '^!')
|
|
593
|
+
target = sha
|
|
594
|
+
} else if (untracked) {
|
|
595
|
+
// 未跟踪文件:用 --no-index 对空文件比,得到整份内容作为新增
|
|
596
|
+
const path = assertRepoPath(options.path)
|
|
597
|
+
const full = join(repo, path)
|
|
598
|
+
const raw = await git(repo, ['diff', '--no-color', '--no-ext-diff', '--no-index', '--', '/dev/null', full], { allowFail: true })
|
|
599
|
+
return { target: path, source: 'untracked', truncated: false, files: parseDiff(raw).files }
|
|
600
|
+
} else {
|
|
601
|
+
if (staged) args.push('--cached')
|
|
602
|
+
target = staged ? 'staged' : 'worktree'
|
|
603
|
+
const path = typeof options.path === 'string' && options.path.trim() ? options.path.trim() : ''
|
|
604
|
+
if (path) args.push('--', assertRepoPath(path))
|
|
605
|
+
}
|
|
606
|
+
const raw = await git(repo, args, { allowFail: true })
|
|
607
|
+
const parsed = parseDiff(raw)
|
|
608
|
+
return { target, source: sha ? 'commit' : staged ? 'staged' : 'worktree', truncated: parsed.truncated, files: parsed.files }
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** 读仓库内某个文件的文本内容(可指定提交)。 */
|
|
612
|
+
async function readFile(repo, options) {
|
|
613
|
+
await assertRepo(repo)
|
|
614
|
+
const path = assertRepoPath(options.path)
|
|
615
|
+
const sha = typeof options.sha === 'string' ? options.sha.trim() : ''
|
|
616
|
+
let content = ''
|
|
617
|
+
if (sha) {
|
|
618
|
+
if (!/^[0-9a-fA-F]{4,64}$/.test(sha)) throw new Error('提交哈希不合法:' + sha)
|
|
619
|
+
content = await git(repo, ['show', sha + ':' + path])
|
|
620
|
+
} else {
|
|
621
|
+
const full = join(repo, path)
|
|
622
|
+
const info = await fsp.stat(full)
|
|
623
|
+
if (info.size > MAX_FILE_BYTES) {
|
|
624
|
+
content = (await fsp.readFile(full)).subarray(0, MAX_FILE_BYTES).toString('utf8')
|
|
625
|
+
return { path, sha, content, truncated: true, size: info.size }
|
|
626
|
+
}
|
|
627
|
+
content = await fsp.readFile(full, 'utf8')
|
|
628
|
+
return { path, sha, content, truncated: false, size: info.size }
|
|
629
|
+
}
|
|
630
|
+
const truncated = content.length > MAX_FILE_BYTES
|
|
631
|
+
return { path, sha, content: truncated ? content.slice(0, MAX_FILE_BYTES) : content, truncated, size: content.length }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
/** 暂存 / 取消暂存指定文件。 */
|
|
635
|
+
async function stageFiles(repo, options) {
|
|
636
|
+
const top = await assertRepo(repo)
|
|
637
|
+
if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
|
|
638
|
+
const paths = Array.isArray(options.paths) ? options.paths : []
|
|
639
|
+
if (paths.length === 0) throw new Error('至少指定一个文件')
|
|
640
|
+
const clean = paths.map(assertRepoPath)
|
|
641
|
+
if (options.unstage === true) {
|
|
642
|
+
await git(top, ['reset', '--', ...clean])
|
|
643
|
+
} else {
|
|
644
|
+
// 新文件与已跟踪文件统一用 add;删除的文件也由 add -A 覆盖
|
|
645
|
+
await git(top, ['add', '--', ...clean])
|
|
646
|
+
}
|
|
647
|
+
return readStatus(top)
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** 提交暂存内容(或指定的文件)。 */
|
|
651
|
+
async function createCommit(repo, options) {
|
|
652
|
+
const top = await assertRepo(repo)
|
|
653
|
+
if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
|
|
654
|
+
const message = typeof options.message === 'string' ? options.message.trim() : ''
|
|
655
|
+
if (message.length === 0) throw new Error('提交说明不能为空')
|
|
656
|
+
const paths = Array.isArray(options.paths) ? options.paths : []
|
|
657
|
+
if (paths.length > 0) {
|
|
658
|
+
// 只提交指定文件:先单独暂存,再提交这些路径
|
|
659
|
+
const clean = paths.map(assertRepoPath)
|
|
660
|
+
await git(top, ['add', '--', ...clean])
|
|
661
|
+
await git(top, ['commit', '-m', message, '--', ...clean])
|
|
662
|
+
} else {
|
|
663
|
+
const staged = await git(top, ['diff', '--cached', '--name-only'])
|
|
664
|
+
if (staged.trim().length === 0) throw new Error('暂存区没有可提交的改动')
|
|
665
|
+
await git(top, ['commit', '-m', message])
|
|
666
|
+
}
|
|
667
|
+
const sha = (await git(top, ['rev-parse', '--short', 'HEAD'])).trim()
|
|
668
|
+
const detail = await readCommit(top, sha)
|
|
669
|
+
return { repo: top, commit: detail }
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** 推送到远端。 */
|
|
673
|
+
async function pushRepo(repo, options) {
|
|
674
|
+
const top = await assertRepo(repo)
|
|
675
|
+
if (options.confirm !== true) throw new Error('写操作需要 confirm: true')
|
|
676
|
+
const remote = typeof options.remote === 'string' ? options.remote.trim() : ''
|
|
677
|
+
const branch = typeof options.branch === 'string' ? options.branch.trim() : ''
|
|
678
|
+
const args = ['push']
|
|
679
|
+
if (remote) args.push(remote)
|
|
680
|
+
if (branch) args.push(branch)
|
|
681
|
+
const output = await git(top, args, { timeout: GIT_PUSH_TIMEOUT_MS, allowFail: true })
|
|
682
|
+
return { repo: top, remote: remote || '(默认)', branch: branch || '(当前分支)', output: output.trim() }
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/** 读取 git 版本(面板用来提示环境是否就绪)。 */
|
|
686
|
+
async function gitVersion() {
|
|
687
|
+
try {
|
|
688
|
+
return (await git(process.cwd(), ['--version'])).trim()
|
|
689
|
+
} catch {
|
|
690
|
+
return ''
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** 统一的 JSON 错误响应。 */
|
|
695
|
+
function fail(res, status, message, code) {
|
|
696
|
+
sendJson(res, status, { ok: false, error: { code: code || 'git-error', message } })
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** 路由主体:按 URL 末段分发。 */
|
|
700
|
+
async function handleGit(req, res) {
|
|
701
|
+
let url
|
|
702
|
+
try {
|
|
703
|
+
url = new URL(req.url || '/', 'http://dsh.internal')
|
|
704
|
+
} catch {
|
|
705
|
+
fail(res, 400, '请求地址无法解析')
|
|
706
|
+
return
|
|
707
|
+
}
|
|
708
|
+
const method = url.pathname.replace(/^\/dsh-dock\/git\/?/, '').split('/')[0] || ''
|
|
709
|
+
|
|
710
|
+
try {
|
|
711
|
+
if (method === 'info' && (req.method === 'GET' || req.method === 'POST')) {
|
|
712
|
+
// info 不需要请求体:GET 直接返回,POST 读空体避免连接上残留未消费数据
|
|
713
|
+
if (req.method === 'POST') await readBody(req).catch(() => ({}))
|
|
714
|
+
const version = await gitVersion()
|
|
715
|
+
sendJson(res, 200, {
|
|
716
|
+
ok: true,
|
|
717
|
+
data: {
|
|
718
|
+
defaultDir: process.cwd(),
|
|
719
|
+
home: homedir(),
|
|
720
|
+
platform: process.platform,
|
|
721
|
+
gitVersion: version,
|
|
722
|
+
available: version.length > 0,
|
|
723
|
+
},
|
|
724
|
+
})
|
|
725
|
+
return
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
if (req.method !== 'POST') {
|
|
729
|
+
fail(res, 405, '只支持 POST(info 除外)', 'method-not-allowed')
|
|
730
|
+
return
|
|
731
|
+
}
|
|
732
|
+
const body = await readBody(req)
|
|
733
|
+
|
|
734
|
+
if (method === 'repos') {
|
|
735
|
+
const root = await assertDirectory(body && body.dir, '查询目录')
|
|
736
|
+
const depth = Number(body && body.depth)
|
|
737
|
+
const includeSubdirs = body ? body.includeSubdirs !== false : true
|
|
738
|
+
const repos = await discoverRepos(root, Number.isFinite(depth) ? depth : 3, includeSubdirs)
|
|
739
|
+
sendJson(res, 200, { ok: true, data: { root, repos } })
|
|
740
|
+
return
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
if (method === 'resolve') {
|
|
744
|
+
const resolved = await resolveRepoForPath(body && body.path)
|
|
745
|
+
sendJson(res, 200, { ok: true, data: resolved })
|
|
746
|
+
return
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
if (method === 'refs') {
|
|
750
|
+
const refs = await readRefs(await assertRepo(body && body.repo))
|
|
751
|
+
sendJson(res, 200, { ok: true, data: refs })
|
|
752
|
+
return
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
if (method === 'status') {
|
|
756
|
+
const status = await readStatus(body && body.repo)
|
|
757
|
+
sendJson(res, 200, { ok: true, data: status })
|
|
758
|
+
return
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
if (method === 'diff') {
|
|
762
|
+
const repo = await assertRepo(body && body.repo)
|
|
763
|
+
const diff = await readDiff(repo, body || {})
|
|
764
|
+
sendJson(res, 200, { ok: true, data: diff })
|
|
765
|
+
return
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
if (method === 'file') {
|
|
769
|
+
const repo = await assertRepo(body && body.repo)
|
|
770
|
+
const file = await readFile(repo, body || {})
|
|
771
|
+
sendJson(res, 200, { ok: true, data: file })
|
|
772
|
+
return
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
if (method === 'stage') {
|
|
776
|
+
const status = await stageFiles(body && body.repo, body || {})
|
|
777
|
+
sendJson(res, 200, { ok: true, data: status })
|
|
778
|
+
return
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
if (method === 'create-commit') {
|
|
782
|
+
const result = await createCommit(body && body.repo, body || {})
|
|
783
|
+
sendJson(res, 200, { ok: true, data: result })
|
|
784
|
+
return
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
if (method === 'push') {
|
|
788
|
+
const result = await pushRepo(body && body.repo, body || {})
|
|
789
|
+
sendJson(res, 200, { ok: true, data: result })
|
|
790
|
+
return
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
if (method === 'authors') {
|
|
794
|
+
// 提交人下拉的可选值:取最近一批提交里的作者,去重后按出现次数排序
|
|
795
|
+
const repo = body && body.repo
|
|
796
|
+
if (!repo) { fail(res, 400, '缺少仓库路径', 'no-repo'); return }
|
|
797
|
+
await assertDirectory(repo, '仓库目录')
|
|
798
|
+
const raw = await git(repo, ['log', '--no-color', '--pretty=format:%an', '-n', '500', 'HEAD'])
|
|
799
|
+
const counts = new Map()
|
|
800
|
+
for (const line of String(raw || '').split('\n')) {
|
|
801
|
+
const name = line.trim()
|
|
802
|
+
if (!name) continue
|
|
803
|
+
counts.set(name, (counts.get(name) || 0) + 1)
|
|
804
|
+
}
|
|
805
|
+
const authors = [...counts.entries()]
|
|
806
|
+
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
807
|
+
.slice(0, 100)
|
|
808
|
+
.map(([name, count]) => ({ name, count }))
|
|
809
|
+
sendJson(res, 200, { ok: true, data: { authors } })
|
|
810
|
+
return
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
if (method === 'commits') {
|
|
814
|
+
const single = body && typeof body.repo === 'string' && body.repo.length > 0
|
|
815
|
+
if (single) {
|
|
816
|
+
const commits = await readCommits(body.repo, body)
|
|
817
|
+
sendJson(res, 200, { ok: true, data: { results: [{ repo: body.repo, ok: true, commits }] } })
|
|
818
|
+
return
|
|
819
|
+
}
|
|
820
|
+
const list = Array.isArray(body && body.repos) ? body.repos : []
|
|
821
|
+
if (list.length === 0) {
|
|
822
|
+
fail(res, 400, '至少选择一个仓库', 'no-repo')
|
|
823
|
+
return
|
|
824
|
+
}
|
|
825
|
+
if (list.length > 20) {
|
|
826
|
+
fail(res, 400, '一次最多查询 20 个仓库', 'too-many-repos')
|
|
827
|
+
return
|
|
828
|
+
}
|
|
829
|
+
const results = []
|
|
830
|
+
for (const repo of list) {
|
|
831
|
+
try {
|
|
832
|
+
const commits = await readCommits(repo, body)
|
|
833
|
+
results.push({ repo, ok: true, commits })
|
|
834
|
+
} catch (error) {
|
|
835
|
+
results.push({ repo, ok: false, error: (error && error.message) || String(error), commits: [] })
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
sendJson(res, 200, { ok: true, data: { results } })
|
|
839
|
+
return
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
if (method === 'commit') {
|
|
843
|
+
const commit = await readCommit(body && body.repo, body && body.sha)
|
|
844
|
+
sendJson(res, 200, { ok: true, data: { commit } })
|
|
845
|
+
return
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
fail(res, 404, '未知接口:' + method, 'method-not-found')
|
|
849
|
+
} catch (error) {
|
|
850
|
+
fail(res, 500, (error && error.message) || String(error))
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/** 功能注册表条目:index.js 组装 FEATURES 时使用。 */
|
|
855
|
+
export const feature = {
|
|
856
|
+
id: 'git',
|
|
857
|
+
name: 'Git 管理',
|
|
858
|
+
description: '仓库工作台:历史与工作区浏览、差异预览、暂存提交与推送',
|
|
859
|
+
// 只读浏览无副作用,默认打开;写操作仍需面板里显式确认
|
|
860
|
+
defaultEnabled: true,
|
|
861
|
+
setup(ctx) {
|
|
862
|
+
const webServer = ctx.get('webServer')
|
|
863
|
+
if (webServer === undefined) throw new Error('webServer 服务不可用,无法提供 Git 管理路由')
|
|
864
|
+
const dispose = webServer.register({
|
|
865
|
+
kind: 'prefix',
|
|
866
|
+
auth: 'required',
|
|
867
|
+
path: '/dsh-dock/git',
|
|
868
|
+
handler: (req, res, peer) => {
|
|
869
|
+
if (rejectUntrustedRequest(ctx, req, res, peer)) return
|
|
870
|
+
void handleGit(req, res)
|
|
871
|
+
},
|
|
872
|
+
})
|
|
873
|
+
return () => {
|
|
874
|
+
try { dispose() } catch { /* 已卸载 */ }
|
|
875
|
+
}
|
|
876
|
+
},
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
export {
|
|
880
|
+
parseLog, parseDiff, parseStatus, discoverRepos, readCommits, readCommit,
|
|
881
|
+
readRefs, readStatus, readDiff, readFile, stageFiles, createCommit, pushRepo,
|
|
882
|
+
resolveRepoForPath,
|
|
883
|
+
repoSummary, assertDirectory, assertRepo, assertRepoPath,
|
|
884
|
+
}
|