File: i18n_init.go

package info (click to toggle)
golang-gopkg-alecthomas-kingpin.v3 3.0~git20180227.b8d601d-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 420 kB
  • sloc: makefile: 6
file content (82 lines) | stat: -rw-r--r-- 1,774 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package kingpin

//go:generate go run ./cmd/embedi18n/main.go en-AU
//go:generate go run ./cmd/embedi18n/main.go fr

import (
	"bytes"
	"compress/gzip"
	"io/ioutil"
	"os"
	"strings"

	"github.com/nicksnyder/go-i18n/i18n"
)

type tError struct {
	msg  string
	args []interface{}
}

// TError is an error that translates itself.
//
// It has the same signature and usage as T().
func TError(msg string, args ...interface{}) error { return &tError{msg: msg, args: args} }
func (i *tError) Error() string                    { return T(i.msg, i.args...) }

// T is a translation function.
var T = initI18N()

func initI18N() i18n.TranslateFunc {
	// Initialise translations.
	i18n.ParseTranslationFileBytes("i18n/en-AU.all.json", decompressLang(i18n_en_AU))
	i18n.ParseTranslationFileBytes("i18n/fr.all.json", decompressLang(i18n_fr))

	// Detect language.
	lang := detectLang()
	t, err := i18n.Tfunc(lang, "en")
	if err != nil {
		panic(err)
	}
	return t
}

func detectLang() string {
	lang := os.Getenv("LANG")
	if lang == "" {
		return "en"
	}
	// Remove encoding spec (eg. ".UTF-8")
	if idx := strings.Index(lang, "."); idx != -1 {
		lang = lang[0:idx]
	}
	// en_AU -> en-AU
	return strings.Replace(lang, "_", "-", -1)
}

func decompressLang(data []byte) []byte {
	r := bytes.NewReader(data)
	gr, err := gzip.NewReader(r)
	if err != nil {
		panic(err)
	}
	out, err := ioutil.ReadAll(gr)
	if err != nil {
		panic(err)
	}
	return out
}

// SetLanguage sets the language for Kingpin.
func SetLanguage(lang string, others ...string) error {
	t, err := i18n.Tfunc(lang, others...)
	if err != nil {
		return err
	}
	T = t
	return nil
}

// V is a convenience alias for translation function variables.
// eg. T("Something {{.Arg0}}", V{"Arg0": "moo"})
type V map[string]interface{}