Files
Reims-Go/internal/config/config.go
T
NwflowerandClaude Opus 5.5 90fbce8b47 refactor: write small files through one atomic writer
Fifteen call sites each had their own temp-file-and-rename code. Some
used a fixed temporary name, so two writers could mix their content, and
most did not flush before the rename. They now share atomicfile.Write.

An architecture test keeps new os.Rename calls out of other packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 20:59:56 -07:00

288 lines
8.9 KiB
Go

package config
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/Nwflower/reims-go/internal/atomicfile"
"github.com/Nwflower/reims-go/internal/i18n"
)
type Config struct {
DataRoot string `json:"data_root"`
Locale i18n.Locale `json:"locale"`
ActiveRuntime string `json:"active_runtime,omitempty"`
AutoPinPCores bool `json:"auto_pin_pcores"`
DefaultGPU string `json:"default_gpu,omitempty"`
// RuntimeChannel is "stable" (default, also when empty) or "alpha" (legacy alias "candidate").
RuntimeChannel string `json:"runtime_channel,omitempty"`
// AppUpdateChannel is "stable" (default, also when empty), "alpha", or "dev":
// controls which Reims-Go client releases CheckAppUpdate offers, and whether
// previous executables/installers are kept on startup for rollback.
AppUpdateChannel string `json:"app_update_channel,omitempty"`
// MinimizeToTray keeps Reims-Go running in the Windows system tray when the
// main window is closed so Guest Tools bridges stay alive. Defaults to true.
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
// SyncHostMemorySMBIOS overrides QEMU's default SMBIOS Type 17 memory spec
// (2666 MHz DDR4) with the host's physical memory speed and generation so
// macOS About This Mac reports the host's real RAM frequency. Defaults to false.
SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"`
HostDNSMode string `json:"host_dns_mode,omitempty"`
HostDNSDoHURL string `json:"host_dns_doh_url,omitempty"`
// EnableHypervisorSwitch unlocks the Hyper-V / WHPX boot launch switch in
// Settings for users who alternate with exclusive-mode VMware. Off by
// default; toggling this preference alone never alters Windows boot config.
EnableHypervisorSwitch bool `json:"enable_hypervisor_switch,omitempty"`
FullscreenHotkeyEnabled bool `json:"fullscreen_hotkey_enabled,omitempty"`
FullscreenHotkey string `json:"fullscreen_hotkey,omitempty"`
}
// ShouldMinimizeToTray returns true when closing the main window should hide to tray.
func (c *Config) ShouldMinimizeToTray() bool {
if c == nil || c.MinimizeToTray == nil {
return true
}
return *c.MinimizeToTray
}
func DefaultDataRoot() string {
if v := os.Getenv("REIMS_GO_DATA_ROOT"); v != "" {
return v
}
if runtime.GOOS == "windows" {
if st, err := os.Stat(`D:\`); err == nil && st.IsDir() {
return `D:\Data\reims-go`
}
}
home, err := os.UserHomeDir()
if err != nil {
return "reims-go-data"
}
return filepath.Join(home, "reims-go-data")
}
// ExpandHomePath resolves a leading ~ for the current user.
func ExpandHomePath(path string) string {
if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) {
return path
}
home, err := os.UserHomeDir()
if err != nil {
return path
}
if path == "~" {
return home
}
return filepath.Join(home, path[2:])
}
// CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the
// folder chosen at first launch (LocationPath), else DefaultDataRoot.
func CurrentDataRoot() string {
if v := os.Getenv("REIMS_GO_DATA_ROOT"); v != "" {
return v
}
if root, ok := ReadLocation(); ok {
return root
}
return DefaultDataRoot()
}
func DefaultConfigPath() string {
return filepath.Join(CurrentDataRoot(), "reims-go.json")
}
// LocationPath is the one small file kept outside the data folder: it records
// which folder was chosen, so the next launch finds it. %APPDATA%\reims-go on
// Windows. Everything else (runtimes, VMs, installers) lives in the data folder.
// REIMS_GO_LOCATION_FILE overrides it (testing the first-launch screen without
// touching the real pointer).
func LocationPath() string {
if p := os.Getenv("REIMS_GO_LOCATION_FILE"); p != "" {
return p
}
dir, err := os.UserConfigDir()
if err != nil {
return ""
}
return filepath.Join(dir, "reims-go", "location.json")
}
type location struct {
DataRoot string `json:"data_root"`
}
// ReadLocation returns the data folder chosen at first launch, if any.
func ReadLocation() (string, bool) {
p := LocationPath()
if p == "" {
return "", false
}
raw, err := os.ReadFile(p)
if err != nil {
return "", false
}
var loc location
if json.Unmarshal(raw, &loc) != nil || loc.DataRoot == "" {
return "", false
}
return loc.DataRoot, true
}
// SaveLocation records the chosen data folder for the next launch.
func SaveLocation(dataRoot string) error {
p := LocationPath()
if p == "" {
return errors.New("no user config directory")
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(location{DataRoot: dataRoot}, "", " ")
if err != nil {
return err
}
return os.WriteFile(p, append(data, '\n'), 0o644)
}
// Resolve loads the config for the app and reports whether first-launch setup
// is needed: no REIMS_GO_DATA_ROOT, no recorded folder, and no reims-go.json in
// the default folder. An install from before the picker existed (a config in
// the default folder) is adopted and recorded, so it is never asked again.
// legacyDataRoot is where installs before the first-launch picker kept their
// 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).
return Default(), true, nil
}
if os.Getenv("REIMS_GO_DATA_ROOT") != "" {
cfg, err = Load("")
return cfg, false, err
}
if _, ok := ReadLocation(); ok {
cfg, err = Load("")
return cfg, false, err
}
legacy := filepath.Join(legacyDataRoot(), "reims-go.json")
if _, statErr := os.Stat(legacy); statErr == nil {
cfg, err = Load(legacy)
if err == nil {
_ = SaveLocation(cfg.DataRoot)
}
return cfg, false, err
}
return Default(), true, nil
}
func Default() *Config {
return &Config{
DataRoot: CurrentDataRoot(),
Locale: i18n.Auto,
AutoPinPCores: true,
DefaultGPU: "auto",
}
}
func Load(path string) (*Config, error) {
if path == "" {
path = DefaultConfigPath()
}
raw, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Default(), nil
}
return nil, err
}
cfg := Default()
disk := struct {
*Config
FullscreenHotkeyEnabled json.RawMessage `json:"fullscreen_hotkey_enabled"`
FullscreenHotkey json.RawMessage `json:"fullscreen_hotkey"`
}{Config: cfg}
if err := json.Unmarshal(raw, &disk); err != nil {
return nil, err
}
if len(disk.FullscreenHotkeyEnabled) != 0 {
// The optional shortcut fields retain their defaults on a type mismatch.
_ = json.Unmarshal(disk.FullscreenHotkeyEnabled, &cfg.FullscreenHotkeyEnabled)
}
if len(disk.FullscreenHotkey) != 0 {
_ = json.Unmarshal(disk.FullscreenHotkey, &cfg.FullscreenHotkey)
cfg.FullscreenHotkey = strings.TrimSpace(cfg.FullscreenHotkey)
}
if cfg.DataRoot == "" {
cfg.DataRoot = filepath.Dir(path)
}
cfg.Locale = i18n.ParsePreference(string(cfg.Locale))
if cfg.RuntimeChannel == "candidate" {
cfg.RuntimeChannel = "alpha"
}
if cfg.AppUpdateChannel != "" {
switch cfg.AppUpdateChannel {
case "stable", "alpha", "dev":
default:
cfg.AppUpdateChannel = "stable"
}
}
return cfg, nil
}
func Save(path string, cfg *Config) error {
if path == "" {
path = filepath.Join(cfg.DataRoot, "reims-go.json")
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
return atomicfile.WriteJSON(path, cfg, 0o644)
}
func (c *Config) RuntimesDir() string { return filepath.Join(c.DataRoot, "runtimes") }
func (c *Config) XDGConfigDir() string { return filepath.Join(c.DataRoot, "config") }
func (c *Config) XDGDataDir() string { return filepath.Join(c.DataRoot, "data") }
func (c *Config) XDGCacheDir() string { return filepath.Join(c.DataRoot, "cache") }
func (c *Config) ImagesDir() string { return filepath.Join(c.DataRoot, "images") }
func (c *Config) TempDir() string { return filepath.Join(c.DataRoot, "tmp") }
func (c *Config) SharedDir() string { return filepath.Join(c.DataRoot, "shared") }
func (c *Config) EnsureDirs() error {
for _, d := range []string{
c.DataRoot,
c.RuntimesDir(),
c.XDGConfigDir(),
c.XDGDataDir(),
c.XDGCacheDir(),
c.ImagesDir(),
c.TempDir(),
c.SharedDir(),
} {
if err := os.MkdirAll(d, 0o755); err != nil {
return err
}
}
return nil
}