Commit 94e79115 authored by zpc's avatar zpc

Add multi-project split release and Maven choice

parent 530bc587
......@@ -19,9 +19,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.2.0</string>
<string>1.3.0</string>
<key>CFBundleVersion</key>
<string>6</string>
<string>7</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
......
......@@ -8,7 +8,7 @@ let package = Package(
targets: [
.target(name: "ReleaseCore"),
.executableTarget(name: "JavaReleaseMenu", dependencies: ["ReleaseCore"]),
.testTarget(name: "ReleaseCoreTests", dependencies: ["ReleaseCore"])
.testTarget(name: "ReleaseCoreTests", dependencies: ["ReleaseCore", "JavaReleaseMenu"])
],
swiftLanguageModes: [.v6]
)
# Java 发布
macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布时,圆环内显示按阶段估算的百分比,暂停时保留当前百分比。发布成功后显示 100%,2 秒后显示总耗时,完成满 10 秒恢复空心圆环。再点圆环会打开发布页,上次结果可从「上次发布详情」查看。右键圆环可退出。
macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布时,圆环内显示当前批次的估算进度。全部成功后显示 100%,2 秒后显示总耗时,完成满 10 秒恢复空心圆环。各项目最近一次发布结果保留在各自窗口内。右键圆环可退出。
## 安装与配置
1. 解压后将整个 `JavaReleaseMenu` 目录放进 `~/SoftSpace`,双击 `dist/JavaReleaseMenu.app`。随附的 App 适用于 Apple 芯片和 macOS 14 或更新版本。
1. 从源码克隆后运行 `./build-app.sh`,再双击 `dist/JavaReleaseMenu.app`。如果拿到的是单独的 App 压缩包,解压后直接打开 App。当前构建适用于 Apple 芯片和 macOS 14 或更新版本。
2. 点击菜单栏圆形图标,在「项目设置」添加本地 Git 仓库。仓库当前分支需要关联远端分支,并已配置本机 Git 认证。
3. CityKeeper Cloud 项目从所选仓库的根 POM 和 `docker/` 识别模块,发布时使用该仓库的 `build-and-deploy`。在发布页展开「发布配置」,单选本次使用的 YAML。点文件旁的铅笔可设置别名和 SSH 目标,点「浏览其他 YAML…」可选择其他位置的文件。
3. CityKeeper Cloud 项目从所选仓库的根 POM 和 `docker/` 识别模块,发布时使用该仓库的 `build-and-deploy`。在项目窗口里选择本次使用的 YAML,点「编辑别名与 SSH 目标」可调整配置,点「浏览其他 YAML…」可选择其他位置的文件。
4. 发布面板的「服务器」从项目设置中的 Ansible hosts 文件读取。选择项目目录时优先填写其中的 `ansible.hosts.yaml`,否则默认使用 `/etc/ansible/hosts`。支持静态 YAML 和 INI 清单。选中组时,组名传给脚本的 `--ds`。脚本默认也用该值连接 SSH,可在发布配置里单独填写 `--ss`。同一份 hosts 会传给 Ansible。发布页的 VPC 默认不勾选,勾选后仅本次命令添加 `--vpc`。
5. 其他 Java 项目可选「自定义 Bash 脚本」,指定脚本和模块列表。App 在项目根目录调用脚本,模块名作为第一个参数,退出码 0 代表成功。
在「模块」可勾选多个模块。App 会记住最后选中的项目、模块、配置和服务器。点击「发布」后先在当前分支执行一次 `git pull --ff-only`。CityKeeper 项目随后核对服务器,把所选模块一起交给 `build-and-deploy`。自定义脚本按模块依次执行,某个模块失败时停止执行后续模块。发布默认传 `-f`,可在项目设置关闭。
发布页最多添加四个项目窗口。每个窗口分别选择项目、发布配置、服务器、Maven 方式和模块。输入模块名可以筛选列表,已勾选的模块会保留。点击「发布此项目」仅运行当前窗口,点击「一起发布」运行所有窗口,各窗口分别显示实时输出、结果和完整日志入口。最多同时执行两个互不冲突的项目,共用项目目录、部署目标或目标不明的自定义脚本会排队;批量发布遇到失败后,已开始的任务会完成,尚未开始的任务不再执行。同名镜像模块的常规批量发布会被拦截。
Maven 默认自动选择 `mvnd`,检测不到时改用 `mvn`。也可在每个窗口或项目设置中指定 `mvnd` 或 `mvn`。项目设置支持分别指定可执行文件路径和补充工具 PATH。点击发布后,所选项目先在当前分支执行 `git pull --ff-only`。CityKeeper 项目核对服务器,把该项目所选模块一起交给 `build-and-deploy`。自定义脚本按模块依次执行,某个模块失败时停止执行后续模块。发布默认传 `-f`,可在项目设置关闭。
## 发布日志
发布过程中,点击菜单栏图标可看正在执行的命令和实时输出。暂停后可继续,也可点「结束发布并返回」停止本机发布进程组,再发起新发布。独立的 Maven 守护进程和已启动的远端任务可能继续运行。
发布过程中,点击菜单栏图标可在各项目窗口看正在执行的命令和实时输出。每个运行中的窗口均可暂停、继续或停止本机发布进程组。独立的 Maven 守护进程和已启动的远端任务可能继续运行。
上次发布详情显示项目、模块、配置、服务器、完成时间(北京时间)和总耗时秒数,耗时从拉取代码前开始计算。展开「详细日志」可以查看、复制或打开完整日志文件。发布失败时会显示识别到的第一条错误,点「跳到错误」定位。若无可识别的错误行,会显示脚本退出原因。CityKeeper 脚本报告部署完成但清理返回非零时,详情标为「部署完成,收尾失败」。
各窗口保存最近一次结果与日志,点击「打开完整日志」可以查看全部输出。错误会显示在对应项目窗口里。CityKeeper 脚本报告部署完成但收尾返回非零时,结果标为「部署完成,收尾失败」。
项目配置、最近发布详情和日志保存在 `~/Library/Application Support/JavaReleaseMenu`。新建或编辑项目时,「运行环境」会从 PATH、Maven 环境变量和常见安装目录查找 `mvn` 与 `mvnd`。留空使用自动探测路径,也可以为项目分别指定可执行文件。发布脚本里的同名命令会使用指定路径。「工具 PATH」可补充其他工具目录,例如 `ansible-inventory` 的安装目录。
项目配置、每个窗口的最近结果和日志保存在 `~/Library/Application Support/JavaReleaseMenu`。新建或编辑项目时,「运行环境」会从 PATH、Maven 环境变量和常见安装目录查找 `mvn` 与 `mvnd`。「工具 PATH」可补充其他工具目录,例如 `ansible-inventory` 的安装目录。
## HQ 验证发布
......
......@@ -18,6 +18,10 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
private let model = AppModel(
storage: URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
)
private lazy var split = SplitReleaseModel(
settings: model,
storage: URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
)
private var item: NSStatusItem?
private let popover = NSPopover()
private var settings: NSWindow?
......@@ -40,13 +44,12 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
popover.behavior = .transient
popover.appearance = NSAppearance(named: .darkAqua)
popover.contentViewController = NSHostingController(rootView: ReleasePanel(
model: model,
popover.contentViewController = NSHostingController(rootView: SplitReleasePanel(
model: split,
settings: { [weak self] in self?.openSettings() },
quit: { NSApplication.shared.terminate(nil) }
))
model.closePopover = { [weak self] in self?.popover.performClose(nil) }
model.statusChanged = { [weak self] in self?.updateIndicator() }
split.statusChanged = { [weak self] in self?.updateIndicator() }
updateIndicator()
}
......@@ -65,7 +68,7 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
popover.performClose(nil)
} else {
settings?.orderOut(nil)
model.preparePopover()
split.preparePopover()
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
popover.contentViewController?.view.window?.makeKey()
}
......@@ -93,11 +96,14 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
}
func windowWillClose(_ notification: Notification) {
if notification.object as? NSWindow === settings { settings = nil }
if notification.object as? NSWindow === settings {
settings = nil
split.preparePopover()
}
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
if model.isRunning {
if split.isRunning {
let alert = NSAlert()
alert.messageText = "发布正在运行"
alert.informativeText = "发布结束后可以退出 Java 发布。"
......@@ -108,15 +114,15 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
}
private func updateIndicator() {
let result = model.indicator
let duration = model.completionDuration
let percentage = result == .succeeded ? 100 : model.progressPercentage
let label = model.stopping ? "正在停止发布" : model.paused ? "发布已暂停" : model.phase?.title ?? result?.title ?? "Java 发布"
let result = split.indicator
let duration = split.completionDuration
let percentage = result == .succeeded ? 100 : split.progressPercentage
let label = split.current?.phase?.title ?? result?.title ?? "Java 发布"
let value = duration.map { "耗时 \($0) 秒" } ?? percentage.map { $0 == 100 ? "100%" : "预计进度 \($0)%" }
item?.button?.toolTip = [label, value].compactMap { $0 }.joined(separator: " · ")
item?.button?.setAccessibilityLabel(label)
item?.button?.setAccessibilityValue(value)
item?.button?.image = Self.indicatorImage(percentage: percentage, duration: duration, paused: model.paused, result: result)
item?.button?.image = Self.indicatorImage(percentage: percentage, duration: duration, paused: split.current?.paused == true, result: result)
}
private static func indicatorImage(percentage: Int?, duration: Int?, paused: Bool, result: ReleaseStatus?) -> NSImage {
......
......@@ -86,6 +86,17 @@ struct ProjectSettings: View {
}
section("运行环境", icon: "terminal") {
row("Maven 方式") {
Picker("Maven 方式", selection: Binding(
get: { draft.mavenCommand ?? .automatic },
set: { draft.mavenCommand = $0 }
)) {
ForEach(MavenCommand.allCases) { command in
Text(command.title).tag(command)
}
}
.labelsHidden()
}
mavenField("mvn", path: $draft.mavenPath)
mavenField("mvnd", path: $draft.mvndPath)
Button("重新扫描 Maven", action: scanMaven)
......
import AppKit
import ReleaseCore
import SwiftUI
import UniformTypeIdentifiers
enum ReleaseColors {
static let panel = Color(red: 0.075, green: 0.088, blue: 0.112)
static let surface = Color(red: 0.115, green: 0.133, blue: 0.165)
static let terminal = Color(red: 0.045, green: 0.054, blue: 0.075)
static let border = Color.white.opacity(0.105)
static let muted = Color(red: 0.62, green: 0.66, blue: 0.73)
static let blue = Color(red: 0.31, green: 0.62, blue: 1)
static let action = Color(red: 0.13, green: 0.35, blue: 0.86)
static let hover = Color(red: 0.17, green: 0.22, blue: 0.29)
static let actionHover = Color(red: 0.20, green: 0.46, blue: 0.98)
}
enum ReleaseTypography {
static let heading = Font.system(size: 17, weight: .semibold)
static let body = Font.system(size: 13)
static let action = Font.system(size: 13, weight: .medium)
static let detail = Font.system(size: 12)
}
struct ReleaseHover: ViewModifier {
var base: Color = .clear
var highlight = ReleaseColors.hover
var radius: CGFloat = 7
@Environment(\.isEnabled) private var enabled
@State private var hovering = false
func body(content: Content) -> some View {
content
.background(enabled && hovering ? highlight : base, in: RoundedRectangle(cornerRadius: radius))
.contentShape(Rectangle())
.onHover { hovering = $0 }
}
}
struct ReleaseButtonStyle: ButtonStyle {
var base: Color = .clear
var prominent = false
var radius: CGFloat = 7
func makeBody(configuration: Configuration) -> some View {
configuration.label
.modifier(ReleaseHover(base: base, highlight: prominent ? ReleaseColors.actionHover : ReleaseColors.hover,
radius: radius))
.opacity(configuration.isPressed ? 0.82 : 1)
}
}
struct ReleasePanel: View {
@Bindable var model: AppModel
let settings: () -> Void
let quit: () -> Void
@State private var openField: Field?
@State private var copied = false
@State private var expanded = false
@State private var jumpRequest = 0
@State private var configurationDraft: DeployProfile?
@State private var useVPC = false
@State private var verifiedRelease = false
private enum Field: String {
case project = "项目"
case module = "模块"
case profile = "发布配置"
case server = "服务器"
}
private let surface = ReleaseColors.surface
private let terminal = ReleaseColors.terminal
private let border = ReleaseColors.border
private let muted = ReleaseColors.muted
private let blue = ReleaseColors.blue
private var requiresDeploymentOptions: Bool { model.project?.type == .cityKeeper }
private var supportsVerifiedRelease: Bool { model.project?.supportsVerifiedRelease(model.profile) == true }
private var ready: Bool {
!model.selection.isEmpty && !model.isRunning
&& (!requiresDeploymentOptions || (model.profile != nil && model.hasSelectedServer))
}
var body: some View {
VStack(alignment: .leading, spacing: 14) {
if model.isRunning && model.page == .details {
running
} else if model.page == .details, let result = model.detailResult {
details(result)
} else {
release
}
if let error = model.error {
Text(error)
.font(.caption)
.foregroundStyle(.red)
.textSelection(.enabled)
}
}
.padding(15)
.frame(width: model.page == .release ? 364 : 440)
.fixedSize(horizontal: false, vertical: true)
.background(ReleaseColors.panel)
.environment(\.colorScheme, .dark)
.onChange(of: model.profileID) { verifiedRelease = false }
}
private var release: some View {
VStack(alignment: .leading, spacing: 14) {
HStack {
Label("Java 发布", systemImage: "shippingbox")
.font(ReleaseTypography.heading)
.labelStyle(.titleAndIcon)
Spacer()
Menu {
Button("项目设置…", action: settings)
Divider()
Button("退出 Java 发布", action: quit)
} label: {
Label("项目设置", systemImage: "gearshape")
.font(ReleaseTypography.detail)
.padding(.horizontal, 8)
.frame(height: 29)
.modifier(ReleaseHover())
}
.menuIndicator(.hidden)
.menuStyle(.borderlessButton)
.fixedSize()
.help("设置")
}
if model.projects.isEmpty {
Text("添加本地项目后即可选择模块发布。").foregroundStyle(muted)
Button(action: settings) {
Text("添加项目…").font(ReleaseTypography.action).padding(.horizontal, 12).frame(height: 34)
}
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.action, prominent: true))
} else {
VStack(spacing: 0) {
choice(.project, value: model.project?.name ?? "选择项目", icon: "folder",
options: model.projects.map(\.name),
selectedIndex: model.projects.firstIndex { $0.id == model.projectID }) {
model.projectID = model.projects[$0].id
useVPC = false
verifiedRelease = false
}
if requiresDeploymentOptions {
separator
configurationPicker
separator
let server = model.servers.firstIndex { $0.name == model.server }
let label = server.map { model.servers[$0].displayName } ?? model.server ?? "选择服务器"
choice(.server, value: model.loadingServers ? "正在读取 hosts…" : label,
icon: "server.rack", options: model.servers.map(\.displayName),
selectedIndex: server) { model.server = model.servers[$0].name }
}
separator
choice(.module, value: moduleSummary, icon: "square.stack", options: model.modules,
checked: Set(model.selection), multiple: true) { model.toggleModule(model.modules[$0]) }
}
.background(surface, in: RoundedRectangle(cornerRadius: 11))
.clipShape(RoundedRectangle(cornerRadius: 11))
.overlay { RoundedRectangle(cornerRadius: 11).strokeBorder(border).allowsHitTesting(false) }
if requiresDeploymentOptions {
Toggle("使用 VPC 镜像地址", isOn: $useVPC)
.toggleStyle(.checkbox)
.font(ReleaseTypography.body)
.tint(blue)
if let inventoryError = model.inventoryError {
Text(inventoryError).font(.caption).foregroundStyle(.red)
}
}
if supportsVerifiedRelease {
HStack {
Toggle("验证发布", isOn: $verifiedRelease)
.toggleStyle(.checkbox)
.tint(blue)
.help("按镜像 digest 部署并逐台验证")
Spacer()
Button("预检") {
openField = nil
resetLogControls()
model.publish(useVPC: useVPC, action: .preflight)
if model.isRunning { expanded = true }
}
.buttonStyle(ReleaseButtonStyle())
.disabled(!ready)
}
.font(ReleaseTypography.body)
}
Button {
openField = nil
resetLogControls()
let action: ReleaseAction = verifiedRelease && supportsVerifiedRelease ? .verified : .standard
model.publish(useVPC: useVPC, action: action)
if model.isRunning {
useVPC = false
verifiedRelease = false
}
} label: {
Label(model.selection.count > 1 ? "发布 \(model.selection.count) 个模块" : "发布", systemImage: "arrow.up.right")
.font(ReleaseTypography.action)
.frame(maxWidth: .infinity, minHeight: 38)
.foregroundStyle(ready ? Color.white : muted)
}
.buttonStyle(ReleaseButtonStyle(base: ready ? ReleaseColors.action : surface, prominent: true, radius: 8))
.disabled(!ready)
}
if let last = model.last {
Button {
openField = nil
resetLogControls()
model.showLastRelease()
} label: {
HStack {
Label("上次发布详情", systemImage: "clock.arrow.circlepath")
Spacer()
Text(last.module).lineLimit(1)
Image(systemName: "chevron.right").font(.system(size: 9, weight: .semibold))
}
.font(ReleaseTypography.detail)
.foregroundStyle(muted)
.padding(.horizontal, 7)
.frame(minHeight: 28)
}
.buttonStyle(ReleaseButtonStyle())
}
}
}
private var separator: some View {
Rectangle().fill(border).frame(height: 1).padding(.horizontal, 12)
}
private var moduleSummary: String {
if model.modules.isEmpty { return "没有可发布模块" }
if model.selection.isEmpty { return "选择模块" }
if model.selection.count == 1 { return model.selection[0] }
return "已选 \(model.selection.count) 个 · " + model.selection.joined(separator: ", ")
}
private var configurationPicker: some View {
VStack(spacing: 0) {
Button {
if openField == .profile {
openField = nil
} else {
model.refreshConfigurationFiles()
openField = .profile
}
configurationDraft = nil
} label: {
choiceHeader(.profile, value: model.profile?.title ?? "选择配置文件", icon: "doc.text", enabled: true)
}
.buttonStyle(ReleaseButtonStyle(radius: 0))
.accessibilityLabel(Field.profile.rawValue)
.accessibilityValue(model.profile?.title ?? "未选择")
if openField == .profile {
VStack(alignment: .leading, spacing: 6) {
let files = model.configurationFiles
if !files.isEmpty {
ScrollView {
VStack(spacing: 2) {
ForEach(files, id: \.self) { configurationRow($0) }
}
.padding(4)
}
.frame(height: min(150, CGFloat(files.count) * 44 + 8))
.background(terminal, in: RoundedRectangle(cornerRadius: 7))
}
if let draft = Binding($configurationDraft) {
configurationEditor(draft)
}
Button(action: browseConfiguration) {
Label("浏览其他 YAML…", systemImage: "folder")
.font(ReleaseTypography.detail)
.padding(.horizontal, 7)
.frame(minHeight: 26)
}
.buttonStyle(ReleaseButtonStyle())
.foregroundStyle(blue)
}
.padding([.horizontal, .bottom], 7)
}
}
}
private func configurationRow(_ file: String) -> some View {
let profile = model.configuration(for: file)
let selected = model.profile?.file == file
return HStack(spacing: 2) {
Button {
configurationDraft = nil
model.saveConfiguration(profile, select: true)
} label: {
HStack(spacing: 8) {
Image(systemName: selected ? "largecircle.fill.circle" : "circle")
.foregroundStyle(selected ? blue : muted)
VStack(alignment: .leading, spacing: 2) {
Text(profile.title).font(ReleaseTypography.body).lineLimit(1)
if profile.title != file {
Text(file).font(.system(.caption, design: .monospaced))
.foregroundStyle(muted).lineLimit(1)
}
}
Spacer(minLength: 3)
}
.padding(.horizontal, 8)
.frame(height: 42)
}
.buttonStyle(ReleaseButtonStyle(base: selected ? blue.opacity(0.12) : .clear, radius: 5))
.accessibilityAddTraits(selected ? .isSelected : [])
Button { configurationDraft = profile } label: {
Image(systemName: "pencil")
.foregroundStyle(blue)
.frame(width: 27, height: 27)
}
.buttonStyle(ReleaseButtonStyle())
.accessibilityLabel("编辑 \(file) 的别名和选项")
.help("编辑别名和选项")
}
}
private func configurationEditor(_ profile: Binding<DeployProfile>) -> some View {
VStack(alignment: .leading, spacing: 6) {
Text(profile.file.wrappedValue).font(.system(.caption, design: .monospaced))
.foregroundStyle(muted).lineLimit(1)
TextField("别名(可选)", text: profile.alias)
TextField("SSH 目标(可选)", text: profile.sshTarget)
HStack {
Spacer()
Button("取消") { configurationDraft = nil }
Button("保存") {
if let configurationDraft, model.saveConfiguration(configurationDraft) {
self.configurationDraft = nil
}
}
}
}
.font(ReleaseTypography.detail)
.padding(8)
.background(terminal, in: RoundedRectangle(cornerRadius: 7))
}
private func browseConfiguration() {
guard let project = model.project else { return }
let panel = NSOpenPanel()
panel.allowedContentTypes = [.yaml]
panel.directoryURL = project.root
panel.canChooseDirectories = false
guard panel.runModal() == .OK, let url = panel.url else { return }
let root = project.root.path + "/"
let path = url.path.hasPrefix(root) ? String(url.path.dropFirst(root.count)) : url.path
model.saveConfiguration(model.configuration(for: path), select: true)
}
private func choiceHeader(_ field: Field, value: String, icon: String, enabled: Bool) -> some View {
HStack(spacing: 9) {
Image(systemName: icon).frame(width: 15)
Text(field.rawValue).frame(width: 60, alignment: .leading)
Text(value).foregroundStyle(enabled ? .primary : muted).lineLimit(1)
Spacer(minLength: 4)
if enabled {
Image(systemName: openField == field ? "chevron.up" : "chevron.down")
.font(.system(size: 9, weight: .semibold))
}
}
.font(ReleaseTypography.body)
.foregroundStyle(muted)
.frame(height: 37)
.padding(.horizontal, 12)
.contentShape(Rectangle())
}
private func choice(
_ field: Field, value: String, icon: String, options: [String], selectedIndex: Int? = nil,
checked: Set<String> = [], multiple: Bool = false,
select: @escaping (Int) -> Void
) -> some View {
VStack(spacing: 0) {
Button {
openField = openField == field ? nil : field
configurationDraft = nil
} label: {
choiceHeader(field, value: value, icon: icon, enabled: !options.isEmpty)
}
.buttonStyle(ReleaseButtonStyle(radius: 0))
.disabled(options.isEmpty)
.accessibilityLabel(field.rawValue)
.accessibilityValue(value)
if openField == field, !options.isEmpty {
ScrollView {
VStack(spacing: 2) {
ForEach(options.indices, id: \.self) { index in
let selected = multiple ? checked.contains(options[index]) : selectedIndex == index
Button {
if !multiple { openField = nil }
select(index)
} label: {
HStack {
if multiple {
Image(systemName: selected ? "checkmark.square.fill" : "square")
.foregroundStyle(selected ? blue : muted)
}
Text(options[index]).lineLimit(field == .server ? nil : 1)
.fixedSize(horizontal: false, vertical: true)
Spacer()
if !multiple && selected {
Image(systemName: "checkmark").foregroundStyle(blue)
}
}
.font(ReleaseTypography.body)
.padding(.horizontal, 9)
.padding(.vertical, 4)
.frame(minHeight: 26)
}
.buttonStyle(ReleaseButtonStyle(base: selected ? blue.opacity(0.12) : .clear, radius: 5))
.accessibilityAddTraits(selected ? .isSelected : [])
}
}
.padding(4)
}
.frame(height: min(148, CGFloat(options.count) * 28 + 8))
.background(terminal, in: RoundedRectangle(cornerRadius: 7))
.padding([.horizontal, .bottom], 7)
}
}
}
private var running: some View {
VStack(alignment: .leading, spacing: 13) {
HStack(spacing: 10) {
if model.paused {
Image(systemName: "pause.circle").font(.system(size: 20)).foregroundStyle(.orange)
} else {
ProgressView().controlSize(.small).tint(blue)
}
Text(model.stopping ? "正在停止发布" : model.paused ? "发布已暂停" : model.phase?.title ?? "正在发布")
.font(ReleaseTypography.heading)
Spacer()
Button(action: model.togglePaused) {
Label(model.paused ? "继续" : "暂停", systemImage: model.paused ? "play.fill" : "pause.fill")
.font(ReleaseTypography.action)
.padding(.horizontal, 10)
.padding(.vertical, 6)
}
.buttonStyle(ReleaseButtonStyle(base: surface))
.disabled(model.stopping)
}
Text(model.runningTarget)
.font(ReleaseTypography.detail)
.foregroundStyle(muted)
.lineLimit(2)
HStack {
Label("实时输出", systemImage: "terminal")
Spacer()
if let started = model.started {
TimelineView(.periodic(from: started, by: 1)) { context in
Text("已用 \(max(0, Int(context.date.timeIntervalSince(started)))) 秒").monospacedDigit()
}
}
}
.font(.system(size: 11, weight: .medium))
.foregroundStyle(muted)
console(model.liveLog.isEmpty ? "等待命令输出…" : model.liveLog, followsOutput: true)
.task { await model.monitorLiveLog() }
if model.paused {
HStack {
Button(action: model.stopAndReturn) {
Label("结束发布并返回", systemImage: "chevron.left")
.font(ReleaseTypography.detail)
.padding(.horizontal, 7)
.frame(minHeight: 27)
}
.buttonStyle(ReleaseButtonStyle())
.foregroundStyle(blue)
.disabled(model.stopping)
Spacer(minLength: 8)
Text("远端任务可能仍在运行")
.font(ReleaseTypography.detail)
.foregroundStyle(muted)
}
}
}
}
private func details(_ last: ReleaseResult) -> some View {
let statusColor: Color = switch last.status {
case .succeeded: .green
case .failed: .red
case .cleanupFailed, .cancelled: .orange
}
let statusIcon = last.status == .succeeded ? "checkmark.circle.fill"
: last.status == .cancelled ? "stop.circle.fill" : "exclamationmark.circle.fill"
return VStack(alignment: .leading, spacing: 13) {
Button {
resetLogControls()
model.showRelease()
} label: {
Label("返回发布", systemImage: "chevron.left").font(ReleaseTypography.detail)
.padding(.horizontal, 7).frame(minHeight: 27)
}
.buttonStyle(ReleaseButtonStyle())
.foregroundStyle(blue)
VStack(alignment: .leading, spacing: 8) {
Label(last.headline, systemImage: statusIcon)
.font(ReleaseTypography.heading)
.foregroundStyle(statusColor)
Text(last.project + " / " + last.module).font(.system(size: 13, weight: .medium))
let configuration = last.configName == last.configFile
? last.configFile : [last.configName, last.configFile].compactMap { $0 }.joined(separator: " · ")
let target = [configuration, last.target].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
if !target.isEmpty { Text(target).font(.caption).foregroundStyle(muted) }
if let directory = last.auditDirectory, directory.hasPrefix("/") {
let manifest = URL(fileURLWithPath: directory).appending(path: "release.json")
if FileManager.default.fileExists(atPath: manifest.path) {
Button("在 Finder 查看发布记录") { NSWorkspace.shared.activateFileViewerSelecting([manifest]) }
.buttonStyle(ReleaseButtonStyle())
.foregroundStyle(blue)
}
}
Text(ReleaseRunner.displayTime(last.finishedAt) + " 北京时间 · \(last.duration) 秒")
.font(.caption).monospacedDigit().foregroundStyle(muted)
}
if let error = last.errorText ?? last.message {
Label(error, systemImage: "exclamationmark.triangle")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(statusColor)
.lineLimit(3)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(statusColor.opacity(0.12), in: RoundedRectangle(cornerRadius: 7))
}
DisclosureGroup("详细日志", isExpanded: $expanded) {
VStack(alignment: .leading, spacing: 8) {
HStack {
if last.errorLine != nil {
Button("跳到错误") { jumpRequest += 1 }
.disabled(model.fullLog == nil)
}
Spacer()
if let log = model.logURL, FileManager.default.fileExists(atPath: log.path) {
Button("打开日志文件") { NSWorkspace.shared.open(log) }
Button(copied ? "已复制" : "复制") {
guard let text = model.fullLog else { return }
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
copied = pasteboard.setString(text, forType: .string)
}
.disabled(model.fullLog == nil)
}
}
.buttonStyle(ReleaseButtonStyle(base: surface))
if let log = model.fullLog { console(log, errorLine: last.errorLine) }
}
.padding(.top, 8)
.task(id: last.logName) { await model.loadLog() }
}
}
}
private func console(_ text: String, errorLine: Int? = nil, followsOutput: Bool = false) -> some View {
LogTextView(text: text, errorLine: errorLine, jumpRequest: jumpRequest, followsOutput: followsOutput)
.frame(height: 208)
.background(terminal)
.clipShape(RoundedRectangle(cornerRadius: 8))
.overlay { RoundedRectangle(cornerRadius: 8).strokeBorder(border) }
}
private func resetLogControls() {
copied = false
expanded = false
jumpRequest = 0
}
}
import SwiftUI
enum ReleaseColors {
static let panel = Color(red: 0.075, green: 0.088, blue: 0.112)
static let surface = Color(red: 0.115, green: 0.133, blue: 0.165)
static let terminal = Color(red: 0.045, green: 0.054, blue: 0.075)
static let border = Color.white.opacity(0.105)
static let muted = Color(red: 0.62, green: 0.66, blue: 0.73)
static let blue = Color(red: 0.31, green: 0.62, blue: 1)
static let action = Color(red: 0.13, green: 0.35, blue: 0.86)
static let hover = Color(red: 0.17, green: 0.22, blue: 0.29)
static let actionHover = Color(red: 0.20, green: 0.46, blue: 0.98)
}
enum ReleaseTypography {
static let heading = Font.system(size: 17, weight: .semibold)
static let body = Font.system(size: 13)
static let action = Font.system(size: 13, weight: .medium)
static let detail = Font.system(size: 12)
}
struct ReleaseHover: ViewModifier {
var base: Color = .clear
var highlight = ReleaseColors.hover
var radius: CGFloat = 7
@Environment(\.isEnabled) private var enabled
@State private var hovering = false
func body(content: Content) -> some View {
content
.background(
enabled && hovering ? highlight : base, in: RoundedRectangle(cornerRadius: radius)
)
.contentShape(Rectangle())
.onHover { hovering = $0 }
}
}
struct ReleaseButtonStyle: ButtonStyle {
var base: Color = .clear
var prominent = false
var radius: CGFloat = 7
func makeBody(configuration: Configuration) -> some View {
configuration.label
.modifier(
ReleaseHover(
base: base,
highlight: prominent ? ReleaseColors.actionHover : ReleaseColors.hover,
radius: radius)
)
.opacity(configuration.isPressed ? 0.82 : 1)
}
}
import Foundation
import Observation
import ReleaseCore
private struct SavedPane: Codable {
var id: UUID
var projectID: UUID
var modules: [String]
var profileID: UUID?
var server: String?
var mavenCommand: MavenCommand?
var useVPC: Bool
var verified: Bool
var result: ReleaseResult?
}
@MainActor
@Observable
final class ReleasePaneState: Identifiable {
enum State: String { case idle, queued, running, finished, skipped }
let id: UUID
var projectID: UUID
var modules: [String]
var profileID: UUID?
var server: String?
var mavenCommand: MavenCommand
var useVPC: Bool
var verified: Bool
var search = ""
var availableModules: [String] = []
var servers: [InventoryTarget] = []
var state: State = .idle
var phase: ReleasePhase?
var result: ReleaseResult?
var log = ""
var error: String?
var paused = false
var stopping = false
@ObservationIgnored var control: ReleaseControl?
@ObservationIgnored var onChange: (() -> Void)?
@ObservationIgnored var inventoryTask: Task<Void, Never>?
fileprivate init(project: ReleaseProject, saved: SavedPane? = nil) {
id = saved?.id ?? UUID()
projectID = project.id
let available = (try? project.modules()) ?? []
availableModules = available
modules =
saved.map { selection in available.filter(Set(selection.modules).contains) }
?? available.first.map { [$0] } ?? []
profileID = saved?.profileID ?? project.profiles.first?.id
server = saved?.server
mavenCommand = saved?.mavenCommand ?? project.mavenCommand ?? .automatic
useVPC = saved?.useVPC ?? false
verified = saved?.verified ?? false
result = saved?.result
if result != nil { state = .finished }
refreshServers(for: project)
}
var selectedCount: Int { modules.count }
func refresh(for project: ReleaseProject) {
guard state != .running && state != .queued else { return }
availableModules = (try? project.modules()) ?? []
modules = availableModules.filter(Set(modules).contains)
if !project.profiles.contains(where: { $0.id == profileID }) {
profileID = project.profiles.first?.id
}
refreshServers(for: project)
}
func refreshServers(for project: ReleaseProject) {
inventoryTask?.cancel()
servers = []
guard project.type == .cityKeeper else { return }
inventoryTask = Task {
let targets = await Task.detached { Result { try project.inventoryTargets() } }.value
guard !Task.isCancelled else { return }
switch targets {
case let .success(found):
servers = found
if let server, !ReleaseProject.containsInventoryTarget(server, in: found) {
self.server = nil
}
case let .failure(error):
self.error = error.localizedDescription
}
}
}
func toggle(_ module: String) {
var checked = Set(modules)
if checked.remove(module) == nil { checked.insert(module) }
modules = availableModules.filter(checked.contains)
onChange?()
}
fileprivate var saved: SavedPane {
SavedPane(
id: id, projectID: projectID, modules: modules, profileID: profileID,
server: server, mavenCommand: mavenCommand, useVPC: useVPC,
verified: verified, result: result)
}
}
@MainActor
@Observable
final class SplitReleaseModel {
let settings: AppModel
private let storage: URL
private(set) var panes: [ReleasePaneState] = []
var error: String?
var statusChanged: (() -> Void)?
private var queued: [UUID] = []
private var batch = false
private var unread = false
private var runIDs = Set<UUID>()
private var batchStarted: Date?
private var completionTask: Task<Void, Never>?
private(set) var completionDuration: Int?
init(settings: AppModel, storage: URL) {
self.settings = settings
self.storage = storage
let path = storage.appending(path: "split-selection.json")
let saved = (try? Data(contentsOf: path)).flatMap {
try? JSONDecoder().decode([SavedPane].self, from: $0)
}
if let saved {
for selection in saved.prefix(4) {
if let project = settings.projects.first(where: { $0.id == selection.projectID }),
!panes.contains(where: { $0.projectID == project.id })
{
let pane = ReleasePaneState(project: project, saved: selection)
if let result = selection.result {
let path = storage.appending(path: "Logs").appending(path: result.logName)
if let bytes = try? Data(contentsOf: path) {
pane.log = String(decoding: bytes.suffix(64 * 1024), as: UTF8.self)
}
}
panes.append(pane)
}
}
}
if panes.isEmpty, let project = settings.project ?? settings.projects.first {
let legacy = (try? Data(contentsOf: storage.appending(path: "selection.json")))
.flatMap { try? JSONDecoder().decode(ReleaseSelection.self, from: $0) }
let initial = legacy.map {
SavedPane(
id: UUID(), projectID: project.id, modules: $0.modules,
profileID: $0.profileID, server: $0.server,
mavenCommand: nil, useVPC: false, verified: false, result: settings.last)
}
panes = [ReleasePaneState(project: project, saved: initial)]
}
panes.forEach { connect($0) }
}
var isRunning: Bool { panes.contains { $0.state == .running || $0.state == .queued } }
var current: ReleasePaneState? { panes.first { $0.state == .running } }
var progressPercentage: Int? {
let active = panes.filter { runIDs.contains($0.id) }
guard isRunning, !active.isEmpty else { return nil }
let completed = active.filter { $0.state == .finished }.count
let partial = active.filter { $0.state == .running }.reduce(0) {
$0 + ($1.phase?.estimatedPercentage ?? 0)
}
return min(99, (completed * 100 + partial) / active.count)
}
var indicator: ReleaseStatus? {
if isRunning { return nil }
if completionTask != nil { return .succeeded }
if unread {
return panes.filter { runIDs.contains($0.id) }.compactMap(\.result).first(where: {
$0.status != .succeeded
})?.status
}
return nil
}
func preparePopover() {
for pane in panes {
if let project = project(for: pane) { pane.refresh(for: project) }
if pane.state == .running { pane.log = pane.control?.liveOutput() ?? pane.log }
}
}
func project(for pane: ReleasePaneState) -> ReleaseProject? {
settings.projects.first { $0.id == pane.projectID }
}
func logURL(for result: ReleaseResult) -> URL {
storage.appending(path: "Logs").appending(path: result.logName)
}
func add() {
guard !isRunning, panes.count < 4,
let next = settings.projects.first(where: { project in
!panes.contains { $0.projectID == project.id }
})
else { return }
let pane = ReleasePaneState(project: next)
connect(pane)
panes.append(pane)
save()
}
func remove(_ pane: ReleasePaneState) {
guard !isRunning else { return }
pane.inventoryTask?.cancel()
panes.removeAll { $0.id == pane.id }
save()
statusChanged?()
}
func replace(_ pane: ReleasePaneState, with project: ReleaseProject) {
guard !isRunning, !panes.contains(where: { $0 !== pane && $0.projectID == project.id }),
let index = panes.firstIndex(where: { $0 === pane })
else { return }
pane.inventoryTask?.cancel()
let replacement = ReleasePaneState(project: project)
connect(replacement)
panes[index] = replacement
save()
}
func save() {
do {
try FileManager.default.createDirectory(at: storage, withIntermediateDirectories: true)
try JSONEncoder().encode(panes.map(\.saved))
.write(to: storage.appending(path: "split-selection.json"), options: .atomic)
} catch {
self.error = "保存项目窗口失败:\(error.localizedDescription)"
}
}
private func connect(_ pane: ReleasePaneState) {
pane.onChange = { [weak self] in self?.save() }
}
private struct Job {
var pane: ReleasePaneState
var project: ReleaseProject
var modules: [String]
var profile: DeployProfile?
var server: String?
var action: ReleaseAction
}
@ObservationIgnored private var jobs: [UUID: Job] = [:]
private func makeJob(_ pane: ReleasePaneState, action requestedAction: ReleaseAction? = nil)
throws -> Job
{
guard var project = project(for: pane) else { throw ReleaseError("项目已被删除。") }
project.mavenCommand = pane.mavenCommand
let profile =
project.type == .cityKeeper ? project.profiles.first { $0.id == pane.profileID } : nil
let server = project.type == .cityKeeper ? pane.server : nil
if project.type == .cityKeeper,
!ReleaseProject.containsInventoryTarget(server ?? "", in: pane.servers)
{
throw ReleaseError("请从 hosts 清单选择服务器。")
}
let action: ReleaseAction = requestedAction ?? (pane.verified ? .verified : .standard)
try project.validate()
_ = try project.commands(
for: pane.modules, profile: profile, server: server,
useVPC: pane.useVPC, action: action)
return Job(
pane: pane, project: project, modules: pane.modules, profile: profile,
server: server, action: action)
}
func publish(_ pane: ReleasePaneState, action: ReleaseAction? = nil) {
enqueue([pane], together: false, action: action)
}
func publishAll() {
enqueue(panes, together: true)
}
private func enqueue(
_ selected: [ReleasePaneState], together: Bool, action: ReleaseAction? = nil
) {
guard !selected.isEmpty, !isRunning else { return }
error = nil
var prepared: [Job] = []
for pane in selected {
do { prepared.append(try makeJob(pane, action: action)) } catch {
self.error = "\(project(for: pane)?.name ?? "项目"):\(error.localizedDescription)"
return
}
}
completionTask?.cancel()
completionTask = nil
completionDuration = nil
unread = false
batch = together
batchStarted = Date()
runIDs = Set(prepared.map { $0.pane.id })
if together, prepared.count > 1 {
let cityJobs = prepared.filter {
$0.project.type == .cityKeeper && $0.action == .standard
}
for index in cityJobs.indices {
for previous in cityJobs[..<index] {
if !Set(previous.modules).isDisjoint(with: cityJobs[index].modules) {
error = "两个项目包含同名镜像模块,请使用验证发布的独立镜像标签,或分别发布。"
runIDs.removeAll()
return
}
}
}
}
for job in prepared {
let pane = job.pane
pane.state = .queued
pane.result = nil
pane.phase = nil
pane.log = ""
pane.error = nil
pane.paused = false
pane.stopping = false
jobs[pane.id] = job
queued.append(pane.id)
}
save()
startAvailable()
}
private func conflicts(_ left: Job, _ right: Job) -> Bool {
if left.project.root == right.project.root { return true }
// Custom scripts have no declared deployment targets or build outputs.
if left.project.type == .custom || right.project.type == .custom { return true }
if let a = left.server, let b = right.server {
// Inventory groups can overlap. Only run deployment to different inventories in parallel.
let leftHosts = left.pane.servers.first { $0.name == a }?.members ?? [a]
let rightHosts = right.pane.servers.first { $0.name == b }?.members ?? [b]
if !Set(leftHosts).isDisjoint(with: rightHosts) { return true }
}
return false
}
private func startAvailable() {
while panes.filter({ $0.state == .running }).count < 2,
let index = queued.firstIndex(where: { id in
guard let candidate = jobs[id] else { return false }
return !panes.filter({ $0.state == .running }).compactMap({ jobs[$0.id] })
.contains(where: { conflicts(candidate, $0) })
})
{
let id = queued.remove(at: index)
guard let job = jobs[id] else { continue }
start(job)
}
statusChanged?()
}
private func start(_ job: Job) {
let pane = job.pane
let control = ReleaseControl()
pane.control = control
pane.state = .running
pane.phase = job.action == .preflight ? .preflight : .pulling
let runner = ReleaseRunner(storage: storage.appending(path: "Logs"))
Task {
let monitor = Task {
while !Task.isCancelled && pane.state == .running {
pane.log = control.liveOutput()
try? await Task.sleep(for: .milliseconds(250))
}
}
for await event in runner.start(
project: job.project, modules: job.modules,
profile: job.profile, server: job.server,
useVPC: pane.useVPC, action: job.action, control: control)
{
switch event {
case let .phase(phase):
pane.phase = phase
statusChanged?()
case let .finished(result):
monitor.cancel()
pane.log = control.liveOutput()
pane.control = nil
pane.result = result
pane.state = .finished
pane.phase = nil
pane.paused = false
pane.stopping = false
jobs.removeValue(forKey: pane.id)
if result.status != .succeeded && batch {
for id in queued {
jobs[id]?.pane.state = .skipped
jobs[id]?.pane.error = "前序项目失败,未执行"
jobs.removeValue(forKey: id)
}
queued.removeAll()
}
save()
if isRunning {
startAvailable()
} else {
unread = job.action != .preflight
let finished = panes.filter { runIDs.contains($0.id) }
if job.action != .preflight,
finished.allSatisfy({ $0.result?.status == .succeeded })
{
let duration = Int(batchStarted?.distance(to: Date()) ?? 0)
showCompletion(duration: duration)
}
}
statusChanged?()
}
}
}
}
func togglePause(_ pane: ReleasePaneState) {
guard pane.state == .running, let control = pane.control, !pane.stopping else { return }
do {
try control.setPaused(!pane.paused)
pane.paused.toggle()
pane.error = nil
statusChanged?()
} catch { pane.error = error.localizedDescription }
}
func stop(_ pane: ReleasePaneState) {
guard pane.state == .running, let control = pane.control, !pane.stopping else { return }
do {
try control.cancel()
pane.stopping = true
statusChanged?()
} catch { pane.error = error.localizedDescription }
}
private func showCompletion(duration: Int) {
let clock = ContinuousClock()
let finished = clock.now
completionTask = Task {
try? await clock.sleep(until: finished + .seconds(2))
guard !Task.isCancelled else { return }
completionDuration = duration
statusChanged?()
try? await clock.sleep(until: finished + .seconds(10))
guard !Task.isCancelled else { return }
completionDuration = nil
completionTask = nil
unread = false
statusChanged?()
}
}
}
import AppKit
import ReleaseCore
import SwiftUI
import UniformTypeIdentifiers
struct SplitReleasePanel: View {
@Bindable var model: SplitReleaseModel
let settings: () -> Void
let quit: () -> Void
private var width: CGFloat {
let desired = CGFloat(max(1, model.panes.count)) * 346 + 30
return min(desired, (NSScreen.main?.visibleFrame.width ?? 1440) - 36)
}
private var columnHeight: CGFloat {
min(630, max(420, (NSScreen.main?.visibleFrame.height ?? 900) - 160))
}
var body: some View {
VStack(spacing: 0) {
HStack {
Label("Java 发布", systemImage: "circle.dotted.circle")
.font(ReleaseTypography.heading)
Spacer()
Button {
model.add()
} label: {
Label("增加窗口", systemImage: "plus")
}
.disabled(
model.isRunning || model.panes.count >= 4
|| model.panes.count >= model.settings.projects.count
)
.buttonStyle(ReleaseButtonStyle())
Menu {
Button("项目设置…", action: settings)
Divider()
Button("退出 Java 发布", action: quit)
} label: {
Image(systemName: "gearshape")
.frame(width: 28, height: 28)
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.fixedSize()
.disabled(model.isRunning)
}
.padding(15)
Rectangle().fill(ReleaseColors.border).frame(height: 1)
if model.panes.isEmpty {
VStack(spacing: 14) {
Text("先在项目设置中添加项目,再增加发布窗口。")
.foregroundStyle(ReleaseColors.muted)
Button("项目设置…", action: settings)
}
.frame(maxWidth: .infinity, minHeight: 240)
} else {
ScrollView(.horizontal) {
HStack(alignment: .top, spacing: 0) {
ForEach(model.panes) { pane in
ProjectReleaseColumn(model: model, pane: pane)
.frame(width: 345)
if pane.id != model.panes.last?.id {
Rectangle().fill(ReleaseColors.border).frame(
width: 1, height: columnHeight)
}
}
}
}
.scrollIndicators(.automatic)
Rectangle().fill(ReleaseColors.border).frame(height: 1)
HStack {
if model.isRunning {
Text(
"运行 \(model.panes.filter { $0.state == .running }.count) · 排队 \(model.panes.filter { $0.state == .queued }.count)"
)
.foregroundStyle(ReleaseColors.muted)
} else {
Text("\(model.panes.count) / 4 个窗口")
.foregroundStyle(ReleaseColors.muted)
}
Spacer()
Button {
model.publishAll()
} label: {
Text("一起发布 \(model.panes.count) 个项目")
.font(ReleaseTypography.action)
.padding(.horizontal, 22)
.frame(height: 36)
}
.disabled(model.isRunning || model.panes.count < 2)
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.action, prominent: true))
}
.padding(14)
}
if let error = model.error {
Text(error)
.font(.caption)
.foregroundStyle(.red)
.textSelection(.enabled)
.padding([.horizontal, .bottom], 14)
}
}
.frame(width: width)
.background(ReleaseColors.panel)
.environment(\.colorScheme, .dark)
.tint(ReleaseColors.blue)
}
}
private struct ProjectReleaseColumn: View {
let model: SplitReleaseModel
@Bindable var pane: ReleasePaneState
@State private var configurationDraft: DeployProfile?
private var project: ReleaseProject? { model.project(for: pane) }
private var profile: DeployProfile? { project?.profiles.first { $0.id == pane.profileID } }
private var editable: Bool {
pane.state != .running && pane.state != .queued && !model.isRunning
}
private var columnHeight: CGFloat {
min(630, max(420, (NSScreen.main?.visibleFrame.height ?? 900) - 160))
}
private var matches: [String] {
let search = pane.search.trimmingCharacters(in: .whitespacesAndNewlines)
return search.isEmpty
? pane.availableModules
: pane.availableModules.filter { $0.localizedStandardContains(search) }
}
var body: some View {
ScrollView(.vertical) {
VStack(alignment: .leading, spacing: 11) {
HStack {
Menu {
ForEach(
model.settings.projects.filter { project in
!model.panes.contains {
$0.id != pane.id && $0.projectID == project.id
}
}
) { item in
Button(item.name) { model.replace(pane, with: item) }
}
} label: {
HStack {
Image(systemName: "folder")
Text(project?.name ?? "选择项目").lineLimit(1)
Image(systemName: "chevron.down")
.font(.system(size: 9))
}
.font(.system(size: 14, weight: .semibold))
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.disabled(!editable)
Spacer(minLength: 4)
Button {
model.remove(pane)
} label: {
Image(systemName: "xmark")
.frame(width: 22, height: 22)
}
.help("减少窗口")
.disabled(!editable)
.buttonStyle(ReleaseButtonStyle())
}
if let project {
if project.type == .cityKeeper {
menuRow("发布配置", selection: profile?.title ?? "选择配置文件") {
let files =
(try? project.configurationFiles()) ?? project.profiles.map(\.file)
ForEach(files, id: \.self) { file in
Button(
project.profiles.first(where: { $0.file == file })?.title
?? file
) {
selectConfiguration(file, in: project)
}
}
Divider()
Button("浏览其他 YAML…") { browseConfiguration(in: project) }
}
if let profile {
Button("编辑别名与 SSH 目标…") { configurationDraft = profile }
.font(ReleaseTypography.detail)
.buttonStyle(ReleaseButtonStyle())
.disabled(!editable)
}
menuRow(
"服务器",
selection: pane.servers.first(where: { $0.name == pane.server })?
.displayName
?? "选择服务器"
) {
ForEach(pane.servers, id: \.name) { target in
Button(target.displayName) {
pane.server = target.name
model.save()
}
}
}
}
if project.type == .cityKeeper {
menuRow("Maven", selection: pane.mavenCommand.title) {
ForEach(MavenCommand.allCases) { command in
Button(command.title) {
pane.mavenCommand = command
model.save()
}
}
}
}
if project.type == .cityKeeper {
HStack {
Toggle("VPC", isOn: $pane.useVPC)
Spacer()
if project.supportsVerifiedRelease(profile) {
Toggle("验证发布", isOn: $pane.verified)
Button("预检") { model.publish(pane, action: .preflight) }
.disabled(!editable || pane.modules.isEmpty)
.buttonStyle(ReleaseButtonStyle())
}
}
.toggleStyle(.checkbox)
.font(ReleaseTypography.detail)
.disabled(!editable)
.onChange(of: pane.useVPC) { model.save() }
.onChange(of: pane.verified) { model.save() }
}
HStack {
Image(systemName: "magnifyingglass")
.foregroundStyle(ReleaseColors.muted)
TextField("搜索模块", text: $pane.search)
.textFieldStyle(.plain)
if !pane.search.isEmpty {
Button {
pane.search = ""
} label: {
Image(systemName: "xmark.circle.fill")
}
.buttonStyle(.plain)
}
}
.padding(8)
.background(ReleaseColors.surface, in: RoundedRectangle(cornerRadius: 7))
.disabled(!editable)
ScrollView {
LazyVStack(spacing: 2) {
ForEach(matches, id: \.self) { module in
Button {
pane.toggle(module)
} label: {
HStack(spacing: 8) {
Image(
systemName: pane.modules.contains(module)
? "checkmark.square.fill" : "square"
)
.foregroundStyle(
pane.modules.contains(module)
? ReleaseColors.blue : ReleaseColors.muted)
Text(module).lineLimit(1)
Spacer()
}
.frame(height: 27)
.padding(.horizontal, 7)
}
.buttonStyle(ReleaseButtonStyle())
.disabled(!editable)
}
if matches.isEmpty {
Text("没有匹配的模块").foregroundStyle(ReleaseColors.muted).padding(8)
}
}
}
.frame(height: 78)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
Text("已选 \(pane.selectedCount) 个模块")
.foregroundStyle(ReleaseColors.muted)
.font(ReleaseTypography.detail)
HStack {
Text(paneTitle).font(ReleaseTypography.detail)
Spacer()
if pane.state == .running {
Button(pane.paused ? "继续" : "暂停") { model.togglePause(pane) }
.disabled(pane.stopping)
Button("停止") { model.stop(pane) }
.disabled(pane.stopping)
}
}
.buttonStyle(ReleaseButtonStyle())
.foregroundStyle(ReleaseColors.muted)
LogTextView(
text: pane.log.isEmpty
? (pane.state == .queued ? "等待构建资源…" : "") : pane.log,
errorLine: nil, jumpRequest: 0,
followsOutput: pane.state == .running
)
.frame(height: 150)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
if let result = pane.result {
Button("打开完整日志") {
NSWorkspace.shared.open(model.logURL(for: result))
}
.font(ReleaseTypography.detail)
.buttonStyle(ReleaseButtonStyle())
}
if let issue = pane.error ?? pane.result?.message, !issue.isEmpty {
Text(issue).font(.caption).foregroundStyle(.red).lineLimit(2)
}
Spacer(minLength: 2)
Button {
model.publish(pane)
} label: {
Text("发布此项目")
.font(ReleaseTypography.action)
.frame(maxWidth: .infinity, minHeight: 33)
}
.disabled(model.isRunning || pane.modules.isEmpty)
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.surface))
}
}
.padding(13)
}
.frame(height: columnHeight)
.font(ReleaseTypography.body)
.popover(item: $configurationDraft) { draft in
ConfigurationEditor(profile: draft) { updated in
saveProfile(updated)
configurationDraft = nil
}
}
}
private var paneTitle: String {
switch pane.state {
case .idle: return "命令行输出"
case .queued: return "排队中"
case .running:
return pane.stopping ? "正在停止" : pane.paused ? "已暂停" : pane.phase?.title ?? "正在发布"
case .skipped: return "未执行"
case .finished: return pane.result?.headline ?? "发布结束"
}
}
private func menuRow<Content: View>(
_ title: String, selection: String,
@ViewBuilder content: () -> Content
) -> some View {
HStack(spacing: 7) {
Text(title).foregroundStyle(ReleaseColors.muted).frame(width: 60, alignment: .leading)
Menu(content: content) {
HStack {
Text(selection).lineLimit(1)
Spacer(minLength: 2)
Image(systemName: "chevron.down").font(.system(size: 9))
}
.padding(.horizontal, 8)
.frame(height: 30)
.background(ReleaseColors.surface, in: RoundedRectangle(cornerRadius: 6))
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.disabled(!editable)
}
}
private func selectConfiguration(_ file: String, in project: ReleaseProject) {
if let existing = project.profiles.first(where: { $0.file == file }) {
pane.profileID = existing.id
model.save()
return
}
var added = DeployProfile()
added.file = file
saveProfile(added)
}
private func browseConfiguration(in project: ReleaseProject) {
let dialog = NSOpenPanel()
dialog.allowedContentTypes = [.yaml]
dialog.directoryURL = project.root
dialog.canChooseDirectories = false
dialog.showsHiddenFiles = true
guard dialog.runModal() == .OK, let file = dialog.url else { return }
let root = project.root.path + "/"
let name = file.path.hasPrefix(root) ? String(file.path.dropFirst(root.count)) : file.path
selectConfiguration(name, in: project)
}
private func saveProfile(_ updated: DeployProfile) {
guard var project else { return }
do {
try project.validate(updated)
if let index = project.profiles.firstIndex(where: { $0.id == updated.id }) {
project.profiles[index] = updated
} else {
project.profiles.append(updated)
}
try model.settings.save(project)
pane.profileID = updated.id
model.save()
} catch {
pane.error = error.localizedDescription
}
}
}
private struct ConfigurationEditor: View {
@State var profile: DeployProfile
let save: (DeployProfile) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 9) {
Text(profile.file).font(.system(size: 12, design: .monospaced))
TextField("别名", text: $profile.alias)
TextField("SSH 目标(可选)", text: $profile.sshTarget)
Button("保存") { save(profile) }
}
.padding(15)
.frame(width: 280)
.environment(\.colorScheme, .dark)
}
}
......@@ -12,6 +12,19 @@ public enum ScriptType: String, Codable, CaseIterable, Identifiable, Sendable {
}
}
public enum MavenCommand: String, Codable, CaseIterable, Identifiable, Sendable {
case automatic, mvnd, mvn
public var id: Self { self }
public var title: String {
switch self {
case .automatic: "自动(优先 mvnd)"
case .mvnd: "mvnd"
case .mvn: "mvn"
}
}
}
public struct DeployProfile: Codable, Identifiable, Equatable, Sendable {
public var id = UUID()
public var alias = ""
......@@ -66,6 +79,8 @@ public struct ReleaseProject: Codable, Identifiable, Equatable, Sendable {
public var toolPath = ""
public var mavenPath: String?
public var mvndPath: String?
// Optional so projects saved before the Maven selector remain decodable.
public var mavenCommand: MavenCommand?
public init() {}
......@@ -258,6 +273,28 @@ public struct ReleaseProject: Codable, Identifiable, Equatable, Sendable {
func mavenOverrides() throws -> [String: String] {
var overrides: [String: String] = [:]
if type == .cityKeeper {
let detected = detectedMavenPaths()
func available(_ name: String, configured: String?) -> String? {
let path = configured?.trimmingCharacters(in: .whitespacesAndNewlines)
let expanded = path.map { ($0 as NSString).expandingTildeInPath }
return expanded.flatMap { Self.isExecutable($0) ? $0 : nil } ?? detected[name]
}
let mvnd = available("mvnd", configured: mvndPath)
let mvn = available("mvn", configured: mavenPath)
let preferred = mavenCommand ?? .automatic
let name: String
switch preferred {
case .automatic: name = mvnd != nil ? "mvnd" : "mvn"
case .mvnd: name = "mvnd"
case .mvn: name = "mvn"
}
guard let executable = name == "mvnd" ? mvnd : mvn else {
throw ReleaseError("找不到 \(name),请在项目设置里选择可执行文件或切换 Maven 方式。")
}
// The existing shell script probes mvnd first. Point both names at the choice.
return ["mvn": executable, "mvnd": executable]
}
for (name, value) in [("mvn", mavenPath), ("mvnd", mvndPath)] {
guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else { continue }
let path = (value as NSString).expandingTildeInPath
......
import Foundation
@testable import JavaReleaseMenu
@testable import ReleaseCore
import XCTest
final class ReleaseRunnerTests: XCTestCase {
@MainActor
func testSplitReleaseKeepsIndependentLogsAndQueuesUnknownScriptTargets() async throws {
let first = try Fixture()
let second = try Fixture()
defer { first.remove(); second.remove() }
try "sleep 0.5\nprintf 'first task completed\\n'\n".write(
to: first.local.appending(path: "release.sh"), atomically: true, encoding: .utf8
)
try "printf 'second task completed\\n'\n".write(
to: second.local.appending(path: "release.sh"), atomically: true, encoding: .utf8
)
let storage = first.base.appending(path: "app-state")
let settings = AppModel(storage: storage)
var alpha = first.project
alpha.name = "Alpha"
var beta = second.project
beta.name = "Beta"
try settings.save(alpha)
try settings.save(beta)
let model = SplitReleaseModel(settings: settings, storage: storage)
model.add()
XCTAssertEqual(model.panes.count, 2)
model.publishAll()
XCTAssertEqual(model.panes.filter { $0.state == .running }.count, 1)
XCTAssertEqual(model.panes.filter { $0.state == .queued }.count, 1)
for _ in 0..<100 where model.isRunning {
try await Task.sleep(for: .milliseconds(50))
}
XCTAssertFalse(model.isRunning)
XCTAssertEqual(model.panes.map { $0.result?.status }, [.succeeded, .succeeded])
XCTAssertTrue(model.panes.contains { $0.log.contains("first task completed") })
XCTAssertTrue(model.panes.contains { $0.log.contains("second task completed") })
let restored = SplitReleaseModel(settings: settings, storage: storage)
XCTAssertEqual(restored.panes.count, 2)
XCTAssertTrue(restored.panes.contains { $0.log.contains("first task completed") })
}
@MainActor
func testSplitReleaseRunsDisjointCityKeeperTargetsConcurrently() async throws {
let first = try Fixture()
let second = try Fixture()
defer { first.remove(); second.remove() }
try first.createCityKeeperFixture()
try second.createCityKeeperFixture()
for fixture in [first, second] {
try "sleep 0.8\nprintf 'independent build completed\\n'\n".write(
to: fixture.local.appending(path: "build-and-deploy"), atomically: true, encoding: .utf8
)
}
let secondInventory = second.local.appending(path: "bin/ansible-inventory")
try "#!/bin/sh\nprintf '@all:\\n |--@SECOND:\\n | |--other-host\\n'\n".write(
to: secondInventory, atomically: true, encoding: .utf8
)
let storage = first.base.appending(path: "app-state")
let settings = AppModel(storage: storage)
var alpha = first.project
alpha.name = "Alpha"
alpha.type = .cityKeeper
alpha.inventoryPath = "hosts"
alpha.toolPath = first.local.appending(path: "bin").path
var beta = second.project
beta.name = "Beta"
beta.type = .cityKeeper
beta.inventoryPath = "hosts"
beta.toolPath = second.local.appending(path: "bin").path
var profile = DeployProfile()
profile.file = "deploy.yaml"
alpha.profiles = [profile]
beta.profiles = [profile]
try settings.save(alpha)
try settings.save(beta)
let model = SplitReleaseModel(settings: settings, storage: storage)
model.add()
for _ in 0..<100 where model.panes.contains(where: { $0.servers.isEmpty }) {
try await Task.sleep(for: .milliseconds(20))
}
for pane in model.panes {
guard let project = model.project(for: pane) else { continue }
pane.server = pane.servers.first?.name
pane.modules = [project.id == alpha.id ? "gateway" : "meter-cloud"]
}
model.publishAll()
XCTAssertNil(model.error)
XCTAssertEqual(model.panes.filter { $0.state == .running }.count, 2)
for _ in 0..<100 where model.isRunning {
try await Task.sleep(for: .milliseconds(50))
}
XCTAssertEqual(model.panes.map { $0.result?.status }, [.succeeded, .succeeded])
}
func testPullUpdatesCodeBeforeStartingScript() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
......@@ -143,6 +234,30 @@ final class ReleaseRunnerTests: XCTestCase {
XCTAssertEqual(legacy.modules, ["gateway"])
}
func testCityKeeperMavenPreferenceAndLegacySelection() throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.createCityKeeperFixture()
var project = fixture.project
project.type = .cityKeeper
project.toolPath = fixture.local.appending(path: "bin").path
let legacy = try JSONEncoder().encode(project)
let oldConfig = try JSONSerialization.jsonObject(with: legacy) as! [String: Any]
XCTAssertNil(oldConfig["mavenCommand"])
let decoded = try JSONDecoder().decode(ReleaseProject.self, from: legacy)
XCTAssertNil(decoded.mavenCommand)
XCTAssertEqual(try decoded.mavenOverrides()["mvn"],
fixture.local.appending(path: "bin/mvnd").path)
project.mavenCommand = .mvn
XCTAssertEqual(try project.mavenOverrides()["mvnd"],
fixture.local.appending(path: "bin/mvn").path)
project.mavenCommand = .mvnd
XCTAssertEqual(try project.mavenOverrides()["mvn"],
fixture.local.appending(path: "bin/mvnd").path)
}
func testMavenPathsAreDetectedAndOverridesReachDeploymentScript() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
......@@ -397,6 +512,11 @@ private struct Fixture {
let inventory = bin.appending(path: "ansible-inventory")
try "#!/bin/sh\nprintf '@all:\\n |--@PHY1:\\n | |--local-fixture\\n'\n".write(to: inventory, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: inventory.path)
for name in ["mvn", "mvnd"] {
let tool = bin.appending(path: name)
try "#!/bin/sh\nexit 0\n".write(to: tool, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: tool.path)
}
}
func advanceOrigin() throws {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment