Skip to content

Commit

Permalink
Merge pull request #29 from lazygophers/luoxin
Browse files Browse the repository at this point in the history
远端配置加载
  • Loading branch information
Luoxin authored Jun 14, 2024
2 parents 8bd8851 + 7ab31a3 commit f8c53c2
Show file tree
Hide file tree
Showing 148 changed files with 843 additions and 25 deletions.
428 changes: 428 additions & 0 deletions cli/sync.go

Large diffs are not rendered by default.

110 changes: 110 additions & 0 deletions cli/sync_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package cli_test

import (
"github.com/lazygophers/codegen/state"
"github.com/lazygophers/log"
"reflect"
"testing"
)

func TestSyncMerge(t *testing.T) {
c := &state.Cfg{
Template: &state.CfgTemplate{
Editorconfig: "222",
},
}

//nc := state.Cfg{
// Template: &state.CfgTemplate{
// Editorconfig: "1",
// Orm: "2",
// TableName: "3",
// TableField: "4",
// Proto: &state.CfgProto{
// Action: map[string]*state.CfgProtoAction{
// "1": {
// Name: "1",
// Req: "2",
// Resp: "3",
// },
// },
// Rpc: "4",
// },
// Impl: &state.CfgImpl{
// Action: nil,
// Impl: "4",
// Path: "5",
// Route: "54",
// },
// Main: "1",
// Conf: "3",
// State: &state.CfgTemplateState{
// Table: "1",
// Conf: "2",
// Cache: "2",
// State: "e",
// I18n: "d",
// },
// Goreleaser: "s",
// Makefile: "w",
// Golangci: "w",
// Gitignore: "q",
// Dockerignore: "s",
// I18nConst: "c",
// },
//}

ncv := reflect.ValueOf(c.Template)
for ncv.Kind() == reflect.Ptr {
ncv = ncv.Elem()
}

var deep func(dst reflect.Value) error
deep = func(dst reflect.Value) error {
for dst.Kind() == reflect.Ptr {
dst = dst.Elem()
}

if !dst.IsValid() {
return nil
}

if dst.IsZero() {
return nil
}

switch dst.Kind() {
case reflect.String:
dst.SetString("sss")

case reflect.Struct:
for i := 0; i < dst.NumField(); i++ {
if err := deep(dst.Field(i)); err != nil {
return err
}
}

case reflect.Map:
for _, key := range dst.MapKeys() {
if err := deep(dst.MapIndex(key)); err != nil {
return err
}
}

case reflect.Slice:
for i := 0; i < dst.Len(); i++ {
if err := deep(dst.Index(i)); err != nil {
return err
}
}

default:
log.Panicf("unsupported type %s", dst.Kind())
}

return nil
}

t.Log(deep(ncv))
t.Log(ncv.Interface())
}
20 changes: 4 additions & 16 deletions i18n/localize.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package i18n

import (
"bytes"
"github.com/lazygophers/log"
"github.com/lazygophers/utils/json"
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
"io"
"os"
"strings"
)
Expand All @@ -26,27 +24,17 @@ var localizer = map[string]Localizer{
var (
jsonLocalizer = NewLocalizerHandle(
func(path string, v any) (err error) {
buf, err := json.Marshal(v)
if err != nil {
log.Errorf("err:%v", err)
return err
}

var b bytes.Buffer
err = json.Indent(&b, buf, "", "\t")
if err != nil {
log.Errorf("err:%v", err)
return err
}

file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
log.Errorf("err:%v", err)
return err
}
defer file.Close()

_, err = io.Copy(file, &b)
encoder := json.NewEncoder(file)
encoder.SetIndent("", "\t")

err = encoder.Encode(v)
if err != nil {
log.Errorf("err:%v", err)
return err
Expand Down
1 change: 0 additions & 1 deletion i18n/translater.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ func NewTransacterGoogleFree() *TransacterGoogleFree {
request.SetHeader("User-Agent", fake.RandomUserAgent())
return nil
}).
SetProxy(os.Getenv("HTTPS_PROXY")).
SetQueryParams(map[string]string{
"client": "gtx",
"ie": "UTF-8",
Expand Down
21 changes: 15 additions & 6 deletions state/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import (
)

type CfgSync struct {
Remote string `json:"remote,omitempty" yaml:"remote,omitempty" toml:"remote,omitempty"`
Remote string `json:"remote,omitempty" yaml:"remote,omitempty" toml:"remote,omitempty"`
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty" toml:"headers,omitempty"`

CacheTemplatePath string `json:"cache-template-path,omitempty" yaml:"cache-template-path,omitempty" toml:"cache-template-path,omitempty"`
}

Expand Down Expand Up @@ -411,7 +413,7 @@ var Config = new(Cfg)

type Unmarshaler func(reader io.Reader, v interface{}) error

var supportedExt = map[string]Unmarshaler{
var SupportedExt = map[string]Unmarshaler{
"json": func(reader io.Reader, v interface{}) error {
return json.NewDecoder(reader).Decode(v)
},
Expand All @@ -426,8 +428,15 @@ var supportedExt = map[string]Unmarshaler{
},
}

func tryFindConfigPath(baseDir string) string {
for ext := range supportedExt {
var supportedExts = [...]string{
"yaml",
"yml",
"json",
"toml",
}

func TryFindConfigPath(baseDir string) string {
for _, ext := range supportedExts {
file := filepath.Join(baseDir, "codegen.cfg."+ext)
if osx.IsFile(file) {
return file
Expand Down Expand Up @@ -455,7 +464,7 @@ func LoadConfig() error {
// NOTE: 从系统目录中获取
if path == "" {
log.Warnf("Try to load config from system folder(%s)", pterm.Gray(filepath.Join(runtime.UserConfigDir(), app.Organization)))
path = tryFindConfigPath(filepath.Join(runtime.UserConfigDir(), app.Organization))
path = TryFindConfigPath(filepath.Join(runtime.UserConfigDir(), app.Organization))
}

file, err := os.Open(path)
Expand All @@ -473,7 +482,7 @@ func LoadConfig() error {
pterm.Success.Printfln("Config file found, use config from %s", path)

ext := filepath.Ext(path)
if unmarshaler, ok := supportedExt[ext[1:]]; ok {
if unmarshaler, ok := SupportedExt[ext[1:]]; ok {
err = unmarshaler(file, &Config)
if err != nil {
log.Errorf("err:%v", err)
Expand Down
4 changes: 3 additions & 1 deletion state/i18n.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion state/lazy_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func LoadLazeConfig(path string) error {
pterm.Warning.Printfln("%s is not found, use default", path)
} else {
defer file.Close()
err = supportedExt["yaml"](file, &LazyConfig)
err = SupportedExt["yaml"](file, &LazyConfig)
if err != nil {
log.Errorf("err:%v", err)
return err
Expand Down
2 changes: 2 additions & 0 deletions state/localize/af.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: '''n Gereedskapstel vir lui mense'
sync:
flags:
password: Wagwoord gebruik om verifikasie te versoek
template-path: Sjabloon sinchronisasie pad
username: Gebruikernaam gebruik om verifikasie te versoek
long: Sinkroniseer die konfigurasie vanaf die afgeleë kant en voeg dit saam met die plaaslike konfigurasie Die sjabloonlêer word terselfdertyd tydens sinchronisasie ondersteun (indien gekonfigureer).
short: Sinkroniseer konfigurasie vanaf afstandbeheer
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/ak.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Adwinnade a wɔde asi hɔ ama anihafo
sync:
flags:
password: Password a wɔde bisa sɛ wɔmfa nyɛ nokware
template-path: Template synchronization kwan no so
username: Edin a wɔde di dwuma de bisa sɛ wɔmfa nyɛ nokware
long: Fa nhyehyeɛ no yɛ pɛ firi akyirikyiri awieeɛ na fa bom kɔ mpɔtam hɔ nhyehyeɛ no mu Wɔboa template fael no wɔ berɛ korɔ no ara mu wɔ synchronization mu (sɛ wɔahyehyɛ a)
short: Synchronize nhyehyeɛ fi akyirikyiri
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/am.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: ለሰነፎች የተዘጋጀ መሳሪያ
sync:
flags:
password: ማረጋገጫ ለመጠየቅ የሚያገለግል የይለፍ ቃል
template-path: የአብነት ማመሳሰል መንገድ
username: የተጠቃሚ ስም ማረጋገጫ ለመጠየቅ ጥቅም ላይ ይውላል
long: አወቃቀሩን ከርቀት ጫፍ ያመሳስሉ እና ወደ አካባቢያዊ ውቅር ያዋህዱት የአብነት ፋይሉ በማመሳሰል ጊዜ (ከተዋቀረ) በተመሳሳይ ጊዜ ይደገፋል።
short: ውቅርን ከርቀት ያመሳስሉ።
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/ar.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: مجموعة أدوات للأشخاص الكسالى
sync:
flags:
password: كلمة المرور المستخدمة لطلب التحقق
template-path: مسار مزامنة القالب
username: اسم المستخدم المستخدم لطلب التحقق
long: قم بمزامنة التكوين من الطرف البعيد ودمجه في التكوين المحلي. يتم دعم ملف القالب في نفس الوقت أثناء المزامنة (إذا تم تكوينه).
short: مزامنة التكوين من جهاز التحكم عن بعد
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/as.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: এলেহুৱা মানুহৰ বাবে এটা সঁজুলিৰ ছেট
sync:
flags:
password: সত্যাপনৰ অনুৰোধ কৰিবলৈ ব্যৱহাৰ কৰা পাছৱৰ্ড
template-path: সাঁচ সমন্বয় পথ
username: সত্যাপনৰ অনুৰোধ কৰিবলৈ ব্যৱহাৰ কৰা ব্যৱহাৰকাৰীৰ নাম
long: দূৰৱৰ্তী শেষৰ পৰা বিন্যাস সমন্বয় কৰক আৰু ইয়াক স্থানীয় বিন্যাসত একত্ৰিত কৰক সাঁচ নথিপত্ৰ সমন্বয়ৰ সময়ত একে সময়তে সমৰ্থিত (যদি বিন্যাস কৰা হৈছে) ।
short: দূৰৱৰ্তী পৰা বিন্যাস সমন্বয় কৰক
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/ay.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Mä herramienta wakicht’ata q’añu jaqinakataki
sync:
flags:
password: Contraseña ukaxa chiqapa mayiwi lurañataki apnaqatawa
template-path: Plantilla sincronización thakhi
username: Usuario sutix chiqapar uñjañ mayiñatakiw apnaqasi
long: Jaya tukuyatat configuración ukar sincronización ukat local configuración ukar mayacht’aña Plantilla arxiwux sincronización ukanx pachpa pachan yanapt’atawa (configuración ukhamächi ukhaxa).
short: Jayankir chiqat configuración ukar sincronización luraña
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/az.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Tənbəl insanlar üçün alət dəsti
sync:
flags:
password: Doğrulama sorğusu üçün istifadə edilən parol
template-path: Şablon sinxronizasiya yolu
username: Doğrulama sorğusu üçün istifadə edilən istifadəçi adı
long: Konfiqurasiyanı uzaq uçdan sinxronlaşdırın və onu yerli konfiqurasiyaya birləşdirin Şablon faylı sinxronizasiya zamanı eyni vaxtda dəstəklənir (əgər konfiqurasiya olunubsa).
short: Uzaqdan konfiqurasiyanı sinxronlaşdırın
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/be.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Набор інструментаў для лянівых
sync:
flags:
password: Пароль, які выкарыстоўваецца для запыту праверкі
template-path: Шлях сінхранізацыі шаблона
username: Імя карыстальніка, якое выкарыстоўваецца для запыту праверкі
long: Сінхранізацыя канфігурацыі з аддаленага канца і аб'яднанне яе з лакальнай канфігурацыяй. Файл шаблону падтрымліваецца адначасова падчас сінхранізацыі (калі наладжана).
short: Сінхранізацыя канфігурацыі з дыстанцыйнага доступу
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/bg.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Комплект инструменти за мързеливи хора
sync:
flags:
password: Парола, използвана за заявка за потвърждение
template-path: Път за синхронизиране на шаблона
username: Потребителско име, използвано за заявка за потвърждение
long: Синхронизирайте конфигурацията от отдалечения край и я обединете с локалната конфигурация. Файлът на шаблона се поддържа едновременно по време на синхронизиране (ако е конфигуриран).
short: Синхронизирайте конфигурацията от дистанционно
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/bho.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: आलसी लोग खातिर सेट एगो औजार
sync:
flags:
password: सत्यापन के अनुरोध करे खातिर इस्तेमाल होखे वाला पासवर्ड
template-path: टेम्पलेट सिंक्रनाइजेशन के रास्ता बा
username: सत्यापन के अनुरोध करे खातिर इस्तेमाल होखे वाला यूजरनेम
long: रिमोट एंड से कॉन्फ़िगरेशन के सिंक्रनाइज़ करीं आ एकरा के लोकल कॉन्फ़िगरेशन में मर्ज करीं सिंक्रनाइजेशन के दौरान टेम्पलेट फाइल के सपोर्ट कइल जाला (अगर कॉन्फ़िगर कइल गइल होखे)।
short: रिमोट से कॉन्फ़िगरेशन के सिंक्रनाइज़ करीं
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/bm.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Baarakɛminɛn min sigilen don mɔgɔ sɛgɛnbaliw ye
sync:
flags:
password: Password min bɛ kɛ ka sɛgɛsɛgɛli ɲini
template-path: Template synchronisation sira
username: Baarakɛla tɔgɔ min bɛ Kɛ ka sɛgɛsɛgɛli ɲini
long: Labɛnni bɛ ɲɔgɔn sɔrɔ ka bɔ yɔrɔjan laban na k’a fara ɲɔgɔn kan sigida labɛncogo la Jatebla filen bɛ dɛmɛ waati kelen na sinsinni waati (ni labɛnna).
short: Labɛncogo sinsinni ka bɔ yɔrɔjan na
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/bn.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: অলস মানুষের জন্য একটি টুল সেট
sync:
flags:
password: যাচাইকরণের অনুরোধ করতে ব্যবহৃত পাসওয়ার্ড
template-path: টেমপ্লেট সিঙ্ক্রোনাইজেশন পাথ
username: যাচাইকরণের অনুরোধ করতে ব্যবহৃত ব্যবহারকারীর নাম
long: দূরবর্তী প্রান্ত থেকে কনফিগারেশন সিঙ্ক্রোনাইজ করুন এবং স্থানীয় কনফিগারেশনে একত্রিত করুন টেমপ্লেট ফাইলটি সিঙ্ক্রোনাইজেশনের সময় একই সময়ে সমর্থিত হয় (যদি কনফিগার করা হয়)।
short: রিমোট থেকে কনফিগারেশন সিঙ্ক্রোনাইজ করুন
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/bs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Set alata za lijene ljude
sync:
flags:
password: Lozinka korištena za traženje verifikacije
template-path: Putanja za sinhronizaciju šablona
username: Korisničko ime korišteno za traženje verifikacije
long: Sinhronizirajte konfiguraciju sa udaljenog kraja i spojite je u lokalnu konfiguraciju.
short: Sinhronizirajte konfiguraciju s daljinskog
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/ca.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Un conjunt d'eines per a mandrosos
sync:
flags:
password: Contrasenya utilitzada per sol·licitar la verificació
template-path: Camí de sincronització de plantilles
username: Nom d'usuari utilitzat per sol·licitar la verificació
long: Sincronitzeu la configuració des de l'extrem remot i fusioneu-la amb la configuració local. El fitxer de plantilla és compatible al mateix temps durant la sincronització (si està configurat).
short: Sincronitza la configuració des del control remot
up-mod:
Expand Down
2 changes: 2 additions & 0 deletions state/localize/ceb.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ cli:
short: Usa ka set nga himan alang sa mga tapolan
sync:
flags:
password: Ang password nga gigamit sa pagpangayo og verification
template-path: Dalan sa pag-synchronize sa template
username: Username nga gigamit sa pagpangayo og verification
long: I-synchronize ang configuration gikan sa hilit nga tumoy ug iusa kini ngadto sa lokal nga configuration Ang template file gisuportahan sa samang higayon atol sa pag-synchronize (kon gi-configure)
short: I-synchronize ang configuration gikan sa hilit
up-mod:
Expand Down
Loading

0 comments on commit f8c53c2

Please sign in to comment.