fanktom / jsonschema

A Go package that parses JSON Schema documents and generates go types including validations
MIT License
6 stars 0 forks source link

Duplicates and Broken code is generated #1

Open franzen opened 4 years ago

franzen commented 4 years ago

Test case

Use the following code to generate the data structures

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"

    jsonschema "github.com/tfkhsr/jsonschema"
    golang "github.com/tfkhsr/jsonschema/golang"
)

func main() {
    url := "https://raw.githubusercontent.com/microsoft/botframework-sdk/master/schemas/protocol/botframework.json"
    fmt.Println("fetch", url)

    response, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()
    schema, _ := ioutil.ReadAll(response.Body)

    idx, err := jsonschema.Parse(schema)
    if err != nil {
        panic(err)
    }

    src, err := golang.PackageSrc(idx, "bot")
    if err != nil {
        panic(err)
    }

    output := "data.go"
    fmt.Println("writing", output)
    err = ioutil.WriteFile(output, src, 0644)
    if err != nil {
        panic(err)
    }
    fmt.Println("done")
}

The generated data.go file is broken

Duplicates

Contains duplicates like:

type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction
type Buttons []CardAction

Wrong Property used

The generated code mixes the names of the created properties, eg. ConversationAccount and Conversation, see the following code generated:

type Activity struct {
...
    Conversation     *ConversationAccount   `json:"ConversationAccount,omitempty"`
...
}

and


func (t *Activity) Validate() error {
...
    err = t.ConversationAccount.Validate()
...
}
fanktom commented 4 years ago

Dear @franzen , thanks for the report.

The code of the jsonschema package was part of a simple POC and I am not surprised it does not work for more complicated settings. There most certainly are problems with more complicated naming, nested structures, etc.

Unfortunately I currently do not have time to look into the issues myself. However, I will happily assist in any PRs that fix or improve the aforementioned issues.