forked from sqlc-dev/sqlc
/
gen.go
54 lines (44 loc) · 1.17 KB
/
gen.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
package process
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"google.golang.org/protobuf/proto"
"github.com/StanVerse/sqld/internal/plugin"
)
type Runner struct {
Cmd string
}
// TODO: Update the gen func signature to take a ctx
func (r Runner) Generate(ctx context.Context, req *plugin.CodeGenRequest) (*plugin.CodeGenResponse, error) {
stdin, err := proto.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to encode codegen request: %s", err)
}
// Check if the output plugin exists
path, err := exec.LookPath(r.Cmd)
if err != nil {
return nil, fmt.Errorf("process: %s not found", r.Cmd)
}
cmd := exec.CommandContext(ctx, path)
cmd.Stdin = bytes.NewReader(stdin)
cmd.Env = []string{
fmt.Sprintf("SQLC_VERSION=%s", req.SqlcVersion),
}
out, err := cmd.Output()
if err != nil {
stderr := err.Error()
var exit *exec.ExitError
if errors.As(err, &exit) {
stderr = string(exit.Stderr)
}
return nil, fmt.Errorf("process: error running command %s", stderr)
}
var resp plugin.CodeGenResponse
if err := proto.Unmarshal(out, &resp); err != nil {
return nil, fmt.Errorf("process: failed to read codegen resp: %s", err)
}
return &resp, nil
}