forked from checkinholiday/prisma-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
101 lines (79 loc) · 2.21 KB
/
generator.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"path"
"github.com/steebchen/prisma-client-go/generator"
"github.com/steebchen/prisma-client-go/jsonrpc"
"github.com/steebchen/prisma-client-go/logger"
)
const DmmfWriteKey = "PRISMA_CLIENT_GO_WRITE_DMMF_FILE"
var writeDebugFile = os.Getenv(DmmfWriteKey) != ""
func reply(w io.Writer, data interface{}) error {
b, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("could not marshal data %w", err)
}
b = append(b, byte('\n'))
if _, err = w.Write(b); err != nil {
return fmt.Errorf("could not write data %w", err)
}
return nil
}
func invokePrisma() error {
reader := bufio.NewReader(os.Stdin)
if logger.Enabled || writeDebugFile {
dir, _ := os.Getwd()
log.Printf("current working dir: %s", dir)
}
for {
content, err := reader.ReadBytes('\n')
if errors.Is(err, io.EOF) {
logger.Debug.Printf("warning: ignoring EOF error. stdin: `%s`", content)
return nil
}
if err != nil {
return fmt.Errorf("could not read bytes from stdin: %w", err)
}
if writeDebugFile {
if err := os.WriteFile("dmmf.json", content, 0600); err != nil {
return fmt.Errorf("could not write dmmf.json: %w", err)
}
}
var input jsonrpc.Request
if err := json.Unmarshal(content, &input); err != nil {
return fmt.Errorf("could not open stdin %w", err)
}
var response interface{}
switch input.Method {
case "getManifest":
response = jsonrpc.ManifestResponse{
Manifest: jsonrpc.Manifest{
DefaultOutput: path.Join(".", "db"),
PrettyName: "Prisma Client Go",
},
}
case "generate":
response = nil // success
var params generator.Root
if err := json.Unmarshal(input.Params, ¶ms); err != nil {
dir, _ := os.Getwd()
return fmt.Errorf("could not unmarshal params into generator.Root type at %s: %w", dir, err)
}
generator.Transform(¶ms)
if err := generator.Run(¶ms); err != nil {
return fmt.Errorf("could not generate code. %w", err)
}
default:
return fmt.Errorf("no such method %s", input.Method)
}
if err := reply(os.Stderr, jsonrpc.NewResponse(input.ID, response)); err != nil {
return fmt.Errorf("could not reply %w", err)
}
}
}