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.
@@ -1,79 +1,996 @@
1
1
  <?php
2
2
  declare(strict_types=1);
3
3
 
4
+ // PHP 7.4 兼容:str_starts_with / str_ends_with 是 PHP 8.0 才内置的函数
5
+ if (!function_exists('str_starts_with')) {
6
+ function str_starts_with(string $haystack, string $needle): bool
7
+ {
8
+ return $needle === '' || strncmp($haystack, $needle, strlen($needle)) === 0;
9
+ }
10
+ }
11
+ if (!function_exists('str_ends_with')) {
12
+ function str_ends_with(string $haystack, string $needle): bool
13
+ {
14
+ return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
15
+ }
16
+ }
17
+
18
+ /**
19
+ * 堡垒机增量部署:将 patch 包内文件覆盖到线上 Backend 根目录,并清理 ThinkPHP 缓存。
20
+ *
21
+ * 用法(Linux Web 终端,在解压后的 patch 目录内):
22
+ * php apply-update.php /path/to/production-api
23
+ * 或设置环境变量:
24
+ * PATCH_BACKEND_ROOT=/path/to/production-api php apply-update.php
25
+ *
26
+ * 安全:不会覆盖 .env(含 .env.*);不会自动删除 MANIFEST-deleted.txt 中列出的文件;
27
+ * 拒绝包内绝对路径、../ 逃逸路径与符号链接。
28
+ * 保护:包内 PROTECT.txt 列出的文件,线上已存在时跳过覆盖(不存在时仍写入)。
29
+ * 备份:覆盖前将线上已有文件复制到版本备份目录(默认 Backend/.deploy-backups/v1.2.2/ 或 r467/)。
30
+ * 默认保留最近 10 个备份会话(--keep-backups=N / PATCH_KEEP_BACKUPS 调整)。
31
+ * 回滚:php apply-update.php --rollback[=版本] <Backend根目录>
32
+ * 回滚会恢复被覆盖的旧文件(含权限),并删除本次部署新增且未被修改过的文件。
33
+ * 列表:php apply-update.php --list-backups <Backend根目录>
34
+ *
35
+ * 要求 PHP >= 7.4。
36
+ */
37
+
38
+ /** patch 包根目录(本脚本所在目录) */
39
+ const PATCH_ROOT = __DIR__;
40
+
41
+ /** 默认备份目录名(位于 Backend 根下,可通过 PATCH_BACKUP_DIR 覆盖父路径) */
42
+ const BACKUP_DIR_BASENAME = '.deploy-backups';
43
+
44
+ /** 当前线上部署版本记录文件(位于 Backend 根下) */
45
+ const DEPLOY_VERSION_FILE = '.deploy-version';
46
+
47
+ /** 版本备份元数据文件名 */
48
+ const DEPLOY_META_FILE = 'DEPLOY-META.txt';
49
+
50
+ /** 备份会话标记文件(用于清理失败/无元数据的旧会话) */
51
+ const BACKUP_SESSION_MARKER = '.deploy-backup-session';
52
+
53
+ /** 部署时跳过的文件名(相对路径 basename 匹配或完整相对路径) */
54
+ const SKIP_FILES = [
55
+ 'apply-update.php',
56
+ 'MANIFEST.txt',
57
+ 'MANIFEST-deleted.txt',
58
+ 'VERSION.txt',
59
+ 'PROTECT.txt',
60
+ 'MODES.txt',
61
+ ];
62
+
63
+ /** 永不覆盖的相对路径(保护生产配置与运行时数据) */
64
+ const PROTECTED_RELATIVE = [
65
+ '.env',
66
+ '.env.local',
67
+ '.env.production',
68
+ ];
69
+
70
+ /** 本地产物路径前缀(误打进 zip 时跳过,避免污染 Backend) */
71
+ const SKIP_PATH_PREFIXES = [
72
+ 'deploy/out/',
73
+ 'out/_verify/',
74
+ 'out/patch-',
75
+ ];
76
+
77
+ /**
78
+ * 解析线上 Backend 根目录(含 app、config、public、vendor 的 trunk 根)。
79
+ */
80
+ function resolveBackendRoot(): string
81
+ {
82
+ foreach (['PATCH_BACKEND_ROOT'] as $envKey) {
83
+ $fromEnv = getenv($envKey);
84
+ if (is_string($fromEnv) && $fromEnv !== '') {
85
+ return rtrim($fromEnv, "/\\");
86
+ }
87
+ }
88
+
89
+ global $argv;
90
+ $flags = ['--check', '--dry-run', '--no-backup', '--list-backups', '--rollback'];
91
+ foreach ($argv as $i => $arg) {
92
+ if ($i === 0) {
93
+ continue;
94
+ }
95
+ if (in_array($arg, $flags, true)) {
96
+ continue;
97
+ }
98
+ if (str_starts_with($arg, '--files=') || str_starts_with($arg, '--file-list=')) {
99
+ continue;
100
+ }
101
+ if (str_starts_with($arg, '--rollback=')) {
102
+ continue;
103
+ }
104
+ if (str_starts_with($arg, '--keep-backups=')) {
105
+ continue;
106
+ }
107
+ if ($arg !== '' && !str_starts_with($arg, '-')) {
108
+ return rtrim($arg, "/\\");
109
+ }
110
+ }
111
+
112
+ fwrite(STDERR, "用法: php apply-update.php [--check] [--rollback[=版本]] [--list-backups] [--keep-backups=N] [--files=<路径>] <Backend根目录>\n");
113
+ fwrite(STDERR, "示例: php apply-update.php /path/to/production-api\n");
114
+ fwrite(STDERR, " php apply-update.php --rollback /path/to/production-api\n");
115
+ fwrite(STDERR, " php apply-update.php --rollback=1.2.2 /path/to/production-api\n");
116
+ fwrite(STDERR, " php apply-update.php --list-backups /path/to/production-api\n");
117
+ exit(1);
118
+ }
119
+
120
+ /**
121
+ * 解析 --rollback[=版本] 参数
122
+ *
123
+ * @return array{enabled: bool, target: string|null}
124
+ */
125
+ function resolveRollbackOption(): array
126
+ {
127
+ global $argv;
128
+
129
+ foreach ($argv ?? [] as $arg) {
130
+ if ($arg === '--rollback') {
131
+ return ['enabled' => true, 'target' => null];
132
+ }
133
+ if (str_starts_with($arg, '--rollback=')) {
134
+ $target = trim(substr($arg, 11));
135
+ if ($target === '') {
136
+ throw new RuntimeException('--rollback= 需要指定版本号');
137
+ }
138
+ return ['enabled' => true, 'target' => $target];
139
+ }
140
+ }
141
+
142
+ return ['enabled' => false, 'target' => null];
143
+ }
144
+
145
+ /**
146
+ * 清洗版本标识(与 Node sanitizeVersionLabel 对齐)
147
+ */
148
+ function sanitizeVersionLabel(string $version): string
149
+ {
150
+ $label = trim($version);
151
+ $label = preg_replace('/^v/i', '', $label) ?? $label;
152
+ $label = preg_replace('/[^a-zA-Z0-9._-]/', '_', $label) ?? $label;
153
+
154
+ return $label;
155
+ }
156
+
157
+ /**
158
+ * 判断包内相对路径是否安全(拒绝绝对路径、盘符、.. 逃逸与空字节)
159
+ */
160
+ function isSafeRelativePath(string $rel): bool
161
+ {
162
+ if ($rel === '' || strpos($rel, "\0") !== false) {
163
+ return false;
164
+ }
165
+
166
+ $normalized = str_replace('\\', '/', $rel);
167
+ if (str_starts_with($normalized, '/') || preg_match('#^[A-Za-z]:/#', $normalized) === 1) {
168
+ return false;
169
+ }
170
+
171
+ foreach (explode('/', $normalized) as $segment) {
172
+ if ($segment === '..') {
173
+ return false;
174
+ }
175
+ }
176
+
177
+ return true;
178
+ }
179
+
180
+ /**
181
+ * 永不覆盖的生产配置(根目录与任意目录下的 .env / .env.*)
182
+ */
183
+ function isProtectedRelativePath(string $rel): bool
184
+ {
185
+ $normalized = str_replace('\\', '/', $rel);
186
+ if (in_array($normalized, PROTECTED_RELATIVE, true)) {
187
+ return true;
188
+ }
189
+
190
+ $base = basename($normalized);
191
+
192
+ return $base === '.env' || str_starts_with($base, '.env.');
193
+ }
194
+
195
+ /**
196
+ * 读取包内 PROTECT.txt(每行一个相对路径,# 为注释)
197
+ *
198
+ * 受保护语义:线上已存在则跳过覆盖;线上不存在时仍写入(便于首次部署)。
199
+ *
200
+ * @return array<string, bool>
201
+ */
202
+ function readProtectList(): array
203
+ {
204
+ static $cache = null;
205
+ if (is_array($cache)) {
206
+ return $cache;
207
+ }
208
+
209
+ $cache = [];
210
+ $path = PATCH_ROOT . '/PROTECT.txt';
211
+ if (!is_file($path)) {
212
+ return $cache;
213
+ }
214
+
215
+ $lines = file($path, FILE_IGNORE_NEW_LINES);
216
+ if ($lines === false) {
217
+ return $cache;
218
+ }
219
+
220
+ foreach ($lines as $line) {
221
+ $trimmed = trim($line);
222
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
223
+ continue;
224
+ }
225
+ $rel = str_replace('\\', '/', $trimmed);
226
+ if (!isSafeRelativePath($rel)) {
227
+ fwrite(STDERR, "忽略 PROTECT.txt 中的不安全路径: {$rel}\n");
228
+ continue;
229
+ }
230
+ $cache[$rel] = true;
231
+ }
232
+
233
+ return $cache;
234
+ }
235
+
236
+ /**
237
+ * 是否在包内保护清单中
238
+ */
239
+ function isProtectListed(string $rel): bool
240
+ {
241
+ $list = readProtectList();
242
+
243
+ return isset($list[str_replace('\\', '/', $rel)]);
244
+ }
245
+
246
+ /**
247
+ * exec 是否可用(disable_functions 可能在堡垒机环境禁用)
248
+ */
249
+ function isExecAvailable(): bool
250
+ {
251
+ if (!function_exists('exec')) {
252
+ return false;
253
+ }
254
+
255
+ $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
256
+
257
+ return !in_array('exec', $disabled, true);
258
+ }
259
+
260
+ /**
261
+ * 读取包内 MODES.txt(可执行文件清单)
262
+ *
263
+ * @return array<string, int> 相对路径 -> 权限(如 0755)
264
+ */
265
+ function readModesList(): array
266
+ {
267
+ static $cache = null;
268
+ if (is_array($cache)) {
269
+ return $cache;
270
+ }
271
+
272
+ $cache = [];
273
+ $path = PATCH_ROOT . '/MODES.txt';
274
+ if (!is_file($path)) {
275
+ return $cache;
276
+ }
277
+
278
+ $lines = file($path, FILE_IGNORE_NEW_LINES);
279
+ if ($lines === false) {
280
+ return $cache;
281
+ }
282
+
283
+ foreach ($lines as $line) {
284
+ $trimmed = trim($line);
285
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
286
+ continue;
287
+ }
288
+ if (preg_match('/^([0-7]{3,4})\s+(.+)$/', $trimmed, $m) !== 1) {
289
+ continue;
290
+ }
291
+ $rel = str_replace('\\', '/', trim($m[2]));
292
+ if (!isSafeRelativePath($rel)) {
293
+ continue;
294
+ }
295
+ $cache[$rel] = octdec($m[1]);
296
+ }
297
+
298
+ return $cache;
299
+ }
300
+
301
+ /**
302
+ * 规范化路径用于比较(Windows 不区分大小写)
303
+ */
304
+ function normalizeComparablePath(string $path): string
305
+ {
306
+ $norm = str_replace('\\', '/', rtrim($path, "/\\"));
307
+ if (DIRECTORY_SEPARATOR === '\\') {
308
+ $norm = strtolower($norm);
309
+ }
310
+
311
+ return $norm;
312
+ }
313
+
314
+ /**
315
+ * 判断路径是否位于某个目录之下
316
+ */
317
+ function isPathInside(string $child, string $parent): bool
318
+ {
319
+ $c = normalizeComparablePath($child);
320
+ $p = normalizeComparablePath($parent);
321
+
322
+ return $c === $p || str_starts_with($c . '/', $p . '/');
323
+ }
324
+
325
+ /**
326
+ * 覆盖前校验目标路径:
327
+ * - 目标本身不能是符号链接(避免写到链接指向的任意文件)
328
+ * - 最近的已存在父目录 realpath 必须仍在 Backend 根内(避免父目录软链逃逸)
329
+ */
330
+ function assertTargetInsideBackend(string $backendRoot, string $dst, string $rel): void
331
+ {
332
+ if (is_link($dst)) {
333
+ throw new RuntimeException('目标是符号链接(拒绝覆盖)');
334
+ }
335
+
336
+ $rootReal = realpath($backendRoot);
337
+ if ($rootReal === false) {
338
+ return;
339
+ }
340
+
341
+ $probe = dirname($dst);
342
+ while (!is_dir($probe) && dirname($probe) !== $probe) {
343
+ $probe = dirname($probe);
344
+ }
345
+
346
+ $probeReal = realpath($probe);
347
+ if ($probeReal === false) {
348
+ throw new RuntimeException('无法解析目标父目录');
349
+ }
350
+
351
+ if (!isPathInside($probeReal, $rootReal)) {
352
+ throw new RuntimeException("目标路径越出 Backend 根目录(疑似符号链接): {$rel}");
353
+ }
354
+ }
355
+
356
+ /**
357
+ * 备份会话保留数量(--keep-backups=N / PATCH_KEEP_BACKUPS,默认 10)
358
+ */
359
+ function resolveKeepBackups(): int
360
+ {
361
+ global $argv;
362
+
363
+ foreach ($argv ?? [] as $arg) {
364
+ if (str_starts_with($arg, '--keep-backups=')) {
365
+ $n = (int) substr($arg, strlen('--keep-backups='));
366
+ return $n > 0 ? $n : 10;
367
+ }
368
+ }
369
+
370
+ $fromEnv = getenv('PATCH_KEEP_BACKUPS');
371
+ if (is_string($fromEnv) && preg_match('/^\d+$/', $fromEnv) === 1) {
372
+ $n = (int) $fromEnv;
373
+ return $n > 0 ? $n : 10;
374
+ }
375
+
376
+ return 10;
377
+ }
378
+
379
+ /**
380
+ * 递归删除目录(仅用于清理旧备份会话)
381
+ */
382
+ function removeDirectoryTree(string $dir): bool
383
+ {
384
+ if (!is_dir($dir)) {
385
+ return true;
386
+ }
387
+
388
+ $iterator = new RecursiveIteratorIterator(
389
+ new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
390
+ RecursiveIteratorIterator::CHILD_FIRST
391
+ );
392
+
393
+ foreach ($iterator as $item) {
394
+ $path = $item->getPathname();
395
+ if ($item->isDir() && !$item->isLink()) {
396
+ @rmdir($path);
397
+ } else {
398
+ @unlink($path);
399
+ }
400
+ }
401
+
402
+ return @rmdir($dir);
403
+ }
404
+
405
+ /**
406
+ * 清理超出保留数量的备份会话(含 DEPLOY-META.txt 或本工具写入的会话标记)
407
+ *
408
+ * @param string|null $excludeDir 当前部署刚创建的会话(始终保留)
409
+ * @return list<string> 被删除的会话名
410
+ */
411
+ function pruneBackupSessions(string $backendRoot, int $keep, ?string $excludeDir = null): array
412
+ {
413
+ $backupRoot = resolveBackupRoot($backendRoot);
414
+ if (!is_dir($backupRoot)) {
415
+ return [];
416
+ }
417
+
418
+ /** @var list<array{dir: string, mtime: int}> $sessions */
419
+ $sessions = [];
420
+ /** @var list<array{dir: string, mtime: int}> $incomplete */
421
+ $incomplete = [];
422
+ foreach (scandir($backupRoot) ?: [] as $name) {
423
+ if ($name === '.' || $name === '..') {
424
+ continue;
425
+ }
426
+ $dir = $backupRoot . '/' . $name;
427
+ if (!is_dir($dir)) {
428
+ continue;
429
+ }
430
+ if ($excludeDir !== null && normalizeComparablePath($dir) === normalizeComparablePath($excludeDir)) {
431
+ continue;
432
+ }
433
+
434
+ $item = ['dir' => $dir, 'mtime' => (int) @filemtime($dir)];
435
+ if (is_file($dir . '/' . DEPLOY_META_FILE)) {
436
+ $sessions[] = $item;
437
+ } elseif (is_file($dir . '/' . BACKUP_SESSION_MARKER)) {
438
+ // 中断/旧包的会话:没有元数据,不计入保留数量,单独按时间清理
439
+ $incomplete[] = $item;
440
+ }
441
+ }
442
+
443
+ usort($sessions, static function (array $a, array $b): int {
444
+ $timeA = readDeployMeta($a['dir'])['backed_up_at'] ?? '';
445
+ $timeB = readDeployMeta($b['dir'])['backed_up_at'] ?? '';
446
+ if ($timeA !== $timeB) {
447
+ return $timeA < $timeB ? 1 : -1;
448
+ }
449
+ if ($a['mtime'] !== $b['mtime']) {
450
+ return $b['mtime'] <=> $a['mtime'];
451
+ }
452
+ return strcmp(basename($b['dir']), basename($a['dir']));
453
+ });
454
+
455
+ // 保留数量包含当前会话
456
+ $keepOthers = max(0, max(1, $keep) - ($excludeDir !== null ? 1 : 0));
457
+ /** @var list<string> $removed */
458
+ $removed = [];
459
+ foreach (array_slice($sessions, $keepOthers) as $item) {
460
+ if (removeDirectoryTree($item['dir'])) {
461
+ $removed[] = basename($item['dir']);
462
+ }
463
+ }
464
+
465
+ // 中断会话最多保留 5 个,且只保留最近 24 小时
466
+ $cutoff = time() - 86400;
467
+ usort($incomplete, static function (array $a, array $b): int {
468
+ return $b['mtime'] <=> $a['mtime'];
469
+ });
470
+ foreach ($incomplete as $index => $item) {
471
+ if ($index < 5 && $item['mtime'] >= $cutoff) {
472
+ continue;
473
+ }
474
+ if (removeDirectoryTree($item['dir'])) {
475
+ $removed[] = basename($item['dir']);
476
+ }
477
+ }
478
+
479
+ return $removed;
480
+ }
481
+
482
+ /**
483
+ * 备份目录位于站点根内时,尽量阻止 Web 直接访问(Apache;nginx 需在配置中 deny)
484
+ */
485
+ function protectBackupDir(string $backupRoot): void
486
+ {
487
+ if (!is_dir($backupRoot) && !mkdir($backupRoot, 0755, true) && !is_dir($backupRoot)) {
488
+ return;
489
+ }
490
+
491
+ $htaccess = $backupRoot . '/.htaccess';
492
+ if (!is_file($htaccess)) {
493
+ @file_put_contents(
494
+ $htaccess,
495
+ "# 备份包含历史源码,禁止 Web 访问\n<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n Deny from all\n</IfModule>\n"
496
+ );
497
+ }
498
+
499
+ $index = $backupRoot . '/index.html';
500
+ if (!is_file($index)) {
501
+ @file_put_contents($index, "Forbidden\n");
502
+ }
503
+ }
504
+
505
+ /**
506
+ * 读取 key=value 多行元数据文件(忽略 # 注释行)
507
+ *
508
+ * @return array<string, string>
509
+ */
510
+ function readKeyValueFile(string $filePath): array
511
+ {
512
+ if (!is_file($filePath)) {
513
+ return [];
514
+ }
515
+
516
+ $lines = file($filePath, FILE_IGNORE_NEW_LINES);
517
+ if ($lines === false) {
518
+ return [];
519
+ }
520
+
521
+ /** @var array<string, string> $meta */
522
+ $meta = [];
523
+ foreach ($lines as $line) {
524
+ $trimmed = trim($line);
525
+ if ($trimmed === '' || str_starts_with($trimmed, '#')) {
526
+ continue;
527
+ }
528
+ $pos = strpos($trimmed, '=');
529
+ if ($pos === false) {
530
+ continue;
531
+ }
532
+ $key = trim(substr($trimmed, 0, $pos));
533
+ $value = trim(substr($trimmed, $pos + 1));
534
+ if ($key !== '') {
535
+ $meta[$key] = $value;
536
+ }
537
+ }
538
+
539
+ return $meta;
540
+ }
541
+
542
+ /**
543
+ * 从 patch 包解析本次部署版本(VERSION.txt 优先,兼容 MANIFEST revision 包)
544
+ */
545
+ function resolvePatchDeployVersion(): ?string
546
+ {
547
+ $versionMeta = readKeyValueFile(PATCH_ROOT . '/VERSION.txt');
548
+ if (isset($versionMeta['version']) && $versionMeta['version'] !== '') {
549
+ return sanitizeVersionLabel($versionMeta['version']);
550
+ }
551
+
552
+ $manifestMeta = readKeyValueFile(PATCH_ROOT . '/MANIFEST.txt');
553
+ if (isset($manifestMeta['version']) && $manifestMeta['version'] !== '') {
554
+ return sanitizeVersionLabel($manifestMeta['version']);
555
+ }
556
+ if (($manifestMeta['vcs'] ?? '') === 'svn' && isset($manifestMeta['to_revision']) && $manifestMeta['to_revision'] !== '') {
557
+ return 'r' . $manifestMeta['to_revision'];
558
+ }
559
+ if (isset($manifestMeta['to_commit']) && $manifestMeta['to_commit'] !== '') {
560
+ return substr($manifestMeta['to_commit'], 0, 12);
561
+ }
562
+
563
+ return null;
564
+ }
565
+
566
+ /**
567
+ * 备份目录名:v1.2.3 / r467 / pre-deploy
568
+ */
569
+ function formatBackupDirName(string $versionLabel): string
570
+ {
571
+ $label = sanitizeVersionLabel($versionLabel);
572
+ if ($label === 'pre-deploy') {
573
+ return 'pre-deploy';
574
+ }
575
+ if (preg_match('/^r\d+$/i', $label) === 1) {
576
+ return strtolower($label);
577
+ }
578
+ if (preg_match('/^\d/', $label) === 1) {
579
+ return 'v' . $label;
580
+ }
581
+
582
+ return $label;
583
+ }
584
+
585
+ /**
586
+ * 读取当前线上部署版本
587
+ */
588
+ function readDeployedVersion(string $backendRoot): ?string
589
+ {
590
+ $path = $backendRoot . '/' . DEPLOY_VERSION_FILE;
591
+ if (!is_file($path)) {
592
+ return null;
593
+ }
594
+
595
+ $value = trim((string) file_get_contents($path));
596
+ if ($value === '') {
597
+ return null;
598
+ }
599
+
600
+ return sanitizeVersionLabel($value);
601
+ }
602
+
603
+ /**
604
+ * 写入当前线上部署版本
605
+ */
606
+ function writeDeployedVersion(string $backendRoot, string $versionLabel): void
607
+ {
608
+ $path = $backendRoot . '/' . DEPLOY_VERSION_FILE;
609
+ file_put_contents($path, sanitizeVersionLabel($versionLabel) . "\n");
610
+ }
611
+
612
+ /**
613
+ * 创建版本备份会话目录(无版本标识时降级为时间戳目录)
614
+ */
615
+ function createVersionBackupSessionDir(string $backupRoot, ?string $currentVersionLabel): string
616
+ {
617
+ if ($currentVersionLabel === null || $currentVersionLabel === '') {
618
+ return createBackupSessionDir($backupRoot);
619
+ }
620
+
621
+ $sessionDir = $backupRoot . '/' . formatBackupDirName($currentVersionLabel);
622
+ if (is_dir($sessionDir)) {
623
+ // 同版本重复部署:追加时间戳子目录,避免覆盖历史备份
624
+ $sessionDir .= '_' . date('Y-m-d_His');
625
+ }
626
+ if (!is_dir($sessionDir) && !mkdir($sessionDir, 0755, true) && !is_dir($sessionDir)) {
627
+ throw new RuntimeException("无法创建版本备份目录: {$sessionDir}");
628
+ }
629
+
630
+ markBackupSession($sessionDir);
631
+
632
+ return $sessionDir;
633
+ }
634
+
635
+ /**
636
+ * 写入版本备份元数据
637
+ *
638
+ * @param list<string> $backedUpFiles 本次被覆盖的旧文件(已备份到本目录)
639
+ * @param list<array{hash: string, rel: string}> $createdFiles 本次新增的文件(回滚时删除)
640
+ * @param array<string, int> $modes 被覆盖文件的原始权限(回滚时恢复)
641
+ * @param bool $partial 是否来自部分部署(子集包)
642
+ */
643
+ function writeDeployMeta(
644
+ string $backupSessionDir,
645
+ string $versionLabel,
646
+ ?string $replacedBy,
647
+ array $backedUpFiles,
648
+ array $createdFiles = [],
649
+ array $modes = [],
650
+ bool $partial = false
651
+ ): void {
652
+ $lines = [
653
+ 'version=' . sanitizeVersionLabel($versionLabel),
654
+ 'backup_label=' . basename($backupSessionDir),
655
+ 'backed_up_at=' . date('Y-m-d H:i:s'),
656
+ 'file_count=' . count($backedUpFiles),
657
+ ];
658
+ if ($replacedBy !== null && $replacedBy !== '') {
659
+ $lines[] = 'replaced_by=' . sanitizeVersionLabel($replacedBy);
660
+ }
661
+ if ($partial) {
662
+ $lines[] = 'partial=1';
663
+ }
664
+ $lines[] = '';
665
+ $lines[] = '# files';
666
+ foreach ($backedUpFiles as $rel) {
667
+ $lines[] = $rel;
668
+ }
669
+
670
+ if ($modes !== []) {
671
+ $lines[] = '';
672
+ $lines[] = '# modes';
673
+ foreach ($modes as $rel => $mode) {
674
+ $lines[] = sprintf('%04o %s', $mode, $rel);
675
+ }
676
+ }
677
+
678
+ if ($createdFiles !== []) {
679
+ $lines[] = '';
680
+ $lines[] = '# created';
681
+ foreach ($createdFiles as $item) {
682
+ $lines[] = $item['hash'] . ' ' . $item['rel'];
683
+ }
684
+ }
685
+
686
+ file_put_contents($backupSessionDir . '/' . DEPLOY_META_FILE, implode("\n", $lines) . "\n");
687
+ }
688
+
4
689
  /**
5
- * 堡垒机增量部署:将 patch 包内文件覆盖到线上 Backend 根目录,并清理 ThinkPHP 缓存。
690
+ * 读取 DEPLOY-META 中的 # modes 段(回滚恢复权限)
6
691
  *
7
- * 用法(Linux Web 终端,在解压后的 patch 目录内):
8
- * php apply-update.php /path/to/production-api
9
- * 或设置环境变量:
10
- * PATCH_BACKEND_ROOT=/path/to/production-api php apply-update.php
692
+ * @return array<string, int>
693
+ */
694
+ function readMetaModes(string $backupSessionDir): array
695
+ {
696
+ $path = $backupSessionDir . '/' . DEPLOY_META_FILE;
697
+ if (!is_file($path)) {
698
+ return [];
699
+ }
700
+
701
+ /** @var array<string, int> $modes */
702
+ $modes = [];
703
+ $inModes = false;
704
+
705
+ foreach (file($path, FILE_IGNORE_NEW_LINES) ?: [] as $line) {
706
+ $trimmed = trim($line);
707
+ if ($trimmed === '# modes') {
708
+ $inModes = true;
709
+ continue;
710
+ }
711
+ if ($inModes && str_starts_with($trimmed, '#')) {
712
+ break;
713
+ }
714
+ if ($inModes && preg_match('/^([0-7]{3,4})\s+(.+)$/', $trimmed, $m) === 1) {
715
+ $rel = str_replace('\\', '/', trim($m[2]));
716
+ if (isSafeRelativePath($rel)) {
717
+ $modes[$rel] = octdec($m[1]);
718
+ }
719
+ }
720
+ }
721
+
722
+ return $modes;
723
+ }
724
+
725
+ /**
726
+ * 读取元数据中本次部署新增的文件(用于回滚时删除)
11
727
  *
12
- * 安全:不会覆盖 .env;不会自动删除 MANIFEST-deleted.txt 中列出的文件。
13
- * 备份:覆盖前将线上已有文件复制到备份目录(默认 Backend/.deploy-backups/<时间戳>/)。
728
+ * @return list<array{hash: string, rel: string}>
14
729
  */
730
+ function readMetaCreatedFiles(string $backupSessionDir): array
731
+ {
732
+ $metaPath = $backupSessionDir . '/' . DEPLOY_META_FILE;
733
+ if (!is_file($metaPath)) {
734
+ return [];
735
+ }
15
736
 
16
- /** patch 包根目录(本脚本所在目录) */
17
- const PATCH_ROOT = __DIR__;
737
+ $lines = file($metaPath, FILE_IGNORE_NEW_LINES);
738
+ if ($lines === false) {
739
+ return [];
740
+ }
18
741
 
19
- /** 默认备份目录名(位于 Backend 根下,可通过 PATCH_BACKUP_DIR 覆盖父路径) */
20
- const BACKUP_DIR_BASENAME = '.deploy-backups';
742
+ /** @var list<array{hash: string, rel: string}> $items */
743
+ $items = [];
744
+ $inCreated = false;
21
745
 
22
- /** 部署时跳过的文件名(相对路径 basename 匹配或完整相对路径) */
23
- const SKIP_FILES = [
24
- 'apply-update.php',
25
- 'MANIFEST.txt',
26
- 'MANIFEST-deleted.txt',
27
- 'VERSION.txt',
28
- ];
746
+ foreach ($lines as $line) {
747
+ $trimmed = trim($line);
748
+ if ($trimmed === '# created') {
749
+ $inCreated = true;
750
+ continue;
751
+ }
752
+ if ($inCreated && str_starts_with($trimmed, '#')) {
753
+ break;
754
+ }
755
+ if ($inCreated && $trimmed !== '' && preg_match('/^([0-9a-f]{64})\s+(.+)$/i', $trimmed, $m) === 1) {
756
+ $rel = str_replace('\\', '/', trim($m[2]));
757
+ if (isSafeRelativePath($rel)) {
758
+ $items[] = ['hash' => strtolower($m[1]), 'rel' => $rel];
759
+ }
760
+ }
761
+ }
29
762
 
30
- /** 永不覆盖的相对路径(保护生产配置与运行时数据) */
31
- const PROTECTED_RELATIVE = [
32
- '.env',
33
- '.env.local',
34
- '.env.production',
35
- ];
763
+ return $items;
764
+ }
36
765
 
37
- /** 本地产物路径前缀(误打进 zip 时跳过,避免污染 Backend) */
38
- const SKIP_PATH_PREFIXES = [
39
- 'deploy/out/',
40
- 'out/_verify/',
41
- 'out/patch-',
42
- ];
766
+ /**
767
+ * 读取备份目录元数据
768
+ *
769
+ * @return array<string, string>
770
+ */
771
+ function readDeployMeta(string $backupSessionDir): array
772
+ {
773
+ return readKeyValueFile($backupSessionDir . '/' . DEPLOY_META_FILE);
774
+ }
43
775
 
44
776
  /**
45
- * 解析线上 Backend 根目录(含 app、config、public、vendor 的 trunk 根)。
777
+ * 列出备份目录内可恢复文件(排除元数据)
778
+ *
779
+ * @return list<string>
46
780
  */
47
- function resolveBackendRoot(): string
781
+ function listBackupFiles(string $backupSessionDir): array
48
782
  {
49
- foreach (['PATCH_BACKEND_ROOT'] as $envKey) {
50
- $fromEnv = getenv($envKey);
51
- if (is_string($fromEnv) && $fromEnv !== '') {
52
- return rtrim($fromEnv, "/\\");
783
+ if (!is_dir($backupSessionDir)) {
784
+ return [];
785
+ }
786
+
787
+ /** @var list<string> $files */
788
+ $files = [];
789
+ $iterator = new RecursiveIteratorIterator(
790
+ new RecursiveDirectoryIterator($backupSessionDir, FilesystemIterator::SKIP_DOTS)
791
+ );
792
+
793
+ foreach ($iterator as $fileInfo) {
794
+ if (!$fileInfo->isFile()) {
795
+ continue;
796
+ }
797
+ $abs = $fileInfo->getPathname();
798
+ $rel = substr($abs, strlen($backupSessionDir) + 1);
799
+ $relNorm = str_replace('\\', '/', $rel);
800
+ if (in_array(basename($relNorm), [DEPLOY_META_FILE, BACKUP_SESSION_MARKER, 'MANIFEST.txt'], true)) {
801
+ continue;
53
802
  }
803
+ $files[] = $relNorm;
54
804
  }
55
805
 
56
- global $argv;
57
- $flags = ['--check', '--dry-run', '--no-backup'];
58
- foreach ($argv as $i => $arg) {
59
- if ($i === 0) {
806
+ sort($files);
807
+
808
+ return $files;
809
+ }
810
+
811
+ /**
812
+ * 列出所有版本备份
813
+ *
814
+ * @return list<array{dir: string, meta: array<string, string>, fileCount: int}>
815
+ */
816
+ function listVersionBackups(string $backendRoot): array
817
+ {
818
+ $backupRoot = resolveBackupRoot($backendRoot);
819
+ if (!is_dir($backupRoot)) {
820
+ return [];
821
+ }
822
+
823
+ /** @var list<array{dir: string, meta: array<string, string>, fileCount: int}> $items */
824
+ $items = [];
825
+ foreach (scandir($backupRoot) ?: [] as $name) {
826
+ if ($name === '.' || $name === '..') {
60
827
  continue;
61
828
  }
62
- if (in_array($arg, $flags, true)) {
829
+ $dir = $backupRoot . '/' . $name;
830
+ if (!is_dir($dir)) {
63
831
  continue;
64
832
  }
65
- if (str_starts_with($arg, '--files=') || str_starts_with($arg, '--file-list=')) {
833
+ $meta = readDeployMeta($dir);
834
+ // 没有元数据的中断会话不列入可回滚版本(仍会被保留策略清理)
835
+ if ($meta === []) {
66
836
  continue;
67
837
  }
68
- if ($arg !== '' && !str_starts_with($arg, '-')) {
69
- return rtrim($arg, "/\\");
838
+ $items[] = [
839
+ 'dir' => $dir,
840
+ 'meta' => $meta,
841
+ 'fileCount' => count(listBackupFiles($dir)),
842
+ ];
843
+ }
844
+
845
+ usort($items, static function (array $a, array $b): int {
846
+ $timeA = $a['meta']['backed_up_at'] ?? '';
847
+ $timeB = $b['meta']['backed_up_at'] ?? '';
848
+ if ($timeA !== $timeB) {
849
+ return $timeA < $timeB ? 1 : -1;
850
+ }
851
+ $mA = (int) @filemtime($a['dir']);
852
+ $mB = (int) @filemtime($b['dir']);
853
+ if ($mA !== $mB) {
854
+ return $mB <=> $mA;
855
+ }
856
+ // 同秒部署:带 _时间戳 后缀的会话更新,排在基础目录之前
857
+ return strcmp(basename($b['dir']), basename($a['dir']));
858
+ });
859
+
860
+ return $items;
861
+ }
862
+
863
+ /**
864
+ * 解析回滚目标备份目录
865
+ */
866
+ function resolveRollbackBackupDir(string $backendRoot, ?string $targetVersion): string
867
+ {
868
+ $backupRoot = resolveBackupRoot($backendRoot);
869
+ $currentVersion = readDeployedVersion($backendRoot);
870
+
871
+ if ($targetVersion !== null && $targetVersion !== '') {
872
+ $targetLabel = sanitizeVersionLabel($targetVersion);
873
+
874
+ // 同一版本可能重复部署(目录会追加 _时间戳),取最近一次会话
875
+ foreach (listVersionBackups($backendRoot) as $item) {
876
+ $metaVersion = sanitizeVersionLabel($item['meta']['version'] ?? '');
877
+ if ($metaVersion === $targetLabel) {
878
+ return $item['dir'];
879
+ }
880
+ }
881
+
882
+ $candidate = $backupRoot . '/' . formatBackupDirName($targetLabel);
883
+ if (!is_dir($candidate)) {
884
+ throw new RuntimeException("未找到版本 {$targetLabel} 的备份目录: {$candidate}");
70
885
  }
886
+ return $candidate;
71
887
  }
72
888
 
73
- fwrite(STDERR, "用法: php apply-update.php [--check] [--files=<路径>] [--file-list=<列表>] <Backend根目录>\n");
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");
76
- exit(1);
889
+ if ($currentVersion === null) {
890
+ throw new RuntimeException('当前无 .deploy-version,请使用 --rollback=<版本> 指定目标');
891
+ }
892
+
893
+ foreach (listVersionBackups($backendRoot) as $item) {
894
+ $replacedBy = $item['meta']['replaced_by'] ?? '';
895
+ if ($replacedBy !== '' && sanitizeVersionLabel($replacedBy) === $currentVersion) {
896
+ return $item['dir'];
897
+ }
898
+ }
899
+
900
+ throw new RuntimeException("未找到可回滚到上一版本的备份(当前版本 {$currentVersion})");
901
+ }
902
+
903
+ /**
904
+ * 从版本备份恢复文件
905
+ *
906
+ * 恢复备份的旧文件;并删除本次部署新增的文件(仅当内容未被修改过)。
907
+ *
908
+ * @return array{ok: int, fail: int, removed: int, kept: int, targetVersion: string}
909
+ */
910
+ function rollbackFromBackup(string $backendRoot, string $backupSessionDir): array
911
+ {
912
+ $meta = readDeployMeta($backupSessionDir);
913
+ $targetVersion = $meta['version'] ?? basename($backupSessionDir);
914
+ $targetVersion = sanitizeVersionLabel($targetVersion);
915
+
916
+ if (($meta['partial'] ?? '') === '1') {
917
+ echo "注意: 该备份来自部分部署(子集包),只会恢复其中的文件。\n";
918
+ }
919
+
920
+ $files = listBackupFiles($backupSessionDir);
921
+ $createdFiles = readMetaCreatedFiles($backupSessionDir);
922
+ $modes = readMetaModes($backupSessionDir);
923
+ if ($files === [] && $createdFiles === []) {
924
+ throw new RuntimeException("备份目录无可用文件: {$backupSessionDir}");
925
+ }
926
+
927
+ $ok = 0;
928
+ $fail = 0;
929
+ foreach ($files as $rel) {
930
+ $src = $backupSessionDir . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
931
+ $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
932
+ try {
933
+ assertTargetInsideBackend($backendRoot, $dst, $rel);
934
+ assertTargetWritable($dst, $rel);
935
+ ensureParentDir($dst);
936
+ if (!copy($src, $dst)) {
937
+ throw new RuntimeException('copy 失败');
938
+ }
939
+ if (isset($modes[$rel])) {
940
+ @chmod($dst, $modes[$rel]);
941
+ }
942
+ echo "OK {$rel}\n";
943
+ $ok++;
944
+ } catch (Throwable $e) {
945
+ echo "FAIL {$rel} — {$e->getMessage()}\n";
946
+ $fail++;
947
+ }
948
+ }
949
+
950
+ // 删除本次部署新增的文件;内容已变化则保留现场,避免误删后续改动
951
+ $removed = 0;
952
+ $kept = 0;
953
+ foreach ($createdFiles as $item) {
954
+ $rel = $item['rel'];
955
+ if (isProtectedRelativePath($rel) || isProtectListed($rel)) {
956
+ echo "SKIP {$rel} — 受保护路径\n";
957
+ $kept++;
958
+ continue;
959
+ }
960
+
961
+ $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
962
+ if (!is_file($dst)) {
963
+ echo "SKIP {$rel} — 已不存在\n";
964
+ continue;
965
+ }
966
+
967
+ $currentHash = @hash_file('sha256', $dst);
968
+ if (!is_string($currentHash) || !hash_equals($item['hash'], $currentHash)) {
969
+ echo "SKIP {$rel} — 部署后已被修改,保留\n";
970
+ $kept++;
971
+ continue;
972
+ }
973
+
974
+ if (@unlink($dst)) {
975
+ echo "DELETED {$rel}\n";
976
+ $removed++;
977
+ } else {
978
+ echo "FAIL-DELETE {$rel} — 无法删除\n";
979
+ $fail++;
980
+ }
981
+ }
982
+
983
+ if ($fail === 0) {
984
+ writeDeployedVersion($backendRoot, $targetVersion);
985
+ }
986
+
987
+ return [
988
+ 'ok' => $ok,
989
+ 'fail' => $fail,
990
+ 'removed' => $removed,
991
+ 'kept' => $kept,
992
+ 'targetVersion' => $targetVersion,
993
+ ];
77
994
  }
78
995
 
79
996
  /**
@@ -124,11 +1041,17 @@ function listPatchFiles(): array
124
1041
  /** @var list<string> $files */
125
1042
  $files = [];
126
1043
  foreach ($fromManifest as $rel) {
1044
+ if (!isSafeRelativePath($rel)) {
1045
+ throw new RuntimeException("MANIFEST.txt 含不安全路径(拒绝部署): {$rel}");
1046
+ }
127
1047
  $abs = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
128
1048
  if (!is_file($abs)) {
129
1049
  continue;
130
1050
  }
131
- if (in_array($rel, PROTECTED_RELATIVE, true)) {
1051
+ if (is_link($abs)) {
1052
+ throw new RuntimeException("patch 包内含符号链接(拒绝部署): {$rel}");
1053
+ }
1054
+ if (isProtectedRelativePath($rel)) {
132
1055
  continue;
133
1056
  }
134
1057
  $files[] = $rel;
@@ -151,13 +1074,20 @@ function listPatchFiles(): array
151
1074
  $rel = substr($abs, strlen(PATCH_ROOT) + 1);
152
1075
  $relNorm = str_replace('\\', '/', $rel);
153
1076
 
1077
+ if (!isSafeRelativePath($relNorm)) {
1078
+ throw new RuntimeException("patch 包内含不安全路径(拒绝部署): {$relNorm}");
1079
+ }
1080
+ if ($fileInfo->isLink()) {
1081
+ throw new RuntimeException("patch 包内含符号链接(拒绝部署): {$relNorm}");
1082
+ }
1083
+
154
1084
  if (in_array(basename($relNorm), SKIP_FILES, true)) {
155
1085
  continue;
156
1086
  }
157
1087
  if (in_array($relNorm, SKIP_FILES, true)) {
158
1088
  continue;
159
1089
  }
160
- if (in_array($relNorm, PROTECTED_RELATIVE, true)) {
1090
+ if (isProtectedRelativePath($relNorm)) {
161
1091
  continue;
162
1092
  }
163
1093
 
@@ -180,6 +1110,20 @@ function listPatchFiles(): array
180
1110
  return $files;
181
1111
  }
182
1112
 
1113
+ /**
1114
+ * 输出 MANIFEST-deleted.txt 提示(不自动删除线上文件)
1115
+ */
1116
+ function printDeletedNotice(): void
1117
+ {
1118
+ $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
1119
+ if (!is_file($deletedList)) {
1120
+ return;
1121
+ }
1122
+
1123
+ echo "\n注意: 存在 MANIFEST-deleted.txt,未自动删除线上文件,请人工确认:\n";
1124
+ echo file_get_contents($deletedList);
1125
+ }
1126
+
183
1127
  /**
184
1128
  * 解析 --files / --file-list / PATCH_DEPLOY_FILES,用于单独部署部分文件
185
1129
  *
@@ -278,6 +1222,9 @@ function detectPhpBinary(): string
278
1222
  if (defined('PHP_BINARY') && PHP_BINARY !== '') {
279
1223
  return PHP_BINARY;
280
1224
  }
1225
+ if (!function_exists('shell_exec')) {
1226
+ return 'php';
1227
+ }
281
1228
  $which = trim((string) shell_exec('command -v php 2>/dev/null'));
282
1229
  if ($which !== '') {
283
1230
  return $which;
@@ -390,9 +1337,22 @@ function createBackupSessionDir(string $backupRoot): string
390
1337
  throw new RuntimeException("无法创建备份目录: {$sessionDir}");
391
1338
  }
392
1339
 
1340
+ markBackupSession($sessionDir);
1341
+
393
1342
  return $sessionDir;
394
1343
  }
395
1344
 
1345
+ /**
1346
+ * 标记本工具创建的备份会话(即使部署中断、没有 DEPLOY-META 也能被保留策略清理)
1347
+ */
1348
+ function markBackupSession(string $sessionDir): void
1349
+ {
1350
+ @file_put_contents(
1351
+ $sessionDir . '/' . BACKUP_SESSION_MARKER,
1352
+ "session=1\ncreated_at=" . date('Y-m-d H:i:s') . "\n"
1353
+ );
1354
+ }
1355
+
396
1356
  /**
397
1357
  * 将被覆盖的线上文件复制到备份目录(保持相对路径结构)
398
1358
  *
@@ -460,6 +1420,11 @@ function tryThinkClear(string $backendRoot): void
460
1420
  return;
461
1421
  }
462
1422
 
1423
+ if (!isExecAvailable()) {
1424
+ echo "提示: exec 被 disable_functions 禁用,跳过 php think clear(已清理 runtime/cache)\n";
1425
+ return;
1426
+ }
1427
+
463
1428
  $phpBin = detectPhpBinary();
464
1429
  $cmd = escapeshellarg($phpBin) . ' ' . escapeshellarg($think) . ' clear 2>&1';
465
1430
  $output = [];
@@ -545,6 +1510,14 @@ function validateBackendRoot(string $backendRoot, array $patchFiles = []): array
545
1510
 
546
1511
  // --- main ---
547
1512
 
1513
+ $listBackups = in_array('--list-backups', $argv ?? [], true);
1514
+ try {
1515
+ $rollbackOption = resolveRollbackOption();
1516
+ } catch (Throwable $e) {
1517
+ fwrite(STDERR, $e->getMessage() . "\n");
1518
+ exit(1);
1519
+ }
1520
+
548
1521
  $backendRoot = resolveBackendRoot();
549
1522
 
550
1523
  if (!is_dir($backendRoot)) {
@@ -552,9 +1525,65 @@ if (!is_dir($backendRoot)) {
552
1525
  exit(1);
553
1526
  }
554
1527
 
555
- $files = listPatchFiles();
1528
+ if ($listBackups) {
1529
+ $currentVersion = readDeployedVersion($backendRoot);
1530
+ echo "BACKEND_ROOT: {$backendRoot}\n";
1531
+ echo 'CURRENT_VERSION: ' . ($currentVersion ?? '(none)') . "\n";
1532
+ echo "BACKUP_ROOT: " . resolveBackupRoot($backendRoot) . "\n\n";
1533
+
1534
+ $backups = listVersionBackups($backendRoot);
1535
+ if ($backups === []) {
1536
+ echo "暂无版本备份。\n";
1537
+ exit(0);
1538
+ }
1539
+
1540
+ foreach ($backups as $item) {
1541
+ $version = $item['meta']['version'] ?? basename($item['dir']);
1542
+ $replacedBy = $item['meta']['replaced_by'] ?? '-';
1543
+ $backedUpAt = $item['meta']['backed_up_at'] ?? '-';
1544
+ echo "- {$version} 文件:{$item['fileCount']} 升级至:{$replacedBy} 时间:{$backedUpAt}\n";
1545
+ echo " 目录: {$item['dir']}\n";
1546
+ }
1547
+ exit(0);
1548
+ }
1549
+
1550
+ if ($rollbackOption['enabled']) {
1551
+ try {
1552
+ $backupDir = resolveRollbackBackupDir($backendRoot, $rollbackOption['target']);
1553
+ } catch (Throwable $e) {
1554
+ fwrite(STDERR, $e->getMessage() . "\n");
1555
+ exit(1);
1556
+ }
1557
+
1558
+ echo "BACKEND_ROOT: {$backendRoot}\n";
1559
+ echo "ROLLBACK_FROM_BACKUP: {$backupDir}\n";
1560
+
1561
+ $result = rollbackFromBackup($backendRoot, $backupDir);
1562
+ if ($result['fail'] > 0) {
1563
+ echo "\n回滚未完成: 成功 {$result['ok']},失败 {$result['fail']}\n";
1564
+ exit(1);
1565
+ }
1566
+
1567
+ clearRuntimeCache($backendRoot);
1568
+ tryThinkClear($backendRoot);
1569
+ echo "\n已回滚至版本 {$result['targetVersion']}(恢复 {$result['ok']} 个文件,删除 {$result['removed']} 个新增文件)\n";
1570
+ if ($result['kept'] > 0) {
1571
+ echo "保留 {$result['kept']} 个新增文件(部署后已修改或受保护)\n";
1572
+ }
1573
+ exit(0);
1574
+ }
1575
+
1576
+ try {
1577
+ $files = listPatchFiles();
1578
+ } catch (Throwable $e) {
1579
+ fwrite(STDERR, $e->getMessage() . "\n");
1580
+ exit(1);
1581
+ }
1582
+
556
1583
  if ($files === []) {
557
1584
  echo "patch 包内无待部署文件。\n";
1585
+ // 仅含删除项的包没有可部署文件,但仍需提示人工删除
1586
+ printDeletedNotice();
558
1587
  exit(0);
559
1588
  }
560
1589
 
@@ -574,6 +1603,11 @@ if (!$rootCheck['valid']) {
574
1603
  $dryRun = in_array('--check', $argv ?? [], true) || in_array('--dry-run', $argv ?? [], true);
575
1604
  $noBackup = in_array('--no-backup', $argv ?? [], true);
576
1605
  $backupEnabled = !$dryRun && !$noBackup;
1606
+ $patchDeployVersion = resolvePatchDeployVersion();
1607
+ $currentDeployedVersion = readDeployedVersion($backendRoot);
1608
+ $versionBackupEnabled = $backupEnabled && $patchDeployVersion !== null;
1609
+ $patchMeta = readKeyValueFile(PATCH_ROOT . '/VERSION.txt');
1610
+ $isPartialDeploy = ($patchMeta['partial'] ?? '') === '1';
577
1611
 
578
1612
  $runUser = function_exists('posix_getpwuid')
579
1613
  ? (posix_getpwuid(posix_geteuid())['name'] ?? 'unknown')
@@ -587,13 +1621,33 @@ if ($rootCheck['markers'] !== []) {
587
1621
  }
588
1622
  echo "\n";
589
1623
  echo "RUN_AS: {$runUser}\n";
1624
+ if (readProtectList() !== []) {
1625
+ echo 'PROTECT: ' . count(readProtectList()) . " 个文件(线上已存在则跳过覆盖)\n";
1626
+ }
590
1627
  if ($dryRun) {
591
1628
  echo "MODE: check-only(不写入文件)\n";
592
1629
  }
1630
+ if ($isPartialDeploy) {
1631
+ echo "PATCH_MODE: partial(子集包,回滚只覆盖其中的文件)\n";
1632
+ }
593
1633
  if ($noBackup) {
594
1634
  echo "BACKUP: disabled(--no-backup)\n";
1635
+ } elseif ($versionBackupEnabled) {
1636
+ $backupLabel = $currentDeployedVersion ?? 'pre-deploy';
1637
+ echo "BACKUP: 按当前版本 {$backupLabel} 建立备份会话(重复部署追加时间戳)\n";
1638
+ echo "PATCH_VERSION: {$patchDeployVersion}\n";
1639
+ echo 'CURRENT_VERSION: ' . ($currentDeployedVersion ?? '(none)') . "\n";
595
1640
  } elseif ($backupEnabled) {
596
- echo "BACKUP: enabled -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
1641
+ echo "BACKUP: timestamp -> " . resolveBackupRoot($backendRoot) . "/<timestamp>/\n";
1642
+ }
1643
+
1644
+ if ($backupEnabled) {
1645
+ $backupRootForCheck = resolveBackupRoot($backendRoot);
1646
+ if (isPathInside($backupRootForCheck, $backendRoot)) {
1647
+ echo "WARN: 备份目录位于 Backend 根内({$backupRootForCheck}),历史源码可能被 Web 访问;\n";
1648
+ echo " 建议将 PATCH_BACKUP_DIR 指向站点根外,或在 Web 配置中禁止访问该目录\n";
1649
+ protectBackupDir($backupRootForCheck);
1650
+ }
597
1651
  }
598
1652
 
599
1653
  try {
@@ -615,21 +1669,42 @@ if ($fileFilter !== null) {
615
1669
 
616
1670
  if ($files === []) {
617
1671
  echo "筛选后无待部署文件。\n";
1672
+ printDeletedNotice();
618
1673
  exit(0);
619
1674
  }
620
1675
 
621
1676
  $ok = 0;
622
1677
  $fail = 0;
1678
+ $protectedSkipped = 0;
623
1679
  $blocked = [];
624
1680
  $backedUp = 0;
1681
+ $modesList = readModesList();
1682
+ /** @var array<string, int> 被覆盖文件的原始权限(回滚时恢复) */
1683
+ $backedUpModes = [];
625
1684
  /** @var string|null 本次部署备份会话目录 */
626
1685
  $backupSessionDir = null;
1686
+ /** @var list<string> 已备份文件列表(用于 DEPLOY-META) */
1687
+ $backedUpFiles = [];
1688
+ /** @var list<array{hash: string, rel: string}> 本次新增文件(用于回滚删除) */
1689
+ $createdFiles = [];
627
1690
 
628
1691
  foreach ($files as $rel) {
629
1692
  $src = PATCH_ROOT . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
630
1693
  $dst = $backendRoot . '/' . str_replace('/', DIRECTORY_SEPARATOR, $rel);
631
1694
 
632
1695
  try {
1696
+ if (!isSafeRelativePath($rel)) {
1697
+ throw new RuntimeException('路径不安全');
1698
+ }
1699
+
1700
+ // 受保护文件:线上已存在则不覆盖(保留运行时被程序改写的内容)
1701
+ if (isProtectListed($rel) && is_file($dst)) {
1702
+ echo "SKIP {$rel} — 受保护文件(线上已存在,未覆盖)\n";
1703
+ $protectedSkipped++;
1704
+ continue;
1705
+ }
1706
+
1707
+ assertTargetInsideBackend($backendRoot, $dst, $rel);
633
1708
  assertTargetWritable($dst, $rel);
634
1709
  if ($dryRun) {
635
1710
  $existsHint = is_file($dst) ? ',线上已有文件' : '';
@@ -638,14 +1713,26 @@ foreach ($files as $rel) {
638
1713
  continue;
639
1714
  }
640
1715
 
641
- // 覆盖前先备份线上旧文件
642
- if ($backupEnabled && is_file($dst)) {
643
- if ($backupSessionDir === null) {
644
- $backupSessionDir = createBackupSessionDir(resolveBackupRoot($backendRoot));
645
- echo "BACKUP_DIR: {$backupSessionDir}\n";
1716
+ $isNewFile = !is_file($dst);
1717
+
1718
+ // 本次部署的备份会话(覆盖旧文件或新增文件都需要,便于回滚时删除新增文件)
1719
+ if ($backupEnabled && $backupSessionDir === null) {
1720
+ $backupRoot = resolveBackupRoot($backendRoot);
1721
+ $backupSessionDir = $versionBackupEnabled
1722
+ ? createVersionBackupSessionDir($backupRoot, $currentDeployedVersion ?? 'pre-deploy')
1723
+ : createBackupSessionDir($backupRoot);
1724
+ echo "BACKUP_DIR: {$backupSessionDir}\n";
1725
+ }
1726
+
1727
+ // 覆盖前先备份线上旧文件(有 patch 版本标识时用版本目录),并记录原权限
1728
+ if ($backupEnabled && !$isNewFile) {
1729
+ $origMode = @fileperms($dst);
1730
+ if ($origMode !== false) {
1731
+ $backedUpModes[$rel] = $origMode & 0777;
646
1732
  }
647
1733
  if (backupExistingFile($dst, $rel, $backupSessionDir)) {
648
1734
  $backedUp++;
1735
+ $backedUpFiles[] = $rel;
649
1736
  }
650
1737
  }
651
1738
 
@@ -653,6 +1740,15 @@ foreach ($files as $rel) {
653
1740
  if (!copy($src, $dst)) {
654
1741
  throw new RuntimeException('copy 失败');
655
1742
  }
1743
+ if (isset($modesList[$rel]) && !@chmod($dst, $modesList[$rel])) {
1744
+ echo "WARN {$rel} — 无法设置权限 0" . decoct($modesList[$rel]) . "\n";
1745
+ }
1746
+ if ($isNewFile) {
1747
+ $hash = @hash_file('sha256', $dst);
1748
+ if (is_string($hash)) {
1749
+ $createdFiles[] = ['hash' => $hash, 'rel' => $rel];
1750
+ }
1751
+ }
656
1752
  echo "OK {$rel}\n";
657
1753
  $ok++;
658
1754
  } catch (Throwable $e) {
@@ -685,30 +1781,74 @@ if ($fail > 0) {
685
1781
  }
686
1782
 
687
1783
  if ($dryRun) {
688
- echo "\n检查完成: 可写 {$ok},不可写 {$fail}\n";
1784
+ echo "\n检查完成: 可写 {$ok},不可写 {$fail}";
1785
+ if ($protectedSkipped > 0) {
1786
+ echo ",跳过 {$protectedSkipped}(受保护)";
1787
+ }
1788
+ echo "\n";
1789
+ printDeletedNotice();
689
1790
  exit($fail > 0 ? 1 : 0);
690
1791
  }
691
1792
 
692
1793
  if ($fail > 0) {
693
1794
  echo "\n存在写入失败,已跳过清缓存(避免未更新代码却刷新缓存)。\n";
694
- echo "完成: 成功 {$ok},失败 {$fail}\n";
1795
+ echo "完成: 成功 {$ok},失败 {$fail}";
1796
+ if ($protectedSkipped > 0) {
1797
+ echo ",跳过 {$protectedSkipped}(受保护)";
1798
+ }
1799
+ echo "\n";
695
1800
  exit(1);
696
1801
  }
697
1802
 
1803
+ if (
1804
+ $backupSessionDir !== null
1805
+ && $backupEnabled
1806
+ ) {
1807
+ $backupVersionLabel = $currentDeployedVersion ?? 'pre-deploy';
1808
+ writeDeployMeta(
1809
+ $backupSessionDir,
1810
+ $backupVersionLabel,
1811
+ $patchDeployVersion,
1812
+ $backedUpFiles,
1813
+ $createdFiles,
1814
+ $backedUpModes,
1815
+ $isPartialDeploy
1816
+ );
1817
+ }
1818
+
698
1819
  clearRuntimeCache($backendRoot);
699
1820
  tryThinkClear($backendRoot);
700
1821
 
1822
+ if ($patchDeployVersion !== null) {
1823
+ writeDeployedVersion($backendRoot, $patchDeployVersion);
1824
+ echo "\nDEPLOY_VERSION: {$patchDeployVersion}\n";
1825
+ }
1826
+
1827
+ // 备份会话保留策略(默认 10 个),避免 .deploy-backups 无限增长
1828
+ if ($backupEnabled && $backupSessionDir !== null) {
1829
+ $keepBackups = resolveKeepBackups();
1830
+ $prunedSessions = pruneBackupSessions($backendRoot, $keepBackups, $backupSessionDir);
1831
+ if ($prunedSessions !== []) {
1832
+ echo "\n已清理旧备份会话 " . count($prunedSessions) . " 个(保留最近 {$keepBackups} 个)\n";
1833
+ echo ' 删除: ' . implode(', ', $prunedSessions) . "\n";
1834
+ }
1835
+ }
1836
+
701
1837
  if ($backupSessionDir !== null) {
702
- $sampleRel = $files[0] ?? 'path/to/file.php';
1838
+ $sampleRel = $backedUpFiles[0] ?? ($files[0] ?? 'path/to/file.php');
703
1839
  echo "\n已备份 {$backedUp} 个旧文件至: {$backupSessionDir}\n";
704
- echo "回滚示例: cp -f {$backupSessionDir}/{$sampleRel} {$backendRoot}/{$sampleRel}\n";
1840
+ if ($versionBackupEnabled) {
1841
+ echo "回滚示例: php apply-update.php --rollback " . escapeshellarg($backendRoot) . "\n";
1842
+ } else {
1843
+ echo "回滚示例: cp -f {$backupSessionDir}/{$sampleRel} {$backendRoot}/{$sampleRel}\n";
1844
+ }
705
1845
  }
706
1846
 
707
- $deletedList = PATCH_ROOT . '/MANIFEST-deleted.txt';
708
- if (is_file($deletedList)) {
709
- echo "\n注意: 存在 MANIFEST-deleted.txt,未自动删除线上文件,请人工确认:\n";
710
- echo file_get_contents($deletedList);
711
- }
1847
+ printDeletedNotice();
712
1848
 
713
- echo "\n完成: 成功 {$ok},失败 {$fail}\n";
1849
+ echo "\n完成: 成功 {$ok},失败 {$fail}";
1850
+ if ($protectedSkipped > 0) {
1851
+ echo ",跳过 {$protectedSkipped}(受保护)";
1852
+ }
1853
+ echo "\n";
714
1854
  exit($fail > 0 ? 1 : 0);