## Summary: In this commit I remove one of the limitations of our support for interfaces, from #52, by adding support for list-of-interface fields. This was surprisingly complex! The issue is that, as before, it's the containing type that has to do all the glue work -- and it's that glue work that is complicated by list-of-interface fields. All in all, it's not that much new code, and by far the hard part is just 20 lines in the UnmarshalJSON template (which come with almost twice as many lines of comments to explain them). It may be easiest to start by reading some of the generated code, and then read the template. I also added support for such fields with `pointer: true` specified, such that the type is `[][]...[]*MyInterface`, although I don't know why you would want that. This does *not* allow e.g. `*[]*[][]*MyInterface`; that would require a way to specify it (see #16) but also add some extra complexity (as we'd have to actually walk the type-unwrap chain properly, instead of just counting the number of slices and whether there's a pointer). Issue: https://github.com/Khan/genqlient/issues/8 ## Test plan: make check Author: benjaminjkraft Reviewers: dnerdy, benjaminjkraft, aberkan, csilvers, MiguelCastillo Required Reviewers: Approved by: dnerdy Checks: ⌛ Test (1.17), ⌛ Test (1.16), ⌛ Test (1.15), ⌛ Test (1.14), ⌛ Test (1.13), ⌛ Lint, ⌛ Lint, ⌛ Test (1.17), ⌛ Test (1.16), ⌛ Test (1.15), ⌛ Test (1.14), ⌛ Test (1.13) Pull request URL: https://github.com/Khan/genqlient/pull/54
58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package generate
|
|
|
|
import (
|
|
"io"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"text/template"
|
|
)
|
|
|
|
var (
|
|
_, thisFilename, _, _ = runtime.Caller(0)
|
|
thisDir = filepath.Dir(thisFilename)
|
|
)
|
|
|
|
func repeat(n int, s string) string {
|
|
var builder strings.Builder
|
|
for i := 0; i < n; i++ {
|
|
builder.WriteString(s)
|
|
}
|
|
return builder.String()
|
|
}
|
|
|
|
func intRange(n int) []int {
|
|
ret := make([]int, n)
|
|
for i := 0; i < n; i++ {
|
|
ret[i] = i
|
|
}
|
|
return ret
|
|
}
|
|
|
|
func sub(x, y int) int { return x - y }
|
|
|
|
// execute executes the given template with the funcs from this generator.
|
|
func (g *generator) execute(tmplRelFilename string, w io.Writer, data interface{}) error {
|
|
tmpl := g.templateCache[tmplRelFilename]
|
|
if tmpl == nil {
|
|
absFilename := filepath.Join(thisDir, tmplRelFilename)
|
|
funcMap := template.FuncMap{
|
|
"ref": g.ref,
|
|
"repeat": repeat,
|
|
"intRange": intRange,
|
|
"sub": sub,
|
|
}
|
|
var err error
|
|
tmpl, err = template.New(tmplRelFilename).Funcs(funcMap).ParseFiles(absFilename)
|
|
if err != nil {
|
|
return errorf(nil, "could not load template %v: %v", absFilename, err)
|
|
}
|
|
g.templateCache[tmplRelFilename] = tmpl
|
|
}
|
|
err := tmpl.Execute(w, data)
|
|
if err != nil {
|
|
return errorf(nil, "could not render template: %v", err)
|
|
}
|
|
return nil
|
|
}
|