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)
......
This diff is collapsed.
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)
}
}
This diff is collapsed.
This diff is collapsed.
......@@ -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