vcs-patch-deploy 1.1.1 → 1.2.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,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### 新增
6
+
7
+ - **版本备份(服务器)**:部署时按版本号备份至 `.deploy-backups/v1.2.2/` 或 `r467/`,写入 `.deploy-version`
8
+ - **回滚与列表**:`apply-update.php --rollback` / `--list-backups`
9
+ - **本地版本归档**:打包后自动归档至 `deploy/archive/`,默认保留 10 个版本(`--keep-versions` / `--no-archive`)
10
+ - 所有 patch 包写入 `VERSION.txt`,revision 包自动使用 `r467` 标识
11
+
3
12
  ## 1.1.1
4
13
 
5
14
  ### 修复
@@ -7,8 +16,6 @@
7
16
  - `apply-update.php`:兼容 ThinkPHP 5(`application/`)及 patch 路径推断,不再强制要求 `app/`
8
17
  - `validatePhpBackend`:识别 `application/` 旧版目录结构
9
18
 
10
- ## Unreleased
11
-
12
19
  ## 1.1.0
13
20
 
14
21
  ### 新增
@@ -10,7 +10,9 @@ 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
+ * 备份:覆盖前将线上已有文件复制到版本备份目录(默认 Backend/.deploy-backups/v1.2.2/ 或 r467/)。
14
+ * 回滚:php apply-update.php --rollback[=版本] <Backend根目录>
15
+ * 列表:php apply-update.php --list-backups <Backend根目录>
14
16
  */
15
17
 
16
18
  /** patch 包根目录(本脚本所在目录) */
@@ -19,6 +21,12 @@ const PATCH_ROOT = __DIR__;
19
21
  /** 默认备份目录名(位于 Backend 根下,可通过 PATCH_BACKUP_DIR 覆盖父路径) */
20
22
  const BACKUP_DIR_BASENAME = '.deploy-backups';
21
23
 
24
+ /** 当前线上部署版本记录文件(位于 Backend 根下) */
25
+ const DEPLOY_VERSION_FILE = '.deploy-version';
26
+
27
+ /** 版本备份元数据文件名 */
28
+ const DEPLOY_META_FILE = 'DEPLOY-META.txt';
29
+
22
30
  /** 部署时跳过的文件名(相对路径 basename 匹配或完整相对路径) */
23
31
  const SKIP_FILES = [
24
32
  'apply-update.php',
@@ -54,7 +62,7 @@ function resolveBackendRoot(): string
54
62
  }
55
63
 
56
64
  global $argv;
57
- $flags = ['--check', '--dry-run', '--no-backup'];
65
+ $flags = ['--check', '--dry-run', '--no-backup', '--list-backups', '--rollback'];
58
66
  foreach ($argv as $i => $arg) {
59
67
  if ($i === 0) {
60
68
  continue;
@@ -65,17 +73,373 @@ function resolveBackendRoot(): string
65
73
  if (str_starts_with($arg, '--files=') || str_starts_with($arg, '--file-list=')) {
66
74
  continue;
67
75
  }
76
+ if (str_starts_with($arg, '--rollback=')) {
77
+ continue;
78
+ }
68
79
  if ($arg !== '' && !str_starts_with($arg, '-')) {
69
80
  return rtrim($arg, "/\\");
70
81
  }
71
82
  }
72
83
 
73
- fwrite(STDERR, "用法: php apply-update.php [--check] [--files=<路径>] [--file-list=<列表>] <Backend根目录>\n");
84
+ fwrite(STDERR, "用法: php apply-update.php [--check] [--rollback[=版本]] [--list-backups] [--files=<路径>] <Backend根目录>\n");
74
85
  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");
86
+ fwrite(STDERR, " php apply-update.php --rollback /path/to/production-api\n");
87
+ fwrite(STDERR, " php apply-update.php --rollback=1.2.2 /path/to/production-api\n");
88
+ fwrite(STDERR, " php apply-update.php --list-backups /path/to/production-api\n");
76
89
  exit(1);
77
90
  }
78
91
 
92
+ /**
93
+ * 解析 --rollback[=版本] 参数
94
+ *
95
+ * @return array{enabled: bool, target: string|null}
96
+ */
97
+ function resolveRollbackOption(): array
98
+ {
99
+ global $argv;
100
+
101
+ foreach ($argv ?? [] as $arg) {
102
+ if ($arg === '--rollback') {
103
+ return ['enabled' => true, 'target' => null];
104
+ }
105
+ if (str_starts_with($arg, '--rollback=')) {
106
+ $target = trim(substr($arg, 11));
107
+ if ($target === '') {
108
+ throw new RuntimeException('--rollback= 需要指定版本号');
109
+ }
110
+ return ['enabled' => true, 'target' => $target];
111
+ }
112
+ }
113
+
114
+ return ['enabled' => false, 'target' => null];
115
+ }
116
+
117
+ /**
118
+ * 清洗版本标识(与 Node sanitizeVersionLabel 对齐)
119
+ */
120
+ function sanitizeVersionLabel(string $version): string
121
+ {
122
+ $label = trim($version);
123
+ $label = preg_replace('/^v/i', '', $label) ?? $label;
124
+ $label = preg_replace('/[^a-zA-Z0-9._-]/', '_', $label) ?? $label;
125
+
126
+ return $label;
127
+ }
128
+
129
+ /**
130
+ * 读取 key=value 多行元数据文件(忽略 # 注释行)
131
+ *
132
+ * @return array<string, string>
133
+ */
134
+ function readKeyValueFile(string $filePath): array
135
+ {
136
+ if (!is_file($filePath)) {
137
+ return [];
138
+ }
139
+
140
+ $lines = file($filePath, FILE_IGNORE_NEW_LINES);
141
+ if ($lines === false) {
142
+ return [];
143
+ }
144
+
145
+ /** @var array<string, string> $meta */
146
+ $meta = [];
147
+ foreach ($lines as $line) {
148
+ $trimmed = trim($line);
149
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
150
+ continue;
151
+ }
152
+ $pos = strpos($trimmed, '=');
153
+ if ($pos === false) {
154
+ continue;
155
+ }
156
+ $key = trim(substr($trimmed, 0, $pos));
157
+ $value = trim(substr($trimmed, $pos + 1));
158
+ if ($key !== '') {
159
+ $meta[$key] = $value;
160
+ }
161
+ }
162
+
163
+ return $meta;
164
+ }
165
+
166
+ /**
167
+ * 从 patch 包解析本次部署版本(VERSION.txt 优先,兼容 MANIFEST revision 包)
168
+ */
169
+ function resolvePatchDeployVersion(): ?string
170
+ {
171
+ $versionMeta = readKeyValueFile(PATCH_ROOT . '/VERSION.txt');
172
+ if (isset($versionMeta['version']) && $versionMeta['version'] !== '') {
173
+ return sanitizeVersionLabel($versionMeta['version']);
174
+ }
175
+
176
+ $manifestMeta = readKeyValueFile(PATCH_ROOT . '/MANIFEST.txt');
177
+ if (isset($manifestMeta['version']) && $manifestMeta['version'] !== '') {
178
+ return sanitizeVersionLabel($manifestMeta['version']);
179
+ }
180
+ if (($manifestMeta['vcs'] ?? '') === 'svn' && isset($manifestMeta['to_revision']) && $manifestMeta['to_revision'] !== '') {
181
+ return 'r' . $manifestMeta['to_revision'];
182
+ }
183
+ if (isset($manifestMeta['to_commit']) && $manifestMeta['to_commit'] !== '') {
184
+ return substr($manifestMeta['to_commit'], 0, 12);
185
+ }
186
+
187
+ return null;
188
+ }
189
+
190
+ /**
191
+ * 备份目录名:v1.2.3 / r467 / pre-deploy
192
+ */
193
+ function formatBackupDirName(string $versionLabel): string
194
+ {
195
+ $label = sanitizeVersionLabel($versionLabel);
196
+ if ($label === 'pre-deploy') {
197
+ return 'pre-deploy';
198
+ }
199
+ if (preg_match('/^r\d+$/i', $label) === 1) {
200
+ return strtolower($label);
201
+ }
202
+ if (preg_match('/^\d/', $label) === 1) {
203
+ return 'v' . $label;
204
+ }
205
+
206
+ return $label;
207
+ }
208
+
209
+ /**
210
+ * 读取当前线上部署版本
211
+ */
212
+ function readDeployedVersion(string $backendRoot): ?string
213
+ {
214
+ $path = $backendRoot . '/' . DEPLOY_VERSION_FILE;
215
+ if (!is_file($path)) {
216
+ return null;
217
+ }
218
+
219
+ $value = trim((string) file_get_contents($path));
220
+ if ($value === '') {
221
+ return null;
222
+ }
223
+
224
+ return sanitizeVersionLabel($value);
225
+ }
226
+
227
+ /**
228
+ * 写入当前线上部署版本
229
+ */
230
+ function writeDeployedVersion(string $backendRoot, string $versionLabel): void
231
+ {
232
+ $path = $backendRoot . '/' . DEPLOY_VERSION_FILE;
233
+ file_put_contents($path, sanitizeVersionLabel($versionLabel) . "\n");
234
+ }
235
+
236
+ /**
237
+ * 创建版本备份会话目录(无版本标识时降级为时间戳目录)
238
+ */
239
+ function createVersionBackupSessionDir(string $backupRoot, ?string $currentVersionLabel): string
240
+ {
241
+ if ($currentVersionLabel === null || $currentVersionLabel === '') {
242
+ return createBackupSessionDir($backupRoot);
243
+ }
244
+
245
+ $sessionDir = $backupRoot . '/' . formatBackupDirName($currentVersionLabel);
246
+ if (is_dir($sessionDir)) {
247
+ // 同版本重复部署:追加时间戳子目录,避免覆盖历史备份
248
+ $sessionDir .= '_' . date('Y-m-d_His');
249
+ }
250
+ if (!is_dir($sessionDir) && !mkdir($sessionDir, 0755, true) && !is_dir($sessionDir)) {
251
+ throw new RuntimeException("无法创建版本备份目录: {$sessionDir}");
252
+ }
253
+
254
+ return $sessionDir;
255
+ }
256
+
257
+ /**
258
+ * 写入版本备份元数据
259
+ *
260
+ * @param list<string> $backedUpFiles
261
+ */
262
+ function writeDeployMeta(
263
+ string $backupSessionDir,
264
+ string $versionLabel,
265
+ ?string $replacedBy,
266
+ array $backedUpFiles
267
+ ): void {
268
+ $lines = [
269
+ 'version=' . sanitizeVersionLabel($versionLabel),
270
+ 'backup_label=' . basename($backupSessionDir),
271
+ 'backed_up_at=' . date('Y-m-d H:i:s'),
272
+ 'file_count=' . count($backedUpFiles),
273
+ ];
274
+ if ($replacedBy !== null && $replacedBy !== '') {
275
+ $lines[] = 'replaced_by=' . sanitizeVersionLabel($replacedBy);
276
+ }
277
+ $lines[] = '';
278
+ $lines[] = '# files';
279
+ foreach ($backedUpFiles as $rel) {
280
+ $lines[] = $rel;
281
+ }
282
+
283
+ file_put_contents($backupSessionDir . '/' . DEPLOY_META_FILE, implode("\n", $lines) . "\n");
284
+ }
285
+
286
+ /**
287
+ * 读取备份目录元数据
288
+ *
289
+ * @return array<string, string>
290
+ */
291
+ function readDeployMeta(string $backupSessionDir): array
292
+ {
293
+ return readKeyValueFile($backupSessionDir . '/' . DEPLOY_META_FILE);
294
+ }
295
+
296
+ /**
297
+ * 列出备份目录内可恢复文件(排除元数据)
298
+ *
299
+ * @return list<string>
300
+ */
301
+ function listBackupFiles(string $backupSessionDir): array
302
+ {
303
+ if (!is_dir($backupSessionDir)) {
304
+ return [];
305
+ }
306
+
307
+ /** @var list<string> $files */
308
+ $files = [];
309
+ $iterator = new RecursiveIteratorIterator(
310
+ new RecursiveDirectoryIterator($backupSessionDir, FilesystemIterator::SKIP_DOTS)
311
+ );
312
+
313
+ foreach ($iterator as $fileInfo) {
314
+ if (!$fileInfo->isFile()) {
315
+ continue;
316
+ }
317
+ $abs = $fileInfo->getPathname();
318
+ $rel = substr($abs, strlen($backupSessionDir) + 1);
319
+ $relNorm = str_replace('\\', '/', $rel);
320
+ if (in_array(basename($relNorm), [DEPLOY_META_FILE, 'MANIFEST.txt'], true)) {
321
+ continue;
322
+ }
323
+ $files[] = $relNorm;
324
+ }
325
+
326
+ sort($files);
327
+
328
+ return $files;
329
+ }
330
+
331
+ /**
332
+ * 列出所有版本备份
333
+ *
334
+ * @return list<array{dir: string, meta: array<string, string>, fileCount: int}>
335
+ */
336
+ function listVersionBackups(string $backendRoot): array
337
+ {
338
+ $backupRoot = resolveBackupRoot($backendRoot);
339
+ if (!is_dir($backupRoot)) {
340
+ return [];
341
+ }
342
+
343
+ /** @var list<array{dir: string, meta: array<string, string>, fileCount: int}> $items */
344
+ $items = [];
345
+ foreach (scandir($backupRoot) ?: [] as $name) {
346
+ if ($name === '.' || $name === '..') {
347
+ continue;
348
+ }
349
+ $dir = $backupRoot . '/' . $name;
350
+ if (!is_dir($dir)) {
351
+ continue;
352
+ }
353
+ $meta = readDeployMeta($dir);
354
+ $items[] = [
355
+ 'dir' => $dir,
356
+ 'meta' => $meta,
357
+ 'fileCount' => count(listBackupFiles($dir)),
358
+ ];
359
+ }
360
+
361
+ usort($items, static function (array $a, array $b): int {
362
+ $timeA = $a['meta']['backed_up_at'] ?? '';
363
+ $timeB = $b['meta']['backed_up_at'] ?? '';
364
+ return $timeA < $timeB ? 1 : -1;
365
+ });
366
+
367
+ return $items;
368
+ }
369
+
370
+ /**
371
+ * 解析回滚目标备份目录
372
+ */
373
+ function resolveRollbackBackupDir(string $backendRoot, ?string $targetVersion): string
374
+ {
375
+ $backupRoot = resolveBackupRoot($backendRoot);
376
+ $currentVersion = readDeployedVersion($backendRoot);
377
+
378
+ if ($targetVersion !== null && $targetVersion !== '') {
379
+ $targetLabel = sanitizeVersionLabel($targetVersion);
380
+ $candidate = $backupRoot . '/' . formatBackupDirName($targetLabel);
381
+ if (!is_dir($candidate)) {
382
+ throw new RuntimeException("未找到版本 {$targetLabel} 的备份目录: {$candidate}");
383
+ }
384
+ return $candidate;
385
+ }
386
+
387
+ if ($currentVersion === null) {
388
+ throw new RuntimeException('当前无 .deploy-version,请使用 --rollback=<版本> 指定目标');
389
+ }
390
+
391
+ foreach (listVersionBackups($backendRoot) as $item) {
392
+ $replacedBy = $item['meta']['replaced_by'] ?? '';
393
+ if ($replacedBy !== '' && sanitizeVersionLabel($replacedBy) === $currentVersion) {
394
+ return $item['dir'];
395
+ }
396
+ }
397
+
398
+ throw new RuntimeException("未找到可回滚到上一版本的备份(当前版本 {$currentVersion})");
399
+ }
400
+
401
+ /**
402
+ * 从版本备份恢复文件
403
+ *
404
+ * @return array{ok: int, fail: int, targetVersion: string}
405
+ */
406
+ function rollbackFromBackup(string $backendRoot, string $backupSessionDir): array
407
+ {
408
+ $meta = readDeployMeta($backupSessionDir);
409
+ $targetVersion = $meta['version'] ?? basename($backupSessionDir);
410
+ $targetVersion = sanitizeVersionLabel($targetVersion);
411
+
412
+ $files = listBackupFiles($backupSessionDir);
413
+ if ($files === []) {
414
+ throw new RuntimeException("备份目录无可用文件: {$backupSessionDir}");
415
+ }
416
+
417
+ $ok = 0;
418
+ $fail = 0;
419
+ foreach ($files as $rel) {
420
+ $src = $backupSessionDir . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
421
+ $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
422
+ try {
423
+ assertTargetWritable($dst, $rel);
424
+ ensureParentDir($dst);
425
+ if (!copy($src, $dst)) {
426
+ throw new RuntimeException('copy 失败');
427
+ }
428
+ echo "OK {$rel}\n";
429
+ $ok++;
430
+ } catch (Throwable $e) {
431
+ echo "FAIL {$rel} — {$e->getMessage()}\n";
432
+ $fail++;
433
+ }
434
+ }
435
+
436
+ if ($fail === 0) {
437
+ writeDeployedVersion($backendRoot, $targetVersion);
438
+ }
439
+
440
+ return ['ok' => $ok, 'fail' => $fail, 'targetVersion' => $targetVersion];
441
+ }
442
+
79
443
  /**
80
444
  * 优先从 MANIFEST.txt 读取文件列表,避免大 patch 全目录扫描
81
445
  *
@@ -545,6 +909,14 @@ function validateBackendRoot(string $backendRoot, array $patchFiles = []): array
545
909
 
546
910
  // --- main ---
547
911
 
912
+ $listBackups = in_array('--list-backups', $argv ?? [], true);
913
+ try {
914
+ $rollbackOption = resolveRollbackOption();
915
+ } catch (Throwable $e) {
916
+ fwrite(STDERR, $e->getMessage() . "\n");
917
+ exit(1);
918
+ }
919
+
548
920
  $backendRoot = resolveBackendRoot();
549
921
 
550
922
  if (!is_dir($backendRoot)) {
@@ -552,6 +924,51 @@ if (!is_dir($backendRoot)) {
552
924
  exit(1);
553
925
  }
554
926
 
927
+ if ($listBackups) {
928
+ $currentVersion = readDeployedVersion($backendRoot);
929
+ echo "BACKEND_ROOT: {$backendRoot}\n";
930
+ echo 'CURRENT_VERSION: ' . ($currentVersion ?? '(none)') . "\n";
931
+ echo "BACKUP_ROOT: " . resolveBackupRoot($backendRoot) . "\n\n";
932
+
933
+ $backups = listVersionBackups($backendRoot);
934
+ if ($backups === []) {
935
+ echo "暂无版本备份。\n";
936
+ exit(0);
937
+ }
938
+
939
+ foreach ($backups as $item) {
940
+ $version = $item['meta']['version'] ?? basename($item['dir']);
941
+ $replacedBy = $item['meta']['replaced_by'] ?? '-';
942
+ $backedUpAt = $item['meta']['backed_up_at'] ?? '-';
943
+ echo "- {$version} 文件:{$item['fileCount']} 升级至:{$replacedBy} 时间:{$backedUpAt}\n";
944
+ echo " 目录: {$item['dir']}\n";
945
+ }
946
+ exit(0);
947
+ }
948
+
949
+ if ($rollbackOption['enabled']) {
950
+ try {
951
+ $backupDir = resolveRollbackBackupDir($backendRoot, $rollbackOption['target']);
952
+ } catch (Throwable $e) {
953
+ fwrite(STDERR, $e->getMessage() . "\n");
954
+ exit(1);
955
+ }
956
+
957
+ echo "BACKEND_ROOT: {$backendRoot}\n";
958
+ echo "ROLLBACK_FROM_BACKUP: {$backupDir}\n";
959
+
960
+ $result = rollbackFromBackup($backendRoot, $backupDir);
961
+ if ($result['fail'] > 0) {
962
+ echo "\n回滚未完成: 成功 {$result['ok']},失败 {$result['fail']}\n";
963
+ exit(1);
964
+ }
965
+
966
+ clearRuntimeCache($backendRoot);
967
+ tryThinkClear($backendRoot);
968
+ echo "\n已回滚至版本 {$result['targetVersion']}(成功 {$result['ok']} 个文件)\n";
969
+ exit(0);
970
+ }
971
+
555
972
  $files = listPatchFiles();
556
973
  if ($files === []) {
557
974
  echo "patch 包内无待部署文件。\n";
@@ -574,6 +991,9 @@ if (!$rootCheck['valid']) {
574
991
  $dryRun = in_array('--check', $argv ?? [], true) || in_array('--dry-run', $argv ?? [], true);
575
992
  $noBackup = in_array('--no-backup', $argv ?? [], true);
576
993
  $backupEnabled = !$dryRun && !$noBackup;
994
+ $patchDeployVersion = resolvePatchDeployVersion();
995
+ $currentDeployedVersion = readDeployedVersion($backendRoot);
996
+ $versionBackupEnabled = $backupEnabled && $patchDeployVersion !== null;
577
997
 
578
998
  $runUser = function_exists('posix_getpwuid')
579
999
  ? (posix_getpwuid(posix_geteuid())['name'] ?? 'unknown')
@@ -592,8 +1012,13 @@ if ($dryRun) {
592
1012
  }
593
1013
  if ($noBackup) {
594
1014
  echo "BACKUP: disabled(--no-backup)\n";
1015
+ } elseif ($versionBackupEnabled) {
1016
+ $backupLabel = $currentDeployedVersion ?? 'pre-deploy';
1017
+ echo "BACKUP: version -> " . resolveBackupRoot($backendRoot) . '/' . formatBackupDirName($backupLabel) . "/\n";
1018
+ echo "PATCH_VERSION: {$patchDeployVersion}\n";
1019
+ echo 'CURRENT_VERSION: ' . ($currentDeployedVersion ?? '(none)') . "\n";
595
1020
  } elseif ($backupEnabled) {
596
- echo "BACKUP: enabled -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
1021
+ echo "BACKUP: timestamp -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
597
1022
  }
598
1023
 
599
1024
  try {
@@ -624,6 +1049,8 @@ $blocked = [];
624
1049
  $backedUp = 0;
625
1050
  /** @var string|null 本次部署备份会话目录 */
626
1051
  $backupSessionDir = null;
1052
+ /** @var list<string> 已备份文件列表(用于 DEPLOY-META) */
1053
+ $backedUpFiles = [];
627
1054
 
628
1055
  foreach ($files as $rel) {
629
1056
  $src = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
@@ -638,14 +1065,18 @@ foreach ($files as $rel) {
638
1065
  continue;
639
1066
  }
640
1067
 
641
- // 覆盖前先备份线上旧文件
1068
+ // 覆盖前先备份线上旧文件(有 patch 版本标识时用版本目录)
642
1069
  if ($backupEnabled && is_file($dst)) {
643
1070
  if ($backupSessionDir === null) {
644
- $backupSessionDir = createBackupSessionDir(resolveBackupRoot($backendRoot));
1071
+ $backupRoot = resolveBackupRoot($backendRoot);
1072
+ $backupSessionDir = $versionBackupEnabled
1073
+ ? createVersionBackupSessionDir($backupRoot, $currentDeployedVersion ?? 'pre-deploy')
1074
+ : createBackupSessionDir($backupRoot);
645
1075
  echo "BACKUP_DIR: {$backupSessionDir}\n";
646
1076
  }
647
1077
  if (backupExistingFile($dst, $rel, $backupSessionDir)) {
648
1078
  $backedUp++;
1079
+ $backedUpFiles[] = $rel;
649
1080
  }
650
1081
  }
651
1082
 
@@ -695,13 +1126,27 @@ if ($fail > 0) {
695
1126
  exit(1);
696
1127
  }
697
1128
 
1129
+ if ($backupSessionDir !== null && $backedUpFiles !== [] && $versionBackupEnabled) {
1130
+ $backupVersionLabel = $currentDeployedVersion ?? 'pre-deploy';
1131
+ writeDeployMeta($backupSessionDir, $backupVersionLabel, $patchDeployVersion, $backedUpFiles);
1132
+ }
1133
+
698
1134
  clearRuntimeCache($backendRoot);
699
1135
  tryThinkClear($backendRoot);
700
1136
 
1137
+ if ($patchDeployVersion !== null) {
1138
+ writeDeployedVersion($backendRoot, $patchDeployVersion);
1139
+ echo "\nDEPLOY_VERSION: {$patchDeployVersion}\n";
1140
+ }
1141
+
701
1142
  if ($backupSessionDir !== null) {
702
- $sampleRel = $files[0] ?? 'path/to/file.php';
1143
+ $sampleRel = $backedUpFiles[0] ?? ($files[0] ?? 'path/to/file.php');
703
1144
  echo "\n已备份 {$backedUp} 个旧文件至: {$backupSessionDir}\n";
704
- echo "回滚示例: cp -f {$backupSessionDir}/{$sampleRel} {$backendRoot}/{$sampleRel}\n";
1145
+ if ($versionBackupEnabled) {
1146
+ echo "回滚示例: php apply-update.php --rollback " . escapeshellarg($backendRoot) . "\n";
1147
+ } else {
1148
+ echo "回滚示例: cp -f {$backupSessionDir}/{$sampleRel} {$backendRoot}/{$sampleRel}\n";
1149
+ }
705
1150
  }
706
1151
 
707
1152
  $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
@@ -36,6 +36,8 @@ ${chalk.yellow('选项:')}
36
36
  --version=<版本号> 安装版本号(如 1.2.3,写入 VERSION.txt 与 versions.json)
37
37
  --only=<文件> 仅打包指定文件(逗号分隔,可重复;支持 @files.txt)
38
38
  --file-list=<文件> 文件列表(每行一个相对路径)
39
+ --no-archive 跳过本地版本归档(deploy/archive/)
40
+ --keep-versions=<N> 本地 archive 保留版本数(默认 10)
39
41
  -h, --help 显示帮助
40
42
 
41
43
  ${chalk.yellow('环境变量:')}
@@ -46,6 +48,8 @@ ${chalk.yellow('环境变量:')}
46
48
  PATCH_ZIP_PREFIX zip 前缀
47
49
  PATCH_VERSION 安装版本号
48
50
  PATCH_FILE_LIST 仅打包的文件列表路径
51
+ PATCH_NO_ARCHIVE true 时跳过本地 archive
52
+ PATCH_KEEP_VERSIONS 本地 archive 保留版本数(默认 10)
49
53
 
50
54
  ${chalk.yellow('版本号 + 单独文件部署:')}
51
55
  patch-build --vcs=svn --version=1.2.3
@@ -88,6 +92,8 @@ function parseArgs () {
88
92
  else if (arg.startsWith('--version=')) opts.version = arg.split('=')[1]
89
93
  else if (arg.startsWith('--only=')) opts.onlyFiles.push(...arg.split('=')[1].split(','))
90
94
  else if (arg.startsWith('--file-list=')) opts.fileList = arg.split('=')[1]
95
+ else if (arg === '--no-archive') opts.noArchive = true
96
+ else if (arg.startsWith('--keep-versions=')) opts.keepVersions = arg.split('=')[1]
91
97
  else console.warn(chalk.yellow(`未知参数: ${arg}`))
92
98
  }
93
99
 
@@ -115,6 +121,8 @@ async function main () {
115
121
  version: opts.version,
116
122
  onlyFiles: opts.onlyFiles,
117
123
  fileList: opts.fileList,
124
+ noArchive: opts.noArchive,
125
+ keepVersions: opts.keepVersions,
118
126
  pkgRoot: path.join(__dirname, '..')
119
127
  })
120
128
 
@@ -139,6 +147,10 @@ async function main () {
139
147
  console.log(chalk.green(` 变更文件: ${result.fileCount} 删除: ${result.deletedCount}`))
140
148
  if (result.patchDir) console.log(chalk.green(` patch 目录: ${result.patchDir}`))
141
149
  if (result.zipPath) console.log(chalk.green(` zip: ${result.zipPath} (${result.zipSize} bytes)`))
150
+ if (result.archiveDir) console.log(chalk.green(` 归档: ${result.archiveDir}`))
151
+ if (result.deployVersionLabel) {
152
+ console.log(chalk.gray(` 部署版本标识: ${result.deployVersionLabel}`))
153
+ }
142
154
  }
143
155
 
144
156
  if (result.warnings?.length) {
package/env.example CHANGED
@@ -33,6 +33,10 @@ PATCH_BACKEND=php
33
33
  # 跳过 PHP 项目结构校验(非标准目录时使用)
34
34
  # PATCH_SKIP_VALIDATION=false
35
35
 
36
+ # 本地版本归档(deploy/archive/,默认保留 10 个版本)
37
+ # PATCH_NO_ARCHIVE=false
38
+ # PATCH_KEEP_VERSIONS=10
39
+
36
40
  # ---------- 工具路径(可选)----------
37
41
  # SVN_EXE=C:/Program Files/TortoiseSVN/bin/svn.exe
38
42
  # GIT_EXE=C:/Program Files/Git/bin/git.exe
@@ -15,6 +15,7 @@ const { resolveSelectedFiles, filterFilesBySelection } = require('./file-filter'
15
15
  const { getSvnInfo, getSvnDiffSummary } = require('./svn')
16
16
  const { getGitInfo, getGitDiffSummary, resolveGitRef } = require('./git')
17
17
  const { createZipFromDirectory } = require('./zip')
18
+ const { buildDeployVersionLabel, archivePatchPackage } = require('./version-archive')
18
19
 
19
20
  /**
20
21
  * @typedef {object} BuildResult
@@ -23,6 +24,8 @@ const { createZipFromDirectory } = require('./zip')
23
24
  * @property {string} message
24
25
  * @property {string} [patchDir]
25
26
  * @property {string} [zipPath]
27
+ * @property {string} [archiveDir]
28
+ * @property {string} [deployVersionLabel]
26
29
  * @property {number} [fileCount]
27
30
  * @property {number} [deletedCount]
28
31
  * @property {string[]} [warnings]
@@ -129,7 +132,9 @@ async function buildPatch (config) {
129
132
  zipPrefix,
130
133
  version,
131
134
  onlyFiles,
132
- fileList
135
+ fileList,
136
+ noArchive,
137
+ keepVersions
133
138
  } = config
134
139
 
135
140
  const backendModule = getBackend(backend)
@@ -282,6 +287,7 @@ async function buildPatch (config) {
282
287
  const zipPath = path.join(outDir, zipName)
283
288
  const stagingDir = `${patchDir}.staging-${Date.now()}`
284
289
  const versionLabel = version ? sanitizeVersionLabel(version) : null
290
+ const deployVersionLabel = buildDeployVersionLabel(vcs, toLabel, versionLabel)
285
291
 
286
292
  await fse.emptyDir(stagingDir)
287
293
 
@@ -323,18 +329,17 @@ async function buildPatch (config) {
323
329
 
324
330
  fs.writeFileSync(path.join(stagingDir, 'MANIFEST.txt'), manifestLines.join('\n'), 'utf8')
325
331
 
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
- }
332
+ // 始终写入 VERSION.txt,供服务器按版本号备份(含 r467 等 revision 包)
333
+ fs.writeFileSync(
334
+ path.join(stagingDir, 'VERSION.txt'),
335
+ [
336
+ `version=${deployVersionLabel}`,
337
+ `vcs=${vcs}`,
338
+ vcs === 'svn' ? `to_revision=${toLabel}` : `to_commit=${toLabel}`,
339
+ `file_count=${deployFiles.length}`
340
+ ].join('\n'),
341
+ 'utf8'
342
+ )
338
343
 
339
344
  if (deployDeleted.length > 0) {
340
345
  fs.writeFileSync(
@@ -355,7 +360,7 @@ async function buildPatch (config) {
355
360
  zipSize = zipResult.size
356
361
  }
357
362
  } catch (error) {
358
- await fse.remove(stagingDir).catch(() => {})
363
+ await fse.remove(stagingDir).catch(() => { })
359
364
  throw error
360
365
  }
361
366
 
@@ -380,6 +385,22 @@ async function buildPatch (config) {
380
385
  })
381
386
  }
382
387
 
388
+ /** @type {string|undefined} */
389
+ let archiveDir
390
+ if (!noArchive) {
391
+ const archived = await archivePatchPackage({
392
+ deployDir,
393
+ archiveLabel: deployVersionLabel,
394
+ patchDir,
395
+ zipPath: noZip ? undefined : zipPath,
396
+ vcs,
397
+ fromLabel,
398
+ toLabel,
399
+ keepVersions: keepVersions || 10
400
+ })
401
+ archiveDir = archived.archiveDir
402
+ }
403
+
383
404
  return {
384
405
  success: true,
385
406
  skipped: false,
@@ -394,6 +415,8 @@ async function buildPatch (config) {
394
415
  fromLabel,
395
416
  toLabel,
396
417
  version: versionLabel || undefined,
418
+ deployVersionLabel,
419
+ archiveDir,
397
420
  markDeployedHint: markDeployed
398
421
  ? undefined
399
422
  : `上线成功后执行:patch-build --vcs=${vcs} --mark-deployed --from=${toLabel} --to=${toLabel}`
package/lib/config.js CHANGED
@@ -68,6 +68,8 @@ function detectVcs (sourceDir) {
68
68
  * @property {string|null} version 安装版本号(如 1.2.3)
69
69
  * @property {string[]} onlyFiles 仅打包/部署指定文件
70
70
  * @property {string|null} fileList 文件列表路径(每行一个相对路径)
71
+ * @property {boolean} noArchive 跳过本地版本归档
72
+ * @property {number} keepVersions 本地 archive 保留版本数(默认 10)
71
73
  */
72
74
 
73
75
  /**
@@ -112,10 +114,24 @@ function resolveConfig (input = {}) {
112
114
  zipPrefix: input.zipPrefix || process.env.PATCH_ZIP_PREFIX || backend.defaultZipPrefix,
113
115
  version: input.version || process.env.PATCH_VERSION || null,
114
116
  onlyFiles: input.onlyFiles || [],
115
- fileList: input.fileList || process.env.PATCH_FILE_LIST || null
117
+ fileList: input.fileList || process.env.PATCH_FILE_LIST || null,
118
+ noArchive: Boolean(input.noArchive || process.env.PATCH_NO_ARCHIVE === 'true'),
119
+ keepVersions: parseKeepVersions(input.keepVersions ?? process.env.PATCH_KEEP_VERSIONS)
116
120
  }
117
121
  }
118
122
 
123
+ /**
124
+ * @param {unknown} value
125
+ * @returns {number}
126
+ */
127
+ function parseKeepVersions (value) {
128
+ const n = parseInt(String(value ?? '10'), 10)
129
+ if (!Number.isFinite(n) || n < 1) {
130
+ return 10
131
+ }
132
+ return n
133
+ }
134
+
119
135
  /**
120
136
  * 初始化 PHP 后端 deploy 目录结构
121
137
  * @param {string} deployDir
@@ -162,5 +178,6 @@ module.exports = {
162
178
  detectVcs,
163
179
  resolveConfig,
164
180
  initDeployDir,
165
- isSvnWorkingCopy
181
+ isSvnWorkingCopy,
182
+ parseKeepVersions
166
183
  }
package/lib/index.js CHANGED
@@ -14,6 +14,12 @@ const { resolveSelectedFiles, filterFilesBySelection } = require('./file-filter'
14
14
  const svn = require('./svn')
15
15
  const git = require('./git')
16
16
  const { createZipFromDirectory } = require('./zip')
17
+ const {
18
+ buildDeployVersionLabel,
19
+ archivePatchPackage,
20
+ readArchiveIndex,
21
+ getArchiveRoot
22
+ } = require('./version-archive')
17
23
 
18
24
  module.exports = {
19
25
  buildPatch,
@@ -33,6 +39,10 @@ module.exports = {
33
39
  getBackend,
34
40
  BACKENDS,
35
41
  createZipFromDirectory,
42
+ buildDeployVersionLabel,
43
+ archivePatchPackage,
44
+ readArchiveIndex,
45
+ getArchiveRoot,
36
46
  svn,
37
47
  git
38
48
  }
@@ -0,0 +1,142 @@
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
+ * @returns {{ versions: object[] }}
42
+ */
43
+ function readArchiveIndex (deployDir) {
44
+ const indexPath = path.join(getArchiveRoot(deployDir), ARCHIVE_INDEX)
45
+ if (!fs.existsSync(indexPath)) {
46
+ return { versions: [] }
47
+ }
48
+
49
+ try {
50
+ const data = JSON.parse(fs.readFileSync(indexPath, 'utf8'))
51
+ if (Array.isArray(data.versions)) {
52
+ return data
53
+ }
54
+ } catch (error) {
55
+ console.warn(`[vcs-patch-deploy] ${ARCHIVE_INDEX} 解析失败: ${error.message}`)
56
+ }
57
+
58
+ return { versions: [] }
59
+ }
60
+
61
+ /**
62
+ * 归档 patch 目录与 zip,并清理超出保留数量的旧版本
63
+ * @param {object} options
64
+ * @param {string} options.deployDir
65
+ * @param {string} options.archiveLabel 如 1.2.3 / r467 / abc123def456
66
+ * @param {string} options.patchDir
67
+ * @param {string} [options.zipPath]
68
+ * @param {'svn'|'git'} options.vcs
69
+ * @param {string} options.fromLabel
70
+ * @param {string} options.toLabel
71
+ * @param {number} [options.keepVersions=10]
72
+ * @returns {Promise<{ archiveDir: string, zipArchivePath?: string }>}
73
+ */
74
+ async function archivePatchPackage ({
75
+ deployDir,
76
+ archiveLabel,
77
+ patchDir,
78
+ zipPath,
79
+ vcs,
80
+ fromLabel,
81
+ toLabel,
82
+ keepVersions = 10
83
+ }) {
84
+ const archiveRoot = getArchiveRoot(deployDir)
85
+ const safeLabel = sanitizeVersionLabel(archiveLabel)
86
+ const archiveDir = path.join(archiveRoot, safeLabel)
87
+
88
+ await fse.ensureDir(archiveRoot)
89
+ await fse.emptyDir(archiveDir)
90
+ await fse.copy(patchDir, archiveDir)
91
+
92
+ /** @type {string|undefined} */
93
+ let zipArchivePath
94
+ if (zipPath && fs.existsSync(zipPath)) {
95
+ zipArchivePath = path.join(archiveRoot, `${safeLabel}.zip`)
96
+ await fse.copy(zipPath, zipArchivePath)
97
+ }
98
+
99
+ const index = readArchiveIndex(deployDir)
100
+ const createdAt = new Date().toISOString()
101
+ const record = {
102
+ label: safeLabel,
103
+ vcs,
104
+ fromLabel,
105
+ toLabel,
106
+ archiveDir,
107
+ zipPath: zipArchivePath,
108
+ createdAt
109
+ }
110
+
111
+ const dupIdx = index.versions.findIndex(v => v.label === safeLabel)
112
+ if (dupIdx >= 0) {
113
+ index.versions[dupIdx] = record
114
+ } else {
115
+ index.versions.push(record)
116
+ }
117
+
118
+ index.versions.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))
119
+
120
+ // 保留最近 keepVersions 个版本,删除更早的归档
121
+ const removed = index.versions.splice(keepVersions)
122
+ writeJsonAtomic(path.join(archiveRoot, ARCHIVE_INDEX), index)
123
+
124
+ for (const old of removed) {
125
+ if (old.archiveDir && fs.existsSync(old.archiveDir)) {
126
+ await fse.remove(old.archiveDir).catch(() => {})
127
+ }
128
+ if (old.zipPath && fs.existsSync(old.zipPath)) {
129
+ await fse.remove(old.zipPath).catch(() => {})
130
+ }
131
+ }
132
+
133
+ return { archiveDir, zipArchivePath }
134
+ }
135
+
136
+ module.exports = {
137
+ ARCHIVE_DIR,
138
+ buildDeployVersionLabel,
139
+ getArchiveRoot,
140
+ readArchiveIndex,
141
+ archivePatchPackage
142
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vcs-patch-deploy",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "PHP 后端(ThinkPHP)增量部署包生成工具 — 支持 SVN revision 与 Git commit 差异对比,打 zip 并附带 apply-update.php,供堡垒机/Web 终端上线",
5
5
  "main": "lib/index.js",
6
6
  "bin": {