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.
package/lib/config.js CHANGED
@@ -7,6 +7,8 @@ const path = require('path')
7
7
  const { isGitRepository } = require('./git')
8
8
  const { findSvnExe, runSvn } = require('./svn')
9
9
  const { getBackend } = require('./backends')
10
+ const { readDeployMarker, listMarkerFiles, parseMarkerFile, isValidProfile } = require('./marker')
11
+ const { resolveProtectFiles } = require('./protect')
10
12
 
11
13
  /**
12
14
  * @param {string} dir
@@ -28,9 +30,23 @@ function isSvnWorkingCopy (dir) {
28
30
  * @returns {'svn'|'git'|null}
29
31
  */
30
32
  function detectVcs (sourceDir) {
31
- const { readDeployMarker } = require('./marker')
32
33
  const deployDir = path.join(sourceDir, 'deploy')
33
- const marker = readDeployMarker(deployDir)
34
+ const profile = process.env.PATCH_PROFILE || null
35
+
36
+ // 指定 profile 时优先用该环境基准;否则依次尝试默认 marker 与其他 profile,
37
+ // 避免“只有 .last-deploy-marker.php85”的项目无法自动识别 VCS
38
+ let marker = null
39
+ try {
40
+ marker = readDeployMarker(deployDir, profile)
41
+ } catch {
42
+ marker = null
43
+ }
44
+ if (!marker) {
45
+ for (const name of listMarkerFiles(deployDir)) {
46
+ marker = parseMarkerFile(path.join(deployDir, name))
47
+ if (marker) break
48
+ }
49
+ }
34
50
 
35
51
  if (marker?.vcs === 'svn' && isSvnWorkingCopy(sourceDir)) return 'svn'
36
52
  if (marker?.vcs === 'git' && isGitRepository(sourceDir)) return 'git'
@@ -54,11 +70,11 @@ function detectVcs (sourceDir) {
54
70
  /**
55
71
  * @typedef {object} BuildConfig
56
72
  * @property {'php'} backend 后端类型(v1 仅 php)
57
- * @property {'svn'|'git'} vcs
73
+ * @property {'svn'|'git'|null} vcs 仅在 needsVcs=false 且无法检测时为 null
58
74
  * @property {string} sourceDir
59
75
  * @property {string} deployDir
60
76
  * @property {string} outDir
61
- * @property {string} applyScriptPath
77
+ * @property {string} applyScriptPath apply-update.php 模板(可用 --apply-script 覆盖)
62
78
  * @property {string|number|null} fromRef
63
79
  * @property {string|number|null} toRef
64
80
  * @property {boolean} noZip
@@ -68,10 +84,19 @@ function detectVcs (sourceDir) {
68
84
  * @property {string|null} version 安装版本号(如 1.2.3)
69
85
  * @property {string[]} onlyFiles 仅打包/部署指定文件
70
86
  * @property {string|null} fileList 文件列表路径(每行一个相对路径)
87
+ * @property {boolean} noArchive 跳过本地版本归档
88
+ * @property {number} keepVersions 本地 archive 保留版本数(默认 10)
89
+ * @property {boolean} pruneOut 构建后清理 deploy/out 旧产物
90
+ * @property {number} keepOut deploy/out 保留数量(默认与 keepVersions 相同)
91
+ * @property {boolean} archiveLink 归档时优先使用硬链接(节省磁盘)
92
+ * @property {boolean} fromWorktree 允许用工作区内容打包(跳过与目标版本的比对)
93
+ * @property {string|null} profile 多环境基准(marker 后缀,如 php85)
94
+ * @property {string[]} protectFiles 受保护文件(线上已存在则跳过覆盖)
95
+ * @property {boolean} diffWorktree SVN:直接打包工作副本改动(对比基准 revision)
71
96
  */
72
97
 
73
98
  /**
74
- * @param {Partial<BuildConfig> & { cwd?: string, pkgRoot?: string }} input
99
+ * @param {Partial<BuildConfig> & { cwd?: string, pkgRoot?: string, needsVcs?: boolean }} input
75
100
  * @returns {BuildConfig}
76
101
  */
77
102
  function resolveConfig (input = {}) {
@@ -86,24 +111,52 @@ function resolveConfig (input = {}) {
86
111
  const backendId = (input.backend || process.env.PATCH_BACKEND || 'php').toLowerCase()
87
112
  const backend = getBackend(backendId)
88
113
 
114
+ const profileRaw = String(input.profile ?? process.env.PATCH_PROFILE ?? '').trim()
115
+ const profile = profileRaw === '' ? null : profileRaw
116
+ if (profile !== null && !isValidProfile(profile)) {
117
+ throw new Error(`非法 profile: ${profile}(仅允许字母、数字、. _ -)`)
118
+ }
119
+
89
120
  let vcs = input.vcs || process.env.PATCH_VCS
90
121
  if (vcs !== 'svn' && vcs !== 'git') {
91
- const detected = detectVcs(sourceDir)
92
- if (!detected) {
93
- throw new Error(
94
- `无法自动检测 VCS 类型:${sourceDir}\n请指定 --vcs=svn 或 --vcs=git`
95
- )
122
+ if (input.needsVcs === false) {
123
+ // 只读 deploy 元数据的命令(如 patch-extract --list-versions)不依赖 VCS
124
+ vcs = null
125
+ } else {
126
+ const detected = detectVcs(sourceDir)
127
+ if (!detected) {
128
+ throw new Error(
129
+ `无法自动检测 VCS 类型:${sourceDir}\n请指定 --vcs=svn 或 --vcs=git`
130
+ )
131
+ }
132
+ vcs = detected
96
133
  }
97
- vcs = detected
98
134
  }
99
135
 
136
+ const applyScriptInput = input.applyScriptPath || process.env.PATCH_APPLY_SCRIPT || ''
137
+ const applyScriptPath = applyScriptInput
138
+ ? path.resolve(applyScriptInput)
139
+ : backend.getApplyScriptPath(pkgRoot)
140
+
141
+ // 受保护文件:deploy/protect.txt + --protect/--protect-file + 环境变量
142
+ const protectFiles = resolveProtectFiles({
143
+ deployDir,
144
+ protectFiles: input.protectFiles || [],
145
+ protectFile: input.protectFile || null
146
+ })
147
+
148
+ const keepVersions = parseKeepVersions(input.keepVersions ?? process.env.PATCH_KEEP_VERSIONS)
149
+ const keepOut = parseKeepVersions(
150
+ input.keepOut ?? process.env.PATCH_KEEP_OUT ?? keepVersions
151
+ )
152
+
100
153
  return {
101
154
  backend: /** @type {'php'} */ (backendId),
102
155
  vcs,
103
156
  sourceDir,
104
157
  deployDir,
105
158
  outDir,
106
- applyScriptPath: backend.getApplyScriptPath(pkgRoot),
159
+ applyScriptPath: applyScriptPath,
107
160
  fromRef: input.fromRef ?? null,
108
161
  toRef: input.toRef ?? null,
109
162
  noZip: Boolean(input.noZip),
@@ -112,10 +165,31 @@ function resolveConfig (input = {}) {
112
165
  zipPrefix: input.zipPrefix || process.env.PATCH_ZIP_PREFIX || backend.defaultZipPrefix,
113
166
  version: input.version || process.env.PATCH_VERSION || null,
114
167
  onlyFiles: input.onlyFiles || [],
115
- fileList: input.fileList || process.env.PATCH_FILE_LIST || null
168
+ fileList: input.fileList || process.env.PATCH_FILE_LIST || null,
169
+ noArchive: Boolean(input.noArchive || process.env.PATCH_NO_ARCHIVE === 'true'),
170
+ keepVersions,
171
+ pruneOut: Boolean(input.pruneOut || process.env.PATCH_PRUNE_OUT === 'true'),
172
+ keepOut,
173
+ archiveLink: Boolean(input.archiveLink || process.env.PATCH_ARCHIVE_LINK === 'true'),
174
+ fromWorktree: Boolean(input.fromWorktree || process.env.PATCH_FROM_WORKTREE === 'true'),
175
+ profile,
176
+ protectFiles,
177
+ diffWorktree: Boolean(input.diffWorktree || process.env.PATCH_DIFF_WORKTREE === 'true')
116
178
  }
117
179
  }
118
180
 
181
+ /**
182
+ * @param {unknown} value
183
+ * @returns {number}
184
+ */
185
+ function parseKeepVersions (value) {
186
+ const n = parseInt(String(value ?? '10'), 10)
187
+ if (!Number.isFinite(n) || n < 1) {
188
+ return 10
189
+ }
190
+ return n
191
+ }
192
+
119
193
  /**
120
194
  * 初始化 PHP 后端 deploy 目录结构
121
195
  * @param {string} deployDir
@@ -137,13 +211,25 @@ function initDeployDir (deployDir, vcs = 'svn') {
137
211
  ## 基准文件
138
212
 
139
213
  - \`.last-deploy-marker\`:上次成功上线标记,格式 \`svn:467\` 或 \`git:abc123...\`
214
+ - \`.last-deploy-marker.<profile>\`:多环境基准(如 \`.last-deploy-marker.php85\`)
140
215
  - \`versions.json\`:版本号与 patch 目录映射(\`patch-build --version=1.2.3\`)
141
216
  - 兼容旧版 SVN:\`.last-deploy-rev\`(仅数字)
142
217
 
218
+ ## 受保护文件(可选)
219
+
220
+ 新建 \`deploy/protect.txt\`,每行一个相对路径(\`#\` 注释):
221
+
222
+ \`\`\`text
223
+ # 运行时被程序改写、线上已存在时不覆盖
224
+ config/date_config.json
225
+ \`\`\`
226
+
143
227
  ## 本机打包
144
228
 
145
229
  \`\`\`bash
146
230
  npx patch-build --vcs=${vcs}
231
+ npx patch-build --vcs=${vcs} --profile=php85 # 预发环境
232
+ npx patch-build --vcs=${vcs} --worktree-diff # SVN:直接打包工作副本改动
147
233
  \`\`\`
148
234
 
149
235
  ## 服务器应用
@@ -162,5 +248,6 @@ module.exports = {
162
248
  detectVcs,
163
249
  resolveConfig,
164
250
  initDeployDir,
165
- isSvnWorkingCopy
251
+ isSvnWorkingCopy,
252
+ parseKeepVersions
166
253
  }
@@ -9,8 +9,30 @@ const { getBackend } = require('./backends')
9
9
  const { createZipFromDirectory } = require('./zip')
10
10
  const { resolveSelectedFiles, filterFilesBySelection, sanitizeVersionLabel } = require('./file-filter')
11
11
  const { findVersionRecord, registerVersion } = require('./version-registry')
12
+ const { readModesFile, writeModesFile } = require('./modes')
13
+ const { readProtectListFromFile, writeProtectFile, PROTECT_FILE } = require('./protect')
12
14
 
13
- const { readManifestFiles } = require('./manifest')
15
+ const { readManifestFiles, readManifestDeleted } = require('./manifest')
16
+
17
+ /**
18
+ * 读取源包 VERSION.txt 中的 version(用于 --from-patch 时保留版本上下文)
19
+ * @param {string} patchDir
20
+ * @returns {string|null}
21
+ */
22
+ function readSourceVersion (patchDir) {
23
+ const versionPath = path.join(patchDir, 'VERSION.txt')
24
+ if (!fs.existsSync(versionPath)) {
25
+ return null
26
+ }
27
+
28
+ for (const line of fs.readFileSync(versionPath, 'utf8').split(/\r?\n/)) {
29
+ const match = line.trim().match(/^version=(.+)$/)
30
+ if (match && match[1].trim()) {
31
+ return match[1].trim()
32
+ }
33
+ }
34
+ return null
35
+ }
14
36
 
15
37
  /**
16
38
  * 解析源 patch 目录(--from-patch 或 --version 查注册表)
@@ -84,12 +106,16 @@ async function extractPatchSubset (config) {
84
106
  subsetLabel,
85
107
  noZip = false,
86
108
  zipPrefix = 'backend-update',
87
- registerSubset = false
109
+ registerSubset = false,
110
+ protectFiles = []
88
111
  } = config
89
112
 
90
113
  const sourcePatchDir = resolveSourcePatchDir({ deployDir, fromPatch, version })
91
114
  const allFiles = readManifestFiles(sourcePatchDir)
92
115
  const selected = resolveSelectedFiles(onlyFiles, fileList)
116
+ // 源包版本:优先 CLI --version,其次源包 VERSION.txt(--from-patch 场景)
117
+ const sourceVersion = version || readSourceVersion(sourcePatchDir)
118
+ const versionTxt = sourceVersion ? sanitizeVersionLabel(sourceVersion) : 'unknown'
93
119
 
94
120
  if (selected.length === 0) {
95
121
  throw new Error('请指定 --only=<文件> 或 --file-list=<列表文件> 以提取子集')
@@ -106,11 +132,15 @@ async function extractPatchSubset (config) {
106
132
 
107
133
  const label = subsetLabel || `partial-${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}`
108
134
  const safeLabel = sanitizeVersionLabel(label)
109
- const patchName = version
110
- ? `patch-v${sanitizeVersionLabel(version)}-${safeLabel}`
135
+ const sourceVersionLabel = sourceVersion ? versionTxt : null
136
+ const patchName = sourceVersionLabel
137
+ ? `patch-v${sourceVersionLabel}-${safeLabel}`
111
138
  : `patch-${safeLabel}`
112
139
  const patchDir = path.join(outDir, patchName)
113
- const zipPath = path.join(outDir, `${zipPrefix}-${safeLabel}.zip`)
140
+ const zipPath = path.join(
141
+ outDir,
142
+ `${zipPrefix}-${sourceVersionLabel ? `${sourceVersionLabel}-` : ''}${safeLabel}.zip`
143
+ )
114
144
 
115
145
  await fse.emptyDir(patchDir)
116
146
 
@@ -126,11 +156,55 @@ async function extractPatchSubset (config) {
126
156
 
127
157
  await fse.copy(applyScriptPath, path.join(patchDir, 'apply-update.php'))
128
158
 
129
- const versionTxt = version ? sanitizeVersionLabel(version) : 'unknown'
159
+ // 保护清单:源包 PROTECT.txt ∪ 当前项目配置(deploy/protect.txt + --protect)
160
+ /** @type {Set<string>} */
161
+ const protectSet = new Set()
162
+ const sourceProtect = path.join(sourcePatchDir, PROTECT_FILE)
163
+ if (fs.existsSync(sourceProtect)) {
164
+ for (const rel of readProtectListFromFile(sourceProtect)) {
165
+ protectSet.add(rel)
166
+ }
167
+ }
168
+ for (const rel of protectFiles) {
169
+ if (rel) protectSet.add(rel)
170
+ }
171
+ writeProtectFile(patchDir, [...protectSet].sort())
172
+
173
+ // 删除清单按本次提取范围过滤:子集包不应提示删除与本次热修复无关的文件
174
+ const sourceDeleted = readManifestDeleted(sourcePatchDir)
175
+ const deletedMatched = sourceDeleted.length > 0
176
+ ? filterFilesBySelection(sourceDeleted, selected).matched
177
+ : []
178
+ if (deletedMatched.length > 0) {
179
+ fs.writeFileSync(
180
+ path.join(patchDir, 'MANIFEST-deleted.txt'),
181
+ deletedMatched.join('\n'),
182
+ 'utf8'
183
+ )
184
+ }
185
+
186
+ // 可执行位:优先读源包 MODES.txt;Linux 上再结合实际文件权限
187
+ const modes = readModesFile(sourcePatchDir)
188
+ if (process.platform !== 'win32') {
189
+ for (const rel of matched) {
190
+ const abs = path.join(sourcePatchDir, rel)
191
+ try {
192
+ const stat = fs.statSync(abs)
193
+ if ((stat.mode & 0o111) !== 0) {
194
+ modes[rel] = 0o755
195
+ }
196
+ } catch {
197
+ // 忽略无法读取的文件
198
+ }
199
+ }
200
+ }
201
+ const executableFiles = matched.filter(rel => modes[rel] === 0o755)
202
+ writeModesFile(patchDir, executableFiles)
203
+
130
204
  const manifestLines = [
131
205
  '# PHP 后端增量部署清单(子集提取)',
132
206
  `extract_mode=partial`,
133
- version ? `source_version=${versionTxt}` : `source_patch=${sourcePatchDir}`,
207
+ sourceVersionLabel ? `source_version=${sourceVersionLabel}` : `source_patch=${sourcePatchDir}`,
134
208
  `extract_label=${label}`,
135
209
  `generated_at=${new Date().toISOString().replace('T', ' ').slice(0, 19)}`,
136
210
  '',
@@ -139,11 +213,19 @@ async function extractPatchSubset (config) {
139
213
  ]
140
214
 
141
215
  fs.writeFileSync(path.join(patchDir, 'MANIFEST.txt'), manifestLines.join('\n'), 'utf8')
216
+
217
+ // 子集包使用独立的版本标识(<源版本>-<标签>),避免服务器把它当成完整版本,
218
+ // 回滚时也不会误用部分部署的备份
219
+ const subsetVersion = sourceVersionLabel
220
+ ? `${sourceVersionLabel}-${safeLabel}`
221
+ : safeLabel
142
222
  fs.writeFileSync(
143
223
  path.join(patchDir, 'VERSION.txt'),
144
224
  [
145
- version ? `version=${versionTxt}` : '',
225
+ `version=${subsetVersion}`,
226
+ sourceVersionLabel ? `source_version=${sourceVersionLabel}` : '',
146
227
  `subset=${label}`,
228
+ 'partial=1',
147
229
  `file_count=${matched.length}`
148
230
  ].filter(Boolean).join('\n'),
149
231
  'utf8'
@@ -151,23 +233,24 @@ async function extractPatchSubset (config) {
151
233
 
152
234
  let zipSize = 0
153
235
  if (!noZip) {
154
- const zipResult = await createZipFromDirectory(patchDir, zipPath)
236
+ const zipResult = await createZipFromDirectory(patchDir, zipPath, { modes })
155
237
  zipSize = zipResult.size
156
238
  }
157
239
 
158
- if (registerSubset && version) {
240
+ if (registerSubset && sourceVersionLabel) {
241
+ const baseRecord = findVersionRecord(deployDir, version || sourceVersionLabel)
159
242
  registerVersion(deployDir, {
160
- version: `${version}-${label}`,
161
- versionLabel: `${sanitizeVersionLabel(version)}-${safeLabel}`,
162
- vcs: findVersionRecord(deployDir, version)?.vcs || 'svn',
163
- fromLabel: findVersionRecord(deployDir, version)?.fromLabel || '',
164
- toLabel: findVersionRecord(deployDir, version)?.toLabel || '',
243
+ version: `${sourceVersionLabel}-${label}`,
244
+ versionLabel: `${sourceVersionLabel}-${safeLabel}`,
245
+ vcs: baseRecord?.vcs || 'svn',
246
+ fromLabel: baseRecord?.fromLabel || '',
247
+ toLabel: baseRecord?.toLabel || '',
165
248
  files: matched,
166
- deleted: [],
249
+ deleted: deletedMatched,
167
250
  patchDir,
168
251
  zipPath: noZip ? undefined : zipPath,
169
252
  partial: true,
170
- sourceVersion: version,
253
+ sourceVersion: sourceVersionLabel,
171
254
  createdAt: new Date().toISOString()
172
255
  })
173
256
  }
@@ -128,6 +128,25 @@ function filterFilesBySelection (allFiles, selected) {
128
128
  }
129
129
  }
130
130
 
131
+ /**
132
+ * 判断是否为安全的包内相对路径(拒绝绝对路径与 ../ 逃逸)
133
+ * @param {string} relativePath
134
+ * @returns {boolean}
135
+ */
136
+ function isSafeRelativePath (relativePath) {
137
+ const raw = String(relativePath)
138
+ if (raw === '' || raw.includes('\0')) {
139
+ return false
140
+ }
141
+
142
+ const normalized = raw.replace(/\\/g, '/')
143
+ if (normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized)) {
144
+ return false
145
+ }
146
+
147
+ return !normalized.split('/').some(segment => segment === '..')
148
+ }
149
+
131
150
  /**
132
151
  * 清理版本号用于目录/zip 命名
133
152
  * @param {string} version
@@ -143,5 +162,6 @@ module.exports = {
143
162
  readFileListFromPath,
144
163
  resolveSelectedFiles,
145
164
  filterFilesBySelection,
165
+ isSafeRelativePath,
146
166
  sanitizeVersionLabel
147
167
  }
package/lib/git.js CHANGED
@@ -86,30 +86,67 @@ function resolveGitRef (sourceDir, ref, gitExe) {
86
86
  * @typedef {{ action: 'A'|'M'|'D', relativePath: string, parseError?: string }} DiffEntry
87
87
  */
88
88
 
89
+ /**
90
+ * 将 git 输出的仓库根相对路径转换为 sourceDir 相对路径
91
+ * @param {string} repoPath
92
+ * @param {string} [prefix] sourceDir 相对仓库根的路径(可为空)
93
+ * @returns {string|null} 不在 prefix 下时返回 null
94
+ */
95
+ function repoPathToSourceRelative (repoPath, prefix = '') {
96
+ const norm = repoPath.trim().replace(/\\/g, '/')
97
+ if (!prefix) {
98
+ return norm
99
+ }
100
+
101
+ const base = prefix.replace(/\\/g, '/').replace(/\/$/, '')
102
+ if (norm === base) {
103
+ return ''
104
+ }
105
+ if (norm.startsWith(base + '/')) {
106
+ return norm.slice(base.length + 1)
107
+ }
108
+
109
+ return null
110
+ }
111
+
89
112
  /**
90
113
  * Git diff --name-status from..to
91
114
  * @param {object} options
92
115
  * @param {string} options.sourceDir
93
116
  * @param {string} options.fromRef
94
117
  * @param {string} options.toRef
118
+ * @param {string} [options.prefix] sourceDir 相对仓库根的路径(非仓库根时必填)
95
119
  * @param {string} [options.gitExe]
96
120
  * @returns {DiffEntry[]}
97
121
  */
98
- function getGitDiffSummary ({ sourceDir, fromRef, toRef, gitExe }) {
122
+ function getGitDiffSummary ({ sourceDir, fromRef, toRef, prefix = '', gitExe }) {
99
123
  const exe = gitExe || findGitExe()
100
124
  const root = runGit(exe, ['rev-parse', '--show-toplevel'], sourceDir).trim()
101
125
  const fromCommit = resolveGitRef(sourceDir, fromRef, exe)
102
126
  const toCommit = resolveGitRef(sourceDir, toRef, exe)
103
127
 
128
+ // core.quotepath=false:避免中文等路径被转义成 "app/\344\270\255.php"
104
129
  const output = runGit(
105
130
  exe,
106
- ['diff', '--name-status', `${fromCommit}..${toCommit}`],
131
+ ['-c', 'core.quotepath=false', 'diff', '--name-status', `${fromCommit}..${toCommit}`],
107
132
  root
108
133
  )
109
134
 
110
135
  /** @type {DiffEntry[]} */
111
136
  const entries = []
112
137
 
138
+ /**
139
+ * @param {'A'|'M'|'D'} action
140
+ * @param {string} repoPath
141
+ */
142
+ const push = (action, repoPath) => {
143
+ const rel = repoPathToSourceRelative(repoPath, prefix)
144
+ if (!rel) {
145
+ return
146
+ }
147
+ entries.push({ action, relativePath: rel })
148
+ }
149
+
113
150
  for (const line of output.split(/\r?\n/)) {
114
151
  if (!line.trim()) continue
115
152
 
@@ -118,44 +155,142 @@ function getGitDiffSummary ({ sourceDir, fromRef, toRef, gitExe }) {
118
155
  const status = parts[0]
119
156
 
120
157
  if (/^[AMD]$/.test(status)) {
121
- entries.push({
122
- action: /** @type {'A'|'M'|'D'} */ (status),
123
- relativePath: parts[1].replace(/\\/g, '/')
124
- })
158
+ push(/** @type {'A'|'M'|'D'} */ (status), parts[1])
125
159
  continue
126
160
  }
127
161
 
128
162
  if (/^[RC]\d+$/.test(status) && parts.length >= 3) {
129
- entries.push({
130
- action: 'M',
131
- relativePath: parts[2].replace(/\\/g, '/')
132
- })
133
- entries.push({
134
- action: 'D',
135
- relativePath: parts[1].replace(/\\/g, '/')
136
- })
163
+ push('M', parts[2])
164
+ push('D', parts[1])
137
165
  continue
138
166
  }
139
167
 
140
168
  // 类型变更(如文件 ↔ 符号链接)
141
169
  if (/^T\d*$/.test(status) && parts.length >= 2) {
170
+ push('M', parts[1])
171
+ continue
172
+ }
173
+
174
+ const rel = repoPathToSourceRelative(parts[parts.length - 1], prefix)
175
+ if (rel) {
142
176
  entries.push({
143
177
  action: 'M',
144
- relativePath: parts[1].replace(/\\/g, '/')
178
+ relativePath: rel,
179
+ parseError: `未识别的 git diff 行:${line}`
145
180
  })
146
- continue
147
181
  }
148
-
149
- entries.push({
150
- action: 'M',
151
- relativePath: parts[parts.length - 1].replace(/\\/g, '/'),
152
- parseError: `未识别的 git diff 行:${line}`
153
- })
154
182
  }
155
183
 
156
184
  return entries
157
185
  }
158
186
 
187
+ /**
188
+ * 检查待打包文件的工作区内容是否与目标 commit 一致
189
+ *
190
+ * 打包是从工作区复制文件的;若工作区未同步到目标 commit(或存在未提交改动),
191
+ * 包内容就会与 MANIFEST 声明的版本范围不符。
192
+ *
193
+ * @param {object} options
194
+ * @param {string} options.sourceDir
195
+ * @param {string} options.toRef 目标 commit/tag
196
+ * @param {string[]} options.files sourceDir 相对路径
197
+ * @param {string} [options.prefix]
198
+ * @param {string} [options.gitExe]
199
+ * @returns {string[]} 内容不一致的文件(sourceDir 相对路径)
200
+ */
201
+ function getGitContentMismatch ({ sourceDir, toRef, files, prefix = '', gitExe }) {
202
+ if (!files || files.length === 0) {
203
+ return []
204
+ }
205
+
206
+ const exe = gitExe || findGitExe()
207
+ const root = runGit(exe, ['rev-parse', '--show-toplevel'], sourceDir).trim()
208
+ const toCommit = resolveGitRef(sourceDir, toRef, exe)
209
+ const repoPaths = files.map(f => (prefix ? `${prefix}/${f}` : f))
210
+
211
+ /** @type {Set<string>} */
212
+ const mismatched = new Set()
213
+ const chunkSize = 100
214
+
215
+ for (let i = 0; i < repoPaths.length; i += chunkSize) {
216
+ const chunk = repoPaths.slice(i, i + chunkSize)
217
+ const output = runGit(
218
+ exe,
219
+ ['-c', 'core.quotepath=false', 'diff', '--name-only', toCommit, '--', ...chunk],
220
+ root
221
+ )
222
+
223
+ for (const line of output.split(/\r?\n/)) {
224
+ if (!line.trim()) continue
225
+ const rel = repoPathToSourceRelative(line, prefix)
226
+ if (rel) {
227
+ mismatched.add(rel)
228
+ }
229
+ }
230
+ }
231
+
232
+ return [...mismatched].sort()
233
+ }
234
+
235
+ /**
236
+ * 读取待打包文件中在 Git 索引里标记为可执行(100755)的路径
237
+ *
238
+ * Windows 上 fs.stat 不体现执行位,跨平台打包时需依赖 Git 索引模式。
239
+ *
240
+ * @param {object} options
241
+ * @param {string} options.sourceDir
242
+ * @param {string[]} options.files sourceDir 相对路径
243
+ * @param {string} [options.prefix]
244
+ * @param {string} [options.gitExe]
245
+ * @returns {string[]}
246
+ */
247
+ function getGitExecutableFiles ({ sourceDir, files, prefix = '', gitExe }) {
248
+ if (!files || files.length === 0) {
249
+ return []
250
+ }
251
+
252
+ const exe = gitExe || findGitExe()
253
+ const root = runGit(exe, ['rev-parse', '--show-toplevel'], sourceDir).trim()
254
+ const repoPaths = files.map(f => (prefix ? `${prefix}/${f}` : f))
255
+
256
+ /** @type {Set<string>} */
257
+ const executable = new Set()
258
+ const chunkSize = 100
259
+
260
+ for (let i = 0; i < repoPaths.length; i += chunkSize) {
261
+ const chunk = repoPaths.slice(i, i + chunkSize)
262
+ const output = runGit(
263
+ exe,
264
+ ['-c', 'core.quotepath=false', 'ls-files', '-s', '--', ...chunk],
265
+ root
266
+ )
267
+
268
+ for (const line of output.split(/\r?\n/)) {
269
+ if (!line.trim()) continue
270
+ // <mode> <sha> <stage>\t<path>
271
+ const match = line.match(/^(\d{6})\s+\S+\s+\d+\t(.+)$/)
272
+ if (!match || match[1] !== '100755') continue
273
+ const rel = repoPathToSourceRelative(match[2], prefix)
274
+ if (rel) {
275
+ executable.add(rel)
276
+ }
277
+ }
278
+ }
279
+
280
+ return [...executable].sort()
281
+ }
282
+
283
+ /**
284
+ * 计算 sourceDir 相对 git 仓库根的路径(用于把 git 输出映射回源码目录)
285
+ * @param {string} root
286
+ * @param {string} sourceDir
287
+ * @returns {string}
288
+ */
289
+ function getGitPrefix (root, sourceDir) {
290
+ const rel = path.relative(path.resolve(root), path.resolve(sourceDir)).replace(/\\/g, '/')
291
+ return rel === '.' || rel === '' ? '' : rel
292
+ }
293
+
159
294
  /**
160
295
  * 判断目录是否在 Git 工作区内(Git 未安装时返回 false,不抛错)
161
296
  * @param {string} dir
@@ -177,5 +312,9 @@ module.exports = {
177
312
  getGitInfo,
178
313
  resolveGitRef,
179
314
  getGitDiffSummary,
315
+ getGitContentMismatch,
316
+ getGitExecutableFiles,
317
+ getGitPrefix,
318
+ repoPathToSourceRelative,
180
319
  isGitRepository
181
320
  }