diff --git a/go.mod b/go.mod index e0b4879..a7df8be 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armmanagedapplications v1.1.1 github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/solutions/armmanagedapplications v1.1.1 github.com/google/go-cmp v0.5.9 - github.com/invopop/jsonschema v0.10.0 + github.com/invopop/jsonschema v0.11.0 github.com/jpillora/longestcommon v0.0.0-20161227235612-adb9d91ee629 golang.org/x/exp v0.0.0-20230905200255-921286631fa9 ) diff --git a/go.sum b/go.sum index b725de6..08b31c4 100644 --- a/go.sum +++ b/go.sum @@ -19,8 +19,8 @@ github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOW github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= -github.com/invopop/jsonschema v0.10.0 h1:c1ktzNLBun3LyQQhyty5WE3lulbOdIIyOVlkmDLehcE= -github.com/invopop/jsonschema v0.10.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0= +github.com/invopop/jsonschema v0.11.0 h1:tdAVvos5ttrsYLyEuVymkVVK31EFpwnTu5hWiyYLGWA= +github.com/invopop/jsonschema v0.11.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/jpillora/longestcommon v0.0.0-20161227235612-adb9d91ee629 h1:1dSBUfGlorLAua2CRx0zFN7kQsTpE2DQSmr7rrTNgY8= github.com/jpillora/longestcommon v0.0.0-20161227235612-adb9d91ee629/go.mod h1:mb5nS4uRANwOJSZj8rlCWAfAcGi72GGMIXx+xGOjA7M= diff --git a/jsonschema/jsonschema.go b/jsonschema/jsonschema.go index cf4bfe4..aa86e68 100644 --- a/jsonschema/jsonschema.go +++ b/jsonschema/jsonschema.go @@ -2,7 +2,9 @@ package jsonschema import ( "encoding/json" - "reflect" + "log" + "os" + "path" "github.com/invopop/jsonschema" ) @@ -10,6 +12,24 @@ import ( // 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) ([]byte, error) { - sc := (&jsonschema.Reflector{RequiredFromJSONSchemaTags: true}).ReflectFromType(reflect.TypeOf(a)) + sc := (&jsonschema.Reflector{RequiredFromJSONSchemaTags: true}).Reflect(a) return json.MarshalIndent(sc, "", " ") } + +func GenerateIntoFile(a any, filePath string) { + data, err := Generate(a) + 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) + } +}