Skip to content

Commit

Permalink
Also generate json schema using the JSON name as the primary name (#19)
Browse files Browse the repository at this point in the history
* Add .jsonschema.json files that use the jsonNames as the primary field name

* lint
  • Loading branch information
Alfus authored Jul 29, 2024
1 parent fd4028e commit 5101e22
Show file tree
Hide file tree
Showing 24 changed files with 6,215 additions and 50 deletions.
53 changes: 31 additions & 22 deletions internal/cmd/jsonschema-generate-testdata/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
_ "github.com/bufbuild/protoschema-plugins/internal/gen/proto/bufext/cel/expr/conformance/proto3"
"github.com/bufbuild/protoschema-plugins/internal/protoschema/golden"
"github.com/bufbuild/protoschema-plugins/internal/protoschema/jsonschema"
"google.golang.org/protobuf/reflect/protoreflect"
)

func main() {
Expand All @@ -40,37 +41,45 @@ func run() error {
return fmt.Errorf("usage: %s [output dir]", os.Args[0])
}
outputDir := os.Args[1]
// Make sure the directory exists
if err := os.MkdirAll(outputDir, 0755); err != nil {
return err
}

testDescs, err := golden.GetTestDescriptors("./internal/testdata")
if err != nil {
return err
}
for _, testDesc := range testDescs {
// Generate the JSON schema
result := jsonschema.Generate(testDesc)

// Make sure the directory exists
if err := os.MkdirAll(outputDir, 0755); err != nil {
// Generate the JSON schema with proto names.
if err := writeJSONSchema(outputDir, jsonschema.Generate(testDesc)); err != nil {
return err
}
// Generate the JSON schema with JSON names.
if err := writeJSONSchema(outputDir, jsonschema.Generate(testDesc, jsonschema.WithJSONNames())); err != nil {
return err
}
}
return nil
}

for _, jsonSchema := range result {
// Serialize the JSON
data, err := json.MarshalIndent(jsonSchema, "", " ")
if err != nil {
return err
}
identifier, ok := jsonSchema["$id"].(string)
if !ok {
return errors.New("expected $id to be a string")
}
if identifier == "" {
return errors.New("expected $id to be non-empty")
}
filePath := filepath.Join(outputDir, identifier)
if err := golden.GenerateGolden(filePath, string(data)+"\n"); err != nil {
return err
}
func writeJSONSchema(outputDir string, schema map[protoreflect.FullName]map[string]interface{}) error {
for _, jsonSchema := range schema {
// Serialize the JSON
data, err := json.MarshalIndent(jsonSchema, "", " ")
if err != nil {
return err
}
identifier, ok := jsonSchema["$id"].(string)
if !ok {
return errors.New("expected $id to be a string")
}
if identifier == "" {
return errors.New("expected $id to be non-empty")
}
filePath := filepath.Join(outputDir, identifier)
if err := golden.GenerateGolden(filePath, string(data)+"\n"); err != nil {
return err
}
}
return nil
Expand Down
37 changes: 30 additions & 7 deletions internal/protoschema/jsonschema/jsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,38 @@ const (
FieldIgnore
)

// Generate generates a JSON schema for the given message descriptor.
func Generate(input protoreflect.MessageDescriptor) map[protoreflect.FullName]map[string]interface{} {
type GeneratorOption func(*jsonSchemaGenerator)

// WithJSONNames sets the generator to use JSON field names as the primary name.
func WithJSONNames() GeneratorOption {
return func(p *jsonSchemaGenerator) {
p.useJSONNames = true
}
}

// Generate generates a JSON schema for the given message descriptor, with protobuf field names.
func Generate(input protoreflect.MessageDescriptor, opts ...GeneratorOption) map[protoreflect.FullName]map[string]interface{} {
generator := &jsonSchemaGenerator{
result: make(map[protoreflect.FullName]map[string]interface{}),
}
generator.custom = generator.makeWktGenerators()
for _, opt := range opts {
opt(generator)
}
generator.generate(input)
return generator.result
}

type jsonSchemaGenerator struct {
result map[protoreflect.FullName]map[string]interface{}
custom map[protoreflect.FullName]func(map[string]interface{}, protoreflect.MessageDescriptor)
result map[protoreflect.FullName]map[string]interface{}
custom map[protoreflect.FullName]func(map[string]interface{}, protoreflect.MessageDescriptor)
useJSONNames bool
}

func (p *jsonSchemaGenerator) getID(desc protoreflect.Descriptor) string {
if p.useJSONNames {
return string(desc.FullName()) + ".jsonschema.json"
}
return string(desc.FullName()) + ".schema.json"
}

Expand Down Expand Up @@ -94,13 +110,20 @@ func (p *jsonSchemaGenerator) generateDefault(result map[string]interface{}, des
// TODO: Add an option to include custom alias.
aliases := make([]string, 0, 1)

if visibility == FieldHide {
switch {
case visibility == FieldHide:
aliases = append(aliases, string(field.Name()))
if field.JSONName() != string(field.Name()) {
aliases = append(aliases, field.JSONName())
}
} else {
// TODO: Optionally make the json name the 'primary' name.
case p.useJSONNames:
// Use the JSON name as the primary name.
properties[field.JSONName()] = fieldSchema
if field.JSONName() != string(field.Name()) {
aliases = append(aliases, string(field.Name()))
}
default:
// Use the proto name as the primary name.
properties[string(field.Name())] = fieldSchema
if field.JSONName() != string(field.Name()) {
aliases = append(aliases, field.JSONName())
Expand Down
59 changes: 38 additions & 21 deletions internal/protoschema/plugin/pluginjsonschema/pluginjsonschema.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

"github.com/bufbuild/protoplugin"
"github.com/bufbuild/protoschema-plugins/internal/protoschema/jsonschema"
"google.golang.org/protobuf/reflect/protoreflect"
)

// Handle implements protoplugin.Handler and is the main entry point for the plugin.
Expand All @@ -38,31 +39,47 @@ func Handle(
for _, fileDescriptor := range fileDescriptors {
for i := range fileDescriptor.Messages().Len() {
messageDescriptor := fileDescriptor.Messages().Get(i)

for _, entry := range jsonschema.Generate(messageDescriptor) {
data, err := json.MarshalIndent(entry, "", " ")
if err != nil {
return err
}
identifier, ok := entry["$id"].(string)
if !ok {
return fmt.Errorf("expected unique id for message %q to be a string, got type %T", messageDescriptor.FullName(), entry["$id"])
}
if identifier == "" {
return fmt.Errorf("expected unique id for message %q to be a non-empty string", messageDescriptor.FullName())
}
if seenIdentifiers[identifier] {
continue
}
responseWriter.AddFile(
identifier,
string(data)+"\n",
)
seenIdentifiers[identifier] = true
protoNameSchema := jsonschema.Generate(messageDescriptor)
if err := writeFiles(responseWriter, messageDescriptor, protoNameSchema, seenIdentifiers); err != nil {
return err
}
jsonNameSchema := jsonschema.Generate(messageDescriptor, jsonschema.WithJSONNames())
if err := writeFiles(responseWriter, messageDescriptor, jsonNameSchema, seenIdentifiers); err != nil {
return err
}
}
}

responseWriter.SetFeatureProto3Optional()
return nil
}

func writeFiles(
responseWriter protoplugin.ResponseWriter,
messageDescriptor protoreflect.MessageDescriptor,
schema map[protoreflect.FullName]map[string]interface{},
seenIdentifiers map[string]bool,
) error {
for _, entry := range schema {
data, err := json.MarshalIndent(entry, "", " ")
if err != nil {
return err
}
identifier, ok := entry["$id"].(string)
if !ok {
return fmt.Errorf("expected unique id for message %q to be a string, got type %T", messageDescriptor.FullName(), entry["$id"])
}
if identifier == "" {
return fmt.Errorf("expected unique id for message %q to be a non-empty string", messageDescriptor.FullName())
}
if seenIdentifiers[identifier] {
continue
}
responseWriter.AddFile(
identifier,
string(data)+"\n",
)
seenIdentifiers[identifier] = true
}
return nil
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 5101e22

Please sign in to comment.