github.com/polarismesh/polaris@v1.17.8/apiserver/httpserver/i18n/cmd/gen.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package main
    19  
    20  import (
    21  	"bufio"
    22  	"bytes"
    23  	"fmt"
    24  	"go/ast"
    25  	"go/parser"
    26  	"go/token"
    27  	"io"
    28  	"io/ioutil"
    29  	"os"
    30  	"os/exec"
    31  	"sort"
    32  	"strconv"
    33  	"strings"
    34  	"text/template"
    35  
    36  	api "github.com/polarismesh/polaris/common/api/v1"
    37  )
    38  
    39  func main() {
    40  	generateI18nMessageSrc("messages.genearate.go")
    41  	reloadI18nFile("en.toml")
    42  	reloadI18nFile("zh.toml")
    43  }
    44  
    45  // reloadI18nFile 根据最新的code 重新刷新i18n文件
    46  func reloadI18nFile(filePath string) {
    47  	list := getSrcCodeInfo()
    48  	existItems := make(map[string]string)
    49  	rfile, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0666)
    50  	if err != nil {
    51  		panic(err)
    52  	}
    53  	defer func() { _ = rfile.Close() }()
    54  
    55  	r := bufio.NewReader(rfile)
    56  	for {
    57  		b, _, e := r.ReadLine()
    58  		if e == io.EOF {
    59  			break
    60  		}
    61  		line := string(b)
    62  		existItems[strings.Split(line, " = ")[0]] = line
    63  	}
    64  	wfile, err := os.Create(filePath)
    65  	if err != nil {
    66  		panic(err)
    67  	}
    68  	defer func() { _ = wfile.Close() }()
    69  	w := bufio.NewWriter(wfile)
    70  	for _, item := range list { // 按照err code的大小编码组织
    71  		k := fmt.Sprintf("%d", item.Code)
    72  		line := fmt.Sprintf("%s = \"%s\"    #%s", k, item.Msg, item.Desc)
    73  		if ov, ok := existItems[k]; ok {
    74  			line = ov // 保留文件中的修改
    75  		}
    76  		if _, ierr := fmt.Fprintln(w, line); ierr != nil {
    77  			panic(ierr)
    78  		}
    79  	}
    80  	if ierr := w.Flush(); ierr != nil {
    81  		panic(ierr)
    82  	}
    83  }
    84  
    85  func generateI18nMessageSrc(fileName string) {
    86  	var buf bytes.Buffer
    87  	if err := template.Must(template.New("source").Parse(source)).
    88  		Execute(&buf, templateData{ErrCodeList: getSrcCodeInfo()}); err != nil {
    89  		panic(err)
    90  	}
    91  	if err := ioutil.WriteFile(fileName, buf.Bytes(), 0644); err != nil {
    92  		panic(err)
    93  	}
    94  	if err := exec.Command("gofmt", "-w", fileName).Run(); err != nil {
    95  		panic(err)
    96  	}
    97  }
    98  
    99  func getSrcCodeInfo() []errCodeItem {
   100  	fset := token.NewFileSet()
   101  	f, err := parser.ParseFile(fset, "../../../common/api/v1/codeinfo.go", nil, parser.ParseComments)
   102  	if err != nil {
   103  		panic(err)
   104  	}
   105  	var list []errCodeItem
   106  	for name, obj := range f.Scope.Objects {
   107  		if obj.Kind.String() != "const" {
   108  			continue
   109  		}
   110  		spec, _ := obj.Decl.(*ast.ValueSpec)
   111  		code, _ := strconv.Atoi(spec.Values[0].(*ast.BasicLit).Value)
   112  		msg := api.Code2Info(uint32(code))
   113  		list = append(list, errCodeItem{
   114  			Code: code,
   115  			Msg:  msg,
   116  			Desc: name, // 变量名作为注释性的描述
   117  		})
   118  	}
   119  	sort.Slice(list, func(i, j int) bool {
   120  		return list[i].Code < list[j].Code
   121  	})
   122  	return list
   123  }
   124  
   125  type errCodeItem struct {
   126  	Code int
   127  	Desc string
   128  	Msg  string
   129  }
   130  
   131  type templateData struct {
   132  	ErrCodeList []errCodeItem
   133  }
   134  
   135  const source = `// Code generated by apiserver/httpserver/i18n/cmd/gen.go; DO NOT EDIT.
   136  /**
   137   * Tencent is pleased to support the open source community by making Polaris available.
   138   *
   139   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
   140   *
   141   * Licensed under the BSD 3-Clause License (the "License");
   142   * you may not use this file except in compliance with the License.
   143   * You may obtain a copy of the License at
   144   *
   145   * https://opensource.org/licenses/BSD-3-Clause
   146   *
   147   * Unless required by applicable law or agreed to in writing, software distributed
   148   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   149   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
   150   * specific language governing permissions and limitations under the License.
   151   */
   152  
   153  package i18n
   154  
   155  import (
   156  	"fmt"
   157  
   158  	ii18n "github.com/nicksnyder/go-i18n/v2/i18n"
   159  	api "github.com/polarismesh/polaris-server/common/api/v1"
   160  )
   161  
   162  func init() {
   163  	i18nMsgCache = map[uint32]*ii18n.Message{
   164  		{{range .ErrCodeList -}}
   165  		api.{{.Desc}}: {ID: fmt.Sprint(api.{{.Desc}})},
   166  		{{end}}
   167  	}
   168  }
   169  `