-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathgen.go
More file actions
62 lines (52 loc) · 1.34 KB
/
gen.go
File metadata and controls
62 lines (52 loc) · 1.34 KB
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
package process
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"google.golang.org/protobuf/proto"
"github.com/sqlc-dev/sqlc/internal/plugin"
)
type Runner struct {
Cmd string
Env []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),
}
for _, key := range r.Env {
if key == "SQLC_AUTH_TOKEN" {
continue
}
cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", key, os.Getenv(key)))
}
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
}