mirror of
https://github.com/miniflux/v2.git
synced 2025-08-06 17:41:00 +00:00
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.
55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
package locale // import "miniflux.app/v2/internal/locale"
|
|
|
|
import "fmt"
|
|
|
|
// Printer converts translation keys to language-specific strings.
|
|
type Printer struct {
|
|
language string
|
|
}
|
|
|
|
// NewPrinter creates a new Printer instance for the given language.
|
|
func NewPrinter(language string) *Printer {
|
|
return &Printer{language}
|
|
}
|
|
|
|
func (p *Printer) Print(key string) string {
|
|
if dict, err := getTranslationDict(p.language); err == nil {
|
|
if str, ok := dict.singulars[key]; ok {
|
|
return str
|
|
}
|
|
}
|
|
return key
|
|
}
|
|
|
|
// Printf is like fmt.Printf, but using language-specific formatting.
|
|
func (p *Printer) Printf(key string, args ...any) string {
|
|
translation := key
|
|
|
|
if dict, err := getTranslationDict(p.language); err == nil {
|
|
if str, ok := dict.singulars[key]; ok {
|
|
translation = str
|
|
}
|
|
}
|
|
|
|
return fmt.Sprintf(translation, args...)
|
|
}
|
|
|
|
// Plural returns the translation of the given key by using the language plural form.
|
|
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.plurals[key]; found {
|
|
index := getPluralForm(p.language, n)
|
|
if len(choices) > index {
|
|
return fmt.Sprintf(choices[index], args...)
|
|
}
|
|
}
|
|
|
|
return key
|
|
}
|