Skip to content

Commit

Permalink
feat: Add yao sui trans command for automatic translation support
Browse files Browse the repository at this point in the history
  • Loading branch information
trheyi committed Jul 15, 2024
1 parent ef8b802 commit 931394b
Show file tree
Hide file tree
Showing 8 changed files with 190 additions and 6 deletions.
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ func init() {
// Sui
suiCmd.AddCommand(sui.WatchCmd)
suiCmd.AddCommand(sui.BuildCmd)
suiCmd.AddCommand(sui.TransCmd)

rootCmd.AddCommand(
versionCmd,
Expand Down
2 changes: 1 addition & 1 deletion cmd/sui/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var BuildCmd = &cobra.Command{
Long: L("Build the template"),
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 2 {
fmt.Fprintln(os.Stderr, color.RedString(L("yao cui build <sui> <template> [data]")))
fmt.Fprintln(os.Stderr, color.RedString(L("yao sui build <sui> <template> [data]")))
return
}

Expand Down
4 changes: 4 additions & 0 deletions cmd/sui/sui.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package sui

var data string
var locales string
var debug bool

func init() {
WatchCmd.PersistentFlags().StringVarP(&data, "data", "d", "::{}", L("Session Data"))
BuildCmd.PersistentFlags().StringVarP(&data, "data", "d", "::{}", L("Session Data"))
BuildCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, L("Debug mode"))
TransCmd.PersistentFlags().StringVarP(&data, "data", "d", "::{}", L("Session Data"))
TransCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false, L("Debug mode"))
TransCmd.PersistentFlags().StringVarP(&locales, "locales", "l", "", L("Locales, separated by commas"))
}
168 changes: 168 additions & 0 deletions cmd/sui/trans.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package sui

import (
"fmt"
"os"
"path/filepath"
"strings"
"time"

"github.com/fatih/color"
"github.com/google/uuid"
jsoniter "github.com/json-iterator/go"
"github.com/spf13/cobra"
"github.com/yaoapp/gou/session"
"github.com/yaoapp/yao/config"
"github.com/yaoapp/yao/engine"
"github.com/yaoapp/yao/sui/core"
"golang.org/x/text/language"
)

// TransCmd command
var TransCmd = &cobra.Command{
Use: "trans",
Short: L("Translate the template"),
Long: L("Translate the template"),
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 2 {
fmt.Fprintln(os.Stderr, color.RedString(L("yao sui trans <sui> <template> [data]")))
return
}

Boot()

cfg := config.Conf
err := engine.Load(cfg, engine.LoadOption{Action: "sui.trans"})
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}

id := args[0]
template := args[1]

var sessionData map[string]interface{}
err = jsoniter.UnmarshalFromString(strings.TrimPrefix(data, "::"), &sessionData)
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}

sid := uuid.New().String()
if sessionData != nil && len(sessionData) > 0 {
session.Global().ID(sid).SetMany(sessionData)
}

sui, has := core.SUIs[id]
if !has {
fmt.Fprintf(os.Stderr, color.RedString(("the sui " + id + " does not exist")))
return
}
sui.WithSid(sid)

tmpl, err := sui.GetTemplate(template)
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}

// -
publicRoot, err := sui.PublicRootWithSid(sid)
localeRoot := filepath.Join(tmpl.GetRoot(), "__locales")
definedLocales := tmpl.Locales()
assetRoot := filepath.Join(publicRoot, "assets")
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}

fmt.Println(color.WhiteString("-----------------------"))
fmt.Println(color.WhiteString("Public Root: /public%s", publicRoot))
fmt.Println(color.WhiteString(" Template: %s", tmpl.GetRoot()))
fmt.Println(color.WhiteString(" Session: %s", strings.TrimLeft(data, "::")))
fmt.Println(color.WhiteString("-----------------------"))

fmt.Println("")
fmt.Println(color.GreenString("Language packs:"))
fmt.Println(color.WhiteString("-----------------------"))
for _, locale := range definedLocales {
if locale.Default {
continue
}
path := filepath.Join(localeRoot, locale.Value)
fmt.Println(color.WhiteString(" %s:\t%s", locale.Label, path))
}
fmt.Println(color.WhiteString("-----------------------"))
fmt.Println("")

// Timecost
start := time.Now()
minify := true
mode := "production"
if debug {
minify = false
mode = "development"
}

option := core.BuildOption{SSR: true, AssetRoot: assetRoot, ExecScripts: true, ScriptMinify: minify, StyleMinify: minify}

// locales filter
if locales != "" {
fmt.Println("")
fmt.Println(color.GreenString("Translate locales:"))
fmt.Println(color.WhiteString("-----------------------"))
localeList := strings.Split(locales, ",")
option.Locales = []string{}
for _, locale := range localeList {
locale = strings.ToLower(strings.TrimSpace(locale))
label := language.Make(locale).String()
option.Locales = append(option.Locales, locale)
path := filepath.Join(localeRoot, locale)
fmt.Println(color.WhiteString(" %s:\t%s", label, path))
}
fmt.Println(color.WhiteString("-----------------------"))
fmt.Println("")
}

warnings, err := tmpl.Trans(&option)
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}
end := time.Now()
timecost := end.Sub(start).Truncate(time.Millisecond)
if debug {
fmt.Println(color.YellowString("Translate succeeded for %s in %s", mode, timecost))
return
}
if len(warnings) > 0 {
for _, warning := range warnings {
fmt.Println(color.YellowString("Warning: %s", warning))
}
}

fmt.Println(color.GreenString("Translate succeeded for %s in %s", mode, timecost))

// build the template
fmt.Println("Start building the template")
start = time.Now()
warnings, err = tmpl.Build(&option)
if err != nil {
fmt.Fprintln(os.Stderr, color.RedString(err.Error()))
return
}

end = time.Now()
timecost = end.Sub(start).Truncate(time.Millisecond)
if debug {
fmt.Println(color.YellowString("Build succeeded for %s in %s", mode, timecost))
return
}
if len(warnings) > 0 {
for _, warning := range warnings {
fmt.Println(color.YellowString("Warning: %s", warning))
}
}
fmt.Println(color.GreenString("Build succeeded for %s in %s", mode, timecost))
},
}
2 changes: 1 addition & 1 deletion cmd/sui/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ var WatchCmd = &cobra.Command{
Long: L("Auto-build when the template file changes"),
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 2 {
fmt.Fprintln(os.Stderr, color.RedString(L("yao cui watch <sui> <template> [data]")))
fmt.Fprintln(os.Stderr, color.RedString(L("yao sui watch <sui> <template> [data]")))
return
}

Expand Down
1 change: 1 addition & 0 deletions sui/core/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,7 @@ type BuildOption struct {
ScriptMinify bool `json:"scriptminify,omitempty"`
StyleMinify bool `json:"styleminify,omitempty"`
ExecScripts bool `json:"exec_scripts,omitempty"`
Locales []string `json:"locales,omitempty"`
}

// Request is the struct for the request
Expand Down
16 changes: 13 additions & 3 deletions sui/storages/local/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/yaoapp/gou/process"
"github.com/yaoapp/kun/log"
"github.com/yaoapp/yao/sui/core"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
)

Expand Down Expand Up @@ -346,7 +347,7 @@ func (page *Page) Trans(globalCtx *core.GlobalBuildContext, option *core.BuildOp
warnings := []string{}
ctx := core.NewBuildContext(globalCtx)

_, messages, err := page.Page.CompileAsComponent(ctx, option)
_, messages, err := page.Page.Compile(ctx, option)
if err != nil {
return warnings, err
}
Expand All @@ -356,7 +357,7 @@ func (page *Page) Trans(globalCtx *core.GlobalBuildContext, option *core.BuildOp
}

// Tranlate the locale files
err = page.writeLocaleSource(ctx)
err = page.writeLocaleSource(ctx, option)
return warnings, err
}

Expand Down Expand Up @@ -471,10 +472,19 @@ func (page *Page) locale(name string, pageOnly ...bool) core.Locale {
return locale
}

func (page *Page) writeLocaleSource(ctx *core.BuildContext) error {
func (page *Page) writeLocaleSource(ctx *core.BuildContext, option *core.BuildOption) error {

locales := page.tmpl.Locales()
translations := ctx.GetTranslations()

if option.Locales != nil && len(option.Locales) > 0 {
locales = []core.SelectOption{}
for _, lc := range option.Locales {
label := language.Make(lc).String()
locales = append(locales, core.SelectOption{Value: lc, Label: label})
}
}

for _, lc := range locales {
if lc.Default {
continue
Expand Down
2 changes: 1 addition & 1 deletion sui/storages/local/local_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ func TestGetTemplates(t *testing.T) {
assert.Len(t, webTmpls[0].Themes(), 2)
assert.Len(t, webTmpls[0].Locales(), 4)
assert.Len(t, webTmpls[0].(*Template).Template.Themes, 2)
assert.Len(t, webTmpls[0].(*Template).Template.Locales, 2)
assert.Len(t, webTmpls[0].(*Template).Template.Locales, 4)
}

func TestGetTemplate(t *testing.T) {
Expand Down

0 comments on commit 931394b

Please sign in to comment.