add jsonDebug, MinimumPrintable to interface (#430)

* add jsonDebug, MinimumPrintable to interface

We want to optionally print print either debugging
(containing all internal data) or user-friendly json
outputs.  This requires a new flag: json-debug, and
an extension to the Print interface: minimumPrintable.
This commit is contained in:
Keepers 2022-07-28 10:26:30 -06:00 committed by GitHub
parent a4d99a74ed
commit 99a210b6da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 7 deletions

View File

@ -12,14 +12,22 @@ import (
"github.com/tomlazar/table"
)
var outputAsJSON bool
var (
outputAsJSON bool
outputAsJSONDebug bool
)
// adds the --output flag to the provided command.
func AddOutputFlag(parent *cobra.Command) {
parent.PersistentFlags().BoolVar(&outputAsJSON, "json", false, "output data in JSON format")
fs := parent.PersistentFlags()
fs.BoolVar(&outputAsJSON, "json", false, "output data in JSON format")
fs.BoolVar(&outputAsJSONDebug, "json-debug", false, "output all internal and debugging data in JSON format")
cobra.CheckErr(fs.MarkHidden("json-debug"))
}
type Printable interface {
// reduces the struct to a minimized format for easier human consumption
MinimumPrintable() any
// should list the property names of the values surfaced in Values()
Headers() []string
// list of values for tabular or csv formatting
@ -52,16 +60,25 @@ func printAll(ps []Printable) {
if len(ps) == 0 {
return
}
if outputAsJSON {
outputJSON(ps)
if outputAsJSON || outputAsJSONDebug {
outputJSON(ps, outputAsJSONDebug)
return
}
outputTable(ps)
}
// output to stdout the list of printable structs as json
func outputJSON(ps []Printable) {
bs, err := json.Marshal(ps)
// output to stdout the list of printable structs as json.
// if debug is false, calls ps.Printable() first
func outputJSON(ps []Printable, debug bool) {
sl := make([]any, 0, len(ps))
for _, p := range ps {
if debug {
sl = append(sl, p)
} else {
sl = append(sl, p.MinimumPrintable())
}
}
bs, err := json.Marshal(sl)
if err != nil {
fmt.Fprintf(os.Stderr, "error formatting results to json: %v\n", err)
return

View File

@ -34,6 +34,12 @@ type Backup struct {
stats.StartAndEndTime
}
// MinimumPrintable reduces the Backup to its minimally printable details.
func (b Backup) MinimumPrintable() any {
// todo: implement printable backup struct
return b
}
// Headers returns the human-readable names of properties in a Backup
// for printing out to a terminal in a columnar display.
func (b Backup) Headers() []string {

View File

@ -41,6 +41,12 @@ func (dm DetailsModel) Paths() []string {
return r
}
// MinimumPrintable DetailsEntries is a passthrough func, because no
// reduction is needed for the json output.
func (de DetailsEntry) MinimumPrintable() any {
return de
}
// Headers returns the human-readable names of properties in a DetailsEntry
// for printing out to a terminal in a columnar display.
func (de DetailsEntry) Headers() []string {