Skip to content

Commit

Permalink
lint(validators): support checking arrays for duplicates (#295)
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. each value must not appear more than once.

The `isArrayOfStrings` and `hasArrayOfStrings` procs now take a
`uniqueValues` argument by which uniqueness of the array values can be
enforced. The default behavior is to allow duplicate values in an array.
  • Loading branch information
ErikSchierboom authored May 1, 2021
1 parent 6111020 commit 96f3446
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 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,18 @@ 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):
let msg = &"The {q context} array contains duplicate " &
&"{q itemStr} values"
result.setFalseAndPrint(msg, path)
else:
let msgStart = &"The {q context} array has length {arrayLen}, " &
"but it must have length "
Expand All @@ -302,6 +311,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 +321,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 96f3446

Please sign in to comment.