vcs-patch-deploy 1.0.0 → 1.1.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.
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * 从已打包版本中提取指定文件,生成可单独部署的子集 patch
5
+ */
6
+
7
+ const path = require('path')
8
+ const chalk = require('chalk')
9
+ const {
10
+ extractPatchSubset,
11
+ resolveConfig,
12
+ listVersionRecords
13
+ } = require('../lib/index')
14
+
15
+ try {
16
+ require('dotenv').config({ path: path.resolve(process.cwd(), '.env') })
17
+ } catch {
18
+ // optional
19
+ }
20
+
21
+ function showHelp () {
22
+ console.log(`
23
+ ${chalk.cyan.bold('patch-extract')} — 按版本号从完整 patch 中提取指定文件
24
+
25
+ ${chalk.yellow('用法:')}
26
+ patch-extract --version=<版本号> --only=<文件1,文件2>
27
+ patch-extract --from-patch=<patch目录> --only=<文件> --file-list=<列表文件>
28
+
29
+ ${chalk.yellow('选项:')}
30
+ --version=<版本> 已注册版本(见 deploy/versions.json)
31
+ --from-patch=<目录> 直接指定源 patch 目录
32
+ --only=<路径> 要提取的文件(逗号分隔,可重复;支持 @files.txt)
33
+ --file-list=<文件> 每行一个相对路径的列表文件
34
+ --deploy=<目录> deploy 目录
35
+ --no-zip 仅生成 patch 目录
36
+ --register 将子集包写入 versions.json
37
+ --list-versions 列出已注册版本
38
+ -h, --help 显示帮助
39
+
40
+ ${chalk.yellow('示例:')}
41
+ # 先打完整版本包
42
+ patch-build --vcs=svn --version=1.2.3
43
+
44
+ # 从 v1.2.3 中只提取部分文件单独部署
45
+ patch-extract --version=1.2.3 --only=app/service/Foo.php,app/controller/Bar.php
46
+
47
+ # 从列表文件提取
48
+ patch-extract --version=1.2.3 --file-list=hotfix-files.txt
49
+ `)
50
+ }
51
+
52
+ function parseArgs () {
53
+ const args = process.argv.slice(2)
54
+ const opts = { showHelp: false, onlyFiles: [] }
55
+
56
+ for (const arg of args) {
57
+ if (arg === '--help' || arg === '-h') opts.showHelp = true
58
+ else if (arg === '--no-zip') opts.noZip = true
59
+ else if (arg === '--register') opts.register = true
60
+ else if (arg === '--list-versions') opts.listVersions = true
61
+ else if (arg.startsWith('--version=')) opts.version = arg.split('=')[1]
62
+ else if (arg.startsWith('--from-patch=')) opts.fromPatch = arg.split('=')[1]
63
+ else if (arg.startsWith('--only=')) opts.onlyFiles.push(...arg.split('=')[1].split(','))
64
+ else if (arg.startsWith('--file-list=')) opts.fileList = arg.split('=')[1]
65
+ else if (arg.startsWith('--deploy=')) opts.deployDir = arg.split('=')[1]
66
+ else console.warn(chalk.yellow(`未知参数: ${arg}`))
67
+ }
68
+
69
+ return opts
70
+ }
71
+
72
+ async function main () {
73
+ const opts = parseArgs()
74
+ if (opts.showHelp) {
75
+ showHelp()
76
+ process.exit(0)
77
+ }
78
+
79
+ const config = resolveConfig({
80
+ deployDir: opts.deployDir,
81
+ pkgRoot: path.join(__dirname, '..')
82
+ })
83
+
84
+ if (opts.listVersions) {
85
+ const versions = listVersionRecords(config.deployDir)
86
+ if (versions.length === 0) {
87
+ console.log(chalk.yellow('暂无已注册版本(使用 patch-build --version= 打包)'))
88
+ } else {
89
+ console.log(chalk.cyan('已注册版本:'))
90
+ for (const v of versions) {
91
+ const tag = v.partial ? chalk.gray(' [子集]') : ''
92
+ console.log(` v${v.versionLabel}${tag} 文件:${v.files.length} ${v.createdAt.slice(0, 19)}`)
93
+ console.log(chalk.gray(` patch: ${v.patchDir}`))
94
+ }
95
+ }
96
+ process.exit(0)
97
+ }
98
+
99
+ const result = await extractPatchSubset({
100
+ deployDir: config.deployDir,
101
+ outDir: config.outDir,
102
+ applyScriptPath: config.applyScriptPath,
103
+ fromPatch: opts.fromPatch,
104
+ version: opts.version,
105
+ onlyFiles: opts.onlyFiles,
106
+ fileList: opts.fileList || null,
107
+ noZip: opts.noZip,
108
+ zipPrefix: config.zipPrefix,
109
+ registerSubset: Boolean(opts.register)
110
+ })
111
+
112
+ console.log(chalk.green(result.message))
113
+ console.log(chalk.green(` 源 patch: ${result.sourcePatchDir}`))
114
+ console.log(chalk.green(` 提取文件: ${result.fileCount}`))
115
+ console.log(chalk.green(` patch 目录: ${result.patchDir}`))
116
+ if (result.zipPath) {
117
+ console.log(chalk.green(` zip: ${result.zipPath} (${result.zipSize} bytes)`))
118
+ }
119
+
120
+ console.log(chalk.cyan('\n下一步: 上传 zip → 解压 → php apply-update.php <Backend根目录>'))
121
+ process.exit(0)
122
+ }
123
+
124
+ main().catch(error => {
125
+ console.error(chalk.red(`错误: ${error.message}`))
126
+ process.exit(1)
127
+ })
package/env.example CHANGED
@@ -6,15 +6,30 @@ PATCH_BACKEND=php
6
6
  # svn | git;留空则自动检测
7
7
  # PATCH_VCS=svn
8
8
 
9
- # PHP 项目根(ThinkPHP 含 app/ config/ 的 trunk 或 Git 仓库根)
10
- # PATCH_SOURCE_DIR=D:/Work/web/newKJCG/BackendSVN/trunk
9
+ # PHP 项目根(ThinkPHP 含 app/ config/ 的目录)
10
+ # PATCH_SOURCE_DIR=/path/to/your-php-api
11
11
 
12
12
  # deploy 配置目录(含 .last-deploy-marker、out/)
13
- # PATCH_DEPLOY_DIR=D:/Work/web/newKJCG/BackendSVN/trunk/deploy
13
+ # PATCH_DEPLOY_DIR=/path/to/your-php-api/deploy
14
+
15
+ # 服务器 apply-update.php:备份根目录(默认 <Backend>/.deploy-backups/)
16
+ # PATCH_BACKUP_DIR=/data/backups/my-api
14
17
 
15
18
  # zip 文件名前缀
16
19
  # PATCH_ZIP_PREFIX=backend-update
17
20
 
21
+ # zip 压缩级别 0-9(默认 6,原 9 较慢)
22
+ # PATCH_ZIP_LEVEL=6
23
+
24
+ # 安装版本号(patch-build --version= 的默认值)
25
+ # PATCH_VERSION=1.2.3
26
+
27
+ # 仅打包/部署的文件列表(每行一个相对路径)
28
+ # PATCH_FILE_LIST=hotfix-files.txt
29
+
30
+ # 服务器 apply-update.php:仅部署指定文件(逗号分隔)
31
+ # PATCH_DEPLOY_FILES=app/service/Foo.php,app/controller/Bar.php
32
+
18
33
  # 跳过 PHP 项目结构校验(非标准目录时使用)
19
34
  # PATCH_SKIP_VALIDATION=false
20
35
 
@@ -9,6 +9,9 @@ const fse = require('fs-extra')
9
9
  const { shouldExcludePath } = require('./exclude')
10
10
  const { getBackend } = require('./backends')
11
11
  const { readDeployMarker, writeDeployMarker } = require('./marker')
12
+ const { registerVersion } = require('./version-registry')
13
+ const { sanitizeVersionLabel } = require('./file-filter')
14
+ const { resolveSelectedFiles, filterFilesBySelection } = require('./file-filter')
12
15
  const { getSvnInfo, getSvnDiffSummary } = require('./svn')
13
16
  const { getGitInfo, getGitDiffSummary, resolveGitRef } = require('./git')
14
17
  const { createZipFromDirectory } = require('./zip')
@@ -44,6 +47,7 @@ function classifyDiffEntries (entries, sourceDir, backendId = 'php') {
44
47
  for (const entry of entries) {
45
48
  if (entry.parseError) {
46
49
  warnings.push(entry.parseError)
50
+ continue
47
51
  }
48
52
 
49
53
  const rel = entry.relativePath.replace(/\\/g, '/')
@@ -81,8 +85,18 @@ function classifyDiffEntries (entries, sourceDir, backendId = 'php') {
81
85
  * 生成 patch 目录名与 zip 名后缀
82
86
  * @param {'svn'|'git'} vcs
83
87
  * @param {string} toLabel
88
+ * @param {string} [version]
84
89
  */
85
- function buildArtifactNames (vcs, toLabel, zipPrefix) {
90
+ function buildArtifactNames (vcs, toLabel, zipPrefix, version = null) {
91
+ const versionLabel = version ? sanitizeVersionLabel(version) : null
92
+
93
+ if (versionLabel) {
94
+ return {
95
+ patchName: `patch-v${versionLabel}`,
96
+ zipName: `${zipPrefix}-v${versionLabel}.zip`
97
+ }
98
+ }
99
+
86
100
  if (vcs === 'svn') {
87
101
  return {
88
102
  patchName: `patch-r${toLabel}`,
@@ -112,7 +126,10 @@ async function buildPatch (config) {
112
126
  noZip,
113
127
  markDeployed,
114
128
  skipValidation,
115
- zipPrefix
129
+ zipPrefix,
130
+ version,
131
+ onlyFiles,
132
+ fileList
116
133
  } = config
117
134
 
118
135
  const backendModule = getBackend(backend)
@@ -152,6 +169,10 @@ async function buildPatch (config) {
152
169
  }
153
170
  }
154
171
 
172
+ if (!Number.isFinite(fromRev) || !Number.isFinite(toRev)) {
173
+ throw new Error(`无效的 SVN revision:from=${fromRev} to=${toRev},请检查 marker 或 --from/--to`)
174
+ }
175
+
155
176
  if (fromRev >= toRev) {
156
177
  if (markDeployed && fromRev === toRev) {
157
178
  writeDeployMarker(deployDir, 'svn', String(toRev))
@@ -226,7 +247,25 @@ async function buildPatch (config) {
226
247
 
227
248
  const { addedOrModified, deleted, warnings } = classifyDiffEntries(diffEntries, sourceDir, backend)
228
249
 
229
- if (addedOrModified.length === 0 && deleted.length === 0) {
250
+ // 按 --only / --file-list 筛选本次打包文件(用于单独提取部署)
251
+ const selectedFiles = resolveSelectedFiles(onlyFiles || [], fileList || null)
252
+ let deployFiles = addedOrModified
253
+ let deployDeleted = deleted
254
+ if (selectedFiles.length > 0) {
255
+ const filePick = filterFilesBySelection(addedOrModified, selectedFiles)
256
+ if (filePick.missing.length > 0) {
257
+ warnings.push(`--only 中以下文件不在本次增量内: ${filePick.missing.join(', ')}`)
258
+ }
259
+ deployFiles = filePick.matched
260
+
261
+ const deletedPick = filterFilesBySelection(deleted, selectedFiles)
262
+ deployDeleted = deletedPick.matched
263
+ if (deletedPick.missing.length > 0) {
264
+ warnings.push(`--only 中以下删除项不在本次增量内: ${deletedPick.missing.join(', ')}`)
265
+ }
266
+ }
267
+
268
+ if (deployFiles.length === 0 && deployDeleted.length === 0) {
230
269
  return {
231
270
  success: true,
232
271
  skipped: true,
@@ -238,78 +277,123 @@ async function buildPatch (config) {
238
277
  }
239
278
  }
240
279
 
241
- const { patchName, zipName } = buildArtifactNames(vcs, toLabel, zipPrefix)
280
+ const { patchName, zipName } = buildArtifactNames(vcs, toLabel, zipPrefix, version)
242
281
  const patchDir = path.join(outDir, patchName)
243
282
  const zipPath = path.join(outDir, zipName)
283
+ const stagingDir = `${patchDir}.staging-${Date.now()}`
284
+ const versionLabel = version ? sanitizeVersionLabel(version) : null
244
285
 
245
- await fse.emptyDir(patchDir)
286
+ await fse.emptyDir(stagingDir)
246
287
 
247
- for (const rel of addedOrModified) {
248
- const src = path.join(sourceDir, rel)
249
- const dst = path.join(patchDir, rel)
250
- await fse.ensureDir(path.dirname(dst))
251
- await fse.copy(src, dst)
252
- }
288
+ let zipSize = 0
289
+ try {
290
+ for (const rel of deployFiles) {
291
+ const src = path.join(sourceDir, rel)
292
+ const dst = path.join(stagingDir, rel)
293
+ await fse.ensureDir(path.dirname(dst))
294
+ await fse.copy(src, dst)
295
+ }
253
296
 
254
- await fse.copy(applyScriptPath, path.join(patchDir, 'apply-update.php'))
255
-
256
- const manifestLines = [
257
- '# PHP 后端增量部署清单',
258
- `backend=${backend}`,
259
- `vcs=${vcs}`,
260
- vcs === 'svn'
261
- ? `from_revision=${fromLabel}`
262
- : `from_commit=${fromLabel}`,
263
- vcs === 'svn'
264
- ? `to_revision=${toLabel}`
265
- : `to_commit=${toLabel}`,
266
- `generated_at=${new Date().toISOString().replace('T', ' ').slice(0, 19)}`,
267
- `generated_by=${os.userInfo().username}`,
268
- '',
269
- '# files',
270
- ...addedOrModified,
271
- '',
272
- '# deleted (需人工确认是否删除线上文件)',
273
- ...(deleted.length > 0 ? deleted : ['# (none)'])
274
- ]
275
-
276
- if (warnings.length > 0) {
277
- manifestLines.push('', '# warnings', ...warnings)
278
- }
297
+ await fse.copy(applyScriptPath, path.join(stagingDir, 'apply-update.php'))
298
+
299
+ const manifestLines = [
300
+ '# PHP 后端增量部署清单',
301
+ `backend=${backend}`,
302
+ `vcs=${vcs}`,
303
+ ...(versionLabel ? [`version=${versionLabel}`] : []),
304
+ vcs === 'svn'
305
+ ? `from_revision=${fromLabel}`
306
+ : `from_commit=${fromLabel}`,
307
+ vcs === 'svn'
308
+ ? `to_revision=${toLabel}`
309
+ : `to_commit=${toLabel}`,
310
+ `generated_at=${new Date().toISOString().replace('T', ' ').slice(0, 19)}`,
311
+ `generated_by=${os.userInfo().username}`,
312
+ '',
313
+ '# files',
314
+ ...deployFiles,
315
+ '',
316
+ '# deleted (需人工确认是否删除线上文件)',
317
+ ...(deployDeleted.length > 0 ? deployDeleted : ['# (none)'])
318
+ ]
319
+
320
+ if (warnings.length > 0) {
321
+ manifestLines.push('', '# warnings', ...warnings)
322
+ }
279
323
 
280
- fs.writeFileSync(path.join(patchDir, 'MANIFEST.txt'), manifestLines.join('\n'), 'utf8')
324
+ fs.writeFileSync(path.join(stagingDir, 'MANIFEST.txt'), manifestLines.join('\n'), 'utf8')
325
+
326
+ if (versionLabel) {
327
+ fs.writeFileSync(
328
+ path.join(stagingDir, 'VERSION.txt'),
329
+ [
330
+ `version=${versionLabel}`,
331
+ `vcs=${vcs}`,
332
+ vcs === 'svn' ? `to_revision=${toLabel}` : `to_commit=${toLabel}`,
333
+ `file_count=${deployFiles.length}`
334
+ ].join('\n'),
335
+ 'utf8'
336
+ )
337
+ }
281
338
 
282
- if (deleted.length > 0) {
283
- fs.writeFileSync(
284
- path.join(patchDir, 'MANIFEST-deleted.txt'),
285
- deleted.join('\n'),
286
- 'utf8'
287
- )
288
- }
339
+ if (deployDeleted.length > 0) {
340
+ fs.writeFileSync(
341
+ path.join(stagingDir, 'MANIFEST-deleted.txt'),
342
+ deployDeleted.join('\n'),
343
+ 'utf8'
344
+ )
345
+ }
289
346
 
290
- let zipSize = 0
291
- if (!noZip) {
292
- const zipResult = await createZipFromDirectory(patchDir, zipPath)
293
- zipSize = zipResult.size
347
+ // 构建成功后再替换目标 patch 目录,避免中途失败清空旧包
348
+ if (fs.existsSync(patchDir)) {
349
+ await fse.remove(patchDir)
350
+ }
351
+ await fse.move(stagingDir, patchDir)
352
+
353
+ if (!noZip) {
354
+ const zipResult = await createZipFromDirectory(patchDir, zipPath)
355
+ zipSize = zipResult.size
356
+ }
357
+ } catch (error) {
358
+ await fse.remove(stagingDir).catch(() => {})
359
+ throw error
294
360
  }
295
361
 
296
362
  if (markDeployed) {
297
363
  writeDeployMarker(deployDir, vcs, toLabel)
298
364
  }
299
365
 
366
+ // 注册版本号到 deploy/versions.json,便于后续 patch-extract 按版本提取
367
+ if (versionLabel) {
368
+ registerVersion(deployDir, {
369
+ version: String(version),
370
+ versionLabel,
371
+ vcs,
372
+ fromLabel,
373
+ toLabel,
374
+ files: deployFiles,
375
+ deleted: deployDeleted,
376
+ patchDir,
377
+ zipPath: noZip ? undefined : zipPath,
378
+ partial: selectedFiles.length > 0,
379
+ createdAt: new Date().toISOString()
380
+ })
381
+ }
382
+
300
383
  return {
301
384
  success: true,
302
385
  skipped: false,
303
- message: `打包完成:${vcs === 'svn' ? `r${fromLabel} -> r${toLabel}` : `${fromLabel.slice(0, 8)}..${toLabel.slice(0, 8)}`}`,
386
+ message: `打包完成:${versionLabel ? `v${versionLabel}` : (vcs === 'svn' ? `r${fromLabel} -> r${toLabel}` : `${fromLabel.slice(0, 8)}..${toLabel.slice(0, 8)}`)}`,
304
387
  patchDir,
305
388
  zipPath: noZip ? undefined : zipPath,
306
389
  zipSize,
307
- fileCount: addedOrModified.length,
308
- deletedCount: deleted.length,
390
+ fileCount: deployFiles.length,
391
+ deletedCount: deployDeleted.length,
309
392
  warnings,
310
393
  vcs,
311
394
  fromLabel,
312
395
  toLabel,
396
+ version: versionLabel || undefined,
313
397
  markDeployedHint: markDeployed
314
398
  ? undefined
315
399
  : `上线成功后执行:patch-build --vcs=${vcs} --mark-deployed --from=${toLabel} --to=${toLabel}`
@@ -0,0 +1,63 @@
1
+ /**
2
+ * CLI 公共参数解析(patch-build / patch-extract 复用)
3
+ */
4
+
5
+ /**
6
+ * @typedef {object} CommonCliOptions
7
+ * @property {boolean} showHelp
8
+ * @property {boolean} [noZip]
9
+ * @property {string} [deployDir]
10
+ * @property {string[]} onlyFiles
11
+ * @property {string} [fileList]
12
+ */
13
+
14
+ /**
15
+ * @param {string[]} args process.argv.slice(2)
16
+ * @param {Record<string, string>} flagMap 布尔开关,如 { noZip: '--no-zip' }
17
+ * @param {Record<string, string>} valueMap 键值参数前缀,如 { deployDir: '--deploy=' }
18
+ * @returns {CommonCliOptions & Record<string, unknown>}
19
+ */
20
+ function parseCommonArgs (args, flagMap = {}, valueMap = {}) {
21
+ /** @type {CommonCliOptions & Record<string, unknown>} */
22
+ const opts = { showHelp: false, onlyFiles: [] }
23
+
24
+ for (const arg of args) {
25
+ if (arg === '--help' || arg === '-h') {
26
+ opts.showHelp = true
27
+ continue
28
+ }
29
+
30
+ let handled = false
31
+
32
+ for (const [key, flag] of Object.entries(flagMap)) {
33
+ if (arg === flag) {
34
+ opts[key] = true
35
+ handled = true
36
+ break
37
+ }
38
+ }
39
+ if (handled) continue
40
+
41
+ for (const [key, prefix] of Object.entries(valueMap)) {
42
+ if (arg.startsWith(prefix)) {
43
+ opts[key] = arg.slice(prefix.length)
44
+ handled = true
45
+ break
46
+ }
47
+ }
48
+ if (handled) continue
49
+
50
+ if (arg.startsWith('--only=')) {
51
+ opts.onlyFiles.push(...arg.slice(7).split(','))
52
+ continue
53
+ }
54
+
55
+ opts.unknownArg = arg
56
+ }
57
+
58
+ return opts
59
+ }
60
+
61
+ module.exports = {
62
+ parseCommonArgs
63
+ }
package/lib/config.js CHANGED
@@ -23,7 +23,7 @@ function isSvnWorkingCopy (dir) {
23
23
  }
24
24
 
25
25
  /**
26
- * 自动检测 VCS 类型(PHP 后端常见:BackendSVN/trunk 可能 Git+SVN 并存)
26
+ * 自动检测 VCS 类型(PHP 项目可能 Git + SVN 工作副本并存)
27
27
  * @param {string} sourceDir
28
28
  * @returns {'svn'|'git'|null}
29
29
  */
@@ -38,7 +38,7 @@ function detectVcs (sourceDir) {
38
38
  const hasSvn = isSvnWorkingCopy(sourceDir)
39
39
  const hasGit = isGitRepository(sourceDir)
40
40
 
41
- // 双仓库并存时:有 SVN marker / 旧版 rev 文件则优先 SVN(KJCG Backend 场景)
41
+ // 双仓库并存时:有 SVN marker / 旧版 rev 文件则优先 SVN
42
42
  if (hasSvn && hasGit) {
43
43
  if (marker?.vcs === 'svn') return 'svn'
44
44
  const legacyRev = path.join(deployDir, '.last-deploy-rev')
@@ -65,6 +65,9 @@ function detectVcs (sourceDir) {
65
65
  * @property {boolean} markDeployed
66
66
  * @property {boolean} skipValidation
67
67
  * @property {string} zipPrefix
68
+ * @property {string|null} version 安装版本号(如 1.2.3)
69
+ * @property {string[]} onlyFiles 仅打包/部署指定文件
70
+ * @property {string|null} fileList 文件列表路径(每行一个相对路径)
68
71
  */
69
72
 
70
73
  /**
@@ -106,7 +109,10 @@ function resolveConfig (input = {}) {
106
109
  noZip: Boolean(input.noZip),
107
110
  markDeployed: Boolean(input.markDeployed),
108
111
  skipValidation: Boolean(input.skipValidation || process.env.PATCH_SKIP_VALIDATION === 'true'),
109
- zipPrefix: input.zipPrefix || process.env.PATCH_ZIP_PREFIX || backend.defaultZipPrefix
112
+ zipPrefix: input.zipPrefix || process.env.PATCH_ZIP_PREFIX || backend.defaultZipPrefix,
113
+ version: input.version || process.env.PATCH_VERSION || null,
114
+ onlyFiles: input.onlyFiles || [],
115
+ fileList: input.fileList || process.env.PATCH_FILE_LIST || null
110
116
  }
111
117
  }
112
118
 
@@ -131,6 +137,7 @@ function initDeployDir (deployDir, vcs = 'svn') {
131
137
  ## 基准文件
132
138
 
133
139
  - \`.last-deploy-marker\`:上次成功上线标记,格式 \`svn:467\` 或 \`git:abc123...\`
140
+ - \`versions.json\`:版本号与 patch 目录映射(\`patch-build --version=1.2.3\`)
134
141
  - 兼容旧版 SVN:\`.last-deploy-rev\`(仅数字)
135
142
 
136
143
  ## 本机打包