1
0
Fork 0
forked from forgejo/forgejo

Provide a way to translate data units

This commit is contained in:
0ko 2024-03-19 15:52:32 +05:00 committed by GitHub
parent 482658a4d0
commit 7b24b669ed
19 changed files with 69 additions and 29 deletions

View file

@ -31,6 +31,10 @@ func (l MockLocale) TrN(cnt any, key1, keyN string, args ...any) template.HTML {
return template.HTML(key1)
}
func (l MockLocale) TrSize(s int64) ByteSize {
return ByteSize{fmt.Sprint(s), ""}
}
func (l MockLocale) PrettyNumber(v any) string {
return fmt.Sprint(v)
}

View file

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/translation/i18n"
"code.gitea.io/gitea/modules/util"
"github.com/dustin/go-humanize"
"golang.org/x/text/language"
"golang.org/x/text/message"
@ -33,6 +34,8 @@ type Locale interface {
Tr(key string, args ...any) template.HTML
TrN(cnt any, key1, keyN string, args ...any) template.HTML
TrSize(size int64) ByteSize
PrettyNumber(v any) string
}
@ -252,6 +255,35 @@ func (l *locale) TrN(cnt any, key1, keyN string, args ...any) template.HTML {
return l.Tr(keyN, args...)
}
type ByteSize struct {
PrettyNumber string
TranslatedUnit string
}
func (bs ByteSize) String() string {
return bs.PrettyNumber + " " + bs.TranslatedUnit
}
// TrSize returns array containing pretty formatted size and localized output of FileSize
// output of humanize.IBytes has to be split in order to be localized
func (l *locale) TrSize(s int64) ByteSize {
us := uint64(s)
if s < 0 {
us = uint64(-s)
}
untranslated := humanize.IBytes(us)
if s < 0 {
untranslated = "-" + untranslated
}
numberVal, unitVal, found := strings.Cut(untranslated, " ")
if !found {
log.Error("no space in go-humanized size of %d: %q", s, untranslated)
}
numberVal = l.PrettyNumber(numberVal)
unitVal = l.TrString("munits.data." + strings.ToLower(unitVal))
return ByteSize{numberVal, unitVal}
}
func (l *locale) PrettyNumber(v any) string {
// TODO: this mechanism is not good enough, the complete solution is to switch the translation system to ICU message format
if s, ok := v.(string); ok {