github.com/elopio/cli@v6.21.2-0.20160902224010-ea909d1fdb2f+incompatible/commands/ui/i18n.go (about)

     1  package ui
     2  
     3  import (
     4  	"fmt"
     5  	"path"
     6  	"strings"
     7  
     8  	"code.cloudfoundry.org/cli/cf/resources"
     9  	"github.com/nicksnyder/go-i18n/i18n"
    10  	"github.com/nicksnyder/go-i18n/i18n/language"
    11  )
    12  
    13  const (
    14  	defaultLocale  = "en-us"
    15  	resourceSuffix = ".all.json"
    16  	zhTW           = "zh-tw"
    17  	zhHK           = "zh-hk"
    18  	zhHant         = "zh-hant"
    19  	hyphen         = "-"
    20  	underscore     = "_"
    21  )
    22  
    23  func GetTranslationFunc(config Config) (i18n.TranslateFunc, error) {
    24  	err := loadAsset("cf/i18n/resources/" + defaultLocale + resourceSuffix)
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	defaultTfunc := i18n.MustTfunc(defaultLocale)
    29  
    30  	assetNames := resources.AssetNames()
    31  
    32  	source := config.Locale()
    33  	for _, l := range language.Parse(source) {
    34  		if l.Tag == zhTW || l.Tag == zhHK {
    35  			l.Tag = zhHant
    36  		}
    37  
    38  		for _, assetName := range assetNames {
    39  			assetLocale := strings.ToLower(strings.Replace(path.Base(assetName), underscore, hyphen, -1))
    40  			if strings.HasPrefix(assetLocale, l.Tag) {
    41  				err := loadAsset(assetName)
    42  				if err != nil {
    43  					return nil, err
    44  				}
    45  
    46  				t := i18n.MustTfunc(l.Tag)
    47  
    48  				return func(translationID string, args ...interface{}) string {
    49  					if translated := t(translationID, args...); translated != translationID {
    50  						return translated
    51  					}
    52  
    53  					return defaultTfunc(translationID, args...)
    54  				}, nil
    55  			}
    56  		}
    57  	}
    58  
    59  	return defaultTfunc, nil
    60  }
    61  
    62  func loadAsset(assetName string) error {
    63  	assetBytes, err := resources.Asset(assetName)
    64  	if err != nil {
    65  		return fmt.Errorf("Could not load asset '%s': %s", assetName, err.Error())
    66  	}
    67  
    68  	err = i18n.ParseTranslationFileBytes(assetName, assetBytes)
    69  	if err != nil {
    70  		return fmt.Errorf("Could not load translations '%s': %s", assetName, err.Error())
    71  	}
    72  	return nil
    73  }