Skip to content

Commit

Permalink
feat: adding additionalFlags object
Browse files Browse the repository at this point in the history
  • Loading branch information
femrtnz committed Sep 30, 2024
1 parent f5c9ea6 commit e7e6812
Show file tree
Hide file tree
Showing 10 changed files with 75 additions and 40 deletions.
6 changes: 3 additions & 3 deletions cmd/kubent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func main() {
log.Fatal().Err(err).Str("name", "Rego").Msg("Failed to filter results")
}

err = outputResults(results, config.Output, config.OutputFile, config.Labels)
err = outputResults(results, config.Output, config.OutputFile, *config.OptionalFlags)
if err != nil {
log.Fatal().Err(err).Msgf("Failed to output results")
}
Expand All @@ -180,14 +180,14 @@ func configureGlobalLogging() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}

func outputResults(results []judge.Result, outputType string, outputFile string, labels bool) error {
func outputResults(results []judge.Result, outputType string, outputFile string, optionalFlags config.OptionalFlags) error {
printer, err := printer.NewPrinter(outputType, outputFile)
if err != nil {
return fmt.Errorf("failed to create printer: %v", err)
}
defer printer.Close()

err = printer.Print(results, labels)
err = printer.Print(results, optionalFlags)
if err != nil {
return fmt.Errorf("failed to print results: %v", err)
}
Expand Down
15 changes: 8 additions & 7 deletions cmd/kubent/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,23 +272,24 @@ func Test_outputResults(t *testing.T) {
ApiVersion: "1.2.3", RuleSet: "rs", ReplaceWith: "rep", Since: testVersion}}

type args struct {
results []judge.Result
outputType string
outputFile string
results []judge.Result
outputType string
outputFile string
optionalFlags config.OptionalFlags
}
tests := []struct {
name string
args args
wantErr bool
}{
{"good", args{testResults, "text", "-"}, false},
{"bad-new-printer-type", args{testResults, "unknown", "-"}, true},
{"bad-new-printer-file", args{testResults, "text", "/unlikely/to/exist/dir"}, true},
{"good", args{testResults, "text", "-", config.OptionalFlags{Labels: false}}, false},
{"bad-new-printer-type", args{testResults, "unknown", "-", config.OptionalFlags{Labels: false}}, true},
{"bad-new-printer-file", args{testResults, "text", "/unlikely/to/exist/dir", config.OptionalFlags{Labels: false}}, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := outputResults(tt.args.results, tt.args.outputType, tt.args.outputFile, false); (err != nil) != tt.wantErr {
if err := outputResults(tt.args.results, tt.args.outputType, tt.args.outputFile, tt.args.optionalFlags); (err != nil) != tt.wantErr {
t.Errorf("unexpected error - got: %v, wantErr: %v", err, tt.wantErr)
}
})
Expand Down
31 changes: 26 additions & 5 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,18 @@ import (
"unicode"

"github.com/doitintl/kube-no-trouble/pkg/judge"
"github.com/doitintl/kube-no-trouble/pkg/printer"
"k8s.io/client-go/tools/clientcmd"

"github.com/rs/zerolog"
flag "github.com/spf13/pflag"
)

const (
JSON = "json"
TEXT = "text"
CSV = "csv"
)

type Config struct {
AdditionalKinds []string
AdditionalAnnotations []string
Expand All @@ -31,13 +36,18 @@ type Config struct {
OutputFile string
TargetVersion *judge.Version
KubentVersion bool
Labels bool
OptionalFlags *OptionalFlags
}

type OptionalFlags struct {
Labels bool
}

func NewFromFlags() (*Config, error) {
config := Config{
LogLevel: ZeroLogLevel(zerolog.InfoLevel),
TargetVersion: &judge.Version{},
OptionalFlags: &OptionalFlags{},
}

flag.StringSliceVarP(&config.AdditionalKinds, "additional-kind", "a", []string{}, "additional kinds of resources to report in Kind.version.group.com format")
Expand All @@ -53,12 +63,12 @@ func NewFromFlags() (*Config, error) {
flag.StringVarP(&config.OutputFile, "output-file", "O", "-", "output file, use - for stdout")
flag.VarP(&config.LogLevel, "log-level", "l", "set log level (trace, debug, info, warn, error, fatal, panic, disabled)")
flag.VarP(config.TargetVersion, "target-version", "t", "target K8s version in SemVer format (autodetected by default)")
flag.BoolVar(&config.Labels, "labels", false, "print resource labels")
flag.BoolVar(&config.OptionalFlags.Labels, "labels", false, "print resource labels")

flag.Parse()

if _, err := printer.ParsePrinter(config.Output); err != nil {
return nil, fmt.Errorf("failed to validate argument output: %w", err)
if !isValidOutputFormat(config.Output) {
return nil, fmt.Errorf("failed to validate argument output: %s", config.Output)
}

if err := validateOutputFile(config.OutputFile); err != nil {
Expand All @@ -79,6 +89,17 @@ func NewFromFlags() (*Config, error) {
return &config, nil
}

// Previuosly this was handled by a printer.go ParsePrinter function
// but we need to avoid cycle imports in order to inject the additional flags
func isValidOutputFormat(format string) bool {
switch format {
case JSON, TEXT, CSV:
return true
default:
return false
}
}

// validateAdditionalResources check that all resources are provided in full form
// resource.version.group.com. E.g. managedcertificate.v1beta1.networking.gke.io
func validateAdditionalResources(resources []string) error {
Expand Down
7 changes: 4 additions & 3 deletions pkg/printer/csv.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"sort"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand All @@ -29,7 +30,7 @@ func (c *csvPrinter) Close() error {
}

// Print will print results in CSV format
func (c *csvPrinter) Print(results []judge.Result, labels bool) error {
func (c *csvPrinter) Print(results []judge.Result, optionalFlags config.OptionalFlags) error {

sort.Slice(results, func(i, j int) bool {
return results[i].Name < results[j].Name
Expand All @@ -56,7 +57,7 @@ func (c *csvPrinter) Print(results []judge.Result, labels bool) error {
"rule_set",
}

if labels {
if optionalFlags.Labels {
fields = append(fields, "labels")
}

Expand All @@ -73,7 +74,7 @@ func (c *csvPrinter) Print(results []judge.Result, labels bool) error {
r.RuleSet,
}

if labels {
if optionalFlags.Labels {
row = append(row, mapToCommaSeparatedString(r.Labels))
}

Expand Down
18 changes: 11 additions & 7 deletions pkg/printer/csv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"testing"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand Down Expand Up @@ -41,16 +42,19 @@ func TestNewCSVPrinter(t *testing.T) {

func TestCSVPrinterPrint(t *testing.T) {
tests := []struct {
name string
labels map[string]interface{}
name string
labels map[string]interface{}
withLabels config.OptionalFlags
}{
{
name: "WithLabels",
labels: map[string]interface{}{"app": "php-apache-app"},
name: "WithLabels",
labels: map[string]interface{}{"app": "php-apache-app"},
withLabels: config.OptionalFlags{Labels: true},
},
{
name: "NoLabels",
labels: map[string]interface{}{},
name: "NoLabels",
labels: map[string]interface{}{},
withLabels: config.OptionalFlags{Labels: false},
},
}
for _, tt := range tests {
Expand All @@ -77,7 +81,7 @@ func TestCSVPrinterPrint(t *testing.T) {
Labels: tt.labels,
}}

if err := tp.Print(results, len(tt.labels) > 0); err != nil {
if err := tp.Print(results, tt.withLabels); err != nil {
t.Fatalf("unexpected error: %v", err)
}

Expand Down
3 changes: 2 additions & 1 deletion pkg/printer/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand All @@ -29,7 +30,7 @@ func (c *jsonPrinter) Close() error {
}

// Print will print results in text format
func (c *jsonPrinter) Print(results []judge.Result, labels bool) error {
func (c *jsonPrinter) Print(results []judge.Result, _ config.OptionalFlags) error {
writer := bufio.NewWriter(c.commonPrinter.outputFile)
defer writer.Flush()

Expand Down
7 changes: 4 additions & 3 deletions pkg/printer/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"reflect"
"testing"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand Down Expand Up @@ -45,17 +46,17 @@ func Test_jsonPrinter_Print(t *testing.T) {
tests := []struct {
name string
labels map[string]interface{}
withLabels bool
withLabels config.OptionalFlags
}{
{
name: "WithLabels",
labels: map[string]interface{}{"label1": "value1", "label2": "value2"},
withLabels: true,
withLabels: config.OptionalFlags{Labels: true},
},
{
name: "NoLabels",
labels: map[string]interface{}{},
withLabels: false,
withLabels: config.OptionalFlags{Labels: false},
},
}

Expand Down
3 changes: 2 additions & 1 deletion pkg/printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand All @@ -14,7 +15,7 @@ var printers = map[string]func(string) (Printer, error){
}

type Printer interface {
Print([]judge.Result, bool) error
Print([]judge.Result, config.OptionalFlags) error
Close() error
}

Expand Down
7 changes: 4 additions & 3 deletions pkg/printer/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"
"text/tabwriter"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand All @@ -30,7 +31,7 @@ func (c *textPrinter) Close() error {
return c.commonPrinter.Close()
}

func (c *textPrinter) Print(results []judge.Result, labels bool) error {
func (c *textPrinter) Print(results []judge.Result, optionalFlags config.OptionalFlags) error {

sort.Slice(results, func(i, j int) bool {
return results[i].Name < results[j].Name
Expand All @@ -54,14 +55,14 @@ func (c *textPrinter) Print(results []judge.Result, labels bool) error {
fmt.Fprintf(w, "%s\n", strings.Repeat("_", 90))
fmt.Fprintf(w, ">>> %s <<<\n", ruleSet)
fmt.Fprintf(w, "%s\n", strings.Repeat("-", 90))
if labels {
if optionalFlags.Labels {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s \t(%s) \t%s\n", "KIND", "NAMESPACE", "NAME", "API_VERSION", "REPLACE_WITH", "SINCE", "LABELS")
} else {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s \t(%s)\n", "KIND", "NAMESPACE", "NAME", "API_VERSION", "REPLACE_WITH", "SINCE")
}

}
if labels {
if optionalFlags.Labels {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s \t(%s) \t%s\n", r.Kind, r.Namespace, r.Name, r.ApiVersion, r.ReplaceWith, r.Since, mapToCommaSeparatedString(r.Labels))
} else {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s \t(%s) \n", r.Kind, r.Namespace, r.Name, r.ApiVersion, r.ReplaceWith, r.Since)
Expand Down
18 changes: 11 additions & 7 deletions pkg/printer/text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"testing"

"github.com/doitintl/kube-no-trouble/pkg/config"
"github.com/doitintl/kube-no-trouble/pkg/judge"
)

Expand Down Expand Up @@ -41,16 +42,19 @@ func Test_newTextPrinter(t *testing.T) {

func Test_textPrinter_Print(t *testing.T) {
tests := []struct {
name string
labels map[string]interface{}
name string
labels map[string]interface{}
withLabels config.OptionalFlags
}{
{
name: "WithLabels",
labels: map[string]interface{}{"label1": "value1", "label2": "value2"},
name: "WithLabels",
labels: map[string]interface{}{"label1": "value1", "label2": "value2"},
withLabels: config.OptionalFlags{Labels: true},
},
{
name: "NoLabels",
labels: map[string]interface{}{},
name: "NoLabels",
labels: map[string]interface{}{},
withLabels: config.OptionalFlags{Labels: false},
},
}

Expand Down Expand Up @@ -78,7 +82,7 @@ func Test_textPrinter_Print(t *testing.T) {
Labels: tt.labels,
}}

if err := tp.Print(results, false); err != nil {
if err := tp.Print(results, tt.withLabels); err != nil {
t.Fatalf("unexpected error: %v", err)
}

Expand Down

0 comments on commit e7e6812

Please sign in to comment.