Skip to content

Commit e25031a

Browse files
authored
Add parent language support (#3)
1 parent ed79327 commit e25031a

1 file changed

Lines changed: 46 additions & 6 deletions

File tree

i18n/i18n.go

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ import (
88
)
99

1010
type Locale struct {
11-
IsoShortCode string
12-
IsoLongCode string
13-
Messages map[MessageId]string
11+
IsoShortCode string
12+
IsoLongCode string
13+
ParentIsoShortCode *string
14+
Messages map[MessageId]string
1415
}
1516

1617
var LocaleEnglish = &Locale{
@@ -21,7 +22,7 @@ var LocaleEnglish = &Locale{
2122
var locales = make(map[string]*Locale)
2223

2324
func Init(localePath string) error {
24-
// Load English
25+
// Load English
2526
if err := loadLocale(localePath, LocaleEnglish); err != nil {
2627
return fmt.Errorf("failed to load English locale: %w", err)
2728
}
@@ -62,9 +63,32 @@ func Init(localePath string) error {
6263
locales[isoLongCode] = locale
6364
}
6465

66+
// Set parent language relationships for sub-languages
67+
setParentLanguages()
68+
6569
return nil
6670
}
6771

72+
func setParentLanguages() {
73+
// German (Switzerland) -> German
74+
if locale, ok := locales["de-CH"]; ok {
75+
parent := "de"
76+
locale.ParentIsoShortCode = &parent
77+
}
78+
79+
// Portuguese (Brazil) -> Portuguese
80+
if locale, ok := locales["pt-BR"]; ok {
81+
parent := "pt"
82+
locale.ParentIsoShortCode = &parent
83+
}
84+
85+
// Chinese (Taiwan) -> Chinese
86+
if locale, ok := locales["zh-TW"]; ok {
87+
parent := "cn"
88+
locale.ParentIsoShortCode = &parent
89+
}
90+
}
91+
6892
func loadLocale(basePath string, locale *Locale) error {
6993
path := fmt.Sprintf("%s/%s.json", basePath, locale.IsoLongCode)
7094

@@ -153,9 +177,25 @@ func GetMessage(locale *Locale, id MessageId, format ...interface{}) string {
153177
}
154178

155179
value, ok := locale.Messages[id]
156-
if !ok || value == "" {
180+
181+
// Check if message exists in English
182+
englishValue, englishExists := LocaleEnglish.Messages[id]
183+
184+
// Message is missing, empty, or same as English
185+
if !ok || value == "" || (englishExists && value == englishValue) {
157186
if locale == LocaleEnglish {
158-
return fmt.Sprintf("error: translation for `%s` is missing", id)
187+
if !ok || value == "" {
188+
return fmt.Sprintf("error: translation for `%s` is missing", id)
189+
}
190+
return fmt.Sprintf(value, format...)
191+
}
192+
193+
// Check if locale has a parent language
194+
if locale.ParentIsoShortCode != nil {
195+
parentLocale := locales[*locale.ParentIsoShortCode]
196+
if parentLocale != nil {
197+
return GetMessage(parentLocale, id, format...) // try parent language first
198+
}
159199
}
160200

161201
return GetMessage(LocaleEnglish, id, format...)

0 commit comments

Comments
 (0)