Files
Reims-Go/internal/cli/plugin.go
T
千川白浪 107a8d73e0 refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 (#200)
* refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积

* fix: preserve download recovery and bound PBZX decoding

Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle.
2026-12-05 20:54:41 +08:00

680 lines
20 KiB
Go

package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/version"
)
func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, *driver.Router, error) {
if err := guest.MigrateFiles(cfg.DataRoot); err != nil {
return nil, nil, err
}
logf := func(source, line string) {
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
}
mgr, router, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{
DataRoot: cfg.DataRoot,
SafeMode: safeMode,
LocaleFn: func() i18n.Locale {
return i18n.EffectiveLocale(cfg.Locale)
},
Logger: logf,
VMInventory: guest.VMInventory(),
Callbacks: builtin.HostCallbacks{
GetConfig: func() config.Config { return *cfg },
PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) {
return nil, checkDirectMacOSNetwork(ctx, cfg, name)
},
Log: logf,
},
RegisterGuest: guest.Register,
StrictRegister: true,
})
if err != nil {
return nil, nil, err
}
mgr.Registry().Reconcile(context.Background())
mgr.MarkBootComplete()
return mgr, router, nil
}
func openCLIMarketClient(cfg *config.Config) *plugin.MarketClient {
return plugin.NewMarketClient(plugin.MarketClientOptions{
Layout: plugin.NewPluginsLayout(cfg.DataRoot),
HostVersion: version.Version,
})
}
func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin <list|search|install|update|pack|link|enable|disable|remove|info|doctor|locale|run|connect>")
}
ctx := context.Background()
switch args[0] {
case "connect":
return pluginConnect(args[1:], cfg.DataRoot)
case "search":
return pluginSearch(ctx, cfg, loc, args[1:])
case "list":
return pluginList(cfg, loc, args[1:])
case "install":
return pluginInstall(ctx, cfg, loc, args[1:])
case "update":
return pluginUpdate(ctx, cfg, loc, args[1:])
case "pack":
return pluginPack(loc, args[1:])
case "link":
return pluginLink(ctx, cfg, loc, args[1:])
case "enable":
return pluginEnable(ctx, cfg, loc, args[1:])
case "disable":
return pluginDisable(ctx, cfg, loc, args[1:])
case "remove":
return pluginRemove(ctx, cfg, loc, args[1:])
case "info":
return pluginInfo(cfg, loc, args[1:])
case "doctor":
return pluginDoctor(cfg, loc, args[1:])
case "locale":
return cmdPluginLocale(loc, args[1:])
case "run":
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] <archive.zip|plugin-id>")
}
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 <id>-<version>.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] <dir>")
}
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 <dir>")
}
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] <id>")
}
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 <id>")
}
// 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] <id>")
}
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 <id>")
}
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 <id> <command> [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 {
if r.HardBlocked {
hasErr = true
}
}
if asJSON {
if len(reports) == 1 {
if err := printJSON(reports[0]); err != nil {
return err
}
} else {
if err := printJSON(reports); err != nil {
return err
}
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
for i, r := range reports {
if i > 0 {
fmt.Println("---")
}
fmt.Println(r.SummaryText(string(loc)))
}
if hasErr {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
return nil
}
func cmdPluginLocale(loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go plugin locale <init|check> ...")
}
switch args[0] {
case "init":
// Allow flags either before or after the positional <bcp47-locale> argument.
var flagArgs, posArgs []string
rest := args[1:]
for i := 0; i < len(rest); i++ {
a := rest[i]
if strings.HasPrefix(a, "-") {
flagArgs = append(flagArgs, a)
if !strings.Contains(a, "=") && i+1 < len(rest) && !strings.HasPrefix(rest[i+1], "-") {
i++
flagArgs = append(flagArgs, rest[i])
}
} else {
posArgs = append(posArgs, a)
}
}
fs := flag.NewFlagSet("plugin locale init", flag.ContinueOnError)
outDir := fs.String("out", "", "Output directory for the scaffolded language pack")
pluginID := fs.String("id", "", "Optional reverse-domain plugin ID (default: community.lang.<locale>)")
forPlugin := fs.String("for", "", "Optional target plugin ID to scaffold pluginOverrides for")
if err := fs.Parse(flagArgs); err != nil {
return err
}
posArgs = append(posArgs, fs.Args()...)
if len(posArgs) < 1 || strings.TrimSpace(*outDir) == "" {
return fmt.Errorf("usage: reims-go plugin locale init <bcp47-locale> --out <dir> [--id <plugin.id>] [--for <target.plugin>]")
}
if err := plugin.InitLocalePack(plugin.LocaleInitOptions{
Locale: posArgs[0],
OutDir: *outDir,
PluginID: *pluginID,
ForPlugin: *forPlugin,
}); err != nil {
return err
}
fmt.Printf("[ok] scaffolded language pack (%s) in %s\n", posArgs[0], *outDir)
return nil
case "check":
var flagArgs, posArgs []string
for _, a := range args[1:] {
if strings.HasPrefix(a, "-") {
flagArgs = append(flagArgs, a)
} else {
posArgs = append(posArgs, a)
}
}
fs := flag.NewFlagSet("plugin locale check", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output structured JSON report")
if err := fs.Parse(flagArgs); err != nil {
return err
}
posArgs = append(posArgs, fs.Args()...)
if len(posArgs) < 1 {
return fmt.Errorf("usage: reims-go plugin locale check [--json] <dir>")
}
reports, findings, err := plugin.CheckLocalePack(posArgs[0])
if err != nil {
return err
}
if *asJSON {
if err := printJSON(reports); err != nil {
return err
}
} else {
for _, rep := range reports {
fmt.Printf("Locale %s (%s): %d/%d translated (%.1f%%)\n",
rep.Locale, rep.PluginID, rep.TotalTranslated, rep.TotalReference, rep.TotalPercent)
for _, d := range rep.Domains {
fmt.Printf(" %-15s %4d/%-4d (%5.1f%%)\n", d.Domain, d.Translated, d.Total, d.Percent)
}
}
for _, f := range findings {
if f.Check == "locale-coverage" {
continue
}
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
}
}
for _, f := range findings {
if f.Severity == "error" {
return fmt.Errorf("%s", i18n.T(loc, "plugin.doctor.errors"))
}
}
return nil
default:
return fmt.Errorf("unknown plugin locale subcommand %q (expected init or check)", args[0])
}
}