1
0
mirror of https://github.com/jesseduffield/lazygit.git synced 2025-06-15 00:15:32 +02:00

merge master

This commit is contained in:
Jesse Duffield
2018-08-18 12:08:21 +10:00
56 changed files with 12960 additions and 145 deletions

201
vendor/github.com/cloudfoundry/jibber_jabber/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 Pivotal
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,22 @@
package jibber_jabber
import (
"strings"
)
const (
COULD_NOT_DETECT_PACKAGE_ERROR_MESSAGE = "Could not detect Language"
)
func splitLocale(locale string) (string, string) {
formattedLocale := strings.Split(locale, ".")[0]
formattedLocale = strings.Replace(formattedLocale, "-", "_", -1)
pieces := strings.Split(formattedLocale, "_")
language := pieces[0]
territory := ""
if len(pieces) > 1 {
territory = strings.Split(formattedLocale, "_")[1]
}
return language, territory
}

View File

@ -0,0 +1,57 @@
// +build darwin freebsd linux netbsd openbsd
package jibber_jabber
import (
"errors"
"os"
"strings"
)
func getLangFromEnv() (locale string) {
locale = os.Getenv("LC_ALL")
if locale == "" {
locale = os.Getenv("LANG")
}
return
}
func getUnixLocale() (unix_locale string, err error) {
unix_locale = getLangFromEnv()
if unix_locale == "" {
err = errors.New(COULD_NOT_DETECT_PACKAGE_ERROR_MESSAGE)
}
return
}
func DetectIETF() (locale string, err error) {
unix_locale, err := getUnixLocale()
if err == nil {
language, territory := splitLocale(unix_locale)
locale = language
if territory != "" {
locale = strings.Join([]string{language, territory}, "-")
}
}
return
}
func DetectLanguage() (language string, err error) {
unix_locale, err := getUnixLocale()
if err == nil {
language, _ = splitLocale(unix_locale)
}
return
}
func DetectTerritory() (territory string, err error) {
unix_locale, err := getUnixLocale()
if err == nil {
_, territory = splitLocale(unix_locale)
}
return
}

View File

@ -0,0 +1,114 @@
// +build windows
package jibber_jabber
import (
"errors"
"syscall"
"unsafe"
)
const LOCALE_NAME_MAX_LENGTH uint32 = 85
var SUPPORTED_LOCALES = map[uintptr]string{
0x0407: "de-DE",
0x0409: "en-US",
0x0c0a: "es-ES", //or is it 0x040a
0x040c: "fr-FR",
0x0410: "it-IT",
0x0411: "ja-JA",
0x0412: "ko_KR",
0x0416: "pt-BR",
//0x0419: "ru_RU", - Will add support for Russian when nicksnyder/go-i18n supports Russian
0x0804: "zh-CN",
0x0c04: "zh-HK",
0x0404: "zh-TW",
}
func getWindowsLocaleFrom(sysCall string) (locale string, err error) {
buffer := make([]uint16, LOCALE_NAME_MAX_LENGTH)
dll := syscall.MustLoadDLL("kernel32")
proc := dll.MustFindProc(sysCall)
r, _, dllError := proc.Call(uintptr(unsafe.Pointer(&buffer[0])), uintptr(LOCALE_NAME_MAX_LENGTH))
if r == 0 {
err = errors.New(COULD_NOT_DETECT_PACKAGE_ERROR_MESSAGE + ":\n" + dllError.Error())
return
}
locale = syscall.UTF16ToString(buffer)
return
}
func getAllWindowsLocaleFrom(sysCall string) (string, error) {
dll, err := syscall.LoadDLL("kernel32")
if err != nil {
return "", errors.New("Could not find kernel32 dll")
}
proc, err := dll.FindProc(sysCall)
if err != nil {
return "", err
}
locale, _, dllError := proc.Call()
if locale == 0 {
return "", errors.New(COULD_NOT_DETECT_PACKAGE_ERROR_MESSAGE + ":\n" + dllError.Error())
}
return SUPPORTED_LOCALES[locale], nil
}
func getWindowsLocale() (locale string, err error) {
dll, err := syscall.LoadDLL("kernel32")
if err != nil {
return "", errors.New("Could not find kernel32 dll")
}
proc, err := dll.FindProc("GetVersion")
if err != nil {
return "", err
}
v, _, _ := proc.Call()
windowsVersion := byte(v)
isVistaOrGreater := (windowsVersion >= 6)
if isVistaOrGreater {
locale, err = getWindowsLocaleFrom("GetUserDefaultLocaleName")
if err != nil {
locale, err = getWindowsLocaleFrom("GetSystemDefaultLocaleName")
}
} else if !isVistaOrGreater {
locale, err = getAllWindowsLocaleFrom("GetUserDefaultLCID")
if err != nil {
locale, err = getAllWindowsLocaleFrom("GetSystemDefaultLCID")
}
} else {
panic(v)
}
return
}
func DetectIETF() (locale string, err error) {
locale, err = getWindowsLocale()
return
}
func DetectLanguage() (language string, err error) {
windows_locale, err := getWindowsLocale()
if err == nil {
language, _ = splitLocale(windows_locale)
}
return
}
func DetectTerritory() (territory string, err error) {
windows_locale, err := getWindowsLocale()
if err == nil {
_, territory = splitLocale(windows_locale)
}
return
}

19
vendor/github.com/nicksnyder/go-i18n/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2014 Nick Snyder https://github.com/nicksnyder
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

129
vendor/github.com/nicksnyder/go-i18n/v2/i18n/bundle.go generated vendored Normal file
View File

@ -0,0 +1,129 @@
package i18n
import (
"fmt"
"io/ioutil"
"github.com/nicksnyder/go-i18n/v2/internal"
"github.com/nicksnyder/go-i18n/v2/internal/plural"
"golang.org/x/text/language"
)
// UnmarshalFunc unmarshals data into v.
type UnmarshalFunc = internal.UnmarshalFunc
// Bundle stores a set of messages and pluralization rules.
// Most applications only need a single bundle
// that is initialized early in the application's lifecycle.
type Bundle struct {
// DefaultLanguage is the default language of the bundle.
DefaultLanguage language.Tag
// UnmarshalFuncs is a map of file extensions to UnmarshalFuncs.
UnmarshalFuncs map[string]UnmarshalFunc
messageTemplates map[language.Tag]map[string]*internal.MessageTemplate
pluralRules plural.Rules
tags []language.Tag
matcher language.Matcher
}
func (b *Bundle) init() {
if b.pluralRules == nil {
b.pluralRules = plural.DefaultRules()
}
b.addTag(b.DefaultLanguage)
}
// RegisterUnmarshalFunc registers an UnmarshalFunc for format.
func (b *Bundle) RegisterUnmarshalFunc(format string, unmarshalFunc UnmarshalFunc) {
if b.UnmarshalFuncs == nil {
b.UnmarshalFuncs = make(map[string]UnmarshalFunc)
}
b.UnmarshalFuncs[format] = unmarshalFunc
}
// LoadMessageFile loads the bytes from path
// and then calls ParseMessageFileBytes.
func (b *Bundle) LoadMessageFile(path string) (*MessageFile, error) {
buf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return b.ParseMessageFileBytes(buf, path)
}
// MustLoadMessageFile is similar to LoadTranslationFile
// except it panics if an error happens.
func (b *Bundle) MustLoadMessageFile(path string) {
if _, err := b.LoadMessageFile(path); err != nil {
panic(err)
}
}
// MessageFile represents a parsed message file.
type MessageFile = internal.MessageFile
// ParseMessageFileBytes parses the bytes in buf to add translations to the bundle.
//
// The format of the file is everything after the last ".".
//
// The language tag of the file is everything after the second to last "." or after the last path separator, but before the format.
func (b *Bundle) ParseMessageFileBytes(buf []byte, path string) (*MessageFile, error) {
messageFile, err := internal.ParseMessageFileBytes(buf, path, b.UnmarshalFuncs)
if err != nil {
return nil, err
}
if err := b.AddMessages(messageFile.Tag, messageFile.Messages...); err != nil {
return nil, err
}
return messageFile, nil
}
// MustParseMessageFileBytes is similar to ParseMessageFileBytes
// except it panics if an error happens.
func (b *Bundle) MustParseMessageFileBytes(buf []byte, path string) {
if _, err := b.ParseMessageFileBytes(buf, path); err != nil {
panic(err)
}
}
// AddMessages adds messages for a language.
// It is useful if your messages are in a format not supported by ParseMessageFileBytes.
func (b *Bundle) AddMessages(tag language.Tag, messages ...*Message) error {
b.init()
pluralRule := b.pluralRules.Rule(tag)
if pluralRule == nil {
return fmt.Errorf("no plural rule registered for %s", tag)
}
if b.messageTemplates == nil {
b.messageTemplates = map[language.Tag]map[string]*internal.MessageTemplate{}
}
if b.messageTemplates[tag] == nil {
b.messageTemplates[tag] = map[string]*internal.MessageTemplate{}
b.addTag(tag)
}
for _, m := range messages {
b.messageTemplates[tag][m.ID] = internal.NewMessageTemplate(m)
}
return nil
}
// MustAddMessages is similar to AddMessages except it panics if an error happens.
func (b *Bundle) MustAddMessages(tag language.Tag, messages ...*Message) {
if err := b.AddMessages(tag, messages...); err != nil {
panic(err)
}
}
func (b *Bundle) addTag(tag language.Tag) {
for _, t := range b.tags {
if t == tag {
// Tag already exists
return
}
}
b.tags = append(b.tags, tag)
b.matcher = language.NewMatcher(b.tags)
}

21
vendor/github.com/nicksnyder/go-i18n/v2/i18n/doc.go generated vendored Normal file
View File

@ -0,0 +1,21 @@
// Package i18n provides support for looking up messages
// according to a set of locale preferences.
//
// Create a Bundle to use for the lifetime of your application.
// bundle := &i18n.Bundle{DefaultLanguage: language.English}
//
// Create a Localizer to use for a set of language preferences.
// func(w http.ResponseWriter, r *http.Request) {
// lang := r.FormValue("lang")
// accept := r.Header.Get("Accept-Language")
// localizer := i18n.NewLocalizer(bundle, lang, accept)
// }
//
// Use the Localizer to lookup messages.
// localizer.MustLocalize(&i18n.LocalizeConfig{
// DefaultMessage: &i18n.Message{
// ID: "HelloWorld",
// Other: "Hello World!",
// },
// })
package i18n

View File

@ -0,0 +1,198 @@
package i18n
import (
"fmt"
"text/template"
"github.com/nicksnyder/go-i18n/v2/internal"
"github.com/nicksnyder/go-i18n/v2/internal/plural"
"golang.org/x/text/language"
)
// Localizer provides Localize and MustLocalize methods that return localized messages.
type Localizer struct {
// bundle contains the messages that can be returned by the Localizer.
bundle *Bundle
// tags is the list of language tags that the Localizer checks
// in order when localizing a message.
tags []language.Tag
}
// NewLocalizer returns a new Localizer that looks up messages
// in the bundle according to the language preferences in langs.
// It can parse Accept-Language headers as defined in http://www.ietf.org/rfc/rfc2616.txt.
func NewLocalizer(bundle *Bundle, langs ...string) *Localizer {
bundle.init()
return &Localizer{
bundle: bundle,
tags: parseTags(langs),
}
}
func parseTags(langs []string) []language.Tag {
tags := []language.Tag{}
for _, lang := range langs {
t, _, err := language.ParseAcceptLanguage(lang)
if err != nil {
continue
}
tags = append(tags, t...)
}
return tags
}
// LocalizeConfig configures a call to the Localize method on Localizer.
type LocalizeConfig struct {
// MessageID is the id of the message to lookup.
// This field is ignored if DefaultMessage is set.
MessageID string
// TemplateData is the data passed when executing the message's template.
// If TemplateData is nil and PluralCount is not nil, then the message template
// will be executed with data that contains the plural count.
TemplateData interface{}
// PluralCount determines which plural form of the message is used.
PluralCount interface{}
// DefaultMessage is used if the message is not found in any message files.
DefaultMessage *Message
// Funcs is used to extend the Go template engines built in functions
Funcs template.FuncMap
}
type invalidPluralCountErr struct {
messageID string
pluralCount interface{}
err error
}
func (e *invalidPluralCountErr) Error() string {
return fmt.Sprintf("invalid plural count %#v for message id %q: %s", e.pluralCount, e.messageID, e.err)
}
type messageNotFoundErr struct {
messageID string
}
func (e *messageNotFoundErr) Error() string {
return fmt.Sprintf("message %q not found", e.messageID)
}
type pluralizeErr struct {
messageID string
tag language.Tag
}
func (e *pluralizeErr) Error() string {
return fmt.Sprintf("unable to pluralize %q because there no plural rule for %q", e.messageID, e.tag)
}
// Localize returns a localized message.
func (l *Localizer) Localize(lc *LocalizeConfig) (string, error) {
messageID := lc.MessageID
if lc.DefaultMessage != nil {
messageID = lc.DefaultMessage.ID
}
var operands *plural.Operands
templateData := lc.TemplateData
if lc.PluralCount != nil {
var err error
operands, err = plural.NewOperands(lc.PluralCount)
if err != nil {
return "", &invalidPluralCountErr{messageID: messageID, pluralCount: lc.PluralCount, err: err}
}
if templateData == nil {
templateData = map[string]interface{}{
"PluralCount": lc.PluralCount,
}
}
}
tag, template := l.getTemplate(messageID, lc.DefaultMessage)
if template == nil {
return "", &messageNotFoundErr{messageID: messageID}
}
pluralForm := l.pluralForm(tag, operands)
if pluralForm == plural.Invalid {
return "", &pluralizeErr{messageID: messageID, tag: tag}
}
return template.Execute(pluralForm, templateData, lc.Funcs)
}
func (l *Localizer) getTemplate(id string, defaultMessage *Message) (language.Tag, *internal.MessageTemplate) {
// Fast path.
// Optimistically assume this message id is defined in each language.
fastTag, template := l.matchTemplate(id, l.bundle.matcher, l.bundle.tags)
if template != nil {
return fastTag, template
}
if fastTag == l.bundle.DefaultLanguage {
if defaultMessage == nil {
return fastTag, nil
}
return fastTag, internal.NewMessageTemplate(defaultMessage)
}
if len(l.bundle.tags) > 1 {
// Slow path.
// We didn't find a translation for the tag suggested by the default matcher
// so we need to create a new matcher that contains only the tags in the bundle
// that have this message.
foundTags := make([]language.Tag, 0, len(l.bundle.messageTemplates))
if l.bundle.DefaultLanguage != fastTag {
foundTags = append(foundTags, l.bundle.DefaultLanguage)
}
for t, templates := range l.bundle.messageTemplates {
if t == fastTag {
// We already tried this tag in the fast path
continue
}
template := templates[id]
if template == nil || template.Other == "" {
continue
}
foundTags = append(foundTags, t)
}
tag, template := l.matchTemplate(id, language.NewMatcher(foundTags), foundTags)
if template != nil {
return tag, template
}
}
if defaultMessage == nil {
return l.bundle.DefaultLanguage, nil
}
return l.bundle.DefaultLanguage, internal.NewMessageTemplate(defaultMessage)
}
func (l *Localizer) matchTemplate(id string, matcher language.Matcher, tags []language.Tag) (language.Tag, *internal.MessageTemplate) {
_, i, _ := matcher.Match(l.tags...)
tag := tags[i]
templates := l.bundle.messageTemplates[tag]
if templates != nil && templates[id] != nil {
return tag, templates[id]
}
return tag, nil
}
func (l *Localizer) pluralForm(tag language.Tag, operands *plural.Operands) plural.Form {
if operands == nil {
return plural.Other
}
pluralRule := l.bundle.pluralRules.Rule(tag)
if pluralRule == nil {
return plural.Invalid
}
return pluralRule.PluralFormFunc(operands)
}
// MustLocalize is similar to Localize, except it panics if an error happens.
func (l *Localizer) MustLocalize(lc *LocalizeConfig) string {
localized, err := l.Localize(lc)
if err != nil {
panic(err)
}
return localized
}

View File

@ -0,0 +1,6 @@
package i18n
import "github.com/nicksnyder/go-i18n/v2/internal"
// Message is a string that can be localized.
type Message = internal.Message

View File

@ -0,0 +1,164 @@
package internal
import (
"fmt"
"strings"
)
// Message is a string that can be localized.
type Message struct {
// ID uniquely identifies the message.
ID string
// Hash uniquely identifies the content of the message
// that this message was translated from.
Hash string
// Description describes the message to give additional
// context to translators that may be relevant for translation.
Description string
// LeftDelim is the left Go template delimiter.
LeftDelim string
// RightDelim is the right Go template delimiter.``
RightDelim string
// Zero is the content of the message for the CLDR plural form "zero".
Zero string
// One is the content of the message for the CLDR plural form "one".
One string
// Two is the content of the message for the CLDR plural form "two".
Two string
// Few is the content of the message for the CLDR plural form "few".
Few string
// Many is the content of the message for the CLDR plural form "many".
Many string
// Other is the content of the message for the CLDR plural form "other".
Other string
}
// NewMessage parses data and returns a new message.
func NewMessage(data interface{}) (*Message, error) {
m := &Message{}
if err := m.unmarshalInterface(data); err != nil {
return nil, err
}
return m, nil
}
// MustNewMessage is similar to NewMessage except it panics if an error happens.
func MustNewMessage(data interface{}) *Message {
m, err := NewMessage(data)
if err != nil {
panic(err)
}
return m
}
// unmarshalInterface unmarshals a message from data.
func (m *Message) unmarshalInterface(v interface{}) error {
strdata, err := stringMap(v)
if err != nil {
return err
}
for k, v := range strdata {
switch strings.ToLower(k) {
case "id":
m.ID = v
case "description":
m.Description = v
case "hash":
m.Hash = v
case "leftDelim":
m.LeftDelim = v
case "rightDelim":
m.RightDelim = v
case "zero":
m.Zero = v
case "one":
m.One = v
case "two":
m.Two = v
case "few":
m.Few = v
case "many":
m.Many = v
case "other":
m.Other = v
}
}
return nil
}
func stringMap(v interface{}) (map[string]string, error) {
switch value := v.(type) {
case string:
return map[string]string{
"other": value,
}, nil
case map[string]string:
return value, nil
case map[string]interface{}:
strdata := map[string]string{}
for k, v := range value {
if k == "translation" {
switch vt := v.(type) {
case string:
strdata["other"] = vt
default:
v1Message, err := stringMap(v)
if err != nil {
return nil, err
}
for kk, vv := range v1Message {
strdata[kk] = vv
}
}
continue
}
vstr, ok := v.(string)
if !ok {
return nil, fmt.Errorf("expected value for key %q be a string but got %#v", k, v)
}
strdata[k] = vstr
}
return strdata, nil
case map[interface{}]interface{}:
strdata := map[string]string{}
for k, v := range value {
kstr, ok := k.(string)
if !ok {
return nil, fmt.Errorf("expected key to be a string but got %#v", k)
}
if kstr == "translation" {
switch vt := v.(type) {
case string:
strdata["other"] = vt
default:
v1Message, err := stringMap(v)
if err != nil {
return nil, err
}
for kk, vv := range v1Message {
strdata[kk] = vv
}
}
continue
}
vstr, ok := v.(string)
if !ok {
return nil, fmt.Errorf("expected value for key %q be a string but got %#v", k, v)
}
strdata[kstr] = vstr
}
return strdata, nil
default:
return nil, fmt.Errorf("unsupported type %#v", value)
}
}

View File

@ -0,0 +1,55 @@
package internal
import (
"bytes"
"text/template"
"github.com/nicksnyder/go-i18n/v2/internal/plural"
)
// MessageTemplate is an executable template for a message.
type MessageTemplate struct {
*Message
PluralTemplates map[plural.Form]*Template
}
// NewMessageTemplate returns a new message template.
func NewMessageTemplate(m *Message) *MessageTemplate {
pluralTemplates := map[plural.Form]*Template{}
setPluralTemplate(pluralTemplates, plural.Zero, m.Zero)
setPluralTemplate(pluralTemplates, plural.One, m.One)
setPluralTemplate(pluralTemplates, plural.Two, m.Two)
setPluralTemplate(pluralTemplates, plural.Few, m.Few)
setPluralTemplate(pluralTemplates, plural.Many, m.Many)
setPluralTemplate(pluralTemplates, plural.Other, m.Other)
if len(pluralTemplates) == 0 {
return nil
}
return &MessageTemplate{
Message: m,
PluralTemplates: pluralTemplates,
}
}
func setPluralTemplate(pluralTemplates map[plural.Form]*Template, pluralForm plural.Form, src string) {
if src != "" {
pluralTemplates[pluralForm] = &Template{Src: src}
}
}
// Execute executes the template for the plural form and template data.
func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, funcs template.FuncMap) (string, error) {
t := mt.PluralTemplates[pluralForm]
if err := t.parse(mt.LeftDelim, mt.RightDelim, funcs); err != nil {
return "", err
}
if t.Template == nil {
return t.Src, nil
}
var buf bytes.Buffer
if err := t.Template.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}

View File

@ -0,0 +1,112 @@
package internal
import (
"encoding/json"
"fmt"
"os"
"golang.org/x/text/language"
)
// UnmarshalFunc unmarshals data into v.
type UnmarshalFunc func(data []byte, v interface{}) error
// MessageFile represents a parsed message file.
type MessageFile struct {
Path string
Tag language.Tag
Format string
Messages []*Message
}
// ParseMessageFileBytes returns the messages parsed from file.
func ParseMessageFileBytes(buf []byte, path string, unmarshalFuncs map[string]UnmarshalFunc) (*MessageFile, error) {
lang, format := parsePath(path)
tag := language.Make(lang)
messageFile := &MessageFile{
Path: path,
Tag: tag,
Format: format,
}
if len(buf) == 0 {
return messageFile, nil
}
unmarshalFunc := unmarshalFuncs[messageFile.Format]
if unmarshalFunc == nil {
if messageFile.Format == "json" {
unmarshalFunc = json.Unmarshal
} else {
return nil, fmt.Errorf("no unmarshaler registered for %s", messageFile.Format)
}
}
var raw interface{}
if err := unmarshalFunc(buf, &raw); err != nil {
return nil, err
}
switch data := raw.(type) {
case map[string]interface{}:
messageFile.Messages = make([]*Message, 0, len(data))
for id, data := range data {
m, err := NewMessage(data)
if err != nil {
return nil, err
}
m.ID = id
messageFile.Messages = append(messageFile.Messages, m)
}
case map[interface{}]interface{}:
messageFile.Messages = make([]*Message, 0, len(data))
for id, data := range data {
strid, ok := id.(string)
if !ok {
return nil, fmt.Errorf("expected key to be string but got %#v", id)
}
m, err := NewMessage(data)
if err != nil {
return nil, err
}
m.ID = strid
messageFile.Messages = append(messageFile.Messages, m)
}
case []interface{}:
// Backward compatibility for v1 file format.
messageFile.Messages = make([]*Message, 0, len(data))
for _, data := range data {
m, err := NewMessage(data)
if err != nil {
return nil, err
}
messageFile.Messages = append(messageFile.Messages, m)
}
default:
return nil, fmt.Errorf("unsupported file format %T", raw)
}
return messageFile, nil
}
func parsePath(path string) (langTag, format string) {
formatStartIdx := -1
for i := len(path) - 1; i >= 0; i-- {
c := path[i]
if os.IsPathSeparator(c) {
if formatStartIdx != -1 {
langTag = path[i+1 : formatStartIdx]
}
return
}
if path[i] == '.' {
if formatStartIdx != -1 {
langTag = path[i+1 : formatStartIdx]
return
}
if formatStartIdx == -1 {
format = path[i+1:]
formatStartIdx = i
}
}
}
if formatStartIdx != -1 {
langTag = path[:formatStartIdx]
}
return
}

View File

@ -0,0 +1,3 @@
// Package plural provides support for pluralizing messages
// according to CLDR rules http://cldr.unicode.org/index/cldr-spec/plural-rules
package plural

View File

@ -0,0 +1,16 @@
package plural
// Form represents a language pluralization form as defined here:
// http://cldr.unicode.org/index/cldr-spec/plural-rules
type Form string
// All defined plural forms.
const (
Invalid Form = ""
Zero Form = "zero"
One Form = "one"
Two Form = "two"
Few Form = "few"
Many Form = "many"
Other Form = "other"
)

View File

@ -0,0 +1,120 @@
package plural
import (
"fmt"
"strconv"
"strings"
)
// Operands is a representation of http://unicode.org/reports/tr35/tr35-numbers.html#Operands
type Operands struct {
N float64 // absolute value of the source number (integer and decimals)
I int64 // integer digits of n
V int64 // number of visible fraction digits in n, with trailing zeros
W int64 // number of visible fraction digits in n, without trailing zeros
F int64 // visible fractional digits in n, with trailing zeros
T int64 // visible fractional digits in n, without trailing zeros
}
// NEqualsAny returns true if o represents an integer equal to any of the arguments.
func (o *Operands) NEqualsAny(any ...int64) bool {
for _, i := range any {
if o.I == i && o.T == 0 {
return true
}
}
return false
}
// NModEqualsAny returns true if o represents an integer equal to any of the arguments modulo mod.
func (o *Operands) NModEqualsAny(mod int64, any ...int64) bool {
modI := o.I % mod
for _, i := range any {
if modI == i && o.T == 0 {
return true
}
}
return false
}
// NInRange returns true if o represents an integer in the closed interval [from, to].
func (o *Operands) NInRange(from, to int64) bool {
return o.T == 0 && from <= o.I && o.I <= to
}
// NModInRange returns true if o represents an integer in the closed interval [from, to] modulo mod.
func (o *Operands) NModInRange(mod, from, to int64) bool {
modI := o.I % mod
return o.T == 0 && from <= modI && modI <= to
}
// NewOperands returns the operands for number.
func NewOperands(number interface{}) (*Operands, error) {
switch number := number.(type) {
case int:
return newOperandsInt64(int64(number)), nil
case int8:
return newOperandsInt64(int64(number)), nil
case int16:
return newOperandsInt64(int64(number)), nil
case int32:
return newOperandsInt64(int64(number)), nil
case int64:
return newOperandsInt64(number), nil
case string:
return newOperandsString(number)
case float32, float64:
return nil, fmt.Errorf("floats should be formatted into a string")
default:
return nil, fmt.Errorf("invalid type %T; expected integer or string", number)
}
}
func newOperandsInt64(i int64) *Operands {
if i < 0 {
i = -i
}
return &Operands{float64(i), i, 0, 0, 0, 0}
}
func newOperandsString(s string) (*Operands, error) {
if s[0] == '-' {
s = s[1:]
}
n, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, err
}
ops := &Operands{N: n}
parts := strings.SplitN(s, ".", 2)
ops.I, err = strconv.ParseInt(parts[0], 10, 64)
if err != nil {
return nil, err
}
if len(parts) == 1 {
return ops, nil
}
fraction := parts[1]
ops.V = int64(len(fraction))
for i := ops.V - 1; i >= 0; i-- {
if fraction[i] != '0' {
ops.W = i + 1
break
}
}
if ops.V > 0 {
f, err := strconv.ParseInt(fraction, 10, 0)
if err != nil {
return nil, err
}
ops.F = f
}
if ops.W > 0 {
t, err := strconv.ParseInt(fraction[:ops.W], 10, 0)
if err != nil {
return nil, err
}
ops.T = t
}
return ops, nil
}

View File

@ -0,0 +1,44 @@
package plural
import (
"golang.org/x/text/language"
)
// Rule defines the CLDR plural rules for a language.
// http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html
// http://unicode.org/reports/tr35/tr35-numbers.html#Operands
type Rule struct {
PluralForms map[Form]struct{}
PluralFormFunc func(*Operands) Form
}
func addPluralRules(rules Rules, ids []string, ps *Rule) {
for _, id := range ids {
if id == "root" {
continue
}
tag := language.MustParse(id)
rules[tag] = ps
}
}
func newPluralFormSet(pluralForms ...Form) map[Form]struct{} {
set := make(map[Form]struct{}, len(pluralForms))
for _, plural := range pluralForms {
set[plural] = struct{}{}
}
return set
}
func intInRange(i, from, to int64) bool {
return from <= i && i <= to
}
func intEqualsAny(i int64, any ...int64) bool {
for _, a := range any {
if i == a {
return true
}
}
return false
}

View File

@ -0,0 +1,561 @@
// This file is generated by i18n/plural/codegen/generate.sh; DO NOT EDIT
package plural
// DefaultRules returns a map of Rules generated from CLDR language data.
func DefaultRules() Rules {
rules := Rules{}
addPluralRules(rules, []string{"bm", "bo", "dz", "id", "ig", "ii", "in", "ja", "jbo", "jv", "jw", "kde", "kea", "km", "ko", "lkt", "lo", "ms", "my", "nqo", "root", "sah", "ses", "sg", "th", "to", "vi", "wo", "yo", "yue", "zh"}, &Rule{
PluralForms: newPluralFormSet(Other),
PluralFormFunc: func(ops *Operands) Form {
return Other
},
})
addPluralRules(rules, []string{"am", "as", "bn", "fa", "gu", "hi", "kn", "mr", "zu"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 0 or n = 1
if intEqualsAny(ops.I, 0) ||
ops.NEqualsAny(1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"ff", "fr", "hy", "kab"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 0,1
if intEqualsAny(ops.I, 0, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"pt"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 0..1
if intInRange(ops.I, 0, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"ast", "ca", "de", "en", "et", "fi", "fy", "gl", "io", "it", "ji", "nl", "pt_PT", "scn", "sv", "sw", "ur", "yi"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 1 and v = 0
if intEqualsAny(ops.I, 1) && intEqualsAny(ops.V, 0) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"si"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0,1 or i = 0 and f = 1
if ops.NEqualsAny(0, 1) ||
intEqualsAny(ops.I, 0) && intEqualsAny(ops.F, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"ak", "bh", "guw", "ln", "mg", "nso", "pa", "ti", "wa"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0..1
if ops.NInRange(0, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"tzm"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0..1 or n = 11..99
if ops.NInRange(0, 1) ||
ops.NInRange(11, 99) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"af", "asa", "az", "bem", "bez", "bg", "brx", "ce", "cgg", "chr", "ckb", "dv", "ee", "el", "eo", "es", "eu", "fo", "fur", "gsw", "ha", "haw", "hu", "jgo", "jmc", "ka", "kaj", "kcg", "kk", "kkj", "kl", "ks", "ksb", "ku", "ky", "lb", "lg", "mas", "mgo", "ml", "mn", "nah", "nb", "nd", "ne", "nn", "nnh", "no", "nr", "ny", "nyn", "om", "or", "os", "pap", "ps", "rm", "rof", "rwk", "saq", "sd", "sdh", "seh", "sn", "so", "sq", "ss", "ssy", "st", "syr", "ta", "te", "teo", "tig", "tk", "tn", "tr", "ts", "ug", "uz", "ve", "vo", "vun", "wae", "xh", "xog"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1
if ops.NEqualsAny(1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"da"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1 or t != 0 and i = 0,1
if ops.NEqualsAny(1) ||
!intEqualsAny(ops.T, 0) && intEqualsAny(ops.I, 0, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"is"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// t = 0 and i % 10 = 1 and i % 100 != 11 or t != 0
if intEqualsAny(ops.T, 0) && intEqualsAny(ops.I%10, 1) && !intEqualsAny(ops.I%100, 11) ||
!intEqualsAny(ops.T, 0) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"mk"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 10 = 1 and i % 100 != 11 or f % 10 = 1 and f % 100 != 11
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 1) && !intEqualsAny(ops.I%100, 11) ||
intEqualsAny(ops.F%10, 1) && !intEqualsAny(ops.F%100, 11) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"fil", "tl"}, &Rule{
PluralForms: newPluralFormSet(One, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i = 1,2,3 or v = 0 and i % 10 != 4,6,9 or v != 0 and f % 10 != 4,6,9
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I, 1, 2, 3) ||
intEqualsAny(ops.V, 0) && !intEqualsAny(ops.I%10, 4, 6, 9) ||
!intEqualsAny(ops.V, 0) && !intEqualsAny(ops.F%10, 4, 6, 9) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"lv", "prg"}, &Rule{
PluralForms: newPluralFormSet(Zero, One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n % 10 = 0 or n % 100 = 11..19 or v = 2 and f % 100 = 11..19
if ops.NModEqualsAny(10, 0) ||
ops.NModInRange(100, 11, 19) ||
intEqualsAny(ops.V, 2) && intInRange(ops.F%100, 11, 19) {
return Zero
}
// n % 10 = 1 and n % 100 != 11 or v = 2 and f % 10 = 1 and f % 100 != 11 or v != 2 and f % 10 = 1
if ops.NModEqualsAny(10, 1) && !ops.NModEqualsAny(100, 11) ||
intEqualsAny(ops.V, 2) && intEqualsAny(ops.F%10, 1) && !intEqualsAny(ops.F%100, 11) ||
!intEqualsAny(ops.V, 2) && intEqualsAny(ops.F%10, 1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"lag"}, &Rule{
PluralForms: newPluralFormSet(Zero, One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0
if ops.NEqualsAny(0) {
return Zero
}
// i = 0,1 and n != 0
if intEqualsAny(ops.I, 0, 1) && !ops.NEqualsAny(0) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"ksh"}, &Rule{
PluralForms: newPluralFormSet(Zero, One, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0
if ops.NEqualsAny(0) {
return Zero
}
// n = 1
if ops.NEqualsAny(1) {
return One
}
return Other
},
})
addPluralRules(rules, []string{"iu", "kw", "naq", "se", "sma", "smi", "smj", "smn", "sms"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1
if ops.NEqualsAny(1) {
return One
}
// n = 2
if ops.NEqualsAny(2) {
return Two
}
return Other
},
})
addPluralRules(rules, []string{"shi"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 0 or n = 1
if intEqualsAny(ops.I, 0) ||
ops.NEqualsAny(1) {
return One
}
// n = 2..10
if ops.NInRange(2, 10) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"mo", "ro"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 1 and v = 0
if intEqualsAny(ops.I, 1) && intEqualsAny(ops.V, 0) {
return One
}
// v != 0 or n = 0 or n != 1 and n % 100 = 1..19
if !intEqualsAny(ops.V, 0) ||
ops.NEqualsAny(0) ||
!ops.NEqualsAny(1) && ops.NModInRange(100, 1, 19) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"bs", "hr", "sh", "sr"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 10 = 1 and i % 100 != 11 or f % 10 = 1 and f % 100 != 11
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 1) && !intEqualsAny(ops.I%100, 11) ||
intEqualsAny(ops.F%10, 1) && !intEqualsAny(ops.F%100, 11) {
return One
}
// v = 0 and i % 10 = 2..4 and i % 100 != 12..14 or f % 10 = 2..4 and f % 100 != 12..14
if intEqualsAny(ops.V, 0) && intInRange(ops.I%10, 2, 4) && !intInRange(ops.I%100, 12, 14) ||
intInRange(ops.F%10, 2, 4) && !intInRange(ops.F%100, 12, 14) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"gd"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1,11
if ops.NEqualsAny(1, 11) {
return One
}
// n = 2,12
if ops.NEqualsAny(2, 12) {
return Two
}
// n = 3..10,13..19
if ops.NInRange(3, 10) || ops.NInRange(13, 19) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"sl"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 100 = 1
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%100, 1) {
return One
}
// v = 0 and i % 100 = 2
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%100, 2) {
return Two
}
// v = 0 and i % 100 = 3..4 or v != 0
if intEqualsAny(ops.V, 0) && intInRange(ops.I%100, 3, 4) ||
!intEqualsAny(ops.V, 0) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"dsb", "hsb"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 100 = 1 or f % 100 = 1
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%100, 1) ||
intEqualsAny(ops.F%100, 1) {
return One
}
// v = 0 and i % 100 = 2 or f % 100 = 2
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%100, 2) ||
intEqualsAny(ops.F%100, 2) {
return Two
}
// v = 0 and i % 100 = 3..4 or f % 100 = 3..4
if intEqualsAny(ops.V, 0) && intInRange(ops.I%100, 3, 4) ||
intInRange(ops.F%100, 3, 4) {
return Few
}
return Other
},
})
addPluralRules(rules, []string{"he", "iw"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 1 and v = 0
if intEqualsAny(ops.I, 1) && intEqualsAny(ops.V, 0) {
return One
}
// i = 2 and v = 0
if intEqualsAny(ops.I, 2) && intEqualsAny(ops.V, 0) {
return Two
}
// v = 0 and n != 0..10 and n % 10 = 0
if intEqualsAny(ops.V, 0) && !ops.NInRange(0, 10) && ops.NModEqualsAny(10, 0) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"cs", "sk"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 1 and v = 0
if intEqualsAny(ops.I, 1) && intEqualsAny(ops.V, 0) {
return One
}
// i = 2..4 and v = 0
if intInRange(ops.I, 2, 4) && intEqualsAny(ops.V, 0) {
return Few
}
// v != 0
if !intEqualsAny(ops.V, 0) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"pl"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// i = 1 and v = 0
if intEqualsAny(ops.I, 1) && intEqualsAny(ops.V, 0) {
return One
}
// v = 0 and i % 10 = 2..4 and i % 100 != 12..14
if intEqualsAny(ops.V, 0) && intInRange(ops.I%10, 2, 4) && !intInRange(ops.I%100, 12, 14) {
return Few
}
// v = 0 and i != 1 and i % 10 = 0..1 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 12..14
if intEqualsAny(ops.V, 0) && !intEqualsAny(ops.I, 1) && intInRange(ops.I%10, 0, 1) ||
intEqualsAny(ops.V, 0) && intInRange(ops.I%10, 5, 9) ||
intEqualsAny(ops.V, 0) && intInRange(ops.I%100, 12, 14) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"be"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n % 10 = 1 and n % 100 != 11
if ops.NModEqualsAny(10, 1) && !ops.NModEqualsAny(100, 11) {
return One
}
// n % 10 = 2..4 and n % 100 != 12..14
if ops.NModInRange(10, 2, 4) && !ops.NModInRange(100, 12, 14) {
return Few
}
// n % 10 = 0 or n % 10 = 5..9 or n % 100 = 11..14
if ops.NModEqualsAny(10, 0) ||
ops.NModInRange(10, 5, 9) ||
ops.NModInRange(100, 11, 14) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"lt"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n % 10 = 1 and n % 100 != 11..19
if ops.NModEqualsAny(10, 1) && !ops.NModInRange(100, 11, 19) {
return One
}
// n % 10 = 2..9 and n % 100 != 11..19
if ops.NModInRange(10, 2, 9) && !ops.NModInRange(100, 11, 19) {
return Few
}
// f != 0
if !intEqualsAny(ops.F, 0) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"mt"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1
if ops.NEqualsAny(1) {
return One
}
// n = 0 or n % 100 = 2..10
if ops.NEqualsAny(0) ||
ops.NModInRange(100, 2, 10) {
return Few
}
// n % 100 = 11..19
if ops.NModInRange(100, 11, 19) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"ru", "uk"}, &Rule{
PluralForms: newPluralFormSet(One, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 10 = 1 and i % 100 != 11
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 1) && !intEqualsAny(ops.I%100, 11) {
return One
}
// v = 0 and i % 10 = 2..4 and i % 100 != 12..14
if intEqualsAny(ops.V, 0) && intInRange(ops.I%10, 2, 4) && !intInRange(ops.I%100, 12, 14) {
return Few
}
// v = 0 and i % 10 = 0 or v = 0 and i % 10 = 5..9 or v = 0 and i % 100 = 11..14
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 0) ||
intEqualsAny(ops.V, 0) && intInRange(ops.I%10, 5, 9) ||
intEqualsAny(ops.V, 0) && intInRange(ops.I%100, 11, 14) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"br"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n % 10 = 1 and n % 100 != 11,71,91
if ops.NModEqualsAny(10, 1) && !ops.NModEqualsAny(100, 11, 71, 91) {
return One
}
// n % 10 = 2 and n % 100 != 12,72,92
if ops.NModEqualsAny(10, 2) && !ops.NModEqualsAny(100, 12, 72, 92) {
return Two
}
// n % 10 = 3..4,9 and n % 100 != 10..19,70..79,90..99
if (ops.NModInRange(10, 3, 4) || ops.NModEqualsAny(10, 9)) && !(ops.NModInRange(100, 10, 19) || ops.NModInRange(100, 70, 79) || ops.NModInRange(100, 90, 99)) {
return Few
}
// n != 0 and n % 1000000 = 0
if !ops.NEqualsAny(0) && ops.NModEqualsAny(1000000, 0) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"ga"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 1
if ops.NEqualsAny(1) {
return One
}
// n = 2
if ops.NEqualsAny(2) {
return Two
}
// n = 3..6
if ops.NInRange(3, 6) {
return Few
}
// n = 7..10
if ops.NInRange(7, 10) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"gv"}, &Rule{
PluralForms: newPluralFormSet(One, Two, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// v = 0 and i % 10 = 1
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 1) {
return One
}
// v = 0 and i % 10 = 2
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%10, 2) {
return Two
}
// v = 0 and i % 100 = 0,20,40,60,80
if intEqualsAny(ops.V, 0) && intEqualsAny(ops.I%100, 0, 20, 40, 60, 80) {
return Few
}
// v != 0
if !intEqualsAny(ops.V, 0) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"ar", "ars"}, &Rule{
PluralForms: newPluralFormSet(Zero, One, Two, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0
if ops.NEqualsAny(0) {
return Zero
}
// n = 1
if ops.NEqualsAny(1) {
return One
}
// n = 2
if ops.NEqualsAny(2) {
return Two
}
// n % 100 = 3..10
if ops.NModInRange(100, 3, 10) {
return Few
}
// n % 100 = 11..99
if ops.NModInRange(100, 11, 99) {
return Many
}
return Other
},
})
addPluralRules(rules, []string{"cy"}, &Rule{
PluralForms: newPluralFormSet(Zero, One, Two, Few, Many, Other),
PluralFormFunc: func(ops *Operands) Form {
// n = 0
if ops.NEqualsAny(0) {
return Zero
}
// n = 1
if ops.NEqualsAny(1) {
return One
}
// n = 2
if ops.NEqualsAny(2) {
return Two
}
// n = 3
if ops.NEqualsAny(3) {
return Few
}
// n = 6
if ops.NEqualsAny(6) {
return Many
}
return Other
},
})
return rules
}

View File

@ -0,0 +1,24 @@
package plural
import "golang.org/x/text/language"
// Rules is a set of plural rules by language tag.
type Rules map[language.Tag]*Rule
// Rule returns the closest matching plural rule for the language tag
// or nil if no rule could be found.
func (r Rules) Rule(tag language.Tag) *Rule {
t := tag
for {
if rule := r[t]; rule != nil {
return rule
}
t = t.Parent()
if t.IsRoot() {
break
}
}
base, _ := tag.Base()
baseTag, _ := language.Parse(base.String())
return r[baseTag]
}

View File

@ -0,0 +1,26 @@
package internal
import (
"strings"
gotemplate "text/template"
)
// Template stores the template for a string.
type Template struct {
Src string
Template *gotemplate.Template
ParseErr *error
}
func (t *Template) parse(leftDelim, rightDelim string, funcs gotemplate.FuncMap) error {
if t.ParseErr == nil {
if strings.Contains(t.Src, leftDelim) {
gt, err := gotemplate.New("").Funcs(funcs).Delims(leftDelim, rightDelim).Parse(t.Src)
t.Template = gt
t.ParseErr = &err
} else {
t.ParseErr = new(error)
}
}
return *t.ParseErr
}