Debian Codegraph @

tpl/lang/lang.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package lang provides template functions for content internationalization.
15 package lang
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "math"
22 "strconv"
23 "strings"
24
25 "github.com/bep/golocales"
26 "github.com/gohugoio/hugo/common/hreflect"
27 "github.com/gohugoio/hugo/deps"
28 "github.com/spf13/cast"
29 )
30
31 // New returns a new instance of the lang-namespaced template functions.
32 func New(deps *deps.Deps, translator golocales.Translator) *Namespace {
33 return &Namespace{
34 translator: translator,
35 deps: deps,
36 }
37 }
38
39 // Namespace provides template functions for the "lang" namespace.
40 type Namespace struct {
41 translator golocales.Translator
42 deps *deps.Deps
43 }
44
45 // Translate returns a translated string for id.
46 func (ns *Namespace) Translate(ctx context.Context, id any, args ...any) (string, error) {
47 var templateData any
48
49 if len(args) > 0 {
50 if len(args) > 1 {
51 return "", fmt.Errorf("wrong number of arguments, expecting at most 2, got %d", len(args)+1)
52 }
53 templateData = args[0]
54 }
55
56 sid, err := cast.ToStringE(id)
57 if err != nil {
58 return "", err
59 }
60
61 return ns.deps.Translate(ctx, sid, templateData), nil
62 }
63
64 // FormatNumber formats number with the given precision for the current language.
65 func (ns *Namespace) FormatNumber(precision, number any) (string, error) {
66 p, n, err := ns.castPrecisionNumber(precision, number)
67 if err != nil {
68 return "", err
69 }
70 return ns.translator.FormatNumber(n, p), nil
71 }
72
73 // FormatPercent formats number with the given precision for the current language.
74 // Note that the number is assumed to be a percentage.
75 func (ns *Namespace) FormatPercent(precision, number any) (string, error) {
76 p, n, err := ns.castPrecisionNumber(precision, number)
77 if err != nil {
78 return "", err
79 }
80 return ns.translator.FormatPercent(n, p), nil
81 }
82
83 // FormatCurrency returns the currency representation of number for the given currency and precision
84 // for the current language.
85 //
86 // The return value is formatted with at least two decimal places.
87 func (ns *Namespace) FormatCurrency(precision, currency, number any) (string, error) {
88 p, n, err := ns.castPrecisionNumber(precision, number)
89 if err != nil {
90 return "", err
91 }
92 return ns.translator.FormatCurrency(n, p, cast.ToString(currency)), nil
93 }
94
95 // FormatAccounting returns the currency representation of number for the given currency and precision
96 // for the current language in accounting notation.
97 //
98 // The return value is formatted with at least two decimal places.
99 func (ns *Namespace) FormatAccounting(precision, currency, number any) (string, error) {
100 p, n, err := ns.castPrecisionNumber(precision, number)
101 if err != nil {
102 return "", err
103 }
104 return ns.translator.FormatAccounting(n, p, cast.ToString(currency)), nil
105 }
106
107 func (ns *Namespace) castPrecisionNumber(precision, number any) (int, float64, error) {
108 p, err := cast.ToIntE(precision)
109 if err != nil {
110 return 0, 0, err
111 }
112
113 // Sanity check.
114 if p > 20 {
115 return 0, 0, fmt.Errorf("invalid precision: %d", precision)
116 }
117
118 n, err := cast.ToFloat64E(number)
119 if err != nil {
120 return 0, 0, err
121 }
122 return p, n, nil
123 }
124
125 // FormatNumberCustom formats a number with the given precision. The first
126 // options parameter is a space-delimited string of characters to represent
127 // negativity, the decimal point, and grouping. The default value is `- . ,`.
128 // The second options parameter defines an alternate delimiting character.
129 //
130 // Note that numbers are rounded up at 5 or greater.
131 // So, with precision set to 0, 1.5 becomes `2`, and 1.4 becomes `1`.
132 //
133 // For a simpler function that adapts to the current language, see FormatNumber.
134 func (ns *Namespace) FormatNumberCustom(precision, number any, options ...any) (string, error) {
135 prec, err := cast.ToIntE(precision)
136 if err != nil {
137 return "", err
138 }
139
140 n, err := cast.ToFloat64E(number)
141 if err != nil {
142 return "", err
143 }
144
145 var neg, dec, grp string
146
147 if len(options) == 0 {
148 // defaults
149 neg, dec, grp = "-", ".", ","
150 } else {
151 delim := " "
152
153 if len(options) == 2 {
154 // custom delimiter
155 s, err := cast.ToStringE(options[1])
156 if err != nil {
157 return "", err
158 }
159
160 delim = s
161 }
162
163 s, err := cast.ToStringE(options[0])
164 if err != nil {
165 return "", err
166 }
167
168 rs := strings.Split(s, delim)
169 switch len(rs) {
170 case 0:
171 case 1:
172 neg = rs[0]
173 case 2:
174 neg, dec = rs[0], rs[1]
175 case 3:
176 neg, dec, grp = rs[0], rs[1], rs[2]
177 default:
178 return "", errors.New("too many fields in options parameter to NumFmt")
179 }
180 }
181
182 exp := math.Pow(10.0, float64(prec))
183 r := math.Round(n*exp) / exp
184
185 // Logic from MIT Licensed github.com/gohugoio/locales/
186 // Original Copyright (c) 2016 Go Playground
187
188 s := strconv.FormatFloat(math.Abs(r), 'f', prec, 64)
189 L := len(s) + 2 + len(s[:len(s)-1-prec])/3
190
191 var count int
192 inWhole := prec == 0
193 b := make([]byte, 0, L)
194
195 for i := len(s) - 1; i >= 0; i-- {
196 if s[i] == '.' {
197 for j := len(dec) - 1; j >= 0; j-- {
198 b = append(b, dec[j])
199 }
200 inWhole = true
201 continue
202 }
203
204 if inWhole {
205 if count == 3 {
206 for j := len(grp) - 1; j >= 0; j-- {
207 b = append(b, grp[j])
208 }
209 count = 1
210 } else {
211 count++
212 }
213 }
214
215 b = append(b, s[i])
216 }
217
218 if n < 0 {
219 for j := len(neg) - 1; j >= 0; j-- {
220 b = append(b, neg[j])
221 }
222 }
223
224 // reverse
225 for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
226 b[i], b[j] = b[j], b[i]
227 }
228
229 return string(b), nil
230 }
231
232 type pagesLanguageMerger interface {
233 MergeByLanguageInterface(other any) (any, error)
234 }
235
236 // Merge creates a union of pages from two languages.
237 func (ns *Namespace) Merge(p2, p1 any) (any, error) {
238 if !hreflect.IsTruthful(p1) {
239 return p2, nil
240 }
241 if !hreflect.IsTruthful(p2) {
242 return p1, nil
243 }
244 merger, ok := p1.(pagesLanguageMerger)
245 if !ok {
246 return nil, fmt.Errorf("language merge not supported for %T", p1)
247 }
248 return merger.MergeByLanguageInterface(p2)
249 }