feat: 支持安装前后ADB命令与安装后启动应用
按工程保存前后置命令和自动启动选项,全程绑定选中设备,区分安装与后续动作失败。通过实际APK及目标设备解析Launcher入口,兼容activity-alias;增加模拟进程回归测试及0.8.0三套服务部署记录。
This commit is contained in:
1 parent
6f9cc7e7ea
commit
b46ebd1070
18 files changed
+472
-35
No files matched your search
@@ -28,15 +28,19 @@ object AdbDevices {
|
||||
|
||||
fun resolve(source: Path, configured: String): String {
|
||||
if (configured.isNotBlank() && configured != "adb") return configured
|
||||
val roots = sdkRoots(source)
|
||||
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
|
||||
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
|
||||
}
|
||||
|
||||
fun sdkRoots(source: Path): List<String> {
|
||||
val properties = Properties()
|
||||
val local = source.resolve("local.properties")
|
||||
if (Files.isRegularFile(local)) Files.newInputStream(local).use(properties::load)
|
||||
val roots = listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
|
||||
return listOfNotNull(properties.getProperty("sdk.dir"), System.getenv("ANDROID_HOME"), System.getenv("ANDROID_SDK_ROOT"),
|
||||
System.getenv("LOCALAPPDATA")?.let { "$it/Android/Sdk" },
|
||||
System.getProperty("user.home")?.let { "$it/Library/Android/sdk" },
|
||||
System.getProperty("user.home")?.let { "$it/Android/Sdk" })
|
||||
val executable = if (System.getProperty("os.name").startsWith("Windows")) "adb.exe" else "adb"
|
||||
return roots.map { Path.of(it).resolve("platform-tools").resolve(executable) }.firstOrNull { Files.isRegularFile(it) }?.toString() ?: "adb"
|
||||
}
|
||||
|
||||
fun list(adb: String): List<AdbDevice> {
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
object InstallActions {
|
||||
private val word = Regex("[A-Za-z0-9_./:@%+=,-]+")
|
||||
fun commands(text: String): List<List<String>> {
|
||||
require(text.toByteArray().size <= 16384) { "安装命令最多16KiB" }
|
||||
return text.lineSequence().map(String::trim).filter { it.isNotEmpty() && !it.startsWith('#') }.map { line ->
|
||||
val parts = line.split(Regex("\\s+")).let { if (it.first().lowercase() in setOf("adb", "adb.exe")) it.drop(1) else it }
|
||||
require(parts.size >= 2 && parts.first() == "shell") { "仅支持adb shell命令;设备由插件自动指定,请勿填写-s/-d/-e" }
|
||||
require(parts.all { word.matches(it) }) { "参数不支持引号、管道、重定向或命令拼接" }
|
||||
parts
|
||||
}.toList().also { require(it.size <= 10) { "每个安装阶段最多10条命令" } }
|
||||
}
|
||||
private fun process(args: List<String>, seconds: Long, log: (String) -> Unit): String {
|
||||
val file = Files.createTempFile("remotecompile-adb-action-", ".log")
|
||||
try {
|
||||
val p = ProcessBuilder(args).redirectErrorStream(true).redirectOutput(file.toFile()).start()
|
||||
try {
|
||||
check(p.waitFor(seconds, TimeUnit.SECONDS)) { "命令超时(${seconds}秒),结果未确认" }
|
||||
val output = Files.newInputStream(file).use { String(it.readNBytes(65536), Charsets.UTF_8) }
|
||||
if (output.isNotBlank()) log(output)
|
||||
log("退出码:${p.exitValue()}")
|
||||
check(p.exitValue() == 0) { "命令失败,退出码${p.exitValue()}" }
|
||||
return output
|
||||
} finally { if (p.isAlive) { p.destroyForcibly(); p.waitFor(3, TimeUnit.SECONDS) } }
|
||||
} finally { Files.deleteIfExists(file) }
|
||||
}
|
||||
private fun hooks(adb: String, serial: String, stage: String, entries: List<List<String>>, log: (String) -> Unit) {
|
||||
entries.forEachIndexed { index, args ->
|
||||
log("[$stage ${index + 1}/${entries.size}] adb -s $serial ${args.joinToString(" ")}")
|
||||
process(listOf(adb, "-s", serial) + args, 30, log)
|
||||
}
|
||||
}
|
||||
private fun applicationId(source: Path, adb: String, apk: Path): String {
|
||||
val roots = AdbDevices.sdkRoots(source) + listOfNotNull(runCatching { Path.of(adb).takeIf { it.isAbsolute }?.parent?.parent?.toString() }.getOrNull())
|
||||
val name = if (System.getProperty("os.name").startsWith("Windows")) "aapt.exe" else "aapt"
|
||||
val candidates = roots.distinct().flatMap { root ->
|
||||
val tools = Path.of(root).resolve("build-tools")
|
||||
if (!Files.isDirectory(tools)) emptyList() else Files.list(tools).use { paths -> paths.sorted(Comparator.reverseOrder()).map { it.resolve(name) }.filter(Files::isRegularFile).toList() }
|
||||
}
|
||||
for (candidate in candidates) {
|
||||
val output = runCatching { process(listOf(candidate.toString(), "dump", "badging", apk.toString()), 15) {} }.getOrNull() ?: continue
|
||||
Regex("(?m)^package: name='([A-Za-z0-9_]+(?:\\.[A-Za-z0-9_]+)+)'").find(output)?.let { return it.groupValues[1] }
|
||||
}
|
||||
error("无法读取APK包名,请检查项目SDK build-tools中的aapt")
|
||||
}
|
||||
private fun launch(source: Path, adb: String, serial: String, apk: Path, log: (String) -> Unit) {
|
||||
val pkg = applicationId(source, adb, apk)
|
||||
val prefix = listOf(adb, "-s", serial, "shell")
|
||||
val resolved = process(prefix + listOf("cmd", "package", "resolve-activity", "--brief", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", pkg), 30, {})
|
||||
val component = resolved.lineSequence().map(String::trim).lastOrNull {
|
||||
it.startsWith("$pkg/") && Regex("[A-Za-z0-9_.]+/[A-Za-z0-9_.$]+").matches(it)
|
||||
} ?: error("${pkg}没有可解析的默认Launcher入口")
|
||||
log("[打开应用] adb -s $serial:$component")
|
||||
val output = process(prefix + listOf("am", "start", "-W", "-a", "android.intent.action.MAIN", "-c", "android.intent.category.LAUNCHER", "-n", "'$component'"), 30, log)
|
||||
check(!output.contains("Error:") && !output.contains("Exception")) { "启动失败,请查看上方输出" }
|
||||
}
|
||||
private val installs = java.util.concurrent.ConcurrentHashMap<String, java.util.concurrent.locks.ReentrantLock>()
|
||||
fun install(source: Path, cfg: Settings.Data, adb: String, serial: String, apk: Path, log: (String) -> Unit) {
|
||||
val lock = installs.computeIfAbsent("$adb\n$serial") { java.util.concurrent.locks.ReentrantLock() }
|
||||
check(lock.tryLock()) { "该本机设备正在安装,请稍后重试" }
|
||||
try {
|
||||
val before = commands(cfg.beforeInstall); val after = commands(cfg.afterInstall)
|
||||
hooks(adb, serial, "安装前", before, log)
|
||||
log("[安装APK] adb -s $serial install -r $apk")
|
||||
val output = process(listOf(adb, "-s", serial, "install", "-r", apk.toString()), 120, log)
|
||||
check(output.contains("Success")) { "ADB未确认安装成功" }
|
||||
log("安装已成功")
|
||||
try {
|
||||
hooks(adb, serial, "安装后", after, log)
|
||||
if (cfg.launchAfterInstall) launch(source, adb, serial, apk, log)
|
||||
} catch (e: Exception) { log("安装已成功,后续操作未完成:${e.message}") }
|
||||
} finally { lock.unlock() }
|
||||
}
|
||||
}
|
||||
@@ -437,13 +437,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
settings.selectDevice(target.serial)
|
||||
append("安装目标:$target")
|
||||
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
|
||||
try {
|
||||
val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString())
|
||||
.redirectErrorStream(true).redirectOutput(outputLog.toFile()).start()
|
||||
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("adb 安装超时") }
|
||||
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
|
||||
} finally { Files.deleteIfExists(outputLog) }
|
||||
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
|
||||
}
|
||||
private fun setBuildId(id: String) = ApplicationManager.getApplication().invokeLater { if (!disposed) buildIdField.text = id }
|
||||
private fun showProgress(message: String, percent: Int = -1) = ApplicationManager.getApplication().invokeLater {
|
||||
@@ -597,12 +591,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
val target = AdbDevices.choose(AdbDevices.list(adb), explicit?.serial ?: cfg.device, explicit != null)
|
||||
check(target != null) { "请选择在线且已授权的设备" }
|
||||
append("安装构建 ${record.buildId} 到 $target")
|
||||
val outputLog = Files.createTempFile("remote-install-", ".log")
|
||||
try {
|
||||
val process = ProcessBuilder(adb, "-s", target.serial, "install", "-r", output.toString()).redirectErrorStream(true).redirectOutput(outputLog.toFile()).start()
|
||||
if (!process.waitFor(120, TimeUnit.SECONDS)) { process.destroyForcibly(); error("安装超时") }
|
||||
append(Files.readString(outputLog)); check(process.exitValue() == 0) { "adb 安装失败" }
|
||||
} finally { Files.deleteIfExists(outputLog) }
|
||||
InstallActions.install(source, cfg, adb, target.serial, output, ::append)
|
||||
} catch (e: Exception) { append("安装失败:${e.message ?: e.javaClass.simpleName}") }
|
||||
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
|
||||
}
|
||||
|
||||
@@ -14,13 +14,13 @@ object ServerAdb {
|
||||
validateEndpoint(base)
|
||||
val token = PasswordSafe.instance.getPassword(credentials(base)).orEmpty()
|
||||
check(token.isNotBlank()) { "请先保存服务器 Token" }
|
||||
val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/adb/$route"))
|
||||
val builder = HttpRequest.newBuilder(URI.create(base + if (route == "health") "/api/v1/health" else "/api/v1/adb/$route"))
|
||||
.header("Authorization", "Bearer $token").header("Content-Type", "application/json")
|
||||
.timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(4))
|
||||
.timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(15))
|
||||
val req = if (body == null) builder.GET().build() else builder.POST(HttpRequest.BodyPublishers.ofString(Gson().toJson(body))).build()
|
||||
val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString())
|
||||
check(response.statusCode() in 200..299) {
|
||||
if (response.statusCode() == 404) "服务端需升级至 0.6.0 才支持远程 ADB" else response.body().replace(token, "***")
|
||||
if (response.statusCode() == 404) "服务端需升级以支持当前ADB功能" else response.body().replace(token, "***")
|
||||
}
|
||||
return Gson().fromJson(response.body(), JsonObject::class.java)
|
||||
}
|
||||
@@ -28,6 +28,13 @@ object ServerAdb {
|
||||
val d = it.asJsonObject
|
||||
AdbDevice(d.get("serial").asString, d.get("state").asString, d.get("model")?.asString.orEmpty())
|
||||
}
|
||||
fun install(cfg: Settings.Data, buildId: String, artifact: String, serial: String): String =
|
||||
call(cfg, "install", mapOf("buildId" to buildId, "artifact" to artifact, "serial" to serial)).get("output").asString
|
||||
fun install(cfg: Settings.Data, buildId: String, artifact: String, serial: String): String {
|
||||
val before = InstallActions.commands(cfg.beforeInstall); val after = InstallActions.commands(cfg.afterInstall)
|
||||
val body = mutableMapOf<String, Any>("buildId" to buildId, "artifact" to artifact, "serial" to serial)
|
||||
if (before.isNotEmpty() || after.isNotEmpty() || cfg.launchAfterInstall) {
|
||||
check(call(cfg, "health").get("installActions")?.asBoolean == true) { "服务端需升级至0.8.0,才支持安装前后命令和安装后打开应用" }
|
||||
body["beforeCommands"] = cfg.beforeInstall; body["afterCommands"] = cfg.afterInstall; body["launchAfter"] = cfg.launchAfterInstall
|
||||
}
|
||||
return call(cfg, "install", body).get("output").asString
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import javax.swing.event.DocumentListener
|
||||
class ConnectionDefaults : PersistentStateComponent<Settings.Data> {
|
||||
@Volatile private var data = Settings.Data()
|
||||
@Synchronized override fun getState() = data.copy()
|
||||
@Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
|
||||
@Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", beforeInstall = "", afterInstall = "", launchAfterInstall = false, remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
|
||||
}
|
||||
|
||||
@State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")])
|
||||
@@ -39,6 +39,9 @@ class Settings : PersistentStateComponent<Settings.Data> {
|
||||
var remoteAdb: Boolean = false,
|
||||
var remoteDevice: String = "",
|
||||
var install: Boolean = false,
|
||||
var beforeInstall: String = "",
|
||||
var afterInstall: String = "",
|
||||
var launchAfterInstall: Boolean = false,
|
||||
var serverCertificate: String = "",
|
||||
var configured: Boolean = false
|
||||
)
|
||||
@@ -46,7 +49,7 @@ class Settings : PersistentStateComponent<Settings.Data> {
|
||||
private fun defaults() = ApplicationManager.getApplication()?.getService(ConnectionDefaults::class.java)
|
||||
@Synchronized fun snapshot(): Data {
|
||||
val shared = if (!data.configured) defaults()?.getState() else null
|
||||
return if (shared?.configured == true) shared.copy(remoteAdb = data.remoteAdb, remoteDevice = data.remoteDevice, projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy()
|
||||
return if (shared?.configured == true) shared.copy(beforeInstall = data.beforeInstall, afterInstall = data.afterInstall, launchAfterInstall = data.launchAfterInstall, remoteAdb = data.remoteAdb, remoteDevice = data.remoteDevice, projectId = data.projectId, device = data.device, remoteFolder = data.remoteFolder, remoteJavaHome = data.remoteJavaHome, taskHistory = data.taskHistory.toMutableList()) else data.copy()
|
||||
}
|
||||
@Synchronized override fun getState(): Data = data.copy()
|
||||
@Synchronized override fun loadState(state: Data) {
|
||||
@@ -102,6 +105,9 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
|
||||
private val adb = JTextField(original.adb)
|
||||
private val certificate = JTextField(original.serverCertificate)
|
||||
private val install = JCheckBox("构建成功后自动安装(无可用设备时仅下载 APK)", original.install)
|
||||
private val beforeInstall = JTextArea(original.beforeInstall, 4, 24)
|
||||
private val afterInstall = JTextArea(original.afterInstall, 4, 24)
|
||||
private val launchAfter = JCheckBox("安装后打开应用(目标设备默认Launcher入口)", original.launchAfterInstall)
|
||||
private val save = JButton("保存配置")
|
||||
private val status = JLabel("Token 留空保留已保存值")
|
||||
private val tokenStatus = JLabel("正在读取已保存 Token…")
|
||||
@@ -143,7 +149,18 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
|
||||
val picker = JFileChooser().apply { fileFilter = javax.swing.filechooser.FileNameExtensionFilter("服务器证书", "crt", "pem", "cer") }
|
||||
if (picker.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) certificate.text = picker.selectedFile.absolutePath
|
||||
}
|
||||
fields.add(choose); fields.add(install); fields.add(checkRemote); fields.add(save); fields.add(status)
|
||||
val actionsButton = JButton("编辑安装前 / 安装后 ADB 命令…")
|
||||
actionsButton.addActionListener {
|
||||
val panel = JPanel(BorderLayout(0, 8)).apply {
|
||||
add(JLabel("每行一条 adb shell 命令,自动绑定所选设备;不支持引号、管道或重定向。"), BorderLayout.NORTH)
|
||||
add(JPanel(GridLayout(2, 1, 0, 8)).apply {
|
||||
add(JPanel(BorderLayout()).apply { add(JLabel("安装前(失败停止安装)"), BorderLayout.NORTH); add(JScrollPane(beforeInstall)) })
|
||||
add(JPanel(BorderLayout()).apply { add(JLabel("安装后(失败停止后续操作,保留安装成功)"), BorderLayout.NORTH); add(JScrollPane(afterInstall)) })
|
||||
}, BorderLayout.CENTER)
|
||||
}
|
||||
JOptionPane.showMessageDialog(this, panel, "安装命令(编辑后点击保存配置)", JOptionPane.PLAIN_MESSAGE)
|
||||
}
|
||||
fields.add(choose); fields.add(install); fields.add(actionsButton); fields.add(launchAfter); fields.add(checkRemote); fields.add(save); fields.add(status)
|
||||
checkRemote.addActionListener { checkRemoteProject() }
|
||||
val content = object : JPanel(BorderLayout(0, 8)), Scrollable {
|
||||
override fun getPreferredScrollableViewportSize() = preferredSize
|
||||
@@ -176,12 +193,12 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
|
||||
restoreToken()
|
||||
save.addActionListener {
|
||||
val base = url.text.trim().trimEnd('/')
|
||||
try { validateEndpoint(base); require(remoteFolder.text.isNotBlank()) { "请填写服务端已有工程文件夹" } }
|
||||
try { InstallActions.commands(beforeInstall.text); InstallActions.commands(afterInstall.text); validateEndpoint(base); require(remoteFolder.text.isNotBlank()) { "请填写服务端已有工程文件夹" } }
|
||||
catch (e: IllegalArgumentException) { status.text = e.message; return@addActionListener }
|
||||
tokenRequest++ // Discard a pending restore before replacing/saving this credential.
|
||||
val entered = String(token.password); token.text = ""
|
||||
val previous = settings.snapshot()
|
||||
val next = previous.copy(url = base, remoteFolder = remoteFolder.text.trim(), remoteJavaHome = (jdks.selectedItem as? JdkChoice)?.home.orEmpty(), ignoreLineEndings = ignoreLineEndings.isSelected, adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(),
|
||||
val next = previous.copy(beforeInstall = beforeInstall.text, afterInstall = afterInstall.text, launchAfterInstall = launchAfter.isSelected, url = base, remoteFolder = remoteFolder.text.trim(), remoteJavaHome = (jdks.selectedItem as? JdkChoice)?.home.orEmpty(), ignoreLineEndings = ignoreLineEndings.isSelected, adb = adb.text.trim(), install = install.isSelected, serverCertificate = certificate.text.trim(),
|
||||
projectId = if (previous.url == base && previous.remoteFolder == remoteFolder.text.trim()) previous.projectId else "")
|
||||
save.isEnabled = false; status.text = "正在保存…"
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
|
||||
Reference in new issue
Block a user