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>
59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package vmstart
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/Nwflower/reims-go/internal/atomicfile"
|
|
)
|
|
|
|
const vmNestedVirtConfigFile = ".reims-go-nested-virt.json"
|
|
|
|
// VMNestedVirtConfig is persisted per VM in <vmDir>/.reims-go-nested-virt.json. The switch is
|
|
// the VM's own; QEMU is told at each start (macosdriver.prepareNestedVirt).
|
|
type VMNestedVirtConfig struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
// ReadVMNestedVirt loads <vmDir>/.reims-go-nested-virt.json. A VM without the file has the
|
|
// switch off. A file that cannot be read is an error: the VM must not silently start without
|
|
// a feature that was switched on.
|
|
func ReadVMNestedVirt(vmDir string) (VMNestedVirtConfig, error) {
|
|
if strings.TrimSpace(vmDir) == "" {
|
|
return VMNestedVirtConfig{}, nil
|
|
}
|
|
path := filepath.Join(vmDir, vmNestedVirtConfigFile)
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return VMNestedVirtConfig{}, nil
|
|
}
|
|
if err != nil {
|
|
return VMNestedVirtConfig{}, err
|
|
}
|
|
var cfg VMNestedVirtConfig
|
|
if err := json.Unmarshal(data, &cfg); err != nil {
|
|
return VMNestedVirtConfig{}, fmt.Errorf("%s: %w", path, err)
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
// SaveVMNestedVirt writes the switch; off removes the file.
|
|
func SaveVMNestedVirt(vmDir string, cfg VMNestedVirtConfig) error {
|
|
if strings.TrimSpace(vmDir) == "" {
|
|
return errors.New("VM directory is empty")
|
|
}
|
|
dst := filepath.Join(vmDir, vmNestedVirtConfigFile)
|
|
if !cfg.Enabled {
|
|
if err := os.Remove(dst); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
return atomicfile.WriteJSON(dst, cfg, 0o600)
|
|
}
|