Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support recursive arrays / arrays of references (plus a bunch of other changes) #55

Merged
merged 13 commits into from
Feb 4, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
fixes for multi-type, nested references, nested arrays, marshal & unm…
…arshal additionalProperties
  • Loading branch information
mwlazlo committed Oct 9, 2018
commit 9f4cd2a5724e7bab8d172902a86722344021c8f7
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/schema-generate
.idea
test/*_gen
13 changes: 11 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,31 @@ BIN := schema-generate

all: clean $(BIN)

$(BIN):
$(BIN): generator.go jsonschema/jsonschema.go cmd/schema-generate/main.go
@echo "+ Building $@"
CGO_ENABLED="0" go build -v -o $@ $(CMD)

clean:
@echo "+ Cleaning $(PKG)"
go clean -i $(PKG)/...
rm -f $(BIN)
rm -rf test/*_gen

# Test

# generate sources
JSON := $(wildcard test/*.json)
GENERATED_SOURCE := $(patsubst %.json,%_gen/generated.go,$(JSON))
test/%_gen/generated.go: test/%.json
mkdir $(shell echo $^ | sed 's/.json/_gen/')
./schema-generate -o $@ -p $(shell echo $^ | sed 's/test\///; s/.json//') $^

.PHONY: test codecheck fmt lint vet

test:
test: $(BIN) $(GENERATED_SOURCE)
@echo "+ Executing tests for $(PKG)"
go test -v -race -cover $(PKG)/...


codecheck: fmt lint vet

Expand Down
142 changes: 140 additions & 2 deletions cmd/schema-generate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,10 @@ func main() {

g := generate.New(schemas...)

structs, aliases, err := g.CreateTypes()
err := g.CreateTypes()
if err != nil {
fmt.Fprintln(os.Stderr, "Failure generating structs: ", err)
os.Exit(1)
}

var w io.Writer = os.Stdout
Expand All @@ -91,7 +92,7 @@ func main() {
}
}

output(w, structs, aliases)
output(w, g.Structs, g.Aliases)
}

func lineAndCharacter(bytes []byte, offset int) (line int, character int, err error) {
Expand Down Expand Up @@ -145,6 +146,23 @@ func output(w io.Writer, structs map[string]generate.Struct, aliases map[string]
fmt.Fprintln(w)
fmt.Fprintf(w, "package %v\n", *p)

willEmitCode := false
for _, v := range structs {
if v.AdditionalValueType != "" {
willEmitCode = true
}
}

if willEmitCode {
fmt.Fprintf(w, `
import (
"fmt"
"encoding/json"
"bytes"
)
`)
}

for _, k := range getOrderedFieldNames(aliases) {
a := aliases[k]

Expand All @@ -169,11 +187,131 @@ func output(w io.Writer, structs map[string]generate.Struct, aliases map[string]
omitempty = ""
}

if f.Comment != "" {
fmt.Fprintf(w, " // %s\n", f.Comment)
}

fmt.Fprintf(w, " %s %s `json:\"%s%s\"`\n", f.Name, f.Type, f.JSONName, omitempty)
}

fmt.Fprintln(w, "}")

if s.AdditionalValueType != "" {
emitMarshalCode(w, s)
emitUnmarshalCode(w, s)
}
}
}

func emitMarshalCode(w io.Writer, s generate.Struct) {
fmt.Fprintf(w,
`
func (strct *%s) MarshalJSON() ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 0))
buf.WriteString("{")
comma := false
`, s.Name)
// Marshal all the defined fields
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.JSONName == "-" {
continue
}
fmt.Fprintf(w,
` // Marshal the "%s" field
if comma {
buf.WriteString(",")
}
buf.WriteString("\"%s\": ")
if tmp, err := json.Marshal(strct.%s); err != nil {
return nil, err
} else {
buf.Write(tmp)
}
comma = true
`, f.JSONName, f.JSONName, f.Name)
}
fmt.Fprintf(w, " // Marshal any additional Properties\n")
// Marshal any additional Properties
fmt.Fprintf(w, ` for k, v := range strct.AdditionalProperties {
if comma {
buf.WriteString(",")
}
buf.WriteString(fmt.Sprintf("\"%%s\":", k))
if tmp, err := json.Marshal(v); err != nil {
return nil, err
} else {
buf.Write(tmp)
}
comma = true
}

buf.WriteString("}")
rv := buf.Bytes()
return rv, nil
}
`)
}

func emitUnmarshalCode(w io.Writer, s generate.Struct) {
// unmarshal code
fmt.Fprintf(w, `
func (strct *%s) UnmarshalJSON(b []byte) error {
var jsonMap map[string]json.RawMessage
if err := json.Unmarshal(b, &jsonMap); err != nil {
return err
}
// first parse all the defined properties
for k, v := range jsonMap {
switch k {
`, s.Name)
// handle defined properties
for _, fieldKey := range getOrderedFieldNames(s.Fields) {
f := s.Fields[fieldKey]
if f.JSONName == "-" {
continue
}
fmt.Fprintf(w, ` case "%s":
if err := json.Unmarshal([]byte(v), &strct.%s); err != nil {
return err
}
`, f.JSONName, f.Name)
}
// now handle additional values
initialiser, isPrimitive := getPrimitiveInitialiser(s.AdditionalValueType)
addressOfInitialiser := "&"
if isPrimitive {
addressOfInitialiser = ""
}
fmt.Fprintf(w, ` default:
// an additional "%s" value
additionalValue := %s
if err := json.Unmarshal([]byte(v), &additionalValue); err != nil {
return err
}
if strct.AdditionalProperties == nil {
strct.AdditionalProperties = make(map[string]%s, 0)
}
strct.AdditionalProperties[k]= %sadditionalValue
`, s.AdditionalValueType, initialiser, s.AdditionalValueType, addressOfInitialiser)
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, " }\n")
fmt.Fprintf(w, " return nil\n")
fmt.Fprintf(w, "}\n")
}

func getPrimitiveInitialiser(typ string) (string, bool) {
// strip *pointer dereference symbol so we can use in declaration
deref := strings.Replace(typ, "*", "", 1)
switch {
case strings.HasPrefix(deref, "int"):
return "0", true
case strings.HasPrefix(deref, "float"):
return "0.0", true
case deref == "string":
return "\"\"", true
}
return deref + "{}", false
}

func outputNameAndDescriptionComment(name, description string, w io.Writer) {
Expand Down
Loading