Commit 811abc0e authored by zpc's avatar zpc

Fix alias editor cancellation crash and ship compact icon toolbar

parent c86ed293
...@@ -19,9 +19,9 @@ ...@@ -19,9 +19,9 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>1.4.2</string> <string>1.4.3</string>
<key>CFBundleVersion</key> <key>CFBundleVersion</key>
<string>12</string> <string>13</string>
<key>LSMinimumSystemVersion</key> <key>LSMinimumSystemVersion</key>
<string>14.0</string> <string>14.0</string>
<key>LSUIElement</key> <key>LSUIElement</key>
......
...@@ -178,6 +178,24 @@ final class AppModel { ...@@ -178,6 +178,24 @@ final class AppModel {
} }
} }
func updateConfiguration(_ profile: DeployProfile, projectID: UUID) throws {
guard let index = projects.firstIndex(where: { $0.id == projectID }) else {
throw ReleaseError("项目已被移除,请重新选择项目。")
}
try projects[index].validate(profile)
var updated = projects
if let existing = updated[index].profiles.firstIndex(where: { $0.id == profile.id || $0.file == profile.file }) {
var saved = profile
saved.id = updated[index].profiles[existing].id
updated[index].profiles[existing] = saved
} else {
updated[index].profiles.append(profile)
}
try persist(updated, to: "projects.json")
projects = updated
if self.projectID == projectID { refreshConfigurationFiles() }
}
func toggleModule(_ module: String) { func toggleModule(_ module: String) {
var checked = Set(selection) var checked = Set(selection)
if checked.remove(module) == nil { checked.insert(module) } if checked.remove(module) == nil { checked.insert(module) }
......
import Observation
import ReleaseCore
import SwiftUI
// A removed editor can still receive a final field update from SwiftUI.
// Keep its draft alive independently of the parent's optional presentation state.
@MainActor
@Observable
final class ConfigurationEditorSession: Identifiable {
let id = UUID()
var draft: DeployProfile
var error: String?
private(set) var isClosed = false
init(profile: DeployProfile) { draft = profile }
func cancel() { isClosed = true }
func save(using persist: (DeployProfile) -> String?) -> Bool {
guard !isClosed else { return false }
error = persist(draft)
if error == nil { isClosed = true }
return error == nil
}
}
struct ConfigurationProfileEditor: View {
@Bindable var session: ConfigurationEditorSession
let cancel: () -> Void
let persist: (DeployProfile) -> String?
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(session.draft.file).font(.system(.caption, design: .monospaced))
.foregroundStyle(ReleaseColors.muted).lineLimit(1)
TextField("别名(可选)", text: $session.draft.alias)
.textFieldStyle(.roundedBorder).accessibilityIdentifier("configuration-alias")
TextField("SSH 目标(可选)", text: $session.draft.sshTarget)
.textFieldStyle(.roundedBorder).accessibilityIdentifier("configuration-ssh")
if let error = session.error {
Text(error).font(.caption).foregroundStyle(ReleaseColors.danger)
.fixedSize(horizontal: false, vertical: true).textSelection(.enabled)
}
HStack {
Spacer()
Button {
session.cancel()
cancel()
} label: {
Text("取消").foregroundStyle(ReleaseColors.muted)
.padding(.horizontal, 10).frame(height: 28)
}
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.surface))
.keyboardShortcut(.cancelAction)
.accessibilityIdentifier("configuration-editor-cancel")
.help("放弃本次修改,保留原来的配置")
Button {
if session.save(using: persist) { cancel() }
} label: {
Text("保存").foregroundStyle(.white)
.padding(.horizontal, 12).frame(height: 28)
}
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.action, prominent: true))
.keyboardShortcut(.defaultAction)
.accessibilityIdentifier("configuration-editor-save")
.help("保存当前配置的别名和 SSH 目标")
}
}
.font(ReleaseTypography.detail).padding(8)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
.environment(\.colorScheme, .dark)
}
}
...@@ -77,7 +77,7 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate { ...@@ -77,7 +77,7 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
private func openSettings() { private func openSettings() {
popover.close() popover.close()
if settings == nil { if settings == nil {
let controller = NSHostingController(rootView: ProjectSettings(model: model)) let controller = NSHostingController(rootView: ProjectSettings(model: model, close: { [weak self] in self?.settings?.close() }))
let window = NSWindow(contentViewController: controller) let window = NSWindow(contentViewController: controller)
window.title = "项目设置" window.title = "项目设置"
window.titleVisibility = .hidden window.titleVisibility = .hidden
...@@ -96,9 +96,12 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate { ...@@ -96,9 +96,12 @@ final class MenuController: NSObject, NSApplicationDelegate, NSWindowDelegate {
} }
func windowWillClose(_ notification: Notification) { func windowWillClose(_ notification: Notification) {
if notification.object as? NSWindow === settings { guard let closedWindow = notification.object as? NSWindow, closedWindow === settings else { return }
settings = nil // Retain the window until AppKit has finished dispatching its close event.
split.preparePopover() Task { @MainActor [weak self, closedWindow] in
guard let self, self.settings === closedWindow, !closedWindow.isVisible else { return }
self.settings = nil
self.split.preparePopover()
} }
} }
......
...@@ -4,6 +4,7 @@ import SwiftUI ...@@ -4,6 +4,7 @@ import SwiftUI
struct ProjectSettings: View { struct ProjectSettings: View {
let model: AppModel let model: AppModel
let close: () -> Void
@State private var draft = ReleaseProject() @State private var draft = ReleaseProject()
@State private var error: String? @State private var error: String?
@State private var confirmingRemoval = false @State private var confirmingRemoval = false
...@@ -125,7 +126,7 @@ struct ProjectSettings: View { ...@@ -125,7 +126,7 @@ struct ProjectSettings: View {
.buttonStyle(SettingsButtonStyle()) .buttonStyle(SettingsButtonStyle())
} }
Spacer() Spacer()
Button("取消") { NSApp.keyWindow?.close() } Button("取消") { close() }
.buttonStyle(SettingsButtonStyle()) .buttonStyle(SettingsButtonStyle())
.keyboardShortcut(.cancelAction) .keyboardShortcut(.cancelAction)
Button("保存", action: save) Button("保存", action: save)
...@@ -255,7 +256,7 @@ struct ProjectSettings: View { ...@@ -255,7 +256,7 @@ struct ProjectSettings: View {
do { do {
try model.save(draft) try model.save(draft)
error = nil error = nil
NSApp.keyWindow?.close() close()
} catch { self.error = error.localizedDescription } } catch { self.error = error.localizedDescription }
} }
......
...@@ -63,6 +63,7 @@ struct ReleaseIconButton: View { ...@@ -63,6 +63,7 @@ struct ReleaseIconButton: View {
let symbol: String let symbol: String
let title: String let title: String
var tint: Color = ReleaseColors.muted var tint: Color = ReleaseColors.muted
var size: CGFloat = 28
let action: () -> Void let action: () -> Void
var body: some View { var body: some View {
...@@ -70,7 +71,7 @@ struct ReleaseIconButton: View { ...@@ -70,7 +71,7 @@ struct ReleaseIconButton: View {
Image(systemName: symbol) Image(systemName: symbol)
.font(.system(size: 12, weight: .medium)) .font(.system(size: 12, weight: .medium))
.foregroundStyle(tint) .foregroundStyle(tint)
.frame(width: 28, height: 28) .frame(width: size, height: size)
.contentShape(RoundedRectangle(cornerRadius: 6)) .contentShape(RoundedRectangle(cornerRadius: 6))
} }
.buttonStyle(ReleaseButtonStyle(radius: 6)) .buttonStyle(ReleaseButtonStyle(radius: 6))
......
...@@ -283,6 +283,30 @@ final class SplitReleaseModel { ...@@ -283,6 +283,30 @@ final class SplitReleaseModel {
settings.projects.first { $0.id == pane.projectID } settings.projects.first { $0.id == pane.projectID }
} }
@discardableResult
func saveConfiguration(_ profile: DeployProfile, for pane: ReleasePaneState, select: Bool)
-> Bool
{
guard panes.contains(where: { $0 === pane }), !isRunning else {
pane.error = "项目窗口已关闭或正在发布,暂时无法修改配置。"
return false
}
do {
try settings.updateConfiguration(profile, projectID: pane.projectID)
if select {
pane.profileID =
project(for: pane)?.profiles.first(where: { $0.file == profile.file })?.id
pane.verified = false
}
pane.error = nil
save()
return true
} catch {
pane.error = error.localizedDescription
return false
}
}
func logURL(for result: ReleaseResult) -> URL { func logURL(for result: ReleaseResult) -> URL {
storage.appending(path: "Logs").appending(path: result.logName) storage.appending(path: "Logs").appending(path: result.logName)
} }
......
...@@ -11,9 +11,9 @@ struct SplitReleasePanel: View { ...@@ -11,9 +11,9 @@ struct SplitReleasePanel: View {
private var columnWidth: CGFloat { private var columnWidth: CGFloat {
let available = (NSScreen.main?.visibleFrame.width ?? 1440) - 32 let available = (NSScreen.main?.visibleFrame.width ?? 1440) - 32
return min( return min(
model.panes.count == 1 ? 460 : 400, model.panes.count == 1 ? 364 : 340,
max( max(
310, 300,
floor( floor(
(available - CGFloat(max(1, model.panes.count))) (available - CGFloat(max(1, model.panes.count)))
/ CGFloat(max(1, model.panes.count))))) / CGFloat(max(1, model.panes.count)))))
...@@ -55,59 +55,49 @@ struct SplitReleasePanel: View { ...@@ -55,59 +55,49 @@ struct SplitReleasePanel: View {
return min(650, base + extra) return min(650, base + extra)
}.max() ?? 280 }.max() ?? 280
let reserved: CGFloat = let reserved: CGFloat =
64 + (model.panes.count > 1 ? 88 : 0) + (model.error == nil ? 0 : 40) + 24 48 + (model.panes.count > 1 ? 88 : 0) + (model.error == nil ? 0 : 40) + 24
return min(desired, max(300, (NSScreen.main?.visibleFrame.height ?? 900) - reserved)) return min(desired, max(300, (NSScreen.main?.visibleFrame.height ?? 900) - reserved))
} }
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
HStack(spacing: 10) { HStack(spacing: 8) {
ZStack { ZStack {
RoundedRectangle(cornerRadius: 9).fill(ReleaseColors.blue.opacity(0.12)) RoundedRectangle(cornerRadius: 8).fill(ReleaseColors.blue.opacity(0.10))
Image(systemName: "shippingbox") Image(systemName: "shippingbox")
.font(.system(size: 19, weight: .medium)).foregroundStyle( .font(.system(size: 18, weight: .medium)).foregroundStyle(
ReleaseColors.blue) ReleaseColors.blue)
}.frame(width: 34, height: 34)
VStack(alignment: .leading, spacing: 2) {
Text("Java 发布").font(.system(size: 18, weight: .semibold))
Text(model.isRunning ? "发布任务进行中" : "本地项目 · 编译与部署")
.font(.system(size: 10)).foregroundStyle(ReleaseColors.muted)
} }
Spacer(minLength: 8) .frame(width: 30, height: 30)
Button(action: model.add) {
Label("增加窗口", systemImage: "plus")
.font(ReleaseTypography.detail)
.padding(.horizontal, 10).frame(height: 30)
}
.disabled(
model.isRunning || model.panes.count >= 4
|| model.panes.count >= model.settings.projects.count
)
.buttonStyle(ReleaseButtonStyle(base: ReleaseColors.surface))
.help( .help(
model.isRunning "Java 发布 \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.4.3")"
)
Spacer()
ReleaseIconButton(
symbol: "plus",
title: model.isRunning
? "发布期间不能增加项目窗口" ? "发布期间不能增加项目窗口"
: model.panes.count >= 4 : model.panes.count >= 4
? "最多支持四个窗口" ? "最多支持四个窗口"
: model.panes.count >= model.settings.projects.count : model.panes.count >= model.settings.projects.count
? "没有其他项目,请先在项目设置中添加" : "增加一个不同项目的发布窗口") ? "没有其他项目,请先在项目设置中添加" : "增加窗口", tint: ReleaseColors.blue, size: 32,
action: model.add
)
.disabled(
model.isRunning || model.panes.count >= 4
|| model.panes.count >= model.settings.projects.count)
ReleaseIconButton( ReleaseIconButton(
symbol: "gearshape", title: model.isRunning ? "发布期间不能修改项目设置" : "项目设置", symbol: "gearshape", title: model.isRunning ? "发布期间不能修改项目设置" : "项目设置", size: 32,
action: settings action: settings
) )
.disabled(model.isRunning) .disabled(model.isRunning)
Menu { ReleaseIconButton(
Text("Java 发布 1.4.2") symbol: "power", title: model.isRunning ? "发布期间不能退出软件" : "退出 Java 发布",
Divider() tint: ReleaseColors.muted, size: 32, action: quit
Button("退出 Java 发布", action: quit) )
} label: { .disabled(model.isRunning)
Image(systemName: "ellipsis").font(.system(size: 15))
.foregroundStyle(ReleaseColors.muted).frame(width: 24, height: 28)
}
.menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()
.help("更多选项").accessibilityLabel("更多选项")
} }
.padding(.horizontal, 18).frame(height: 64) .padding(.horizontal, 16).frame(height: 48)
Rectangle().fill(ReleaseColors.border).frame(height: 1) Rectangle().fill(ReleaseColors.border).frame(height: 1)
...@@ -253,7 +243,7 @@ private struct ProjectReleaseColumn: View { ...@@ -253,7 +243,7 @@ private struct ProjectReleaseColumn: View {
let model: SplitReleaseModel let model: SplitReleaseModel
@Bindable var pane: ReleasePaneState @Bindable var pane: ReleasePaneState
let height: CGFloat let height: CGFloat
@State private var configurationDraft: DeployProfile? @State private var configurationEditor: ConfigurationEditorSession?
@FocusState private var moduleSearchFocused: Bool @FocusState private var moduleSearchFocused: Bool
private var project: ReleaseProject? { model.project(for: pane) } private var project: ReleaseProject? { model.project(for: pane) }
...@@ -293,7 +283,7 @@ private struct ProjectReleaseColumn: View { ...@@ -293,7 +283,7 @@ private struct ProjectReleaseColumn: View {
configuration configuration
} }
} }
.padding(18) .padding(16)
.frame(height: height) .frame(height: height)
.background(pane.state == .running ? ReleaseColors.blue.opacity(0.09) : .clear) .background(pane.state == .running ? ReleaseColors.blue.opacity(0.09) : .clear)
.font(ReleaseTypography.body) .font(ReleaseTypography.body)
...@@ -324,7 +314,7 @@ private struct ProjectReleaseColumn: View { ...@@ -324,7 +314,7 @@ private struct ProjectReleaseColumn: View {
Image(systemName: "hammer").foregroundStyle(ReleaseColors.muted).frame( Image(systemName: "hammer").foregroundStyle(ReleaseColors.muted).frame(
width: 20) width: 20)
Text("Maven").foregroundStyle(ReleaseColors.muted).frame( Text("Maven").foregroundStyle(ReleaseColors.muted).frame(
width: 66, alignment: .leading) width: 62, alignment: .leading)
Picker("Maven", selection: $pane.mavenCommand) { Picker("Maven", selection: $pane.mavenCommand) {
Text("mvnd").tag(MavenCommand.mvnd) Text("mvnd").tag(MavenCommand.mvnd)
Text("mvn").tag(MavenCommand.mvn) Text("mvn").tag(MavenCommand.mvn)
...@@ -419,23 +409,24 @@ private struct ProjectReleaseColumn: View { ...@@ -419,23 +409,24 @@ private struct ProjectReleaseColumn: View {
_ field: ReleasePaneState.ConfigurationField, _ label: String, symbol: String, value: String _ field: ReleasePaneState.ConfigurationField, _ label: String, symbol: String, value: String
) -> some View { ) -> some View {
Button { Button {
configurationDraft = nil configurationEditor?.cancel()
configurationEditor = nil
pane.expandedField = pane.expandedField == field ? nil : field pane.expandedField = pane.expandedField == field ? nil : field
} label: { } label: {
HStack(spacing: 12) { HStack(spacing: 9) {
Image(systemName: symbol).font(.system(size: 15, weight: .regular)) Image(systemName: symbol).font(.system(size: 15, weight: .regular))
.foregroundStyle( .foregroundStyle(
pane.expandedField == field ? ReleaseColors.blue : ReleaseColors.muted pane.expandedField == field ? ReleaseColors.blue : ReleaseColors.muted
).frame(width: 20) ).frame(width: 18)
Text(label).foregroundStyle(ReleaseColors.muted).frame( Text(label).foregroundStyle(ReleaseColors.muted).frame(
width: 66, alignment: .leading) width: 62, alignment: .leading)
Text(value).foregroundStyle(.white.opacity(0.9)).lineLimit(1).truncationMode(.tail) Text(value).foregroundStyle(.white.opacity(0.9)).lineLimit(1).truncationMode(.tail)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
Image(systemName: pane.expandedField == field ? "chevron.up" : "chevron.down").font( Image(systemName: pane.expandedField == field ? "chevron.up" : "chevron.down").font(
.system(size: 11) .system(size: 11)
).foregroundStyle( ).foregroundStyle(
ReleaseColors.muted) ReleaseColors.muted)
}.padding(.horizontal, 14).frame(height: 46).contentShape(Rectangle()) }.padding(.horizontal, 12).frame(height: 44).contentShape(Rectangle())
}.buttonStyle( }.buttonStyle(
ReleaseButtonStyle( ReleaseButtonStyle(
base: pane.expandedField == field ? ReleaseColors.blue.opacity(0.06) : .clear, base: pane.expandedField == field ? ReleaseColors.blue.opacity(0.06) : .clear,
...@@ -766,26 +757,13 @@ private struct ProjectReleaseColumn: View { ...@@ -766,26 +757,13 @@ private struct ProjectReleaseColumn: View {
.frame(height: min(160, CGFloat(files.count) * 46 + 8)) .frame(height: min(160, CGFloat(files.count) * 46 + 8))
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7)) .background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
} }
if let draft = Binding($configurationDraft) { if let editor = configurationEditor {
VStack(alignment: .leading, spacing: 8) { ConfigurationProfileEditor(session: editor, cancel: { configurationEditor = nil }) {
Text(draft.file.wrappedValue).font(.system(.caption, design: .monospaced)) updated in
.foregroundStyle(ReleaseColors.muted).lineLimit(1) model.saveConfiguration(updated, for: pane, select: false)
TextField("别名(可选)", text: draft.alias).textFieldStyle(.roundedBorder) ? nil : pane.error ?? "保存配置失败,请检查后重试。"
TextField("SSH 目标(可选)", text: draft.sshTarget).textFieldStyle(.roundedBorder)
HStack {
Spacer()
Button("取消") { configurationDraft = nil }
Button("保存") {
if let configurationDraft,
saveProfile(configurationDraft, select: false)
{
self.configurationDraft = nil
}
}
}
} }
.font(ReleaseTypography.detail).padding(8) .id(editor.id)
.background(ReleaseColors.terminal, in: RoundedRectangle(cornerRadius: 7))
} }
Button { Button {
if let project { browseConfiguration(in: project) } if let project { browseConfiguration(in: project) }
...@@ -802,7 +780,8 @@ private struct ProjectReleaseColumn: View { ...@@ -802,7 +780,8 @@ private struct ProjectReleaseColumn: View {
let selected = profile?.file == file let selected = profile?.file == file
return HStack(spacing: 2) { return HStack(spacing: 2) {
Button { Button {
configurationDraft = nil configurationEditor?.cancel()
configurationEditor = nil
if let project { selectConfiguration(file, in: project) } if let project { selectConfiguration(file, in: project) }
} label: { } label: {
HStack(spacing: 8) { HStack(spacing: 8) {
...@@ -825,7 +804,8 @@ private struct ProjectReleaseColumn: View { ...@@ -825,7 +804,8 @@ private struct ProjectReleaseColumn: View {
.accessibilityAddTraits(selected ? .isSelected : []) .accessibilityAddTraits(selected ? .isSelected : [])
.help("\(option.title) · \(file)") .help("\(option.title) · \(file)")
Button { Button {
configurationDraft = option configurationEditor?.cancel()
configurationEditor = ConfigurationEditorSession(profile: option)
} label: { } label: {
Image(systemName: "pencil").foregroundStyle(ReleaseColors.blue) Image(systemName: "pencil").foregroundStyle(ReleaseColors.blue)
.font(.system(size: 12, weight: .medium)).frame(width: 28, height: 28) .font(.system(size: 12, weight: .medium)).frame(width: 28, height: 28)
...@@ -848,15 +828,9 @@ private struct ProjectReleaseColumn: View { ...@@ -848,15 +828,9 @@ private struct ProjectReleaseColumn: View {
} }
private func selectConfiguration(_ file: String, in project: ReleaseProject) { private func selectConfiguration(_ file: String, in project: ReleaseProject) {
if let existing = project.profiles.first(where: { $0.file == file }) { var profile = project.profiles.first(where: { $0.file == file }) ?? DeployProfile()
pane.profileID = existing.id profile.file = file
pane.verified = false model.saveConfiguration(profile, for: pane, select: true)
model.save()
return
}
var added = DeployProfile()
added.file = file
saveProfile(added)
} }
private func browseConfiguration(in project: ReleaseProject) { private func browseConfiguration(in project: ReleaseProject) {
...@@ -871,26 +845,4 @@ private struct ProjectReleaseColumn: View { ...@@ -871,26 +845,4 @@ private struct ProjectReleaseColumn: View {
selectConfiguration(name, in: project) selectConfiguration(name, in: project)
} }
@discardableResult
private func saveProfile(_ updated: DeployProfile, select: Bool = true) -> Bool {
guard var project else { return false }
do {
try project.validate(updated)
if let index = project.profiles.firstIndex(where: { $0.id == updated.id }) {
project.profiles[index] = updated
} else {
project.profiles.append(updated)
}
try model.settings.save(project)
if select {
pane.profileID = updated.id
pane.verified = false
}
model.save()
return true
} catch {
pane.error = error.localizedDescription
return false
}
}
} }
import AppKit
import Observation
import ReleaseCore
import SwiftUI
import XCTest
@testable import JavaReleaseMenu
@MainActor
@Observable
private final class EditorOwner {
var session: ConfigurationEditorSession?
}
private struct EditorHost: View {
@Bindable var owner: EditorOwner
var body: some View {
VStack {
if let session = owner.session {
ConfigurationProfileEditor(session: session, cancel: { owner.session = nil }, persist: { _ in nil })
.id(session.id)
}
}
.frame(width: 320, height: 220)
}
}
final class ConfigurationEditorTests: XCTestCase {
@MainActor
func testCancelWhileFieldsAreMountedDoesNotInvalidateTheirBindings() {
_ = NSApplication.shared
let owner = EditorOwner()
let view = NSHostingView(rootView: EditorHost(owner: owner))
view.frame = NSRect(x: 0, y: 0, width: 320, height: 220)
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..<30 {
var original = DeployProfile()
original.file = "deploy-\(index).yaml"
original.alias = "original"
let session = ConfigurationEditorSession(profile: original)
owner.session = session
flush(view)
@Bindable var fields = session
let alias = $fields.draft.alias
let ssh = $fields.draft.sshTarget
alias.wrappedValue = "edited-\(index)"
ssh.wrappedValue = "user@host"
flush(view)
session.cancel()
owner.session = nil
flush(view)
// AppKit may deliver a final edit after the cancel action removed the form.
XCTAssertEqual(alias.wrappedValue, "edited-\(index)")
ssh.wrappedValue = "late-field-update"
XCTAssertEqual(original.alias, "original")
XCTAssertNil(owner.session)
}
}
@MainActor
func testSwitchingEditorsKeepsLateUpdatesInThePreviousDraft() {
var first = DeployProfile(); first.file = "first.yaml"
var second = DeployProfile(); second.file = "second.yaml"
let owner = EditorOwner()
let old = ConfigurationEditorSession(profile: first)
owner.session = old
@Bindable var oldFields = old
let oldAlias = $oldFields.draft.alias
let replacement = ConfigurationEditorSession(profile: second)
owner.session = replacement
oldAlias.wrappedValue = "old pending edit"
XCTAssertEqual(replacement.draft.file, "second.yaml")
XCTAssertEqual(replacement.draft.alias, "")
XCTAssertNotEqual(old.id, replacement.id)
}
@MainActor
func testFailedSaveKeepsDraftAndSuccessfulSaveClearsError() {
var profile = DeployProfile(); profile.file = "deploy.yaml"
let session = ConfigurationEditorSession(profile: profile)
session.draft.alias = "测试环境"
XCTAssertFalse(session.save { _ in "invalid SSH target" })
XCTAssertEqual(session.draft.alias, "测试环境")
XCTAssertEqual(session.error, "invalid SSH target")
var saved: DeployProfile?
XCTAssertTrue(session.save { saved = $0; return nil })
XCTAssertNil(session.error)
XCTAssertEqual(saved?.alias, "测试环境")
}
@MainActor
func testCancelledOrAlreadySavedEditorCannotSubmitAgain() {
let cancelled = ConfigurationEditorSession(profile: DeployProfile())
var calls = 0
cancelled.cancel()
XCTAssertFalse(cancelled.save { _ in calls += 1; return nil })
XCTAssertEqual(calls, 0)
let saved = ConfigurationEditorSession(profile: DeployProfile())
XCTAssertTrue(saved.save { _ in calls += 1; return nil })
XCTAssertFalse(saved.save { _ in calls += 1; return nil })
XCTAssertEqual(calls, 1)
}
@MainActor
private func flush(_ view: NSView) {
view.layoutSubtreeIfNeeded()
if let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
view.cacheDisplay(in: view.bounds, to: bitmap)
}
RunLoop.current.run(until: Date().addingTimeInterval(0.005))
}
}
...@@ -168,6 +168,67 @@ final class ReleaseRunnerTests: XCTestCase { ...@@ -168,6 +168,67 @@ final class ReleaseRunnerTests: XCTestCase {
XCTAssertEqual(model.indicator, .failed) XCTAssertEqual(model.indicator, .failed)
} }
@MainActor
func testAliasSaveOnlyUpdatesItsProjectAndPreservesSelections() throws {
let first = try Fixture()
let second = try Fixture()
defer { first.remove(); second.remove() }
for fixture in [first, second] {
try "unchanged YAML contents".write(to: fixture.local.appending(path: "deploy.yaml"), atomically: true, encoding: .utf8)
}
var alpha = first.project; alpha.name = "Alpha"
var beta = second.project; beta.name = "Beta"
var profileA = DeployProfile(); profileA.file = "deploy.yaml"; profileA.alias = "original"
var profileB = DeployProfile(); profileB.file = "deploy.yaml"
alpha.profiles = [profileA]; beta.profiles = [profileB]
let storage = first.base.appending(path: "alias-state")
let settings = AppModel(storage: storage)
try settings.save(alpha); try settings.save(beta)
let model = SplitReleaseModel(settings: settings, storage: storage)
model.add()
let paneA = try XCTUnwrap(model.panes.first { $0.projectID == alpha.id })
let paneB = try XCTUnwrap(model.panes.first { $0.projectID == beta.id })
let modules = paneA.modules
profileA.alias = "测试环境"; profileA.sshTarget = "deploy@host"
// Metadata editing must still work when the build script is temporarily absent.
try FileManager.default.removeItem(at: first.local.appending(path: "release.sh"))
XCTAssertTrue(model.saveConfiguration(profileA, for: paneA, select: false))
XCTAssertEqual(settings.projectID, beta.id)
XCTAssertEqual(paneA.profileID, profileA.id)
XCTAssertEqual(paneB.profileID, profileB.id)
XCTAssertEqual(paneA.modules, modules)
XCTAssertEqual(settings.projects.first { $0.id == alpha.id }?.profiles.first?.alias, "测试环境")
let restored = AppModel(storage: storage)
XCTAssertEqual(restored.projects.first { $0.id == alpha.id }?.profiles.first?.alias, "测试环境")
XCTAssertEqual(try String(contentsOf: first.local.appending(path: "deploy.yaml"), encoding: .utf8), "unchanged YAML contents")
var duplicate = profileA; duplicate.id = UUID(); duplicate.alias = "updated again"
XCTAssertTrue(model.saveConfiguration(duplicate, for: paneA, select: true))
XCTAssertEqual(settings.projects.first { $0.id == alpha.id }?.profiles.count, 1)
XCTAssertEqual(paneA.profileID, profileA.id)
}
@MainActor
func testInvalidAliasOptionsAndRemovedPaneCannotOverwriteSavedConfiguration() throws {
let fixture = try Fixture()
defer { fixture.remove() }
try "".write(to: fixture.local.appending(path: "deploy.yaml"), atomically: true, encoding: .utf8)
var project = fixture.project
var profile = DeployProfile(); profile.file = "deploy.yaml"; profile.alias = "original"
project.profiles = [profile]
let settings = AppModel(storage: fixture.base.appending(path: "alias-invalid"))
try settings.save(project)
let model = SplitReleaseModel(settings: settings, storage: fixture.base.appending(path: "alias-invalid"))
let pane = try XCTUnwrap(model.panes.first)
var invalid = profile; invalid.alias = "invalid"; invalid.sshTarget = "bad target"
XCTAssertFalse(model.saveConfiguration(invalid, for: pane, select: false))
XCTAssertEqual(settings.projects.first?.profiles.first?.alias, "original")
XCTAssertNotNil(pane.error)
model.remove(pane)
var valid = profile; valid.alias = "late update"
XCTAssertFalse(model.saveConfiguration(valid, for: pane, select: false))
XCTAssertEqual(settings.projects.first?.profiles.first?.alias, "original")
}
@MainActor @MainActor
func testIdlePaneCanCloseWhileAnotherReleaseRuns() async throws { func testIdlePaneCanCloseWhileAnotherReleaseRuns() async throws {
let first = try Fixture() let first = try Fixture()
......
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