feat(dataroot): guard data folder writes and migrations
This commit is contained in:
1 parent
2ffddf94b4
commit
6dcf33f71b
38 files changed
+1104
-128
No files matched your search
@@ -113,7 +113,9 @@ flowchart TB
|
||||
### 4.7 数据目录版本与迁移
|
||||
- `<DataRoot>\.reims-go-data.json` 记录数据布局版本 `data_version`,以及最后一次提升它的应用版本 `written_by`。它不放进 `reims-go.json`,因为配置每次保存都会按结构体整体重写,旧版本会丢掉不认识的字段。
|
||||
- 每个版本都带着从旧布局升到自身布局的全部迁移步骤(`internal/datamigrate`),GUI 与 CLI 启动时、读取数据之前按版本号依次执行。步骤必须可重复执行;某步失败时,版本号停在最后一个成功的步骤,下次启动从那里继续。用户可以从任意旧版本直接升到新版本。
|
||||
- 数据目录的版本高于本程序所知时(降级运行),不做任何改动,只记一条日志。
|
||||
- GUI 启动、首次设置、切换数据目录与 CLI 都经 `internal/dataroot` 打开数据目录:先不加锁读取版本戳,需要迁移时才取 `<DataRoot>.reims-go.lock` 并在锁内重读版本戳,两个进程同时打开同一目录时迁移只执行一次。
|
||||
- 数据目录由更新版本写入、版本戳无法解析、迁移失败或另一进程长时间持锁时,以只读模式打开,不创建或修改任何文件(包括锁文件):GUI 不启动插件、不轮询虚拟机,以只读界面代替工作台;CLI 只放行 `version`、`help` 与 `doctor`。版本戳损坏时可由用户显式修复,从 v0 重新执行全部步骤。
|
||||
- 首次设置选定目录之前,宿主不写入默认建议目录:不迁移、不启动插件、不轮询,界面中的选择只保存在内存里,由 `CompleteSetup` 写入选定的目录。
|
||||
- 只有删除很老的迁移步骤之后,才需要「最低迁移版本」:新版本根据 `data_version` 判断,并提示先安装某个中间版本。这个判断看的是数据本身,所以直接下载新版本运行也会生效。
|
||||
- 现有步骤:v1 为 reims-ctl 管理的每台 VM(目录含 `vm.toml`)补写驱动归属标记,见 [plugin-architecture.md](plugin-architecture.md) 的「VM 归属」。
|
||||
|
||||
|
||||
+14
-2
@@ -9,6 +9,7 @@ import type { ThemeMode } from './components/AppSettingsPage'
|
||||
import { LogPanel, LogTab } from './components/LogPanel'
|
||||
import { TitleMenus } from './components/TitleMenus'
|
||||
import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule'
|
||||
import { DataRootReadOnly } from './components/DataRootReadOnly'
|
||||
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar'
|
||||
import { VMAction, VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
@@ -446,6 +447,9 @@ export const App: React.FC = () => {
|
||||
setSetupStage(s?.active_runtime ? null : 'runtime')
|
||||
}
|
||||
const showSetup = !!state && (state.needs_setup || setupStage === 'runtime')
|
||||
// The data folder opened read-only (internal/dataroot): nothing in it may be
|
||||
// changed, so the workspace gives way to a screen that explains why.
|
||||
const showReadOnly = !!state && !showSetup && !!state.data_root_status?.read_only
|
||||
|
||||
// UI Contract v1 read-only document state attributes (§5.1).
|
||||
const currentView = showSetup ? 'setup' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm'
|
||||
@@ -859,7 +863,7 @@ export const App: React.FC = () => {
|
||||
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
|
||||
shortcutRef.current = (e: KeyboardEvent) => {
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
if (showSetup || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
|
||||
if (showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
|
||||
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
|
||||
const k = e.key.toLowerCase()
|
||||
if (k === 'n') { e.preventDefault(); openWizard() }
|
||||
@@ -929,7 +933,7 @@ export const App: React.FC = () => {
|
||||
<TooltipProvider>
|
||||
<div className="app-shell rg-p-shell">
|
||||
<header className="titlebar rg-p-titlebar" onDoubleClick={() => WindowToggleMaximise()}>
|
||||
{showSetup || !state ? (
|
||||
{showSetup || showReadOnly || !state ? (
|
||||
<div className="brand rg-p-brand">
|
||||
<img className="brand-mark" src="/logo.svg" alt="" aria-hidden="true" />
|
||||
Reims-Go
|
||||
@@ -1009,6 +1013,14 @@ export const App: React.FC = () => {
|
||||
onImportRuntime={importRuntime}
|
||||
/>
|
||||
</Suspense>
|
||||
) : showReadOnly && state ? (
|
||||
<DataRootReadOnly
|
||||
locale={locale}
|
||||
status={state.data_root_status}
|
||||
message={state.data_root_message ?? ''}
|
||||
onChanged={() => { void refresh() }}
|
||||
onError={fail}
|
||||
/>
|
||||
) : (
|
||||
<div className={`workspace rg-p-workspace${sidebarOpen ? '' : ' sidebar-hidden'}`}>
|
||||
{sidebarOpen && <div className="sidebar-backdrop" aria-hidden="true" onClick={toggleSidebar} />}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { FolderOpen } from 'lucide-react'
|
||||
import React, { useState } from 'react'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { AppState, Locale } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { api } from '../wails'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
status: AppState['data_root_status']
|
||||
/** Localized reason from the backend (dataroot.Error). */
|
||||
message: string
|
||||
/** The folder changed or reopened; the app reloads its state. */
|
||||
onChanged: () => void
|
||||
onError: (title: string, e: unknown) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown instead of the workspace while the data folder is open read-only
|
||||
* (written by a newer release, damaged version record, failed or concurrent
|
||||
* upgrade). Nothing in the folder has been changed; the user can repair it,
|
||||
* try again, or pick another folder.
|
||||
*/
|
||||
export const DataRootReadOnly: React.FC<Props> = ({ locale, status, message, onChanged, onError }) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const [busy, setBusy] = useState<'' | 'repair' | 'retry' | 'choose'>('')
|
||||
|
||||
const run = async (kind: 'repair' | 'retry' | 'choose', fn: () => Promise<unknown>) => {
|
||||
setBusy(kind)
|
||||
try {
|
||||
await fn()
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
onError(tr('failGeneric'), e)
|
||||
} finally {
|
||||
setBusy('')
|
||||
}
|
||||
}
|
||||
|
||||
const choose = () => run('choose', async () => {
|
||||
const dir = await api.PickDirectory(tr('dataRootChooseTitle'))
|
||||
if (dir) await api.SetDataRoot(dir)
|
||||
})
|
||||
|
||||
const canRepair = status.reason === 'damaged'
|
||||
const canRetry = status.reason === 'busy' || status.reason === 'migration_failed'
|
||||
|
||||
return (
|
||||
<div className="setup">
|
||||
<div className="setup-card">
|
||||
<div className="setup-head">
|
||||
<h1>{tr('dataRootReadOnlyTitle')}</h1>
|
||||
<p>{message}</p>
|
||||
</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('dataRootReadOnlyFolder')}</div>
|
||||
<div className="row-sub mono selectable">{status.dir}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{status.detail && (
|
||||
<details className="dataroot-detail">
|
||||
<summary>{tr('dataRootReadOnlyDetail')}</summary>
|
||||
<pre className="mono selectable">{status.detail}</pre>
|
||||
</details>
|
||||
)}
|
||||
<div className="setup-foot">
|
||||
<span className="hstack">
|
||||
{canRepair && (
|
||||
<Button busy={busy === 'repair'} disabled={!!busy} onClick={() => void run('repair', () => api.ReopenDataRoot(true))}>
|
||||
{tr('dataRootRepair')}
|
||||
</Button>
|
||||
)}
|
||||
{canRetry && (
|
||||
<Button busy={busy === 'retry'} disabled={!!busy} onClick={() => void run('retry', () => api.ReopenDataRoot(false))}>
|
||||
{tr('dataRootRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
<Button variant="primary" icon={<FolderOpen size={14} aria-hidden="true" />} busy={busy === 'choose'} disabled={!!busy} onClick={() => void choose()}>
|
||||
{tr('dataRootChooseOther')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -14,6 +14,13 @@ export const coreZh: Record<string, string> = {
|
||||
"collapseLogs": "收起日志",
|
||||
"copy": "复制",
|
||||
"copyTechInfo": "复制技术信息",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
"dataRootChooseTitle": "选择数据目录",
|
||||
"dataRootReadOnlyDetail": "详细信息",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
@@ -196,6 +203,13 @@ export const coreEn: Record<string, string> = {
|
||||
"collapseLogs": "Hide logs",
|
||||
"copy": "Copy",
|
||||
"copyTechInfo": "Copy technical details",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
"dataRootChooseTitle": "Choose data folder",
|
||||
"dataRootReadOnlyDetail": "Details",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
|
||||
@@ -123,6 +123,13 @@ export type I18nKey =
|
||||
| "cpuRecHint"
|
||||
| "createNow"
|
||||
| "createStartedHint"
|
||||
| "dataRootChooseOther"
|
||||
| "dataRootChooseTitle"
|
||||
| "dataRootReadOnlyDetail"
|
||||
| "dataRootReadOnlyFolder"
|
||||
| "dataRootReadOnlyTitle"
|
||||
| "dataRootRepair"
|
||||
| "dataRootRetry"
|
||||
| "delete"
|
||||
| "deleteConfirm"
|
||||
| "deleteDesc"
|
||||
|
||||
@@ -1256,6 +1256,14 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
.setup-head h1 { font-size: var(--fs-24); font-weight: var(--fw-strong); letter-spacing: -0.02em; text-wrap: balance; }
|
||||
.setup-head p { margin-top: var(--sp-1); color: var(--text-2); font-size: var(--fs-14); }
|
||||
.setup-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); }
|
||||
/* Read-only data folder screen (DataRootReadOnly) */
|
||||
.dataroot-detail { font-size: var(--fs-12); color: var(--text-2); }
|
||||
.dataroot-detail summary { cursor: pointer; }
|
||||
.dataroot-detail pre {
|
||||
margin: var(--sp-2) 0 0; padding: var(--sp-3); border-radius: var(--r-md);
|
||||
background: var(--surface-1); border: 1px solid var(--border);
|
||||
white-space: pre-wrap; word-break: break-word; max-height: 160px; overflow: auto;
|
||||
}
|
||||
/* First-run offer of a market language pack for the OS language */
|
||||
.setup-langpack {
|
||||
display: flex; align-items: center; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4);
|
||||
|
||||
Vendored
+3
@@ -8,6 +8,7 @@ import {driver} from '../models';
|
||||
import {runtime} from '../models';
|
||||
import {installer} from '../models';
|
||||
import {http} from '../models';
|
||||
import {dataroot} from '../models';
|
||||
|
||||
export function ApplyVMSettings(arg1:reims.SetOpts):Promise<void>;
|
||||
|
||||
@@ -177,6 +178,8 @@ export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
|
||||
export function RemoveRuntime(arg1:string):Promise<void>;
|
||||
|
||||
export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
|
||||
|
||||
export function RequestClose():Promise<void>;
|
||||
|
||||
export function ResizeVMDisk(arg1:string,arg2:string):Promise<reims.DiskResizeResult>;
|
||||
|
||||
@@ -338,6 +338,10 @@ export function RemoveRuntime(arg1) {
|
||||
return window['go']['app']['App']['RemoveRuntime'](arg1);
|
||||
}
|
||||
|
||||
export function ReopenDataRoot(arg1) {
|
||||
return window['go']['app']['App']['ReopenDataRoot'](arg1);
|
||||
}
|
||||
|
||||
export function RequestClose() {
|
||||
return window['go']['app']['App']['RequestClose']();
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ export namespace app {
|
||||
active_guides?: string[];
|
||||
install_guide_enabled?: boolean;
|
||||
needs_setup: boolean;
|
||||
data_root_status: dataroot.Status;
|
||||
data_root_message?: string;
|
||||
app_version: string;
|
||||
safe_mode?: boolean;
|
||||
plugin_crash_detected?: boolean;
|
||||
@@ -36,6 +38,8 @@ export namespace app {
|
||||
this.active_guides = source["active_guides"];
|
||||
this.install_guide_enabled = source["install_guide_enabled"];
|
||||
this.needs_setup = source["needs_setup"];
|
||||
this.data_root_status = this.convertValues(source["data_root_status"], dataroot.Status);
|
||||
this.data_root_message = source["data_root_message"];
|
||||
this.app_version = source["app_version"];
|
||||
this.safe_mode = source["safe_mode"];
|
||||
this.plugin_crash_detected = source["plugin_crash_detected"];
|
||||
@@ -489,6 +493,35 @@ export namespace config {
|
||||
|
||||
}
|
||||
|
||||
export namespace dataroot {
|
||||
|
||||
export class Status {
|
||||
dir: string;
|
||||
read_only: boolean;
|
||||
reason?: string;
|
||||
detail?: string;
|
||||
version: number;
|
||||
known: number;
|
||||
migrated?: string[];
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new Status(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.dir = source["dir"];
|
||||
this.read_only = source["read_only"];
|
||||
this.reason = source["reason"];
|
||||
this.detail = source["detail"];
|
||||
this.version = source["version"];
|
||||
this.known = source["known"];
|
||||
this.migrated = source["migrated"];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export namespace driver {
|
||||
|
||||
export class CreateRequest {
|
||||
|
||||
+50
-9
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
@@ -51,8 +52,12 @@ type AppState struct {
|
||||
// InstallGuideEnabled is true while the builtin.install-guide plugin is active.
|
||||
InstallGuideEnabled bool `json:"install_guide_enabled,omitempty"`
|
||||
// NeedsSetup is true on first launch, until a data folder is chosen (setup.go).
|
||||
NeedsSetup bool `json:"needs_setup"`
|
||||
AppVersion string `json:"app_version"`
|
||||
NeedsSetup bool `json:"needs_setup"`
|
||||
// DataRoot says how the data folder opened; read_only means the app shows
|
||||
// the read-only screen instead of the workspace (dataroot_flow.go).
|
||||
DataRoot dataroot.Status `json:"data_root_status"`
|
||||
DataRootMessage string `json:"data_root_message,omitempty"` // why it is read-only, localized
|
||||
AppVersion string `json:"app_version"`
|
||||
SafeMode bool `json:"safe_mode,omitempty"`
|
||||
PluginCrashDetected bool `json:"plugin_crash_detected,omitempty"`
|
||||
DetectedLocale string `json:"detected_locale,omitempty"`
|
||||
@@ -85,6 +90,7 @@ type App struct {
|
||||
procSamples map[string]host.ProcessSample
|
||||
recentLogs []string
|
||||
needsSetup bool
|
||||
root dataroot.Status // how the current data folder opened (dataroot_flow.go)
|
||||
launch cli.WindowArgs // flags this window was started with (window_launch.go)
|
||||
trayIcon []byte // embedded PNG passed in from package main
|
||||
logCaptures map[string][]*logCapture // emitLog source → captures (window_launch.go)
|
||||
@@ -142,6 +148,14 @@ func (a *App) startup(ctx context.Context) {
|
||||
a.stopPoll = cancel
|
||||
a.bindGuideEvents(ctx)
|
||||
a.startTray()
|
||||
a.mu.Lock()
|
||||
needsSetup := a.needsSetup
|
||||
a.mu.Unlock()
|
||||
// Before first-run setup there is no chosen folder to open; CompleteSetup
|
||||
// opens the one the user picks and starts plugins then.
|
||||
if !needsSetup {
|
||||
a.openDataRoot()
|
||||
}
|
||||
a.initPlugins()
|
||||
// Without a plugin manager, run the IME bridge and Guest Tools directly.
|
||||
// With one, their plugins own them, and a plugin switched off stays off.
|
||||
@@ -150,7 +164,9 @@ func (a *App) startup(ctx context.Context) {
|
||||
a.mu.Unlock()
|
||||
if !pluginsUp {
|
||||
a.startIMEBridge()
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
if a.dataRootUsable() {
|
||||
go a.registerExistingGuestTools(pollCtx)
|
||||
}
|
||||
}
|
||||
go a.finishAppUpdate()
|
||||
a.startUIHealthWatchdog(pollCtx)
|
||||
@@ -258,6 +274,11 @@ func (a *App) pollVMs(ctx context.Context) {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
timer.Reset(next)
|
||||
// reims-ctl keeps its state in the data folder; leave it alone until
|
||||
// setup has chosen one, and while it is open read-only.
|
||||
if !a.dataRootUsable() {
|
||||
continue
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
continue
|
||||
@@ -610,6 +631,7 @@ func (a *App) GetState() AppState {
|
||||
pcCopy[k] = append([]PendingChange(nil), v...)
|
||||
}
|
||||
needsSetup := a.needsSetup
|
||||
rootStatus := a.root
|
||||
a.mu.Unlock()
|
||||
|
||||
rep := host.Inspect(cfgCopy.DataRoot)
|
||||
@@ -656,6 +678,8 @@ func (a *App) GetState() AppState {
|
||||
ActiveGuides: activeGuides,
|
||||
InstallGuideEnabled: installGuideEnabled,
|
||||
NeedsSetup: needsSetup,
|
||||
DataRoot: rootStatus,
|
||||
DataRootMessage: dataRootMessage(i18n.EffectiveLocale(cfgCopy.Locale), rootStatus),
|
||||
AppVersion: version.Version,
|
||||
SafeMode: safeMode,
|
||||
PluginCrashDetected: crashDetected,
|
||||
@@ -683,7 +707,7 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
|
||||
func (a *App) SetLocale(raw string) error {
|
||||
a.mu.Lock()
|
||||
a.cfg.Locale = i18n.ParsePreference(raw)
|
||||
err := config.Save("", a.cfg)
|
||||
err := a.saveConfigLocked()
|
||||
eff := i18n.EffectiveLocale(a.cfg.Locale)
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -700,14 +724,14 @@ func (a *App) SetAutoPinPCores(enabled bool) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.AutoPinPCores = enabled
|
||||
return config.Save("", a.cfg)
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
func (a *App) SetMinimizeToTray(enabled bool) error {
|
||||
a.mu.Lock()
|
||||
v := enabled
|
||||
a.cfg.MinimizeToTray = &v
|
||||
err := config.Save("", a.cfg)
|
||||
err := a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
@@ -899,6 +923,10 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
if err := validateDataRoot(dir, loc); err != nil {
|
||||
return err
|
||||
}
|
||||
// Check (and if needed upgrade) the target before writing anything into it.
|
||||
if st := dataroot.Open(dir, version.Version); st.ReadOnly {
|
||||
return dataroot.Error(loc, st)
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.Load(cfgPath)
|
||||
@@ -925,12 +953,19 @@ func (a *App) SetDataRoot(dir string) error {
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
// A folder created just now gets its version stamp here.
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
|
||||
a.mu.Lock()
|
||||
wasReadOnly := a.root.ReadOnly
|
||||
a.cfg = nextCfg
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
|
||||
if filepath.Clean(prev) != filepath.Clean(dir) {
|
||||
// Leaving a read-only folder starts the plugins and polling it held back,
|
||||
// even when the user picked the same folder again after fixing it.
|
||||
if filepath.Clean(prev) != filepath.Clean(dir) || wasReadOnly {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
@@ -985,7 +1020,7 @@ func (a *App) InstallRuntimeArchive(archivePath string) (*rt.Installed, error) {
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = inst.Commit
|
||||
_ = config.Save("", a.cfg)
|
||||
_ = a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
a.emitLog("runtime", fmt.Sprintf("Runtime %s installed & activated -> %s", inst.Commit, inst.Dir))
|
||||
return inst, nil
|
||||
@@ -995,7 +1030,7 @@ func (a *App) UseRuntime(commit string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.ActiveRuntime = commit
|
||||
return config.Save("", a.cfg)
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
func (a *App) RemoveRuntime(commit string) error {
|
||||
@@ -1048,6 +1083,9 @@ func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.createVMFlow(opts)
|
||||
}
|
||||
|
||||
@@ -1318,6 +1356,9 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
|
||||
}
|
||||
|
||||
func (a *App) StartVM(name string) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
prep, err := a.prep(name)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -68,11 +68,10 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
if err := a.updateSupported(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
a.mu.Unlock()
|
||||
return "", errors.New("choose a data folder first")
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
|
||||
@@ -228,7 +227,7 @@ func (a *App) finishAppUpdateWithExe(exe string) {
|
||||
if a.launch.WaitPID == 0 {
|
||||
return
|
||||
}
|
||||
if !keepOld && dataRoot != "" {
|
||||
if !keepOld && dataRoot != "" && a.dataRootUsable() {
|
||||
_ = os.RemoveAll(appUpdateDir(dataRoot))
|
||||
}
|
||||
if keepOld {
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
// openDataRoot opens the current data folder (dataroot.Open: version check,
|
||||
// migration under the folder lock) and records whether it may be written.
|
||||
func (a *App) openDataRoot() dataroot.Status {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.DataRoot
|
||||
a.mu.Unlock()
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
return st
|
||||
}
|
||||
|
||||
func (a *App) logDataRoot(st dataroot.Status) {
|
||||
switch {
|
||||
case st.ReadOnly:
|
||||
msg := fmt.Sprintf("Data folder %s opened read-only (%s)", st.Dir, st.Reason)
|
||||
if st.Detail != "" {
|
||||
msg += ": " + st.Detail
|
||||
}
|
||||
a.emitLog("app", msg)
|
||||
case len(st.Migrated) > 0:
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded to layout v%d (%s)", st.Version, strings.Join(st.Migrated, ", ")))
|
||||
}
|
||||
}
|
||||
|
||||
// dataRootUsable reports whether anything may read the data folder through
|
||||
// reims-ctl or write to it: not before first-run setup has chosen a folder,
|
||||
// and not while the folder is open read-only.
|
||||
func (a *App) dataRootUsable() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.needsSetup && !a.root.ReadOnly
|
||||
}
|
||||
|
||||
// requireWritableDataRoot is the guard for bindings that change the data
|
||||
// folder and can be reached without the main window, such as a VM start
|
||||
// handed over from the CLI.
|
||||
func (a *App) requireWritableDataRoot() error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.needsSetup {
|
||||
return i18n.NewCodedError(i18n.EffectiveLocale(a.cfg.Locale), "E_DATAROOT_SETUP", "err.dataroot.needs_setup", nil, nil)
|
||||
}
|
||||
return dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root)
|
||||
}
|
||||
|
||||
// saveConfigLocked persists a.cfg; a.mu must be held. Before first-run setup
|
||||
// a.cfg points at a suggested folder the user has not chosen, so changes stay
|
||||
// in memory until CompleteSetup writes them into the chosen folder. A folder
|
||||
// open read-only refuses the write.
|
||||
func (a *App) saveConfigLocked() error {
|
||||
if a.needsSetup {
|
||||
return nil
|
||||
}
|
||||
if err := dataroot.Error(i18n.EffectiveLocale(a.cfg.Locale), a.root); err != nil {
|
||||
return err
|
||||
}
|
||||
return config.Save("", a.cfg)
|
||||
}
|
||||
|
||||
// ReopenDataRoot opens the current data folder again: after another process
|
||||
// finished upgrading it, after a failed upgrade, or with repair set, to rebuild
|
||||
// a damaged version record on the user's request. When the folder becomes
|
||||
// writable, the parts that were held back start.
|
||||
func (a *App) ReopenDataRoot(repair bool) (dataroot.Status, error) {
|
||||
a.mu.Lock()
|
||||
if a.needsSetup {
|
||||
st := a.root
|
||||
a.mu.Unlock()
|
||||
return st, nil
|
||||
}
|
||||
dir := a.cfg.DataRoot
|
||||
wasReadOnly := a.root.ReadOnly
|
||||
a.mu.Unlock()
|
||||
|
||||
var st dataroot.Status
|
||||
if repair {
|
||||
st = dataroot.Repair(dir, version.Version)
|
||||
} else {
|
||||
st = dataroot.Open(dir, version.Version)
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
|
||||
if wasReadOnly && st.Writable() {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
}
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
}
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// dataRootMessage is the localized explanation the read-only screen shows,
|
||||
// without the error code and raw detail (shown separately).
|
||||
func dataRootMessage(loc i18n.Locale, st dataroot.Status) string {
|
||||
var ce *i18n.CodedError
|
||||
if errors.As(dataroot.Error(loc, st), &ce) {
|
||||
return ce.Summary(loc)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func dirEntries(t *testing.T, dir string) []string {
|
||||
t.Helper()
|
||||
var out []string
|
||||
_ = filepath.Walk(dir, func(p string, _ os.FileInfo, err error) error {
|
||||
if err == nil && p != dir {
|
||||
out = append(out, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Before first-run setup a.cfg only suggests a folder. Picking a language on
|
||||
// the setup screen or starting plugins must not write anything into it.
|
||||
func TestNothingWrittenBeforeSetup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, needsSetup: true}
|
||||
|
||||
if err := a.SetLocale("en-US"); err != nil {
|
||||
t.Fatalf("SetLocale before setup: %v", err)
|
||||
}
|
||||
if a.cfg.Locale != "en-US" {
|
||||
t.Fatalf("locale not kept in memory: %q", a.cfg.Locale)
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started before setup")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != 0 {
|
||||
t.Fatalf("suggested folder written before setup: %v", got)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM before setup must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
// A folder written by a newer release opens read-only: settings, VM starts
|
||||
// and plugins are all refused, and the folder is left as it was.
|
||||
func TestReadOnlyFolderRefusesWrites(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
if err := os.WriteFile(cfgPath, []byte(`{"data_root": "x", "locale": "zh-CN"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := dirEntries(t, dir)
|
||||
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = dir
|
||||
a := &App{cfg: cfg, root: dataroot.Open(dir, version.Version)}
|
||||
if !a.root.ReadOnly {
|
||||
t.Fatalf("root = %+v, want read-only", a.root)
|
||||
}
|
||||
|
||||
if err := a.SetLocale("en-US"); err == nil {
|
||||
t.Fatal("SetLocale on a read-only folder must fail")
|
||||
}
|
||||
if raw, _ := os.ReadFile(cfgPath); string(raw) != `{"data_root": "x", "locale": "zh-CN"}` {
|
||||
t.Fatalf("config rewritten: %s", raw)
|
||||
}
|
||||
if err := a.StartVM("mac"); err == nil {
|
||||
t.Fatal("StartVM on a read-only folder must be refused")
|
||||
}
|
||||
a.initPlugins()
|
||||
if a.pluginMgr != nil {
|
||||
t.Fatal("plugins started on a read-only folder")
|
||||
}
|
||||
a.appendUICrashLog("renderer unresponsive")
|
||||
if got := dirEntries(t, dir); len(got) != len(before) {
|
||||
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/guesttools"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
@@ -48,20 +47,17 @@ type PluginUIContributions struct {
|
||||
}
|
||||
|
||||
func (a *App) initPlugins() {
|
||||
// Plugins keep their state in the data folder. Before setup there is no
|
||||
// chosen folder, and a read-only folder must not be written; the app runs
|
||||
// without a plugin manager then (see startup).
|
||||
if !a.dataRootUsable() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
dataRoot := a.cfg.DataRoot
|
||||
safeMode := a.launch.SafeMode
|
||||
a.mu.Unlock()
|
||||
|
||||
// Bring the data folder to this build's layout before anything reads it.
|
||||
if res, err := datamigrate.Run(dataRoot, version.Version); err != nil {
|
||||
a.emitLog("app", "Data migration failed: "+err.Error())
|
||||
} else if res.Newer {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder uses layout v%d from a newer Reims-Go (this build knows v%d); leaving it unchanged", res.From, datamigrate.CurrentVersion))
|
||||
} else if len(res.Applied) > 0 {
|
||||
a.emitLog("app", fmt.Sprintf("Data folder upgraded from layout v%d to v%d (%s)", res.From, res.To, strings.Join(res.Applied, ", ")))
|
||||
}
|
||||
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
||||
DataRoot: dataRoot,
|
||||
HostVersion: version.Version,
|
||||
@@ -748,6 +744,9 @@ func (a *App) ListRuntimeKinds() []rt.KindSpec {
|
||||
}
|
||||
|
||||
func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
|
||||
if err := a.requireWritableDataRoot(); err != nil {
|
||||
return err
|
||||
}
|
||||
a.mu.Lock()
|
||||
dr := a.driverRouter
|
||||
mgr := a.pluginMgr
|
||||
|
||||
@@ -80,7 +80,7 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
defer a.mu.Unlock()
|
||||
a.cfg.RuntimeChannel = channel
|
||||
forgetRemoteRuntimes()
|
||||
return config.Save("", a.cfg)
|
||||
return a.saveConfigLocked()
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
@@ -168,7 +168,7 @@ func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, ta
|
||||
|
||||
a.mu.Lock()
|
||||
a.cfg.ActiveRuntime = r.Commit
|
||||
err = config.Save("", a.cfg)
|
||||
err = a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -203,7 +203,7 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
}
|
||||
a.mu.Lock()
|
||||
a.cfg.AppUpdateChannel = channel
|
||||
err := config.Save("", a.cfg)
|
||||
err := a.saveConfigLocked()
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
+15
-8
@@ -12,8 +12,10 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||
)
|
||||
|
||||
@@ -107,6 +109,11 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := validateDataRoot(dir, locale); err != nil {
|
||||
return err
|
||||
}
|
||||
// Check the folder before writing anything into it: one written by a
|
||||
// newer release, or with a damaged version record, is refused untouched.
|
||||
if st := dataroot.Open(dir, version.Version); st.ReadOnly {
|
||||
return dataroot.Error(i18n.EffectiveLocale(locale), st)
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
cfg, err := config.Load(cfgPath)
|
||||
@@ -129,18 +136,18 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
if err := config.SaveLocation(dir); err != nil {
|
||||
return err
|
||||
}
|
||||
// A folder created just now gets its version stamp here.
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
prevRoot := ""
|
||||
if a.cfg != nil {
|
||||
prevRoot = a.cfg.DataRoot
|
||||
}
|
||||
a.cfg = cfg
|
||||
a.needsSetup = false
|
||||
a.root = st
|
||||
a.mu.Unlock()
|
||||
if filepath.Clean(prevRoot) != filepath.Clean(dir) {
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
}
|
||||
a.logDataRoot(st)
|
||||
// Nothing touching the data folder ran before setup (startup), so plugins
|
||||
// start now whichever folder was chosen.
|
||||
a.resetDataRootCaches()
|
||||
a.reloadPlugins()
|
||||
a.wakePoll()
|
||||
if a.ctx != nil {
|
||||
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
|
||||
|
||||
@@ -177,6 +177,11 @@ func (a *App) probeUIHealth(ctx context.Context, reason string) {
|
||||
}
|
||||
|
||||
func (a *App) appendUICrashLog(msg string) {
|
||||
// The message already went to the log panel; the file copy waits until a
|
||||
// data folder is chosen and writable (internal/dataroot).
|
||||
if !a.dataRootUsable() {
|
||||
return
|
||||
}
|
||||
a.mu.Lock()
|
||||
root := ""
|
||||
if a.cfg != nil {
|
||||
|
||||
+18
-5
@@ -12,7 +12,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
@@ -70,10 +70,8 @@ func run(args []string) (i18n.Locale, error) {
|
||||
if *dataRootFlag != "" {
|
||||
cfg.DataRoot = *dataRootFlag
|
||||
}
|
||||
// Same data-folder upgrade the GUI runs on startup.
|
||||
if _, err := datamigrate.Run(cfg.DataRoot, version.Version); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "warning:", err)
|
||||
}
|
||||
// Same check and upgrade the GUI runs on startup (internal/dataroot).
|
||||
root := dataroot.Open(cfg.DataRoot, version.Version)
|
||||
// Load enabled static language packs from <DataRoot>/plugins before resolving
|
||||
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
|
||||
plugin.LoadStaticLocalePacks(cfg.DataRoot)
|
||||
@@ -89,6 +87,11 @@ func run(args []string) (i18n.Locale, error) {
|
||||
printUsage(loc)
|
||||
return loc, nil
|
||||
}
|
||||
// A folder open read-only (written by a newer release, damaged version
|
||||
// record, failed upgrade) only serves commands that never write to it.
|
||||
if root.ReadOnly && !readOnlySafeCommand(rest[0]) {
|
||||
return loc, dataroot.Error(loc, root)
|
||||
}
|
||||
|
||||
switch rest[0] {
|
||||
case "doctor":
|
||||
@@ -633,3 +636,13 @@ func resolveCLIDiskPath(d reims.VMDetail) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// readOnlySafeCommand reports whether cmd runs without writing to the data
|
||||
// folder, so it may run while the folder is open read-only.
|
||||
func readOnlySafeCommand(cmd string) bool {
|
||||
switch cmd {
|
||||
case "version", "-v", "--version", "help", "-h", "--help", "doctor":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -130,6 +130,20 @@ func SaveLocation(dataRoot string) error {
|
||||
// config; a variable so tests can point it elsewhere.
|
||||
var legacyDataRoot = DefaultDataRoot
|
||||
|
||||
// ErrFirstRunNotIsolated refuses REIMS_GO_FIRST_RUN without its own
|
||||
// REIMS_GO_LOCATION_FILE: finishing the simulated setup would otherwise
|
||||
// repoint the user's real data folder record.
|
||||
var ErrFirstRunNotIsolated = errors.New("REIMS_GO_FIRST_RUN=1 also needs REIMS_GO_LOCATION_FILE pointing at a test location file")
|
||||
|
||||
// CheckFirstRunIsolation reports ErrFirstRunNotIsolated when the first-run
|
||||
// test mode is on without a test location file.
|
||||
func CheckFirstRunIsolation() error {
|
||||
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" && os.Getenv("REIMS_GO_LOCATION_FILE") == "" {
|
||||
return ErrFirstRunNotIsolated
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Resolve() (cfg *Config, needsSetup bool, err error) {
|
||||
if os.Getenv("REIMS_GO_FIRST_RUN") == "1" {
|
||||
// Simulate a fresh machine (testing the first-launch screen).
|
||||
@@ -206,7 +220,13 @@ func Save(path string, cfg *Config) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(path, append(data, '\n'), 0o644)
|
||||
// Temp file + rename: a crash mid-write leaves the old file, not a
|
||||
// truncated one.
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -92,3 +93,22 @@ func TestLegacyCandidateChannelReadsAsAlpha(t *testing.T) {
|
||||
t.Fatalf("runtime_channel = %q, want alpha", cfg.RuntimeChannel)
|
||||
}
|
||||
}
|
||||
|
||||
// The first-run test mode must not be able to repoint the real data folder
|
||||
// record, so it needs its own location file.
|
||||
func TestFirstRunNeedsItsOwnLocationFile(t *testing.T) {
|
||||
t.Setenv("REIMS_GO_FIRST_RUN", "1")
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", "")
|
||||
if err := CheckFirstRunIsolation(); !errors.Is(err, ErrFirstRunNotIsolated) {
|
||||
t.Fatalf("FIRST_RUN without location file: err = %v", err)
|
||||
}
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(t.TempDir(), "location.json"))
|
||||
if err := CheckFirstRunIsolation(); err != nil {
|
||||
t.Fatalf("FIRST_RUN with location file: %v", err)
|
||||
}
|
||||
t.Setenv("REIMS_GO_FIRST_RUN", "")
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", "")
|
||||
if err := CheckFirstRunIsolation(); err != nil {
|
||||
t.Fatalf("normal launch: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -60,10 +60,22 @@ type Result struct {
|
||||
// Run brings the data folder at dataRoot up to CurrentVersion. A missing or
|
||||
// empty dataRoot is not an error: there is nothing to migrate yet.
|
||||
func Run(dataRoot, appVersion string) (Result, error) {
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now)
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, false)
|
||||
}
|
||||
|
||||
func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time) (Result, error) {
|
||||
// ErrDamagedStamp reports a StampFile that cannot be read. Run then changes
|
||||
// nothing: the folder may belong to a newer release whose stamp this build
|
||||
// cannot parse. Repair rebuilds it on the user's explicit request.
|
||||
var ErrDamagedStamp = errors.New("data version stamp is damaged")
|
||||
|
||||
// Repair is Run for a folder whose stamp is damaged: it treats the folder as
|
||||
// unstamped and runs every step from version 0. Steps are idempotent, so this
|
||||
// is safe on a folder that was already partly or fully migrated.
|
||||
func Repair(dataRoot, appVersion string) (Result, error) {
|
||||
return run(dataRoot, appVersion, steps, CurrentVersion, time.Now, true)
|
||||
}
|
||||
|
||||
func run(dataRoot, appVersion string, steps []Step, current int, now func() time.Time, repair bool) (Result, error) {
|
||||
if dataRoot == "" {
|
||||
return Result{}, nil
|
||||
}
|
||||
@@ -73,7 +85,9 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time
|
||||
|
||||
stamp, readErr := ReadStamp(dataRoot)
|
||||
if readErr != nil {
|
||||
// Steps are idempotent, so a damaged stamp is safe to rebuild from 0.
|
||||
if !repair {
|
||||
return Result{}, fmt.Errorf("%w: %v", ErrDamagedStamp, readErr)
|
||||
}
|
||||
stamp = Stamp{}
|
||||
}
|
||||
res := Result{From: stamp.DataVersion, To: stamp.DataVersion}
|
||||
|
||||
@@ -95,16 +95,25 @@ func TestRunLeavesNewerLayoutAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunRebuildsDamagedStamp(t *testing.T) {
|
||||
// A damaged stamp may come from a newer release, so Run leaves the folder
|
||||
// alone; Repair, on the user's request, rebuilds it from version 0.
|
||||
func TestDamagedStampNeedsExplicitRepair(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, StampFile), []byte("{not json"), 0o644); err != nil {
|
||||
stampPath := filepath.Join(root, StampFile)
|
||||
if err := os.WriteFile(stampPath, []byte("{not json"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Run(root, "0.2.12"); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
if _, err := Run(root, "0.2.12"); !errors.Is(err, ErrDamagedStamp) {
|
||||
t.Fatalf("Run on a damaged stamp: err = %v, want ErrDamagedStamp", err)
|
||||
}
|
||||
if raw, _ := os.ReadFile(stampPath); string(raw) != "{not json" {
|
||||
t.Fatalf("Run rewrote a damaged stamp: %q", raw)
|
||||
}
|
||||
if _, err := Repair(root, "0.2.12"); err != nil {
|
||||
t.Fatalf("Repair: %v", err)
|
||||
}
|
||||
if st, err := ReadStamp(root); err != nil || st.DataVersion != CurrentVersion {
|
||||
t.Fatalf("stamp after rebuild = %+v, %v", st, err)
|
||||
t.Fatalf("stamp after repair = %+v, %v", st, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +129,7 @@ func TestRunStopsAtFailedStep(t *testing.T) {
|
||||
{To: 3, Name: "three", Run: ok("three")},
|
||||
}
|
||||
now := func() time.Time { return time.Unix(0, 0) }
|
||||
res, err := run(root, "1.0.0", steps, 3, now)
|
||||
res, err := run(root, "1.0.0", steps, 3, now, false)
|
||||
if err == nil || !strings.Contains(err.Error(), `"two"`) {
|
||||
t.Fatalf("expected failure in step two, got %v", err)
|
||||
}
|
||||
@@ -134,7 +143,7 @@ func TestRunStopsAtFailedStep(t *testing.T) {
|
||||
// Next start resumes from layout 1 once the problem is gone.
|
||||
steps[1].Run = ok("two")
|
||||
ran = nil
|
||||
res, err = run(root, "1.0.0", steps, 3, now)
|
||||
res, err = run(root, "1.0.0", steps, 3, now, false)
|
||||
if err != nil || res.From != 1 || res.To != 3 || !reflect.DeepEqual(ran, []string{"two", "three"}) {
|
||||
t.Fatalf("resume = %+v, ran %v, err %v", res, ran, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
// Package dataroot is the one way the GUI, first-run setup, switching the
|
||||
// data folder and the CLI open a data folder: it checks the layout version,
|
||||
// migrates under a cross-process lock when needed, and says whether the
|
||||
// folder may be written.
|
||||
//
|
||||
// A folder this build cannot safely write (written by a newer release, a
|
||||
// damaged version stamp, a failed migration) opens read-only, and opening it
|
||||
// that way creates or changes nothing, not even the lock file.
|
||||
package dataroot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
)
|
||||
|
||||
// LockFile is taken while a folder is migrated, so two processes opening the
|
||||
// same folder at once do not both migrate it.
|
||||
const LockFile = ".reims-go.lock"
|
||||
|
||||
// lockWait bounds how long Open waits for another process to finish
|
||||
// migrating the same folder.
|
||||
var lockWait = 30 * time.Second
|
||||
|
||||
// Reason says why a folder opened read-only.
|
||||
type Reason string
|
||||
|
||||
const (
|
||||
ReasonNewer Reason = "newer" // written by a newer release
|
||||
ReasonDamaged Reason = "damaged" // version stamp cannot be read
|
||||
ReasonMigrationFailed Reason = "migration_failed" // an upgrade step failed
|
||||
ReasonBusy Reason = "busy" // another process kept the folder locked
|
||||
)
|
||||
|
||||
// Status describes an opened data folder.
|
||||
type Status struct {
|
||||
Dir string `json:"dir"`
|
||||
ReadOnly bool `json:"read_only"`
|
||||
Reason Reason `json:"reason,omitempty"`
|
||||
Detail string `json:"detail,omitempty"`
|
||||
// Version is the layout version on disk (-1 when unknown); Known is the
|
||||
// newest layout this build writes.
|
||||
Version int `json:"version"`
|
||||
Known int `json:"known"`
|
||||
// Migrated lists the upgrade steps this Open ran.
|
||||
Migrated []string `json:"migrated,omitempty"`
|
||||
}
|
||||
|
||||
// Writable reports whether callers may write to the folder.
|
||||
func (s Status) Writable() bool { return !s.ReadOnly }
|
||||
|
||||
// Open checks dir and brings it to this build's layout. A folder that does
|
||||
// not exist yet is writable: there is nothing to migrate, and the caller
|
||||
// creates it.
|
||||
func Open(dir, appVersion string) Status {
|
||||
return open(dir, appVersion, false)
|
||||
}
|
||||
|
||||
// Repair is Open for a folder whose version stamp is damaged: it rebuilds the
|
||||
// stamp by running every upgrade step from version 0. Only on the user's
|
||||
// explicit request.
|
||||
func Repair(dir, appVersion string) Status {
|
||||
return open(dir, appVersion, true)
|
||||
}
|
||||
|
||||
func open(dir, appVersion string, repair bool) Status {
|
||||
st := Status{Dir: dir, Version: -1, Known: datamigrate.CurrentVersion}
|
||||
if dir == "" {
|
||||
return st
|
||||
}
|
||||
if info, err := os.Stat(dir); err != nil || !info.IsDir() {
|
||||
return st
|
||||
}
|
||||
|
||||
// Decide without the lock first: a folder this build must not touch is
|
||||
// left exactly as it is, and an up-to-date folder needs no lock at all.
|
||||
stamp, err := datamigrate.ReadStamp(dir)
|
||||
switch {
|
||||
case err != nil && !repair:
|
||||
return readOnly(st, ReasonDamaged, err.Error())
|
||||
case err == nil && stamp.DataVersion > datamigrate.CurrentVersion:
|
||||
st.Version = stamp.DataVersion
|
||||
return readOnly(st, ReasonNewer, "")
|
||||
case err == nil && stamp.DataVersion == datamigrate.CurrentVersion && stampExists(dir):
|
||||
st.Version = stamp.DataVersion
|
||||
return st
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), lockWait)
|
||||
defer cancel()
|
||||
release, err := filelock.Acquire(ctx, filepath.Join(dir, LockFile), 100*time.Millisecond)
|
||||
if err != nil {
|
||||
return readOnly(st, ReasonBusy, err.Error())
|
||||
}
|
||||
defer release()
|
||||
|
||||
// The migrator reads the stamp again under the lock, so a folder another
|
||||
// process finished migrating meanwhile is left as it is.
|
||||
migrate := datamigrate.Run
|
||||
if repair {
|
||||
migrate = datamigrate.Repair
|
||||
}
|
||||
res, err := migrate(dir, appVersion)
|
||||
st.Version = res.To
|
||||
switch {
|
||||
case errors.Is(err, datamigrate.ErrDamagedStamp):
|
||||
st.Version = -1
|
||||
return readOnly(st, ReasonDamaged, err.Error())
|
||||
case err != nil:
|
||||
return readOnly(st, ReasonMigrationFailed, err.Error())
|
||||
case res.Newer:
|
||||
return readOnly(st, ReasonNewer, "")
|
||||
}
|
||||
st.Migrated = res.Applied
|
||||
return st
|
||||
}
|
||||
|
||||
func readOnly(st Status, reason Reason, detail string) Status {
|
||||
st.ReadOnly = true
|
||||
st.Reason = reason
|
||||
st.Detail = detail
|
||||
return st
|
||||
}
|
||||
|
||||
func stampExists(dir string) bool {
|
||||
_, err := os.Stat(filepath.Join(dir, datamigrate.StampFile))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Error explains why st cannot be written, for the GUI and the CLI alike. It
|
||||
// is nil for a writable folder.
|
||||
func Error(loc i18n.Locale, st Status) error {
|
||||
if !st.ReadOnly {
|
||||
return nil
|
||||
}
|
||||
var cause error
|
||||
if st.Detail != "" {
|
||||
cause = errors.New(st.Detail)
|
||||
}
|
||||
vars := i18n.Vars{"dir": st.Dir, "version": st.Version, "known": st.Known}
|
||||
switch st.Reason {
|
||||
case ReasonNewer:
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_NEWER", "err.dataroot.newer", vars, cause)
|
||||
case ReasonDamaged:
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_DAMAGED", "err.dataroot.damaged", vars, cause)
|
||||
case ReasonBusy:
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_LOCKED", "err.dataroot.locked", vars, cause)
|
||||
default:
|
||||
return i18n.NewCodedError(loc, "E_DATAROOT_MIGRATION", "err.dataroot.migration_failed", vars, cause)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package dataroot
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
)
|
||||
|
||||
func writeStamp(t *testing.T, dir string, raw string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, datamigrate.StampFile), []byte(raw), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot lists every entry under dir with its size and modification time,
|
||||
// to prove a read-only open created or changed nothing.
|
||||
func snapshot(t *testing.T, dir string) map[string]string {
|
||||
t.Helper()
|
||||
out := map[string]string{}
|
||||
_ = filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
|
||||
if err == nil {
|
||||
out[p] = fmt.Sprintf("%s/%d", info.ModTime(), info.Size())
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func assertUntouched(t *testing.T, dir string, before map[string]string) {
|
||||
t.Helper()
|
||||
after := snapshot(t, dir)
|
||||
if len(after) != len(before) {
|
||||
t.Fatalf("entries changed: before %d, after %d (%v)", len(before), len(after), after)
|
||||
}
|
||||
for p, v := range before {
|
||||
if after[p] != v {
|
||||
t.Fatalf("%s changed", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewerFolderOpensReadOnlyAndUntouched(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStamp(t, dir, `{"data_version": 999}`)
|
||||
before := snapshot(t, dir)
|
||||
|
||||
st := Open(dir, "0.2.12")
|
||||
if !st.ReadOnly || st.Reason != ReasonNewer || st.Version != 999 {
|
||||
t.Fatalf("Open = %+v, want read-only newer v999", st)
|
||||
}
|
||||
assertUntouched(t, dir, before)
|
||||
}
|
||||
|
||||
func TestDamagedStampOpensReadOnlyUntilRepaired(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeStamp(t, dir, `{not json`)
|
||||
before := snapshot(t, dir)
|
||||
|
||||
st := Open(dir, "0.2.12")
|
||||
if !st.ReadOnly || st.Reason != ReasonDamaged {
|
||||
t.Fatalf("Open = %+v, want read-only damaged", st)
|
||||
}
|
||||
assertUntouched(t, dir, before)
|
||||
|
||||
st = Repair(dir, "0.2.12")
|
||||
if st.ReadOnly || st.Version != datamigrate.CurrentVersion {
|
||||
t.Fatalf("Repair = %+v, want writable at v%d", st, datamigrate.CurrentVersion)
|
||||
}
|
||||
if again := Open(dir, "0.2.12"); again.ReadOnly || len(again.Migrated) != 0 {
|
||||
t.Fatalf("Open after repair = %+v, want writable with nothing to migrate", again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnstampedFolderMigratesOnce(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
st := Open(dir, "0.2.12")
|
||||
if st.ReadOnly || st.Version != datamigrate.CurrentVersion {
|
||||
t.Fatalf("Open = %+v, want writable at v%d", st, datamigrate.CurrentVersion)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, datamigrate.StampFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stamp datamigrate.Stamp
|
||||
if json.Unmarshal(raw, &stamp) != nil || stamp.WrittenBy != "0.2.12" {
|
||||
t.Fatalf("stamp = %s", raw)
|
||||
}
|
||||
|
||||
// An up-to-date folder needs no lock, so opening it creates nothing.
|
||||
if err := os.Remove(filepath.Join(dir, LockFile)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := snapshot(t, dir)
|
||||
if st := Open(dir, "0.2.12"); st.ReadOnly {
|
||||
t.Fatalf("second Open = %+v", st)
|
||||
}
|
||||
assertUntouched(t, dir, before)
|
||||
}
|
||||
|
||||
func TestMissingFolderIsWritable(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "not-yet")
|
||||
if st := Open(dir, "0.2.12"); st.ReadOnly {
|
||||
t.Fatalf("Open = %+v, want writable", st)
|
||||
}
|
||||
if _, err := os.Stat(dir); !os.IsNotExist(err) {
|
||||
t.Fatal("Open created the folder")
|
||||
}
|
||||
}
|
||||
|
||||
// Two processes opening one unmigrated folder at once: the lock and the
|
||||
// second stamp read under it mean the steps run exactly once.
|
||||
func TestConcurrentOpensMigrateOnce(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
const n = 4
|
||||
var wg sync.WaitGroup
|
||||
results := make([]Status, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
results[i] = Open(dir, "0.2.12")
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
ran := 0
|
||||
for _, st := range results {
|
||||
if st.ReadOnly {
|
||||
t.Fatalf("Open = %+v", st)
|
||||
}
|
||||
if len(st.Migrated) > 0 {
|
||||
ran++
|
||||
}
|
||||
}
|
||||
if ran != 1 {
|
||||
t.Fatalf("migration ran %d times, want 1", ran)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeldLockOpensReadOnlyBusy(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
release, err := filelock.Acquire(context.Background(), filepath.Join(dir, LockFile), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer release()
|
||||
old := lockWait
|
||||
lockWait = 200 * time.Millisecond
|
||||
defer func() { lockWait = old }()
|
||||
|
||||
if st := Open(dir, "0.2.12"); !st.ReadOnly || st.Reason != ReasonBusy {
|
||||
t.Fatalf("Open = %+v, want read-only busy", st)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// Package filelock takes exclusive, cross-process locks on files. The lock is
|
||||
// LockFileEx over the whole file on Windows and flock elsewhere, which is
|
||||
// what Rust's File::try_lock uses, so it also excludes reims-ctl and
|
||||
// reims-util where they lock the same file.
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TryLock takes an exclusive lock on f without waiting. It reports false when
|
||||
// another process holds it.
|
||||
func TryLock(f *os.File) (bool, error) { return tryLock(f) }
|
||||
|
||||
// Unlock releases a lock taken with TryLock.
|
||||
func Unlock(f *os.File) { unlock(f) }
|
||||
|
||||
// Acquire creates path if needed and waits until it holds an exclusive lock
|
||||
// on it, checking every poll, until ctx ends. The returned function releases
|
||||
// the lock and closes the file.
|
||||
func Acquire(ctx context.Context, path string, poll time.Duration) (func(), error) {
|
||||
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if poll <= 0 {
|
||||
poll = 100 * time.Millisecond
|
||||
}
|
||||
for {
|
||||
ok, err := tryLock(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("lock %s: %w", path, err)
|
||||
}
|
||||
if ok {
|
||||
return func() { unlock(f); f.Close() }, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("lock %s: %w", path, ctx.Err())
|
||||
case <-time.After(poll):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//go:build !windows
|
||||
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// flock(LOCK_EX | LOCK_NB), as Rust's File::try_lock on Unix.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, syscall.EWOULDBLOCK) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func unlock(f *os.File) {
|
||||
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//go:build windows
|
||||
|
||||
package filelock
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY over (0, MAX), the same
|
||||
// range Rust's File::try_lock locks.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
ol := new(windows.Overlapped)
|
||||
err := windows.LockFileEx(
|
||||
windows.Handle(f.Fd()),
|
||||
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
|
||||
0, ^uint32(0), ^uint32(0), ol,
|
||||
)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func unlock(f *os.File) {
|
||||
ol := new(windows.Overlapped)
|
||||
_ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, ^uint32(0), ^uint32(0), ol)
|
||||
}
|
||||
@@ -68,6 +68,13 @@ var catalog = map[Locale]map[string]string{
|
||||
"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": "详细信息",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"delete": "删除…",
|
||||
"deleteEllipsis": "删除…",
|
||||
"displays": "显示器数量",
|
||||
@@ -117,6 +124,11 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.commit_memory": "内存不够启动:这台虚拟机要 {need, number, .0} GB,Windows 现在只能再分配 {avail, number, .1} GB。关掉一些程序再试,或在设置里把内存改为 {rec, number, .0} GB",
|
||||
"err.dataroot.busy_tasks": "仍有后台下载或创建任务进行中,请等待任务结束或取消后再切换数据目录",
|
||||
"err.dataroot.busy_vms": "仍有虚拟机正在运行,请先全部关机后再切换数据目录",
|
||||
"err.dataroot.damaged": "数据目录 {dir} 的数据版本记录已损坏,已以只读方式打开,没有做任何修改。确认目录来自当前或更早的版本后,可在界面中修复版本记录",
|
||||
"err.dataroot.locked": "数据目录 {dir} 正被另一个 Reims-Go 进程升级,请等它完成后重试",
|
||||
"err.dataroot.migration_failed": "升级数据目录 {dir} 时出错,已停止写入。可以重试,或选择其他数据目录",
|
||||
"err.dataroot.needs_setup": "请先在首次设置中选择数据目录",
|
||||
"err.dataroot.newer": "数据目录 {dir} 由更新版本的 Reims-Go 写入(数据版本 v{version},本程序支持到 v{known}),已以只读方式打开,没有做任何修改。请安装更新的版本,或选择其他数据目录",
|
||||
"err.fullscreen_failed": "无法切换 {name} 的全屏状态",
|
||||
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
|
||||
"err.gpu_device_lost": "宿主显卡 Vulkan 设备丢失(ERROR_DEVICE_LOST)。请更新显卡驱动;若为 AMD Vega/Polaris 等受影响显卡,请改用其他独显或在设置中将虚拟显卡切为 VMware SVGA",
|
||||
@@ -580,6 +592,13 @@ var catalog = map[Locale]map[string]string{
|
||||
"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",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"delete": "Delete…",
|
||||
"deleteEllipsis": "Delete…",
|
||||
"displays": "Displays",
|
||||
@@ -629,6 +648,11 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.commit_memory": "Not enough memory to start: this VM needs {need, number, .0} GB and Windows can commit only {avail, number, .1} GB more. Close some programs, or set its memory to {rec, number, .0} GB",
|
||||
"err.dataroot.busy_tasks": "Wait for active download or creation tasks to finish before switching the data folder",
|
||||
"err.dataroot.busy_vms": "Stop all running virtual machines before switching the data folder",
|
||||
"err.dataroot.damaged": "The data version record in {dir} is damaged. The folder was opened read-only and nothing was changed. If it comes from this or an older version, you can repair the record in the app",
|
||||
"err.dataroot.locked": "Another Reims-Go process is upgrading the data folder {dir}. Try again once it finishes",
|
||||
"err.dataroot.migration_failed": "Upgrading the data folder {dir} failed, so nothing more is written to it. Try again or choose another data folder",
|
||||
"err.dataroot.needs_setup": "Choose a data folder in first-run setup first",
|
||||
"err.dataroot.newer": "The data folder {dir} was written by a newer Reims-Go (data version v{version}; this build supports up to v{known}). It was opened read-only and nothing was changed. Install the newer version or choose another data folder",
|
||||
"err.fullscreen_failed": "Couldn’t toggle full screen for {name}",
|
||||
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
|
||||
"err.gpu_device_lost": "Host Vulkan GPU device lost (ERROR_DEVICE_LOST). Update GPU drivers; on affected AMD Vega/Polaris GPUs, switch to another discrete GPU or use VMware SVGA in VM Settings",
|
||||
@@ -1066,6 +1090,10 @@ var paramOrder = map[string][]string{
|
||||
"err.clone.overlay_exists": {"path"},
|
||||
"err.clone.source_running": {"name"},
|
||||
"err.commit_memory": {"need", "avail", "rec"},
|
||||
"err.dataroot.damaged": {"dir"},
|
||||
"err.dataroot.locked": {"dir"},
|
||||
"err.dataroot.migration_failed": {"dir"},
|
||||
"err.dataroot.newer": {"dir", "known", "version"},
|
||||
"err.fullscreen_failed": {"name"},
|
||||
"err.fullscreen_vmware_svga": {"name"},
|
||||
"err.gpu_icd_stale": {"path"},
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/filelock"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
)
|
||||
|
||||
@@ -272,13 +273,13 @@ func (c *Client) lock(ctx context.Context, onUpdate func(Update)) (func(), error
|
||||
}
|
||||
said := false
|
||||
for {
|
||||
ok, err := tryLock(f)
|
||||
ok, err := filelock.TryLock(f)
|
||||
if err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("lock %s: %w", path, err)
|
||||
}
|
||||
if ok {
|
||||
return func() { unlock(f); f.Close() }, nil
|
||||
return func() { filelock.Unlock(f); f.Close() }, nil
|
||||
}
|
||||
if !said {
|
||||
// Same wording as reims-ctl (reims_util.rs:587).
|
||||
@@ -302,11 +303,11 @@ func (c *Client) Busy() bool {
|
||||
return false
|
||||
}
|
||||
defer f.Close()
|
||||
ok, err := tryLock(f)
|
||||
ok, err := filelock.TryLock(f)
|
||||
if err != nil || !ok {
|
||||
return err == nil
|
||||
}
|
||||
unlock(f)
|
||||
filelock.Unlock(f)
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -2,27 +2,6 @@
|
||||
|
||||
package installer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
import "os/exec"
|
||||
|
||||
func configureCmd(*exec.Cmd) {}
|
||||
|
||||
// tryLock is flock(LOCK_EX | LOCK_NB), as Rust's File::try_lock on Unix.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, syscall.EWOULDBLOCK) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func unlock(f *os.File) {
|
||||
_ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
|
||||
}
|
||||
@@ -3,12 +3,8 @@
|
||||
package installer
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
const createNoWindow = 0x08000000
|
||||
@@ -19,28 +15,3 @@ func configureCmd(cmd *exec.Cmd) {
|
||||
CreationFlags: createNoWindow,
|
||||
}
|
||||
}
|
||||
|
||||
// tryLock takes an exclusive lock on the whole file without waiting. Rust's
|
||||
// File::try_lock, which reims-ctl uses on the same file, is LockFileEx with
|
||||
// LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY over (0, MAX), so the two
|
||||
// exclude each other.
|
||||
func tryLock(f *os.File) (bool, error) {
|
||||
ol := new(windows.Overlapped)
|
||||
err := windows.LockFileEx(
|
||||
windows.Handle(f.Fd()),
|
||||
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
|
||||
0, ^uint32(0), ^uint32(0), ol,
|
||||
)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func unlock(f *os.File) {
|
||||
ol := new(windows.Overlapped)
|
||||
_ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, ^uint32(0), ^uint32(0), ol)
|
||||
}
|
||||
@@ -61,20 +61,18 @@ var retiredSettings = map[string]string{
|
||||
// carries a switched-off workaround over to its core setting. Safe to call on
|
||||
// every start; it only writes when an old record is still there.
|
||||
func MigrateRetired(mgr *plugin.Manager) error {
|
||||
removed, err := mgr.RetireRecords(RetiredIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
off := map[string]any{}
|
||||
for id, rec := range removed {
|
||||
if key, ok := retiredSettings[id]; ok && rec != nil && !rec.Enabled {
|
||||
off[key] = false
|
||||
// Dropping the old records and writing the core setting happen in one
|
||||
// state.json save, so a crash in between cannot lose a switched-off choice.
|
||||
_, err := mgr.RetireRecordsInto(RetiredIDs, IDCore, func(removed map[string]*plugin.PluginRecord) map[string]any {
|
||||
off := map[string]any{}
|
||||
for id, rec := range removed {
|
||||
if key, ok := retiredSettings[id]; ok && rec != nil && !rec.Enabled {
|
||||
off[key] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(off) == 0 {
|
||||
return nil
|
||||
}
|
||||
return mgr.SetSettings(IDCore, "", off)
|
||||
return off
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// MigrateLedger hands arg fragments owned by retired plugin IDs to the core,
|
||||
|
||||
@@ -718,9 +718,17 @@ func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error {
|
||||
// records so the caller can carry their choices over. Nothing is saved when
|
||||
// none of the IDs has a record.
|
||||
func (m *Manager) RetireRecords(ids []string) (map[string]*PluginRecord, error) {
|
||||
return m.RetireRecordsInto(ids, "", nil)
|
||||
}
|
||||
|
||||
// RetireRecordsInto drops the state.json records of ids and, in the same save,
|
||||
// merges the app settings carry derives from them into target's record. One
|
||||
// write means a crash cannot drop an old record without the setting that
|
||||
// replaced it. carry may be nil.
|
||||
func (m *Manager) RetireRecordsInto(ids []string, target string, carry func(removed map[string]*PluginRecord) map[string]any) (map[string]*PluginRecord, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.state == nil {
|
||||
m.mu.Unlock()
|
||||
return nil, m.stateNotLoadedErr()
|
||||
}
|
||||
removed := map[string]*PluginRecord{}
|
||||
@@ -731,9 +739,34 @@ func (m *Manager) RetireRecords(ids []string) (map[string]*PluginRecord, error)
|
||||
}
|
||||
}
|
||||
if len(removed) == 0 {
|
||||
m.mu.Unlock()
|
||||
return removed, nil
|
||||
}
|
||||
return removed, m.store.Save(m.state)
|
||||
var carried map[string]any
|
||||
if carry != nil && target != "" {
|
||||
carried = carry(removed)
|
||||
}
|
||||
if len(carried) > 0 {
|
||||
rec := m.state.Plugins[target]
|
||||
if rec == nil {
|
||||
rec = &PluginRecord{ID: target}
|
||||
m.state.Plugins[target] = rec
|
||||
}
|
||||
if rec.AppSettings == nil {
|
||||
rec.AppSettings = map[string]any{}
|
||||
}
|
||||
for k, v := range carried {
|
||||
rec.AppSettings[k] = v
|
||||
}
|
||||
rec.UpdatedAt = time.Now()
|
||||
}
|
||||
err := m.store.Save(m.state)
|
||||
cb := m.opts.OnSettingsChanged
|
||||
m.mu.Unlock()
|
||||
if err == nil && len(carried) > 0 && cb != nil {
|
||||
cb(target, "")
|
||||
}
|
||||
return removed, err
|
||||
}
|
||||
|
||||
func (m *Manager) stateNotLoadedErr() error {
|
||||
|
||||
@@ -248,5 +248,12 @@
|
||||
"fontMissingFoDHint": {
|
||||
"message": "Windows optional {script} fonts are not installed; native overlay text may use fallback glyphs. Install them under Windows Settings › Apps › Optional features.",
|
||||
"$comment": "纯净英文版 Windows 缺少东亚按需字体包(FoD)时的非阻断提示"
|
||||
}
|
||||
},
|
||||
"dataRootReadOnlyTitle": "This data folder can’t be used right now",
|
||||
"dataRootReadOnlyFolder": "Data folder",
|
||||
"dataRootReadOnlyDetail": "Details",
|
||||
"dataRootRepair": "Repair version record",
|
||||
"dataRootRetry": "Try again",
|
||||
"dataRootChooseOther": "Choose another data folder",
|
||||
"dataRootChooseTitle": "Choose data folder"
|
||||
}
|
||||
@@ -959,5 +959,10 @@
|
||||
"font.script.zh_hant": "Traditional Chinese (繁體中文)",
|
||||
"font.script.zh_hans": "Simplified Chinese (简体中文)",
|
||||
"font.script.ja": "Japanese (日本語)",
|
||||
"font.script.ko": "Korean (한국어)"
|
||||
"font.script.ko": "Korean (한국어)",
|
||||
"err.dataroot.newer": "The data folder {dir} was written by a newer Reims-Go (data version v{version}; this build supports up to v{known}). It was opened read-only and nothing was changed. Install the newer version or choose another data folder",
|
||||
"err.dataroot.damaged": "The data version record in {dir} is damaged. The folder was opened read-only and nothing was changed. If it comes from this or an older version, you can repair the record in the app",
|
||||
"err.dataroot.locked": "Another Reims-Go process is upgrading the data folder {dir}. Try again once it finishes",
|
||||
"err.dataroot.migration_failed": "Upgrading the data folder {dir} failed, so nothing more is written to it. Try again or choose another data folder",
|
||||
"err.dataroot.needs_setup": "Choose a data folder in first-run setup first"
|
||||
}
|
||||
@@ -248,5 +248,12 @@
|
||||
"fontMissingFoDHint": {
|
||||
"message": "当前 Windows 缺少 {script} 可选字体包,部分原生弹窗字形可能回退;可在「Windows 设置 › 应用 › 可选功能」添加对应补充字体。",
|
||||
"$comment": "纯净英文版 Windows 缺少东亚按需字体包(FoD)时的非阻断提示"
|
||||
}
|
||||
},
|
||||
"dataRootReadOnlyTitle": "数据目录暂时无法使用",
|
||||
"dataRootReadOnlyFolder": "数据目录",
|
||||
"dataRootReadOnlyDetail": "详细信息",
|
||||
"dataRootRepair": "修复版本记录",
|
||||
"dataRootRetry": "重试",
|
||||
"dataRootChooseOther": "选择其他数据目录",
|
||||
"dataRootChooseTitle": "选择数据目录"
|
||||
}
|
||||
@@ -959,5 +959,10 @@
|
||||
"font.script.zh_hant": "繁体中文(繁體中文)",
|
||||
"font.script.zh_hans": "简体中文",
|
||||
"font.script.ja": "日语(日本語)",
|
||||
"font.script.ko": "韩语(한국어)"
|
||||
"font.script.ko": "韩语(한국어)",
|
||||
"err.dataroot.newer": "数据目录 {dir} 由更新版本的 Reims-Go 写入(数据版本 v{version},本程序支持到 v{known}),已以只读方式打开,没有做任何修改。请安装更新的版本,或选择其他数据目录",
|
||||
"err.dataroot.damaged": "数据目录 {dir} 的数据版本记录已损坏,已以只读方式打开,没有做任何修改。确认目录来自当前或更早的版本后,可在界面中修复版本记录",
|
||||
"err.dataroot.locked": "数据目录 {dir} 正被另一个 Reims-Go 进程升级,请等它完成后重试",
|
||||
"err.dataroot.migration_failed": "升级数据目录 {dir} 时出错,已停止写入。可以重试,或选择其他数据目录",
|
||||
"err.dataroot.needs_setup": "请先在首次设置中选择数据目录"
|
||||
}
|
||||
@@ -3,11 +3,13 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/app"
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
|
||||
"github.com/wailsapp/wails/v2"
|
||||
@@ -43,6 +45,10 @@ func main() {
|
||||
cancel()
|
||||
}
|
||||
|
||||
if err := config.CheckFirstRunIsolation(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
app.RegisterLicenseTexts(licenseText, noticeText)
|
||||
desktopApp, hooks := app.New(trayIconPNG, launch)
|
||||
err := wails.Run(&options.App{
|
||||
|
||||
Reference in new issue
Block a user