Skip to content

Commit fdd1738

Browse files
committed
Use config.FileName
1 parent fe7303a commit fdd1738

File tree

4 files changed

+54
-32
lines changed

4 files changed

+54
-32
lines changed

kubeval/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ func AddKubevalFlags(cmd *cobra.Command, config *Config) *cobra.Command {
5757
cmd.Flags().BoolVar(&config.IgnoreMissingSchemas, "ignore-missing-schemas", false, "Skip validation for resource definitions without a schema")
5858
cmd.Flags().BoolVar(&config.OpenShift, "openshift", false, "Use OpenShift schemas instead of upstream Kubernetes")
5959
cmd.Flags().BoolVar(&config.Strict, "strict", false, "Disallow additional properties not in schema")
60-
cmd.Flags().StringP("filename", "f", "stdin", "filename to be displayed when testing manifests read from stdin")
60+
cmd.Flags().StringVarP(&config.FileName, "filename", "f", "stdin", "filename to be displayed when testing manifests read from stdin")
6161
cmd.Flags().StringSliceVar(&config.KindsToSkip, "skip-kinds", []string{}, "Comma-separated list of case-sensitive kinds to skip when validating against schemas")
6262
cmd.Flags().StringVar(&config.SchemaLocation, "schema-location", "", "Base URL used to download schemas. Can also be specified with the environment variable KUBEVAL_SCHEMA_LOCATION")
6363
cmd.Flags().StringVarP(&config.KubernetesVersion, "kubernetes-version", "v", "master", "Version of Kubernetes to validate against")

kubeval/kubeval.go

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -94,13 +94,13 @@ func determineBaseURL(config *Config) string {
9494

9595
// validateResource validates a single Kubernetes resource against
9696
// the relevant schema, detecting the type of resource automatically
97-
func validateResource(data []byte, fileName string, schemaCache map[string]*gojsonschema.Schema, config *Config) (ValidationResult, error) {
97+
func validateResource(data []byte, schemaCache map[string]*gojsonschema.Schema, config *Config) (ValidationResult, error) {
9898
result := ValidationResult{}
99-
result.FileName = fileName
99+
result.FileName = config.FileName
100100
var body map[string]interface{}
101101
err := yaml.Unmarshal(data, &body)
102102
if err != nil {
103-
return result, fmt.Errorf("Failed to decode YAML from %s: %s", fileName, err.Error())
103+
return result, fmt.Errorf("Failed to decode YAML from %s: %s", result.FileName, err.Error())
104104
} else if body == nil {
105105
return result, nil
106106
}
@@ -184,16 +184,16 @@ func NewSchemaCache() map[string]*gojsonschema.Schema {
184184

185185
// Validate a Kubernetes YAML file, parsing out individual resources
186186
// and validating them all according to the relevant schemas
187-
func Validate(input []byte, fileName string, conf ...*Config) ([]ValidationResult, error) {
187+
func Validate(input []byte, conf ...*Config) ([]ValidationResult, error) {
188188
schemaCache := NewSchemaCache()
189-
return ValidateWithCache(input, fileName, schemaCache, conf...)
189+
return ValidateWithCache(input, schemaCache, conf...)
190190
}
191191

192192
// ValidateWithCache validates a Kubernetes YAML file, parsing out individual resources
193193
// and validating them all according to the relevant schemas
194194
// Allows passing a kubeval.NewSchemaCache() to cache schemas in-memory
195195
// between validations
196-
func ValidateWithCache(input []byte, fileName string, schemaCache map[string]*gojsonschema.Schema, conf ...*Config) ([]ValidationResult, error) {
196+
func ValidateWithCache(input []byte, schemaCache map[string]*gojsonschema.Schema, conf ...*Config) ([]ValidationResult, error) {
197197
config := NewDefaultConfig()
198198
if len(conf) == 1 {
199199
config = conf[0]
@@ -203,29 +203,33 @@ func ValidateWithCache(input []byte, fileName string, schemaCache map[string]*go
203203

204204
if len(input) == 0 {
205205
result := ValidationResult{}
206-
result.FileName = fileName
206+
result.FileName = config.FileName
207207
results = append(results, result)
208208
return results, nil
209209
}
210210

211211
bits := bytes.Split(input, []byte(detectLineBreak(input)+"---"+detectLineBreak(input)))
212212

213+
var errors *multierror.Error
214+
213215
// special case regexp for helm
214216
helmSourcePattern := regexp.MustCompile(`^(?:---` + detectLineBreak(input) + `)?# Source: (.*)`)
215217

216-
var errors *multierror.Error
217-
218-
// Start with the fileName we were provided; if we detect a new fileName
219-
// we'll use that until we find a new one.
220-
detectedFileName := fileName
218+
// Save the fileName we were provided; if we detect a new fileName
219+
// we'll use that, but we'll need to revert to the default afterward
220+
originalFileName := config.FileName
221+
defer func() {
222+
// revert the filename back to the original
223+
config.FileName = originalFileName
224+
}()
221225

222226
for _, element := range bits {
223227
if len(element) > 0 {
224228
if found := helmSourcePattern.FindStringSubmatch(string(element)); found != nil {
225-
detectedFileName = found[1]
229+
config.FileName = found[1]
226230
}
227231

228-
result, err := validateResource(element, detectedFileName, schemaCache, config)
232+
result, err := validateResource(element, schemaCache, config)
229233
if err != nil {
230234
errors = multierror.Append(errors, err)
231235
if config.ExitOnError {
@@ -235,7 +239,7 @@ func ValidateWithCache(input []byte, fileName string, schemaCache map[string]*go
235239
results = append(results, result)
236240
} else {
237241
result := ValidationResult{}
238-
result.FileName = detectedFileName
242+
result.FileName = config.FileName
239243
results = append(results, result)
240244
}
241245
}

kubeval/kubeval_test.go

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@ import (
1313

1414
func TestValidateBlankInput(t *testing.T) {
1515
blank := []byte("")
16-
_, err := Validate(blank, "sample")
16+
config := NewDefaultConfig()
17+
config.FileName = "blank"
18+
_, err := Validate(blank, config)
1719
if err != nil {
1820
t.Errorf("Validate should pass when passed a blank string")
1921
}
@@ -36,7 +38,9 @@ func TestValidateValidInputs(t *testing.T) {
3638
for _, test := range tests {
3739
filePath, _ := filepath.Abs("../fixtures/" + test)
3840
fileContents, _ := ioutil.ReadFile(filePath)
39-
_, err := Validate(fileContents, test)
41+
config := NewDefaultConfig()
42+
config.FileName = test
43+
_, err := Validate(fileContents, config)
4044
if err != nil {
4145
t.Errorf("Validate should pass when testing valid configuration in " + test)
4246
}
@@ -62,7 +66,9 @@ func TestValidateValidInputsWithCache(t *testing.T) {
6266
for _, test := range tests {
6367
filePath, _ := filepath.Abs("../fixtures/" + test)
6468
fileContents, _ := ioutil.ReadFile(filePath)
65-
_, err := ValidateWithCache(fileContents, test, schemaCache)
69+
config := NewDefaultConfig()
70+
config.FileName = test
71+
_, err := ValidateWithCache(fileContents, schemaCache, config)
6672
if err != nil {
6773
t.Errorf("Validate should pass when testing valid configuration in " + test)
6874
}
@@ -77,7 +83,9 @@ func TestValidateInvalidInputs(t *testing.T) {
7783
for _, test := range tests {
7884
filePath, _ := filepath.Abs("../fixtures/" + test)
7985
fileContents, _ := ioutil.ReadFile(filePath)
80-
_, err := Validate(fileContents, test)
86+
config := NewDefaultConfig()
87+
config.FileName = test
88+
_, err := Validate(fileContents, config)
8189
if err == nil {
8290
t.Errorf("Validate should not pass when testing invalid configuration in " + test)
8391
}
@@ -97,7 +105,9 @@ func TestValidateSourceExtraction(t *testing.T) {
97105
}
98106
filePath, _ := filepath.Abs("../fixtures/multi_valid_source.yaml")
99107
fileContents, _ := ioutil.ReadFile(filePath)
100-
results, err := Validate(fileContents, "multi_valid_source.yaml")
108+
config := NewDefaultConfig()
109+
config.FileName = "multi_valid_source.yaml"
110+
results, err := Validate(fileContents, config)
101111
if err != nil {
102112
t.Fatalf("Unexpected error while validating source: %v", err)
103113
}
@@ -111,9 +121,10 @@ func TestValidateSourceExtraction(t *testing.T) {
111121
func TestStrictCatchesAdditionalErrors(t *testing.T) {
112122
config := NewDefaultConfig()
113123
config.Strict = true
124+
config.FileName = "extra_property.yaml"
114125
filePath, _ := filepath.Abs("../fixtures/extra_property.yaml")
115126
fileContents, _ := ioutil.ReadFile(filePath)
116-
results, _ := Validate(fileContents, "extra_property.yaml", config)
127+
results, _ := Validate(fileContents, config)
117128
if len(results[0].Errors) == 0 {
118129
t.Errorf("Validate should not pass when testing for additional properties not in schema")
119130
}
@@ -122,10 +133,11 @@ func TestStrictCatchesAdditionalErrors(t *testing.T) {
122133
func TestValidateMultipleVersions(t *testing.T) {
123134
config := NewDefaultConfig()
124135
config.Strict = true
136+
config.FileName = "valid_version.yaml"
125137
config.KubernetesVersion = "1.14.0"
126138
filePath, _ := filepath.Abs("../fixtures/valid_version.yaml")
127139
fileContents, _ := ioutil.ReadFile(filePath)
128-
results, err := Validate(fileContents, "valid_version.yaml", config)
140+
results, err := Validate(fileContents, config)
129141
if err != nil || len(results[0].Errors) > 0 {
130142
t.Errorf("Validate should pass when testing valid configuration with multiple versions: %v", err)
131143
}
@@ -139,7 +151,9 @@ func TestValidateInputsWithErrors(t *testing.T) {
139151
for _, test := range tests {
140152
filePath, _ := filepath.Abs("../fixtures/" + test)
141153
fileContents, _ := ioutil.ReadFile(filePath)
142-
results, _ := Validate(fileContents, test)
154+
config := NewDefaultConfig()
155+
config.FileName = test
156+
results, _ := Validate(fileContents, config)
143157
if len(results[0].Errors) == 0 {
144158
t.Errorf("Validate should not pass when testing invalid configuration in " + test)
145159
}
@@ -155,7 +169,8 @@ func TestValidateMultipleResourcesWithErrors(t *testing.T) {
155169
filePath, _ := filepath.Abs("../fixtures/" + test)
156170
fileContents, _ := ioutil.ReadFile(filePath)
157171
config.ExitOnError = true
158-
_, err := Validate(fileContents, test, config)
172+
config.FileName = test
173+
_, err := Validate(fileContents, config)
159174
if err == nil {
160175
t.Errorf("Validate should not pass when testing invalid configuration in " + test)
161176
} else if merr, ok := err.(*multierror.Error); ok {
@@ -164,7 +179,7 @@ func TestValidateMultipleResourcesWithErrors(t *testing.T) {
164179
}
165180
}
166181
config.ExitOnError = false
167-
_, err = Validate(fileContents, test, config)
182+
_, err = Validate(fileContents, config)
168183
if err == nil {
169184
t.Errorf("Validate should not pass when testing invalid configuration in " + test)
170185
} else if merr, ok := err.(*multierror.Error); ok {
@@ -284,23 +299,24 @@ func TestGetString(t *testing.T) {
284299
}
285300

286301
func TestSkipCrdSchemaMiss(t *testing.T) {
302+
config := NewDefaultConfig()
303+
config.FileName = "test_crd.yaml"
287304
filePath, _ := filepath.Abs("../fixtures/test_crd.yaml")
288305
fileContents, _ := ioutil.ReadFile(filePath)
289-
_, err := Validate(fileContents, "test_crd.yaml")
306+
_, err := Validate(fileContents)
290307
if err == nil {
291308
t.Errorf("For custom CRD's with schema missing we should error without IgnoreMissingSchemas flag")
292309
}
293310

294-
config := NewDefaultConfig()
295311
config.IgnoreMissingSchemas = true
296-
results, _ := Validate(fileContents, "test_crd.yaml", config)
312+
results, _ := Validate(fileContents, config)
297313
if len(results[0].Errors) != 0 {
298314
t.Errorf("For custom CRD's with schema missing we should skip with IgnoreMissingSchemas flag")
299315
}
300316

301317
config.IgnoreMissingSchemas = false
302318
config.KindsToSkip = []string{"SealedSecret"}
303-
results, _ = Validate(fileContents, "test_crd.yaml", config)
319+
results, _ = Validate(fileContents, config)
304320
if len(results[0].Errors) != 0 {
305321
t.Errorf("We should skip resources listed in KindsToSkip")
306322
}

main.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,8 @@ var RootCmd = &cobra.Command{
6666
buffer.WriteString(scanner.Text() + "\n")
6767
}
6868
schemaCache := kubeval.NewSchemaCache()
69-
results, err := kubeval.ValidateWithCache(buffer.Bytes(), viper.GetString("filename"), schemaCache, config)
69+
config.FileName = viper.GetString("filename")
70+
results, err := kubeval.ValidateWithCache(buffer.Bytes(), schemaCache, config)
7071
if err != nil {
7172
log.Error(err)
7273
os.Exit(1)
@@ -92,7 +93,8 @@ var RootCmd = &cobra.Command{
9293
success = false
9394
continue
9495
}
95-
results, err := kubeval.ValidateWithCache(fileContents, fileName, schemaCache, config)
96+
config.FileName = fileName
97+
results, err := kubeval.ValidateWithCache(fileContents, schemaCache, config)
9698
if err != nil {
9799
log.Error(err)
98100
earlyExit()

0 commit comments

Comments
 (0)