feat: 完善远程构建恢复、工程同步与变体选择
增加持久化构建记录、历史 APK 恢复、断点下载、Gradle 缓存复用、系统代理与按工程选择服务端 JDK。 支持已有工程目录、Git 状态检查、原生忽略规则和文本换行等价比较,修复干净检出与历史同步快照不一致时的误拦截。 优化插件设备可选构建、侧栏滚动、左右日志布局、时间显示和构建变体快速选择,并补充部署与协议文档。 验证:17 项 Go 测试、22 项插件测试及 HTTP/HTTPS 两条端到端测试通过;Linux/macOS 服务端交叉编译通过。
This commit is contained in:
1 parent
2203afde3c
commit
2cb70beb69
44 files changed
+3310
-236
No files matched your search
@@ -17,6 +17,7 @@ import com.intellij.openapi.wm.ToolWindow
|
||||
import com.intellij.openapi.wm.ToolWindowFactory
|
||||
import com.intellij.openapi.wm.ToolWindowManager
|
||||
import com.intellij.ui.content.ContentFactory
|
||||
import com.intellij.util.ui.JBUI
|
||||
import java.awt.BorderLayout
|
||||
import java.net.URI
|
||||
import java.net.URLEncoder
|
||||
@@ -64,6 +65,9 @@ class RemoteSettingsAction : AnAction() {
|
||||
|
||||
class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Disposable {
|
||||
private val settings = project.getService(Settings::class.java)
|
||||
private val taskSelector = JComboBox<String>().apply { isEditable = true; maximumRowCount = 12 }
|
||||
private var updatingTasks = false
|
||||
private var discoveredTasks = emptyList<String>()
|
||||
private val devices = JComboBox<AdbDevice>()
|
||||
private val refresh = JButton("刷新设备")
|
||||
private val deviceStatus = JLabel("正在读取本机设备…")
|
||||
@@ -72,7 +76,22 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
@Volatile private var disposed = false
|
||||
private val run = JButton("Remote Run")
|
||||
private val cancel = JButton("取消远程构建")
|
||||
private val log = JTextArea().apply { isEditable = false }
|
||||
private val buildIdField = JTextField(24)
|
||||
private val progress = JProgressBar(0, 100).apply {
|
||||
isStringPainted = false
|
||||
preferredSize = JBUI.size(220, 12)
|
||||
}
|
||||
private val progressPercent = JLabel("—")
|
||||
private val progressStatus = JTextArea("就绪", 2, 0).apply {
|
||||
isEditable = false; isOpaque = false; lineWrap = true; wrapStyleWord = true
|
||||
font = UIManager.getFont("Label.font")
|
||||
foreground = UIManager.getColor("Label.foreground")
|
||||
minimumSize = JBUI.size(0, 32)
|
||||
}
|
||||
private val resume = JButton("恢复上次构建")
|
||||
private val fetch = JButton("下载 APK")
|
||||
private val log = JTextArea().apply { isEditable = false; lineWrap = true; wrapStyleWord = true }
|
||||
private val logFormat = TimestampedLog()
|
||||
@Volatile private var activeBuild = ""
|
||||
@Volatile private var cancelRequested = false
|
||||
@Volatile private var busy = false
|
||||
@@ -81,8 +100,23 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
private val polling = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay({ refreshDevices() }, 1, 5, TimeUnit.SECONDS)
|
||||
init {
|
||||
val configure = JButton("连接设置")
|
||||
val buttons = JPanel().apply { add(JLabel("目标设备")); add(devices); add(refresh); add(run); add(cancel); add(configure) }
|
||||
val top = JPanel(BorderLayout()).apply { add(buttons, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) }
|
||||
val refreshTasks = JButton("刷新变体")
|
||||
val variants = JPanel(BorderLayout(0, JBUI.scale(6))).apply {
|
||||
add(JLabel("构建变体 / Gradle 任务"), BorderLayout.NORTH)
|
||||
add(taskSelector, BorderLayout.CENTER); add(refreshTasks, BorderLayout.SOUTH)
|
||||
}
|
||||
taskSelector.toolTipText = "选择任务或直接输入;自动记住最近 20 个任务"
|
||||
updateTaskChoices(settings.snapshot().task)
|
||||
taskSelector.addActionListener {
|
||||
if (!updatingTasks) {
|
||||
val value = taskSelector.editor.item?.toString()?.trim().orEmpty()
|
||||
if (BuildTasks.valid(value)) { settings.selectTask(value); updateTaskChoices(value) }
|
||||
}
|
||||
}
|
||||
refreshTasks.addActionListener { refreshTaskChoices(refreshTasks) }
|
||||
refreshTaskChoices(refreshTasks)
|
||||
val buttons = JPanel(java.awt.GridLayout(0, 2, JBUI.scale(6), JBUI.scale(6))).apply { add(run); add(cancel); add(refresh); add(configure) }
|
||||
val top = JPanel(BorderLayout(0, JBUI.scale(6))).apply { add(JLabel("目标设备"), BorderLayout.NORTH); add(devices, BorderLayout.CENTER); add(deviceStatus, BorderLayout.SOUTH) }
|
||||
devices.prototypeDisplayValue = AdbDevice("serial", "device", "选择本机设备或模拟器")
|
||||
devices.renderer = object : DefaultListCellRenderer() {
|
||||
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, selected: Boolean, focus: Boolean): java.awt.Component {
|
||||
@@ -94,10 +128,79 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
devices.addActionListener { if (!updatingDevices) (devices.selectedItem as? AdbDevice)?.takeIf { it.online }?.let { settings.selectDevice(it.serial) } }
|
||||
refresh.addActionListener { refreshDevices() }
|
||||
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
|
||||
add(top, BorderLayout.NORTH); add(JScrollPane(log), BorderLayout.CENTER)
|
||||
val recovery = JPanel(java.awt.GridLayout(0, 1, 0, JBUI.scale(6))).apply {
|
||||
add(JLabel("构建ID(留空找回上次)")); add(buildIdField); add(resume); add(fetch)
|
||||
val history = JButton("构建历史"); history.addActionListener { showHistory() }; add(history)
|
||||
val installLast = JButton("安装已下载 APK"); installLast.addActionListener { installDownloaded() }; add(installLast)
|
||||
val environment = JButton("查看构建环境")
|
||||
environment.addActionListener { showEnvironment() }; add(environment)
|
||||
}
|
||||
val progressArea = JPanel(BorderLayout(0, JBUI.scale(4))).apply {
|
||||
border = JBUI.Borders.empty(4, 8, 6, 8)
|
||||
add(JPanel(java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0)).apply {
|
||||
add(progress)
|
||||
add(JLabel(" "))
|
||||
add(progressPercent)
|
||||
}, BorderLayout.NORTH)
|
||||
add(JScrollPane(progressStatus).apply {
|
||||
border = BorderFactory.createEmptyBorder()
|
||||
isOpaque = false; viewport.isOpaque = false
|
||||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||||
}, BorderLayout.CENTER)
|
||||
}
|
||||
val sections = JPanel().apply {
|
||||
layout = BoxLayout(this, BoxLayout.Y_AXIS)
|
||||
listOf(top, variants, buttons, recovery, progressArea).forEach { section ->
|
||||
section.alignmentX = java.awt.Component.LEFT_ALIGNMENT
|
||||
section.maximumSize = java.awt.Dimension(Int.MAX_VALUE, section.preferredSize.height)
|
||||
add(section); add(Box.createVerticalStrut(JBUI.scale(10)))
|
||||
}
|
||||
}
|
||||
val controls = object : JPanel(BorderLayout()), Scrollable {
|
||||
override fun getPreferredScrollableViewportSize() = preferredSize
|
||||
override fun getScrollableTracksViewportWidth() = true
|
||||
override fun getScrollableTracksViewportHeight() = false
|
||||
override fun getScrollableUnitIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = JBUI.scale(20)
|
||||
override fun getScrollableBlockIncrement(rect: java.awt.Rectangle, orientation: Int, direction: Int) = maxOf(JBUI.scale(20), rect.height - JBUI.scale(20))
|
||||
}.apply { border = JBUI.Borders.empty(10); add(sections, BorderLayout.NORTH) }
|
||||
resume.addActionListener { recoverBuild(false) }
|
||||
fetch.addActionListener { recoverBuild(true) }
|
||||
val controlsScroll = JScrollPane(controls).apply {
|
||||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||||
minimumSize = JBUI.size(220, 0)
|
||||
}
|
||||
val logScroll = JScrollPane(log).apply {
|
||||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||||
minimumSize = JBUI.size(200, 0)
|
||||
}
|
||||
add(JSplitPane(JSplitPane.HORIZONTAL_SPLIT, controlsScroll, logScroll).apply {
|
||||
isContinuousLayout = true; isOneTouchExpandable = true
|
||||
resizeWeight = 0.0; dividerLocation = JBUI.scale(320)
|
||||
border = BorderFactory.createEmptyBorder()
|
||||
}, BorderLayout.CENTER)
|
||||
run.addActionListener { runBuild() }
|
||||
cancel.addActionListener { cancelRequested = true; append("已请求取消,等待当前网络操作结束…") }
|
||||
}
|
||||
private fun updateTaskChoices(selected: String) {
|
||||
val cfg = settings.snapshot()
|
||||
val choices = (listOf(selected) + cfg.taskHistory + discoveredTasks + listOf(":app:assembleDebug")).filter { it.isNotBlank() }.distinct()
|
||||
updatingTasks = true
|
||||
try { taskSelector.model = DefaultComboBoxModel(choices.toTypedArray()); taskSelector.selectedItem = selected }
|
||||
finally { updatingTasks = false }
|
||||
}
|
||||
private fun refreshTaskChoices(button: JButton) {
|
||||
button.isEnabled = false
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
val result = runCatching { project.basePath?.let { BuildTasks.discover(Path.of(it)) }.orEmpty() }
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed) {
|
||||
button.isEnabled = true
|
||||
result.onSuccess { discoveredTasks = it; updateTaskChoices(taskSelector.editor.item?.toString()?.trim().orEmpty().ifEmpty { settings.snapshot().task }) }
|
||||
.onFailure { append("读取变体候选失败,可直接输入任务:${it.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
override fun dispose() {
|
||||
disposed = true; polling.cancel(false)
|
||||
if (!project.isDisposed && project.getService(PanelService::class.java).panel === this) project.getService(PanelService::class.java).panel = null
|
||||
@@ -126,9 +229,20 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
}
|
||||
private fun append(text: String) = ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed) { log.append(text + "\n"); log.caretPosition = log.document.length }
|
||||
if (!disposed && !project.isDisposed) { log.append(logFormat.message(text)); log.caretPosition = log.document.length }
|
||||
}
|
||||
private fun appendBuildChunk(text: String) = ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed) { log.append(logFormat.chunk(text)); log.caretPosition = log.document.length }
|
||||
}
|
||||
private fun hash(data: ByteArray) = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
|
||||
private fun fileHash(path: Path): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
Files.newInputStream(path).use { input ->
|
||||
val buffer = ByteArray(128 * 1024)
|
||||
while (true) { val count = input.read(buffer); if (count < 0) break; digest.update(buffer, 0, count) }
|
||||
}
|
||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
||||
}
|
||||
private fun request(base: String, secret: String, method: String, route: String, body: Any? = null): ByteArray {
|
||||
val publisher = if (body == null) HttpRequest.BodyPublishers.noBody() else HttpRequest.BodyPublishers.ofString(gson.toJson(body))
|
||||
val req = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofMinutes(5))
|
||||
@@ -156,16 +270,16 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
}
|
||||
private fun beginBuild() {
|
||||
val selectedTask = taskSelector.editor.item?.toString()?.trim().orEmpty()
|
||||
settings.selectTask(selectedTask)
|
||||
updateTaskChoices(selectedTask)
|
||||
val cfg = settings.snapshot()
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
validateEndpoint(base)
|
||||
require(cfg.remoteFolder.isNotBlank()) { "请在 Remote Configuration 中填写服务端已有工程文件夹,并点击检查远程工程" }
|
||||
val selected = devices.selectedItem as? AdbDevice
|
||||
if (cfg.install) {
|
||||
require(selected == null || selected.online) { "请选择已连接且已授权的设备" }
|
||||
if (selected != null) cfg.device = selected.serial
|
||||
}
|
||||
val source = project.basePath?.let { Path.of(it) } ?: error("项目路径不存在")
|
||||
cancelRequested = false; activeBuild = ""; log.text = ""
|
||||
cancelRequested = false; activeBuild = ""; log.text = ""; logFormat.reset()
|
||||
object : Task.Backgroundable(project, "Remote Compilation", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
var secret = ""
|
||||
@@ -173,80 +287,67 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
http = ServerTls.client(cfg.serverCertificate)
|
||||
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
|
||||
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
|
||||
if (cfg.install) {
|
||||
val connected = AdbDevices.list(AdbDevices.resolve(source, cfg.adb)).filter { it.online }
|
||||
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
|
||||
check(target != null) { "请从设备列表选择已连接且已授权的设备" }
|
||||
cfg.device = target.serial
|
||||
settings.selectDevice(target.serial)
|
||||
refreshDevices()
|
||||
append("目标设备:$target")
|
||||
}
|
||||
json(base, secret, "GET", "/health")
|
||||
append("构建任务:${cfg.task}")
|
||||
append(if (selected?.online == true) "目标设备:$selected" else "当前没有选中的在线设备;继续远程编译并下载 APK")
|
||||
val health = json(base, secret, "GET", "/health")
|
||||
check(health.get("recovery")?.asBoolean == true) { "编译服务需升级到 0.2.0 才支持任务找回与环境复用" }
|
||||
check(health.get("textComparison")?.asBoolean == true && health.get("jdkSelection")?.asBoolean == true) { "编译服务需升级到 0.4.0 才支持换行比较及 JDK 选择" }
|
||||
check(health.get("workspaceSelection")?.asBoolean == true) { "编译服务需升级到 0.3.0 才支持工程目录与 Git 检查" }
|
||||
val localGit = SourceFiles.snapshot(source)
|
||||
val checkBody = mapOf("workspacePath" to cfg.remoteFolder, "projectId" to cfg.projectId, "git" to localGit)
|
||||
val inspection = json(base, secret, "POST", "/projects/check", checkBody)
|
||||
append("远程位置:${inspection.get("workspacePath").asString}")
|
||||
append("Git 检查:${inspection.get("message").asString};本机=$localGit;服务端=${inspection.get("git")}")
|
||||
check(inspection.get("canSync").asBoolean) { inspection.get("message").asString }
|
||||
val candidates = SourceFiles.collect(source, localGit)
|
||||
if (cfg.projectId.isBlank()) {
|
||||
cfg.projectId = json(base, secret, "POST", "/projects").get("id").asString
|
||||
settings.projectAllocated(base, cfg.projectId)
|
||||
cfg.projectId = json(base, secret, "POST", "/projects", checkBody).get("id").asString
|
||||
settings.projectAllocated(base, cfg.projectId, cfg.remoteFolder)
|
||||
}
|
||||
val manifest = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest").getAsJsonObject("files")
|
||||
val files = linkedMapOf<String, Map<String, String>>()
|
||||
val excludes = setOf(".git", ".gradle", ".idea", "build", ".remotecompile", "node_modules", ".kotlin")
|
||||
var changed = 0
|
||||
Files.walk(source).use { paths -> paths.filter { path ->
|
||||
val rel = source.relativize(path)
|
||||
rel.none { it.toString() in excludes } && !Files.isDirectory(path)
|
||||
}.forEach { path ->
|
||||
check(!Files.isSymbolicLink(path)) { "暂不支持符号链接:$path" }
|
||||
var changed = 0; var lineEndingsOnly = 0
|
||||
for (path in candidates) {
|
||||
val name = source.relativize(path).joinToString("/")
|
||||
val leaf = path.fileName.toString()
|
||||
if (leaf == "local.properties" || leaf.endsWith(".jks") || leaf.endsWith(".keystore") || leaf.startsWith(".env") || leaf in setOf("key.properties", "keystore.properties")) return@forEach
|
||||
check(Files.size(path) <= 64L * 1024 * 1024) { "文件超过首版 64MiB 上限:$name" }
|
||||
val bytes = Files.readAllBytes(path); val hash = hash(bytes)
|
||||
files[name] = if (manifest?.getAsJsonObject(name)?.get("hash")?.asString == hash) mapOf("hash" to hash)
|
||||
else { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
|
||||
} }
|
||||
val remote = manifest?.getAsJsonObject(name)
|
||||
val remoteHash = remote?.get("hash")?.asString
|
||||
val remoteTextHash = remote?.get("textHash")?.asString
|
||||
files[name] = when {
|
||||
remoteHash == hash -> mapOf("hash" to hash)
|
||||
cfg.ignoreLineEndings && remoteTextHash != null && remoteTextHash == SyncComparison.textHash(name, bytes) -> {
|
||||
lineEndingsOnly++; mapOf("hash" to checkNotNull(remoteHash))
|
||||
}
|
||||
else -> { changed++; mapOf("hash" to hash, "data" to Base64.getEncoder().encodeToString(bytes)) }
|
||||
}
|
||||
}
|
||||
check(SourceFiles.snapshot(source).let { it?.head == localGit?.head && it?.branch == localGit?.branch }) { "扫描期间 Git 状态发生变化,请重新运行" }
|
||||
check(!cancelRequested) { "已取消" }
|
||||
val revision = UUID.randomUUID().toString()
|
||||
append("同步 ${files.size} 个文件,上传 $changed 个变更文件…")
|
||||
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files))
|
||||
append("同步 ${files.size} 个文件,上传 $changed 个变更文件,跳过 $lineEndingsOnly 个仅换行不同的文件…")
|
||||
json(base, secret, "POST", "/projects/${cfg.projectId}/sync", mapOf("revision" to revision, "files" to files, "git" to localGit))
|
||||
check(!cancelRequested) { "已取消" }
|
||||
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds", mapOf("revision" to revision, "task" to cfg.task)).get("id").asString
|
||||
var offset = 0
|
||||
var result: JsonObject
|
||||
while (true) {
|
||||
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$activeBuild"); error("已请求取消远程构建") }
|
||||
result = json(base, secret, "GET", "/builds/$activeBuild")
|
||||
val lines = result.getAsJsonArray("logs")
|
||||
while (offset < lines.size()) append(lines[offset++].asString)
|
||||
if (result.get("status").asString !in listOf("queued", "running")) break
|
||||
Thread.sleep(700)
|
||||
}
|
||||
check(result.get("status").asString == "success") { "构建状态:${result.get("status").asString}" }
|
||||
val artifacts = result.getAsJsonArray("artifacts")
|
||||
check(artifacts.size() == 1) { "首版要求恰好一个 APK,实际 ${artifacts.size()} 个;请调整构建任务" }
|
||||
val artifact = artifacts[0].asJsonObject
|
||||
val name = artifact.get("name").asString
|
||||
val encodedName = URLEncoder.encode(name, Charsets.UTF_8).replace("+", "%20")
|
||||
val bytes = request(base, secret, "GET", "/builds/$activeBuild/artifacts/$encodedName")
|
||||
check(hash(bytes) == artifact.get("hash").asString) { "APK 校验失败" }
|
||||
val output = source.resolve(".remotecompile").resolve("$activeBuild.apk")
|
||||
Files.createDirectories(output.parent); Files.write(output, bytes)
|
||||
append("APK 已保存:$output")
|
||||
val record = LastBuild(base, cfg.projectId, revision, cfg.task, UUID.randomUUID().toString(), certificate = cfg.serverCertificate, javaHome = cfg.remoteJavaHome)
|
||||
LastBuildStore.save(source, record)
|
||||
activeBuild = json(base, secret, "POST", "/projects/${cfg.projectId}/builds",
|
||||
mapOf("revision" to revision, "task" to cfg.task, "clientRequestId" to record.clientRequestId, "javaHome" to record.javaHome)).get("id").asString
|
||||
record.buildId = activeBuild; LastBuildStore.save(source, record)
|
||||
setBuildId(activeBuild)
|
||||
append("构建ID:$activeBuild(已保存,断网后可恢复)")
|
||||
val result = watchBuild(base, secret, activeBuild)
|
||||
val output = downloadApk(base, secret, activeBuild, source, result)
|
||||
check(!cancelRequested) { "已取消安装" }
|
||||
if (cfg.install) {
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
check(AdbDevices.list(adb).any { it.serial == cfg.device && it.online }) { "目标设备已断开或未授权,已保留 APK" }
|
||||
val pb = ProcessBuilder(adb, "-s", cfg.device, "install", "-r", output.toString()).redirectErrorStream(true)
|
||||
val outputLog = Files.createTempFile("remotecompile-adb-", ".log")
|
||||
try {
|
||||
val process = pb.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) }
|
||||
try { installApkWhenAvailable(source, cfg, selected, output) }
|
||||
catch (e: Exception) {
|
||||
append("编译和下载已成功,安装未完成:${e.message ?: e.javaClass.simpleName};APK 已保留,可稍后点击安装已下载 APK")
|
||||
}
|
||||
}
|
||||
append("Remote Run 完成")
|
||||
append("远程编译和 APK 下载完成")
|
||||
} catch (e: Exception) {
|
||||
// Never print request headers or the token.
|
||||
append("失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||||
append((if (activeBuild.isNotEmpty()) "构建失败(记录已保留,可点击恢复上次构建):" else "同步或启动失败(尚未确认创建构建任务):") + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||||
} finally {
|
||||
activeBuild = ""; busy = false
|
||||
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
|
||||
@@ -254,4 +355,216 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
private fun installApkWhenAvailable(source: Path, cfg: Settings.Data, selected: AdbDevice?, output: Path) {
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
val connected = AdbDevices.list(adb)
|
||||
val target = AdbDevices.choose(connected, selected?.serial ?: cfg.device, explicit = selected != null)
|
||||
if (target == null) {
|
||||
append("编译成功,APK 已保存;没有可安装的目标设备或尚未明确选择,跳过自动安装。连接并选择设备后可点击安装已下载 APK")
|
||||
return
|
||||
}
|
||||
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) }
|
||||
}
|
||||
private fun setBuildId(id: String) = ApplicationManager.getApplication().invokeLater { if (!disposed) buildIdField.text = id }
|
||||
private fun showProgress(message: String, percent: Int = -1) = ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed) {
|
||||
progress.isIndeterminate = percent < 0
|
||||
if (percent >= 0) progress.value = percent.coerceIn(0, 100)
|
||||
progressPercent.text = if (percent < 0) "进行中" else "${progress.value}%"
|
||||
progressStatus.text = message; progressStatus.caretPosition = 0
|
||||
progressStatus.toolTipText = message; progress.toolTipText = message
|
||||
}
|
||||
}
|
||||
private fun watchBuild(base: String, secret: String, id: String): JsonObject {
|
||||
var offset = 0; var failures = 0; var environmentPrinted = false
|
||||
while (true) {
|
||||
check(!project.isDisposed && !disposed) { "项目已关闭,远端任务不受影响" }
|
||||
if (cancelRequested) { json(base, secret, "DELETE", "/builds/$id"); error("已请求取消远程构建") }
|
||||
val result = try { json(base, secret, "GET", "/builds/$id").also { failures = 0 } }
|
||||
catch (e: java.io.IOException) {
|
||||
failures++; showProgress("连接中断,重试 $failures/3;远端构建不会被取消")
|
||||
if (failures >= 3) throw e
|
||||
Thread.sleep(failures * 1500L); continue
|
||||
}
|
||||
val lines = result.getAsJsonArray("logs")
|
||||
while (offset < lines.size()) appendBuildChunk(lines[offset++].asString)
|
||||
if (!environmentPrinted && result.has("environment")) {
|
||||
append("实际构建环境:" + result.get("environment")); environmentPrinted = true
|
||||
}
|
||||
val status = result.get("status").asString
|
||||
val detail = result.getAsJsonObject("progress")
|
||||
val message = detail?.get("message")?.asString.orEmpty()
|
||||
val path = detail?.get("path")?.asString.orEmpty()
|
||||
showProgress(if (message.isNotBlank()) "$message $path" else "构建 $id:$status", if (message.isNotBlank()) detail?.get("percent")?.asInt ?: -1 else -1)
|
||||
if (status !in listOf("queued", "running")) {
|
||||
showProgress("构建 $id:$status", if (status == "success") 100 else 0)
|
||||
check(status == "success") { "构建状态:$status;可查看上方日志" }
|
||||
return result
|
||||
}
|
||||
Thread.sleep(1000)
|
||||
}
|
||||
}
|
||||
private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject): Path {
|
||||
require(id.matches(Regex("[a-f0-9]{32}"))) { "无效构建 ID" }
|
||||
val artifacts = result.getAsJsonArray("artifacts")
|
||||
check(artifacts.size() == 1) { "当前要求恰好一个 APK,实际 ${artifacts.size()} 个" }
|
||||
val artifact = artifacts[0].asJsonObject
|
||||
val expected = artifact.get("hash").asString
|
||||
val size = artifact.get("size").asLong
|
||||
val output = source.resolve(".remotecompile/$id.apk"); Files.createDirectories(output.parent)
|
||||
if (Files.exists(output) && fileHash(output) == expected) { rememberArtifact(source, id, expected); append("复用已下载 APK:$output"); return output }
|
||||
val part = output.resolveSibling("$id.apk.part")
|
||||
var received = if (Files.exists(part)) Files.size(part) else 0L
|
||||
if (received > size) { Files.delete(part); received = 0 }
|
||||
if (received < size) {
|
||||
val name = URLEncoder.encode(artifact.get("name").asString, Charsets.UTF_8).replace("+", "%20")
|
||||
val builder = HttpRequest.newBuilder(URI.create("$base/api/v1/builds/$id/artifacts/$name"))
|
||||
.header("Authorization", "Bearer $secret").timeout(Duration.ofMinutes(5))
|
||||
if (received > 0) builder.header("Range", "bytes=$received-")
|
||||
val response = http.send(builder.GET().build(), HttpResponse.BodyHandlers.ofInputStream())
|
||||
response.body().use { input ->
|
||||
check(response.statusCode() == 200 || response.statusCode() == 206) { "下载 HTTP ${response.statusCode()}" }
|
||||
if (response.statusCode() == 200) received = 0
|
||||
else check(response.headers().firstValue("Content-Range").orElse("").startsWith("bytes $received-")) { "断点下载偏移不匹配" }
|
||||
val options = if (received > 0) arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND)
|
||||
else arrayOf(java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING)
|
||||
Files.newOutputStream(part, *options).use { out ->
|
||||
val buffer = ByteArray(128 * 1024); var last = 0L
|
||||
while (true) {
|
||||
check(!cancelRequested) { "下载已停止,分片保留以便续传" }
|
||||
val count = input.read(buffer); if (count < 0) break
|
||||
out.write(buffer, 0, count); received += count
|
||||
if (System.currentTimeMillis() - last > 300) { showProgress("APK 下载 $received / $size 字节", if (size > 0) (received * 100 / size).toInt() else -1); last = System.currentTimeMillis() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
check(Files.size(part) == size && fileHash(part) == expected) { Files.deleteIfExists(part); "APK 校验失败,已清理损坏分片" }
|
||||
Files.move(part, output, java.nio.file.StandardCopyOption.REPLACE_EXISTING)
|
||||
rememberArtifact(source, id, expected)
|
||||
showProgress("APK 下载完成", 100); append("APK 已保存:$output"); return output
|
||||
}
|
||||
private fun rememberArtifact(source: Path, id: String, expected: String) {
|
||||
LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; LastBuildStore.save(source, it) }
|
||||
}
|
||||
private fun installDownloaded() {
|
||||
if (busy) return
|
||||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||||
val record = try { LastBuildStore.load(source) ?: error("没有已下载构建记录") }
|
||||
catch (e: Exception) { append(e.message ?: "读取记录失败"); return }
|
||||
if (!record.buildId.matches(Regex("[a-f0-9]{32}")) || record.artifactHash.isBlank() || (buildIdField.text.isNotBlank() && buildIdField.text.trim() != record.buildId)) { append("请先下载并校验当前任务的 APK"); return }
|
||||
val cfg = settings.snapshot(); val explicit = devices.selectedItem as? AdbDevice
|
||||
busy = true; run.isEnabled = false
|
||||
object : Task.Backgroundable(project, "安装已下载 APK", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
try {
|
||||
val output = source.resolve(".remotecompile/${record.buildId}.apk")
|
||||
check(Files.isRegularFile(output) && fileHash(output) == record.artifactHash) { "已下载 APK 缺失或校验失败,请重新下载" }
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
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) }
|
||||
} catch (e: Exception) { append("安装失败:${e.message ?: e.javaClass.simpleName}") }
|
||||
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
private fun recoverBuild(downloadOnly: Boolean) {
|
||||
if (busy) return
|
||||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||||
val cfg = settings.snapshot(); val overrideId = buildIdField.text.trim()
|
||||
val record = try {
|
||||
val last = LastBuildStore.load(source)
|
||||
if (overrideId.isNotBlank() && overrideId != last?.buildId) LastBuild(cfg.url, cfg.projectId, buildId = overrideId, certificate = cfg.serverCertificate)
|
||||
else last ?: if (cfg.projectId.isNotBlank()) LastBuild(cfg.url, cfg.projectId, certificate = cfg.serverCertificate) else error("本项目没有上次构建记录;可填写构建 ID")
|
||||
} catch (e: Exception) { append(e.message ?: "读取构建记录失败"); return }
|
||||
try { validateEndpoint(record.server) } catch (e: Exception) { append(e.message ?: "地址无效"); return }
|
||||
busy = true; cancelRequested = false; run.isEnabled = false; log.text = ""; logFormat.reset()
|
||||
object : Task.Backgroundable(project, "恢复远程构建", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
var secret = ""
|
||||
try {
|
||||
http = ServerTls.client(record.certificate)
|
||||
secret = PasswordSafe.instance.getPassword(credentials(record.server)).orEmpty()
|
||||
check(secret.isNotBlank()) { "请先保存该服务器 Token:${record.server}" }
|
||||
if (record.buildId.isBlank()) {
|
||||
val found = json(record.server, secret, "GET", "/projects/${record.projectId}/builds?clientRequestId=${record.clientRequestId}").getAsJsonArray("builds")
|
||||
check(found.size() > 0 && (record.clientRequestId.isBlank() || found.size() == 1)) { "服务器未找到该提交,可核对网络恢复后再次查询;不要重复提交" }
|
||||
record.buildId = found[0].asJsonObject.get("id").asString
|
||||
}
|
||||
require(record.buildId.matches(Regex("[a-f0-9]{32}"))) { "构建 ID 格式错误" }
|
||||
activeBuild = record.buildId; LastBuildStore.save(source, record); setBuildId(activeBuild)
|
||||
append("恢复构建:$activeBuild;服务器:${record.server}")
|
||||
val result = if (downloadOnly) json(record.server, secret, "GET", "/builds/$activeBuild").also {
|
||||
check(it.get("status").asString == "success") { "构建尚未成功,请点击恢复上次构建继续查看" }
|
||||
} else watchBuild(record.server, secret, activeBuild)
|
||||
append("源码版本:${result.get("revision").asString};任务:${result.get("task").asString}")
|
||||
downloadApk(record.server, secret, activeBuild, source, result)
|
||||
append("恢复操作完成;已取回 APK,未自动安装旧版本")
|
||||
} catch (e: Exception) {
|
||||
append("恢复失败:" + (e.message ?: e.javaClass.simpleName).let { if (secret.isNotEmpty()) it.replace(secret, "***") else it })
|
||||
} finally {
|
||||
activeBuild = ""; busy = false
|
||||
ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true }
|
||||
}
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
private fun showEnvironment() {
|
||||
val cfg = settings.snapshot()
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
try {
|
||||
val client = ServerTls.client(cfg.serverCertificate)
|
||||
val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty()
|
||||
val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/environment")).header("Authorization", "Bearer $secret").build()
|
||||
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
|
||||
append("服务端环境:HTTP ${response.statusCode()} ${response.body()}")
|
||||
} catch (e: Exception) { append("读取环境失败:${e.javaClass.simpleName}") }
|
||||
}
|
||||
}
|
||||
private fun showHistory() {
|
||||
if (busy) return
|
||||
val cfg = settings.snapshot()
|
||||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||||
val projectId = cfg.projectId.ifBlank { runCatching { LastBuildStore.load(source)?.takeIf { it.server == cfg.url }?.projectId.orEmpty() }.getOrDefault("") }
|
||||
if (projectId.isBlank()) { append("本项目尚未关联远程工作区;可手动填写构建 ID"); return }
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
try {
|
||||
val client = ServerTls.client(cfg.serverCertificate)
|
||||
val secret = PasswordSafe.instance.getPassword(credentials(cfg.url)).orEmpty()
|
||||
val request = HttpRequest.newBuilder(URI.create("${cfg.url}/api/v1/projects/$projectId/builds")).header("Authorization", "Bearer $secret").build()
|
||||
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
|
||||
check(response.statusCode() == 200) { "HTTP ${response.statusCode()}" }
|
||||
val builds = gson.fromJson(response.body(), JsonObject::class.java).getAsJsonArray("builds")
|
||||
val choices = builds.map { item ->
|
||||
val b = item.asJsonObject
|
||||
"${b.get("id").asString} · ${b.get("status").asString} · ${b.get("task").asString} · 源码 ${b.get("revision").asString.take(12)}"
|
||||
}.toTypedArray()
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (!disposed && !project.isDisposed && !busy) {
|
||||
if (choices.isEmpty()) append("此工作区暂无构建历史")
|
||||
else {
|
||||
val choice = JOptionPane.showInputDialog(this, "选择任务后点击恢复或下载", "构建历史(最近50条)", JOptionPane.PLAIN_MESSAGE, null, choices, choices.first()) as? String
|
||||
if (choice != null) { buildIdField.text = choice.substringBefore(" · "); append("已选择:$choice") }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) { append("读取历史失败:${e.javaClass.simpleName}") }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user