gotext

package module
v0.0.0-...-6570881 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2024 License: BSD-3-Clause, MIT Imports: 16 Imported by: 0

README

GitHub release MIT license Gotext build Go Report Card PkgGoDev

Gotext

GNU gettext utilities for Go.

Features

  • Implements GNU gettext support in native Go.
  • Complete support for PO files including:
  • Support for MO files.
  • Thread-safe: This package is safe for concurrent use across multiple goroutines.
  • It works with UTF-8 encoding as it's the default for Go language.
  • Unit tests available.
  • Language codes are automatically simplified from the form en_UK to en if the first isn't available.
  • Ready to use inside Go templates.
  • Objects are serializable to []byte to store them in cache.
  • Support for Go Modules.
  • 优化 po 文件解析
  • 支持解析注释

License

MIT license

Documentation

Refer to the Godoc package documentation at (https://godoc.org/github.com/leonelquinteros/gotext)

Installation

go get github.com/leonelquinteros/gotext
  • There are no requirements or dependencies to use this package.
  • No need to install GNU gettext utilities (unless specific needs of CLI tools).
  • No need for environment variables. Some naming conventions are applied but not needed.

Version vendoring

Stable releases use semantic versioning tagging on this repository.

You can rely on this to use your preferred vendoring tool or to manually retrieve the corresponding release tag from the GitHub repository.

NOTE: v1.5.0 contains a breaking change on how Po objects are initialised, see (https://github.com/leonelquinteros/gotext/issues/56)

Add github.com/leonelquinteros/gotext inside the require section in your go.mod file.

i.e.

require (
    github.com/leonelquinteros/gotext v1.4.0
)
Vendoring with gopkg.in

http://gopkg.in/leonelquinteros/gotext.v1

To get the latest v1 package stable release, execute:

go get gopkg.in/leonelquinteros/gotext.v1

Import as

import "gopkg.in/leonelquinteros/gotext.v1"

Refer to it as gotext.

Locales directories structure

The package will assume a directories structure starting with a base path that will be provided to the package configuration or to object constructors depending on the use, but either will use the same convention to lookup inside the base path.

Inside the base directory where will be the language directories named using the language and country 2-letter codes (en_US, es_AR, ...). All package functions can lookup after the simplified version for each language in case the full code isn't present but the more general language code exists. So if the language set is en_UK, but there is no directory named after that code and there is a directory named en, all package functions will be able to resolve this generalization and provide translations for the more general library.

The language codes are assumed to be ISO 639-1 codes (2-letter codes). That said, most functions will work with any coding standard as long the directory name matches the language code set on the configuration.

Then, there can be a LC_MESSAGES containing all PO files or the PO files themselves. A library directory structure can look like:

/path/to/locales
/path/to/locales/en_US
/path/to/locales/en_US/LC_MESSAGES
/path/to/locales/en_US/LC_MESSAGES/default.po
/path/to/locales/en_US/LC_MESSAGES/extras.po
/path/to/locales/en_UK
/path/to/locales/en_UK/LC_MESSAGES
/path/to/locales/en_UK/LC_MESSAGES/default.po
/path/to/locales/en_UK/LC_MESSAGES/extras.po
/path/to/locales/en_AU
/path/to/locales/en_AU/LC_MESSAGES
/path/to/locales/en_AU/LC_MESSAGES/default.po
/path/to/locales/en_AU/LC_MESSAGES/extras.po
/path/to/locales/es
/path/to/locales/es/default.po
/path/to/locales/es/extras.po
/path/to/locales/es_ES
/path/to/locales/es_ES/default.po
/path/to/locales/es_ES/extras.po
/path/to/locales/fr
/path/to/locales/fr/default.po
/path/to/locales/fr/extras.po

And so on...

Usage examples

Using package for single language/domain settings

For quick/simple translations you can use the package level functions directly.

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Configure package
    gotext.Configure("/path/to/locales/root/dir", "en_UK", "domain-name")

    // Translate text from default domain
    fmt.Println(gotext.Get("My text on 'domain-name' domain"))

    // Translate text from a different domain without reconfigure
    fmt.Println(gotext.GetD("domain2", "Another text on a different domain"))
}

Using dynamic variables on translations

All translation strings support dynamic variables to be inserted without translate. Use the fmt.Printf syntax (from Go's "fmt" package) to specify how to print the non-translated variable inside the translation string.

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Configure package
    gotext.Configure("/path/to/locales/root/dir", "en_UK", "domain-name")

    // Set variables
    name := "John"

    // Translate text with variables
    fmt.Println(gotext.Get("Hi, my name is %s", name))
}

Using Locale object

When having multiple languages/domains/libraries at the same time, you can create Locale objects for each variation so you can handle each settings on their own.

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Create Locale with library path and language code
    l := gotext.NewLocale("/path/to/locales/root/dir", "es_UY")

    // Load domain '/path/to/locales/root/dir/es_UY/default.po'
    l.AddDomain("default")

    // Translate text from default domain
    fmt.Println(l.Get("Translate this"))

    // Load different domain
    l.AddDomain("translations")

    // Translate text from domain
    fmt.Println(l.GetD("translations", "Translate this"))
}

This is also helpful for using inside templates (from the "text/template" package), where you can pass the Locale object to the template. If you set the Locale object as "Loc" in the template, then the template code would look like:

{{ .Loc.Get "Translate this" }}

Using the Po object to handle .po files and PO-formatted strings

For when you need to work with PO files and strings, you can directly use the Po object to parse it and access the translations in there in the same way.

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Set PO content
    str := `
msgid "Translate this"
msgstr "Translated text"

msgid "Another string"
msgstr ""

msgid "One with var: %s"
msgstr "This one sets the var: %s"
`

    // Create Po object
    po := gotext.NewPo()
    po.Parse(str)

    fmt.Println(po.Get("Translate this"))
}

Use plural forms of translations

PO format supports defining one or more plural forms for the same translation. Relying on the PO file headers, a Plural-Forms formula can be set on the translation file as defined in (https://www.gnu.org/savannah-checkouts/gnu/gettext/manual/html_node/Plural-forms.html)

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Set PO content
    str := `
msgid ""
msgstr ""

# Header below
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

msgid "Translate this"
msgstr "Translated text"

msgid "Another string"
msgstr ""

msgid "One with var: %s"
msgid_plural "Several with vars: %s"
msgstr[0] "This one is the singular: %s"
msgstr[1] "This one is the plural: %s"
`

    // Create Po object
    po := new(gotext.Po)
    po.Parse(str)

    fmt.Println(po.GetN("One with var: %s", "Several with vars: %s", 54, v))
    // "This one is the plural: Variable"
}

Contribute

  • Please, contribute.
  • Use the package on your projects.
  • Report issues on Github.
  • Send pull requests for bugfixes and improvements.
  • Send proposals on Github issues.

Documentation

Overview

Package gotext implements GNU gettext utilities.

For quick/simple translations you can use the package level functions directly.

    import (
	    "fmt"
	    "github.com/leonelquinteros/gotext"
    )

    func main() {
        // Configure package
        gotext.Configure("/path/to/locales/root/dir", "en_UK", "domain-name")

        // Translate text from default domain
        fmt.Println(gotext.Get("My text on 'domain-name' domain"))

        // Translate text from a different domain without reconfigure
        fmt.Println(gotext.GetD("domain2", "Another text on a different domain"))
    }

Index

Constants

View Source
const (
	// MoMagicLittleEndian encoding
	MoMagicLittleEndian = 0x950412de
	// MoMagicBigEndian encoding
	MoMagicBigEndian = 0xde120495

	// EotSeparator msgctxt and msgid separator
	EotSeparator = "\x04"
	// NulSeparator msgid and msgstr separator
	NulSeparator = "\x00"
)

Variables

View Source
var FallbackLocale = "en_US"

Functions

func Appendf

func Appendf(b []byte, str string, vars ...interface{}) []byte

Appendf applies text formatting only when needed to parse variables.

func Configure

func Configure(lib, lang, dom string)

Configure sets all configuration variables to be used at package level and reloads the corresponding Translation file. It receives the library path, language code and domain name. This function is recommended to be used when changing more than one setting, as using each setter will introduce a I/O overhead because the Translation file will be loaded after each set.

func EscapeSpecialCharacters

func EscapeSpecialCharacters(s string) string

func Get

func Get(str string, vars ...interface{}) string

Get uses the default domain globally set to return the corresponding Translation of a given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetC

func GetC(str, ctx string, vars ...interface{}) string

GetC uses the default domain globally set to return the corresponding Translation of the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetD

func GetD(dom, str string, vars ...interface{}) string

GetD returns the corresponding Translation in the given domain for a given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetDC

func GetDC(dom, str, ctx string, vars ...interface{}) string

GetDC returns the corresponding Translation in the given domain for the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetDomain

func GetDomain() string

GetDomain is the domain getter for the package configuration

func GetLanguage

func GetLanguage() string

GetLanguage returns the language gotext will translate into. If multiple languages have been supplied, the first one will be returned. If no language has been supplied, the fallback will be returned.

func GetLanguages

func GetLanguages() []string

GetLanguages returns all languages that have been supplied.

func GetLibrary

func GetLibrary() string

GetLibrary is the library getter for the package configuration

func GetN

func GetN(str, plural string, n int, vars ...interface{}) string

GetN retrieves the (N)th plural form of Translation for the given string in the default domain. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetNC

func GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context in the default domain. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetND

func GetND(dom, str, plural string, n int, vars ...interface{}) string

GetND retrieves the (N)th plural form of Translation in the given domain for a given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func GetNDC

func GetNDC(dom, str, plural string, n int, ctx string, vars ...interface{}) string

GetNDC retrieves the (N)th plural form of Translation in the given domain for a given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func IsTranslated

func IsTranslated(str string, langs ...string) bool

IsTranslated reports whether a string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedC

func IsTranslatedC(str, ctx string, langs ...string) bool

IsTranslatedC reports whether a context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedD

func IsTranslatedD(dom, str string, langs ...string) bool

IsTranslatedD reports whether a domain string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedDC

func IsTranslatedDC(dom, str, ctx string, langs ...string) bool

IsTranslatedDC reports whether a domain context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedN

func IsTranslatedN(str string, n int, langs ...string) bool

IsTranslatedN reports whether a plural string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedNC

func IsTranslatedNC(str string, n int, ctx string, langs ...string) bool

IsTranslatedNC reports whether a plural context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedND

func IsTranslatedND(dom, str string, n int, langs ...string) bool

IsTranslatedND reports whether a plural domain string is translated in any of given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedNDC

func IsTranslatedNDC(dom, str string, n int, ctx string, langs ...string) bool

IsTranslatedNDC reports whether a plural domain context string is translated in any of given languages. When the langs argument is omitted, the output of GetLanguages is used.

func NPrintf

func NPrintf(format string, params map[string]interface{})

NPrintf support named format NPrintf("%(name)s is Type %(type)s", map[string]interface{}{"name": "Gotext", "type": "struct"})

func Printf

func Printf(str string, vars ...interface{}) string

Printf applies text formatting only when needed to parse variables.

func SetDomain

func SetDomain(dom string)

SetDomain sets the name for the domain to be used at package level. It reloads the corresponding Translation file.

func SetLanguage

func SetLanguage(lang string)

SetLanguage sets the language code (or colon separated language codes) to be used at package level. It reloads the corresponding Translation file.

func SetLibrary

func SetLibrary(lib string)

SetLibrary sets the root path for the locale directories and files to be used at package level. It reloads the corresponding Translation file.

func SetLocales

func SetLocales(locales []*Locale)

SetLocales allows for overriding the global Locale objects with ones built manually with NewLocale(). This makes it possible to attach custom Domain objects from in-memory po/mo. The library, language and domain of the first Locale will set the default global configuration.

func SetStorage deprecated

func SetStorage(locale *Locale)

SetStorage allows overriding the global Locale object with one built manually with NewLocale().

Deprecated: Storage has been renamed to Locale for consistency, use SetLocales instead.

func SimplifiedLocale

func SimplifiedLocale(lang string) string

SimplifiedLocale simplified locale like " en_US"/"de_DE "/en_US.UTF-8/zh_CN/zh_TW/el_GR@euro/... to en_US, de_DE, zh_CN, el_GR...

func Sprintf

func Sprintf(format string, params map[string]interface{}) string

Sprintf support named format

Sprintf("%(name)s is Type %(type)s", map[string]interface{}{"name": "Gotext", "type": "struct"})

Types

type AppendTranslator

type AppendTranslator interface {
	Translator
	Append(b []byte, str string, vars ...interface{}) []byte
	AppendN(b []byte, str, plural string, n int, vars ...interface{}) []byte
	AppendC(b []byte, str, ctx string, vars ...interface{}) []byte
	AppendNC(b []byte, str, plural string, n int, ctx string, vars ...interface{}) []byte
}

type Domain

type Domain struct {
	Headers HeaderMap

	// Language header
	Language string

	// Plural-Forms header
	PluralForms string
	// contains filtered or unexported fields
}

Domain has all the common functions for dealing with a gettext domain it's initialized with a GettextFile (which represents either a Po or Mo file)

func NewDomain

func NewDomain() *Domain

func (*Domain) AddRefs

func (do *Domain) AddRefs(str string, refs []string)

Add source references for a given translation

func (*Domain) Append

func (do *Domain) Append(b []byte, str string, vars ...interface{}) []byte

func (*Domain) AppendC

func (do *Domain) AppendC(b []byte, str, ctx string, vars ...interface{}) []byte

AppendC retrieves the corresponding Translation for a given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) AppendN

func (do *Domain) AppendN(b []byte, str, plural string, n int, vars ...interface{}) []byte

GetN retrieves the (N)th plural form of Translation for the given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) AppendNC

func (do *Domain) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...interface{}) []byte

AppendNC retrieves the (N)th plural form of Translation for the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) ClearAllRefs

func (do *Domain) ClearAllRefs()

Clear all source references

func (*Domain) ClearRefs

func (do *Domain) ClearRefs(str string)

Clear source references for a given translation

func (*Domain) DropStaleTranslations

func (do *Domain) DropStaleTranslations()

Drops any translations stored that have not been Set*() since 'po' was initialised

func (*Domain) Get

func (do *Domain) Get(str string, vars ...interface{}) string

func (*Domain) GetC

func (do *Domain) GetC(str, ctx string, vars ...interface{}) string

GetC retrieves the corresponding Translation for a given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetN

func (do *Domain) GetN(str, plural string, n int, vars ...interface{}) string

GetN retrieves the (N)th plural form of Translation for the given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetNC

func (do *Domain) GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetRefs

func (do *Domain) GetRefs(str string) []string

Get source references for a given translation

func (*Domain) GetTranslations

func (do *Domain) GetTranslations() map[string]*Translation

GetTranslations returns a copy of every translation in the domain. It does not support contexts.

func (*Domain) IsTranslated

func (do *Domain) IsTranslated(str string) bool

IsTranslated reports whether a string is translated

func (*Domain) IsTranslatedC

func (do *Domain) IsTranslatedC(str, ctx string) bool

IsTranslatedC reports whether a context string is translated

func (*Domain) IsTranslatedN

func (do *Domain) IsTranslatedN(str string, n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Domain) IsTranslatedNC

func (do *Domain) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC reports whether a plural context string is translated

func (*Domain) MarshalBinary

func (do *Domain) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler interface

func (*Domain) MarshalText

func (do *Domain) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface Assists round-trip of POT/PO content

func (*Domain) Set

func (do *Domain) Set(id, str string)

Set the translation of a given string

func (*Domain) SetC

func (do *Domain) SetC(id, ctx, str string)

Set the translation for the given string in the given context

func (*Domain) SetN

func (do *Domain) SetN(id, plural string, n int, str string)

Set the (N)th plural form for the given string

func (*Domain) SetNC

func (do *Domain) SetNC(id, plural, ctx string, n int, str string)

Set the (N)th plural form for the given string in the given context

func (*Domain) SetPluralResolver

func (do *Domain) SetPluralResolver(f func(int) int)

func (*Domain) SetRefs

func (do *Domain) SetRefs(str string, refs []string)

Set source references for a given translation

func (*Domain) UnmarshalBinary

func (do *Domain) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler interface

type HeaderMap

type HeaderMap map[string][]string

Preserve MIMEHeader behaviour, without the canonicalisation

func (HeaderMap) Add

func (m HeaderMap) Add(key, value string)

func (HeaderMap) Del

func (m HeaderMap) Del(key string)

func (HeaderMap) Get

func (m HeaderMap) Get(key string) string

func (HeaderMap) Set

func (m HeaderMap) Set(key, value string)

func (HeaderMap) Values

func (m HeaderMap) Values(key string) []string

type IsTranslatedDomainIntrospector

type IsTranslatedDomainIntrospector interface {
	IsTranslated(str string) bool
	IsTranslatedN(str string, n int) bool
	IsTranslatedD(dom, str string) bool
	IsTranslatedND(dom, str string, n int) bool
	IsTranslatedC(str, ctx string) bool
	IsTranslatedNC(str string, n int, ctx string) bool
	IsTranslatedDC(dom, str, ctx string) bool
	IsTranslatedNDC(dom, str string, n int, ctx string) bool
}

IsTranslatedDomainIntrospector is able to determine whether a given string is translated. Example of this introspector is Locale, which holds multiple domains. Simpler objects that are domain-specific, like Po or Mo, implement IsTranslatedIntrospector.

type IsTranslatedIntrospector

type IsTranslatedIntrospector interface {
	IsTranslated(str string) bool
	IsTranslatedN(str string, n int) bool
	IsTranslatedC(str, ctx string) bool
	IsTranslatedNC(str string, n int, ctx string) bool
}

IsTranslatedIntrospector is able to determine whether a given string is translated. Examples of this introspector are Po and Mo, which are specific to their domain. Locale holds multiple domains and also implements IsTranslatedDomainIntrospector.

type Locale

type Locale struct {

	// List of available Domains for this locale.
	Domains map[string]Translator

	// Sync Mutex
	sync.RWMutex
	// contains filtered or unexported fields
}

Locale wraps the entire i18n collection for a single language (locale) It's used by the package functions, but it can also be used independently to handle multiple languages at the same time by working with this object.

Example:

    import (
	"encoding/gob"
	"bytes"
	    "fmt"
	    "github.com/leonelquinteros/gotext"
    )

    func main() {
        // Create Locale with library path and language code
        l := gotext.NewLocale("/path/to/i18n/dir", "en_US")

        // Load domain '/path/to/i18n/dir/en_US/LC_MESSAGES/default.{po,mo}'
        l.AddDomain("default")

        // Translate text from default domain
        fmt.Println(l.Get("Translate this"))

        // Load different domain ('/path/to/i18n/dir/en_US/LC_MESSAGES/extras.{po,mo}')
        l.AddDomain("extras")

        // Translate text from domain
        fmt.Println(l.GetD("extras", "Translate this"))
    }

func GetLocales

func GetLocales() []*Locale

func GetStorage deprecated

func GetStorage() *Locale

GetStorage is the locale storage getter for the package configuration.

Deprecated: Storage has been renamed to Locale for consistency, use GetLocales instead.

func NewLocale

func NewLocale(p, l string) *Locale

NewLocale creates and initializes a new Locale object for a given language. It receives a path for the i18n .po/.mo files directory (p) and a language code to use (l).

func NewLocaleFS

func NewLocaleFS(l string, filesystem fs.FS) *Locale

NewLocaleFS returns a Locale working with a fs.FS

func NewLocaleFSWithPath

func NewLocaleFSWithPath(l string, filesystem fs.FS, p string) *Locale

NewLocaleFSWithPath returns a Locale working with a fs.FS on a p path folder.

func (*Locale) AddDRefs

func (l *Locale) AddDRefs(dom string, str string, refs ...string)

Add source references for a given translation

func (*Locale) AddDomain

func (l *Locale) AddDomain(dom string)

AddDomain creates a new domain for a given locale object and initializes the Po object. If the domain exists, it gets reloaded.

func (*Locale) AddRefs

func (l *Locale) AddRefs(str string, refs ...string)

Add source references for a given translation

func (*Locale) AddTranslator

func (l *Locale) AddTranslator(dom string, tr Translator)

AddTranslator takes a domain name and a Translator object to make it available in the Locale object.

func (*Locale) ClearAllRefs

func (l *Locale) ClearAllRefs()

Clear all source references

func (*Locale) ClearDAllRefs

func (l *Locale) ClearDAllRefs(dom string)

func (*Locale) ClearDRefs

func (l *Locale) ClearDRefs(dom string, str string)

Clear source references for a given translation

func (*Locale) ClearRefs

func (l *Locale) ClearRefs(str string)

Clear source references for a given translation

func (*Locale) Get

func (l *Locale) Get(str string, vars ...interface{}) string

Get uses a domain "default" to return the corresponding Translation of a given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetActualLanguage

func (l *Locale) GetActualLanguage(dom string) string

GetActualLanguage inspects the filesystem and decides whether to strip a CC part of the ll_CC locale string.

func (*Locale) GetC

func (l *Locale) GetC(str, ctx string, vars ...interface{}) string

GetC uses a domain "default" to return the corresponding Translation of the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetD

func (l *Locale) GetD(dom, str string, vars ...interface{}) string

GetD returns the corresponding Translation in the given domain for the given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetDC

func (l *Locale) GetDC(dom, str, ctx string, vars ...interface{}) string

GetDC returns the corresponding Translation in the given domain for the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetDomain

func (l *Locale) GetDomain() string

GetDomain is the domain getter for Locale configuration

func (*Locale) GetLanguage

func (l *Locale) GetLanguage() string

GetLanguage is the lang getter for Locale configuration

func (*Locale) GetN

func (l *Locale) GetN(str, plural string, n int, vars ...interface{}) string

GetN retrieves the (N)th plural form of Translation for the given string in the "default" domain. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetNC

func (l *Locale) GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context in the "default" domain. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetND

func (l *Locale) GetND(dom, str, plural string, n int, vars ...interface{}) string

GetND retrieves the (N)th plural form of Translation in the given domain for the given string. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetNDC

func (l *Locale) GetNDC(dom, str, plural string, n int, ctx string, vars ...interface{}) string

GetNDC retrieves the (N)th plural form of Translation in the given domain for the given string in the given context. Supports optional parameters (vars... interface{}) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetPath

func (l *Locale) GetPath() string

func (*Locale) GetTranslations

func (l *Locale) GetTranslations() map[string]*Translation

GetTranslations returns a copy of all translations in all domains of this locale. It does not support contexts.

func (*Locale) IsTranslated

func (l *Locale) IsTranslated(str string) bool

IsTranslated reports whether a string is translated

func (*Locale) IsTranslatedC

func (l *Locale) IsTranslatedC(str, ctx string) bool

IsTranslatedC reports whether a context string is translated

func (*Locale) IsTranslatedD

func (l *Locale) IsTranslatedD(dom, str string) bool

IsTranslatedD reports whether a domain string is translated

func (*Locale) IsTranslatedDC

func (l *Locale) IsTranslatedDC(dom, str, ctx string) bool

IsTranslatedDC reports whether a domain context string is translated

func (*Locale) IsTranslatedN

func (l *Locale) IsTranslatedN(str string, n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Locale) IsTranslatedNC

func (l *Locale) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC reports whether a plural context string is translated

func (*Locale) IsTranslatedND

func (l *Locale) IsTranslatedND(dom, str string, n int) bool

IsTranslatedND reports whether a plural domain string is translated

func (*Locale) IsTranslatedNDC

func (l *Locale) IsTranslatedNDC(dom string, str string, n int, ctx string) bool

IsTranslatedNDC reports whether a plural domain context string is translated

func (*Locale) MarshalBinary

func (l *Locale) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding BinaryMarshaler interface

func (*Locale) MarshalPo

func (l *Locale) MarshalPo() bool

MarshalPo

func (*Locale) MarshalPoD

func (l *Locale) MarshalPoD(dom string) bool

func (*Locale) SetDomain

func (l *Locale) SetDomain(dom string)

SetDomain sets the name for the domain to be used.

func (*Locale) UnmarshalBinary

func (l *Locale) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding BinaryUnmarshaler interface

type LocaleEncoding

type LocaleEncoding struct {
	Path          string
	Lang          string
	Domains       map[string][]byte
	DefaultDomain string
}

LocaleEncoding is used as intermediary storage to encode Locale objects to Gob.

type Mo

type Mo struct {
	// these three public members are for backwards compatibility. they are just set to the value in the domain
	Headers     HeaderMap
	Language    string
	PluralForms string
	// contains filtered or unexported fields
}

Mo parses the content of any MO file and provides all the Translation functions needed. It's the base object used by all package methods. And it's safe for concurrent use by multiple goroutines by using the sync package for locking.

Example:

import (
	"fmt"
	"github.com/leonelquinteros/gotext"
)

func main() {
	// Create mo object
	mo := gotext.NewMo()

	// Parse .mo file
	mo.ParseFile("/path/to/po/file/translations.mo")

	// Get Translation
	fmt.Println(mo.Get("Translate this"))
}

func NewMo

func NewMo() *Mo

NewMo should always be used to instantiate a new Mo object

func NewMoFS

func NewMoFS(filesystem fs.FS) *Mo

NewMoFS works like NewMO but adds an optional fs.FS

func (*Mo) Append

func (mo *Mo) Append(b []byte, str string, vars ...interface{}) []byte

func (*Mo) AppendC

func (mo *Mo) AppendC(b []byte, str, ctx string, vars ...interface{}) []byte

func (*Mo) AppendN

func (mo *Mo) AppendN(b []byte, str, plural string, n int, vars ...interface{}) []byte

func (*Mo) AppendNC

func (mo *Mo) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...interface{}) []byte

func (*Mo) Get

func (mo *Mo) Get(str string, vars ...interface{}) string

all of the Get functions are for convenience and aid in backwards compatibility

func (*Mo) GetC

func (mo *Mo) GetC(str, ctx string, vars ...interface{}) string

func (*Mo) GetDomain

func (mo *Mo) GetDomain() *Domain

func (*Mo) GetN

func (mo *Mo) GetN(str, plural string, n int, vars ...interface{}) string

func (*Mo) GetNC

func (mo *Mo) GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

func (*Mo) IsTranslated

func (mo *Mo) IsTranslated(str string) bool

func (*Mo) IsTranslatedC

func (mo *Mo) IsTranslatedC(str, ctx string) bool

func (*Mo) IsTranslatedN

func (mo *Mo) IsTranslatedN(str string, n int) bool

func (*Mo) IsTranslatedNC

func (mo *Mo) IsTranslatedNC(str string, n int, ctx string) bool

func (*Mo) MarshalBinary

func (mo *Mo) MarshalBinary() ([]byte, error)

func (*Mo) Parse

func (mo *Mo) Parse(buf []byte)

Parse loads the translations specified in the provided byte slice, in the GNU gettext .mo format

func (*Mo) ParseFile

func (mo *Mo) ParseFile(f string)

func (*Mo) UnmarshalBinary

func (mo *Mo) UnmarshalBinary(data []byte) error

type Po

type Po struct {
	// these three public members are for backwards compatibility. they are just set to the value in the domain
	Headers     HeaderMap
	Language    string
	PluralForms string
	// contains filtered or unexported fields
}

Po parses the content of any PO file and provides all the Translation functions needed. It's the base object used by all package methods. And it's safe for concurrent use by multiple goroutines by using the sync package for locking.

Example:

import (
	"fmt"
	"github.com/leonelquinteros/gotext"
)

func main() {
	// Create po object
	po := gotext.NewPo()

	// Parse .po file
	po.ParseFile("/path/to/po/file/translations.po")

	// Get Translation
	fmt.Println(po.Get("Translate this"))
}

func NewPo

func NewPo() *Po

NewPo should always be used to instantiate a new Po object

func NewPoFS

func NewPoFS(filesystem fs.FS) *Po

NewPoFS works like NewPO but adds an optional fs.FS

func (*Po) Append

func (po *Po) Append(b []byte, str string, vars ...interface{}) []byte

func (*Po) AppendC

func (po *Po) AppendC(b []byte, str, ctx string, vars ...interface{}) []byte

func (*Po) AppendN

func (po *Po) AppendN(b []byte, str, plural string, n int, vars ...interface{}) []byte

func (*Po) AppendNC

func (po *Po) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...interface{}) []byte

func (*Po) DropStaleTranslations

func (po *Po) DropStaleTranslations()

Convenience interfaces

func (*Po) Get

func (po *Po) Get(str string, vars ...interface{}) string

func (*Po) GetC

func (po *Po) GetC(str, ctx string, vars ...interface{}) string

func (*Po) GetDomain

func (po *Po) GetDomain() *Domain

func (*Po) GetN

func (po *Po) GetN(str, plural string, n int, vars ...interface{}) string

func (*Po) GetNC

func (po *Po) GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

func (*Po) GetRefs

func (po *Po) GetRefs(str string) []string

func (*Po) IsTranslated

func (po *Po) IsTranslated(str string) bool

func (*Po) IsTranslatedC

func (po *Po) IsTranslatedC(str, ctx string) bool

func (*Po) IsTranslatedN

func (po *Po) IsTranslatedN(str string, n int) bool

func (*Po) IsTranslatedNC

func (po *Po) IsTranslatedNC(str string, n int, ctx string) bool

func (*Po) MarshalBinary

func (po *Po) MarshalBinary() ([]byte, error)

func (*Po) MarshalText

func (po *Po) MarshalText() ([]byte, error)

func (*Po) Parse

func (po *Po) Parse(buf []byte)

Parse loads the translations specified in the provided byte slice (buf)

func (*Po) ParseFile

func (po *Po) ParseFile(f string)

func (*Po) Set

func (po *Po) Set(id, str string)

func (*Po) SetC

func (po *Po) SetC(id, ctx, str string)

func (*Po) SetN

func (po *Po) SetN(id, plural string, n int, str string)

func (*Po) SetNC

func (po *Po) SetNC(id, plural, ctx string, n int, str string)

func (*Po) SetPluralResolver

func (po *Po) SetPluralResolver(f func(int) int)

func (*Po) SetRefs

func (po *Po) SetRefs(str string, refs []string)

func (*Po) UnmarshalBinary

func (po *Po) UnmarshalBinary(data []byte) error

type SourceReference

type SourceReference struct {
	// contains filtered or unexported fields
}

type Translation

type Translation struct {
	ID       string
	PluralID string
	Trs      map[int]string
	Refs     []string

	Ctx               string
	TranslatorComment []string // #  translator-comments // TrimSpace
	ExtractedComment  []string // #. extracted-comments
	Flags             []string // #, fuzzy,c-format,range:0..10
	PrevMsgContext    string   // #| msgctxt previous-context
	PrevMsgId         string   // #| msgid previous-untranslated-string
	// contains filtered or unexported fields
}

Translation is the struct for the Translations parsed via Po or Mo files and all coming parsers

func NewTranslation

func NewTranslation() *Translation

NewTranslation returns the Translation object and initialized it.

func NewTranslationWithRefs

func NewTranslationWithRefs(refs []string) *Translation

func (*Translation) AddRefs

func (t *Translation) AddRefs(refs []string)

func (*Translation) ClearRefs

func (t *Translation) ClearRefs()

func (*Translation) Get

func (t *Translation) Get() string

Get returns the string of the translation

func (*Translation) GetN

func (t *Translation) GetN(n int) string

GetN returns the string of the plural translation

func (*Translation) IsStale

func (t *Translation) IsStale() bool

func (*Translation) IsTranslated

func (t *Translation) IsTranslated() bool

IsTranslated reports whether a string is translated

func (*Translation) IsTranslatedN

func (t *Translation) IsTranslatedN(n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Translation) Set

func (t *Translation) Set(str string)

func (*Translation) SetN

func (t *Translation) SetN(n int, str string)

func (*Translation) SetRefs

func (t *Translation) SetRefs(refs []string)

type Translator

type Translator interface {
	ParseFile(f string)
	Parse(buf []byte)
	Get(str string, vars ...interface{}) string
	GetN(str, plural string, n int, vars ...interface{}) string
	GetC(str, ctx string, vars ...interface{}) string
	GetNC(str, plural string, n int, ctx string, vars ...interface{}) string

	MarshalBinary() ([]byte, error)
	UnmarshalBinary([]byte) error
	GetDomain() *Domain
}

Translator interface is used by Locale and Po objects.Translator It contains all methods needed to parse translation sources and obtain corresponding translations. Also implements gob.GobEncoder/gob.DobDecoder interfaces to allow serialization of Locale objects.

type TranslatorEncoding

type TranslatorEncoding struct {
	// Headers storage
	Headers HeaderMap

	// Language header
	Language string

	// Plural-Forms header
	PluralForms string

	// Parsed Plural-Forms header values
	Nplurals int
	Plural   string

	// Storage
	Translations map[string]*Translation
	Contexts     map[string]map[string]*Translation
}

TranslatorEncoding is used as intermediary storage to encode Translator objects to Gob.

func (*TranslatorEncoding) GetTranslator

func (te *TranslatorEncoding) GetTranslator() Translator

GetTranslator is used to recover a Translator object after unmarshalling the TranslatorEncoding object. Internally uses a Po object as it should be switchable with Mo objects without problem. External Translator implementations should be able to serialize into a TranslatorEncoding object in order to deserialize into a Po-compatible object.

Directories

Path Synopsis
cli
Package plurals is the pluralform compiler to get the correct translation id of the plural string
Package plurals is the pluralform compiler to get the correct translation id of the plural string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL