Skip to content

Commit 5908968

Browse files
author
Felipe Amaral
committed
feat: add labels flag as optional
1 parent 8582f7c commit 5908968

22 files changed

+258
-39
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ Otherwise there's `Makefile`
223223
```sh
224224
$ make
225225
make
226-
all Cean, build and pack
226+
all Clean, build and pack
227227
help Prints list of tasks
228228
build Build binary
229229
generate Go generate

cmd/kubent/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func main() {
156156
log.Fatal().Err(err).Str("name", "Rego").Msg("Failed to filter results")
157157
}
158158

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

183-
func outputResults(results []judge.Result, outputType string, outputFile string) error {
183+
func outputResults(results []judge.Result, outputType string, outputFile string, optionalFlags config.OptionalFlags) error {
184184
printer, err := printer.NewPrinter(outputType, outputFile)
185185
if err != nil {
186186
return fmt.Errorf("failed to create printer: %v", err)
187187
}
188188
defer printer.Close()
189189

190-
err = printer.Print(results)
190+
err = printer.Print(results, optionalFlags)
191191
if err != nil {
192192
return fmt.Errorf("failed to print results: %v", err)
193193
}

cmd/kubent/main_test.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -272,23 +272,24 @@ func Test_outputResults(t *testing.T) {
272272
ApiVersion: "1.2.3", RuleSet: "rs", ReplaceWith: "rep", Since: testVersion}}
273273

274274
type args struct {
275-
results []judge.Result
276-
outputType string
277-
outputFile string
275+
results []judge.Result
276+
outputType string
277+
outputFile string
278+
optionalFlags config.OptionalFlags
278279
}
279280
tests := []struct {
280281
name string
281282
args args
282283
wantErr bool
283284
}{
284-
{"good", args{testResults, "text", "-"}, false},
285-
{"bad-new-printer-type", args{testResults, "unknown", "-"}, true},
286-
{"bad-new-printer-file", args{testResults, "text", "/unlikely/to/exist/dir"}, true},
285+
{"good", args{testResults, "text", "-", config.OptionalFlags{Labels: false}}, false},
286+
{"bad-new-printer-type", args{testResults, "unknown", "-", config.OptionalFlags{Labels: false}}, true},
287+
{"bad-new-printer-file", args{testResults, "text", "/unlikely/to/exist/dir", config.OptionalFlags{Labels: false}}, true},
287288
}
288289

289290
for _, tt := range tests {
290291
t.Run(tt.name, func(t *testing.T) {
291-
if err := outputResults(tt.args.results, tt.args.outputType, tt.args.outputFile); (err != nil) != tt.wantErr {
292+
if err := outputResults(tt.args.results, tt.args.outputType, tt.args.outputFile, tt.args.optionalFlags); (err != nil) != tt.wantErr {
292293
t.Errorf("unexpected error - got: %v, wantErr: %v", err, tt.wantErr)
293294
}
294295
})

fixtures/expected-json-output.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"ApiVersion": "apps/v1beta1",
77
"RuleSet": "Deprecated APIs removed in 1.16",
88
"ReplaceWith": "apps/v1",
9-
"Since": "1.9.0"
9+
"Since": "1.9.0",
10+
"Labels": {}
1011
}
1112
]

pkg/collector/file_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func TestFileCollectorGet(t *testing.T) {
5252
t.Errorf("Expected to get %d, got %d", len(tc.expected), len(manifests))
5353
}
5454

55-
for i, _ := range manifests {
55+
for i := range manifests {
5656
if manifests[i]["kind"] != tc.expected[i] {
5757
t.Errorf("Expected to get %s, instead got: %s", tc.expected[i], manifests[i]["kind"])
5858
}

pkg/config/config.go

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,18 @@ import (
1010
"unicode"
1111

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

1615
"github.com/rs/zerolog"
1716
flag "github.com/spf13/pflag"
1817
)
1918

19+
const (
20+
JSON = "json"
21+
TEXT = "text"
22+
CSV = "csv"
23+
)
24+
2025
type Config struct {
2126
AdditionalKinds []string
2227
AdditionalAnnotations []string
@@ -31,12 +36,18 @@ type Config struct {
3136
OutputFile string
3237
TargetVersion *judge.Version
3338
KubentVersion bool
39+
OptionalFlags *OptionalFlags
40+
}
41+
42+
type OptionalFlags struct {
43+
Labels bool
3444
}
3545

3646
func NewFromFlags() (*Config, error) {
3747
config := Config{
3848
LogLevel: ZeroLogLevel(zerolog.InfoLevel),
3949
TargetVersion: &judge.Version{},
50+
OptionalFlags: &OptionalFlags{},
4051
}
4152

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

5668
flag.Parse()
5769

58-
if _, err := printer.ParsePrinter(config.Output); err != nil {
59-
return nil, fmt.Errorf("failed to validate argument output: %w", err)
70+
if !isValidOutputFormat(config.Output) {
71+
return nil, fmt.Errorf("failed to validate argument output: %s", config.Output)
6072
}
6173

6274
if err := validateOutputFile(config.OutputFile); err != nil {
@@ -77,6 +89,17 @@ func NewFromFlags() (*Config, error) {
7789
return &config, nil
7890
}
7991

92+
// Previuosly this was handled by a printer.go ParsePrinter function
93+
// but we need to avoid cycle imports in order to inject the additional flags
94+
func isValidOutputFormat(format string) bool {
95+
switch format {
96+
case JSON, TEXT, CSV:
97+
return true
98+
default:
99+
return false
100+
}
101+
}
102+
80103
// validateAdditionalResources check that all resources are provided in full form
81104
// resource.version.group.com. E.g. managedcertificate.v1beta1.networking.gke.io
82105
func validateAdditionalResources(resources []string) error {

pkg/config/config_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ func TestValidateAdditionalResources(t *testing.T) {
7272

7373
func TestValidateAdditionalResourcesFail(t *testing.T) {
7474
testCases := [][]string{
75-
[]string{"abcdef"},
76-
[]string{""},
77-
[]string{"test.v1.com"},
75+
{"abcdef"},
76+
{""},
77+
{"test.v1.com"},
7878
}
7979

8080
for _, tc := range testCases {

pkg/judge/judge.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ type Result struct {
88
RuleSet string
99
ReplaceWith string
1010
Since *Version
11+
Labels map[string]interface{}
1112
}
1213

1314
type Judge interface {

pkg/judge/rego.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ func (j *RegoJudge) Eval(input []map[string]interface{}) ([]Result, error) {
6363
m["Namespace"] = "<undefined>"
6464
}
6565

66+
var labels map[string]interface{}
67+
if v, ok := m["Labels"].(map[string]interface{}); ok {
68+
labels = v
69+
} else {
70+
labels = make(map[string]interface{})
71+
}
6672
results = append(results, Result{
6773
Name: m["Name"].(string),
6874
Namespace: m["Namespace"].(string),
@@ -71,6 +77,7 @@ func (j *RegoJudge) Eval(input []map[string]interface{}) ([]Result, error) {
7177
ReplaceWith: m["ReplaceWith"].(string),
7278
RuleSet: m["RuleSet"].(string),
7379
Since: since,
80+
Labels: labels,
7481
})
7582
}
7683
}

pkg/judge/rego_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ func TestEvalRules(t *testing.T) {
9090
t.Errorf("expected %d findings, instead got: %d", len(tc.expected), len(results))
9191
}
9292

93-
for i, _ := range results {
93+
for i := range results {
9494
if results[i].Kind != tc.expected[i] {
9595
t.Errorf("expected to get %s finding, instead got: %s", tc.expected[i], results[i].Kind)
9696
}

0 commit comments

Comments
 (0)