refactor: remove unused functions and keep the codebase free of them

Delete functions that no product code calls, and fold "simple plus
WithOptions" pairs into the one signature callers actually use. Rename
the live macOS lifecycle functions that were labelled Legacy.

The architecture tests now share one source loader and reject functions
without a product caller and catalog messages nobody reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
千川白浪andClaude Opus 5.5 committed 2026-12-03 20:55:03 -07:00
1 parent 150269c2cd
commit c639682a88
107 files changed
+575 -1435

No files matched your search

-6
View File
@@ -14,7 +14,6 @@ export const pluginsZh: Record<string, string> = {
"pluginBuiltinSection": "内置插件",
"pluginClearSecret": "清除",
"pluginColorSchemes": "配色方案",
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
"pluginDeleteScheme": "删除方案",
"pluginDisable": "停用",
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
@@ -70,7 +69,6 @@ export const pluginsZh: Record<string, string> = {
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
"pluginMarketSyncing": "正在同步插件市场",
"pluginMarketUpdate": "更新至 v{version}",
"pluginMarketUpdateShort": "更新",
"pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}",
"pluginMarketWithdrawn": "已撤回",
@@ -98,7 +96,6 @@ export const pluginsZh: Record<string, string> = {
"pluginScanHardSection": "硬性拦截项(禁止安装)",
"pluginScanInspect": "安全扫描",
"pluginScanInstallConfirm": "确认导入安装",
"pluginScanLoading": "正在扫描插件包…",
"pluginScanModalTitle": "插件静态安全报告",
"pluginScanMoreItems": "另有 {count} 项已折叠",
"pluginSchemeDefault": "默认",
@@ -139,7 +136,6 @@ export const pluginsEn: Record<string, string> = {
"pluginBuiltinSection": "Built-in plugins",
"pluginClearSecret": "Clear",
"pluginColorSchemes": "Color schemes",
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
"pluginDeleteScheme": "Delete scheme",
"pluginDisable": "Disable",
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
@@ -195,7 +191,6 @@ export const pluginsEn: Record<string, string> = {
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
"pluginMarketSyncing": "Syncing the plugin market",
"pluginMarketUpdate": "Update to v{version}",
"pluginMarketUpdateShort": "Update",
"pluginMarketVersionTip": "v{installed} installed, v{version} available",
"pluginMarketWithdrawn": "Withdrawn",
@@ -223,7 +218,6 @@ export const pluginsEn: Record<string, string> = {
"pluginScanHardSection": "Hard blockers (install refused)",
"pluginScanInspect": "Security scan",
"pluginScanInstallConfirm": "Proceed with install",
"pluginScanLoading": "Scanning plugin package…",
"pluginScanModalTitle": "Plugin security report",
"pluginScanMoreItems": "...and {count} more",
"pluginSchemeDefault": "Default",
-44
View File
@@ -59,7 +59,6 @@ export const settingsZh: Record<string, string> = {
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
"affinityTitle": "处理器核心",
"appCheckUpdate": "检查更新",
"appDownloadUpdate": "前往下载",
"appUpToDate": "已是最新",
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
@@ -169,11 +168,9 @@ export const settingsZh: Record<string, string> = {
"effectNextStart": "下次启动生效",
"enableAudio": "音频",
"enableLogs": "记录图形与串口日志",
"enableNetwork": "网络(NAT)",
"enableWHPX": "启用",
"extraArgs": "额外 QEMU 参数",
"extraArgsDesc": "原样追加到 QEMU 命令行",
"failAffinity": "设置处理器相关性失败",
"folderShareAdd": "添加目录…",
"folderShareAddTitle": "宿主机目录",
"folderShareConfirmRWAction": "改为读写",
@@ -199,9 +196,6 @@ export const settingsZh: Record<string, string> = {
"folderShareRemove": "移除目录",
"folderShareTitle": "自定义共享目录",
"folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录",
"footerDisk": "磁盘可用 {gb} GB",
"footerMem": "内存 {pct}%",
"footerMemAvail": "可用 {avail} GB",
"forceQuitAppButton": "强制退出",
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
"forceQuitAppTitle": "强制退出 Reims-Go",
@@ -247,7 +241,6 @@ export const settingsZh: Record<string, string> = {
"groupMacOS": "macOS",
"groupPerformance": "性能",
"groupQemu": "QEMU",
"gtInstallCmd": "安装命令",
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
"guestLangShort": "系统语言",
@@ -279,9 +272,6 @@ export const settingsZh: Record<string, string> = {
"guestTimezoneUTC": "UTC(协调世界时)",
"guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令",
"guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}",
"guestToolsConnected": "已连接",
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
"guestToolsReady": "已配置",
"hidpiPresetBadge": "HiDPI",
"hostAudioInput": "Windows 麦克风",
"hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音",
@@ -356,7 +346,6 @@ export const settingsZh: Record<string, string> = {
"installersDownloaded": "已下载",
"installersDownloadingForVM": "为 {vm} 下载中",
"installersDownloadingPct": "下载中 {p}%",
"installersEmpty": "还没有下载任何镜像",
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
"installersKindOffline": "离线完整包",
"installersKindOnline": "在线恢复镜像",
@@ -425,7 +414,6 @@ export const settingsZh: Record<string, string> = {
"nestedVirtLabel": "嵌套虚拟化",
"nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。",
"networkBridge": "桥接",
"networkDesc": "通过 Windows 的网络连接上网",
"networkNAT": "NAT",
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
"networkTitle": "网络",
@@ -436,7 +424,6 @@ export const settingsZh: Record<string, string> = {
"npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查",
"npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认",
"npcapStopFirst": "安装驱动前需先关闭全部虚拟机",
"offlineListFailed": "无法读取 Apple 的版本列表",
"opencore": "OpenCore",
"optAuto": "已自动开启",
"optAvailable": "可用",
@@ -449,11 +436,9 @@ export const settingsZh: Record<string, string> = {
"optPCoreSub": "仅调度到性能核({detail}),减少卡顿",
"optPCoreUnavailable": "当前处理器无大小核架构,无需开启",
"optRecommended": "推荐",
"optSchedBackground": "后台服务",
"optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)",
"optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)",
"optSchedOpen": "更改…",
"optSchedPrograms": "程序优先",
"optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)",
"optSchedTitle": "Windows 处理器调度",
"optUnavailable": "不可用",
@@ -462,7 +447,6 @@ export const settingsZh: Record<string, string> = {
"recommendedBadge": "推荐",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
"resFullscreen": "全屏",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"resNativeBadge": "原生",
"resScaleToFitWindow": "缩放以适应窗口",
@@ -504,11 +488,6 @@ export const settingsZh: Record<string, string> = {
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
"sshPort": "SSH 转发端口",
"startAfterCreate": "创建后立即启动",
"statsCPU": "QEMU CPU",
"statsDisk": "磁盘占用",
"statsDiskSub": "实际 {actual} / 上限 {virtual}",
"statsMemory": "宿主机内存",
"statsUptime": "运行时长",
"stopBeforeDiskOp": "关机后才能操作",
"stopTimeout": "关机等待时间",
"stopTimeoutHint": "0 表示一直等待",
@@ -547,7 +526,6 @@ export const settingsZh: Record<string, string> = {
"vcpus": "虚拟处理器",
"vmDir": "存放目录",
"vmName": "名称",
"welcomeCheckHost": "先完成内核环境配置 →",
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
"welcomeTitle": "创建第一台 macOS 虚拟机",
"whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows",
@@ -624,7 +602,6 @@ export const settingsEn: Record<string, string> = {
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
"affinityTitle": "CPU cores",
"appCheckUpdate": "Check for updates",
"appDownloadUpdate": "Download",
"appUpToDate": "Up to date",
"appUpdateAvailable": "New stable release {v} available",
"appUpdateAvailableAlpha": "New alpha release {v} available",
@@ -734,11 +711,9 @@ export const settingsEn: Record<string, string> = {
"effectNextStart": "Next start",
"enableAudio": "Audio",
"enableLogs": "Keep graphics and serial logs",
"enableNetwork": "Network (NAT)",
"enableWHPX": "Enable",
"extraArgs": "Extra QEMU arguments",
"extraArgsDesc": "Appended to the QEMU command line as is",
"failAffinity": "Could not update processor affinity",
"folderShareAdd": "Add folder…",
"folderShareAddTitle": "Host folders",
"folderShareConfirmRWAction": "Enable read-write",
@@ -764,9 +739,6 @@ export const settingsEn: Record<string, string> = {
"folderShareRemove": "Remove folder",
"folderShareTitle": "Custom shared folders",
"folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly",
"footerDisk": "Disk {gb} GB free",
"footerMem": "Memory {pct}%",
"footerMemAvail": "{avail} GB free",
"forceQuitAppButton": "Force quit",
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
"forceQuitAppTitle": "Force quit Reims-Go",
@@ -812,7 +784,6 @@ export const settingsEn: Record<string, string> = {
"groupMacOS": "macOS",
"groupPerformance": "Performance",
"groupQemu": "QEMU",
"gtInstallCmd": "Install command",
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
"guestLangShort": "System language",
@@ -844,9 +815,6 @@ export const settingsEn: Record<string, string> = {
"guestTimezoneUTC": "UTC",
"guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}",
"guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}",
"guestToolsConnected": "Connected",
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
"guestToolsReady": "Configured",
"hidpiPresetBadge": "HiDPI",
"hostAudioInput": "Windows microphone",
"hostAudioMissingIn": "No microphone found; macOS will record silence",
@@ -921,7 +889,6 @@ export const settingsEn: Record<string, string> = {
"installersDownloaded": "Downloaded",
"installersDownloadingForVM": "Downloading for {vm}",
"installersDownloadingPct": "Downloading {p}%",
"installersEmpty": "No images downloaded yet",
"installersHint": "Downloaded images can be reused for new VMs",
"installersKindOffline": "Offline installer",
"installersKindOnline": "Online recovery",
@@ -990,7 +957,6 @@ export const settingsEn: Record<string, string> = {
"nestedVirtLabel": "Nested virtualization",
"nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.",
"networkBridge": "Bridged",
"networkDesc": "Uses the Windows network connection",
"networkNAT": "NAT",
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
"networkTitle": "Network",
@@ -1001,7 +967,6 @@ export const settingsEn: Record<string, string> = {
"npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards",
"npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard",
"npcapStopFirst": "Shut down all VMs before installing the driver",
"offlineListFailed": "Couldn’t read Apple’s release list",
"opencore": "OpenCore",
"optAuto": "Automatic",
"optAvailable": "Available",
@@ -1014,11 +979,9 @@ export const settingsEn: Record<string, string> = {
"optPCoreSub": "Schedule QEMU on performance cores only ({detail})",
"optPCoreUnavailable": "CPU has no hybrid P/E cores",
"optRecommended": "Recommended",
"optSchedBackground": "Background services",
"optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)",
"optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)",
"optSchedOpen": "Change…",
"optSchedPrograms": "Programs",
"optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)",
"optSchedTitle": "Windows processor scheduling",
"optUnavailable": "Unavailable",
@@ -1027,7 +990,6 @@ export const settingsEn: Record<string, string> = {
"recommendedBadge": "Recommended",
"resCustom": "Custom",
"resCustomSub": "Width × height",
"resFullscreen": "Full screen",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"resNativeBadge": "Native",
"resScaleToFitWindow": "Scale to fit window",
@@ -1069,11 +1031,6 @@ export const settingsEn: Record<string, string> = {
"sshOffDesc": "Log in to macOS over SSH from Windows",
"sshPort": "SSH forward port",
"startAfterCreate": "Start after creating",
"statsCPU": "QEMU CPU",
"statsDisk": "Disk usage",
"statsDiskSub": "{actual} actual / {virtual} max",
"statsMemory": "Host RAM",
"statsUptime": "Uptime",
"stopBeforeDiskOp": "Shut down the VM first",
"stopTimeout": "Shutdown timeout",
"stopTimeoutHint": "0 waits indefinitely",
@@ -1112,7 +1069,6 @@ export const settingsEn: Record<string, string> = {
"vcpus": "Virtual CPUs",
"vmDir": "Folder",
"vmName": "Name",
"welcomeCheckHost": "Set up Engine first →",
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
"welcomeTitle": "Create your first macOS VM",
"whpxHvOff": "Hypervisor launch is off — enable and restart Windows",
-25
View File
@@ -59,7 +59,6 @@ export type I18nKey =
| "affinitySummaryPCores"
| "affinityTitle"
| "appCheckUpdate"
| "appDownloadUpdate"
| "appUpToDate"
| "appUpdateAvailable"
| "appUpdateAvailableAlpha"
@@ -245,7 +244,6 @@ export type I18nKey =
| "emptyVMs"
| "enableAudio"
| "enableLogs"
| "enableNetwork"
| "enableWHPX"
| "endpointCopyADB"
| "endpointEditConnection"
@@ -278,7 +276,6 @@ export type I18nKey =
| "factGraphics"
| "factGuestOS"
| "factMemory"
| "failAffinity"
| "failAttachInstaller"
| "failCloneVM"
| "failCreate"
@@ -346,14 +343,11 @@ export type I18nKey =
| "folderShareTitle"
| "folderShareWritableWarn"
| "fontMissingFoDHint"
| "footerDisk"
| "footerDiskLabel"
| "footerDiskTip"
| "footerDiskValue"
| "footerHostIssue"
| "footerHostIssueTip"
| "footerMem"
| "footerMemAvail"
| "footerMemLabel"
| "footerMemTip"
| "footerMemValue"
@@ -412,7 +406,6 @@ export type I18nKey =
| "groupPerformance"
| "groupQemu"
| "gtInstall"
| "gtInstallCmd"
| "gtInstallSub"
| "gtNotInstalledDesc"
| "gtStatusConnected"
@@ -464,13 +457,10 @@ export type I18nKey =
| "guestTimezoneUTC"
| "guestTimezoneUpgradeAttachHint"
| "guestTimezoneUpgradeHint"
| "guestToolsConnected"
| "guestToolsHostDNS"
| "guestToolsModeSync"
| "guestToolsModeWebDAV"
| "guestToolsPreventSleep"
| "guestToolsPreventSleepSub"
| "guestToolsReady"
| "guestToolsSleepActive"
| "guestToolsTitle"
| "guestToolsUpgradeHint"
@@ -588,7 +578,6 @@ export type I18nKey =
| "installersDownloading"
| "installersDownloadingForVM"
| "installersDownloadingPct"
| "installersEmpty"
| "installersHint"
| "installersKindOffline"
| "installersKindOnline"
@@ -694,7 +683,6 @@ export type I18nKey =
| "netOff"
| "netShared"
| "networkBridge"
| "networkDesc"
| "networkNAT"
| "networkOfflineHint"
| "networkTitle"
@@ -712,7 +700,6 @@ export type I18nKey =
| "offlineCached"
| "offlineDownloading"
| "offlineHint"
| "offlineListFailed"
| "offlineListFailedDetail"
| "offlineLoading"
| "offlineQueued"
@@ -737,11 +724,9 @@ export type I18nKey =
| "optPCoreSub"
| "optPCoreUnavailable"
| "optRecommended"
| "optSchedBackground"
| "optSchedNowBackground"
| "optSchedNowPrograms"
| "optSchedOpen"
| "optSchedPrograms"
| "optSchedSub"
| "optSchedTitle"
| "optUnavailable"
@@ -767,7 +752,6 @@ export type I18nKey =
| "pluginBuiltinSection"
| "pluginClearSecret"
| "pluginColorSchemes"
| "pluginColorSchemesHint"
| "pluginDeleteScheme"
| "pluginDisable"
| "pluginDisableInUseBody"
@@ -823,7 +807,6 @@ export type I18nKey =
| "pluginMarketSearchPlaceholder"
| "pluginMarketStaleBanner"
| "pluginMarketSyncing"
| "pluginMarketUpdate"
| "pluginMarketUpdateShort"
| "pluginMarketVersionTip"
| "pluginMarketWithdrawn"
@@ -852,7 +835,6 @@ export type I18nKey =
| "pluginScanHardSection"
| "pluginScanInspect"
| "pluginScanInstallConfirm"
| "pluginScanLoading"
| "pluginScanModalTitle"
| "pluginScanMoreItems"
| "pluginSchemeDefault"
@@ -884,7 +866,6 @@ export type I18nKey =
| "refresh"
| "resCustom"
| "resCustomSub"
| "resFullscreen"
| "resInvalid"
| "resLooksLike"
| "resNativeBadge"
@@ -1051,11 +1032,6 @@ export type I18nKey =
| "state_stopping"
| "state_suspended"
| "state_suspending"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
| "statsMemory"
| "statsUptime"
| "step1"
| "step2"
| "step3"
@@ -1208,7 +1184,6 @@ export type I18nKey =
| "vmDir"
| "vmName"
| "vulkanProbeFailed"
| "welcomeCheckHost"
| "welcomeSub"
| "welcomeTitle"
| "whpxHvOff"
+1 -1
View File
@@ -175,7 +175,7 @@ func (a *App) InstallAppUpdate() error {
}
a.mu.Unlock()
target := selfupdate.Target(exe, filepath.Base(path))
if err := selfupdate.SwapWithOptions(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
if err := selfupdate.Swap(exe, target, path, version.KeepsPreviousInstall(channel)); err != nil {
return err
}
a.emitLog("app", fmt.Sprintf("Installed update %s at %s; restarting", ver, target))
+1 -1
View File
@@ -56,7 +56,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
ctx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
taskID, w, finishTask := a.ctlTaskWriterWithCancel("vm-create", opts.Name, cancel)
taskID, w, finishTask := a.ctlTaskWriter("vm-create", opts.Name, cancel)
if opts.NetworkMode == "bridge" {
tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: networkmsg.Text(a.locale(), "log.create_network_prepare"), Percent: -1})
}
+2 -2
View File
@@ -23,7 +23,7 @@ func (a *App) ResizeVMDiskWithDriver(driverID, name, newSize string) (driver.Dis
ref := driver.VMRef{DriverID: driverID, Name: name}
taskCtx, cancel := context.WithCancel(a.baseCtx())
defer cancel()
_, w, finishTask := a.ctlTaskWriterWithCancel("vm-disk-resize", ref.Key(), cancel)
_, w, finishTask := a.ctlTaskWriter("vm-disk-resize", ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Resizing disk for %s (%s)...", name, strings.TrimSpace(newSize)))
res, err := svc.ResizeDisk(taskCtx, ref, newSize, w, w)
if err != nil {
@@ -70,7 +70,7 @@ func (a *App) runCompactVMDisk(driverID, name string, optimize bool) (driver.Dis
taskKind = "vm-disk-optimize"
message = fmt.Sprintf("Optimizing qcow2 disk for %s with extended L2 subclusters...", name)
}
_, w, finishTask := a.ctlTaskWriterWithCancel(taskKind, ref.Key(), cancel)
_, w, finishTask := a.ctlTaskWriter(taskKind, ref.Key(), cancel)
a.emitVMLogForDriver(driverID, name, message)
var (
res driver.DiskCompactResult
+1 -10
View File
@@ -14,7 +14,6 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/qmp"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -199,9 +198,6 @@ func (a *App) currentGuestToolsServer() *guesttools.Server {
return a.guestTools
}
var sendDropClickAndPaste = qmp.SendAbsoluteClickAndPaste
var defaultDropClickAndPaste = true
func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID string, displayIndex int, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
if _, running := a.currentVMPID(ctx, name); !running {
return fmt.Errorf("%s is not running", name)
@@ -210,12 +206,7 @@ func (a *App) handleHostDropPaste(ctx context.Context, vmKey, name, dropID strin
if err != nil {
return err
}
if defaultDropClickAndPaste && fmt.Sprintf("%p", sendDropClickAndPaste) == fmt.Sprintf("%p", qmp.SendAbsoluteClickAndPaste) {
if svc, svcErr := a.computerUseService(); svcErr == nil && svc != nil {
return svc.SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
}
}
return sendDropClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
return a.computerUseInternalService().SendAbsoluteClickAndPaste(ctx, d.Directory, normX, normY, activateClick, commandKey, focusWait)
}
func (a *App) handleHostDropAck(vmKey, name string, ack guesttools.DropEventAck) {
+6 -6
View File
@@ -79,7 +79,7 @@ func (a *App) EnterRecovery(name string) error {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.enterRecoveryLegacy(name)
return a.enterMacOSRecovery(name)
}
raw, err := svc.InvokeAction(context.Background(), driver.NewVMRef("", name), "enter_recovery", nil)
if err != nil {
@@ -103,10 +103,10 @@ func (a *App) EnterRecovery(name string) error {
return nil
}
// enterRecoveryLegacy is the direct reims-ctl fallback when the lifecycle
// enterMacOSRecovery is the direct reims-ctl fallback when the lifecycle
// router is unconfigured; it enables OpenCore's boot picker (--boot-selection=true)
// immediately when stopped or queues a "want" marker when running.
func (a *App) enterRecoveryLegacy(name string) error {
func (a *App) enterMacOSRecovery(name string) error {
c, err := a.client()
if err != nil {
return err
@@ -286,7 +286,7 @@ func (a *App) FinishInstall(name string) error {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.finishInstallLegacy(name)
return a.finishMacOSInstall(name)
}
vm, err := a.resolveVMInfo("", name)
if err != nil {
@@ -333,10 +333,10 @@ func (a *App) FinishInstall(name string) error {
return nil
}
// FinishInstall exits recovery mode: ejects any attached installer, removes
// finishMacOSInstall exits recovery mode: ejects any attached installer, removes
// REIMSHELP, enables the network if off, and restores OpenCore direct boot
// (--boot-selection=false) if recovery mode enabled the boot picker.
func (a *App) finishInstallLegacy(name string) error {
func (a *App) finishMacOSInstall(name string) error {
c, err := a.client()
if err != nil {
return err
+6 -6
View File
@@ -118,7 +118,7 @@ func (a *App) StartVMWithDriver(driverID, name string) error {
return err
}
return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error {
return a.startVMLegacy(vm.Name)
return a.startMacOSVM(vm.Name)
})
}
_, vm, err := svc.Resolve(context.Background(), driverID, name)
@@ -137,7 +137,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface {
Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error)
}, vm driver.VMInfo) error {
if svc == nil {
return a.startVMLegacy(vm.Name)
return a.startMacOSVM(vm.Name)
}
ref := vm.Ref()
key := ref.Key()
@@ -193,7 +193,7 @@ func (a *App) stopVMWithDriverCtx(ctx context.Context, driverID, name string, fo
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.stopVMLegacyCtx(ctx, name, force)
return a.stopMacOSVM(ctx, name, force)
}
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
@@ -238,7 +238,7 @@ func (a *App) EjectInstallerWithDriver(driverID, name string) error {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.ejectInstallerLegacy(name)
return a.ejectMacOSInstaller(name)
}
vm, err := a.resolveVMInfo(driverID, name)
if err != nil {
@@ -260,7 +260,7 @@ func (a *App) ReadVMLogsWithDriver(driverID, name string, serial bool) (string,
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.readVMLogsLegacy(name, serial)
return a.readMacOSVMLogs(name, serial)
}
return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial)
}
@@ -318,7 +318,7 @@ func (a *App) DeleteVMWithDriver(driverID, name string, keepFiles bool) error {
if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID {
return errors.New("driver is unavailable without the plugin manager")
}
return a.deleteVMLegacy(name, keepFiles)
return a.deleteMacOSVM(name, keepFiles)
}
d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name)
if err != nil {
+2 -2
View File
@@ -30,7 +30,7 @@ func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo {
return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data}
}
func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, error) {
func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
c, err := a.client()
if err != nil {
return reims.VMDetail{}, err
@@ -56,7 +56,7 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) {
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return a.getVMDetailLegacy(name, epoch)
return a.loadMacOSVMDetail(name, epoch)
}
// This adapter only serves the built-in macOS driver, so resolve within it:
// a same-named VM in another driver must not make the lookup ambiguous.
+9 -13
View File
@@ -194,7 +194,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
return strings.TrimSpace(s)
}
func (a *App) startVMLegacy(name string) error {
func (a *App) startMacOSVM(name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
@@ -433,11 +433,7 @@ func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlCli
return nil
}
func (a *App) stopVMLegacy(name string, force bool) error {
return a.stopVMLegacyCtx(context.Background(), name, force)
}
func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) error {
func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error {
c, err := a.client()
if err != nil {
return err
@@ -447,11 +443,11 @@ func (a *App) stopVMLegacyCtx(ctx context.Context, name string, force bool) erro
return err
}
return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error {
return a.stopVMLegacyLocked(operationCtx, name, force, c)
return a.stopMacOSVMLocked(operationCtx, name, force, c)
})
}
func (a *App) stopVMLegacyLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
a.mu.Lock()
@@ -541,7 +537,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo
return true, a.startResolvedVMLocked(ctx, svc, vm)
}
func (a *App) ejectInstallerLegacy(name string) error {
func (a *App) ejectMacOSInstaller(name string) error {
c, err := a.client()
if err != nil {
return err
@@ -563,7 +559,7 @@ func (a *App) ejectInstallerLegacy(name string) error {
return nil
}
func (a *App) deleteVMLegacy(name string, keepFiles bool) error {
func (a *App) deleteMacOSVM(name string, keepFiles bool) error {
c, err := a.client()
if err != nil {
return err
@@ -573,11 +569,11 @@ func (a *App) deleteVMLegacy(name string, keepFiles bool) error {
return err
}
return a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error {
return a.deleteVMLegacyLocked(ctx, name, keepFiles, c)
return a.deleteMacOSVMLocked(ctx, name, keepFiles, c)
})
}
func (a *App) deleteVMLegacyLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error {
func (a *App) deleteMacOSVMLocked(ctx context.Context, name string, keepFiles bool, c *reims.Client) error {
a.cancelRebootWatcher(name)
stopVMMonitor(name)
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
@@ -628,7 +624,7 @@ func (a *App) ReadVMLogs(name string, serial bool) (string, error) {
return a.ReadVMLogsWithDriver("", name, serial)
}
func (a *App) readVMLogsLegacy(name string, serial bool) (string, error) {
func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) {
c, err := a.client()
if err != nil {
return "", err
+3 -26
View File
@@ -36,7 +36,7 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
root := a.cfg.DataRoot
loc := i18n.EffectiveLocale(a.cfg.Locale)
a.mu.Unlock()
issues := reims.ValidateCreateLocalized(opts, host.Inspect(root), loc)
issues := reims.ValidateCreate(opts, host.Inspect(root), loc)
// reims-ctl refuses a name already registered; say so before the create runs.
if vms, err := a.listVMsInternal(context.Background()); err == nil {
for _, vm := range vms {
@@ -69,7 +69,7 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) {
root := a.cfg.DataRoot
loc := a.cfg.Locale
a.mu.Unlock()
return reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc), nil
return reims.ValidateSet(opts, cur, host.Inspect(root), loc), nil
}
func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
@@ -107,7 +107,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
root := a.cfg.DataRoot
loc := a.cfg.Locale
a.mu.Unlock()
if issues := reims.ValidateSetLocalized(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
if issues := reims.ValidateSet(opts, cur, host.Inspect(root), loc); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
w := vmstart.LineWriter(func(line string) { a.emitVMLog(opts.Name, line) })
@@ -526,29 +526,6 @@ func (a *App) recoverPacketNetwork(ctx context.Context, c networkControlClient,
})()
}
// 启动和恢复只重开 Npcap 通道,不改写封存的设备参数。
func (a *App) prepareVMNetwork(c *reims.Client, d reims.VMDetail) (err error) {
defer a.localizeNetworkError(&err)
record, err := reims.ReadNetworkRecord(d.Directory)
if err != nil {
return err
}
if record.Corrupt {
return networkmsg.Error("record_invalid", nil)
}
if record.Pending {
return networkmsg.Error("packet_pending", nil)
}
if d.NetworkMode != "bridge" {
a.stopPacketBridge(d.Name)
return nil
}
if !a.npcapPluginEnabled() {
return networkmsg.Error("plugin_disabled", nil)
}
return a.preparePacketNetwork(a.baseCtx(), c, d, record, false)
}
func selectPacketUplink(adapters []packetbridge.Adapter, guid string) (packetbridge.Adapter, error) {
for _, adapter := range adapters {
if guid != "" && adapterGUIDKey(adapter.GUID) == adapterGUIDKey(guid) && adapter.Status == "Up" {
-86
View File
@@ -1,86 +0,0 @@
package app
import (
"context"
"errors"
"fmt"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// ToggleVMFullscreen switches the running VM's display between full screen and windowed mode.
func (a *App) toggleVMFullscreenLegacy(name string) (bool, error) {
a.mu.Lock()
preference := a.cfg.Locale
a.mu.Unlock()
loc := i18n.EffectiveLocale(preference)
c, err := a.client()
if err != nil {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", i18n.Vars{"name": name}, err)
}
fullscreen, err := toggleVMFullscreen(context.Background(), name, loc, c, host.ToggleProcessWindowFullscreen)
if err != nil {
return false, err
}
a.emitVMLog(name, fmt.Sprintf("VM window full screen: %t", fullscreen))
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
return fullscreen, nil
}
type fullscreenVMClient interface {
Show(context.Context, string) (reims.VMDetail, error)
List(context.Context) ([]driver.VMListItem, error)
}
func findRunningVMPID(vms []driver.VMListItem, name string) (uint32, bool) {
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return uint32(*vm.PID), true
}
}
return 0, false
}
func toggleVMFullscreen(ctx context.Context, name string, loc i18n.Locale, c fullscreenVMClient, toggleWindow func(uint32) (bool, error)) (bool, error) {
vars := i18n.Vars{"name": name}
beforeVMs, err := c.List(ctx)
if err != nil {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
}
pidBefore, ok := findRunningVMPID(beforeVMs, name)
if !ok {
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
}
detail, err := c.Show(ctx, name)
if err != nil {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
}
if detail.State != "running" {
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
}
if detail.Graphics == "vmware-svga" {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_VMWARE_SVGA", "err.fullscreen_vmware_svga", vars, nil)
}
afterVMs, err := c.List(ctx)
if err != nil {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
}
pidAfter, ok := findRunningVMPID(afterVMs, name)
if !ok || pidAfter != pidBefore {
return false, i18n.NewCodedError(loc, "E_VM_NOT_RUNNING", "err.vm_not_running", vars, nil)
}
fullscreen, err := toggleWindow(pidAfter)
if errors.Is(err, host.ErrDisplayWindowNotFound) {
return false, i18n.NewCodedError(loc, "E_VM_WINDOW_NOT_FOUND", "err.vm_window_not_found", vars, err)
}
if err != nil {
return false, i18n.NewCodedError(loc, "E_FULLSCREEN_FAILED", "err.fullscreen_failed", vars, err)
}
return fullscreen, nil
}
+1 -1
View File
@@ -103,7 +103,7 @@ func (a *App) initPlugins() {
}
kindReg := rt.NewKindRegistry()
drvRouter := driver.NewRouterWithDataRoot(mgr.Registry(), func() string {
drvRouter := driver.NewRouter(mgr.Registry(), func() string {
a.mu.Lock()
defer a.mu.Unlock()
return a.cfg.DataRoot
+1 -1
View File
@@ -234,7 +234,7 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL {
return *appUpdateCache.info, nil
}
info, err := version.DefaultSource().CheckUpdateChannel(a.baseCtx(), version.Version, ch)
info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version, ch)
if err != nil {
return info, err
}
+2 -9
View File
@@ -15,9 +15,6 @@ const sshUserFileName = ".reims-go-ssh-user"
var safeSSHUserRe = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)
// sshHostAlias returns a stable ~/.ssh/config Host alias for a VM.
func sshHostAlias(vmName string) string { return sshHostAliasForDriver("", vmName) }
func sshHostAliasForDriver(driverID, vmName string) string {
var b strings.Builder
b.WriteString("reims-")
@@ -183,7 +180,7 @@ func (a *App) WriteSSHConfigWithDriver(driverID, name, user string) (string, err
}
cfgPath := filepath.Join(sshDir, "config")
alias := sshHostAliasForDriver(driverID, name)
if err := upsertSSHConfigBlockHost(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil {
if err := upsertSSHConfigBlock(cfgPath, sshConfigKey(driverID, name), alias, sshHost, sshPort, user); err != nil {
return "", err
}
a.emitVMLogForDriver(driverID, name, fmt.Sprintf("Updated ~/.ssh/config with Host %s (%s:%d)", alias, sshHost, sshPort))
@@ -218,11 +215,7 @@ func (a *App) OpenVSCodeSSHWithDriver(driverID, name, user string) error {
return nil
}
func upsertSSHConfigBlock(cfgPath, vmName, alias string, port int, user string) error {
return upsertSSHConfigBlockHost(cfgPath, vmName, alias, "127.0.0.1", port, user)
}
func upsertSSHConfigBlockHost(cfgPath, vmName, alias, host string, port int, user string) error {
func upsertSSHConfigBlock(cfgPath, vmName, alias, host string, port int, user string) error {
startMark := fmt.Sprintf("# >>> reims-go:%s >>>", vmName)
endMark := fmt.Sprintf("# <<< reims-go:%s <<<", vmName)
+4 -4
View File
@@ -11,10 +11,10 @@ func TestSSHHostAlias(t *testing.T) {
if sshHostAliasForDriver("test.driver.linux", "dev") == sshHostAliasForDriver("", "dev") {
t.Fatal("same-name drivers share an SSH alias")
}
if got := sshHostAlias("macos-tahoe"); got != "reims-macos-tahoe" {
if got := sshHostAliasForDriver("", "macos-tahoe"); got != "reims-macos-tahoe" {
t.Fatalf("alias = %q", got)
}
if got := sshHostAlias("My Mac 26"); got != "reims-my-mac-26" {
if got := sshHostAliasForDriver("", "My Mac 26"); got != "reims-my-mac-26" {
t.Fatalf("alias = %q", got)
}
}
@@ -26,7 +26,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) {
t.Fatal(err)
}
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2222, "alice"); err != nil {
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2222, "alice"); err != nil {
t.Fatal(err)
}
b1, _ := os.ReadFile(cfg)
@@ -36,7 +36,7 @@ func TestUpsertSSHConfigBlockIdempotent(t *testing.T) {
}
// Updating port and user must replace the block in place without duplicating it.
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", 2223, "bob"); err != nil {
if err := upsertSSHConfigBlock(cfg, "macos-tahoe", "reims-macos-tahoe", "127.0.0.1", 2223, "bob"); err != nil {
t.Fatal(err)
}
b2, _ := os.ReadFile(cfg)
+1 -6
View File
@@ -399,12 +399,7 @@ func (a *App) ensureTaskEmitter() {
// a "<vm>: " prefix, which is dropped from the step. Each new step is logged
// once, so the log keeps the milestones without one line per percent.
// finish closes the task with the command's error.
func (a *App) ctlTaskWriter(kind, vm string) (w io.Writer, finish func(error)) {
_, w, finish = a.ctlTaskWriterWithCancel(kind, vm, nil)
return w, finish
}
func (a *App) ctlTaskWriterWithCancel(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) {
func (a *App) ctlTaskWriter(kind, vm string, cancel context.CancelFunc) (id string, w io.Writer, finish func(error)) {
a.ensureTaskEmitter()
id = tasks.start(kind, vm, vm, cancel)
lastStep := ""
+1 -1
View File
@@ -75,7 +75,7 @@ func TestTaskCancelAndFailure(t *testing.T) {
func TestCtlTaskWriterRoutesProgressToTheTask(t *testing.T) {
sent := newTestTasks(t)
a := &App{} // no Wails context: emitLog is a no-op
w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe")
_, w, finish := a.ctlTaskWriter("vm-create", "macos-tahoe", nil)
fmt.Fprintln(w, "macos-tahoe: creating the disk")
for p := 0; p <= 100; p += 5 {
fmt.Fprintf(w, "macos-tahoe: downloading OpenCore 1.0.8: %d%% of 11 MB\n", p)
-5
View File
@@ -41,7 +41,6 @@ var thumbLocks = struct {
locks map[string]*sync.Mutex
}{locks: make(map[string]*sync.Mutex)}
func (a *App) thumbPath(name string) string { return a.thumbPathForDriver("", name) }
func (a *App) thumbPathForDriver(driverID, name string) string {
a.mu.Lock()
dir := a.cfg.XDGCacheDir()
@@ -58,7 +57,6 @@ func (a *App) thumbPathForDriver(driverID, name string) string {
return filepath.Join(dir, "thumbs", prefix+name+".jpg")
}
func vmThumbLock(name string) *sync.Mutex { return vmThumbLockForDriver("", name) }
func vmThumbLockForDriver(driverID, name string) *sync.Mutex {
key := vmKeyForDriver(driverID, name)
thumbLocks.mu.Lock()
@@ -237,9 +235,6 @@ func (a *App) CopyVMScreenshotWithDriver(driverID, name string) error {
return nil
}
func (a *App) captureThumb(name, path string) (VMThumbnail, bool) {
return a.captureThumbWithDriver("", name, path)
}
func (a *App) captureThumbWithDriver(driverID, name, path string) (VMThumbnail, bool) {
typing.mu.Lock()
busy := typing.busy[vmKeyForDriver(driverID, name)]
+48 -111
View File
@@ -2,20 +2,23 @@ package app
import (
"context"
"errors"
"slices"
"os"
"runtime"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
const name = "thumbnail-release-test"
t.Cleanup(func() { releaseVMThumbnail(name) })
first := vmThumbLock(name)
if got := vmThumbLock(name); got != first {
first := vmThumbLockForDriver("", name)
if got := vmThumbLockForDriver("", name); got != first {
t.Fatal("same VM should share a thumbnail lock")
}
releaseVMThumbnail(name)
@@ -25,124 +28,58 @@ func TestReleaseVMThumbnailRemovesLock(t *testing.T) {
if remaining != 0 {
t.Fatalf("thumbnail locks remain after release: %d", remaining)
}
if got := vmThumbLock(name); got == first {
if got := vmThumbLockForDriver("", name); got == first {
t.Fatal("released lock was reused")
}
}
type testFullscreenClient struct {
detail reims.VMDetail
vms []reims.VMListItem
listCalls [][]reims.VMListItem
calls []string
}
func (c *testFullscreenClient) Show(_ context.Context, name string) (reims.VMDetail, error) {
c.calls = append(c.calls, "show "+name)
return c.detail, nil
}
func (c *testFullscreenClient) List(context.Context) ([]reims.VMListItem, error) {
idx := 0
for _, call := range c.calls {
if call == "list" {
idx++
}
}
c.calls = append(c.calls, "list")
if len(c.listCalls) > 0 {
if idx < len(c.listCalls) {
return c.listCalls[idx], nil
}
return c.listCalls[len(c.listCalls)-1], nil
}
return c.vms, nil
}
func TestToggleVMFullscreenUsesLiveVMState(t *testing.T) {
const name = "Tahoe"
oldPID, livePID, zeroPID, invalidPID := 301, 542, 0, -1
for _, tt := range []struct {
name string
state string
vms []reims.VMListItem
listCalls [][]reims.VMListItem
wantCalls []string
target uint32
}{
{"stopped at show", "stopped", []reims.VMListItem{{Name: name, State: "running", PID: &oldPID}}, nil, []string{"list", "show Tahoe"}, 0},
{"stopped before first list", "running", []reims.VMListItem{{Name: name, State: "stopped", PID: &oldPID}}, nil, []string{"list"}, 0},
{"missing from list", "running", []reims.VMListItem{{Name: "Other", State: "running", PID: &oldPID}}, nil, []string{"list"}, 0},
{"missing PID", "running", []reims.VMListItem{{Name: name, State: "running"}}, nil, []string{"list"}, 0},
{"zero PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &zeroPID}}, nil, []string{"list"}, 0},
{"negative PID", "running", []reims.VMListItem{{Name: name, State: "running", PID: &invalidPID}}, nil, []string{"list"}, 0},
{"restarted with different PID between show and list (e.g. switched to SVGA)", "running", nil, [][]reims.VMListItem{
{{Name: name, State: "running", PID: &oldPID}},
{{Name: name, State: "running", PID: &livePID}},
}, []string{"list", "show Tahoe", "list"}, 0},
{"live running VM with stable PID", "running", []reims.VMListItem{
{Name: "Other", State: "running", PID: &oldPID}, {Name: name, State: "running", PID: &livePID},
}, nil, []string{"list", "show Tahoe", "list"}, uint32(livePID)},
} {
t.Run(tt.name, func(t *testing.T) {
c := &testFullscreenClient{detail: reims.VMDetail{State: tt.state, Graphics: "reims-vgpu"}, vms: tt.vms, listCalls: tt.listCalls}
got, err := toggleVMFullscreen(context.Background(), name, i18n.EnUS, c, func(pid uint32) (bool, error) {
if pid != tt.target || tt.target == 0 {
t.Fatalf("toggled PID %d, want %d", pid, tt.target)
}
return true, nil
})
if !slices.Equal(c.calls, tt.wantCalls) {
t.Fatalf("client calls = %v, want %v", c.calls, tt.wantCalls)
}
if tt.target == 0 {
if got || err == nil || err.Error() != "VM Tahoe is not running [E_VM_NOT_RUNNING]" {
t.Fatalf("toggle = (%v, %v), want a not-running error", got, err)
}
} else if !got || err != nil {
t.Fatalf("toggle = (%v, %v), want (true, nil)", got, err)
}
})
}
}
// Every refusal carries a localized summary and a stable code.
func TestToggleVMFullscreenLocalizesErrors(t *testing.T) {
win32Error := errors.New("SetWindowPos: access denied")
pid := 542
windowless := os.Getpid()
for _, tt := range []struct {
name string
detail reims.VMDetail
hostError error
en, zh string
name, state, graphics string
pid *int
en, zh string
}{
{"stopped", reims.VMDetail{State: "stopped"}, nil,
{"stopped", "stopped", "", nil,
"VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"},
{"SVGA", reims.VMDetail{State: "running", Graphics: "vmware-svga"}, nil,
{"no process", "running", "reims-vgpu", nil,
"VM Tahoe is not running [E_VM_NOT_RUNNING]", "虚拟机 Tahoe 未运行 [E_VM_NOT_RUNNING]"},
{"SVGA", "running", "vmware-svga", &windowless,
"Press Ctrl+Alt+F in the QEMU window for Tahoe to toggle full screen [E_FULLSCREEN_VMWARE_SVGA]",
"在 Tahoe 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏 [E_FULLSCREEN_VMWARE_SVGA]"},
{"missing window", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, host.ErrDisplayWindowNotFound,
{"missing window", "running", "reims-vgpu", &windowless,
"Couldn’t find the display window for Tahoe [E_VM_WINDOW_NOT_FOUND]", "找不到 Tahoe 的显示窗口 [E_VM_WINDOW_NOT_FOUND]"},
{"Win32 failure", reims.VMDetail{State: "running", Graphics: "reims-vgpu"}, win32Error,
"Couldn’t toggle full screen for Tahoe [E_FULLSCREEN_FAILED]", "无法切换 Tahoe 的全屏状态 [E_FULLSCREEN_FAILED]"},
} {
for loc, summary := range map[i18n.Locale]string{i18n.EnUS: tt.en, i18n.ZhCN: tt.zh} {
t.Run(tt.name+"/"+string(loc), func(t *testing.T) {
c := &testFullscreenClient{detail: tt.detail, vms: []reims.VMListItem{{Name: "Tahoe", State: "running", PID: &pid}}}
got, err := toggleVMFullscreen(context.Background(), "Tahoe", loc, c, func(uint32) (bool, error) {
if tt.hostError == nil {
t.Fatal("toggled a stopped or SVGA VM")
}
return false, tt.hostError
})
want := summary
if tt.hostError != nil {
want += "\n[detail] " + tt.hostError.Error()
if !errors.Is(err, tt.hostError) {
t.Errorf("error lost original cause: %v", err)
}
if tt.name == "missing window" && runtime.GOOS != "windows" {
continue // only the Windows host looks for windows
}
for locale, want := range map[string]string{"en-US": tt.en, "zh-CN": tt.zh} {
t.Run(tt.name+"/"+locale, func(t *testing.T) {
drv := &appSecondDriver{id: driver.BuiltinReimsMacOSDriverID, vms: []driver.VMInfo{{
Name: "Tahoe", DriverID: driver.BuiltinReimsMacOSDriverID, Directory: t.TempDir(),
State: tt.state, PID: tt.pid, DriverData: map[string]any{"graphics": tt.graphics},
}}}
reg := plugin.NewRegistry(nil)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.macos", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
reg.RegisterGuestDriver(sc, drv.id, drv)
return nil
},
}); err != nil {
t.Fatal(err)
}
if got || err == nil || err.Error() != want {
t.Fatalf("toggle = (%v, %v), want (false, %q)", got, err, want)
reg.Reconcile(t.Context())
a := &App{cfg: &config.Config{DataRoot: t.TempDir(), Locale: i18n.Locale(locale)},
lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil),
transitions: map[string]string{}, pendingChanges: map[string][]PendingChange{}}
got, err := a.ToggleVMFullscreen("Tahoe")
if got || err == nil {
t.Fatalf("toggle = (%v, %v), want an error", got, err)
}
if summary, _, _ := strings.Cut(err.Error(), "\n"); summary != want {
t.Fatalf("summary = %q, want %q", summary, want)
}
})
}
+11 -1
View File
@@ -12,6 +12,16 @@ import (
"github.com/Nwflower/reims-go/internal/tray"
)
// runningVMPID returns the process ID of the named VM when it is running.
func runningVMPID(vms []driver.VMListItem, name string) (uint32, bool) {
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil && *vm.PID > 0 {
return uint32(*vm.PID), true
}
}
return 0, false
}
func (a *App) confirmVMWindowClose(name string) {
if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending {
return
@@ -56,7 +66,7 @@ func (a *App) confirmVMWindowClose(name string) {
a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error())
return
}
if current, running := findRunningVMPID(vms, ref.Name); !running || current != uint32(pid) {
if current, running := runningVMPID(vms, ref.Name); !running || current != uint32(pid) {
return
}
if choice == host.VMCloseSuspend {
+3 -3
View File
@@ -9,7 +9,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/host"
)
func TestLogTailDiscardsOversizeLinesAndResumes(t *testing.T) {
@@ -96,11 +96,11 @@ func TestFormatBootHeartbeatAndRedactLogLine(t *testing.T) {
t.Fatalf("unexpected heartbeat: %q", hb)
}
redacted := reims.RedactLogLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222")
redacted := host.RedactLine("network user, mac 52:54:00:bc:bc:0d, ssh on 127.0.0.1:2222")
if strings.Contains(redacted, "bc:bc:0d") || !strings.Contains(redacted, "mac [redacted]") {
t.Fatalf("MAC not redacted: %q", redacted)
}
redactedSerial := reims.RedactLogLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T")
redactedSerial := host.RedactLine("OpenCore presents the VM as an iMac20,1, serial C02FDGY9PN5T")
if strings.Contains(redactedSerial, "C02FDGY9PN5T") || !strings.Contains(redactedSerial, "serial [redacted]") {
t.Fatalf("serial not redacted: %q", redactedSerial)
}
-10
View File
@@ -11,16 +11,6 @@ import (
"github.com/Nwflower/reims-go/internal/vmstart"
)
// canScreendump reports whether the host can read a VM's screen over its QMP
// socket: the VM must declare `qmp` and must not be hosted. A VM with no
// declared capabilities is a legacy macOS VM.
func canScreendump(caps []string) bool {
if driver.IsHosted(caps) {
return false
}
return len(caps) == 0 || driver.HasCapability(caps, driver.CapQMP)
}
// readyToken and endpointSignature fold a VM's readiness and endpoints into
// the poll signature, so the UI refreshes when a driver flips them.
func readyToken(ready *bool) string {
-3
View File
@@ -35,7 +35,4 @@ func TestSameNamedVMMemoryStatesUseDriverQualifiedKeys(t *testing.T) {
if a.thumbPathForDriver("test.driver.a", "shared") == a.thumbPathForDriver("test.driver.b", "shared") {
t.Fatal("same-named VMs share a thumbnail path")
}
if got := a.thumbPath("shared"); got != a.thumbPathForDriver("", "shared") {
t.Fatal("default thumbnail path changed")
}
}
+5 -38
View File
@@ -1,9 +1,6 @@
package archtest
import (
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -20,44 +17,14 @@ var externalDriverIDs = []string{
}
func TestHostCodeNamesNoExternalDriver(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
t.Fatal(err)
}
skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true}
scanned := 0
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
for _, s := range sources(t) {
if s.isTest() {
continue
}
rel, _ := filepath.Rel(root, path)
rel = filepath.ToSlash(rel)
if d.IsDir() {
if skipDirs[d.Name()] || rel == "internal/archtest" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
scanned++
text := string(raw)
for _, id := range externalDriverIDs {
if strings.Contains(text, id) {
t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", rel, id)
if strings.Contains(s.raw, id) {
t.Errorf("%s names the external driver %q: host code must stay driver-agnostic", s.rel, id)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
if scanned < 50 {
t.Fatalf("scanned only %d Go files: the walk no longer finds the host sources", scanned)
}
}
+75
View File
@@ -0,0 +1,75 @@
package archtest
import (
"encoding/json"
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
var stringLiteral = regexp.MustCompile("[\"'`]([A-Za-z0-9_.-]+)(?:[\"'`]|[$]{|%s)")
// Every message costs a translation in every language pack, so one that no
// code shows must go. A key also counts as used when code builds it from a
// literal prefix, such as "cli.start." + step.
func TestCatalogHasNoUnusedMessages(t *testing.T) {
literals := map[string]bool{}
collect := func(text string) {
for _, m := range stringLiteral.FindAllStringSubmatch(text, -1) {
literals[m[1]] = true
}
}
for _, s := range sources(t) {
if !strings.HasSuffix(s.rel, "_gen.go") && !s.isTest() {
collect(s.raw)
}
}
err := filepath.WalkDir(filepath.Join("..", "..", "frontend", "src"), func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || strings.Contains(p, ".gen.") {
return err
}
raw, err := os.ReadFile(p)
collect(string(raw))
return err
})
if err != nil {
t.Fatal(err)
}
used := func(key string) bool {
if literals[key] {
return true
}
for i := range key {
if (key[i] == '.' || key[i] == '_') && literals[key[:i+1]] {
return true
}
}
return false
}
catalogs, err := filepath.Glob(filepath.Join("..", "..", "locales", "en-US", "*.json"))
if err != nil || len(catalogs) == 0 {
t.Fatalf("no message catalogs: %v", err)
}
for _, path := range catalogs {
if filepath.Base(path) == "macos-glossary.json" {
continue // Apple's wording, looked up by the text it translates
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var messages map[string]json.RawMessage
if err := json.Unmarshal(raw, &messages); err != nil {
t.Fatalf("%s: %v", path, err)
}
for key := range messages {
if !strings.HasPrefix(key, "$") && !used(key) {
t.Errorf("%s: no code shows message %q", filepath.Base(path), key)
}
}
}
}
+20 -84
View File
@@ -1,19 +1,11 @@
package archtest
import (
"go/parser"
"go/token"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
)
const macosImportPrefix = "github.com/Nwflower/reims-go/internal/macos"
// macosImporter is a package outside internal/macos that may still import
// macOS code: debt to pay down before macOS leaves this repository.
type macosImporter struct {
@@ -29,7 +21,6 @@ var macosImporters = map[string]macosImporter{
"internal/datamigrate": {src: true, test: true, why: "data layout v3 invokes and verifies the macOS-owned state and ledger migration"},
"internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"},
"internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"},
"internal/plugin": {test: true, why: "sidecar manager test builds a reims-ctl stand-in"},
}
// macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go
@@ -48,7 +39,6 @@ var macosSourceFiles = map[string][]string{
"internal/app/macos_detail.go",
"internal/app/macos_lifecycle_native.go",
"internal/app/macos_settings.go",
"internal/app/macos_window.go",
"internal/app/opencore_flow.go",
"internal/app/plugins_flow.go",
},
@@ -60,55 +50,28 @@ var macosSourceFiles = map[string][]string{
}
func TestMacOSBoundary(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
t.Fatal(err)
}
type use struct{ src, test []string }
found := map[string]*use{}
skipDirs := map[string]bool{".git": true, ".debug": true, "build": true, "frontend": true, "node_modules": true}
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
for _, s := range sources(t) {
if isMacOSDir(s.dir()) {
continue
}
rel, _ := filepath.Rel(root, path)
rel = filepath.ToSlash(rel)
if d.IsDir() {
if skipDirs[d.Name()] || rel == "internal/macos" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") {
return nil
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
p, _ := strconv.Unquote(imp.Path.Value)
if p != macosImportPrefix && !strings.HasPrefix(p, macosImportPrefix+"/") {
for _, dir := range s.imports() {
if !isMacOSDir(dir) {
continue
}
dir := filepath.ToSlash(filepath.Dir(rel))
u := found[dir]
u := found[s.dir()]
if u == nil {
u = &use{}
found[dir] = u
found[s.dir()] = u
}
if strings.HasSuffix(path, "_test.go") {
u.test = append(u.test, rel)
if s.isTest() {
u.test = append(u.test, s.rel)
} else {
u.src = append(u.src, rel)
u.src = append(u.src, s.rel)
}
break
}
return nil
})
if err != nil {
t.Fatal(err)
}
var problems []string
@@ -162,14 +125,6 @@ func TestMacOSBoundary(t *testing.T) {
}
}
// The ratchet only means something if internal/macos exists where the test
// looks; guard against the walk silently finding nothing after a move.
func TestMacOSBoundaryRootExists(t *testing.T) {
if st, err := os.Stat(filepath.Join("..", "macos")); err != nil || !st.IsDir() {
t.Fatalf("internal/macos not found next to internal/archtest: %v", err)
}
}
// macosHostImports is the reverse ratchet: dependencies of internal/macos on
// private host packages. External repositories cannot import these, so the
// list must shrink to zero before macOS becomes a separate Go module.
@@ -190,39 +145,16 @@ var macosHostImports = map[string]string{
}
func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", "macos"))
if err != nil {
t.Fatal(err)
}
found := map[string][]string{}
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
for _, s := range sources(t) {
if !isMacOSDir(s.dir()) {
continue
}
if d.IsDir() || !strings.HasSuffix(path, ".go") {
return nil
}
f, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ImportsOnly)
if err != nil {
return err
}
for _, imp := range f.Imports {
p, _ := strconv.Unquote(imp.Path.Value)
const prefix = "github.com/Nwflower/reims-go/internal/"
if !strings.HasPrefix(p, prefix) {
continue
for _, dir := range s.imports() {
if name, ok := strings.CutPrefix(dir, "internal/"); ok && !isMacOSDir(dir) {
found[name] = append(found[name], s.rel)
}
name := strings.TrimPrefix(p, prefix)
if strings.HasPrefix(name, "macos") {
continue
}
rel, _ := filepath.Rel(root, path)
found[name] = append(found[name], filepath.ToSlash(rel))
}
return nil
})
if err != nil {
t.Fatal(err)
}
for name, files := range found {
if _, ok := macosHostImports[name]; !ok {
@@ -235,3 +167,7 @@ func TestMacOSDoesNotGainPrivateHostDependencies(t *testing.T) {
}
}
}
func isMacOSDir(dir string) bool {
return dir == "internal/macos" || strings.HasPrefix(dir, "internal/macos/")
}
+98
View File
@@ -0,0 +1,98 @@
package archtest
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
)
const modulePath = "github.com/Nwflower/reims-go"
// source is one Go file of the repository. All build constraints are covered:
// the checks read every file, not one platform's selection.
type source struct {
rel string // slash-separated path from the repository root
raw string
file *ast.File
}
func (s source) dir() string { return path.Dir(s.rel) }
func (s source) isTest() bool { return strings.HasSuffix(s.rel, "_test.go") }
// imports maps the local name of every module-internal import to its
// repository directory.
func (s source) imports() map[string]string {
out := map[string]string{}
for _, imp := range s.file.Imports {
p, err := strconv.Unquote(imp.Path.Value)
if err != nil || !strings.HasPrefix(p, modulePath+"/") {
continue
}
name := path.Base(p)
if imp.Name != nil {
name = imp.Name.Name
}
out[name] = strings.TrimPrefix(p, modulePath+"/")
}
return out
}
var fileSet = token.NewFileSet()
var loadSources = sync.OnceValues(func() ([]source, error) {
root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil {
return nil, err
}
skip := map[string]bool{".git": true, ".debug": true, ".local": true, "build": true, "frontend": true, "node_modules": true, "archtest": true}
var out []source
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if skip[d.Name()] {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(p, ".go") {
return nil
}
raw, err := os.ReadFile(p)
if err != nil {
return err
}
f, err := parser.ParseFile(fileSet, p, raw, parser.SkipObjectResolution)
if err != nil {
return err
}
rel, err := filepath.Rel(root, p)
if err != nil {
return err
}
out = append(out, source{rel: filepath.ToSlash(rel), raw: string(raw), file: f})
return nil
})
return out, err
})
func sources(t *testing.T) []source {
t.Helper()
all, err := loadSources()
if err != nil {
t.Fatal(err)
}
if len(all) < 300 {
t.Fatalf("found only %d Go files: the walk no longer sees the repository", len(all))
}
return all
}
+61
View File
@@ -0,0 +1,61 @@
package archtest
import (
"go/ast"
"strings"
"testing"
)
// A function that only tests call is a second implementation the product does
// not run: delete it and test the one it does run. pkg/ is public API and
// internal/testutil exists for tests, so both are exempt. Exported methods are
// too, since interfaces and the Wails bindings call them.
func TestProductCodeHasNoUncalledFunctions(t *testing.T) {
type decl struct {
src source
fn *ast.FuncDecl
}
decls := map[string]decl{} // "<dir>.<name>"
used := map[string]bool{}
for _, s := range sources(t) {
if s.isTest() {
continue
}
imports := s.imports()
for _, d := range s.file.Decls {
fn, _ := d.(*ast.FuncDecl)
self := ""
if fn != nil {
self = s.dir() + "." + fn.Name.Name
checked := strings.HasPrefix(s.rel, "internal/") && !strings.HasPrefix(s.rel, "internal/testutil/") || strings.HasPrefix(s.rel, "cmd/")
entry := fn.Name.Name == "main" || fn.Name.Name == "init" || fn.Name.Name == "_"
if checked && !entry && (fn.Recv == nil || !fn.Name.IsExported()) {
decls[self] = decl{s, fn}
}
}
ast.Inspect(d, func(n ast.Node) bool {
switch n := n.(type) {
case *ast.SelectorExpr:
if x, ok := n.X.(*ast.Ident); ok {
if dir, ok := imports[x.Name]; ok {
used[dir+"."+n.Sel.Name] = true
return false
}
}
case *ast.Ident:
// The declaration's own name and recursion are not callers.
if key := s.dir() + "." + n.Name; key != self {
used[key] = true
}
}
return true
})
}
}
for key, d := range decls {
if !used[key] {
t.Errorf("%s: no product code calls %s", fileSet.Position(d.fn.Pos()), d.fn.Name.Name)
}
}
}
+1 -15
View File
@@ -53,7 +53,7 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *
return value, ok
},
}
router := driver.NewRouterWithDataRoot(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory())
router := driver.NewRouter(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory())
mgr.Registry().SetInUseChecker(router.PluginInUseChecker())
mgr.Registry().SetBusyChecker(router.PluginBusyChecker())
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
@@ -582,20 +582,6 @@ func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool)
return nil
}
func printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error {
hasErr := false
for _, f := range findings {
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
if f.Severity == "error" {
hasErr = true
}
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
func cmdPluginLocale(loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin locale <init|check> ...")
+1 -1
View File
@@ -122,7 +122,7 @@ func (m *Manager) SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, n
focusWait = 120 * time.Millisecond
}
return m.withConn(ctx, vmDir, func(conn qmpSession) error {
return qmp.ClickAndPasteWithActivate(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
return qmp.ClickAndPaste(ctx, conn, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
})
}
+8
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
@@ -159,3 +160,10 @@ func TestManagerQMPOperationHoldsLifecycleFileLock(t *testing.T) {
}
filelock.Unlock(lockFile)
}
func TestSendPasteShortcutComboRejectsBadComboBeforeDialing(t *testing.T) {
err := NewManager().SendPasteShortcutCombo(t.Context(), t.TempDir(), "ctrl+")
if err == nil || !strings.Contains(err.Error(), "empty key") {
t.Fatalf("err = %v", err)
}
}
+4 -1
View File
@@ -51,7 +51,10 @@ func TestV1ToV3GuestPluginMigration(t *testing.T) {
if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID {
t.Fatalf("late v1 VM marker = %q", got)
}
st := plugin.ReadState(root)
st, err := store.Load()
if err != nil {
t.Fatal(err)
}
rec := st.Plugins[guest.ID]
if rec == nil || !rec.Enabled {
t.Fatalf("guest record = %+v", rec)
+4 -1
View File
@@ -37,7 +37,10 @@ func TestUnstampedReleaseUpgradeRestoresOriginalBackup(t *testing.T) {
if got := marker(t, vmDir); got != driver.BuiltinReimsMacOSDriverID {
t.Fatalf("owner marker = %q", got)
}
st := plugin.ReadState(root)
st, err := store.Load()
if err != nil {
t.Fatal(err)
}
rec := st.Plugins[guest.ID]
if rec == nil || guest.SettingOn(rec.AppSettings, guest.SettingWHPXFallback) || guest.SettingOn(rec.AppSettings, guest.SettingInstallGuide) {
t.Fatalf("guest settings = %+v", rec)
-14
View File
@@ -5,20 +5,6 @@ import (
"github.com/Nwflower/reims-go/internal/plugin"
)
// migrateVMRefSettings qualifies legacy per-VM plugin settings with the only
// driver that existed before VMRef. Existing qualified keys win field by field.
func migrateVMRefSettings(dataRoot string) error {
store := plugin.NewStateStore(plugin.NewPluginsLayout(dataRoot).Root)
st, err := store.Load()
if err != nil {
return err
}
if migrateVMRefSettingsState(st) {
return store.Save(st)
}
return nil
}
func migrateVMRefSettingsState(st *plugin.StateFile) bool {
changed := false
for _, rec := range st.Plugins {
+4 -1
View File
@@ -28,7 +28,10 @@ func TestV3MigratesVMSettingsToVMRefKeys(t *testing.T) {
if err != nil || res.From != 2 || res.To != 3 {
t.Fatalf("Run = %+v, %v", res, err)
}
st := plugin.ReadState(root)
st, err := store.Load()
if err != nil {
t.Fatal(err)
}
vals := st.Plugins["test.plugin"].VMSettings[key]
if vals["legacy"] != true || vals["priority"] != "new" {
t.Fatalf("merged settings = %+v", vals)
+6 -15
View File
@@ -316,11 +316,10 @@ const HostedReportMaxAge = 15 * time.Second
// Router aggregates active guest drivers from the plugin Registry and routes
// VM operations by ownership (§5.3).
type Router struct {
reg *plugin.Registry
dataRootDir func() string // DataRoot for statically declared guest VM roots
legacyVMRoot func() string // compatibility root for tests and older embedders
inventories []VMInventory
states *StateTable
reg *plugin.Registry
dataRootDir func() string // DataRoot for statically declared guest VM roots
inventories []VMInventory
states *StateTable
}
// SetStateTable attaches the table of driver-reported VM states that
@@ -345,14 +344,9 @@ type VMInventory struct {
List func(dataRoot string) ([]VMInfo, error)
}
// NewRouter creates a driver Router backed by reg.
func NewRouter(reg *plugin.Registry, vmRootDir func() string) *Router {
return &Router{reg: reg, legacyVMRoot: vmRootDir}
}
// NewRouterWithDataRoot discovers unavailable VMs through driver inventories
// NewRouter discovers unavailable VMs through driver inventories
// or through ownership markers in declared roots.
func NewRouterWithDataRoot(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router {
func NewRouter(reg *plugin.Registry, dataRootDir func() string, inventories ...VMInventory) *Router {
return &Router{reg: reg, dataRootDir: dataRootDir, inventories: inventories}
}
@@ -379,9 +373,6 @@ func (rt *Router) vmRoots() []string {
}
}
}
if rt != nil && rt.legacyVMRoot != nil {
add(rt.legacyVMRoot())
}
return roots
}
+42 -20
View File
@@ -16,25 +16,43 @@ type fakeDriver struct {
vms []VMInfo
}
func (f *fakeDriver) ID() string { return f.id }
func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} }
func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" }
func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} }
func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil }
func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) { return VMInfo{Name: n, DriverID: f.id}, nil }
func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) { return StartResult{}, nil }
func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) ID() string { return f.id }
func (f *fakeDriver) DisplayName() plugin.LocalizedText { return plugin.LocalizedText{EnUS: f.id} }
func (f *fakeDriver) RuntimeKind() string { return "qemu-ovmf" }
func (f *fakeDriver) RuntimeAPIRange() string { return "^1.0.0" }
func (f *fakeDriver) Capabilities() []string { return []string{CapCloudInit, CapSSH} }
func (f *fakeDriver) CreateSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) SettingsSchema() *plugin.SettingsSchema { return nil }
func (f *fakeDriver) List(context.Context) ([]VMInfo, error) { return f.vms, nil }
func (f *fakeDriver) Show(_ context.Context, n string) (VMInfo, error) {
return VMInfo{Name: n, DriverID: f.id}, nil
}
func (f *fakeDriver) ValidateCreate(context.Context, CreateRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Create(context.Context, CreateRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) ValidateSet(context.Context, SetRequest) []ValidationIssue { return nil }
func (f *fakeDriver) Set(context.Context, SetRequest, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Start(context.Context, StartRequest) (StartResult, error) {
return StartResult{}, nil
}
func (f *fakeDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func (f *fakeDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
// declareVMRoot registers an installed but disabled driver plugin that keeps
// its VMs in <dataRoot>/vms.
func declareVMRoot(t *testing.T, reg *plugin.Registry, driverID string) {
t.Helper()
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "test.disabled-driver", Version: "1.0.0",
Contributes: plugin.Contributes{GuestDrivers: []plugin.GuestDriverContribution{{ID: driverID, VMRoots: []string{"vms"}}}}},
Source: plugin.SourceBuiltin,
}); err != nil {
t.Fatal(err)
}
}
func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) {
vmRoot := t.TempDir()
dataRoot := t.TempDir()
vmRoot := filepath.Join(dataRoot, "vms")
legacyVM := filepath.Join(vmRoot, "macos-tahoe")
_ = os.MkdirAll(legacyVM, 0o755)
if got := ReadOwnerDriver(legacyVM); got != BuiltinReimsMacOSDriverID {
@@ -63,8 +81,9 @@ func TestOwnerMarkerZeroMigrationAndRouterUnavailable(t *testing.T) {
},
})
reg.Reconcile(context.Background())
declareVMRoot(t, reg, "reims.driver.linux")
router := NewRouter(reg, func() string { return vmRoot })
router := NewRouter(reg, func() string { return dataRoot })
all, err := router.ListAllVMs(context.Background())
if err != nil {
t.Fatal(err)
@@ -97,7 +116,8 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) {
RenamedDriverIDs[BuiltinReimsMacOSDriverID] = newID
t.Cleanup(func() { delete(RenamedDriverIDs, BuiltinReimsMacOSDriverID) })
vmRoot := t.TempDir()
dataRoot := t.TempDir()
vmRoot := filepath.Join(dataRoot, "vms")
vmDir := filepath.Join(vmRoot, "macos-tahoe")
if err := WriteOwnerDriver(vmDir, BuiltinReimsMacOSDriverID); err != nil {
t.Fatal(err)
@@ -106,7 +126,9 @@ func TestRenamedDriverKeepsMarkedVMsVisible(t *testing.T) {
t.Fatalf("renamed owner = %q, want %q", got, newID)
}
router := NewRouter(plugin.NewRegistry(nil), func() string { return vmRoot })
reg := plugin.NewRegistry(nil)
declareVMRoot(t, reg, newID)
router := NewRouter(reg, func() string { return dataRoot })
all, err := router.ListAllVMs(context.Background())
if err != nil {
t.Fatal(err)
+1 -1
View File
@@ -57,7 +57,7 @@ func TestRouterScansDeclaredVMRoots(t *testing.T) {
}, Source: plugin.SourceBuiltin}); err != nil {
t.Fatal(err)
}
router := NewRouterWithDataRoot(reg, func() string { return dataRoot })
router := NewRouter(reg, func() string { return dataRoot })
vms, err := router.ListAllVMs(context.Background())
if err != nil || len(vms) != 1 || !vms[0].DriverUnavailable {
t.Fatalf("ListAllVMs = %+v, %v", vms, err)
-4
View File
@@ -4,10 +4,6 @@ package host
import "github.com/Nwflower/reims-go/internal/i18n"
func CheckMissingLocaleFonts(locale string) string {
return ""
}
func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string {
return ""
}
-8
View File
@@ -65,14 +65,6 @@ func hasInstalledFontFamily(name string) bool {
return fontDetectHit
}
// CheckMissingLocaleFonts checks whether Windows has at least one modern UI
// font installed for the East Asian script required by locale (detecting missing
// Windows Features-on-Demand supplemental font packages on non-CJK Windows installs).
// Returns "" when fonts are present or not needed, or a localized script label.
func CheckMissingLocaleFonts(locale string) string {
return CheckMissingLocaleFontsForUI(locale, i18n.ResolveLocale(locale))
}
// CheckMissingLocaleFontsForUI checks whether Windows has fonts for targetLocale
// and returns the localized script name in uiLocale when missing.
func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string {
-3
View File
@@ -5,9 +5,6 @@ package host
// ForegroundPID is not implemented off Windows and always reports no owner.
func ForegroundPID() uint32 { return 0 }
// FocusProcessWindow is not implemented off Windows.
func FocusProcessWindow(uint32) bool { return false }
// FocusProcessTreeWindow is not implemented off Windows.
func FocusProcessTreeWindow([]uint32) bool { return false }
-6
View File
@@ -73,12 +73,6 @@ func enumFocusWindowProc(hwnd uintptr, _ uintptr) uintptr {
return 1
}
// FocusProcessWindow finds the primary visible top-level window belonging to
// pid, restores it if minimized, and brings it to the foreground.
func FocusProcessWindow(pid uint32) bool {
return FocusProcessTreeWindow([]uint32{pid})
}
// FocusProcessTreeWindow does the same for a launcher and the child processes
// it started: the first visible top-level window of any of pids is focused.
func FocusProcessTreeWindow(pids []uint32) bool {
-8
View File
@@ -4,17 +4,9 @@ package host
import "errors"
// IsProcessWindowFullscreen is not implemented off Windows.
func IsProcessWindowFullscreen(uint32) bool { return false }
// IsProcessTreeWindowFullscreen is not implemented off Windows.
func IsProcessTreeWindowFullscreen([]uint32) bool { return false }
// ToggleProcessWindowFullscreen is not implemented off Windows.
func ToggleProcessWindowFullscreen(uint32) (bool, error) {
return false, errors.New("toggling a VM window's full screen mode is only supported on Windows")
}
// ToggleProcessTreeWindowFullscreen is not implemented off Windows.
func ToggleProcessTreeWindowFullscreen([]uint32) (bool, error) {
return false, errors.New("toggling a VM window's full screen mode is only supported on Windows")
-11
View File
@@ -168,11 +168,6 @@ func liveWindowPID(hwnd uintptr) uint32 {
return windowPID(hwnd)
}
// IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame.
func IsProcessWindowFullscreen(pid uint32) bool {
return IsProcessTreeWindowFullscreen([]uint32{pid})
}
// IsProcessTreeWindowFullscreen is IsProcessWindowFullscreen for a process tree.
func IsProcessTreeWindowFullscreen(pids []uint32) bool {
fullscreenState.prune(liveWindowPID)
@@ -200,12 +195,6 @@ func IsProcessTreeWindowFullscreen(pids []uint32) bool {
return err == nil && isBorderlessFullscreenRect(style, rect, WindowRect(monitor.Monitor))
}
// ToggleProcessWindowFullscreen switches the selected display window between
// borderless fullscreen and windowed mode.
func ToggleProcessWindowFullscreen(pid uint32) (bool, error) {
return ToggleProcessTreeWindowFullscreen([]uint32{pid})
}
// ToggleProcessTreeWindowFullscreen is ToggleProcessWindowFullscreen for a
// process tree: the display window may belong to any of pids.
func ToggleProcessTreeWindowFullscreen(pids []uint32) (bool, error) {
-8
View File
@@ -37,10 +37,6 @@ func ProbeVulkanGPUs() []GPUInfo {
return nil
}
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
func SetProcessAffinityMask(pid uint32, mask uint64) error {
return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS)
}
@@ -52,7 +48,3 @@ func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) {
func DisableProcessPowerThrottling(pid uint32) error {
return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS)
}
func EnableWHPXElevated() error {
return fmt.Errorf("WHPX elevation is only supported on Windows (current OS: %s)", runtime.GOOS)
}
+5 -22
View File
@@ -3,7 +3,6 @@
package host
import (
"context"
"encoding/binary"
"fmt"
"math/bits"
@@ -38,11 +37,11 @@ var (
)
const (
hkeyLocalMachine = 0x80000002
keyRead = 0x20019
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
hkeyLocalMachine = 0x80000002
keyRead = 0x20019
regSZ = 1
regExpandSZ = 2
regMultiSZ = 7
processSetInformation = 0x0200
processQueryLimitedInformation = 0x1000
processPowerThrottlingClass = 4
@@ -197,11 +196,6 @@ func Inspect(dataRoot string) Report {
return rep
}
// PinProcessToPCores restricts the given PID's affinity mask to the given bitmask.
func PinProcessToPCores(pid uint32, mask uint64) error {
return SetProcessAffinityMask(pid, mask)
}
// SetProcessAffinityMask sets the Win32 processor affinity mask for pid.
func SetProcessAffinityMask(pid uint32, mask uint64) error {
if mask == 0 {
@@ -273,17 +267,6 @@ func DisableProcessPowerThrottling(pid uint32) error {
return nil
}
// EnableWHPXElevated invokes a standard Windows UAC prompt to enable Windows
// Hypervisor Platform (if missing) and set hypervisorlaunchtype to auto.
func EnableWHPXElevated() error {
return SetHypervisorBootElevated(context.Background(), true)
}
func probeWHPX() WHPXState {
st, _ := probeWHPXAndFirmware()
return st
}
func probeWHPXAndFirmware() (WHPXState, bool) {
firmwareVirt := probeFirmwareVirtEnabled()
mod := syscall.NewLazyDLL("WinHvPlatform.dll")
-8
View File
@@ -157,10 +157,6 @@ func RecordPendingHypervisorBoot(dataRoot string, liveState WHPXState, enable bo
return recordPendingHypervisorBootSession(dataRoot, liveState, enable, currentBootSession())
}
func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string {
return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch})
}
func recordPendingHypervisorBootSession(dataRoot string, liveState WHPXState, enable bool, sess bootSession) string {
target := ResolvePendingHypervisorTarget(liveState, enable)
pendingBootMu.Lock()
@@ -208,10 +204,6 @@ func ReadPendingHypervisorBoot(dataRoot string, liveState WHPXState) string {
return readPendingHypervisorBootSession(dataRoot, liveState, currentBootSession())
}
func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string {
return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch})
}
func readPendingHypervisorBootSession(dataRoot string, liveState WHPXState, sess bootSession) string {
if !sess.valid() {
return ""
+9 -1
View File
@@ -104,6 +104,15 @@ func TestPendingHypervisorBootLifecycle(t *testing.T) {
}
}
// The epoch-only helpers stand in for a boot session without a volatile marker.
func recordPendingHypervisorBootAt(dataRoot string, liveState WHPXState, enable bool, bootEpoch int64) string {
return recordPendingHypervisorBootSession(dataRoot, liveState, enable, bootSession{EpochSec: bootEpoch})
}
func readPendingHypervisorBootAt(dataRoot string, liveState WHPXState, bootEpoch int64) string {
return readPendingHypervisorBootSession(dataRoot, liveState, bootSession{EpochSec: bootEpoch})
}
func TestPendingHypervisorBootUndoAcrossDataRoots(t *testing.T) {
defer func() {
pendingBootMu.Lock()
@@ -185,4 +194,3 @@ func TestPendingHypervisorBootFastRebootAndSleepResilience(t *testing.T) {
t.Fatalf("fallback fast reboot with reset TickMs must expire pending state, got %q", got)
}
}
-4
View File
@@ -68,10 +68,6 @@ func currentBootSession() bootSession {
}
}
func currentBootEpochSec() int64 {
return currentBootSession().EpochSec
}
// probeVolatileBootMarker reads the LastWriteTime of HKLM\HARDWARE\DESCRIPTION\System,
// an in-memory REG_OPTION_VOLATILE hive recreated by the Windows kernel on every OS
// boot. Unlike wall-clock minus GetTickCount64, it stays constant across S3 sleep,
+26
View File
@@ -0,0 +1,26 @@
package host
import "testing"
func TestParseCtlLine(t *testing.T) {
// Formats from reims_util.rs:480-488 and its test at :777-786.
u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB")
if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 {
t.Fatalf("percent line = %+v", u)
}
u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB")
if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 {
t.Fatalf("ctl-prefixed line = %+v", u)
}
u, _ = ParseCtlLine("downloading the installer: 300 MB")
if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 {
t.Fatalf("size line = %+v", u)
}
u, _ = ParseCtlLine("creating the disk")
if u.Kind != KindNote || u.Message != "creating the disk" {
t.Fatalf("note = %+v", u)
}
if _, ok := ParseCtlLine(" "); ok {
t.Fatal("blank line")
}
}
-17
View File
@@ -2,7 +2,6 @@ package host
import (
"encoding/binary"
"fmt"
)
// HostMemorySpec describes the host's physical memory speed and generation
@@ -13,22 +12,6 @@ type HostMemorySpec struct {
TypeName string `json:"type_name,omitempty"`
}
// FormatMemorySpec returns a concise human-readable label such as
// "6400 MHz DDR5" or "3200 MHz", or "" when speed is unknown.
func FormatMemorySpec(spec *HostMemorySpec) string {
if spec == nil || spec.SpeedMHz <= 0 {
return ""
}
name := spec.TypeName
if name == "" && spec.MemoryType > 0 {
name = SMBIOSMemoryTypeName(spec.MemoryType)
}
if name != "" {
return fmt.Sprintf("%d MHz %s", spec.SpeedMHz, name)
}
return fmt.Sprintf("%d MHz", spec.SpeedMHz)
}
// SMBIOSMemoryTypeName maps DMTF SMBIOS Type 17 Memory Type codes to short
// display names. Returns "" for unknown/unspecified codes.
func SMBIOSMemoryTypeName(code int) string {
+1 -4
View File
@@ -44,9 +44,6 @@ func TestParseSMBIOSType17DDR5ConfiguredSpeed(t *testing.T) {
if spec.SpeedMHz != 6400 || spec.MemoryType != 34 || spec.TypeName != "DDR5" {
t.Fatalf("got %+v, want 6400 MHz DDR5 (type 34)", spec)
}
if got := FormatMemorySpec(spec); got != "6400 MHz DDR5" {
t.Fatalf("FormatMemorySpec = %q, want %q", got, "6400 MHz DDR5")
}
}
func TestParseSMBIOSType17FallsBackToRatedSpeed(t *testing.T) {
@@ -86,7 +83,7 @@ func TestProbeHostMemorySpecLiveWindows(t *testing.T) {
t.Skip("Windows live SMBIOS probe test")
}
spec := probeHostMemorySpec()
t.Logf("live Windows host memory spec: %+v (%q)", spec, FormatMemorySpec(spec))
t.Logf("live Windows host memory spec: %+v", spec)
if spec != nil && (spec.SpeedMHz < 200 || spec.SpeedMHz > 65535) {
t.Fatalf("out-of-range live SpeedMHz: %+v", spec)
}
-16
View File
@@ -251,22 +251,6 @@ func resolveDiskPathFromVMToml(vmDir string) string {
return filepath.Join(vmDir, "disk.qcow2")
}
// readQCOW2VirtualSize reads the 8-byte big-endian virtual size from a QCOW2
// header (magic "QFI\xfb", version 2 or 3, size at byte offset 24).
func readQCOW2VirtualSize(path string) (uint64, bool) {
size, _, _, ok := readQCOW2HeaderMeta(path)
return size, ok
}
func readQCOW2HeaderMeta(path string) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) {
f, err := os.Open(path)
if err != nil {
return 0, false, 0, false
}
defer f.Close()
return decodeQCOW2HeaderMeta(f)
}
func decodeQCOW2HeaderMeta(f io.ReaderAt) (virtualSize uint64, extendedL2 bool, snapshotCount uint32, ok bool) {
var hdr [104]byte
n, err := f.ReadAt(hdr[:], 0)
-34
View File
@@ -76,10 +76,6 @@ var catalog = map[Locale]map[string]string{
"copy": "复制",
"copyTechInfo": "复制技术信息",
"core.preflight.whpx_irqchip_advice": "宿主不支持 nested-virt 属性且当前运行时未包含非致命降级补丁,启动虚拟机时将自动附加 kernel-irqchip=off",
"core.start.warn.offline_helper_skipped": "已跳过离线装机辅助盘挂载:{err}",
"core.start.warn.opencore_lang_failed": "未能向 OpenCore 写入客户机语言设置:{err}",
"core.start.warn.opencore_picker_failed": "未能更新 OpenCore 启动选择器配置:{err}",
"core.start.warn.whpx_irqchip_applied": "宿主拒绝了嵌套虚拟化属性,已自动启用 kernel-irqchip=off 兼容参数",
"dataRootChooseOther": "选择其他数据目录",
"dataRootChooseTitle": "选择数据目录",
"dataRootReadOnlyDetail": "详细信息",
@@ -619,7 +615,6 @@ var catalog = map[Locale]map[string]string{
"tray.menu.suspend": "挂起(&P)",
"tray.menu.toggle_fullscreen": "切换全屏",
"tray.notify.app_window_paste_retry": "剪贴板尚未同步,再试一次",
"tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态",
"tray.notify.focus_fail": "找不到 {name} 的窗口",
"tray.notify.force_stop_fail": "无法强制关机 {name}",
"tray.notify.fullscreen_fail": "无法切换 {name} 全屏",
@@ -632,8 +627,6 @@ var catalog = map[Locale]map[string]string{
"tray.notify.stop_fail": "无法关机 {name}",
"tray.notify.suspend_fail": "无法挂起 {name}",
"tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}",
"tray.running.many": "Reims-Go — {count} 台虚拟机运行中",
"tray.running.one": "Reims-Go — 1 台虚拟机运行中",
"tray.state.broken": "配置损坏",
"tray.state.resuming": "正在恢复…",
"tray.state.running": "运行中",
@@ -688,21 +681,16 @@ var catalog = map[Locale]map[string]string{
"viewLogs": "查看日志",
"vm.already_running": "{name} 已在运行中",
"vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)",
"vm.compact.stop_first": "请先停止 {name} 再回收磁盘空间",
"vm.empty": "当前没有已创建的虚拟机。",
"vm.install_guide.step1": "1. 打开「磁盘工具」,选中「QEMU HARDDISK Media」并点「抹掉」(格式选 APFS)。",
"vm.install_guide.step2": "2. 回到「恢复」窗口,选「重新安装 macOS」,装到刚抹掉的磁盘上(中途会自动重启几次)。",
"vm.install_guide.step3": "3. 看到「设置助理」后,运行 `reims-go vm eject {name}`(或在界面点「退出恢复模式」)移除安装盘,下次启动生效。",
"vm.install_guide.title": "macOS 装机步骤(简体中文恢复界面):",
"vm.resize.done": "{name}:虚拟磁盘已扩容 {before, number, .0} GB -> {after, number, .0} GB\n请在 macOS 终端执行以下命令扩展 APFS 容器:\n {cmd}",
"vm.resize.stop_first": "请先停止 {name} 再扩容虚拟磁盘",
"vm.typed": "{count, plural, other {已敲入 # 个键。}}",
"vmstart.compat.nested_virt": "[兼容] 当前 Windows 不支持嵌套虚拟化属性({code}),已自动启用 kernel-irqchip=off",
"vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。",
"vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。",
"vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)",
"vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)",
"vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿",
"window.close.description": "关机将请求系统关闭。挂起会保存当前会话。",
"window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"window.close.suspend": "挂起",
@@ -781,10 +769,6 @@ var catalog = map[Locale]map[string]string{
"copy": "Copy",
"copyTechInfo": "Copy technical details",
"core.preflight.whpx_irqchip_advice": "Host lacks nested-virt property and runtime lacks nested-virt-nonfatal capability; kernel-irqchip=off will be auto-applied",
"core.start.warn.offline_helper_skipped": "Offline install helper disk skipped: {err}",
"core.start.warn.opencore_lang_failed": "Could not apply macOS language to OpenCore: {err}",
"core.start.warn.opencore_picker_failed": "Could not update OpenCore boot picker: {err}",
"core.start.warn.whpx_irqchip_applied": "Host rejects nested-virtualization property; enabled kernel-irqchip=off automatically",
"dataRootChooseOther": "Choose another data folder",
"dataRootChooseTitle": "Choose data folder",
"dataRootReadOnlyDetail": "Details",
@@ -1324,7 +1308,6 @@ var catalog = map[Locale]map[string]string{
"tray.menu.suspend": "Sus&pend",
"tray.menu.toggle_fullscreen": "Toggle full screen",
"tray.notify.app_window_paste_retry": "Clipboard is still syncing. Try pasting again",
"tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}",
"tray.notify.focus_fail": "Couldn't find the window of {name}",
"tray.notify.force_stop_fail": "Couldn't force shut down {name}",
"tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}",
@@ -1337,8 +1320,6 @@ var catalog = map[Locale]map[string]string{
"tray.notify.stop_fail": "Couldn't shut down {name}",
"tray.notify.suspend_fail": "Couldn't suspend {name}",
"tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}",
"tray.running.many": "Reims-Go — {count} VMs running",
"tray.running.one": "Reims-Go — 1 VM running",
"tray.state.broken": "Broken",
"tray.state.resuming": "Resuming…",
"tray.state.running": "Running",
@@ -1393,21 +1374,16 @@ var catalog = map[Locale]map[string]string{
"viewLogs": "View logs",
"vm.already_running": "{name} is already running",
"vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)",
"vm.compact.stop_first": "stop {name} before compacting its disk",
"vm.empty": "No virtual machines found.",
"vm.install_guide.step1": "1. Open 'Disk Utility', select 'QEMU HARDDISK Media', and Erase as APFS.",
"vm.install_guide.step2": "2. Back in the Recovery window, choose 'Reinstall macOS' and install onto the disk you erased (it restarts a few times).",
"vm.install_guide.step3": "3. When Setup Assistant appears, run `reims-go vm eject {name}` (or click 'Exit recovery mode') to remove the installer at next start.",
"vm.install_guide.title": "macOS Setup Steps (Recovery UI):",
"vm.resize.done": "{name}: expanded disk {before, number, .0} GB -> {after, number, .0} GB\nRun inside macOS Terminal to expand APFS:\n {cmd}",
"vm.resize.stop_first": "stop {name} before resizing its disk",
"vm.typed": "{count, plural, one {Typed # key.} other {Typed # keys.}}",
"vmstart.compat.nested_virt": "[compat] Host rejects nested-virtualization property ({code}); enabled kernel-irqchip=off automatically",
"vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.",
"vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.",
"vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)",
"vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)",
"vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall",
"window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.",
"window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.",
"window.close.suspend": "Suspend",
@@ -1438,9 +1414,6 @@ var paramOrder = map[string][]string{
"cli.start.spawning_tray": {"name"},
"cli.start.timeout": {"name", "timeout"},
"compat.gpu_icd_rebound": {"old", "new"},
"core.start.warn.offline_helper_skipped": {"err"},
"core.start.warn.opencore_lang_failed": {"err"},
"core.start.warn.opencore_picker_failed": {"err"},
"doctor.cow_chain.broken": {"vm", "depth", "path"},
"doctor.cow_chain.item": {"vm", "depth", "warn"},
"doctor.ecores.detail": {"count", "cpus"},
@@ -1574,7 +1547,6 @@ var paramOrder = map[string][]string{
"toastInstallerReady": {"v"},
"toastRuntimeReady": {"v"},
"toastSSHConfigWritten": {"alias"},
"tray.notify.discard_suspend_fail": {"name"},
"tray.notify.focus_fail": {"name"},
"tray.notify.force_stop_fail": {"name"},
"tray.notify.fullscreen_fail": {"name"},
@@ -1585,7 +1557,6 @@ var paramOrder = map[string][]string{
"tray.notify.stop_fail": {"name"},
"tray.notify.suspend_fail": {"name"},
"tray.running": {"count"},
"tray.running.many": {"count"},
"updateCapsuleAvailable": {"v"},
"updateCapsuleDownloadingPct": {"p"},
"updateCapsuleReady": {"v"},
@@ -1602,14 +1573,9 @@ var paramOrder = map[string][]string{
"validate.name_taken": {"name"},
"vm.already_running": {"name"},
"vm.compact.done": {"name", "before", "after", "saved"},
"vm.compact.stop_first": {"name"},
"vm.install_guide.step3": {"name"},
"vm.resize.done": {"name", "before", "after", "cmd"},
"vm.resize.stop_first": {"name"},
"vm.typed": {"count"},
"vmstart.compat.nested_virt": {"code"},
"vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"},
"vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"},
"vmstart.pin.skipped": {"vcpus", "pthreads"},
"window.close.title": {"name"},
}
-8
View File
@@ -95,14 +95,6 @@ func rewriteLegacyPositionalVerbs(s string) string {
return b.String()
}
// HasPluginLocale reports whether an active plugin pack provides translations for loc.
func HasPluginLocale(loc Locale) bool {
pluginCatalogMu.RLock()
_, ok := pluginCatalogs[loc]
pluginCatalogMu.RUnlock()
return ok
}
func primarySubtag(tag string) string {
s := strings.ToLower(strings.TrimSpace(tag))
if idx := strings.IndexAny(s, "-_"); idx >= 0 {
-21
View File
@@ -42,27 +42,6 @@ func SettingOn(vals map[string]any, key string) bool {
return true
}
// SettingOnInState reads a setting without starting a Manager. Explicit
// values on the new plugin win over the released former core record.
func SettingOnInState(st *plugin.StateFile, key string) bool {
if st == nil {
return true
}
for _, id := range []string{ID, builtin.IDCore} {
if rec := st.Plugins[id]; rec != nil {
if _, ok := rec.AppSettings[key]; ok {
return SettingOn(rec.AppSettings, key)
}
}
}
if key == SettingInstallGuide {
if rec := st.Plugins[LegacyInstallGuideID]; rec != nil {
return rec.Enabled
}
}
return true
}
func settingOn(cb builtin.HostCallbacks, key string) bool {
if cb.GetSetting == nil {
return true
+4 -4
View File
@@ -79,9 +79,6 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) {
}}); err != nil {
t.Fatal(err)
}
if SettingOnInState(plugin.ReadState(root), SettingWHPXFallback) {
t.Fatal("old off switch not honoured")
}
if err := MigrateFiles(root); err != nil {
t.Fatal(err)
}
@@ -94,7 +91,10 @@ func TestMigrateFilesPreservesChoicesBeforeRegistration(t *testing.T) {
if string(first) != string(second) {
t.Fatal("second migration rewrote state")
}
st := plugin.ReadState(root)
st, err := store.Load()
if err != nil {
t.Fatal(err)
}
rec := st.Plugins[ID]
if rec == nil || !rec.Enabled {
t.Fatalf("guest record = %+v", rec)
-3
View File
@@ -59,6 +59,3 @@ func percentOf(done, total int64) float64 {
}
return float64(done) * 100 / float64(total)
}
// ParseCtlLine delegates engine progress parsing to the host progress package.
func ParseCtlLine(line string) (Update, bool) { return host.ParseCtlLine(line) }
@@ -227,29 +227,6 @@ func TestListCachedSkipsHiddenFiles(t *testing.T) {
}
}
func TestParseCtlLine(t *testing.T) {
// Formats from reims_util.rs:480-488 and its test at :777-786.
u, _ := ParseCtlLine("downloading the macOS Tahoe 26 recovery image: 45% of 2.0 GB")
if u.Kind != KindProgress || u.Step != "downloading the macOS Tahoe 26 recovery image" || u.Percent != 45 || u.Total != 2_000_000_000 {
t.Fatalf("percent line = %+v", u)
}
u, _ = ParseCtlLine("macos-tahoe: downloading OpenCore 1.0.8: 5% of 11 MB")
if u.Step != "macos-tahoe: downloading OpenCore 1.0.8" || u.Total != 11_000_000 {
t.Fatalf("ctl-prefixed line = %+v", u)
}
u, _ = ParseCtlLine("downloading the installer: 300 MB")
if u.Kind != KindProgress || u.Percent != -1 || u.Done != 300_000_000 {
t.Fatalf("size line = %+v", u)
}
u, _ = ParseCtlLine("creating the disk")
if u.Kind != KindNote || u.Message != "creating the disk" {
t.Fatalf("note = %+v", u)
}
if _, ok := ParseCtlLine(" "); ok {
t.Fatal("blank line")
}
}
// TestLockExcludesReimsCtl checks the lock against the real reims-ctl: while we
// hold installers/.lock, `reims-ctl downloads delete` must refuse a file as
// "being downloaded" (downloads.rs:139-159). Runs only with REIMS_GO_TEST_CTL
+1 -1
View File
@@ -91,7 +91,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
return fmt.Errorf("source disk %s: %w", srcDisk, err)
}
rep := host.Inspect(cfg.DataRoot)
for _, issue := range reims.ValidateCreateLocalized(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) {
for _, issue := range reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) {
if issue.Field == "name" {
return fmt.Errorf("invalid clone name %q: %s", cloneName, issue.Message)
}
+2 -2
View File
@@ -225,7 +225,7 @@ func (d *ReimsMacOSDriver) ValidateCreate(_ context.Context, req driver.CreateRe
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateCreateLocalized(opts, rep, cfg.Locale)
issues := reims.ValidateCreate(opts, rep, cfg.Locale)
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
@@ -276,7 +276,7 @@ func (d *ReimsMacOSDriver) ValidateSet(ctx context.Context, req driver.SetReques
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
issues := reims.ValidateSetLocalized(opts, cur, rep, cfg.Locale)
issues := reims.ValidateSet(opts, cur, rep, cfg.Locale)
out := make([]driver.ValidationIssue, 0, len(issues))
for _, is := range issues {
out = append(out, driver.ValidationIssue{Field: is.Field, Message: is.Message})
@@ -47,17 +47,6 @@ func DriverOptimizations(rep host.Report, runtimePatches []string) []host.Optimi
return out
}
// EvaluateOptimizations preserves the existing host-page ordering.
func EvaluateOptimizations(rep host.Report, runtimePatches []string) []host.Optimization {
core := host.EvaluateCoreOptimizations(rep)
extra := DriverOptimizations(rep, runtimePatches)
if len(core) == 0 {
return extra
}
out := append([]host.Optimization{core[0]}, extra...)
return append(out, core[1:]...)
}
func (d *ReimsMacOSDriver) EvaluateOptimizations(_ context.Context, rep host.Report) []host.Optimization {
var patches []string
if _, active, err := d.startClient(); err == nil {
@@ -20,8 +20,8 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) {
win10 := host.Report{WHPX: host.WHPXReady, HasHybridCores: true, PCoreCount: 8, ECoreCount: 4, NeedsColdRebootWorkaround: true,
WHPXCaps: host.WHPXCapabilities{APICEmulation: true, KernelIrqchipAvailable: true},
RecommendedGPU: &host.GPUInfo{Name: "NVIDIA GeForce RTX 4070 Ti", Kind: host.GPUDiscrete, VulkanICD: "nv-vk64.json"}}
opts := EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"})
if o := findOpt(t, opts, "pcore_pin"); o.Status != "recommended" || !o.Supported {
opts := DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch"})
if o := findOpt(t, host.EvaluateCoreOptimizations(win10), "pcore_pin"); o.Status != "recommended" || !o.Supported {
t.Fatalf("pcore_pin = %+v", o)
}
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "win10-needs-patch" {
@@ -30,26 +30,26 @@ func TestEvaluateOptimizationsWin10AndWin11(t *testing.T) {
if o := findOpt(t, opts, "cold_reboot"); o.Status != "auto" {
t.Fatalf("cold_reboot = %+v", o)
}
opts = EvaluateOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"})
opts = DriverOptimizations(win10, []string{"qemu-whpx-win10-compat.patch", "qemu-whpx-win10-startup-ipis.patch"})
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "experimental" || !o.Supported {
t.Fatalf("patched kernel_irqchip = %+v", o)
}
win11 := host.Report{WHPX: host.WHPXReady, WHPXCaps: host.WHPXCapabilities{ModernOS: true, APICEmulation: true, KernelIrqchipAvailable: true, NestedVirtProperty: false, NestedVirtProbeError: "0x80370302"}}
opts = EvaluateOptimizations(win11, nil)
opts = DriverOptimizations(win11, nil)
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "unavailable" || o.Detail != "0x80370302" {
t.Fatalf("win11 broken nested = %+v", o)
}
if o := findOpt(t, opts, "cold_reboot"); o.Status != "unavailable" {
t.Fatalf("win11 cold_reboot = %+v", o)
}
opts = EvaluateOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"})
opts = DriverOptimizations(win11, []string{"qemu-whpx-nested-virt-nonfatal.patch"})
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported {
t.Fatalf("win11 patched = %+v", o)
}
win11.WHPXCaps.NestedVirtProperty = true
win11.WHPXCaps.NestedVirtProbeError = ""
opts = EvaluateOptimizations(win11, nil)
opts = DriverOptimizations(win11, nil)
if o := findOpt(t, opts, "kernel_irqchip"); o.Status != "recommended" || !o.Supported {
t.Fatalf("win11 full support = %+v", o)
}
+1 -1
View File
@@ -165,7 +165,7 @@ func (d *ReimsMacOSDriver) compactDiskWithOptions(ctx context.Context, name stri
}
defer releaseDisk()
cfg := d.getConfig()
res, err := reims.CompactDiskWithOptions(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr)
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), rt.BuildChildEnv(&cfg, active), diskPath, opts, stdout, stderr)
if err != nil {
return driver.DiskCompactResult{}, err
}
-15
View File
@@ -23,21 +23,6 @@ type Preset struct {
LabelEN string `json:"label_en"`
}
// Presets returns the built-in macOS prev-lang:kbd choices.
// `:0` pairs the locale with the standard US keyboard layout so terminal
// commands in macOS Recovery / Setup Assistant stay predictable; `:252` uses
// OpenCore's Pinyin layout ID.
func Presets() []Preset {
return []Preset{
{Value: "zh-Hans:0", LabelZH: "简体中文(美式键盘,推荐)", LabelEN: "Simplified Chinese (US Keyboard)"},
{Value: "zh-Hans:252", LabelZH: "简体中文(拼音键盘)", LabelEN: "Simplified Chinese (Pinyin)"},
{Value: "zh-Hant:0", LabelZH: "繁體中文(美式键盘)", LabelEN: "Traditional Chinese (US Keyboard)"},
{Value: "en-US:0", LabelZH: "English (US)", LabelEN: "English (US)"},
{Value: "ja-JP:0", LabelZH: "日本語(美式键盘)", LabelEN: "Japanese (US Keyboard)"},
{Value: "ko-KR:0", LabelZH: "한국어(美式键盘)", LabelEN: "Korean (US Keyboard)"},
}
}
// DefaultGuestLang chooses the default macOS prev-lang:kbd matching the app UI locale.
func DefaultGuestLang(locale i18n.Locale) string {
resolved := strings.ToLower(string(i18n.ResolveLocale(string(locale))))
+2 -9
View File
@@ -282,13 +282,6 @@ func TestBuildDeleteArgs(t *testing.T) {
}
}
func TestRedactLogLine(t *testing.T) {
got := RedactLogLine("mac 52:54:00:12:34:56 serial C02ABCDEFGH")
if got != "mac [redacted] serial [redacted]" {
t.Fatalf("RedactLogLine = %q", got)
}
}
func TestCleanAbortedCreateDir(t *testing.T) {
dataDir := t.TempDir()
vmDir := filepath.Join(dataDir, "reims-ctl", "vms", "macos-tahoe")
@@ -474,11 +467,11 @@ func TestDiskImportAndCoWArgs(t *testing.T) {
if conv != "convert -O qcow2 -o "+wantOpts+" in.vmdk out.qcow2" {
t.Fatalf("BuildConvertToQCOW2Args = %q", conv)
}
cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2"), " ")
cow := strings.Join(BuildCoWOverlayArgs("golden.qcow2", "cow-dev.qcow2", DefaultQCOW2CreateOptions()), " ")
if cow != "create -f qcow2 -b golden.qcow2 -F qcow2 -o "+wantOpts+" cow-dev.qcow2" {
t.Fatalf("BuildCoWOverlayArgs = %q", cow)
}
cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp"), " ")
cmp := strings.Join(BuildCompactDiskArgs("disk.qcow2", "disk.compact.tmp", DefaultQCOW2CreateOptions()), " ")
if cmp != "convert -p -f qcow2 -O qcow2 -o "+wantOpts+" disk.qcow2 disk.compact.tmp" {
t.Fatalf("BuildCompactDiskArgs = %q", cmp)
}
+8 -37
View File
@@ -223,15 +223,9 @@ func BuildResizeDiskArgs(diskPath, sizeArg string) []string {
return []string{"resize", diskPath, sizeArg}
}
// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2` arguments
// using the default qcow2 creation options.
func BuildCompactDiskArgs(srcPath, dstPath string) []string {
return BuildCompactDiskArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions())
}
// BuildCompactDiskArgsWithOptions builds `qemu-img convert -p -f qcow2 -O qcow2`
// BuildCompactDiskArgs builds `qemu-img convert -p -f qcow2 -O qcow2`
// arguments preserving explicit qcow2 creation options.
func BuildCompactDiskArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string {
func BuildCompactDiskArgs(srcPath, dstPath string, opts QCOW2CreateOptions) []string {
args := []string{"convert", "-p", "-f", "qcow2", "-O", "qcow2"}
if optStr := opts.OptionString(); optStr != "" {
args = append(args, "-o", optStr)
@@ -247,30 +241,14 @@ func NeedsDiskConversion(srcPath string) bool {
}
// BuildConvertToQCOW2Args constructs `qemu-img convert -O qcow2` arguments
// using the canonical default qcow2 creation options.
// using the default qcow2 creation options.
func BuildConvertToQCOW2Args(srcPath, dstPath string) []string {
return BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath, DefaultQCOW2CreateOptions())
}
// BuildConvertToQCOW2ArgsWithOptions constructs `qemu-img convert -O qcow2`
// arguments with explicit qcow2 creation options.
func BuildConvertToQCOW2ArgsWithOptions(srcPath, dstPath string, opts QCOW2CreateOptions) []string {
args := []string{"convert", "-O", "qcow2"}
if optStr := opts.OptionString(); optStr != "" {
args = append(args, "-o", optStr)
}
return append(args, srcPath, dstPath)
return []string{"convert", "-O", "qcow2", "-o", DefaultQCOW2CreateOptions().OptionString(), srcPath, dstPath}
}
// BuildCoWOverlayArgs constructs `qemu-img create -f qcow2 -b <backing> -F qcow2`
// arguments using the default qcow2 creation options.
func BuildCoWOverlayArgs(backingPath, overlayPath string) []string {
return BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, DefaultQCOW2CreateOptions())
}
// BuildCoWOverlayArgsWithOptions constructs `qemu-img create -f qcow2 -b <backing> -F qcow2`
// arguments with explicit qcow2 creation options inherited from the backing image.
func BuildCoWOverlayArgsWithOptions(backingPath, overlayPath string, opts QCOW2CreateOptions) []string {
func BuildCoWOverlayArgs(backingPath, overlayPath string, opts QCOW2CreateOptions) []string {
args := []string{"create", "-f", "qcow2", "-b", backingPath, "-F", "qcow2"}
if optStr := opts.OptionString(); optStr != "" {
args = append(args, "-o", optStr)
@@ -319,7 +297,7 @@ func CreateCoWOverlay(ctx context.Context, qemuImgPath string, env []string, bac
if err != nil {
return fmt.Errorf("inspect backing qcow2 options: %w", err)
}
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgsWithOptions(backingPath, overlayPath, opts)...)
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCoWOverlayArgs(backingPath, overlayPath, opts)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
@@ -372,14 +350,7 @@ func ResizeDisk(ctx context.Context, qemuImgPath string, env []string, diskPath,
}, nil
}
// CompactDisk rewrites a stopped VM's standalone qcow2 image into a freshly
// compacted sparse qcow2 file, verifies it with `qemu-img check`, and atomically
// swaps it into place to reclaim deleted/TRIMmed host disk space.
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, stdout, stderr io.Writer) (DiskCompactResult, error) {
return CompactDiskWithOptions(ctx, qemuImgPath, env, diskPath, CompactDiskOptions{}, stdout, stderr)
}
func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) {
func CompactDisk(ctx context.Context, qemuImgPath string, env []string, diskPath string, compactOpts CompactDiskOptions, stdout, stderr io.Writer) (DiskCompactResult, error) {
before, err := host.InspectDiskUsage(diskPath)
if err != nil {
return DiskCompactResult{}, fmt.Errorf("inspect disk %s: %w", diskPath, err)
@@ -420,7 +391,7 @@ func CompactDiskWithOptions(ctx context.Context, qemuImgPath string, env []strin
_ = os.Remove(tmpPath)
defer os.Remove(tmpPath)
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgsWithOptions(diskPath, tmpPath, opts)...)
cmd := exec.CommandContext(ctx, qemuImgPath, BuildCompactDiskArgs(diskPath, tmpPath, opts)...)
configureCmd(cmd)
cmd.Env = env
if stdout != nil {
+4 -4
View File
@@ -62,8 +62,8 @@ func TestDiskRewriteRefusesSnapshotsAndBackingFiles(t *testing.T) {
if err := os.WriteFile(disk, hdr, 0o644); err != nil {
t.Fatal(err)
}
_, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, nil, nil)
_, optimizeErr := CompactDiskWithOptions(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil)
_, compactErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{}, nil, nil)
_, optimizeErr := CompactDisk(context.Background(), missingQemuImg, nil, disk, CompactDiskOptions{EnableExtendedL2: true}, nil, nil)
for _, err := range []error{compactErr, optimizeErr} {
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("rewrite error = %v, want %q", err, want)
@@ -331,7 +331,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) {
if res.NewVirtualBytes != 128<<20 {
t.Fatalf("NewVirtualBytes = %d, want %d", res.NewVirtualBytes, 128<<20)
}
cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, nil, nil)
cmp, err := CompactDisk(context.Background(), qemuImg, nil, disk, CompactDiskOptions{}, nil, nil)
if err != nil {
t.Fatalf("CompactDisk: %v", err)
}
@@ -355,7 +355,7 @@ func TestResizeAndCompactRealQemuImg(t *testing.T) {
t.Fatalf("unexpected beforeOpts: %+v", beforeOpts)
}
if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, nil, nil); err != nil {
if _, err := CompactDisk(context.Background(), qemuImg, nil, customDisk, CompactDiskOptions{}, nil, nil); err != nil {
t.Fatalf("CompactDisk(custom): %v", err)
}
afterCompactOpts, err := InspectQCOW2CreateOptions(context.Background(), qemuImg, nil, customDisk)
-35
View File
@@ -127,17 +127,6 @@ type mainNetwork struct {
func isMainNetworkID(id string) bool { return id == "net0" || id == PacketBridgeID }
func setQEMUField(value, key, replacement string) string {
parts := qemuFields(value)
for i, part := range parts {
if strings.HasPrefix(part, key+"=") {
parts[i] = key + "=" + replacement
}
parts[i] = strings.ReplaceAll(parts[i], "\x00", ",,")
}
return strings.Join(parts, ",")
}
func findMainNetwork(args []string) (mainNetwork, error) {
var n mainNetwork
for i := 0; i < len(args); i++ {
@@ -435,27 +424,3 @@ func PacketBridgeUnixTokens(mac, socketPath string) ([]string, error) {
"-device", fmt.Sprintf("virtio-net-pci,netdev=%s,id=net0,mac=%s,addr=0x3", PacketBridgeID, strings.ToLower(hw.String())),
}, nil
}
// BuildPacketBridgeExtra 保留用于兼容旧版调用与回归测试。
func BuildPacketBridgeExtra(extra, generated string, port int) (string, error) {
if port < 1 || port > 65535 {
return "", networkError("packet_port", nil)
}
args, err := cleanMainNetwork(extra)
if err != nil {
return "", err
}
all, err := ShellArgs(generated)
if err != nil {
return "", err
}
actual, err := findMainNetwork(all)
if err != nil {
return "", err
}
if actual.backends != 1 || actual.devices != 1 {
return "", networkError("args_main_unknown", nil)
}
args = append(args, "-netdev", fmt.Sprintf("stream,id=%s,server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=%d,reconnect-ms=1000", PacketBridgeID, port), "-device", setQEMUField(actual.device, "netdev", PacketBridgeID))
return JoinShellArgs(args), nil
}
+2 -4
View File
@@ -66,10 +66,8 @@ func TestNetworkModesAndUnixTokens(t *testing.T) {
}
// Legacy TCP bridge detection still works for pre-upgrade running/suspended VMs.
legacy, err := BuildPacketBridgeExtra("-cpu host", "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac="+mac+",addr=0x3", 12363)
if err != nil {
t.Fatalf("BuildPacketBridgeExtra: %v", err)
}
legacy := "-cpu host -netdev stream,id=" + PacketBridgeID + ",server=off,addr.type=inet,addr.host=127.0.0.1,addr.port=12363,reconnect-ms=1000" +
" -device virtio-net-pci,netdev=" + PacketBridgeID + ",id=net0,mac=" + mac + ",addr=0x3"
if got := NetworkMode(false, legacy); got != "bridge" {
t.Fatalf("NetworkMode(legacy tcp) = %q, want bridge", got)
}
-9
View File
@@ -1,9 +0,0 @@
package reims
import "github.com/Nwflower/reims-go/internal/host"
// RedactLogLine preserves the engine package API while sharing the host redactor.
func RedactLogLine(line string) string { return host.RedactLine(line) }
// RedactText applies RedactLogLine across a multi-line text block.
func RedactText(s string) string { return host.RedactText(s) }
+4 -14
View File
@@ -215,13 +215,8 @@ func ParseSizeGB(raw string) (float64, bool) {
return v, true
}
// ValidateCreate performs pre-save validation aligned with VZVirtualMachineConfiguration.validate().
func ValidateCreate(o CreateOpts, rep host.Report) []ValidationIssue {
return ValidateCreateLocalized(o, rep, i18n.EnUS)
}
// ValidateCreateLocalized performs pre-save validation with localized issue messages.
func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue {
// ValidateCreate performs pre-save validation with localized issue messages.
func ValidateCreate(o CreateOpts, rep host.Report, loc i18n.Locale) []ValidationIssue {
var issues []ValidationIssue
if o.NetworkMode != "" && o.NetworkMode != "off" && o.NetworkMode != "nat" && o.NetworkMode != "bridge" {
issues = append(issues, ValidationIssue{Field: "network_mode", Code: "invalid_network_mode", Message: i18n.T(loc, "validate.invalid_network_mode")})
@@ -290,13 +285,8 @@ func ValidateCreateLocalized(o CreateOpts, rep host.Report, loc i18n.Locale) []V
return issues
}
// ValidateSet validates configuration edits before invoking `reims-ctl set`.
func ValidateSet(o SetOpts, current VMDetail, rep host.Report) []ValidationIssue {
return ValidateSetLocalized(o, current, rep, i18n.EnUS)
}
// ValidateSetLocalized validates configuration edits with localized issue messages.
func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue {
// ValidateSet validates configuration edits with localized issue messages.
func ValidateSet(o SetOpts, current VMDetail, rep host.Report, loc i18n.Locale) []ValidationIssue {
var issues []ValidationIssue
if strings.TrimSpace(o.Name) == "" {
issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")})
-15
View File
@@ -206,21 +206,6 @@ func shortRev(rev string) string {
return rev
}
// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`.
func HasIncomingDeferArg(extraArgs string) bool {
tokens := splitShellTokens(extraArgs)
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" {
return true
}
if tok == "-incoming=defer" {
return true
}
}
return false
}
// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer`
// arguments from QEMU extra-args while leaving all other arguments intact.
func StripIncomingDeferArgs(existing string) string {
+2 -5
View File
@@ -90,11 +90,8 @@ func TestSuspendStateLifecycle(t *testing.T) {
}
func TestIncomingDeferArgsIdempotent(t *testing.T) {
if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") {
t.Fatal("unexpected HasIncomingDeferArg=true")
}
m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`)
if !HasIncomingDeferArg(m) {
if !strings.HasSuffix(m, " -incoming defer") {
t.Fatalf("expected -incoming defer in %q", m)
}
if m2 := MergeIncomingDeferArgs(m); m2 != m {
@@ -126,7 +123,7 @@ func TestSuspendLegacyRuntimeStillRequiresExactVersion(t *testing.T) {
}
func TestValidateSetRejectsSuspendedVM(t *testing.T) {
issues := ValidateSetLocalized(
issues := ValidateSet(
SetOpts{Name: "tahoe", CPUs: 6},
VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"},
host.Report{LogicalCPUs: 16, TotalRAMGB: 32},
@@ -4,4 +4,3 @@ package packetbridge
func AcquireBridgeStart() (func(), error) { return func() {}, nil }
func AcquireNpcapInstall() (func(), error) { return func() {}, nil }
func AcquireVMStart() (func(), error) { return func() {}, nil }
@@ -61,11 +61,6 @@ func AcquireNpcapInstall() (func(), error) {
return acquireGuard(lockPath, statePath, true)
}
// AcquireVMStart 保留向后兼容别名,语义已收敛为共享读锁(供桥接 VM 启动使用)。
func AcquireVMStart() (func(), error) {
return AcquireBridgeStart()
}
func acquireGuard(lockPath, statePath string, exclusive bool) (func(), error) {
if err := checkTrackedInstaller(statePath); err != nil {
return nil, err
+1 -1
View File
@@ -125,7 +125,7 @@ func (a *AssetServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ct = "image/svg+xml; charset=utf-8"
data = SanitizeSVG(data)
} else {
if err := ValidateThemeCSSSafetyInDir(string(data), filepath.Dir(fullPath)); err != nil {
if err := ValidateThemeCSSSafety(string(data), filepath.Dir(fullPath)); err != nil {
http.Error(w, "unsafe stylesheet blocked", http.StatusForbidden)
return
}
+3 -3
View File
@@ -191,7 +191,7 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) {
{"traversal-url", `.rg-p-shell { background: url("../../secret.png"); }`},
}
for _, tc := range badCSS {
if err := ValidateThemeCSSSafety(tc.css); err == nil {
if err := ValidateThemeCSSSafety(tc.css, ""); err == nil {
t.Errorf("ValidateThemeCSSSafety(%s) expected error, got nil", tc.name)
}
}
@@ -204,10 +204,10 @@ func TestValidateThemeCSSAndContributionBlocksBypasses(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "assets", "bg.png"), []byte("png"), 0o644); err != nil {
t.Fatal(err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil {
if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/bg.png"); }`, dir); err != nil {
t.Errorf("valid local asset rejected: %v", err)
}
if err := ValidateThemeCSSSafetyInDir(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil {
if err := ValidateThemeCSSSafety(`.rg-p-shell { background: url("assets/missing.png"); }`, dir); err == nil {
t.Error("missing local asset should be rejected")
}
+4 -2
View File
@@ -445,10 +445,12 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) {
}
// Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain.
stripped, changed := StripPluginFromArgs(res.ExtraArgs, reloaded, "thirdparty.tweak")
if !changed {
delete(active, "thirdparty.tweak")
after := ReconcileStartIntents(res.ExtraArgs, reloaded, active, intents[:1])
if !after.Changed {
t.Fatal("expected change on strip")
}
stripped := after.ExtraArgs
if strings.Contains(stripped, "usb-tablet") {
t.Fatalf("plugin fragment not stripped: %q", stripped)
}
-13
View File
@@ -596,19 +596,6 @@ func reconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlu
return res
}
// StripPluginFromArgs removes all fragments owned by pluginID from currentExtraArgs
// and updates ledger, leaving user args and other plugins' args intact.
func StripPluginFromArgs(currentExtraArgs string, ledger *ArgLedger, pluginID string) (string, bool) {
if ledger == nil || len(ledger.Owners[pluginID]) == 0 {
return strings.TrimSpace(currentExtraArgs), false
}
sub := &ArgLedger{Owners: map[string][]ArgFragment{pluginID: ledger.Owners[pluginID]}}
tokens := stripOwnedTokens(SplitShellTokens(currentExtraArgs), sub)
delete(ledger.Owners, pluginID)
next := strings.TrimSpace(strings.Join(tokens, " "))
return next, next != strings.TrimSpace(currentExtraArgs)
}
func fragWins(candidate, existing ArgFragment) bool {
if candidate.Builtin != existing.Builtin {
return candidate.Builtin
+1 -1
View File
@@ -1326,7 +1326,7 @@ func (m *Manager) ActiveThemePayload() ActiveThemePayload {
if installDir != "" && th.Stylesheet != "" {
if full, err := safeJoin(installDir, th.Stylesheet); err == nil {
if raw, err := os.ReadFile(full); err == nil {
if ValidateThemeCSSSafetyInDir(string(raw), filepath.Dir(full)) == nil {
if ValidateThemeCSSSafety(string(raw), filepath.Dir(full)) == nil {
payload.CSS = string(raw)
}
}
+5 -5
View File
@@ -19,7 +19,7 @@ import (
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
@@ -148,7 +148,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
RedactFn: reims.RedactText,
RedactFn: host.RedactText,
})
if err != nil {
t.Fatal(err)
@@ -268,7 +268,7 @@ func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
// 4. Market redline: reject Apple .ipsw inside zip.
redlineZip := makePluginZip(t, map[string][]byte{
"plugin.json": manifestJSON,
"plugin.json": manifestJSON,
"Universal.ipsw": []byte("nope"),
}, nil, false)
if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil {
@@ -289,7 +289,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
dataRoot := t.TempDir()
layout := plugin.NewPluginsLayout(dataRoot)
reg := plugin.NewRegistry(nil)
broker := plugin.NewBroker(layout, reg, reims.RedactText)
broker := plugin.NewBroker(layout, reg, host.RedactText)
notified := make(chan string, 1)
broker.SetNotifier(func(pid, title, body string) {
@@ -361,7 +361,7 @@ func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
}
// 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1).
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText)
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", host.RedactText)
if len(diags) != 1 {
t.Fatalf("expected 1 diag entry, got %d", len(diags))
}
+7 -7
View File
@@ -403,7 +403,7 @@ func ScanDirectory(dir, hostVersion string, opts ScanOptions) ScanReport {
if ext == ".css" && !declaredThemeCSS[rel] && !inRelDir(rel, declaredPanelDir) && info.Size() <= maxScanTextBytes {
if b, rErr := os.ReadFile(full); rErr == nil {
if err := ValidateThemeCSSSafetyInDir(string(b), filepath.Dir(full)); err != nil {
if err := ValidateThemeCSSSafety(string(b), filepath.Dir(full)); err != nil {
addHard("theme-css", rel, fmt.Sprintf("unsafe CSS %s: %v", rel, err),
fmt.Sprintf("样式文件 %s 未通过安全校验:%v", rel, err),
fmt.Sprintf("Stylesheet %s failed safety check: %v", rel, err))
@@ -843,12 +843,12 @@ func describePermission(perm string) (LocalizedText, LocalizedText) {
if strings.HasPrefix(perm, "net:") {
host := strings.TrimPrefix(perm, "net:")
return LocalizedText{
ZhCN: "访问指定网络主机",
EnUS: "Access declared network host",
}, LocalizedText{
ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host),
EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host),
}
ZhCN: "访问指定网络主机",
EnUS: "Access declared network host",
}, LocalizedText{
ZhCN: fmt.Sprintf("允许向 %s 发起网络请求。", host),
EnUS: fmt.Sprintf("Allows outbound network requests to %s.", host),
}
}
switch perm {
case "ui:script":
-12
View File
@@ -145,18 +145,6 @@ func (s *StateStore) Save(st *StateFile) error {
return nil
}
// ReadState reads `<dataRoot>/plugins/state.json` without starting a Manager,
// for processes such as `vm start` that only need a setting or two. It returns
// nil when the file is unreadable; callers then use their defaults, as the
// GUI's Manager does.
func ReadState(dataRoot string) *StateFile {
st, err := NewStateStore(NewPluginsLayout(dataRoot).Root).Load()
if err != nil {
return nil
}
return st
}
// --- Safe-mode startup sentinel (§9) ---
// SentinelPath returns `<DataRoot>/plugins/.startup-sentinel`.
+11 -17
View File
@@ -12,26 +12,20 @@ import (
)
var (
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
reTokenKey = regexp.MustCompile(`^--[a-z0-9][a-z0-9-]*$`)
reSafeFontFamily = regexp.MustCompile(`^[\p{L}\p{N} _-]{1,80}$`)
reFontWeight = regexp.MustCompile(`^[0-9a-zA-Z\s-]+$`)
reFontStyle = regexp.MustCompile(`^(normal|italic|oblique(\s+-?[0-9]+(\.[0-9]+)?deg)?)$`)
reUnicodeRange = regexp.MustCompile(`^[U+0-9a-fA-F?,\s-]+$`)
reSafeAssetRel = regexp.MustCompile(`^[a-zA-Z0-9._/@ -]+$`)
reSchemePrefix = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9+.-]*:`)
)
// ValidateThemeCSSSafety rejects unbalanced braces, unclosed strings/comments,
// CSS-escaped url()/image-set()/expression() bypasses, remote @import, and
// external or unsafe data: URLs.
func ValidateThemeCSSSafety(css string) error {
return ValidateThemeCSSSafetyInDir(css, "")
}
// ValidateThemeCSSSafetyInDir performs ValidateThemeCSSSafety and, when rootDir
// is non-empty, also verifies that every relative url()/@import resolves to an
// existing file inside rootDir.
func ValidateThemeCSSSafetyInDir(css, rootDir string) error {
// external or unsafe data: URLs. When rootDir is non-empty, every relative
// url()/@import must also resolve to an existing file inside rootDir.
func ValidateThemeCSSSafety(css, rootDir string) error {
if strings.Contains(strings.ToLower(css), "</style") {
return errors.New("theme stylesheet cannot contain </style")
}
@@ -507,7 +501,7 @@ func ValidateThemeContribution(th ThemeContribution, rootDir string) error {
}
// Relative url() inside stylesheet resolves relative to stylesheet's dir;
// verify inside package rootDir as well.
if err := ValidateThemeCSSSafetyInDir(string(cssRaw), filepath.Dir(cssPath)); err != nil {
if err := ValidateThemeCSSSafety(string(cssRaw), filepath.Dir(cssPath)); err != nil {
return fmt.Errorf("unsafe theme CSS %q: %w", th.Stylesheet, err)
}
}
-23
View File
@@ -1,7 +1,6 @@
package qmp
import (
"context"
"encoding/json"
"fmt"
)
@@ -90,28 +89,6 @@ func (c *Conn) SetBlockLatencyHistogram(id string, boundaries []uint64) error {
return c.Execute("block-latency-histogram-set", args)
}
// QueryBlockStatsVM performs a single short-lived QMP query-blockstats call
// against a running VM's qmp.sock and closes the connection immediately.
func QueryBlockStatsVM(ctx context.Context, vmDir string) ([]BlockStats, error) {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return nil, err
}
defer q.Close()
return q.QueryBlockStats()
}
// SetBlockLatencyHistogramVM performs a single short-lived QMP
// block-latency-histogram-set call against a running VM's qmp.sock.
func SetBlockLatencyHistogramVM(ctx context.Context, vmDir, id string, boundaries []uint64) error {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer q.Close()
return q.SetBlockLatencyHistogram(id, boundaries)
}
// FindBlockStats locates a block device entry by device name, qdev, or node-name.
func FindBlockStats(entries []BlockStats, name string) (BlockStats, bool) {
for _, e := range entries {
-8
View File
@@ -2,7 +2,6 @@ package qmp
import (
"reflect"
"strings"
"testing"
)
@@ -36,10 +35,3 @@ func TestParseKeyCombo(t *testing.T) {
}
}
}
func TestSendPasteShortcutComboRejectsBadComboBeforeDialing(t *testing.T) {
err := SendPasteShortcutCombo(t.Context(), t.TempDir(), "ctrl+")
if err == nil || !strings.Contains(err.Error(), "empty key") {
t.Fatalf("err = %v", err)
}
}
+2 -69
View File
@@ -253,30 +253,6 @@ func ParseKeyCombo(combo string) (key string, modifiers []string, err error) {
return key, modifiers, nil
}
// SendPasteShortcut presses Command+V (meta_l + v) in a running macOS VM over
// its QMP socket. Works in every macOS app without Accessibility permissions.
func SendPasteShortcut(ctx context.Context, vmDir string) error {
return SendPasteShortcutCombo(ctx, vmDir, DefaultPasteCombo)
}
// SendPasteShortcutCombo presses the paste combination of the guest's driver;
// an empty combo means the macOS default.
func SendPasteShortcutCombo(ctx context.Context, vmDir, combo string) error {
if strings.TrimSpace(combo) == "" {
combo = DefaultPasteCombo
}
key, modifiers, err := ParseKeyCombo(combo)
if err != nil {
return err
}
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer q.Close()
return PressCombo(ctx, q, 25*time.Millisecond, key, modifiers...)
}
func absEvent(axis string, value int) map[string]any {
return map[string]any{"type": "abs", "data": map[string]any{"axis": axis, "value": value}}
}
@@ -296,13 +272,8 @@ func clampAbsCoord(norm float64) int {
}
}
// ClickAndPaste clicks at normalized absolute coordinates and presses Command+V.
func ClickAndPaste(ctx context.Context, q Executor, normX, normY float64, clickHold, focusWait, keyHold time.Duration) error {
return ClickAndPasteWithActivate(ctx, q, normX, normY, false, 0, clickHold, focusWait, keyHold, "")
}
// ClickAndPasteWithActivate optionally activates the window before clicking the paste target.
func ClickAndPasteWithActivate(ctx context.Context, q Executor, normX, normY float64, activateClick bool, activateGap, clickHold, focusWait, keyHold time.Duration, commandKey string) error {
// ClickAndPaste optionally activates the window before clicking the paste target.
func ClickAndPaste(ctx context.Context, q Executor, normX, normY float64, activateClick bool, activateGap, clickHold, focusWait, keyHold time.Duration, commandKey string) error {
if err := ctx.Err(); err != nil {
return err
}
@@ -355,44 +326,6 @@ func leftClick(ctx context.Context, q Executor, clickHold time.Duration) error {
return nil
}
// SendAbsoluteClickAndPaste clicks and pastes through the VM's QMP socket.
func SendAbsoluteClickAndPaste(ctx context.Context, vmDir string, normX, normY float64, activateClick bool, commandKey string, focusWait time.Duration) error {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer q.Close()
if focusWait <= 0 {
focusWait = 120 * time.Millisecond
}
return ClickAndPasteWithActivate(ctx, q, normX, normY, activateClick, 550*time.Millisecond, 25*time.Millisecond, focusWait, 25*time.Millisecond, commandKey)
}
// TypeIntoVM types text into a running VM through its QMP socket and returns
// how many keys it pressed.
func TypeIntoVM(ctx context.Context, vmDir, text string, progress func(done, total int)) (int, error) {
strokes, err := Strokes(text)
if err != nil {
return 0, err
}
if len(strokes) == 0 {
return 0, fmt.Errorf("nothing to type")
}
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return 0, err
}
defer q.Close()
done := 0
err = TypeStrokes(ctx, q, strokes, 20*time.Millisecond, 15*time.Millisecond, func(n int) {
done = n
if progress != nil {
progress(n, len(strokes))
}
})
return done, err
}
func sleep(ctx context.Context, d time.Duration) {
if d <= 0 {
return
+4 -4
View File
@@ -159,7 +159,7 @@ func TestClickAndPaste(t *testing.T) {
}
t.Run("click then paste", func(t *testing.T) {
r := &clickRecorder{}
if err := ClickAndPaste(context.Background(), r, 0.5, 1, 0, 0, 0); err != nil {
if err := ClickAndPaste(context.Background(), r, 0.5, 1, false, 0, 0, 0, 0, ""); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(r.batches, want) {
@@ -168,7 +168,7 @@ func TestClickAndPaste(t *testing.T) {
})
t.Run("alt", func(t *testing.T) {
r := &clickRecorder{}
if err := ClickAndPasteWithActivate(context.Background(), r, 0.5, 1, false, 0, 0, 0, 0, "alt"); err != nil {
if err := ClickAndPaste(context.Background(), r, 0.5, 1, false, 0, 0, 0, 0, "alt"); err != nil {
t.Fatal(err)
}
wantAlt := append(want[:3:3], [][]map[string]any{
@@ -182,7 +182,7 @@ func TestClickAndPaste(t *testing.T) {
t.Run("activate then click and paste", func(t *testing.T) {
const gap = 20 * time.Millisecond
r := &clickRecorder{}
if err := ClickAndPasteWithActivate(context.Background(), r, 0.5, 1, true, gap, 0, 0, 0, ""); err != nil {
if err := ClickAndPaste(context.Background(), r, 0.5, 1, true, gap, 0, 0, 0, ""); err != nil {
t.Fatal(err)
}
wantActive := append(want[:3:3], want[1:]...)
@@ -197,7 +197,7 @@ func TestClickAndPaste(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r := &clickRecorder{cancel: cancel}
if err := ClickAndPaste(ctx, r, 0.5, 1, time.Second, 0, 0); !errors.Is(err, context.Canceled) {
if err := ClickAndPaste(ctx, r, 0.5, 1, false, 0, time.Second, 0, 0, ""); !errors.Is(err, context.Canceled) {
t.Fatalf("got %v, want context.Canceled", err)
}
if !reflect.DeepEqual(r.batches, want[:3]) {
-15
View File
@@ -103,21 +103,6 @@ func MouseButton(q Executor, button string, down bool) error {
return sendMouseButton(q, button, down)
}
// MouseClick presses and releases a mouse button as one serialized QMP job.
func MouseClick(q Executor, button string) error {
if q == nil {
return errors.New("QMP session is unavailable")
}
button = normalizeMouseButton(button)
if !validMouseButton(button) {
return fmt.Errorf("unsupported mouse button %q", button)
}
return q.Execute("input-send-event", map[string]any{"events": []any{
mouseButtonEvent(button, true),
mouseButtonEvent(button, false),
}})
}
// MouseScroll sends vertical or horizontal wheel steps. A positive delta means
// down or right, and a negative delta means up or left.
func MouseScroll(q Executor, delta int, horizontal bool) error {
-11
View File
@@ -1,7 +1,6 @@
package qmp
import (
"context"
"errors"
)
@@ -33,13 +32,3 @@ func ScreendumpDisplay(q Executor, path, device string, head int) (string, error
}
return "ppm", nil
}
// ScreendumpVM connects to a running VM's QMP socket and writes one frame.
func ScreendumpVM(ctx context.Context, vmDir, path string) (string, error) {
q, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return "", err
}
defer q.Close()
return q.Screendump(path)
}
-12
View File
@@ -167,18 +167,6 @@ func splitShellTokens(s string) []string {
return out
}
// WatchForGuestReset connects to QEMU's secondary QMP endpoint (AF_UNIX path or
// "unix:<path>"), negotiates capabilities, and waits for a SHUTDOWN event. It
// returns true iff the VM exited because the guest requested a reset
// (`reason == "guest-reset"` under `-no-reboot`).
func WatchForGuestReset(ctx context.Context, addr string) (bool, error) {
reason, err := WatchShutdownReason(ctx, addr)
if err != nil {
return false, err
}
return reason == "guest-reset", nil
}
// WatchShutdownReason waits for QEMU's SHUTDOWN event over QMP and returns its
// reason (e.g. "guest-reset", "guest-shutdown", "host-qmp-quit"), or "" on EOF.
func WatchShutdownReason(ctx context.Context, addr string) (string, error) {
+8 -16
View File
@@ -66,7 +66,7 @@ func TestRebootSocketPathFallback(t *testing.T) {
}
}
func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) {
func runMockQMPUnix(t *testing.T, eventJSON string) (string, error) {
t.Helper()
const sockPath = "reims-go-reboot.sock"
ln, err := net.Listen("unix", sockPath)
@@ -91,25 +91,17 @@ func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
return WatchForGuestReset(ctx, "unix:"+sockPath)
return WatchShutdownReason(ctx, "unix:"+sockPath)
}
func TestWatchForGuestReset(t *testing.T) {
func TestWatchShutdownReason(t *testing.T) {
// Unix socket addresses have a small byte limit. The isolated working
// directory lets the mock and watcher use the same short relative address.
t.Chdir(t.TempDir())
reset, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-reset"}}`)
if err != nil || !reset {
t.Fatalf("guest-reset: got reset=%v err=%v, want true nil", reset, err)
}
reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-shutdown"}}`)
if err != nil || reset {
t.Fatalf("guest-shutdown: got reset=%v err=%v, want false nil", reset, err)
}
reset, err = runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":false,"reason":"host-ui"}}`)
if err != nil || reset {
t.Fatalf("host-ui: got reset=%v err=%v, want false nil", reset, err)
for _, want := range []string{"guest-reset", "guest-shutdown", "host-ui"} {
got, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"`+want+`"}}`)
if err != nil || got != want {
t.Fatalf("reason = %q, %v, want %q", got, err, want)
}
}
}
+4 -11
View File
@@ -71,17 +71,10 @@ func Writable(dir string) error {
}
// Swap installs newExe at target (see Target; usually exe itself) and moves
// the running exe aside to "<exe>.old" (or a timestamped name when an earlier
// one is still locked). A file already at target is replaced. On any failure
// the original executable is left in place.
func Swap(exe, target, newExe string) error {
return SwapWithOptions(exe, target, newExe, false)
}
// SwapWithOptions behaves like Swap, except when keepOld is true it never
// deletes an existing "<exe>.old" backup (falling back to a timestamped
// ".old-<ns>" name instead).
func SwapWithOptions(exe, target, newExe string, keepOld bool) error {
// the running exe aside to "<exe>.old", or to a timestamped name when an
// earlier backup is still locked or keepOld asks to preserve it. A file already
// at target is replaced. On any failure the original executable stays in place.
func Swap(exe, target, newExe string, keepOld bool) error {
staged := target + ".new"
if err := copyFile(newExe, staged); err != nil {
os.Remove(staged)
+4 -4
View File
@@ -30,7 +30,7 @@ func TestSwapAndCleanup(t *testing.T) {
write(t, newExe, "new build")
write(t, exe+".old", "left over from an earlier update")
if err := Swap(exe, exe, newExe); err != nil {
if err := Swap(exe, exe, newExe, false); err != nil {
t.Fatal(err)
}
if got := read(t, exe); got != "new build" {
@@ -56,7 +56,7 @@ func TestSwapLeavesExeOnFailure(t *testing.T) {
dir := t.TempDir()
exe := filepath.Join(dir, "reims-go.exe")
write(t, exe, "old build")
if err := Swap(exe, exe, filepath.Join(dir, "missing.exe")); err == nil {
if err := Swap(exe, exe, filepath.Join(dir, "missing.exe"), false); err == nil {
t.Fatal("a missing download must fail")
}
if got := read(t, exe); got != "old build" {
@@ -107,7 +107,7 @@ func TestSwapRenamesReleaseFile(t *testing.T) {
write(t, newExe, "v0.2.6")
target := Target(exe, filepath.Base(newExe))
if err := Swap(exe, target, newExe); err != nil {
if err := Swap(exe, target, newExe, false); err != nil {
t.Fatal(err)
}
if got := read(t, target); got != "v0.2.6" {
@@ -138,7 +138,7 @@ func TestSwapKeepOldAndCleanupStaging(t *testing.T) {
write(t, exe+".old", "stable backup")
write(t, newExe, "new dev-2")
if err := SwapWithOptions(exe, exe, newExe, true); err != nil {
if err := Swap(exe, exe, newExe, true); err != nil {
t.Fatal(err)
}
if got := read(t, exe); got != "new dev-2" {
+1 -1
View File
@@ -34,7 +34,7 @@ func NewHarness(t *testing.T) *Harness {
broker.SetVMStateHandler(func(_ string, rep plugin.ReportedVMState) error {
return states.Report(driver.ReportedStateFromPlugin(rep))
})
router := driver.NewRouterWithDataRoot(reg, func() string { return root })
router := driver.NewRouter(reg, func() string { return root })
router.SetStateTable(states)
h := &Harness{Registry: reg, Broker: broker, Router: router, States: states, DataRoot: root,
StopFile: filepath.Join(t.TempDir(), "stop"), t: t}
+2 -14
View File
@@ -109,12 +109,6 @@ type ghAsset struct {
URL string `json:"browser_download_url"`
}
// ParseSemver parses a tag like "v0.2.1" or "0.2.1-rc1" into major/minor/patch.
func ParseSemver(v string) (major, minor, patch int, ok bool) {
major, minor, patch, _, ok = parseSemverFull(v)
return major, minor, patch, ok
}
func parseSemverFull(v string) (major, minor, patch int, pre string, ok bool) {
s := strings.TrimSpace(v)
s = strings.TrimPrefix(s, "v")
@@ -242,12 +236,6 @@ func Compare(a, b string) int {
return comparePrerelease(aPre, bPre)
}
// CheckUpdate queries GitHub Releases for the newest stable (non-draft,
// non-prerelease) application release tagged "vX.Y.Z".
func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) {
return s.CheckUpdateChannel(ctx, current, ChannelStable)
}
type releaseCandidate struct {
rel *ghRelease
ver string
@@ -322,9 +310,9 @@ func isSameBaseDevBuild(a, b string) bool {
strings.HasPrefix(strings.ToLower(bPre), "dev-")
}
// CheckUpdateChannel queries GitHub Releases for the newest eligible Reims-Go
// CheckUpdate queries GitHub Releases for the newest eligible Reims-Go
// release on the requested channel ("stable", "alpha", or "dev").
func (s Source) CheckUpdateChannel(ctx context.Context, current, channel string) (UpdateInfo, error) {
func (s Source) CheckUpdate(ctx context.Context, current, channel string) (UpdateInfo, error) {
if current == "" {
current = Version
}
+8 -8
View File
@@ -61,7 +61,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) {
defer srv.Close()
src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()}
info, err := src.CheckUpdate(context.Background(), "v0.2.1")
info, err := src.CheckUpdate(context.Background(), "v0.2.1", ChannelStable)
if err != nil {
t.Fatalf("CheckUpdate: %v", err)
}
@@ -79,7 +79,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) {
}
// Same version reports up to date.
upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2")
upToDate, err := src.CheckUpdate(context.Background(), "v0.2.2", ChannelStable)
if err != nil {
t.Fatalf("CheckUpdate(same): %v", err)
}
@@ -89,7 +89,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) {
// Prerelease of the released stable version upgrades to stable.
for _, pre := range []string{"v0.2.2-alpha.1", "v0.2.2-dev-66da194"} {
preInfo, err := src.CheckUpdate(context.Background(), pre)
preInfo, err := src.CheckUpdate(context.Background(), pre, ChannelStable)
if err != nil {
t.Fatalf("CheckUpdate(%s): %v", pre, err)
}
@@ -99,7 +99,7 @@ func TestCheckUpdateFindsNewerStableOnly(t *testing.T) {
}
// Prerelease of a newer version does not downgrade to an older stable release.
ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194")
ahead, err := src.CheckUpdate(context.Background(), "v0.2.3-dev-66da194", ChannelStable)
if err != nil {
t.Fatalf("CheckUpdate(ahead): %v", err)
}
@@ -155,7 +155,7 @@ func TestCheckUpdateChannels(t *testing.T) {
src := Source{APIBase: srv.URL, Repo: "Nwflower/Reims-Go", Client: srv.Client()}
// Stable channel ignores alpha and dev.
st, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelStable)
st, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelStable)
if err != nil {
t.Fatalf("stable: %v", err)
}
@@ -164,7 +164,7 @@ func TestCheckUpdateChannels(t *testing.T) {
}
// Alpha channel picks v0.2.9-alpha.1 (ignoring dev).
al, err := src.CheckUpdateChannel(context.Background(), "v0.2.8", ChannelAlpha)
al, err := src.CheckUpdate(context.Background(), "v0.2.8", ChannelAlpha)
if err != nil {
t.Fatalf("alpha: %v", err)
}
@@ -173,7 +173,7 @@ func TestCheckUpdateChannels(t *testing.T) {
}
// Dev channel extracts version from rolling dev asset and detects update across non-monotonic SHAs.
dv, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-fffffff", ChannelDev)
dv, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-fffffff", ChannelDev)
if err != nil {
t.Fatalf("dev: %v", err)
}
@@ -182,7 +182,7 @@ func TestCheckUpdateChannels(t *testing.T) {
}
// Dev channel reports up to date when SHA matches.
dvSame, err := src.CheckUpdateChannel(context.Background(), "v0.2.9-dev-0123456", ChannelDev)
dvSame, err := src.CheckUpdate(context.Background(), "v0.2.9-dev-0123456", ChannelDev)
if err != nil {
t.Fatalf("dev same: %v", err)
}
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more