Cue Lang介紹

Cue,是一種開源語言,用於定義,生成和驗證各種數據:配置,API,數據庫模式,代碼......。它能夠將數據的結構、約束、數值作爲同一層級成員,從而簡化配置文件的生成。
Cue教程

Cue格式說明

  1. 使用//進行單行註釋
  2. 對象被稱爲結構體
  3. 對象成員稱爲結構字段
  4. 對於沒有特殊字符的字段名,可以省略引號
  5. 結構字段後面無需,
  6. 在列表中的最後一個元素後放置,
  7. 最外層的{}可省略

例子:

str: "hello world"
num: 42
flt: 3.14

// Special field name (and a comment)
"k8s.io/annotation": "secure-me"

// lists can have different element types
list: [
    "a", "b", "c",
    1,
    2,
    3,
]

obj: {
    foo: "bar"
    // reuse another field?!
    L: list
}

Cue 結構、約束、數據

// 結構
album: {
    title: string
    year: int
    live: bool
}
// 約束
album: {
    title: string
    year: >1950
    live: false
}
// 數據
album: {
    title: "Houses of the Holy"
    year: 1973
    live: false
}

Cue的最佳實踐:從開放的結構模式開始,限制上下文可能性,最終具體到數據實例。
Cue哲學:爲了保證唯一性,Cue的數據不會被覆蓋。

Cue核心規則

  1. 數據可被重複定義,但必須值保持一致
  2. 結構字段可以被更強限制覆蓋
  3. 結構的字段會被合併,如果是列表,必須嚴格匹配
  4. 規則可被遞規應用
hello: "world"
hello: "world"

// set a type
s: { a: int }

// set some data
s: { a: 1, b: 2 }

// set a nested field without curly braces
s: c: d: 3

// lists must have the same elements
// and cannot change length
l: ["abc", "123"]
l: [
    "abc",
    "123"
]

結構

  1. 結構並不會輸出
  2. 它的值可能是不確認、不完整的
  3. 字段必須完全

使用#mydef來定義結構,使用...來定義一個開放的結構體

#Album: {
    artist: string
    title: string
    year: int

    // ...  uncomment to open, must be last
}

// This is a conjunction, it says "album" has to be "#Album"
album: #Album & {
    artist: "Led Zeppelin"
    title: "Led Zeppelin I"
    year: 1969

    // studio: true  (uncomment to trigger error)
}

#Person: {
 name: string
... // open struct
}

Jim: #Person & {
 name: "jim"
 age: 12
}

約束

約束與數值使用&字符進行連接時,會將值進行校驗

// conjunctions on a field
n: int & >0 & <100
n: 23

// conjuction of schemas
val: #Def1 & #Def2
val: { foo: "bar", ans: 42 }

#Def1: {
    foo: string
    ans: int
}

#Def2: {
    foo: =~ "[a-z]+"
    ans: >0
}

替換

使用|可以實現支持多種結構。同時它也可以爲出錯值設置替換值

// disjunction of values (like an enum)
hello: "world" | "bob" | "mary"
hello: "world"

// disjunction of types
port: string | int
port: 5432

// disjunction of schemas
val: #Def1 | #Def2
val: { foo: "bar", ans: 42 }

#Def1: {
    foo: string
    ans: int
}

#Def2: {
    name: string
    port: int
}

默認值與可選

使用*來設置默認值, ?設置可選字段

s: {
    // field with a default
    hello: string | *"world" | "apple"
    // an optional integer
    count?: int
}

開放模式與封閉模式

開放模式意味着結構可以擴展,關閉模式意味着不能擴展。 默認情況下,結構是開放模式,定義是封閉模式。 可以通過定義的最後添加...來申明開放模式定義;另外通過過close強制爲結構體設置爲關閉模式

// Open definition
#d: {
    foo: "bar"
    ... // must be last
}

// Closed struct
s: close({
    foo: "bar"
})

jim: {
  name: "Jim"
}
jim: {
  age: 12
}

推薦從基礎定義開始,複用定義

在編寫Cue時,推薦從基礎定義開始,這樣能夠有更好的複用能力。

#Base: {
    name: string
    kind: string
    ... // so it can be extended
}
#Meta: {
    // string and a semver regex
    version: string & =~"^v[0-9]+\\.[0-9]+\\.[0-9]+$"
    // list of strings
    labels: [...string]
}

#Permissions: {
    role: string
    public: bool | *false
}

// Building up a schema using a conjunction and embedding
#Schema: #Base & {
    // "embed" meta and permissions
    #Meta
    #Permissions
    // with no '...' this is final
}

value: #Schema & {
    name: "app"
    kind: "deploy"
    version: "v1.0.42"
    labels: ["server", "prod"]
    role: "backend"
    // public: false  (by default)
}

使用"""來定義多行字符串

str1: #"avoid using \ to "escape""#
str2: """
a nested multiline
string goes here
"""

List

List 可被定義爲開放模式,這樣便可與其它數據進行合併,

empty: []
any: [...]
ints: [...int]
nested: [...[...string]]

opened: ints & [1,2,...]
closed: ints & [1,2,3]

// list of for constrained ints
ip: 4 * [uint8]
// sets the first element
tendot: ip & [10, ...uint8]
// uses constraint as second element
one72: ip & [172, >=16 & <=32, ...]

mixed: any & [...] & ["a",1, { foo: "bar" }]
join: [1,2] + [3,4]
Join: opened & join

Struct

結構體是Cue的主要內容,也是最終數據的輸出。如上介紹,默認情況下它是開放模式。除了使用Json類型形式進行設置值,還可通過級聯:來設置,如a: hello: "world"

// an open struct
a: {
    foo: "bar"
}

// shorthand nested field
a: hello: "world"

// a closed struct
b: close({
    left: "right"
})

模式匹配約束

模式匹配允許您爲與模式匹配的標籤指定約束。可以將約束應用於字符串標籤,並使用標識符來設置字段。

#schema: {
    name: string
    ans: string
    num: int | *42
}

// match elem fields and alias labels to Name,
// unify with schema, set name to Name by label
elems: [Name=_]: #schema & { name: Name }

elems: {
    one: {
        ans: "solo"
        num: 1
    }
    two: {
        ans: "life"
    }
}

elems: other: { ans: "id", num: 23 }

表達式

  1. 引用字段,使用\(**)顯用其它字段
container: {
    repo: "docker.io/cuelang"
    image: "cue"
    version: "v0.3.0"
    full: "\(repo)/\(image):\(version)"
}

name: "Tony"
msg: "Hello \(name)"
// conver string to bytes
b: '\(msg)'
// convert bytes to string
s: "\(b)"
  1. Cue也能夠爲通過\(**)來設置key
apps: ["nginx", "express", "postgres"]
#labels: [string]: string
stack: {
    for i, app in apps {
        "\(app)": {
            name: app
            labels: #labels & {
                app: "foo"
                tier: "\(i)"
            }
        }
    }
}
  1. List遍歷
    遍歷List數據格式如下:[ for key, val in <iterable> [condition] { production } ]
nums: [1,2,3,4,5,6]
sqrd: [ for _, n in nums { n*n } ]
even: [ for _, n in nums if mod(n,2) == 0 { n } ]

listOfStructs: [ for p, n in nums {
    pos: p
    val: n
}]

extractVals: [ for p, S in listOfStructs { S.val } ]
  1. 條件控制語句
    沒有else,所有判斷都會被執行
app: {
    name: string
    tech: string
    mem: int

    if tech == "react" {
        tier: "frontend"
    }
    if tech != "react" {
        tier: "backend"
    }

    if mem < 1Gi {
        footprint: "small"
    }
    if mem >= 1Gi && mem < 4Gi {
        footprint: "medium"
    }
    if mem  >= 4Gi {
        footprint: "large"
    }
}

標準庫

Cue的標準庫中包含了很多的幫助包(helper packages)。

  1. Encoding
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)
  1. Strings
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")
  1. List
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)
  1. Constrain
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"

參考文檔

cue torials

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章