CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON.

Cuetils

CUE utilities and helpers for working with tree based objects in any combination of CUE, Yaml, and JSON.

Using

As a command line binary

The cuetils CLI is useful for bulk operations or when you don't want to write extra CUE or Go.

Download a release from GitHub.

cuetils -h

As a Go library

The Go libraries are optimized and have more capabilities.*

go get github.com/hofstadter-io/cuetils@latest
import "github.com/hofstadter-io/cuetils/structural"

* work in progress, unoptimized use the CUE helper and RecurseN

As a CUE library

The CUE libraries all use the RecurseN helper and make use of the "function" pattern. You can also write custom operators.

Add to your project with hof mod or another method. See: https://cuetorials.com/first-steps/modules-and-packages/#dependency-management

import "github.com/hofstadter-io/cuetils/structural"

Structural Helpers

  • Count the nodes in an object
  • Depth how deep an object is
  • Diff two objects, producing a structured diff
  • Patch an object, producing a new object
  • Pick a subojbect from another, selecting only the parts you want
  • Maks a subobject from another, filtering out parts you don't want
  • Replace with a subobject, updating fields found
  • Upsert with a subobject, updating and adding fields
  • Transform one or more objects into another using CUE
  • Validate one or more objects with the power of CUE

The helpers work by checking if two operands unify. We try to make note of the edge cases where appropriate, as it depends on both the operation and the method you are using (CUE, Go, or cuetils).

Count

#Count calculates how many nodes are in an object.

CLI example
a: {
	foo: "bar"
	a: b: c: "d"
}
cow: "moo"
$ cuetils count tree.cue
9
CUE example
import "github.com/hofstadter-io/cuetils/structural"

tree: {
	a: {
		foo: "bar"
		a: b: c: "d"
	}
	cow: "moo"
}

depth: (structural.#Count & { #in: tree }).out
depth: 9
Go example

Depth

#Depth calculates the deepest branch of an object.

CLI example
a: {
	foo: "bar"
	a: b: c: "d"
}
cow: "moo"
$ cuetils depth tree.cue
5
CUE example
import "github.com/hofstadter-io/cuetils/structural"

tree: {
	a: {
		foo: "bar"
		a: b: c: "d"
	}
	cow: "moo"
}

depth: (structural.#Depth & { #in: tree }).out
depth: 5
Go example
import "github.com/hofstadter-io/cuetils/structural"

Diff

#Diff computes a semantic diff object

CLI example
-- a.json --
{
	"a": {
		"b": "B"
	}
}
-- b.yaml --
a:
  c: C
b: B
$ cuetils diff a.json b.yaml
{
	"+": {
		b: "B"
	}
	a: {
		"-": {
			b: "B"
		}
		"+": {
			c: "C"
		}
	}
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"

x: {
	a: "a"
	b: "b"
	d: "d"
	e: {
		a: "a"
		b: "b"
		d: "d"
	}
}

y: {
	b: "b"
	c: "c"
	d: "D"
	e:  {
		b: "b"
		c: "c"
		d: 1
	}
}

diff: (structural.#Diff & { #X: x, #Y: y }).diff
diff: {
	"-": {
		a: "a"
		d: "d"
	}
	e: {
		"-": {
			a: "a"
			d: "d"
		}
		"+": {
			d: 1
			c: "c"
		}
	}
	"+": {
		d: "D"
		c: "c"
	}
}
Go example
import "github.com/hofstadter-io/cuetils/structural"

For diff and patch, int & 1 like expressions will not be detected. Lists are not currently supported for diff and patch. It may be workable if the list sizes are known and order consistent. Associative Lists may solve this issue. We don't currently have good syntax for specifying the key to match elements on.

Patch

#Patch applies a diff object

CLI example
-- patch.json --
{
  "+": {
    b: "B"
  }
  a: {
    "-": {
      b: "B"
    }
    "+": {
      c: "C"
    }
  }
}
-- a.json --
{
	"a": {
		"b": "B"
	}
}
$ cuetils patch patch.json a.json
{
	b: "B"
	a: {
		c: "C"
	}
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"

x: {
	a: "a"
	b: "b"
	d: "d"
	e: {
		a: "a"
		b: "b"
		d: "d"
	}
}

p: {
	"-": {
		a: "a"
		d: "d"
	}
	e: {
		"-": {
			a: "a"
			d: "d"
		}
		"+": {
			d: 1
			c: "c"
		}
	}
	"+": {
		d: "D"
		c: "c"
	}
}

patch: (structural.#Patch & { #X: x, #Y: y }).patch
patch: {
	b: "b"
	c: "c"
	d: "D"
	e:  {
		b: "b"
		c: "c"
		d: 1
	}
}
Go example
import "github.com/hofstadter-io/cuetils/structural"

Pick

#Pick extracts a subobject

CLI example
-- pick.cue --
{
	a: {
		b: string
	}
	c: int
	d: "D"
}
-- a.json --
{
	"a": {
		"b": "B"
	},
	"b": 1,
	"c": 2,
	"d": "D"
}
$ cuetils pick pick.cue a.json
{
	a: {
		b: "B"
	}
	c: 2
	d: "D"
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"

x: {
	a: "a"
	b: "b"
	d: "d"
	e: {
		a: "a"
		b: "b1"
		d: "cd"
	}
}
p: {
	b: string
	d: int
	e: {
		a: _
		b: =~"^b"
		d: =~"^d"
	}
}
pick: (structural.#Pick & { #X: x, #P: p }).pick
pick: {
	b: "b"
	e:  {
		a: "a"
		b: "b1"
	}
}
Go example
import "github.com/hofstadter-io/cuetils/structural"

Mask

#Mask removes a subobject

CLI example
-- mask.cue --
{
	a: {
		b: string
	}
	c: int
	d: "D"
}
-- a.json --
{
	"a": {
		"b": "B"
		"c": "C"
	},
	"b": 1,
	"c": 2,
	"d": "D"
}
$ cuetils mask mask.cue a.json
{
	a: {
		c: "C"
	}
	b: 1
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"

x: {
	a: "a"
	b: "b"
	d: "d"
	e: {
		a: "a"
		b: "b1"
		d: "cd"
	}
}
m: {
	b: string
	d: int
	e: {
		a: _
		b: =~"^b"
		d: =~"^d"
	}
}
mask: (structural.#Mask & { #X: x, #M: m }).mask
mask: {
	a: "a"
	d: "d"
	e:  {
		d: "cd"
	}
}
Go example
import "github.com/hofstadter-io/cuetils/structural"

Replace

CLI example
-- replace.cue --
{
	a: {
		b: "b"
	}
	d: "d"
	e: "E"
}
-- a.json --
{
	"a": {
		"b": "B"
	},
	"b": 1,
	"c": 2,
	"d": "D"
}
$ cuetils replace replace.cue a.json
{
	b: 1
	c: 2
	a: {
		b: "b"
	}
	d: "d"
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"
Go example
import "github.com/hofstadter-io/cuetils/structural"

Upsert

CLI example
-- upsert.cue --
{
	a: {
		b: "b"
	}
	d: "d"
	e: "E"
}
-- a.json --
{
	"a": {
		"b": "B"
	},
	"b": 1,
	"d": "D"
}
$ cuetils upsert upsert.cue a.json
{
	b: 1
	a: {
		b: "b"
	}
	d: "d"
	e: "E"
}
CUE example
import "github.com/hofstadter-io/cuetils/structural"
Go example
import "github.com/hofstadter-io/cuetils/structural"

Transform

CLI example
-- t.cue --
#In: _        // required, filled in during processing
{
	B: #In.a.b
	C: #In.a.c
	D: #In.d
}

-- a.json --
{
	"a": {
		"b": "b"
		"c": "c"
	}
	"d": "d"
}
$ cuetils transform t.cue a.json
{
	B: "b"
	C: "c"
	D: "d"
}
Go example
import "github.com/hofstadter-io/cuetils/structural"

Validate

CLI example
-- schema.cue --
{
	a: {
		b: int
	}
	c: int
	d: "D"
}
-- a.json --
{
	"a": {
		"b": "B"
	},
	"b": 1,
	"c": 2,
	"d": "D"
}
$ cuetils validate schema.cue a.json
a.json
----------------------
a.b: conflicting values "B" and int (mismatched types string and int):
    ./schema.cue:1:1
    ./schema.cue:3:6
    a.json:3:8


Errors in 1 file(s)
Go example
import "github.com/hofstadter-io/cuetils/structural"

RecurseN

A function factory for bounded recursion, defaulting to 20. This is a pattern to get around CUE's cycle detection by creating a struct with fields named for each iteration. See https://cuetorials.com/deep-dives/recursion/ for more details.

#RecurseN: {
	#maxiter: uint | *20
	#funcFactory: {
		#next: _
		#func: _
	}

	for k, v in list.Range(0, #maxiter, 1) {
		#funcs: "\(k)": (#funcFactory & {#next: #funcs["\(k+1)"]}).#func
	}
	#funcs: "\(#maxiter)": null

	#funcs["0"]
}

The core of the bounded recursion is this structural comprehension (unrolled for loop). The "recursive call" is made with the following pattern.

(#funcFactory & {#next: #funcs["\(k+1)"]}).#func

You can override the iterations with { #maxdepth: 100 } at the point of usage or by creating new helpers from the existing ones. You may need to adjust this

  • up for deep objects
  • down if runtime is an issue
import "github.com/hofstadter-io/cuetils/structural"

#LeaguesDeep: structural.#Depth & { #maxdepth: 10000 }

Custom Helpers

You can make new helpers by building on the #RecurseN pattern. You need two definitions, a factory and the user facing, recursed version.

package structural

import (
	"list"

	"github.com/hofstadter-io/cuetils/recurse"
)

// A function factory
#depthF: {
	// always required
	#next: _
	
	// the actual computation, must be named #func
	#func: {
		// you can have any args
		#in: _
		// or internal helpers
		#multi: {...} | [...]
		
		// the result, can be named anything
    depth: {
			// detect leafs
			if (#in & #multi) == _|_ { 1 }
			// detect struct
			if (#in & {...}) != _|_ {
				list.Max([for k,v in #in {(#next & {#in: v}).depth}]) + 1
			}
			// detect list
			if (#in & [...]) != _|_ {
				list.Max([for k,v in #in {(#next & {#in: v}).depth}])
			}
    }
	}
}

// The user facing, recursed version
#Depth: recurse.#RecurseN & {#funcFactory: #depthF}

The core of the recursive calling is:

(#next & {#in: v}).depth
Owner
_Hofstadter
Developing new ways to develop
_Hofstadter
Comments
  • feature/pipeline

    feature/pipeline

    • implements the pipeline command and library
    • based on cue/flow DAG engine, tasks found by attributes
      • [x] @pipeline(name,[tags]) and @task([task/type],[tags])
    • supports many ops
      • [x] cuetils/structural
      • [x] @log (named @print currently)
      • [x] cue/tools/...
      • [x] api requests
      • [x] api server (?)
      • [x] db conn / call
      • [ ] background commands (bg, fg, kill)

    questions:

    • how to compose pipelines and still find tasks?
    • getting the final value?
    • is a pipeline a task as well?
    • progress reporting via chans?

    later / follow up issues:

    • drawing the pipeline?
  • Go implementations for improved performance and capabilities

    Go implementations for improved performance and capabilities

    Today, the implementations are in CUE and entry is at the top level. Go implementations would likely have better performance. Additionally, they may open up features like Pattern Constraints l: [string]: string and Closedness close(), #def, and ...

    The idea would be to walk values and the AST as needed.

    • [x] count
    • [x] depth
    • [x] diff
    • [x] patch
    • [x] pick
    • [x] mask
    • [x] replace
    • [x] insert
    • [x] upsert
    • [x] transform
    • [x] validate
  • Enable overwriting of files, or modifying name

    Enable overwriting of files, or modifying name

    When operating on many files, it would be helpful to

    • overwrite inplace
    • provide a pattern for alternative naming so as to write out without overwriting
  • Output when doing shell pipes and redirects

    Output when doing shell pipes and redirects

    Currently, redirecting or piping output is troublesome as output has headings when using globs. This should only be enabled with a flag so that piping / redir is easier in the default case

  • Don't use flags directly in structural Go funcs

    Don't use flags directly in structural Go funcs

    Flagpoles should be passed in rather than used directly. Would like to avoid having an extra config object since the flags are in their own package anyhow. Is this an anti-pattern?

    Support passing nil to the pkg funcs and filling in as necessary? How to handle defaults? Viper handles this via the bind that happens in the CLI, maybe modify hofmod-cli to create a DefaultFlagpole var?

  • support expressions for args

    support expressions for args

    args are always files, there are places where an expression could be useful like: mask / pick / query / replace

    cuetils query '{
      kind: _
      metadata: {
        name: _
        namespace: _
        labels: [string]: string
      }
    }' k8s/*.yaml
    
  • Additional helpers

    Additional helpers

    • [x] Replace - only if found, simpler input than patch
    • [x] Upsert - replace and add, simpler input than patch
    • [ ] ~Query - more capable than pick?~ (#18)
    • [x] Transform - mainly for bulk operations
    • [x] Validate - mainly for bulk operations
    • [x] Count - how many nodes are in object

    Others:

    Stats helper

    • combine depth and count
    • other stats?
    • demo of multiple multiple return

    ValidateDetail

    • show in object where validation errors happen, as a structured object
  • field not allowed: #content

    field not allowed: #content

    // schema.cue
    #a: {
      name: string
    }
    #a
    
    # a.yaml
    name: foo
    
    > cuetils validate schema.cue a.yaml
    a.yaml
    ----------------------
    field not allowed: #content
    
    
    Errors in 1 file(s)
    
    > cuetils version  
    cuetils ConfigDir "/Users/samlee/Library/Application Support/cuetils" <nil>
    
    Version:     v0.4.0
    Commit:      6263ed1672d52dfca3bb3cd7d5d27adfa102ec53
    
    BuildDate:   2022-02-02T05:05:42Z
    GoVersion:   go1.14
    OS / Arch:   darwin amd64
    
    
    Author:   Hofstadter, Inc
    Homepage: https://docs.hofstadter.io
    GitHub:   https://github.com/hofstadter-io/cuetils
    

    Workaround

    > cue vet schema.cue a.yaml
    >
    
  • No `cuetils` executable in container image v0.4

    No `cuetils` executable in container image v0.4

    # Executable file not found in $PATH
    $ docker run -it --rm hofstadter/cuetils:v0.4
    docker: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "cuetils": executable file not found in $PATH: unknown.
    
    # Nothing found
    $ docker run -it --rm --entrypoint find hofstadter/cuetils:v0.4 / -iname cuetils
    
  • cmd/extract

    cmd/extract

    Add an extract command that takes a CUE path and returns the result as a top level value, or maybe just add an -e flag?

    Maybe we have some of this with the input.cue:path.to.value syntax at the cli?

  • How might an operator be defined as a recursive structure?

    How might an operator be defined as a recursive structure?

    Creating an issue to capture the later thought in #32

    How could we define an operator input, such that it applies recursively to a tree which is itself recursive?

    a tree:

    name: "a1
    val: 0
    children: [{
      name: "b1"
      val: 0
      children: [ { name: "c1", val: 0 }]
    },{  
      name: "b2"
      val: 0
      children: [ { name: "c2", val: 0 }]
    }]
    

    the desired pick per node would produce the tree with just names

    name: string
    children: <...>?
    
  • Support Operators working on Go values

    Support Operators working on Go values

    An interesting use case is derived from the conversation in https://github.com/cue-lang/cue/discussions/1389

    Where one would like to pretty print a CUE AST with kr/pretty but without all the noise

    So how might Pick be applied recursively to an already recursive structure? meta...

  • Make an API mode

    Make an API mode

    Support an API mode, where ops & pipelines can be stored and then data can be sent.

    • v0, ops are loaded from disk
    • v1, a proper api with CRUD on ops
Related tags
GoLang-based client-side circuit breakers and helpers

Overview Example library for circuit breaking in GoLang. Written to support a blog post on https://www.wojno.com. Use this library in your SDK's to pr

Dec 5, 2021
Helpers for making the use of reflection easier

go-xray This is a Golang library with reflection related functions which I use in my different projects. KeyValue This type is used to construct a key

Oct 24, 2022
Raw ANSI sequence helpers

Raw ANSI sequence helpers

Oct 23, 2022
Goety - Generics based Go utilities

goety General purpose Go utilities. Package channel Utilities to work with chann

May 16, 2022
Utilities and immutable collections for functional programming in Golang

Utilities and immutable collections for functional programming in Golang. This is an experimental library to play with the new Generics Feature in Go 1.18.

Sep 1, 2022
Utilities for rounding and truncating floating point numbers.

Rounders Provides utilities for rounding and truncating floating point numbers. Example: rounders.RoundToDecimals(12.48881, 2)

Jan 6, 2022
Go-path - A helper package that provides utilities for parsing and using ipfs paths

go-path is a helper package that provides utilities for parsing and using ipfs paths

Jan 18, 2022
A collection of small Go utilities to make life easier.

The simplego package provides a collection of Go utilities for common tasks.

Jan 4, 2023
Utilities to generate (reference) documentation for the docker CLI

About This is a library containing utilities to generate (reference) documentation for the docker CLI on docs.docker.com. Disclaimer This library is i

Dec 28, 2022
Utilities for interacting with Dockerfiles
Utilities for interacting with Dockerfiles

go-dockerfile Golang utilities for interacting with Dockerfiles. This is not a place of honor. No esteemed source code is commemorated here. Don't tak

Apr 6, 2022
Simple utilities for creating ascii text in Go

Simple utilities for creating ascii text in Go

Oct 30, 2021
golden provides utilities for golden file tests.

golden provides utilities for golden file tests.

Dec 27, 2022
Source Repo for utilities used in Atlas

Atlas-Utilities Source Repo for utilities used in Atlas filepicker Simple file picker in Go using go-common-file-dialog This returns the path of a fil

Dec 25, 2022
List-Utils - 🔧 Utilities for maintaining the list of repost sites

SMR List Utils This is a Go CLI tool that helps with managing the StopModReposts blacklist. Install Use GitHub Releases and download binary. Linux Qui

Jan 3, 2022
Utilities for processing Wikipedia dumps in Go

Utilities for processing Wikipedia dumps in Go A Go package providing utilities for processing Wikipedia dumps. Features: Supports Wikidata entities J

Nov 29, 2022
Go-Utils is a library containing a collection of Golang utilities

Go-Utils is a library containing a collection of Golang utilities

Jun 2, 2022
This project provides some working examples using Go and Hotwire Turbo.

hotwire-golang-website This project provides some working examples using Go the hotwire/turbo library published by basecamp.

Dec 29, 2022
tool for working with numbers and units

tool for working with numbers and units

Nov 26, 2022
Payload is a simple tool for working with production data in your local environment.

Payload Payload is a simple tool for working with production data in your local environment. What problem does it solve? You're working with Cloud SQL

Oct 13, 2021