enable printing a summary at the end of the run

This commit is contained in:
Yann Hamon 2020-05-30 20:03:27 +02:00
parent 5f3504724f
commit bb478da7e0
3 changed files with 60 additions and 14 deletions

View file

@ -12,11 +12,13 @@ type result struct {
}
type JSONOutput struct {
withSummary bool
results []result
}
func NewJSONOutput() Output{
func NewJSONOutput(withSummary bool) Output{
return &JSONOutput{
withSummary: withSummary,
results: []result{},
}
}
@ -25,7 +27,7 @@ func (o *JSONOutput) Write(filename string,err error, skipped bool) {
status := "VALID"
msg := ""
if err != nil {
status = "ERROR"
status = "INVALID"
msg = err.Error()
}
if skipped {
@ -36,7 +38,43 @@ func (o *JSONOutput) Write(filename string,err error, skipped bool) {
}
func (o *JSONOutput) Flush() {
res, err := json.MarshalIndent(o.results,"", " ")
var err error
var res []byte
if o.withSummary {
jsonObj := struct {
Resources []result `json:"resources"`
Summary struct {
Valid int `json:"valid"`
Invalid int `json:"invalid"`
Skipped int `json:"skipped"`
} `json:"summary"`
} {
Resources: o.results,
}
for _, r := range o.results {
switch {
case r.Status == "VALID":
jsonObj.Summary.Valid++
case r.Status == "INVALID":
jsonObj.Summary.Invalid++
case r.Status == "SKIPPED":
jsonObj.Summary.Skipped++
}
}
res, err = json.MarshalIndent(jsonObj,"", " ")
} else {
jsonObj := struct {
Resources []result
} {
Resources: o.results,
}
res, err = json.MarshalIndent(jsonObj,"", " ")
}
if err != nil {
fmt.Printf("error print results: %s", err)
return

View file

@ -1,37 +1,45 @@
package output
import (
"fmt"
"github.com/yannh/kubeconform/pkg/validator"
"log"
)
type TextOutput struct {
withSummary bool
nValid, nInvalid, nSkipped int
}
func NewTextOutput() Output {
return &TextOutput{}
func NewTextOutput(withSummary bool) Output {
return &TextOutput{withSummary, 0,0,0}
}
func (o *TextOutput) Write(filename string,err error, skipped bool) {
if skipped {
log.Printf("skipping resource\n")
fmt.Printf("skipping resource\n")
o.nSkipped++
return
}
if err != nil {
o.nInvalid++
if _, ok := err.(validator.InvalidResourceError); ok {
log.Printf("invalid resource: %s\n", err)
fmt.Printf("invalid resource: %s\n", err)
} else {
log.Printf("failed validating resource in file %s: %s\n", filename, err)
fmt.Printf("failed validating resource in file %s: %s\n", filename, err)
}
return
}
if !skipped{
log.Printf("file %s is valid\n", filename)
fmt.Printf("file %s is valid\n", filename)
o.nValid++
}
}
func (o *TextOutput) Flush() {
if o.withSummary {
fmt.Printf("Run summary - Valid: %d, Invalid: %d, Skipped: %d\n", o.nValid, o.nInvalid, o.nSkipped)
}
}