fix: change flag parse error handling to return errors instead of exiting (#107)

* fix: change flag parse error handling to return errors instead of exiting

Having ExitOnError in combination with SetOutput to a buffer instead of
stdout/stderr means flags.Parse output is swallowed and kubeconform silently
exits directly with exit code 2 instead of returning the error.

Setting ContinueOnError instead returns the error, and writes usage help to
the buffer, so error handling code in main is reached.

* Add test for parsing incorrect flags

Co-authored-by: Yann Hamon <yann@mandragor.org>
This commit is contained in:
Calle Pettersson 2022-06-19 18:38:52 +02:00 committed by GitHub
parent 014cbf754f
commit 7bf1e01dec
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 1 deletions

View file

@ -11,6 +11,12 @@ resetCacheFolder() {
[ "${lines[0]}" == 'Usage: bin/kubeconform [OPTION]... [FILE OR FOLDER]...' ]
}
@test "Fail and display help when using an incorrect flag" {
run bin/kubeconform -xyz
[ "$status" -eq 1 ]
[ "${lines[0]}" == 'flag provided but not defined: -xyz' ]
}
@test "Pass when parsing a valid Kubernetes config YAML file" {
run bin/kubeconform -summary fixtures/valid.yaml
[ "$status" -eq 0 ]

View file

@ -56,7 +56,7 @@ func splitCSV(csvStr string) map[string]struct{} {
func FromFlags(progName string, args []string) (Config, string, error) {
var schemaLocationsParam, ignoreFilenamePatterns arrayParam
var skipKindsCSV, rejectKindsCSV string
flags := flag.NewFlagSet(progName, flag.ExitOnError)
flags := flag.NewFlagSet(progName, flag.ContinueOnError)
var buf bytes.Buffer
flags.SetOutput(&buf)