Files
Reims-Go/internal/cli/cli.go
T
千川白浪andClaude Opus 5.5 2f1e0bb0e4 feat(cli): fold the command line into reims-go.exe
Only reims-go.exe ships now; reims-go-cli.exe is gone. Without
arguments it opens the window, with a command it runs command-line mode
(cmd/reims-go moved to internal/cli). Missing standard handles are
attached to the parent console; handles the caller passes in (pipes,
files) are kept, so scripts and agents get output and exit codes.

`vm start` hands the VM to the window process so it gets Guest Tools
and the Win10 cold-reboot watcher, which a command that exits could not
run:
- a running window gets the request through Wails' single-instance
  protocol and stays hidden;
- otherwise the command launches the window tray-only (--background),
  detached from the caller's console and handles;
- the window writes the outcome, with the VM's last log lines on
  failure, to <DataRoot>\tmp\cli-start-*.json (it accepts no other
  path) and the command reports it.
With --data-root the VM still starts in the command itself.

The window now takes a single-instance lock: a second double-click
brings the running window forward. `wails dev` builds use their own
lock name.

Tested on Win10 19045 with macos-tahoe: start from the command line
with no window running (4 s, exit 0) and with one running (3 s, exit 0,
same process); the cold-reboot monitor was held by the window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:52:07 -07:00

515 lines
19 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/installer"
"github.com/Nwflower/reims-go/internal/opencore"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
"github.com/Nwflower/reims-go/internal/vmstart"
)
// Package cli is reims-go's command-line mode. The single reims-go.exe opens
// the desktop window when started without a command and runs this package
// when given one (see main.go); both share the internal/ packages.
// Main runs one command and returns the process exit code.
func Main(args []string) int {
if err := run(args); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return 1
}
return 0
}
// IsCommand reports whether args ask for command-line mode rather than the
// desktop window: anything except no arguments or the window's own flags.
func IsCommand(args []string) bool {
_, isWindow := ParseWindowArgs(args)
return !isWindow
}
func run(args []string) error {
fs := flag.NewFlagSet("reims-go", flag.ContinueOnError)
langFlag := fs.String("lang", "", "UI/CLI language: zh-CN | en-US")
dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory")
if err := fs.Parse(args); err != nil {
return err
}
cfgPath := ""
if *dataRootFlag != "" {
cfgPath = filepath.Join(*dataRootFlag, "reims-go.json")
}
cfg, err := config.Load(cfgPath)
if err != nil {
return err
}
if *dataRootFlag != "" {
cfg.DataRoot = *dataRootFlag
}
if *langFlag != "" {
cfg.Locale = i18n.Normalize(*langFlag)
}
loc := cfg.Locale
rest := fs.Args()
if len(rest) == 0 {
printUsage(loc)
return nil
}
switch rest[0] {
case "doctor":
return cmdDoctor(cfg, loc, rest[1:])
case "runtime":
return cmdRuntime(cfg, loc, rest[1:])
case "vm":
return cmdVM(cfg, loc, rest[1:], *dataRootFlag == "")
case "installer":
return cmdInstaller(cfg, loc, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return nil
case "help", "-h", "--help":
printUsage(loc)
return nil
default:
return fmt.Errorf("unknown command %q", rest[0])
}
}
func printUsage(loc i18n.Locale) {
if loc == i18n.ZhCN {
fmt.Println("reims-go - Windows 一站式免编译 reims-vgpu 启动器")
fmt.Println("\n用法:")
fmt.Println(" reims-go 打开界面(--background:只在托盘运行,不显示窗口)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <命令> [参数]")
fmt.Println("\n 在交互式 PowerShell / cmd 中提示符会先返回;要等命令结束并拿到退出码,请加 | Out-Host 或用管道。")
fmt.Println("\n命令:")
fmt.Println(" doctor 宿主机环境体检(WHPX / 显卡 ICD / P-E 核 / 磁盘 / 运行时)")
fmt.Println(" runtime available 列出 GitHub 上发布的运行时(--alpha 含 alpha 版)")
fmt.Println(" runtime fetch [commit] 在线下载、校验并安装运行时(默认最新;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" runtime install <archive> 导入并校验本地运行时包(.tar.zst 或 .zip)")
fmt.Println(" runtime list 查看已安装的便携运行时版本")
fmt.Println(" runtime use <commit> 切换当前激活运行时")
fmt.Println(" vm list 列出已创建的虚拟机")
fmt.Println(" vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)")
fmt.Println(" vm set [options] <name> 修改虚拟机配置(下次启动生效)")
fmt.Println(" vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)")
fmt.Println(" vm compact <name> 停机回收 .qcow2 磁盘未用空间")
fmt.Println(" vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动")
fmt.Println(" vm stop|eject <name> 停止 / 弹出安装盘")
fmt.Println(" vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)")
fmt.Println(" installer list 列出 Apple 提供的离线安装包版本(需联网)")
fmt.Println(" installer download <版本> 下载离线安装包(如 26.7.1、tahoe、latest;Ctrl+C 暂停,再次运行续传)")
fmt.Println(" installer cached 查看已下载的安装包及占用空间")
fmt.Println(" installer delete <文件名> 删除已下载的安装包(正在使用或下载中的会被拒绝)")
fmt.Println(" version 查看当前版本")
return
}
fmt.Println("reims-go - Portable one-stop reims-vgpu launcher for Windows")
fmt.Println("\nUsage:")
fmt.Println(" reims-go Open the window (--background: tray only, no window)")
fmt.Println(" reims-go [--lang zh-CN|en-US] [--data-root DIR] <command> [args]")
fmt.Println("\n Interactive PowerShell / cmd return to the prompt early; pipe the output (e.g. | Out-Host)")
fmt.Println(" to wait for the command and get its exit code.")
fmt.Println("\nCommands:")
fmt.Println(" doctor Inspect host (WHPX / Vulkan GPUs / P-E cores / disk / runtime)")
fmt.Println(" runtime available List runtimes published on GitHub (--alpha includes alpha builds)")
fmt.Println(" runtime fetch [commit] Download, verify and install a runtime (newest by default; Ctrl+C pauses)")
fmt.Println(" runtime install <archive> Verify and install a local runtime package (.tar.zst or .zip)")
fmt.Println(" runtime list List installed portable runtimes")
fmt.Println(" runtime use <commit> Activate an installed runtime version")
fmt.Println(" vm list List virtual machines")
fmt.Println(" vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)")
fmt.Println(" vm set [options] <name> Update VM settings (applies on next start)")
fmt.Println(" vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)")
fmt.Println(" vm compact <name> Compact stopped .qcow2 disk to reclaim unused space")
fmt.Println(" vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),")
fmt.Println(" with clipboard and shared folders; with --data-root it starts in this process")
fmt.Println(" vm stop|eject <name> Stop / eject installer")
fmt.Println(" vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)")
fmt.Println(" installer list List offline macOS installers Apple offers (needs network)")
fmt.Println(" installer download <ver> Download an offline installer (26.7.1, tahoe, latest; Ctrl+C pauses, rerun resumes)")
fmt.Println(" installer cached List downloaded installers and the space they take")
fmt.Println(" installer delete <name> Delete a downloaded installer (refused if in use or downloading)")
fmt.Println(" version Show current version")
}
func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error {
fs := flag.NewFlagSet("doctor", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args); err != nil {
return err
}
rep := host.Inspect(cfg.DataRoot)
active, _ := rt.ResolveActive(cfg)
if *asJSON {
payload := map[string]any{
"host": rep,
"config": cfg,
"runtime": active,
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(payload)
}
fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title"))
fmt.Printf("%-36s: %s/%s\n", i18n.T(loc, "doctor.os"), rep.OS, rep.Arch)
fmt.Printf("%-36s: %dC / %dT\n", i18n.T(loc, "doctor.cpu"), rep.PhysicalCores, rep.LogicalCPUs)
if rep.HasHybridCores {
fmt.Printf("%-36s: %d cores, mask %s (CPUs %v)\n", i18n.T(loc, "doctor.pcores"), rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs)
fmt.Printf("%-36s: %d cores (CPUs %v)\n", i18n.T(loc, "doctor.ecores"), rep.ECoreCount, rep.ECoreLogicalCPUs)
}
if rep.TotalRAMGB > 0 {
fmt.Printf("%-36s: %.1f GB total / %.1f GB avail\n", i18n.T(loc, "doctor.ram"), rep.TotalRAMGB, rep.AvailRAMGB)
}
if rep.FreeDiskGB > 0 {
fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot)
}
whpxKey := "doctor.whpx.unsupported"
switch rep.WHPX {
case host.WHPXReady:
whpxKey = "doctor.whpx.ok"
case host.WHPXNoHypervisor:
whpxKey = "doctor.whpx.no_hv"
case host.WHPXMissing:
whpxKey = "doctor.whpx.missing"
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey))
if len(rep.GPUs) == 0 {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.T(loc, "doctor.gpu.none"))
} else {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu"))
for _, g := range rep.GPUs {
rec := ""
if rep.RecommendedGPU != nil && rep.RecommendedGPU.VulkanICD == g.VulkanICD {
rec = " [" + i18n.T(loc, "doctor.gpu.recommended") + "]"
}
fmt.Printf(" - [%s] %s%s\n ICD: %s\n", g.Kind, g.Name, rec, g.VulkanICD)
}
}
if active == nil {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none"))
} else {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
}
return nil
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use>")
}
switch args[0] {
case "install":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime install <archive.tar.zst|zip>")
}
inst, err := rt.InstallFromArchive(cfg, args[1])
if err != nil {
return err
}
cfg.ActiveRuntime = inst.Commit
if err := config.Save("", cfg); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
return nil
case "list":
list, err := rt.List(cfg)
if err != nil {
return err
}
if len(list) == 0 {
fmt.Println(i18n.T(loc, "runtime.empty"))
return nil
}
for _, item := range list {
mark := " "
if item.Active {
mark = "*"
}
fmt.Printf("%s %s %s (%s)\n", mark, item.Commit, item.Manifest.QemuVersion, item.Dir)
}
return nil
case "use":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime use <commit>")
}
list, err := rt.List(cfg)
if err != nil {
return err
}
for _, item := range list {
if item.Commit == args[1] {
cfg.ActiveRuntime = item.Commit
if err := config.Save("", cfg); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", item.Commit))
return nil
}
}
return fmt.Errorf("runtime %q not found", args[1])
case "available":
return cmdRuntimeAvailable(cfg, loc, args[1:])
case "fetch":
return cmdRuntimeFetch(cfg, loc, args[1:])
default:
return fmt.Errorf("unknown runtime subcommand %q", args[0])
}
}
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
}
prep, err := vmstart.New(*cfg, func(line string) { fmt.Fprintln(os.Stderr, line) })
if err != nil {
return err
}
client, active := prep.Client, &prep.Runtime
ctx := context.Background()
switch args[0] {
case "list":
vms, err := client.ListRaw(ctx)
if err != nil {
return err
}
if len(vms) == 0 {
fmt.Println(i18n.T(loc, "vm.empty"))
return nil
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(vms)
case "create":
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
dir := fs.String("dir", "", "Custom VM directory")
macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)")
cpus := fs.Int("cpus", 8, "vCPU count")
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
guestLang := fs.String("guest-lang", opencore.DefaultGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
start := fs.Bool("start", false, "Start VM immediately after creation")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
startAfterCreate := *start
opts := reims.CreateOpts{
Name: name,
Dir: *dir,
MacOS: *macos,
CPUs: *cpus,
Memory: *mem,
DiskSize: *diskSize,
GPU: *gpu,
Capture: capture,
Logs: logs,
GuestLang: strings.TrimSpace(*guestLang),
Start: false,
}
existingVMs, _ := client.List(ctx)
if removed, rerr := reims.CleanAbortedCreateDir(cfg.XDGDataDir(), opts, existingVMs); rerr == nil && removed != "" {
fmt.Fprintf(os.Stderr, "Removed unfinished directory from earlier interrupted create: %s\n", removed)
}
if installer.ShouldPrefetchOcBinaryData(active.Manifest.UtilCommit, active.Manifest.UtilVersion) {
if err := installer.EnsureCachedAsset(ctx, cfg.XDGCacheDir(), installer.OcBinaryDataAsset, nil, nil); err != nil {
fmt.Fprintf(os.Stderr, "OpenCore resource pre-fetch skipped (reims-ctl will retry): %v\n", err)
}
}
if err := client.Create(ctx, opts, os.Stdout, os.Stderr); err != nil {
return err
}
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
if serr := client.Set(ctx, postSet, os.Stdout, os.Stderr); serr != nil {
fmt.Fprintf(os.Stderr, "Warning: could not apply post-create defaults: %v\n", serr)
}
}
if opts.GuestLang != "" {
vmDir := opts.Dir
if d, serr := client.Show(ctx, name); serr == nil && d.Directory != "" {
vmDir = d.Directory
} else if vmDir == "" {
vmDir = filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms", name)
}
if lerr := prep.ApplyGuestLang(ctx, vmDir, opts.GuestLang, false); lerr != nil {
fmt.Fprintf(os.Stderr, "Warning: could not apply macOS language (%s): %v\n", opts.GuestLang, lerr)
}
}
if startAfterCreate {
if err := startVM(ctx, cfg, prep, name, viaWindow); err != nil {
return err
}
}
fmt.Println("\n" + i18n.T(loc, "vm.install_guide.title"))
fmt.Println(i18n.T(loc, "vm.install_guide.step1"))
fmt.Println(i18n.T(loc, "vm.install_guide.step2"))
fmt.Println(i18n.T(loc, "vm.install_guide.step3", name))
return nil
case "set":
fs := flag.NewFlagSet("vm set", flag.ContinueOnError)
cpus := fs.Int("cpus", 0, "vCPU count")
mem := fs.String("memory", "", "RAM size")
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [flags] <name>")
}
setOpts := reims.SetOpts{
Name: fs.Arg(0),
CPUs: *cpus,
Memory: *mem,
GPU: *gpu,
Resolution: *res,
AudioBackend: strings.TrimSpace(*audioBackend),
GuestLang: strings.TrimSpace(*guestLang),
}
if reims.HasCtlSetChanges(setOpts) {
if err := client.Set(ctx, setOpts, os.Stdout, os.Stderr); err != nil {
return err
}
}
if setOpts.GuestLang != "" {
d, err := client.Show(ctx, setOpts.Name)
if err != nil {
return err
}
if err := prep.ApplyGuestLang(ctx, d.Directory, setOpts.GuestLang, d.State == "running"); err != nil {
return err
}
}
return nil
case "start":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm start <name>")
}
return startVM(ctx, cfg, prep, args[1], viaWindow)
case "stop":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm stop <name>")
}
return client.Stop(ctx, args[1], os.Stdout, os.Stderr)
case "eject":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm eject <name>")
}
return client.Eject(ctx, args[1], os.Stdout, os.Stderr)
case "type":
// Paste as keystrokes: the text argument, else stdin.
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm type <name> [text] (no text: read stdin)")
}
text := strings.Join(args[2:], " ")
if len(args) < 3 {
b, err := io.ReadAll(os.Stdin)
if err != nil {
return err
}
text = strings.TrimRight(string(b), "\r\n")
}
d, err := client.Show(ctx, args[1])
if err != nil {
return err
}
n, err := qmp.TypeIntoVM(ctx, d.Directory, text, nil)
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "vm.typed", n))
return nil
case "resize":
if len(args) < 3 {
return fmt.Errorf("usage: reims-go vm resize <name> <size> (e.g. 256G or +64G)")
}
d, err := client.Show(ctx, args[1])
if err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before resizing its disk", args[1])
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.ResizeDisk(ctx, active.QemuImgPath(), client.Env, diskPath, args[2], os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: expanded disk %.0f GB -> %.0f GB\nRun inside macOS Terminal to expand APFS:\n %s\n",
args[1], float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd)
return nil
case "compact":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go vm compact <name>")
}
d, err := client.Show(ctx, args[1])
if err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("stop %s before compacting its disk", args[1])
}
diskPath := resolveCLIDiskPath(d)
res, err := reims.CompactDisk(ctx, active.QemuImgPath(), client.Env, diskPath, os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("%s: compacted disk %.2f GB -> %.2f GB (reclaimed %.2f GB)\n",
args[1], float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))
return nil
default:
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
}
}
func resolveCLIDiskPath(d reims.VMDetail) string {
raw := strings.TrimSpace(d.Disk)
if idx := strings.Index(raw, " ("); idx > 0 {
raw = strings.TrimSpace(raw[:idx])
}
if raw != "" {
if filepath.IsAbs(raw) {
return raw
}
if d.Directory != "" {
return filepath.Join(d.Directory, raw)
}
}
if d.Directory != "" {
return filepath.Join(d.Directory, "disk.qcow2")
}
return ""
}