WMS_PDA/scripts/dev-adb.cjs
zm2000 263adfb759 fix(更新弹窗+调试脚本): 兼容旧真机 flex gap 与 dev 打包参数被吞
- 更新弹窗/登录页/关于页统一移除 flex gap,改用兄弟选择器 margin 控制间距,
  修复旧机型 WebView 不支持 gap 导致版本号、信息行、提示、按钮之间无间距
- :deep(.u-button) 改为 ::v-deep,兼容旧真机样式穿透;关于页补上按钮 flex:1
- dev-adb 打包由 npm run android:pack:raw -- -Dev -NoUpload 改为直接执行
  android-offline/pack.ps1 -Dev -NoUpload,避免 PowerShell 吞掉 -- 使参数失效,
  打包成发行包并覆盖正式 APK、dev 目录无产物导致装回旧包
2026-10-30 18:16:28 +08:00

447 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 真机调试(测试模式):注入接口地址 → 编译 → 打包 → 装机 → 启动 → 跟随日志 → 监听改动自动重来。
*
* 与 `npm run build:apk` 的区别:
* - build:apk → 发行包。接口地址固定为 src/env.js 的 PROD_API_BASE,构建后强制校验产物不含内网地址。
* - dev:adb → 测试包。接口地址在编译期由本脚本注入(默认取 .env.development.local 的
* VUE_APP_API_BASE_URL),产物进 release/android/dev/*_dev.apk,绝不覆盖发行包。
*
* 注入方式(与工作台 wms_worker_station 一致):命令行环境变量 VUE_APP_API_BASE_OVERRIDE,
* 不写入任何 .env 文件、不落盘;在 src/env.js 中优先级高于生产常量,详见该文件顶部说明。
*
* 用法:
* npm run dev:adb # 默认:构建→装机→启动→跟随真机日志→监听改动自动重来
* npm run dev:adb -- --once # 只跑一遍(CI/脚本调用用,不监听)
* npm run dev:adb -- --prod-api # 不注入,产出与发行包一致的包(排查线上问题时用)
* npm run dev:adb -- --api=http://192.168.1.10:6060
* npm run dev:adb -- --no-install # 只编译 + 打包
* npm run dev:adb -- --no-launch # 装机后不自动启动
* npm run dev:adb -- --no-logcat # 不跟随真机日志
* npm run dev:adb -- --serial=4235737 # 多设备时指定目标设备
*
* 真机日志:release 包里 JS 的 console 走 UniConsole(逻辑层) / UniViewConsole(视图层) 两个 tag,
* 本脚本默认跟随这两个 tag 实时打印到控制台(出错行标红)。
*/
const { spawn, spawnSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const readline = require('readline')
const ROOT = path.resolve(__dirname, '..')
const APP_BUILD_DIR = path.join(ROOT, 'dist', 'build', 'app-plus')
const DEV_APK_DIR = path.join(ROOT, 'release', 'android', 'dev')
const PACKAGE_NAME = 'com.gztbyc.pda_wms'
const argv = process.argv.slice(2)
const hasFlag = (name) => argv.includes(name)
const argValue = (name) => {
const hit = argv.find((a) => a.startsWith(`${name}=`))
return hit ? hit.slice(name.length + 1) : ''
}
const ONCE = hasFlag('--once') || hasFlag('--no-watch')
const NO_INSTALL = hasFlag('--no-install')
const NO_LAUNCH = hasFlag('--no-launch')
const NO_LOGCAT = hasFlag('--no-logcat')
const log = (msg) => console.log(`[dev:adb] ${msg}`)
// ---------- adb 探测 ----------
function detectAdb() {
const candidates = []
const home = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT || ''
if (home) candidates.push(path.join(home, 'platform-tools', process.platform === 'win32' ? 'adb.exe' : 'adb'))
if (process.env.LOCALAPPDATA) candidates.push(path.join(process.env.LOCALAPPDATA, 'Android', 'Sdk', 'platform-tools', 'adb.exe'))
candidates.push(process.platform === 'win32' ? 'adb.exe' : 'adb')
for (const c of candidates) {
const res = spawnSync(c, ['version'], { encoding: 'utf-8' })
if (res.status === 0 && /Android Debug Bridge/.test(res.stdout || '')) return c
}
return 'adb'
}
const ADB = detectAdb()
// ---------- 接口地址解析 ----------
function readEnvValue(file, key) {
try {
const text = fs.readFileSync(path.join(ROOT, file), 'utf-8')
for (const line of text.split(/\r?\n/)) {
const m = line.match(/^\s*([A-Za-z0-9_]+)\s*=\s*(.*)$/)
if (m && m[1] === key) return m[2].trim().replace(/^["']|["']$/g, '')
}
} catch (e) {
// 文件不存在视为未配置
}
return ''
}
function resolveApiTarget() {
if (hasFlag('--prod-api')) return { base: '', note: '--prod-api 指定,与发行包一致(生产地址)' }
const argApi = argValue('--api')
if (argApi) return { base: argApi, note: '命令行 --api 指定' }
const fromEnv = readEnvValue('.env.development.local', 'VUE_APP_API_BASE_URL') || readEnvValue('.env.local', 'VUE_APP_API_BASE_URL')
if (fromEnv) return { base: fromEnv, note: '.env.development.local 的 VUE_APP_API_BASE_URL' }
return { base: '', note: '未配置开发地址,沿用构建默认(生产地址)' }
}
const API_TARGET = resolveApiTarget()
const BUILD_ENV = {
...(API_TARGET.base
? { VUE_APP_API_BASE_OVERRIDE: API_TARGET.base }
// 不注入地址时(--prod-api / 未配置开发地址),显式删除继承的环境变量(null=删除),
// 避免终端里残留的 VUE_APP_API_BASE_OVERRIDE / VUE_APP_API_BASE_URL 把开发地址带进包
: { VUE_APP_API_BASE_OVERRIDE: null, VUE_APP_API_BASE_URL: null }),
// 测试包始终开启 JS→logcat 转发(发行包不注入该变量,见 src/core/utils/dev-log.js)
VUE_APP_JS_LOG_TO_LOGCAT: '1',
}
// ---------- 工具 ----------
function run(cmd, args, env) {
const mergedEnv = { ...process.env, ...(env || {}) }
// 值为 null 的变量表示「显式删除」,避免终端里继承的旧值被带进子进程
for (const key of Object.keys(env || {})) {
if (env[key] === null) delete mergedEnv[key]
}
const res = spawnSync(cmd, args, {
cwd: ROOT,
stdio: 'inherit',
env: mergedEnv,
shell: process.platform === 'win32',
})
if (res.error) {
console.error(`[dev:adb] 执行失败 ${cmd}: ${res.error.message}`)
return false
}
return res.status === 0
}
function collectFiles(dir, out = []) {
if (!fs.existsSync(dir)) return out
for (const name of fs.readdirSync(dir)) {
const full = path.join(dir, name)
if (fs.statSync(full).isDirectory()) collectFiles(full, out)
else if (/\.(js|html|json)$/i.test(name)) out.push(full)
}
return out
}
function findDevApk() {
if (!fs.existsSync(DEV_APK_DIR)) return null
const apks = fs.readdirSync(DEV_APK_DIR)
.filter((f) => f.endsWith('.apk'))
.map((f) => ({ name: f, mtime: fs.statSync(path.join(DEV_APK_DIR, f)).mtimeMs }))
if (!apks.length) return null
apks.sort((a, b) => b.mtime - a.mtime)
return path.join(DEV_APK_DIR, apks[0].name)
}
// ---------- 设备 ----------
// 上次选择的设备记在本文件里(不提交 git):多设备时自动选回它,避免每次都要选
const STATE_FILE = path.join(ROOT, '.dev-adb.local.json')
function readSavedSerial() {
try {
return JSON.parse(fs.readFileSync(STATE_FILE, 'utf-8')).serial || ''
} catch (e) {
return ''
}
}
function saveSerial(serial) {
try {
fs.writeFileSync(STATE_FILE, `${JSON.stringify({ serial }, null, 2)}\n`)
} catch (e) {
// 写入失败不影响流程
}
}
function listDevices() {
const res = spawnSync(ADB, ['devices', '-l'], { encoding: 'utf-8' })
const devices = []
for (const line of (res.stdout || '').split(/\r?\n/)) {
const m = line.trim().match(/^(\S+)\s+device\b(.*)$/)
if (m) devices.push({ serial: m[1], desc: m[2].trim() })
}
return devices
}
function ask(question) {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close()
resolve(String(answer || '').trim())
})
})
}
function printDevices(devices) {
devices.forEach((d, i) => console.error(` [${i + 1}] ${d.serial} ${d.desc}`))
}
async function pickDevice() {
const devices = listDevices()
if (!devices.length) {
console.error('[dev:adb] 未检测到已连接设备(USB 未插好、未授权,或无线调试未 adb connect)')
process.exit(1)
}
// 1. 命令行指定优先
const wanted = argValue('--serial')
if (wanted) {
const hit = devices.find((d) => d.serial === wanted)
if (!hit) {
console.error(`[dev:adb] 未找到设备 ${wanted},当前:${devices.map((d) => d.serial).join(', ')}`)
process.exit(1)
}
saveSerial(hit.serial)
return hit
}
// 2. 上次用过的设备仍然在线 → 直接用
const saved = readSavedSerial()
if (saved) {
const hit = devices.find((d) => d.serial === saved)
if (hit) {
log(`使用上次选择的设备: ${hit.serial} ${hit.desc}(可用 --serial= 更换)`)
return hit
}
}
// 3. 只有一台 → 自动选中
if (devices.length === 1) {
saveSerial(devices[0].serial)
return devices[0]
}
// 4. 多台 → 交互选择(与工作台 dev:adb 一致)
console.error('[dev:adb] 检测到多台设备:')
printDevices(devices)
if (!process.stdin.isTTY) {
console.error('[dev:adb] 当前终端不能交互,请用 --serial=<序列号> 指定,例如:')
console.error(` npm run dev:adb -- --serial=${devices[0].serial}`)
process.exit(1)
}
const answer = await ask(`请选择设备序号 [1-${devices.length}],默认 1: `)
const idx = answer ? Number(answer) - 1 : 0
if (!Number.isInteger(idx) || idx < 0 || idx >= devices.length) {
console.error(`[dev:adb] 无效序号: ${answer}`)
process.exit(1)
}
saveSerial(devices[idx].serial)
return devices[idx]
}
// ---------- 真机日志跟随 ----------
let logcatProc = null
let shuttingDown = false
function clearLogcat(serial) {
spawnSync(ADB, ['-s', serial, 'logcat', '-c'], { stdio: 'ignore' })
}
function startLogcat(serial) {
if (NO_LOGCAT || logcatProc || shuttingDown) return
clearLogcat(serial)
logcatProc = spawn(ADB, ['-s', serial, 'logcat', '-v', 'time', 'jsLog:V', 'UniConsole:V', 'UniViewConsole:V', '*:S'], {
stdio: ['ignore', 'pipe', 'inherit'],
})
let buf = ''
logcatProc.stdout.setEncoding('utf-8')
logcatProc.stdout.on('data', (chunk) => {
buf += chunk
let idx
while ((idx = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, idx).trim()
buf = buf.slice(idx + 1)
if (!line) continue
const isErr = / W\/| E\//.test(line)
console.log(isErr ? `\x1b[31m[真机] ${line}\x1b[0m` : `\x1b[36m[真机] ${line}\x1b[0m`)
}
})
logcatProc.on('exit', () => {
logcatProc = null
if (!shuttingDown) {
// adb 重连/设备重启后自动恢复跟随
setTimeout(() => startLogcat(serial), 3000)
}
})
log('真机 console 实时打印已开启(jsLog / UniConsole / UniViewConsole)')
}
process.on('SIGINT', () => {
shuttingDown = true
if (logcatProc) {
logcatProc.kill()
logcatProc = null
}
log('已退出监听的日志跟随')
process.exit(0)
})
// ---------- 构建 → 安装 → 启动 ----------
async function buildAndInstall(device, trigger) {
const serial = device.serial
const t0 = Date.now()
log(`开始构建(触发: ${trigger})`)
log(`接口地址 = ${API_TARGET.base || 'src/env.js 的 PROD_API_BASE(生产)'} 〔${API_TARGET.note}〕`)
// 1. 编译 App 资源(生产模式编译,但注入 override 指向测试环境)
if (!run('npm', ['run', 'build:app-plus:dev'], BUILD_ENV)) {
log('✗ 编译失败,跳过安装')
return false
}
// 2. 校验注入结果(正向:期望地址必须出现在产物里)
const files = collectFiles(APP_BUILD_DIR)
if (!files.length) {
log(`✗ 未找到构建产物: ${path.relative(ROOT, APP_BUILD_DIR)}`)
return false
}
if (API_TARGET.base) {
const host = API_TARGET.base.replace(/^https?:\/\//, '').replace(/\/.*$/, '')
const hit = files.find((f) => fs.readFileSync(f, 'utf-8').includes(host))
if (!hit) {
log(`✗ 产物中未找到注入的地址 ${API_TARGET.base},注入可能未生效,已中止`)
return false
}
log(`✓ 已确认产物使用 ${API_TARGET.base}`)
} else if (!run('node', ['scripts/check-build-env.cjs', 'dist/build/app-plus'])) {
log('✗ 产物地址校验未通过')
return false
}
// 3. 离线打包(-Dev:产物进 release/android/dev 且带 _dev 后缀,不触发发布上传)
// 注意:不要用 `npm run android:pack:raw -- -Dev -NoUpload`。
// PowerShell 会把 `--` 吞掉,`-Dev/-NoUpload` 随即被 npm 当作未知选项丢弃,
// 结果是打出「发行包」(覆盖 release/android/ 下的正式 APK),而 dev 目录没有新文件,
// 后面 findDevApk() 就会装回旧包,真机上看到的永远是老界面。
// 这里直接调 pack.ps1,参数一定生效。
if (!run('powershell', [
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', path.join(ROOT, 'android-offline', 'pack.ps1'),
'-Dev',
'-NoUpload',
])) {
log('✗ 打包失败,跳过安装')
return false
}
const apk = findDevApk()
if (!apk) {
log(`✗ 未找到 APK: ${path.relative(ROOT, DEV_APK_DIR)}`)
return false
}
log(`APK: ${path.relative(ROOT, apk)}`)
if (NO_INSTALL) {
log(`✓ 编译 + 打包完成,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s(--no-install 未安装)`)
return true
}
// 4. 安装(设备忙时常见失败,重试 3 次)
for (let i = 0; i < 3; i++) {
if (spawnSync(ADB, ['-s', serial, 'install', '-r', apk], { stdio: 'inherit' }).status === 0) break
if (i === 2) {
log('✗ adb install 失败(已重试 3 次)')
return false
}
log(`安装失败,2 秒后重试 (${i + 1}/2)`)
await new Promise((r) => setTimeout(r, 2000))
}
// 5. 启动(先停进程,再用 monkey 拉起 launcher 入口最稳)
if (!NO_LAUNCH) {
if (!NO_LOGCAT) startLogcat(serial)
else clearLogcat(serial)
spawnSync(ADB, ['-s', serial, 'shell', 'am', 'force-stop', PACKAGE_NAME], { stdio: 'ignore' })
spawnSync(ADB, ['-s', serial, 'shell', 'monkey', '-p', PACKAGE_NAME, '-c', 'android.intent.category.LAUNCHER', '1'], { stdio: 'ignore' })
log('已启动应用')
}
log(`✓ 完成,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`)
return true
}
let building = false
let pending = false
async function triggerBuild(device, trigger) {
if (building) {
pending = true
return
}
building = true
try {
await buildAndInstall(device, trigger)
} finally {
building = false
if (pending) {
pending = false
log('构建期间有新变更,继续构建...')
triggerBuild(device, 'pending')
}
}
}
// ---------- 目录监听 ----------
// 监听范围:src/(uni-app 前端)、原生 java、以及 src/main 直接子文件(AndroidManifest.xml)。
// 注意:不监听 src/main/assets(prepare 注入产物)与 res(图标/启动图覆盖产物),否则构建会自触发死循环。
const WATCH_ROOTS = [
{ dir: path.join(ROOT, 'src'), recursive: true },
{ dir: path.join(ROOT, 'android-offline', 'HBuilder-Integrate-AS', 'simpleDemo', 'src', 'main', 'java'), recursive: true },
{ dir: path.join(ROOT, 'android-offline', 'HBuilder-Integrate-AS', 'simpleDemo', 'src', 'main'), recursive: false },
]
const WATCH_EXTS = new Set(['.vue', '.js', '.ts', '.json', '.scss', '.css', '.cjs', '.ps1', '.xml', '.java', '.png', '.jpg', '.jpeg'])
const IGNORE_SEGMENTS = [`${path.sep}assets${path.sep}`, `${path.sep}unpackage${path.sep}`, `${path.sep}dist${path.sep}`, `${path.sep}node_modules${path.sep}`]
function startWatch(device) {
let timer = null
for (const root of WATCH_ROOTS) {
if (!fs.existsSync(root.dir)) {
log(`警告: 监听目录不存在: ${path.relative(ROOT, root.dir)}`)
continue
}
try {
fs.watch(root.dir, { recursive: root.recursive }, (event, filename) => {
const rel = filename ? path.join(root.dir, filename) : root.dir
if (IGNORE_SEGMENTS.some((seg) => rel.includes(seg))) return
if (filename && !WATCH_EXTS.has(path.extname(filename).toLowerCase())) return
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null
triggerBuild(device, path.relative(ROOT, rel))
}, 800)
})
log(`监听中: ${path.relative(ROOT, root.dir)}${root.recursive ? '' : '(不递归)'}`)
} catch (e) {
log(`警告: 无法监听 ${root.dir}: ${e.message}`)
}
}
log('改动文件即自动重编重装(Ctrl+C 退出)')
}
// ---------- 主流程 ----------
async function main() {
const device = await pickDevice()
log(`目标设备: ${device.serial} ${device.desc}`)
await triggerBuild(device, '首次')
log(`单独查看真机日志:adb -s ${device.serial} logcat jsLog:V UniConsole:V UniViewConsole:V *:S`)
if (ONCE) {
if (NO_LOGCAT || NO_LAUNCH) {
log('--once 指定,不进入监听,结束')
} else {
log('--once 指定:不监听文件改动,但继续跟随真机日志(Ctrl+C 退出)')
}
return
}
startWatch(device)
}
main()