Commit 530bc587 authored by zpc's avatar zpc

Initial JavaReleaseMenu app

parents
.build/
dist/
.DS_Store
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>zh-Hans</string>
<key>CFBundleDisplayName</key>
<string>Java 发布</string>
<key>CFBundleExecutable</key>
<string>JavaReleaseMenu</string>
<key>CFBundleIdentifier</key>
<string>local.javareleasemenu</string>
<key>CFBundleIconFile</key>
<string>JavaReleaseMenu.icns</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>JavaReleaseMenu</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.2.0</string>
<key>CFBundleVersion</key>
<string>6</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
<true/>
<key>NSHighResolutionCapable</key>
<true/>
</dict>
</plist>
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "JavaReleaseMenu",
platforms: [.macOS(.v14)],
products: [.executable(name: "JavaReleaseMenu", targets: ["JavaReleaseMenu"])],
targets: [
.target(name: "ReleaseCore"),
.executableTarget(name: "JavaReleaseMenu", dependencies: ["ReleaseCore"]),
.testTarget(name: "ReleaseCoreTests", dependencies: ["ReleaseCore"])
],
swiftLanguageModes: [.v6]
)
# Java 发布
macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布时,圆环内显示按阶段估算的百分比,暂停时保留当前百分比。发布成功后显示 100%,2 秒后显示总耗时,完成满 10 秒恢复空心圆环。再点圆环会打开发布页,上次结果可从「上次发布详情」查看。右键圆环可退出。
## 安装与配置
1. 解压后将整个 `JavaReleaseMenu` 目录放进 `~/SoftSpace`,双击 `dist/JavaReleaseMenu.app`。随附的 App 适用于 Apple 芯片和 macOS 14 或更新版本。
2. 点击菜单栏圆形图标,在「项目设置」添加本地 Git 仓库。仓库当前分支需要关联远端分支,并已配置本机 Git 认证。
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 守护进程和已启动的远端任务可能继续运行。
上次发布详情显示项目、模块、配置、服务器、完成时间(北京时间)和总耗时秒数,耗时从拉取代码前开始计算。展开「详细日志」可以查看、复制或打开完整日志文件。发布失败时会显示识别到的第一条错误,点「跳到错误」定位。若无可识别的错误行,会显示脚本退出原因。CityKeeper 脚本报告部署完成但清理返回非零时,详情标为「部署完成,收尾失败」。
项目配置、最近发布详情和日志保存在 `~/Library/Application Support/JavaReleaseMenu`。新建或编辑项目时,「运行环境」会从 PATH、Maven 环境变量和常见安装目录查找 `mvn` 与 `mvnd`。留空使用自动探测路径,也可以为项目分别指定可执行文件。发布脚本里的同名命令会使用指定路径。「工具 PATH」可补充其他工具目录,例如 `ansible-inventory` 的安装目录。
## HQ 验证发布
项目仓库接入发布脚本补丁后,选择 `deploy_hq.yaml` 即可看到「预检」和「验证发布」。预检检查本机工具、配置和目标主机清单,不拉 Git、不编译、不推镜像。验证发布默认不勾选,勾选后按 digest 发布,并逐台核对运行镜像与容器状态。发布详情可定位到该次记录的 `release.json`。
终端可先构建再部署,适合先检查要发的镜像。使用相同仓库、发布配置和 Ansible inventory。
```bash
./build-and-deploy --preflight --verified --ds <组名> --config deploy_hq.yaml <模块>
./build-and-deploy --verified --build-only --ds <组名> --config deploy_hq.yaml <模块>
./build-and-deploy --deploy-run <记录目录>
./build-and-deploy --recheck-run <记录目录>
```
`--deploy-run` 只接受尚未开始部署的构建记录。部署已开始或远端状态不明时,用 `--recheck-run` 生成独立复核记录,原记录仍可查阅。实际的服务接口探活、镜像仓库访问与 VPC 网络要在目标环境中验证。来自不同工作站的发布需要团队侧协调。
## 本地构建与测试
使用 Swift 6 工具链。运行 `swift test` 验证本地 Git 仓库和假发布脚本,运行 `./build-app.sh` 生成当前机器架构的 App。
import AppKit
import Observation
import ReleaseCore
@MainActor
@Observable
final class AppModel {
enum Page { case release, details }
private(set) var projects: [ReleaseProject] = []
var projectID: UUID? {
didSet {
if oldValue != projectID, !restoring {
selectedModules = nil
server = nil
refreshOptions()
refreshServers()
rememberSelection()
}
}
}
private(set) var selectedModules: [String]?
var selection: [String] { selectedModules ?? [] }
var profileID: UUID? {
didSet { if oldValue != profileID { rememberSelection() } }
}
var server: String? {
didSet { if oldValue != server { rememberSelection() } }
}
private(set) var servers: [InventoryTarget] = []
var hasSelectedServer: Bool {
guard let server else { return false }
return ReleaseProject.containsInventoryTarget(server, in: servers)
}
private(set) var loadingServers = false
private(set) var inventoryError: String?
private var inventoryTask: Task<Void, Never>?
var profile: DeployProfile? { project?.profiles.first { $0.id == profileID } }
private(set) var configurationFiles: [String] = []
private(set) var modules: [String] = []
private(set) var phase: ReleasePhase?
private(set) var last: ReleaseResult?
private(set) var detailResult: ReleaseResult?
private(set) var started: Date?
private(set) var runningTarget = ""
private(set) var paused = false
private(set) var stopping = false
private var pausedPercentage: Int?
var progressPercentage: Int? { pausedPercentage ?? phase?.estimatedPercentage }
private(set) var liveLog = ""
private var control: ReleaseControl?
private(set) var fullLog: String?
private var restoring = true
var page: Page = .release
var error: String?
var statusChanged: (() -> Void)?
var closePopover: (() -> Void)?
private let storage: URL
private var unreadResult = false
private var completionTask: Task<Void, Never>?
private(set) var completionDuration: Int?
var project: ReleaseProject? { projects.first { $0.id == projectID } }
var isRunning: Bool { started != nil }
var indicator: ReleaseStatus? {
if completionTask != nil { return .succeeded }
guard detailResult?.action != .preflight else { return nil }
return unreadResult ? detailResult?.status : nil
}
var logURL: URL? {
detailResult.map { storage.appending(path: "Logs").appending(path: $0.logName) }
}
init(storage: URL) {
self.storage = storage
do {
projects = try load([ReleaseProject].self, from: "projects.json") ?? []
last = try load(ReleaseResult.self, from: "latest.json")
} catch {
self.error = "读取本地记录失败:\(error.localizedDescription)"
}
do {
if let selection = try load(ReleaseSelection.self, from: "selection.json") {
projectID = projects.first { $0.id == selection.projectID }?.id ?? projects.first?.id
if projectID == selection.projectID { selectedModules = selection.modules }
profileID = selection.profileID
server = selection.server
} else {
projectID = projects.first?.id
}
} catch {
projectID = projects.first?.id
self.error = "读取上次选择失败:\(error.localizedDescription)"
}
refreshOptions()
restoring = false
refreshServers()
}
func refreshServers() {
inventoryTask?.cancel()
servers = []
inventoryError = nil
loadingServers = false
guard let project, project.type == .cityKeeper else { return }
loadingServers = true
inventoryTask = Task {
let result = await Task.detached { Result { try project.inventoryTargets() } }.value
guard !Task.isCancelled else { return }
loadingServers = false
switch result {
case let .success(hosts):
servers = hosts
if server != nil, !hasSelectedServer { server = nil }
case let .failure(error):
inventoryError = error.localizedDescription
}
}
}
func refreshOptions() {
let wasRestoring = restoring
restoring = true
defer { restoring = wasRestoring }
if profile == nil { profileID = project?.profiles.first?.id }
refreshConfigurationFiles()
do {
modules = try project?.modules() ?? []
} catch {
modules = []
self.error = "读取发布模块失败:\(error.localizedDescription)"
}
if let selectedModules {
self.selectedModules = modules.filter(Set(selectedModules).contains)
} else if let first = modules.first {
selectedModules = [first]
}
}
func refreshConfigurationFiles() {
guard let project, project.type == .cityKeeper else {
configurationFiles = []
return
}
configurationFiles = (try? project.configurationFiles()) ?? project.profiles.map(\.file).sorted()
}
func configuration(for file: String) -> DeployProfile {
if let profile, profile.file == file { return profile }
if let saved = project?.profiles.first(where: { $0.file == file }) { return saved }
var profile = DeployProfile()
profile.file = file
return profile
}
@discardableResult
func saveConfiguration(_ profile: DeployProfile, select: Bool = false) -> Bool {
guard let index = projects.firstIndex(where: { $0.id == projectID }) else { return false }
do {
try projects[index].validate(profile)
var updated = projects
if let existing = updated[index].profiles.firstIndex(where: { $0.id == profile.id }) {
updated[index].profiles[existing] = profile
} else {
updated[index].profiles.append(profile)
}
try persist(updated, to: "projects.json")
projects = updated
refreshConfigurationFiles()
error = nil
if select { profileID = profile.id }
return true
} catch {
self.error = error.localizedDescription
return false
}
}
func toggleModule(_ module: String) {
var checked = Set(selection)
if checked.remove(module) == nil { checked.insert(module) }
selectedModules = modules.filter(checked.contains)
rememberSelection()
}
func save(_ project: ReleaseProject) throws {
try project.validate()
var updated = projects
if let index = updated.firstIndex(where: { $0.id == project.id }) {
updated[index] = project
} else {
updated.append(project)
}
try persist(updated, to: "projects.json")
projects = updated
error = nil
projectID = project.id
refreshOptions()
refreshServers()
rememberSelection()
}
func removeProject(_ id: UUID) throws {
let updated = projects.filter { $0.id != id }
try persist(updated, to: "projects.json")
projects = updated
if projectID == id { projectID = projects.first?.id }
}
func preparePopover() {
if isRunning || unreadResult {
page = .details
liveLog = control?.liveOutput() ?? liveLog
} else {
page = .release
refreshOptions()
if servers.isEmpty && !loadingServers { refreshServers() }
}
}
func showLastRelease() {
fullLog = nil
detailResult = last
page = .details
}
func togglePaused() {
guard let control, !stopping else { return }
do {
try control.setPaused(!paused)
pausedPercentage = paused ? nil : phase?.estimatedPercentage
paused.toggle()
error = nil
statusChanged?()
} catch {
self.error = "切换暂停状态失败:\(error.localizedDescription)"
}
}
func stopAndReturn() {
guard paused, !stopping, let control else { return }
do {
try control.cancel()
stopping = true
error = nil
statusChanged?()
} catch {
self.error = "停止发布失败:\(error.localizedDescription)"
}
}
func monitorLiveLog() async {
guard let control else { return }
while !Task.isCancelled, isRunning {
let output = control.liveOutput()
if output != liveLog { liveLog = output }
try? await Task.sleep(for: .milliseconds(250))
}
}
func loadLog() async {
guard fullLog == nil, let logURL else { return }
let result = await Task.detached {
Result {
let data = try Data(contentsOf: logURL)
return String(decoding: data, as: UTF8.self).replacing(/\u{1B}\[[0-9;]*[A-Za-z]/, with: "")
}
}.value
guard !Task.isCancelled, self.logURL == logURL else { return }
switch result {
case let .success(text): fullLog = text
case let .failure(error): self.error = "读取日志失败:\(error.localizedDescription)"
}
}
func showRelease() {
guard !isRunning else { return }
unreadResult = false
page = .release
refreshOptions()
rememberSelection()
statusChanged?()
}
func publish(useVPC: Bool, action: ReleaseAction = .standard) {
guard !isRunning, let project, !selection.isEmpty else { return }
error = nil
let selected = selection
let selectedProfile = project.type == .cityKeeper ? profile : nil
let selectedServer = project.type == .cityKeeper ? server : nil
if project.type == .cityKeeper {
guard hasSelectedServer else {
error = "请从 hosts 清单选择服务器。"
return
}
}
do {
_ = try project.commands(for: selected, profile: selectedProfile, server: selectedServer, useVPC: useVPC, action: action)
} catch {
self.error = error.localizedDescription
return
}
rememberSelection()
completionTask?.cancel()
completionTask = nil
completionDuration = nil
unreadResult = false
runningTarget = ([project.name, selected.joined(separator: ", ")] + [selectedProfile?.title, selectedServer].compactMap { $0 })
.joined(separator: " / ")
fullLog = nil
liveLog = ""
paused = false
let control = ReleaseControl()
self.control = control
started = Date()
phase = action == .preflight ? .preflight : .pulling
page = .details
if action != .preflight { closePopover?() }
statusChanged?()
let runner = ReleaseRunner(storage: storage.appending(path: "Logs"))
Task {
for await event in runner.start(project: project, modules: selected, profile: selectedProfile,
server: selectedServer, useVPC: useVPC, action: action, control: control) {
switch event {
case let .phase(current):
phase = current
case let .finished(result):
let returnToRelease = stopping
if action != .preflight {
do {
try persist(result, to: "latest.json")
} catch {
self.error = "保存发布详情失败:\(error.localizedDescription)"
}
last = result
}
detailResult = result
phase = nil
started = nil
paused = false
stopping = false
pausedPercentage = nil
liveLog = ""
self.control = nil
if returnToRelease {
showRelease()
} else {
unreadResult = true
page = .details
if result.status == .succeeded && action != .preflight {
startCompletionDisplay(duration: result.duration)
}
}
}
statusChanged?()
}
}
}
private func startCompletionDisplay(duration: Int) {
let clock = ContinuousClock()
let finished = clock.now
completionTask = Task { [weak self] in
try? await clock.sleep(until: finished + .seconds(2))
guard !Task.isCancelled else { return }
self?.completionDuration = duration
self?.statusChanged?()
try? await clock.sleep(until: finished + .seconds(10))
guard let self, !Task.isCancelled else { return }
self.completionDuration = nil
self.completionTask = nil
self.unreadResult = false
self.statusChanged?()
}
}
private func rememberSelection() {
guard !restoring else { return }
do {
try persist(ReleaseSelection(projectID: projectID, modules: selection, profileID: profileID, server: server), to: "selection.json")
} catch {
self.error = "保存本次选择失败:\(error.localizedDescription)"
}
}
private func load<T: Decodable>(_ type: T.Type, from name: String) throws -> T? {
let url = storage.appending(path: name)
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
return try JSONDecoder().decode(type, from: Data(contentsOf: url))
}
private func persist<T: Encodable>(_ value: T, to name: String) throws {
try FileManager.default.createDirectory(at: storage, withIntermediateDirectories: true)
try JSONEncoder().encode(value).write(to: storage.appending(path: name), options: .atomic)
}
}
import AppKit
import SwiftUI
import ReleaseCore
@main
struct JavaReleaseApp {
@MainActor static func main() {
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let delegate = MenuController()
app.delegate = delegate
withExtendedLifetime(delegate) { app.run() }
}
}
@MainActor
final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
private let model = AppModel(
storage: URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
)
private var item: NSStatusItem?
private let popover = NSPopover()
private var settings: NSWindow?
func applicationDidFinishLaunching(_ notification: Notification) {
let menu = NSMenu()
let edit = NSMenuItem()
edit.submenu = NSMenu(title: "编辑")
edit.submenu?.addItem(withTitle: "剪切", action: #selector(NSText.cut(_:)), keyEquivalent: "x")
edit.submenu?.addItem(withTitle: "复制", action: #selector(NSText.copy(_:)), keyEquivalent: "c")
edit.submenu?.addItem(withTitle: "粘贴", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
edit.submenu?.addItem(withTitle: "全选", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")
menu.addItem(edit)
NSApp.mainMenu = menu
let item = NSStatusBar.system.statusItem(withLength: 29)
self.item = item
item.button?.target = self
item.button?.action = #selector(toggle)
item.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
popover.behavior = .transient
popover.appearance = NSAppearance(named: .darkAqua)
popover.contentViewController = NSHostingController(rootView: ReleasePanel(
model: model,
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() }
updateIndicator()
}
@objc private func toggle() {
guard let button = item?.button else { return }
if let event = NSApp.currentEvent, event.type == .rightMouseUp {
popover.close()
let menu = NSMenu()
let quit = NSMenuItem(title: "退出 Java 发布", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
quit.target = NSApp
menu.addItem(quit)
menu.popUp(positioning: nil, at: NSPoint(x: 0, y: button.bounds.minY), in: button)
return
}
if popover.isShown {
popover.performClose(nil)
} else {
settings?.orderOut(nil)
model.preparePopover()
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
popover.contentViewController?.view.window?.makeKey()
}
}
private func openSettings() {
popover.close()
if settings == nil {
let controller = NSHostingController(rootView: ProjectSettings(model: model))
let window = NSWindow(contentViewController: controller)
window.title = "项目设置"
window.titleVisibility = .hidden
window.styleMask = [.titled, .closable, .resizable]
window.appearance = NSAppearance(named: .darkAqua)
window.backgroundColor = NSColor(ReleaseColors.panel)
window.contentMinSize = NSSize(width: 560, height: 430)
window.setContentSize(NSSize(width: 600, height: 616))
window.isReleasedWhenClosed = false
window.delegate = self
window.center()
settings = window
}
settings?.makeKeyAndOrderFront(nil)
NSApplication.shared.activate()
}
func windowWillClose(_ notification: Notification) {
if notification.object as? NSWindow === settings { settings = nil }
}
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
if model.isRunning {
let alert = NSAlert()
alert.messageText = "发布正在运行"
alert.informativeText = "发布结束后可以退出 Java 发布。"
alert.runModal()
return .terminateCancel
}
return .terminateNow
}
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 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)
}
private static func indicatorImage(percentage: Int?, duration: Int?, paused: Bool, result: ReleaseStatus?) -> NSImage {
let image = NSImage(size: NSSize(width: 24, height: 24), flipped: false) { _ in
let circle = NSBezierPath(ovalIn: NSRect(x: 5, y: 5, width: 14, height: 14))
circle.lineWidth = 1.5
if let percentage {
let color: NSColor = paused ? .systemOrange : result == .succeeded ? .systemGreen : .systemBlue
let ring = NSBezierPath(ovalIn: NSRect(x: 1.4, y: 1.4, width: 21.2, height: 21.2))
ring.lineWidth = 1.65
color.withAlphaComponent(0.28).setStroke()
ring.stroke()
color.setStroke()
if percentage == 100 {
ring.stroke()
} else {
let arc = NSBezierPath()
arc.appendArc(withCenter: NSPoint(x: 12, y: 12), radius: 10.6,
startAngle: 90, endAngle: 90 - 3.6 * CGFloat(percentage), clockwise: true)
arc.lineWidth = ring.lineWidth
arc.lineCapStyle = .round
arc.stroke()
}
let label = duration.map { "\($0)s" } ?? "\(percentage)%"
let fontSize = min(8, 26 / CGFloat(label.count))
let text = NSAttributedString(string: label, attributes: [
.font: NSFont.monospacedDigitSystemFont(ofSize: fontSize, weight: .bold),
.foregroundColor: color
])
let size = text.size()
text.draw(at: NSPoint(x: (24 - size.width) / 2, y: (24 - size.height) / 2))
} else if let result {
let color: NSColor = result == .cleanupFailed ? .systemOrange : .systemRed
color.setStroke()
circle.stroke()
let glyph = NSBezierPath()
glyph.lineWidth = 1.45
glyph.lineCapStyle = .round
glyph.lineJoinStyle = .round
glyph.move(to: NSPoint(x: 12, y: 15.2))
glyph.line(to: NSPoint(x: 12, y: 11.2))
glyph.move(to: NSPoint(x: 12, y: 8.9))
glyph.line(to: NSPoint(x: 12, y: 8.8))
glyph.stroke()
} else {
NSColor.black.setStroke()
circle.stroke()
}
return true
}
image.isTemplate = percentage == nil && result == nil
return image
}
}
import AppKit
import SwiftUI
struct LogTextView: NSViewRepresentable {
let text: String
let errorLine: Int?
let jumpRequest: Int
var followsOutput = false
final class Coordinator {
var text: String?
var errorRange: NSRange?
var lastJump = 0
}
func makeCoordinator() -> Coordinator { Coordinator() }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSTextView.scrollableTextView()
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
scroll.drawsBackground = false
if let editor = scroll.documentView as? NSTextView {
editor.isEditable = false
editor.isSelectable = true
editor.drawsBackground = false
editor.usesFindBar = true
editor.textContainerInset = NSSize(width: 10, height: 9)
editor.setAccessibilityLabel("完整发布日志")
}
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let editor = scroll.documentView as? NSTextView else { return }
let coordinator = context.coordinator
if coordinator.text != text {
let visible = scroll.contentView.bounds
let follow = followsOutput && (coordinator.text == nil || visible.maxY >= editor.bounds.height - 24)
let selection = editor.selectedRange()
coordinator.text = text
coordinator.errorRange = nil
let styled = NSMutableAttributedString(string: text, attributes: [
.font: NSFont.monospacedSystemFont(ofSize: 11, weight: .regular),
.foregroundColor: NSColor(srgbRed: 0.78, green: 0.83, blue: 0.90, alpha: 1)
])
if let errorLine, let range = lineRange(at: errorLine) {
styled.addAttribute(.foregroundColor, value: NSColor.systemRed, range: range)
coordinator.errorRange = range
}
editor.textStorage?.setAttributedString(styled)
if NSMaxRange(selection) <= styled.length { editor.setSelectedRange(selection) }
if follow {
editor.scrollRangeToVisible(NSRange(location: styled.length, length: 0))
} else if followsOutput {
scroll.contentView.scroll(to: visible.origin)
scroll.reflectScrolledClipView(scroll.contentView)
}
}
if coordinator.lastJump != jumpRequest {
coordinator.lastJump = jumpRequest
if let range = coordinator.errorRange {
editor.setSelectedRange(range)
editor.scrollRangeToVisible(range)
editor.window?.makeFirstResponder(editor)
}
}
}
private func lineRange(at line: Int) -> NSRange? {
let source = text as NSString
var start = 0
for _ in 0..<line {
let newline = source.range(of: "\n", range: NSRange(location: start, length: source.length - start))
guard newline.location != NSNotFound else { return nil }
start = NSMaxRange(newline)
}
guard start < source.length else { return nil }
let newline = source.range(of: "\n", range: NSRange(location: start, length: source.length - start))
let end = newline.location == NSNotFound ? source.length : newline.location
return NSRange(location: start, length: end - start)
}
}
import AppKit
import ReleaseCore
import SwiftUI
struct ProjectSettings: View {
let model: AppModel
@State private var draft = ReleaseProject()
@State private var error: String?
@State private var confirmingRemoval = false
@State private var detectedMavenPaths: [String: String] = [:]
private var editing: Bool { model.projects.contains { $0.id == draft.id } }
var body: some View {
VStack(alignment: .leading, spacing: 0) {
HStack(spacing: 10) {
Label("项目设置", systemImage: "gearshape")
.font(ReleaseTypography.heading)
Spacer()
Button { edit(ReleaseProject()) } label: {
Label("新建项目", systemImage: "plus")
}
.buttonStyle(SettingsButtonStyle())
}
.padding(.horizontal, 22)
.padding(.vertical, 17)
ScrollView {
VStack(alignment: .leading, spacing: 14) {
if !model.projects.isEmpty {
Menu {
ForEach(model.projects) { project in
Button(project.name) { edit(project) }
}
} label: {
menuLabel(editing ? draft.name : "选择已保存的项目", icon: "folder")
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.accessibilityLabel("已保存的项目")
}
section("项目", icon: "folder") {
field("名称", text: $draft.name)
HStack(spacing: 8) {
field("目录", text: $draft.directory, monospaced: true)
Button("选择…", action: chooseDirectory).buttonStyle(SettingsButtonStyle())
}
row("发布方式") {
Menu {
ForEach(ScriptType.allCases) { type in
Button { draft.type = type } label: {
if draft.type == type {
Label(type.title, systemImage: "checkmark")
} else {
Text(type.title)
}
}
}
} label: {
menuLabel(draft.type.title)
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.accessibilityLabel("发布方式")
}
}
section("发布环境", icon: "shippingbox") {
if draft.type == .cityKeeper {
HStack(spacing: 8) {
field("Ansible hosts", text: $draft.inventoryPath, prompt: "/etc/ansible/hosts", monospaced: true)
Button("浏览…", action: chooseInventory).buttonStyle(SettingsButtonStyle())
}
Button("使用系统 hosts") { draft.inventoryPath = "/etc/ansible/hosts" }
.buttonStyle(SettingsButtonStyle())
.padding(.leading, 92)
toggle("重新构建同版本镜像(-f)", isOn: $draft.forceBuild)
} else {
HStack(spacing: 8) {
field("发布脚本", text: $draft.script, monospaced: true)
Button("选择…", action: chooseScript).buttonStyle(SettingsButtonStyle())
}
field("可发布模块", text: $draft.customModules, prompt: "用逗号分隔")
}
}
section("运行环境", icon: "terminal") {
mavenField("mvn", path: $draft.mavenPath)
mavenField("mvnd", path: $draft.mvndPath)
Button("重新扫描 Maven", action: scanMaven)
.buttonStyle(SettingsButtonStyle())
.padding(.leading, 92)
field("工具 PATH", text: $draft.toolPath, prompt: "可选,用冒号分隔目录", monospaced: true)
}
}
.padding(.horizontal, 22)
.padding(.bottom, 16)
}
Rectangle().fill(ReleaseColors.border).frame(height: 1)
VStack(alignment: .leading, spacing: 9) {
if let error {
Label(error, systemImage: "exclamationmark.circle")
.font(.caption).foregroundStyle(.red)
.textSelection(.enabled)
}
HStack {
if editing {
Button("移除项目", role: .destructive) { confirmingRemoval = true }
.buttonStyle(SettingsButtonStyle())
}
Spacer()
Button("取消") { NSApp.keyWindow?.close() }
.buttonStyle(SettingsButtonStyle())
.keyboardShortcut(.cancelAction)
Button("保存", action: save)
.buttonStyle(SettingsButtonStyle(prominent: true))
.keyboardShortcut(.defaultAction)
}
}
.padding(.horizontal, 22)
.padding(.vertical, 13)
}
.frame(minWidth: 560, idealWidth: 600, minHeight: 430, idealHeight: 616)
.background(ReleaseColors.panel)
.environment(\.colorScheme, .dark)
.tint(ReleaseColors.blue)
.onAppear {
edit(model.project ?? ReleaseProject())
}
.onChange(of: draft.toolPath) { scanMaven() }
.confirmationDialog("移除“\(draft.name)”的发布配置?", isPresented: $confirmingRemoval) {
Button("移除项目", role: .destructive) {
do {
try model.removeProject(draft.id)
edit(model.project ?? ReleaseProject())
} catch { self.error = error.localizedDescription }
}
}
}
private func section<Content: View>(_ title: String, icon: String, @ViewBuilder content: () -> Content) -> some View {
VStack(alignment: .leading, spacing: 9) {
Label(title, systemImage: icon).font(.system(size: 13, weight: .semibold))
.padding(.bottom, 3)
content()
}
.padding(13)
.frame(maxWidth: .infinity, alignment: .leading)
.background(ReleaseColors.surface, in: RoundedRectangle(cornerRadius: 11))
.overlay { RoundedRectangle(cornerRadius: 11).strokeBorder(ReleaseColors.border).allowsHitTesting(false) }
}
private func row<Content: View>(_ label: String, @ViewBuilder content: () -> Content) -> some View {
HStack(spacing: 8) {
Text(label).font(ReleaseTypography.body).foregroundStyle(ReleaseColors.muted)
.frame(width: 84, alignment: .leading)
content().frame(maxWidth: .infinity, alignment: .leading)
}
}
private func field(_ label: String, text: Binding<String>, prompt: String = "", monospaced: Bool = false) -> some View {
row(label) {
TextField(label, text: text, prompt: Text(prompt).foregroundStyle(ReleaseColors.muted))
.labelsHidden()
.textFieldStyle(.plain)
.font(monospaced ? .system(size: 12, design: .monospaced) : ReleaseTypography.body)
.padding(.horizontal, 10)
.frame(height: 30)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 6))
.overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(ReleaseColors.border).allowsHitTesting(false) }
}
}
private func menuLabel(_ value: String, icon: String? = nil) -> some View {
HStack(spacing: 8) {
if let icon { Image(systemName: icon).foregroundStyle(ReleaseColors.muted) }
Text(value).lineLimit(1)
Spacer(minLength: 8)
Image(systemName: "chevron.down").font(.system(size: 9, weight: .semibold))
.foregroundStyle(ReleaseColors.muted)
}
.font(ReleaseTypography.body)
.padding(.horizontal, 10)
.frame(height: 30)
.modifier(ReleaseHover(base: ReleaseColors.terminal, radius: 6))
.overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(ReleaseColors.border).allowsHitTesting(false) }
}
private func toggle(_ label: String, isOn: Binding<Bool>) -> some View {
Toggle(label, isOn: isOn)
.toggleStyle(.checkbox)
.font(ReleaseTypography.body)
.padding(.leading, 92)
}
private func edit(_ project: ReleaseProject) {
draft = project
error = nil
scanMaven()
}
private func scanMaven() {
detectedMavenPaths = draft.detectedMavenPaths()
}
private func mavenField(_ name: String, path: Binding<String?>) -> some View {
let text = Binding(get: { path.wrappedValue ?? "" }, set: { path.wrappedValue = $0.isEmpty ? nil : $0 })
return HStack(spacing: 8) {
field(name, text: text, prompt: detectedMavenPaths[name] ?? "未找到,选择可执行文件", monospaced: true)
Button("选择…") {
let panel = NSOpenPanel()
panel.canChooseDirectories = false
panel.showsHiddenFiles = true
panel.prompt = "选择 \(name)"
if let current = path.wrappedValue ?? detectedMavenPaths[name] {
let expanded = (current as NSString).expandingTildeInPath
panel.directoryURL = URL(fileURLWithPath: expanded).deletingLastPathComponent()
}
if panel.runModal() == .OK, let url = panel.url { path.wrappedValue = url.path }
}
.buttonStyle(SettingsButtonStyle())
.accessibilityLabel("选择 \(name) 可执行文件")
}
.help(path.wrappedValue ?? detectedMavenPaths[name] ?? "")
}
private func chooseInventory() {
let panel = NSOpenPanel()
panel.canChooseDirectories = false
panel.showsHiddenFiles = true
panel.directoryURL = draft.inventoryPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
? URL(fileURLWithPath: "/etc/ansible", isDirectory: true)
: draft.inventoryURL.deletingLastPathComponent()
if panel.runModal() == .OK, let url = panel.url { draft.inventoryPath = url.path }
}
private func save() {
do {
try model.save(draft)
error = nil
NSApp.keyWindow?.close()
} catch { self.error = error.localizedDescription }
}
private func chooseDirectory() {
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.prompt = "选择项目"
if !draft.directory.isEmpty { panel.directoryURL = draft.root }
if panel.runModal() == .OK, let url = panel.url {
draft.directory = url.path
if draft.name.isEmpty { draft.name = url.lastPathComponent }
let cityKeeper = url.appending(path: "build-and-deploy").path
draft.type = FileManager.default.fileExists(atPath: cityKeeper) ? .cityKeeper : .custom
if draft.type == .cityKeeper, draft.inventoryPath == "/etc/ansible/hosts",
FileManager.default.fileExists(atPath: url.appending(path: "ansible.hosts.yaml").path) {
draft.inventoryPath = "ansible.hosts.yaml"
}
scanMaven()
}
}
private func chooseScript() {
let panel = NSOpenPanel()
panel.canChooseDirectories = false
panel.prompt = "选择脚本"
if !draft.directory.isEmpty { panel.directoryURL = draft.root }
if panel.runModal() == .OK, let url = panel.url { draft.script = url.path }
}
}
private struct SettingsButtonStyle: ButtonStyle {
var prominent = false
func makeBody(configuration: Configuration) -> some View {
configuration.label
.font(ReleaseTypography.action)
.padding(.horizontal, prominent ? 21 : 10)
.frame(height: 30)
.foregroundStyle(configuration.role == .destructive ? Color.red : Color.white)
.modifier(ReleaseHover(base: prominent ? ReleaseColors.action : ReleaseColors.surface,
highlight: prominent ? ReleaseColors.actionHover : ReleaseColors.hover, radius: 6))
.overlay { RoundedRectangle(cornerRadius: 6).strokeBorder(ReleaseColors.border).allowsHitTesting(false) }
.opacity(configuration.isPressed ? 0.72 : 1)
.contentShape(Rectangle())
}
}
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 Foundation
public struct InventoryTarget: Equatable, Sendable {
public let name: String
public let members: [String]
public var displayName: String {
members.isEmpty ? name : "\(name)(\(members.joined(separator: "、")))"
}
}
extension ReleaseProject {
public var inventoryURL: URL {
let path = (inventoryPath as NSString).expandingTildeInPath
return path.hasPrefix("/") ? URL(fileURLWithPath: path) : root.appending(path: path)
}
public func inventoryTargets() throws -> [InventoryTarget] {
try inventoryTargets(control: ReleaseControl())
}
func inventoryTargets(control: ReleaseControl) throws -> [InventoryTarget] {
guard !inventoryPath.isEmpty,
(try? inventoryURL.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else {
throw ReleaseError("找不到 Ansible hosts 文件,请在项目设置选择。")
}
let scratch = FileManager.default.temporaryDirectory.appending(path: "java-release-inventory-" + UUID().uuidString)
try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
defer { try? FileManager.default.removeItem(at: scratch) }
let config = scratch.appending(path: "ansible.cfg")
try "[defaults]\n".write(to: config, atomically: true, encoding: .utf8)
var environment = deploymentEnvironment()
environment["ANSIBLE_CONFIG"] = config.path
environment["ANSIBLE_LOCAL_TEMP"] = scratch.appending(path: "temp").path
environment["ANSIBLE_INVENTORY_ENABLED"] = "yaml,ini"
environment["ANSIBLE_INVENTORY_ANY_UNPARSED_IS_FAILED"] = "true"
environment["ANSIBLE_NOCOLOR"] = "1"
var data = Data()
let status = try control.run("/usr/bin/env", ["ansible-inventory", "-i", inventoryURL.path, "--graph"],
in: root, environment: environment) { data.append($0) }
guard status == 0 else {
throw ReleaseError("无法读取 hosts,请核对静态 YAML/INI 清单和 ansible-inventory 的 PATH。")
}
let targets = Self.parseInventoryGraph(String(decoding: data, as: UTF8.self))
guard !targets.isEmpty else { throw ReleaseError("hosts 清单中没有服务器。") }
return targets
}
static func parseInventoryGraph(_ graph: String) -> [InventoryTarget] {
var groups: [(name: String, indent: Int)] = []
var membersByGroup: [String: Set<String>] = [:]
var hostNames = Set<String>()
for line in graph.split(separator: "\n") {
guard let marker = line.range(of: "|--") else { continue }
let indent = line.distance(from: line.startIndex, to: marker.lowerBound)
while let group = groups.last, group.indent >= indent { groups.removeLast() }
let value = String(line[marker.upperBound...]).trimmingCharacters(in: .whitespaces)
if value.hasPrefix("@"), value.hasSuffix(":") {
let name = String(value.dropFirst().dropLast())
if name != "all", name != "ungrouped", isInventoryTarget(name) {
groups.append((name, indent))
}
} else if isInventoryTarget(value) {
for group in groups { membersByGroup[group.name, default: []].insert(value) }
hostNames.insert(value)
}
}
let ascending: (String, String) -> Bool = { $0.localizedStandardCompare($1) == .orderedAscending }
let groupedHosts = Set(membersByGroup.values.flatMap { $0 })
let groupTargets = membersByGroup.keys.sorted(by: ascending).map {
InventoryTarget(name: $0, members: membersByGroup[$0, default: []].sorted(by: ascending))
}
return groupTargets + hostNames.subtracting(groupedHosts).sorted(by: ascending).map {
InventoryTarget(name: $0, members: [])
}
}
public static func containsInventoryTarget(_ name: String, in targets: [InventoryTarget]) -> Bool {
targets.contains { $0.name == name || $0.members.contains(name) }
}
private static func isInventoryTarget(_ name: String) -> Bool {
name.wholeMatch(of: /[A-Za-z0-9_][A-Za-z0-9_.:-]*/) != nil
}
}
import Darwin
import Foundation
public final class ReleaseControl: Sendable {
private struct State {
var process: pid_t?
var paused = false
var cancelled = false
var output = Data()
}
private let condition = NSCondition()
nonisolated(unsafe) private var state = State()
public init() {}
public func setPaused(_ paused: Bool) throws {
condition.lock()
defer { condition.unlock() }
if state.cancelled { throw CancellationError() }
guard paused != state.paused else { return }
if let process = state.process, kill(-process, paused ? SIGSTOP : SIGCONT) != 0, errno != ESRCH {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
state.paused = paused
if !paused { condition.broadcast() }
}
public func cancel() throws {
condition.lock()
defer { condition.unlock() }
guard !state.cancelled else { return }
if let process = state.process, kill(-process, SIGKILL) != 0, errno != ESRCH {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
state.cancelled = true
condition.broadcast()
}
var isCancelled: Bool {
condition.lock()
defer { condition.unlock() }
return state.cancelled
}
public func liveOutput() -> String {
condition.lock()
let bytes = state.output
condition.unlock()
return String(decoding: bytes.drop(while: { $0 & 0xC0 == 0x80 }), as: UTF8.self)
.replacing(/\u{1B}\[[0-?]*[ -\/]*[@-~]/, with: "")
.replacingOccurrences(of: "\r\n", with: "\n")
.replacingOccurrences(of: "\r", with: "\n")
}
func append(_ bytes: Data) {
condition.lock()
defer { condition.unlock() }
state.output.append(bytes)
let limit = 64 * 1024
if state.output.count > limit { state.output = Data(state.output.suffix(limit)) }
}
func run(
_ executable: String, _ arguments: [String], in directory: URL,
environment: [String: String], receive: (Data) throws -> Void
) throws -> Int32 {
let pipe = Pipe()
let reader = pipe.fileHandleForReading
let writer = pipe.fileHandleForWriting
defer { try? reader.close(); try? writer.close() }
var actions: posix_spawn_file_actions_t?
try Self.check(posix_spawn_file_actions_init(&actions))
defer { posix_spawn_file_actions_destroy(&actions) }
try Self.check(posix_spawn_file_actions_addchdir_np(&actions, directory.path))
try Self.check(posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0))
try Self.check(posix_spawn_file_actions_adddup2(&actions, writer.fileDescriptor, STDOUT_FILENO))
try Self.check(posix_spawn_file_actions_adddup2(&actions, writer.fileDescriptor, STDERR_FILENO))
var attributes: posix_spawnattr_t?
try Self.check(posix_spawnattr_init(&attributes))
defer { posix_spawnattr_destroy(&attributes) }
try Self.check(posix_spawnattr_setpgroup(&attributes, 0))
try Self.check(posix_spawnattr_setflags(&attributes, Int16(POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_CLOEXEC_DEFAULT)))
var argv = ([executable] + arguments).map { strdup($0) }
var envp = environment.map { strdup("\($0.key)=\($0.value)") }
defer {
argv.forEach { free($0) }
envp.forEach { free($0) }
}
guard !argv.contains(nil), !envp.contains(nil) else { throw POSIXError(.ENOMEM) }
argv.append(nil)
envp.append(nil)
var pid: pid_t = 0
condition.lock()
while state.paused && !state.cancelled { condition.wait() }
if state.cancelled {
condition.unlock()
throw CancellationError()
}
let launchError = posix_spawn(&pid, executable, &actions, &attributes, &argv, &envp)
if launchError == 0 { state.process = pid }
condition.unlock()
try Self.check(launchError)
try? writer.close()
var outputError: Error?
var buffer = [UInt8](repeating: 0, count: 32 * 1024)
var input = pollfd(fd: reader.fileDescriptor, events: Int16(POLLIN), revents: 0)
while !isCancelled {
let ready = poll(&input, 1, 100)
if ready == 0 || (ready < 0 && errno == EINTR) { continue }
if ready < 0 {
outputError = outputError ?? POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
try? reader.close()
break
}
let count = buffer.withUnsafeMutableBytes { read(reader.fileDescriptor, $0.baseAddress, $0.count) }
if count > 0 {
if outputError == nil {
do { try receive(Data(buffer.prefix(count))) } catch { outputError = error }
}
} else if count == 0 {
break
} else if errno != EINTR {
outputError = outputError ?? POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
try? reader.close()
break
}
}
// Keep the PID reserved until it is no longer reachable by pause/resume.
var info = siginfo_t()
while waitid(P_PID, id_t(pid), &info, WEXITED | WNOWAIT) == -1 && errno == EINTR {}
condition.lock()
state.process = nil
var status: Int32 = 0
var reaped: pid_t
repeat { reaped = waitpid(pid, &status, 0) } while reaped == -1 && errno == EINTR
let waitError = errno
let cancelled = state.cancelled
condition.unlock()
if cancelled { throw CancellationError() }
if reaped == -1 { throw POSIXError(POSIXErrorCode(rawValue: waitError) ?? .EIO) }
if let outputError { throw outputError }
let signal = status & 0x7F
return signal == 0 ? (status >> 8) & 0xFF : 128 + signal
}
private static func check(_ error: Int32) throws {
if error != 0 { throw POSIXError(POSIXErrorCode(rawValue: error) ?? .EIO) }
}
}
import Foundation
public enum ScriptType: String, Codable, CaseIterable, Identifiable, Sendable {
case cityKeeper, custom
public var id: Self { self }
public var title: String {
switch self {
case .cityKeeper: "CityKeeper Cloud"
case .custom: "自定义 Bash 脚本"
}
}
}
public struct DeployProfile: Codable, Identifiable, Equatable, Sendable {
public var id = UUID()
public var alias = ""
public var file = ""
public var sshTarget = ""
public init() {}
public var title: String { alias.isEmpty ? file : alias }
}
public struct ReleaseSelection: Codable, Equatable, Sendable {
public var projectID: UUID?
public var modules: [String]
public var profileID: UUID?
public var server: String?
public init(projectID: UUID? = nil, modules: [String] = [], profileID: UUID? = nil, server: String? = nil) {
self.projectID = projectID
self.modules = modules
self.profileID = profileID
self.server = server
}
private enum CodingKeys: String, CodingKey { case projectID, modules, profileID, server }
private enum LegacyKeys: String, CodingKey { case module }
public init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
projectID = try values.decodeIfPresent(UUID.self, forKey: .projectID)
profileID = try values.decodeIfPresent(UUID.self, forKey: .profileID)
server = try values.decodeIfPresent(String.self, forKey: .server)
if let saved = try values.decodeIfPresent([String].self, forKey: .modules) {
modules = saved
} else {
let legacy = try decoder.container(keyedBy: LegacyKeys.self)
let module = try legacy.decodeIfPresent(String.self, forKey: .module) ?? ""
modules = module.isEmpty ? [] : [module]
}
}
}
public struct ReleaseProject: Codable, Identifiable, Equatable, Sendable {
public var id = UUID()
public var name = ""
public var directory = ""
public var type: ScriptType = .cityKeeper
public var profiles: [DeployProfile] = []
public var inventoryPath = "/etc/ansible/hosts"
public var forceBuild = true
public var script = ""
public var customModules = ""
public var toolPath = ""
public var mavenPath: String?
public var mvndPath: String?
public init() {}
public var root: URL { URL(fileURLWithPath: directory, isDirectory: true).standardizedFileURL }
public func modules() throws -> [String] {
switch type {
case .cityKeeper:
let docker = root.appending(path: "docker", directoryHint: .isDirectory)
guard FileManager.default.fileExists(atPath: docker.path) else {
throw ReleaseError("项目根目录缺少 docker/,无法识别可发布模块。")
}
let folders = try FileManager.default.contentsOfDirectory(
at: docker, includingPropertiesForKeys: nil, options: .skipsHiddenFiles
)
let imageNames = folders.filter {
Self.isModuleName($0.lastPathComponent) && Self.isFile($0.appending(path: "Dockerfile"))
}.map(\.lastPathComponent).sorted { $0.count > $1.count }
let pom = try XMLDocument(contentsOf: root.appending(path: "pom.xml"),
options: [.nodeLoadExternalEntitiesNever])
let modules = try pom.nodes(forXPath: """
/*[local-name()='project']/*[local-name()='modules']/*[local-name()='module']
""")
let deployable = modules.compactMap { node -> String? in
guard let path = node.stringValue?.trimmingCharacters(in: .whitespacesAndNewlines),
!path.isEmpty else { return nil }
let project = root.appending(path: path, directoryHint: .isDirectory).standardizedFileURL
guard Self.isFile(project.appending(path: "pom.xml")) else { return nil }
let name = project.lastPathComponent
return imageNames.first { name == $0 || name.hasSuffix("-" + $0) }
}
return Set(deployable).sorted()
case .custom:
return Array(Set(customModules.split(whereSeparator: {
$0.isWhitespace || $0 == ","
}).map(String.init))).sorted()
}
}
public func validate() throws {
guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw ReleaseError("请输入项目名称。")
}
guard directory.hasPrefix("/"), FileManager.default.fileExists(atPath: root.path) else {
throw ReleaseError("请选择本地项目目录。")
}
let git = root.appending(path: ".git")
guard FileManager.default.fileExists(atPath: git.path) else {
throw ReleaseError("请选择 Git 仓库根目录。")
}
_ = try mavenOverrides()
switch type {
case .cityKeeper:
guard !root.path.contains(where: \.isWhitespace) else {
throw ReleaseError("现有 CityKeeper 脚本要求项目路径没有空白字符。")
}
guard Self.isFile(root.appending(path: "build-and-deploy")),
Self.isFile(root.appending(path: "pom.xml")) else {
throw ReleaseError("此目录缺少 build-and-deploy 或 pom.xml。")
}
guard !inventoryPath.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw ReleaseError("请选择 Ansible hosts 文件。")
}
for profile in profiles { try validate(profile) }
case .custom:
guard !script.isEmpty, Self.isFile(file(script)) else {
throw ReleaseError("请选择有效的 Bash 发布脚本。")
}
}
let available = try modules()
if type == .cityKeeper, available.isEmpty {
throw ReleaseError("没有识别到可发布模块。请检查根 pom.xml 中的模块是否有对应的 docker/<模块名>/Dockerfile。")
}
guard !available.isEmpty, available.allSatisfy(Self.isModuleName) else {
throw ReleaseError("请配置可发布模块。模块名可使用字母、数字、点、下划线和连字符。")
}
}
public func availableYAMLFiles() throws -> [String] {
try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isRegularFileKey],
options: .skipsHiddenFiles)
.filter { Self.isYAML($0.pathExtension) && Self.isFile($0) }
.map(\.lastPathComponent).sorted()
}
public func configurationFiles() throws -> [String] {
let files = try availableYAMLFiles().filter { path in
let candidate = file(path)
let name = candidate.deletingPathExtension().lastPathComponent
return candidate.standardizedFileURL.path != inventoryURL.standardizedFileURL.path
&& !["hosts", "ansible.hosts", "inventory"].contains(name.lowercased())
}
return Set(files + profiles.map(\.file)).sorted()
}
public func validate(_ profile: DeployProfile) throws {
guard profile.sshTarget.isEmpty || Self.isTarget(profile.sshTarget) else {
throw ReleaseError("请输入有效的 SSH 目标。")
}
guard profile.file.wholeMatch(of: #/[A-Za-z0-9_./][A-Za-z0-9_./-]*/#) != nil,
Self.isYAML(file(profile.file).pathExtension), Self.isFile(file(profile.file)) else {
throw ReleaseError("请选择有效的 YAML 文件,路径可使用字母、数字、点、下划线、连字符和斜线。")
}
}
public func supportsVerifiedRelease(_ profile: DeployProfile?) -> Bool {
guard type == .cityKeeper, let profile else { return false }
let config = file(profile.file).standardizedFileURL
return config == root.appending(path: "deploy_hq.yaml").standardizedFileURL
&& Self.isFile(root.appending(path: "release-verify.yml"))
&& Self.isFile(root.appending(path: "release-manifest.py"))
}
public func commands(for selected: [String], profile: DeployProfile? = nil, server: String? = nil,
useVPC: Bool = false, action: ReleaseAction = .standard) throws -> [[String]] {
let available = Set(try modules())
guard !selected.isEmpty else { throw ReleaseError("请至少选择一个模块。") }
guard Set(selected).count == selected.count,
selected.allSatisfy({ Self.isModuleName($0) && available.contains($0) }) else {
throw ReleaseError("所选模块已不在项目中或存在重复模块。")
}
if action != .standard, !supportsVerifiedRelease(profile) {
throw ReleaseError("此配置尚未接入验证发布,请使用常规发布,或为 HQ 安装发布脚本补丁。")
}
switch type {
case .cityKeeper:
guard let profile, profiles.contains(profile) else { throw ReleaseError("请选择发布配置。") }
try validate(profile)
guard let server, Self.isTarget(server) else { throw ReleaseError("请选择服务器。") }
let scriptURL = root.appending(path: "build-and-deploy")
guard Self.isFile(scriptURL) else { throw ReleaseError("找不到 build-and-deploy。") }
var arguments = [scriptURL.path]
if action != .standard { arguments.append("--verified") }
if action == .preflight { arguments.append("--preflight") }
if forceBuild { arguments.append("-f") }
if useVPC { arguments.append("--vpc") }
arguments += ["--ds", server, "--config", profile.file]
if !profile.sshTarget.isEmpty { arguments += ["--ss", profile.sshTarget] }
return [arguments + selected]
case .custom:
let scriptURL = file(script)
guard !script.isEmpty, Self.isFile(scriptURL) else { throw ReleaseError("找不到发布脚本。") }
return selected.map { [scriptURL.path, $0] }
}
}
public func deploymentEnvironment() -> [String: String] {
var environment = ProcessInfo.processInfo.environment
let home = FileManager.default.homeDirectoryForCurrentUser
let localMavenBins = (try? FileManager.default.contentsOfDirectory(
at: home, includingPropertiesForKeys: nil, options: .skipsHiddenFiles
))?.filter {
$0.lastPathComponent.hasPrefix("apache-maven-") || $0.lastPathComponent.hasPrefix("maven-mvnd-")
}.sorted {
$0.lastPathComponent.compare($1.lastPathComponent, options: .numeric) == .orderedDescending
}.map { $0.appending(path: "bin").path } ?? []
let mavenHomeBins = ["MAVEN_HOME", "M2_HOME", "MVND_HOME"].compactMap { key in
environment[key].flatMap { $0.isEmpty ? nil : ($0 as NSString).appendingPathComponent("bin") }
}
let standard = [
"/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin",
home.appending(path: ".local/bin").path, home.appending(path: ".docker/bin").path,
home.appending(path: ".sdkman/candidates/maven/current/bin").path,
home.appending(path: ".sdkman/candidates/mvnd/current/bin").path
]
let entries = (toolPath + ":" + (environment["PATH"] ?? "")).split(separator: ":").map(String.init)
var seen = Set<String>()
let paths = (entries + mavenHomeBins + standard + localMavenBins).map {
($0 as NSString).expandingTildeInPath
}.filter { $0.hasPrefix("/") && seen.insert($0).inserted }
environment["PATH"] = paths.joined(separator: ":")
environment["GIT_TERMINAL_PROMPT"] = "0"
if type == .cityKeeper {
environment["ANSIBLE_INVENTORY"] = inventoryURL.path
environment["PYTHONUNBUFFERED"] = "1"
}
return environment
}
public func detectedMavenPaths() -> [String: String] {
let paths = (deploymentEnvironment()["PATH"] ?? "").split(separator: ":").map(String.init)
var detected: [String: String] = [:]
for name in ["mvn", "mvnd"] {
detected[name] = paths.lazy.map { ($0 as NSString).appendingPathComponent(name) }
.first(where: Self.isExecutable)
}
return detected
}
func mavenOverrides() throws -> [String: String] {
var overrides: [String: String] = [:]
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
guard path.hasPrefix("/"), Self.isExecutable(path) else {
throw ReleaseError("\(name) 路径不可执行,请在项目设置中选择对应的可执行文件。")
}
overrides[name] = path
}
return overrides
}
private static func isExecutable(_ path: String) -> Bool {
var isDirectory: ObjCBool = false
let files = FileManager.default
return files.fileExists(atPath: path, isDirectory: &isDirectory)
&& !isDirectory.boolValue && files.isExecutableFile(atPath: path)
}
private func file(_ path: String) -> URL {
path.hasPrefix("/") ? URL(fileURLWithPath: path) : root.appending(path: path)
}
private static func isYAML(_ fileExtension: String) -> Bool {
["yaml", "yml"].contains(fileExtension.lowercased())
}
private static func isFile(_ url: URL) -> Bool {
(try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true
}
private static func isModuleName(_ value: String) -> Bool {
value.wholeMatch(of: /[A-Za-z0-9][A-Za-z0-9._-]*/) != nil
}
private static func isTarget(_ value: String) -> Bool {
value.wholeMatch(of: /[A-Za-z0-9_][A-Za-z0-9_.@:-]*/) != nil
}
}
public struct ReleaseError: LocalizedError, Sendable {
public let message: String
public init(_ message: String) { self.message = message }
public var errorDescription: String? { message }
}
import Foundation
public enum ReleaseAction: String, Codable, Sendable {
case standard, verified, preflight
}
public enum ReleasePhase: String, Codable, Sendable {
case pulling, inventory, building, image, deploying, verifying, preflight, script
public var title: String {
switch self {
case .pulling: "正在拉取代码"
case .inventory: "正在核对服务器"
case .building: "正在打包"
case .image: "正在构建镜像"
case .deploying: "正在部署"
case .verifying: "正在验证镜像与容器"
case .preflight: "正在检查发布配置"
case .script: "正在运行发布脚本"
}
}
public var estimatedPercentage: Int {
switch self {
case .pulling: 10
case .inventory: 20
case .building: 35
case .image: 65
case .deploying: 85
case .verifying: 95
case .preflight: 20
case .script: 50
}
}
}
public enum ReleaseStatus: String, Codable, Sendable {
case succeeded, failed, cleanupFailed, cancelled
public var title: String {
switch self {
case .succeeded: "发布成功"
case .failed: "发布失败"
case .cleanupFailed: "部署完成,收尾失败"
case .cancelled: "发布已停止"
}
}
}
public struct ReleaseResult: Codable, Sendable {
public let project: String
public let module: String
public let target: String
public let configName: String?
public let configFile: String?
public let errorLine: Int?
public let errorText: String?
public let finishedAt: Date
public let duration: Int
public let status: ReleaseStatus
public let phase: ReleasePhase
public let message: String?
public let logName: String
public let action: ReleaseAction?
public let auditDirectory: String?
public var headline: String {
guard action == .preflight else { return status.title }
return switch status {
case .succeeded: "预检通过"
case .cancelled: "预检已停止"
default: "预检未通过"
}
}
}
public enum ReleaseEvent: Sendable {
case phase(ReleasePhase)
case finished(ReleaseResult)
}
public struct ReleaseRunner: Sendable {
public let storage: URL
public init(storage: URL) { self.storage = storage }
public func start(project: ReleaseProject, modules: [String], profile: DeployProfile? = nil, server: String? = nil,
useVPC: Bool = false, action: ReleaseAction = .standard, control: ReleaseControl = ReleaseControl()) -> AsyncStream<ReleaseEvent> {
let (stream, events) = AsyncStream.makeStream(of: ReleaseEvent.self)
Task.detached {
let result = execute(project: project, modules: modules, profile: profile, server: server,
useVPC: useVPC, action: action, control: control) {
events.yield(.phase($0))
}
events.yield(.finished(result))
events.finish()
}
return stream
}
private func execute(
project: ReleaseProject, modules: [String], profile: DeployProfile?, server: String?,
useVPC: Bool, action: ReleaseAction, control: ReleaseControl, report: (ReleasePhase) -> Void
) -> ReleaseResult {
let clock = ContinuousClock()
let started = clock.now
let name = UUID().uuidString + ".log"
var phase: ReleasePhase = action == .preflight ? .preflight : .pulling
var deploymentCompleted = false
var auditDirectory: String?
var log: FileHandle?
var mavenBin: URL?
var scanner = LogScanner()
let moduleLabel = modules.joined(separator: ", ")
func write(_ bytes: Data) throws {
control.append(bytes)
try log?.write(contentsOf: bytes)
scanner.scan(bytes) { line in
if action == .verified, line.hasPrefix("发布记录:") {
auditDirectory = String(line.dropFirst("发布记录:".count)).trimmingCharacters(in: .whitespaces)
}
guard project.type == .cityKeeper, phase != .pulling, phase != .inventory,
phase != .preflight else { return }
if phase == .building && (line.hasPrefix("Transferring ")
|| line.hasPrefix("Building ") || line.contains("## Enumerate Images ##")) {
phase = .image
report(phase)
}
if phase != .deploying && line.contains("## deploy ##") {
phase = .deploying
report(phase)
}
if phase == .deploying, line.contains("TASK [CITYKEEPER_RELEASE_VERIFY]") {
phase = .verifying
report(phase)
}
if line.contains("========== 部署完成 ==========") { deploymentCompleted = true }
}
}
func logLine(_ message: String) throws {
let separator = scanner.endsWithNewline ? "" : "\n"
try write(Data((separator + "[\(Self.displayTime(Date(), full: false))] " + message + "\n").utf8))
}
func result(_ status: ReleaseStatus, message: String? = nil) -> ReleaseResult {
ReleaseResult(
project: project.name, module: moduleLabel, target: server ?? "",
configName: profile?.title, configFile: profile?.file,
errorLine: status == .failed || status == .cleanupFailed ? scanner.errorLine : nil,
errorText: status == .failed || status == .cleanupFailed ? scanner.errorText : nil,
finishedAt: Date(), duration: Int(started.duration(to: clock.now).components.seconds),
status: status, phase: phase, message: message, logName: name,
action: action, auditDirectory: auditDirectory
)
}
defer {
try? log?.close()
if let mavenBin { try? FileManager.default.removeItem(at: mavenBin) }
}
do {
try FileManager.default.createDirectory(
at: storage, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]
)
let url = storage.appending(path: name)
guard FileManager.default.createFile(atPath: url.path, contents: nil, attributes: [.posixPermissions: 0o600]) else {
throw ReleaseError("无法创建发布日志。")
}
log = try FileHandle(forWritingTo: url)
try logLine("项目 \(project.name) / \(moduleLabel)")
if let profile { try logLine("发布配置 \(profile.title) / \(profile.file)") }
_ = try project.commands(for: modules, profile: profile, server: server, useVPC: useVPC, action: action)
let overrides = try project.mavenOverrides()
let environment = project.deploymentEnvironment()
if action == .preflight {
report(.preflight)
} else {
report(.pulling)
try logLine("$ git pull --ff-only")
let git = try control.run("/usr/bin/git", ["pull", "--ff-only"], in: project.root, environment: environment, receive: write)
guard git == 0 else { throw ReleaseError("git pull 退出码 \(git),发布已停止。") }
if project.type == .cityKeeper, let server {
phase = .inventory
report(phase)
let targets = try project.inventoryTargets(control: control)
guard ReleaseProject.containsInventoryTarget(server, in: targets) else {
throw ReleaseError("所选服务器已不在 hosts 清单中,发布已停止。")
}
}
}
let commands = try project.commands(for: modules, profile: profile, server: server, useVPC: useVPC, action: action)
var scriptEnvironment = environment
if !overrides.isEmpty {
let bin = FileManager.default.temporaryDirectory.appending(path: "java-release-maven-" + UUID().uuidString)
try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: false,
attributes: [.posixPermissions: 0o700])
mavenBin = bin
for (name, path) in overrides.sorted(by: { $0.key < $1.key }) {
let launcher = bin.appending(path: name)
// Invoke the selected executable at its original path so it can locate its installation.
let quotedPath = "'" + path.replacingOccurrences(of: "'", with: "'\\''") + "'"
try "#!/bin/sh\nexec \(quotedPath) \"$@\"\n".write(to: launcher, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: launcher.path)
try logLine("Maven \(name):\(path)")
}
scriptEnvironment["PATH"] = bin.path + ":" + (environment["PATH"] ?? "")
}
if action != .preflight {
phase = project.type == .cityKeeper ? .building : .script
report(phase)
}
for arguments in commands {
let command = project.type == .cityKeeper ? ["./build-and-deploy"] + arguments.dropFirst() : ["bash"] + arguments
try logLine("$ " + command.joined(separator: " "))
let code = try control.run("/bin/bash", arguments, in: project.root, environment: scriptEnvironment, receive: write)
if !scanner.endsWithNewline { try write(Data([10])) }
if code != 0 {
let prefix = commands.count > 1 ? "模块 \(arguments[1]):" : ""
throw ReleaseError("\(prefix)发布脚本退出码 \(code),请查看日志。")
}
}
if control.isCancelled { throw CancellationError() }
try logLine(action == .preflight ? "预检通过" : "发布成功")
return result(.succeeded)
} catch where control.isCancelled {
try? logLine("发布已停止。已启动的远端任务可能仍在运行。")
return result(.cancelled)
} catch {
let message = error.localizedDescription
if !scanner.endsWithNewline { try? write(Data([10])) }
if scanner.errorLine == nil { scanner.mark(message) }
try? logLine("失败:\(message)")
return result(deploymentCompleted ? .cleanupFailed : .failed, message: message)
}
}
public static func displayTime(_ date: Date, full: Bool = true) -> String {
let format = DateFormatter()
format.locale = Locale(identifier: "en_US_POSIX")
format.timeZone = TimeZone(identifier: "Asia/Shanghai")
format.dateFormat = full ? "yyyy-MM-dd HH:mm:ss" : "HH:mm:ss"
return format.string(from: date)
}
}
private struct LogScanner {
private var buffer = Data()
private var nextLine = 0
private var lineWasTruncated = false
private let ansi = /\u{1B}\[[0-9;]*[A-Za-z]/
private(set) var errorLine: Int?
private(set) var errorText: String?
var endsWithNewline: Bool { buffer.isEmpty && !lineWasTruncated }
mutating func scan(_ bytes: Data, inspect: (String) -> Void) {
buffer.append(bytes)
let maximumLineLength = 64 * 1024
var start = buffer.startIndex
while let end = buffer[start...].firstIndex(of: 10) {
let raw = String(decoding: buffer[start..<end].prefix(maximumLineLength), as: UTF8.self)
let line = raw.replacing(ansi, with: "")
inspect(line)
let lower = line.lowercased().trimmingCharacters(in: .whitespaces)
if lower.hasPrefix("[error]") || lower.hasPrefix("error:") || lower.hasPrefix("error!") || lower.hasPrefix("fatal:")
|| lower.contains("compilation error")
|| lower.contains("permission denied") || lower.contains("command not found") {
if errorLine == nil { mark(line) }
}
nextLine += 1
lineWasTruncated = false
start = buffer.index(after: end)
}
buffer.removeSubrange(..<start)
if buffer.count > maximumLineLength {
buffer = Data(buffer.prefix(maximumLineLength))
lineWasTruncated = true
}
}
mutating func mark(_ line: String) {
errorLine = nextLine
errorText = String(line.prefix(350))
}
}
import Foundation
@testable import ReleaseCore
import XCTest
final class ReleaseRunnerTests: XCTestCase {
func testPullUpdatesCodeBeforeStartingScript() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.advanceOrigin()
let (result, phases) = try await fixture.release()
XCTAssertEqual(phases, [.pulling, .script])
XCTAssertEqual(result.status, .succeeded)
XCTAssertEqual(result.module, "gateway")
XCTAssertEqual(try String(contentsOf: fixture.local.appending(path: "script-ran"), encoding: .utf8), "updated")
let log = try fixture.readLog(result)
XCTAssertTrue(log.contains("$ git pull --ff-only"))
XCTAssertTrue(log.contains("fixture script ran for gateway"))
}
func testDivergentPullDoesNotStartScript() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.advanceOrigin()
try fixture.commit(in: fixture.local, file: "local-only", content: "local change")
let (result, phases) = try await fixture.release()
XCTAssertEqual(phases, [.pulling])
XCTAssertEqual(result.status, .failed)
XCTAssertEqual(result.phase, .pulling)
XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.local.appending(path: "script-ran").path))
XCTAssertTrue(try fixture.readLog(result).contains("git pull 退出码"))
}
func testNonzeroScriptExitIsReportedWithStderr() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
try "printf '\\033[31m[ERROR] fixture failure\\033[0m' >&2\nexit 7\n".write(
to: fixture.local.appending(path: "release.sh"), atomically: true, encoding: .utf8
)
let (result, phases) = try await fixture.release()
XCTAssertEqual(phases, [.pulling, .script])
XCTAssertEqual(result.status, .failed)
XCTAssertEqual(result.phase, .script)
XCTAssertTrue(try fixture.readLog(result).contains("fixture failure"))
XCTAssertTrue(result.message?.contains("7") == true)
XCTAssertEqual(result.errorText, "[ERROR] fixture failure")
let lines = try fixture.readLog(result).components(separatedBy: "\n")
let errorLine = try XCTUnwrap(result.errorLine)
XCTAssertTrue(lines[errorLine].contains("fixture failure"))
}
func testCityKeeperModuleMappingAndCleanupStatus() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.createCityKeeperFixture()
var project = fixture.project
project.type = .cityKeeper
var profile = try JSONDecoder().decode(DeployProfile.self, from: Data(#"{"id":"DD7E62C6-C2B8-4F1A-9E90-EBEF1FBA32D1","alias":"","file":"deploy.yaml","sshTarget":"","vpc":true}"#.utf8))
profile.alias = "测试环境"
profile.sshTarget = "fixture-ssh"
project.profiles = [profile]
project.inventoryPath = "hosts"
project.toolPath = fixture.local.appending(path: "bin").path
XCTAssertEqual(try project.availableYAMLFiles(), ["deploy.yaml", "deploy_test.yml"])
XCTAssertEqual(try project.configurationFiles(), ["deploy.yaml", "deploy_test.yml"])
let targets = try project.inventoryTargets()
XCTAssertEqual(targets.map(\.displayName), ["PHY1(local-fixture)"])
XCTAssertTrue(ReleaseProject.containsInventoryTarget("local-fixture", in: targets))
XCTAssertEqual(try project.modules(), ["gateway", "meter-cloud"])
let modules = ["gateway", "meter-cloud"]
let commands = try project.commands(for: modules, profile: profile, server: "PHY1")
XCTAssertEqual(commands.map { Array($0.dropFirst()) },
[["-f", "--ds", "PHY1", "--config", "deploy.yaml", "--ss", "fixture-ssh"] + modules])
let vpcCommands = try project.commands(for: modules, profile: profile, server: "PHY1", useVPC: true)
XCTAssertEqual(vpcCommands.map { Array($0.dropFirst()) },
[["-f", "--vpc", "--ds", "PHY1", "--config", "deploy.yaml", "--ss", "fixture-ssh"] + modules])
XCTAssertThrowsError(try project.commands(for: ["gateway", "monitor"], profile: profile, server: "PHY1"))
let (result, phases) = try await fixture.release(project: project, modules: modules, profile: profile, server: "PHY1")
XCTAssertEqual(phases, [.pulling, .inventory, .building, .image, .deploying])
XCTAssertEqual(result.status, .cleanupFailed)
XCTAssertEqual(result.configName, "测试环境")
XCTAssertEqual(result.configFile, "deploy.yaml")
XCTAssertEqual(result.target, "PHY1")
XCTAssertEqual(result.module, "gateway, meter-cloud")
let log = try fixture.readLog(result)
XCTAssertEqual(log.components(separatedBy: "inventory passed").count, 2)
XCTAssertTrue(log.contains("script argument: gateway\nscript argument: meter-cloud"))
XCTAssertFalse(log.contains("script argument: --vpc"))
let (blocked, blockedPhases) = try await fixture.release(project: project, profile: profile, server: "removed-node")
XCTAssertEqual(blockedPhases, [.pulling, .inventory])
XCTAssertEqual(blocked.status, .failed)
XCTAssertTrue(blocked.message?.contains("hosts") == true)
XCTAssertFalse(try fixture.readLog(blocked).contains("inventory passed"))
}
func testVerifiedPreflightDoesNotPullOrPublish() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.createCityKeeperFixture()
var project = fixture.project
project.type = .cityKeeper
var profile = DeployProfile()
profile.file = "deploy_hq.yaml"
project.profiles = [profile]
let modules = ["gateway"]
for file in ["deploy_hq.yaml", "release-manifest.py", "release-verify.yml"] {
try "".write(to: fixture.local.appending(path: file), atomically: true, encoding: .utf8)
}
try """
if [[ "$1 $2" != "--verified --preflight" ]]; then exit 7; fi
printf 'fixture configuration ready\\n'
""".write(to: fixture.local.appending(path: "build-and-deploy"), atomically: true, encoding: .utf8)
try fixture.advanceOrigin()
XCTAssertTrue(project.supportsVerifiedRelease(profile))
let events = ReleaseRunner(storage: fixture.logs).start(
project: project, modules: modules, profile: profile, server: "PHY1", action: .preflight
)
var recorded: ReleaseResult?
var phases: [ReleasePhase] = []
for await event in events {
switch event {
case .phase(let phase): phases.append(phase)
case .finished(let result): recorded = result
}
}
let result = try XCTUnwrap(recorded)
let log = try fixture.readLog(result)
XCTAssertEqual(result.headline, "预检通过")
XCTAssertEqual(phases, [.preflight])
XCTAssertTrue(log.contains("fixture configuration ready"))
XCTAssertFalse(log.contains("git pull"))
XCTAssertEqual(try String(contentsOf: fixture.local.appending(path: "version"), encoding: .utf8), "initial")
}
func testSelectionRoundTrips() throws {
let selection = ReleaseSelection(projectID: UUID(), modules: ["gateway", "meter-cloud"], profileID: UUID(), server: "test-node")
let decoded = try JSONDecoder().decode(ReleaseSelection.self, from: JSONEncoder().encode(selection))
XCTAssertEqual(decoded, selection)
let legacy = try JSONDecoder().decode(ReleaseSelection.self, from: Data(#"{"module":"gateway"}"#.utf8))
XCTAssertEqual(legacy.modules, ["gateway"])
}
func testMavenPathsAreDetectedAndOverridesReachDeploymentScript() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
var project = fixture.project
let fallback = fixture.local.appending(path: "maven-bin")
let manual = fixture.local.appending(path: "custom Maven's bin")
for directory in [fallback, manual] {
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
for name in ["mvn", "mvnd"] {
let executable = directory.appending(path: name)
try "#!/bin/sh\nprintf '%s|%s\\n' \"$0\" \"$1\"\n".write(to: executable, atomically: true, encoding: .utf8)
try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: executable.path)
}
}
project.toolPath = fallback.path
XCTAssertEqual(project.detectedMavenPaths()["mvn"], fallback.appending(path: "mvn").path)
XCTAssertEqual(project.detectedMavenPaths()["mvnd"], fallback.appending(path: "mvnd").path)
let legacy = try JSONDecoder().decode(ReleaseProject.self, from: JSONEncoder().encode(project))
XCTAssertNil(legacy.mavenPath)
XCTAssertNil(legacy.mvndPath)
project.mavenPath = manual.appending(path: "mvn").path
project.mvndPath = manual.appending(path: "mvnd").path
XCTAssertEqual(try JSONDecoder().decode(ReleaseProject.self, from: JSONEncoder().encode(project)), project)
try """
set -eu
mvn 'clean package'
mvnd 'verify package'
""".write(to: fixture.local.appending(path: "release.sh"), atomically: true, encoding: .utf8)
let (result, _) = try await fixture.release(project: project)
XCTAssertEqual(result.status, .succeeded)
let log = try fixture.readLog(result)
XCTAssertTrue(log.contains("\(try XCTUnwrap(project.mavenPath))|clean package"))
XCTAssertTrue(log.contains("\(try XCTUnwrap(project.mvndPath))|verify package"))
project.mvndPath = manual.path
XCTAssertThrowsError(try project.validate())
let (invalid, _) = try await fixture.release(project: project)
XCTAssertEqual(invalid.status, .failed)
XCTAssertTrue(invalid.message?.contains("mvnd 路径不可执行") == true)
XCTAssertFalse(try fixture.readLog(invalid).contains("$ git pull"))
}
func testCityKeeperDiscoversModulesFromSelectedRepository() throws {
let fixture = try Fixture()
defer { fixture.remove() }
try fixture.createCityKeeperFixture()
var project = fixture.project
project.type = .cityKeeper
for path in ["ucn-cloud-gateway/pom.xml", "nested/ucn-cloud-heat-control/pom.xml",
"docker/heat-control/Dockerfile", "docker/control/Dockerfile"] {
let file = fixture.local.appending(path: path)
try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
try "".write(to: file, atomically: true, encoding: .utf8)
}
try """
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modules>
<module>ucn-cloud-gateway</module>
<module>nested/ucn-cloud-heat-control</module>
<module>ucn-cloud-monitor</module>
</modules>
</project>
""".write(to: fixture.local.appending(path: "pom.xml"), atomically: true, encoding: .utf8)
XCTAssertEqual(try project.modules(), ["gateway", "heat-control"])
XCTAssertNoThrow(try project.validate())
}
func testCustomReleaseStopsAtFailedModule() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
var project = fixture.project
project.customModules = "gateway,broken,remaining"
try """
printf 'ran %s\\n' "$1"
if [[ "$1" == broken ]]; then exit 7; fi
""".write(to: fixture.local.appending(path: "release.sh"), atomically: true, encoding: .utf8)
let (result, _) = try await fixture.release(project: project, modules: ["gateway", "broken", "remaining"])
let log = try fixture.readLog(result)
XCTAssertEqual(result.status, .failed)
XCTAssertTrue(result.message?.contains("broken") == true)
XCTAssertTrue(log.contains("ran gateway"))
XCTAssertTrue(log.contains("ran broken"))
XCTAssertFalse(log.contains("ran remaining"))
XCTAssertEqual(log.components(separatedBy: "$ git pull --ff-only").count, 2)
}
func testInventoryGraphListsNonemptyGroupsAndDeduplicatesTargets() {
let targets = ReleaseProject.parseInventoryGraph("""
@all:
|--@empty:
|--@backend:
| |--@PHY1:
| | |--node-2
| | |--node-10
|--@ungrouped:
| |--standalone
|--@node-10:
| |--node-10
""")
XCTAssertEqual(targets.map(\.displayName), ["backend(node-2、node-10)", "node-10(node-10)", "PHY1(node-2、node-10)", "standalone"])
}
func testLiveOutputPausesAndResumesScriptAndItsChild() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
let script = """
while [ ! -e continue-child ]; do sleep 0.05; done
printf 'child continued\\n' > child-ran
printf 'child finished\\n'
"""
try script.write(to: fixture.local.appending(path: "child.sh"), atomically: true, encoding: .utf8)
try """
/bin/bash ./child.sh &
child=$!
printf 'release started\\n' >&2
wait "$child"
printf 'release finished\\n'
""".write(to: fixture.local.appending(path: "release.sh"), atomically: true, encoding: .utf8)
let control = ReleaseControl()
let allowChild = fixture.local.appending(path: "continue-child")
defer {
try? "".write(to: allowChild, atomically: true, encoding: .utf8)
try? control.setPaused(false)
}
let events = ReleaseRunner(storage: fixture.logs).start(project: fixture.project, modules: ["gateway"], control: control)
for _ in 0..<100 {
if control.liveOutput().contains("release started") { break }
try await Task.sleep(for: .milliseconds(20))
}
XCTAssertTrue(control.liveOutput().contains("release started"))
try control.setPaused(true)
try "".write(to: allowChild, atomically: true, encoding: .utf8)
try await Task.sleep(for: .milliseconds(200))
XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.local.appending(path: "child-ran").path))
XCTAssertFalse(control.liveOutput().contains("release finished"))
try control.setPaused(false)
var result: ReleaseResult?
for await event in events {
if case let .finished(release) = event { result = release }
}
XCTAssertEqual(result?.status, .succeeded)
XCTAssertTrue(control.liveOutput().contains("child finished\nrelease finished"))
}
func testStoppingPausedReleasePreventsLaterModulesAndAllowsNewRelease() async throws {
let fixture = try Fixture()
defer { fixture.remove() }
var project = fixture.project
project.customModules = "gateway,remaining"
try """
printf 'started %s\\n' "$1"
if [[ "$1" == gateway ]]; then
while [ ! -e allow-gateway ]; do sleep 0.05; done
touch gateway-finished
fi
""".write(to: fixture.local.appending(path: "release.sh"), atomically: true, encoding: .utf8)
let allow = fixture.local.appending(path: "allow-gateway")
let control = ReleaseControl()
defer { try? control.cancel() }
let events = ReleaseRunner(storage: fixture.logs).start(project: project, modules: ["gateway", "remaining"], control: control)
for _ in 0..<100 {
if control.liveOutput().contains("started gateway") { break }
try await Task.sleep(for: .milliseconds(20))
}
XCTAssertTrue(control.liveOutput().contains("started gateway"))
try control.setPaused(true)
try control.cancel()
try "".write(to: allow, atomically: true, encoding: .utf8)
var result: ReleaseResult?
for await event in events {
if case let .finished(release) = event { result = release }
}
XCTAssertEqual(result?.status, .cancelled)
XCTAssertFalse(FileManager.default.fileExists(atPath: fixture.local.appending(path: "gateway-finished").path))
XCTAssertFalse(control.liveOutput().contains("started remaining"))
let (next, _) = try await fixture.release(project: project, modules: ["remaining"])
XCTAssertEqual(next.status, .succeeded)
}
}
private struct Fixture {
let base: URL
var local: URL { base.appending(path: "local") }
var upstream: URL { base.appending(path: "upstream") }
var remote: URL { base.appending(path: "remote.git") }
var logs: URL { base.appending(path: "logs") }
var project: ReleaseProject {
var project = ReleaseProject()
project.name = "Test project"
project.directory = local.path
project.type = .custom
project.script = "release.sh"
project.customModules = "gateway"
return project
}
init() throws {
base = FileManager.default.temporaryDirectory.appending(path: "java-release-test-" + UUID().uuidString)
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
do {
try git(["init", "--bare", "-b", "main", remote.path], in: base)
try git(["init", "-b", "main", upstream.path], in: base)
try commit(in: upstream, file: "version", content: "initial")
try commit(in: upstream, file: "release.sh", content: """
set -eu
cat version > script-ran
printf 'fixture script ran for %s\\n' "$1"
""")
try git(["remote", "add", "origin", remote.path], in: upstream)
try git(["push", "-u", "origin", "main"], in: upstream)
try git(["clone", remote.path, local.path], in: base)
} catch {
remove()
throw error
}
}
func createCityKeeperFixture() throws {
let script = """
[[ "$ANSIBLE_INVENTORY" -ef "$PWD/hosts" ]] || exit 9
printf 'inventory passed\\n'
printf 'script argument: %s\\n' "$@"
printf '[INFO] Building Maven reactor\\n'
printf 'Transferring fixture\\n'
printf '################## deploy ##################\\n'
printf '========== 部署完成 ==========\\n'
exit 8
"""
try script.write(to: local.appending(path: "build-and-deploy"), atomically: true, encoding: .utf8)
for path in ["hosts", "deploy.yaml", "deploy_test.yml", "docker/meter-cloud/Dockerfile", "docker/gateway/Dockerfile",
"docker/monitor/Dockerfile", "ucn-meter-cloud/pom.xml", "ucn-meter-cloud-gateway/pom.xml"] {
let file = local.appending(path: path)
try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
try "".write(to: file, atomically: true, encoding: .utf8)
}
try """
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modules>
<module>ucn-meter-cloud</module>
<module>ucn-meter-cloud-gateway</module>
</modules>
</project>
""".write(to: local.appending(path: "pom.xml"), atomically: true, encoding: .utf8)
let bin = local.appending(path: "bin")
try FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
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)
}
func advanceOrigin() throws {
try commit(in: upstream, file: "version", content: "updated")
try git(["push"], in: upstream)
}
func commit(in directory: URL, file: String, content: String) throws {
try content.write(to: directory.appending(path: file), atomically: true, encoding: .utf8)
try git(["add", "--", file], in: directory)
try git(["commit", "-m", file], in: directory)
}
func release(project: ReleaseProject? = nil, modules: [String] = ["gateway"], profile: DeployProfile? = nil, server: String? = nil)
async throws -> (ReleaseResult, [ReleasePhase]) {
var phases = [ReleasePhase]()
for await event in ReleaseRunner(storage: logs).start(project: project ?? self.project, modules: modules, profile: profile, server: server) {
switch event {
case let .phase(phase): phases.append(phase)
case let .finished(result): return (result, phases)
}
}
throw ReleaseError("fixture release never finished")
}
func readLog(_ result: ReleaseResult) throws -> String {
try String(contentsOf: logs.appending(path: result.logName), encoding: .utf8)
}
func remove() { try? FileManager.default.removeItem(at: base) }
private func git(_ args: [String], in directory: URL) throws {
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/git")
process.currentDirectoryURL = directory
process.arguments = ["-c", "user.name=Release Test", "-c", "user.email=release-test@example.invalid",
"-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false"] + args
let pipe = Pipe()
process.standardOutput = pipe
process.standardError = pipe
try process.run()
let data = try pipe.fileHandleForReading.readToEnd() ?? Data()
process.waitUntilExit()
guard process.terminationStatus == 0 else { throw ReleaseError(String(decoding: data, as: UTF8.self)) }
}
}
#!/bin/bash
set -euo pipefail
cd "$(dirname "$0")"
swift build -c release "$@"
binary_dir=$(swift build -c release --show-bin-path "$@")
app="$PWD/dist/JavaReleaseMenu.app"
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources"
install -m 755 "$binary_dir/JavaReleaseMenu" "$app/Contents/MacOS/JavaReleaseMenu"
install -m 644 Info.plist "$app/Contents/Info.plist"
install -m 644 Assets/JavaReleaseMenu.icns "$app/Contents/Resources/JavaReleaseMenu.icns"
codesign --force --sign - "$app"
printf '%s\n' "$app"
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