diff --git a/internal/cli/cli.go b/internal/cli/cli.go index f72a96b..7c92845 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -163,9 +163,7 @@ func cmdDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { "config": cfg, "runtime": active, } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(payload) + return printJSON(payload) } fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title")) @@ -380,18 +378,17 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error { func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { if len(args) == 0 { - return fmt.Errorf("usage: reims-go vm ") + return fmt.Errorf("usage: reims-go vm ") } ctx := context.Background() switch args[0] { case "list": - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() vms, err := svc.List(ctx) if len(vms) == 0 { if err != nil { @@ -400,155 +397,41 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.empty")) return nil } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return errors.Join(enc.Encode(vms), err) + return errors.Join(printJSON(vms), err) case "create": - fs := flag.NewFlagSet("vm create", flag.ContinueOnError) - driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") - 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", defaultMacOSGuestLang(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 := fs.Arg(0) - // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). - if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { - mgr, router, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - drv, err := router.DriverByID(*driverID) - if err != nil { - return err - } - req := driver.CreateRequest{ - DriverID: drv.ID(), - Name: name, - Dir: *dir, - Options: map[string]any{ - "cpus": *cpus, - "memory": *mem, - "disk_size": *diskSize, - }, - } - if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { - return fmt.Errorf("%s", issues[0].Message) - } - if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil { - return err - } - if *start { - svc := lifecycle.New(mgr.Registry(), router, nil) - _, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) - return err - } - return nil - } - return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow) + return vmCreate(ctx, cfg, loc, args[1:], viaWindow) case "set": - fs := flag.NewFlagSet("vm set", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - 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") - nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm set [--driver ] [flags] ") - } - changes := map[string]any{} - if *cpus != 0 { - changes["cpus"] = *cpus - } - if *mem != "" { - changes["memory"] = *mem - } - if *gpu != "" { - changes["gpu"] = *gpu - } - if *res != "" { - changes["resolution"] = *res - } - if *audioBackend != "" { - changes["audio_backend"] = *audioBackend - } - if *guestLang != "" { - changes["guest_lang"] = *guestLang - } - fs.Visit(func(f *flag.Flag) { - if f.Name == "nested-virt" { - changes["nested_virt"] = *nestedVirt - } - }) - return setVM(ctx, cfg, *driverID, fs.Arg(0), changes) + return vmSet(ctx, cfg, args[1:]) case "start": - fs := flag.NewFlagSet("vm start", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm start [--driver ] ") - } - return startVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow) + return startVM(ctx, cfg, driverID, name, viaWindow) case "stop": - fs := flag.NewFlagSet("vm stop", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm stop [--driver ] ") - } - return stopVM(ctx, cfg, *driverID, fs.Arg(0), false) + return stopVM(ctx, cfg, driverID, name) case "suspend": - fs := flag.NewFlagSet("vm suspend", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm suspend [--driver ] ") - } - return suspendVM(ctx, cfg, *driverID, fs.Arg(0)) + return suspendVM(ctx, cfg, driverID, name) case "resume": - fs := flag.NewFlagSet("vm resume", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm resume [--driver ] ") - } - return resumeVM(ctx, cfg, *driverID, fs.Arg(0), viaWindow) + return resumeVM(ctx, cfg, driverID, name, viaWindow) case "discard-suspend": - fs := flag.NewFlagSet("vm discard-suspend", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm discard-suspend [--driver ] ") - } - return discardSuspendVM(ctx, cfg, *driverID, fs.Arg(0)) + return discardSuspendVM(ctx, cfg, driverID, name) case "delete": fs := flag.NewFlagSet("vm delete", flag.ContinueOnError) driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") @@ -561,15 +444,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e } return deleteVM(ctx, cfg, *driverID, fs.Arg(0), *keepFiles) case "eject": - fs := flag.NewFlagSet("vm eject", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { + driverID, name, err := parseVMTarget(args) + if err != nil { return err } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm eject [--driver ] ") - } - return actionVM(ctx, cfg, *driverID, fs.Arg(0), "eject", nil) + return actionVM(ctx, cfg, driverID, name, "eject", nil) case "type": return typeMacOSVM(ctx, cfg, loc, args) case "resize": @@ -588,25 +467,140 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e fmt.Println(i18n.T(loc, "vm.resize.done", fs.Arg(0), float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd)) return nil case "compact": - fs := flag.NewFlagSet("vm compact", flag.ContinueOnError) - driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go vm compact [--driver ] ") - } - res, err := compactVM(ctx, cfg, *driverID, fs.Arg(0)) + driverID, name, err := parseVMTarget(args) if err != nil { return err } - fmt.Println(i18n.T(loc, "vm.compact.done", fs.Arg(0), float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30))) + res, err := compactVM(ctx, cfg, driverID, name) + if err != nil { + return err + } + fmt.Println(i18n.T(loc, "vm.compact.done", name, 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, " ")) } } +// parseVMTarget parses " [--driver ] ". +func parseVMTarget(args []string) (driverID, name string, err error) { + fs := flag.NewFlagSet("vm "+args[0], flag.ContinueOnError) + fs.StringVar(&driverID, "driver", "", "Owning driver ID when VM names are ambiguous") + if err := fs.Parse(args[1:]); err != nil { + return "", "", err + } + if fs.NArg() < 1 { + return "", "", fmt.Errorf("usage: reims-go vm %s [--driver ] ", args[0]) + } + return driverID, fs.Arg(0), nil +} + +func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error { + fs := flag.NewFlagSet("vm create", flag.ContinueOnError) + driverID := fs.String("driver", driver.BuiltinReimsMacOSDriverID, "Guest VM driver ID (default: builtin.driver.reims-macos)") + 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", defaultMacOSGuestLang(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); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm create [flags] ") + } + name := fs.Arg(0) + // Route non-reims guest drivers through the plugin Driver Router (§5.3, §10). + if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID { + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + drv, err := router.DriverByID(*driverID) + if err != nil { + return err + } + req := driver.CreateRequest{ + DriverID: drv.ID(), + Name: name, + Dir: *dir, + Options: map[string]any{ + "cpus": *cpus, + "memory": *mem, + "disk_size": *diskSize, + }, + } + if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 { + return fmt.Errorf("%s", issues[0].Message) + } + if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil { + return err + } + if *start { + svc := lifecycle.New(mgr.Registry(), router, nil) + _, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr) + return err + } + return nil + } + return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow) +} + +func vmSet(ctx context.Context, cfg *config.Config, args []string) error { + fs := flag.NewFlagSet("vm set", flag.ContinueOnError) + driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous") + 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") + nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go vm set [--driver ] [flags] ") + } + changes := map[string]any{} + if *cpus != 0 { + changes["cpus"] = *cpus + } + if *mem != "" { + changes["memory"] = *mem + } + if *gpu != "" { + changes["gpu"] = *gpu + } + if *res != "" { + changes["resolution"] = *res + } + if *audioBackend != "" { + changes["audio_backend"] = *audioBackend + } + if *guestLang != "" { + changes["guest_lang"] = *guestLang + } + fs.Visit(func(f *flag.Flag) { + if f.Name == "nested-virt" { + changes["nested_virt"] = *nestedVirt + } + }) + return setVM(ctx, cfg, *driverID, fs.Arg(0), changes) +} + +func printJSON(v any) error { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(v) +} + // 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 { diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 5966720..25e1d41 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -87,465 +87,487 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { case "connect": return pluginConnect(args[1:], cfg.DataRoot) case "search": - fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) - kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") - includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins") - refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index") - asJSON := fs.Bool("json", false, "Output JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - mc := openCLIMarketClient(cfg) - query := strings.TrimSpace(strings.Join(fs.Args(), " ")) - res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{ - Query: query, - Kind: *kind, - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - } - if res.Stale && res.FetchError != "" { - fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError) - } - for _, w := range res.WithdrawnInstalled { - fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc))) - if w.InsteadID != "" { - fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID) - } - fmt.Fprintln(os.Stderr) - } - if len(res.Items) == 0 { - fmt.Println(i18n.T(loc, "plugin.market.empty")) - return nil - } - for _, it := range res.Items { - status := it.Entry.Channel - switch { - case it.Withdrawn != nil: - status = "withdrawn" - case !it.Compatible: - status = "incompat" - case it.UpdateAvailable: - status = "update:" + it.InstalledVersion + "->" + it.Entry.Version - case it.Installed: - status = "installed" - } - kindLabel := it.Entry.Kind - if kindLabel == "" { - kindLabel = string(it.Entry.Tier) - } - if kindLabel == "" { - kindLabel = "-" - } - fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n", - it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc))) - } - return nil - + return pluginSearch(ctx, cfg, loc, args[1:]) case "list": - fs := flag.NewFlagSet("plugin list", flag.ContinueOnError) - asJSON := fs.Bool("json", false, "Output JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - list := mgr.LocalizePluginInfos(mgr.Registry().ListVisible()) - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(list) - } - for _, p := range list { - mark := " " - switch p.State { - case plugin.StateActive: - mark = "*" - case plugin.StateDegraded, plugin.StateFailed: - mark = "!" - } - fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n", - mark, p.ID, p.Version, p.Tier, p.Trust, p.State, p.Name.Get(string(loc))) - } - return nil - + return pluginList(cfg, loc, args[1:]) case "install": - fs := flag.NewFlagSet("plugin install", flag.ContinueOnError) - includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID") - refresh := fs.Bool("refresh", false, "Refresh market index before installing") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] ") - } - target := fs.Arg(0) - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - - isLocalFile := false - if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() { - isLocalFile = true - } else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) { - isLocalFile = true - } - - var info *plugin.PluginInfo - if isLocalFile { - info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{}) - } else { - mc := openCLIMarketClient(cfg) - info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - } - if err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - return nil - + return pluginInstall(ctx, cfg, loc, args[1:]) case "update": - fs := flag.NewFlagSet("plugin update", flag.ContinueOnError) - includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates") - refresh := fs.Bool("refresh", true, "Refresh market index before checking updates") - if err := fs.Parse(args[1:]); err != nil { - return err - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - mc := openCLIMarketClient(cfg) - if fs.NArg() > 0 { - id := fs.Arg(0) - if _, ok := mgr.Registry().Info(id); !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id)) - } - info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: *refresh, - }) - if uErr != nil { - return uErr - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - return nil - } - updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh) - if browse.Stale && browse.FetchError != "" { - fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError) - } - if len(updates) == 0 { - fmt.Println(i18n.T(loc, "plugin.market.up_to_date")) - return nil - } - for _, up := range updates { - info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{ - IncludeAlpha: *includeAlpha, - ForceRefresh: false, - }) - if uErr != nil { - return fmt.Errorf("update %s: %w", up.Entry.ID, uErr) - } - fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) - if info.NeedsApproval { - fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) - } - } - return nil - + return pluginUpdate(ctx, cfg, loc, args[1:]) case "pack": - fs := flag.NewFlagSet("plugin pack", flag.ContinueOnError) - outPath := fs.String("out", "", "Output .zip path (defaults to -.zip)") - contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") - signKeySpec := fs.String("sign-key", "", "Optional ed25519 private key (file path or hex/base64) to sign SHA256SUMS.sig") - asJSON := fs.Bool("json", false, "Output JSON summary") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin pack [--out file.zip] [--contract ui-contract.json] [--sign-key key] [--json] ") - } - var contract *plugin.UIContract - if *contractPath != "" { - raw, rErr := os.ReadFile(*contractPath) - if rErr != nil { - return rErr - } - var c plugin.UIContract - if rErr := json.Unmarshal(raw, &c); rErr != nil { - return fmt.Errorf("parse ui-contract.json: %w", rErr) - } - contract = &c - } - packOpts := plugin.PackOptions{ - HostVersion: version.Version, - Contract: contract, - OutputPath: *outPath, - } - if strings.TrimSpace(*signKeySpec) != "" { - pk, kErr := plugin.ParseEd25519PrivateKey(*signKeySpec) - if kErr != nil { - return fmt.Errorf("parse --sign-key: %w", kErr) - } - packOpts.SignKey = pk - } - res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts) - if pErr != nil { - if res.Report.HardBlocked && !*asJSON { - fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc))) - } - return pErr - } - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - } - fmt.Println(i18n.T(loc, "plugin.packed", res.PluginID, res.Version, res.OutputPath)) - fmt.Printf("SHA-256: %s\n", res.SHA256) - fmt.Printf("Size: %d bytes (%d files, signed=%v)\n", res.SizeBytes, res.FileCount, res.Signed) - return nil - + return pluginPack(loc, args[1:]) case "link": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin link ") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - info, err := mgr.LinkDev(ctx, args[1]) - if err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir)) - return nil - + return pluginLink(ctx, cfg, loc, args[1:]) case "enable": - fs := flag.NewFlagSet("plugin enable", flag.ContinueOnError) - approve := fs.Bool("approve-high-risk", false, "Explicitly approve high-risk permissions or community L3 execution") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() < 1 { - return fmt.Errorf("usage: reims-go plugin enable [--approve-high-risk] ") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Enable(ctx, fs.Arg(0), *approve); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.enabled", fs.Arg(0))) - return nil - + return pluginEnable(ctx, cfg, loc, args[1:]) case "disable": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin disable ") - } - // Load in safeMode so a broken external plugin never prevents disabling it. - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Disable(ctx, args[1]); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.disabled", args[1])) - return nil - + return pluginDisable(ctx, cfg, loc, args[1:]) case "remove": - fs := flag.NewFlagSet("plugin remove", flag.ContinueOnError) - purge := fs.Bool("purge", false, "Also delete plugin private data and logs") - if err := fs.Parse(args[1:]); err != nil { - return err - } - if fs.NArg() != 1 { - return fmt.Errorf("usage: reims-go plugin remove [--purge] ") - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - if err := mgr.Remove(ctx, fs.Arg(0), *purge); err != nil { - return err - } - fmt.Println(i18n.T(loc, "plugin.removed", fs.Arg(0), *purge)) - return nil - + return pluginRemove(ctx, cfg, loc, args[1:]) case "info": - if len(args) < 2 { - return fmt.Errorf("usage: reims-go plugin info ") - } - mgr, _, err := openCLIPluginManager(cfg, true) - if err != nil { - return err - } - defer mgr.Close() - info, ok := mgr.Registry().Info(args[1]) - if !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", args[1])) - } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(info) - + return pluginInfo(cfg, loc, args[1:]) case "doctor": - fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError) - contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") - asJSON := fs.Bool("json", false, "Output structured ScanReport JSON") - if err := fs.Parse(args[1:]); err != nil { - return err - } - var contract *plugin.UIContract - if *contractPath != "" { - raw, err := os.ReadFile(*contractPath) - if err != nil { - return err - } - var c plugin.UIContract - if err := json.Unmarshal(raw, &c); err != nil { - return fmt.Errorf("parse ui-contract.json: %w", err) - } - contract = &c - } - scanOpts := plugin.ScanOptions{Contract: contract, Keyring: plugin.DefaultKeyring()} - target := "" - if fs.NArg() > 0 { - target = fs.Arg(0) - } - // Direct directory or .zip archive inspection (developer & market CI workflow, §5.1). - if target != "" { - if st, err := os.Stat(target); err == nil { - if st.IsDir() { - rep := plugin.ScanDirectory(target, version.Version, scanOpts) - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - if strings.HasSuffix(strings.ToLower(target), ".zip") { - layout := plugin.NewPluginsLayout(cfg.DataRoot) - rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts) - if sErr != nil { - return sErr - } - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - } - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - if target != "" { - info, ok := mgr.Registry().Info(target) - if !ok { - return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target)) - } - if info.InstallDir == "" { - if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(plugin.ScanReport{ - PluginID: info.ID, - Version: info.Version, - Name: info.Name, - Tier: info.Tier, - Trust: info.Trust, - Passed: true, - Headline: plugin.LocalizedText{ - ZhCN: "内置插件状态正常", - EnUS: "Built-in plugin is healthy", - }, - }) - } - fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) - return nil - } - rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts) - return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) - } - // Audit all installed external plugins. - var reports []plugin.ScanReport - for _, info := range mgr.Registry().List() { - if info.InstallDir != "" { - reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)) - } - } - if len(reports) == 0 { - if *asJSON { - fmt.Println("[]") - return nil - } - for _, info := range mgr.Registry().ListVisible() { - fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) - } - return nil - } - return printScanReports(loc, reports, *asJSON) - + return pluginDoctor(cfg, loc, args[1:]) case "locale": return cmdPluginLocale(loc, args[1:]) - case "run": - if len(args) < 3 { - return fmt.Errorf("usage: reims-go plugin run [key=value...]") - } - mgr, _, err := openCLIPluginManager(cfg, false) - if err != nil { - return err - } - defer mgr.Close() - cmdArgs := map[string]any{} - for _, kv := range args[3:] { - k, v, ok := strings.Cut(kv, "=") - if !ok || strings.TrimSpace(k) == "" { - return fmt.Errorf("invalid argument %q (expected key=value)", kv) - } - cmdArgs[k] = v - } - res, err := mgr.Registry().InvokeCommand(ctx, args[1], args[2], cmdArgs) - if err != nil { - return err - } - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - return enc.Encode(res) - + return pluginRun(ctx, cfg, args[1:]) default: return fmt.Errorf("unknown plugin subcommand %q", args[0]) } } +func pluginSearch(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin search", flag.ContinueOnError) + kind := fs.String("kind", "", "Filter by plugin kind (theme, locale, driver, tool, template, runtime)") + includeAlpha := fs.Bool("alpha", false, "Include alpha channel plugins") + refresh := fs.Bool("refresh", false, "Bypass cache and refresh market index") + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + query := strings.TrimSpace(strings.Join(fs.Args(), " ")) + res := mc.Browse(ctx, mgr.Registry().List(), plugin.MarketBrowseOptions{ + Query: query, + Kind: *kind, + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if *asJSON { + return printJSON(res) + } + if res.Stale && res.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), res.FetchError) + } + for _, w := range res.WithdrawnInstalled { + fmt.Fprintf(os.Stderr, "[warn] %s: %s", w.ID, w.Reason.Get(string(loc))) + if w.InsteadID != "" { + fmt.Fprintf(os.Stderr, " -> %s", w.InsteadID) + } + fmt.Fprintln(os.Stderr) + } + if len(res.Items) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.empty")) + return nil + } + for _, it := range res.Items { + status := it.Entry.Channel + switch { + case it.Withdrawn != nil: + status = "withdrawn" + case !it.Compatible: + status = "incompat" + case it.UpdateAvailable: + status = "update:" + it.InstalledVersion + "->" + it.Entry.Version + case it.Installed: + status = "installed" + } + kindLabel := it.Entry.Kind + if kindLabel == "" { + kindLabel = string(it.Entry.Tier) + } + if kindLabel == "" { + kindLabel = "-" + } + fmt.Printf("%-34s %-10s %-8s %-9s %-18s %s\n", + it.Entry.ID, it.Entry.Version, kindLabel, it.Entry.Trust, status, it.Entry.Name.Get(string(loc))) + } + return nil +} + +func pluginList(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin list", flag.ContinueOnError) + asJSON := fs.Bool("json", false, "Output JSON") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + list := mgr.LocalizePluginInfos(mgr.Registry().ListVisible()) + if *asJSON { + return printJSON(list) + } + for _, p := range list { + mark := " " + switch p.State { + case plugin.StateActive: + mark = "*" + case plugin.StateDegraded, plugin.StateFailed: + mark = "!" + } + fmt.Printf("%s %-34s %-8s %-8s %-9s %-8s %s\n", + mark, p.ID, p.Version, p.Tier, p.Trust, p.State, p.Name.Get(string(loc))) + } + return nil +} + +func pluginInstall(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin install", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel when installing by market plugin ID") + refresh := fs.Bool("refresh", false, "Refresh market index before installing") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin install [--alpha] [--refresh] ") + } + target := fs.Arg(0) + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + + isLocalFile := false + if st, statErr := os.Stat(target); statErr == nil && !st.IsDir() { + isLocalFile = true + } else if strings.HasSuffix(strings.ToLower(target), ".zip") || strings.ContainsAny(target, `/\`) { + isLocalFile = true + } + + var info *plugin.PluginInfo + if isLocalFile { + info, err = mgr.InstallLocalArchive(ctx, target, plugin.PackageInstallOptions{}) + } else { + mc := openCLIMarketClient(cfg) + info, err = mc.InstallFromMarket(ctx, mgr, target, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + } + if err != nil { + return err + } + printInstalled(loc, info) + return nil +} + +func pluginUpdate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin update", flag.ContinueOnError) + includeAlpha := fs.Bool("alpha", false, "Allow alpha channel updates") + refresh := fs.Bool("refresh", true, "Refresh market index before checking updates") + if err := fs.Parse(args); err != nil { + return err + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + mc := openCLIMarketClient(cfg) + if fs.NArg() > 0 { + id := fs.Arg(0) + if _, ok := mgr.Registry().Info(id); !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", id)) + } + info, uErr := mc.InstallFromMarket(ctx, mgr, id, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: *refresh, + }) + if uErr != nil { + return uErr + } + printInstalled(loc, info) + return nil + } + updates, browse := mc.CheckUpdates(ctx, mgr.Registry().List(), *includeAlpha, *refresh) + if browse.Stale && browse.FetchError != "" { + fmt.Fprintf(os.Stderr, "[warn] %s (%s)\n", i18n.T(loc, "plugin.market.stale_warn"), browse.FetchError) + } + if len(updates) == 0 { + fmt.Println(i18n.T(loc, "plugin.market.up_to_date")) + return nil + } + for _, up := range updates { + info, uErr := mc.InstallFromMarket(ctx, mgr, up.Entry.ID, plugin.MarketInstallOptions{ + IncludeAlpha: *includeAlpha, + ForceRefresh: false, + }) + if uErr != nil { + return fmt.Errorf("update %s: %w", up.Entry.ID, uErr) + } + printInstalled(loc, info) + } + return nil +} + +func pluginPack(loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin pack", flag.ContinueOnError) + outPath := fs.String("out", "", "Output .zip path (defaults to -.zip)") + contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") + signKeySpec := fs.String("sign-key", "", "Optional ed25519 private key (file path or hex/base64) to sign SHA256SUMS.sig") + asJSON := fs.Bool("json", false, "Output JSON summary") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin pack [--out file.zip] [--contract ui-contract.json] [--sign-key key] [--json] ") + } + contract, err := loadUIContract(*contractPath) + if err != nil { + return err + } + packOpts := plugin.PackOptions{ + HostVersion: version.Version, + Contract: contract, + OutputPath: *outPath, + } + if strings.TrimSpace(*signKeySpec) != "" { + pk, kErr := plugin.ParseEd25519PrivateKey(*signKeySpec) + if kErr != nil { + return fmt.Errorf("parse --sign-key: %w", kErr) + } + packOpts.SignKey = pk + } + res, pErr := plugin.PackDirectory(fs.Arg(0), packOpts) + if pErr != nil { + if res.Report.HardBlocked && !*asJSON { + fmt.Fprintln(os.Stderr, res.Report.SummaryText(string(loc))) + } + return pErr + } + if *asJSON { + return printJSON(res) + } + fmt.Println(i18n.T(loc, "plugin.packed", res.PluginID, res.Version, res.OutputPath)) + fmt.Printf("SHA-256: %s\n", res.SHA256) + fmt.Printf("Size: %d bytes (%d files, signed=%v)\n", res.SizeBytes, res.FileCount, res.Signed) + return nil +} + +func pluginLink(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin link ") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + info, err := mgr.LinkDev(ctx, args[0]) + if err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir)) + return nil +} + +func pluginEnable(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin enable", flag.ContinueOnError) + approve := fs.Bool("approve-high-risk", false, "Explicitly approve high-risk permissions or community L3 execution") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() < 1 { + return fmt.Errorf("usage: reims-go plugin enable [--approve-high-risk] ") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Enable(ctx, fs.Arg(0), *approve); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.enabled", fs.Arg(0))) + return nil +} + +func pluginDisable(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin disable ") + } + // Load in safeMode so a broken external plugin never prevents disabling it. + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Disable(ctx, args[0]); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.disabled", args[0])) + return nil +} + +func pluginRemove(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin remove", flag.ContinueOnError) + purge := fs.Bool("purge", false, "Also delete plugin private data and logs") + if err := fs.Parse(args); err != nil { + return err + } + if fs.NArg() != 1 { + return fmt.Errorf("usage: reims-go plugin remove [--purge] ") + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + if err := mgr.Remove(ctx, fs.Arg(0), *purge); err != nil { + return err + } + fmt.Println(i18n.T(loc, "plugin.removed", fs.Arg(0), *purge)) + return nil +} + +func pluginInfo(cfg *config.Config, loc i18n.Locale, args []string) error { + if len(args) < 1 { + return fmt.Errorf("usage: reims-go plugin info ") + } + mgr, _, err := openCLIPluginManager(cfg, true) + if err != nil { + return err + } + defer mgr.Close() + info, ok := mgr.Registry().Info(args[0]) + if !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.not_found", args[0])) + } + return printJSON(info) +} + +func pluginDoctor(cfg *config.Config, loc i18n.Locale, args []string) error { + fs := flag.NewFlagSet("plugin doctor", flag.ContinueOnError) + contractPath := fs.String("contract", "", "Optional path to ui-contract.json for CSS validation") + asJSON := fs.Bool("json", false, "Output structured ScanReport JSON") + if err := fs.Parse(args); err != nil { + return err + } + contract, err := loadUIContract(*contractPath) + if err != nil { + return err + } + scanOpts := plugin.ScanOptions{Contract: contract, Keyring: plugin.DefaultKeyring()} + target := "" + if fs.NArg() > 0 { + target = fs.Arg(0) + } + // Direct directory or .zip archive inspection (developer & market CI workflow, §5.1). + if target != "" { + if st, err := os.Stat(target); err == nil { + if st.IsDir() { + rep := plugin.ScanDirectory(target, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + if strings.HasSuffix(strings.ToLower(target), ".zip") { + layout := plugin.NewPluginsLayout(cfg.DataRoot) + rep, sErr := plugin.ScanArchive(target, layout.TmpDir(), version.Version, scanOpts) + if sErr != nil { + return sErr + } + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + } + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + if target != "" { + info, ok := mgr.Registry().Info(target) + if !ok { + return fmt.Errorf("%s", i18n.T(loc, "plugin.target_not_found", target)) + } + if info.InstallDir == "" { + if *asJSON { + return printJSON(plugin.ScanReport{ + PluginID: info.ID, + Version: info.Version, + Name: info.Name, + Tier: info.Tier, + Trust: info.Trust, + Passed: true, + Headline: plugin.LocalizedText{ + ZhCN: "内置插件状态正常", + EnUS: "Built-in plugin is healthy", + }, + }) + } + fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) + return nil + } + rep := plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts) + return printScanReports(loc, []plugin.ScanReport{rep}, *asJSON) + } + // Audit all installed external plugins. + var reports []plugin.ScanReport + for _, info := range mgr.Registry().List() { + if info.InstallDir != "" { + reports = append(reports, plugin.ScanDirectory(info.InstallDir, version.Version, scanOpts)) + } + } + if len(reports) == 0 { + if *asJSON { + fmt.Println("[]") + return nil + } + for _, info := range mgr.Registry().ListVisible() { + fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State) + } + return nil + } + return printScanReports(loc, reports, *asJSON) +} + +func pluginRun(ctx context.Context, cfg *config.Config, args []string) error { + if len(args) < 2 { + return fmt.Errorf("usage: reims-go plugin run [key=value...]") + } + mgr, _, err := openCLIPluginManager(cfg, false) + if err != nil { + return err + } + defer mgr.Close() + cmdArgs := map[string]any{} + for _, kv := range args[2:] { + k, v, ok := strings.Cut(kv, "=") + if !ok || strings.TrimSpace(k) == "" { + return fmt.Errorf("invalid argument %q (expected key=value)", kv) + } + cmdArgs[k] = v + } + res, err := mgr.Registry().InvokeCommand(ctx, args[0], args[1], cmdArgs) + if err != nil { + return err + } + return printJSON(res) +} + +func printInstalled(loc i18n.Locale, info *plugin.PluginInfo) { + fmt.Println(i18n.T(loc, "plugin.installed", info.ID, info.Version, info.Trust, info.Tier)) + if info.NeedsApproval { + fmt.Println(i18n.T(loc, "plugin.needs_approval", info.ID)) + } +} + +// loadUIContract reads the ui-contract.json used for CSS validation. An empty +// path means no contract. +func loadUIContract(path string) (*plugin.UIContract, error) { + if path == "" { + return nil, nil + } + raw, err := os.ReadFile(path) + if err != nil { + return nil, err + } + var c plugin.UIContract + if err := json.Unmarshal(raw, &c); err != nil { + return nil, fmt.Errorf("parse ui-contract.json: %w", err) + } + return &c, nil +} + func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) error { hasErr := false for _, r := range reports { @@ -554,14 +576,12 @@ func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) } } if asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") if len(reports) == 1 { - if err := enc.Encode(reports[0]); err != nil { + if err := printJSON(reports[0]); err != nil { return err } } else { - if err := enc.Encode(reports); err != nil { + if err := printJSON(reports); err != nil { return err } } @@ -648,9 +668,7 @@ func cmdPluginLocale(loc i18n.Locale, args []string) error { return err } if *asJSON { - enc := json.NewEncoder(os.Stdout) - enc.SetIndent("", " ") - if err := enc.Encode(reports); err != nil { + if err := printJSON(reports); err != nil { return err } } else { diff --git a/internal/cli/start.go b/internal/cli/start.go index 078a7ff..9d24bd1 100644 --- a/internal/cli/start.go +++ b/internal/cli/start.go @@ -21,6 +21,14 @@ import ( // report back. Preparation can rebuild the OpenCore image before QEMU starts. const startHandoffTimeout = 5 * time.Minute +func openCLILifecycle(cfg *config.Config) (*lifecycle.Service, func(), error) { + mgr, router, err := openCLIPluginManager(cfg, false) + if err != nil { + return nil, nil, err + } + return lifecycle.New(mgr.Registry(), router, nil), mgr.Close, nil +} + // startVM resolves the VM, then hands it to the desktop window: the // one already running, or a new one in the tray (`--background`). The window // runs the GUI's StartVM, so a VM started from the command line gets Guest @@ -29,12 +37,11 @@ const startHandoffTimeout = 5 * time.Minute // // 显式传入管理器当前数据目录仍交给管理器;其他目录的桥接禁止直接启动。 func startVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -50,64 +57,58 @@ func startVM(ctx context.Context, cfg *config.Config, driverID, name string, via } func actionVM(ctx context.Context, cfg *config.Config, driverID, name, action string, params map[string]any) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, err = svc.InvokeAction(ctx, driver.VMRef{DriverID: driverID, Name: name}, action, params) return err } func setVM(ctx context.Context, cfg *config.Config, driverID, name string, changes map[string]any) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.Set(ctx, driver.VMRef{DriverID: driverID, Name: name}, changes, os.Stdout, os.Stderr) } func deleteVM(ctx context.Context, cfg *config.Config, driverID, name string, keepFiles bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.Delete(ctx, driver.VMRef{DriverID: driverID, Name: name}, keepFiles, os.Stdout, os.Stderr) } func resizeVM(ctx context.Context, cfg *config.Config, driverID, name, newSize string) (driver.DiskResizeResult, error) { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskResizeResult{}, err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.ResizeDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, newSize, os.Stdout, os.Stderr) } func compactVM(ctx context.Context, cfg *config.Config, driverID, name string) (driver.DiskCompactResult, error) { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return driver.DiskCompactResult{}, err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() return svc.CompactDisk(ctx, driver.VMRef{DriverID: driverID, Name: name}, os.Stdout, os.Stderr) } -func stopVM(ctx context.Context, cfg *config.Config, driverID, name string, force bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) +func stopVM(ctx context.Context, cfg *config.Config, driverID, name string) error { + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) - return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, force, os.Stdout, os.Stderr) + defer closeService() + return svc.Stop(ctx, driver.VMRef{DriverID: driverID, Name: name}, false, os.Stdout, os.Stderr) } func startInWindow(ctx context.Context, cfg *config.Config, driverID, name string) error { diff --git a/internal/cli/suspend.go b/internal/cli/suspend.go index dcd6ef2..f9c101c 100644 --- a/internal/cli/suspend.go +++ b/internal/cli/suspend.go @@ -9,17 +9,15 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/vmstart" ) func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -34,12 +32,11 @@ func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) e } func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string, viaWindow bool) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { return err @@ -76,12 +73,11 @@ func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string, vi } func discardSuspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error { - mgr, router, err := openCLIPluginManager(cfg, false) + svc, closeService, err := openCLILifecycle(cfg) if err != nil { return err } - defer mgr.Close() - svc := lifecycle.New(mgr.Registry(), router, nil) + defer closeService() if err := svc.DiscardSuspend(ctx, driver.VMRef{DriverID: driverID, Name: name}); err != nil { return err }