vcs-patch-deploy 1.0.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/git.js ADDED
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Git 命令封装 — 增量 diff 与 commit 解析
3
+ */
4
+
5
+ const { execFileSync, execSync } = require('child_process')
6
+ const fs = require('fs')
7
+ const path = require('path')
8
+
9
+ /**
10
+ * @returns {string}
11
+ */
12
+ function findGitExe () {
13
+ if (process.env.GIT_EXE && fs.existsSync(process.env.GIT_EXE)) {
14
+ return process.env.GIT_EXE
15
+ }
16
+
17
+ try {
18
+ const which = process.platform === 'win32' ? 'where' : 'command -v'
19
+ const result = execSync(`${which} git`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] })
20
+ const first = result.split(/\r?\n/).find(Boolean)
21
+ if (first) return first.trim()
22
+ } catch {
23
+ // ignore
24
+ }
25
+
26
+ throw new Error('未找到 git 可执行文件,请安装 Git 并加入 PATH,或设置环境变量 GIT_EXE')
27
+ }
28
+
29
+ /**
30
+ * @param {string} gitExe
31
+ * @param {string[]} args
32
+ * @param {string} cwd
33
+ * @returns {string}
34
+ */
35
+ function runGit (gitExe, args, cwd) {
36
+ try {
37
+ return execFileSync(gitExe, args, {
38
+ cwd,
39
+ encoding: 'utf8',
40
+ stdio: ['pipe', 'pipe', 'pipe']
41
+ })
42
+ } catch (error) {
43
+ const stderr = error.stderr ? error.stderr.toString() : ''
44
+ const stdout = error.stdout ? error.stdout.toString() : ''
45
+ throw new Error([stdout, stderr, error.message].filter(Boolean).join('\n'))
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {string} sourceDir Git 仓库根或子目录
51
+ * @param {string} [gitExe]
52
+ * @returns {{ commit: string, shortCommit: string, root: string }}
53
+ */
54
+ function getGitInfo (sourceDir, gitExe = findGitExe()) {
55
+ const root = runGit(gitExe, ['rev-parse', '--show-toplevel'], sourceDir).trim()
56
+ const commit = runGit(gitExe, ['rev-parse', 'HEAD'], sourceDir).trim()
57
+ const shortCommit = runGit(gitExe, ['rev-parse', '--short', 'HEAD'], sourceDir).trim()
58
+
59
+ return { commit, shortCommit, root }
60
+ }
61
+
62
+ /**
63
+ * @param {string} sourceDir
64
+ * @param {string} ref
65
+ * @param {string} [gitExe]
66
+ * @returns {string} 完整 commit hash
67
+ */
68
+ function resolveGitRef (sourceDir, ref, gitExe = findGitExe()) {
69
+ return runGit(gitExe, ['rev-parse', ref], sourceDir).trim()
70
+ }
71
+
72
+ /**
73
+ * @typedef {{ action: 'A'|'M'|'D', relativePath: string, parseError?: string }} DiffEntry
74
+ */
75
+
76
+ /**
77
+ * Git diff --name-status from..to
78
+ * @param {object} options
79
+ * @param {string} options.sourceDir
80
+ * @param {string} options.fromRef
81
+ * @param {string} options.toRef
82
+ * @param {string} [options.gitExe]
83
+ * @returns {DiffEntry[]}
84
+ */
85
+ function getGitDiffSummary ({ sourceDir, fromRef, toRef, gitExe = findGitExe() }) {
86
+ const root = runGit(gitExe, ['rev-parse', '--show-toplevel'], sourceDir).trim()
87
+ const fromCommit = resolveGitRef(sourceDir, fromRef, gitExe)
88
+ const toCommit = resolveGitRef(sourceDir, toRef, gitExe)
89
+
90
+ const output = runGit(
91
+ gitExe,
92
+ ['diff', '--name-status', `${fromCommit}..${toCommit}`],
93
+ root
94
+ )
95
+
96
+ /** @type {DiffEntry[]} */
97
+ const entries = []
98
+
99
+ for (const line of output.split(/\r?\n/)) {
100
+ if (!line.trim()) continue
101
+
102
+ // M\tpath | A\tpath | D\tpath | R100\told\tnew | C100\told\tnew
103
+ const parts = line.split('\t')
104
+ const status = parts[0]
105
+
106
+ if (/^[AMD]$/.test(status)) {
107
+ entries.push({
108
+ action: /** @type {'A'|'M'|'D'} */ (status),
109
+ relativePath: parts[1].replace(/\\/g, '/')
110
+ })
111
+ continue
112
+ }
113
+
114
+ if (/^[RC]\d+$/.test(status) && parts.length >= 3) {
115
+ entries.push({
116
+ action: 'M',
117
+ relativePath: parts[2].replace(/\\/g, '/')
118
+ })
119
+ entries.push({
120
+ action: 'D',
121
+ relativePath: parts[1].replace(/\\/g, '/')
122
+ })
123
+ continue
124
+ }
125
+
126
+ entries.push({
127
+ action: 'M',
128
+ relativePath: parts[parts.length - 1].replace(/\\/g, '/'),
129
+ parseError: `未识别的 git diff 行:${line}`
130
+ })
131
+ }
132
+
133
+ return entries
134
+ }
135
+
136
+ /**
137
+ * 判断目录是否在 Git 工作区内
138
+ * @param {string} dir
139
+ * @param {string} [gitExe]
140
+ */
141
+ function isGitRepository (dir, gitExe = findGitExe()) {
142
+ try {
143
+ runGit(gitExe, ['rev-parse', '--is-inside-work-tree'], dir)
144
+ return true
145
+ } catch {
146
+ return false
147
+ }
148
+ }
149
+
150
+ module.exports = {
151
+ findGitExe,
152
+ runGit,
153
+ getGitInfo,
154
+ resolveGitRef,
155
+ getGitDiffSummary,
156
+ isGitRepository
157
+ }
package/lib/index.js ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * vcs-patch-deploy 主入口
3
+ */
4
+
5
+ const { buildPatch } = require('./build-patch')
6
+ const { resolveConfig, detectVcs, initDeployDir } = require('./config')
7
+ const { readDeployMarker, writeDeployMarker } = require('./marker')
8
+ const { shouldExcludePath } = require('./exclude')
9
+ const { getBackend, BACKENDS } = require('./backends')
10
+ const svn = require('./svn')
11
+ const git = require('./git')
12
+ const { createZipFromDirectory } = require('./zip')
13
+
14
+ module.exports = {
15
+ buildPatch,
16
+ resolveConfig,
17
+ initDeployDir,
18
+ detectVcs,
19
+ readDeployMarker,
20
+ writeDeployMarker,
21
+ shouldExcludePath,
22
+ getBackend,
23
+ BACKENDS,
24
+ createZipFromDirectory,
25
+ svn,
26
+ git
27
+ }
package/lib/marker.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * 上次成功上线基准标记(统一 SVN / Git)
3
+ *
4
+ * 主文件 `.last-deploy-marker` 格式(单行):
5
+ * svn:467
6
+ * git:abc123def456789...
7
+ *
8
+ * 兼容 KJCG 旧版:若无 marker 则读取 `.last-deploy-rev`(仅 SVN)
9
+ */
10
+
11
+ const fs = require('fs')
12
+ const path = require('path')
13
+
14
+ const MARKER_FILE = '.last-deploy-marker'
15
+ const LEGACY_SVN_FILE = '.last-deploy-rev'
16
+
17
+ /**
18
+ * @param {string} deployDir
19
+ * @returns {{ vcs: 'svn'|'git', value: string } | null}
20
+ */
21
+ function readDeployMarker (deployDir) {
22
+ const markerPath = path.join(deployDir, MARKER_FILE)
23
+ if (fs.existsSync(markerPath)) {
24
+ const line = fs.readFileSync(markerPath, 'utf8').trim()
25
+ const match = line.match(/^(svn|git):(.+)$/)
26
+ if (match) {
27
+ return { vcs: /** @type {'svn'|'git'} */ (match[1]), value: match[2].trim() }
28
+ }
29
+ }
30
+
31
+ const legacyPath = path.join(deployDir, LEGACY_SVN_FILE)
32
+ if (fs.existsSync(legacyPath)) {
33
+ const rev = fs.readFileSync(legacyPath, 'utf8').trim()
34
+ if (/^\d+$/.test(rev)) {
35
+ return { vcs: 'svn', value: rev }
36
+ }
37
+ }
38
+
39
+ return null
40
+ }
41
+
42
+ /**
43
+ * @param {string} deployDir
44
+ * @param {'svn'|'git'} vcs
45
+ * @param {string} value
46
+ */
47
+ function writeDeployMarker (deployDir, vcs, value) {
48
+ fs.mkdirSync(deployDir, { recursive: true })
49
+ fs.writeFileSync(path.join(deployDir, MARKER_FILE), `${vcs}:${value}`, 'utf8')
50
+
51
+ // SVN 兼容:同步写旧文件
52
+ if (vcs === 'svn') {
53
+ fs.writeFileSync(path.join(deployDir, LEGACY_SVN_FILE), value, 'utf8')
54
+ }
55
+ }
56
+
57
+ module.exports = {
58
+ MARKER_FILE,
59
+ LEGACY_SVN_FILE,
60
+ readDeployMarker,
61
+ writeDeployMarker
62
+ }
package/lib/svn.js ADDED
@@ -0,0 +1,181 @@
1
+ /**
2
+ * SVN 命令封装
3
+ */
4
+
5
+ const { execFileSync, execSync } = require('child_process')
6
+ const fs = require('fs')
7
+ const path = require('path')
8
+ const os = require('os')
9
+
10
+ /**
11
+ * 查找 svn 可执行文件
12
+ * @returns {string}
13
+ */
14
+ function findSvnExe () {
15
+ if (process.env.SVN_EXE && fs.existsSync(process.env.SVN_EXE)) {
16
+ return process.env.SVN_EXE
17
+ }
18
+
19
+ try {
20
+ const which = process.platform === 'win32' ? 'where' : 'command -v'
21
+ const result = execSync(`${which} svn`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] })
22
+ const first = result.split(/\r?\n/).find(Boolean)
23
+ if (first) return first.trim()
24
+ } catch {
25
+ // ignore
26
+ }
27
+
28
+ if (process.platform === 'win32') {
29
+ const candidates = [
30
+ 'C:\\Program Files\\TortoiseSVN\\bin\\svn.exe',
31
+ 'C:\\Program Files\\SlikSvn\\bin\\svn.exe',
32
+ 'C:\\Program Files\\VisualSVN Server\\bin\\svn.exe'
33
+ ]
34
+ for (const p of candidates) {
35
+ if (fs.existsSync(p)) return p
36
+ }
37
+ }
38
+
39
+ throw new Error('未找到 svn 可执行文件,请安装 TortoiseSVN/SlikSVN 并加入 PATH,或设置环境变量 SVN_EXE')
40
+ }
41
+
42
+ /**
43
+ * @param {string} svnExe
44
+ * @param {string[]} args
45
+ * @param {string} cwd
46
+ * @returns {string}
47
+ */
48
+ function runSvn (svnExe, args, cwd) {
49
+ try {
50
+ return execFileSync(svnExe, args, {
51
+ cwd,
52
+ encoding: 'utf8',
53
+ stdio: ['pipe', 'pipe', 'pipe']
54
+ })
55
+ } catch (error) {
56
+ const stderr = error.stderr ? error.stderr.toString() : ''
57
+ const stdout = error.stdout ? error.stdout.toString() : ''
58
+ throw new Error([stdout, stderr, error.message].filter(Boolean).join('\n'))
59
+ }
60
+ }
61
+
62
+ /**
63
+ * @param {string} sourceDir SVN 源码目录(如 trunk)
64
+ * @returns {{ revision: number, wcRoot: string }}
65
+ */
66
+ function getSvnInfo (sourceDir, svnExe = findSvnExe()) {
67
+ const output = runSvn(svnExe, ['info', sourceDir], sourceDir)
68
+ const revMatch = output.match(/^Revision:\s*(\d+)/m)
69
+ const wcMatch = output.match(/^Working Copy Root Path:\s*(.+)$/m)
70
+
71
+ if (!revMatch) {
72
+ throw new Error(`无法读取 SVN revision:${sourceDir}`)
73
+ }
74
+
75
+ return {
76
+ revision: parseInt(revMatch[1], 10),
77
+ wcRoot: wcMatch ? wcMatch[1].trim() : sourceDir
78
+ }
79
+ }
80
+
81
+ /**
82
+ * 解析 svn diff --summarize 输出中的相对路径
83
+ * @param {string} rawPath
84
+ * @param {string} sourceDir
85
+ * @param {string} svnRoot
86
+ */
87
+ function normalizeRelativePath (rawPath, sourceDir, svnRoot) {
88
+ const trunkNorm = path.resolve(sourceDir).replace(/\\/g, '/').replace(/\/$/, '')
89
+ const svnNorm = path.resolve(svnRoot).replace(/\\/g, '/').replace(/\/$/, '')
90
+ let normalized = rawPath.trim().replace(/\\/g, '/').replace(/\/$/, '')
91
+
92
+ if (normalized.toLowerCase().startsWith(trunkNorm.toLowerCase())) {
93
+ return normalized.slice(trunkNorm.length).replace(/^\//, '')
94
+ }
95
+
96
+ if (normalized.toLowerCase().startsWith(svnNorm.toLowerCase())) {
97
+ const rest = normalized.slice(svnNorm.length).replace(/^\//, '')
98
+ const trunkMatch = rest.match(/^trunk\/(.+)$/)
99
+ return trunkMatch ? trunkMatch[1] : rest
100
+ }
101
+
102
+ const trunkMatch = normalized.match(/^trunk\/(.+)$/)
103
+ if (trunkMatch) return trunkMatch[1]
104
+
105
+ throw new Error(`无法解析 SVN 路径:${rawPath}`)
106
+ }
107
+
108
+ /**
109
+ * @typedef {{ action: 'A'|'M'|'D', relativePath: string }} DiffEntry
110
+ */
111
+
112
+ /**
113
+ * @param {object} options
114
+ * @param {string} options.sourceDir
115
+ * @param {number} options.fromRev
116
+ * @param {number} options.toRev
117
+ * @param {string} [options.svnExe]
118
+ * @returns {DiffEntry[]}
119
+ */
120
+ function getSvnDiffSummary ({ sourceDir, fromRev, toRev, svnExe = findSvnExe() }) {
121
+ const svnRoot = path.dirname(sourceDir) // 常见 layout: BackendSVN/trunk
122
+ const output = runSvn(
123
+ svnExe,
124
+ ['diff', '-r', `${fromRev}:${toRev}`, '--summarize', sourceDir],
125
+ svnRoot
126
+ )
127
+
128
+ /** @type {DiffEntry[]} */
129
+ const entries = []
130
+
131
+ for (const line of output.split(/\r?\n/)) {
132
+ const match = line.match(/^\s*([AMD])\s+(.+)$/)
133
+ if (!match) continue
134
+
135
+ try {
136
+ entries.push({
137
+ action: /** @type {'A'|'M'|'D'} */ (match[1]),
138
+ relativePath: normalizeRelativePath(match[2], sourceDir, svnRoot)
139
+ })
140
+ } catch (error) {
141
+ entries.push({
142
+ action: /** @type {'A'|'M'|'D'} */ (match[1]),
143
+ relativePath: match[2],
144
+ parseError: error.message
145
+ })
146
+ }
147
+ }
148
+
149
+ return entries
150
+ }
151
+
152
+ /**
153
+ * 读取上次上线 revision
154
+ * @param {string} lastRevFile
155
+ * @returns {number|null}
156
+ */
157
+ function readLastDeployRev (lastRevFile) {
158
+ if (!fs.existsSync(lastRevFile)) return null
159
+ const content = fs.readFileSync(lastRevFile, 'utf8')
160
+ const line = content.split(/\r?\n/).find(l => /^\s*\d+\s*$/.test(l))
161
+ return line ? parseInt(line.trim(), 10) : null
162
+ }
163
+
164
+ /**
165
+ * @param {string} lastRevFile
166
+ * @param {number} rev
167
+ */
168
+ function writeLastDeployRev (lastRevFile, rev) {
169
+ fs.mkdirSync(path.dirname(lastRevFile), { recursive: true })
170
+ fs.writeFileSync(lastRevFile, String(rev), 'utf8')
171
+ }
172
+
173
+ module.exports = {
174
+ findSvnExe,
175
+ runSvn,
176
+ getSvnInfo,
177
+ normalizeRelativePath,
178
+ getSvnDiffSummary,
179
+ readLastDeployRev,
180
+ writeLastDeployRev
181
+ }
package/lib/zip.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * 将 patch 目录压缩为 zip
3
+ */
4
+
5
+ const fs = require('fs')
6
+ const path = require('path')
7
+ const archiver = require('archiver')
8
+
9
+ /**
10
+ * @param {string} sourceDir patch 目录
11
+ * @param {string} zipPath 输出 zip 路径
12
+ * @returns {Promise<{ zipPath: string, size: number }>}
13
+ */
14
+ function createZipFromDirectory (sourceDir, zipPath) {
15
+ return new Promise((resolve, reject) => {
16
+ fs.mkdirSync(path.dirname(zipPath), { recursive: true })
17
+
18
+ const output = fs.createWriteStream(zipPath)
19
+ const archive = archiver('zip', { zlib: { level: 9 } })
20
+
21
+ output.on('close', () => {
22
+ resolve({ zipPath, size: archive.pointer() })
23
+ })
24
+
25
+ archive.on('error', reject)
26
+ output.on('error', reject)
27
+
28
+ archive.pipe(output)
29
+ archive.directory(sourceDir, false)
30
+ archive.finalize()
31
+ })
32
+ }
33
+
34
+ module.exports = {
35
+ createZipFromDirectory
36
+ }
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "vcs-patch-deploy",
3
+ "version": "1.0.0",
4
+ "description": "PHP 后端(ThinkPHP)增量部署包生成工具 — 支持 SVN revision 与 Git commit 差异对比,打 zip 并附带 apply-update.php,供堡垒机/Web 终端上线",
5
+ "main": "lib/index.js",
6
+ "bin": {
7
+ "patch-build": "bin/patch-build.js"
8
+ },
9
+ "scripts": {
10
+ "test": "node bin/patch-build.js --help",
11
+ "prepublishOnly": "node -e \"require('./lib/index.js')\""
12
+ },
13
+ "keywords": [
14
+ "svn",
15
+ "git",
16
+ "deploy",
17
+ "patch",
18
+ "incremental",
19
+ "vcs",
20
+ "zip",
21
+ "php",
22
+ "thinkphp",
23
+ "bastion",
24
+ "cli",
25
+ "增量部署",
26
+ "堡垒机"
27
+ ],
28
+ "author": "qingyuai",
29
+ "license": "MIT",
30
+ "engines": {
31
+ "node": ">=16.0.0"
32
+ },
33
+ "dependencies": {
34
+ "archiver": "^7.0.1",
35
+ "chalk": "^4.1.2",
36
+ "fs-extra": "^11.3.0"
37
+ },
38
+ "optionalDependencies": {
39
+ "dotenv": "^16.6.1"
40
+ },
41
+ "files": [
42
+ "bin/",
43
+ "lib/",
44
+ "assets/",
45
+ "README.md",
46
+ "LICENSE",
47
+ "env.example"
48
+ ],
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/QINGYUAI/vcs-patch-deploy.git"
52
+ },
53
+ "bugs": {
54
+ "url": "https://github.com/QINGYUAI/vcs-patch-deploy/issues"
55
+ },
56
+ "homepage": "https://github.com/QINGYUAI/vcs-patch-deploy#readme"
57
+ }