vcs-patch-deploy 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,31 @@
1
+ # Changelog
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
+
23
+ ## 1.0.1
24
+
25
+ - 文档与示例改用通用占位路径,移除项目专有目录名
26
+ - `apply-update.php` 仅保留 `PATCH_BACKEND_ROOT` 环境变量
27
+ - 补充 GitHub 仓库链接
28
+
29
+ ## 1.0.0
30
+
31
+ - 首次发布:PHP 后端增量部署,支持 SVN / Git
package/README.md CHANGED
@@ -2,6 +2,9 @@
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>
7
+
5
8
  > v1 仅内置 **PHP 后端**配置;Node/Java 等后端可在后续版本通过 `--backend` 扩展。
6
9
 
7
10
  ## 安装
@@ -15,8 +18,10 @@ npx patch-build --help
15
18
 
16
19
  ## 快速开始(ThinkPHP + SVN)
17
20
 
21
+ 在 **PHP 项目根目录**(含 `app/`、`config/` 或 `think`)执行:
22
+
18
23
  ```bash
19
- cd BackendSVN/trunk
24
+ cd /path/to/your-php-api
20
25
 
21
26
  # 首次:初始化 deploy 目录
22
27
  patch-build --init --vcs=svn
@@ -32,41 +37,86 @@ patch-build --vcs=svn
32
37
  # deploy/out/patch-r{rev}/
33
38
  ```
34
39
 
40
+ SVN 常见目录结构为 `repo-root/trunk`,进入 `trunk` 后执行上述命令即可。
41
+
35
42
  ## Git 仓库
36
43
 
37
44
  ```bash
38
- cd BackendSVN/trunk # 若 trunk 为 Git 仓库
45
+ cd /path/to/your-php-api
39
46
 
40
47
  echo git:abc123def... > deploy/.last-deploy-marker
41
48
  patch-build --vcs=git
42
49
  patch-build --vcs=git --from=v1.0.0 --to=HEAD
43
50
  ```
44
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
+
45
83
  ## 服务器应用
46
84
 
47
85
  ```bash
48
86
  unzip -o backend-update-r467.zip -d patch-r467
49
87
  cd patch-r467
50
88
 
51
- php apply-update.php --check /usr/local/tool/THS/html/BackendSVN/Backend
52
- php apply-update.php /usr/local/tool/THS/html/BackendServer/Backend
89
+ php apply-update.php --check /path/to/production-api
90
+ php apply-update.php /path/to/production-api
53
91
 
54
92
  # 或环境变量
55
- export PATCH_BACKEND_ROOT=/path/to/backend
93
+ export PATCH_BACKEND_ROOT=/path/to/production-api
56
94
  php apply-update.php
57
95
  ```
58
96
 
59
97
  `apply-update.php` 行为:
60
98
 
61
99
  - 按包内路径覆盖线上文件
100
+ - **覆盖前备份** 线上已有文件到 `Backend/.deploy-backups/<时间戳>/`(保持相对路径)
62
101
  - **不覆盖** `.env`
63
102
  - **不自动删除** `MANIFEST-deleted.txt` 中的文件
64
103
  - 成功后清理 `runtime/cache`,并尝试 `php think clear`
65
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
+
66
116
  ## CLI 参数
67
117
 
68
118
  | 参数 | 说明 |
69
- |------|------|
119
+ | ------ | ------ |
70
120
  | `--backend=php` | 后端类型(默认 php) |
71
121
  | `--vcs=svn\|git` | 强制 VCS 类型 |
72
122
  | `--source=<dir>` | PHP 项目根 |
@@ -76,6 +126,20 @@ php apply-update.php
76
126
  | `--no-zip` | 只生成 patch 目录 |
77
127
  | `--mark-deployed` | 更新基准 marker |
78
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 |
79
143
 
80
144
  ## 不会打进包的内容
81
145
 
@@ -86,21 +150,26 @@ php apply-update.php
86
150
  ## 基准文件
87
151
 
88
152
  | 文件 | 格式 |
89
- |------|------|
153
+ | ------ | ------ |
90
154
  | `deploy/.last-deploy-marker` | `svn:467` 或 `git:fullsha` |
91
- | `deploy/.last-deploy-rev` | 兼容旧版 SVN(仅数字) |
155
+ | `deploy/.last-deploy-rev` | 兼容旧版 SVN 工具(仅数字) |
156
+ | `deploy/versions.json` | 版本号与 patch 目录映射 |
92
157
 
93
158
  **上线成功后再更新基准**,否则下次增量会漏文件。
94
159
 
95
160
  ## 编程式调用
96
161
 
162
+ 默认以 **当前工作目录** 为 PHP 项目根,无需写死路径:
163
+
97
164
  ```javascript
165
+ const path = require('path')
98
166
  const { buildPatch, resolveConfig } = require('vcs-patch-deploy')
99
167
 
168
+ // 在 PHP 项目根目录运行,或显式指定 sourceDir
100
169
  const config = resolveConfig({
101
170
  backend: 'php',
102
171
  vcs: 'svn',
103
- sourceDir: 'D:/Work/web/newKJCG/BackendSVN/trunk',
172
+ cwd: path.join(__dirname), // 调用方项目根
104
173
  fromRef: 430,
105
174
  toRef: 467
106
175
  })
@@ -108,6 +177,14 @@ const config = resolveConfig({
108
177
  buildPatch(config).then(console.log)
109
178
  ```
110
179
 
180
+ 也可通过环境变量配置(见 `env.example`):
181
+
182
+ ```bash
183
+ export PATCH_SOURCE_DIR=/path/to/your-php-api
184
+ export PATCH_VCS=svn
185
+ patch-build
186
+ ```
187
+
111
188
  ## License
112
189
 
113
190
  MIT
@@ -5,21 +5,26 @@ declare(strict_types=1);
5
5
  * 堡垒机增量部署:将 patch 包内文件覆盖到线上 Backend 根目录,并清理 ThinkPHP 缓存。
6
6
  *
7
7
  * 用法(Linux Web 终端,在解压后的 patch 目录内):
8
- * php apply-update.php /www/kjcg-api
8
+ * php apply-update.php /path/to/production-api
9
9
  * 或设置环境变量:
10
- * KJCG_BACKEND_ROOT=/www/kjcg-api php apply-update.php
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
  /** 永不覆盖的相对路径(保护生产配置与运行时数据) */
@@ -41,7 +46,7 @@ const SKIP_PATH_PREFIXES = [
41
46
  */
42
47
  function resolveBackendRoot(): string
43
48
  {
44
- foreach (['PATCH_BACKEND_ROOT', 'KJCG_BACKEND_ROOT'] as $envKey) {
49
+ foreach (['PATCH_BACKEND_ROOT'] as $envKey) {
45
50
  $fromEnv = getenv($envKey);
46
51
  if (is_string($fromEnv) && $fromEnv !== '') {
47
52
  return rtrim($fromEnv, "/\\");
@@ -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");
66
- fwrite(STDERR, "示例: php apply-update.php /usr/local/tool/THS/html/BackendSVN/Backend\n");
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");
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 失败');
@@ -332,7 +578,7 @@ if ($fail > 0) {
332
578
  $phpBin = detectPhpBinary();
333
579
  echo "\n--- 权限排查 ---\n";
334
580
  echo "当前终端用户「{$runUser}」无法覆盖 app/ 下 PHP 文件(runtime/cache 可写不代表源码可写)。\n";
335
- echo "源码属主与 PHP-FPM 不一致时,THS 常见:文件 UID 48 无 passwd 条目,而 php-fpm 以 nyncb 运行。\n";
581
+ echo "源码属主与 PHP-FPM 不一致时较常见:Web 终端用户与 php-fpm 运行用户不同。\n";
336
582
  echo "建议: sudo chown -R {$runUser}:{$runUser} {$backendRoot}/app 后,再以 {$runUser} 执行本脚本;或 sudo cp 覆盖。\n";
337
583
  echo "请在 Backend 根目录执行:\n";
338
584
  echo " whoami\n";
@@ -342,8 +588,8 @@ if ($fail > 0) {
342
588
  echo "常见处理方式(择一,需运维配合):\n";
343
589
  echo " 1) sudo chown -R {$runUser}:{$runUser} {$backendRoot}/app && {$phpBin} apply-update.php {$backendRoot}\n";
344
590
  echo " 2) sudo cp -f app/service/... {$backendRoot}/app/service/...(在 patch 目录内)\n";
345
- echo " 3) 请运维在 THS 控制台代为覆盖 patch 内文件\n";
346
- echo "注意: 本 THS 环境通常无 www/nginx/apache 用户,勿用 sudo -u nginx。\n";
591
+ echo " 3) 请运维在面板/堡垒机代为覆盖 patch 内文件\n";
592
+ echo "注意: 勿假设固定系统用户(如 nginx/www),以 whoami 与 ls -ln 实际属主为准。\n";
347
593
  if ($blocked !== []) {
348
594
  echo "\n未写入文件数: " . count($blocked) . "\n";
349
595
  }
@@ -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,13 +44,21 @@ ${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 仅打包的文件列表路径
44
49
 
45
- ${chalk.yellow('ThinkPHP + SVN(BackendSVN/trunk):')}
46
- cd BackendSVN/trunk
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
55
+
56
+ ${chalk.yellow('ThinkPHP + SVN:')}
57
+ cd /path/to/your-php-api
47
58
  patch-build --vcs=svn
48
59
 
49
60
  ${chalk.yellow('ThinkPHP + Git:')}
50
- cd BackendSVN/trunk
61
+ cd /path/to/your-php-api
51
62
  patch-build --vcs=git --from=<commit> --to=HEAD
52
63
 
53
64
  ${chalk.yellow('服务器应用:')}
@@ -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)