The next generation of go-storage definitions

Hi, I’m working on the next generation of go-storage definitions.

About go-storage definitions: Go-storage Source Code Reading: Code Generation

I plan to use Xuanwo/gg to replace the code template that used in definitions. Here is the first PR: https://github.com/beyondstorage/go-storage/pull/728

Before

// Code generated by go generate cmd/definitions; DO NOT EDIT.
package pairs

import (
    "context"
    "time"

    "github.com/beyondstorage/go-storage/v4/pkg/httpclient"
    . "github.com/beyondstorage/go-storage/v4/types"

)

{{- range $_, $v := .Pairs }}
{{- $pname := $v.Name | toPascal }}
// With{{ $pname }} will apply {{ $v.Name }} value to Options.
//
{{ $v.Description }}
func With{{ $pname }}(v {{ $v.Type }}) Pair {
    return Pair{
        Key: "{{ $v.Name }}",
        Value: v,
    }
}

{{ if $v.Defaultable }}
// WithDefault{{ $pname }} will apply default_{{ $v.Name }} value to Options.
//
{{ $v.Description }}
func WithDefault{{ $pname }}(v {{ $v.Type }}) Pair {
    return Pair{
        Key: "default_{{ $v.Name }}",
        Value: v,
    }
}
{{- end }}
{{- end }}

After

func generatePair(data *Data, path string) {
	f := gg.Group()
	f.Comment("Code generated by go generate cmd/definitions; DO NOT EDIT.")
	f.Package("pairs")
	f.Imports().
		Path("context").
		Path("time").
		Line().
		Path("github.com/beyondstorage/go-storage/v4/pkg/httpclient").
		Dot("github.com/beyondstorage/go-storage/v4/types")

	ps := make([]*Pair, 0, len(data.Pairs))
	for _, v := range data.Pairs {
		v := v
		ps = append(ps, v)
	}
	sort.SliceStable(ps, func(i, j int) bool {
		return ps[i].Name < ps[j].Name
	})

	for _, v := range ps {
		pname := templateutils.ToPascal(v.Name)

		xfn := f.Function("With" + pname)

		xfn.CommentF(`With%s will apply %s value to Options.

%s %s`, pname, v.Name, pname, v.originalDescription)
		xfn.Parameter("v", v.Type())
		xfn.Result("p", "Pair")
		xfn.Body(
			gg.Embed(func() gg.Node {
				r := gg.Return()
				r.Value("Pair").
					Field("Key", gg.Lit(v.Name).String()).
					Field("Value", "v")
				return r
			}),
		)
		if v.Defaultable {
			name := "default_" + v.Name
			pname := templateutils.ToPascal(name)

			xfn := f.Function("With" + pname)

			xfn.CommentF(`With%s will apply %s value to Options.

%s %s`, pname, name, pname, v.originalDescription)
			xfn.Parameter("v", v.Type())
			xfn.Result("p", "Pair")
			xfn.Body(
				gg.Embed(func() gg.Node {
					r := gg.Return()
					r.Value("Pair").
						Field("Key", gg.Lit(name).String()).
						Field("Value", "v")
					return r
				}),
			)
		}
	}

	err := f.WriteFile(path)
	if err != nil {
		log.Fatalf("generate to %s: %v", path, err)
	}
}

I’m going to replace more complex parts like services and operations.


Welcome for any comments!

1 Like