Debian Codegraph @

debian/go/src/github.com/gohugoio/go-i18n/v2/goi18n/marshal.go

raw
1 package main
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "path/filepath"
8
9 "github.com/BurntSushi/toml"
10 "github.com/gohugoio/go-i18n/v2/i18n"
11 "github.com/gohugoio/go-i18n/v2/internal/plural"
12 "golang.org/x/text/language"
13 yaml "gopkg.in/yaml.v3"
14 )
15
16 func writeFile(outdir, label string, langTag language.Tag, format string, messageTemplates map[string]*i18n.MessageTemplate, sourceLanguage bool) (path string, content []byte, err error) {
17 v := marshalValue(messageTemplates, sourceLanguage)
18 content, err = marshal(v, format)
19 if err != nil {
20 return "", nil, fmt.Errorf("failed to marshal %s strings to %s: %s", langTag, format, err)
21 }
22 path = filepath.Join(outdir, fmt.Sprintf("%s.%s.%s", label, langTag, format))
23 return
24 }
25
26 func marshalValue(messageTemplates map[string]*i18n.MessageTemplate, sourceLanguage bool) interface{} {
27 v := make(map[string]interface{}, len(messageTemplates))
28 for id, template := range messageTemplates {
29 if other := template.PluralTemplates[plural.Other]; sourceLanguage && len(template.PluralTemplates) == 1 &&
30 other != nil && template.Description == "" && template.LeftDelim == "" && template.RightDelim == "" {
31 v[id] = other.Src
32 } else {
33 m := map[string]string{}
34 if template.Description != "" {
35 m["description"] = template.Description
36 }
37 if !sourceLanguage {
38 m["hash"] = template.Hash
39 }
40 for pluralForm, template := range template.PluralTemplates {
41 m[string(pluralForm)] = template.Src
42 }
43 v[id] = m
44 }
45 }
46 return v
47 }
48
49 func marshal(v interface{}, format string) ([]byte, error) {
50 switch format {
51 case "json":
52 var buf bytes.Buffer
53 enc := json.NewEncoder(&buf)
54 enc.SetEscapeHTML(false)
55 enc.SetIndent("", " ")
56 err := enc.Encode(v)
57 return buf.Bytes(), err
58 case "toml":
59 var buf bytes.Buffer
60 enc := toml.NewEncoder(&buf)
61 enc.Indent = ""
62 err := enc.Encode(v)
63 return buf.Bytes(), err
64 case "yaml":
65 return yaml.Marshal(v)
66 }
67 return nil, fmt.Errorf("unsupported format: %s", format)
68 }