forked from ns1/jsonschema2go
/
printer.go
60 lines (51 loc) · 1.3 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package print
import (
"bytes"
"context"
"fmt"
"github.com/jwilner/jsonschema2go/pkg/gen"
"go/format"
"io"
"text/template"
)
var baseImports = []string{"fmt"} // used for error messaging
type Printer interface {
Print(ctx context.Context, w io.Writer, goPath string, plans []gen.Plan) error
}
//go:generate go run ../cmd/embedtmpl/embedtmpl.go print values.tmpl tmpl.gen.go
func New(t *template.Template) Printer {
if t == nil {
t = tmpl
}
return &printer{t}
}
type printer struct {
tmpl *template.Template
}
func (p *printer) Print(ctx context.Context, w io.Writer, goPath string, plans []gen.Plan) error {
depPaths := make([]string, len(baseImports))
copy(depPaths, baseImports)
for _, pl := range plans {
for _, d := range pl.Deps() {
depPaths = append(depPaths, d.GoPath)
}
}
imps := gen.NewImports(goPath, depPaths)
var buf bytes.Buffer
if err := p.tmpl.Execute(&buf, &Plans{imps, defaultSort(plans)}); err != nil {
return fmt.Errorf("unable to execute tmpl: %w", err)
}
formatted, err := format.Source(buf.Bytes())
if err != nil {
if gen.IsDebug(ctx) {
_, _ = w.Write(buf.Bytes()) // write unformatted for debugging
}
return fmt.Errorf("unable to format: %w", err)
}
_, err = w.Write(formatted)
return err
}
type Plans struct {
Imports *gen.Imports
Plans []gen.Plan
}