Standard Library



Cue has a standard library with numerous helper packages.

Overview

Root of the Go docs

There are broadly two types of packages

  1. Hermetic functions which you can use from pure.cue files.
  2. Non-hermetic functions which interact with the outside world. These are for the scripting layer in _tool.cue files.
Pure Packages
  • crypto/...: Hash calculations
  • encoding/...: To / from [base64, csv, hex, json, yaml]
  • html: For (un)escaping HTML strings
  • list: For working with lists
  • math: Extra advanced functions
  • net: Constraints for network related values
  • path: Work with filepaths with OS awareness
  • regexp: More advanced regexp functions
  • strconv: Format and parse numbers, quote and unquote runes
  • strings: Advanced helpers for working with strings
  • struct: Set min and max fields allowed
  • text/tabwriter: Write tabular data
  • text/template: Advanced string templates
  • time: Format, parse, and constraint times and durations
Tool Packages
  • tool/cli: Work with stdio
  • tool/exec: Run external commands
  • tool/file: List, read, and write files
  • tool/http: Make http requests
  • tool/os: work with environment vars

Examples

Encoding

encoding.cue

package stdlib

import (
	"encoding/json"
)

data: """
	{
		"hello": "world",
		"list": [ 1, 2 ],
		"nested": {
			"foo": "bar"
		}
	}
	"""

jval: json.Unmarshal(data)

val: {
	hello: "world"
	list: [1, 2]
	nested: foo: "bar"
}

cjson: json.Marshal(val)
Strings

strings.cue

package stdlib

import "strings"

s: "HelloWorld"

u: strings.ToUpper(s)
l: strings.ToLower(s)

line:  "Cue stands for configure, unify, execute"
words: strings.Split(line, " ")
lined: strings.Join(words, " ")

haspre: strings.HasPrefix(line, "Cue")
index:  strings.Index(line, "unify")
List

list.cue

package stdlib

import "list"

l1: [1, 2, 3, 4, 5]
l2: ["c", "b", "a"]

// constrain length
l2: list.MinItems(1)
l2: list.MaxItems(3)

// slice a list
l3: list.Slice(l1, 2, 4)

// get the sum and product
sum: list.Sum(l1)
prd: list.Product(l1)

// linear search for list (no binary)
lc: list.Contains(l1, 2)

// sort a list
ls:  list.Sort(l2, list.Ascending)
l2s: list.IsSorted(l2, list.Ascending)
lss: list.IsSorted(ls, list.Ascending)

// Flatten a list
ll: [1, [2, 3], [4, [5]]]
lf: list.FlattenN(ll, 1)

Constrain

constrain.cue

package stdlib

import (
	"net"
	"time"
)

// string with ip format
ip: net.IPv4
ip: "10.1.2.3"

// string with time format
ts: time.Format(time.ANSIC)
ts: "Mon Jan 2 15:04:05 2006"
We'll never share your email with anyone else.
2024 Hofstadter, Inc