nicksnyder / go-i18n

Translate your Go program into multiple languages.
MIT License
2.96k stars 271 forks source link

error `unsupported file format <nil>` when a yaml value is empty #325

Closed LemonNekoGH closed 6 months ago

LemonNekoGH commented 6 months ago

Here is minimum reproduction code, runs on version 1.22.1: main.go

package main

import (
    "github.com/nicksnyder/go-i18n/v2/i18n"
    "golang.org/x/text/language"
    "gopkg.in/yaml.v3"
)

func main() {
    bundle := i18n.NewBundle(language.English)
    bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
    _, err := bundle.LoadMessageFile("en.yaml")
    if err != nil {
        panic(err)
    }

    localizer := i18n.NewLocalizer(bundle, language.English.String())
    localizedStr := localizer.MustLocalize(&i18n.LocalizeConfig{
        MessageID: "empty-key",
    })

    println(localizedStr)
}

en.yaml

key: value
empty-key-but-type-specified: ''
empty-key:

The yaml.Unmarshal function will return nil value when a key with empty value, and nil won't be matched in the code: https://github.com/nicksnyder/go-i18n/blob/521f1962775fbc66486eebbbddc6775f6dffb14a/i18n/parse.go#L63-L117

Should we fallback to empty string "" when we got nil value?

nicksnyder commented 6 months ago

Yeah that probably makes sense. I would accept a PR that adds a test and fixes this.