Skip to content

Commit

Permalink
lint(validators): support checking arrays for duplicates
Browse files Browse the repository at this point in the history
Some string arrays have a constraint that their values must be unique, i.e. they must not be repeated.

The `isArrayOfStrings` and `hasArrayOfStrings` functions now take a `uniqueValues` argument with which uniqueness of the array values can be enforced. The default behavior is to allow duplicate values in an array.
  • Loading branch information
ErikSchierboom committed Apr 30, 2021
1 parent 6111020 commit 3ab3a42
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/lint/validators.nim
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ proc isArrayOfStrings*(data: JsonNode;
context: string;
path: Path;
isRequired = true;
uniqueValues = false;
allowed: HashSet[string];
allowedArrayLen: Slice;
checkIsKebab: bool): bool =
Expand All @@ -273,10 +274,16 @@ proc isArrayOfStrings*(data: JsonNode;
let arrayLen = data.len
if arrayLen > 0:
if arrayLen in allowedArrayLen:
var processedItems = initHashSet[string](arrayLen)

for item in data:
if not isString(item, context, path, "", isRequired, allowed,
checkIsKebab = checkIsKebab, isInArray = true):
result = false
elif uniqueValues:
let itemStr = item.getStr()
if processedItems.containsOrIncl(itemStr):
result.setFalseAndPrint(&"The {q context} array contains duplicate {q itemStr} values", path)
else:
let msgStart = &"The {q context} array has length {arrayLen}, " &
"but it must have length "
Expand All @@ -302,6 +309,7 @@ proc hasArrayOfStrings*(data: JsonNode;
path: Path;
context = "";
isRequired = true;
uniqueValues = false;
allowed = emptySetOfStrings;
allowedArrayLen = 1..int.high;
checkIsKebab = false): bool =
Expand All @@ -311,7 +319,7 @@ proc hasArrayOfStrings*(data: JsonNode;
if data.hasKey(key, path, context, isRequired):
let contextAndKey = joinWithDot(context, key)
result = isArrayOfStrings(data[key], contextAndKey, path, isRequired,
allowed, allowedArrayLen,
uniqueValues, allowed, allowedArrayLen,
checkIsKebab = checkIsKebab)
elif not isRequired:
result = true
Expand Down

0 comments on commit 3ab3a42

Please sign in to comment.