Skip to content

Commit

Permalink
Add missing relationship constraint (#177)
Browse files Browse the repository at this point in the history
* Add constraint "at least one"

the connector needs at least one field/envvar set/passed, otherwise it
will fail to run

* Check for zero-value of string slice
  • Loading branch information
shackra authored Jul 17, 2024
1 parent a1186f0 commit 95bc6b2
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,8 @@ func DefineConfiguration(
mainCMD.MarkFlagsMutuallyExclusive(listFieldConstrainsAsStrings(constrain)...)
case field.RequiredTogether:
mainCMD.MarkFlagsRequiredTogether(listFieldConstrainsAsStrings(constrain)...)
case field.AtLeastOne:
mainCMD.MarkFlagsOneRequired(listFieldConstrainsAsStrings(constrain)...)
}
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/field/relationships.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ type Relationship int
const (
RequiredTogether Relationship = iota + 1
MutuallyExclusive
AtLeastOne
)

type SchemaFieldRelationship struct {
Expand All @@ -25,3 +26,10 @@ func FieldsMutuallyExclusive(fields ...SchemaField) SchemaFieldRelationship {
Fields: fields,
}
}

func FieldsAtLeastOneUsed(fields ...SchemaField) SchemaFieldRelationship {
return SchemaFieldRelationship{
Kind: AtLeastOne,
Fields: fields,
}
}
16 changes: 16 additions & 0 deletions pkg/field/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ func Validate(c Configuration, v *viper.Viper) error {
isNonZero = v.GetInt(f.FieldName) != 0
case reflect.String:
isNonZero = v.GetString(f.FieldName) != ""
case reflect.Slice:
isNonZero = len(v.GetStringSlice(f.FieldName)) == 0
default:
return fmt.Errorf("field %s has unsupported type %s", f.FieldName, f.FieldType)
}
Expand Down Expand Up @@ -80,6 +82,9 @@ func validateConstraints(fieldsPresent map[string]int, relationships []SchemaFie
if present > 0 && present < len(relationship.Fields) && relationship.Kind == RequiredTogether {
return makeNeededTogetherError(fieldsPresent, relationship)
}
if present == 0 && relationship.Kind == AtLeastOne {
return makeAtLeastOneError(fieldsPresent, relationship)
}
}

return nil
Expand All @@ -106,3 +111,14 @@ func makeNeededTogetherError(fields map[string]int, relation SchemaFieldRelation

return fmt.Errorf("fields marked as needed together are missing: %s", strings.Join(found, ", "))
}

func makeAtLeastOneError(fields map[string]int, relation SchemaFieldRelationship) error {
var found []string
for _, f := range relation.Fields {
if fields[f.FieldName] == 0 {
found = append(found, f.FieldName)
}
}

return fmt.Errorf("at least one field was expected, any of: %s", strings.Join(found, ", "))
}

0 comments on commit 95bc6b2

Please sign in to comment.