- 按前缀归类: dev:*(h5/adb/electron)、build:*(h5/app/exe/apk)、android:*(prepare/pack) - 改名: dev:h5:electron→dev:h5、debug:electron→dev:electron、build:h5:electron→build:h5、build:app-plus→build:app - 新增快捷入口: dev→dev:h5、build→build:h5、build:apk(编译+打包+发布一键) - build:apk 不重复调 prepare.cjs(pack.ps1 内部已注入) - 同步更新所有内部引用(dev-electron/build-exe/dev-adb/pack.ps1 提示)与文档
371 lines
11 KiB
JavaScript
371 lines
11 KiB
JavaScript
/**
|
||
* ADB 真机调试(类热更新):
|
||
* 1. 列出所有已连接设备,可选择目标设备(多台时交互选择,单台自动选中)
|
||
* 2. 进程常驻,监听源码变更
|
||
* 3. 变更后自动:build:app → 离线打包(gradle 增量) → adb install -r → 启动应用
|
||
*
|
||
* 用法:
|
||
* npm run dev:adb # 自动选唯一设备
|
||
* npm run dev:adb -- --no-launch # 重装后不自动启动应用
|
||
* npm run dev:adb -- --adb=adb路径 # 自定义 adb 路径
|
||
*
|
||
* 变更监听范围:
|
||
* src/(uni-app 前端资源)
|
||
* android-offline/HBuilder-Integrate-AS/simpleDemo/src/(原生工程:Manifest/Java/res)
|
||
*/
|
||
const { spawnSync, spawn } = require('child_process')
|
||
const fs = require('fs')
|
||
const path = require('path')
|
||
const readline = require('readline')
|
||
|
||
const ROOT = path.resolve(__dirname, '..')
|
||
|
||
// ---------- adb 路径探测(PATH 里没有时从 SDK 目录找) ----------
|
||
function detectAdb() {
|
||
const arg = process.argv.find((a) => a.startsWith('--adb='))
|
||
if (arg) {
|
||
return arg.slice('--adb='.length)
|
||
}
|
||
if (process.env.ADB) {
|
||
return process.env.ADB
|
||
}
|
||
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) {
|
||
try {
|
||
const res = spawnSync(c, ['version'], { encoding: 'utf-8' })
|
||
if (res.status === 0 && /Android Debug Bridge/.test(res.stdout || '')) {
|
||
return c
|
||
}
|
||
} catch (e) {
|
||
// 继续
|
||
}
|
||
}
|
||
return 'adb'
|
||
}
|
||
|
||
const ADB = detectAdb()
|
||
const NO_LAUNCH = process.argv.includes('--no-launch')
|
||
|
||
// 监听范围与扩展名
|
||
// 注意:不要监听 simpleDemo/src/main/assets(构建注入产物)、res(prepare 会覆盖图标/启动图)、build 目录,否则构建自触发死循环
|
||
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,
|
||
},
|
||
{
|
||
// 只监听直接文件(AndroidManifest.xml),不递归:assets 是 prepare 注入产物
|
||
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', '.md',
|
||
])
|
||
|
||
const log = (msg) => console.log(`[dev-adb] ${msg}`)
|
||
const run = (cmd, args, opts = {}) => {
|
||
// Windows 下通过 shell 执行,自动解析 npm.cmd / 全路径 exe
|
||
const res = spawnSync(cmd, args, {
|
||
cwd: opts.cwd || ROOT,
|
||
stdio: 'inherit',
|
||
env: { ...process.env, ...(opts.env || {}) },
|
||
shell: process.platform === 'win32',
|
||
})
|
||
if (res.error) {
|
||
console.error(`[dev-adb] spawn 失败 ${cmd}: ${res.error.message}`)
|
||
return false
|
||
}
|
||
return res.status === 0
|
||
}
|
||
|
||
// ---------- 1. 列出并解析设备 ----------
|
||
function listDevices() {
|
||
const res = spawnSync(ADB, ['devices', '-l'], { encoding: 'utf-8' })
|
||
const out = res.stdout || ''
|
||
log(`adb devices 输出:\n${out.trim()}`)
|
||
const lines = out.split(/\r?\n/)
|
||
const devices = []
|
||
for (const line of lines) {
|
||
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())
|
||
})
|
||
})
|
||
}
|
||
|
||
async function pickDevice(devices) {
|
||
if (devices.length === 0) {
|
||
console.error('[dev-adb] 未检测到任何已连接设备,请检查 USB 连接/ADB 授权后重试')
|
||
process.exit(1)
|
||
}
|
||
if (devices.length === 1) {
|
||
log(`唯一设备,自动选中: ${devices[0].serial} (${devices[0].desc})`)
|
||
return devices[0]
|
||
}
|
||
devices.forEach((d, i) => console.log(` [${i + 1}] ${d.serial} ${d.desc}`))
|
||
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)
|
||
}
|
||
return devices[idx]
|
||
}
|
||
|
||
// ---------- 2. 构建 → 打包 → 安装 → 启动 ----------
|
||
let logcatProc = null
|
||
|
||
// 真机 console 实时打印:logcat 只跟随 UniConsole(逻辑层) 与 UniViewConsole(视图层 renderjs)
|
||
function startLogcat(serial) {
|
||
if (logcatProc) {
|
||
return
|
||
}
|
||
spawnSync(ADB, ['-s', serial, 'logcat', '-c'], { stdio: 'ignore' })
|
||
logcatProc = spawn(ADB, ['-s', serial, 'logcat', '-v', 'time', '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)
|
||
buf = buf.slice(idx + 1)
|
||
const trimmed = line.trim()
|
||
if (!trimmed) {
|
||
continue
|
||
}
|
||
const isErr = trimmed.includes(' W/') || trimmed.includes(' E/')
|
||
console.log(isErr ? `\x1b[31m[真机] ${trimmed}\x1b[0m` : `\x1b[36m[真机] ${trimmed}\x1b[0m`)
|
||
}
|
||
})
|
||
logcatProc.on('exit', () => {
|
||
logcatProc = null
|
||
// adb 重连/设备重启后自动恢复跟随
|
||
setTimeout(() => startLogcat(serial), 3000)
|
||
})
|
||
log('真机 console 实时打印已开启(UniConsole/UniViewConsole)')
|
||
}
|
||
|
||
function clearLogcat(serial) {
|
||
spawnSync(ADB, ['-s', serial, 'logcat', '-c'], { stdio: 'ignore' })
|
||
}
|
||
|
||
function findApk() {
|
||
// 优先按 package.json version 精确匹配
|
||
try {
|
||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf-8'))
|
||
const exact = path.join(ROOT, 'release', 'android', `wms-worker-station_v${pkg.version}_release.apk`)
|
||
if (fs.existsSync(exact)) {
|
||
return exact
|
||
}
|
||
} catch (e) {
|
||
// 忽略
|
||
}
|
||
// 兜底:目录里最新的 apk
|
||
const dir = path.join(ROOT, 'release', 'android')
|
||
if (!fs.existsSync(dir)) {
|
||
return null
|
||
}
|
||
const apks = fs.readdirSync(dir).filter((f) => f.endsWith('.apk')).map((f) => ({
|
||
name: f,
|
||
mtime: fs.statSync(path.join(dir, f)).mtimeMs,
|
||
}))
|
||
if (apks.length === 0) {
|
||
return null
|
||
}
|
||
apks.sort((a, b) => b.mtime - a.mtime)
|
||
return path.join(dir, apks[0].name)
|
||
}
|
||
|
||
let building = false
|
||
let pending = false
|
||
let lastChangeAt = 0
|
||
let buildFinishedAt = 0
|
||
|
||
async function buildAndInstall(serial, trigger) {
|
||
const t0 = Date.now()
|
||
log(`开始构建(触发: ${trigger})`)
|
||
// 1. uni-app 编译 App 资源
|
||
if (!run('npm', ['run', 'build:app'])) {
|
||
log('✗ build:app 失败,跳过安装')
|
||
return false
|
||
}
|
||
// 2. 离线打包(prepare + gradle 增量 + 复制 APK),跳过发布上传
|
||
if (!run('npm', ['run', 'android:pack', '--', '-NoUpload'])) {
|
||
log('✗ android:pack 失败,跳过安装')
|
||
return false
|
||
}
|
||
// 3. 定位 APK
|
||
const apk = findApk()
|
||
if (!apk) {
|
||
log('✗ 未找到 APK 产物')
|
||
return false
|
||
}
|
||
log(`APK: ${path.relative(ROOT, apk)}`)
|
||
// 4. 安装(失败重试 2 次,设备忙时常见)
|
||
for (let i = 0; i < 3; i++) {
|
||
const res = spawnSync(ADB, ['-s', serial, 'install', '-r', apk], { stdio: 'inherit' })
|
||
if (res.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. 启动应用(Android 7 用 monkey 拉起 launcher 入口最稳)
|
||
if (!NO_LAUNCH) {
|
||
clearLogcat(serial)
|
||
spawnSync(ADB, ['-s', serial, 'shell', 'am', 'force-stop', 'com.gztbyc.sandan'], { stdio: 'ignore' })
|
||
spawnSync(ADB, ['-s', serial, 'shell', 'monkey', '-p', 'com.gztbyc.sandan', '-c', 'android.intent.category.LAUNCHER', '1'], { stdio: 'ignore' })
|
||
log('已启动应用')
|
||
}
|
||
log(`✓ 完成,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`)
|
||
return true
|
||
}
|
||
|
||
async function triggerBuild(serial, trigger) {
|
||
if (building) {
|
||
pending = true
|
||
return
|
||
}
|
||
building = true
|
||
try {
|
||
await buildAndInstall(serial, trigger)
|
||
} finally {
|
||
building = false
|
||
buildFinishedAt = Date.now()
|
||
if (pending) {
|
||
pending = false
|
||
log('构建期间有新变更,继续构建...')
|
||
triggerBuild(serial, 'pending')
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---------- 3. 目录监听(Windows 兼容:watch 每个子目录) ----------
|
||
function collectWatchDirs() {
|
||
const dirs = new Set()
|
||
for (const root of WATCH_ROOTS) {
|
||
if (!fs.existsSync(root.dir)) {
|
||
log(`警告: 监听目录不存在: ${root.dir}`)
|
||
continue
|
||
}
|
||
dirs.add(root.dir)
|
||
if (!root.recursive) {
|
||
continue
|
||
}
|
||
const walk = (dir) => {
|
||
let entries = []
|
||
try {
|
||
entries = fs.readdirSync(dir, { withFileTypes: true })
|
||
} catch (e) {
|
||
return
|
||
}
|
||
for (const e of entries) {
|
||
if (e.isDirectory()) {
|
||
const full = path.join(dir, e.name)
|
||
if (e.name === 'node_modules' || e.name === '.git' || e.name === 'build' || e.name === '.gradle') {
|
||
continue
|
||
}
|
||
dirs.add(full)
|
||
walk(full)
|
||
}
|
||
}
|
||
}
|
||
walk(root.dir)
|
||
}
|
||
return [...dirs]
|
||
}
|
||
|
||
function watchDirs(serial) {
|
||
const watched = new Set()
|
||
const attach = (dir) => {
|
||
if (watched.has(dir)) {
|
||
return
|
||
}
|
||
watched.add(dir)
|
||
try {
|
||
const watcher = fs.watch(dir, (eventType, filename) => {
|
||
if (!filename) {
|
||
return
|
||
}
|
||
// 构建期间自身写入产物(图标/启动图覆盖等)的变更直接忽略,防止自触发循环
|
||
if (building || Date.now() - buildFinishedAt < 3000) {
|
||
return
|
||
}
|
||
const ext = path.extname(filename).toLowerCase()
|
||
if (!WATCH_EXTS.has(ext)) {
|
||
return
|
||
}
|
||
const now = Date.now()
|
||
if (now - lastChangeAt < 150) {
|
||
// 一次保存可能触发多次事件,靠防抖合并
|
||
}
|
||
lastChangeAt = now
|
||
clearTimeout(watchDirs._debounce)
|
||
watchDirs._debounce = setTimeout(() => {
|
||
triggerBuild(serial, `${dir}/${filename}`.slice(ROOT.length + 1))
|
||
}, 800)
|
||
})
|
||
watcher.on('error', () => {
|
||
// 目录可能被删除重建,稍后重新收集
|
||
})
|
||
} catch (e) {
|
||
// 忽略
|
||
}
|
||
}
|
||
for (const dir of collectWatchDirs()) {
|
||
attach(dir)
|
||
}
|
||
// 目录结构变化(新增/删除目录)时重新收集
|
||
setInterval(() => {
|
||
for (const dir of collectWatchDirs()) {
|
||
attach(dir)
|
||
}
|
||
}, 10000)
|
||
log(`正在监听 ${watched.size} 个目录,保存文件后自动构建重装...`)
|
||
}
|
||
|
||
// ---------- 主流程 ----------
|
||
async function main() {
|
||
log(`ADB: ${ADB}`)
|
||
const devices = listDevices()
|
||
const target = await pickDevice(devices)
|
||
log(`目标设备: ${target.serial}`)
|
||
startLogcat(target.serial)
|
||
watchDirs(target.serial)
|
||
log('首次启动构建...')
|
||
triggerBuild(target.serial, 'initial')
|
||
}
|
||
|
||
main().catch((err) => {
|
||
console.error('[dev-adb] 异常:', err)
|
||
process.exit(1)
|
||
})
|