Commit e87c320b authored by zpc's avatar zpc

Add release templates and isolated Beta deployment workflow

Persist per-project release modes, show completed-step progress and concise or full logs, and collect deployment diagnostics. Fix Ansible module tags and ship 1.6.2 Beta 3.
parent 811abc0e
......@@ -19,9 +19,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.4.3</string>
<string>1.6.2</string>
<key>CFBundleVersion</key>
<string>13</string>
<string>18</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>LSUIElement</key>
......
......@@ -6,7 +6,7 @@ let package = Package(
platforms: [.macOS(.v14)],
products: [.executable(name: "JavaReleaseMenu", targets: ["JavaReleaseMenu"])],
targets: [
.target(name: "ReleaseCore"),
.target(name: "ReleaseCore", resources: [.copy("Resources")]),
.executableTarget(name: "JavaReleaseMenu", dependencies: ["ReleaseCore"]),
.testTarget(name: "ReleaseCoreTests", dependencies: ["ReleaseCore", "JavaReleaseMenu"])
],
......
# Java 发布
macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布时,圆环内显示当前批次的估算进度。全部成功后显示 100%,2 秒后显示总耗时,完成满 10 秒恢复空心圆环。各项目最近一次发布结果保留在各自窗口内。右键圆环可退出。
当前测试版:**1.6.2 Beta 3**。修复 Beta 遗漏所选模块的 Ansible tags,避免执行未选模块的部署任务。面板顶部可切换「普通发布 / Beta 发布」,首次默认普通发布,之后按项目保留上次选择;重新选择当前项目、切换项目、关闭窗口和重启都不会覆盖该选择。两种流程都在独立缓存副本中运行,不在业务原仓库执行拉取、编译、脚本修改或生成发布产物。
## 普通与 Beta 发布
- 普通发布:在缓存中执行原有 `build-and-deploy`、`manage` 和 Dockerfile,保留原发布顺序与部署行为。
- Beta 发布:支持现有 CityKeeper / ucn-cloud 的标准 Spring Boot 2.x Dockerfile 和启动脚本。一次 Maven 打包后,将第三方依赖、项目依赖和业务代码分层,最多两个服务并行构建并推送。任一镜像失败都不会进入部署;镜像使用独立 Beta 标签和推送成功后的 digest。复用所选 Ansible 配置,部署后核对所选镜像有运行中的容器。保留 JVM 参数、启动延迟、基础镜像与原工作目录。业务接口效果仍需按原方式验收。
- Beta 不执行原脚本中的本机重复拉取、单独 SSH 预拉取或发布后全量 prune。目标主机的镜像拉取由 Ansible 容器任务完成。Beta 暂不支持自定义脚本、特殊 Dockerfile、特殊启动脚本,以及发布配置未定义所选模块镜像变量的情况;遇到不兼容会报错停止,不会自动切换流程。
- Beta 使用自身的镜像验证流程;普通版的 HQ 验证发布及预检保留在普通模式下。
每次结果记录模式、代码版本、是否含本地修改、各阶段耗时及 Beta 镜像 digest。完成相同项目、模块、配置、服务器、VPC 和 Maven 方式的两种发布后显示上一次对比。仅对同版本、无本地修改且未暂停的成功记录计算时间差;其他情况标为仅供参考。历史保留最近 100 次,不自动执行另一种发布。
缓存会复制当前分支及本地未提交文件,在副本中执行 `git pull --ff-only`。应用为子进程设置原仓库及 Git 元数据只读规则;无法建立保护时直接失败。为兼容原脚本,实际工作目录使用不含空白的应用缓存路径。使用应用默认存储位置时,缓存位于 `~/Library/Caches/JavaReleaseMenu/Workspaces`。项目外的 hosts 可只读引用;发布脚本和发布 YAML 须位于项目内。绝对符号链接和指向项目外的符号链接不会复制到缓存。多个项目涉及 Beta 时排队执行,整个批次最多两个镜像任务;同一项目缓存另有进程锁。
开发和验证只能修改 JavaReleaseMenu 应用仓库,用户业务仓库只读;不得修改业务项目的发布脚本、Dockerfile、启动脚本、POM 或工作区文件。测试使用临时仓库和假 Docker/Ansible,不连接真实业务环境。
macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布时,圆环内显示当前批次已完成步骤的进度。全部成功后显示 100%,2 秒后显示总耗时,完成满 10 秒恢复空心圆环。各项目最近一次发布结果保留在各自窗口内。右键圆环可退出。
## 安装与配置
......@@ -12,11 +27,29 @@ macOS 菜单栏发布工具。点击圆形图标选择项目和模块。发布
发布页最多添加四个项目窗口。每个窗口分别选择项目、发布配置、服务器、Maven 方式和模块。输入模块名可以筛选列表,已勾选的模块会保留。点击「发布此项目」仅运行当前窗口,点击「一起发布」运行所有窗口,各窗口分别显示实时输出、结果和完整日志入口。最多同时执行两个互不冲突的项目,共用项目目录、部署目标或目标不明的自定义脚本会排队;批量发布遇到失败后,已开始的任务会完成,尚未开始的任务不再执行。同名镜像模块的常规批量发布会被拦截。
发布配置支持按文件名或别名搜索,服务器支持按组名或主机地址搜索。打开面板时保留已读取的服务器列表及选择;hosts 内容、路径或运行环境变化后自动重读,也可点击服务器列表旁的刷新图标重试。正式发布仍会在拉取代码后重新核对 hosts。
## 发布模板
「项目」下方的「发布模板」按项目分别保存发布配置和服务器组合,支持按模板名称、配置文件名、服务器搜索。点击右侧保存图标可命名保存;已有模板时可选择覆盖或另存。每项右侧的省略号支持重命名和删除,删除只影响模板记录。选择「不使用模板」保留当前配置和服务器。
切换模板前校验当前配置文件及 hosts 清单,通过后同时选好两项。模块、Maven、VPC 和验证开关保留当前值。手动更改发布配置或服务器后标记「已修改」,不会自动覆盖模板。模板引用发布配置,不复制 YAML 内容;修改配置别名不影响关联。模板记录及上次选择保存在本机 `release-templates.json`,应用重启后保留,重新打开项目窗口时校验后恢复上次模板。模板失效时提示原因,不会回退到其他服务器或配置。
完整发布日志和最近结果记录当次模板名称;使用手动修改的组合时附带「已修改」,同时记录实际配置文件和服务器。重命名或删除模板不会改动历史记录。
## 发布进度
进度按实际完成的发布阶段和镜像模块数计算,并显示已完成步骤与已用时。耗时增长不会推动百分比,不把步骤百分比当作时间比例。至少三次相同项目、模块、配置、服务器、Maven、VPC、强制构建设置和发布模式的成功记录后,才显示历史剩余时间范围;样本不足时不显示精确倒计时。暂停期间冻结已用时;成功结果返回后才显示 100%。
Maven 默认自动选择 `mvnd`,检测不到时改用 `mvn`。也可在每个窗口或项目设置中指定 `mvnd` 或 `mvn`。项目设置支持分别指定可执行文件路径和补充工具 PATH。点击发布后,所选项目先在当前分支执行 `git pull --ff-only`。CityKeeper 项目核对服务器,把该项目所选模块一起交给 `build-and-deploy`。自定义脚本按模块依次执行,某个模块失败时停止执行后续模块。发布默认传 `-f`,可在项目设置关闭。
## 发布日志
发布过程中,点击菜单栏图标可在各项目窗口看正在执行的命令和实时输出。每个运行中的窗口均可暂停、继续或停止本机发布进程组。独立的 Maven 守护进程和已启动的远端任务可能继续运行。
控制台默认「简洁」,展示阶段、服务结果、耗时和错误;切换「全量」可查看原始输出。两种显示方式均完整保存日志,复制按钮复制当前显示的内容。每个运行中的窗口均可暂停、继续或停止本机发布进程组。独立的 Maven 守护进程和已启动的远端任务可能继续运行。
每次发布自动生成诊断目录,结果旁的图表图标可直接打开。`release-result.json` 保存工具版本、模式、代码版本、总耗时和阶段耗时;`ansible-tasks.jsonl` 记录任务名称、主机、成功/失败和耗时,不记录任务参数及返回数据;Beta 的 `beta-summary.json` 记录命令阶段耗时、镜像传输量、缓存命中、导出和推送耗时。完整原始输出仍保存在 Logs。以后分析以这些记录为依据。
Beta 分层缓存会复用内容未变化的依赖文件,减少重复写盘,同时移除已删除的业务类,防止旧文件残留。
各窗口保存最近一次结果与日志,点击「打开完整日志」可以查看全部输出。错误会显示在对应项目窗口里。CityKeeper 脚本报告部署完成但收尾返回非零时,结果标为「部署完成,收尾失败」。
......
......@@ -7,7 +7,15 @@ struct JavaReleaseApp {
@MainActor static func main() {
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let delegate = MenuController()
var storage = URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
#if DEBUG
if let index = CommandLine.arguments.firstIndex(of: "--preview-storage"), index + 1 < CommandLine.arguments.count {
storage = URL(fileURLWithPath: CommandLine.arguments[index + 1])
} else if let path = Bundle.main.object(forInfoDictionaryKey: "JRMPreviewStorage") as? String {
storage = URL(fileURLWithPath: path)
}
#endif
let delegate = MenuController(storage: storage)
app.delegate = delegate
withExtendedLifetime(delegate) { app.run() }
}
......@@ -15,16 +23,20 @@ struct JavaReleaseApp {
@MainActor
final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
private let model = AppModel(
storage: URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
)
private lazy var split = SplitReleaseModel(
settings: model,
storage: URL.applicationSupportDirectory.appending(path: "JavaReleaseMenu", directoryHint: .isDirectory)
)
private let model: AppModel
private let split: SplitReleaseModel
init(storage: URL) {
model = AppModel(storage: storage)
split = SplitReleaseModel(settings: model, storage: storage)
super.init()
}
private var item: NSStatusItem?
private let popover = NSPopover()
private var settings: NSWindow?
#if DEBUG
private var previewWindow: NSWindow?
#endif
func applicationDidFinishLaunching(_ notification: Notification) {
let menu = NSMenu()
......@@ -51,7 +63,27 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
))
split.statusChanged = { [weak self] in self?.updateIndicator() }
updateIndicator()
#if DEBUG
if Bundle.main.object(forInfoDictionaryKey: "JRMPreviewStorage") != nil {
appPreview()
}
#endif
}
#if DEBUG
private func appPreview() {
NSApp.setActivationPolicy(.regular)
let window = NSWindow(contentViewController: NSHostingController(rootView: SplitReleasePanel(
model: split, settings: { [weak self] in self?.openSettings() },
quit: { NSApp.terminate(nil) })))
window.title = "隔离发布体验测试"
window.isReleasedWhenClosed = false
window.center()
window.makeKeyAndOrderFront(nil)
previewWindow = window
NSApp.activate(ignoringOtherApps: true)
}
#endif
@objc private func toggle() {
guard let button = item?.button else { return }
......@@ -121,7 +153,9 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
let duration = split.completionDuration
let percentage = result == .succeeded ? 100 : split.progressPercentage
let label = split.current?.phase?.title ?? result?.title ?? "Java 发布"
let value = duration.map { "耗时 \($0) 秒" } ?? percentage.map { $0 == 100 ? "100%" : "预计进度 \($0)%" }
let value = duration.map { "耗时 \($0) 秒" } ?? percentage.map {
$0 == 100 ? "100%" : "步骤进度 \($0)% · \(split.countdown)"
}
item?.button?.toolTip = [label, value].compactMap { $0 }.joined(separator: " · ")
item?.button?.setAccessibilityLabel(label)
item?.button?.setAccessibilityValue(value)
......
......@@ -7,6 +7,7 @@ struct LogTextView: NSViewRepresentable {
let jumpRequest: Int
var followsOutput = false
var fontSize: CGFloat = 11
var label = "完整发布日志"
final class Coordinator {
var text: String?
......@@ -27,13 +28,14 @@ struct LogTextView: NSViewRepresentable {
editor.drawsBackground = false
editor.usesFindBar = true
editor.textContainerInset = NSSize(width: 10, height: 9)
editor.setAccessibilityLabel("完整发布日志")
editor.setAccessibilityLabel(label)
}
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let editor = scroll.documentView as? NSTextView else { return }
editor.setAccessibilityLabel(label)
let coordinator = context.coordinator
if coordinator.text != text {
let visible = scroll.contentView.bounds
......
import Observation
import SwiftUI
@MainActor
@Observable
final class ReleaseTemplateEditorSession: Identifiable {
enum Mode { case create, overwrite, rename }
let id = UUID()
let mode: Mode
let template: ReleaseTemplate?
var name: String
var error: String?
private(set) var isClosed = false
init(mode: Mode, template: ReleaseTemplate? = nil) {
self.mode = mode
self.template = template
name = mode == .create ? "" : template?.name ?? ""
}
var title: String {
switch mode {
case .create: "保存新模板"
case .overwrite: "覆盖当前模板"
case .rename: "重命名模板"
}
}
func cancel() { isClosed = true }
func save(using persist: (String) -> String?) -> Bool {
guard !isClosed else { return false }
error = persist(name)
if error == nil { isClosed = true }
return error == nil
}
}
struct ReleaseTemplateEditor: View {
@Bindable var session: ReleaseTemplateEditorSession
let summary: String
let cancel: () -> Void
let persist: (String) -> String?
@FocusState private var focused: Bool
var body: some View {
VStack(alignment: .leading, spacing: 9) {
Text(session.title).font(.system(size: 12, weight: .semibold))
Text("模板名称").foregroundStyle(ReleaseColors.muted)
TextField("输入模板名称", text: $session.name)
.textFieldStyle(.roundedBorder).focused($focused)
.accessibilityIdentifier("template-editor-name")
.onAppear { focused = true }
Text(summary).foregroundStyle(ReleaseColors.muted)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
if let error = session.error {
Text(error).foregroundStyle(ReleaseColors.danger)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
}
HStack {
Spacer()
Button("取消") { session.cancel(); cancel() }
.buttonStyle(ReleaseButtonStyle()).keyboardShortcut(.cancelAction)
.accessibilityIdentifier("template-editor-cancel")
Button {
if session.save(using: persist) { cancel() }
} label: {
Text(session.mode == .rename ? "保存名称" : "保存模板")
.foregroundStyle(.white).padding(.horizontal, 12).frame(height: 28)
}
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.action, prominent: true))
.keyboardShortcut(.defaultAction).accessibilityIdentifier("template-editor-save")
}
}
.font(.system(size: 11)).padding(10)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
.environment(\.colorScheme, .dark)
}
}
import Foundation
import ReleaseCore
struct ReleaseTemplate: Codable, Identifiable, Equatable {
var id = UUID()
var projectID: UUID
var name: String
var profileID: UUID
var server: String
}
struct ReleaseTemplateLibrary: Codable {
var templates: [ReleaseTemplate] = []
var selections: [UUID: UUID] = [:]
}
extension SplitReleaseModel {
func loadTemplates() {
let url = storage.appending(path: "release-templates.json")
guard FileManager.default.fileExists(atPath: url.path) else { return }
do {
templateLibrary = try JSONDecoder().decode(ReleaseTemplateLibrary.self, from: Data(contentsOf: url))
} catch {
templateLoadError = "读取发布模板失败,原文件已保留:\(error.localizedDescription)"
self.error = templateLoadError
}
}
private func persistTemplates(_ updated: ReleaseTemplateLibrary) throws {
if let templateLoadError { throw ReleaseError(templateLoadError) }
try FileManager.default.createDirectory(at: storage, withIntermediateDirectories: true)
try JSONEncoder().encode(updated).write(
to: storage.appending(path: "release-templates.json"), options: .atomic)
templateLibrary = updated
}
func templates(for pane: ReleasePaneState) -> [ReleaseTemplate] {
templateLibrary.templates.filter { $0.projectID == pane.projectID }
.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
}
func selectedTemplate(for pane: ReleasePaneState) -> ReleaseTemplate? {
templates(for: pane).first { $0.id == pane.templateID }
}
func templateIsModified(for pane: ReleasePaneState) -> Bool {
guard let template = selectedTemplate(for: pane) else { return false }
return template.profileID != pane.profileID || template.server != pane.server
}
func templateProblem(_ template: ReleaseTemplate, for pane: ReleasePaneState) -> String? {
guard template.projectID == pane.projectID, let project = project(for: pane),
project.type == .cityKeeper else { return "模板不属于当前项目" }
guard let profile = project.profiles.first(where: { $0.id == template.profileID }) else {
return "发布配置已移除"
}
do { try project.validate(profile) }
catch { return "发布配置已失效:\(error.localizedDescription)" }
if pane.loadingServers { return "正在校验服务器清单…" }
if pane.inventoryError != nil { return "服务器清单读取失败,请刷新后重试" }
guard ReleaseProject.containsInventoryTarget(template.server, in: pane.servers) else {
return "服务器 \(template.server) 已不在 hosts 清单中"
}
return nil
}
func templateCombinationProblem(for pane: ReleasePaneState) -> String? {
guard let profileID = pane.profileID, let server = pane.server else {
return "请先选好发布配置和服务器"
}
return templateProblem(ReleaseTemplate(projectID: pane.projectID, name: "",
profileID: profileID, server: server), for: pane)
}
private func requireTemplateEditing(_ pane: ReleasePaneState) throws {
guard !isRunning, panes.contains(where: { $0 === pane }),
project(for: pane)?.type == .cityKeeper else {
throw ReleaseError("项目窗口已关闭或正在发布,暂时无法修改模板。")
}
}
private func templateName(_ value: String, projectID: UUID, excluding id: UUID?) throws -> String {
let name = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, name.count <= 60,
name.rangeOfCharacter(from: .controlCharacters) == nil else {
throw ReleaseError("请输入 1–60 字的模板名称,不可包含换行。")
}
guard !templateLibrary.templates.contains(where: {
$0.projectID == projectID && $0.id != id
&& $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame
}) else { throw ReleaseError("当前项目已有同名模板,请换个名称或覆盖原模板。") }
return name
}
func applyTemplate(_ template: ReleaseTemplate, to pane: ReleasePaneState) throws {
try requireTemplateEditing(pane)
guard templates(for: pane).contains(template) else { throw ReleaseError("模板已变更,请重新选择。") }
if let problem = templateProblem(template, for: pane) { throw ReleaseError(problem) }
var updated = templateLibrary
updated.selections[pane.projectID] = template.id
try persistTemplates(updated)
// Commit both fields only after the full combination has passed validation.
pane.profileID = template.profileID
pane.server = template.server
pane.templateID = template.id
pane.pendingTemplateID = nil
pane.error = nil
save()
}
func clearTemplate(for pane: ReleasePaneState) throws {
try requireTemplateEditing(pane)
var updated = templateLibrary
updated.selections.removeValue(forKey: pane.projectID)
try persistTemplates(updated)
pane.templateID = nil
pane.pendingTemplateID = nil
pane.error = nil
save()
}
func restorePendingTemplate(for pane: ReleasePaneState) {
guard !pane.loadingServers, let id = pane.pendingTemplateID else { return }
pane.pendingTemplateID = nil
guard let template = templates(for: pane).first(where: { $0.id == id }) else { return }
do { try applyTemplate(template, to: pane) }
catch {
// Do not fall back to an unrelated default combination when restoration fails.
pane.templateID = id
pane.profileID = nil
pane.server = nil
pane.error = "模板「\(template.name)」无法恢复:\(error.localizedDescription)"
}
}
func saveTemplate(name: String, for pane: ReleasePaneState, replacing id: UUID? = nil) throws {
try requireTemplateEditing(pane)
if let problem = templateCombinationProblem(for: pane) { throw ReleaseError(problem) }
guard let profileID = pane.profileID, let server = pane.server else {
throw ReleaseError("请先选好发布配置和服务器。")
}
let name = try templateName(name, projectID: pane.projectID, excluding: id)
var updated = templateLibrary
let template = ReleaseTemplate(id: id ?? UUID(), projectID: pane.projectID,
name: name, profileID: profileID, server: server)
if let id {
guard let index = updated.templates.firstIndex(where: { $0.id == id && $0.projectID == pane.projectID }) else {
throw ReleaseError("原模板已被删除,请另存为新模板。")
}
updated.templates[index] = template
} else { updated.templates.append(template) }
updated.selections[pane.projectID] = template.id
try persistTemplates(updated)
pane.templateID = template.id
pane.error = nil
save()
}
func renameTemplate(_ template: ReleaseTemplate, name: String, for pane: ReleasePaneState) throws {
try requireTemplateEditing(pane)
let name = try templateName(name, projectID: pane.projectID, excluding: template.id)
var updated = templateLibrary
guard let index = updated.templates.firstIndex(where: { $0.id == template.id && $0.projectID == pane.projectID }) else {
throw ReleaseError("模板已被删除。")
}
updated.templates[index].name = name
try persistTemplates(updated)
pane.error = nil
}
func deleteTemplate(_ template: ReleaseTemplate, for pane: ReleasePaneState) throws {
try requireTemplateEditing(pane)
guard template.projectID == pane.projectID else { throw ReleaseError("模板不属于当前项目。") }
var updated = templateLibrary
updated.templates.removeAll { $0.id == template.id && $0.projectID == pane.projectID }
updated.selections = updated.selections.filter { $0.value != template.id }
try persistTemplates(updated)
for current in panes where current.templateID == template.id {
current.templateID = nil
current.pendingTemplateID = nil
}
pane.error = nil
save()
}
}
import Foundation
enum BetaRelease {
static func resource(_ name: String) throws -> URL {
let bundled = Bundle.main.resourceURL?.appending(path: "JavaReleaseMenu_ReleaseCore.bundle")
let bundle = bundled.flatMap(Bundle.init(url:)) ?? Bundle.module
guard let url = bundle.url(forResource: name, withExtension: "py", subdirectory: "Resources") else {
throw ReleaseError("缺少发布运行文件,请重新安装应用。")
}
return url
}
static func diagnostics(root: URL, runID: String, environment: inout [String: String]) throws -> URL {
let directory = root.deletingLastPathComponent().appending(path: "diagnostics/" + runID)
let plugins = root.deletingLastPathComponent().appending(path: "callbacks")
for folder in [directory, plugins] {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
}
try Data(contentsOf: resource("jrm_timing")).write(to: plugins.appending(path: "jrm_timing.py"), options: .atomic)
environment["ANSIBLE_CALLBACK_PLUGINS"] = plugins.path + ":" + (environment["ANSIBLE_CALLBACK_PLUGINS"] ?? "")
let existing = (environment["ANSIBLE_CALLBACKS_ENABLED"] ?? "").split(separator: ",").map(String.init)
environment["ANSIBLE_CALLBACKS_ENABLED"] = Array(Set(existing + ["jrm_timing"])).sorted().joined(separator: ",")
environment["JRM_DIAGNOSTICS_DIR"] = directory.path
return directory
}
static func arguments(project: ReleaseProject, modules: [String], profile: DeployProfile?,
server: String?, useVPC: Bool) throws -> [String] {
guard project.type == .cityKeeper, let profile, let server else {
throw ReleaseError("Beta 仅支持 CityKeeper 项目,请先选好配置和服务器。")
}
let script = try resource("beta-release")
let generated = project.root.deletingLastPathComponent().appending(path: "beta-generated")
try FileManager.default.createDirectory(at: generated, withIntermediateDirectories: true,
attributes: [.posixPermissions: 0o700])
let executable = generated.appending(path: "beta-release.py")
try Data(contentsOf: script).write(to: executable, options: .atomic)
let maven = try project.mavenOverrides()["mvn"] ?? "mvn"
let config = profile.file.hasPrefix("/") ? profile.file : project.root.appending(path: profile.file).path
let options: [String: Any] = ["root": project.root.path, "modules": modules,
"server": server, "config": config, "vpc": useVPC, "maven": maven]
let file = generated.appending(path: "options.json")
try JSONSerialization.data(withJSONObject: options).write(to: file, options: .atomic)
return ["python3", executable.path, file.path]
}
}
......@@ -5,8 +5,12 @@ public final class ReleaseControl: Sendable {
private struct State {
var process: pid_t?
var paused = false
var wasPaused = false
var cancelled = false
var output = Data()
var protectedPaths: [String] = []
var summary: [String] = []
var completedImages = 0
}
private let condition = NSCondition()
......@@ -14,6 +18,18 @@ public final class ReleaseControl: Sendable {
public init() {}
func protectSource(_ paths: [String]) {
// Foundation preserves /var and /tmp aliases; Seatbelt rules need the physical pathname.
let canonical = paths.compactMap { path -> String? in
guard let resolved = realpath(path, nil) else { return nil }
defer { free(resolved) }
return String(cString: resolved)
}
condition.lock()
state.protectedPaths = Array(Set(state.protectedPaths + paths + canonical))
condition.unlock()
}
public func setPaused(_ paused: Bool) throws {
condition.lock()
defer { condition.unlock() }
......@@ -23,6 +39,7 @@ public final class ReleaseControl: Sendable {
throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
}
state.paused = paused
if paused { state.wasPaused = true }
if !paused { condition.broadcast() }
}
......@@ -43,6 +60,12 @@ public final class ReleaseControl: Sendable {
return state.cancelled
}
var wasPaused: Bool {
condition.lock()
defer { condition.unlock() }
return state.wasPaused
}
public func liveOutput() -> String {
condition.lock()
let bytes = state.output
......@@ -53,6 +76,27 @@ public final class ReleaseControl: Sendable {
.replacingOccurrences(of: "\r", with: "\n")
}
public func summaryOutput() -> String {
condition.lock()
defer { condition.unlock() }
return state.summary.joined(separator: "\n")
}
func summarize(_ line: String) {
condition.lock()
defer { condition.unlock() }
if state.summary.last != line { state.summary.append(line) }
if state.summary.count > 500 { state.summary.removeFirst() }
}
func completedImageCount(_ count: Int) {
condition.lock(); state.completedImages = count; condition.unlock()
}
public var imageCount: Int {
condition.lock(); defer { condition.unlock() }; return state.completedImages
}
func append(_ bytes: Data) {
condition.lock()
defer { condition.unlock() }
......@@ -65,6 +109,20 @@ public final class ReleaseControl: Sendable {
_ executable: String, _ arguments: [String], in directory: URL,
environment: [String: String], receive: (Data) throws -> Void
) throws -> Int32 {
condition.lock()
let protectedPaths = state.protectedPaths
condition.unlock()
var executable = executable
var arguments = arguments
if !protectedPaths.isEmpty {
let rules = protectedPaths.map { path in
let escaped = path.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "\"", with: "\\\"")
return "(deny file-write* (subpath \"\(escaped)\"))"
}.joined(separator: " ")
arguments = ["-p", "(version 1) (allow default) " + rules, executable] + arguments
executable = "/usr/bin/sandbox-exec"
}
let pipe = Pipe()
let reader = pipe.fileHandleForReading
let writer = pipe.fileHandleForWriting
......
import Foundation
public enum ReleaseLogSummary {
public static func line(_ input: String) -> String? {
let text = input.replacing(/\u{1B}\[[0-9;]*[A-Za-z]/, with: "")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return nil }
if let range = text.range(of: "[发布计时] "),
let bytes = String(text[range.upperBound...]).data(using: .utf8),
let record = try? JSONSerialization.jsonObject(with: bytes) as? [String: Any],
let task = record["task"] as? String, let seconds = record["seconds"] as? Double {
let status = record["status"] as? String ?? "ok"
let suffix = status == "ok" ? "" : " · \(status)"
return "部署任务:\(task) · \(String(format: "%.1f", seconds)) 秒\(suffix)"
}
if text.contains("[ERROR]") || text.contains("fatal:") || text.contains("FAILED!")
|| text.contains("失败:") || text.contains("发布已停止") {
return String(text.prefix(700))
}
if text.contains("构建和推送耗时") || text.contains("分层准备完成") {
return text
}
if text.contains("阶段用时"), ["[compile]", "[deploy]", "[verify]", "[preflight]"].contains(where: text.hasPrefix) { return text }
if text.wholeMatch(of: /\[\d\d:\d\d:\d\d\].*/) != nil {
let allowed = ["发布模式:", "工具版本:", "项目 ", "发布配置 ", "发布服务器 ", "发布模板 ", "代码版本:", "发布成功", "Beta 发布成功", "预检通过"]
if allowed.contains(where: text.contains) { return text }
}
return nil
}
public static func compact(_ text: String) -> String {
text.components(separatedBy: .newlines).compactMap(line).joined(separator: "\n")
}
}
import Foundation
public enum ReleaseMode: String, Codable, CaseIterable, Identifiable, Sendable {
case normal, beta
public var id: Self { self }
public var title: String { self == .beta ? "Beta 发布" : "普通发布" }
}
public struct ReleaseStageTime: Codable, Sendable {
public let phase: ReleasePhase
public let seconds: Double
}
import Foundation
/// Completed workflow steps, never a percentage inferred from elapsed time.
public struct ReleaseProgress: Sendable {
public let expectedDuration: TimeInterval
public private(set) var elapsed: TimeInterval = 0
private let phases: [ReleasePhase]
private let imageCount: Int
private var current = 0
private var imagesDone = 0
private var succeeded = false
private let samples: [TimeInterval]
public init(expectedDuration: TimeInterval, phases: [ReleasePhase] = [.preparing, .pulling, .building, .image, .deploying, .verifying],
imageCount: Int = 1, referenceDurations: [TimeInterval] = []) {
self.expectedDuration = max(1, expectedDuration)
self.phases = phases
self.imageCount = max(1, imageCount)
samples = referenceDurations.filter { $0 > 0 }.suffix(5).sorted()
}
public mutating func advance(by seconds: TimeInterval) { elapsed += max(0, seconds) }
public mutating func enter(_ phase: ReleasePhase) {
if let index = phases.firstIndex(of: phase) { current = max(current, index) }
}
public mutating func completeImages(_ count: Int) { imagesDone = max(imagesDone, min(imageCount, count)) }
public mutating func finish() { succeeded = true }
public var totalSteps: Int { phases.count + (phases.contains(.image) ? imageCount - 1 : 0) }
public var completedSteps: Int {
if succeeded { return totalSteps }
let previous = phases.prefix(current).reduce(0) { $0 + ($1 == .image ? imageCount : 1) }
return previous + (phases.indices.contains(current) && phases[current] == .image ? imagesDone : 0)
}
public var percentage: Double { totalSteps == 0 ? 0 : Double(completedSteps) / Double(totalSteps) * 100 }
public var hasReliableEstimate: Bool { samples.count >= 3 }
public var remainingSeconds: Int { max(0, Int(ceil((samples.last ?? expectedDuration) - elapsed))) }
public var countdown: String {
guard hasReliableEstimate, let lower = samples.first, let upper = samples.last else { return "剩余时间采样中" }
if elapsed >= upper { return "已超出历史参考耗时" }
return "历史参考剩余 \(Self.duration(max(0, Int(ceil(lower - elapsed)))))–\(Self.duration(remainingSeconds))"
}
public static func steps(type: ScriptType, mode: ReleaseMode, action: ReleaseAction) -> [ReleasePhase] {
if action == .preflight { return [.preparing, .preflight] }
if type == .custom { return [.preparing, .pulling, .script] }
var plan: [ReleasePhase] = [.preparing, .pulling, .inventory, .building, .image, .deploying]
if mode == .beta || action == .verified { plan.append(.verifying) }
return plan
}
public static func duration(_ seconds: Int) -> String {
String(format: "%02d:%02d", seconds / 60, seconds % 60)
}
}
This diff is collapsed.
import Foundation
import Darwin
struct ReleaseWorkspace {
var project: ReleaseProject
var profile: DeployProfile?
let lock: FileHandle
static func prepare(project: ReleaseProject, profile: DeployProfile?, storage: URL,
control: ReleaseControl, receive: (Data) throws -> Void) throws -> Self {
let files = FileManager.default
// Existing shell scripts require a working directory without spaces.
let cache = storage.path.contains(where: \.isWhitespace)
? URL.cachesDirectory.appending(path: "JavaReleaseMenu") : storage
let parent = cache.appending(path: "Workspaces/" + project.id.uuidString)
let destination = parent.appending(path: "repository")
let source = project.root.resolvingSymlinksInPath().path
let resolved = destination.resolvingSymlinksInPath().path
guard resolved != source, !resolved.hasPrefix(source + "/") else {
throw ReleaseError("发布缓存不可放在原项目目录内。")
}
try files.createDirectory(at: parent, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
let descriptor = open(parent.appending(path: "workspace.lock").path, O_CREAT | O_RDWR, 0o600)
guard descriptor >= 0 else { throw ReleaseError("无法创建发布缓存锁。") }
let lock = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
guard flock(descriptor, LOCK_EX | LOCK_NB) == 0 else { throw ReleaseError("该项目已有发布任务正在使用缓存,请稍后重试。") }
var environment = project.deploymentEnvironment()
environment["GIT_OPTIONAL_LOCKS"] = "0"
func git(_ arguments: [String], at directory: URL = project.root, quiet: Bool = false) throws -> String {
var output = Data()
let code = try control.run("/usr/bin/git", arguments, in: directory, environment: environment) {
output.append($0)
if !quiet { try receive($0) }
}
guard code == 0 else { throw ReleaseError("无法准备发布缓存(Git 退出码 \(code))。") }
return String(decoding: output, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
}
control.protectSource([project.root.resolvingSymlinksInPath().path])
let gitDirectory = try git(["rev-parse", "--absolute-git-dir"], quiet: true)
let common = try git(["rev-parse", "--git-common-dir"], quiet: true)
let commonURL = common.hasPrefix("/") ? URL(fileURLWithPath: common) : project.root.appending(path: common)
control.protectSource([gitDirectory, commonURL.standardizedFileURL.resolvingSymlinksInPath().path])
let branch = try git(["symbolic-ref", "--short", "HEAD"], quiet: true)
let remote = try git(["config", "--get", "branch.\(branch).remote"], quiet: true)
guard remote != ".", !remote.isEmpty else { throw ReleaseError("发布分支需要关联远端分支。") }
let merge = try git(["config", "--get", "branch.\(branch).merge"], quiet: true)
let remoteURL = try git(["remote", "get-url", remote], quiet: true)
if !files.fileExists(atPath: destination.appending(path: ".git").path) {
_ = try git(["clone", "--no-hardlinks", "--local", "--", project.root.path, destination.path])
} else {
_ = try git(["fetch", "--no-tags", "--", project.root.path, "HEAD"], at: destination)
_ = try git(["checkout", "-f", "-B", branch, "FETCH_HEAD"], at: destination)
_ = try git(["reset", "--hard", "FETCH_HEAD"], at: destination)
}
_ = try git(["config", "remote.\(remote).url", remoteURL], at: destination, quiet: true)
_ = try git(["config", "remote.\(remote).fetch", "+refs/heads/*:refs/remotes/\(remote)/*"], at: destination, quiet: true)
_ = try git(["config", "branch.\(branch).remote", remote], at: destination, quiet: true)
_ = try git(["config", "branch.\(branch).merge", merge], at: destination, quiet: true)
// Copy the working tree, including local edits and untracked configurations, without sharing Git metadata.
let code = try control.run("/usr/bin/rsync", ["-a", "--safe-links", "--delete",
"--exclude=.git", "--exclude=target/", "--exclude=.idea/",
project.root.path + "/", destination.path + "/"], in: parent, environment: environment, receive: receive)
guard code == 0 else { throw ReleaseError("复制项目到发布缓存失败(退出码 \(code))。") }
func relocate(_ path: String) throws -> String {
guard path.hasPrefix("/") else { return path }
guard path.hasPrefix(project.root.path + "/") else {
throw ReleaseError("缓存发布要求发布配置和脚本位于项目目录内,请选择项目内的文件。")
}
return destination.path + path.dropFirst(project.root.path.count)
}
var isolated = project
isolated.directory = destination.path
isolated.script = try relocate(project.script)
if project.inventoryPath.hasPrefix(project.root.path + "/") {
isolated.inventoryPath = try relocate(project.inventoryPath)
}
var selected = profile
if let profile {
selected?.file = try relocate(profile.file)
isolated.profiles = selected.map { [$0] } ?? []
}
return Self(project: isolated, profile: selected, lock: lock)
}
}
This diff is collapsed.
"""Ansible aggregate callback: timings only, never task arguments or result payloads."""
import json
import os
import time
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'jrm_timing'
CALLBACK_NEEDS_ENABLED = True
def __init__(self):
super(CallbackModule, self).__init__()
self.starts = {}
def v2_playbook_on_task_start(self, task, is_conditional):
self.starts[str(task._uuid)] = time.monotonic()
def emit(self, result, status):
task = result._task
started = self.starts.get(str(task._uuid))
if started is None:
return
record = dict(task=task.get_name(), host=result._host.get_name(), status=status,
seconds=round(time.monotonic() - started, 3))
line = json.dumps(record, ensure_ascii=False)
self._display.display('[发布计时] ' + line)
directory = os.environ.get('JRM_DIAGNOSTICS_DIR')
if directory:
try:
with open(os.path.join(directory, 'ansible-tasks.jsonl'), 'a') as sink:
sink.write(line + '\n')
except OSError as error:
self._display.warning('无法保存发布任务计时:' + str(error))
def v2_runner_on_ok(self, result):
self.emit(result, 'ok')
def v2_runner_on_failed(self, result, ignore_errors=False):
self.emit(result, 'failed')
def v2_runner_on_unreachable(self, result):
self.emit(result, 'unreachable')
This diff is collapsed.
......@@ -25,7 +25,60 @@ private struct EditorHost: View {
}
}
@MainActor
@Observable
private final class TemplateEditorOwner {
var session: ReleaseTemplateEditorSession?
}
private struct TemplateEditorHost: View {
@Bindable var owner: TemplateEditorOwner
var body: some View {
if let session = owner.session {
ReleaseTemplateEditor(session: session, summary: "deploy.yaml · PHY1",
cancel: { owner.session = nil }, persist: { _ in nil }).id(session.id)
}
}
}
final class ConfigurationEditorTests: XCTestCase {
@MainActor
func testTemplateEditorCancellationAndFailedSaveKeepLateFieldUpdatesSafe() {
_ = NSApplication.shared
let owner = TemplateEditorOwner()
let view = NSHostingView(rootView: TemplateEditorHost(owner: owner))
view.frame = NSRect(x: 0, y: 0, width: 320, height: 240)
let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.contentView = view
defer { window.close() }
for index in 0..<20 {
let session = ReleaseTemplateEditorSession(mode: .create)
owner.session = session
flush(view)
@Bindable var fields = session
let name = $fields.name
name.wrappedValue = "新模板"
if index == 0, let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
view.cacheDisplay(in: view.bounds, to: bitmap)
let previews = URL(fileURLWithPath: "/private/tmp/java-release-preview")
try? FileManager.default.createDirectory(at: previews, withIntermediateDirectories: true)
try? bitmap.representation(using: .png, properties: [:])?
.write(to: previews.appending(path: "template-editor.png"))
}
XCTAssertFalse(session.save { _ in "已有同名模板" })
XCTAssertEqual(session.name, "新模板")
session.cancel()
owner.session = nil
flush(view)
name.wrappedValue = "最后一次编辑"
XCTAssertEqual(session.name, "最后一次编辑")
XCTAssertFalse(session.save { _ in XCTFail("Cancelled editor must not save"); return nil })
}
let completed = ReleaseTemplateEditorSession(mode: .create)
XCTAssertTrue(completed.save { _ in nil })
XCTAssertFalse(completed.save { _ in XCTFail("Completed editor must not save twice"); return nil })
}
@MainActor
func testCancelWhileFieldsAreMountedDoesNotInvalidateTheirBindings() {
_ = NSApplication.shared
......
import ReleaseCore
import XCTest
final class ReleaseProgressTests: XCTestCase {
func testTimeDoesNotInventProgressAndCompletedImagesAdvanceSteps() {
var progress = ReleaseProgress(expectedDuration: 100,
phases: ReleaseProgress.steps(type: .cityKeeper, mode: .beta, action: .standard), imageCount: 2)
progress.advance(by: 10000)
XCTAssertEqual(progress.percentage, 0)
XCTAssertEqual(progress.countdown, "剩余时间采样中")
progress.enter(.image)
XCTAssertEqual(progress.completedSteps, 4)
XCTAssertEqual(progress.totalSteps, 8)
XCTAssertEqual(progress.percentage, 50)
progress.completeImages(1)
XCTAssertEqual(progress.percentage, 62.5)
progress.completeImages(100)
XCTAssertEqual(progress.percentage, 75)
progress.enter(.verifying)
XCTAssertEqual(progress.percentage, 87.5)
progress.advance(by: 10000)
XCTAssertEqual(progress.percentage, 87.5)
progress.finish()
XCTAssertEqual(progress.percentage, 100)
}
func testCountdownRequiresMultipleSamplesAndShowsHistoricalRange() {
var insufficient = ReleaseProgress(expectedDuration: 100, referenceDurations: [100, 110])
insufficient.advance(by: 50)
XCTAssertFalse(insufficient.hasReliableEstimate)
XCTAssertEqual(insufficient.countdown, "剩余时间采样中")
var sampled = ReleaseProgress(expectedDuration: 100, referenceDurations: [90, 100, 110])
sampled.advance(by: 20)
XCTAssertEqual(sampled.countdown, "历史参考剩余 01:10–01:30")
sampled.advance(by: 1000)
XCTAssertEqual(sampled.countdown, "已超出历史参考耗时")
XCTAssertEqual(sampled.percentage, 0)
}
func testConciseLogOmitsCommandNoiseAndRetainsFailuresAndTaskTime() {
let full = """
[12:00:00] 发布模式:Beta 发布
[INFO] Compiling 1500 source files
#4 COPY third-party/ /.ucn/service/
#4 CACHED
[gateway] 阶段用时 4.196 秒
[gateway] 构建和推送耗时 4.20 秒
[compile] 阶段用时 3.000 秒
[发布计时] {"task":"Start gateway","seconds":12.5,"status":"ok"}
[发布计时] {"task":"Start failed","seconds":1.5,"status":"failed"}
[compile] [ERROR] fixture deployment failed
"""
let concise = ReleaseLogSummary.compact(full)
XCTAssertTrue(concise.contains("Beta 发布"))
XCTAssertTrue(concise.contains("4.20 秒"))
XCTAssertTrue(concise.contains("Start gateway · 12.5 秒"))
XCTAssertTrue(concise.contains("Start failed · 1.5 秒 · failed"))
XCTAssertTrue(concise.contains("[compile] 阶段用时"))
XCTAssertFalse(concise.contains("4.196"))
XCTAssertTrue(concise.contains("fixture deployment failed"))
XCTAssertFalse(concise.contains("Compiling"))
XCTAssertFalse(concise.contains("CACHED"))
}
}
......@@ -9,5 +9,6 @@ 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"
cp -R "$binary_dir/JavaReleaseMenu_ReleaseCore.bundle" "$app/Contents/Resources/"
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