├── example ├── lang │ ├── generator.go │ ├── en-EN.json │ └── generated_lang.go └── main.go ├── go.mod ├── Makefile ├── go.sum ├── internal └── cli │ ├── types │ ├── message_value.go │ ├── util.go │ ├── message_value_string.go │ ├── message_value_conditional.go │ ├── message_value_multiline.go │ ├── message_value_parametrized.go │ ├── message_entry.go │ ├── message_instance.go │ ├── arguments.go │ └── message_bag.go │ ├── assert │ └── assertions.go │ ├── util │ ├── warnings_collector.go │ ├── errors.go │ └── stream.go │ ├── writing │ ├── naming.go │ └── main.go │ ├── main.go │ └── parse │ ├── walk.go │ └── main.go ├── .vscode └── launch.json ├── cmd └── i18n │ └── main.go ├── README.md ├── LICENSE └── docs └── messages.md /example/lang/generator.go: -------------------------------------------------------------------------------- 1 | package lang 2 | 3 | //go:generate go run ../../cmd/i18n -default-language en-EN -messages . 4 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/MrNemo64/go-n-i18n 2 | 3 | go 1.23.2 4 | 5 | require github.com/iancoleman/orderedmap v0.3.0 6 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | generate: 2 | go generate ./... 3 | 4 | run: 5 | go run ./example 6 | 7 | install: 8 | cd cmd/i18n && go install . -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/iancoleman/orderedmap v0.3.0 h1:5cbR2grmZR/DiVt+VJopEhtVs9YGInGIxAoMJn+Ichc= 2 | github.com/iancoleman/orderedmap v0.3.0/go.mod h1:XuLcCUkdL5owUCQeF2Ue9uuw1EptkJDkXXS7VoV7XGE= 3 | -------------------------------------------------------------------------------- /internal/cli/types/message_value.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type MessageValue interface { 4 | AsValueString() *ValueString 5 | AsValueParametrized() *ValueParametrized 6 | AsMultiline() *ValueMultiline 7 | AsConditional() *ValueConditional 8 | } 9 | -------------------------------------------------------------------------------- /internal/cli/types/util.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "strings" 4 | 5 | func copyAndAdd[T any](ori []T, new ...T) []T { 6 | ret := make([]T, len(ori)) 7 | copy(ret, ori) 8 | return append(ret, new...) 9 | } 10 | 11 | func ResolveFullPath(parent *MessageBag, child string) []string { 12 | if parent == nil { 13 | if child == "" { 14 | return []string{} 15 | } 16 | return []string{child} 17 | } 18 | return copyAndAdd(parent.Path(), child) 19 | } 20 | 21 | func PathAsStr(path []string) string { 22 | return strings.Join(path, ".") 23 | } 24 | -------------------------------------------------------------------------------- /internal/cli/assert/assertions.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import "fmt" 4 | 5 | func NonNil(v any, msg string) { 6 | if v == nil { 7 | panic(fmt.Errorf("expected non nil but was nil: %s", msg)) 8 | } 9 | } 10 | 11 | func NoError(err error) { 12 | if err != nil { 13 | panic(fmt.Errorf("reached unreachable error: %w", err)) 14 | } 15 | } 16 | 17 | func Has[T comparable](arr []T, el T) { 18 | for _, e := range arr { 19 | if e == el { 20 | return 21 | } 22 | } 23 | panic(fmt.Errorf("expected slice %+v to have the element %+v", arr, el)) 24 | } 25 | -------------------------------------------------------------------------------- /internal/cli/util/warnings_collector.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | type WarningsCollector struct { 4 | warnings []error 5 | } 6 | 7 | func NewWarningsCollector() *WarningsCollector { 8 | return &WarningsCollector{warnings: make([]error, 0)} 9 | } 10 | 11 | func (wc *WarningsCollector) AddWarning(err error) { 12 | wc.warnings = append(wc.warnings, err) 13 | } 14 | 15 | func (wc *WarningsCollector) Warnings() []error { 16 | return wc.warnings 17 | } 18 | 19 | func (wc *WarningsCollector) IsEmpty() bool { 20 | return len(wc.warnings) == 0 21 | } 22 | 23 | func (wc *WarningsCollector) Clear() { 24 | wc.warnings = make([]error, 0) 25 | } 26 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch Package", 9 | "type": "go", 10 | "request": "launch", 11 | "mode": "auto", 12 | "program": "./cmd/i18n/main.go", 13 | "args": [ 14 | "-default-language", 15 | "en-EN", 16 | "-messages", 17 | "${cwd}/example/lang", 18 | "-out-file", 19 | "${cwd}/example/lang/generated_lang.go", 20 | "-out-package", 21 | "lang" 22 | ] 23 | } 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/MrNemo64/go-n-i18n/example/lang" 7 | ) 8 | 9 | func main() { 10 | bundle := lang.MessagesForMust("en-EN") 11 | 12 | fmt.Println(bundle.WhereAmI()) // Assume this json is in the file "en-EN.json" 13 | fmt.Println(bundle.NestedMessages().Parametrized(4)) // This message has an amout parameter of type int: 4 14 | fmt.Println(bundle.ConditionalMessages(100)) 15 | /* 16 | This is the "else" branch 17 | This multiline message is used 18 | And shows the amount: 100 19 | */ 20 | fmt.Println(bundle.MultilineMessage("MrNemo64", 13.1267)) 21 | /* 22 | Hello MrNemo64! 23 | Messages can be multiline 24 | And each one can have parameters 25 | This one has a float formated with 2 decimals! 13.13 26 | */ 27 | } 28 | -------------------------------------------------------------------------------- /example/lang/en-EN.json: -------------------------------------------------------------------------------- 1 | { 2 | "where-am-i": "Assume this json is in the file \"en-EN.json\"", 3 | "nested-messages": { 4 | "simple": "This is just a simple message nested into \"nested-messages\"", 5 | "parametrized": "This message has an amount parameter of type int: {amount:int}" 6 | }, 7 | "multi-line-message": [ 8 | "Hello {user:str}!", 9 | "Messages can be multi-line", 10 | "And each one can have parameters", 11 | "This one has a float formatted with 2 decimals! {amount:float64:.2f}" 12 | ], 13 | "?conditional-messages": { 14 | "amount == 0": "If amount is 0, this message is used", 15 | "amount == 1": "This message is returned if the amount is 1", 16 | "": [ 17 | "This is the \"else\" branch", 18 | "This multi-line message is used", 19 | "And shows the amount: {amount:int}" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /internal/cli/types/message_value_string.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "strings" 4 | 5 | type ValueString struct { 6 | message string 7 | } 8 | 9 | func NewStringLiteralValue(message string) *ValueString { 10 | return &ValueString{message: message} 11 | } 12 | 13 | func (*ValueString) multilineMarker() {} 14 | func (*ValueString) conditionableMarker() {} 15 | func (s *ValueString) AsValueString() *ValueString { return s } 16 | func (*ValueString) AsValueParametrized() *ValueParametrized { 17 | panic("called AsValueParametrized on a ValueString") 18 | } 19 | func (*ValueString) AsMultiline() *ValueMultiline { 20 | panic("called AsMultiline on a ValueString") 21 | } 22 | func (*ValueString) AsConditional() *ValueConditional { 23 | panic("called AsConditional on a ValueString") 24 | } 25 | func (s *ValueString) Escaped(quote string) string { 26 | return strings.ReplaceAll(s.message, quote, "\\\"") 27 | } 28 | -------------------------------------------------------------------------------- /internal/cli/util/errors.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Error struct { 8 | msg string 9 | args []any 10 | } 11 | 12 | func MakeError(msg string) Error { 13 | return Error{msg: msg} 14 | } 15 | 16 | func (err Error) WithArgs(arg ...any) Error { 17 | copy := err 18 | copy.args = arg 19 | return copy 20 | } 21 | 22 | func (err Error) Error() string { 23 | return fmt.Errorf(err.msg, err.args...).Error() 24 | } 25 | 26 | func (err Error) Is(other error) bool { 27 | casted, ok := other.(Error) 28 | if !ok { 29 | return false 30 | } 31 | if casted.msg == err.msg { 32 | return true 33 | } 34 | return false 35 | } 36 | 37 | func (err Error) Unwrap() []error { 38 | if err.args == nil { 39 | return []error{} 40 | } 41 | var errors []error 42 | for _, arg := range err.args { 43 | if e, ok := arg.(error); ok { 44 | errors = append(errors, e) 45 | } 46 | } 47 | return errors 48 | } 49 | -------------------------------------------------------------------------------- /internal/cli/types/message_value_conditional.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | type Conditionable interface { 4 | conditionableMarker() 5 | } 6 | 7 | type Condition struct { 8 | Condition string 9 | Value Conditionable 10 | } 11 | 12 | type ValueConditional struct { 13 | Conditions []Condition 14 | Else Conditionable 15 | } 16 | 17 | func NewConditionalValue(conditions []Condition, elseCondition Conditionable) (*ValueConditional, error) { 18 | return &ValueConditional{ 19 | Conditions: conditions, 20 | Else: elseCondition, 21 | }, nil 22 | } 23 | 24 | func (c *ValueConditional) AsConditional() *ValueConditional { return c } 25 | func (*ValueConditional) AsValueString() *ValueString { 26 | panic("called AsValueString on a ValueConditional") 27 | } 28 | func (*ValueConditional) AsValueParametrized() *ValueParametrized { 29 | panic("called AsValueParametrized on a ValueConditional") 30 | } 31 | func (*ValueConditional) AsMultiline() *ValueMultiline { 32 | panic("called AsMultiline on a ValueConditional") 33 | } 34 | -------------------------------------------------------------------------------- /internal/cli/types/message_value_multiline.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/MrNemo64/go-n-i18n/internal/cli/util" 4 | 5 | var ( 6 | ErrInsuficientLines util.Error = util.MakeError("there must be at least one line") 7 | ) 8 | 9 | type Multilineable interface { 10 | multilineMarker() 11 | } 12 | 13 | type ValueMultiline struct { 14 | Lines []Multilineable 15 | } 16 | 17 | func NewMultilineValue(lines []Multilineable) (*ValueMultiline, error) { 18 | if len(lines) == 0 { 19 | return nil, ErrInsuficientLines 20 | } 21 | return &ValueMultiline{Lines: lines}, nil 22 | } 23 | 24 | func (*ValueMultiline) conditionableMarker() {} 25 | func (s *ValueMultiline) AsMultiline() *ValueMultiline { return s } 26 | func (*ValueMultiline) AsValueString() *ValueString { 27 | panic("called AsValueString on a ValueMultiline") 28 | } 29 | func (*ValueMultiline) AsValueParametrized() *ValueParametrized { 30 | panic("called AsValueParametrized on a ValueMultiline") 31 | } 32 | func (*ValueMultiline) AsConditional() *ValueConditional { 33 | panic("called AsConditional on a ValueMultiline") 34 | } 35 | -------------------------------------------------------------------------------- /cmd/i18n/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log/slog" 7 | "os" 8 | 9 | "github.com/MrNemo64/go-n-i18n/internal/cli" 10 | ) 11 | 12 | func main() { 13 | defaultLanguage := flag.String("default-language", "", "Specifies the default language") 14 | messagesDir := flag.String("messages", "", "Specifies the directory with the files with the messages") 15 | outFile := flag.String("out-file", "generated_lang.go", "Specifies the output file with the messages") 16 | outPackage := flag.String("out-package", os.Getenv("GOPACKAGE"), "Specifies the output package name") 17 | topInterfaceName := flag.String("top-interface-name", "messages", "Specifies the name for the top level interface") 18 | publicNonNamedInterfaces := flag.Bool("public-non-named-interfaces", false, "Specifies that all generated interfaces should be public, even non named ones") 19 | flag.Parse() 20 | 21 | if *defaultLanguage == "" || *messagesDir == "" || *outFile == "" || *outPackage == "" || *topInterfaceName == "" { 22 | flag.Usage() 23 | fmt.Println("Version v0.0.3") 24 | os.Exit(1) 25 | } 26 | 27 | cli.Run(cli.CliArgs{ 28 | MessagesDirectory: *messagesDir, 29 | DefaultLanguage: *defaultLanguage, 30 | OutFile: *outFile, 31 | Package: *outPackage, 32 | TopLevelInterfaceName: *topInterfaceName, 33 | PublicNonNamedInterfaces: *publicNonNamedInterfaces, 34 | LogLevel: slog.LevelDebug, 35 | }) 36 | } 37 | -------------------------------------------------------------------------------- /internal/cli/types/message_value_parametrized.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 5 | ) 6 | 7 | var ( 8 | ErrInvalidAmountOfTextSegmentsAndArguments util.Error = util.MakeError("the amount of text segments (%d) is not the amount of arguments (%d) + 1") 9 | ) 10 | 11 | type ValueParametrized struct { 12 | TextSegments []*ValueString 13 | Args []*UsedArgument 14 | } 15 | 16 | type UsedArgument struct { 17 | Argument *MessageArgument 18 | Format string 19 | } 20 | 21 | func NewParametrizedStringValue(textSegments []*ValueString, args []*UsedArgument) (*ValueParametrized, error) { 22 | if len(textSegments) != len(args)+1 { 23 | return nil, ErrInvalidAmountOfTextSegmentsAndArguments.WithArgs(len(textSegments), len(args)) 24 | } 25 | return &ValueParametrized{ 26 | TextSegments: textSegments, 27 | Args: args, 28 | }, nil 29 | } 30 | 31 | func (*ValueParametrized) multilineMarker() {} 32 | func (*ValueParametrized) conditionableMarker() {} 33 | func (s *ValueParametrized) AsValueParametrized() *ValueParametrized { return s } 34 | func (*ValueParametrized) AsValueString() *ValueString { 35 | panic("called AsValueString on a ParametrizedString") 36 | } 37 | func (*ValueParametrized) AsMultiline() *ValueMultiline { 38 | panic("called AsMultiline on a ValueParametrized") 39 | } 40 | func (*ValueParametrized) AsConditional() *ValueConditional { 41 | panic("called AsConditional on a ValueParametrized") 42 | } 43 | -------------------------------------------------------------------------------- /internal/cli/util/stream.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | func copySlice[T any](arr []T, newElement ...T) []T { 4 | copied := make([]T, len(arr)) 5 | copy(copied, arr) 6 | return append(copied, newElement...) 7 | } 8 | 9 | func Map[T any, R any](v []T, mapper func(int, *T) R) []R { 10 | r := make([]R, len(v)) 11 | for i := 0; i < len(v); i++ { 12 | r[i] = mapper(i, &v[i]) 13 | } 14 | return r 15 | } 16 | 17 | func Has[T comparable](v []T, val T) bool { 18 | for i := range v { 19 | if val == v[i] { 20 | return true 21 | } 22 | } 23 | return false 24 | } 25 | 26 | func MergeIntoA[K comparable, V any](a map[K]V, b map[K]V, merger func(*V, *V) V) bool { 27 | redefined := false 28 | for key, bVal := range b { 29 | if aVal, found := a[key]; found { 30 | a[key] = merger(&aVal, &bVal) 31 | redefined = true 32 | } else { 33 | a[key] = bVal 34 | } 35 | } 36 | return redefined 37 | } 38 | 39 | type Set[T comparable] struct { 40 | values []T 41 | } 42 | 43 | func NewSet[T comparable]() *Set[T] { 44 | return &Set[T]{values: make([]T, 0)} 45 | } 46 | 47 | func (s *Set[T]) Add(value T) { 48 | if !s.Contains(value) { 49 | s.values = append(s.values, value) 50 | } 51 | } 52 | 53 | func (s *Set[T]) Contains(value T) bool { 54 | for _, v := range s.values { 55 | if v == value { 56 | return true 57 | } 58 | } 59 | return false 60 | } 61 | 62 | func (s *Set[T]) Get() []T { 63 | return copySlice(s.values) 64 | } 65 | 66 | func (s *Set[T]) Size() int { 67 | return len(s.values) 68 | } 69 | 70 | func (s *Set[T]) AddAll(other *Set[T]) { 71 | for _, v := range other.values { 72 | s.Add(v) 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /internal/cli/types/message_entry.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "regexp" 5 | 6 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 7 | ) 8 | 9 | type MessageEntryType int 10 | 11 | const ( 12 | MessageEntryInstance MessageEntryType = iota 13 | MessageEntryBag 14 | ) 15 | 16 | var ( 17 | ErrInvalidKey util.Error = util.MakeError("the key '%s' does not follow the allowed format (^[a-zA-Z][a-zA-Z0-9_-]*$)") 18 | ErrCreateEntry = util.MakeError("could not make entry with key '%s': %w") 19 | ) 20 | 21 | var ValidKey = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_-]*$") 22 | 23 | func IsValidKey(key string) bool { return ValidKey.MatchString(key) } 24 | func CheckKey(key string) error { 25 | if !IsValidKey(key) { 26 | return ErrInvalidKey.WithArgs(key) 27 | } 28 | return nil 29 | } 30 | 31 | type MessageEntry interface { 32 | Key() string 33 | Parent() *MessageBag 34 | AssignParent(*MessageBag) 35 | Path() []string 36 | PathAsStr() string 37 | Type() MessageEntryType 38 | Languages() *util.Set[string] 39 | MustHaveAllLangs(langs []string, defLang string) map[string][]string 40 | 41 | IsBag() bool 42 | IsInstance() bool 43 | AsBag() *MessageBag 44 | AsInstance() *MessageInstance 45 | } 46 | 47 | type messageEntry struct { 48 | key string 49 | parent *MessageBag 50 | } 51 | 52 | func (e *messageEntry) Key() string { 53 | return e.key 54 | } 55 | 56 | func (e *messageEntry) Parent() *MessageBag { 57 | return e.parent 58 | } 59 | 60 | func (e *messageEntry) AssignParent(parent *MessageBag) { 61 | e.parent = parent 62 | } 63 | 64 | func (e *messageEntry) Path() []string { 65 | return ResolveFullPath(e.Parent(), e.Key()) 66 | } 67 | 68 | func (e *messageEntry) PathAsStr() string { 69 | return PathAsStr(e.Path()) 70 | } 71 | -------------------------------------------------------------------------------- /internal/cli/writing/naming.go: -------------------------------------------------------------------------------- 1 | package writing 2 | 3 | import ( 4 | "strings" 5 | 6 | "github.com/MrNemo64/go-n-i18n/internal/cli/types" 7 | ) 8 | 9 | type MessageEntryNamer interface { 10 | FunctionName(me types.MessageEntry) string 11 | InterfaceName(me *types.MessageBag) string 12 | FunctionNameForLang(lang string, me types.MessageEntry) string 13 | InterfaceNameForLang(lang string, me *types.MessageBag) string 14 | TopLevelName() string 15 | } 16 | 17 | type goNamer struct { 18 | publicNonNamedInterfaces bool 19 | topLevelName string 20 | } 21 | 22 | func GoNamer(topLevelName string, publicNonNamedInterfaces bool) *goNamer { 23 | return &goNamer{ 24 | topLevelName: topLevelName, 25 | publicNonNamedInterfaces: publicNonNamedInterfaces, 26 | } 27 | } 28 | 29 | func (*goNamer) toGo(key string, public bool) string { 30 | newName := key[:1] 31 | if public { 32 | newName = strings.ToUpper(key[:1]) 33 | } 34 | 35 | for j := 1; j < len(key); j++ { 36 | if key[j] == '-' || key[j] == '_' { 37 | if j == len(key)-1 { 38 | break // last char is a _ or a - so just ignore it 39 | } 40 | j++ 41 | newName += strings.ToUpper(key[j : j+1]) 42 | } else { 43 | newName += key[j : j+1] 44 | } 45 | } 46 | return newName 47 | } 48 | 49 | func (m *goNamer) FunctionName(me types.MessageEntry) string { 50 | if me.Key() == "" { 51 | panic("tryed to get the function name of the root bag") 52 | } 53 | return m.toGo(me.Key(), true) 54 | } 55 | 56 | func (m goNamer) FunctionNameForLang(lang string, me types.MessageEntry) string { 57 | return strings.ReplaceAll(lang, "-", "_") + "_" + m.FunctionName(me) 58 | } 59 | 60 | func (m *goNamer) InterfaceName(me *types.MessageBag) string { 61 | if me.Key() == "" { 62 | return m.TopLevelName() 63 | } 64 | if me.Name != "" { 65 | return m.toGo(me.Name, true) 66 | } 67 | name := "" 68 | for _, part := range me.Path() { 69 | name += m.toGo(part, m.publicNonNamedInterfaces) 70 | } 71 | return name 72 | } 73 | 74 | func (m *goNamer) InterfaceNameForLang(lang string, me *types.MessageBag) string { 75 | return strings.ReplaceAll(lang, "-", "_") + "_" + m.InterfaceName(me) 76 | } 77 | 78 | func (m *goNamer) TopLevelName() string { 79 | return m.toGo(m.topLevelName, true) 80 | } 81 | -------------------------------------------------------------------------------- /example/lang/generated_lang.go: -------------------------------------------------------------------------------- 1 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 2 | * Any changes to this file will be lost on the next tool run */ 3 | 4 | package lang 5 | 6 | import ( 7 | "fmt" 8 | "strings" 9 | ) 10 | 11 | func MessagesFor(tag string) (Messages, bool) { 12 | switch strings.ReplaceAll(tag, "_", "-") { 13 | case "en-EN": 14 | return en_EN_Messages{}, true 15 | } 16 | return nil, false 17 | } 18 | 19 | func MessagesForMust(tag string) Messages { 20 | switch strings.ReplaceAll(tag, "_", "-") { 21 | case "en-EN": 22 | return en_EN_Messages{} 23 | } 24 | panic(fmt.Errorf("unknwon language tag: " + tag)) 25 | } 26 | 27 | func MessagesForOrDefault(tag string) Messages { 28 | switch strings.ReplaceAll(tag, "_", "-") { 29 | case "en-EN": 30 | return en_EN_Messages{} 31 | } 32 | return en_EN_Messages{} 33 | } 34 | 35 | type Messages interface{ 36 | WhereAmI() string 37 | NestedMessages() nestedMessages 38 | MultiLineMessage(user string, amount float64) string 39 | ConditionalMessages(amount int) string 40 | } 41 | type nestedMessages interface{ 42 | Simple() string 43 | Parametrized(amount int) string 44 | } 45 | 46 | type en_EN_Messages struct{} 47 | func (en_EN_Messages) WhereAmI() string { 48 | return "Assume this json is in the file \"en-EN.json\"" 49 | } 50 | func (en_EN_Messages) NestedMessages() nestedMessages { 51 | return en_EN_nestedMessages{} 52 | } 53 | type en_EN_nestedMessages struct{} 54 | func (en_EN_nestedMessages) Simple() string { 55 | return "This is just a simple message nested into \"nested-messages\"" 56 | } 57 | func (en_EN_nestedMessages) Parametrized(amount int) string { 58 | return fmt.Sprintf("This message has an amount parameter of type int: %d", amount) 59 | } 60 | func (en_EN_Messages) MultiLineMessage(user string, amount float64) string { 61 | return fmt.Sprintf("Hello %s!", user) + "\n" + 62 | "Messages can be multi-line" + "\n" + 63 | "And each one can have parameters" + "\n" + 64 | fmt.Sprintf("This one has a float formatted with 2 decimals! %.2f", amount) 65 | } 66 | func (en_EN_Messages) ConditionalMessages(amount int) string { 67 | if amount == 0 { 68 | return "If amount is 0, this message is used" 69 | } else if amount == 1 { 70 | return "This message is returned if the amount is 1" 71 | } else { 72 | return "This is the \"else\" branch" + "\n" + 73 | "This multi-line message is used" + "\n" + 74 | fmt.Sprintf("And shows the amount: %d", amount) 75 | } 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /internal/cli/main.go: -------------------------------------------------------------------------------- 1 | package cli 2 | 3 | import ( 4 | "log/slog" 5 | "os" 6 | 7 | "github.com/MrNemo64/go-n-i18n/internal/cli/parse" 8 | "github.com/MrNemo64/go-n-i18n/internal/cli/types" 9 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 10 | "github.com/MrNemo64/go-n-i18n/internal/cli/writing" 11 | ) 12 | 13 | type CliArgs struct { 14 | MessagesDirectory string 15 | DefaultLanguage string 16 | OutFile string 17 | Package string 18 | TopLevelInterfaceName string 19 | PublicNonNamedInterfaces bool 20 | LogLevel slog.Level 21 | } 22 | 23 | func Run(args CliArgs) { 24 | log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ 25 | AddSource: false, 26 | Level: args.LogLevel, 27 | })) 28 | wc := util.NewWarningsCollector() 29 | 30 | log.Info("Collecting files") 31 | walker, err := parse.IoDirWalker(args.MessagesDirectory, args.DefaultLanguage) 32 | if err != nil { 33 | log.Error("Could not collect all files in the messages directory", "err", err) 34 | os.Exit(1) 35 | } 36 | 37 | argProvider := types.NewArgumentProvider() 38 | 39 | log.Info("Parsing files") 40 | messages, err := parse.ParseJson(walker, wc, argProvider) 41 | if err != nil { 42 | log.Error("Could not parse all files in the messages directory", "err", err) 43 | os.Exit(1) 44 | } 45 | 46 | if !wc.IsEmpty() { 47 | for _, warning := range wc.Warnings() { 48 | log.Warn(warning.Error()) 49 | } 50 | os.Exit(1) 51 | } 52 | 53 | allLangs := messages.Languages() 54 | if !allLangs.Contains(args.DefaultLanguage) { 55 | log.Error("Could not find messages of the default language") 56 | os.Exit(1) 57 | } 58 | 59 | removed := messages.RemoveEntriesWithoutLang(args.DefaultLanguage) 60 | if len(removed) > 0 { 61 | log.Warn("Removed entries without the default language", "default-language", args.DefaultLanguage, 62 | "removed-entries", util.Map(removed, func(_ int, t *types.MessageEntry) string { return (*t).PathAsStr() })) 63 | } 64 | 65 | filled := messages.MustHaveAllLangs(allLangs.Get(), args.DefaultLanguage) 66 | if len(filled) > 0 { 67 | log.Warn("Some entries were missing in some languages. Using the message of the default language", "missing-entries", filled) 68 | } 69 | 70 | log.Info("Generating code") 71 | code := writing.GenerateGoCode(messages, writing.GoNamer(args.TopLevelInterfaceName, args.PublicNonNamedInterfaces), allLangs.Get(), args.DefaultLanguage, args.Package) 72 | 73 | file, err := os.Create(args.OutFile) 74 | if err != nil { 75 | log.Error("Could not open output file", "err", err) 76 | os.Exit(1) 77 | } 78 | defer file.Close() 79 | if _, err = file.WriteString(code); err != nil { 80 | log.Error("Could not write to output file", "err", err) 81 | os.Exit(1) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /internal/cli/parse/walk.go: -------------------------------------------------------------------------------- 1 | package parse 2 | 3 | import ( 4 | "errors" 5 | "os" 6 | "path/filepath" 7 | "slices" 8 | "strings" 9 | ) 10 | 11 | var ErrNoMoreFiles = errors.New("no more files in the walker") 12 | 13 | type DirWalker interface { 14 | Next() (FileEntry, error) 15 | } 16 | 17 | type FileEntry interface { 18 | Path() []string 19 | Language() string 20 | FullPath() string 21 | ReadContents() ([]byte, error) 22 | } 23 | 24 | type IOFileEntry struct { 25 | path []string 26 | language string 27 | fullPath string 28 | } 29 | 30 | func (fe *IOFileEntry) Path() []string { return fe.path } 31 | func (fe *IOFileEntry) Language() string { return fe.language } 32 | func (fe *IOFileEntry) FullPath() string { return fe.fullPath } 33 | func (fe *IOFileEntry) ReadContents() ([]byte, error) { return os.ReadFile(fe.fullPath) } 34 | 35 | type ioDirWalker struct { 36 | Origin string 37 | files []IOFileEntry 38 | current int 39 | } 40 | 41 | func IoDirWalker(dir string, defLang string) (*ioDirWalker, error) { 42 | walker := &ioDirWalker{Origin: dir, current: -1} 43 | err := walker.loadFiles() 44 | if err != nil { 45 | return nil, err 46 | } 47 | slices.SortFunc(walker.files, func(i, j IOFileEntry) int { 48 | if i.language == defLang { 49 | if j.language == defLang { 50 | return 0 51 | } 52 | return -1 53 | } else { 54 | if j.language == defLang { 55 | return 0 56 | } 57 | return 1 58 | } 59 | }) 60 | return walker, nil 61 | } 62 | 63 | func (walker *ioDirWalker) loadFiles() error { 64 | err := filepath.WalkDir(walker.Origin, func(path string, d os.DirEntry, err error) error { 65 | if err != nil { 66 | return err 67 | } 68 | if !d.IsDir() && strings.HasSuffix(d.Name(), ".json") { 69 | relPath, err := filepath.Rel(walker.Origin, path) 70 | if err != nil { 71 | return err 72 | } 73 | 74 | // Get the path components and remove the extension from the name 75 | dirPath := filepath.Dir(relPath) 76 | if dirPath == "." { 77 | dirPath = "" 78 | } 79 | // Use empty slice if path is "." 80 | splitedRelativePath := strings.Split(dirPath, string(filepath.Separator)) 81 | var relativePath []string 82 | for _, part := range splitedRelativePath { 83 | if part != "" { 84 | relativePath = append(relativePath, part) 85 | } 86 | } 87 | 88 | // Save only the file name without the extension 89 | fileNameWithoutExt := strings.TrimSuffix(d.Name(), filepath.Ext(d.Name())) 90 | 91 | walker.files = append(walker.files, IOFileEntry{ 92 | path: relativePath, 93 | language: fileNameWithoutExt, 94 | fullPath: path, 95 | }) 96 | } 97 | return nil 98 | }) 99 | return err 100 | } 101 | 102 | func (walker *ioDirWalker) Next() (FileEntry, error) { 103 | walker.current++ 104 | if walker.current >= len(walker.files) || walker.files == nil { 105 | return nil, ErrNoMoreFiles 106 | } 107 | return &walker.files[walker.current], nil 108 | } 109 | -------------------------------------------------------------------------------- /internal/cli/types/message_instance.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | 7 | "github.com/MrNemo64/go-n-i18n/internal/cli/assert" 8 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 9 | ) 10 | 11 | var ( 12 | ErrMessageRedefinition util.Error = util.MakeError("the message %s already is defined for %s but it got redefined") 13 | ErrMergeMessageInstance = util.MakeError("could not merge message instances: %w") 14 | ) 15 | 16 | type MessageInstance struct { 17 | messageEntry 18 | message map[string]MessageValue 19 | args *ArgumentList 20 | } 21 | 22 | func NewMessageInstance(key string) (*MessageInstance, error) { 23 | if !IsValidKey(key) { 24 | return nil, ErrInvalidKey.WithArgs(key) 25 | } 26 | return &MessageInstance{ 27 | messageEntry: messageEntry{ 28 | key: key, 29 | }, 30 | message: make(map[string]MessageValue), 31 | args: NewArgumentList(), 32 | }, nil 33 | } 34 | 35 | func (*MessageInstance) AsBag() *MessageBag { panic("called AsBag on an instance") } 36 | func (m *MessageInstance) AsInstance() *MessageInstance { return m } 37 | func (m *MessageInstance) Args() *ArgumentList { return m.args } 38 | func (*MessageInstance) Type() MessageEntryType { return MessageEntryInstance } 39 | func (*MessageInstance) IsBag() bool { return false } 40 | func (*MessageInstance) IsInstance() bool { return true } 41 | func (m *MessageInstance) Message(lang string) (MessageValue, bool) { 42 | v, f := m.message[lang] 43 | return v, f 44 | } 45 | func (m *MessageInstance) MessageMust(lang string) MessageValue { 46 | v, f := m.message[lang] 47 | if !f { 48 | panic(fmt.Errorf("had to had message for lang %s in entry %s but it is not present in %+v", lang, m.PathAsStr(), m.message)) 49 | } 50 | return v 51 | } 52 | 53 | func (m *MessageInstance) AddArgs(args *ArgumentList) error { 54 | return m.args.Merge(args) 55 | } 56 | 57 | func (m *MessageInstance) AddLanguage(lang string, message MessageValue) error { 58 | assert.NonNil(message, "message") 59 | if _, found := m.message[lang]; found { 60 | return ErrMessageRedefinition.WithArgs(m.PathAsStr(), lang) 61 | } 62 | m.message[lang] = message 63 | return nil 64 | } 65 | 66 | func (m *MessageInstance) Merge(other *MessageInstance) error { 67 | var errs []error 68 | if err := m.args.Merge(other.args); err != nil { 69 | errs = append(errs, err) 70 | } 71 | for lang, value := range other.message { 72 | if err := m.AddLanguage(lang, value); err != nil { 73 | errs = append(errs, err) 74 | } 75 | } 76 | if len(errs) == 0 { 77 | return nil 78 | } 79 | return ErrMergeMessageInstance.WithArgs(errors.Join(errs...)) 80 | } 81 | 82 | func (m *MessageInstance) Languages() *util.Set[string] { 83 | langs := util.NewSet[string]() 84 | for key := range m.message { 85 | langs.Add(key) 86 | } 87 | return langs 88 | } 89 | 90 | func (m *MessageInstance) MustHaveAllLangs(langs []string, defLang string) map[string][]string { 91 | defMsg, found := m.message[defLang] 92 | if !found { 93 | panic(fmt.Errorf("called MustHaveAllLangs with default lang %s but it is not present in the languages %+v", defLang, m.Languages().Get())) 94 | } 95 | missing := make(map[string][]string) 96 | path := m.PathAsStr() 97 | for _, lang := range langs { 98 | if _, hasIt := m.message[lang]; !hasIt { 99 | m.message[lang] = defMsg 100 | missing[lang] = []string{path} 101 | } 102 | } 103 | return missing 104 | } 105 | -------------------------------------------------------------------------------- /internal/cli/types/arguments.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/MrNemo64/go-n-i18n/internal/cli/assert" 7 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 8 | ) 9 | 10 | var ( 11 | ErrArgumentCollition util.Error = util.MakeError("argument %s has a type colition: %s != %s") 12 | ErrMergeArgumentList = util.MakeError("could not merge argument lists: %w") 13 | ) 14 | 15 | type ArgumentType struct { 16 | Name string 17 | Aliases []string 18 | Type string 19 | DefaultFormat string 20 | IsUnknown bool 21 | } 22 | 23 | func (t *ArgumentType) Is(name string) bool { 24 | if name == t.Name { 25 | return true 26 | } 27 | for _, alias := range t.Aliases { 28 | if alias == name { 29 | return true 30 | } 31 | } 32 | return false 33 | } 34 | 35 | type ArgumentProvider struct { 36 | types []*ArgumentType 37 | } 38 | 39 | func NewArgumentProvider() *ArgumentProvider { 40 | p := &ArgumentProvider{} 41 | p.Register(&ArgumentType{ 42 | Name: "any", 43 | Aliases: []string{"any", "unknown"}, 44 | Type: "any", 45 | DefaultFormat: "v", 46 | IsUnknown: true, 47 | }) 48 | p.Register(&ArgumentType{ 49 | Name: "string", 50 | Aliases: []string{"string", "str"}, 51 | Type: "string", 52 | DefaultFormat: "s", 53 | }) 54 | p.Register(&ArgumentType{ 55 | Name: "boolean", 56 | Aliases: []string{"boolean", "bool"}, 57 | Type: "bool", 58 | DefaultFormat: "t", 59 | }) 60 | p.Register(&ArgumentType{ 61 | Name: "integer", 62 | Aliases: []string{"integer", "int"}, 63 | Type: "int", 64 | DefaultFormat: "d", 65 | }) 66 | p.Register(&ArgumentType{ 67 | Name: "float64", 68 | Aliases: []string{"float64", "f64", "f", "double"}, 69 | Type: "float64", 70 | DefaultFormat: "g", 71 | }) 72 | return p 73 | } 74 | 75 | func (p *ArgumentProvider) UnknwonType() *ArgumentType { 76 | return p.types[0] 77 | } 78 | 79 | func (p *ArgumentProvider) Register(arg *ArgumentType) bool { 80 | if _, found := p.FindArgument(arg.Name); found { 81 | return false 82 | } 83 | for _, alias := range arg.Aliases { 84 | if _, found := p.FindArgument(alias); found { 85 | return false 86 | } 87 | } 88 | p.types = append(p.types, arg) 89 | return true 90 | } 91 | 92 | func (p *ArgumentProvider) FindArgument(name string) (*ArgumentType, bool) { 93 | for _, arg := range p.types { 94 | if arg.Is(name) { 95 | return arg, true 96 | } 97 | } 98 | return nil, false 99 | } 100 | 101 | func (p *ArgumentProvider) FindArgumentOrUnknwonType(name string) *ArgumentType { 102 | if arg, found := p.FindArgument(name); found { 103 | return arg 104 | } 105 | return p.UnknwonType() 106 | } 107 | 108 | type MessageArgument struct { 109 | Name string 110 | Type *ArgumentType 111 | } 112 | 113 | type ArgumentList struct { 114 | Args []*MessageArgument 115 | } 116 | 117 | func NewArgumentList() *ArgumentList { 118 | return &ArgumentList{Args: make([]*MessageArgument, 0)} 119 | } 120 | 121 | func (l *ArgumentList) Merge(other *ArgumentList) error { 122 | var errs []error 123 | for _, arg := range other.Args { 124 | if _, err := l.AddArgument(arg); err != nil { 125 | errs = append(errs, err) 126 | } 127 | } 128 | if len(errs) == 0 { 129 | return nil 130 | } 131 | return ErrMergeArgumentList.WithArgs(errors.Join(errs...)) 132 | } 133 | 134 | func (l *ArgumentList) AddArgument(arg *MessageArgument) (*MessageArgument, error) { 135 | assert.NonNil(arg.Type, "arg.Type") 136 | existing, found := l.GetArgument(arg.Name) 137 | if !found { 138 | l.Args = append(l.Args, arg) 139 | return arg, nil 140 | } 141 | 142 | if arg.Type.IsUnknown { 143 | return existing, nil 144 | } 145 | if existing.Type.IsUnknown { 146 | existing.Type = arg.Type // arg.Type != unknown and existing.Type == unknown -> specify the type 147 | return existing, nil 148 | } 149 | if existing.Type != arg.Type { 150 | return nil, ErrArgumentCollition.WithArgs(arg.Name, arg.Type.Name, existing.Type.Name) 151 | } 152 | return existing, nil 153 | } 154 | 155 | func (l *ArgumentList) GetArgument(name string) (*MessageArgument, bool) { 156 | for i := range l.Args { 157 | if l.Args[i].Name == name { 158 | return l.Args[i], true 159 | } 160 | } 161 | return nil, false 162 | } 163 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-n-i18n 2 | 3 | A Go-based code generation tool for type-safe, efficient, and feature-rich internationalization inspired by [ParaglideJS](https://inlang.com/m/gerre34r/library-inlang-paraglideJs). It automatically generates code to ensure type safety, improve code readability, and eliminate runtime errors when handling localized messages. 4 | 5 | ## How it works 6 | 7 | Messages are defined in a JSON file, 8 | go-n-i18n will extract the messages from these files and generate code with it. 9 | Here is an example: 10 | 11 | ```JSON 12 | { 13 | "where-am-i": "Assume this json is in the file \"en-EN.json\"", 14 | "nested-messages": { 15 | "simple": "This is just a simple message nested into \"nested-messages\"", 16 | "parametrized": "This message has an amount parameter of type int: {amount:int}" 17 | }, 18 | "multi-line-message": [ 19 | "Hello {user:str}!", 20 | "Messages can be multi-line", 21 | "And each one can have parameters", 22 | "This one has a float formatted with 2 decimals! {amount:float64:.2f}" 23 | ], 24 | "?conditional-messages": { 25 | "amount == 0": "If amount is 0, this message is used", 26 | "amount == 1": "This message is returned if the amount is 1", 27 | "": [ 28 | "This is the \"else\" branch", 29 | "This multi-line message is used", 30 | "And shows the amount: {amount:int}" 31 | ] 32 | } 33 | } 34 | ``` 35 | 36 | When running go-n-i18n, you'll get code that looks like this: 37 | 38 | ```go 39 | // Utility methods 40 | func MessagesFor(tag string) (Messages, bool) { ... } 41 | 42 | func MessagesForMust(tag string) Messages { ... } 43 | 44 | // Default is the language specified as default when running the tool 45 | func MessagesForOrDefault(tag string) Messages { ... } 46 | 47 | type Messages interface{ 48 | WhereAmI() string 49 | NestedMessages() nestedMessages 50 | MultiLineMessage(user string, amount float64) string 51 | ConditionalMessages(amount int) string 52 | } 53 | type nestedMessages interface{ 54 | Simple() string 55 | Parametrized(amount int) string 56 | } 57 | 58 | // Struct that implements Messages returning the messages defined in the language file 59 | type en_EN_Messages struct{} 60 | // More code... See examples/lang/generated_lang.go for all of it 61 | ``` 62 | 63 | Now you can get an instance of your messages and use them! 64 | 65 | ```go 66 | func main() { 67 | bundle := lang.MessagesForMust("en-EN") 68 | 69 | fmt.Println(bundle.WhereAmI()) 70 | // Assume this json is in the file "en-EN.json" 71 | 72 | fmt.Println(bundle.NestedMessages().Parametrized(4)) 73 | // This message has an amount parameter of type int: 4 74 | 75 | fmt.Println(bundle.ConditionalMessages(100)) 76 | /* 77 | This is the "else" branch 78 | This multi-line message is used 79 | And shows the amount: 100 80 | */ 81 | 82 | fmt.Println(bundle.MultiLineMessage("MrNemo64", 13.1267)) 83 | /* 84 | Hello MrNemo64! 85 | Messages can be multi-line 86 | And each one can have parameters 87 | This one has a float formated with 2 decimals! 13.13 88 | */ 89 | } 90 | ``` 91 | 92 | ## Why? 93 | 94 | `go-n-i18n` offers a different approach to internationalization by moving most of the work into compile-time with several advantages: 95 | 96 | - **Type-safe message access**: By generating functions for each message, it eliminates runtime errors from mistyped or missing message identifiers. 97 | - **Improved code readability**: Autocomplete surfaces all available messages, so developers don’t need to remember or look up message identifiers. 98 | - **Efficient parameter handling**: Parameters are passed as function arguments instead of map allocations, reducing memory overhead. 99 | - **Compile-time error checking**: Any misidentified messages result in compile-time errors, ensuring your code is correct before runtime. 100 | 101 | ## Installing and using 102 | 103 | Install by cloning the repository and running `make install` or by running `go install github.com/MrNemo64/go-n-i18n/cmd/i18n@v0.0.3`. 104 | 105 | To use it you must invoke the generator. This can be done by using a specific file in your language folder as a generator: 106 | 107 | ```go 108 | package lang 109 | 110 | // use en-EN as default language and start looking for language files in the current directory 111 | //go:generate i18n -default-language en-EN -messages . 112 | ``` 113 | 114 | Or by manually running the command. 115 | 116 | ## More information 117 | 118 | See the [wiki](https://github.com/MrNemo64/go-n-i18n/wiki) or the [docs](https://github.com/MrNemo64/go-n-i18n/tree/main/docs) folder for more details on how to use the tool. 119 | -------------------------------------------------------------------------------- /internal/cli/types/message_bag.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 7 | ) 8 | 9 | type MessageBag struct { 10 | messageEntry 11 | children []MessageEntry 12 | Name string 13 | } 14 | 15 | var ( 16 | ErrParentIsNotBag util.Error = util.MakeError("could not make or get bag entry %s because %s is not a bag") 17 | ErrAddedEntryIsNotSameType = util.MakeError("the entry to add %s is of kind %d but there is already an entry of type %d") 18 | ErrInvalidName = util.MakeError("the name '%s' does not follow the allowed format (^[a-zA-Z][a-zA-Z0-9_-]*$)") 19 | ) 20 | 21 | func IsValidName(name string) bool { return ValidKey.MatchString(name) } 22 | func CheckName(name string) error { 23 | if !IsValidName(name) { 24 | return ErrInvalidName.WithArgs(name) 25 | } 26 | return nil 27 | } 28 | 29 | func NewMessageBag(key string) (*MessageBag, error) { 30 | if !IsValidKey(key) { 31 | return nil, ErrInvalidKey.WithArgs(key) 32 | } 33 | return &MessageBag{ 34 | messageEntry: messageEntry{ 35 | key: key, 36 | }, 37 | children: make([]MessageEntry, 0), 38 | }, nil 39 | } 40 | 41 | func MakeRoot() *MessageBag { 42 | return &MessageBag{ 43 | messageEntry: messageEntry{ 44 | key: "", 45 | }, 46 | children: make([]MessageEntry, 0), 47 | } 48 | } 49 | func (m *MessageBag) AsBag() *MessageBag { return m } 50 | func (*MessageBag) AsInstance() *MessageInstance { panic("called AsInstance on a bag") } 51 | func (m *MessageBag) IsRoot() bool { return m.key == "" } 52 | func (*MessageBag) Type() MessageEntryType { return MessageEntryBag } 53 | func (*MessageBag) IsBag() bool { return true } 54 | func (*MessageBag) IsInstance() bool { return false } 55 | func (m *MessageBag) Children() []MessageEntry { return m.children } 56 | 57 | func (b *MessageBag) GetEntry(key string) (MessageEntry, bool) { 58 | for _, e := range b.children { 59 | if e.Key() == key { 60 | return e, true 61 | } 62 | } 63 | return nil, false 64 | } 65 | 66 | func (m *MessageBag) FindOrCreateChildBag(path ...string) (*MessageBag, error) { 67 | if len(path) == 0 { 68 | return m, nil 69 | } 70 | actual := m 71 | for i := 0; i < len(path); i++ { 72 | found, ok := actual.GetEntry(path[i]) 73 | if !ok { 74 | child, err := NewMessageBag(path[i]) 75 | if err != nil { 76 | return nil, ErrCreateEntry.WithArgs(path[i], err) 77 | } 78 | actual.AddChildren(child) 79 | actual = child 80 | continue 81 | } 82 | if !found.IsBag() { 83 | return nil, ErrParentIsNotBag.WithArgs(PathAsStr(path), PathAsStr(path[:i+1])) 84 | } 85 | actual = found.AsBag() 86 | } 87 | return actual, nil 88 | } 89 | 90 | func (m *MessageBag) AddChildren(children ...MessageEntry) error { 91 | for _, child := range children { 92 | if child.IsBag() && child.AsBag().IsRoot() { 93 | if err := m.AddChildren(child.AsBag().children...); err != nil { 94 | return err 95 | } 96 | continue 97 | } 98 | 99 | existing, found := m.GetEntry(child.Key()) 100 | if !found { 101 | child.AssignParent(m) 102 | m.children = append(m.children, child) 103 | continue 104 | } 105 | if existing.Type() != child.Type() { 106 | return ErrAddedEntryIsNotSameType.WithArgs(child.Key(), child.Type(), existing.Type()) 107 | } 108 | switch existing.Type() { 109 | case MessageEntryBag: 110 | if err := existing.AsBag().AddChildren(child.AsBag().children...); err != nil { 111 | return err 112 | } 113 | case MessageEntryInstance: 114 | if err := existing.AsInstance().Merge(child.AsInstance()); err != nil { 115 | return err 116 | } 117 | default: 118 | panic(fmt.Errorf("unknown message entry type %d", existing.Type())) 119 | } 120 | } 121 | return nil 122 | } 123 | 124 | func (m *MessageBag) RemoveEntriesWithoutLang(lang string) []MessageEntry { 125 | var removed []MessageEntry 126 | var remaining []MessageEntry 127 | for _, child := range m.children { 128 | switch child.Type() { 129 | case MessageEntryBag: 130 | removed = append(removed, child.AsBag().RemoveEntriesWithoutLang(lang)...) 131 | if len(child.AsBag().children) > 0 { 132 | remaining = append(remaining, child) 133 | } else { 134 | removed = append(removed, child) 135 | } 136 | case MessageEntryInstance: 137 | if child.Languages().Contains(lang) { 138 | remaining = append(remaining, child) 139 | } else { 140 | removed = append(removed, child) 141 | } 142 | default: 143 | panic(fmt.Errorf("unknown message entry type %d", child.Type())) 144 | } 145 | } 146 | m.children = remaining 147 | return removed 148 | } 149 | 150 | func (m *MessageBag) MustHaveAllLangs(langs []string, defLang string) map[string][]string { 151 | ret := make(map[string][]string) 152 | for _, child := range m.children { 153 | util.MergeIntoA(ret, child.MustHaveAllLangs(langs, defLang), func(v1, v2 *[]string) []string { return append(*v1, *v2...) }) 154 | } 155 | return ret 156 | } 157 | 158 | func (m *MessageBag) Languages() *util.Set[string] { 159 | set := util.NewSet[string]() 160 | for _, child := range m.children { 161 | set.AddAll(child.Languages()) 162 | } 163 | return set 164 | } 165 | -------------------------------------------------------------------------------- /internal/cli/writing/main.go: -------------------------------------------------------------------------------- 1 | package writing 2 | 3 | import ( 4 | "fmt" 5 | "slices" 6 | "strings" 7 | 8 | "github.com/MrNemo64/go-n-i18n/internal/cli/assert" 9 | "github.com/MrNemo64/go-n-i18n/internal/cli/types" 10 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 11 | ) 12 | 13 | type GoCodeWriter struct { 14 | sb *strings.Builder 15 | indent int 16 | inNewLine bool 17 | msgs *types.MessageBag 18 | namer MessageEntryNamer 19 | langs []string 20 | defLang string 21 | pack string 22 | } 23 | 24 | func GenerateGoCode(msgs *types.MessageBag, namer MessageEntryNamer, langs []string, defLang, pack string) string { 25 | assert.Has(langs, defLang) 26 | slices.Sort(langs) 27 | cw := GoCodeWriter{ 28 | sb: &strings.Builder{}, 29 | msgs: msgs, 30 | indent: 0, 31 | inNewLine: true, 32 | namer: namer, 33 | langs: langs, 34 | defLang: defLang, 35 | pack: pack, 36 | } 37 | cw.GenerateCode() 38 | return cw.sb.String() 39 | } 40 | 41 | func (w *GoCodeWriter) GenerateCode() { 42 | w.WriteHeader() 43 | w.WriteGetMethods() 44 | w.WriteInterfaces() 45 | w.WriteStructs() 46 | } 47 | 48 | func (w *GoCodeWriter) WriteHeader() { 49 | w.w("/** Code generated using https://github.com/MrNemo64/go-n-i18n \n") 50 | w.w(" * Any changes to this file will be lost on the next tool run */\n\n") 51 | w.w("package ") 52 | w.w(w.pack) 53 | w.w("\n\n") 54 | w.w("import (\n") 55 | w.w(" \"fmt\"\n") 56 | w.w(" \"strings\"\n") 57 | w.w(")\n\n") 58 | } 59 | 60 | func (w *GoCodeWriter) WriteGetMethods() { 61 | w.w("func MessagesFor(tag string) (%s, bool) {\n", w.namer.TopLevelName()) 62 | w.w(" switch strings.ReplaceAll(tag, \"_\", \"-\") {\n") 63 | for _, lang := range w.langs { 64 | w.w(" case \"%s\":\n", lang) 65 | w.w(" return %s{}, true\n", w.namer.InterfaceNameForLang(lang, w.msgs)) 66 | } 67 | w.w(" }\n") 68 | w.w(" return nil, false\n") 69 | w.w("}\n\n") 70 | 71 | w.w("func MessagesForMust(tag string) %s {\n", w.namer.TopLevelName()) 72 | w.w(" switch strings.ReplaceAll(tag, \"_\", \"-\") {\n") 73 | for _, lang := range w.langs { 74 | w.w(" case \"%s\":\n", lang) 75 | w.w(" return %s{}\n", w.namer.InterfaceNameForLang(lang, w.msgs)) 76 | } 77 | w.w(" }\n") 78 | w.w(" panic(fmt.Errorf(\"unknwon language tag: \" + tag))\n") 79 | w.w("}\n\n") 80 | 81 | w.w("func MessagesForOrDefault(tag string) %s {\n", w.namer.TopLevelName()) 82 | w.w(" switch strings.ReplaceAll(tag, \"_\", \"-\") {\n") 83 | for _, lang := range w.langs { 84 | w.w(" case \"%s\":\n", lang) 85 | w.w(" return %s{}\n", w.namer.InterfaceNameForLang(lang, w.msgs)) 86 | } 87 | w.w(" }\n") 88 | w.w(" return %s{}\n", w.namer.InterfaceNameForLang(w.defLang, w.msgs)) 89 | w.w("}\n\n") 90 | } 91 | 92 | func (w *GoCodeWriter) WriteInterfaces() { 93 | w.writeInterface(w.msgs) 94 | w.w("\n") 95 | } 96 | 97 | func (w *GoCodeWriter) writeInterface(i *types.MessageBag) { 98 | w.w("type %s interface{\n", w.namer.InterfaceName(i)) 99 | w.addIndent() 100 | for _, child := range i.Children() { 101 | w.w("%s(%s) ", w.namer.FunctionName(child), w.createArgList(child)) 102 | switch child.Type() { 103 | case types.MessageEntryBag: 104 | w.w("%s\n", w.namer.InterfaceName(child.AsBag())) 105 | case types.MessageEntryInstance: 106 | w.w("string\n") 107 | default: 108 | panic(fmt.Errorf("unknown message entry type %d", child.Type())) 109 | } 110 | } 111 | w.removeIndent() 112 | w.w("}\n") 113 | 114 | for _, child := range i.Children() { 115 | if child.IsBag() { 116 | w.writeInterface(child.AsBag()) 117 | } 118 | } 119 | } 120 | 121 | func (w *GoCodeWriter) WriteStructs() { 122 | for _, lang := range w.langs { 123 | w.writeStruct(lang, w.msgs) 124 | w.w("\n\n") 125 | } 126 | } 127 | 128 | func (w *GoCodeWriter) writeStruct(lang string, msgs *types.MessageBag) { 129 | w.w("type %s struct{}\n", w.namer.InterfaceNameForLang(lang, msgs)) 130 | for _, child := range msgs.Children() { 131 | w.writeFunction(lang, child) 132 | if child.IsBag() { 133 | w.writeStruct(lang, child.AsBag()) 134 | } 135 | } 136 | } 137 | 138 | func (w *GoCodeWriter) writeFunction(lang string, msg types.MessageEntry) { 139 | w.w("func (%s) %s(%s) ", w.namer.InterfaceNameForLang(lang, msg.Parent()), w.namer.FunctionName(msg), w.createArgList(msg)) 140 | switch msg.Type() { 141 | case types.MessageEntryBag: 142 | w.w("%s {\n", w.namer.InterfaceName(msg.AsBag())) 143 | w.w(" return %s{}\n", w.namer.InterfaceNameForLang(lang, msg.AsBag())) 144 | w.w("}\n") 145 | case types.MessageEntryInstance: 146 | w.w("string {\n") 147 | w.addIndent() 148 | w.writeFunctionBody(lang, msg.AsInstance()) 149 | w.removeIndent() 150 | w.w("}\n") 151 | default: 152 | panic(fmt.Errorf("unknown message entry type %d", msg.Type())) 153 | } 154 | } 155 | 156 | func (w *GoCodeWriter) createArgList(msg types.MessageEntry) string { 157 | switch msg.Type() { 158 | case types.MessageEntryBag: 159 | return "" 160 | case types.MessageEntryInstance: 161 | return strings.Join( 162 | util.Map(msg.AsInstance().Args().Args, func(_ int, t **types.MessageArgument) string { return (*t).Name + " " + (*t).Type.Type }), 163 | ", ", 164 | ) 165 | default: 166 | panic(fmt.Errorf("unknown message entry type %d", msg.Type())) 167 | } 168 | } 169 | 170 | func (w *GoCodeWriter) writeFunctionBody(lang string, msg *types.MessageInstance) { 171 | val := msg.MessageMust(lang) 172 | w.writeValue(val) 173 | } 174 | 175 | func (w *GoCodeWriter) writeValue(val types.MessageValue) { 176 | switch val.(type) { 177 | case *types.ValueString: 178 | w.w("return %s\n", w.createValueValueString(val.AsValueString())) 179 | case *types.ValueParametrized: 180 | w.w("return %s\n", w.createValueParametrizedValue(val.AsValueParametrized())) 181 | case *types.ValueMultiline: 182 | lines := val.AsMultiline().Lines 183 | w.w("return %s", w.createMultilineableString(lines[0])) 184 | if len(lines) == 1 { 185 | return 186 | } 187 | w.w(` + "\n" +` + "\n") // writen like this so maybe the compiler joins them 188 | w.addIndent() 189 | for i := 1; i < len(lines); i++ { 190 | w.wl(w.createMultilineableString(lines[i])) 191 | if i != len(lines)-1 { 192 | w.w(` + "\n" +` + "\n") // writen like this so maybe the compiler joins them 193 | } 194 | } 195 | w.w("\n") 196 | w.removeIndent() 197 | case *types.ValueConditional: 198 | conditions := val.AsConditional() 199 | w.w("if %s {\n", conditions.Conditions[0].Condition) 200 | w.addIndent() 201 | mval, ok := conditions.Conditions[0].Value.(types.MessageValue) 202 | if !ok { 203 | panic("") // TODO 204 | } 205 | w.writeValue(mval) 206 | w.removeIndent() 207 | w.w("}") 208 | for i := 1; i < len(conditions.Conditions); i++ { 209 | condition := conditions.Conditions[i] 210 | w.w(" else if %s {\n", condition.Condition) 211 | w.addIndent() 212 | mval, ok := conditions.Conditions[i].Value.(types.MessageValue) 213 | if !ok { 214 | panic("") // TODO 215 | } 216 | w.writeValue(mval) 217 | w.removeIndent() 218 | w.w("}") 219 | } 220 | w.w(" else {\n") 221 | w.addIndent() 222 | if conditions.Else == nil { 223 | w.wl(`panic(fmt.Errorf("no condition was true in conditional"))` + "\n") 224 | } else { 225 | mval, ok := conditions.Else.(types.MessageValue) 226 | if !ok { 227 | panic("") // TODO 228 | } 229 | w.writeValue(mval) 230 | } 231 | w.removeIndent() 232 | w.w("}\n") 233 | } 234 | } 235 | 236 | func (w *GoCodeWriter) createMultilineableString(s types.Multilineable) string { 237 | switch s.(type) { 238 | case *types.ValueString: 239 | return w.createValueValueString(s.(*types.ValueString)) 240 | case *types.ValueParametrized: 241 | return w.createValueParametrizedValue(s.(*types.ValueParametrized)) 242 | default: 243 | panic(fmt.Errorf("unknown Multilineable type %+v", s)) 244 | } 245 | } 246 | 247 | func (w *GoCodeWriter) createValueValueString(s *types.ValueString) string { 248 | return "\"" + s.AsValueString().Escaped("\"") + "\"" 249 | } 250 | 251 | func (w *GoCodeWriter) createValueParametrizedValue(p *types.ValueParametrized) string { 252 | messagePartSb := &strings.Builder{} 253 | for i, arg := range p.Args { 254 | messagePartSb.WriteString(p.TextSegments[i].Escaped("\"")) 255 | messagePartSb.WriteString("%") 256 | if arg.Format == "" { 257 | messagePartSb.WriteString(p.Args[i].Argument.Type.DefaultFormat) 258 | } else { 259 | messagePartSb.WriteString(p.Args[i].Format) 260 | } 261 | } 262 | messagePartSb.WriteString(p.TextSegments[len(p.TextSegments)-1].Escaped("\"")) 263 | argListPart := strings.Join( 264 | util.Map(p.Args, func(_ int, t **types.UsedArgument) string { return (*t).Argument.Name }), 265 | ", ", 266 | ) 267 | messagePart := messagePartSb.String() 268 | return fmt.Sprintf("fmt.Sprintf(\"%s\", %s)", messagePart, argListPart) 269 | } 270 | 271 | func (w *GoCodeWriter) w(str string, args ...any) { 272 | if w.indent > 0 && w.inNewLine { 273 | w.sb.WriteString(strings.Repeat(" ", w.indent)) 274 | } 275 | msg := fmt.Sprintf(str, args...) 276 | w.sb.WriteString(msg) 277 | w.inNewLine = strings.HasSuffix(msg, "\n") 278 | } 279 | 280 | func (w *GoCodeWriter) wl(str string) { 281 | if w.indent > 0 && w.inNewLine { 282 | w.sb.WriteString(strings.Repeat(" ", w.indent)) 283 | } 284 | w.sb.WriteString(str) 285 | w.inNewLine = strings.HasSuffix(str, "\n") 286 | } 287 | 288 | func (w *GoCodeWriter) indentBy(amount int) { 289 | w.indent = max(0, w.indent+amount) 290 | } 291 | 292 | func (w *GoCodeWriter) addIndent() { 293 | w.indentBy(4) 294 | } 295 | 296 | func (w *GoCodeWriter) removeIndent() { 297 | w.indentBy(-4) 298 | } 299 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 MrNemo64 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /internal/cli/parse/main.go: -------------------------------------------------------------------------------- 1 | package parse 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "regexp" 7 | "strings" 8 | 9 | "github.com/MrNemo64/go-n-i18n/internal/cli/assert" 10 | "github.com/MrNemo64/go-n-i18n/internal/cli/types" 11 | "github.com/MrNemo64/go-n-i18n/internal/cli/util" 12 | "github.com/iancoleman/orderedmap" 13 | ) 14 | 15 | var ( 16 | ErrNextFile util.Error = util.MakeError("could get next file to parse: %w") 17 | ErrIO = util.MakeError("could not read contents of file %s: %w") 18 | ErrUnmarshal = util.MakeError("could not unmarshal contents of file %s: %w") 19 | ErrInvalidKeyName = util.MakeError("invalid key in path %s: %w") 20 | ErrInvalidBagName = util.MakeError("invalid bag name in path %s: %w") 21 | ErrBagNameReasignation = util.MakeError("the bag %s in the lang %s has the name %s but it got reasigned to %s") 22 | ErrUnknownEntryType = util.MakeError("could not identify the type of entry in the path %s: %+v") 23 | ErrAddChildren = util.MakeError("could not add child %s to %s: %w") 24 | ErrUnknwonArgumentType = util.MakeError("unknown argument type '%s' in path %s, using the unknown type") 25 | ErrInvalidConditionalEntry = util.MakeError("the entry %s in the lang %s is marked as conditional but no conditions are provided") 26 | ErrInvalidConditionalCondition = util.MakeError("the condition %s in the path %s in the lang %s is not a valid conditional value") 27 | ErrInvalidConditional = util.MakeError("the conditional in the path %s in the lang %s is not a valid: %w") 28 | 29 | ErrKeyIsConditionalButValueIsNotObject = util.MakeError("invalid key '%s': has the ? prefix so it's a conditional key but the value is not an object: %v") 30 | ErrCouldNotAddEntry = util.MakeError("could not add %s entry %s: %w") 31 | ErrCouldNotAddArg = util.MakeError("could not add argument {%s:%s:%s}: %w") 32 | ) 33 | 34 | var ArgumentExtractor = regexp.MustCompile(`\{([a-zA-Z_]\w*):?(\w*)?:?([\w\.]*)?\}`) 35 | 36 | type JsonParser struct { 37 | *util.WarningsCollector 38 | argProvider *types.ArgumentProvider 39 | } 40 | 41 | func ParseJson(walker DirWalker, wc *util.WarningsCollector, argProvider *types.ArgumentProvider) (*types.MessageBag, error) { 42 | return (&JsonParser{WarningsCollector: wc, argProvider: argProvider}).ParseWalker(walker) 43 | } 44 | 45 | func (p *JsonParser) ParseWalker(walker DirWalker) (*types.MessageBag, error) { 46 | root := types.MakeRoot() 47 | for { 48 | file, err := walker.Next() 49 | if err == ErrNoMoreFiles { 50 | return root, nil 51 | } 52 | if err != nil { 53 | return nil, ErrNextFile.WithArgs(err) 54 | } 55 | content, err := file.ReadContents() 56 | if err != nil { 57 | return nil, ErrIO.WithArgs(file.FullPath(), err) 58 | } 59 | entries := orderedmap.New() 60 | if err := json.Unmarshal(content, entries); err != nil { 61 | return nil, ErrUnmarshal.WithArgs(file.FullPath(), err) 62 | } 63 | 64 | dest, err := root.FindOrCreateChildBag(file.Path()...) 65 | if err != nil { 66 | return nil, err 67 | } 68 | 69 | if err := p.ParseGroupOfMessagesInto(dest, entries, file.Language()); err != nil { 70 | return nil, err 71 | } 72 | } 73 | } 74 | 75 | func (p *JsonParser) ParseGroupOfMessagesInto(dest *types.MessageBag, entries *orderedmap.OrderedMap, lang string) error { 76 | keys := entries.Keys() 77 | for _, key := range keys { 78 | value, found := entries.Get(key) 79 | if !found { 80 | panic(fmt.Errorf("the ordered map is missing the key '%s', this is a bug in the github.com/iancoleman/orderedmap library. Dest: %s", key, dest.PathAsStr())) 81 | } 82 | 83 | if strings.HasPrefix(key, "?") { // is conditional? 84 | key = key[1:] 85 | if err := types.CheckKey(key); err != nil { 86 | p.AddWarning(ErrInvalidKeyName.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), err)) 87 | continue 88 | } 89 | mapValue, ok := value.(orderedmap.OrderedMap) 90 | if !ok { 91 | p.WarningsCollector.AddWarning(ErrInvalidConditionalEntry.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), lang)) 92 | continue 93 | } 94 | args := types.NewArgumentList() 95 | parsed, ok := p.ParseConditionalMessageValue(types.PathAsStr(types.ResolveFullPath(dest, key)), &mapValue, args, lang) 96 | if !ok { 97 | continue 98 | } 99 | newEntry, err := types.NewMessageInstance(key) 100 | assert.NoError(err) // key is valid, we checked it above 101 | assert.NoError(newEntry.AddArgs(args)) // entry is empty, it must accept the new args 102 | assert.NoError(newEntry.AddLanguage(lang, parsed)) // entry is empty, it must accept the new language 103 | if err := dest.AddChildren(newEntry); err != nil { 104 | p.AddWarning(ErrAddChildren.WithArgs(key, dest.PathAsStr(), err)) 105 | } 106 | continue 107 | } 108 | 109 | if inner, ok := value.(orderedmap.OrderedMap); ok { // is bag or parametrized with `_args` to specify args 110 | if _, found := inner.Get("_args"); found { // parametrized with `_args` 111 | panic("todo") 112 | } else { // bag 113 | name := "" 114 | if strings.Contains(key, ":") { 115 | parts := strings.SplitN(key, ":", 2) 116 | if len(parts) == 1 || parts[1] == "" { 117 | name = parts[0] 118 | } else { 119 | name = parts[1] 120 | } 121 | key = key[:strings.Index(key, ":")] 122 | } 123 | 124 | if err := types.CheckKey(key); err != nil { 125 | p.AddWarning(ErrInvalidKeyName.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), err)) 126 | continue 127 | } 128 | 129 | newDest, err := dest.FindOrCreateChildBag(key) 130 | if err != nil { 131 | p.AddWarning(ErrAddChildren.WithArgs(key, dest.PathAsStr(), err)) 132 | continue 133 | } 134 | if newDest.Name == "" && name != "" { 135 | if err := types.CheckName(name); err != nil { 136 | p.AddWarning(ErrInvalidBagName.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), err)) 137 | continue 138 | } 139 | newDest.Name = name 140 | } else if newDest.Name != name && name != "" { 141 | p.WarningsCollector.AddWarning(ErrBagNameReasignation.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), lang, newDest.Name, name)) 142 | continue 143 | } 144 | if err := p.ParseGroupOfMessagesInto(newDest, &inner, lang); err != nil { 145 | return err 146 | } 147 | continue 148 | } 149 | } 150 | 151 | if err := types.CheckKey(key); err != nil { 152 | p.AddWarning(ErrInvalidKeyName.WithArgs(types.PathAsStr(types.ResolveFullPath(dest, key)), err)) 153 | continue 154 | } 155 | 156 | args := types.NewArgumentList() 157 | parsed, ok := p.ParseMessageValue(types.PathAsStr(types.ResolveFullPath(dest, key)), value, args) 158 | if !ok { 159 | continue 160 | } 161 | newEntry, err := types.NewMessageInstance(key) 162 | assert.NoError(err) // key is valid, we checked it above 163 | assert.NoError(newEntry.AddArgs(args)) // entry is empty, it must accept the new args 164 | assert.NoError(newEntry.AddLanguage(lang, parsed)) // entry is empty, it must accept the new language 165 | if err := dest.AddChildren(newEntry); err != nil { 166 | p.AddWarning(ErrAddChildren.WithArgs(key, dest.PathAsStr(), err)) 167 | } 168 | } 169 | return nil 170 | } 171 | 172 | func (p *JsonParser) ParseMessageValue(fullKey string, value any, argList *types.ArgumentList) (types.MessageValue, bool) { 173 | switch value.(type) { 174 | case string: 175 | str := value.(string) 176 | if !p.HasArguments(str) { 177 | return types.NewStringLiteralValue(str), true 178 | } 179 | return p.ParseParametrizedMessage(fullKey, str, argList) 180 | case []any: 181 | arr := value.([]any) 182 | if len(arr) == 0 || !p.IsStringSlice(arr) { 183 | p.AddWarning(ErrUnknownEntryType.WithArgs(fullKey, value)) 184 | return nil, false 185 | } 186 | lines := make([]types.Multilineable, 0) 187 | for _, line := range arr { 188 | str := line.(string) 189 | if !p.HasArguments(str) { 190 | lines = append(lines, types.NewStringLiteralValue(str)) 191 | } else { 192 | if parsed, ok := p.ParseParametrizedMessage(fullKey, str, argList); ok { 193 | lines = append(lines, parsed) 194 | } else { 195 | return nil, false 196 | } 197 | } 198 | } 199 | multi, err := types.NewMultilineValue(lines) 200 | assert.NoError(err) // err if len(lines) == 0 but we checked above 201 | return multi, true 202 | default: 203 | p.AddWarning(ErrUnknownEntryType.WithArgs(fullKey, value)) 204 | return nil, false 205 | } 206 | } 207 | 208 | func (p *JsonParser) ParseConditionalMessageValue(fullKey string, value *orderedmap.OrderedMap, argList *types.ArgumentList, lang string) (*types.ValueConditional, bool) { 209 | finishOk := true 210 | var conditions []types.Condition 211 | var elseCondition types.Conditionable 212 | for _, condition := range value.Keys() { 213 | if condition == "_args" { 214 | panic(fmt.Errorf("specifying the args in a `_args` entry is not yet supported")) 215 | } 216 | value, found := value.Get(condition) 217 | if !found { 218 | panic(fmt.Errorf("the ordered map is missing the key '%s', this is a bug in the github.com/iancoleman/orderedmap library. Dest: %s", condition, fullKey)) 219 | } 220 | parsed, ok := p.ParseMessageValue(fullKey+"."+condition, value, argList) 221 | if !ok { 222 | finishOk = false 223 | continue 224 | } 225 | conditionValue, ok := parsed.(types.Conditionable) 226 | if !ok { 227 | finishOk = false 228 | p.AddWarning(ErrInvalidConditionalCondition.WithArgs(condition, fullKey, lang)) 229 | continue 230 | } 231 | if condition == "" { 232 | elseCondition = conditionValue 233 | } else { 234 | conditions = append(conditions, types.Condition{ 235 | Condition: condition, 236 | Value: conditionValue, 237 | }) 238 | } 239 | } 240 | if !finishOk { 241 | return nil, false 242 | } 243 | cond, err := types.NewConditionalValue(conditions, elseCondition) 244 | if err != nil { 245 | p.WarningsCollector.AddWarning(ErrInvalidConditional.WithArgs(fullKey, lang, err)) 246 | return nil, false 247 | } 248 | return cond, true 249 | } 250 | 251 | func (p *JsonParser) ParseParametrizedMessage(fullKey string, str string, argList *types.ArgumentList) (*types.ValueParametrized, bool) { 252 | textSegments, arguments := p.SeparateArgumentsFromText(str) 253 | if len(textSegments) != len(arguments)+1 { 254 | panic(fmt.Errorf("JsonParser.SeparateArgumentsFromText returned an unexpected amount of text segments (%d) and arguments (%d) for the path %s", len(textSegments), len(arguments), fullKey)) 255 | } 256 | usedArgs := util.Map(arguments, func(index int, foundArg *foundArgument) *types.UsedArgument { 257 | argType, found := p.argProvider.FindArgument(foundArg.Type) 258 | if !found { 259 | if foundArg.Type != "" { 260 | p.WarningsCollector.AddWarning(ErrUnknwonArgumentType.WithArgs(foundArg.Type, fullKey)) 261 | } 262 | argType = p.argProvider.UnknwonType() 263 | } 264 | arg, err := argList.AddArgument(&types.MessageArgument{ 265 | Name: foundArg.Name, 266 | Type: argType, 267 | }) 268 | if err != nil { 269 | p.WarningsCollector.AddWarning(err) 270 | return nil 271 | } 272 | return &types.UsedArgument{ 273 | Argument: arg, 274 | Format: foundArg.Format, 275 | } 276 | }) 277 | if util.Has(usedArgs, nil) { 278 | return nil, false 279 | } 280 | parametrized, err := types.NewParametrizedStringValue( 281 | util.Map(textSegments, func(_ int, t *string) *types.ValueString { return types.NewStringLiteralValue(*t) }), 282 | usedArgs, 283 | ) 284 | assert.NoError(err) 285 | return parametrized, true 286 | } 287 | 288 | type foundArgument struct { 289 | Name string 290 | Type string 291 | Format string 292 | } 293 | 294 | func (p *JsonParser) SeparateArgumentsFromText(message string) ([]string, []foundArgument) { 295 | var textSegments []string 296 | var arguments []foundArgument 297 | 298 | // Track the position as we move through the string 299 | lastIndex := 0 300 | matches := ArgumentExtractor.FindAllStringSubmatchIndex(message, -1) 301 | 302 | // If the first match starts at index 0, add an empty text segment at the beginning 303 | if len(matches) > 0 && matches[0][0] == 0 { 304 | textSegments = append(textSegments, "") 305 | } 306 | 307 | for i, match := range matches { 308 | start, end := match[0], match[1] 309 | 310 | // Capture the normal text before this argument 311 | if start > lastIndex { 312 | textSegments = append(textSegments, message[lastIndex:start]) 313 | } else if i > 0 { 314 | // If two arguments are consecutive, insert an empty text segment 315 | textSegments = append(textSegments, "") 316 | } 317 | 318 | // Extract components based on regex capture groups 319 | name := message[match[2]:match[3]] 320 | argType := "" 321 | format := "" 322 | if match[4] != -1 { 323 | argType = message[match[4]:match[5]] 324 | } 325 | if match[6] != -1 { 326 | format = message[match[6]:match[7]] 327 | } 328 | 329 | // Create an Argument and add to the list 330 | arguments = append(arguments, foundArgument{Name: name, Type: argType, Format: format}) 331 | 332 | // Update lastIndex to continue after this match 333 | lastIndex = end 334 | } 335 | 336 | // Append any remaining text after the last argument 337 | if lastIndex < len(message) { 338 | textSegments = append(textSegments, message[lastIndex:]) 339 | } else if len(matches) > 0 && lastIndex == len(message) { 340 | // If the last match ends at the end of the input, add an empty text segment at the end 341 | textSegments = append(textSegments, "") 342 | } 343 | 344 | return textSegments, arguments 345 | } 346 | 347 | func (*JsonParser) HasArguments(str string) bool { return ArgumentExtractor.MatchString(str) } 348 | func (*JsonParser) IsStringSlice(arr []any) bool { 349 | for i := range arr { 350 | if _, ok := arr[i].(string); !ok { 351 | return false 352 | } 353 | } 354 | return true 355 | } 356 | -------------------------------------------------------------------------------- /docs/messages.md: -------------------------------------------------------------------------------- 1 | # Messages 2 | 3 | ## Message types 4 | 5 | ### Literal messages 6 | 7 | These messages are just a literal string 8 | 9 | ```json 10 | { 11 | "key": "message" 12 | } 13 | ``` 14 | 15 |
16 | Generated code 17 | 18 | ```go 19 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 20 | * Any changes to this file will be lost on the next tool run */ 21 | 22 | package lang 23 | 24 | import ( 25 | "fmt" 26 | "strings" 27 | ) 28 | 29 | func MessagesFor(tag string) (Messages, bool) { 30 | switch strings.ReplaceAll(tag, "_", "-") { 31 | case "en-EN": 32 | return en_EN_Messages{}, true 33 | } 34 | return nil, false 35 | } 36 | 37 | func MessagesForMust(tag string) Messages { 38 | switch strings.ReplaceAll(tag, "_", "-") { 39 | case "en-EN": 40 | return en_EN_Messages{} 41 | } 42 | panic(fmt.Errorf("unknwon language tag: " + tag)) 43 | } 44 | 45 | func MessagesForOrDefault(tag string) Messages { 46 | switch strings.ReplaceAll(tag, "_", "-") { 47 | case "en-EN": 48 | return en_EN_Messages{} 49 | } 50 | return en_EN_Messages{} 51 | } 52 | 53 | type Messages interface { 54 | Key() string 55 | } 56 | 57 | type en_EN_Messages struct{} 58 | 59 | func (en_EN_Messages) Key() string { 60 | return "message" 61 | } 62 | ``` 63 | 64 |
65 | 66 | ### Parametrized messages 67 | 68 | These messages hold one or more parameters. Parameters are specified by following the format `{name:type:format}` where the type and format are optional. 69 | 70 | - `{name}`: Parameter of unknown type named `name` 71 | - `{name:str}`: Parameter of type string named `name` 72 | - `{amount:float64:.2f}`: Parameter of type float with 64 bits with a format rounded to 2 decimals 73 | 74 | The same parameter can be used several times on the same language, using diferent formats but always the same type. The type only needs to be specified ones in one language and all languages will use the same type. It is recomended to specify in the default language all the types and just reference the parameters by name in the rest of languages. 75 | 76 | ```json 77 | { 78 | "key": "message with a parameter of type float with 64 bits and rounded to 2 decimals {value:float64:.2f}" 79 | } 80 | ``` 81 | 82 |
83 | Generated code 84 | 85 | ```go 86 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 87 | * Any changes to this file will be lost on the next tool run */ 88 | 89 | package lang 90 | 91 | import ( 92 | "fmt" 93 | "strings" 94 | ) 95 | 96 | func MessagesFor(tag string) (Messages, bool) { 97 | switch strings.ReplaceAll(tag, "_", "-") { 98 | case "en-EN": 99 | return en_EN_Messages{}, true 100 | } 101 | return nil, false 102 | } 103 | 104 | func MessagesForMust(tag string) Messages { 105 | switch strings.ReplaceAll(tag, "_", "-") { 106 | case "en-EN": 107 | return en_EN_Messages{} 108 | } 109 | panic(fmt.Errorf("unknwon language tag: " + tag)) 110 | } 111 | 112 | func MessagesForOrDefault(tag string) Messages { 113 | switch strings.ReplaceAll(tag, "_", "-") { 114 | case "en-EN": 115 | return en_EN_Messages{} 116 | } 117 | return en_EN_Messages{} 118 | } 119 | 120 | type Messages interface{ 121 | Key(value float64) string 122 | } 123 | 124 | type en_EN_Messages struct{} 125 | func (en_EN_Messages) Key(value float64) string { 126 | return fmt.Sprintf("message with a parameter of type float with 64 bits and rounded to 2 decimals %.2f", value) 127 | } 128 | ``` 129 | 130 |
131 | 132 | #### Allowed arguments 133 | 134 | | Name | Type | Aliases | Default format | 135 | | ------- | ------- | -------------- | -------------- | 136 | | any | any | unknown | v | 137 | | string | string | str | s | 138 | | boolean | bool | boolean | t | 139 | | integer | int | int | d | 140 | | float | float64 | f64, f, double | g | 141 | 142 | More arguments will be aded with time 143 | 144 | ### Multiline messages 145 | 146 | These messages span multiple lines. Each line may be a [literal message](#literal-messages) or a [parametrized message](#parametrized-messages). All lines share the same parameters 147 | 148 | ```json 149 | { 150 | "key": [ 151 | "first line of the message", 152 | "the seccond line has a parameter {arg:int} of type int", 153 | "and the thir line reuses that parameter {arg}" 154 | ] 155 | } 156 | ``` 157 | 158 |
159 | Generated code 160 | 161 | ```go 162 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 163 | * Any changes to this file will be lost on the next tool run */ 164 | 165 | package lang 166 | 167 | import ( 168 | "fmt" 169 | "strings" 170 | ) 171 | 172 | func MessagesFor(tag string) (Messages, bool) { 173 | switch strings.ReplaceAll(tag, "_", "-") { 174 | case "en-EN": 175 | return en_EN_Messages{}, true 176 | } 177 | return nil, false 178 | } 179 | 180 | func MessagesForMust(tag string) Messages { 181 | switch strings.ReplaceAll(tag, "_", "-") { 182 | case "en-EN": 183 | return en_EN_Messages{} 184 | } 185 | panic(fmt.Errorf("unknwon language tag: " + tag)) 186 | } 187 | 188 | func MessagesForOrDefault(tag string) Messages { 189 | switch strings.ReplaceAll(tag, "_", "-") { 190 | case "en-EN": 191 | return en_EN_Messages{} 192 | } 193 | return en_EN_Messages{} 194 | } 195 | 196 | type Messages interface { 197 | Key(arg int) string 198 | } 199 | 200 | type en_EN_Messages struct{} 201 | 202 | func (en_EN_Messages) Key(arg int) string { 203 | return "first line of the message" + "\n" + 204 | fmt.Sprintf("the seccond line has a parameter %d of type int", arg) + "\n" + 205 | fmt.Sprintf("and the thir line reuses that parameter %d", arg) 206 | } 207 | ``` 208 | 209 |
210 | 211 | ### Conditional messages 212 | 213 | These messages allow to change the message itself based on a condition and have its key prefixed by a `?`. Useful, for example, for quantitnes. Each condition value may be a [literal message](#literal-messages), a [parametrized message](#parametrized-messages) or a [multiline message](#multiline-messages). All condition values share the same parameters. 214 | 215 | Conditions and their respective associated message are specified as key-value pairs in an object. An empty key can be specified to indicate the "else" message, the message to be used if none of the conditions evaluate to true. If no else message is specified, an else branch is added with a call to panic. Conditions are writen in the code as they're found in the json, in the same order and copying each one into the if statement. 216 | 217 | ```json 218 | { 219 | "?key": { 220 | "messages > 100": "You have a lot of new messages ({messages:int})!", 221 | "messages > 10": "You have {messages} new messages", 222 | "messages == 1": "You have one new message", 223 | "messages == 0": "No new messages" 224 | }, 225 | "?key-with-else-branch": { 226 | "amount > 0": "The amount is positive ({amount:int})", 227 | "amount < 0": "The amount is negative ({amount})", 228 | "": "The amount is 0" 229 | } 230 | } 231 | ``` 232 | 233 |
234 | Generated code 235 | 236 | ```go 237 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 238 | * Any changes to this file will be lost on the next tool run */ 239 | 240 | package lang 241 | 242 | import ( 243 | "fmt" 244 | "strings" 245 | ) 246 | 247 | func MessagesFor(tag string) (Messages, bool) { 248 | switch strings.ReplaceAll(tag, "_", "-") { 249 | case "en-EN": 250 | return en_EN_Messages{}, true 251 | } 252 | return nil, false 253 | } 254 | 255 | func MessagesForMust(tag string) Messages { 256 | switch strings.ReplaceAll(tag, "_", "-") { 257 | case "en-EN": 258 | return en_EN_Messages{} 259 | } 260 | panic(fmt.Errorf("unknwon language tag: " + tag)) 261 | } 262 | 263 | func MessagesForOrDefault(tag string) Messages { 264 | switch strings.ReplaceAll(tag, "_", "-") { 265 | case "en-EN": 266 | return en_EN_Messages{} 267 | } 268 | return en_EN_Messages{} 269 | } 270 | 271 | type Messages interface { 272 | Key(messages int) string 273 | KeyWithElseBranch(amount int) string 274 | } 275 | 276 | type en_EN_Messages struct{} 277 | 278 | func (en_EN_Messages) Key(messages int) string { 279 | if messages > 100 { 280 | return fmt.Sprintf("You have a lot of new messages (%d)!", messages) 281 | } else if messages > 10 { 282 | return fmt.Sprintf("You have %d new messages", messages) 283 | } else if messages == 1 { 284 | return "You have one new message" 285 | } else if messages == 0 { 286 | return "No new messages" 287 | } else { 288 | panic(fmt.Errorf("no condition was true in conditional")) 289 | } 290 | } 291 | func (en_EN_Messages) KeyWithElseBranch(amount int) string { 292 | if amount > 0 { 293 | return fmt.Sprintf("The amount is positive (%d)", amount) 294 | } else if amount < 0 { 295 | return fmt.Sprintf("The amount is negative (%d)", amount) 296 | } else { 297 | return "The amount is 0" 298 | } 299 | } 300 | ``` 301 | 302 |
303 | 304 | ## Message nesting / Grouping messages 305 | 306 | Messages can be grouped or nested by nesting json objets. 307 | By nesting messages, a separation is done and each group of messages is placed into their own interface and structs. 308 | This way autocompletion of messages is not polluted with hunderds of messages and its easyer to navigate them. 309 | It also means that each part of a program can receive only the interface with the messages it needs. 310 | 311 | ```json 312 | { 313 | "key-level-1": { 314 | "key-level-2": { 315 | "key-level-3": "Assume this message is in the file `en-EN.json`" 316 | } 317 | } 318 | } 319 | ``` 320 | 321 | To get the message we need to call `messages.KeyLevel1().KeyLevel2().KeyLevel3()`. 322 | 323 | Another way of nesting messages is using folders to nest files. 324 | 325 | ```json 326 | { 327 | "key-level-3": "Assume this message is in the file `key-level-1/key-level-2/en-EN.json`" 328 | } 329 | ``` 330 | 331 | To get this message we also need to call `messages.KeyLevel1().KeyLevel2().KeyLevel3()`. 332 | 333 | Nested levels can be defined by using nested json objects, nesting files in folders or both. 334 | 335 |
336 | Generated code 337 | 338 | ```go 339 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 340 | * Any changes to this file will be lost on the next tool run */ 341 | 342 | package lang 343 | 344 | import ( 345 | "fmt" 346 | "strings" 347 | ) 348 | 349 | func MessagesFor(tag string) (Messages, bool) { 350 | switch strings.ReplaceAll(tag, "_", "-") { 351 | case "en-EN": 352 | return en_EN_Messages{}, true 353 | } 354 | return nil, false 355 | } 356 | 357 | func MessagesForMust(tag string) Messages { 358 | switch strings.ReplaceAll(tag, "_", "-") { 359 | case "en-EN": 360 | return en_EN_Messages{} 361 | } 362 | panic(fmt.Errorf("unknwon language tag: " + tag)) 363 | } 364 | 365 | func MessagesForOrDefault(tag string) Messages { 366 | switch strings.ReplaceAll(tag, "_", "-") { 367 | case "en-EN": 368 | return en_EN_Messages{} 369 | } 370 | return en_EN_Messages{} 371 | } 372 | 373 | type Messages interface { 374 | KeyLevel1() keyLevel1 375 | } 376 | type keyLevel1 interface { 377 | KeyLevel2() keyLevel1keyLevel2 378 | } 379 | type keyLevel1keyLevel2 interface { 380 | KeyLevel3() string 381 | } 382 | 383 | type en_EN_Messages struct{} 384 | 385 | func (en_EN_Messages) KeyLevel1() keyLevel1 { 386 | return en_EN_keyLevel1{} 387 | } 388 | 389 | type en_EN_keyLevel1 struct{} 390 | 391 | func (en_EN_keyLevel1) KeyLevel2() keyLevel1keyLevel2 { 392 | return en_EN_keyLevel1keyLevel2{} 393 | } 394 | 395 | type en_EN_keyLevel1keyLevel2 struct{} 396 | 397 | func (en_EN_keyLevel1keyLevel2) KeyLevel3() string { 398 | return "Assume this message is in the file `en-EN.json`" 399 | } 400 | ``` 401 | 402 |
403 | 404 | ### Interface renaming 405 | 406 | By default the name used to create the interface of nested groups of messages is the full path of the group of messages. 407 | In the example above, 3 interfaces would have been generated: `Messages`, `keyLevel1` and `keyLevel1keyLevel2` (if `public-non-named-interfaces` is specified when generating the code, the names would been `Messages`, `KeyLevel1` and `KeyLevel1KeyLevel2` to make all of them public). 408 | 409 | When nesting too much, these interface names can get long. 410 | Since we may want to use some of the generated interfaces in our code, we can provide a name for them in the json by putting `:name` after the key of the group of messages. 411 | 412 | ```json 413 | { 414 | "key-level-1:l1": { 415 | "key-level-2:l2": { 416 | "key-level-3": "Assume this message is in the file `en-EN.json`" 417 | } 418 | } 419 | } 420 | ``` 421 | 422 | In this case since we renamed the keys to `l1` and `l2` the generated interfaces will be named `Messages`, `L1` and `L2`. 423 | If we want to rename a group specified by folders, since `:` is not a valid character for folder names, we can rename the key in the parent group of messages with an empty json object. 424 | 425 | ```json 426 | { 427 | "key-level-3": "Assume this message is in the file `key-level-1/key-level-2/en-EN.json`" 428 | } 429 | ``` 430 | 431 | ```json 432 | { 433 | "key-level-1:l1": { 434 | "key-level-2:l2": {} 435 | } 436 | } 437 | ``` 438 | 439 | Here we renamed both groups of messages even though these groups are defined by folders and not by nesting json objects. 440 | 441 |
442 | Generated code 443 | 444 | ```go 445 | /** Code generated using https://github.com/MrNemo64/go-n-i18n 446 | * Any changes to this file will be lost on the next tool run */ 447 | 448 | package lang 449 | 450 | import ( 451 | "fmt" 452 | "strings" 453 | ) 454 | 455 | func MessagesFor(tag string) (Messages, bool) { 456 | switch strings.ReplaceAll(tag, "_", "-") { 457 | case "en-EN": 458 | return en_EN_Messages{}, true 459 | } 460 | return nil, false 461 | } 462 | 463 | func MessagesForMust(tag string) Messages { 464 | switch strings.ReplaceAll(tag, "_", "-") { 465 | case "en-EN": 466 | return en_EN_Messages{} 467 | } 468 | panic(fmt.Errorf("unknwon language tag: " + tag)) 469 | } 470 | 471 | func MessagesForOrDefault(tag string) Messages { 472 | switch strings.ReplaceAll(tag, "_", "-") { 473 | case "en-EN": 474 | return en_EN_Messages{} 475 | } 476 | return en_EN_Messages{} 477 | } 478 | 479 | type Messages interface { 480 | KeyLevel1() L1 481 | } 482 | type L1 interface { 483 | KeyLevel2() L2 484 | } 485 | type L2 interface { 486 | KeyLevel3() string 487 | } 488 | 489 | type en_EN_Messages struct{} 490 | 491 | func (en_EN_Messages) KeyLevel1() L1 { 492 | return en_EN_L1{} 493 | } 494 | 495 | type en_EN_L1 struct{} 496 | 497 | func (en_EN_L1) KeyLevel2() L2 { 498 | return en_EN_L2{} 499 | } 500 | 501 | type en_EN_L2 struct{} 502 | 503 | func (en_EN_L2) KeyLevel3() string { 504 | return "Assume this message is in the file `en-EN.json`" 505 | } 506 | ``` 507 | 508 |
509 | --------------------------------------------------------------------------------