vcs-patch-deploy 1.0.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### 新增
6
+
7
+ - **版本号部署**:`patch-build --version=1.2.3` 写入 `VERSION.txt` 与 `deploy/versions.json`
8
+ - **单独文件提取**:`patch-extract --version=1.2.3 --only=<文件>` 从完整包提取子集
9
+ - **按文件打包/部署**:`--only` / `--file-list`(打包端)、`--files` / `PATCH_DEPLOY_FILES`(服务器端)
10
+ - 新增 CLI:`patch-extract`
11
+ - 单元测试(`npm test`)与 GitHub Actions CI
12
+
13
+ ### 改进
14
+
15
+ - `apply-update.php`:部署前自动备份;优先读 MANIFEST 减少目录扫描
16
+ - `versions.json`:原子写入、损坏时告警、子集版本去重
17
+ - `build-patch`:staging 目录构建,失败不破坏旧 patch;SVN revision NaN 校验
18
+ - `git.js`:Git 未安装时 `detectVcs` 不再崩溃;支持类型变更 diff
19
+ - zip 默认压缩级别 6(可通过 `PATCH_ZIP_LEVEL` 调整)
20
+
21
+ ## Unreleased
22
+
3
23
  ## 1.0.1
4
24
 
5
25
  - 文档与示例改用通用占位路径,移除项目专有目录名
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  PHP 后端(ThinkPHP)增量部署包生成工具。对比 **SVN revision** 或 **Git commit** 差异,生成本地 zip,附带 `apply-update.php`,供堡垒机 / Web 终端上线。
4
4
 
5
- - npm:https://www.npmjs.com/package/vcs-patch-deploy
6
- - GitHub:https://github.com/QINGYUAI/vcs-patch-deploy
5
+ - npm:<https://www.npmjs.com/package/vcs-patch-deploy>
6
+ - GitHub:<https://github.com/QINGYUAI/vcs-patch-deploy>
7
7
 
8
8
  > v1 仅内置 **PHP 后端**配置;Node/Java 等后端可在后续版本通过 `--backend` 扩展。
9
9
 
@@ -49,6 +49,37 @@ patch-build --vcs=git
49
49
  patch-build --vcs=git --from=v1.0.0 --to=HEAD
50
50
  ```
51
51
 
52
+ ## 版本号与单独文件部署
53
+
54
+ 为每次上线打上**安装版本号**,并支持从完整包中**提取部分文件**单独部署:
55
+
56
+ ```bash
57
+ # 1. 打完整版本包(写入 VERSION.txt、deploy/versions.json)
58
+ patch-build --vcs=svn --version=1.2.3
59
+
60
+ # 2. 打包时只包含指定文件(从本次增量中筛选)
61
+ patch-build --vcs=svn --version=1.2.3 --only=app/service/Foo.php,app/controller/Bar.php
62
+ patch-build --vcs=svn --version=1.2.3 --file-list=hotfix-files.txt
63
+
64
+ # 3. 从已打好的 v1.2.3 完整包中提取子集(无需重新 diff)
65
+ patch-extract --version=1.2.3 --only=app/service/Foo.php
66
+ patch-extract --list-versions
67
+
68
+ # 产物示例
69
+ # deploy/out/patch-v1.2.3/
70
+ # deploy/out/backend-update-v1.2.3.zip
71
+ # deploy/versions.json
72
+ ```
73
+
74
+ 服务器上也可在完整 patch 包内**只部署部分文件**:
75
+
76
+ ```bash
77
+ php apply-update.php --files=app/service/Foo.php /path/to/production-api
78
+ php apply-update.php --file-list=deploy-files.txt /path/to/production-api
79
+ export PATCH_DEPLOY_FILES=app/service/Foo.php,app/controller/Bar.php
80
+ php apply-update.php /path/to/production-api
81
+ ```
82
+
52
83
  ## 服务器应用
53
84
 
54
85
  ```bash
@@ -66,14 +97,26 @@ php apply-update.php
66
97
  `apply-update.php` 行为:
67
98
 
68
99
  - 按包内路径覆盖线上文件
100
+ - **覆盖前备份** 线上已有文件到 `Backend/.deploy-backups/<时间戳>/`(保持相对路径)
69
101
  - **不覆盖** `.env`
70
102
  - **不自动删除** `MANIFEST-deleted.txt` 中的文件
71
103
  - 成功后清理 `runtime/cache`,并尝试 `php think clear`
72
104
 
105
+ 备份相关:
106
+
107
+ ```bash
108
+ # 默认开启备份;跳过备份
109
+ php apply-update.php --no-backup /path/to/production-api
110
+
111
+ # 自定义备份根目录(仍会在其下创建 <时间戳>/ 子目录)
112
+ export PATCH_BACKUP_DIR=/data/backups/my-api
113
+ php apply-update.php /path/to/production-api
114
+ ```
115
+
73
116
  ## CLI 参数
74
117
 
75
118
  | 参数 | 说明 |
76
- |------|------|
119
+ | ------ | ------ |
77
120
  | `--backend=php` | 后端类型(默认 php) |
78
121
  | `--vcs=svn\|git` | 强制 VCS 类型 |
79
122
  | `--source=<dir>` | PHP 项目根 |
@@ -83,6 +126,20 @@ php apply-update.php
83
126
  | `--no-zip` | 只生成 patch 目录 |
84
127
  | `--mark-deployed` | 更新基准 marker |
85
128
  | `--init` | 初始化 deploy 目录 |
129
+ | `--version=<版本>` | 安装版本号(写入 VERSION.txt、versions.json) |
130
+ | `--only=<文件>` | 仅打包指定文件(逗号分隔) |
131
+ | `--file-list=<文件>` | 文件列表(每行一个相对路径) |
132
+
133
+ ### patch-extract
134
+
135
+ | 参数 | 说明 |
136
+ | ------ | ------ |
137
+ | `--version=<版本>` | 从已注册版本提取 |
138
+ | `--from-patch=<目录>` | 直接指定源 patch 目录 |
139
+ | `--only=<文件>` | 要提取的文件 |
140
+ | `--file-list=<文件>` | 文件列表 |
141
+ | `--list-versions` | 列出 deploy/versions.json 中的版本 |
142
+ | `--register` | 将子集包注册到 versions.json |
86
143
 
87
144
  ## 不会打进包的内容
88
145
 
@@ -93,9 +150,10 @@ php apply-update.php
93
150
  ## 基准文件
94
151
 
95
152
  | 文件 | 格式 |
96
- |------|------|
153
+ | ------ | ------ |
97
154
  | `deploy/.last-deploy-marker` | `svn:467` 或 `git:fullsha` |
98
155
  | `deploy/.last-deploy-rev` | 兼容旧版 SVN 工具(仅数字) |
156
+ | `deploy/versions.json` | 版本号与 patch 目录映射 |
99
157
 
100
158
  **上线成功后再更新基准**,否则下次增量会漏文件。
101
159
 
@@ -10,16 +10,21 @@ declare(strict_types=1);
10
10
  * PATCH_BACKEND_ROOT=/path/to/production-api php apply-update.php
11
11
  *
12
12
  * 安全:不会覆盖 .env;不会自动删除 MANIFEST-deleted.txt 中列出的文件。
13
+ * 备份:覆盖前将线上已有文件复制到备份目录(默认 Backend/.deploy-backups/<时间戳>/)。
13
14
  */
14
15
 
15
16
  /** patch 包根目录(本脚本所在目录) */
16
17
  const PATCH_ROOT = __DIR__;
17
18
 
19
+ /** 默认备份目录名(位于 Backend 根下,可通过 PATCH_BACKUP_DIR 覆盖父路径) */
20
+ const BACKUP_DIR_BASENAME = '.deploy-backups';
21
+
18
22
  /** 部署时跳过的文件名(相对路径 basename 匹配或完整相对路径) */
19
23
  const SKIP_FILES = [
20
24
  'apply-update.php',
21
25
  'MANIFEST.txt',
22
26
  'MANIFEST-deleted.txt',
27
+ 'VERSION.txt',
23
28
  ];
24
29
 
25
30
  /** 永不覆盖的相对路径(保护生产配置与运行时数据) */
@@ -49,7 +54,7 @@ function resolveBackendRoot(): string
49
54
  }
50
55
 
51
56
  global $argv;
52
- $flags = ['--check', '--dry-run'];
57
+ $flags = ['--check', '--dry-run', '--no-backup'];
53
58
  foreach ($argv as $i => $arg) {
54
59
  if ($i === 0) {
55
60
  continue;
@@ -57,21 +62,81 @@ function resolveBackendRoot(): string
57
62
  if (in_array($arg, $flags, true)) {
58
63
  continue;
59
64
  }
65
+ if (str_starts_with($arg, '--files=') || str_starts_with($arg, '--file-list=')) {
66
+ continue;
67
+ }
60
68
  if ($arg !== '' && !str_starts_with($arg, '-')) {
61
69
  return rtrim($arg, "/\\");
62
70
  }
63
71
  }
64
72
 
65
- fwrite(STDERR, "用法: php apply-update.php [--check] <Backend根目录>\n");
73
+ fwrite(STDERR, "用法: php apply-update.php [--check] [--files=<路径>] [--file-list=<列表>] <Backend根目录>\n");
66
74
  fwrite(STDERR, "示例: php apply-update.php /path/to/production-api\n");
75
+ fwrite(STDERR, " php apply-update.php --files=app/service/Foo.php /path/to/production-api\n");
67
76
  exit(1);
68
77
  }
69
78
 
79
+ /**
80
+ * 优先从 MANIFEST.txt 读取文件列表,避免大 patch 全目录扫描
81
+ *
82
+ * @return list<string>|null
83
+ */
84
+ function readManifestFileList(): ?array
85
+ {
86
+ $manifestPath = PATCH_ROOT . '/MANIFEST.txt';
87
+ if (!is_file($manifestPath)) {
88
+ return null;
89
+ }
90
+
91
+ $lines = file($manifestPath, FILE_IGNORE_NEW_LINES);
92
+ if ($lines === false) {
93
+ return null;
94
+ }
95
+
96
+ /** @var list<string> $files */
97
+ $files = [];
98
+ $inFiles = false;
99
+
100
+ foreach ($lines as $line) {
101
+ $trimmed = trim($line);
102
+ if ($trimmed === '# files') {
103
+ $inFiles = true;
104
+ continue;
105
+ }
106
+ if ($inFiles && str_starts_with($trimmed, '#')) {
107
+ break;
108
+ }
109
+ if ($inFiles && $trimmed !== '') {
110
+ $files[] = str_replace('\\', '/', $trimmed);
111
+ }
112
+ }
113
+
114
+ return $files === [] ? null : $files;
115
+ }
116
+
70
117
  /**
71
118
  * @return list<string> 相对路径,使用 /
72
119
  */
73
120
  function listPatchFiles(): array
74
121
  {
122
+ $fromManifest = readManifestFileList();
123
+ if ($fromManifest !== null) {
124
+ /** @var list<string> $files */
125
+ $files = [];
126
+ foreach ($fromManifest as $rel) {
127
+ $abs = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
128
+ if (!is_file($abs)) {
129
+ continue;
130
+ }
131
+ if (in_array($rel, PROTECTED_RELATIVE, true)) {
132
+ continue;
133
+ }
134
+ $files[] = $rel;
135
+ }
136
+ sort($files);
137
+ return $files;
138
+ }
139
+
75
140
  $files = [];
76
141
  $iterator = new RecursiveIteratorIterator(
77
142
  new RecursiveDirectoryIterator(PATCH_ROOT, FilesystemIterator::SKIP_DOTS)
@@ -115,6 +180,99 @@ function listPatchFiles(): array
115
180
  return $files;
116
181
  }
117
182
 
183
+ /**
184
+ * 解析 --files / --file-list / PATCH_DEPLOY_FILES,用于单独部署部分文件
185
+ *
186
+ * @return list<string>|null null 表示部署全部
187
+ */
188
+ function resolveDeployFileFilter(): ?array
189
+ {
190
+ global $argv;
191
+
192
+ /** @var list<string> $selected */
193
+ $selected = [];
194
+
195
+ $fromEnv = getenv('PATCH_DEPLOY_FILES');
196
+ if (is_string($fromEnv) && $fromEnv !== '') {
197
+ foreach (explode(',', $fromEnv) as $item) {
198
+ $item = trim(str_replace('\\', '/', $item));
199
+ if ($item !== '') {
200
+ $selected[] = $item;
201
+ }
202
+ }
203
+ }
204
+
205
+ foreach ($argv ?? [] as $arg) {
206
+ if (str_starts_with($arg, '--files=')) {
207
+ foreach (explode(',', substr($arg, 8)) as $item) {
208
+ $item = trim(str_replace('\\', '/', $item));
209
+ if ($item !== '') {
210
+ $selected[] = $item;
211
+ }
212
+ }
213
+ }
214
+ if (str_starts_with($arg, '--file-list=')) {
215
+ $listPath = substr($arg, 12);
216
+ if (!is_file($listPath)) {
217
+ throw new RuntimeException("文件列表不存在: {$listPath}");
218
+ }
219
+ foreach (file($listPath, FILE_IGNORE_NEW_LINES) ?: [] as $line) {
220
+ $line = trim($line);
221
+ if ($line === '' || str_starts_with($line, '#')) {
222
+ continue;
223
+ }
224
+ $selected[] = str_replace('\\', '/', $line);
225
+ }
226
+ }
227
+ }
228
+
229
+ if ($selected === []) {
230
+ return null;
231
+ }
232
+
233
+ return array_values(array_unique($selected));
234
+ }
235
+
236
+ /**
237
+ * 按筛选条件过滤待部署文件;支持目录前缀(以 / 结尾)
238
+ *
239
+ * @param list<string> $allFiles
240
+ * @param list<string> $selected
241
+ * @return array{matched: list<string>, missing: list<string>}
242
+ */
243
+ function filterDeployFiles(array $allFiles, array $selected): array
244
+ {
245
+ /** @var array<string, true> $matchedMap */
246
+ $matchedMap = [];
247
+ /** @var list<string> $missing */
248
+ $missing = [];
249
+
250
+ foreach ($selected as $sel) {
251
+ if (str_ends_with($sel, '/')) {
252
+ $hits = array_values(array_filter($allFiles, static fn(string $f): bool => str_starts_with($f, $sel)));
253
+ if ($hits === []) {
254
+ $missing[] = $sel;
255
+ } else {
256
+ foreach ($hits as $hit) {
257
+ $matchedMap[$hit] = true;
258
+ }
259
+ }
260
+ continue;
261
+ }
262
+
263
+ if (in_array($sel, $allFiles, true)) {
264
+ $matchedMap[$sel] = true;
265
+ } else {
266
+ $missing[] = $sel;
267
+ }
268
+ }
269
+
270
+ $matched = array_keys($matchedMap);
271
+ sort($matched);
272
+
273
+ return ['matched' => $matched, 'missing' => $missing];
274
+ }
275
+
118
276
  function detectPhpBinary(): string
119
277
  {
120
278
  if (defined('PHP_BINARY') && PHP_BINARY !== '') {
@@ -208,6 +366,53 @@ function ensureParentDir(string $path): void
208
366
  }
209
367
  }
210
368
 
369
+ /**
370
+ * 解析备份根目录:PATCH_BACKUP_DIR 优先,否则 Backend/.deploy-backups
371
+ */
372
+ function resolveBackupRoot(string $backendRoot): string
373
+ {
374
+ $fromEnv = getenv('PATCH_BACKUP_DIR');
375
+ if (is_string($fromEnv) && $fromEnv !== '') {
376
+ return rtrim($fromEnv, "/\\");
377
+ }
378
+
379
+ return $backendRoot . '/' . BACKUP_DIR_BASENAME;
380
+ }
381
+
382
+ /**
383
+ * 创建本次部署的备份会话目录(按时间戳区分)
384
+ */
385
+ function createBackupSessionDir(string $backupRoot): string
386
+ {
387
+ $timestamp = date('Y-m-d_His');
388
+ $sessionDir = $backupRoot . '/' . $timestamp;
389
+ if (!is_dir($sessionDir) && !mkdir($sessionDir, 0755, true) && !is_dir($sessionDir)) {
390
+ throw new RuntimeException("无法创建备份目录: {$sessionDir}");
391
+ }
392
+
393
+ return $sessionDir;
394
+ }
395
+
396
+ /**
397
+ * 将被覆盖的线上文件复制到备份目录(保持相对路径结构)
398
+ *
399
+ * @return bool 是否执行了备份(目标文件不存在则 false)
400
+ */
401
+ function backupExistingFile(string $dst, string $rel, string $backupSessionDir): bool
402
+ {
403
+ if (!is_file($dst)) {
404
+ return false;
405
+ }
406
+
407
+ $backupPath = $backupSessionDir . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
408
+ ensureParentDir($backupPath);
409
+ if (!copy($dst, $backupPath)) {
410
+ throw new RuntimeException("备份失败: {$rel}");
411
+ }
412
+
413
+ return true;
414
+ }
415
+
211
416
  function clearRuntimeCache(string $backendRoot): void
212
417
  {
213
418
  $cacheDir = $backendRoot . '/runtime/cache';
@@ -255,7 +460,8 @@ function tryThinkClear(string $backendRoot): void
255
460
  return;
256
461
  }
257
462
 
258
- $cmd = 'php ' . escapeshellarg($think) . ' clear 2>&1';
463
+ $phpBin = detectPhpBinary();
464
+ $cmd = escapeshellarg($phpBin) . ' ' . escapeshellarg($think) . ' clear 2>&1';
259
465
  $output = [];
260
466
  $code = 0;
261
467
  exec($cmd, $output, $code);
@@ -281,6 +487,8 @@ if (!is_dir($backendRoot . '/app')) {
281
487
  }
282
488
 
283
489
  $dryRun = in_array('--check', $argv ?? [], true) || in_array('--dry-run', $argv ?? [], true);
490
+ $noBackup = in_array('--no-backup', $argv ?? [], true);
491
+ $backupEnabled = !$dryRun && !$noBackup;
284
492
 
285
493
  $runUser = function_exists('posix_getpwuid')
286
494
  ? (posix_getpwuid(posix_geteuid())['name'] ?? 'unknown')
@@ -292,8 +500,31 @@ echo "RUN_AS: {$runUser}\n";
292
500
  if ($dryRun) {
293
501
  echo "MODE: check-only(不写入文件)\n";
294
502
  }
503
+ if ($noBackup) {
504
+ echo "BACKUP: disabled(--no-backup)\n";
505
+ } elseif ($backupEnabled) {
506
+ echo "BACKUP: enabled -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
507
+ }
295
508
 
296
509
  $files = listPatchFiles();
510
+
511
+ try {
512
+ $fileFilter = resolveDeployFileFilter();
513
+ } catch (Throwable $e) {
514
+ fwrite(STDERR, $e->getMessage() . "\n");
515
+ exit(1);
516
+ }
517
+
518
+ if ($fileFilter !== null) {
519
+ $filterResult = filterDeployFiles($files, $fileFilter);
520
+ if ($filterResult['missing'] !== []) {
521
+ fwrite(STDERR, "以下文件不在 patch 包内:\n - " . implode("\n - ", $filterResult['missing']) . "\n");
522
+ exit(1);
523
+ }
524
+ $files = $filterResult['matched'];
525
+ echo "DEPLOY_FILTER: " . count($files) . " 个文件(单独部署模式)\n";
526
+ }
527
+
297
528
  if ($files === []) {
298
529
  echo "patch 包内无待部署文件。\n";
299
530
  exit(0);
@@ -302,6 +533,9 @@ if ($files === []) {
302
533
  $ok = 0;
303
534
  $fail = 0;
304
535
  $blocked = [];
536
+ $backedUp = 0;
537
+ /** @var string|null 本次部署备份会话目录 */
538
+ $backupSessionDir = null;
305
539
 
306
540
  foreach ($files as $rel) {
307
541
  $src = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
@@ -310,11 +544,23 @@ foreach ($files as $rel) {
310
544
  try {
311
545
  assertTargetWritable($dst, $rel);
312
546
  if ($dryRun) {
313
- echo "OK {$rel}(可写)\n";
547
+ $existsHint = is_file($dst) ? ',线上已有文件' : '';
548
+ echo "OK {$rel}(可写{$existsHint})\n";
314
549
  $ok++;
315
550
  continue;
316
551
  }
317
552
 
553
+ // 覆盖前先备份线上旧文件
554
+ if ($backupEnabled && is_file($dst)) {
555
+ if ($backupSessionDir === null) {
556
+ $backupSessionDir = createBackupSessionDir(resolveBackupRoot($backendRoot));
557
+ echo "BACKUP_DIR: {$backupSessionDir}\n";
558
+ }
559
+ if (backupExistingFile($dst, $rel, $backupSessionDir)) {
560
+ $backedUp++;
561
+ }
562
+ }
563
+
318
564
  ensureParentDir($dst);
319
565
  if (!copy($src, $dst)) {
320
566
  throw new RuntimeException('copy 失败');
@@ -363,6 +609,11 @@ if ($fail > 0) {
363
609
  clearRuntimeCache($backendRoot);
364
610
  tryThinkClear($backendRoot);
365
611
 
612
+ if ($backupSessionDir !== null) {
613
+ echo "\n已备份 {$backedUp} 个旧文件至: {$backupSessionDir}\n";
614
+ echo "回滚示例: cp -f {$backupSessionDir}/app/... {$backendRoot}/app/...\n";
615
+ }
616
+
366
617
  $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
367
618
  if (is_file($deletedList)) {
368
619
  echo "\n注意: 存在 MANIFEST-deleted.txt,未自动删除线上文件,请人工确认:\n";
@@ -33,6 +33,9 @@ ${chalk.yellow('选项:')}
33
33
  --init 初始化 deploy 目录结构
34
34
  --skip-validation 跳过 PHP 项目结构校验
35
35
  --zip-prefix=<前缀> zip 前缀(默认 backend-update)
36
+ --version=<版本号> 安装版本号(如 1.2.3,写入 VERSION.txt 与 versions.json)
37
+ --only=<文件> 仅打包指定文件(逗号分隔,可重复;支持 @files.txt)
38
+ --file-list=<文件> 文件列表(每行一个相对路径)
36
39
  -h, --help 显示帮助
37
40
 
38
41
  ${chalk.yellow('环境变量:')}
@@ -41,6 +44,14 @@ ${chalk.yellow('环境变量:')}
41
44
  PATCH_SOURCE_DIR 源码根
42
45
  PATCH_DEPLOY_DIR deploy 目录
43
46
  PATCH_ZIP_PREFIX zip 前缀
47
+ PATCH_VERSION 安装版本号
48
+ PATCH_FILE_LIST 仅打包的文件列表路径
49
+
50
+ ${chalk.yellow('版本号 + 单独文件部署:')}
51
+ patch-build --vcs=svn --version=1.2.3
52
+ patch-build --vcs=svn --version=1.2.3 --only=app/service/Foo.php
53
+ patch-extract --version=1.2.3 --only=app/service/Foo.php,app/controller/Bar.php
54
+ patch-extract --list-versions
44
55
 
45
56
  ${chalk.yellow('ThinkPHP + SVN:')}
46
57
  cd /path/to/your-php-api
@@ -59,7 +70,7 @@ ${chalk.yellow('服务器应用:')}
59
70
 
60
71
  function parseArgs () {
61
72
  const args = process.argv.slice(2)
62
- const opts = { showHelp: false }
73
+ const opts = { showHelp: false, onlyFiles: [] }
63
74
 
64
75
  for (const arg of args) {
65
76
  if (arg === '--help' || arg === '-h') opts.showHelp = true
@@ -74,6 +85,9 @@ function parseArgs () {
74
85
  else if (arg.startsWith('--from=')) opts.fromRef = arg.split('=')[1]
75
86
  else if (arg.startsWith('--to=')) opts.toRef = arg.split('=')[1]
76
87
  else if (arg.startsWith('--zip-prefix=')) opts.zipPrefix = arg.split('=')[1]
88
+ else if (arg.startsWith('--version=')) opts.version = arg.split('=')[1]
89
+ else if (arg.startsWith('--only=')) opts.onlyFiles.push(...arg.split('=')[1].split(','))
90
+ else if (arg.startsWith('--file-list=')) opts.fileList = arg.split('=')[1]
77
91
  else console.warn(chalk.yellow(`未知参数: ${arg}`))
78
92
  }
79
93
 
@@ -98,6 +112,9 @@ async function main () {
98
112
  markDeployed: opts.markDeployed,
99
113
  skipValidation: opts.skipValidation,
100
114
  zipPrefix: opts.zipPrefix,
115
+ version: opts.version,
116
+ onlyFiles: opts.onlyFiles,
117
+ fileList: opts.fileList,
101
118
  pkgRoot: path.join(__dirname, '..')
102
119
  })
103
120
 
@@ -136,6 +153,9 @@ async function main () {
136
153
 
137
154
  if (!result.skipped && !opts.markDeployed) {
138
155
  console.log(chalk.cyan('\n下一步: 上传 zip → 解压 → php apply-update.php <Backend根目录>'))
156
+ if (result.version) {
157
+ console.log(chalk.cyan(` 子集提取: patch-extract --version=${result.version} --only=<文件>`))
158
+ }
139
159
  }
140
160
 
141
161
  process.exit(result.success ? 0 : 1)
@@ -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
+ })