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

Validate multiple files #2

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ go 1.21.3
require github.com/xeipuuv/gojsonschema v1.2.0

require (
github.com/gobwas/glob v0.2.3 // indirect
github.com/sgreben/flagvar v1.10.1 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/sgreben/flagvar v1.10.1 h1:ukN3zqVj9T9U7CiKG6owmejxswJYMbAg9Mxkhi1B4tw=
github.com/sgreben/flagvar v1.10.1/go.mod h1:AxDmbFDIxZ4dHj2zg8LxuJn5CSwSS28iY/Wy56e+nhI=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
Expand Down
142 changes: 84 additions & 58 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,75 +1,101 @@
package main

import (
"fmt"
"io/fs"
"os"
"strings"
"github.com/xeipuuv/gojsonschema"
)

var validationErrors []string
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
"text/tabwriter"

func main() {
dirs, _ := os.ReadDir("./")
"github.com/sgreben/flagvar"
"github.com/xeipuuv/gojsonschema"
)

for _, dir := range dirs {
validate(dir)
}
var validationErrors map[string][]string

outputResults()
}
var (
schemaFile string
outputFormat flagvar.Enum
)

func validate(dir fs.DirEntry) {
dirName := dir.Name()
if dir.IsDir() && stringContains(gatewayDirNames(), dirName) {
fmt.Println("Running schema validation against sample " + dirName + " identities")
schemaLoader := gojsonschema.NewReferenceLoader("file://" + dirName + "/schema.json")
func main() {
validationErrors = make(map[string][]string)
outputFormat.Choices = []string{"text", "json"}
outputFormat.Value = "text"

files, _ := os.ReadDir(dirName + "/identities")
for _, file := range files {
fileName := file.Name()
if !file.IsDir() {
documentLoader := gojsonschema.NewReferenceLoader("file://" + dirName + "/identities/" + fileName)
flag.StringVar(&schemaFile, "schema", "./schema.json", "load `FILE` as the schema when validating")
flag.Var(&outputFormat, "format", "output in `FORMAT` (json, text)")

result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
panic(err.Error())
}
flag.Parse()

if !result.Valid() {
for _, desc := range result.Errors() {
e := "- " + dirName + "/" + fileName + ": " + desc.Description()
validationErrors = append(validationErrors, e)
}
}
}
}
}
}
data, err := os.ReadFile(schemaFile)
if err != nil {
log.Fatalf("cannot load schema file: %v", err)
}
schema := gojsonschema.NewBytesLoader(data)

func stringContains(slice []string, ele string) bool {
for _, sliceEle := range slice {
if sliceEle == ele {
return true
}
}
for _, file := range flag.Args() {
var data []byte
var err error

return false
}
if file == "-" {
data, err = io.ReadAll(os.Stdin)
} else {
data, err = os.ReadFile(file)
}
if err != nil {
log.Fatalf("cannot load document: %v", err)
}
valid, errors, err := validateDocument(schema, string(data))
if !valid {
if err != nil {
log.Fatalf("cannot validate document: %v", err)
}
validationErrors[filepath.Base(file)] = make([]string, 0)
validationErrors[filepath.Base(file)] = append(validationErrors[filepath.Base(file)], errors...)
}
}

func gatewayDirNames() []string {
return []string{"3scale", "turnpike"}
switch outputFormat.Value {
case "json":
data, err := json.Marshal(validationErrors)
if err != nil {
log.Fatalf("cannot marshal json: %v", err)
}
fmt.Println(string(data))
case "text":
writer := tabwriter.NewWriter(os.Stdout, 4, 4, 2, ' ', 0)
fmt.Fprint(writer, "FILE\tERROR\n")
for file, errors := range validationErrors {
for _, err := range errors {
fmt.Fprintf(writer, "%v\t%v\n", file, err)
}
}
if err := writer.Flush(); err != nil {
log.Fatalf("unable to flush tab writer: %v", err)
}
default:
log.Fatalf("unknown format type: %v", outputFormat.Value)
}
}

func outputResults() {
fmt.Println()
// validateDocument runs JSON schema validation using the given loader on the
// conents of the document.
func validateDocument(loader gojsonschema.JSONLoader, document string) (bool, []string, error) {
result, err := gojsonschema.Validate(loader, gojsonschema.NewStringLoader(document))
if err != nil {
return false, nil, fmt.Errorf("cannot validate document: %w", err)
}

if len(validationErrors) > 0 {
fmt.Printf("Error(s) found in validation:\n")
fmt.Println(strings.Join(validationErrors, "\n"))
os.Exit(1)
} else {
fmt.Printf("No errors found.\n")
}
if !result.Valid() {
errors := make([]string, 0)
for _, desc := range result.Errors() {
errors = append(errors, desc.Description())
}
return false, errors, nil
}
return true, nil, nil
}