refactor(tools): modularize CLI with urfave/cli/v2, externalise template metadata

- Split monolithic build-preview.go into modular packages:
  tools.go (entry), cli/ (list/create/delete/preview commands),
  config/ (JSON loading), preview/ (rendering engine, funcs, locale)
- Extract all template metadata into data/templates_config.json
  as single source of truth — no hardcoded template data in Go
- Replace hand-rolled CLI parsing with github.com/urfave/cli/v2
- Add sensible defaults for --folder (../themes) and --config
  (./data/templates_config.json) — most commands now run bare
- Add type-coercing gt/lt/ge/le template funcs for JSON float64
- Fix AppUrl to gitea.com matching official template convention
- rendered.js now exports __REGISTRY__ and __PARAMS__ alongside
  __RENDERED__ — preview/index.html reads all from single source
- Cross-validate all 11 template data contexts against official
  Gitea source (services/mailer/*.go + templates/mail/*.tmpl)
- Update all docs (README, AGENTS, CONTRIBUTING, 5 languages)
  to reflect new CLI workflow with create scaffolding command

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
KenanZhuandClaude Opus 4.8 committed 2026-06-04 12:26:44 +08:00
1 parent 77854ee0ed
commit 0bf982ffb9
30 files changed
+1274 -540

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
package cli
// Package cli defines all subcommands for the Gitea Mail Templates CLI tool.
// Command definitions use github.com/urfave/cli/v2.
//
// Shared flag names used across multiple subcommands:
// --folder : path to the themes directory
// --config : path to templates_config.json
+86
View File
@@ -0,0 +1,86 @@
package cli
import (
"fmt"
"os"
"path/filepath"
"github.com/urfave/cli/v2"
"gitea-mail-templates/tools/config"
)
// CreateCommand returns the "create" subcommand.
func CreateCommand() *cli.Command {
return &cli.Command{
Name: "create",
Usage: "Create one or more new theme style directories",
UsageText: "go run . create [--folder <themes-dir>] [--config <config-file>] <style-name>...",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "folder",
Value: "../themes",
Usage: "Path to the themes directory",
},
&cli.StringFlag{
Name: "config",
Value: "./data/templates_config.json",
Usage: "Path to templates_config.json",
},
},
Action: runCreate,
}
}
func runCreate(c *cli.Context) error {
names := c.Args().Slice()
if len(names) == 0 {
return fmt.Errorf("at least one style name is required")
}
folder := c.String("folder")
cfg, err := config.Load(c.String("config"))
if err != nil {
return err
}
for _, styleName := range names {
styleDir := filepath.Join(folder, styleName)
if info, err := os.Stat(styleDir); err == nil {
if info.IsDir() {
fmt.Printf(" [skip] '%s' already exists\n", styleName)
continue
}
return fmt.Errorf("'%s' exists but is not a directory", styleName)
}
created := 0
for _, tplCfg := range cfg.Templates {
tmplPath := filepath.Join(styleDir, tplCfg.PathStr())
dir := filepath.Dir(tmplPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("cannot create directory %s: %w", dir, err)
}
placeholder := fmt.Sprintf("<!DOCTYPE html>\n<html>\n<head>\n"+
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"+
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n"+
" <title>{{.locale.Tr \"mail.%s.title\"}}</title>\n"+
" <style type=\"text/css\">\n /* TODO: Add your custom styles here */\n"+
" </style>\n</head>\n<body style=\"margin:0;padding:0;\">\n"+
" <!-- TODO: Add your custom template design for: %s -->\n"+
"</body>\n</html>\n", tplCfg.Name, tplCfg.Desc)
if err := os.WriteFile(tmplPath, []byte(placeholder), 0644); err != nil {
return fmt.Errorf("cannot write %s: %w", tmplPath, err)
}
created++
}
fmt.Printf(" Created style '%s' with %d template files\n", styleName, created)
}
return nil
}
+51
View File
@@ -0,0 +1,51 @@
package cli
import (
"fmt"
"os"
"path/filepath"
"github.com/urfave/cli/v2"
)
// DeleteCommand returns the "delete" subcommand.
func DeleteCommand() *cli.Command {
return &cli.Command{
Name: "delete",
Usage: "Delete one or more theme style directories",
UsageText: "go run . delete [--folder <themes-dir>] <style-name>...",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "folder",
Value: "../themes",
Usage: "Path to the themes directory",
},
},
Action: runDelete,
}
}
func runDelete(c *cli.Context) error {
names := c.Args().Slice()
if len(names) == 0 {
return fmt.Errorf("at least one style name is required")
}
folder := c.String("folder")
for _, styleName := range names {
styleDir := filepath.Join(folder, styleName)
if _, err := os.Stat(styleDir); os.IsNotExist(err) {
fmt.Printf(" [skip] '%s' does not exist\n", styleName)
continue
}
if err := os.RemoveAll(styleDir); err != nil {
return fmt.Errorf("cannot delete %s: %w", styleDir, err)
}
fmt.Printf(" Deleted style '%s'\n", styleName)
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
package cli
import (
"fmt"
"os"
"path/filepath"
"sort"
"github.com/urfave/cli/v2"
"gitea-mail-templates/tools/preview"
)
// ListCommand returns the "list" subcommand.
func ListCommand() *cli.Command {
return &cli.Command{
Name: "list",
Usage: "List available theme styles in the target folder",
UsageText: "go run . list [--folder <themes-dir>]",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "folder",
Value: "../themes",
Usage: "Path to the themes directory",
},
},
Action: runList,
}
}
func runList(c *cli.Context) error {
folder := c.String("folder")
themes, err := preview.DiscoverThemes(folder)
if err != nil {
return err
}
absDir, _ := filepath.Abs(folder)
fmt.Printf("Available styles in '%s' (%d):\n", filepath.Base(absDir), len(themes))
sort.Strings(themes)
for _, t := range themes {
count := 0
filepath.Walk(filepath.Join(folder, t), func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if filepath.Ext(path) == ".tmpl" {
count++
}
return nil
})
fmt.Printf(" %-16s (%d .tmpl files)\n", t, count)
}
return nil
}
+85
View File
@@ -0,0 +1,85 @@
package cli
import (
"fmt"
"log"
"path/filepath"
"github.com/urfave/cli/v2"
"gitea-mail-templates/tools/config"
"gitea-mail-templates/tools/preview"
)
// PreviewCommand returns the "preview" subcommand.
func PreviewCommand() *cli.Command {
return &cli.Command{
Name: "preview",
Usage: "Pre-render mail templates for preview/testing",
UsageText: `go run . preview [--folder <themes-dir>] [--config <config-file>] [--output <output.js>] all
go run . preview [--folder <themes-dir>] [--config <config-file>] <style-name>...`,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "folder",
Value: "../themes",
Usage: "Path to the themes directory",
},
&cli.StringFlag{
Name: "config",
Value: "./data/templates_config.json",
Usage: "Path to templates_config.json",
},
&cli.StringFlag{
Name: "output",
Usage: "Path to output rendered.js (default: derived from --folder)",
},
},
Action: runPreview,
}
}
func runPreview(c *cli.Context) error {
folder := c.String("folder")
configPath := c.String("config")
outputPath := c.String("output")
if outputPath == "" {
outputPath = filepath.Join(filepath.Dir(folder), "preview", "rendered.js")
}
names := c.Args().Slice()
if len(names) == 0 {
return fmt.Errorf("specify style names or 'all' (e.g. go run . preview all)")
}
cfg, err := config.Load(configPath)
if err != nil {
return err
}
var themeFilter map[string]bool
if len(names) == 1 && names[0] == "all" {
themeFilter = nil
} else {
themeFilter = make(map[string]bool)
for _, name := range names {
themeFilter[name] = true
}
}
result := preview.RenderAll(folder, cfg, themeFilter)
if result == nil {
return fmt.Errorf("no results produced")
}
if err := preview.WriteRenderedJS(result, outputPath); err != nil {
return err
}
preview.PrintDetailedSummary(result, folder, cfg)
log.Printf("Wrote %d themes x %d templates to %s",
len(result.Summaries), len(cfg.Templates), outputPath)
return nil
}