Skip to content

Commit

Permalink
new one
Browse files Browse the repository at this point in the history
  • Loading branch information
quenbyako committed Aug 31, 2020
1 parent 96b83ec commit 8bb3800
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 73 deletions.
60 changes: 60 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,63 @@ func (lc *Context) tr(key string) (string, error) {

return ctx.tr(key)
}

func (lc *Context) Message(key string) MessageCode {
t := Translator(lc)
return ImplicitCtxMessage(&t, key)
}
func (lc *Context) MessageWithParams(key string) MessageWithParamsCode {
t := Translator(lc)
return ImplicitCtxMessageWithParams(&t, key)
}

func (lc *Context) MustAll(items []string) error {
errorsMultiple := &errs.MultipleErrors{}
for _, item := range items {
_, err := lc.TrWithError(item)
errorsMultiple.Add(err)
}
return errorsMultiple.Normalize()
}

type MsgCodeReturner interface {
Code() string
}

type codeGetter uint8

type MessageCode func(privateParamss ...interface{}) string

func ImplicitCtxMessage(lc *Translator, key string) MessageCode {
return func(privateParams ...interface{}) string {
if len(privateParams) > 0 {
if _, ok := privateParams[0].(codeGetter); !ok {
panic("do not use additional parameters")
}
return key
}
return (*lc).Tr(key)
}
}

func (m MessageCode) Code() string {
return m(codeGetter(0))
}

type MessageWithParamsCode func(params map[string]interface{}, privateParams ...interface{}) string

func ImplicitCtxMessageWithParams(lc *Translator, key string) MessageWithParamsCode {
return func(params map[string]interface{}, privateParams ...interface{}) string {
if len(privateParams) > 0 {
if _, ok := privateParams[0].(codeGetter); !ok {
panic("do not use additional parameters")
}
return key
}
return (*lc).Strf(key, params)
}
}

func (m MessageWithParamsCode) Code() string {
return m(nil, codeGetter(0))
}
27 changes: 13 additions & 14 deletions doc/en_US/CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Contributing to go-l10n

based on [Xelaj styleguides](https://github.com/xelaj/xelaj/birch/blob/master/CONTRIBUTING.md).
based on [Xelaj styleguides](https://github.com/xelaj/birch/blob/master/CONTRIBUTING.md).

**english** [русский](https://github.com/xelaj/go-l10n/blob/master/doc/ru_RU/CONTRIBUTING.md)

:new_moon_with_face: :new_moon_with_face: First of all, thanks for your helping! :full_moon_with_face: :full_moon_with_face:
🌚🌚 First of all, thanks for your helping! 🌝🌝

This page briefly describes the process of developing both the specific go-l10n package and all Xelaj projects. if you read all these rules, you will be the best helper in the whole wild west!

Expand All @@ -24,7 +24,7 @@ And we also actually want to do [FAQ](https://github.com/xelaj/go-l10n/blob/mast

## What do I need to know before I can help?

`¯ \ _ (ツ) _ / ¯`
`¯\_(ツ)_/¯`

## And how can I help?

Expand Down Expand Up @@ -52,14 +52,13 @@ Here it is up to you, the only thing is: we are more willing to take pull reques
* write briefly (no more than 60 characters), everything else - in the description after two (2) new lines
* pour all your misery into the commit description, not the comment (❌ — `fool, forgot to delete ...` ✅ — `removed ...`)
* use prefixes, damn it! in general, we love emoji, so attach emoji:
* :art: `:art:` if you added a new method to the API.
* :memo: `:memo:` if you added documentation (**pay attention!** if you write documentation for the commit you made, you do not need to make a separate commit with the documentation!)
* :shirt: `:shirt:` if the build process was updated
* :pill: `:pill:` minor updates, fixes in one letter in the documentation, etc. not affecting the operation of the code
* :bug: `:bug:` bug fixes!
* :lock: `:lock:` if this is a security bug
* :twisted_rightwards_arrows: `:twisted_rightwards_arrows:` merge commits. any
* :racehorse: `:racehorse:` refactoring code
* :white_check_mark: `:white_check_mark:` work with tests
* :fire: `:fire:` if you delete (irrevocably!) any part of the service: code, file, configs, whatever.

* 🎨 `:art:` if you added a new method to the API.
* 📝 `:memo:` if you added documentation (**pay attention!** if you write documentation for the commit you made, you do not need to make a separate commit with the documentation!)
* 👕 `:shirt:` if the build process was updated
* 💊 `:pill:` minor updates, fixes in one letter in the documentation, etc. not affecting the operation of the code
* 🐛 `:bug:` bug fixes!
* 🔒 `:lock:` if this is a security bug
* 🔀 `:twisted_rightwards_arrows:` merge commits. any
* 🏇 `:racehorse:` refactoring code
*`:white_check_mark:` work with tests
* 🔥 `:fire:` if you delete (irrevocably!) any part of the service: code, file, configs, whatever.
2 changes: 1 addition & 1 deletion doc/ru_RU/CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@
## Немножко о другом
Писав данные правила, мы придерживались [Contributor Covenant](https://contributor-covenant.org). Это означает, что его бы тоже стоило почитать и вообще придерживаться данного завета.

Учитывайте так же, что некоторые правила в целом-то можно нарушить, мы же не звери. Но главное: **не говноедить** и **желать сообществу добра**. Добро это всегда хорошо.
Учитывайте так же, что некоторые правила в целом-то можно нарушить, мы же не звери. Но главное: **не говноедить** и **желать сообществу добра**. Добро это всегда хорошо.
22 changes: 11 additions & 11 deletions doc/ru_RU/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ based on [Xelaj styleguides](https://github.com/xelaj/xelaj/birch/blob/master/CO

[english](https://github.com/xelaj/go-l10n/blob/master/doc/en_US/CONTRIBUTING.md) **русский**

:new_moon_with_face: :new_moon_with_face: В первую очередь, спасибо, что уделяете время нашему проекту! :full_moon_with_face: :full_moon_with_face:
🌚🌚 В первую очередь, спасибо, что уделяете время нашему проекту! 🌝🌝

эта статья вкратце описывает процесс разработки как конкретно библиотеки go-l10n, так и всех проектов Xelaj. если вы прочтете все эти правила, вы будете лучшим помощником на всем диком западе!

Expand Down Expand Up @@ -52,13 +52,13 @@ based on [Xelaj styleguides](https://github.com/xelaj/xelaj/birch/blob/master/CO
* пишите кратко (не более 60 символов), все остальное — в описание через две (2) новые строки
* выливайте все свои страдания в описание коммита, а не комментарий (❌—`я дурак, забыл удалить ...` ✅—`удалено ...`)
* используйте префиксы, черт возьми! вообще мы любим эмоджи, поэтому прикрепляйте эмоджи:
* :art: `:art:` если вы добавили новый метод к API.
* :memo: `:memo:` если добавили документацию (**обратите внимание!** если вы пишете документацию для коммита, который вы сделали, не нужно делать отдельный коммит с документацией!)
* :shirt: `:shirt:` если обновили процесс сборки
* :pill: `:pill:` минорные обновления, фиксы в одну букву в документации и др. т.е. не влияющие на работу кода
* :bug: `:bug:` баг фиксы!
* :lock: `:lock:` если это багфикс, связаный с безопасностью
*:twisted_rightwards_arrows: `:twisted_rightwards_arrows:` мердж коммиты. любые.
* :racehorse: `:racehorse:` рефакторинг кода
* :white_check_mark: `:white_check_mark:` работа с тестами
* :fire: `:fire:` если вы удаляете (безвозвратно!) какую либо часть сервиса: код, файл, конфиги, что угодно.
* 🎨 `:art:` если вы добавили новый метод к API.
* 📝 `:memo:` если добавили документацию (**обратите внимание!** если вы пишете документацию для коммита, который вы сделали, не нужно делать отдельный коммит с документацией!)
* 👕 `:shirt:` если обновили процесс сборки
* 💊 `:pill:` минорные обновления, фиксы в одну букву в документации и др. т.е. не влияющие на работу кода
* 🐛 `:bug:` баг фиксы!
* 🔒 `:lock:` если это багфикс, связаный с безопасностью
* 🔀 `:twisted_rightwards_arrows:` мердж коммиты. любые.
* 🏇 `:racehorse:` рефакторинг кода
* `:white_check_mark:` работа с тестами
* 🔥 `:fire:` если вы удаляете (безвозвратно!) какую либо часть сервиса: код, файл, конфиги, что угодно.
4 changes: 4 additions & 0 deletions examples/locale/ru_RU/YourAppName/locale2.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
sometext: пососи
another:
desc: пенис
msg: дик
49 changes: 7 additions & 42 deletions l10n.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package l10n
import (
"path/filepath"

"github.com/xelaj/errs"

"github.com/gobuffalo/envy"
"github.com/iafan/Plurr/go/plurr"
"github.com/pkg/errors"
Expand Down Expand Up @@ -90,52 +88,19 @@ func LoadResource(lang string) error {
func MustAll(items []string) error {
Init()

errorsMultiple := &errs.MultipleErrors{}
for _, item := range items {
_, err := mainContext.TrWithError(item)
errorsMultiple.Add(err)
}
return errorsMultiple.Normalize()
}

type MsgCodeReturner interface {
Code() string
return mainContext.MustAll(items)
}

type codeGetter uint8

type MessageCode func(privateParamss ...interface{}) string

func Message(key string) MessageCode {
return func(privateParams ...interface{}) string {
if len(privateParams) > 0 {
if _, ok := privateParams[0].(codeGetter); !ok {
panic("do not use additional parameters")
}
return key
}
return Tr(key)
}
return ImplicitCtxMessage(&mainContext, key)
}

func (m MessageCode) Code() string {
return m(codeGetter(0))
}

type MessageWithParamsCode func(params map[string]interface{}, privateParams ...interface{}) string

func MessageWithParams(key string) MessageWithParamsCode {
return func(params map[string]interface{}, privateParams ...interface{}) string {
if len(privateParams) > 0 {
if _, ok := privateParams[0].(codeGetter); !ok {
panic("do not use additional parameters")
}
return key
}
return Strf(key, params)
}
return ImplicitCtxMessageWithParams(&mainContext, key)
}

func (m MessageWithParamsCode) Code() string {
return m(nil, codeGetter(0))
func DefaultTranslator() Translator {
Init()

return mainContext
}
11 changes: 6 additions & 5 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@ package l10n
import (
"path/filepath"

"github.com/xelaj/errs"

"github.com/ungerik/go-dry"

"github.com/iafan/Plurr/go/plurr"
"github.com/pkg/errors"
"github.com/ungerik/go-dry"
"github.com/xelaj/errs"
)

type Translator interface {
Expand All @@ -17,6 +15,9 @@ type Translator interface {
Trf(key string, params plurr.Params) (string, error)
Strf(key string, params plurr.Params) string
Lang() string
MustAll(items []string) error
Message(key string) MessageCode
MessageWithParams(key string) MessageWithParamsCode
}

// Resources is an array that holds string resources for a particular language
Expand Down Expand Up @@ -64,7 +65,7 @@ func (lp *Pool) GetContext(lang string) (*Context, error) {
}

return &Context{
pool: builtinPool,
pool: lp,
lang: lang,
plurr: plurr.New().SetLocale(lang),
}, nil
Expand Down

0 comments on commit 8bb3800

Please sign in to comment.