mirror of
https://github.com/miniflux/v2.git
synced 2025-09-15 18:57:04 +00:00
refactor(locale): introspect the translation files at load time
Since Go doesn't support unions, and because the translation format is a bit wacky with the same field having multiple types, we must resort to introspection to switch between single-item translation (for singular), and multi-items ones (for plurals). Previously, introspection was done at runtime, which is not only slow, but will also only catch typing errors while trying to use the translations. The current approach is to use a struct with a different field per possible type, and implement a custom unmarshaller to dispatch the translations to the right one. This should marginally reduce the memory consumption since interface-boxing doesn't happen anymore, speed up the translations matching, and enforce proper typing earlier. This also allows us to remove a bunch of now-useless tests.
This commit is contained in:
parent
f3052eb8ed
commit
181e1341e1
5 changed files with 180 additions and 205 deletions
|
@ -17,10 +17,8 @@ func NewPrinter(language string) *Printer {
|
|||
|
||||
func (p *Printer) Print(key string) string {
|
||||
if dict, err := getTranslationDict(p.language); err == nil {
|
||||
if str, ok := dict[key]; ok {
|
||||
if translation, ok := str.(string); ok {
|
||||
return translation
|
||||
}
|
||||
if str, ok := dict.singulars[key]; ok {
|
||||
return str
|
||||
}
|
||||
}
|
||||
return key
|
||||
|
@ -31,10 +29,8 @@ func (p *Printer) Printf(key string, args ...any) string {
|
|||
translation := key
|
||||
|
||||
if dict, err := getTranslationDict(p.language); err == nil {
|
||||
if str, ok := dict[key]; ok {
|
||||
if translation, ok = str.(string); !ok {
|
||||
translation = key
|
||||
}
|
||||
if str, ok := dict.singulars[key]; ok {
|
||||
translation = str
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -42,29 +38,16 @@ func (p *Printer) Printf(key string, args ...any) string {
|
|||
}
|
||||
|
||||
// Plural returns the translation of the given key by using the language plural form.
|
||||
func (p *Printer) Plural(key string, n int, args ...interface{}) string {
|
||||
func (p *Printer) Plural(key string, n int, args ...any) string {
|
||||
dict, err := getTranslationDict(p.language)
|
||||
if err != nil {
|
||||
return key
|
||||
}
|
||||
|
||||
if choices, found := dict[key]; found {
|
||||
var plurals []string
|
||||
|
||||
switch v := choices.(type) {
|
||||
case []string:
|
||||
plurals = v
|
||||
case []any:
|
||||
for _, v := range v {
|
||||
plurals = append(plurals, fmt.Sprint(v))
|
||||
}
|
||||
default:
|
||||
return key
|
||||
}
|
||||
|
||||
if choices, found := dict.plurals[key]; found {
|
||||
index := getPluralForm(p.language, n)
|
||||
if len(plurals) > index {
|
||||
return fmt.Sprintf(plurals[index], args...)
|
||||
if len(choices) > index {
|
||||
return fmt.Sprintf(choices[index], args...)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue