-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate.go
46 lines (39 loc) · 1.1 KB
/
generate.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
package jsonschema
import (
"encoding/json"
"log"
"os"
"path"
"github.com/invopop/jsonschema"
)
// Generate returns a formatted JSON schema for the input struct, according to the tags
// defined by https://github.com/invopop/jsonschema
func Generate(a any, options ...Option) ([]byte, error) {
reflector := &jsonschema.Reflector{
RequiredFromJSONSchemaTags: true,
NullableFromType: true,
}
for _, opt := range options {
opt(reflector)
}
sc := reflector.Reflect(a)
if err := Sanitize(sc); err != nil {
return nil, err
}
return json.MarshalIndent(sc, "", " ")
}
func GenerateIntoFile(a any, filePath string, options ...Option) {
data, err := Generate(a, options...)
if err != nil {
log.Fatalf("failed to generate JSON schema for %T", a)
}
ensureDir(filePath)
if err = os.WriteFile(filePath, append(data, '\n'), 0o644); err != nil {
log.Fatalf("failed to write file %s: %s", filePath, err.Error())
}
}
func ensureDir(filePath string) {
if err := os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil {
log.Fatalf("failed to create dir for file %s: %v", filePath, err)
}
}