From eff142bf03fba24030735f8864641a0c23d2b644 Mon Sep 17 00:00:00 2001 From: Nick Dumas Date: Tue, 6 Jun 2023 16:45:45 -0400 Subject: [PATCH] Implementing prettier printing of validation errors First pass was JSON output. --- cmd/obp/cmd/validate.go | 5 ++--- validate.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/cmd/obp/cmd/validate.go b/cmd/obp/cmd/validate.go index 5f0a5e0..323d2d8 100644 --- a/cmd/obp/cmd/validate.go +++ b/cmd/obp/cmd/validate.go @@ -6,7 +6,6 @@ package cmd import ( "fmt" "io/fs" - "log" "os" "path/filepath" @@ -51,7 +50,6 @@ var validateCmd = &cobra.Command{ return nil } - log.Printf("scanning %q\n", path) absPath, err := filepath.Abs(filepath.Join(target, path)) if err != nil { return fmt.Errorf("error generating absolute path for %q", target) @@ -63,7 +61,8 @@ var validateCmd = &cobra.Command{ defer target.Close() err = obp.Validate(schema, target) 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 }) diff --git a/validate.go b/validate.go index 1bc3649..bb2ceab 100644 --- a/validate.go +++ b/validate.go @@ -1,6 +1,7 @@ package obp import ( + "encoding/json" "fmt" "io" @@ -9,6 +10,14 @@ import ( "gopkg.in/yaml.v3" ) +type PrettyDetailFormat int + +const ( + JSON = iota + Markdown + CSV +) + func Validate(schemaURL string, r io.Reader) error { var m interface{} @@ -29,3 +38,30 @@ func Validate(schemaURL string, r io.Reader) error { 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 +}