Implementing prettier printing of validation errors

First pass was JSON output.
main
Nick Dumas 2 years ago
parent 9bf9e2f2ef
commit eff142bf03

@ -6,7 +6,6 @@ package cmd
import ( import (
"fmt" "fmt"
"io/fs" "io/fs"
"log"
"os" "os"
"path/filepath" "path/filepath"
@ -51,7 +50,6 @@ var validateCmd = &cobra.Command{
return nil return nil
} }
log.Printf("scanning %q\n", path)
absPath, err := filepath.Abs(filepath.Join(target, path)) absPath, err := filepath.Abs(filepath.Join(target, path))
if err != nil { if err != nil {
return fmt.Errorf("error generating absolute path for %q", target) return fmt.Errorf("error generating absolute path for %q", target)
@ -63,7 +61,8 @@ var validateCmd = &cobra.Command{
defer target.Close() defer target.Close()
err = obp.Validate(schema, target) err = obp.Validate(schema, target)
if err != nil { if err != nil {
log.Printf("error validating input file %q: %#+v\n", path, err.(*jsonschema.ValidationError).DetailedOutput()) details := err.(*jsonschema.ValidationError).DetailedOutput()
obp.PrettyDetails(cmd.OutOrStdout(), obp.JSON, details)
} }
return nil return nil
}) })

@ -1,6 +1,7 @@
package obp package obp
import ( import (
"encoding/json"
"fmt" "fmt"
"io" "io"
@ -9,6 +10,14 @@ import (
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
type PrettyDetailFormat int
const (
JSON = iota
Markdown
CSV
)
func Validate(schemaURL string, r io.Reader) error { func Validate(schemaURL string, r io.Reader) error {
var m interface{} var m interface{}
@ -29,3 +38,30 @@ func Validate(schemaURL string, r io.Reader) error {
return nil return nil
} }
func recurseDetails(detailed jsonschema.Detailed, acc []jsonschema.Detailed) []jsonschema.Detailed {
acc = append(acc, detailed)
for _, e := range detailed.Errors {
acc = append(acc, recurseDetails(e, acc)...)
}
return acc
}
func PrettyDetails(w io.Writer, format PrettyDetailFormat, details jsonschema.Detailed) error {
acc := make([]jsonschema.Detailed, 0)
errors := recurseDetails(details, acc)
switch format {
case JSON:
enc := json.NewEncoder(w)
err := enc.Encode(errors)
if err != nil {
return fmt.Errorf("error writing JSON payload to provided writer: %w", err)
}
default:
return fmt.Errorf("unknown format")
}
return nil
}

Loading…
Cancel
Save