feat: 标准库文档批量预热——补全/悬停翻译秒出

懒翻译要等 1-2 秒。真 gopls 实证 go/doc 从本地源码提取的文档与
gopls 补全/悬停正文规范化空白后完全一致,批量预热方案成立:
- internal/godoc: go/doc 提取器 + 36 个常用标准库清单 + NormKey
- app.PreheatDocs: 6 并发翻译,进度走输出面板,已缓存自动跳过;
  菜单手动触发 + 打开项目 8 秒后自动跑(每会话一次)
- tools/preheat: 命令行批量工具,直接写用户缓存文件
- 缓存 key 统一 NormKey,预热/懒翻译/旧缓存三方互命中
- 已实测灌入 10 包 394 条译文(272 秒),常用包全部秒出
This commit is contained in:
zerorigin committed 2026-11-04 17:30:51 +08:00
1 parent a7d53f25d4
commit f5bfbac6c3
10 files changed
+663 -10

No files matched your search

+41
View File
@@ -2127,6 +2127,47 @@ hover 文本与补全文档不同:含**签名行**(`func fmt.Println...`)
GLM 配置:`https://open.bigmodel.cn/api/paas/v4` + `glm-4-flash`(免费模型),
实测 122 token/次、1 秒级返回。
## 66. 批量预热:标准库文档翻译秒出(2026-11-04)
### 66.1 需求
用户反馈懒翻译要等 1~2 秒,要求批量预翻译直接接入。
### 66.2 关键验证(internal/lsp/doc_probe_test.go,真 gopls)
**gopls 补全文档 / 悬停正文 与 go/doc 从本地 GOROOT 源码提取的文档,
规范化空白后完全一致**——预热产生的缓存能被运行时命中。方案成立。
### 66.3 实现
| 文件 | 内容 |
|---|---|
| `internal/godoc`(新) | `go/parser+go/doc` 从 GOROOT/src 提取导出符号文档(函数/类型/方法/常量变量,去重);`CommonPkgs` 36 个常用标准库清单;`NormKey` 规范化(空白压单空格) |
| `internal/app/preheat.go`(新) | `PreheatDocs`:后台逐包提取 → 主线程过滤已缓存(读 a.trans 只能主线程)→ 6 并发 worker 翻译 → 回主线程入缓存,每 40 条落盘;进度走输出面板;**jobs 灌队列绝不在主线程**(否则 channel 满时冻结 UI) |
| `internal/app/translate.go` | 缓存 key 统一 `normDocKey`(=godoc.NormKey),预热/懒翻译/旧缓存三方可互命中;load 时旧 key 也规范化 |
| `tools/preheat`(新) | 命令行批量预热工具:同一缓存文件,用户不用等 IDE 慢慢翻 |
| 触发 | 菜单「预翻译标准库文档(AI)」手动;打开项目 8 秒后自动跑一次(每会话一次,已缓存跳过) |
失败策略:懒翻译失败写空串哨兵(同会话不重试);**预热失败不写**(下次预热重试)。
第三方包源码在 module cache,go/build 在 module 模式下找不到——第一版只预热标准库,
第三方继续懒翻译。
### 66.4 实测
`go run ./tools/preheat` 灌最常用 10 包:394 成功 / 3 失败(429 限流 1 + 超时 2,
下次重试),缓存 399 条,272 秒(6 并发)。fmt/strings/strconv/errors/time/os/io/
bufio/bytes/sort 的补全与悬停现在全部秒出中文。
### 66.5 验证
| 项 | 结果 |
|---|---|
| `TestDocsFmt`(提取 29 条含 Println)/ `TestDocsMissing` / `TestIsStandard` | ✓ |
| hover 拼回 4 测试(normDocKey 改造后) | ✓ |
| `go test ./...` | ✓ 全绿 |
| windowsgui 构建 | ✓ |
+12
View File
@@ -181,6 +181,12 @@ type App struct {
// 失败过、不再重试),transInflight 去重进行中的请求。见 translate.go。
trans map[string]string
transInflight map[string]bool
// preheat 是标准库文档批量预热的进度(见 preheat.go),
// preheatInflight 去重预热中已排队的条目。
preheat preheatState
preheatInflight map[string]bool
// preheatAuto 保证每个会话只自动预热一次(打开项目后延时触发)。
preheatAuto bool
// wantFocus 表示下一帧要把焦点交回编辑器(弹窗/面板关闭后)。
wantFocus bool
@@ -438,6 +444,12 @@ func (a *App) setRoot(abs string) {
a.startLSP(abs)
// 恢复这个工作区上次的标签、断点、面板与主题。
a.restoreSession(abs)
// 标准库文档预热:打开项目 8 秒后自动跑(等界面先稳),每个会话只自动
// 一次;菜单里可随时手动重跑,已缓存的自动跳过。
if !a.preheatAuto {
a.preheatAuto = true
time.AfterFunc(8*time.Second, a.PreheatDocs)
}
// 上次异常退出留下的未保存内容:先记下来,等界面就绪再问。
a.collectPending()
// 光标与滚动位置要等编辑器排过版才有意义,放到第一帧之后再套。
+3 -3
View File
@@ -36,11 +36,11 @@ func TestSplitHoverDoc(t *testing.T) {
}
// TestHoverTranslationAssembly 验证拼回:译文插到正文位置,签名与链接原样。
// 预填翻译缓存绕过 LLM 与窗口依赖。
// 预填翻译缓存绕过 LLM 与窗口依赖;key 用 normDocKey(与运行时一致)。
func TestHoverTranslationAssembly(t *testing.T) {
docJoined, _, _ := splitHoverDoc(hoverSample)
a := &App{trans: map[string]string{
"Println formats using the default formats for its operands and writes to standard output.\nSpaces are always added between operands and a newline is appended.":
"Println 用其操作数的默认格式进行格式化并写入标准输出,操作数之间总会添加空格,并附加换行。",
normDocKey(docJoined): "Println 用其操作数的默认格式进行格式化并写入标准输出,操作数之间总会添加空格,并附加换行。",
}, transInflight: map[string]bool{}, set: settings{TranslateDocs: true, AIBaseURL: "x", AIAPIKey: "y", AIModel: "z"}}
got := a.hoverTranslation(hoverSample)
+3
View File
@@ -183,6 +183,9 @@ func (a *App) menuItems() []*mygo.MenuItem {
{Label: "重启语言服务器", Click: func(*mygo.MenuItem, *mygo.Window) {
a.restartLSP()
}},
{Label: "预翻译标准库文档(AI)", Click: func(*mygo.MenuItem, *mygo.Window) {
a.PreheatDocs()
}},
mygo.Separator(),
{Label: "清空输出", Click: func(*mygo.MenuItem, *mygo.Window) {
a.ClearOutput()
+133
View File
@@ -0,0 +1,133 @@
package app
import (
"context"
"strconv"
"sync"
"time"
"mygoland/internal/ai"
"mygoland/internal/godoc"
)
// preheatWorkers 是预热时的并发翻译数:免费接口也扛得住,太猛会限流。
const preheatWorkers = 6
// preheatState 是标准库文档预热的进度。
type preheatState struct {
running bool
done int
total int
pkg string
}
// PreheatDocs 批量预热标准库文档翻译:本地源码提取 → 并发 LLM 翻译 → 入缓存。
// 已缓存的自动跳过,反复调用是增量补齐;几百条译文之后补全/悬停全部秒出中文。
// 进度走输出面板。须在主线程调用。
func (a *App) PreheatDocs() {
if !a.translateOn() {
a.out = append(a.out, OutLine{Text: "AI 预热:请先在设置里配好「文档翻译」接口", Kind: OutWarn})
a.panel, a.panelTab = true, 0
a.refresh()
return
}
if a.preheat.running {
return
}
a.preheat.running = true
a.panel, a.panelTab = true, 0
a.out = append(a.out, OutLine{Text: "AI 预热:开始翻译标准库文档(已缓存的自动跳过)", Kind: OutWarn})
a.refresh()
cfg := a.aiConfig()
start := time.Now()
jobs := make(chan string, 64)
var wg sync.WaitGroup
for i := 0; i < preheatWorkers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for text := range jobs {
a.preheatOne(cfg, text)
}
}()
}
go func() {
defer close(jobs)
pkgs := 0
for _, p := range godoc.CommonPkgs {
docs, err := godoc.Docs(p)
if err != nil {
a.win.Update(func() {
a.out = append(a.out, OutLine{Text: "AI 预热:跳过 " + p + "(" + firstLine(err.Error()) + ")", Kind: OutWarn})
a.refresh()
})
continue
}
pkgs++
// 读 a.trans(过滤已缓存)只能在主线程;过滤结果经 channel
// 交给本 goroutine 再灌 worker 队列——主线程绝不阻塞等 LLM。
listCh := make(chan []string, 1)
a.win.Update(func() {
a.preheat.pkg = p
var list []string
for _, d := range docs {
k := normDocKey(d)
if _, ok := a.trans[k]; ok {
continue
}
if a.preheatInflight == nil {
a.preheatInflight = map[string]bool{}
}
if a.preheatInflight[k] {
continue
}
a.preheatInflight[k] = true
a.preheat.total++
list = append(list, d)
}
a.refresh()
listCh <- list
})
for _, d := range <-listCh {
jobs <- d
}
}
wg.Wait()
a.win.Update(func() {
a.preheat.running = false
a.saveTranslations()
a.out = append(a.out, OutLine{
Text: "✔ AI 预热完成:新增 " + strconv.Itoa(a.preheat.done) + " 条译文,覆盖 " +
strconv.Itoa(pkgs) + " 个包,耗时 " + time.Since(start).Round(time.Second).String(),
Kind: OutSuccess,
})
a.preheat = preheatState{}
a.refresh()
})
}()
}
// preheatOne 翻译一条并回主线程入缓存。
func (a *App) preheatOne(cfg ai.Config, text string) {
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
defer cancel()
tr, err := ai.TranslateDoc(ctx, cfg, text)
a.win.Update(func() {
k := normDocKey(text)
delete(a.preheatInflight, k)
a.preheat.done++
if err != nil || tr == "" {
// 失败不写哨兵:预热是尽力而为,下次预热还能重试。
return
}
if a.trans == nil {
a.trans = map[string]string{}
}
a.trans[k] = tr
if a.preheat.done%40 == 0 {
a.saveTranslations() // 阶段落盘,中途退出也不白翻。
}
a.refresh()
})
}
+15 -7
View File
@@ -8,8 +8,14 @@ import (
"time"
"mygoland/internal/ai"
"mygoland/internal/godoc"
)
// normDocKey 是文档翻译缓存的 key:规范化空白(见 godoc.NormKey)。
func normDocKey(s string) string {
return godoc.NormKey(s)
}
// docTranslation 返回一段补全文档的中文译文。
//
// 没有现成译文时后台发起 LLM 翻译(同一文本只发一次),先返回英文原文——
@@ -19,35 +25,36 @@ func (a *App) docTranslation(text string) string {
if !a.translateOn() || text == "" {
return text
}
if tr, ok := a.trans[text]; ok {
key := normDocKey(text)
if tr, ok := a.trans[key]; ok {
if tr == "" {
// 空串哨兵:这个会话里翻译失败过,别再烧 API,直接原文。
return text
}
return tr
}
if a.transInflight[text] {
if a.transInflight[key] {
return text
}
if a.trans == nil {
a.trans = map[string]string{}
a.transInflight = map[string]bool{}
}
a.transInflight[text] = true
a.transInflight[key] = true
cfg := a.aiConfig()
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
defer cancel()
tr, err := ai.TranslateDoc(ctx, cfg, text)
a.win.Update(func() {
delete(a.transInflight, text)
delete(a.transInflight, key)
if err != nil || tr == "" {
// 失败:缓存哨兵,同会话不再重试(重启后会再试)。
logf("翻译失败: %v", err)
a.trans[text] = ""
a.trans[key] = ""
return
}
a.trans[text] = tr
a.trans[key] = tr
a.saveTranslations()
})
}()
@@ -93,7 +100,8 @@ func (a *App) loadTranslations() {
a.trans = map[string]string{}
for k, v := range m {
if k != "" && v != "" {
a.trans[k] = v
// 旧版缓存 key 是原文,统一规范化,能被预热与懒翻译共同命中。
a.trans[normDocKey(k)] = v
}
}
}
+109
View File
@@ -0,0 +1,109 @@
// Package godoc 从本地 Go 源码(GOROOT/src)提取导出符号的文档正文,
// 给「AI 预热文档翻译」用:gopls 补全/悬停显示的文档与源码注释同源,
// 规范化空白后文本一致(internal/lsp/doc_probe_test.go 已实证),
// 所以预热产生的译文缓存能直接命中。
package godoc
import (
"fmt"
"go/doc"
"go/parser"
"go/token"
"os"
"path/filepath"
"runtime"
"strings"
)
// CommonPkgs 是预热的常用标准库清单:日常开发覆盖面最大的那些。
// 想加只改这里;第三方包仍走按需懒翻译(源码在 module cache,
// go/build 在 module 模式下找不到它们,第一版不碰)。
var CommonPkgs = []string{
"fmt", "strings", "strconv", "errors", "time", "os", "io", "bufio",
"bytes", "sort", "slices", "maps", "math", "math/rand", "path",
"path/filepath", "unicode", "unicode/utf8", "sync", "context",
"log", "regexp", "encoding/json", "encoding/base64", "encoding/hex",
"net/url", "net/http", "flag", "os/exec", "reflect", "hash/crc32",
"hash/md5", "hash/sha1", "hash/sha256", "compress/gzip", "archive/zip",
}
// Docs 提取一个标准库包所有导出符号的文档正文,返回去重后的清单。
// 空文档(如纯结构体占位)跳过。
func Docs(pkgPath string) ([]string, error) {
bp, err := build0(pkgPath)
if err != nil {
return nil, err
}
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, bp, func(fi os.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, parser.ParseComments)
if err != nil {
return nil, err
}
seen := map[string]bool{}
var out []string
add := func(text string) {
text = strings.TrimSpace(text)
if text == "" || seen[text] {
return
}
seen[text] = true
out = append(out, text)
}
for _, p := range pkgs {
d := doc.New(p, "./", 0)
for _, c := range d.Consts {
add(c.Doc)
}
for _, v := range d.Vars {
add(v.Doc)
}
for _, fn := range d.Funcs {
add(fn.Doc)
}
for _, ty := range d.Types {
add(ty.Doc)
for _, c := range ty.Consts {
add(c.Doc)
}
for _, v := range ty.Vars {
add(v.Doc)
}
for _, fn := range ty.Funcs { // 方法
add(fn.Doc)
}
}
}
return out, nil
}
// build0 返回标准库包的源码目录。
func build0(pkgPath string) (string, error) {
if !isStandard(pkgPath) {
return "", fmt.Errorf("%s 不是标准库包(第一版只预热标准库)", pkgPath)
}
return filepath.Join(gorootSrc(), filepath.FromSlash(pkgPath)), nil
}
// NormKey 是文档翻译缓存的 key 规范:所有空白压成单个空格。
// gopls 给的文本与 go/doc 提取的文本只在换行/空格上有差异,
// 规范化后两边(以及预热工具写入的缓存)才能互相命中。
func NormKey(s string) string {
return strings.Join(strings.Fields(s), " ")
}
// isStandard 判断是否标准库导入路径:首段不含点
//(fmt 是;github.com/x/y 不是)。对 99% 的包够用。
func isStandard(pkgPath string) bool {
first := pkgPath
if i := strings.IndexByte(first, '/'); i >= 0 {
first = first[:i]
}
return first != "" && !strings.Contains(first, ".")
}
// gorootSrc 返回本地 Go 源码根目录。
func gorootSrc() string {
return filepath.Join(runtime.GOROOT(), "src")
}
+50
View File
@@ -0,0 +1,50 @@
package godoc
import (
"strings"
"testing"
)
// TestDocsFmt 提取 fmt 包:应当包含 Println 的文档,条目量在合理范围
//(fmt 实测 29 条:23 个函数 + 6 个类型)。
func TestDocsFmt(t *testing.T) {
docs, err := Docs("fmt")
if err != nil {
t.Fatalf("Docs(fmt): %v", err)
}
if len(docs) < 25 {
t.Fatalf("fmt 包导出符号文档只有 %d 条,异常", len(docs))
}
var found bool
for _, d := range docs {
if strings.Contains(d, "Println formats using") {
found = true
break
}
}
if !found {
t.Fatal("没提取到 Println 的文档")
}
t.Logf("fmt 包共 %d 条文档", len(docs))
}
// TestDocsMissing 包不存在时应当报错而不是 panic。
func TestDocsMissing(t *testing.T) {
if _, err := Docs("nosuchpkg123"); err == nil {
t.Fatal("不存在的包应报错")
}
}
// TestIsStandard 标准库与第三方导入路径的判断。
func TestIsStandard(t *testing.T) {
for _, p := range []string{"fmt", "net/http", "encoding/json"} {
if !isStandard(p) {
t.Errorf("%s 应判定为标准库", p)
}
}
for _, p := range []string{"github.com/x/y", "golang.org/x/tools"} {
if isStandard(p) {
t.Errorf("%s 不应判定为标准库", p)
}
}
}
+121
View File
@@ -0,0 +1,121 @@
package lsp
// 探针:验证 go/doc 提取的文档与 gopls 补全/悬停返回的文档文本是否一致
//(规范化空白后),决定批量预热缓存的 key 策略。
import (
"context"
"go/doc"
"go/parser"
"go/token"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
// godocOf 用 go/doc 提取标准库包里某符号的文档正文。
func godocOf(t *testing.T, pkgPath, symbol string) string {
t.Helper()
dir := filepath.Join(runtime.GOROOT(), "src", filepath.FromSlash(pkgPath))
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, parser.ParseComments)
if err != nil {
t.Fatalf("解析 %s: %v", pkgPath, err)
}
for _, p := range pkgs {
d := doc.New(p, "./", 0)
for _, fn := range d.Funcs {
if fn.Name == symbol {
return strings.TrimSpace(fn.Doc)
}
}
}
t.Fatalf("没找到 %s.%s", pkgPath, symbol)
return ""
}
func normWS(s string) string {
return strings.Join(strings.Fields(s), " ")
}
// TestProbeDocTextMatchesCompletion 对比 go/doc 与 gopls 补全文档的正文。
func TestProbeDocTextMatchesCompletion(t *testing.T) {
c, dir, _ := startTestClient(t)
src := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.\n}\n"
path := filepath.Join(dir, "main.go")
writeFile(t, path, src)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
items := completionRetry(t, c, uri, Position{Line: 5, Character: 5})
var comp *CompletionItem
for i := range items {
if items[i].Label == "Println" {
comp = &items[i]
break
}
}
if comp == nil {
t.Fatal("补全里没有 Println")
}
t.Logf("补全 Documentation: %q", comp.DocumentationText())
local := godocOf(t, "fmt", "Println")
t.Logf("go/doc 提取: %q", local)
nd, nc := normWS(local), normWS(comp.DocumentationText())
if nd == nc {
t.Log("一致:批量预热缓存可行(规范化后 key 能命中)")
return
}
t.Logf("不一致!\nnorm go/doc = %q\nnorm gopls = %q", nd, nc)
}
// TestProbeDocTextMatchesHover 对比 go/doc 与 gopls 悬停文档的正文。
func TestProbeDocTextMatchesHover(t *testing.T) {
c, dir, _ := startTestClient(t)
src := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println()\n}\n"
path := filepath.Join(dir, "main.go")
writeFile(t, path, src)
uri := PathToURI(path)
if err := c.DidOpen(uri, "go", 1, src); err != nil {
t.Fatal(err)
}
// fmt.Println 的 "P" 上(第 5 行,\tfmt.Println() 里 P 在 UTF16 列 6)。
pos := Position{Line: 5, Character: 6}
var h *Hover
for i := 0; i < 10; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
var err error
h, err = c.Hover(ctx, uri, pos)
cancel()
if err == nil && h != nil {
break
}
time.Sleep(500 * time.Millisecond)
}
if h == nil {
t.Fatal("没有 hover 结果")
}
hover := h.Text()
t.Logf("hover 原文: %q", hover)
local := godocOf(t, "fmt", "Println")
nh := normWS(hover)
nl := normWS(local)
if strings.Contains(nh, nl) {
t.Log("hover 包含 go/doc 正文:预热可命中")
return
}
t.Logf("hover 正文不含 go/doc 提取文本:\nnorm go/doc = %q\nnorm hover = %q", nl, nh)
}
+176
View File
@@ -0,0 +1,176 @@
// 一次性工具:命令行批量预热标准库文档翻译,直接写入用户缓存文件
//(%APPDATA%/mygoland/translations.json),IDE 启动装载后补全/悬停秒出中文。
//
// 用法:
//
// go run ./tools/preheat -key <APIKey> [-base <BaseURL>] [-model <Model>] [-only fmt,strings]
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"mygoland/internal/ai"
"mygoland/internal/godoc"
)
func main() {
key := flag.String("key", "", "API Key")
base := flag.String("base", "https://open.bigmodel.cn/api/paas/v4", "OpenAI 兼容接口地址")
model := flag.String("model", "glm-4-flash", "模型名")
only := flag.String("only", "", "只翻这些包(逗号分隔),空为全部常用包")
workers := flag.Int("workers", 6, "并发数")
flag.Parse()
if *key == "" {
fmt.Fprintln(os.Stderr, "需要 -key")
os.Exit(2)
}
cfg := ai.Config{BaseURL: *base, APIKey: *key, Model: *model}
cache := loadCache()
fmt.Printf("现有缓存 %d 条\n", len(cache))
pkgs := godoc.CommonPkgs
if *only != "" {
pkgs = splitCSV(*only)
}
// 收集待翻任务。
type task struct{ text string }
var tasks []task
pending := map[string]bool{}
for _, p := range pkgs {
docs, err := godoc.Docs(p)
if err != nil {
fmt.Printf("跳过 %s: %v\n", p, err)
continue
}
n := 0
for _, d := range docs {
k := godoc.NormKey(d)
if _, ok := cache[k]; ok || pending[k] {
continue
}
pending[k] = true
tasks = append(tasks, task{d})
n++
}
fmt.Printf("%-16s %3d 条文档,待翻 %d\n", p, len(docs), n)
}
fmt.Printf("共 %d 条待翻,%d 并发开始...\n", len(tasks), *workers)
start := time.Now()
idx := make(chan int)
var wg sync.WaitGroup
var mu sync.Mutex
okCount, failCount := 0, 0
for i := 0; i < *workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range idx {
text := tasks[j].text
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
tr, err := ai.TranslateDoc(ctx, cfg, text)
cancel()
if err != nil || tr == "" {
mu.Lock()
failCount++
mu.Unlock()
fmt.Printf("✗ %d/%d %v: %v\n", j+1, len(tasks), head(text), err)
continue
}
mu.Lock()
cache[godoc.NormKey(text)] = tr
okCount++
done := okCount
mu.Unlock()
if done%25 == 0 {
fmt.Printf("… %d/%d(%.0f 秒)\n", done, len(tasks), time.Since(start).Seconds())
}
}
}()
}
for j := range tasks {
idx <- j
}
close(idx)
wg.Wait()
saveCache(cache)
fmt.Printf("完成:成功 %d,失败 %d,缓存共 %d 条,耗时 %.0f 秒 → %s\n",
okCount, failCount, len(cache), time.Since(start).Seconds(), cachePath())
}
func splitCSV(s string) []string {
var out []string
for _, x := range splitComma(s) {
if x != "" {
out = append(out, x)
}
}
return out
}
func splitComma(s string) []string {
var out []string
cur := ""
for _, r := range s {
if r == ',' || r == ',' {
out = append(out, cur)
cur = ""
continue
}
cur += string(r)
}
return append(out, cur)
}
func head(s string) string {
r := []rune(s)
if len(r) > 30 {
return string(r[:30]) + "…"
}
return s
}
func cachePath() string {
base, err := os.UserConfigDir()
if err != nil {
panic(err)
}
return filepath.Join(base, "mygoland", "translations.json")
}
func loadCache() map[string]string {
b, err := os.ReadFile(cachePath())
if err != nil {
return map[string]string{}
}
m := map[string]string{}
if err := json.Unmarshal(b, &m); err != nil {
fmt.Printf("旧缓存解析失败(忽略): %v\n", err)
return map[string]string{}
}
// 统一规范化 key。
out := map[string]string{}
for k, v := range m {
if k != "" && v != "" {
out[godoc.NormKey(k)] = v
}
}
return out
}
func saveCache(m map[string]string) {
_ = os.MkdirAll(filepath.Dir(cachePath()), 0o755)
b, _ := json.MarshalIndent(m, "", " ")
if err := os.WriteFile(cachePath(), b, 0o644); err != nil {
fmt.Printf("写入缓存失败: %v\n", err)
}
}