uniapp-android-cli 0.1.0 → 0.1.3
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/README.md +246 -450
- package/bin/uni-pack.js +0 -0
- package/package.json +1 -1
- package/src/cli.js +63 -5
- package/src/commands/build.js +4 -0
- package/src/commands/debug.js +103 -3
- package/src/commands/device.js +8 -2
- package/src/commands/doctor.js +10 -0
- package/src/commands/init.js +290 -79
- package/src/commands/projects.js +31 -0
- package/src/commands/wgt.js +51 -7
- package/src/core/adb.js +71 -13
- package/src/core/build.js +91 -26
- package/src/core/config.js +52 -1
- package/src/core/debugPreset.js +56 -0
- package/src/core/devicePairing.js +2 -1
- package/src/core/fsx.js +12 -1
- package/src/core/gradle.js +192 -46
- package/src/core/gradleLog.js +188 -0
- package/src/core/hash.js +18 -0
- package/src/core/hbuilderx.js +2 -0
- package/src/core/hbuilderxCli.js +168 -0
- package/src/core/initConfig.js +214 -0
- package/src/core/initEnv.js +140 -0
- package/src/core/interactive.js +93 -0
- package/src/core/output.js +123 -16
- package/src/core/patch/assets.js +63 -32
- package/src/core/patch/gradle.js +40 -2
- package/src/core/patch/template.js +28 -10
- package/src/core/patch/utsPlugins.js +1 -0
- package/src/core/process.js +66 -17
- package/src/core/project.js +13 -0
- package/src/core/resourceVersion.js +87 -0
- package/src/core/sdk.js +6 -1
- package/src/core/signing.js +24 -6
- package/src/core/templateCache.js +81 -0
- package/src/core/webBuild.js +10 -2
- package/src/core/wgt.js +47 -25
- package/src/core/workdir.js +44 -0
package/src/core/build.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { copyFile, readdir } from 'node:fs/promises'
|
|
1
|
+
import { copyFile, readdir, rm } from 'node:fs/promises'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { PackError, EXIT } from './errors.js'
|
|
4
4
|
import { emptyDir, ensureDir, exists } from './fsx.js'
|
|
@@ -9,10 +9,12 @@ import { patchAppGradle, patchRootGradle } from './patch/gradle.js'
|
|
|
9
9
|
import { applyAssets } from './patch/assets.js'
|
|
10
10
|
import { applyNativePlugins } from './patch/nativePlugins.js'
|
|
11
11
|
import { mergeProjectManifest } from './patch/projectManifest.js'
|
|
12
|
-
import { prepareTemplate } from './patch/template.js'
|
|
12
|
+
import { prepareTemplate, refreshTemplateFiles } from './patch/template.js'
|
|
13
|
+
import { cleanIncrementalInputs, readTemplateState, templateFingerprint, writeTemplateState } from './templateCache.js'
|
|
13
14
|
import { UTS_AAR, integrateUtsPlugins, scanUtsPlugins } from './patch/utsPlugins.js'
|
|
14
15
|
import {
|
|
15
16
|
detectVueVersion,
|
|
17
|
+
missingAppKeyHint,
|
|
16
18
|
normalizeManifest,
|
|
17
19
|
readProjectManifest,
|
|
18
20
|
readProjectPackage,
|
|
@@ -30,7 +32,9 @@ import {
|
|
|
30
32
|
import { resolveSigning } from './signing.js'
|
|
31
33
|
import { assertVersionMatch, readCompilerVersion, readSdkVersion, versionMismatchError } from './version.js'
|
|
32
34
|
import { runWebBuild } from './webBuild.js'
|
|
33
|
-
import {
|
|
35
|
+
import { assertResourceVersion } from './resourceVersion.js'
|
|
36
|
+
import { resolveBuildTempDir, resolveWorkRoot } from './workdir.js'
|
|
37
|
+
import { apkBaseName, findApk, publishApk, resolveApkPrefix } from './output.js'
|
|
34
38
|
|
|
35
39
|
/**
|
|
36
40
|
* @param {Object} input
|
|
@@ -43,6 +47,12 @@ import { apkBaseName, findApk, publishApk } from './output.js'
|
|
|
43
47
|
export async function buildProject(input) {
|
|
44
48
|
const { config, project, mode, options, logger } = input
|
|
45
49
|
const debug = mode === 'debug'
|
|
50
|
+
const prune = options.prune === undefined ? undefined : Number(options.prune)
|
|
51
|
+
if (prune !== undefined && (!Number.isInteger(prune) || prune < 0)) {
|
|
52
|
+
throw new PackError(`--prune 需要一个非负整数,收到:${String(options.prune)}`, EXIT.CONFIG, {
|
|
53
|
+
hint: '例如 --prune 5 表示每个 mode 只保留最近 5 个时间戳 APK,latest 永远保留',
|
|
54
|
+
})
|
|
55
|
+
}
|
|
46
56
|
|
|
47
57
|
const { manifest, file, type, inputDir } = await readProjectManifest(project.projectDir)
|
|
48
58
|
project.type = type
|
|
@@ -63,6 +73,10 @@ export async function buildProject(input) {
|
|
|
63
73
|
logger.detail(
|
|
64
74
|
`manifest: ${file}(${type === 'hbuilderx' ? 'HBuilderX' : 'CLI'} 项目,Vue ${vueVersion})`,
|
|
65
75
|
)
|
|
76
|
+
const appKeyHint = missingAppKeyHint(project.appKey)
|
|
77
|
+
if (appKeyHint) {
|
|
78
|
+
logger.warn(appKeyHint)
|
|
79
|
+
}
|
|
66
80
|
|
|
67
81
|
const hbuilderx = type === 'hbuilderx' ? await resolveHbuilderx(config, { project }) : null
|
|
68
82
|
if (type === 'hbuilderx' && !hbuilderx && !options.skipWeb) {
|
|
@@ -105,6 +119,8 @@ export async function buildProject(input) {
|
|
|
105
119
|
logger.warn(`版本不一致:uni-app ${versions.compiler ?? '未知'} / SDK ${versions.sdk ?? '未知'}(已跳过检查)`)
|
|
106
120
|
}
|
|
107
121
|
|
|
122
|
+
const workRoot = resolveWorkRoot(config, project)
|
|
123
|
+
const buildTemp = resolveBuildTempDir(workRoot)
|
|
108
124
|
let resourcesDir = path.resolve(
|
|
109
125
|
project.projectDir,
|
|
110
126
|
String(project.webBuild?.outputDir ?? (type === 'hbuilderx' ? 'unpackage/dist/build/app-plus' : 'dist/build/app')),
|
|
@@ -115,9 +131,22 @@ export async function buildProject(input) {
|
|
|
115
131
|
}
|
|
116
132
|
logger.info(`跳过前端构建,使用 ${resourcesDir}`)
|
|
117
133
|
} else {
|
|
118
|
-
resourcesDir = (
|
|
134
|
+
resourcesDir = (
|
|
135
|
+
await runWebBuild(project, logger, {
|
|
136
|
+
hbuilderx: hbuilderx ?? undefined,
|
|
137
|
+
vueVersion,
|
|
138
|
+
tempDir: buildTemp.tempDir,
|
|
139
|
+
})
|
|
140
|
+
).dir
|
|
119
141
|
}
|
|
120
142
|
|
|
143
|
+
const resourceVersion = await assertResourceVersion({
|
|
144
|
+
resourcesDir,
|
|
145
|
+
expected: resolved,
|
|
146
|
+
skip: Boolean(options.skipResourceCheck),
|
|
147
|
+
logger,
|
|
148
|
+
})
|
|
149
|
+
|
|
121
150
|
const utsPlugins = await scanUtsPlugins({ projectDir: project.projectDir, resourcesDir })
|
|
122
151
|
const hasUts = utsPlugins.some((plugin) => plugin.usable)
|
|
123
152
|
if (utsPlugins.length > 0) {
|
|
@@ -134,12 +163,30 @@ export async function buildProject(input) {
|
|
|
134
163
|
)
|
|
135
164
|
const tools = await resolveAndroidTools(config, { preferredBuildTools: buildToolsVersion })
|
|
136
165
|
const javaHome = await resolveJavaHome(config)
|
|
137
|
-
const workRoot = path.join(config.workDir, sanitize(project.name ?? 'project'))
|
|
138
166
|
const gradleRoot = path.join(workRoot, 'gradle')
|
|
139
167
|
|
|
140
168
|
logger.step('准备构建工程')
|
|
141
|
-
await
|
|
142
|
-
await
|
|
169
|
+
const template = await templateFingerprint({ root: sdk.root, templateRoot: sdk.templateRoot, version: sdkVersion })
|
|
170
|
+
const previous = await readTemplateState(gradleRoot)
|
|
171
|
+
if (
|
|
172
|
+
previous?.fingerprint === template.fingerprint &&
|
|
173
|
+
(await exists(path.join(gradleRoot, 'simpleDemo/build.gradle')))
|
|
174
|
+
) {
|
|
175
|
+
await refreshTemplateFiles(sdk.templateRoot, gradleRoot)
|
|
176
|
+
const cleaned = await cleanIncrementalInputs({ gradleRoot, appid: resolved.appid })
|
|
177
|
+
logger.info(`复用上次构建工程(模板未变化,清理 ${cleaned.length} 项增量输入)`)
|
|
178
|
+
} else {
|
|
179
|
+
await emptyDir(gradleRoot)
|
|
180
|
+
await prepareTemplate(sdk.templateRoot, gradleRoot)
|
|
181
|
+
await writeTemplateState(gradleRoot, {
|
|
182
|
+
fingerprint: template.fingerprint,
|
|
183
|
+
sdkRoot: sdk.root,
|
|
184
|
+
templateRoot: sdk.templateRoot,
|
|
185
|
+
version: sdkVersion ?? undefined,
|
|
186
|
+
builtAt: new Date().toISOString(),
|
|
187
|
+
})
|
|
188
|
+
logger.info('已复制离线 SDK 模板到工作目录')
|
|
189
|
+
}
|
|
143
190
|
const aars = await copyAars({
|
|
144
191
|
sdk,
|
|
145
192
|
targetDir: path.join(gradleRoot, 'simpleDemo/libs'),
|
|
@@ -176,7 +223,9 @@ export async function buildProject(input) {
|
|
|
176
223
|
debug,
|
|
177
224
|
})
|
|
178
225
|
await mergeProjectManifest({ targetFile: androidManifest, projectDir: project.projectDir, logger })
|
|
179
|
-
|
|
226
|
+
// 密钥库只复制到工作目录供 Gradle 本次构建使用,构建结束后立即删除
|
|
227
|
+
const keystoreCopy = path.join(gradleRoot, 'simpleDemo/aw-pack.jks')
|
|
228
|
+
await copyFile(signing.keystore, keystoreCopy)
|
|
180
229
|
await applyAssets({
|
|
181
230
|
moduleDir: path.join(gradleRoot, 'simpleDemo'),
|
|
182
231
|
dataDir: sdk.dataDir,
|
|
@@ -187,6 +236,7 @@ export async function buildProject(input) {
|
|
|
187
236
|
debug,
|
|
188
237
|
projectDir: project.projectDir,
|
|
189
238
|
manifest,
|
|
239
|
+
logger,
|
|
190
240
|
})
|
|
191
241
|
await applyNativePlugins({
|
|
192
242
|
projectDir: project.projectDir,
|
|
@@ -199,32 +249,43 @@ export async function buildProject(input) {
|
|
|
199
249
|
gradleRoot,
|
|
200
250
|
mainModule: 'simpleDemo',
|
|
201
251
|
compileSdkVersion,
|
|
252
|
+
kotlinVersion: templateDefaults.kotlinVersion,
|
|
202
253
|
logger,
|
|
203
254
|
})
|
|
204
255
|
logger.success('配置写入完成')
|
|
205
256
|
|
|
206
257
|
logger.step(`Gradle ${debug ? 'assembleDebug' : 'assembleRelease'}`)
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
258
|
+
try {
|
|
259
|
+
await runGradle({
|
|
260
|
+
gradlew: sdk.gradlew,
|
|
261
|
+
cwd: gradleRoot,
|
|
262
|
+
task: debug ? 'assembleDebug' : 'assembleRelease',
|
|
263
|
+
javaHome,
|
|
264
|
+
androidSdkDir: config.android.sdkDir,
|
|
265
|
+
offline: Boolean(options.offline),
|
|
266
|
+
daemon: options.noDaemon !== true,
|
|
267
|
+
signing,
|
|
268
|
+
logger,
|
|
269
|
+
})
|
|
270
|
+
} finally {
|
|
271
|
+
await rm(keystoreCopy, { force: true }).catch((error) => {
|
|
272
|
+
logger.warn(`临时签名文件删除失败:${error instanceof Error ? error.message : String(error)}`)
|
|
273
|
+
})
|
|
274
|
+
}
|
|
216
275
|
|
|
217
276
|
const apkDir = path.join(gradleRoot, 'simpleDemo/build/outputs/apk', mode)
|
|
218
277
|
const apk = await findApk(apkDir, mode)
|
|
219
278
|
await verifySignature(tools.apksigner, apk, logger)
|
|
220
279
|
|
|
221
|
-
const baseName = apkBaseName(project
|
|
280
|
+
const baseName = apkBaseName(resolveApkPrefix(project, resolved), resolved.versionName, resolved.versionCode)
|
|
222
281
|
const published = await publishApk({
|
|
223
282
|
apk,
|
|
224
283
|
outputDir: path.resolve(String(options.out ?? project.outputDir)),
|
|
225
284
|
baseName,
|
|
226
285
|
mode,
|
|
227
286
|
workDir: workRoot,
|
|
287
|
+
logger,
|
|
288
|
+
prune,
|
|
228
289
|
record: {
|
|
229
290
|
appid: resolved.appid,
|
|
230
291
|
packageName: resolved.packageName,
|
|
@@ -242,7 +303,18 @@ export async function buildProject(input) {
|
|
|
242
303
|
|
|
243
304
|
logger.success(`APK:${published.target}`)
|
|
244
305
|
logger.info(`最新副本:${published.latest}`)
|
|
245
|
-
|
|
306
|
+
logger.info(`产物清单:${published.recordFile}`)
|
|
307
|
+
return {
|
|
308
|
+
apk: published.target,
|
|
309
|
+
latest: published.latest,
|
|
310
|
+
sha256: published.sha256,
|
|
311
|
+
apkRecord: published.recordFile,
|
|
312
|
+
latestLinked: published.latestLinked,
|
|
313
|
+
resourceVersion: resourceVersion.versionName,
|
|
314
|
+
resourceVersionCode: resourceVersion.versionCode,
|
|
315
|
+
resolved,
|
|
316
|
+
workRoot,
|
|
317
|
+
}
|
|
246
318
|
}
|
|
247
319
|
|
|
248
320
|
/**
|
|
@@ -365,10 +437,3 @@ function firstNonEmpty(...values) {
|
|
|
365
437
|
}
|
|
366
438
|
return ''
|
|
367
439
|
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* @param {string} value
|
|
371
|
-
*/
|
|
372
|
-
function sanitize(value) {
|
|
373
|
-
return value.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'project'
|
|
374
|
-
}
|
package/src/core/config.js
CHANGED
|
@@ -85,6 +85,33 @@ export async function resolveProject(config, nameOrPath, cwd = process.cwd()) {
|
|
|
85
85
|
return finalizeProject(config, byPath[0], byPath[1])
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
+
// 支持用项目名/目录名/唯一子串代替长路径,例如 -p PRO_PHONE 或 -p phone
|
|
89
|
+
const wanted = normalizeProjectName(target)
|
|
90
|
+
if (wanted && !target.includes('/') && !target.includes('\\')) {
|
|
91
|
+
const entries = Object.entries(projects)
|
|
92
|
+
const exact = entries.filter(
|
|
93
|
+
([key, entry]) =>
|
|
94
|
+
normalizeProjectName(key) === wanted || normalizeProjectName(path.basename(String(entry.projectDir ?? ''))) === wanted,
|
|
95
|
+
)
|
|
96
|
+
if (exact.length === 1) {
|
|
97
|
+
return finalizeProject(config, exact[0][0], exact[0][1])
|
|
98
|
+
}
|
|
99
|
+
if (exact.length > 1) {
|
|
100
|
+
throw projectAmbiguous(target, exact)
|
|
101
|
+
}
|
|
102
|
+
const partial = entries.filter(
|
|
103
|
+
([key, entry]) =>
|
|
104
|
+
normalizeProjectName(key).includes(wanted) ||
|
|
105
|
+
normalizeProjectName(path.basename(String(entry.projectDir ?? ''))).includes(wanted),
|
|
106
|
+
)
|
|
107
|
+
if (partial.length === 1) {
|
|
108
|
+
return finalizeProject(config, partial[0][0], partial[0][1])
|
|
109
|
+
}
|
|
110
|
+
if (partial.length > 1) {
|
|
111
|
+
throw projectAmbiguous(target, partial)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
88
115
|
if (!nameOrPath) {
|
|
89
116
|
if (!(await isUniappProject(absolute))) {
|
|
90
117
|
throw new PackError('当前目录不是 uni-app 项目,请用 --project 指定项目目录或先在配置里登记', EXIT.CONFIG)
|
|
@@ -93,11 +120,35 @@ export async function resolveProject(config, nameOrPath, cwd = process.cwd()) {
|
|
|
93
120
|
}
|
|
94
121
|
|
|
95
122
|
if (!(await isUniappProject(absolute))) {
|
|
96
|
-
throw new PackError(`找不到项目:${nameOrPath}(既不是已登记的项目名,也不是 uni-app 项目目录)`, EXIT.CONFIG
|
|
123
|
+
throw new PackError(`找不到项目:${nameOrPath}(既不是已登记的项目名,也不是 uni-app 项目目录)`, EXIT.CONFIG, {
|
|
124
|
+
hint: '用 uni-pack projects 查看已登记项目,或 --project 传完整路径',
|
|
125
|
+
})
|
|
97
126
|
}
|
|
98
127
|
return finalizeProject(config, path.basename(absolute), { projectDir: absolute })
|
|
99
128
|
}
|
|
100
129
|
|
|
130
|
+
/**
|
|
131
|
+
* @param {string} value
|
|
132
|
+
* @returns {string}
|
|
133
|
+
*/
|
|
134
|
+
function normalizeProjectName(value) {
|
|
135
|
+
return String(value ?? '')
|
|
136
|
+
.toLowerCase()
|
|
137
|
+
.replace(/[^\w]+/g, '-')
|
|
138
|
+
.replace(/^-+|-+$/g, '')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* @param {string} target
|
|
143
|
+
* @param {Array<[string, any]>} entries
|
|
144
|
+
* @returns {PackError}
|
|
145
|
+
*/
|
|
146
|
+
function projectAmbiguous(target, entries) {
|
|
147
|
+
return new PackError(`项目名不唯一:${target}`, EXIT.CONFIG, {
|
|
148
|
+
hint: `候选:${entries.map(([key, entry]) => `${key}(${entry.projectDir})`).join(';')}`,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
101
152
|
/**
|
|
102
153
|
* CLI 的 Vue 2 项目通常用 build:app-plus(产物 dist/build/app-plus),
|
|
103
154
|
* Vue 3 项目用 build:app-android(产物 dist/build/app)。
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {Object} DebugPreset
|
|
3
|
+
* @property {'hbuilderx' | 'legacy'} [strategy]
|
|
4
|
+
* @property {'standard' | 'custom'} [playground]
|
|
5
|
+
* @property {'local' | 'device'} [customType]
|
|
6
|
+
* @property {string} [device]
|
|
7
|
+
* @property {boolean} [logs]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 项目预设只作为默认值;显式调用 HBuilderX 参数优先,基座相关参数强制走 uni-pack 自己的流程。
|
|
12
|
+
* @param {{ hbuilderx?: boolean, playground?: string, customType?: string, push?: boolean, build?: boolean,
|
|
13
|
+
* base?: string, install?: boolean }} options
|
|
14
|
+
* @param {DebugPreset} [preset]
|
|
15
|
+
* @returns {'hbuilderx' | 'legacy'}
|
|
16
|
+
*/
|
|
17
|
+
export function resolveDebugStrategy(options, preset = {}) {
|
|
18
|
+
const forceLegacy = Boolean(options.push || options.build || options.base || options.install)
|
|
19
|
+
const wantsHbuilderx = Boolean(options.hbuilderx || options.playground || options.customType)
|
|
20
|
+
if (wantsHbuilderx) {
|
|
21
|
+
return 'hbuilderx'
|
|
22
|
+
}
|
|
23
|
+
return !forceLegacy && preset.strategy === 'hbuilderx' ? 'hbuilderx' : 'legacy'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {{ playground?: string, customType?: string }} options
|
|
28
|
+
* @param {DebugPreset} [preset]
|
|
29
|
+
* @returns {{ playground: 'standard' | 'custom', customType: 'local' | 'device' }}
|
|
30
|
+
*/
|
|
31
|
+
export function resolveDebugBase(options, preset = {}) {
|
|
32
|
+
const playground = String(options.playground ?? preset.playground ?? 'standard').toLowerCase()
|
|
33
|
+
const customType = String(options.customType ?? preset.customType ?? 'local').toLowerCase()
|
|
34
|
+
return {
|
|
35
|
+
playground: /** @type {'standard' | 'custom'} */ (playground === 'custom' ? 'custom' : 'standard'),
|
|
36
|
+
customType: /** @type {'local' | 'device'} */ (customType === 'device' ? 'device' : 'local'),
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* @param {{ device?: string }} options
|
|
42
|
+
* @param {DebugPreset} [preset]
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export function resolveDebugDevice(options, preset = {}) {
|
|
46
|
+
return String(options.device ?? preset.device ?? '').trim()
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* @param {{ logs?: boolean }} options
|
|
51
|
+
* @param {DebugPreset} [preset]
|
|
52
|
+
* @returns {boolean}
|
|
53
|
+
*/
|
|
54
|
+
export function resolveDebugLogs(options, preset = {}) {
|
|
55
|
+
return Boolean(options.logs ?? preset.logs)
|
|
56
|
+
}
|
|
@@ -79,7 +79,8 @@ export function pairingPayload(service, code) {
|
|
|
79
79
|
export function selectPairingService(services, seen, service) {
|
|
80
80
|
const pairing = services.filter((item) => item.type === 'pairing')
|
|
81
81
|
const fresh = pairing.filter((item) => !seen.has(item.address))
|
|
82
|
-
|
|
82
|
+
// 新版 adb 的实例名就是二维码里的 S;老版本会带 ._adb-tls-pairing._tcp 后缀
|
|
83
|
+
const named = fresh.find((item) => item.name === service || item.name.startsWith(`${service}.`))
|
|
83
84
|
if (named) {
|
|
84
85
|
return named
|
|
85
86
|
}
|
package/src/core/fsx.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
|
|
1
|
+
import { cp, link, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -148,6 +148,17 @@ export async function copyTree(from, to, skip) {
|
|
|
148
148
|
})
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
+
/**
|
|
152
|
+
* 用硬链接把 target 指向 source:latest 副本零复制,且 source 被覆盖时不会影响已发布文件。
|
|
153
|
+
* @param {string} source
|
|
154
|
+
* @param {string} target
|
|
155
|
+
*/
|
|
156
|
+
export async function replaceHardLink(source, target) {
|
|
157
|
+
await ensureDir(path.dirname(target))
|
|
158
|
+
await rm(target, { force: true })
|
|
159
|
+
await link(source, target)
|
|
160
|
+
}
|
|
161
|
+
|
|
151
162
|
/**
|
|
152
163
|
* @param {string} dir
|
|
153
164
|
*/
|
package/src/core/gradle.js
CHANGED
|
@@ -1,75 +1,221 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs'
|
|
1
2
|
import path from 'node:path'
|
|
2
3
|
import { PackError, EXIT } from './errors.js'
|
|
3
|
-
import { ensureDir,
|
|
4
|
+
import { ensureDir, readJson, writeJson } from './fsx.js'
|
|
5
|
+
import { GradleLogAggregator, formatFailureHint } from './gradleLog.js'
|
|
4
6
|
import { run } from './process.js'
|
|
5
7
|
|
|
8
|
+
/** 配置缓存兼容性记录在工作目录根部,不兼容一次后不再重试。 */
|
|
9
|
+
export const GRADLE_FLAGS_FILE = 'gradle-flags.json'
|
|
10
|
+
|
|
6
11
|
/**
|
|
7
|
-
* @
|
|
8
|
-
* @
|
|
9
|
-
* @
|
|
10
|
-
* @
|
|
11
|
-
* @
|
|
12
|
-
* @
|
|
13
|
-
* @
|
|
14
|
-
* @
|
|
12
|
+
* @typedef {Object} RunGradleOptions
|
|
13
|
+
* @property {string} gradlew
|
|
14
|
+
* @property {string} cwd
|
|
15
|
+
* @property {'assembleRelease' | 'assembleDebug'} task
|
|
16
|
+
* @property {string} javaHome
|
|
17
|
+
* @property {string} androidSdkDir
|
|
18
|
+
* @property {boolean} [offline]
|
|
19
|
+
* @property {boolean} [daemon] 默认 true;CI 可用 --no-daemon 关闭
|
|
20
|
+
* @property {boolean} [buildCache] 默认 true
|
|
21
|
+
* @property {boolean} [configurationCache] 默认自动尝试
|
|
22
|
+
* @property {{ storePassword: string, keyPassword: string }} [signing] 只通过环境变量传给 Gradle,不落盘
|
|
23
|
+
* @property {import('./logger.js').Logger} logger
|
|
15
24
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {{ task: 'assembleRelease' | 'assembleDebug', offline?: boolean, daemon?: boolean,
|
|
28
|
+
* buildCache?: boolean, configurationCache?: boolean }} options
|
|
29
|
+
* @returns {string[]}
|
|
30
|
+
*/
|
|
31
|
+
export function buildGradleArgs(options) {
|
|
32
|
+
const args = [`:simpleDemo:${options.task}`, '--console=plain']
|
|
33
|
+
if (options.daemon === false) {
|
|
34
|
+
args.push('--no-daemon')
|
|
35
|
+
}
|
|
36
|
+
if (options.buildCache !== false) {
|
|
37
|
+
args.push('--build-cache')
|
|
38
|
+
}
|
|
39
|
+
args.push('--parallel')
|
|
18
40
|
if (options.offline) {
|
|
19
41
|
args.push('--offline')
|
|
20
42
|
}
|
|
43
|
+
if (options.configurationCache) {
|
|
44
|
+
args.push('--configuration-cache')
|
|
45
|
+
}
|
|
46
|
+
return args
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Gradle 8 / AGP 版本组合不总支持配置缓存;命中这些文案时回退普通构建。
|
|
51
|
+
* @param {string} output
|
|
52
|
+
* @returns {boolean}
|
|
53
|
+
*/
|
|
54
|
+
export function isConfigurationCacheFailure(output) {
|
|
55
|
+
if (!output) {
|
|
56
|
+
return false
|
|
57
|
+
}
|
|
58
|
+
return new RegExp(
|
|
59
|
+
[
|
|
60
|
+
'configuration cache problems found',
|
|
61
|
+
'not compatible with the configuration cache',
|
|
62
|
+
'problems were found storing the configuration cache',
|
|
63
|
+
'Configuration cache state could not be cached',
|
|
64
|
+
'Configuration cache entry discarded with',
|
|
65
|
+
'Invocation of Task\\.project',
|
|
66
|
+
].join('|'),
|
|
67
|
+
'i',
|
|
68
|
+
).test(output)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* @param {Pick<RunGradleOptions, 'javaHome' | 'androidSdkDir' | 'signing'>} options
|
|
73
|
+
* @returns {Record<string, string>}
|
|
74
|
+
*/
|
|
75
|
+
export function buildGradleEnv(options) {
|
|
76
|
+
return {
|
|
77
|
+
JAVA_HOME: options.javaHome,
|
|
78
|
+
ANDROID_HOME: options.androidSdkDir,
|
|
79
|
+
ANDROID_SDK_ROOT: options.androidSdkDir,
|
|
80
|
+
...(options.signing
|
|
81
|
+
? {
|
|
82
|
+
UNI_PACK_STORE_PASS: options.signing.storePassword,
|
|
83
|
+
UNI_PACK_KEY_PASS: options.signing.keyPassword,
|
|
84
|
+
}
|
|
85
|
+
: {}),
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @typedef {Object} GradleAttempt
|
|
91
|
+
* @property {string[]} lines
|
|
92
|
+
* @property {Array<{ label: string, count: number, sample: string[] }>} groups
|
|
93
|
+
* @property {unknown} failure
|
|
94
|
+
* @property {Error | null} logWriteError
|
|
95
|
+
* @property {string} logFile
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* @param {RunGradleOptions & { args: string[], logFile: string }} options
|
|
100
|
+
* @returns {Promise<GradleAttempt>}
|
|
101
|
+
*/
|
|
102
|
+
async function executeGradleAttempt(options) {
|
|
103
|
+
const verbose = Boolean(options.logger.verbose)
|
|
104
|
+
const lines = []
|
|
21
105
|
|
|
22
|
-
const
|
|
23
|
-
|
|
106
|
+
const stream = createWriteStream(options.logFile)
|
|
107
|
+
/** @type {{ error: Error | null }} */
|
|
108
|
+
const logWrite = { error: null }
|
|
109
|
+
stream.on('error', (error) => {
|
|
110
|
+
logWrite.error = error
|
|
111
|
+
})
|
|
112
|
+
const aggregator = verbose ? null : new GradleLogAggregator({ onLine: (line) => stream.write(`${line}\n`) })
|
|
24
113
|
|
|
114
|
+
/** @type {unknown} */
|
|
115
|
+
let failure = null
|
|
25
116
|
try {
|
|
26
|
-
await run(options.gradlew, args, {
|
|
117
|
+
await run(options.gradlew, options.args, {
|
|
27
118
|
cwd: options.cwd,
|
|
28
|
-
env:
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
ANDROID_SDK_ROOT: options.androidSdkDir,
|
|
32
|
-
},
|
|
119
|
+
env: buildGradleEnv(options),
|
|
120
|
+
// 非 verbose 时只写聚合后的日志;verbose 时原样流式落盘
|
|
121
|
+
onChunk: verbose ? (chunk) => stream.write(chunk) : undefined,
|
|
33
122
|
onLine: (line) => {
|
|
34
|
-
|
|
35
|
-
|
|
123
|
+
lines.push(line)
|
|
124
|
+
if (verbose) {
|
|
125
|
+
options.logger.detail(line)
|
|
126
|
+
} else {
|
|
127
|
+
aggregator?.push(line)
|
|
128
|
+
}
|
|
36
129
|
},
|
|
37
130
|
})
|
|
38
131
|
} catch (error) {
|
|
39
|
-
|
|
40
|
-
await ensureDir(path.dirname(logFile))
|
|
41
|
-
await writeText(logFile, output)
|
|
42
|
-
throw new PackError('Gradle 构建失败', EXIT.GRADLE, {
|
|
43
|
-
hint: `${diagnose(output)}\n完整日志:${logFile}`,
|
|
44
|
-
cause: error,
|
|
45
|
-
})
|
|
132
|
+
failure = error
|
|
46
133
|
}
|
|
47
134
|
|
|
48
|
-
|
|
49
|
-
await
|
|
50
|
-
|
|
51
|
-
return logFile
|
|
135
|
+
const groups = aggregator ? aggregator.finish() : []
|
|
136
|
+
await closeStream(stream)
|
|
137
|
+
return { lines, groups, failure, logWriteError: logWrite.error, logFile: options.logFile }
|
|
52
138
|
}
|
|
53
139
|
|
|
54
140
|
/**
|
|
55
|
-
* @param {
|
|
141
|
+
* @param {RunGradleOptions} options
|
|
56
142
|
*/
|
|
57
|
-
function
|
|
58
|
-
|
|
59
|
-
|
|
143
|
+
export async function runGradle(options) {
|
|
144
|
+
const workRoot = path.dirname(options.cwd)
|
|
145
|
+
const logDir = path.join(workRoot, 'logs')
|
|
146
|
+
await ensureDir(logDir)
|
|
147
|
+
|
|
148
|
+
const flagsFile = path.join(workRoot, GRADLE_FLAGS_FILE)
|
|
149
|
+
const flags = await readJson(flagsFile).catch(() => ({}))
|
|
150
|
+
const tryConfigurationCache = options.configurationCache !== false && flags.configurationCache !== false
|
|
151
|
+
|
|
152
|
+
const baseArgs = buildGradleArgs({
|
|
153
|
+
task: options.task,
|
|
154
|
+
offline: options.offline,
|
|
155
|
+
daemon: options.daemon,
|
|
156
|
+
buildCache: options.buildCache,
|
|
157
|
+
configurationCache: false,
|
|
158
|
+
})
|
|
159
|
+
const stamp = Date.now()
|
|
160
|
+
let attempt = await executeGradleAttempt({
|
|
161
|
+
...options,
|
|
162
|
+
args: tryConfigurationCache ? [...baseArgs, '--configuration-cache'] : baseArgs,
|
|
163
|
+
logFile: path.join(logDir, `gradle-${stamp}.log`),
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
if (attempt.failure && tryConfigurationCache && isConfigurationCacheFailure(attempt.lines.join('\n'))) {
|
|
167
|
+
options.logger.warn('Gradle 配置缓存与该工程不兼容,已回退为普通构建(后续构建不再尝试)')
|
|
168
|
+
await writeJson(flagsFile, { ...flags, configurationCache: false })
|
|
169
|
+
attempt = await executeGradleAttempt({
|
|
170
|
+
...options,
|
|
171
|
+
args: baseArgs,
|
|
172
|
+
logFile: path.join(logDir, `gradle-${stamp}-no-cc.log`),
|
|
173
|
+
})
|
|
60
174
|
}
|
|
61
|
-
|
|
62
|
-
|
|
175
|
+
|
|
176
|
+
if (attempt.logWriteError) {
|
|
177
|
+
options.logger.warn(`Gradle 日志写入失败:${attempt.logWriteError.message}`)
|
|
63
178
|
}
|
|
64
|
-
if (
|
|
65
|
-
|
|
179
|
+
if (!options.logger.verbose) {
|
|
180
|
+
printWarningSummary(attempt.groups, options.logger)
|
|
66
181
|
}
|
|
67
|
-
|
|
68
|
-
|
|
182
|
+
|
|
183
|
+
if (attempt.failure) {
|
|
184
|
+
throw new PackError('Gradle 构建失败', EXIT.GRADLE, {
|
|
185
|
+
hint: formatFailureHint({ lines: attempt.lines, logFile: attempt.logFile }),
|
|
186
|
+
cause: attempt.failure,
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
options.logger.success(`Gradle ${options.task} 完成`)
|
|
191
|
+
options.logger.info(`完整日志:${attempt.logFile}`)
|
|
192
|
+
return attempt.logFile
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* @param {Array<{ label: string, count: number, sample: string[] }>} groups
|
|
197
|
+
* @param {import('./logger.js').Logger} logger
|
|
198
|
+
*/
|
|
199
|
+
function printWarningSummary(groups, logger) {
|
|
200
|
+
if (groups.length === 0) {
|
|
201
|
+
return
|
|
69
202
|
}
|
|
70
|
-
|
|
71
|
-
|
|
203
|
+
const total = groups.reduce((sum, group) => sum + group.count, 0)
|
|
204
|
+
// 一次 warn 输出整段摘要:warn 走 stderr、info 走 stdout,分开输出会被缓冲打乱顺序
|
|
205
|
+
const lines = [`Gradle 告警:${total} 条同类告警已聚合为 ${groups.length} 类(看原始栈请用 --verbose 重跑)`]
|
|
206
|
+
for (const group of groups) {
|
|
207
|
+
lines.push(` ${group.label} ×${group.count}`)
|
|
208
|
+
if (group.sample[0]) {
|
|
209
|
+
lines.push(` 样例:${group.sample[0]}`)
|
|
210
|
+
}
|
|
72
211
|
}
|
|
73
|
-
|
|
74
|
-
|
|
212
|
+
logger.warn(lines.join('\n'))
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* @param {import('node:fs').WriteStream} stream
|
|
217
|
+
* @returns {Promise<void>}
|
|
218
|
+
*/
|
|
219
|
+
function closeStream(stream) {
|
|
220
|
+
return new Promise((resolve) => stream.end(resolve))
|
|
75
221
|
}
|