24
definition/defenition.go
Executable file → Normal file
24
definition/defenition.go
Executable file → Normal file
@@ -1,29 +1,23 @@
|
||||
package definition
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gitoa.ru/go-4devs/config"
|
||||
)
|
||||
|
||||
func New() Definition {
|
||||
return Definition{}
|
||||
func New(opts ...config.Option) *Definition {
|
||||
return &Definition{
|
||||
options: opts,
|
||||
}
|
||||
}
|
||||
|
||||
type Definition struct {
|
||||
options Options
|
||||
options []config.Option
|
||||
}
|
||||
|
||||
func (d *Definition) Add(opts ...Option) *Definition {
|
||||
func (d *Definition) Add(opts ...config.Option) {
|
||||
d.options = append(d.options, opts...)
|
||||
|
||||
return d
|
||||
}
|
||||
|
||||
func (d *Definition) View(handle func(Option) error) error {
|
||||
for idx, opt := range d.options {
|
||||
if err := handle(opt); err != nil {
|
||||
return fmt.Errorf("%s[%d]:%w", opt.Kind(), idx, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
func (d *Definition) Options() []config.Option {
|
||||
return d.options
|
||||
}
|
||||
|
||||
94
definition/generate/bootstrap/bootstrap.go
Normal file
94
definition/generate/bootstrap/bootstrap.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition/generate/pkg"
|
||||
)
|
||||
|
||||
//go:embed *.tpl
|
||||
var tpls embed.FS
|
||||
|
||||
type Boot struct {
|
||||
Config
|
||||
|
||||
imp *pkg.Imports
|
||||
Configure []string
|
||||
OutName string
|
||||
}
|
||||
|
||||
func (b Boot) Imports() []pkg.Import {
|
||||
return b.imp.Imports()
|
||||
}
|
||||
|
||||
type Config interface {
|
||||
File() string
|
||||
Methods() []string
|
||||
SkipContext() bool
|
||||
Prefix() string
|
||||
Suffix() string
|
||||
FullPkg() string
|
||||
Pkg() string
|
||||
}
|
||||
|
||||
func Bootstrap(ctx context.Context, cfg Config) (string, error) {
|
||||
fInfo, err := os.Stat(cfg.File())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("stat:%w", err)
|
||||
}
|
||||
|
||||
pkgPath, err := pkg.ByPath(ctx, cfg.File(), fInfo.IsDir())
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("pkg by path:%w", err)
|
||||
}
|
||||
|
||||
tmpFile, err := os.CreateTemp(filepath.Dir(fInfo.Name()), "config-bootstrap")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create tmp file:%w", err)
|
||||
}
|
||||
|
||||
tpl, err := template.ParseFS(tpls, "bootstrap.go.tpl")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("parse template:%w", err)
|
||||
}
|
||||
|
||||
imports := pkg.NewImports("main").
|
||||
Adds(
|
||||
"context",
|
||||
"gitoa.ru/go-4devs/config/definition",
|
||||
"gitoa.ru/go-4devs/config/definition/generate",
|
||||
"os",
|
||||
"fmt",
|
||||
"go/format",
|
||||
pkgPath,
|
||||
)
|
||||
|
||||
data := Boot{
|
||||
imp: imports,
|
||||
Configure: cfg.Methods(),
|
||||
OutName: fInfo.Name()[0:len(fInfo.Name())-3] + "_config.go",
|
||||
Config: cfg,
|
||||
}
|
||||
|
||||
if err := tpl.Execute(tmpFile, data); err != nil {
|
||||
return "", fmt.Errorf("execute:%w", err)
|
||||
}
|
||||
|
||||
src := tmpFile.Name()
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
return src, fmt.Errorf("close file:%w", err)
|
||||
}
|
||||
|
||||
dest := src + ".go"
|
||||
|
||||
if err := os.Rename(src, dest); err != nil {
|
||||
return dest, fmt.Errorf("rename idt:%w", err)
|
||||
}
|
||||
|
||||
return dest, nil
|
||||
}
|
||||
59
definition/generate/bootstrap/bootstrap.go.tpl
Normal file
59
definition/generate/bootstrap/bootstrap.go.tpl
Normal file
@@ -0,0 +1,59 @@
|
||||
//go:build ignore
|
||||
// +build ignore
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
{{range .Imports}}
|
||||
{{- .Alias }}"{{ .Package }}"
|
||||
{{end}}
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
ctx := context.Background()
|
||||
|
||||
f, err := os.Create("{{.OutName}}")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defs:=make([]generate.Input,0)
|
||||
{{ range .Configure }}
|
||||
def{{.}} := definition.New()
|
||||
if err := {{$.Pkg}}.{{.}}(ctx, def{{.}}); err != nil {
|
||||
return err
|
||||
}
|
||||
defs = append(defs,generate.NewInput("{{.}}",def{{.}}))
|
||||
{{ end }}
|
||||
|
||||
opts := make([]generate.Option,0)
|
||||
{{ if .SkipContext }}opts = append(opts, generate.WithSkipContext){{ end }}
|
||||
opts = append(opts,
|
||||
generate.WithPrefix("{{.Prefix}}"),
|
||||
generate.WithSuffix("{{.Suffix}}"),
|
||||
generate.WithFullPkg("{{.FullPkg}}"),
|
||||
)
|
||||
|
||||
if gerr := generate.Run(ctx,generate.NewConfig(opts...),f, defs...);gerr != nil {
|
||||
return gerr
|
||||
}
|
||||
|
||||
in, err := os.ReadFile(f.Name())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
out, err := format.Source(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(f.Name(), out, 0644)
|
||||
}
|
||||
37
definition/generate/example/config.go
Normal file
37
definition/generate/example/config.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
"gitoa.ru/go-4devs/config/definition/group"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/definition/proto"
|
||||
)
|
||||
|
||||
type Level string
|
||||
|
||||
func (l *Level) UnmarshalText(in []byte) error {
|
||||
data := string(in)
|
||||
*l = Level(data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Config(_ context.Context, def *definition.Definition) error {
|
||||
def.Add(
|
||||
option.String("test", "test string", view.WithSkipContext),
|
||||
group.New("user", "configure user",
|
||||
option.String("name", "name", option.Default("4devs")),
|
||||
option.String("pass", "password"),
|
||||
),
|
||||
|
||||
group.New("log", "configure logger",
|
||||
option.New("level", "log level", Level("")),
|
||||
proto.New("service", "servise logger", option.New("level", "log level", Level(""))),
|
||||
),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
206
definition/generate/example/config_config.go
Normal file
206
definition/generate/example/config_config.go
Normal file
@@ -0,0 +1,206 @@
|
||||
// Code generated gitoa.ru/go-4devs/config DO NOT EDIT.
|
||||
package example
|
||||
|
||||
import (
|
||||
context "context"
|
||||
fmt "fmt"
|
||||
config "gitoa.ru/go-4devs/config"
|
||||
)
|
||||
|
||||
func WithInputConfigLog(log func(context.Context, string, ...any)) func(*InputConfig) {
|
||||
return func(ci *InputConfig) {
|
||||
ci.log = log
|
||||
}
|
||||
}
|
||||
|
||||
func NewInputConfig(prov config.Provider, opts ...func(*InputConfig)) InputConfig {
|
||||
i := InputConfig{
|
||||
Provider: prov,
|
||||
log: func(_ context.Context, format string, args ...any) {
|
||||
fmt.Printf(format, args...)
|
||||
},
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&i)
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
type InputConfig struct {
|
||||
config.Provider
|
||||
log func(context.Context, string, ...any)
|
||||
}
|
||||
|
||||
// readTest test string.
|
||||
func (i InputConfig) readTest(ctx context.Context) (v string, e error) {
|
||||
val, err := i.Value(ctx, "test")
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"test"}, err)
|
||||
|
||||
}
|
||||
|
||||
return val.ParseString()
|
||||
|
||||
}
|
||||
|
||||
// ReadTest test string.
|
||||
func (i InputConfig) ReadTest() (string, error) {
|
||||
return i.readTest(context.Background())
|
||||
}
|
||||
|
||||
// Test test string.
|
||||
func (i InputConfig) Test() string {
|
||||
val, err := i.readTest(context.Background())
|
||||
if err != nil {
|
||||
i.log(context.Background(), "get [%v]: %v", []string{"test"}, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
type InputConfigUser struct {
|
||||
InputConfig
|
||||
}
|
||||
|
||||
// User configure user.
|
||||
func (i InputConfig) User() InputConfigUser {
|
||||
return InputConfigUser{i}
|
||||
}
|
||||
|
||||
// readName name.
|
||||
func (i InputConfigUser) readName(ctx context.Context) (v string, e error) {
|
||||
val, err := i.Value(ctx, "user", "name")
|
||||
if err != nil {
|
||||
i.log(context.Background(), "read [%v]: %v", []string{"user", "name"}, err)
|
||||
|
||||
return "4devs", nil
|
||||
}
|
||||
|
||||
return val.ParseString()
|
||||
|
||||
}
|
||||
|
||||
// ReadName name.
|
||||
func (i InputConfigUser) ReadName(ctx context.Context) (string, error) {
|
||||
return i.readName(ctx)
|
||||
}
|
||||
|
||||
// Name name.
|
||||
func (i InputConfigUser) Name(ctx context.Context) string {
|
||||
val, err := i.readName(ctx)
|
||||
if err != nil {
|
||||
i.log(ctx, "get [%v]: %v", []string{"user", "name"}, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
// readPass password.
|
||||
func (i InputConfigUser) readPass(ctx context.Context) (v string, e error) {
|
||||
val, err := i.Value(ctx, "user", "pass")
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"user", "pass"}, err)
|
||||
|
||||
}
|
||||
|
||||
return val.ParseString()
|
||||
|
||||
}
|
||||
|
||||
// ReadPass password.
|
||||
func (i InputConfigUser) ReadPass(ctx context.Context) (string, error) {
|
||||
return i.readPass(ctx)
|
||||
}
|
||||
|
||||
// Pass password.
|
||||
func (i InputConfigUser) Pass(ctx context.Context) string {
|
||||
val, err := i.readPass(ctx)
|
||||
if err != nil {
|
||||
i.log(ctx, "get [%v]: %v", []string{"user", "pass"}, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
type InputConfigLog struct {
|
||||
InputConfig
|
||||
}
|
||||
|
||||
// Log configure logger.
|
||||
func (i InputConfig) Log() InputConfigLog {
|
||||
return InputConfigLog{i}
|
||||
}
|
||||
|
||||
// readLevel log level.
|
||||
func (i InputConfigLog) readLevel(ctx context.Context) (v Level, e error) {
|
||||
val, err := i.Value(ctx, "log", "level")
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"log", "level"}, err)
|
||||
|
||||
}
|
||||
|
||||
pval, perr := val.ParseString()
|
||||
if perr != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"log", "level"}, perr)
|
||||
}
|
||||
|
||||
return v, v.UnmarshalText([]byte(pval))
|
||||
}
|
||||
|
||||
// ReadLevel log level.
|
||||
func (i InputConfigLog) ReadLevel(ctx context.Context) (Level, error) {
|
||||
return i.readLevel(ctx)
|
||||
}
|
||||
|
||||
// Level log level.
|
||||
func (i InputConfigLog) Level(ctx context.Context) Level {
|
||||
val, err := i.readLevel(ctx)
|
||||
if err != nil {
|
||||
i.log(ctx, "get [%v]: %v", []string{"log", "level"}, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
type InputConfigLogService struct {
|
||||
InputConfigLog
|
||||
service string
|
||||
}
|
||||
|
||||
// Service servise logger.
|
||||
func (i InputConfigLog) Service(key string) InputConfigLogService {
|
||||
return InputConfigLogService{i, key}
|
||||
}
|
||||
|
||||
// readLevel log level.
|
||||
func (i InputConfigLogService) readLevel(ctx context.Context) (v Level, e error) {
|
||||
val, err := i.Value(ctx, "log", i.service, "level")
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"log", i.service, "level"}, err)
|
||||
|
||||
}
|
||||
|
||||
pval, perr := val.ParseString()
|
||||
if perr != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"log", i.service, "level"}, perr)
|
||||
}
|
||||
|
||||
return v, v.UnmarshalText([]byte(pval))
|
||||
}
|
||||
|
||||
// ReadLevel log level.
|
||||
func (i InputConfigLogService) ReadLevel(ctx context.Context) (Level, error) {
|
||||
return i.readLevel(ctx)
|
||||
}
|
||||
|
||||
// Level log level.
|
||||
func (i InputConfigLogService) Level(ctx context.Context) Level {
|
||||
val, err := i.readLevel(ctx)
|
||||
if err != nil {
|
||||
i.log(ctx, "get [%v]: %v", []string{"log", i.service, "level"}, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
59
definition/generate/example/generate_test.go
Normal file
59
definition/generate/example/generate_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package example_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/bootstrap"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/example"
|
||||
)
|
||||
|
||||
func TestGenerate_Bootstrap(t *testing.T) {
|
||||
t.SkipNow()
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
options := definition.New()
|
||||
_ = example.Config(ctx, options)
|
||||
|
||||
cfg, _ := generate.NewGConfig("./config.go",
|
||||
generate.WithMethods("Config"),
|
||||
generate.WithFullPkg("gitoa.ru/go-4devs/config/definition/generate/example"),
|
||||
)
|
||||
|
||||
path, err := bootstrap.Bootstrap(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
os.Remove(path)
|
||||
|
||||
t.Log(path)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
func TestGenerate_Genereate(t *testing.T) {
|
||||
t.SkipNow()
|
||||
t.Parallel()
|
||||
|
||||
ctx := context.Background()
|
||||
options := definition.New()
|
||||
_ = example.Config(ctx, options)
|
||||
|
||||
cfg, _ := generate.NewGConfig("./config.go",
|
||||
generate.WithMethods("Config"),
|
||||
generate.WithFullPkg("gitoa.ru/go-4devs/config/definition/generate/example"),
|
||||
)
|
||||
|
||||
err := generate.Generate(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
t.FailNow()
|
||||
}
|
||||
78
definition/generate/exec.go
Normal file
78
definition/generate/exec.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"go/format"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition/generate/bootstrap"
|
||||
)
|
||||
|
||||
func NewGConfig(fname string, opts ...Option) (Config, error) {
|
||||
opts = append([]Option{
|
||||
WithFile(fname),
|
||||
}, opts...)
|
||||
|
||||
return NewConfig(opts...), nil
|
||||
}
|
||||
|
||||
type GConfig interface {
|
||||
BuildTags() string
|
||||
OutName() string
|
||||
bootstrap.Config
|
||||
}
|
||||
|
||||
func Generate(ctx context.Context, cfg GConfig) error {
|
||||
path, err := bootstrap.Bootstrap(ctx, cfg)
|
||||
defer os.Remove(path)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("build bootstrap:%w", err)
|
||||
}
|
||||
|
||||
tmpFile, err := os.Create(cfg.File() + ".tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create tmp file:%w", err)
|
||||
}
|
||||
|
||||
defer os.Remove(tmpFile.Name()) // will not remove after rename
|
||||
|
||||
execArgs := []string{"run"}
|
||||
if len(cfg.BuildTags()) > 0 {
|
||||
execArgs = append(execArgs, "-tags", cfg.BuildTags())
|
||||
}
|
||||
|
||||
execArgs = append(execArgs, filepath.Base(path))
|
||||
cmd := exec.CommandContext(ctx, "go", execArgs...)
|
||||
|
||||
cmd.Stdout = tmpFile
|
||||
cmd.Stderr = os.Stderr
|
||||
|
||||
cmd.Dir = filepath.Dir(path)
|
||||
if err = cmd.Run(); err != nil {
|
||||
return fmt.Errorf("start cmd:%w", err)
|
||||
}
|
||||
|
||||
tmpFile.Close()
|
||||
|
||||
// format file and write to out path
|
||||
in, err := os.ReadFile(tmpFile.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("read file: %w", err)
|
||||
}
|
||||
|
||||
out, err := format.Source(in)
|
||||
if err != nil {
|
||||
return fmt.Errorf("format source:%w", err)
|
||||
}
|
||||
|
||||
err = os.WriteFile(cfg.OutName(), out, 0o644) //nolint:gosec,mnd
|
||||
if err != nil {
|
||||
return fmt.Errorf("write file:%w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
233
definition/generate/generate.go
Normal file
233
definition/generate/generate.go
Normal file
@@ -0,0 +1,233 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/template"
|
||||
"unicode"
|
||||
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/pkg"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/render"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
type Option func(*Config)
|
||||
|
||||
func WithSkipContext(c *Config) {
|
||||
view.WithSkipContext(c.Params)
|
||||
}
|
||||
|
||||
func WithPrefix(name string) Option {
|
||||
return func(c *Config) {
|
||||
c.prefix = name
|
||||
}
|
||||
}
|
||||
|
||||
func WithSuffix(name string) Option {
|
||||
return func(c *Config) {
|
||||
c.suffix = name
|
||||
}
|
||||
}
|
||||
|
||||
// WithMethods set methosd.
|
||||
//
|
||||
// generate.WithMethods(runtime.FuncForPC(reflect.ValueOf(configure).Pointer()).Name()).
|
||||
func WithMethods(in ...string) Option {
|
||||
return func(c *Config) {
|
||||
c.methods = in
|
||||
}
|
||||
}
|
||||
|
||||
func WithOutName(in string) Option {
|
||||
return func(c *Config) {
|
||||
c.outName = in
|
||||
}
|
||||
}
|
||||
|
||||
func WithFile(in string) Option {
|
||||
return func(c *Config) {
|
||||
c.file = in
|
||||
}
|
||||
}
|
||||
|
||||
func WithFullPkg(in string) Option {
|
||||
return func(c *Config) {
|
||||
c.fullPkg = in
|
||||
}
|
||||
}
|
||||
|
||||
func NewConfig(opts ...Option) Config {
|
||||
var cfg Config
|
||||
|
||||
cfg.Params = param.New()
|
||||
cfg.prefix = "Input"
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&cfg)
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
param.Params
|
||||
|
||||
methods []string
|
||||
prefix string
|
||||
suffix string
|
||||
fullPkg string
|
||||
pkg string
|
||||
file string
|
||||
buildTags string
|
||||
outName string
|
||||
}
|
||||
|
||||
func (c Config) BuildTags() string {
|
||||
return c.buildTags
|
||||
}
|
||||
|
||||
func (c Config) Pkg() string {
|
||||
if c.pkg == "" {
|
||||
if idx := strings.LastIndex(c.fullPkg, "/"); idx != -1 {
|
||||
c.pkg = c.fullPkg[idx+1:]
|
||||
}
|
||||
}
|
||||
|
||||
return c.pkg
|
||||
}
|
||||
|
||||
func (c Config) FullPkg() string {
|
||||
return c.fullPkg
|
||||
}
|
||||
|
||||
func (c Config) SkipContext() bool {
|
||||
return view.IsSkipContext(c.Params)
|
||||
}
|
||||
|
||||
func (c Config) Methods() []string {
|
||||
return c.methods
|
||||
}
|
||||
|
||||
func (c Config) Prefix() string {
|
||||
return c.prefix
|
||||
}
|
||||
|
||||
func (c Config) Suffix() string {
|
||||
return c.suffix
|
||||
}
|
||||
|
||||
func (c Config) File() string {
|
||||
return c.file
|
||||
}
|
||||
|
||||
func (c Config) OutName() string {
|
||||
return c.outName
|
||||
}
|
||||
|
||||
//go:embed tpl/*
|
||||
var tpls embed.FS
|
||||
|
||||
var initTpl = template.Must(template.New("tpls").ParseFS(tpls, "tpl/*.tpl")).Lookup("init.go.tpl")
|
||||
|
||||
func Run(_ context.Context, cfg Config, w io.Writer, inputs ...Input) error {
|
||||
data := Data{
|
||||
Config: cfg,
|
||||
imp: pkg.NewImports(cfg.FullPkg()).Adds("fmt", "context", "gitoa.ru/go-4devs/config"),
|
||||
}
|
||||
|
||||
var buff bytes.Buffer
|
||||
|
||||
for _, in := range inputs {
|
||||
vi := view.NewViews(in.Method(), data.Params, in.Options(), view.WithKeys())
|
||||
|
||||
if err := render.Render(&buff, vi, data); err != nil {
|
||||
return fmt.Errorf("render:%w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := initTpl.Execute(w, data); err != nil {
|
||||
return fmt.Errorf("render base:%w", err)
|
||||
}
|
||||
|
||||
if _, err := io.Copy(w, &buff); err != nil {
|
||||
return fmt.Errorf("copy:%w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Data struct {
|
||||
Config
|
||||
|
||||
imp *pkg.Imports
|
||||
}
|
||||
|
||||
func (f Data) Imports() []pkg.Import {
|
||||
return f.imp.Imports()
|
||||
}
|
||||
|
||||
func (f Data) StructName(name string) string {
|
||||
return f.Prefix() + FuncName(name) + f.Suffix()
|
||||
}
|
||||
|
||||
func (f Data) FuncName(in string) string {
|
||||
return FuncName(in)
|
||||
}
|
||||
|
||||
func (f Data) AddType(pkg string) (string, error) {
|
||||
short, err := f.imp.AddType(pkg)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("data: %w", err)
|
||||
}
|
||||
|
||||
return short, nil
|
||||
}
|
||||
|
||||
func FuncName(name string) string {
|
||||
data := strings.Builder{}
|
||||
toUp := true
|
||||
|
||||
for _, char := range name {
|
||||
isLeter := unicode.IsLetter(char)
|
||||
isAllowed := isLeter || unicode.IsDigit(char)
|
||||
|
||||
switch {
|
||||
case isAllowed && !toUp:
|
||||
data.WriteRune(char)
|
||||
case !isAllowed:
|
||||
toUp = true
|
||||
case toUp:
|
||||
data.WriteString(strings.ToUpper(string(char)))
|
||||
|
||||
toUp = false
|
||||
}
|
||||
}
|
||||
|
||||
return data.String()
|
||||
}
|
||||
|
||||
func NewInput(method string, options config.Options) Input {
|
||||
return Input{
|
||||
method: method,
|
||||
options: options,
|
||||
}
|
||||
}
|
||||
|
||||
type Input struct {
|
||||
options config.Options
|
||||
method string
|
||||
}
|
||||
|
||||
func (i Input) Method() string {
|
||||
return i.method
|
||||
}
|
||||
|
||||
func (i Input) Options() config.Options {
|
||||
return i.options
|
||||
}
|
||||
33
definition/generate/generate_test.go
Normal file
33
definition/generate/generate_test.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package generate_test
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
"gitoa.ru/go-4devs/config/definition/group"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/definition/proto"
|
||||
)
|
||||
|
||||
type LogLevel string
|
||||
|
||||
func (l *LogLevel) UnmarshalText(in []byte) error {
|
||||
data := string(in)
|
||||
*l = LogLevel(data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Configure(def *definition.Definition) {
|
||||
def.Add(
|
||||
option.String("test", "test string", view.WithSkipContext),
|
||||
group.New("user", "configure user",
|
||||
option.String("name", "name", option.Default("4devs")),
|
||||
option.String("pass", "password"),
|
||||
),
|
||||
|
||||
group.New("log", "configure logger",
|
||||
option.New("level", "log level", LogLevel("")),
|
||||
proto.New("service", "servise logger", option.New("level", "log level", LogLevel(""))),
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
)
|
||||
|
||||
type Generator struct {
|
||||
pkg string
|
||||
ViewOption
|
||||
Imp Imports
|
||||
errs []error
|
||||
defaultErrors []string
|
||||
}
|
||||
|
||||
func (g Generator) Pkg() string {
|
||||
return g.pkg
|
||||
}
|
||||
|
||||
func (g Generator) Imports() []Import {
|
||||
return g.Imp.Imports()
|
||||
}
|
||||
|
||||
func (g Generator) Handle(w io.Writer, data Handler, opt definition.Option) error {
|
||||
handle := get(opt.Kind())
|
||||
|
||||
return handle(w, data, opt)
|
||||
}
|
||||
|
||||
func (g Generator) StructName() string {
|
||||
return FuncName(g.Prefix + "_" + g.Struct + "_" + g.Suffix)
|
||||
}
|
||||
|
||||
func (g Generator) Options() ViewOption {
|
||||
return g.ViewOption
|
||||
}
|
||||
|
||||
func (g Generator) Keys() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Generator) DefaultErrors() []string {
|
||||
if len(g.defaultErrors) > 0 {
|
||||
return g.defaultErrors
|
||||
}
|
||||
|
||||
if len(g.ViewOption.Errors.Default) > 0 {
|
||||
g.Imp.Adds("errors")
|
||||
}
|
||||
|
||||
g.defaultErrors = make([]string, len(g.ViewOption.Errors.Default))
|
||||
for idx, name := range g.ViewOption.Errors.Default {
|
||||
short, err := g.AddType(name)
|
||||
if err != nil {
|
||||
g.errs = append(g.errs, fmt.Errorf("add default error[%d]:%w", idx, err))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
g.defaultErrors[idx] = short
|
||||
}
|
||||
|
||||
return g.defaultErrors
|
||||
}
|
||||
|
||||
func (g *Generator) AddType(pkg string) (string, error) {
|
||||
return g.Imp.AddType(pkg)
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/iancoleman/strcase"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrAlreadyExist = errors.New("already exist")
|
||||
ErrWrongType = errors.New("wrong type")
|
||||
ErrWrongFormat = errors.New("wrong format")
|
||||
)
|
||||
|
||||
func FuncName(in string) string {
|
||||
return strcase.ToCamel(in)
|
||||
}
|
||||
29
definition/generate/pkg/alias.go
Normal file
29
definition/generate/pkg/alias.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
func AliasName(name string) string {
|
||||
data := strings.Builder{}
|
||||
toUp := false
|
||||
|
||||
for _, char := range name {
|
||||
isLeter := unicode.IsLetter(char)
|
||||
isAllowed := isLeter || unicode.IsDigit(char)
|
||||
|
||||
switch {
|
||||
case isAllowed && !toUp:
|
||||
data.WriteRune(char)
|
||||
case !isAllowed && data.Len() > 0:
|
||||
toUp = true
|
||||
case toUp:
|
||||
data.WriteString(strings.ToUpper(string(char)))
|
||||
|
||||
toUp = false
|
||||
}
|
||||
}
|
||||
|
||||
return data.String()
|
||||
}
|
||||
8
definition/generate/pkg/errors.go
Normal file
8
definition/generate/pkg/errors.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package pkg
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrWrongFormat = errors.New("wrong format")
|
||||
ErrNotFound = errors.New("not found")
|
||||
)
|
||||
@@ -1,4 +1,4 @@
|
||||
package generate
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
@@ -6,17 +6,21 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func NewImports() Imports {
|
||||
return Imports{
|
||||
func NewImports(pkg string) *Imports {
|
||||
imp := Imports{
|
||||
data: make(map[string]string),
|
||||
pkg: pkg,
|
||||
}
|
||||
|
||||
return &imp
|
||||
}
|
||||
|
||||
type Imports struct {
|
||||
data map[string]string
|
||||
pkg string
|
||||
}
|
||||
|
||||
func (i Imports) Imports() []Import {
|
||||
func (i *Imports) Imports() []Import {
|
||||
imports := make([]Import, 0, len(i.data))
|
||||
for name, alias := range i.data {
|
||||
imports = append(imports, Import{
|
||||
@@ -44,25 +48,38 @@ func (i *Imports) Short(fullType string) (string, error) {
|
||||
func (i *Imports) AddType(fullType string) (string, error) {
|
||||
idx := strings.LastIndexByte(fullType, '.')
|
||||
if idx == -1 {
|
||||
return "", fmt.Errorf("%w: expect pckage.Type", ErrWrongFormat)
|
||||
return "", fmt.Errorf("%w: expect pckage.Type got %v", ErrWrongFormat, fullType)
|
||||
}
|
||||
|
||||
imp := i.Add(fullType[:idx])
|
||||
|
||||
if imp.Alias == "" {
|
||||
return fullType[idx+1:], nil
|
||||
}
|
||||
|
||||
return imp.Alias + fullType[idx:], nil
|
||||
}
|
||||
|
||||
func (i *Imports) Adds(pkgs ...string) {
|
||||
func (i *Imports) Adds(pkgs ...string) *Imports {
|
||||
for _, pkg := range pkgs {
|
||||
i.Add(pkg)
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func (i *Imports) Add(pkg string) Import {
|
||||
if pkg == i.pkg {
|
||||
return Import{
|
||||
Alias: "",
|
||||
Package: pkg,
|
||||
}
|
||||
}
|
||||
|
||||
alias := pkg
|
||||
|
||||
if idx := strings.LastIndexByte(pkg, '/'); idx != -1 {
|
||||
alias = pkg[idx+1:]
|
||||
alias = AliasName(pkg[idx+1:])
|
||||
}
|
||||
|
||||
if al, ok := i.data[pkg]; ok {
|
||||
187
definition/generate/pkg/pkg.go
Normal file
187
definition/generate/pkg/pkg.go
Normal file
@@ -0,0 +1,187 @@
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"go/build"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var cache = sync.Map{}
|
||||
|
||||
func ByPath(ctx context.Context, fname string, isDir bool) (string, error) {
|
||||
if !filepath.IsAbs(fname) {
|
||||
pwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w", err)
|
||||
}
|
||||
|
||||
fname = filepath.Join(pwd, fname)
|
||||
}
|
||||
|
||||
goModPath, _ := goModPath(ctx, fname, isDir)
|
||||
if strings.Contains(goModPath, "go.mod") {
|
||||
pkgPath, err := getPkgPathFromGoMod(fname, isDir, goModPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return pkgPath, nil
|
||||
}
|
||||
|
||||
return getPkgPathFromGOPATH(fname, isDir)
|
||||
}
|
||||
|
||||
// empty if no go.mod, GO111MODULE=off or go without go modules support.
|
||||
func goModPath(ctx context.Context, fname string, isDir bool) (string, error) {
|
||||
root := fname
|
||||
if !isDir {
|
||||
root = filepath.Dir(fname)
|
||||
}
|
||||
|
||||
var modPath string
|
||||
|
||||
loadModPath, ok := cache.Load(root)
|
||||
if ok {
|
||||
modPath, _ = loadModPath.(string)
|
||||
|
||||
return modPath, nil
|
||||
}
|
||||
|
||||
defer func() {
|
||||
cache.Store(root, modPath)
|
||||
}()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "go", "env", "GOMOD")
|
||||
cmd.Dir = root
|
||||
|
||||
stdout, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w", err)
|
||||
}
|
||||
|
||||
modPath = string(bytes.TrimSpace(stdout))
|
||||
|
||||
return modPath, nil
|
||||
}
|
||||
|
||||
func getPkgPathFromGoMod(fname string, isDir bool, goModPath string) (string, error) {
|
||||
modulePath := getModulePath(goModPath)
|
||||
if modulePath == "" {
|
||||
return "", fmt.Errorf("c%w module path from %s", ErrNotFound, goModPath)
|
||||
}
|
||||
|
||||
rel := path.Join(modulePath, filePathToPackagePath(strings.TrimPrefix(fname, filepath.Dir(goModPath))))
|
||||
|
||||
if !isDir {
|
||||
return path.Dir(rel), nil
|
||||
}
|
||||
|
||||
return path.Clean(rel), nil
|
||||
}
|
||||
|
||||
func getModulePath(goModPath string) string {
|
||||
var pkgPath string
|
||||
|
||||
cacheOkgPath, ok := cache.Load(goModPath)
|
||||
if ok {
|
||||
pkgPath, _ = cacheOkgPath.(string)
|
||||
|
||||
return pkgPath
|
||||
}
|
||||
|
||||
defer func() {
|
||||
cache.Store(goModPath, pkgPath)
|
||||
}()
|
||||
|
||||
data, err := os.ReadFile(goModPath)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
pkgPath = modulePath(data)
|
||||
|
||||
return pkgPath
|
||||
}
|
||||
|
||||
func getPkgPathFromGOPATH(fname string, isDir bool) (string, error) {
|
||||
gopath := os.Getenv("GOPATH")
|
||||
if gopath == "" {
|
||||
gopath = build.Default.GOPATH
|
||||
}
|
||||
|
||||
for _, p := range strings.Split(gopath, string(filepath.ListSeparator)) {
|
||||
prefix := filepath.Join(p, "src") + string(filepath.Separator)
|
||||
|
||||
rel, err := filepath.Rel(prefix, fname)
|
||||
if err == nil && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
if !isDir {
|
||||
return path.Dir(filePathToPackagePath(rel)), nil
|
||||
}
|
||||
|
||||
return path.Clean(filePathToPackagePath(rel)), nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("%w: file '%v' is not in GOPATH '%v'", ErrNotFound, fname, gopath)
|
||||
}
|
||||
|
||||
func filePathToPackagePath(path string) string {
|
||||
return filepath.ToSlash(path)
|
||||
}
|
||||
|
||||
var (
|
||||
slashSlash = []byte("//")
|
||||
moduleStr = []byte("module")
|
||||
)
|
||||
|
||||
// modulePath returns the module path from the gomod file text.
|
||||
// If it cannot find a module path, it returns an empty string.
|
||||
// It is tolerant of unrelated problems in the go.mod file.
|
||||
func modulePath(mod []byte) string {
|
||||
for len(mod) > 0 {
|
||||
line := mod
|
||||
|
||||
mod = nil
|
||||
if i := bytes.IndexByte(line, '\n'); i >= 0 {
|
||||
line, mod = line[:i], line[i+1:]
|
||||
}
|
||||
|
||||
if i := bytes.Index(line, slashSlash); i >= 0 {
|
||||
line = line[:i]
|
||||
}
|
||||
|
||||
line = bytes.TrimSpace(line)
|
||||
if !bytes.HasPrefix(line, moduleStr) {
|
||||
continue
|
||||
}
|
||||
|
||||
line = line[len(moduleStr):]
|
||||
n := len(line)
|
||||
|
||||
line = bytes.TrimSpace(line)
|
||||
if len(line) == n || len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if line[0] == '"' || line[0] == '`' {
|
||||
p, err := strconv.Unquote(string(line))
|
||||
if err != nil {
|
||||
return "" // malformed quoted string or multiline module path
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
return string(line)
|
||||
}
|
||||
|
||||
return "" // missing module path
|
||||
}
|
||||
61
definition/generate/render/data.go
Normal file
61
definition/generate/render/data.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/definition/generate/pkg"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
)
|
||||
|
||||
func NewViewData(render Rendering, view view.View) ViewData {
|
||||
return ViewData{
|
||||
Rendering: render,
|
||||
View: view,
|
||||
}
|
||||
}
|
||||
|
||||
type ViewData struct {
|
||||
Rendering
|
||||
view.View
|
||||
}
|
||||
|
||||
func (d ViewData) StructName() string {
|
||||
return d.Rendering.StructName(d.View.ParentName() + "_" + d.View.Name())
|
||||
}
|
||||
|
||||
func (d ViewData) FuncName() string {
|
||||
return d.Rendering.FuncName(d.View.FuncName())
|
||||
}
|
||||
|
||||
func (d ViewData) ParentName() string {
|
||||
name := d.View.ParentName()
|
||||
if name == "" {
|
||||
name = d.Name()
|
||||
}
|
||||
|
||||
return d.Rendering.StructName(name)
|
||||
}
|
||||
|
||||
func (d ViewData) Name() string {
|
||||
return pkg.AliasName(d.View.Name())
|
||||
}
|
||||
|
||||
func (d ViewData) Type() string {
|
||||
return Type(d)
|
||||
}
|
||||
|
||||
func (d ViewData) Keys(parent string) string {
|
||||
return Keys(append(d.View.Keys(), d.Name()), parent)
|
||||
}
|
||||
|
||||
func (d ViewData) Value(name, val string) string {
|
||||
return Value(name, val, d)
|
||||
}
|
||||
|
||||
func (d ViewData) Default(name string) string {
|
||||
return Data(d.View.Default(), name, d)
|
||||
}
|
||||
|
||||
type Rendering interface {
|
||||
StructName(name string) string
|
||||
FuncName(name string) string
|
||||
AddType(pkg string) (string, error)
|
||||
}
|
||||
5
definition/generate/render/errors.go
Normal file
5
definition/generate/render/errors.go
Normal file
@@ -0,0 +1,5 @@
|
||||
package render
|
||||
|
||||
import "errors"
|
||||
|
||||
var ErrNotFound = errors.New("not found")
|
||||
34
definition/generate/render/keys.go
Normal file
34
definition/generate/render/keys.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition/generate/pkg"
|
||||
"gitoa.ru/go-4devs/config/key"
|
||||
)
|
||||
|
||||
func Keys(keys []string, val string) string {
|
||||
if len(keys) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
|
||||
for idx, one := range keys {
|
||||
if key.IsWild(one) {
|
||||
out.WriteString(val)
|
||||
out.WriteString(".")
|
||||
out.WriteString(pkg.AliasName(one))
|
||||
} else {
|
||||
out.WriteString("\"")
|
||||
out.WriteString(one)
|
||||
out.WriteString("\"")
|
||||
}
|
||||
|
||||
if len(keys)-1 != idx {
|
||||
out.WriteString(", ")
|
||||
}
|
||||
}
|
||||
|
||||
return out.String()
|
||||
}
|
||||
49
definition/generate/render/render.go
Normal file
49
definition/generate/render/render.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
"gitoa.ru/go-4devs/config/definition/group"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/definition/proto"
|
||||
)
|
||||
|
||||
type Execute func(w io.Writer, vi view.View, rnd Rendering) error
|
||||
|
||||
var randders = map[reflect.Type]Execute{
|
||||
reflect.TypeFor[*definition.Definition](): Template(defTpl),
|
||||
reflect.TypeFor[group.Group](): Template(groupTpl),
|
||||
reflect.TypeFor[option.Option](): Template(optTpl),
|
||||
reflect.TypeFor[proto.Proto](): Template(protoTpl),
|
||||
}
|
||||
|
||||
func Renders() map[reflect.Type]Execute {
|
||||
return randders
|
||||
}
|
||||
|
||||
func Add(rt reflect.Type, fn Execute) {
|
||||
randders[rt] = fn
|
||||
}
|
||||
|
||||
func Render(w io.Writer, view view.View, data Rendering) error {
|
||||
rnd, ok := randders[view.Kind()]
|
||||
if !ok {
|
||||
return fmt.Errorf("%w:%v", ErrNotFound, view.Kind())
|
||||
}
|
||||
|
||||
if err := rnd(w, view, data); err != nil {
|
||||
return fmt.Errorf("render:%v, err:%w", view.Kind(), err)
|
||||
}
|
||||
|
||||
for _, ch := range view.Views() {
|
||||
if err := Render(w, ch, data); err != nil {
|
||||
return fmt.Errorf("render[%v]:%w", ch.Name(), err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
41
definition/generate/render/tpl.go
Normal file
41
definition/generate/render/tpl.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
)
|
||||
|
||||
//go:embed tpl/*
|
||||
var tplFS embed.FS
|
||||
|
||||
var (
|
||||
tpls = template.Must(
|
||||
template.New("tpls").
|
||||
Funcs(template.FuncMap{
|
||||
"trim": strings.Trim,
|
||||
}).
|
||||
ParseFS(tplFS, "tpl/*.go.tpl"),
|
||||
)
|
||||
defTpl = tpls.Lookup("definition.go.tpl")
|
||||
groupTpl = tpls.Lookup("group.go.tpl")
|
||||
protoTpl = tpls.Lookup("proto.go.tpl")
|
||||
optTpl = template.Must(
|
||||
template.New("opt").ParseFS(tplFS, "tpl/option/option.go.tpl"),
|
||||
).Lookup("option.go.tpl")
|
||||
parceTpls = template.Must(template.New("data").ParseFS(tplFS, "tpl/data/*.go.tpl"))
|
||||
)
|
||||
|
||||
func Template(tpl *template.Template) Execute {
|
||||
return func(w io.Writer, v view.View, rnd Rendering) error {
|
||||
if err := tpl.Execute(w, NewViewData(rnd, v)); err != nil {
|
||||
return fmt.Errorf("template[%v]:%w", tpl.Name(), err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
3
definition/generate/render/tpl/data/any.go.tpl
Normal file
3
definition/generate/render/tpl/data/any.go.tpl
Normal file
@@ -0,0 +1,3 @@
|
||||
{{block "Any" . }}
|
||||
return {{.ValName}}.Any(), nil
|
||||
{{end}}
|
||||
8
definition/generate/render/tpl/data/flag_value.go.tpl
Normal file
8
definition/generate/render/tpl/data/flag_value.go.tpl
Normal file
@@ -0,0 +1,8 @@
|
||||
{{ block "FlagValue" . -}}
|
||||
pval, perr := {{.ValName}}.ParseString()
|
||||
if perr != nil {
|
||||
return {{.Value}}, fmt.Errorf("read [%v]:%w",[]string{ {{- .Keys "i" -}} }, perr)
|
||||
}
|
||||
|
||||
return {{.Value}}, {{.Value}}.Set(pval)
|
||||
{{- end }}
|
||||
3
definition/generate/render/tpl/data/scan_value.go.tpl
Normal file
3
definition/generate/render/tpl/data/scan_value.go.tpl
Normal file
@@ -0,0 +1,3 @@
|
||||
{{ block "ScanValue" . -}}
|
||||
return {{.Value}}, {{.Value}}.Scan({{.ValName}}.Any())
|
||||
{{- end }}
|
||||
@@ -0,0 +1,8 @@
|
||||
{{block "UnmarshalJSON" . -}}
|
||||
pval, perr := {{.ValName}}.ParseString()
|
||||
if perr != nil {
|
||||
return {{.Value}}, fmt.Errorf("read [%v]:%w", []string{ {{- .Keys "i" -}} }, perr)
|
||||
}
|
||||
|
||||
return {{.Value}}, {{.Value}}.UnmarshalJSON([]byte(pval))
|
||||
{{- end }}
|
||||
@@ -0,0 +1,8 @@
|
||||
{{ block "UnmarshalText" . -}}
|
||||
pval, perr := {{.ValName}}.ParseString()
|
||||
if perr != nil {
|
||||
return {{.Value}}, fmt.Errorf("read [%v]:%w", []string{ {{- .Keys "i" -}} }, perr)
|
||||
}
|
||||
|
||||
return {{.Value}}, {{.Value}}.UnmarshalText([]byte(pval))
|
||||
{{- end }}
|
||||
@@ -1,19 +1,3 @@
|
||||
package generate
|
||||
|
||||
import "text/template"
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
tpl = template.Must(template.New("tpls").Parse(baseTemplate))
|
||||
baseTemplate = `// Code generated gitoa.ru/go-4devs/config DO NOT EDIT.
|
||||
package {{.Pkg}}
|
||||
|
||||
import (
|
||||
{{range .Imports}}
|
||||
{{- .Alias }}"{{ .Package }}"
|
||||
{{end}}
|
||||
)
|
||||
|
||||
func With{{.StructName}}Log(log func(context.Context, string, ...any)) func(*{{.StructName}}) {
|
||||
return func(ci *{{.StructName}}) {
|
||||
ci.log = log
|
||||
@@ -39,5 +23,3 @@ type {{.StructName}} struct {
|
||||
config.Provider
|
||||
log func(context.Context, string, ...any)
|
||||
}
|
||||
`
|
||||
)
|
||||
8
definition/generate/render/tpl/group.go.tpl
Normal file
8
definition/generate/render/tpl/group.go.tpl
Normal file
@@ -0,0 +1,8 @@
|
||||
type {{.StructName}} struct {
|
||||
{{.ParentName}}
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) {{.FuncName}}() {{.StructName}} {
|
||||
return {{.StructName}}{i}
|
||||
}
|
||||
30
definition/generate/render/tpl/option/option.go.tpl
Normal file
30
definition/generate/render/tpl/option/option.go.tpl
Normal file
@@ -0,0 +1,30 @@
|
||||
// read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) read{{.FuncName}}(ctx context.Context) (v {{.Type}},e error) {
|
||||
val, err := i.Value(ctx, {{ .Keys "i" }})
|
||||
if err != nil {
|
||||
{{- if .HasDefault }}
|
||||
i.log({{ if not .SkipContext }}context.Background(){{else}}ctx{{ end }}, "read [%v]: %v",[]string{ {{- .Keys "i" -}} }, err)
|
||||
|
||||
{{ .Default "val" -}}
|
||||
{{ else }}
|
||||
return v, fmt.Errorf("read [%v]:%w",[]string{ {{- .Keys "i" -}} }, err)
|
||||
{{ end }}
|
||||
}
|
||||
|
||||
{{ .Value "val" "v" }}
|
||||
}
|
||||
|
||||
// Read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) Read{{.FuncName}}({{if not .SkipContext}} ctx context.Context {{end}}) ({{.Type}}, error) {
|
||||
return i.read{{.FuncName}}({{if .SkipContext}}context.Background(){{else}}ctx{{end}})
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) {{.FuncName}}({{if not .SkipContext}} ctx context.Context {{end}}) {{.Type}} {
|
||||
val, err := i.read{{.FuncName}}({{ if .SkipContext }}context.Background(){{else}}ctx{{ end }})
|
||||
if err != nil {
|
||||
i.log({{ if .SkipContext }}context.Background(){{else}}ctx{{ end }}, "get [%v]: %v",[]string{ {{- .Keys "i" -}} }, err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
9
definition/generate/render/tpl/proto.go.tpl
Normal file
9
definition/generate/render/tpl/proto.go.tpl
Normal file
@@ -0,0 +1,9 @@
|
||||
type {{.StructName}} struct {
|
||||
{{.ParentName}}
|
||||
{{ .Name }} string
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) {{.FuncName}}(key string) {{.StructName}} {
|
||||
return {{.StructName}}{i,key}
|
||||
}
|
||||
266
definition/generate/render/value.go
Normal file
266
definition/generate/render/value.go
Normal file
@@ -0,0 +1,266 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Value(name, val string, data ViewData) string {
|
||||
rnd := renderType(data)
|
||||
|
||||
res, err := rnd(ValueData{ValName: name, Value: val, ViewData: data})
|
||||
if err != nil {
|
||||
return fmt.Sprintf("render value:%v", err)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func Type(data ViewData) string {
|
||||
dt := data.View.Type()
|
||||
rtype := reflect.TypeOf(dt)
|
||||
|
||||
slice := ""
|
||||
if rtype.Kind() == reflect.Slice {
|
||||
slice = "[]"
|
||||
rtype = rtype.Elem()
|
||||
}
|
||||
|
||||
short := rtype.Name()
|
||||
|
||||
if rtype.PkgPath() != "" {
|
||||
var err error
|
||||
|
||||
short, err = data.AddType(rtype.PkgPath() + "." + rtype.Name())
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
return slice + short
|
||||
}
|
||||
|
||||
func Data(val any, name string, view ViewData) string {
|
||||
fn := renderData(view)
|
||||
|
||||
data, err := fn(val, ValueData{ValName: name, Value: "", ViewData: view})
|
||||
if err != nil {
|
||||
return fmt.Sprintf("render dara:%v", err)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func renderDataTime(val any, _ ValueData) (string, error) {
|
||||
data, _ := val.(time.Time)
|
||||
|
||||
return fmt.Sprintf("time.Parse(%q,time.RFC3339Nano)", data.Format(time.RFC3339Nano)), nil
|
||||
}
|
||||
|
||||
func renderDataDuration(val any, _ ValueData) (string, error) {
|
||||
data, _ := val.(time.Duration)
|
||||
|
||||
return fmt.Sprintf("time.ParseDuration(%q)", data), nil
|
||||
}
|
||||
|
||||
func renderDataUnmarhal(val any, view ValueData) (string, error) {
|
||||
res, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("render data unmarshal:%w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("return {{.%[1]s}}, {{.%[1]s}}.UnmarshalJSON(%q)", view.ValName, res), nil
|
||||
}
|
||||
|
||||
func renderDataUnmarhalText(val any, view ValueData) (string, error) {
|
||||
res, err := json.Marshal(val)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("render data unmarshal:%w", err)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("return {{.%[1]s}}, {{.%[1]s}}.UnmarshalText(%s)", view.ValName, res), nil
|
||||
}
|
||||
|
||||
func renderDataFlag(val any, view ValueData) (string, error) {
|
||||
return fmt.Sprintf("return {{.%[1]s}}, {{.%[1]s}}.Set(%[2]q)", view.ValName, val), nil
|
||||
}
|
||||
|
||||
func renderType(view ViewData) func(data ValueData) (string, error) {
|
||||
return dataRender(view).Type
|
||||
}
|
||||
|
||||
func renderData(view ViewData) func(in any, data ValueData) (string, error) {
|
||||
return dataRender(view).Value
|
||||
}
|
||||
|
||||
func dataRender(view ViewData) DataRender {
|
||||
data := view.View.Type()
|
||||
vtype := reflect.TypeOf(data)
|
||||
|
||||
if vtype.Kind() == reflect.Slice {
|
||||
return render[reflect.TypeFor[json.Unmarshaler]()]
|
||||
}
|
||||
|
||||
if h, ok := render[vtype]; ok {
|
||||
return h
|
||||
}
|
||||
|
||||
if vtype.Kind() != reflect.Interface && vtype.Kind() != reflect.Ptr {
|
||||
vtype = reflect.PointerTo(vtype)
|
||||
}
|
||||
|
||||
for extypes := range render {
|
||||
if extypes == nil || extypes.Kind() != reflect.Interface {
|
||||
continue
|
||||
}
|
||||
|
||||
if vtype.Implements(extypes) {
|
||||
return render[extypes]
|
||||
}
|
||||
}
|
||||
|
||||
return render[reflect.TypeOf((any)(nil))]
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var render = map[reflect.Type]DataRender{
|
||||
reflect.TypeFor[encoding.TextUnmarshaler](): NewDataRender(unmarshalTextType, renderDataUnmarhalText),
|
||||
reflect.TypeFor[json.Unmarshaler](): NewDataRender(unmarshalType, renderDataUnmarhal),
|
||||
reflect.TypeFor[flag.Value](): NewDataRender(flagType, renderDataFlag),
|
||||
reflect.TypeFor[sql.Scanner](): NewDataRender(scanType, nil),
|
||||
reflect.TypeFor[int](): NewDataRender(internalType, nil),
|
||||
reflect.TypeFor[int64](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[bool](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[string](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[float64](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[uint](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[int64](): NewDataRender(internalType, anyValue),
|
||||
reflect.TypeFor[time.Duration](): NewDataRender(durationType, renderDataDuration),
|
||||
reflect.TypeFor[time.Time](): NewDataRender(timeType, renderDataTime),
|
||||
reflect.TypeOf((any)(nil)): NewDataRender(anyType, anyValue),
|
||||
}
|
||||
|
||||
func timeType(data ValueData) (string, error) {
|
||||
return fmt.Sprintf("return %s.ParseTime()", data.ValName), nil
|
||||
}
|
||||
|
||||
func durationType(data ValueData) (string, error) {
|
||||
return fmt.Sprintf("return %s.ParseDuration()", data.ValName), nil
|
||||
}
|
||||
|
||||
func scanType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.Lookup("scan_value.go.tpl").Execute(&b, data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute scan value:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func flagType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.Lookup("flag_value.go.tpl").Execute(&b, data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute flag value:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func anyType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.ExecuteTemplate(&b, "any.go.tpl", data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unmarshal execute any.go.tpl:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func anyValue(data any, _ ValueData) (string, error) {
|
||||
return fmt.Sprintf("return %#v, nil", data), nil
|
||||
}
|
||||
|
||||
func unmarshalType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.ExecuteTemplate(&b, "unmarshal_json.go.tpl", data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("unmarshal execute unmarshal_json.go.tpl:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func unmarshalTextType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.Lookup("unmarshal_text.go.tpl").Execute(&b, data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute unmarshal text:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func internalType(data ValueData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := parceTpls.Lookup("parse.go.tpl").Execute(&b, data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("internal execute parce.go.tpl:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
type ValueData struct {
|
||||
ViewData
|
||||
|
||||
ValName string
|
||||
Value string
|
||||
}
|
||||
|
||||
func (v ValueData) FuncType() string {
|
||||
name := reflect.TypeOf(v.ViewData.Type()).Name()
|
||||
|
||||
return v.Rendering.FuncName(name)
|
||||
}
|
||||
|
||||
type DataRender struct {
|
||||
renderType func(data ValueData) (string, error)
|
||||
renderValue func(data any, view ValueData) (string, error)
|
||||
}
|
||||
|
||||
func (d DataRender) Type(data ValueData) (string, error) {
|
||||
return d.renderType(data)
|
||||
}
|
||||
|
||||
func (d DataRender) Value(data any, view ValueData) (string, error) {
|
||||
return d.renderValue(data, view)
|
||||
}
|
||||
|
||||
func NewDataRender(rendeType func(data ValueData) (string, error), renderValue func(data any, view ValueData) (string, error)) DataRender {
|
||||
if rendeType == nil {
|
||||
rendeType = anyType
|
||||
}
|
||||
|
||||
if renderValue == nil {
|
||||
renderValue = anyValue
|
||||
}
|
||||
|
||||
return DataRender{
|
||||
renderType: rendeType,
|
||||
renderValue: renderValue,
|
||||
}
|
||||
}
|
||||
129
definition/generate/render/value_test.go
Normal file
129
definition/generate/render/value_test.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package render_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition/generate/render"
|
||||
"gitoa.ru/go-4devs/config/definition/generate/view"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
)
|
||||
|
||||
type flagValue int
|
||||
|
||||
func (f flagValue) String() string {
|
||||
return strconv.Itoa(int(f))
|
||||
}
|
||||
|
||||
func (f *flagValue) Set(in string) error {
|
||||
data, err := strconv.Atoi(in)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w", err)
|
||||
}
|
||||
|
||||
*f = flagValue(data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestValue_FlagType(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const ex = `pval, perr := val.ParseString()
|
||||
if perr != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w",[]string{"flagValue"}, perr)
|
||||
}
|
||||
|
||||
return v, v.Set(pval)`
|
||||
|
||||
viewData := render.NewViewData(nil, view.NewView(option.New("flag_value", "flag desc", flagValue(0)), nil))
|
||||
result := render.Value("val", "v", viewData)
|
||||
|
||||
if result != ex {
|
||||
t.Errorf("failed render flag type ex:%s, res:%s", ex, result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestData_Flag(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const ex = `return {{.val}}, {{.val}}.Set("42")`
|
||||
|
||||
viewData := render.NewViewData(nil, view.NewView(option.New("flag_value", "flag desc", flagValue(0)), nil))
|
||||
result := render.Data(flagValue(42), "val", viewData)
|
||||
|
||||
if result != ex {
|
||||
t.Errorf("failed render flag value ex:%s, res:%s", ex, result)
|
||||
}
|
||||
}
|
||||
|
||||
type scanValue int
|
||||
|
||||
func (s *scanValue) Scan(src any) error {
|
||||
res, _ := src.(string)
|
||||
|
||||
data, err := strconv.Atoi(res)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w", err)
|
||||
}
|
||||
|
||||
*s = scanValue(data)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestValue_Scan(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const ex = `return v, v.Scan(val.Any())`
|
||||
|
||||
viewData := render.NewViewData(nil, view.NewView(option.New("scan_value", "scan desc", scanValue(42)), nil))
|
||||
result := render.Value("val", "v", viewData)
|
||||
|
||||
if result != ex {
|
||||
t.Errorf("failed render flag value ex:%s, res:%s", ex, result)
|
||||
}
|
||||
}
|
||||
|
||||
type textData string
|
||||
|
||||
func (j *textData) UnmarshalText(in []byte) error {
|
||||
val := string(in)
|
||||
|
||||
*j = textData(val)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestData_UnmarshalText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const ex = `return {{.val}}, {{.val}}.UnmarshalText("4devs")`
|
||||
|
||||
data := textData("4devs")
|
||||
viewData := render.NewViewData(nil, view.NewView(option.New("tvalue", "unmarshal text desc", textData("")), nil))
|
||||
result := render.Data(data, "val", viewData)
|
||||
|
||||
if result != ex {
|
||||
t.Errorf("failed render flag value ex:%s, res:%s", ex, result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValue_UnmarshalText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const ex = `pval, perr := val.ParseString()
|
||||
if perr != nil {
|
||||
return v, fmt.Errorf("read [%v]:%w", []string{"tvalue"}, perr)
|
||||
}
|
||||
|
||||
return v, v.UnmarshalText([]byte(pval))`
|
||||
|
||||
viewData := render.NewViewData(nil, view.NewView(option.New("tvalue", "unmarshal text desc", textData("")), nil))
|
||||
result := render.Value("val", "v", viewData)
|
||||
|
||||
if result != ex {
|
||||
t.Errorf("failed render flag value ex:%s, res:%s", ex, result)
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
)
|
||||
|
||||
func Run(w io.Writer, pkgName string, defs definition.Definition, viewOpt ViewOption) error {
|
||||
gen := Generator{
|
||||
pkg: pkgName,
|
||||
ViewOption: viewOpt,
|
||||
Imp: NewImports(),
|
||||
}
|
||||
|
||||
gen.Imp.Adds("gitoa.ru/go-4devs/config", "fmt", "context")
|
||||
|
||||
var view bytes.Buffer
|
||||
|
||||
err := defs.View(func(o definition.Option) error {
|
||||
return gen.Handle(&view, &gen, o)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("render options:%w", err)
|
||||
}
|
||||
|
||||
if err := tpl.Execute(w, gen); err != nil {
|
||||
return fmt.Errorf("render base:%w", err)
|
||||
}
|
||||
|
||||
_, cerr := io.Copy(w, &view)
|
||||
if cerr != nil {
|
||||
return fmt.Errorf("copy error:%w", cerr)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
8
definition/generate/tpl/init.go.tpl
Normal file
8
definition/generate/tpl/init.go.tpl
Normal file
@@ -0,0 +1,8 @@
|
||||
// Code generated gitoa.ru/go-4devs/config DO NOT EDIT.
|
||||
package {{.Pkg}}
|
||||
|
||||
import (
|
||||
{{range .Imports}}
|
||||
{{- .Alias }} "{{ .Package }}"
|
||||
{{end}}
|
||||
)
|
||||
@@ -1,63 +0,0 @@
|
||||
package generate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
)
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var handlers = sync.Map{}
|
||||
|
||||
func Add(kind string, h Handle) error {
|
||||
_, ok := handlers.Load(kind)
|
||||
if ok {
|
||||
return fmt.Errorf("kind %v: %w", kind, ErrAlreadyExist)
|
||||
}
|
||||
|
||||
handlers.Store(kind, h)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//nolint:forcetypeassert
|
||||
func get(kind string) Handle {
|
||||
handler, ok := handlers.Load(kind)
|
||||
if !ok {
|
||||
return func(w io.Writer, h Handler, o definition.Option) error {
|
||||
return fmt.Errorf("handler by %v:%w", kind, ErrNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
return handler.(Handle)
|
||||
}
|
||||
|
||||
func MustAdd(kind string, h Handle) {
|
||||
if err := Add(kind, h); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
type Handle func(io.Writer, Handler, definition.Option) error
|
||||
|
||||
type Handler interface {
|
||||
StructName() string
|
||||
Handle(w io.Writer, handler Handler, opt definition.Option) error
|
||||
Options() ViewOption
|
||||
Keys() []string
|
||||
AddType(fullName string) (string, error)
|
||||
DefaultErrors() []string
|
||||
}
|
||||
|
||||
type ViewOption struct {
|
||||
Prefix, Suffix string
|
||||
Context bool
|
||||
Struct string
|
||||
Errors ViewErrors
|
||||
}
|
||||
|
||||
type ViewErrors struct {
|
||||
Default []string
|
||||
}
|
||||
191
definition/generate/view/view.go
Normal file
191
definition/generate/view/view.go
Normal file
@@ -0,0 +1,191 @@
|
||||
package view
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const (
|
||||
viewParamFunctName key = iota + 1
|
||||
viewParamSkipContext
|
||||
)
|
||||
|
||||
func WithSkipContext(p param.Params) param.Params {
|
||||
return param.With(p, viewParamSkipContext, true)
|
||||
}
|
||||
|
||||
func WithContext(p param.Params) param.Params {
|
||||
return param.With(p, viewParamSkipContext, false)
|
||||
}
|
||||
|
||||
func IsSkipContext(p param.Params) bool {
|
||||
data, has := p.Param(viewParamSkipContext)
|
||||
|
||||
if has {
|
||||
skip, ok := data.(bool)
|
||||
|
||||
return ok && skip
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
type Option func(*View)
|
||||
|
||||
func WithParent(name string) Option {
|
||||
return func(v *View) {
|
||||
v.parent = name
|
||||
}
|
||||
}
|
||||
|
||||
func WithKeys(keys ...string) Option {
|
||||
return func(v *View) {
|
||||
v.keys = keys
|
||||
}
|
||||
}
|
||||
|
||||
func NewViews(name string, get param.Params, option config.Options, opts ...Option) View {
|
||||
view := newView(name, get, option, opts...)
|
||||
|
||||
for _, op := range option.Options() {
|
||||
view.children = append(view.children, NewView(op, get, WithParent(name)))
|
||||
}
|
||||
|
||||
return view
|
||||
}
|
||||
|
||||
type IOption any
|
||||
|
||||
func newView(name string, get param.Params, in any, opts ...Option) View {
|
||||
vi := View{
|
||||
kind: reflect.TypeOf(in),
|
||||
name: name,
|
||||
Params: get,
|
||||
dtype: param.Type(get),
|
||||
children: nil,
|
||||
keys: nil,
|
||||
parent: "",
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&vi)
|
||||
}
|
||||
|
||||
return vi
|
||||
}
|
||||
|
||||
func NewView(opt config.Option, get param.Params, opts ...Option) View {
|
||||
vi := newView(opt.Name(), param.Chain(get, opt), opt, opts...)
|
||||
|
||||
if data, ok := opt.(config.Group); ok {
|
||||
for _, chi := range data.Options() {
|
||||
vi.children = append(vi.children, NewView(
|
||||
chi,
|
||||
param.Chain(vi.Params, chi),
|
||||
WithParent(vi.ParentName()+"_"+opt.Name()),
|
||||
WithKeys(append(vi.keys, opt.Name())...),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
return vi
|
||||
}
|
||||
|
||||
type View struct {
|
||||
param.Params
|
||||
|
||||
children []View
|
||||
keys []string
|
||||
kind reflect.Type
|
||||
name string
|
||||
parent string
|
||||
dtype any
|
||||
}
|
||||
|
||||
func (v View) Types() []any {
|
||||
types := make([]any, 0)
|
||||
if v.dtype != nil {
|
||||
types = append(types, v.dtype)
|
||||
}
|
||||
|
||||
for _, child := range v.children {
|
||||
types = append(types, child.Types()...)
|
||||
}
|
||||
|
||||
return types
|
||||
}
|
||||
|
||||
func (v View) Kind() reflect.Type {
|
||||
return v.kind
|
||||
}
|
||||
|
||||
func (v View) Views() []View {
|
||||
return v.children
|
||||
}
|
||||
|
||||
func (v View) Param(key any) string {
|
||||
data, ok := v.Params.Param(key)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
if res, ok := data.(string); ok {
|
||||
return res
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%v", data)
|
||||
}
|
||||
|
||||
func (v View) SkipContext() bool {
|
||||
return IsSkipContext(v.Params)
|
||||
}
|
||||
|
||||
func (v View) Name() string {
|
||||
return v.name
|
||||
}
|
||||
|
||||
func (v View) Keys() []string {
|
||||
return v.keys
|
||||
}
|
||||
|
||||
func (v View) Type() any {
|
||||
return v.dtype
|
||||
}
|
||||
|
||||
func (v View) FuncName() string {
|
||||
data, ok := v.Params.Param(viewParamFunctName)
|
||||
name, valid := data.(string)
|
||||
|
||||
if !ok || !valid {
|
||||
return v.name
|
||||
}
|
||||
|
||||
return name
|
||||
}
|
||||
|
||||
func (v View) ParentName() string {
|
||||
return v.parent
|
||||
}
|
||||
|
||||
func (v View) Description() string {
|
||||
return option.DataDescription(v.Params)
|
||||
}
|
||||
|
||||
func (v View) Default() any {
|
||||
data, ok := option.DataDefaut(v.Params)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func (v View) HasDefault() bool {
|
||||
return option.HasDefaut(v.Params)
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
module gitoa.ru/go-4devs/config/definition
|
||||
|
||||
go 1.21
|
||||
|
||||
require github.com/iancoleman/strcase v0.3.0
|
||||
@@ -1,2 +0,0 @@
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
35
definition/group/group.go
Executable file → Normal file
35
definition/group/group.go
Executable file → Normal file
@@ -1,27 +1,34 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
const Kind = "group"
|
||||
var _ config.Group = New("", "")
|
||||
|
||||
var _ definition.Option = Group{}
|
||||
|
||||
func New(name, desc string, opts ...definition.Option) Group {
|
||||
return Group{
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Options: opts,
|
||||
func New(name, desc string, opts ...config.Option) Group {
|
||||
group := Group{
|
||||
name: name,
|
||||
opts: opts,
|
||||
Params: param.New(option.Description(desc)),
|
||||
}
|
||||
|
||||
return group
|
||||
}
|
||||
|
||||
type Group struct {
|
||||
Options definition.Options
|
||||
Name string
|
||||
Description string
|
||||
param.Params
|
||||
|
||||
name string
|
||||
opts []config.Option
|
||||
}
|
||||
|
||||
func (o Group) Kind() string {
|
||||
return Kind
|
||||
func (g Group) Name() string {
|
||||
return g.name
|
||||
}
|
||||
|
||||
func (g Group) Options() []config.Option {
|
||||
return g.opts
|
||||
}
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
package group
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate"
|
||||
)
|
||||
|
||||
//nolint:gochecknoinits
|
||||
func init() {
|
||||
generate.MustAdd(Kind, handle)
|
||||
}
|
||||
|
||||
func handle(w io.Writer, data generate.Handler, option definition.Option) error {
|
||||
group, ok := option.(Group)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w:%T", generate.ErrWrongType, option)
|
||||
}
|
||||
|
||||
viewData := View{
|
||||
Group: group,
|
||||
ParentName: data.StructName(),
|
||||
ViewOption: data.Options(),
|
||||
}
|
||||
|
||||
err := tpl.Execute(w, viewData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("render group:%w", err)
|
||||
}
|
||||
|
||||
childData := ChildData{
|
||||
Handler: data,
|
||||
structName: viewData.StructName(),
|
||||
keys: append(data.Keys(), group.Name),
|
||||
}
|
||||
for idx, child := range group.Options {
|
||||
if cerr := data.Handle(w, childData, child); cerr != nil {
|
||||
return fmt.Errorf("render group child[%d]:%w", idx, cerr)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type ChildData struct {
|
||||
generate.Handler
|
||||
structName string
|
||||
keys []string
|
||||
}
|
||||
|
||||
func (c ChildData) StructName() string {
|
||||
return c.structName
|
||||
}
|
||||
|
||||
func (c ChildData) Keys() []string {
|
||||
return c.keys
|
||||
}
|
||||
|
||||
type View struct {
|
||||
Group
|
||||
ParentName string
|
||||
generate.ViewOption
|
||||
}
|
||||
|
||||
func (v View) FuncName() string {
|
||||
return generate.FuncName(v.Name)
|
||||
}
|
||||
|
||||
func (v View) StructName() string {
|
||||
return generate.FuncName(v.Prefix + v.Name + v.Suffix)
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
tpl = template.Must(template.New("tpls").Parse(gpoupTemplate))
|
||||
gpoupTemplate = `type {{.StructName}} struct {
|
||||
{{.ParentName}}
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.ParentName}}) {{.FuncName}}() {{.StructName}} {
|
||||
return {{.StructName}}{i}
|
||||
}
|
||||
`
|
||||
)
|
||||
@@ -1,27 +0,0 @@
|
||||
package definition
|
||||
|
||||
type Option interface {
|
||||
Kind() string
|
||||
}
|
||||
|
||||
type Options []Option
|
||||
|
||||
func (s Options) Len() int { return len(s) }
|
||||
func (s Options) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
|
||||
type Params []Param
|
||||
|
||||
func (p Params) Get(name string) (any, bool) {
|
||||
for _, param := range p {
|
||||
if param.Name == name {
|
||||
return param.Value, true
|
||||
}
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
type Param struct {
|
||||
Name string
|
||||
Value any
|
||||
}
|
||||
30
definition/option/errors.go
Normal file
30
definition/option/errors.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package option
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Key []string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (o Error) Error() string {
|
||||
return fmt.Sprintf("%s: %s", o.Key, o.Err)
|
||||
}
|
||||
|
||||
func (o Error) Is(err error) bool {
|
||||
return errors.Is(err, o.Err)
|
||||
}
|
||||
|
||||
func (o Error) Unwrap() error {
|
||||
return o.Err
|
||||
}
|
||||
|
||||
func Err(err error, key []string) Error {
|
||||
return Error{
|
||||
Key: key,
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
102
definition/option/option.go
Executable file → Normal file
102
definition/option/option.go
Executable file → Normal file
@@ -1,100 +1,66 @@
|
||||
package option
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"time"
|
||||
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
var _ definition.Option = Option{}
|
||||
var _ config.Option = New("", "", nil)
|
||||
|
||||
const (
|
||||
Kind = "option"
|
||||
)
|
||||
|
||||
const (
|
||||
TypeString = "string"
|
||||
TypeInt = "int"
|
||||
TypeInt64 = "int64"
|
||||
TypeUint = "uint"
|
||||
TypeUint64 = "uint64"
|
||||
TypeFloat64 = "float64"
|
||||
TypeBool = "bool"
|
||||
TypeTime = "time.Time"
|
||||
TypeDuration = "time.Duration"
|
||||
)
|
||||
|
||||
func Default(v any) func(*Option) {
|
||||
return func(o *Option) {
|
||||
o.Default = v
|
||||
}
|
||||
}
|
||||
|
||||
func New(name, desc string, vtype any, opts ...func(*Option)) Option {
|
||||
option := Option{
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Type: vtype,
|
||||
func New(name, desc string, vtype any, opts ...param.Option) Option {
|
||||
opts = append(opts, Description(desc), WithType(vtype))
|
||||
res := Option{
|
||||
name: name,
|
||||
Params: param.New(opts...),
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&option)
|
||||
}
|
||||
|
||||
return option
|
||||
return res
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
Name string
|
||||
Description string
|
||||
Type any
|
||||
Default any
|
||||
Params definition.Params
|
||||
param.Params
|
||||
|
||||
name string
|
||||
}
|
||||
|
||||
func (o Option) WithParams(params ...definition.Param) Option {
|
||||
return Option{
|
||||
Name: o.Name,
|
||||
Description: o.Description,
|
||||
Type: o.Type,
|
||||
Params: append(params, o.Params...),
|
||||
}
|
||||
func (o Option) Name() string {
|
||||
return o.name
|
||||
}
|
||||
|
||||
func (o Option) Kind() string {
|
||||
return Kind
|
||||
func String(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, "", opts...)
|
||||
}
|
||||
|
||||
func Time(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeTime, opts...)
|
||||
func Bool(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, false, opts...)
|
||||
}
|
||||
|
||||
func Duration(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeDuration, opts...)
|
||||
func Duration(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, time.Duration(0), opts...)
|
||||
}
|
||||
|
||||
func String(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeString, opts...)
|
||||
func Float64(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, float64(0), opts...)
|
||||
}
|
||||
|
||||
func Int(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeInt, opts...)
|
||||
func Int(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, int(0), opts...)
|
||||
}
|
||||
|
||||
func Int64(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeInt64, opts...)
|
||||
func Int64(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, int64(0), opts...)
|
||||
}
|
||||
|
||||
func Uint(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeUint, opts...)
|
||||
func Time(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, time.Time{}, opts...)
|
||||
}
|
||||
|
||||
func Uint64(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeUint64, opts...)
|
||||
func Uint(name, description string, opts ...param.Option) Option {
|
||||
return New(name, description, uint(0), opts...)
|
||||
}
|
||||
|
||||
func Float64(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeFloat64, opts...)
|
||||
}
|
||||
|
||||
func Bool(name, desc string, opts ...func(*Option)) Option {
|
||||
return New(name, desc, TypeBool, opts...)
|
||||
func Uint64(name, descriontion string, opts ...param.Option) Option {
|
||||
return New(name, descriontion, uint64(0), opts...)
|
||||
}
|
||||
|
||||
125
definition/option/params.go
Normal file
125
definition/option/params.go
Normal file
@@ -0,0 +1,125 @@
|
||||
package option
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
const (
|
||||
paramHidden key = iota + 1
|
||||
paramDefault
|
||||
paramDesc
|
||||
paramRequired
|
||||
paramSlice
|
||||
paramBool
|
||||
paramPos
|
||||
paramShort
|
||||
)
|
||||
|
||||
func Short(in rune) param.Option {
|
||||
return func(v param.Params) param.Params {
|
||||
return param.With(v, paramShort, string(in))
|
||||
}
|
||||
}
|
||||
|
||||
func ParamShort(fn param.Params) (string, bool) {
|
||||
data, ok := param.String(fn, paramShort)
|
||||
|
||||
return data, ok
|
||||
}
|
||||
|
||||
func HasShort(short string) param.Has {
|
||||
return func(fn param.Params) bool {
|
||||
data, ok := param.String(fn, paramShort)
|
||||
|
||||
return ok && data == short
|
||||
}
|
||||
}
|
||||
|
||||
func WithType(in any) param.Option {
|
||||
return func(v param.Params) param.Params {
|
||||
out := param.WithType(in)(v)
|
||||
if _, ok := in.(bool); ok {
|
||||
return param.With(out, paramBool, ok)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
func Position(pos uint64) param.Option {
|
||||
return func(p param.Params) param.Params {
|
||||
return param.With(p, paramPos, pos)
|
||||
}
|
||||
}
|
||||
|
||||
func Hidden(v param.Params) param.Params {
|
||||
return param.With(v, paramHidden, true)
|
||||
}
|
||||
|
||||
func Required(v param.Params) param.Params {
|
||||
return param.With(v, paramRequired, true)
|
||||
}
|
||||
|
||||
func Slice(v param.Params) param.Params {
|
||||
return param.With(v, paramSlice, true)
|
||||
}
|
||||
|
||||
func Default(in any) param.Option {
|
||||
return func(v param.Params) param.Params {
|
||||
return param.With(v, paramDefault, in)
|
||||
}
|
||||
}
|
||||
|
||||
func Description(in string) param.Option {
|
||||
return func(v param.Params) param.Params {
|
||||
return param.With(v, paramDesc, in)
|
||||
}
|
||||
}
|
||||
|
||||
func HasDefaut(fn param.Params) bool {
|
||||
_, ok := fn.Param(paramDefault)
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func DataPosition(fn param.Params) (uint64, bool) {
|
||||
return param.Uint64(paramPos, fn)
|
||||
}
|
||||
|
||||
func DataDefaut(fn param.Params) (any, bool) {
|
||||
data, ok := fn.Param(paramDefault)
|
||||
|
||||
return data, ok
|
||||
}
|
||||
|
||||
func IsSlice(fn param.Params) bool {
|
||||
data, ok := param.Bool(paramSlice, fn)
|
||||
|
||||
return ok && data
|
||||
}
|
||||
|
||||
func IsBool(fn param.Params) bool {
|
||||
data, ok := param.Bool(paramBool, fn)
|
||||
|
||||
return ok && data
|
||||
}
|
||||
|
||||
func IsHidden(fn param.Params) bool {
|
||||
data, ok := param.Bool(paramHidden, fn)
|
||||
|
||||
return ok && data
|
||||
}
|
||||
|
||||
func IsRequired(fn param.Params) bool {
|
||||
data, ok := param.Bool(paramRequired, fn)
|
||||
|
||||
return ok && data
|
||||
}
|
||||
|
||||
func DataDescription(fn param.Params) string {
|
||||
data, _ := param.String(fn, paramDesc)
|
||||
|
||||
return data
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) read{{.FuncName}}(ctx context.Context) (v {{.Type}},e error) {
|
||||
val, err := i.Value(ctx, {{ .ParentKeys }}"{{ .Name }}")
|
||||
if err != nil {
|
||||
{{if .HasDefault}}
|
||||
{{$default := .Default}}
|
||||
{{range .DefaultErrors}}
|
||||
if errors.Is(err,{{.}}){
|
||||
return {{$default}}
|
||||
}
|
||||
{{end}}
|
||||
{{end}}
|
||||
return v, fmt.Errorf("read {{.Keys}}:%w",err)
|
||||
}
|
||||
|
||||
{{.Parse "val" "v" .Keys }}
|
||||
}
|
||||
|
||||
// Read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) Read{{.FuncName}}(ctx context.Context) ({{.Type}}, error) {
|
||||
return i.read{{.FuncName}}(ctx)
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) {{.FuncName}}({{if .Context}} ctx context.Context {{end}}) {{.Type}} {
|
||||
{{if not .Context}} ctx := context.Background() {{end}}
|
||||
val, err := i.read{{.FuncName}}(ctx)
|
||||
if err != nil {
|
||||
i.log(ctx, "get {{.Keys}}: %v", err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{{block "UnmarshalJSON" . }}
|
||||
pval, perr := {{.ValName}}.ParseString()
|
||||
if perr != nil {
|
||||
return {{.Value}}, fmt.Errorf("read {{.Keys}}:%w", perr)
|
||||
}
|
||||
|
||||
return {{.Value}}, {{.Value}}.UnmarshalJSON([]byte(pval))
|
||||
{{end}}
|
||||
@@ -1,8 +0,0 @@
|
||||
{{block "UnmarshalText" . }}
|
||||
pval, perr := {{.ValName}}.ParseString()
|
||||
if perr != nil {
|
||||
return {{.Value}}, fmt.Errorf("read {{.Keys}}:%w", perr)
|
||||
}
|
||||
|
||||
return {{.Value}}, {{.Value}}.UnmarshalText([]byte(pval))
|
||||
{{end}}
|
||||
@@ -1,235 +0,0 @@
|
||||
package option
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"encoding"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate"
|
||||
)
|
||||
|
||||
//go:embed tpl/*
|
||||
var tpls embed.FS
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var tpl = template.Must(template.New("tpls").ParseFS(tpls, "tpl/*.tmpl"))
|
||||
|
||||
//nolint:gochecknoinits
|
||||
func init() {
|
||||
generate.MustAdd(Kind, Handle(tpl.Lookup("option.tmpl")))
|
||||
}
|
||||
|
||||
func Handle(tpl *template.Template) generate.Handle {
|
||||
return func(w io.Writer, h generate.Handler, o definition.Option) error {
|
||||
opt, _ := o.(Option)
|
||||
if err := tpl.Execute(w, View{Option: opt, Handler: h}); err != nil {
|
||||
return fmt.Errorf("option tpl:%w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
type View struct {
|
||||
Option
|
||||
generate.Handler
|
||||
}
|
||||
|
||||
func (v View) Context() bool {
|
||||
return v.Options().Context
|
||||
}
|
||||
|
||||
func (v View) FuncName() string {
|
||||
if funcName, ok := v.Option.Params.Get(ViewParamFunctName); ok {
|
||||
name, _ := funcName.(string)
|
||||
|
||||
return name
|
||||
}
|
||||
|
||||
return generate.FuncName(v.Name)
|
||||
}
|
||||
|
||||
func (v View) Description() string {
|
||||
if desc, ok := v.Option.Params.Get(ViewParamDescription); ok {
|
||||
description, _ := desc.(string)
|
||||
|
||||
return description
|
||||
}
|
||||
|
||||
return v.Option.Description
|
||||
}
|
||||
|
||||
func (v View) Default() string {
|
||||
switch data := v.Option.Default.(type) {
|
||||
case time.Time:
|
||||
return fmt.Sprintf("time.Parse(%q,time.RFC3339Nano)", data.Format(time.RFC3339Nano))
|
||||
case time.Duration:
|
||||
return fmt.Sprintf("time.ParseDuration(%q)", data)
|
||||
default:
|
||||
return fmt.Sprintf("%#v, nil", data)
|
||||
}
|
||||
}
|
||||
|
||||
func (v View) HasDefault() bool {
|
||||
return v.Option.Default != nil
|
||||
}
|
||||
|
||||
func (v View) ParentKeys() string {
|
||||
if len(v.Handler.Keys()) > 0 {
|
||||
return `"` + strings.Join(v.Handler.Keys(), `","`) + `",`
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (v View) Type() string {
|
||||
slice := ""
|
||||
|
||||
if vtype, ok := v.Option.Type.(string); ok {
|
||||
if strings.Contains(vtype, ".") {
|
||||
if name, err := v.AddType(vtype); err == nil {
|
||||
return slice + name
|
||||
}
|
||||
}
|
||||
|
||||
return vtype
|
||||
}
|
||||
|
||||
rtype := reflect.TypeOf(v.Option.Type)
|
||||
|
||||
if rtype.PkgPath() == "" {
|
||||
return rtype.String()
|
||||
}
|
||||
|
||||
if rtype.Kind() == reflect.Slice {
|
||||
slice = "[]"
|
||||
}
|
||||
|
||||
short, err := v.AddType(rtype.PkgPath() + "." + rtype.Name())
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
return slice + short
|
||||
}
|
||||
|
||||
func (v View) FuncType() string {
|
||||
return generate.FuncName(v.Type())
|
||||
}
|
||||
|
||||
func (v View) Parse(valName string, value string, keys []string) string {
|
||||
h := parser(v.Option.Type)
|
||||
|
||||
data, err := h(ParseData{
|
||||
Value: value,
|
||||
ValName: valName,
|
||||
Keys: keys,
|
||||
View: v,
|
||||
})
|
||||
if err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals,unparam
|
||||
var parses = map[string]func(data ParseData) (string, error){
|
||||
typesIntreface[0].Name(): func(data ParseData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := tpl.ExecuteTemplate(&b, "unmarshal_text.tmpl", data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute unmarshal text:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
},
|
||||
typesIntreface[1].Name(): func(data ParseData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := tpl.ExecuteTemplate(&b, "unmarshal_json.tmpl", data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute unmarshal json:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
},
|
||||
TypeInt: internal,
|
||||
TypeInt64: internal,
|
||||
TypeBool: internal,
|
||||
TypeString: internal,
|
||||
TypeFloat64: internal,
|
||||
TypeUint: internal,
|
||||
TypeUint64: internal,
|
||||
"time.Duration": func(data ParseData) (string, error) {
|
||||
return fmt.Sprintf("return %s.ParseDuration()", data.ValName), nil
|
||||
},
|
||||
"time.Time": func(data ParseData) (string, error) {
|
||||
return fmt.Sprintf("return %s.ParseTime()", data.ValName), nil
|
||||
},
|
||||
"any": func(data ParseData) (string, error) {
|
||||
return fmt.Sprintf("return %[2]s, %[1]s.Unmarshal(&%[2]s)", data.ValName, data.Value), nil
|
||||
},
|
||||
}
|
||||
|
||||
func internal(data ParseData) (string, error) {
|
||||
var b bytes.Buffer
|
||||
|
||||
err := tpl.ExecuteTemplate(&b, "parse.tmpl", data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("execute parse.tmpl:%w", err)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var typesIntreface = [...]reflect.Type{
|
||||
reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem(),
|
||||
reflect.TypeOf((*json.Unmarshaler)(nil)).Elem(),
|
||||
}
|
||||
|
||||
func parser(data any) func(ParseData) (string, error) {
|
||||
vtype := reflect.TypeOf(data)
|
||||
name := vtype.Name()
|
||||
|
||||
if v, ok := data.(string); ok {
|
||||
name = v
|
||||
}
|
||||
|
||||
if vtype.Kind() == reflect.Slice {
|
||||
return parses["any"]
|
||||
}
|
||||
|
||||
if h, ok := parses[name]; ok {
|
||||
return h
|
||||
}
|
||||
|
||||
for _, extypes := range typesIntreface {
|
||||
if vtype.Implements(extypes) {
|
||||
return parses[extypes.Name()]
|
||||
}
|
||||
|
||||
if vtype.Kind() != reflect.Ptr && reflect.PointerTo(vtype).Implements(extypes) {
|
||||
return parses[extypes.Name()]
|
||||
}
|
||||
}
|
||||
|
||||
return parses["any"]
|
||||
}
|
||||
|
||||
type ParseData struct {
|
||||
Value string
|
||||
ValName string
|
||||
Keys []string
|
||||
View
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package option
|
||||
|
||||
const (
|
||||
ViewParamFunctName = "view.funcName"
|
||||
ViewParamDescription = "view.description"
|
||||
)
|
||||
@@ -1,27 +1,33 @@
|
||||
package proto
|
||||
|
||||
import (
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
"gitoa.ru/go-4devs/config/key"
|
||||
"gitoa.ru/go-4devs/config/param"
|
||||
)
|
||||
|
||||
const Kind = "proto"
|
||||
var _ config.Group = New("", "")
|
||||
|
||||
func New(name, desc string, opt definition.Option) Proto {
|
||||
pr := Proto{
|
||||
Name: name,
|
||||
Description: desc,
|
||||
Option: opt,
|
||||
func New(name string, desc string, opts ...config.Option) Proto {
|
||||
return Proto{
|
||||
name: key.Wild(name),
|
||||
opts: opts,
|
||||
Params: param.New(option.Description(desc)),
|
||||
}
|
||||
|
||||
return pr
|
||||
}
|
||||
|
||||
type Proto struct {
|
||||
Name string
|
||||
Description string
|
||||
Option definition.Option
|
||||
param.Params
|
||||
|
||||
opts []config.Option
|
||||
name string
|
||||
}
|
||||
|
||||
func (p Proto) Kind() string {
|
||||
return Kind
|
||||
func (p Proto) Options() []config.Option {
|
||||
return p.opts
|
||||
}
|
||||
|
||||
func (p Proto) Name() string {
|
||||
return p.name
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
package proto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/config/definition"
|
||||
"gitoa.ru/go-4devs/config/definition/generate"
|
||||
"gitoa.ru/go-4devs/config/definition/option"
|
||||
)
|
||||
|
||||
//nolint:gochecknoinits
|
||||
func init() {
|
||||
generate.MustAdd(Kind, handle)
|
||||
}
|
||||
|
||||
func handle(w io.Writer, data generate.Handler, opt definition.Option) error {
|
||||
proto, ok := opt.(Proto)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w:%T", generate.ErrWrongType, opt)
|
||||
}
|
||||
|
||||
if viewOpt, ok := proto.Option.(option.Option); ok {
|
||||
viewOpt = viewOpt.WithParams(
|
||||
definition.Param{
|
||||
Name: option.ViewParamFunctName,
|
||||
Value: generate.FuncName(proto.Name) + generate.FuncName(viewOpt.Name),
|
||||
},
|
||||
definition.Param{
|
||||
Name: option.ViewParamDescription,
|
||||
Value: proto.Description + " " + viewOpt.Description,
|
||||
},
|
||||
)
|
||||
|
||||
return option.Handle(tpl)(w, data, viewOpt)
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w:%T", generate.ErrWrongType, opt)
|
||||
}
|
||||
|
||||
//nolint:gochecknoglobals
|
||||
var (
|
||||
tpl = template.Must(template.New("tpls").Funcs(template.FuncMap{"join": strings.Join}).Parse(templateOption))
|
||||
templateOption = `// read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) read{{.FuncName}}(ctx context.Context, key string) (v {{.Type}},e error) {
|
||||
val, err := i.Value(ctx, {{ .ParentKeys }} key, "{{.Name}}")
|
||||
if err != nil {
|
||||
{{if .HasDefault}}
|
||||
{{$default := .Default}}
|
||||
{{range .DefaultErrors}}
|
||||
if errors.Is(err,{{.}}){
|
||||
return {{$default}}
|
||||
}
|
||||
{{end}}
|
||||
{{end}}
|
||||
return v, fmt.Errorf("read {{.Keys}}:%w",err)
|
||||
}
|
||||
|
||||
{{.Parse "val" "v" .Keys }}
|
||||
}
|
||||
|
||||
// Read{{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) Read{{.FuncName}}(ctx context.Context, key string) ({{.Type}}, error) {
|
||||
return i.read{{.FuncName}}(ctx, key)
|
||||
}
|
||||
|
||||
// {{.FuncName}} {{.Description}}.
|
||||
func (i {{.StructName}}) {{.FuncName}}({{if .Context}} ctx context.Context, {{end}} key string) {{.Type}} {
|
||||
{{if not .Context}} ctx := context.Background() {{end}}
|
||||
val, err := i.read{{.FuncName}}(ctx, key)
|
||||
if err != nil {
|
||||
i.log(ctx, "get {{.Keys}}: %v", err)
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
`
|
||||
)
|
||||
Reference in New Issue
Block a user