Skip to content

Commit

Permalink
First commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
atombender committed Sep 27, 2018
0 parents commit 6720f94
Show file tree
Hide file tree
Showing 31 changed files with 2,493 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Alexander Staubo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
123 changes: 123 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
**go-jsonschema is a tool to generate Go data types from [JSON Schema](http://json-schema.org/) definitions.**

This tool generates Go data types and structs that corresponds to definitions in the schema, along with unmarshaling code that validates the input JSON according to the schema's validation rules.

## Status

While not finished, go-jsonschema can be used today. Aside from some minor features, only specific validations remain to be fully implemented.

### Validation

- Core ([RFC draft](http://json-schema.org/latest/json-schema-core.html))
- [x] Data model (§4.2.1)
- [x] `null`
- [x] `boolean`
- [x] `object`
- [x] `array`
- [x] `number`
- [ ] Option to use `json.Number`
- [x] `string`
- [ ] Location identifiers (§8.2.3)
- [x] References against top-level names: `#/Definitions/someName`
- [ ] References against nested names: `#/Definitions/someName/Definitions/someOtherName`
- [x] References against top-level names in external files: `myschema.json#/Definitions/someName`
- [ ] References against nested names: `myschema.json#/Definitions/someName/Definitions/someOtherName`
- [x] Comments (§9)
- Validation ([RFC draft](http://json-schema.org/latest/json-schema-validation.html))
- [ ] Schema annotations (§10)
- [x] `description`
- [ ] `default`
- [ ] `readOnly`
- [ ] `writeOnly`
- [ ] ~~`title`~~ (N/A)
- [ ] ~~`examples`~~ (N/A)
- [ ] General validation (§6.1)
- [x] `enum`
- [x] `type`
- [ ] `const`
- [ ] Numeric validation (§6.2)
- [ ] `multipleOf`
- [ ] `maximum`
- [ ] `exclusiveMaximum`
- [ ] `minimum`
- [ ] `exclusiveMinimum`
- [ ] String validation (§6.3)
- [ ] `maxLength`
- [ ] `minLength`
- [ ] `pattern`
- [ ] Array validation (§6.4)
- [X] `items`
- [ ] `maxItems`
- [ ] `minItems`
- [ ] `uniqueItems`
- [ ] `additionalItems`
- [ ] `contains`
- [ ] Object validation (§6.5)
- [x] `required`
- [x] `properties`
- [ ] `patternProperties`
- [ ] `dependencies`
- [ ] `propertyNames`
- [ ] `maxProperties`
- [ ] `minProperties`
- [ ] Conditional subschemas (§6.6)
- [ ] `if`
- [ ] `then`
- [ ] `else`
- [ ] Boolean subschemas (§6.7)
- [ ] `allOf`
- [ ] `anyOf`
- [ ] `oneOf`
- [ ] `not`
- [ ] Semantic formats (§7.3)
- [ ] Dates and times
- [ ] Email addresses
- [ ] Hostnames
- [ ] IP addresses
- [ ] Resource identifiers
- [ ] URI-template
- [ ] JSON pointers
- [ ] Regex

## Usage

At its most basic:

```shell
$ gojsonschema -p main schema.json
```

This will write a Go source file to standard output, declared under the package `main`.

You can generate code for multiple schemas in the same invocation, optionally writing to different files inside different packages:

```shell
$ gojsonschema \
--schema-package=https://example.com/schema1=github.com/myuser/myproject \
--schema-output=https://example.com/schema1=schema1.go \
--schema-package=https://example.com/schema2=github.com/myuser/myproject/stuff \
--schema-output=https://example.com/schema2=stuff/schema2.go \
schema1.json schema2.json
```

This will create `schema1.go` (declared as `package myproject`) and `stuff/schema2.go` (declared as `package stuff`). If `schema1.json` refers to `schema2.json` or vice versa, the two Go files will import the other package that it depends on. Note the flag format:

```
--schema-package=https://example.com/schema1=github.com/myuser/myproject \
^ ^
| |
schema $id full import URL
```

## Installing

Requires Go 1.11 or later, with Go modules enabled. To install:

```shell
$ go get github.com/atombender/go-jsonschema/...
$ go install github.com/atombender/go-jsonschema/cmd/gojsonschema
```

## License

BSD license. See `LICENSE` file.
198 changes: 198 additions & 0 deletions cmd/gojsonschema/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package main

import (
"fmt"
"go/format"
"os"
"strings"

"github.com/spf13/cobra"

"github.com/atombender/go-jsonschema/pkg/generator"
"github.com/atombender/go-jsonschema/pkg/schemas"
)

var (
verbose bool
defaultPackage string
defaultOutput string
schemaPackages []string
schemaOutputs []string
schemaRootTypes []string
)

var rootCmd = &cobra.Command{
Use: "gojsonschema FILE ...",
Short: "Generates Go code from JSON Schema files.",
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
abort("No arguments specified. Run with --help for usage.")
}

if defaultPackage == "" && len(schemaPackages) == 0 {
abort("Package name not specified.")
}

schemaPackageMap, err := stringSliceToStringMap(schemaPackages)
if err != nil {
abortWithErr(err)
}

schemaOutputMap, err := stringSliceToStringMap(schemaOutputs)
if err != nil {
abortWithErr(err)
}

schemaRootTypeMap, err := stringSliceToStringMap(schemaRootTypes)
if err != nil {
abortWithErr(err)
}

schemaMappings := []generator.SchemaMapping{}
for _, id := range allKeys(schemaPackageMap, schemaOutputMap, schemaRootTypeMap) {
mapping := generator.SchemaMapping{SchemaID: id}
if s, ok := schemaPackageMap[id]; ok {
mapping.PackageName = s
} else {
mapping.PackageName = defaultPackage
}
if s, ok := schemaOutputMap[id]; ok {
mapping.OutputName = s
} else {
mapping.OutputName = defaultOutput
}
if s, ok := schemaRootTypeMap[id]; ok {
mapping.RootType = s
}
schemaMappings = append(schemaMappings, mapping)
}

generator, err := generator.New(schemaMappings, defaultPackage, defaultOutput, func(message string) {
log("Warning: %s", message)
})
if err != nil {
abortWithErr(err)
}

for _, fileName := range args {
verboseLog("Loading %s", fileName)

f, err := os.Open(fileName)
if err != nil {
abortWithErr(err)
}
defer func() { _ = f.Close() }()

schema, err := schemas.FromReader(f)
if err != nil {
abortWithErr(err)
}
_ = f.Close()

if err = generator.AddFile(fileName, schema); err != nil {
abortWithErr(err)
}
}

for fileName, source := range generator.Sources() {
if fileName != "-" {
verboseLog("Writing %s", fileName)
}

src, err := format.Source(source)
if err != nil {
verboseLog("the generated code could not be formatted automatically; "+
"falling back to unformatted: %s", err)
src = source
}

if fileName == "-" {
if _, err = os.Stdout.Write(src); err != nil {
abortWithErr(err)
}
} else {
w, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
abortWithErr(err)
}
defer func() { _ = w.Close() }()
if _, err = w.Write(src); err != nil {
abortWithErr(err)
}
_ = w.Close()
}
}

os.Exit(0)
},
}

func main() {
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false,
"Verbose output")
rootCmd.PersistentFlags().StringVarP(&defaultPackage, "package", "p", "",
"Default name of package to declare Go files under, unless overridden with --schema-package")
rootCmd.PersistentFlags().StringVarP(&defaultOutput, "output", "o", "-",
"File to write (- for standard output)")
rootCmd.PersistentFlags().StringSliceVar(&schemaPackages, "schema-package", nil,
"Name of package to declare Go files for a specific schema ID under; "+
"must be in the format URI=PACKAGE.")
rootCmd.PersistentFlags().StringSliceVar(&schemaOutputs, "schema-output", nil,
"File to write (- for standard output) a specific schema ID to; "+
"must be in the format URI=PACKAGE.")
rootCmd.PersistentFlags().StringSliceVar(&schemaRootTypes, "schema-root-type", nil,
"Override name to use for the root type of a specific schema ID; "+
"must be in the format URI=PACKAGE. By default, it is derived from the file name.")

abortWithErr(rootCmd.Execute())
}

func abortWithErr(err error) {
if err != nil {
abort(err.Error())
}
}

func abort(message string) {
log("Failed: %s", message)
os.Exit(1)
}

func stringSliceToStringMap(s []string) (map[string]string, error) {
result := make(map[string]string, len(s))
for _, p := range s {
i := strings.IndexRune(p, '=')
if i == -1 {
return nil, fmt.Errorf("flag must be in the format URI=PACKAGE: %q", p)
}
result[p[0:i]] = p[i+1:]
}
return result, nil
}

func allKeys(in ...map[string]string) []string {
type dummy struct{}
keySet := map[string]dummy{}
for _, m := range in {
for k := range m {
keySet[k] = dummy{}
}
}
result := make([]string, 0, len(keySet))
for k := range keySet {
result = append(result, k)
}
return result
}

func log(format string, args ...interface{}) {
fmt.Fprint(os.Stderr, "gojsonschema: ")
fmt.Fprintf(os.Stderr, format, args...)
fmt.Fprint(os.Stderr, "\n")
}

func verboseLog(format string, args ...interface{}) {
if verbose {
log(format, args...)
}
}
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/atombender/go-jsonschema

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/golangci/golangci-lint v1.10.2
github.com/mitchellh/go-wordwrap v1.0.0
github.com/sanity-io/litter v1.1.0
github.com/spf13/cobra v0.0.3
github.com/spf13/pflag v1.0.2 // indirect
github.com/stretchr/testify v1.2.2 // indirect
)
Loading

0 comments on commit 6720f94

Please sign in to comment.