Declare the reims guest driver statically, merge the install guide into the optional macOS plugin, and keep compatibility settings under the new owner. Add data layout v2 with atomic state migration, ledger backups, targeted argument ownership moves, and idempotent v1 upgrade coverage. Reduce builtin.core to the default theme. Add a reverse import ratchet for internal/macos and document the transition. The macOS plugin remains enabled by default during migration; that default and the future privilege/trust rules remain subject to review.
702 lines
21 KiB
Go
702 lines
21 KiB
Go
package cli
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"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/macos/reims"
|
|
"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
|
|
}
|
|
mgr, err := plugin.NewManager(plugin.ManagerOptions{
|
|
DataRoot: cfg.DataRoot,
|
|
HostVersion: version.Version,
|
|
SafeMode: safeMode,
|
|
RedactFn: reims.RedactText,
|
|
LocaleFn: func() i18n.Locale {
|
|
return i18n.EffectiveLocale(cfg.Locale)
|
|
},
|
|
Logger: func(source, line string) {
|
|
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
|
},
|
|
SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any {
|
|
return driver.NewSidecarDriver(contrib, sup)
|
|
},
|
|
})
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
cb := builtin.HostCallbacks{
|
|
GetConfig: func() config.Config { return *cfg },
|
|
Log: func(source, line string) {
|
|
fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line)
|
|
},
|
|
}
|
|
router := driver.NewRouter(mgr.Registry(), func() string {
|
|
return filepath.Join(cfg.XDGDataDir(), "reims-ctl", "vms")
|
|
})
|
|
mgr.Registry().SetInUseChecker(func(pluginID string) (bool, string, error) {
|
|
seen := map[string]bool{}
|
|
candidates := append([]string{pluginID}, mgr.Registry().DeclaredDriverIDs(pluginID)...)
|
|
for _, did := range candidates {
|
|
if did == "" || seen[did] {
|
|
continue
|
|
}
|
|
seen[did] = true
|
|
if inUse, reason, err := router.CheckDriverInUse(context.Background(), did); err != nil || inUse {
|
|
return inUse, reason, err
|
|
}
|
|
}
|
|
return false, "", nil
|
|
})
|
|
if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
|
mgr.Close()
|
|
return nil, nil, err
|
|
}
|
|
if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil {
|
|
mgr.Close()
|
|
return nil, nil, err
|
|
}
|
|
_ = mgr.LoadExternal()
|
|
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>")
|
|
}
|
|
ctx := context.Background()
|
|
switch args[0] {
|
|
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
|
|
|
|
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().List())
|
|
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
|
|
|
|
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] <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
|
|
}
|
|
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
|
|
|
|
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
|
|
|
|
case "pack":
|
|
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[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] <dir>")
|
|
}
|
|
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
|
|
|
|
case "link":
|
|
if len(args) < 2 {
|
|
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[1])
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fmt.Println(i18n.T(loc, "plugin.linked", info.ID, info.Version, info.InstallDir))
|
|
return nil
|
|
|
|
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] <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
|
|
|
|
case "disable":
|
|
if len(args) < 2 {
|
|
return fmt.Errorf("usage: reims-go plugin disable <id>")
|
|
}
|
|
// Load in safeMode so a broken external plugin never prevents disabling it (M9).
|
|
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
|
|
|
|
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] <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
|
|
|
|
case "info":
|
|
if len(args) < 2 {
|
|
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[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)
|
|
|
|
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().List() {
|
|
fmt.Printf("[ok] %s@%s (%s, state=%s)\n", info.ID, info.Version, info.Source, info.State)
|
|
}
|
|
return nil
|
|
}
|
|
return printScanReports(loc, reports, *asJSON)
|
|
|
|
case "locale":
|
|
return cmdPluginLocale(loc, args[1:])
|
|
|
|
case "run":
|
|
if len(args) < 3 {
|
|
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[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)
|
|
|
|
default:
|
|
return fmt.Errorf("unknown plugin subcommand %q", args[0])
|
|
}
|
|
}
|
|
|
|
func printScanReports(loc i18n.Locale, reports []plugin.ScanReport, asJSON bool) error {
|
|
hasErr := false
|
|
for _, r := range reports {
|
|
if r.HardBlocked {
|
|
hasErr = true
|
|
}
|
|
}
|
|
if asJSON {
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
if len(reports) == 1 {
|
|
if err := enc.Encode(reports[0]); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
if err := enc.Encode(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 printDoctorFindings(loc i18n.Locale, findings []plugin.DoctorFinding) error {
|
|
hasErr := false
|
|
for _, f := range findings {
|
|
fmt.Printf("[%s] (%s) %s\n", f.Severity, f.Check, f.Message)
|
|
if f.Severity == "error" {
|
|
hasErr = true
|
|
}
|
|
}
|
|
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 {
|
|
enc := json.NewEncoder(os.Stdout)
|
|
enc.SetIndent("", " ")
|
|
if err := enc.Encode(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])
|
|
}
|
|
}
|