91 lines
2.5 KiB
Go
91 lines
2.5 KiB
Go
// gen-dict Day 41(清债②):openapi.yaml x-isc-dict → web/src/api/dict.ts 前端字典 codegen。
|
|
// 契约源=api/openapi.yaml;与后端 internal/pkg/errors/codes.go 由 openapi_sync_test 双向锁定。
|
|
// 用法:go run ./tools/gen-dict 生成(默认写 web/src/api/dict.ts)
|
|
//
|
|
// go run ./tools/gen-dict -check 仅校验,不一致 exit 1(CI/门禁用)
|
|
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"flag"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"sort"
|
|
"strings"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
func main() {
|
|
root := repoRoot()
|
|
src := filepath.Join(root, "api", "openapi.yaml")
|
|
out := filepath.Join(root, "web", "src", "api", "dict.ts")
|
|
check := flag.Bool("check", false, "仅校验生成物一致,不写文件")
|
|
flag.Parse()
|
|
|
|
raw, err := os.ReadFile(src)
|
|
must(err)
|
|
var doc map[string]any
|
|
must(yaml.Unmarshal(raw, &doc))
|
|
node, ok := doc["x-isc-dict"].(map[string]any)
|
|
if !ok || len(node) == 0 {
|
|
fatal("openapi.yaml 缺 x-isc-dict 字典节")
|
|
}
|
|
codes := make([]string, 0, len(node))
|
|
for k := range node {
|
|
codes = append(codes, k)
|
|
}
|
|
sort.Strings(codes)
|
|
|
|
var b bytes.Buffer
|
|
b.WriteString("// Codegen:由 tools/gen-dict 从 api/openapi.yaml x-isc-dict 生成,勿手改。\n")
|
|
b.WriteString("// 源码级锁定:internal/pkg/errors/openapi_sync_test.go(后端 codes.go ↔ openapi 双向一致)。\n")
|
|
b.WriteString("// 重新生成:go run ./tools/gen-dict\n\n")
|
|
b.WriteString("export const ISC_CN: Record<string, string> = {\n")
|
|
for _, c := range codes {
|
|
fmt.Fprintf(&b, " '%s': '%s',\n", c, strings.ReplaceAll(fmt.Sprint(node[c]), "'", "\\'"))
|
|
}
|
|
b.WriteString("}\n\n")
|
|
b.WriteString("/** ISC 错误码 → 中文;未知码原样返回(后端新增码未同步时降级展示)。 */\n")
|
|
b.WriteString("export function iscText(code: string): string {\n")
|
|
b.WriteString(" return ISC_CN[code] ?? code\n")
|
|
b.WriteString("}\n")
|
|
|
|
if *check {
|
|
cur, err := os.ReadFile(out)
|
|
must(err)
|
|
if !bytes.Equal(cur, b.Bytes()) {
|
|
fatal("dict.ts 与 openapi.yaml x-isc-dict 不一致:go run ./tools/gen-dict 后提交")
|
|
}
|
|
fmt.Println("check ok:", out)
|
|
return
|
|
}
|
|
must(os.WriteFile(out, b.Bytes(), 0o644))
|
|
fmt.Println("generated:", out, len(codes), "codes")
|
|
}
|
|
|
|
func repoRoot() string {
|
|
p, err := os.Getwd()
|
|
must(err)
|
|
for i := 0; i < 5; i++ {
|
|
if _, e := os.Stat(filepath.Join(p, "go.mod")); e == nil {
|
|
return p
|
|
}
|
|
p = filepath.Dir(p)
|
|
}
|
|
fatal("未找到仓库根(缺 go.mod)")
|
|
return ""
|
|
}
|
|
|
|
func must(err error) {
|
|
if err != nil {
|
|
fatal(err)
|
|
}
|
|
}
|
|
|
|
func fatal(v any) {
|
|
fmt.Fprintln(os.Stderr, "gen-dict:", v)
|
|
os.Exit(1)
|
|
}
|