kubeconform/pkg/output/json.go
2020-06-01 12:44:59 +02:00

106 lines
2.1 KiB
Go

package output
import (
"encoding/json"
"fmt"
)
type result struct {
Filename string `json:"filename"`
Kind string `json:"kind"`
Version string `json:"version"`
Status string `json:"status"`
Msg string `json:"msg"`
}
type jsono struct {
withSummary bool
quiet bool
results []result
nValid, nInvalid, nErrors, nSkipped int
}
func JSON(withSummary bool, quiet bool) Output {
return &jsono{
withSummary: withSummary,
quiet: quiet,
results: []result{},
nValid: 0,
nInvalid: 0,
nErrors: 0,
nSkipped: 0,
}
}
func (o *jsono) Write(filename, kind, version string, err error, skipped bool) {
msg, st := "", ""
s := status(err, skipped)
switch s {
case VALID:
st = "VALID"
o.nValid++
case INVALID:
st = "INVALID"
msg = err.Error()
o.nInvalid++
case ERROR:
st = "ERROR"
msg = err.Error()
o.nErrors++
case SKIPPED:
st = "SKIPPED"
o.nSkipped++
}
if !o.quiet || (s != VALID && s != SKIPPED) {
o.results = append(o.results, result{Filename: filename, Kind: kind, Version: version, Status: st, Msg: msg})
}
}
func (o *jsono) Flush() {
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"`
Errors int `json:"errors"`
Skipped int `json:"skipped"`
} `json:"summary"`
}{
Resources: o.results,
Summary: struct {
Valid int `json:"valid"`
Invalid int `json:"invalid"`
Errors int `json:"errors"`
Skipped int `json:"skipped"`
}{
Valid: o.nValid,
Invalid: o.nInvalid,
Errors: o.nErrors,
Skipped: o.nSkipped,
},
}
res, err = json.MarshalIndent(jsonObj, "", " ")
} else {
jsonObj := struct {
Resources []result `json:"resources"`
}{
Resources: o.results,
}
res, err = json.MarshalIndent(jsonObj, "", " ")
}
if err != nil {
fmt.Printf("error print results: %s", err)
return
}
fmt.Printf("%s\n", res)
}