vcs-patch-deploy 1.1.1 → 1.3.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/lib/svn.js CHANGED
@@ -102,6 +102,11 @@ function normalizeRelativePath (rawPath, sourceDir, svnRoot) {
102
102
  const trunkMatch = normalized.match(/^trunk\/(.+)$/)
103
103
  if (trunkMatch) return trunkMatch[1]
104
104
 
105
+ // svn 对相对目标会输出相对路径(如 "app/x.php"),直接使用
106
+ if (!path.isAbsolute(rawPath)) {
107
+ return normalized
108
+ }
109
+
105
110
  throw new Error(`无法解析 SVN 路径:${rawPath}`)
106
111
  }
107
112
 
@@ -109,6 +114,41 @@ function normalizeRelativePath (rawPath, sourceDir, svnRoot) {
109
114
  * @typedef {{ action: 'A'|'M'|'D', relativePath: string }} DiffEntry
110
115
  */
111
116
 
117
+ /**
118
+ * 解析 `svn diff --summarize` 输出
119
+ * @param {string} output
120
+ * @param {string} sourceDir
121
+ * @param {string} svnRoot
122
+ * @returns {Array<DiffEntry & { parseError?: string }>}
123
+ */
124
+ function parseSummarizeOutput (output, sourceDir, svnRoot) {
125
+ /** @type {Array<DiffEntry & { parseError?: string }>} */
126
+ const entries = []
127
+
128
+ for (const line of output.split(/\r?\n/)) {
129
+ // svn diff --summarize 的状态包含 A/M/D/R(R = 替换)
130
+ const match = line.match(/^\s*([AMDR])\s+(.+)$/)
131
+ if (!match) continue
132
+
133
+ const action = match[1] === 'R' ? 'M' : match[1]
134
+
135
+ try {
136
+ entries.push({
137
+ action: /** @type {'A'|'M'|'D'} */ (action),
138
+ relativePath: normalizeRelativePath(match[2], sourceDir, svnRoot)
139
+ })
140
+ } catch (error) {
141
+ entries.push({
142
+ action: /** @type {'A'|'M'|'D'} */ (action),
143
+ relativePath: match[2],
144
+ parseError: error.message
145
+ })
146
+ }
147
+ }
148
+
149
+ return entries
150
+ }
151
+
112
152
  /**
113
153
  * @param {object} options
114
154
  * @param {string} options.sourceDir
@@ -125,28 +165,377 @@ function getSvnDiffSummary ({ sourceDir, fromRev, toRev, svnExe = findSvnExe() }
125
165
  svnRoot
126
166
  )
127
167
 
128
- /** @type {DiffEntry[]} */
168
+ return parseSummarizeOutput(output, sourceDir, svnRoot)
169
+ }
170
+
171
+ /**
172
+ * 工作副本 vs 指定 revision 的差异(单 revision 形式,包含未提交改动)
173
+ * @param {object} options
174
+ * @param {string} options.sourceDir
175
+ * @param {number} options.rev
176
+ * @param {string} [options.svnExe]
177
+ * @returns {Array<DiffEntry & { parseError?: string }>}
178
+ */
179
+ function getSvnDiffVsRevision ({ sourceDir, rev, svnExe = findSvnExe() }) {
180
+ const svnRoot = path.dirname(sourceDir)
181
+ const output = runSvn(
182
+ svnExe,
183
+ ['diff', '-r', String(rev), '--summarize', sourceDir],
184
+ svnRoot
185
+ )
186
+
187
+ return parseSummarizeOutput(output, sourceDir, svnRoot)
188
+ }
189
+
190
+ /**
191
+ * XML 属性值反转义(svn status --xml)
192
+ * @param {string} value
193
+ */
194
+ function decodeXmlAttr (value) {
195
+ return value
196
+ .replace(/&lt;/g, '<')
197
+ .replace(/&gt;/g, '>')
198
+ .replace(/&quot;/g, '"')
199
+ .replace(/&apos;/g, "'")
200
+ .replace(/&amp;/g, '&')
201
+ }
202
+
203
+ /**
204
+ * @param {string} attrs
205
+ * @param {string} name
206
+ */
207
+ function readXmlAttr (attrs, name) {
208
+ const match = attrs.match(new RegExp(`\\b${name}="([^"]*)"`))
209
+ return match ? decodeXmlAttr(match[1]) : null
210
+ }
211
+
212
+ /**
213
+ * 解析 `svn status --xml`(纯函数,便于测试)
214
+ *
215
+ * item: modified / added / deleted / replaced / missing / unversioned / conflicted / ...
216
+ * @param {string} xml
217
+ * @param {{ sourceDir: string, svnRoot: string }} paths
218
+ * @returns {{ entries: Array<DiffEntry & { parseError?: string }>, conflicted: string[] }}
219
+ */
220
+ function parseSvnStatusXml (xml, { sourceDir, svnRoot }) {
221
+ /** @type {Array<DiffEntry & { parseError?: string }>} */
129
222
  const entries = []
223
+ /** @type {string[]} */
224
+ const conflicted = []
130
225
 
131
- for (const line of output.split(/\r?\n/)) {
132
- const match = line.match(/^\s*([AMD])\s+(.+)$/)
133
- if (!match) continue
226
+ const entryRe = /<entry\s+path="([^"]*)"[^>]*>([\s\S]*?)<\/entry>/g
227
+ let match
134
228
 
229
+ while ((match = entryRe.exec(xml)) !== null) {
230
+ const rawPath = decodeXmlAttr(match[1])
231
+ const body = match[2]
232
+ const statusMatch = body.match(/<wc-status\b([^>]*?)(?:\/>|>([\s\S]*?)<\/wc-status>)/)
233
+ if (!statusMatch) continue
234
+
235
+ const attrs = statusMatch[1]
236
+ const item = readXmlAttr(attrs, 'item') || 'none'
237
+ const treeConflicted = readXmlAttr(attrs, 'tree-conflicted') === 'true'
238
+
239
+ let rel
135
240
  try {
136
- entries.push({
137
- action: /** @type {'A'|'M'|'D'} */ (match[1]),
138
- relativePath: normalizeRelativePath(match[2], sourceDir, svnRoot)
139
- })
241
+ rel = normalizeRelativePath(rawPath, sourceDir, svnRoot)
140
242
  } catch (error) {
243
+ entries.push({ action: 'M', relativePath: rawPath, parseError: error.message })
244
+ continue
245
+ }
246
+
247
+ if (item === 'conflicted' || treeConflicted) {
248
+ conflicted.push(rel)
249
+ continue
250
+ }
251
+
252
+ /** @type {'A'|'M'|'D'|null} */
253
+ let action = null
254
+ if (item === 'modified' || item === 'replaced') action = 'M'
255
+ else if (item === 'added') action = 'A'
256
+ else if (item === 'deleted' || item === 'missing') action = 'D'
257
+ else if (item === 'unversioned') action = 'A'
258
+ else if (item === 'obstructed' || item === 'incomplete') {
141
259
  entries.push({
142
- action: /** @type {'A'|'M'|'D'} */ (match[1]),
143
- relativePath: match[2],
144
- parseError: error.message
260
+ action: 'M',
261
+ relativePath: rel,
262
+ parseError: `SVN 状态异常(${item}): ${rel}`
145
263
  })
264
+ continue
265
+ }
266
+
267
+ if (action) {
268
+ entries.push({ action, relativePath: rel })
146
269
  }
147
270
  }
148
271
 
149
- return entries
272
+ return { entries, conflicted }
273
+ }
274
+
275
+ /**
276
+ * 解析 `svn propget -R --xml` 的输出,返回设置了属性的路径(sourceDir 相对)
277
+ * @param {string} xml
278
+ * @param {{ sourceDir: string, svnRoot: string }} paths
279
+ * @returns {string[]}
280
+ */
281
+ function parseSvnPropgetXml (xml, { sourceDir, svnRoot }) {
282
+ /** @type {Set<string>} */
283
+ const executable = new Set()
284
+ const targetRe = /<target\s+path="([^"]*)"[^>]*>([\s\S]*?)<\/target>/g
285
+ let match
286
+
287
+ while ((match = targetRe.exec(xml)) !== null) {
288
+ const rawPath = decodeXmlAttr(match[1])
289
+ const body = match[2]
290
+ if (!/<property\b/.test(body)) continue
291
+
292
+ try {
293
+ const rel = normalizeRelativePath(rawPath, sourceDir, svnRoot).replace(/\\/g, '/')
294
+ executable.add(rel)
295
+ } catch {
296
+ // 无法解析的路径忽略
297
+ }
298
+ }
299
+
300
+ return [...executable].sort()
301
+ }
302
+
303
+ /**
304
+ * 读取待打包文件中设置了 svn:executable 属性的路径
305
+ *
306
+ * Windows 上 fs.stat 不体现执行位;SVN 属性是跨平台的可靠来源。
307
+ *
308
+ * @param {object} options
309
+ * @param {string} options.sourceDir
310
+ * @param {string[]} options.files sourceDir 相对路径
311
+ * @param {string} [options.svnExe]
312
+ * @returns {string[]}
313
+ */
314
+ function getSvnExecutableFiles ({ sourceDir, files, svnExe = findSvnExe() }) {
315
+ if (!files || files.length === 0) {
316
+ return []
317
+ }
318
+
319
+ const svnRoot = path.dirname(sourceDir)
320
+ let output
321
+ try {
322
+ // 在 sourceDir 内执行并传 ".":输出路径相对 sourceDir,可直接用于匹配。
323
+ // 使用 --xml 避免路径中含 " - " 时被普通文本输出误拆。
324
+ output = runSvn(svnExe, ['propget', '-R', '--xml', 'svn:executable', '.'], sourceDir)
325
+ } catch (error) {
326
+ // 旧版 svn 在属性不存在时的报错不阻断打包;其余错误交给上层告警
327
+ if (/W200017|property.*not found|属性.*不存在/i.test(error.message)) {
328
+ return []
329
+ }
330
+ throw error
331
+ }
332
+
333
+ const wanted = new Set(files.map(f => f.replace(/\\/g, '/')))
334
+ return parseSvnPropgetXml(output, { sourceDir, svnRoot }).filter(rel => wanted.has(rel))
335
+ }
336
+
337
+ /**
338
+ * 递归列出未纳入版本控制的目录内容(svn status 只列出目录本身)
339
+ *
340
+ * @param {string} dirAbs
341
+ * @param {string} relBase
342
+ * @param {object} [options]
343
+ * @param {(rel: string) => boolean} [options.shouldSkip] 排除规则(目录会带尾部 /)
344
+ * @param {number} [options.maxFiles] 文件数上限,防止误扫 node_modules 等大目录
345
+ * @returns {string[]}
346
+ */
347
+ function expandUnversionedDir (dirAbs, relBase, options = {}) {
348
+ const shouldSkip = options.shouldSkip || (() => false)
349
+ const maxFiles = options.maxFiles ?? 20000
350
+ /** @type {string[]} */
351
+ const files = []
352
+ const stack = [[dirAbs, relBase]]
353
+
354
+ while (stack.length > 0) {
355
+ const [abs, rel] = stack.pop()
356
+ let names
357
+ try {
358
+ names = fs.readdirSync(abs)
359
+ } catch {
360
+ continue
361
+ }
362
+
363
+ for (const name of names) {
364
+ if (name === '.svn') continue
365
+ const childAbs = path.join(abs, name)
366
+ const childRel = rel ? `${rel}/${name}` : name
367
+
368
+ let stat
369
+ try {
370
+ stat = fs.lstatSync(childAbs)
371
+ } catch {
372
+ continue
373
+ }
374
+ if (stat.isSymbolicLink()) continue
375
+
376
+ if (stat.isDirectory()) {
377
+ if (!shouldSkip(`${childRel}/`)) {
378
+ stack.push([childAbs, childRel])
379
+ }
380
+ continue
381
+ }
382
+
383
+ if (stat.isFile()) {
384
+ if (shouldSkip(childRel)) continue
385
+ if (files.length >= maxFiles) {
386
+ throw new Error(
387
+ `未纳入版本控制的目录文件过多(>${maxFiles}): ${relBase}\n` +
388
+ '请将大目录(node_modules、runtime、deploy/out 等)加入忽略规则,或先提交/排除后再打包'
389
+ )
390
+ }
391
+ files.push(childRel)
392
+ }
393
+ }
394
+ }
395
+
396
+ return files
397
+ }
398
+
399
+ /**
400
+ * 工作副本本地改动(svn status):新增/修改/删除/未纳入版本控制的文件
401
+ *
402
+ * @param {object} options
403
+ * @param {string} options.sourceDir
404
+ * @param {string} [options.svnExe]
405
+ * @param {(rel: string) => boolean} [options.shouldSkip]
406
+ * @param {number} [options.maxFiles]
407
+ * @returns {Array<DiffEntry & { parseError?: string }>}
408
+ */
409
+ function getSvnStatusEntries ({ sourceDir, svnExe = findSvnExe(), shouldSkip, maxFiles }) {
410
+ const svnRoot = path.dirname(sourceDir)
411
+ const output = runSvn(
412
+ svnExe,
413
+ ['status', '--xml', '--ignore-externals', sourceDir],
414
+ svnRoot
415
+ )
416
+
417
+ const { entries, conflicted } = parseSvnStatusXml(output, { sourceDir, svnRoot })
418
+
419
+ if (conflicted.length > 0) {
420
+ throw new Error(
421
+ `工作副本存在未解决冲突,请先 svn resolve 后再打包:\n - ${conflicted.join('\n - ')}`
422
+ )
423
+ }
424
+
425
+ // 未纳入版本控制的目录:展开为具体文件(否则会漏掉整个新增目录)
426
+ /** @type {Array<DiffEntry & { parseError?: string }>} */
427
+ const expanded = []
428
+ for (const entry of entries) {
429
+ if (entry.parseError || entry.action !== 'A') {
430
+ expanded.push(entry)
431
+ continue
432
+ }
433
+
434
+ const abs = path.join(sourceDir, entry.relativePath.split('/').join(path.sep))
435
+ let stat = null
436
+ try {
437
+ stat = fs.lstatSync(abs)
438
+ } catch {
439
+ // 已删除的 A 条目等,交给后续打包阶段提示
440
+ }
441
+
442
+ if (stat && stat.isDirectory()) {
443
+ const expandedFiles = expandUnversionedDir(abs, entry.relativePath, { shouldSkip, maxFiles })
444
+ for (const rel of expandedFiles) {
445
+ expanded.push({ action: 'A', relativePath: rel })
446
+ }
447
+ } else {
448
+ expanded.push(entry)
449
+ }
450
+ }
451
+
452
+ return expanded
453
+ }
454
+
455
+ /**
456
+ * 工作副本增量:`svn diff -r <fromRev>`(含已提交与本地改动)∪ `svn status`(含未纳入版本控制的文件)
457
+ *
458
+ * @param {object} options
459
+ * @param {string} options.sourceDir
460
+ * @param {number} options.fromRev 上次上线基准 revision
461
+ * @param {string} [options.svnExe]
462
+ * @param {(rel: string) => boolean} [options.shouldSkip] 扫描未纳入版本控制目录时的排除规则
463
+ * @param {number} [options.maxFiles]
464
+ * @returns {DiffEntry[]}
465
+ */
466
+ function getSvnWorktreeDiffEntries ({ sourceDir, fromRev, svnExe = findSvnExe(), shouldSkip, maxFiles }) {
467
+ /** @type {Map<string, 'A'|'M'|'D'>} */
468
+ const merged = new Map()
469
+
470
+ /** @param {Array<DiffEntry & { parseError?: string }>} entries */
471
+ const absorb = (entries) => {
472
+ for (const entry of entries) {
473
+ if (entry.parseError) continue
474
+ const rel = entry.relativePath.replace(/\\/g, '/')
475
+ const prev = merged.get(rel)
476
+ if (entry.action === 'D' || prev === 'D') {
477
+ merged.set(rel, 'D')
478
+ } else if (prev === 'A' || entry.action === 'A') {
479
+ merged.set(rel, 'A')
480
+ } else {
481
+ merged.set(rel, 'M')
482
+ }
483
+ }
484
+ }
485
+
486
+ absorb(getSvnDiffVsRevision({ sourceDir, rev: fromRev, svnExe }))
487
+ absorb(getSvnStatusEntries({ sourceDir, svnExe, shouldSkip, maxFiles }))
488
+
489
+ return [...merged.entries()]
490
+ .map(([relativePath, action]) => ({ action, relativePath }))
491
+ .sort((a, b) => a.relativePath.localeCompare(b.relativePath))
492
+ }
493
+
494
+
495
+ /**
496
+ * 检查工作副本内容是否与目标 revision 一致
497
+ *
498
+ * 用 `svn diff -r <toRev>` 将工作副本与目标版本对比(单 revision 形式),
499
+ * 能覆盖“未 update 到 toRev”“混合版本”“本地未提交改动”三种情况。
500
+ *
501
+ * @param {object} options
502
+ * @param {string} options.sourceDir
503
+ * @param {number} options.toRev
504
+ * @param {string[]} options.files 待打包的 sourceDir 相对路径
505
+ * @param {string} [options.svnExe]
506
+ * @returns {string[]} 内容不一致的文件(sourceDir 相对路径)
507
+ */
508
+ function getSvnContentMismatch ({ sourceDir, toRev, files, svnExe = findSvnExe() }) {
509
+ if (!files || files.length === 0) {
510
+ return []
511
+ }
512
+
513
+ const svnRoot = path.dirname(sourceDir)
514
+ const output = runSvn(
515
+ svnExe,
516
+ ['diff', '-r', String(toRev), '--summarize', sourceDir],
517
+ svnRoot
518
+ )
519
+
520
+ const wanted = new Set(files)
521
+ /** @type {Set<string>} */
522
+ const mismatched = new Set()
523
+
524
+ for (const line of output.split(/\r?\n/)) {
525
+ const match = line.match(/^\s*([AMDR])\s+(.+)$/)
526
+ if (!match) continue
527
+
528
+ try {
529
+ const rel = normalizeRelativePath(match[2], sourceDir, svnRoot).replace(/\\/g, '/')
530
+ if (wanted.has(rel)) {
531
+ mismatched.add(rel)
532
+ }
533
+ } catch {
534
+ // 无法解析的路径不参与比对;真正打包时会再校验
535
+ }
536
+ }
537
+
538
+ return [...mismatched].sort()
150
539
  }
151
540
 
152
541
  /**
@@ -175,7 +564,15 @@ module.exports = {
175
564
  runSvn,
176
565
  getSvnInfo,
177
566
  normalizeRelativePath,
567
+ parseSummarizeOutput,
178
568
  getSvnDiffSummary,
569
+ getSvnDiffVsRevision,
570
+ parseSvnStatusXml,
571
+ getSvnStatusEntries,
572
+ parseSvnPropgetXml,
573
+ getSvnWorktreeDiffEntries,
574
+ getSvnExecutableFiles,
575
+ getSvnContentMismatch,
179
576
  readLastDeployRev,
180
577
  writeLastDeployRev
181
578
  }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * 本地 patch 版本归档 — 保留最近 N 个版本包(方案 C)
3
+ */
4
+
5
+ const fs = require('fs')
6
+ const path = require('path')
7
+ const fse = require('fs-extra')
8
+ const { sanitizeVersionLabel } = require('./file-filter')
9
+ const { writeJsonAtomic } = require('./version-registry')
10
+
11
+ const ARCHIVE_DIR = 'archive'
12
+ const ARCHIVE_INDEX = 'index.json'
13
+
14
+ /**
15
+ * 生成部署/归档用版本标识(与 apply-update.php 对齐)
16
+ * @param {'svn'|'git'} vcs
17
+ * @param {string} toLabel
18
+ * @param {string|null} [versionLabel] --version 清洗后的标签
19
+ * @returns {string}
20
+ */
21
+ function buildDeployVersionLabel (vcs, toLabel, versionLabel = null) {
22
+ if (versionLabel) {
23
+ return sanitizeVersionLabel(versionLabel)
24
+ }
25
+ if (vcs === 'svn') {
26
+ return `r${toLabel}`
27
+ }
28
+ return String(toLabel).slice(0, 12)
29
+ }
30
+
31
+ /**
32
+ * @param {string} deployDir
33
+ * @returns {string}
34
+ */
35
+ function getArchiveRoot (deployDir) {
36
+ return path.join(deployDir, ARCHIVE_DIR)
37
+ }
38
+
39
+ /**
40
+ * @param {string} deployDir
41
+ * @param {string} absPath
42
+ * @returns {string}
43
+ */
44
+ function toDeployRelative (deployDir, absPath) {
45
+ if (!absPath) return absPath
46
+ if (!path.isAbsolute(absPath)) return absPath.replace(/\\/g, '/')
47
+ const rel = path.relative(deployDir, absPath)
48
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return absPath
49
+ return rel.split(path.sep).join('/')
50
+ }
51
+
52
+ /**
53
+ * @param {string} deployDir
54
+ * @param {string} value
55
+ * @returns {string}
56
+ */
57
+ function fromDeployRelative (deployDir, value) {
58
+ if (!value || path.isAbsolute(value)) return value
59
+ return path.resolve(deployDir, value)
60
+ }
61
+
62
+ /**
63
+ * @param {string} deployDir
64
+ * @returns {{ versions: object[] }}
65
+ */
66
+ function readArchiveIndex (deployDir) {
67
+ const indexPath = path.join(getArchiveRoot(deployDir), ARCHIVE_INDEX)
68
+ if (!fs.existsSync(indexPath)) {
69
+ return { versions: [] }
70
+ }
71
+
72
+ try {
73
+ const data = JSON.parse(fs.readFileSync(indexPath, 'utf8'))
74
+ if (Array.isArray(data.versions)) {
75
+ for (const record of data.versions) {
76
+ if (!record || typeof record !== 'object') continue
77
+ if (record.archiveDir) record.archiveDir = fromDeployRelative(deployDir, record.archiveDir)
78
+ if (record.zipPath) record.zipPath = fromDeployRelative(deployDir, record.zipPath)
79
+ }
80
+ return data
81
+ }
82
+ } catch (error) {
83
+ console.warn(`[vcs-patch-deploy] ${ARCHIVE_INDEX} 解析失败: ${error.message}`)
84
+ }
85
+
86
+ return { versions: [] }
87
+ }
88
+
89
+ /**
90
+ * 优先硬链接,失败时退回复制(跨盘/文件系统不支持硬链接)
91
+ * @param {string} src
92
+ * @param {string} dst
93
+ */
94
+ function linkOrCopyFile (src, dst) {
95
+ try {
96
+ fs.linkSync(src, dst)
97
+ } catch {
98
+ fs.copyFileSync(src, dst)
99
+ }
100
+ }
101
+
102
+ /**
103
+ * 递归硬链接目录内容(归档可选,节省磁盘);符号链接跳过
104
+ * @param {string} srcDir
105
+ * @param {string} dstDir
106
+ */
107
+ function linkOrCopyTree (srcDir, dstDir) {
108
+ fs.mkdirSync(dstDir, { recursive: true })
109
+ const stack = [[srcDir, dstDir]]
110
+
111
+ while (stack.length > 0) {
112
+ const [src, dst] = stack.pop()
113
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
114
+ const srcPath = path.join(src, entry.name)
115
+ const dstPath = path.join(dst, entry.name)
116
+ if (entry.isSymbolicLink()) continue
117
+ if (entry.isDirectory()) {
118
+ fs.mkdirSync(dstPath, { recursive: true })
119
+ stack.push([srcPath, dstPath])
120
+ continue
121
+ }
122
+ if (entry.isFile()) {
123
+ linkOrCopyFile(srcPath, dstPath)
124
+ }
125
+ }
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 归档 patch 目录与 zip,并清理超出保留数量的旧版本
131
+ * @param {object} options
132
+ * @param {string} options.deployDir
133
+ * @param {string} options.archiveLabel 如 1.2.3 / r467 / abc123def456
134
+ * @param {string} options.patchDir
135
+ * @param {string} [options.zipPath]
136
+ * @param {'svn'|'git'} options.vcs
137
+ * @param {string} options.fromLabel
138
+ * @param {string} options.toLabel
139
+ * @param {boolean} [options.partial=false] 子集包(独立保留配额,避免挤掉正式版本)
140
+ * @param {boolean} [options.link=false] 优先硬链接归档(同一磁盘时节省空间)
141
+ * @param {number} [options.keepVersions=10]
142
+ * @returns {Promise<{ archiveDir: string, zipArchivePath?: string }>}
143
+ */
144
+ async function archivePatchPackage ({
145
+ deployDir,
146
+ archiveLabel,
147
+ patchDir,
148
+ zipPath,
149
+ vcs,
150
+ fromLabel,
151
+ toLabel,
152
+ partial = false,
153
+ link = false,
154
+ keepVersions = 10
155
+ }) {
156
+ const archiveRoot = getArchiveRoot(deployDir)
157
+ const safeLabel = sanitizeVersionLabel(archiveLabel)
158
+ const archiveDir = path.join(archiveRoot, safeLabel)
159
+
160
+ await fse.ensureDir(archiveRoot)
161
+ await fse.emptyDir(archiveDir)
162
+ if (link) {
163
+ linkOrCopyTree(patchDir, archiveDir)
164
+ } else {
165
+ await fse.copy(patchDir, archiveDir)
166
+ }
167
+
168
+ /** @type {string|undefined} */
169
+ let zipArchivePath
170
+ if (zipPath && fs.existsSync(zipPath)) {
171
+ zipArchivePath = path.join(archiveRoot, `${safeLabel}.zip`)
172
+ if (link) {
173
+ linkOrCopyFile(zipPath, zipArchivePath)
174
+ } else {
175
+ await fse.copy(zipPath, zipArchivePath)
176
+ }
177
+ }
178
+
179
+ const index = readArchiveIndex(deployDir)
180
+ const createdAt = new Date().toISOString()
181
+ const record = {
182
+ label: safeLabel,
183
+ vcs,
184
+ fromLabel,
185
+ toLabel,
186
+ partial,
187
+ archiveDir: toDeployRelative(deployDir, archiveDir),
188
+ zipPath: zipArchivePath ? toDeployRelative(deployDir, zipArchivePath) : undefined,
189
+ createdAt
190
+ }
191
+
192
+ const dupIdx = index.versions.findIndex(v => v.label === safeLabel)
193
+ if (dupIdx >= 0) {
194
+ index.versions[dupIdx] = record
195
+ } else {
196
+ index.versions.push(record)
197
+ }
198
+
199
+ index.versions.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
200
+
201
+ // 完整包与子集包分别保留最近 keepVersions 个,避免热修复子集挤掉正式版本归档
202
+ const limit = Math.max(1, keepVersions)
203
+ const fullVersions = index.versions.filter(v => !v.partial)
204
+ const partialVersions = index.versions.filter(v => v.partial)
205
+ const retained = new Set([
206
+ ...fullVersions.slice(0, limit),
207
+ ...partialVersions.slice(0, limit)
208
+ ])
209
+ const removed = index.versions.filter(v => !retained.has(v))
210
+ index.versions = index.versions.filter(v => retained.has(v))
211
+
212
+ for (const old of index.versions) {
213
+ old.archiveDir = toDeployRelative(deployDir, old.archiveDir)
214
+ if (old.zipPath) old.zipPath = toDeployRelative(deployDir, old.zipPath)
215
+ }
216
+ writeJsonAtomic(path.join(archiveRoot, ARCHIVE_INDEX), index)
217
+
218
+ for (const old of removed) {
219
+ const oldDir = old.archiveDir ? fromDeployRelative(deployDir, old.archiveDir) : null
220
+ const oldZip = old.zipPath ? fromDeployRelative(deployDir, old.zipPath) : null
221
+ if (oldDir && fs.existsSync(oldDir)) {
222
+ await fse.remove(oldDir).catch(() => {})
223
+ }
224
+ if (oldZip && fs.existsSync(oldZip)) {
225
+ await fse.remove(oldZip).catch(() => {})
226
+ }
227
+ }
228
+
229
+ return { archiveDir, zipArchivePath }
230
+ }
231
+
232
+ module.exports = {
233
+ ARCHIVE_DIR,
234
+ buildDeployVersionLabel,
235
+ getArchiveRoot,
236
+ readArchiveIndex,
237
+ archivePatchPackage
238
+ }