Skip to content

Commit

Permalink
pkg/imagefilter/formatter: implement SupportedOutputFormats()
Browse files Browse the repository at this point in the history
Implements function to get a list of all supported output formats.
  • Loading branch information
schuellerf committed Jan 27, 2025
1 parent 69ba37a commit 152bc6e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
3 changes: 3 additions & 0 deletions pkg/imagefilter/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package imagefilter

var SupportedFormatterMap = supportedFormatterMap
33 changes: 22 additions & 11 deletions pkg/imagefilter/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"io"
"sort"
"strings"

// we cannot use "maps" yet, as it needs go1.23
"golang.org/x/exp/maps"
)

// OutputFormat contains the valid output formats for formatting results
Expand All @@ -25,20 +28,28 @@ type ResultsFormatter interface {
Output(io.Writer, []Result) error
}

// NewResultFormatter will create a formatter based on the given format.
var supportedFormatterMap = map[string]ResultsFormatter{
string(OutputFormatDefault): &textResultsFormatter{},
string(OutputFormatText): &textResultsFormatter{},
string(OutputFormatJSON): &jsonResultsFormatter{},
string(OutputFormatTextShell): &shellResultsFormatter{},
string(OutputFormatTextShort): &textShortResultsFormatter{},
}

// SupportedOutputFormats returns a list of supported output formats
func SupportedOutputFormats() []string {
keys := maps.Keys(supportedFormatterMap)
sort.Strings(keys)
return keys
}

// NewResultsFormatter will create a formatter based on the given format.
func NewResultsFormatter(format OutputFormat) (ResultsFormatter, error) {
switch format {
case OutputFormatDefault, OutputFormatText:
return &textResultsFormatter{}, nil
case OutputFormatJSON:
return &jsonResultsFormatter{}, nil
case OutputFormatTextShell:
return &shellResultsFormatter{}, nil
case OutputFormatTextShort:
return &textShortResultsFormatter{}, nil
default:
rs, ok := supportedFormatterMap[string(format)]
if !ok {
return nil, fmt.Errorf("unsupported formatter %q", format)
}
return rs, nil
}

type textResultsFormatter struct{}
Expand Down
9 changes: 9 additions & 0 deletions pkg/imagefilter/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,12 @@ func TestResultsFormatter(t *testing.T) {
assert.Equal(t, tc.expectsOutput, buf.String(), tc)
}
}

func TestSupportedOutputFormats(t *testing.T) {
formatters := SupportedOutputFormats()
assert.Len(t, formatters, len(supportedFormatterMap))
assert.Contains(t, formatters, "text")
assert.Contains(t, formatters, "json")
assert.Contains(t, formatters, "shell")
assert.Contains(t, formatters, "short")
}

0 comments on commit 152bc6e

Please sign in to comment.