-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoutput.go
50 lines (43 loc) · 1.13 KB
/
output.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
package codegen
import (
"bytes"
"fmt"
"go/parser"
"go/printer"
"go/token"
"io"
"io/ioutil"
"github.com/pkg/errors"
)
func Output(ctx *GenContext, filePath string) error {
if ctx.PackageName == "" {
return errors.New("missing package name")
}
var unformatted bytes.Buffer
fmt.Fprint(&unformatted, "// Code generated by go-codegen; DO NOT EDIT.\n\n")
fmt.Fprintf(&unformatted, "package %s\n", ctx.PackageName)
outputImports(ctx.Imports(), &unformatted)
for _, g := range ctx.Generated() {
fmt.Fprintln(&unformatted, g)
}
// Parsing and printing ensures formatting.
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, filePath, unformatted.Bytes(), parser.ParseComments)
if err != nil {
fmt.Println(unformatted.String())
return errors.Wrap(err, "parsing generated code")
}
var formatted bytes.Buffer
printer.Fprint(&formatted, fset, file)
return ioutil.WriteFile(filePath, formatted.Bytes(), 0644)
}
func outputImports(imports []string, w io.Writer) {
if len(imports) == 0 {
return
}
fmt.Fprintln(w, "import (")
for _, i := range imports {
fmt.Fprintf(w, "\t\"%s\"\n", i)
}
fmt.Fprintln(w, ")")
}