Skip to content

Add dictionary in generated mfd file #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,21 @@
[xml-vt](/generators/xml-vt) - генератор неймспейсов и сущностей в них для vt-часть проекта.
[xml-lang](/generators/xml-lang) - генератор языковых xml файлов.

#### Кастомизация переводов через `<dict>`

Для гибкой настройки и переопределения стандартных переводов в `.mfd` файле можно использовать секцию `<Dictionary>`. Это позволяет изменять или добавлять переводы для ключей, не внося изменений в код генератора.
Генератор считывает этот блок и обновляет им глобальную карту переводов.
Пример использования в `.mfd` файле:
```xml
<Project xmlns:xsi="" xmlns:xsd="">
<Dictionary>
<user>Пользователь (кастомный)</user>
<myCustomButton>Моя новая кнопка</myCustomButton>
</Dictionary>
</Project>
```
В сгенерированном коде вызов `Translate(RuLang, "user")` вернет "Пользователь (кастомный)".

**Вторая группа:**
[model](/generators/model) - генератор golang модели для взаимодействия с базой данных. В качестве источника данных используется результат xml генератора.
[repo](/generators/repo) - генератор golang репозиториев для манипуляций с данными в базе с помощью моделей.
Expand Down
1 change: 1 addition & 0 deletions generators/xml-lang/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ func (g *Generator) Generate() error {
g.options.Namespaces = project.VTNamespaceNames()
}

mfd.AddCustomTranslations(project.Dictionary)
langs := mergeLangs(project.Languages, g.options.Languages)

translations, err := mfd.LoadTranslations(g.options.MFDPath, langs)
Expand Down
57 changes: 56 additions & 1 deletion mfd/dict_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package mfd

import "testing"
import (
"encoding/xml"
"testing"
)

func TestTranslate(t *testing.T) {
var testCases = []struct {
Expand All @@ -24,3 +27,55 @@ func TestTranslate(t *testing.T) {
}
}
}

func TestAddCustomTranslations(t *testing.T) {
var testCases = []struct {
name string
in string
dict *Dictionary
want string
}{
{
"with updated word",
"user",
&Dictionary{
Entries: []Entry{
{XMLName: xml.Name{Local: "user"}, Value: "Пользователь (Обновленный)"},
},
},
"Пользователь (Обновленный)",
},
{
"with new word",
"newKey",
&Dictionary{
Entries: []Entry{
{XMLName: xml.Name{Local: "newKey"}, Value: "Изображение (Обновленное)"},
},
},
"Изображение (Обновленное)",
},
{
"with empty dict",
"",
&Dictionary{
Entries: []Entry{},
},
"",
},
{
"with nil dict",
"",
nil,
"",
},
}
for _, tt := range testCases {
old := Translate(RuLang, tt.in)
AddCustomTranslations(tt.dict)
updated := Translate(RuLang, tt.in)
if updated != tt.want {
t.Errorf("%v: got %q, want %q", tt.in, old, tt.want)
}
}
}
8 changes: 8 additions & 0 deletions mfd/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,11 @@ func LoadTemplate(path, def string) (string, error) {

return string(contents), nil
}

func AddCustomTranslations(d *Dictionary) {
if d != nil {
for _, e := range d.Entries {
presetsTranslations[RuLang][e.XMLName.Local] = e.Value
}
}
}
10 changes: 10 additions & 0 deletions mfd/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,22 @@ type Project struct {
Languages []string `xml:"Languages>string" json:"languages"`
GoPGVer int `xml:"GoPGVer" json:"goPGVer"`
CustomTypes CustomTypes `xml:"CustomTypes>CustomType,omitempty" json:"customTypes,omitempty"`
Dictionary *Dictionary `xml:"Dictionary" json:"dict,omitempty"`

Namespaces []*Namespace `xml:"-" json:"-"`
VTNamespaces []*VTNamespace `xml:"-" json:"-"`
NSMapping []NSMapping `xml:"-" json:"namespaces"`
}

type Dictionary struct {
Entries []Entry `xml:",any"`
}

type Entry struct {
XMLName xml.Name
Value string `xml:",chardata"`
}

func NewProject(name string, goPGVer int) *Project {
return &Project{
Name: name,
Expand Down
Loading