Skip to content

Commit

Permalink
Add more code docs for the required field validation (#4979)
Browse files Browse the repository at this point in the history
This code is kind of funky, and having comments makes it a little more
understandable.

Signed-off-by: Juan Antonio Osorio <[email protected]>
  • Loading branch information
JAORMX authored Nov 15, 2024
1 parent 8edba54 commit 5f7b253
Showing 1 changed file with 13 additions and 3 deletions.
16 changes: 13 additions & 3 deletions internal/util/schemaupdate/schemaupdate.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,19 +204,24 @@ func validateRequired(oldSchemaMap, newSchemaMap map[string]any) error {
oldRequired, hasOldRequired := oldSchemaMap["required"]
newRequired, hasNewRequired := newSchemaMap["required"]

// If we don't have required fields in either schema, we're good
if !hasNewRequired && !hasOldRequired {
// If we don't have required fields in either schema, we're good
// profiles using this rule type won't break
return nil
}

// If the new schema doesn't have required fields, but the old schema does,
// we're good
if !hasNewRequired && hasOldRequired {
// If we don't have required fields in the new schema but do
// in the old schema, we're good.
// profiles using this rule type won't break
return nil
}

// If the new schema has required fields, but the old schema doesn't,
// we may break profiles using this rule type
if hasNewRequired && !hasOldRequired {
// If we have required fields in the new schema but not the old
// schema, we may break profiles using this rule type
Expand All @@ -235,15 +240,20 @@ func validateRequired(oldSchemaMap, newSchemaMap map[string]any) error {

// We need to make sure that the old required fields are
// a superset of the new required fields
oldSet := sets.New(oldRequiredSlice...)
newSet := sets.New(newRequiredSlice...)
if !oldSet.IsSuperset(newSet) {
if !requiredIsSuperset(oldRequiredSlice, newRequiredSlice) {
return fmt.Errorf("cannot add required fields to rule schema")
}

return nil
}

func requiredIsSuperset(oldRequired, newRequired []interface{}) bool {
oldSet := sets.New(oldRequired...)
newSet := sets.New(newRequired...)

return oldSet.IsSuperset(newSet)
}

func schemaIsNilOrEmpty(schema *structpb.Struct) bool {
if schema == nil {
return true
Expand Down

0 comments on commit 5f7b253

Please sign in to comment.