feat: 增加独立构建工作区、服务端ADB与私有文件清单
支持Git提交导入及未提交源码叠加,APK原名下载和完成通知。新增服务端设备安装与按工程维护的私有文件清单,修复Wrapper预检查、布局及IDE读锁和保存状态问题。更新协议、测试和部署记录;服务端0.7.0,插件0.7.1。
This commit is contained in:
1 parent
87652364bc
commit
6f9cc7e7ea
44 files changed
+2742
-87
No files matched your search
@@ -3,7 +3,7 @@ package studio.tongtong.remotecompile
|
||||
import com.google.gson.JsonObject
|
||||
import java.util.Locale
|
||||
|
||||
data class ApkArtifact(val name: String, val hash: String, val size: Long, val sourcePath: String) {
|
||||
data class ApkArtifact(val name: String, val hash: String, val size: Long, val sourcePath: String, val fileName: String = sourcePath.substringAfterLast('/').replace(Regex("^\\d+-"), "")) {
|
||||
override fun toString() = "$sourcePath — ${String.format(Locale.ROOT, "%.1f", size / 1048576.0)} MiB ($name)"
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ object ApkArtifacts {
|
||||
fun read(result: JsonObject): List<ApkArtifact> = result.getAsJsonArray("artifacts").map { value ->
|
||||
val item = value.asJsonObject
|
||||
ApkArtifact(item.get("name").asString, item.get("hash").asString, item.get("size").asLong,
|
||||
item.get("sourcePath")?.asString ?: item.get("name").asString)
|
||||
item.get("sourcePath")?.asString ?: item.get("name").asString,
|
||||
item.get("fileName")?.asString ?: item.get("sourcePath")?.asString?.substringAfterLast('/') ?: item.get("name").asString.replace(Regex("^\\d+-"), ""))
|
||||
}.filter { it.name.endsWith(".apk", ignoreCase = true) }.onEach {
|
||||
require(it.hash.matches(Regex("[a-f0-9]{64}")) && it.size > 0) { "服务端 APK 摘要或大小无效:${it.name}" }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import java.nio.file.*
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
object ApkFiles {
|
||||
fun validName(name: String): Boolean = name.endsWith(".apk", true) &&
|
||||
name.none { it < ' ' || it in "\\/:*?\"<>|" } &&
|
||||
!Regex("(?i)^(CON|PRN|AUX|NUL|COM[0-9]|LPT[0-9])(?:\\.|$)").containsMatchIn(name)
|
||||
|
||||
fun publish(part: Path, directory: Path, originalName: String, now: LocalDateTime = LocalDateTime.now()): Path {
|
||||
require(validName(originalName)) { "无效的服务端 APK 文件名:$originalName" }
|
||||
val stem = originalName.dropLast(4)
|
||||
val stamp = now.format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"))
|
||||
var attempt = 0
|
||||
while (true) {
|
||||
val name = when (attempt) { 0 -> originalName; 1 -> "${stem}_$stamp.apk"; else -> "${stem}_${stamp}_${attempt}.apk" }
|
||||
val target = directory.resolve(name)
|
||||
val output = try { Files.newOutputStream(target, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) }
|
||||
catch (_: FileAlreadyExistsException) { attempt++; continue }
|
||||
try {
|
||||
output.use { out -> Files.newInputStream(part).use { it.transferTo(out) } }
|
||||
} catch (e: Exception) { Files.deleteIfExists(target); throw e }
|
||||
Files.delete(part)
|
||||
return target
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import com.intellij.ide.actions.RevealFileAction
|
||||
import com.intellij.notification.NotificationAction
|
||||
import com.intellij.notification.NotificationGroupManager
|
||||
import com.intellij.notification.NotificationType
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import com.intellij.openapi.util.text.StringUtil
|
||||
import java.nio.file.Path
|
||||
|
||||
object ApkNotifications {
|
||||
fun description(projectName: String, task: String): String {
|
||||
val segments = task.split(':').filter { it.isNotBlank() }
|
||||
val module = segments.dropLast(1).joinToString(".").ifBlank { "main" }
|
||||
val variant = segments.lastOrNull().orEmpty().removePrefix("assemble").replaceFirstChar { it.lowercaseChar() }
|
||||
return "Build completed successfully for module '${StringUtil.escapeXmlEntities(projectName)}.${StringUtil.escapeXmlEntities(module)}' with 1 build variant:<br/>" +
|
||||
"Build variant '${StringUtil.escapeXmlEntities(variant)}': locate or analyze the APK."
|
||||
}
|
||||
|
||||
fun show(project: Project, apk: Path, task: String) {
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (project.isDisposed) return@invokeLater
|
||||
val notice = NotificationGroupManager.getInstance().getNotificationGroup("Remote Compilation Builds")
|
||||
.createNotification("Remote build completed", description(project.name, task), NotificationType.INFORMATION)
|
||||
notice.addAction(NotificationAction.createSimple("locate") { RevealFileAction.openFile(apk.toFile()) })
|
||||
notice.addAction(NotificationAction.createSimple("analyze") {
|
||||
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(apk.toFile())?.let {
|
||||
FileEditorManager.getInstance(project).openFile(it, true)
|
||||
}
|
||||
})
|
||||
notice.notify(project)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
|
||||
object GitBundles {
|
||||
fun create(root: Path, head: String, base: String?): Path {
|
||||
require(head.matches(Regex("[a-fA-F0-9]{40}|[a-fA-F0-9]{64}"))) { "本机 Git 提交无效" }
|
||||
val directory = Files.createTempDirectory("remotecompile-bundle-")
|
||||
val bundle = directory.resolve("source.bundle")
|
||||
try {
|
||||
val args = mutableListOf("bundle", "create", "--version=3", bundle.toString(), "HEAD", "--filter=blob:none")
|
||||
if (!base.isNullOrBlank() && base != head && base.matches(Regex("[a-fA-F0-9]{40}|[a-fA-F0-9]{64}")) &&
|
||||
SourceFiles.git(root, listOf("merge-base", "--is-ancestor", base, head)).first == 0) args.add("^$base")
|
||||
check(SourceFiles.git(root, args).first == 0) { "生成 Git bundle 失败;请确认提交和完整 Git 历史可用" }
|
||||
check(SourceFiles.snapshot(root)?.head == head) { "生成 bundle 期间本机提交改变,请重试" }
|
||||
return bundle
|
||||
} catch (e: Exception) { Files.deleteIfExists(bundle); Files.deleteIfExists(directory); throw e }
|
||||
}
|
||||
fun delete(bundle: Path) { Files.deleteIfExists(bundle); Files.deleteIfExists(bundle.parent) }
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
data class LastBuild(var server: String = "", var projectId: String = "", var revision: String = "", var task: String = "", var clientRequestId: String = "", var buildId: String = "", var certificate: String = "", var artifactHash: String = "", var javaHome: String = "", var artifactName: String = "")
|
||||
data class LastBuild(var server: String = "", var projectId: String = "", var revision: String = "", var task: String = "", var clientRequestId: String = "", var buildId: String = "", var certificate: String = "", var artifactHash: String = "", var javaHome: String = "", var artifactName: String = "", var artifactFile: String? = null)
|
||||
object LastBuildStore {
|
||||
private val gson = Gson()
|
||||
fun load(root: Path): LastBuild? {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||||
import com.intellij.openapi.application.ApplicationManager
|
||||
import com.intellij.openapi.application.PathManager
|
||||
import com.intellij.openapi.components.Service
|
||||
import com.intellij.openapi.fileEditor.FileDocumentManager
|
||||
import com.intellij.openapi.fileEditor.FileEditorManager
|
||||
import com.intellij.openapi.project.Project
|
||||
import com.intellij.openapi.vfs.LocalFileSystem
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import com.intellij.openapi.util.Computable
|
||||
import java.net.URI
|
||||
import java.net.URLEncoder
|
||||
import java.net.http.HttpRequest
|
||||
import java.net.http.HttpResponse
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.security.MessageDigest
|
||||
import java.time.Duration
|
||||
import javax.swing.JOptionPane
|
||||
|
||||
@Service(Service.Level.PROJECT)
|
||||
class PrivateFilesEditor(private val project: Project) {
|
||||
private data class Session(val file: VirtualFile, var hash: String, var content: String)
|
||||
private val sessions = mutableMapOf<String, Session>()
|
||||
private val active = mutableSetOf<String>()
|
||||
private fun key(cfg: Settings.Data) = cfg.url.trim().trimEnd('/') + "\n" + cfg.remoteFolder.trim()
|
||||
private fun call(cfg: Settings.Data, content: String? = null, hash: String = ""): JsonObject {
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
validateEndpoint(base)
|
||||
require(cfg.remoteFolder.isNotBlank()) { "请先填写并保存服务端工程来源目录" }
|
||||
val secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty()
|
||||
check(secret.isNotBlank()) { "请先保存服务器Token" }
|
||||
val route = "/private-files" + if (content == null) "?workspacePath=" + URLEncoder.encode(cfg.remoteFolder.trim(), Charsets.UTF_8) else ""
|
||||
val builder = HttpRequest.newBuilder(URI.create(base + "/api/v1" + route)).timeout(Duration.ofSeconds(60))
|
||||
.header("Authorization", "Bearer $secret").header("Content-Type", "application/json")
|
||||
val req = if (content == null) builder.GET().build() else builder.PUT(HttpRequest.BodyPublishers.ofString(Gson().toJson(
|
||||
mapOf("workspacePath" to cfg.remoteFolder.trim(), "content" to content, "baseHash" to hash)))).build()
|
||||
val response = ServerTls.client(cfg.serverCertificate).send(req, HttpResponse.BodyHandlers.ofString())
|
||||
check(response.statusCode() in 200..299) {
|
||||
if (response.statusCode() == 404) "服务端需升级至0.7.0以支持私有文件清单" else response.body().replace(secret, "***")
|
||||
}
|
||||
return Gson().fromJson(response.body(), JsonObject::class.java)
|
||||
}
|
||||
private fun describe(data: JsonObject): String = buildString {
|
||||
append(data.get("message").asString)
|
||||
append("\n清单位置:").append(data.get("manifestPath").asString)
|
||||
data.getAsJsonArray("entries").forEach {
|
||||
val entry = it.asJsonObject
|
||||
append("\n[").append(entry.get("status").asString).append("] ")
|
||||
.append(entry.get("path").asString).append(":").append(entry.get("message").asString)
|
||||
}
|
||||
}
|
||||
fun check(cfg: Settings.Data, status: (String) -> Unit) = execute(cfg, status, { call(cfg) }) { status(describe(it)) }
|
||||
|
||||
// Network requests run on a worker; model reads hold a read action.
|
||||
private fun documentText(file: VirtualFile): String? = ApplicationManager.getApplication().runReadAction(Computable {
|
||||
FileDocumentManager.getInstance().getDocument(file)?.text
|
||||
})
|
||||
private fun onEditorThread(status: (String) -> Unit, action: () -> Unit) {
|
||||
// invokeLater supplies write intent on modern IDEs; avoid linking the changing
|
||||
// WriteIntentReadAction.run binary signature across Android Studio versions.
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
if (project.isDisposed) return@invokeLater
|
||||
try { action() } catch (e: Exception) { status("清单编辑失败:${e.message}") }
|
||||
}
|
||||
}
|
||||
fun edit(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean = false) =
|
||||
onEditorThread(status) { editOnEditorThread(cfg, status, reload) }
|
||||
private fun editOnEditorThread(cfg: Settings.Data, status: (String) -> Unit, reload: Boolean) {
|
||||
val key = key(cfg)
|
||||
val existing = sessions[key]
|
||||
if (existing != null && !reload) {
|
||||
FileEditorManager.getInstance(project).openFile(existing.file, true)
|
||||
status("已打开本地清单。修改后点击侧边栏“保存清单到服务端”;Ctrl+S只保存本地编辑副本。")
|
||||
return
|
||||
}
|
||||
if (existing != null && reload) {
|
||||
val current = documentText(existing.file)
|
||||
if (current != existing.content && JOptionPane.showConfirmDialog(null, "重新读取会替换本地清单修改,是否继续?", "重新读取私有文件清单", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return
|
||||
}
|
||||
execute(cfg, status, { call(cfg) }) { data ->
|
||||
val text = data.get("content").asString.replace("\r\n", "\n").replace('\r', '\n')
|
||||
val id = MessageDigest.getInstance("SHA-256").digest(key.toByteArray()).joinToString("") { "%02x".format(it) }
|
||||
val directory = Path.of(PathManager.getSystemPath(), "remotecompile-private-lists")
|
||||
Files.createDirectories(directory)
|
||||
val folder = directory.resolve(id)
|
||||
Files.createDirectories(folder)
|
||||
val path = folder.resolve("私有文件清单.txt")
|
||||
// Keep a recoverable local draft when reopening after IDE restart.
|
||||
if (existing == null && Files.exists(path) && Files.readString(path) != text) {
|
||||
Files.copy(path, folder.resolve("私有文件清单.draft-${System.currentTimeMillis()}.txt"))
|
||||
}
|
||||
val initial = text.ifBlank { "# 每行一个相对于服务端工程来源目录的文件路径,使用 /\n# config.gradle\n# app/keystore/example.jks\n" }
|
||||
ApplicationManager.getApplication().runWriteAction {
|
||||
if (existing == null) Files.writeString(path, initial)
|
||||
val file = existing?.file ?: LocalFileSystem.getInstance().refreshAndFindFileByIoFile(path.toFile()) ?: error("无法创建清单编辑副本")
|
||||
file.charset = Charsets.UTF_8
|
||||
val document = FileDocumentManager.getInstance().getDocument(file) ?: error("无法打开清单文档")
|
||||
document.setText(initial)
|
||||
FileDocumentManager.getInstance().saveDocument(document)
|
||||
sessions[key] = Session(file, data.get("hash").asString, initial)
|
||||
FileEditorManager.getInstance(project).openFile(file, true)
|
||||
}
|
||||
status(describe(data) + "\n已在IDE打开;编辑后请点击“保存清单到服务端”。本地副本只包含路径,不包含签名文件内容。")
|
||||
}
|
||||
}
|
||||
fun save(cfg: Settings.Data, status: (String) -> Unit) =
|
||||
onEditorThread(status) { saveOnEditorThread(cfg, status) }
|
||||
private fun saveOnEditorThread(cfg: Settings.Data, status: (String) -> Unit) {
|
||||
val session = sessions[key(cfg)] ?: run { status("请先点击编辑私有文件清单"); return }
|
||||
val document = ApplicationManager.getApplication().runReadAction(Computable {
|
||||
FileDocumentManager.getInstance().getDocument(session.file)
|
||||
}) ?: run { status("清单文档不可用,请重新编辑"); return }
|
||||
FileDocumentManager.getInstance().saveDocument(document)
|
||||
// IDE save actions may strip trailing spaces or add a final newline.
|
||||
// Publish the document after those changes, never a pre-save snapshot.
|
||||
val content = documentText(session.file) ?: run { status("清单文档不可用,请重新编辑"); return }
|
||||
execute(cfg, status, { call(cfg, content, session.hash) }) { data ->
|
||||
session.hash = data.get("hash").asString; session.content = data.get("content").asString
|
||||
status("已保存到服务端;构建前会按清单复制文件。\n" + describe(data))
|
||||
}
|
||||
}
|
||||
fun requirePublished(cfg: Settings.Data) {
|
||||
val key = key(cfg)
|
||||
check(key !in active) { "私有文件清单操作仍在进行,请完成后再构建" }
|
||||
sessions[key]?.let { session ->
|
||||
val text = documentText(session.file)
|
||||
check(text == null || PrivateListText.entries(text) == PrivateListText.entries(session.content)) { "私有文件清单已在IDE修改,请先点击侧边栏“保存清单到服务端”" }
|
||||
}
|
||||
}
|
||||
private fun execute(cfg: Settings.Data, status: (String) -> Unit, work: () -> JsonObject, done: (JsonObject) -> Unit) {
|
||||
val key = key(cfg)
|
||||
if (!active.add(key)) { status("清单操作正在进行,请稍后"); return }
|
||||
status("正在处理服务端私有文件清单…")
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
val result = runCatching(work)
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
active.remove(key)
|
||||
if (project.isDisposed) return@invokeLater
|
||||
try { result.fold(done) { status("私有文件清单操作失败:${it.message}") } }
|
||||
catch (e: Exception) { status("清单编辑失败:${e.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
/** Compare the same effective paths that the server consumes, ignoring editor formatting. */
|
||||
object PrivateListText {
|
||||
fun entries(text: String): List<String> = text.removePrefix("\uFEFF").lineSequence()
|
||||
.map(String::trim).filter { it.isNotEmpty() && !it.startsWith('#') }.toList()
|
||||
}
|
||||
@@ -70,6 +70,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
private var discoveredTasks = emptyList<String>()
|
||||
private val devices = JComboBox<AdbDevice>()
|
||||
private val refresh = JButton("刷新设备")
|
||||
private val remoteAdb = JCheckBox("使用服务端 ADB 安装", settings.snapshot().remoteAdb).apply { toolTipText = "读取服务器设备;构建成功后由服务端直接安装 APK,同时保留本机下载" }
|
||||
private val deviceStatus = JLabel("正在读取本机设备…")
|
||||
private val refreshing = AtomicBoolean(false)
|
||||
private var updatingDevices = false
|
||||
@@ -102,10 +103,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
init {
|
||||
val configure = JButton("连接设置")
|
||||
val refreshTasks = JButton("刷新变体")
|
||||
val variants = JPanel(BorderLayout(0, JBUI.scale(6))).apply {
|
||||
add(JLabel("构建变体 / Gradle 任务"), BorderLayout.NORTH)
|
||||
add(taskSelector, BorderLayout.CENTER)
|
||||
}
|
||||
taskSelector.toolTipText = "选择任务或直接输入;自动记住最近 20 个任务"
|
||||
updateTaskChoices(settings.snapshot().task)
|
||||
taskSelector.addActionListener {
|
||||
@@ -116,7 +113,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
refreshTasks.addActionListener { refreshTaskChoices(refreshTasks) }
|
||||
refreshTaskChoices(refreshTasks)
|
||||
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 {
|
||||
@@ -127,6 +123,13 @@ 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() }
|
||||
remoteAdb.addActionListener {
|
||||
if (busy) { remoteAdb.isSelected = settings.snapshot().remoteAdb; return@addActionListener }
|
||||
settings.selectRemoteAdb(remoteAdb.isSelected)
|
||||
updatingDevices = true; devices.removeAllItems(); updatingDevices = false
|
||||
deviceStatus.text = if (remoteAdb.isSelected) "正在读取服务端设备…" else "正在读取本机设备…"
|
||||
refreshDevices()
|
||||
}
|
||||
configure.addActionListener { ToolWindowManager.getInstance(project).getToolWindow("Remote Configuration")?.show() }
|
||||
val history = JButton("构建历史").apply { addActionListener { showHistory() } }
|
||||
val installLast = JButton("安装已下载 APK").apply { addActionListener { installDownloaded() } }
|
||||
@@ -143,7 +146,6 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
|
||||
}, BorderLayout.CENTER)
|
||||
}
|
||||
top.minimumSize = JBUI.size(0, 0)
|
||||
devices.minimumSize = JBUI.size(0, 24)
|
||||
taskSelector.minimumSize = JBUI.size(0, 24)
|
||||
fun column(vararg parts: JComponent) = JPanel().apply {
|
||||
@@ -156,14 +158,27 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
add(part)
|
||||
}
|
||||
}
|
||||
val buildIdentity = JPanel(BorderLayout(0, JBUI.scale(6))).apply {
|
||||
add(JLabel("构建 ID"), BorderLayout.NORTH)
|
||||
add(buildIdField, BorderLayout.CENTER)
|
||||
add(JLabel("留空找回上次构建"), BorderLayout.SOUTH)
|
||||
}
|
||||
val headings = JPanel(java.awt.GridLayout(1, 2, JBUI.scale(8), 0)).apply {
|
||||
add(JPanel(BorderLayout()).apply { add(column(top, variants), BorderLayout.NORTH) })
|
||||
add(JPanel(BorderLayout()).apply { add(buildIdentity, BorderLayout.NORTH) })
|
||||
// Both columns share the same rows, including the differently sized label/checkbox.
|
||||
val headings = JPanel(java.awt.GridBagLayout()).apply {
|
||||
fun cell(component: JComponent, x: Int, y: Int, gap: Int) {
|
||||
component.minimumSize = JBUI.size(0, component.minimumSize.height)
|
||||
component.preferredSize = java.awt.Dimension(0, component.preferredSize.height)
|
||||
add(component, java.awt.GridBagConstraints().apply {
|
||||
gridx = x; gridy = y; weightx = 1.0
|
||||
fill = java.awt.GridBagConstraints.BOTH
|
||||
insets = JBUI.insets(gap, if (x == 0) 0 else 4, 0, if (x == 0) 4 else 0)
|
||||
})
|
||||
}
|
||||
cell(JLabel("目标设备"), 0, 0, 0)
|
||||
cell(JLabel("构建 ID"), 1, 0, 0)
|
||||
cell(devices, 0, 1, 6)
|
||||
cell(buildIdField, 1, 1, 6)
|
||||
cell(deviceStatus, 0, 2, 6)
|
||||
cell(JLabel("留空找回上次构建"), 1, 2, 6)
|
||||
cell(JLabel("构建变体 / Gradle 任务"), 0, 3, 10)
|
||||
cell(remoteAdb, 1, 3, 10)
|
||||
cell(taskSelector, 0, 4, 6)
|
||||
cell(JButton("服务端安装 APK").apply { addActionListener { installServerBuild() } }, 1, 4, 6)
|
||||
}
|
||||
val actions = JPanel(java.awt.GridLayout(0, 2, JBUI.scale(8), JBUI.scale(6))).apply {
|
||||
add(refreshTasks); add(resume)
|
||||
@@ -227,12 +242,12 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
if (disposed || project.isDisposed || !refreshing.compareAndSet(false, true)) return
|
||||
ApplicationManager.getApplication().executeOnPooledThread {
|
||||
val cfg = settings.snapshot()
|
||||
val result = runCatching { AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
|
||||
val result = runCatching { if (cfg.remoteAdb) ServerAdb.devices(cfg) else AdbDevices.list(AdbDevices.resolve(Path.of(project.basePath ?: error("项目路径不存在")), cfg.adb)) }
|
||||
ApplicationManager.getApplication().invokeLater {
|
||||
try {
|
||||
if (!disposed && !project.isDisposed) {
|
||||
if (!disposed && !project.isDisposed && settings.snapshot().let { it.remoteAdb == cfg.remoteAdb && it.url == cfg.url }) {
|
||||
val found = result.getOrDefault(emptyList())
|
||||
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: settings.snapshot().device
|
||||
val previous = (devices.selectedItem as? AdbDevice)?.serial ?: (if (cfg.remoteAdb) cfg.remoteDevice else cfg.device)
|
||||
if ((0 until devices.itemCount).map { devices.getItemAt(it) } != found) {
|
||||
updatingDevices = true
|
||||
try {
|
||||
@@ -240,7 +255,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
devices.selectedItem = AdbDevices.choose(found, previous)
|
||||
} finally { updatingDevices = false }
|
||||
}
|
||||
deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${found.count { it.online }} 台可用设备;可自动识别插拔"
|
||||
deviceStatus.text = result.exceptionOrNull()?.message ?: if (found.isEmpty()) "没有检测到设备;请连接手机或启动模拟器" else "${if (cfg.remoteAdb) "服务端" else "本机"} ${found.count { it.online }} 台可用设备;可自动识别插拔"
|
||||
}
|
||||
} finally { refreshing.set(false) }
|
||||
}
|
||||
@@ -292,6 +307,7 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
settings.selectTask(selectedTask)
|
||||
updateTaskChoices(selectedTask)
|
||||
val cfg = settings.snapshot()
|
||||
project.getService(PrivateFilesEditor::class.java).requirePublished(cfg)
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
validateEndpoint(base)
|
||||
require(cfg.remoteFolder.isNotBlank()) { "请在 Remote Configuration 中填写服务端已有工程文件夹,并点击检查远程工程" }
|
||||
@@ -307,27 +323,36 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
secret = PasswordSafe.instance.getPassword(credentials(base)) ?: ""
|
||||
check(secret.length >= 24) { "请在右侧 Remote Configuration 中保存服务 Token" }
|
||||
append("构建任务:${cfg.task}")
|
||||
append("安装位置:${if (cfg.remoteAdb) "服务端 ADB" else "本机 ADB"}")
|
||||
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, "javaHome" to cfg.remoteJavaHome)
|
||||
val dedicated = localGit != null
|
||||
if (dedicated) check(health.get("dedicatedGit")?.asBoolean == true) { "服务端需升级至0.5.0以支持专用Git工作区" }
|
||||
val checkBody = mapOf("workspacePath" to cfg.remoteFolder, "projectId" to cfg.projectId, "git" to localGit, "javaHome" to cfg.remoteJavaHome, "dedicated" to dedicated)
|
||||
val inspection = json(base, secret, "POST", "/projects/check", checkBody)
|
||||
append("远程位置:${inspection.get("workspacePath").asString}")
|
||||
append("Git 检查:${inspection.get("message").asString};本机=$localGit;服务端=${inspection.get("git")}")
|
||||
append("Git 检查:${inspection.get("message").asString};本机=$localGit;编译工作区基线=${inspection.get("git")}")
|
||||
check(inspection.get("canSync").asBoolean) { inspection.get("message").asString }
|
||||
inspection.getAsJsonObject("preflight")?.let { report ->
|
||||
append(PreflightChecks.describe(report))
|
||||
check(report.get("ready").asBoolean) { "远程环境检查未通过,请处理上方错误后重试" }
|
||||
}
|
||||
val candidates = SourceFiles.collect(source, localGit)
|
||||
if (cfg.projectId.isBlank()) {
|
||||
if (cfg.projectId.isBlank() || dedicated) {
|
||||
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 remoteState = json(base, secret, "GET", "/projects/${cfg.projectId}/manifest")
|
||||
if (dedicated) {
|
||||
val previousHead = remoteState.getAsJsonObject("git")?.get("head")?.asString
|
||||
if (previousHead != localGit!!.head) uploadGitBundle(base, secret, cfg.projectId, source, localGit.head, previousHead)
|
||||
append("专用编译工作区:${remoteState.get("workspacePath").asString}")
|
||||
}
|
||||
val manifest = remoteState.getAsJsonObject("files")
|
||||
val files = linkedMapOf<String, Map<String, String>>()
|
||||
var changed = 0; var lineEndingsOnly = 0
|
||||
for (path in candidates) {
|
||||
@@ -361,9 +386,14 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
val result = watchBuild(base, secret, activeBuild)
|
||||
buildSucceeded = true
|
||||
append("构建已成功,正在选择和下载 APK")
|
||||
val output = downloadApk(base, secret, activeBuild, source, result)
|
||||
val chosen = selectArtifact(source, activeBuild, result)
|
||||
if (cfg.remoteAdb) {
|
||||
try { installServer(cfg, activeBuild, chosen, selected) }
|
||||
catch (e: Exception) { append("构建成功,服务端安装未完成:${e.message};产物保留,可稍后点击服务端安装 APK") }
|
||||
}
|
||||
val output = downloadApk(base, secret, activeBuild, source, result, chosen)
|
||||
check(!cancelRequested) { "已取消安装" }
|
||||
if (cfg.install) {
|
||||
if (cfg.install && !cfg.remoteAdb) {
|
||||
try { installApkWhenAvailable(source, cfg, selected, output) }
|
||||
catch (e: Exception) {
|
||||
append("编译和下载已成功,安装未完成:${e.message ?: e.javaClass.simpleName};APK 已保留,可稍后点击安装已下载 APK")
|
||||
@@ -380,6 +410,23 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
private fun uploadGitBundle(base: String, secret: String, projectId: String, source: Path, head: String, previous: String?) {
|
||||
fun send(baseHead: String?) {
|
||||
append("正在生成提交元数据 bundle(不包含文件内容)…")
|
||||
val bundle = GitBundles.create(source, head, baseHead)
|
||||
try {
|
||||
append("上传 Git 提交 $head,bundle ${Files.size(bundle)} 字节")
|
||||
val req = HttpRequest.newBuilder(URI.create("$base/api/v1/projects/$projectId/git?head=$head"))
|
||||
.header("Authorization", "Bearer $secret").header("Content-Type", "application/octet-stream")
|
||||
.timeout(Duration.ofMinutes(10)).POST(HttpRequest.BodyPublishers.ofFile(bundle)).build()
|
||||
val response = http.send(req, HttpResponse.BodyHandlers.ofString())
|
||||
check(response.statusCode() == 200) { ServerErrors.describe(response.statusCode(), "/projects/$projectId/git", response.body()) }
|
||||
} finally { GitBundles.delete(bundle) }
|
||||
}
|
||||
try { send(previous) } catch (e: Exception) {
|
||||
if (!previous.isNullOrBlank() && e.message.orEmpty().startsWith("HTTP 400:")) { append("增量bundle不可用,重试完整提交历史"); send(null) } else throw e
|
||||
}
|
||||
}
|
||||
private fun installApkWhenAvailable(source: Path, cfg: Settings.Data, selected: AdbDevice?, output: Path) {
|
||||
val adb = AdbDevices.resolve(source, cfg.adb)
|
||||
val connected = AdbDevices.list(adb)
|
||||
@@ -437,18 +484,18 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
Thread.sleep(1000)
|
||||
}
|
||||
}
|
||||
private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject): Path {
|
||||
private fun selectArtifact(source: Path, id: String, result: JsonObject): ApkArtifact {
|
||||
require(id.matches(Regex("[a-f0-9]{32}"))) { "无效构建 ID" }
|
||||
val artifacts = ApkArtifacts.read(result)
|
||||
check(artifacts.isNotEmpty()) { "成功构建没有可下载的 APK" }
|
||||
val previous = LastBuildStore.load(source)?.takeIf { it.buildId == id }?.artifactName
|
||||
val artifact = if (artifacts.size == 1) artifacts.single() else {
|
||||
append("构建生成 ${artifacts.size} 个 APK,请选择要下载的完整安装包;其他产物保留在服务端")
|
||||
append("构建生成 ${artifacts.size} 个 APK,请选择要使用的完整安装包;其他产物保留在服务端")
|
||||
var chosen: ApkArtifact? = null
|
||||
ApplicationManager.getApplication().invokeAndWait {
|
||||
if (!disposed && !project.isDisposed) {
|
||||
chosen = JOptionPane.showInputDialog(this,
|
||||
"选择要下载的 APK;不同渠道或签名包请按实际用途选择。\n拆分 APK 需成套安装,当前不支持自动安装拆分包。",
|
||||
"选择要使用的 APK;不同渠道或签名包请按实际用途选择。\n拆分 APK 需成套安装,当前不支持自动安装拆分包。",
|
||||
"选择构建产物", JOptionPane.QUESTION_MESSAGE, null,
|
||||
artifacts.toTypedArray(), artifacts.firstOrNull { it.name == previous } ?: artifacts.first()) as? ApkArtifact
|
||||
}
|
||||
@@ -456,11 +503,14 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
chosen ?: error("已取消选择 APK;构建已成功,产物仍保留,可点击下载 APK 重新选择")
|
||||
}
|
||||
append("选择 APK:$artifact")
|
||||
return artifact
|
||||
}
|
||||
private fun downloadApk(base: String, secret: String, id: String, source: Path, result: JsonObject, selectedArtifact: ApkArtifact? = null): Path {
|
||||
val artifact = selectedArtifact ?: selectArtifact(source, id, result)
|
||||
val expected = artifact.hash
|
||||
val size = artifact.size
|
||||
val output = source.resolve(".remotecompile/$id-$expected.apk"); Files.createDirectories(output.parent)
|
||||
if (Files.exists(output) && fileHash(output) == expected) { rememberArtifact(source, id, expected, artifact.name); append("复用已下载 APK:$output"); return output }
|
||||
val part = output.resolveSibling("$id-$expected.apk.part")
|
||||
val directory = source.resolve(".remotecompile"); Files.createDirectories(directory)
|
||||
val part = directory.resolve("$id-$expected.apk.part")
|
||||
var received = if (Files.exists(part)) Files.size(part) else 0L
|
||||
if (received > size) { Files.delete(part); received = 0 }
|
||||
if (received < size) {
|
||||
@@ -487,15 +537,49 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
}
|
||||
}
|
||||
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, artifact.name)
|
||||
showProgress("APK 下载完成", 100); append("APK 已保存:$output"); return output
|
||||
val output = ApkFiles.publish(part, directory, artifact.fileName)
|
||||
rememberArtifact(source, id, expected, artifact.name, output.fileName.toString())
|
||||
showProgress("APK 下载完成", 100); append("APK 已保存:$output")
|
||||
ApkNotifications.show(project, output, result.get("task")?.asString.orEmpty())
|
||||
return output
|
||||
}
|
||||
private fun rememberArtifact(source: Path, id: String, expected: String, name: String) {
|
||||
LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; it.artifactName = name; LastBuildStore.save(source, it) }
|
||||
private fun rememberArtifact(source: Path, id: String, expected: String, name: String, file: String) {
|
||||
LastBuildStore.load(source)?.takeIf { it.buildId == id }?.let { it.artifactHash = expected; it.artifactName = name; it.artifactFile = file; LastBuildStore.save(source, it) }
|
||||
}
|
||||
private fun installServer(cfg: Settings.Data, id: String, artifact: ApkArtifact, device: AdbDevice?) {
|
||||
if (device?.online != true) { append("未选择在线服务端设备;跳过安装,继续下载 APK"); return }
|
||||
append("正在使用服务端 ADB 安装到:$device")
|
||||
append(ServerAdb.install(cfg, id, artifact.name, device.serial))
|
||||
append("服务端安装成功:${artifact.fileName}")
|
||||
}
|
||||
private fun installServerBuild() {
|
||||
if (busy) return
|
||||
val cfg = settings.snapshot()
|
||||
if (!cfg.remoteAdb) { append("请先勾选使用服务端 ADB 安装,并选择服务端设备"); return }
|
||||
val selected = devices.selectedItem as? AdbDevice
|
||||
if (selected?.online != true) { append("请选择在线且已授权的服务端设备"); return }
|
||||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||||
val id = buildIdField.text.trim().ifBlank { LastBuildStore.load(source)?.buildId.orEmpty() }
|
||||
if (!id.matches(Regex("[a-f0-9]{32}"))) { append("请填写成功构建 ID 或先运行构建"); return }
|
||||
busy = true; run.isEnabled = false
|
||||
object : Task.Backgroundable(project, "服务端安装 APK", false) {
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
var secret = ""
|
||||
try {
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
http = ServerTls.client(cfg.serverCertificate)
|
||||
secret = PasswordSafe.instance.getPassword(credentials(base)).orEmpty()
|
||||
val result = json(base, secret, "GET", "/builds/$id")
|
||||
check(result.get("status").asString == "success") { "该构建尚未成功" }
|
||||
installServer(cfg, id, selectArtifact(source, id, result), selected)
|
||||
} catch (e: Exception) { append("服务端安装失败:${e.message}".let { if (secret.isNotEmpty()) it.replace(secret, "***") else it }) }
|
||||
finally { busy = false; ApplicationManager.getApplication().invokeLater { if (!disposed && !project.isDisposed) run.isEnabled = true } }
|
||||
}
|
||||
}.queue()
|
||||
}
|
||||
private fun installDownloaded() {
|
||||
if (busy) return
|
||||
if (settings.snapshot().remoteAdb) { installServerBuild(); return }
|
||||
val source = project.basePath?.let { Path.of(it) } ?: return
|
||||
val record = try { LastBuildStore.load(source) ?: error("没有已下载构建记录") }
|
||||
catch (e: Exception) { append(e.message ?: "读取记录失败"); return }
|
||||
@@ -506,7 +590,8 @@ class RemotePanel(private val project: Project) : JPanel(BorderLayout()), Dispos
|
||||
override fun run(indicator: ProgressIndicator) {
|
||||
try {
|
||||
val selectedOutput = source.resolve(".remotecompile/${record.buildId}-${record.artifactHash}.apk")
|
||||
val output = if (Files.isRegularFile(selectedOutput)) selectedOutput else source.resolve(".remotecompile/${record.buildId}.apk")
|
||||
val recorded = record.artifactFile?.let { require(ApkFiles.validName(it)) { "保存的 APK 文件名无效" }; source.resolve(".remotecompile").resolve(it) }
|
||||
val output = recorded ?: if (Files.isRegularFile(selectedOutput)) selectedOutput else 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)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package studio.tongtong.remotecompile
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import com.intellij.ide.passwordSafe.PasswordSafe
|
||||
import java.net.URI
|
||||
import java.net.http.HttpRequest
|
||||
import java.net.http.HttpResponse
|
||||
import java.time.Duration
|
||||
|
||||
object ServerAdb {
|
||||
private fun call(cfg: Settings.Data, route: String, body: Any? = null): JsonObject {
|
||||
val base = cfg.url.trim().trimEnd('/')
|
||||
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"))
|
||||
.header("Authorization", "Bearer $token").header("Content-Type", "application/json")
|
||||
.timeout(if (body == null) Duration.ofSeconds(25) else Duration.ofMinutes(4))
|
||||
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, "***")
|
||||
}
|
||||
return Gson().fromJson(response.body(), JsonObject::class.java)
|
||||
}
|
||||
fun devices(cfg: Settings.Data): List<AdbDevice> = call(cfg, "devices").getAsJsonArray("devices").map {
|
||||
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
|
||||
}
|
||||
@@ -4,6 +4,7 @@ object ServerErrors {
|
||||
fun describe(status: Int, route: String, body: String): String {
|
||||
val detail = body.trim().take(4000)
|
||||
val help = when {
|
||||
detail.contains("unknown field \"dedicated\"") -> "请将服务端升级至0.5.0,新插件需要专用Git工作区接口。"
|
||||
status == 401 -> "请重新保存该服务器的 Token,再重试。"
|
||||
status == 404 && route == "/health" ->
|
||||
"未找到编译服务的健康接口。请核对服务器地址和端口,连接地址不要重复填写 /api/v1;在远程 Windows 管理员 PowerShell 执行 Get-Service RemoteCompile,Linux 执行 sudo systemctl status remotecompile。"
|
||||
|
||||
@@ -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 = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
|
||||
@Synchronized override fun loadState(state: Settings.Data) { data = state.copy(projectId = "", device = "", remoteAdb = false, remoteDevice = "", remoteFolder = "", remoteJavaHome = "", taskHistory = mutableListOf()) }
|
||||
}
|
||||
|
||||
@State(name = "RemoteCompilation", storages = [Storage("remote-compilation.xml")])
|
||||
@@ -36,6 +36,8 @@ class Settings : PersistentStateComponent<Settings.Data> {
|
||||
var taskHistory: MutableList<String> = mutableListOf(),
|
||||
var adb: String = "",
|
||||
var device: String = "",
|
||||
var remoteAdb: Boolean = false,
|
||||
var remoteDevice: String = "",
|
||||
var install: Boolean = false,
|
||||
var serverCertificate: String = "",
|
||||
var configured: Boolean = false
|
||||
@@ -44,7 +46,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(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(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) {
|
||||
@@ -54,7 +56,7 @@ class Settings : PersistentStateComponent<Settings.Data> {
|
||||
}
|
||||
@Synchronized fun saveConfiguration(next: Data, preserveTask: Boolean = false) {
|
||||
val current = snapshot()
|
||||
data = next.copy(task = if (preserveTask) current.task else next.task, projectId = if (current.url == next.url && current.remoteFolder == next.remoteFolder) current.projectId else "", device = current.device, taskHistory = current.taskHistory.toMutableList(), configured = true)
|
||||
data = next.copy(task = if (preserveTask) current.task else next.task, projectId = if (current.url == next.url && current.remoteFolder == next.remoteFolder) current.projectId else "", remoteAdb = current.remoteAdb, remoteDevice = if (current.url == next.url) current.remoteDevice else "", device = current.device, taskHistory = current.taskHistory.toMutableList(), configured = true)
|
||||
defaults()?.loadState(data)
|
||||
}
|
||||
@Synchronized fun selectTask(task: String) {
|
||||
@@ -62,7 +64,8 @@ class Settings : PersistentStateComponent<Settings.Data> {
|
||||
val current = snapshot()
|
||||
data = current.copy(task = task, taskHistory = (listOf(task) + current.taskHistory).distinct().take(20).toMutableList(), configured = true)
|
||||
}
|
||||
@Synchronized fun selectDevice(serial: String) { data = data.copy(device = serial) }
|
||||
@Synchronized fun selectDevice(serial: String) { data = if (snapshot().remoteAdb) data.copy(remoteDevice = serial) else data.copy(device = serial) }
|
||||
@Synchronized fun selectRemoteAdb(enabled: Boolean) { data = snapshot().copy(remoteAdb = enabled, configured = true) }
|
||||
@Synchronized fun projectAllocated(url: String, id: String, remoteFolder: String = snapshot().remoteFolder) {
|
||||
val current = snapshot()
|
||||
if (current.url == url && current.remoteFolder == remoteFolder) data = current.copy(projectId = id, configured = true)
|
||||
@@ -105,11 +108,30 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
|
||||
private var tokenRequest = 0
|
||||
init {
|
||||
val fields = JPanel(GridLayout(0, 1, 0, 5))
|
||||
listOf("服务地址" to url, "Token(留空保留)" to token, "服务端已有工程文件夹(必填绝对路径)" to remoteFolder,
|
||||
listOf("服务地址" to url, "Token(留空保留)" to token, "服务端工程来源目录(必填;Git工程只读初始化)" to remoteFolder,
|
||||
"adb 路径(留空自动使用项目 SDK)" to adb).forEach { (label, field) -> fields.add(JLabel(label)); fields.add(field) }
|
||||
val browse = JButton("选择服务端文件夹…")
|
||||
browse.addActionListener { browseRemoteFolder("") }
|
||||
fields.add(browse)
|
||||
fields.add(JLabel("私有文件清单(按服务端工程来源目录绑定)"))
|
||||
fun privateAction(action: String) {
|
||||
val cfg = settings.snapshot()
|
||||
if (cfg.url.trim().trimEnd('/') != url.text.trim().trimEnd('/') || cfg.remoteFolder != remoteFolder.text.trim() || cfg.serverCertificate != certificate.text.trim()) {
|
||||
checkResult.text = "请先保存连接设置,再操作该工程的私有文件清单"; return
|
||||
}
|
||||
val editor = project.getService(PrivateFilesEditor::class.java)
|
||||
val report: (String) -> Unit = { if (!project.isDisposed) checkResult.text = it }
|
||||
when (action) {
|
||||
"check" -> editor.check(cfg, report)
|
||||
"edit" -> editor.edit(cfg, report)
|
||||
"save" -> editor.save(cfg, report)
|
||||
"reload" -> editor.edit(cfg, report, reload = true)
|
||||
}
|
||||
}
|
||||
listOf("检查私有文件清单" to "check", "编辑私有文件清单(IDE)" to "edit", "保存清单到服务端" to "save", "重新读取服务端清单" to "reload").forEach { (label, action) ->
|
||||
fields.add(JButton(label).apply { addActionListener { privateAction(action) } })
|
||||
}
|
||||
|
||||
fields.add(JLabel("构建变体请在构建日志面板左侧选择"))
|
||||
fields.add(JLabel("服务端 JDK(按工程保存)")); fields.add(jdks)
|
||||
val refreshJdks = JButton("检测服务端 JDK(where / 安装目录)")
|
||||
@@ -279,14 +301,14 @@ private class RemoteSettingsPanel(private val project: Project) : JPanel(BorderL
|
||||
val local = SourceFiles.snapshot(source)
|
||||
val body = mapOf("workspacePath" to folder, "git" to local,
|
||||
"projectId" to (if (saved.url == base && saved.remoteFolder == folder) saved.projectId else ""),
|
||||
"javaHome" to selectedJavaHome)
|
||||
"javaHome" to selectedJavaHome, "dedicated" to (local != null))
|
||||
val req = java.net.http.HttpRequest.newBuilder(java.net.URI.create(base + "/api/v1/projects/check"))
|
||||
.timeout(java.time.Duration.ofSeconds(90)).header("Authorization", "Bearer $secret")
|
||||
.header("Content-Type", "application/json").POST(java.net.http.HttpRequest.BodyPublishers.ofString(com.google.gson.Gson().toJson(body))).build()
|
||||
val response = ServerTls.client(cert).send(req, java.net.http.HttpResponse.BodyHandlers.ofString())
|
||||
check(response.statusCode() == 200) { ServerErrors.describe(response.statusCode(), "/projects/check", response.body()) }
|
||||
val remote = com.google.gson.Gson().fromJson(response.body(), com.google.gson.JsonObject::class.java)
|
||||
"${remote.get("message").asString}\n服务端位置:${remote.get("workspacePath").asString}\n本机 Git:$local\n服务端 Git:${remote.get("git")}\n${PreflightChecks.describe(remote.getAsJsonObject("preflight"))}\n(上游差异使用已有本地引用,检查不会 fetch/pull,也不会修改文件)"
|
||||
"${remote.get("message").asString}\n服务端位置:${remote.get("workspacePath").asString}\n本机 Git:$local\n编译工作区基线:${remote.get("git")}\n${PreflightChecks.describe(remote.getAsJsonObject("preflight"))}\n(上游差异使用已有本地引用,检查不会 fetch/pull,也不会修改文件)"
|
||||
}.getOrElse { (it.message ?: it.javaClass.simpleName).let { message -> if (secret.isEmpty()) message else message.replace(secret, "***") } }
|
||||
ApplicationManager.getApplication().invokeLater { if (!project.isDisposed) { checkRemote.isEnabled = true; checkResult.text = result } }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user