generated from d2iq-archive/golang-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Validate empty values for required flags
- Loading branch information
1 parent
578497a
commit 201f88d
Showing
6 changed files
with
91 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// Copyright 2023 D2iQ, Inc. All rights reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package flags | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/spf13/cobra" | ||
) | ||
|
||
func ValidateRequiredFlagValues(cmd *cobra.Command, requiredFlagsWithValues ...string) error { | ||
fs := cmd.Flags() | ||
|
||
missingFlagValues := []string{} | ||
for _, flagName := range requiredFlagsWithValues { | ||
foundFlag := fs.Lookup(flagName) | ||
if foundFlag == nil { | ||
continue | ||
} | ||
|
||
if foundFlag.Value.String() == "" || foundFlag.Value.String() == "[]" { | ||
missingFlagValues = append(missingFlagValues, flagName) | ||
} | ||
} | ||
|
||
if len(missingFlagValues) > 0 { | ||
return fmt.Errorf(`required flag value(s) "%s" not set`, strings.Join(missingFlagValues, `", "`)) | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters