Search code examples
validationyamlcuelang

Validating uniqueness of struct field values with cue


I'm evaluating using a cue schema to replace bespoke validation code for an existing YAML format that looks something like this:

items:
  - name: a
    description: something
  - name: b
    description: other thing

Following the tutorials has made it pretty easy to get the basics working: enforcing the required and optional fields on each item, and their types and value constraints.

However, a feature of the existing validation code that I'd like to replicate is the ability to enforce that no two entries in the items list share the same value for name. It's not obvious to me from the documentation whether or how this might be possible with cue. Is it?

(I know that I could and maybe should just use a map here instead of a list, and promote the name field into a key in the map, but I'd like to avoid changing the YAML format for the benefit of the validation code / tool if possible.)

Here's a specific example of the kind of thing that I'd want to fail validation (because the name a is reused):

items:
  - name: a
    description: something
  - name: a
    description: other thing

Solution

  • Disclaimer: I'm VERY new to CUE and there's probably a better solution to this.

    The solution I could think of is having a guard-like private variable _uniqueName: true and leveraging the fact that CUE will fail validation if we try to assign a conflicting value to the same var. Therefore you could reassign _uniqueName to a result of list.UniqueItems after massaging the items list first.

    See https://cuelang.org/play/?id=WZyVeYCEsEM#cue@export@yaml

    Granted the error message is not the most descriptive one or doesn't show you which value is duplicated, but it generally does what you need/asked.

    To improve a bit you could e.g. rename the variable to _namesInItemsMustBeUnique.