-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
75 lines (61 loc) · 1.73 KB
/
main.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"os/exec"
"text/template"
"github.com/sqlc-dev/plugin-sdk-go/codegen"
"github.com/sqlc-dev/plugin-sdk-go/plugin"
)
func main() {
codegen.Run(generate)
}
type Options struct {
Template string `json:"template" yaml:"template"`
Filename string `json:"filename" yaml:"filename"`
FormatterCommand string `json:"formatter_cmd" yaml:"formatter_cmd"`
Out string `json:"out" yaml:"out"`
}
func parseOpts(req *plugin.GenerateRequest) (*Options, error) {
var options Options
if len(req.PluginOptions) == 0 {
return &options, nil
}
if err := json.Unmarshal(req.PluginOptions, &options); err != nil {
return nil, fmt.Errorf("unmarshalling plugin options: %w", err)
}
return &options, nil
}
func generate(ctx context.Context, req *plugin.GenerateRequest) (*plugin.GenerateResponse, error) {
// fmt.Println(req)
options, _ := parseOpts(req)
templateFileName := options.Template
tmpl, err := template.ParseFiles(templateFileName)
if err != nil {
log.Fatalf("Error parsing template file: %v", err)
}
resp := plugin.GenerateResponse{}
var buf bytes.Buffer
err = tmpl.Execute(&buf, req)
if err != nil {
log.Fatalf("Error executing template: %v", err)
}
if options.FormatterCommand != "" {
execCommand := exec.Command("/usr/bin/env", "bash", "-c", options.FormatterCommand)
execCommand.Stdin = bytes.NewReader(buf.Bytes())
var output bytes.Buffer
execCommand.Stdout = &output
if err := execCommand.Run(); err != nil {
log.Fatalf("Error executing formatter command: %v", err)
}
buf = output
}
resp.Files = append(resp.Files, &plugin.File{
Name: options.Filename,
Contents: buf.Bytes(),
})
return &resp, nil
}