From 1f22b009e0ecbf341e4096fdfea51efed4d2fbe9 Mon Sep 17 00:00:00 2001 From: ayala-orca <93713792+ayala-orca@users.noreply.github.com> Date: Thu, 21 Nov 2024 13:51:17 +0200 Subject: [PATCH] Create flag.go --- flag.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 flag.go diff --git a/flag.go b/flag.go new file mode 100644 index 000000000..5aadb7f1a --- /dev/null +++ b/flag.go @@ -0,0 +1,30 @@ +package validator + +import ( + "fmt" + "reflect" + "strings" + + "golang.org/x/exp/slices" + + "github.com/orcasecurity/shiftleft-cli/lib/utils" +) + +type FlagDependencyValidator[T any] struct { +} + +func (v FlagDependencyValidator[T]) Validate(cmdOptions T, dependentField string, dependencyField string, allowedValues []string) error { + cmd := reflect.ValueOf(cmdOptions) + dependentFieldValue := reflect.Indirect(cmd).FieldByName(dependentField) + dependencyFieldValue := reflect.Indirect(cmd).FieldByName(dependencyField) + if slices.Contains(allowedValues, "") && dependencyFieldValue.IsZero() { + return nil + } + allowedValues = utils.RemoveFromSlice(allowedValues, "") + if !dependentFieldValue.IsZero() && !slices.Contains(allowedValues, dependencyFieldValue.String()) { + allowedValues := strings.Join(allowedValues, ",") + return fmt.Errorf("input error - '%s' option can be used only with %s=%s", dependentField, dependencyField, allowedValues) + } + + return nil +}