From 7ea0b1ef0d3223cbcf2cd52538e5b51edd638eb6 Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Tue, 12 Dec 2023 15:46:10 +0545 Subject: [PATCH] feat: add new functions to cel-go docs * format the markdown as well --- canary-checker/docs/scripting/cel.md | 3180 +++++++--------- mission-control/.gitignore | 1 + .../docs/reference/authentication.md | 102 - mission-control/docs/reference/connections.md | 92 - .../docs/reference/scripting/cel-extra.md | 598 --- .../docs/reference/scripting/cel.md | 3317 ----------------- .../docs/reference/scripting/functions.md | 73 - .../docs/reference/scripting/gotemplate.md | 2203 ----------- .../docs/reference/scripting/javascript.md | 55 - .../docs/reference/scripting/overview.md | 7 - 10 files changed, 1361 insertions(+), 8267 deletions(-) delete mode 100644 mission-control/docs/reference/authentication.md delete mode 100644 mission-control/docs/reference/connections.md delete mode 100644 mission-control/docs/reference/scripting/cel-extra.md delete mode 100644 mission-control/docs/reference/scripting/cel.md delete mode 100644 mission-control/docs/reference/scripting/functions.md delete mode 100644 mission-control/docs/reference/scripting/gotemplate.md delete mode 100644 mission-control/docs/reference/scripting/javascript.md delete mode 100644 mission-control/docs/reference/scripting/overview.md diff --git a/canary-checker/docs/scripting/cel.md b/canary-checker/docs/scripting/cel.md index e510b594..685b5869 100644 --- a/canary-checker/docs/scripting/cel.md +++ b/canary-checker/docs/scripting/cel.md @@ -1,8 +1,7 @@ - # CEL Expressions -`expr` expressions in canary checker use the [Go Common Expression Language (CEL)](https://github.com/google/cel-go) See [Language Definition](https://github.com/google/cel-spec/blob/master/doc/langdef.md#overview) - +`expr` expressions in canary checker use the [Go Common Expression Language (CEL)](https://github.com/google/cel-go). +See [Language Definition](https://github.com/google/cel-spec/blob/master/doc/langdef.md#overview) ```yaml title=http-check-expr.yaml apiVersion: canaries.flanksource.com/v1 @@ -19,7 +18,92 @@ spec: ``` --- -## Collections + +## aws + +### arnToMap + +Takes in an AWS arn and parses it and returns a map. + +Snytax + +``` + arnToMap(string): map[string]string + + Where + - arg: string + - returns: map[string]string{ + "service": string, + "region": string, + "account": string, + "resource": string, + } +``` + +Examples: + +```javascript +arnToMap("arn:aws:sns:eu-west-1:123:MMS-Topic").region; // evaluates to 'eu-west-1' +``` + +### fromAWSMap + +`fromAWSMap` takes a list of `map[string]string` and merges them into a single map. The input map is expected to have the field "Name". + +Syntax + +``` + fromAWSMap([]map[string]string{}): map[string]string{} +``` + +Examples: + +```javascript +`fromAWSMap(x).hello" == "world"`; // evaluates to `true` +// Where +// x = [ +// { Name: 'hello', Value: 'world' }, +// { Name: 'John', Value: 'Doe' }, +// ]; +``` + +--- + +## base64 + +### base64.encode + +The `base64.encode` function encodes the given byte slice to a Base64 encoded string. + +Syntax: + + base64.encode([]bytes): string + +Examples: + +```javascript +base64.decode("aGVsbG8="); // return b'hello' +base64.decode("aGVsbG8"); // error +``` + +### base64.decode + +The `base64.decode` function decodes the given base64 encoded string back to its original form. + +Syntax: + + base64.decode(string): []bytes + +Examples: + +```javascript +base64.decode("aGVsbG8="); // return b'hello' +base64.decode("aGVsbG8"); // error +``` + +--- + +## collections ### in @@ -35,18 +119,19 @@ Examples: ```javascript `"apple" in ["apple", "banana"]` // evaluates to `true` -`3 in [1, 2, 4]` // evaluates to `false` +`3 in [1, 2, 4]`; // evaluates to `false` ``` ---- ### size The `size` function in CEL is used to determine the number of elements in a collection or the number of Unicode characters in a string. Syntax: + ``` collection.size() or string.size() ``` + Examples: ```javascript @@ -57,8 +142,6 @@ Determining the number of characters in a string: "hello".size() // Evaluates to 5 ``` ---- - ### has The `has` macro checks for the presence of a field in a message. It's particularly useful for protobuf messages where fields can be absent rather than set to a default value. It's especially useful for distinguishing between a field being set to its default value and a field being unset. For instance, in a protobuf message, an unset integer field is indistinguishable from that field set to 0 without the `has` macro. @@ -66,7 +149,7 @@ The `has` macro checks for the presence of a field in a message. It's particular Syntax ```javascript -x.has(y) +x.has(y); ``` Where `x` is the message and `y` is the field you're checking for. @@ -76,13 +159,11 @@ Examples: If you have a message `person` with a potential field `name`, you can check for its presence with: ```javascript -person.has(name) // Evaluates to true if 'name' is present, false otherwise +person.has(name); // Evaluates to true if 'name' is present, false otherwise -addressBook.has(person.email) // Evaluates to true if 'email' field is present in 'person' within 'addressBook' +addressBook.has(person.email); // Evaluates to true if 'email' field is present in 'person' within 'addressBook' ``` ---- - ### map The `map` macro creates a new collection by applying a function to each entry of an existing collection. It's useful for transforming the elements of a list or the values of a map. @@ -110,23 +191,19 @@ Examples: ```javascript // Transforming each element of a list by multiplying it by 2: -[1, 2, 3].map(e, e * 2) // Evaluates to [2, 4, 6] +[1, 2, 3].map(e, e * 2); // Evaluates to [2, 4, 6] ``` - ```javascript // Transforming the values of a map by appending "!" to each value: {"a": "apple", "b": "banana"}.map(k, v, v + "!") // Evaluates to {"a": "apple!", "b": "banana!"} ``` - ```javascript // Using both key and value for transformation in a map: {"a": 1, "b": 2}.map(k, v, k + v) // Evaluates to {"a": "a1", "b": "b2"} ``` ---- - ### filter The `filter` macro creates a new collection containing only the elements or entries of an existing collection that satisfy a given condition. @@ -160,8 +237,6 @@ Examples: {"a": 1, "b": 2, "c": 3}.filter(k, v, v > 1) // Evaluates to {"b": 2, "c": 3} ``` ---- - ### all The `all` macro checks if all elements of a collection, such as a list or a map, satisfy a given condition. It returns a boolean value based on the evaluation. @@ -198,8 +273,6 @@ Examples: {"a": 1, "b": 2, "c": 3}.all(k, v, k != "a" || v > 1) // Evaluates to true ``` ---- - ### exists The `exists` macro checks if there exists an element in a collection, such as a list or a map, that satisfies a given condition. It returns a boolean value based on the evaluation. @@ -236,8 +309,6 @@ Examples: {"a": 1, "b": 2, "c": 3}.exists(k, v, k == "a" && v == 1) // Evaluates to true ``` ---- - ### fold The `fold` macro is used to combine all elements of a collection, such as a list or a map, using a binary function. It's a powerful tool for aggregating or reducing data. @@ -252,7 +323,6 @@ list.fold(e, acc, ) map.fold(k, v, acc, ) ``` - Where: - `list` is the list you're folding. @@ -273,11 +343,8 @@ Examples: {"a": "apple", "b": "banana"}.fold(k, v, acc, acc + v) // Evaluates to "applebanana" ``` ---- - ### slice - Returns a new sub-list using the indexes provided. ```javascript @@ -287,12 +354,15 @@ Returns a new sub-list using the indexes provided. Examples: ```javascript -[1,2,3,4].slice(1, 3) // return [2, 3] -[1,2,3,4].slice(2, 4) // return [3 ,4] +[1, 2, 3, 4] + .slice(1, 3) // return [2, 3] + [(1, 2, 3, 4)].slice(2, 4); // return [3 ,4] ``` --- +## sets + ### sets.contains Returns whether the first list argument contains all elements in the second @@ -313,8 +383,6 @@ sets.contains([1, 2, 3, 4], [2, 3]) // true sets.contains([1, 2.0, 3u], [1.0, 2u, 3]) // true ``` ---- - ### sets.equivalent Returns whether the first and second list are set equivalent. Lists are set @@ -334,8 +402,6 @@ sets.equivalent([1], [1u, 1.0]) // true sets.equivalent([1, 2, 3], [3u, 2.0, 1]) // true ``` ---- - ### sets.intersects Returns whether the first list has at least one element whose value is equal @@ -347,902 +413,249 @@ be false. Examples: ```javascript -sets.intersects([1], []) // false -sets.intersects([1], [1, 2]) // true -sets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // true +sets.intersects([1], []); // false +sets.intersects([1], [1, 2]); // true +sets.intersects( + [[1], [2, 3]], + [ + [1, 2], + [2, 3.0], + ] +); // true ``` --- -## Strings +## csv -### matches +### CSV -The `matches` function in CEL is used to determine if a string matches a given regular expression pattern. It returns a boolean value indicating whether the string conforms to the pattern. +The `CSV` function converts a CSV formatted array into a two-dimensional array, where each element is a row string. Syntax: -```javascript -string.matches(pattern) -``` + CSV(csvRowList) Where: -- `string` is the string you're checking. -- `pattern` is the regular expression pattern you're matching against. +- `csvRowList` is a list of rows. Examples: ```javascript -// Checking if a string matches a simple pattern: -"apple".matches("^a.*e$") // Evaluates to true - -// Validating an email format: -"example@email.com".matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$") // Evaluates to true - -// Checking for a pattern of digits: -"12345".matches("^\\d+$") // Evaluates to true +CSV(["Alice,30", "Bob,31"])[0][0]; // Evaluates to "Alice" ``` + --- -### startsWith + -### size +## crypto -The `size` function in CEL is used to determine the number of elements in a collection or the number of Unicode characters in a string. +### crypto.SHA1 + +The `crypto.SHA1` function in CEL is used to compute the SHA-1 hash of the input data. Note that SHA-1 is considered insecure for cryptographic purposes. Syntax: - collection.size() or string.size() + crypto.SHA1(data) + +Where: + +- `data` is the input data to be hashed. Examples: ```javascript -// Getting the size of a list: -["apple", "banana", "cherry"].size() // Evaluates to 3 +Hashing a simple string: +crypto.SHA1("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c" -// Determining the number of characters in a string: -"hello".size() // Evaluates to 5 -``` +Hashing a number represented as a string: +crypto.SHA1("12345") // Might evaluate to "8cb2237d0679ca88db6464eac60da96345513964" ---- +Hashing special characters: +crypto.SHA1("!@#") // Might evaluate to "8f9b6cb1cf7d70f23c16c9b9d4894d7f3b8fe15d" +``` -### charAt +### crypto.SHA224 -Returns the character at the given position. If the position is negative, or -greater than the length of the string, the function will produce an error: -``` - .charAt() -> -``` -Examples: +The `crypto.SHA224` function in CEL calculates the SHA-224 hash of the provided input data, offering a balance between security and performance. -```javascript -'hello'.charAt(4) // return 'o' -'hello'.charAt(5) // return '' -'hello'.charAt(-1) // error -``` +Syntax: ---- + crypto.SHA224(data) -### indexOf +Where: -Returns the integer index of the first occurrence of the search string. If the -search string is not found the function returns -1. +- `data` is the input data to be hashed. -The function also accepts an optional position from which to begin the -substring search. If the substring is the empty string, the index where the -search starts is returned (zero or custom). -``` - .indexOf() -> - .indexOf(, ) -> -``` Examples: ```javascript -'hello mellow'.indexOf('') // returns 0 -'hello mellow'.indexOf('ello') // returns 1 -'hello mellow'.indexOf('jello') // returns -1 -'hello mellow'.indexOf('', 2) // returns 2 -'hello mellow'.indexOf('ello', 2) // returns 7 -'hello mellow'.indexOf('ello', 20) // error +Hashing a simple string: +crypto.SHA224("hello") // Might evaluate to "ea09ae9cc6768c50fcee903ed054556e5bfc8347907f12598aa24193" + +Hashing a number represented as a string: +crypto.SHA224("12345") // Might evaluate to "a7470858e79c282bc2f6adfd831b132672dfd1224c1e78cbf5bcd057" ``` ---- +### crypto.SHA256 -### lastIndexOf +The `crypto.SHA256` function in CEL calculates the SHA-256 hash of the provided input data, offering a balance between security and performance. -Returns the integer index of the last occurrence of the search string. If the -search string is not found the function returns -1. +Syntax: + + crypto.SHA256(data) + +Where: + +- `data` is the input data to be hashed. -The function also accepts an optional position which represents the last index -to be considered as the beginning of the substring match. If the substring is -the empty string, the index where the search starts is returned (string length -or custom). -``` - .lastIndexOf() -> - .lastIndexOf(, ) -> -``` Examples: ```javascript -'hello mellow'.lastIndexOf('') // returns 12 -'hello mellow'.lastIndexOf('ello') // returns 7 -'hello mellow'.lastIndexOf('jello') // returns -1 -'hello mellow'.lastIndexOf('ello', 6) // returns 1 -'hello mellow'.lastIndexOf('ello', -1) // error -``` +Hashing a simple string: +crypto.SHA256("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" ---- +Hashing a number represented as a string: +crypto.SHA256("12345") // Might evaluate to "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2" -### join +Hashing special characters: +crypto.SHA256("!@#") // Might evaluate to "d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8" +``` -Returns a new string where the elements of string list are concatenated. +### crypto.SHA384 -The function also accepts an optional separator which is placed between -elements in the resulting string. -``` - >.join() -> - >.join() -> -``` -Examples: +The `crypto.SHA384` function in CEL is used for computing the SHA-384 hash of the input data, which is a truncated version of SHA-512 and provides enhanced security. -```javascript -['hello', 'mellow'].join() // returns 'hellomellow' -['hello', 'mellow'].join(' ') // returns 'hello mellow' -[].join() // returns '' -[].join('/') // returns '' -``` +Syntax: ---- + crypto.SHA384(data) + +Where: -### quote +- `data` is the input data to be hashed. -Takes the given string and makes it safe to print (without any formatting due to escape sequences). -If any invalid UTF-8 characters are encountered, they are replaced with \uFFFD. -``` - strings.quote() -``` Examples: ```javascript -strings.quote('single-quote with "double quote"') // returns '"single-quote with \"double quote\""' -strings.quote("two escape sequences \a\n") // returns '"two escape sequences \\a\\n"' -``` +Hashing a simple string: +crypto.SHA384("hello") // Might evaluate to a long hash string ---- +Hashing a number represented as a string: +crypto.SHA384("12345") // Might evaluate to another long hash string -### replace +Hashing special characters: +crypto.SHA384("!@#") // Might evaluate to yet another long hash string +``` -Returns a new string based on the target, which replaces the occurrences of a -search string with a replacement string if present. The function accepts an -optional limit on the number of substring replacements to be made. - -When the replacement limit is 0, the result is the original string. When the -limit is a negative number, the function behaves the same as replace all. - -```javascript -.replace(, ) -> -.replace(, , ) -> -``` - -Examples: - -```javascript -'hello hello'.replace('he', 'we') // returns 'wello wello' -'hello hello'.replace('he', 'we', -1) // returns 'wello wello' -'hello hello'.replace('he', 'we', 1) // returns 'wello hello' -'hello hello'.replace('he', 'we', 0) // returns 'hello hello' -``` - ---- - -### split - -Returns a list of strings split from the input by the given separator. The -function accepts an optional argument specifying a limit on the number of -substrings produced by the split. - -When the split limit is 0, the result is an empty list. When the limit is 1, -the result is the target string to split. When the limit is a negative -number, the function behaves the same as split all. -``` - .split() -> > - .split(, ) -> > -``` -Examples: - -```javascript -'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello'] -'hello hello hello'.split(' ', 0) // returns [] -'hello hello hello'.split(' ', 1) // returns ['hello hello hello'] -'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello'] -'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello'] -``` - ---- - -### substring - -Returns the substring given a numeric range corresponding to character -positions. Optionally may omit the trailing range for a substring from a given -character position until the end of a string. - -Character offsets are 0-based with an inclusive start range and exclusive end -range. It is an error to specify an end range that is lower than the start -range, or for either the start or end index to be negative or exceed the string -length. -``` - .substring() -> - .substring(, ) -> -``` -Examples: - -```javascript -'tacocat'.substring(4) // returns 'cat' -'tacocat'.substring(0, 4) // returns 'taco' -'tacocat'.substring(-1) // error -'tacocat'.substring(2, 1) // error -``` - ---- - -### trim - -Returns a new string which removes the leading and trailing whitespace in the -target string. The trim function uses the Unicode definition of whitespace -which does not include the zero-width spaces. See: -https://en.wikipedia.org/wiki/Whitespace_character#Unicode -``` - .trim() -> -``` -Examples: - - ' \ttrim\n '.trim() // returns 'trim' - - -### TrimPrefix - -The `TrimPrefix` function in CEL removes a given prefix from a string if the string starts with that prefix. - -Syntax: - - TrimPrefix(prefix, string) - -Where: - -- `prefix` is the starting substring to remove. -- `string` is the string from which the prefix will be removed. - -Examples: - -```javascript -// Removing a prefix from a string: -TrimPrefix("Mr.", "Mr. Smith") // Evaluates to "Smith" - -// Another example: -TrimPrefix("Astro", "Astronaut") // Evaluates to "naut" - -// If the prefix is not present: -TrimPrefix("Dr.", "Mr. Smith") // Evaluates to "Mr. Smith" -``` - ---- - -### TrimSuffix - -The `TrimSuffix` function in CEL removes a given suffix from a string if the string ends with that suffix. - -Syntax: - - TrimSuffix(suffix, string) - -Where: - -- `suffix` is the ending substring to remove. -- `string` is the string from which the suffix will be removed. - -Examples: - -```javascript -// Removing a suffix from a string: -TrimSuffix(".jpg", "image.jpg") // Evaluates to "image" - - -// If the suffix is not present: -TrimSuffix(".png", "image.jpg") // Evaluates to "image.jpg" -``` ---- - -### lowerAscii - -Returns a new string where all ASCII characters are lower-cased. - -This function does not perform Unicode case-mapping for characters outside the -ASCII range. -``` - .lowerAscii() -> -``` -Examples: - -```javascript - 'TacoCat'.lowerAscii() // returns 'tacocat' - 'TacoCÆt Xii'.lowerAscii() // returns 'tacocÆt xii' -``` - ---- - -### - -### upperAscii - -Returns a new string where all ASCII characters are upper-cased. - -This function does not perform Unicode case-mapping for characters outside the -ASCII range. -``` - .upperAscii() -> -``` -Examples: - -```javascript - 'TacoCat'.upperAscii() // returns 'TACOCAT' - 'TacoCÆt Xii'.upperAscii() // returns 'TACOCÆT XII' -``` - ---- - -### reverse - -Returns a new string whose characters are the same as the target string, only formatted in -reverse order. -This function relies on converting strings to rune arrays in order to reverse. -It can be located in Version 3 of strings. -``` - .reverse() -> -``` -Examples: - -```javascript -'gums'.reverse() // returns 'smug' -'John Smith'.reverse() // returns 'htimS nhoJ' -``` - ---- - - - -### HumanDuration - -The `HumanDuration` function in CEL converts a duration into a human-readable format. - -Syntax: - - HumanDuration(duration) - -Where: - -- `duration` is the duration you want to convert. - -Examples: - -```javascript -// Converting a duration into a human-readable format: -HumanDuration(3600) // Evaluates to "1 hour" - -// Converting another duration: -HumanDuration(600) // Evaluates to "10 minutes" - -// Converting a longer duration: -HumanDuration(86400) // Evaluates to "1 day" -``` - ---- - -### HumanSize - -The `HumanSize` function in CEL converts a size in bytes into a human-readable format. - -Syntax: - - HumanSize(size) - -Where: - -- `size` is the size in bytes you want to convert. - -Examples: - -```javascript -// Converting a size into a human-readable format: -HumanSize(1024) // Evaluates to "1 KiB" - -// Converting another size: -HumanSize(1048576) // Evaluates to "1 MiB" - -// Converting a larger size: -HumanSize(1073741824) // Evaluates to "1 GiB" -``` - ---- - -### Semver - -The `Semver` function in CEL parses a version string and returns a map containing the major, minor, patch, prerelease, metadata, and original version. - -Syntax: - - Semver(version) - -Where: - -- `version` is the version string to parse. - -Examples: - -```javascript -// Parsing a semantic version: -Semver("1.2.3-alpha+meta") // Evaluates to a map with major: "1", minor: "2", patch: "3", prerelease: "alpha", metadata: "meta", original: "1.2.3-alpha+meta" - -Semver("2.3.4-beta+meta2") // Evaluates to a map with major: "2", minor: "3", patch: "4", prerelease: "beta", metadata: "meta2", original: "2.3.4-beta+meta2" - -// Parsing a simple semantic version: -Semver("3.4.5") // Evaluates to a map with major: "3", minor: "4", patch: "5", prerelease: "", metadata: "", original: "3.4.5" -``` - ---- - -### SemverCompare - -The `SemverCompare` function in CEL compares two semantic version strings. - -Syntax: - - SemverCompare(version1, version2) - -Where: - -- `version1` is the first version string to compare. -- `version2` is the second version string to compare. - -Examples: - -```javascript -// Comparing two semantic versions: -SemverCompare("1.2.3", "1.2.4") // Evaluates to false - -// Comparing two identical versions: -SemverCompare("2.3.4", "2.3.4") // Evaluates to true - -// Comparing with a prerelease version: -SemverCompare("3.4.5", "3.4.5-alpha") // Evaluates to false -``` - ---- - -### ReplaceAll - -The `ReplaceAll` function in CEL replaces all occurrences of a substring within a string with another substring. - -Syntax: - - ReplaceAll(old, new, string) - -Where: - -- `old` is the substring to be replaced. -- `new` is the substring to replace with. -- `string` is the original string. - -Examples: - -```javascript -// Replacing a substring: -ReplaceAll("apple", "orange", "I have an apple") // Evaluates to "I have an orange" - -// Replacing another substring: -ReplaceAll("cat", "dog", "The cat sat on the mat") // Evaluates to "The dog sat on the mat" - -// Replacing a substring with a number: -ReplaceAll("one", "1", "I have one apple") // Evaluates to "I have 1 apple" -``` - ---- - - - -### Repeat - -The `Repeat` function in CEL repeats a string for a given number of times. - -Syntax: - - Repeat(count, string) - -Where: - -- `count` is the number of times the string should be repeated. -- `string` is the string to repeat. - -Examples: - -```javascript -// Repeating a string: -Repeat(3, "apple") // Evaluates to "appleappleapple" - -``` - ---- - -### Sort - -The `Sort` function in CEL sorts a list of strings. - -Syntax: - - Sort(list) - -Where: - -- `list` is the list of strings to sort. - -Examples: - -```javascript -Sorting a list of strings: -Sort(["banana", "apple", "cherry"]) // Evaluates to ["apple", "banana", "cherry"] - -Sorting another list: -Sort(["dog", "cat", "bird"]) // Evaluates to ["bird", "cat", "dog"] - -Sorting a list with numbers: -Sort(["3", "1", "2"]) // Evaluates to ["1", "2", "3"] -``` - ---- - - ---- - - -### Title - -The `Title` function in CEL converts the first character of each word in a string to uppercase. - -Syntax: - - Title(string) - -Where: - -- `string` is the string to convert. - -Examples: - -```javascript -// Converting a string: -Title("hello world") // Evaluates to "Hello World" - -// Working with mixed case: -Title("mIxEd CaSe") // Evaluates to "MIxED CASe" -``` - ---- - - -### Indent - -The `Indent` function in CEL indents each line of a string by a specified number of spaces or a specified prefix. - -Syntax: - - Indent(width or prefix, string) - -Where: - -- `width or prefix` is the number of spaces or the prefix string to add before each line. -- `string` is the string to indent. - -Examples: - -```javascript -// Indenting with spaces: -Indent(4, "Line1\nLine2") // Evaluates to " Line1\n Line2" - -//Indenting with a prefix: -Indent("> ", "Line1\nLine2") // Evaluates to "> Line1\n> Line2" - -// Indenting with a mixed prefix: -Indent("==", "Line1\nLine2") // Evaluates to "==Line1\n==Line2" -``` - ---- - -### Slug - -The `Slug` function in CEL converts a given string into a URL-friendly slug format. - -Syntax: - - Slug(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -// Converting a string to a slug: -Slug("Hello World!") // Evaluates to "hello-world" - -// Converting a string with special characters: -Slug("Hello, World!") // Evaluates to "hello-world" - -// Converting a multi-word string: -Slug("Hello Beautiful World") // Evaluates to "hello-beautiful-world" -``` - ---- - -### Quote - -The `Quote` function in CEL adds double quotes around a given string. - -Syntax: - - Quote(string) - -Examples: - -```javascript -//Quoting a simple string: -Quote("Hello World") // Evaluates to "\"Hello World\"" - -// Quoting a string with a number: -Quote("12345") // Evaluates to "\"12345\"" - -// Quoting an already quoted string: -Quote("\"Hello World\"") // Evaluates to "\"\"Hello World\"\"" -``` - ---- - -### ShellQuote - -The `ShellQuote` function in CEL quotes a string such that it can be safely used as a token in a shell command. - -Syntax: - - ShellQuote(string) - -Examples: - -```javascript -// Shell quoting a string: -ShellQuote("Hello World") // Evaluates to "'Hello World'" - -// Shell quoting a string with special characters: -ShellQuote("Hello$World") // Evaluates to "'Hello$World'" - -// Shell quoting a string with spaces and special characters: -ShellQuote("Hello World$123") // Evaluates to "'Hello World$123'" -``` - ---- - -### Squote - -The `Squote` function in CEL adds single quotes around a given string. - -Syntax: - - Squote(string) - - - -Examples: - -```javascript -Single quoting a simple string: -Squote("Hello World") // Evaluates to "'Hello World'" - -Single quoting a string with a number: -Squote("12345") // Evaluates to "'12345'" - -Single quoting an already single quoted string: -Squote("'Hello World'") // Evaluates to "'''Hello World'''" -``` - ---- - -### SnakeCase - -The `SnakeCase` function in CEL converts a given string into snake_case format. - -Syntax: - - SnakeCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -Converting a string to snake_case: -SnakeCase("Hello World") // Evaluates to "hello_world" - -Converting a CamelCase string: -SnakeCase("HelloWorld") // Evaluates to "hello_world" - -Converting a string with spaces and special characters: -SnakeCase("Hello Beautiful World!") // Evaluates to "hello_beautiful_world" -``` - ---- - -### CamelCase - -The `CamelCase` function in CEL converts a given string into CamelCase format. - -Syntax: - - CamelCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -Converting a string to CamelCase: -CamelCase("hello world") // Evaluates to "HelloWorld" - -Converting a snake_case string: -CamelCase("hello_world") // Evaluates to "HelloWorld" - -Converting a string with spaces and special characters: -CamelCase("hello beautiful world!") // Evaluates to "HelloBeautifulWorld" -``` - ---- - -### KebabCase - -The `KebabCase` function in CEL converts a given string into kebab-case format. - -Syntax: - - KebabCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: +### crypto.SHA512 -```javascript -Converting a string to kebab-case: -KebabCase("Hello World") // Evaluates to "hello-world" - -Converting a CamelCase string: -KebabCase("HelloWorld") // Evaluates to "hello-world" - -Converting a string with spaces and special characters: -KebabCase("Hello Beautiful World!") // Evaluates to "hello-beautiful-world" -``` - ---- - -### WordWrap - -The `WordWrap` function in CEL wraps the input string at the specified width. - -Syntax: - - WordWrap(width, string) - -Where: - -- `width` is the number of characters at which to wrap the string. -- `string` is the input string to be wrapped. - -Examples: - -```javascript -Wrapping a string at a specified width: -WordWrap(5, "Hello World") // Evaluates to "Hello\nWorld" - -Wrapping a longer string: -WordWrap(10, "Hello Beautiful World") // Evaluates to "Hello\nBeautiful\nWorld" - -Wrapping a string with special characters: -WordWrap(5, "Hello$World") // Evaluates to "Hello\n$World" -``` - ---- - -### RuneCount - -The `RuneCount` function in CEL counts the number of runes in a given string. +The `crypto.SHA512` function in CEL calculates the SHA-512 hash of the given input data. It's commonly used for data integrity verification and password storage. Syntax: - RuneCount(string) + crypto.SHA512(data) Where: -- `string` is the input string whose runes are to be counted. +- `data` is the input data to be hashed. Examples: ```javascript -Counting runes in a string: -RuneCount("Hello World") // Evaluates to 11 +Hashing a simple string: +crypto.SHA512("hello") // Might evaluate to a very long hash string -Counting runes in a string with special characters: -RuneCount("Hello$World") // Evaluates to 11 +Hashing a number represented as a string: +crypto.SHA512("12345") // Might evaluate to another very long hash string -Counting runes in an empty string: -RuneCount("") // Evaluates to 0 +Hashing special characters: +crypto.SHA512("!@#") // Might evaluate to yet another very long hash string ``` --- - - -## Dates +## dates ### timestamp @@ -1266,8 +679,6 @@ Creating another timestamp: timestamp("2023-07-04T12:00:00Z") ``` ---- - ### getDate The `getDate` function in CEL is used to extract the date part from a timestamp. It returns a string representation of the date. @@ -1290,26 +701,20 @@ Getting the date from another timestamp: "2023-07-04T00:00:00Z".getDate() // Evaluates to "2023-07-04" ``` ---- - ### get[DatePart] - - -| Function | Description | Example | -| ------------------------ | ------------------------------------------------------------ | ------- | -| `{date>.getDayOfMonth()` | A integer value representing the day of the month, with the first day being 1. | 1 - 31 | -|` .getDayOfWeek()` | eturns an integer value representing the day of the week, where Sunday is 0 and Saturday is 6. | 0 - 6 | -| `.getDayOfYear()` | an integer value representing the day of the year, with January 1st being day 1. | 1 - 366 | -| `.getDayOfMonth()` | the full year (4 digits for 4-digit years) of the specified timestamp. | | -| `.getHours()` | the full year (4 digits for 4-digit years) of the specified timestamp. | 0- 23 | -| `.getMilliseconds()` | | 0 -999 | -| `.getMinutes()` | | | -| `.getMonth()` | | 0 -11 | -| `.getSeconds()` | 0 - 59 | 0 - 59 | -| `.getHours()` | | | - - +| Function | Description | Example | +| -------------------------- | ---------------------------------------------------------------------------------------------- | ------- | +| `{date>.getDayOfMonth()` | A integer value representing the day of the month, with the first day being 1. | 1 - 31 | +| ` .getDayOfWeek()` | eturns an integer value representing the day of the week, where Sunday is 0 and Saturday is 6. | 0 - 6 | +| `.getDayOfYear()` | an integer value representing the day of the year, with January 1st being day 1. | 1 - 366 | +| `.getDayOfMonth()` | the full year (4 digits for 4-digit years) of the specified timestamp. | | +| `.getHours()` | the full year (4 digits for 4-digit years) of the specified timestamp. | 0- 23 | +| `.getMilliseconds()` | | 0 -999 | +| `.getMinutes()` | | | +| `.getMonth()` | | 0 -11 | +| `.getSeconds()` | 0 - 59 | 0 - 59 | +| `.getHours()` | | | ### duration @@ -1329,25 +734,17 @@ Creating a duration of 30 minutes: duration("30m") // Represents a duration of 30 minutes ``` - Durations can also be crated using arithmetic: -| Field | Description | -| ---------------- | ------------------------------------------------------------ | +| Field | Description | +| ---------------- | ----------------------------------------------------------------------------- | | time.Unix(epoch) | converts a UNIX time (seconds since the UNIX epoch) into a `time.Time` object | -| time.Nanosecond | converts to a time.Duration | -| time.Microsecond | | -| time.Millisecond | | -| time.Second | | -| time.Minute | | -| time.Hour | | - - ---- - - - - +| time.Nanosecond | converts to a time.Duration | +| time.Microsecond | | +| time.Millisecond | | +| time.Second | | +| time.Minute | | +| time.Hour | | ### time.ZoneName @@ -1370,8 +767,6 @@ Yet another example: time.ZoneName() // Might evaluate to "UTC" for Coordinated Universal Time ``` ---- - ### time.ZoneOffset The `time.ZoneOffset` function in CEL returns the offset of the local system's time zone in minutes. It helps in understanding the time difference between the local time zone and UTC. @@ -1393,8 +788,6 @@ Yet another example: time.ZoneOffset() // Could evaluate to 330 for IST (Indian Standard Time) ``` ---- - ### time.Parse The `time.Parse` function in CEL is used to parse a given string into a time object based on a specified layout. It's handy for converting string representations of time into actual time objects. @@ -1421,8 +814,6 @@ Parsing a time with hour and minute information: time.Parse("15:04 02-01-2006", "14:30 26-09-2023") // Includes time of day information ``` ---- - ### time.ParseLocal The `time.ParseLocal` function in CEL parses a given string into a time object according to a specified layout and the local time zone. It's useful for working with local times. @@ -1449,8 +840,6 @@ Parsing with a different time format: time.ParseLocal("15:04 02-01-2006", "14:30 26-09-2023") // Includes time of day information in local time zone ``` ---- - ### time.ParseInLocation The `time.ParseInLocation` function in CEL parses a string into a time object according to a specified layout and time zone. It provides more control over the time zone compared to `time.ParseLocal`. @@ -1478,1840 +867,1991 @@ Parsing with hour and minute for a specific zone: time.ParseInLocation("15:04 02-01-2006", "Asia/Tokyo", "14:30 26-09-2023") // Evaluates to a time object for JST ``` ---- - ### time.Now The `time.Now` function in CEL returns the current time. It's a straightforward way to retrieve the current date and time according to the system's local time zone. Syntax: - time.Now() + time.Now() + +Examples: + +```javascript +Getting the current time: +time.Now() // Evaluates to the current date and time + +Another example of retrieving the current time: +time.Now() // Will always return the current moment's date and time + +Yet another example: +time.Now() // Useful for timestamping or time-stamping events in real-time +``` + +### time.ParseDuration + +The `time.ParseDuration` function in CEL parses a string into a duration. It supports various units like "s" for seconds, "m" for minutes, "h" for hours, etc. + +Syntax: + + time.ParseDuration(duration) + +Where: + +- `duration` is the string representation of the duration. + +Examples: + +```javascript +Parsing a duration string: +time.ParseDuration("1h30m") // Evaluates to a duration of 1 hour and 30 minutes + +Another example with a different format: +time.ParseDuration("15m30s") // Evaluates to a duration of 15 minutes and 30 seconds + +Parsing a negative duration: +time.ParseDuration("-2h45m") // Evaluates to a duration of -2 hours and -45 minutes +``` + +### time.Since + +The `time.Since` function in CEL calculates the duration that has elapsed since a given time. It is commonly used to measure the time difference between a specified time and the current moment. + +Syntax: + + time.Since(pastTime) + +Where: + +- `pastTime` is a `time.Time` object representing a past point in time. + +Examples: + +```javascript +Calculating the time elapsed since a specific past time: +time.Since(time.Parse("2006-01-02", "2023-09-26")) // Evaluates to the duration since September 26, 2023 + +Another example with a different past time: +time.Since(time.Parse("15:04 02-01-2006", "14:30 26-09-2023")) // Evaluates to the duration since 14:30 on September 26, 2023 + +Using the `time.Now` function for a real-time duration: +time.Since(time.Now()) // Always evaluates to a very small duration, as it's the time since "now" +``` + +### time.Until + +The `time.Until` function in CEL calculates the duration remaining until a specified future time. It helps in determining the time left for an event or deadline. + +Syntax: + + time.Until(futureTime) + +Where: + +- `futureTime` is a `time.Time` object representing a future point in time. + +Examples: + +```javascript +Calculating the time remaining until a specific future time: +time.Until(time.Parse("2006-01-02", "2023-10-01")) // Evaluates to the duration until October 1, 2023 + +Another example with a different future time: +time.Until(time.Parse("15:04 02-01-2006", "16:00 30-09-2023")) // Evaluates to the duration until 16:00 on September 30, 2023 + +Using the `time.Now` function for a real-time duration: +time.Until(time.Now()) // Always evaluates to zero, as it's the time until "now" +``` + +--- + +## encode + +### urlencode + +The `urlencode` function encodes the given string into a URL-encoded string. + +Syntax: + + urlencode(string) + +Examples: + +```javascript +urlencode("hello world ?"); // Evaluates to hello+world+%3F +``` + +### urldecode + +The `urldecode` function decodes a URL-encoded string. + +Syntax: + + urldecode(string) + +Examples: + +```javascript +urldecode("hello+world+%3F"); // Evaluates to 'hello world ?' +``` + +--- + +## filepath + +### filepath.Base + +The `filepath.Base` function returns the last element of path. +Trailing path separators are removed before extracting the last element. +If the path is empty, Base returns ".". +If the path consists entirely of separators, Base returns a single separator. + +Syntax: + + filepath.Base(string) + +Examples: + +```javascript +filepath.Base("/home/flanksource/projects/gencel"); // Evaluates to gencel +``` + +### filepath.Clean + +`filepath.Clean` returns the shortest path name equivalent to path by purely lexical processing. +It applies the following rules iteratively until no further processing can be done: + +Syntax: + + filepath.Clean(string) + +Examples: + +```javascript +filepath.Clean("/foo/bar/../baz"); // Evaluates /foo/baz +``` + +### filepath.Dir + +`filepath.Dir` returns all but the last element of path, typically the path's directory. +After dropping the final element, Dir calls Clean on the path and trailing +slashes are removed. +If the path is empty, Dir returns ".". +If the path consists entirely of separators, Dir returns a single separator. +The returned path does not end in a separator unless it is the root directory. + +Syntax: + + filepath.Dir(string) + +Examples: + +```javascript +filepath.Dir("/home/flanksource/projects/gencel"); // Evaluates to /home/flanksource/projects +``` + +### filepath.Ext + +`filepath.Ext` returns the file name extension used by path. +The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot. + +Syntax: + + filepath.Ext(string) + +Examples: + +```javascript +filepath.Ext("/opt/image.jpg"); // Evaluates to .jpg +``` + +### filepath.IsAbs + +The `filepath.IsAbs` function reports whether the path is absolute. + +Syntax: + + filepath.IsAbs(string) + +Examples: + +```javascript +filepath.Base("/home/flanksource/projects/gencel"); // Evaluates to true +filepath.Base("projects/gencel"); // Evaluates to false +``` + +### filepath.Join + +The `filepath.Join` function joins any number of path elements into a single path, +separating them with an OS specific Separator. Empty elements +are ignored. The result is Cleaned. However, if the argument +list is empty or all its elements are empty, Join returns +an empty string. +On Windows, the result will only be a UNC path if the first +non-empty element is a UNC path. + +Syntax: + + filepath.Join([]string) + +Examples: + +```javascript +filepath.Join(["/home/flanksource", "projects", "gencel"]; // Evaluates to /home/flanksource/projects/gencel +``` + +### filepath.Match + +The `filepath.Match` function reports whether name matches the shell file name pattern. + +Syntax: + + filepath.Match(pattern, inputString) Examples: ```javascript -Getting the current time: -time.Now() // Evaluates to the current date and time +filepath.Match("*.txt", "foo.json"); // Evaluates to false +filepath.Match("*.txt", "foo.txt"); // Evaluates to true +``` -Another example of retrieving the current time: -time.Now() // Will always return the current moment's date and time +### filepath.Rel -Yet another example: -time.Now() // Useful for timestamping or time-stamping events in real-time -``` +The `filepath.Rel` function returns a relative path that is lexically equivalent to targpath when +joined to basepath with an intervening separator. That is, +Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. +On success, the returned path will always be relative to basepath, +even if basepath and targpath share no elements. +An error is returned if targpath can't be made relative to basepath or if +knowing the current working directory would be necessary to compute it. +Rel calls Clean on the result. ---- +Syntax: + filepath.Rel(basepath, targetpath) -### time.ParseDuration +Examples: -The `time.ParseDuration` function in CEL parses a string into a duration. It supports various units like "s" for seconds, "m" for minutes, "h" for hours, etc. +```javascript +filepath.Rel("/foo/bar", "/foo/bar/baz"); // Evaluates to baz +``` -Syntax: +### filepath.Split - time.ParseDuration(duration) +The `filepath.Split` function splits path immediately following the final Separator, +separating it into a directory and file name component. +If there is no Separator in path, Split returns an empty dir +and file set to path. +The returned values have the property that path = dir+file. -Where: +Syntax: -- `duration` is the string representation of the duration. + filepath.Split(path) (dir, file) Examples: ```javascript -Parsing a duration string: -time.ParseDuration("1h30m") // Evaluates to a duration of 1 hour and 30 minutes - -Another example with a different format: -time.ParseDuration("15m30s") // Evaluates to a duration of 15 minutes and 30 seconds - -Parsing a negative duration: -time.ParseDuration("-2h45m") // Evaluates to a duration of -2 hours and -45 minutes +filepath.Split("/foo/bar/baz"); // Evaluates to [/foo/bar/ baz] ``` --- -### time.Since +## JSON -The `time.Since` function in CEL calculates the duration that has elapsed since a given time. It is commonly used to measure the time difference between a specified time and the current moment. +### jq + +The `jq` function in CEL applies a jq expression to filter or transform data. Syntax: - time.Since(pastTime) + jq(jqExpr, data) Where: -- `pastTime` is a `time.Time` object representing a past point in time. +- `jqExpr` is the jq expression you're applying. +- `data` is the data you're filtering or transforming. Examples: ```javascript -Calculating the time elapsed since a specific past time: -time.Since(time.Parse("2006-01-02", "2023-09-26")) // Evaluates to the duration since September 26, 2023 +Filtering data with a jq expression: +jq(".name", {"name": "John", "age": 30}) // Evaluates to "John" -Another example with a different past time: -time.Since(time.Parse("15:04 02-01-2006", "14:30 26-09-2023")) // Evaluates to the duration since 14:30 on September 26, 2023 +Transforming data with a jq expression: +jq("{name, age}", {"name": "John", "age": 30, "city": "NY"}) // Evaluates to {"name": "John", "age": 30} -Using the `time.Now` function for a real-time duration: -time.Since(time.Now()) // Always evaluates to a very small duration, as it's the time since "now" +Using a complex jq expression: +jq(".[] | select(.age > 25)", [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]) // Evaluates to [{"name": "John", "age": 30}] ``` ---- - -### time.Until +### JSON -The `time.Until` function in CEL calculates the duration remaining until a specified future time. It helps in determining the time left for an event or deadline. +The `JSON` function in CEL is used to convert a JSON formatted string into a map. It returns a map containing the JSON data. Syntax: - time.Until(futureTime) + JSON(jsonString) Where: -- `futureTime` is a `time.Time` object representing a future point in time. +- `jsonString` is the JSON formatted string. Examples: ```javascript -Calculating the time remaining until a specific future time: -time.Until(time.Parse("2006-01-02", "2023-10-01")) // Evaluates to the duration until October 1, 2023 +Converting a JSON string to a map: +JSON("{\"name\": \"Alice\", \"age\": 30}") // Evaluates to a map with keys "name" and "age" -Another example with a different future time: -time.Until(time.Parse("15:04 02-01-2006", "16:00 30-09-2023")) // Evaluates to the duration until 16:00 on September 30, 2023 +Handling an array in JSON: +JSON("{\"numbers\": [1, 2, 3]}") // Evaluates to a map with a key "numbers" containing an array -Using the `time.Now` function for a real-time duration: -time.Until(time.Now()) // Always evaluates to zero, as it's the time until "now" +Nested JSON string conversion: +JSON("{\"person\": {\"name\": \"Bob\", \"age\": 35}}") // Evaluates to a nested map ``` ---- - - -## Random - -### random.ASCII +### JSONArray -The `random.ASCII` function in CEL generates a random ASCII string of a given length. The characters in the string are within the ASCII printable character range. +The `JSONArray` function converts a JSON formatted string into an array. It is particularly useful for handling JSON arrays. Syntax: - random.ASCII(count) + JSONArray(jsonArrayString) Where: -- `count` is the length of the random ASCII string to be generated. +- `jsonArrayString` is the JSON formatted string representing an array. Examples: ```javascript -Generating a 5-character random ASCII string: -random.ASCII(5) // Might evaluate to "A7!2k" +Converting a JSON array string to an array: +JSONArray('["1", "2"]')[0] // Evaluates to "1" -Creating a 10-character random ASCII string: -random.ASCII(10) // Might evaluate to "3e$7^2Go1" +Handling complex objects in a JSON array: +JSONArray("[{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]") // Evaluates to an array of maps -Producing a 15-character random ASCII string: -random.ASCII(15) // Might evaluate to "7g$!3H8^2Kl0p9" +An empty JSON array string: +JSONArray("[]") // Evaluates to an empty array ``` ---- - -### random.Alpha +### toJSONPretty -The `random.Alpha` function in CEL generates a random alphabetic string containing uppercase and lowercase letters, with a specified length. +The `toJSONPretty` function converts JSON object into a pretty-formatted JSON string with indents. Syntax: - random.Alpha(count) + toJSONPretty(indent, data) Where: -- `count` is the length of the random alphabetic string to be generated. +- `indent` is the string used for indentation. +- `data` is the map or array to be converted. Examples: ```javascript -Generating a 5-character random alphabetic string: -random.Alpha(5) // Might evaluate to "aBcDe" +toJSONPretty('\t', {'name': 'aditya'} +// Evaluates to +{ + "name": "aditya" +} -Creating a 10-character random alphabetic string: -random.Alpha(10) // Might evaluate to "FgHiJkLmNo" +Using tab for indentation: +toJSONPretty("\t", ["Alice", 30]) // Evaluates to a pretty-formatted JSON string with tabs -Producing a 15-character random alphabetic string: -random.Alpha(15) // Might evaluate to "pQrStUvWxYzAbCdEf" +An empty map with four spaces indent: +toJSONPretty(" ", {}) // Evaluates to "{}" with no indents as the map is empty ``` --- -### random.AlphaNum +## kubernetes + +### IsHealthy -The `random.AlphaNum` function in CEL generates a random alphanumeric string containing both letters and digits, with a specified length. +The `IsHealthy` function in CEL is used to determine if a Kubernetes resource is healthy. It returns a boolean value indicating the health status of the resource. Syntax: - random.AlphaNum(count) + IsHealthy(resource) Where: -- `count` is the length of the random alphanumeric string to be generated. +- `resource` is the Kubernetes resource you're checking. Examples: ```javascript -Generating a 5-character random alphanumeric string: -random.AlphaNum(5) // Might evaluate to "a1B2c" +Checking if a pod is healthy: +IsHealthy(pod) // Evaluates to true if the pod is healthy -Creating a 10-character random alphanumeric string: -random.AlphaNum(10) // Might evaluate to "3D4e5F6g7H" +Verifying the health of a service: +IsHealthy(service) // Evaluates to false if the service is not healthy -Producing a 15-character random alphanumeric string: -random.AlphaNum(15) // Might evaluate to "8i9J0k1L2m3N4o5" +Assessing the health of a deployment: +IsHealthy(deployment) // Evaluates to true if the deployment is healthy ``` ---- - -### random.String +### GetStatus -The `random.String` function in CEL generates a random string based on provided character sets or bounds, with a specified length. +The `GetStatus` function in CEL retrieves the status of a Kubernetes resource as a string. It provides detailed information about the current state of the resource. Syntax: - random.String(count, characterSetOrBounds) + GetStatus(resource) Where: -- `count` is the length of the random string to be generated. -- `characterSetOrBounds` can be a character set string or lower and upper bounds for character codes. +- `resource` is the Kubernetes resource whose status you're retrieving. Examples: ```javascript -Generating a 5-character random string from a character set: -random.String(5, "abc123") // Might evaluate to "1a2b3" +Retrieving the status of a pod: +GetStatus(pod) // Evaluates to "Running" if the pod is running -Creating a 10-character random string within character code bounds: -random.String(10, 65, 90) // Might evaluate to random uppercase letters +Getting the status of a service: +GetStatus(service) // Evaluates to "Active" if the service is active -Producing a 15-character random string from a regex character class: -random.String(15, "[[:alnum:]]") // Might evaluate to a mix of letters and digits +Checking the status of a deployment: +GetStatus(deployment) // Evaluates to "Deployed" if the deployment is successful ``` ---- - -### random.Item +### GetHealth -The `random.Item` function in CEL selects a random item from a given list of items. +The `GetHealth` function in CEL retrieves the health status of a Kubernetes resource as a map. The map contains key-value pairs providing detailed information about the resource's health. Syntax: - random.Item(list) + GetHealth(resource) Where: -- `list` is an array or list from which a random item is selected. +- `resource` is the Kubernetes resource whose health information you're retrieving. Examples: ```javascript -Selecting a random item from a list of fruits: -random.Item(["apple", "banana", "cherry"]) // Might evaluate to "banana" +Retrieving the health information of a pod: +GetHealth(pod) // Evaluates to a map with keys and values indicating the pod's health -Choosing a random number from a list: -random.Item([1, 2, 3, 4, 5]) // Might evaluate to 3 +Getting the health information of a service: +GetHealth(service) // Evaluates to a map with keys and values indicating the service's health -Picking a random word from a list: -random.Item(["hello", "world", "foo", "bar"]) // Might evaluate to "foo" +Checking the health information of a deployment: +GetHealth(deployment) // Evaluates to a map with keys and values indicating the deployment's health ``` --- -### random.Number - -The `random.Number` function in CEL generates a random integer within a specified range. +## math -Syntax: +### math.Add - random.Number(min, max) +The `math.Add` function takes a list of number and returns their sum -Where: +Syntax: -- `min` is the minimum value of the range (inclusive). -- `max` is the maximum value of the range (inclusive). + math.Add(list) -Examples: +Example: ```javascript -Generating a random number between 1 and 10: -random.Number(1, 10) // Might evaluate to 7 +math.Add([1, 2, 3, 4, 5]); // Evaluates to 15 +``` -Creating a random number between 50 and 100: -random.Number(50, 100) // Might evaluate to 89 +### math.Sub -Producing a random number between 0 and 1000: -random.Number(0, 1000) // Might evaluate to 456 -``` +The `math.Sub` function takes two numbers and returns their difference ---- +Syntax: -### random.Float + math.Sub(num1, num2) -The `random.Float` function in CEL generates a random floating-point number within a specified range. +Example: -Syntax: +```javascript +math.Sub(5, 4); // Evaluates to 1 +``` - random.Float(min, max) +### math.Mul -Where: +The `math.Mul` function takes a list of numbers and returns their product -- `min` is the minimum value of the range (inclusive). -- `max` is the maximum value of the range (inclusive). +Syntax: -Examples: + math.Mul(list) + +Example: ```javascript -Generating a random float between 0 and 1: -random.Float(0, 1) // Might evaluate to 0.572 +math.Mul([1, 2, 3, 4, 5]); // Evaluates to 120 +``` -Creating a random float between 5 and 10: -random.Float(5, 10) // Might evaluate to 7.283 +### math.Div -Producing a random float between -1 and 1: -random.Float(-1, 1) // Might evaluate to -0.456 -``` +The `math.Div` function takes two numbers and returns their quotient ---- +Syntax: -## base64 + math.Div(num1, num2) -### base64.Encode +Example: -The `base64.Encode` function in CEL is used to encode input data into a Base64 string. The function can accept various types of input, including strings, byte slices, and types that can be converted to a byte slice. +```javascript +math.Div(4, 2); // Evaluates to 2 +``` -Syntax: +### math.Rem - base64.Encode(data) +The `math.Rem` function takes two numbers and returns their remainder -Where: +Syntax: -- `data` is the input you're encoding. It can be a string, byte slice, or any type that can be converted to a byte slice. + math.Rem(num1, num2) -Examples: +Example: ```javascript -Encoding a simple string: -base64.Encode("hello") // Expected Output: "aGVsbG8=" +math.Rem(4, 3); // Evaluates to 1 +``` -Encoding a number (which will first be converted to a string): -base64.Encode(12345) // Expected Output: "MTIzNDU=" +### math.Pow -Encoding a byte slice representation of a string: -base64.Encode([104, 101, 108, 108, 111]) // Expected Output: "aGVsbG8=" -``` +The `math.Pow` function takes two numbers and returns their power ---- +Syntax: + math.Pow(num1, num2) +Example: + +```javascript +math.Pow(4, 2); // Evaluates to 16 +``` -### base64.Decode +### math.Seq -The `base64.Decode` function in CEL is used to decode a Base64 encoded string back to its original form. The function returns the decoded string. +The `math.Seq` function generates a sequence of numbers from the start value to the end value, incrementing by the step value. Syntax: - base64.Decode(encodedData) + math.Seq([start, end, ?step]) Where: -- `encodedData` is the Base64 encoded string you're decoding. +- `start` is the starting value of the sequence. +- `end` is the ending value of the sequence. +- `step` is the increment value of the sequence. (optional. Defaults to 1) Examples: ```javascript -Decoding a Base64 encoded string: -base64.Decode("aGVsbG8=") // Expected Output: "hello" - -Decoding another example: -base64.Decode("MTIzNDU=") // Expected Output: "12345" - -Decoding an encoded special character: -base64.Decode("4pyT") // Expected Output: "✓" +math.Seq([1, 5]); // Evaluates to [1, 2, 3, 4, 5] +math.Seq([1, 6, 2]); // Evaluates to [1, 3, 5] ``` ---- - -Where: +## random -- `value` is the value you're appending. -- `list` is the list you're appending to. +### random.ASCII -Examples: +The `random.ASCII` function generates random ASCII strings of a specified length. - Appending to a list: - Append(3, [1, 2]) // Evaluates to [1, 2, 3] +Syntax: - Appending a string to a list: - Append("c", ["a", "b"]) // Evaluates to ["a", "b", "c"] + random.ASCII(count) - Appending to an empty list: - Append(1, []) // Evaluates to [1] +Examples: ---- +```javascript +random.ASCII(5); +``` -### Prepend +### random.Alpha -The `Prepend` function in CEL adds a value to the beginning of a list. +The `random.Alpha` function generates random alphabetic strings of a specified length. Syntax: - Prepend(value, list) - -Where: + random.Alpha(count) -- `value` is the value you're prepending. -- `list` is the list you're adding to. +```javascript +random.Alpha(5); +``` -Examples: +### random.AlphaNum - Prepending to a list: - Prepend(0, [1, 2, 3]) // Evaluates to [0, 1, 2, 3] +The `random.AlphaNum` function generates random alphanumeric strings of a specified length. - Prepending a string to a list: - Prepend("a", ["b", "c"]) // Evaluates to ["a", "b", "c"] +Syntax: - Prepending to an empty list: - Prepend(1, []) // Evaluates to [1] + random.AlphaNum(count) ---- +```javascript +random.AlphaNum(5); +``` -### Uniq +### random.String -The `Uniq` function in CEL removes duplicate values from a list. +The `random.String` function generates random strings of a specified length and character set. Syntax: - Uniq(list) + random.String(count, [min, max]) Where: - -- `list` is the list you're removing duplicates from. +characters is a list specifying the characters to be used in the string. +Optionally, the list can also be left empty to use the default character set. Examples: - Removing duplicates from a list: - Uniq([1, 2, 2, 3, 3, 3]) // Evaluates to [1, 2, 3] +```javascript +random.String(5, ["a", "d"]); +random.String(5, []); +``` - Removing duplicates from a string list: - Uniq(["a", "b", "a", "c", "b"]) // Evaluates to ["a", "b", "c"] +### random.Item - Using a list without duplicates: - Uniq([1, 2, 3]) // Evaluates to [1, 2, 3] +The `random.Item` function generates a random item from a list. ---- +Syntax: -### Reverse + random.Item(list) -The `Reverse` function in CEL reverses the order of elements in a list. +Example: -Syntax: +```javascript +random.Item(["a", "b", "c"]); +``` - Reverse(list) +### random.Number -Where: +The `random.Number` function generates a random integer within a specified range. -- `list` is the list you're reversing. +Syntax: -Examples: + random.Number(min, max) - Reversing a list: - Reverse([1, 2, 3]) // Evaluates to [3, 2, 1] +Where: - Reversing a string list: - Reverse(["a", "b", "c"]) // Evaluates to ["c", "b", "a"] +- `min` is the minimum value of the range (inclusive). +- `max` is the maximum value of the range (inclusive). - Reversing an empty list: - Reverse([]) // Evaluates to [] +Examples: ---- +```javascript +random.Number(1, 10); +``` -### Sort +### random.Float -The `Sort` function in CEL sorts a list. If provided with a key, it sorts based on that key. +The `random.Float` function generates a random float within a specified range. Syntax: - Sort(list) - Sort(key, list) + random.Float(min, max) Where: -- `key` is the key to sort by (optional). -- `list` is the list you're sorting. +- `min` is the minimum value of the range (inclusive). +- `max` is the maximum value of the range (inclusive). Examples: - Sorting a list of numbers: - Sort([3, 1, 2]) // Evaluates to [1, 2, 3] - - Sorting a list of strings: - Sort(["banana", "apple", "cherry"]) // Evaluates to ["apple", "banana", "cherry"] - - Sorting a list of dictionaries by a key: - Sort("age", [{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]) // Evaluates to [{"name": "Jane", "age": 25}, {"name": "John", "age": 30}] +```javascript +random.Float(1, 10); +``` --- +## regexp +### regexp.Find -### Flatten - -The `Flatten` function in CEL flattens a nested list structure. +The `regexp.Find` function in CEL is used to find the first occurrence of a pattern within a string. It returns the matched substring or an error if the pattern is invalid. Syntax: - Flatten(list) - Flatten(depth, list) + regexp.Find(pattern, input) Where: -- `depth` is the depth to which the list should be flattened (optional). -- `list` is the list you're flattening. +- `pattern` is the regular expression pattern you're looking for. +- `input` is the string you're searching within. Examples: - Flattening a nested list: - Flatten([1, [2, 3], [4, [5, 6]]]) // Evaluates to [1, 2, 3, 4, 5, 6] + Finding a pattern within a string: + regexp.Find("llo", "hello") // Evaluates to "llo" - Flattening to a specific depth: - Flatten(1, [1, [2, 3], [4, [5, 6]]]) // Evaluates to [1, 2, 3, 4, [5, 6]] + Searching for digits within a string: + regexp.Find("\\d+", "abc123def") // Evaluates to "123" - Flattening an already flat list: - Flatten([1, 2, 3]) // Evaluates to [1, 2, 3] + Pattern not found in the string: + regexp.Find("xyz", "hello") // Evaluates to "" --- -### Pick +### regexp.FindAll -The `Pick` function in CEL creates a new dictionary by picking specific keys from the provided dictionary. +The `regexp.FindAll` function in CEL retrieves all occurrences of a pattern within a string, up to a specified count. It returns a list of matched substrings or an error if the pattern is invalid. Syntax: - Pick(key1, key2, ..., dict) + regexp.FindAll(pattern, count, input) Where: -- `keyN` is the Nth key you're picking. -- `dict` is the dictionary you're picking from. +- `pattern` is the regular expression pattern to find. +- `count` is the maximum number of occurrences to return. +- `input` is the string to search within. Examples: - Picking specific keys from a dictionary: - Pick("apple", "cherry", {"apple": 1, "banana": 2, "cherry": 3}) // Evaluates to {"apple": 1, "cherry": 3} + Finding all occurrences of a pattern: + regexp.FindAll("a.", -1, "banana") // Evaluates to ["ba", "na", "na"] - Picking a non-existent key: - Pick("apple", "orange", {"apple": 1, "banana": 2}) // Evaluates to {"apple": 1} + Limiting the number of matches: + regexp.FindAll("\\d", 2, "12345") // Evaluates to ["1", "2"] - Picking from an empty dictionary: - Pick("apple", {}) // Evaluates to {} + Pattern not found: + regexp.FindAll("z", -1, "hello") // Evaluates to [] --- -### Omit +### regexp.Match -The `Omit` function in CEL creates a new dictionary by omitting specific keys from the provided dictionary. +The `regexp.Match` function in CEL checks if a string matches a given regular expression pattern. It returns a boolean value indicating the match status. Syntax: - Omit(key1, key2, ..., dict) + regexp.Match(pattern, input) Where: -- `keyN` is the Nth key you're omitting. -- `dict` is the dictionary you're omitting from. +- `pattern` is the regular expression pattern to match. +- `input` is the string to check. Examples: - Omitting specific keys from a dictionary: - Omit("banana", {"apple": 1, "banana": 2, "cherry": 3}) // Evaluates to {"apple": 1, "cherry": 3} + Checking if a string matches a pattern: + regexp.Match("^h.llo", "hello") // Evaluates to true - Omitting a non-existent key: - Omit("orange", {"apple": 1, "banana": 2}) // Evaluates to {"apple": 1, "banana": 2} + Pattern does not match the string: + regexp.Match("^b", "apple") // Evaluates to false - Omitting from an empty dictionary: - Omit("apple", {}) // Evaluates to {} + Matching digits in a string: + regexp.Match("\\d+", "abc123") // Evaluates to true --- -### conv.Has +### regexp.QuoteMeta -The `conv.Has` function in CEL checks if a given key exists in the provided input, which can be a map or other collection. +The `regexp.QuoteMeta` function in CEL quotes all regular expression metacharacters inside a string. It returns the quoted string. Syntax: - conv.Has(collection, key) + regexp.QuoteMeta(input) Where: -- `collection` is the map or collection you're checking. -- `key` is the key or item you're looking for. +- `input` is the string containing metacharacters to be quoted. Examples: - Checking for a key in a map: - conv.Has({"apple": 1, "banana": 2}, "apple") // Evaluates to true + Quoting metacharacters in a string: + regexp.QuoteMeta("a.b") // Evaluates to "a\\.b" + + String without metacharacters: + regexp.QuoteMeta("abc") // Evaluates to "abc" - Checking for a missing key: - conv.Has({"apple": 1, "banana": 2}, "cherry") // Evaluates to false + Quoting a complex pattern: + regexp.QuoteMeta("[a-z].*") // Evaluates to "\\[a\\-z\\]\\.\\*" --- -### conv.URL +### regexp.Replace -The `conv.URL` function in CEL is used to parse a string into a URL. It returns a URL object and an error if the parsing fails. +The `regexp.Replace` function in CEL replaces occurrences of a pattern within a string with a specified replacement string. It returns the modified string. Syntax: - conv.URL(input) + regexp.Replace(pattern, replacement, input) Where: -- `input` is the string representation of the URL. +- `pattern` is the regular expression pattern to replace. +- `replacement` is the string to replace the pattern with. +- `input` is the original string. Examples: - Parsing a valid URL: - conv.URL("https://www.example.com") // Evaluates to a URL object + Replacing a pattern in a string: + regexp.Replace("a.", "x", "banana") // Evaluates to "bxnxna" - Parsing an invalid URL: - conv.URL("invalid-url") // Evaluates to an error + Pattern not found: + regexp.Replace("z", "x", "apple") // Evaluates to "apple" - Parsing a URL with query parameters: - conv.URL("https://www.example.com?page=1&sort=asc") // Evaluates to a URL object with query parameters + Replacing digits: + regexp.Replace("\\d+", "num", "abc123") // Evaluates to "abcnum" ---- --> +--- -### conv.Default +### regexp.ReplaceLiteral -The `conv.Default` function in CEL is used to return the input value if it is true; otherwise, it returns the default value. +The `regexp.ReplaceLiteral` function in CEL replaces occurrences of a pattern within a string with a specified replacement string, without interpreting the pattern as a regular expression. It returns the modified string or an error if the pattern is invalid. Syntax: - conv.Default(default, input) + regexp.ReplaceLiteral(pattern, replacement, input) + +Where: + +- `pattern` is the substring to replace. +- `replacement` is the string to replace the pattern with. +- `input` is the original string. Examples: - Using a truthy input value: - conv.Default("default", "input") // Evaluates to "input" + Replacing a substring: + regexp.ReplaceLiteral("apple", "orange", "apple pie") // Evaluates to "orange pie" - Using a falsy input value: - conv.Default("default", "") // Evaluates to "default" + Substring not found: + regexp.ReplaceLiteral("z", "x", "apple") // Evaluates to "apple" - Using a non-string input value: - conv.Default("default", 123) // Evaluates to 123 + Replacing a pattern without regex interpretation: + regexp.ReplaceLiteral("a.", "x", "a.b c.d") // Evaluates to "x.b c.d" --- -### conv.Dict +### regexp.Split -The `conv.Dict` function in CEL is used to create a dictionary or map from the provided key-value pairs. +The `regexp.Split` function in CEL splits a string into a slice of substrings separated by a pattern. It returns the slice of strings or an error if the pattern is invalid. Syntax: - conv.Dict(key1, value1, key2, value2, ...) + regexp.Split(pattern, count, input) + +Where: + +- `pattern` is the regular expression pattern that separates the substrings. +- `count` is the maximum number of splits. Use -1 for no limit. +- `input` is the string to split. Examples: -``` - //Creating a dictionary with string keys and values: - conv.Dict("apple", "fruit", "carrot", "vegetable") // Evaluates to {"apple": "fruit", "carrot": "vegetable"} - //Creating a mixed dictionary: - conv.Dict("name", "Alice", "age", 30) // Evaluates to {"name": "Alice", "age": 30} + Splitting a string by a pattern: + regexp.Split("a.", -1, "banana") // Evaluates to ["", "n", "n"] - //Creating a dictionary with nested values: - conv.Dict("user", conv.Dict("name", "Alice", "age", 30), "active", true) // Evaluates to {"user": {"name": "Alice", "age": 30}, "active": true} -``` -## crypto + Limiting the number of splits: + regexp.Split("\\s", 2, "apple pie is delicious") // Evaluates to ["apple", "pie is delicious"] + + Pattern not found: + regexp.Split("z", -1, "hello") // Evaluates to ["hello"] -### SHA1 +--- -The `crypto.SHA1` function in CEL is used to compute the SHA-1 hash of the input data. Note that SHA-1 is considered insecure for cryptographic purposes. +## strings + +### .camelCase + +The `camelCase` method in CEL converts a given string into camelCase format. Syntax: - crypto.SHA1(data) + 'string'.camelCase() Where: -- `data` is the input data to be hashed. +- `string` is the input string to be converted. Examples: ```javascript -Hashing a simple string: -crypto.SHA1("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c" +Converting a string to camelCase: +"hello world".camelCase() // Evaluates to "HelloWorld" -Hashing a number represented as a string: -crypto.SHA1("12345") // Might evaluate to "8cb2237d0679ca88db6464eac60da96345513964" +Converting a snake_case string: +"hello_world".camelCase() // Evaluates to "HelloWorld" -Hashing special characters: -crypto.SHA1("!@#") // Might evaluate to "8f9b6cb1cf7d70f23c16c9b9d4894d7f3b8fe15d" +Converting a string with spaces and special characters: +"hello beautiful world!".camelCase() // Evaluates to "HelloBeautifulWorld" ``` ---- - -### SHA256 - -The `crypto.SHA256` function in CEL calculates the SHA-256 hash of the provided input data, offering a balance between security and performance. - -Syntax: - crypto.SHA256(data) +### .charAt -Where: +Returns the character at the given position. If the position is negative, or +greater than the length of the string, the function will produce an error: -- `data` is the input data to be hashed. +``` + .charAt() -> +``` Examples: ```javascript -Hashing a simple string: -crypto.SHA256("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" - -Hashing a number represented as a string: -crypto.SHA256("12345") // Might evaluate to "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2" - -Hashing special characters: -crypto.SHA256("!@#") // Might evaluate to "d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8" +"hello".charAt(4); // return 'o' +"hello".charAt(5); // return '' +"hello".charAt(-1); // error ``` ---- -### SHA384 +### .contains -The `crypto.SHA384` function in CEL is used for computing the SHA-384 hash of the input data, which is a truncated version of SHA-512 and provides enhanced security. +The `contains` function in CEL is used to check if a string contains a given substring. Syntax: - crypto.SHA384(data) - -Where: - -- `data` is the input data to be hashed. + string.contains(substring) Examples: ```javascript -Hashing a simple string: -crypto.SHA384("hello") // Might evaluate to a long hash string - -Hashing a number represented as a string: -crypto.SHA384("12345") // Might evaluate to another long hash string - -Hashing special characters: -crypto.SHA384("!@#") // Might evaluate to yet another long hash string +//Checking if a string contains a certain substring: +"apple".contains("app"); // Evaluates to true ``` ---- -### SHA512 +### .endsWith -The `crypto.SHA512` function in CEL calculates the SHA-512 hash of the given input data. It's commonly used for data integrity verification and password storage. +The `endsWith` function in CEL is used to determine if a string ends with a specified substring. Syntax: - crypto.SHA512(data) - -Where: - -- `data` is the input data to be hashed. + string.endsWith(substring) Examples: ```javascript -Hashing a simple string: -crypto.SHA512("hello") // Might evaluate to a very long hash string +// Checking if a string ends with a certain substring: +"hello".endsWith("lo"); // Evaluates to true +``` -Hashing a number represented as a string: -crypto.SHA512("12345") // Might evaluate to another very long hash string +### .indexOf + +Returns the integer index of the first occurrence of the search string. If the +search string is not found the function returns -1. + +The function also accepts an optional position from which to begin the +substring search. If the substring is the empty string, the index where the +search starts is returned (zero or custom). -Hashing special characters: -crypto.SHA512("!@#") // Might evaluate to yet another very long hash string ``` ---- - - ---- - +When the replacement limit is 0, the result is the original string. When the +limit is a negative number, the function behaves the same as replace all. - ---- +Returns a new string whose characters are the same as the target string, only formatted in +reverse order. +This function relies on converting strings to rune arrays in order to reverse. +It can be located in Version 3 of strings. + +``` + .reverse() -> +``` + +Examples: - ---- +// Converting a multi-word string: +"Hello Beautiful World".slug(); // Evaluates to "hello-beautiful-world" +``` - - - - -### data.ToTOML -The `data.ToTOML` function converts a map or an array into a TOML formatted string. +### .split -Syntax: - - data.ToTOML(data) +Returns a list of strings split from the input by the given separator. The +function accepts an optional argument specifying a limit on the number of +substrings produced by the split. -Where: +When the split limit is 0, the result is an empty list. When the limit is 1, +the result is the target string to split. When the limit is a negative +number, the function behaves the same as split all. -- `data` is the map or array to be converted. +``` + .split() -> > + .split(, ) -> > +``` Examples: ```javascript -Converting a map to a TOML string: -data.ToTOML({"name": "Alice", "age": 30}) // Evaluates to "name = \"Alice\"\nage = 30" - -Handling an array (TOML arrays must be of the same type): -data.ToTOML({"people": ["Alice", "Bob"]}) // Evaluates to "people = [\"Alice\", \"Bob\"]" - -An empty map: -data.ToTOML({}) // Evaluates to an empty string +"hello hello hello".split(" "); // returns ['hello', 'hello', 'hello'] +"hello hello hello".split(" ", 0); // returns [] +"hello hello hello".split(" ", 1); // returns ['hello hello hello'] +"hello hello hello".split(" ", 2); // returns ['hello', 'hello hello'] +"hello hello hello".split(" ", -1); // returns ['hello', 'hello', 'hello'] ``` ---- +### .squote -## Kubernetes - -### IsHealthy - -The `IsHealthy` function in CEL is used to determine if a Kubernetes resource is healthy. It returns a boolean value indicating the health status of the resource. +The `squote` method in CEL adds single quotes around a given string. Syntax: - IsHealthy(resource) - -Where: - -- `resource` is the Kubernetes resource you're checking. + 'string'.squote() Examples: ```javascript -Checking if a pod is healthy: -IsHealthy(pod) // Evaluates to true if the pod is healthy +Single quoting a simple string: +"Hello World".squote() // Evaluates to "'Hello World'" -Verifying the health of a service: -IsHealthy(service) // Evaluates to false if the service is not healthy +Single quoting a string with a number: +"12345".squote() // Evaluates to "'12345'" -Assessing the health of a deployment: -IsHealthy(deployment) // Evaluates to true if the deployment is healthy +Single quoting an already single quoted string: +"'Hello World'".squote() // Evaluates to "'''Hello World'''" ``` ---- -### GetStatus +### .startsWith -The `GetStatus` function in CEL retrieves the status of a Kubernetes resource as a string. It provides detailed information about the current state of the resource. +The `startsWith` function in CEL is used to determine if a string starts with a specified substring. Syntax: - GetStatus(resource) - -Where: - -- `resource` is the Kubernetes resource whose status you're retrieving. + string.startsWith(substring) Examples: ```javascript -Retrieving the status of a pod: -GetStatus(pod) // Evaluates to "Running" if the pod is running - -Getting the status of a service: -GetStatus(service) // Evaluates to "Active" if the service is active - -Checking the status of a deployment: -GetStatus(deployment) // Evaluates to "Deployed" if the deployment is successful +// Checking if a string starts with a certain substring: +"hello".startsWith("he"); // Evaluates to true ``` ---- - -### GetHealth - -The `GetHealth` function in CEL retrieves the health status of a Kubernetes resource as a map. The map contains key-value pairs providing detailed information about the resource's health. - -Syntax: +### .substring - GetHealth(resource) +Returns the substring given a numeric range corresponding to character +positions. Optionally may omit the trailing range for a substring from a given +character position until the end of a string. -Where: +Character offsets are 0-based with an inclusive start range and exclusive end +range. It is an error to specify an end range that is lower than the start +range, or for either the start or end index to be negative or exceed the string +length. -- `resource` is the Kubernetes resource whose health information you're retrieving. +``` + .substring() -> + .substring(, ) -> +``` Examples: ```javascript -Retrieving the health information of a pod: -GetHealth(pod) // Evaluates to a map with keys and values indicating the pod's health +"tacocat".substring(4); // returns 'cat' +"tacocat".substring(0, 4); // returns 'taco' +"tacocat".substring(-1); // error +"tacocat".substring(2, 1); // error +``` -Getting the health information of a service: -GetHealth(service) // Evaluates to a map with keys and values indicating the service's health +### .title -Checking the health information of a deployment: -GetHealth(deployment) // Evaluates to a map with keys and values indicating the deployment's health -``` ---- +The `title` method in CEL converts the first character of each word in a string to uppercase. -## Math +Syntax: + 'string'.title() -### Greatest +Where: -Returns the greatest valued number present in the arguments to the macro. +- `string` is the string to convert. -Greatest is a variable argument count macro which must take at least one -argument. Simple numeric and list literals are supported as valid argument -types; however, other literals will be flagged as errors during macro -expansion. If the argument expression does not resolve to a numeric or -list(numeric) type during type-checking, or during runtime then an error -will be produced. If a list argument is empty, this too will produce an -error. -``` - math.greatest(, ...) -> -``` Examples: ```javascript -math.greatest(1) // 1 -math.greatest(1u, 2u) // 2u -math.greatest(-42.0, -21.5, -100.0) // -21.5 -math.greatest([-42.0, -21.5, -100.0]) // -21.5 -math.greatest(numbers) // numbers must be list(numeric) +// Converting a string: +"hello world".title(); // Evaluates to "Hello World" -math.greatest() // parse error -math.greatest('string') // parse error -math.greatest(a, b) // check-time error if a or b is non-numeric -math.greatest(dyn('string')) // runtime error +// Working with mixed case: +"mIxEd CaSe".title(); // Evaluates to "MIxED CASe" ``` ---- -### least +### .trim -Returns the least valued number present in the arguments to the macro. +Returns a new string which removes the leading and trailing whitespace in the +target string. The trim function uses the Unicode definition of whitespace +which does not include the zero-width spaces. See: +https://en.wikipedia.org/wiki/Whitespace_character#Unicode -Least is a variable argument count macro which must take at least one -argument. Simple numeric and list literals are supported as valid argument -types; however, other literals will be flagged as errors during macro -expansion. If the argument expression does not resolve to a numeric or -list(numeric) type during type-checking, or during runtime then an error -will be produced. If a list argument is empty, this too will produce an error. ``` - math.least(, ...) -> + .trim() -> ``` -Examples: - math.least(1) // 1 - math.least(1u, 2u) // 1u - math.least(-42.0, -21.5, -100.0) // -100.0 - math.least([-42.0, -21.5, -100.0]) // -100.0 - math.least(numbers) // numbers must be list(numeric) +Examples: - math.least() // parse error - math.least('string') // parse error - math.least(a, b) // check-time error if a or b is non-numeric - math.least(dyn('string')) // runtime error ---- + ' \ttrim\n '.trim() // returns 'trim' -### math.IsInt +### .trimPrefix -The `math.IsInt` function in CEL checks if the given input is an integer. It returns a boolean value indicating whether the input is an integer or not. +The `trimPrefix` method in CEL removes a given prefix from a string if the string starts with that prefix. Syntax: - math.IsInt(value) + 'string'.trimPrefix(prefix) Where: -- `value` is the input value you're checking. +- `prefix` is the starting substring to remove. +- `string` is the string from which the prefix will be removed. Examples: ```javascript -Checking if a number is an integer: -math.IsInt(5) // Evaluates to true +// Removing a prefix from a string: +"Mr. Smith".trimPrefix("Mr."); // Evaluates to "Smith" -Checking a float value: -math.IsInt(5.5) // Evaluates to false +// Another example: +"Astronaut".trimPrefix("Astro"); // Evaluates to "naut" -Checking a string that represents an integer: -math.IsInt("5") // Evaluates to true +// If the prefix is not present: +"Mr. Smith".trimPrefix("Dr."); // Evaluates to "Mr. Smith" ``` + --- -### math.IsFloat +### .trimSuffix -The `math.IsFloat` function determines if the provided value is a floating-point number. It returns a boolean indicating the result. +The `trimSuffix` method in CEL removes a given suffix from a string if the string ends with that suffix. Syntax: - math.IsFloat(value) + trimSuffix(suffix, string) Where: -- `value` is the input being evaluated. +- `suffix` is the ending substring to remove. +- `string` is the string from which the suffix will be removed. Examples: ```javascript -Evaluating a floating-point number: -math.IsFloat(3.14) // Evaluates to true - -Evaluating an integer: -math.IsFloat(7) // Evaluates to false +// Removing a suffix from a string: +"image.jpg".trimSuffix(".jpg"); // Evaluates to "image" -Evaluating a string representing a float: -math.IsFloat("3.14") // Evaluates to true +// If the suffix is not present: +"image.jpg".trimSuffix(".png"); // Evaluates to "image.jpg" ``` ---- -### math.IsNum +### .upperAscii -The `math.IsNum` function checks if the provided value is a number (either integer or float). It returns a boolean value. - -Syntax: - - math.IsNum(value) +Returns a new string where all ASCII characters are upper-cased. -Where: +This function does not perform Unicode case-mapping for characters outside the +ASCII range. -- `value` is the input to check. +``` + .upperAscii() -> +``` Examples: ```javascript -Checking an integer: -math.IsNum(42) // Evaluates to true - -Checking a float: -math.IsNum(3.14) // Evaluates to true - -Checking a non-number string: -math.IsNum("hello") // Evaluates to false +"TacoCat".upperAscii(); // returns 'TACOCAT' +"TacoCÆt Xii".upperAscii(); // returns 'TACOCÆT XII' ``` ---- -### math.Abs +### Abbrev -The `math.Abs` function returns the absolute value of the given number. It supports both integers and floats. +The `Abbrev` abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "...s the time for..." +This function works like `Abbreviate(string, int)`, but allows you to specify a "left edge" offset. Note that this left edge is not +necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear +somewhere in the result. +In no case will it return a string of length greater than maxWidth. +``` Syntax: - - math.Abs(number) + Abbrev([maxWidth, string]) + Abbrev([offset, maxWidth, string]) Where: -- `number` is the input value. + - str - the string to check + - offset - left edge of source string + - maxWidth - maximum length of result string, must be at least 4 +``` Examples: ```javascript -Getting the absolute value of a negative integer: -math.Abs(-5) // Evaluates to 5 - -Getting the absolute value of a float: -math.Abs(-3.14) // Evaluates to 3.14 - -Using a positive integer: -math.Abs(7) // Evaluates to 7 +Abbrev([5, 20, "Now is the time for all good men"]); // "...s the time for..." +Abbrev([1, 5, "KubernetesPod"]); // "Ku..." +Abbrev([6, "KubernetesPod"]); // "Kub..." ``` ---- -### math.Pow +### HumanDuration -The `math.Pow` function calculates the power of the first number raised to the second number. It supports both integers and floats. +The `HumanDuration` function in CEL converts a duration into a human-readable format. Syntax: - math.Pow(base, exponent) + HumanDuration(duration) Where: -- `base` is the base number. -- `exponent` is the exponent to which the base is raised. +- `duration` is the duration you want to convert. Examples: ```javascript -Calculating the power of integers: -math.Pow(2, 3) // Evaluates to 8 +// Converting a duration into a human-readable format: +HumanDuration(3600); // Evaluates to "1 hour" -Calculating the power of floats: -math.Pow(2.5, 3.5) // Evaluates to approximately 24.705 +// Converting another duration: +HumanDuration(600); // Evaluates to "10 minutes" -Using a negative exponent: -math.Pow(2, -3) // Evaluates to 0.125 +// Converting a longer duration: +HumanDuration(86400); // Evaluates to "1 day" ``` ---- -### math.Seq +### HumanSize -The `math.Seq` function generates a sequence of integers from the start value to the end value, incrementing by the step value. +The `HumanSize` function in CEL converts a size in bytes into a human-readable format. Syntax: - math.Seq(start, end, step) + HumanSize(size) Where: -- `start` is the starting value of the sequence. -- `end` is the ending value of the sequence. -- `step` is the increment step. +- `size` is the size in bytes you want to convert. Examples: ```javascript -Generating a sequence from 1 to 5: -math.Seq(1, 5, 1) // Evaluates to [1, 2, 3, 4, 5] +// Converting a size into a human-readable format: +HumanSize(1024); // Evaluates to "1 KiB" -Generating a sequence with a step of 2: -math.Seq(1, 5, 2) // Evaluates to [1, 3, 5] +// Converting another size: +HumanSize(1048576); // Evaluates to "1 MiB" -Generating a descending sequence: -math.Seq(5, 1, -1) // Evaluates to [5, 4, 3, 2, 1] +// Converting a larger size: +HumanSize(1073741824); // Evaluates to "1 GiB" ``` ---- -### max +### Indent -The `math.Max` function returns the maximum value among the provided numbers. It supports both integers and floats. +The `Indent` function in CEL indents each line of a string by a specified number of spaces or a specified prefix. Syntax: - math.Max(a, b, ...) + Indent(width or prefix, string) Where: -- `a` is the first number. -- `b` is the second number. -- `...` represents additional numbers. +- `width or prefix` is the number of spaces or the prefix string to add before each line. +- `string` is the string to indent. Examples: - Finding the maximum of integers: - math.Max(1, 2, 3) // Evaluates to 3 +```javascript +// Indenting with spaces: +Indent(4, "Line1\nLine2"); // Evaluates to " Line1\n Line2" - Finding the maximum of floats: - math.Max(1.2, 2.3, 3.1) // Evaluates to 3.1 +//Indenting with a prefix: +Indent("> ", "Line1\nLine2"); // Evaluates to "> Line1\n> Line2" - Finding the maximum in a mixed list: - math.Max(1, 2.5, 3) // Evaluates to 3 ---- +// Indenting with a mixed prefix: +Indent("==", "Line1\nLine2"); // Evaluates to "==Line1\n==Line2" +``` -### min +### Semver -The `math.Min` function returns the minimum value among the provided numbers. It supports both integers and floats. +The `Semver` function in CEL parses a version string and returns a map containing the major, minor, patch, prerelease, metadata, and original version. Syntax: - math.Min(a, b, ...) + Semver(version) Where: -- `a` is the first number. -- `b` is the second number. -- `...` represents additional numbers. +- `version` is the version string to parse. Examples: ```javascript -Finding the minimum of integers: -math.Min(1, 2, 3) // Evaluates to 1 +// Parsing a semantic version: +Semver("1.2.3-alpha+meta"); // Evaluates to a map with major: "1", minor: "2", patch: "3", prerelease: "alpha", metadata: "meta", original: "1.2.3-alpha+meta" -Finding the minimum of floats: -math.Min(1.2, 2.3, 0.1) // Evaluates to 0.1 +Semver("2.3.4-beta+meta2"); // Evaluates to a map with major: "2", minor: "3", patch: "4", prerelease: "beta", metadata: "meta2", original: "2.3.4-beta+meta2" -Finding the minimum in a mixed list: -math.Min(1, 2.5, 0) // Evaluates to 0 +// Parsing a simple semantic version: +Semver("3.4.5"); // Evaluates to a map with major: "3", minor: "4", patch: "5", prerelease: "", metadata: "", original: "3.4.5" ``` ---- -### math.Ceil +### SemverCompare -The `math.Ceil` function returns the smallest integer greater than or equal to the provided float. +The `SemverCompare` function in CEL compares two semantic version strings. Syntax: - math.Ceil(value) + SemverCompare(version1, version2) Where: -- `value` is the floating-point number. +- `version1` is the first version string to compare. +- `version2` is the second version string to compare. Examples: ```javascript -Rounding up a positive float: -math.Ceil(2.3) // Evaluates to 3 +// Comparing two semantic versions: +SemverCompare("1.2.3", "1.2.4"); // Evaluates to false -Rounding up a negative float: -math.Ceil(-2.3) // Evaluates to -2 +// Comparing two identical versions: +SemverCompare("2.3.4", "2.3.4"); // Evaluates to true -Using an integer: -math.Ceil(5) // Evaluates to 5 +// Comparing with a prerelease version: +SemverCompare("3.4.5", "3.4.5-alpha"); // Evaluates to false ``` ---- -### math.Floor +### Sort -The `math.Floor` function returns the largest integer less than or equal to the provided float. +The `Sort` function in CEL sorts a list of strings. Syntax: - math.Floor(value) + Sort(list) Where: -- `value` is the floating-point number. +- `list` is the list of strings to sort. Examples: - Rounding down a positive float: - math.Floor(2.7) // Evaluates to 2 +```javascript +Sorting a list of strings: +Sort(["banana", "apple", "cherry"]) // Evaluates to ["apple", "banana", "cherry"] - Rounding down a negative float: - math.Floor(-2.7) // Evaluates to -3 +Sorting another list: +Sort(["dog", "cat", "bird"]) // Evaluates to ["bird", "cat", "dog"] - Using an integer: - math.Floor(5) // Evaluates to 5 ---- +Sorting a list with numbers: +Sort(["3", "1", "2"]) // Evaluates to ["1", "2", "3"] +``` -### math.Round +### WordWrap -The `math.Round` function rounds the provided float to the nearest integer. +The `WordWrap` function inserts line-breaks into the string, before it reaches the given width Syntax: - math.Round(value) + WordWrap(width, string) Where: -- `value` is the floating-point number. +- `width` is the number of characters at which to wrap the string. +- `string` is the input string to be wrapped. Examples: - Rounding a positive float: - math.Round(2.5) // Evaluates to 3 - - Rounding a negative float: - math.Round(-2.5) // Evaluates to -3 - - Using an integer: - math.Round(5) // Evaluates to 5 ---- +```javascript +Wrapping a string at a specified width: +WordWrap([5, "Hello World"]) // Evaluates to "Hello\nWorld" +Wrapping a longer string: +WordWrap([10, "Hello Beautiful World"]) // Evaluates to "Hello\nBeautiful\nWorld" -## Regexp +Wrapping a string with special characters: +WordWrap([5, "Hello$World"]) // Evaluates to "Hello\n$World" +``` +## YAML -### regexp.Find +### YAML -The `regexp.Find` function in CEL is used to find the first occurrence of a pattern within a string. It returns the matched substring or an error if the pattern is invalid. +The `YAML` function in CEL converts a YAML formatted string into a map. It provides an easy way to handle YAML data. Syntax: - regexp.Find(pattern, input) + YAML(yamlString) Where: -- `pattern` is the regular expression pattern you're looking for. -- `input` is the string you're searching within. +- `yamlString` is the YAML formatted string. Examples: - Finding a pattern within a string: - regexp.Find("llo", "hello") // Evaluates to "llo" +```javascript +Converting a simple YAML string to a map: +YAML("name: Alice\nage: 30") // Evaluates to a map with keys "name" and "age" - Searching for digits within a string: - regexp.Find("\\d+", "abc123def") // Evaluates to "123" +Handling a YAML sequence: +YAML("numbers:\n- 1\n- 2\n- 3") // Evaluates to a map with a key "numbers" containing an array - Pattern not found in the string: - regexp.Find("xyz", "hello") // Evaluates to "" ---- +Nested YAML data conversion: +YAML("person:\n name: Bob\n age: 35") // Evaluates to a nested map +``` -### regexp.FindAll +### toYAML -The `regexp.FindAll` function in CEL retrieves all occurrences of a pattern within a string, up to a specified count. It returns a list of matched substrings or an error if the pattern is invalid. +The `toYAML` function converts an object into a YAML formatted string. Syntax: - regexp.FindAll(pattern, count, input) - -Where: - -- `pattern` is the regular expression pattern to find. -- `count` is the maximum number of occurrences to return. -- `input` is the string to search within. + toYAML(object|array) Examples: - Finding all occurrences of a pattern: - regexp.FindAll("a.", -1, "banana") // Evaluates to ["ba", "na", "na"] - - Limiting the number of matches: - regexp.FindAll("\\d", 2, "12345") // Evaluates to ["1", "2"] - - Pattern not found: - regexp.FindAll("z", -1, "hello") // Evaluates to [] ---- +```javascript +toYAML({ name: "John" }); +toYAML(["John", "Alice"]); +``` -### regexp.Match +### YAMLArray -The `regexp.Match` function in CEL checks if a string matches a given regular expression pattern. It returns a boolean value indicating the match status. +The `YAMLArray` function converts a YAML formatted string representing a sequence into an array. Syntax: - regexp.Match(pattern, input) + YAMLArray(yamlArrayString) Where: -- `pattern` is the regular expression pattern to match. -- `input` is the string to check. +- `yamlArrayString` is the YAML formatted string representing a sequence. Examples: - Checking if a string matches a pattern: - regexp.Match("^h.llo", "hello") // Evaluates to true +```javascript +Converting a YAML sequence to an array: +YAMLArray("- 1\n- 2\n- 3") // Evaluates to an array [1, 2, 3] - Pattern does not match the string: - regexp.Match("^b", "apple") // Evaluates to false +Handling complex objects in a YAML sequence: +YAMLArray("- name: Alice\n- name: Bob") // Evaluates to an array of maps + +An empty YAML sequence: +YAMLArray("") // Evaluates to an empty array +``` - Matching digits in a string: - regexp.Match("\\d+", "abc123") // Evaluates to true --- -### regexp.QuoteMeta +## TOML -The `regexp.QuoteMeta` function in CEL quotes all regular expression metacharacters inside a string. It returns the quoted string. +### TOML -Syntax: +The `TOML` function converts a TOML formatted string into a map, making it easy to work with TOML data. - regexp.QuoteMeta(input) +Syntax:ToYAML + + TOML(tomlString) Where: -- `input` is the string containing metacharacters to be quoted. +- `tomlString` is the TOML formatted string. Examples: - Quoting metacharacters in a string: - regexp.QuoteMeta("a.b") // Evaluates to "a\\.b" +```javascript +Converting a TOML string to a map: +TOML("name = \"Alice\"\nage = 30") // Evaluates to a map with keys "name" and "age" - String without metacharacters: - regexp.QuoteMeta("abc") // Evaluates to "abc" +Handling an array in TOML: +TOML("numbers = [1, 2, 3]") // Evaluates to a map with a key "numbers" containing an array - Quoting a complex pattern: - regexp.QuoteMeta("[a-z].*") // Evaluates to "\\[a\\-z\\]\\.\\*" ---- +Nested TOML data conversion: +TOML("[person]\nname = \"Bob\"\nage = 35") // Evaluates to a nested map +``` -### regexp.Replace +### toTOML -The `regexp.Replace` function in CEL replaces occurrences of a pattern within a string with a specified replacement string. It returns the modified string. +The `toTOML` function converts a map or an array into a TOML formatted string. Syntax: - regexp.Replace(pattern, replacement, input) + toTOML(data) Where: -- `pattern` is the regular expression pattern to replace. -- `replacement` is the string to replace the pattern with. -- `input` is the original string. +- `data` is the map or array to be converted. Examples: - Replacing a pattern in a string: - regexp.Replace("a.", "x", "banana") // Evaluates to "bxnxna" +```javascript +Converting a map to a TOML string: +toTOML({"name": "Alice", "age": 30}) // Evaluates to "name = \"Alice\"\nage = 30" - Pattern not found: - regexp.Replace("z", "x", "apple") // Evaluates to "apple" +Handling an array (TOML arrays must be of the same type): +toTOML({"people": ["Alice", "Bob"]}) // Evaluates to "people = [\"Alice\", \"Bob\"]" + +An empty map: +toTOML({}) // Evaluates to an empty string +``` - Replacing digits: - regexp.Replace("\\d+", "num", "abc123") // Evaluates to "abcnum" --- -### regexp.ReplaceLiteral +## uuid -The `regexp.ReplaceLiteral` function in CEL replaces occurrences of a pattern within a string with a specified replacement string, without interpreting the pattern as a regular expression. It returns the modified string or an error if the pattern is invalid. +### uuid.Nil + +The `uuid.Nil` function returns the nil UUID. Syntax: - regexp.ReplaceLiteral(pattern, replacement, input) + uuid.Nil() -Where: +### uuid.V1 -- `pattern` is the substring to replace. -- `replacement` is the string to replace the pattern with. -- `input` is the original string. +The `uuid.V1` function returns a version 1 UUID. -Examples: +Syntax: - Replacing a substring: - regexp.ReplaceLiteral("apple", "orange", "apple pie") // Evaluates to "orange pie" + uuid.V1() - Substring not found: - regexp.ReplaceLiteral("z", "x", "apple") // Evaluates to "apple" +Example: - Replacing a pattern without regex interpretation: - regexp.ReplaceLiteral("a.", "x", "a.b c.d") // Evaluates to "x.b c.d" +```javascript +uuuuid.V1() != uuid.Nil(); +``` ---- +### uuid.V4 -### regexp.Split +The `uuid.V4` function returns a version 4 UUID. -The `regexp.Split` function in CEL splits a string into a slice of substrings separated by a pattern. It returns the slice of strings or an error if the pattern is invalid. +Syntax: + + uuid.V4() + +Example: + +```javascript +uuid.V4() != uuid.Nil(); +``` + +### uuid.IsValid + +The `uuid.IsValid` function checks if a string is a valid UUID. Syntax: - regexp.Split(pattern, count, input) + uuid.IsValid(uuid) -Where: +Example: -- `pattern` is the regular expression pattern that separates the substrings. -- `count` is the maximum number of splits. Use -1 for no limit. -- `input` is the string to split. +```javascript +uuid.IsValid("2a42e576-c308-4db9-8525-0513af307586"); +``` -Examples: +### uuid.Parse - Splitting a string by a pattern: - regexp.Split("a.", -1, "banana") // Evaluates to ["", "n", "n"] +The `uuid.Parse` function parses a string into a UUID. - Limiting the number of splits: - regexp.Split("\\s", 2, "apple pie is delicious") // Evaluates to ["apple", "pie is delicious"] +Syntax: - Pattern not found: - regexp.Split("z", -1, "hello") // Evaluates to ["hello"] ---- + uuid.Parse(uuid) + +Example: +```javascript +uuid.Parse("2a42e576-c308-4db9-8525-0513af307586"); +``` diff --git a/mission-control/.gitignore b/mission-control/.gitignore index 7b32ccc2..c0365ac7 100644 --- a/mission-control/.gitignore +++ b/mission-control/.gitignore @@ -21,4 +21,5 @@ yarn-error.log* # copied from canary-checker docs/canary-checker +docs/reference static/img/icons diff --git a/mission-control/docs/reference/authentication.md b/mission-control/docs/reference/authentication.md deleted file mode 100644 index ab71e90e..00000000 --- a/mission-control/docs/reference/authentication.md +++ /dev/null @@ -1,102 +0,0 @@ -# Authentication - -Canary checker uses the Kubernetes ValuesFrom pattern to retrieve sensitive values like usernames, password and access keys. - -Whenever a field uses the `EnvVar` object type you have the option of specifying the value in 3 ways: - -## EnvVar - -1. Statically in the `value` field -1. Via a Kubernetes Config Map via the `configMapKeyRef` field -1. Via a Kubernetes Secret via the `secretKeyRef` field - -### Static Values - -Using a HTTP health check as an example for static values: - -```yaml title="http-basic-auth-static.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth -spec: - http: - - url: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - value: hello - password: - value: world -``` - -### Kubernetes Configmaps - -To use a configmap, we first need to create the configmap: - -```bash -kubectl create configmap basic-auth --from-literal=user=hello --from-literal=pass=world -n default -``` - -```yaml title="http-basic-auth-configmap.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth-configmap -spec: - http: - - url: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - valueFrom: - configMapKeyRef: - name: basic-auth - key: user - password: - valueFrom: - configMapKeyRef: - name: basic-auth - key: pass -``` - -### Kubernetes Secrets - -To use a secret, first we create the secret: - -```bash -kubectl create secret generic basic-auth --from-literal=user=hello --from-literal=pass=world -n default -``` - -```yaml title="http-basic-auth-secret.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth-configmap -spec: - http: - - url: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - valueFrom: - secretKeyRef: - name: basic-auth - key: user - password: - valueFrom: - secretKeyRef: - name: basic-auth - key: pass -``` - -### Recommendations - -Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store (etcd). Anyone with API access can retrieve or modify a Secret, and so can anyone with access to etcd. With this in mind, it is recommended to implement some level of security to prevent unauthorized access to your Kubernetes secrets. -You may consider the following for your encryption and security needs: - -- [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/getting-started/) -- [Bitnami Sealed Secrets](https://www.youtube.com/watch?v=xd2QoV6GJlc&ab_channel=DevOpsToolkit) -- [KSOPS](https://blog.oddbit.com/post/2021-03-09-getting-started-with-ksops/) -- [Enable Encryption at Rest](https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/) -- [Enable or configure RBAC rules](https://kubernetes.io/docs/reference/access-authn-authz/authorization/) diff --git a/mission-control/docs/reference/connections.md b/mission-control/docs/reference/connections.md deleted file mode 100644 index d170da87..00000000 --- a/mission-control/docs/reference/connections.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Connections ---- -# Authentication - -Mission Control uses the Kubernetes ValuesFrom pattern to retrieve sensitive values like usernames, password and access keys. - -Whenever a field uses the `EnvVar` object type you have the option of specifying the value in 3 ways: - -1. Statically in the `value` field -1. Via a Kubernetes Config Map via the `configMapKeyRef` field -1. Via a Kubernetes Secret via the `secretKeyRef` field - -### Static Values - -Using a HTTP health check as an example for static values: - -```yaml title="http-basic-auth-static.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth -spec: - http: - - endpoint: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - value: hello - password: - value: world -``` - -### Kubernetes Configmaps - -To use a configmap, we first need to create the configmap: - -```bash -kubectl create configmap basic-auth --from-literal=user=hello --from-literal=pass=world -n default -``` - -```yaml title="http-basic-auth-configmap.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth-configmap -spec: - http: - - endpoint: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - valueFrom: - configMapKeyRef: - name: basic-auth - key: user - password: - valueFrom: - configMapKeyRef: - name: basic-auth - key: pass -``` - -### Kubernetes Secrets - -To use a secret, first we create the secret: - -```bash -kubectl create secret generic basic-auth --from-literal=user=hello --from-literal=pass=world -n default -``` - -```yaml title="http-basic-auth-secret.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-basic-auth-configmap -spec: - http: - - endpoint: https://httpbin.org/basic-auth/hello/world - responseCodes: [200] - authentication: - username: - valueFrom: - secretKeyRef: - name: basic-auth - key: user - password: - valueFrom: - secretKeyRef: - name: basic-auth - key: pass -``` \ No newline at end of file diff --git a/mission-control/docs/reference/scripting/cel-extra.md b/mission-control/docs/reference/scripting/cel-extra.md deleted file mode 100644 index 6460ea0e..00000000 --- a/mission-control/docs/reference/scripting/cel-extra.md +++ /dev/null @@ -1,598 +0,0 @@ -## Filepath - -### filepath.Base - -The `filepath.Base` function in CEL returns the last element of a file path. It effectively extracts the file name from the provided path. - -Syntax: - - filepath.Base(path) - -Where: - -- `path` is the file path string. - -Examples: - - Extracting the file name from a full path: - filepath.Base("/path/to/file.txt") // Evaluates to "file.txt" - - Working with a relative path: - filepath.Base("folder/file.txt") // Evaluates to "file.txt" - - When the path is a directory: - filepath.Base("/path/to/directory/") // Evaluates to "directory" - ---- - -### filepath.Clean - -The `filepath.Clean` function in CEL returns the shortest path name equivalent to the provided path by purely lexical processing. - -Syntax: - - filepath.Clean(path) - -Where: - -- `path` is the file path string. - -Examples: - - Cleaning a path with redundant elements: - filepath.Clean("/path/./to/file.txt") // Evaluates to "/path/to/file.txt" - - Resolving parent directory references: - filepath.Clean("folder/../file.txt") // Evaluates to "file.txt" - - Handling multiple slashes: - filepath.Clean("//path/to//file.txt") // Evaluates to "/path/to/file.txt" - ---- - -### filepath.Dir - -The `filepath.Dir` function in CEL returns all but the last element of a file path, typically the path's directory. - -Syntax: - - filepath.Dir(path) - -Where: - -- `path` is the file path string. - -Examples: - - Getting the directory of a file path: - filepath.Dir("/path/to/file.txt") // Evaluates to "/path/to" - - Working with a relative file path: - filepath.Dir("folder/file.txt") // Evaluates to "folder" - - When the path is a directory: - filepath.Dir("/path/to/directory/") // Evaluates to "/path/to" - ---- - -### filepath.Ext - -The `filepath.Ext` function in CEL returns the file name extension used by a file path. - -Syntax: - - filepath.Ext(path) - -Where: - -- `path` is the file path string. - -Examples: - - Extracting the extension from a file path: - filepath.Ext("/path/to/file.txt") // Evaluates to ".txt" - - Working with a file without an extension: - filepath.Ext("/path/to/file") // Evaluates to "" - - When the path is a directory: - filepath.Ext("/path/to/directory/") // Evaluates to "" - ---- - -### filepath.FromSlash - -The `filepath.FromSlash` function in CEL returns the result of replacing each slash ('/') character in the path with a separator character. - -Syntax: - - filepath.FromSlash(path) - -Where: - -- `path` is the file path string. - -Examples: - - Converting slashes on a UNIX system: - filepath.FromSlash("/path/to/file.txt") // Evaluates to "/path/to/file.txt" - - Converting slashes on a Windows system: - filepath.FromSlash("/path/to/file.txt") // Evaluates to "\\path\\to\\file.txt" - - Working with a relative path: - filepath.FromSlash("folder/file.txt") // System-dependent - ---- - -### filepath.IsAbs - -The `filepath.IsAbs` function in CEL reports whether the file path is absolute. - -Syntax: - - filepath.IsAbs(path) - -Where: - -- `path` is the file path string. - -Examples: - - Checking an absolute path: - filepath.IsAbs("/path/to/file.txt") // Evaluates to true - - Checking a relative path: - filepath.IsAbs("folder/file.txt") // Evaluates to false - - Working with a Windows-style absolute path: - filepath.IsAbs("C:\\path\\to\\file.txt") // Evaluates to true - ---- - -### filepath.Join - -The `filepath.Join` function in CEL concatenates multiple string elements to create a single file path. - -Syntax: - - filepath.Join(element1, element2, ...) - -Where: - -- `element1, element2, ...` are the path elements to concatenate. - -Examples: - - Joining path elements: - filepath.Join("/path", "to", "file.txt") // Evaluates to "/path/to/file.txt" - - Handling trailing and leading slashes: - filepath.Join("/path/", "/to/", "file.txt") // Evaluates to "/path/to/file.txt" - - Working with relative paths: - filepath.Join("folder", "subfolder", "file.txt") // Evaluates to "folder/subfolder/file.txt" - ---- - -### filepath.Match - -The `filepath.Match` function in CEL reports whether the file name matches the shell file pattern. - -Syntax: - - filepath.Match(pattern, name) - -Where: - -- `pattern` is the shell file pattern. -- `name` is the file name string. - -Examples: - - Matching a file name with a pattern: - filepath.Match("*.txt", "file.txt") // Evaluates to true - - A non-matching pattern: - filepath.Match("*.jpg", "file.txt") // Evaluates to false - - Using character ranges in patterns: - filepath.Match("[0-9].txt", "5.txt") // Evaluates to true - ---- - -### filepath.Rel - -The `filepath.Rel` function in CEL returns a relative path that is lexically equivalent to the target path when joined to the base path with an intervening separator. - -Syntax: - - filepath.Rel(basepath, targpath) - -Where: - -- `basepath` is the base file path string. -- `targpath` is the target file path string. - -Examples: - - Getting a relative path: - filepath.Rel("/path/to", "/path/to/file.txt") // Evaluates to "file.txt" - - When the target is a subdirectory: - filepath.Rel("/path", "/path/to/directory") // Evaluates to "to/directory" - - Handling different directory levels: - filepath.Rel("/path/to", "/path/from/file.txt") // Evaluates to "../from/file.txt" - ---- - -### filepath.Split - -The `filepath.Split` function in CEL splits a file path into a directory and file name. - -Syntax: - - filepath.Split(path) - -Where: - -- `path` is the file path string. - -Examples: - - Splitting a standard file path: - filepath.Split("/path/to/file.txt") // Evaluates to ["/path/to/", "file.txt"] - - Working with a file in the root directory: - filepath.Split("/file.txt") // Evaluates to ["/", "file.txt"] - - When the path is a directory: - filepath.Split("/path/to/directory/") // Evaluates to ["/path/to/directory/", ""] - ---- - -### filepath.ToSlash - -The `filepath.ToSlash` function in CEL returns the result of replacing each separator character in the path with a slash ('/') character. - -Syntax: - - filepath.ToSlash(path) - -Where: - -- `path` is the file path string. - -Examples: - - Converting backslashes to slashes: - filepath.ToSlash("\\path\\to\\file.txt") // Evaluates to "/path/to/file.txt" - - Working with an already slash-separated path: - filepath.ToSlash("/path/to/file.txt") // Evaluates to "/path/to/file.txt" - - Handling mixed separators: - filepath.ToSlash("\\path/to\\file.txt") // Evaluates to "/path/to/file.txt" - ---- - -### filepath.VolumeName - -The `filepath.VolumeName` function in CEL returns the volume name of the file path. - -Syntax: - - filepath.VolumeName(path) - -Where: - -- `path` is the file path string. - -Examples: - - Extracting the volume name on a Windows system: - filepath.VolumeName("C:\\path\\to\\file.txt") // Evaluates to "C:" - - Working with a UNIX file path: - filepath.VolumeName("/path/to/file.txt") // Evaluates to "" - - Handling a Windows UNC path: - filepath.VolumeName("\\\\server\\share\\file.txt") // Evaluates to "\\\\server\\share" - ---- - -## Path - -### path.Base - -The `path.Base` function in CEL is used to extract the last element of a path. It returns the base name of the provided path. - -Syntax: - - path.Base(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Extracting the file name from a path: - path.Base("/tmp/myfile.txt") // Evaluates to "myfile.txt" - - Getting the last directory in a path: - path.Base("/home/user/docs") // Evaluates to "docs" - - When provided with an empty path: - path.Base("") // Evaluates to "." - ---- - -### path.Clean - -The `path.Clean` function in CEL returns the shortest path name equivalent to the provided path by purely lexical processing. - -Syntax: - - path.Clean(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Cleaning a path with dot segments: - path.Clean("/home/../usr/bin") // Evaluates to "/usr/bin" - - Cleaning a path with multiple slashes: - path.Clean("/tmp//myfile.txt") // Evaluates to "/tmp/myfile.txt" - - Cleaning a relative path: - path.Clean("./docs") // Evaluates to "docs" - ---- - -### path.Dir - -The `path.Dir` function in CEL returns all but the last element of a path, typically the path's directory. - -Syntax: - - path.Dir(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Getting the directory for a file path: - path.Dir("/tmp/myfile.txt") // Evaluates to "/tmp" - - Getting the parent directory: - path.Dir("/home/user/docs") // Evaluates to "/home/user" - - When provided with a root path: - path.Dir("/") // Evaluates to "/" - ---- - -### path.Ext - -The `path.Ext` function in CEL returns the file name extension used by the provided path. - -Syntax: - - path.Ext(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Extracting the extension from a file path: - path.Ext("/tmp/myfile.txt") // Evaluates to ".txt" - - When the file has no extension: - path.Ext("/tmp/myfile") // Evaluates to "" - - Extracting extension from a hidden file: - path.Ext("/tmp/.myfile") // Evaluates to "" - ---- - -### path.IsAbs - -The `path.IsAbs` function in CEL checks if the provided path is an absolute path. - -Syntax: - - path.IsAbs(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Checking an absolute path: - path.IsAbs("/tmp/myfile.txt") // Evaluates to true - - Checking a relative path: - path.IsAbs("tmp/myfile.txt") // Evaluates to false - - Checking an empty path: - path.IsAbs("") // Evaluates to false - ---- - -### path.Join - -The `path.Join` function in CEL concatenates multiple string elements to create a single, joined path. - -Syntax: - - path.Join(element1, element2, ...) - -Where: - -- `element1, element2, ...` are the path elements to join. - -Examples: - - Joining path elements: - path.Join("/home", "user", "docs") // Evaluates to "/home/user/docs" - - Joining elements with a relative path: - path.Join("home", "user", "docs") // Evaluates to "home/user/docs" - - Joining elements with extra slashes: - path.Join("/tmp/", "/myfile.txt") // Evaluates to "/tmp/myfile.txt" - ---- - -### path.Match - -The `path.Match` function in CEL checks if the provided string matches the pattern. - -Syntax: - - path.Match(pattern, name) - -Where: - -- `pattern` is the pattern to match. -- `name` is the string to check. - -Examples: - - Matching a simple pattern: - path.Match("*.txt", "myfile.txt") // Evaluates to true - - Pattern not matching: - path.Match("*.txt", "myfile.doc") // Evaluates to false - - Matching with wildcard: - path.Match("*file.txt", "myfile.txt") // Evaluates to true - ---- - -### path.Split - -The `path.Split` function in CEL splits the path into a directory and file name. - -Syntax: - - path.Split(path) - -Where: - -- `path` is the file or directory path string. - -Examples: - - Splitting a standard file path: - path.Split("/tmp/myfile.txt") // Evaluates to ["/tmp/", "myfile.txt"] - - Splitting a path ending with a slash: - path.Split("/home/user/docs/") // Evaluates to ["/home/user/docs", ""] - - Splitting a relative path: - path.Split("docs/myfile.txt") // Evaluates to ["docs/", "myfile.txt"] - ---- - -### - -## UUID - -### uuid.V1 - -The `uuid.V1` function in CEL generates a version 1 UUID, which is based on the current MAC address and date/time. It returns a string representation of the generated UUID. - -Syntax: - - uuid.V1() - -Examples: - - Generating a version 1 UUID: - uuid.V1() // Evaluates to a string like "6ba7b810-9dad-11d1-80b4-00c04fd430c8" - ---- - -### uuid.V4 - -The `uuid.V4` function in CEL generates a version 4 UUID, which is random. It returns a string representation of the generated UUID. - -Syntax: - - uuid.V4() - -Examples: - - Generating a random UUID: - uuid.V4() // Evaluates to a string like "550e8400-e29b-41d4-a716-446655440000" - ---- - -### uuid.Nil - -The `uuid.Nil` function in CEL returns a nil UUID, which is a UUID with all bits set to zero. - -Syntax: - - uuid.Nil() - -Examples: - - Retrieving a nil UUID: - uuid.Nil() // Evaluates to "00000000-0000-0000-0000-000000000000" - ---- - -### uuid.IsValid - -The `uuid.IsValid` function in CEL checks if the given string is in the correct UUID format. It returns a boolean value indicating the validity. - -Syntax: - - uuid.IsValid(uuidString) - -Where: - -- `uuidString` is the UUID string you're validating. - -Examples: - - Validating a correct UUID format: - uuid.IsValid("550e8400-e29b-41d4-a716-446655440000") // Evaluates to true - - Checking an incorrect UUID format: - uuid.IsValid("invalid-uuid") // Evaluates to false - - Validating a nil UUID: - uuid.IsValid("00000000-0000-0000-0000-000000000000") // Evaluates to true - ---- - -### uuid.Parse - -The `uuid.Parse` function in CEL parses a given UUID string for further manipulation or inspection. It returns the parsed UUID. - -Syntax: - - uuid.Parse(uuidString) - -Where: - -- `uuidString` is the UUID string you're parsing. - -Examples: - - Parsing a valid UUID: - uuid.Parse("550e8400-e29b-41d4-a716-446655440000") // Evaluates to the same UUID if valid - diff --git a/mission-control/docs/reference/scripting/cel.md b/mission-control/docs/reference/scripting/cel.md deleted file mode 100644 index e510b594..00000000 --- a/mission-control/docs/reference/scripting/cel.md +++ /dev/null @@ -1,3317 +0,0 @@ - -# CEL Expressions - -`expr` expressions in canary checker use the [Go Common Expression Language (CEL)](https://github.com/google/cel-go) See [Language Definition](https://github.com/google/cel-spec/blob/master/doc/langdef.md#overview) - - -```yaml title=http-check-expr.yaml -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-check-expr -spec: - interval: 30 - http: - - name: http pass response 200 status code - endpoint: https://httpbin.demo.aws.flanksource.com/status/200 - test: - expr: "code in [200,201,301] and sslAge < Duration('7d')" -``` - ---- -## Collections - -### in - -The membership test operator checks whether an element is a member of a collection, such as a list or a map. It's worth noting that the `in` operator doesn't check for value membership in maps, only key membership. - -Syntax: - -```javascript -`a in b` Where `a` is the element you're checking for, and `b` is the collection. -``` - -Examples: - -```javascript -`"apple" in ["apple", "banana"]` // evaluates to `true` -`3 in [1, 2, 4]` // evaluates to `false` -``` ---- - -### size - -The `size` function in CEL is used to determine the number of elements in a collection or the number of Unicode characters in a string. - -Syntax: -``` - collection.size() or string.size() -``` -Examples: - -```javascript -Getting the size of a list: -["apple", "banana", "cherry"].size() // Evaluates to 3 - -Determining the number of characters in a string: -"hello".size() // Evaluates to 5 -``` - ---- - -### has - -The `has` macro checks for the presence of a field in a message. It's particularly useful for protobuf messages where fields can be absent rather than set to a default value. It's especially useful for distinguishing between a field being set to its default value and a field being unset. For instance, in a protobuf message, an unset integer field is indistinguishable from that field set to 0 without the `has` macro. - -Syntax - -```javascript -x.has(y) -``` - -Where `x` is the message and `y` is the field you're checking for. - -Examples: - -If you have a message `person` with a potential field `name`, you can check for its presence with: - -```javascript -person.has(name) // Evaluates to true if 'name' is present, false otherwise - -addressBook.has(person.email) // Evaluates to true if 'email' field is present in 'person' within 'addressBook' -``` - ---- - -### map - -The `map` macro creates a new collection by applying a function to each entry of an existing collection. It's useful for transforming the elements of a list or the values of a map. - -Syntax: - -```javascript -//For lists -list.map(e, ) - -//For maps: -map.map(k, v, ) -``` - -Where: - -- `list` is the list you're transforming. -- `map` is the map you're transforming. -- `e` represents each element of the list. -- `k` represents each key of the map. -- `v` represents each value of the map. -- `` is the transformation function applied to each entry. - -Examples: - -```javascript -// Transforming each element of a list by multiplying it by 2: -[1, 2, 3].map(e, e * 2) // Evaluates to [2, 4, 6] -``` - - -```javascript -// Transforming the values of a map by appending "!" to each value: -{"a": "apple", "b": "banana"}.map(k, v, v + "!") // Evaluates to {"a": "apple!", "b": "banana!"} -``` - - -```javascript -// Using both key and value for transformation in a map: -{"a": 1, "b": 2}.map(k, v, k + v) // Evaluates to {"a": "a1", "b": "b2"} -``` - ---- - -### filter - -The `filter` macro creates a new collection containing only the elements or entries of an existing collection that satisfy a given condition. - -Syntax: - -```javascript -//For lists: -list.filter(e, ) - -//For maps: -map.filter(k, v, ) -``` - -Where: - -- `list` is the list you're filtering. -- `map` is the map you're filtering. -- `e` represents each element of the list. -- `k` represents each key of the map. -- `v` represents each value of the map. -- `` is the condition applied to each entry. - -Examples: - -```javascript -// Filtering a list to include only numbers greater than 2: -[1, 2, 3, 4].filter(e, e > 2) // Evaluates to [3, 4] - -// Filtering a map to include only entries with values greater than 1: -{"a": 1, "b": 2, "c": 3}.filter(k, v, v > 1) // Evaluates to {"b": 2, "c": 3} -``` - ---- - -### all - -The `all` macro checks if all elements of a collection, such as a list or a map, satisfy a given condition. It returns a boolean value based on the evaluation. - -Syntax: - -```javascript -//For lists: -list.all(e, ) - -//For maps: -map.all(k, v, ) -``` - -Where: - -- `list` is the list you're checking. -- `map` is the map you're checking. -- `e` represents each element of the list. -- `k` represents each key of the map. -- `v` represents each value of the map. -- `` is the condition applied to each entry. - -Examples: - -```javascript -// Checking if all elements of a list are greater than 0: -[1, 2, 3].all(e, e > 0) // Evaluates to true - -// Checking if all values of a map are non-empty strings: -{"a": "apple", "b": "banana", "c": ""}.all(k, v, v != "") // Evaluates to false - -// Using both key and value for condition in a map: -{"a": 1, "b": 2, "c": 3}.all(k, v, k != "a" || v > 1) // Evaluates to true -``` - ---- - -### exists - -The `exists` macro checks if there exists an element in a collection, such as a list or a map, that satisfies a given condition. It returns a boolean value based on the evaluation. - -Syntax: - -```javascript -// For lists -list.exists(e, ) - -// For maps -map.exists(k, v, ) -``` - -Where: - -- `list` is the list you're checking. -- `map` is the map you're checking. -- `e` represents each element of the list. -- `k` represents each key of the map. -- `v` represents each value of the map. -- `` is the condition applied to each entry. - -Examples: - -```javascript -//Checking if any element of a list is equal to 2: -[1, 2, 3].exists(e, e == 2) // Evaluates to true - -//Checking if any value of a map is an empty string: -{"a": "apple", "b": "banana", "c": ""}.exists(k, v, v == "") // Evaluates to true - -/Using both key and value for condition in a map: -{"a": 1, "b": 2, "c": 3}.exists(k, v, k == "a" && v == 1) // Evaluates to true -``` - ---- - -### fold - -The `fold` macro is used to combine all elements of a collection, such as a list or a map, using a binary function. It's a powerful tool for aggregating or reducing data. - -Syntax: - -```javascript -//For lists: -list.fold(e, acc, ) - -//For maps: -map.fold(k, v, acc, ) -``` - - -Where: - -- `list` is the list you're folding. -- `map` is the map you're folding. -- `e` represents each element of the list. -- `k` represents each key of the map. -- `v` represents each value of the map. -- `acc` is the accumulator, which holds the intermediate results. -- `` is the function applied to each entry and the accumulator. - -Examples: - -```javascript -// Computing the sum of all elements of a list: -[1, 2, 3].fold(e, acc, acc + e) // Evaluates to 6 - -// Concatenating all values of a map: -{"a": "apple", "b": "banana"}.fold(k, v, acc, acc + v) // Evaluates to "applebanana" -``` - ---- - -### slice - - -Returns a new sub-list using the indexes provided. - -```javascript -.slice(, ) -> -``` - -Examples: - -```javascript -[1,2,3,4].slice(1, 3) // return [2, 3] -[1,2,3,4].slice(2, 4) // return [3 ,4] -``` - ---- - -### sets.contains - -Returns whether the first list argument contains all elements in the second -list argument. The list may contain elements of any type and standard CEL -equality is used to determine whether a value exists in both lists. If the -second list is empty, the result will always return true. - -```javascript -sets.contains(list(T), list(T)) -> bool -``` - -Examples: - -```javascript -sets.contains([], []) // true -sets.contains([], [1]) // false -sets.contains([1, 2, 3, 4], [2, 3]) // true -sets.contains([1, 2.0, 3u], [1.0, 2u, 3]) // true -``` - ---- - -### sets.equivalent - -Returns whether the first and second list are set equivalent. Lists are set -equivalent if for every item in the first list, there is an element in the -second which is equal. The lists may not be of the same size as they do not -guarantee the elements within them are unique, so size does not factor into -the computation. - - sets.equivalent(list(T), list(T)) -> bool - -Examples: - -```javascript -sets.equivalent([], []) // true -sets.equivalent([1], [1, 1]) // true -sets.equivalent([1], [1u, 1.0]) // true -sets.equivalent([1, 2, 3], [3u, 2.0, 1]) // true -``` - ---- - -### sets.intersects - -Returns whether the first list has at least one element whose value is equal -to an element in the second list. If either list is empty, the result will -be false. - - sets.intersects(list(T), list(T)) -> bool - -Examples: - -```javascript -sets.intersects([1], []) // false -sets.intersects([1], [1, 2]) // true -sets.intersects([[1], [2, 3]], [[1, 2], [2, 3.0]]) // true -``` - ---- - -## Strings - -### matches - -The `matches` function in CEL is used to determine if a string matches a given regular expression pattern. It returns a boolean value indicating whether the string conforms to the pattern. - -Syntax: - -```javascript -string.matches(pattern) -``` - -Where: - -- `string` is the string you're checking. -- `pattern` is the regular expression pattern you're matching against. - -Examples: - -```javascript -// Checking if a string matches a simple pattern: -"apple".matches("^a.*e$") // Evaluates to true - -// Validating an email format: -"example@email.com".matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$") // Evaluates to true - -// Checking for a pattern of digits: -"12345".matches("^\\d+$") // Evaluates to true -``` ---- - -### startsWith - -The `startsWith` function in CEL is used to determine if a string starts with a specified substring. - -Syntax: - - string.startsWith(substring) - -Examples: - -```javascript -// Checking if a string starts with a certain substring: -"hello".startsWith("he") // Evaluates to true -``` - ---- - -### endsWith - -The `endsWith` function in CEL is used to determine if a string ends with a specified substring. - -Syntax: - - string.endsWith(substring) - -Examples: - -```javascript -// Checking if a string ends with a certain substring: -"hello".endsWith("lo") // Evaluates to true -``` - ---- - -### contains - -The `contains` function in CEL is used to check if a string contains a given substring. - -Syntax: - - string.contains(substring) - -Examples: - -```javascript -//Checking if a string contains a certain substring: -"apple".contains("app") // Evaluates to true -``` - ---- - -### size - -The `size` function in CEL is used to determine the number of elements in a collection or the number of Unicode characters in a string. - -Syntax: - - collection.size() or string.size() - -Examples: - -```javascript -// Getting the size of a list: -["apple", "banana", "cherry"].size() // Evaluates to 3 - -// Determining the number of characters in a string: -"hello".size() // Evaluates to 5 -``` - ---- - -### charAt - -Returns the character at the given position. If the position is negative, or -greater than the length of the string, the function will produce an error: -``` - .charAt() -> -``` -Examples: - -```javascript -'hello'.charAt(4) // return 'o' -'hello'.charAt(5) // return '' -'hello'.charAt(-1) // error -``` - ---- - -### indexOf - -Returns the integer index of the first occurrence of the search string. If the -search string is not found the function returns -1. - -The function also accepts an optional position from which to begin the -substring search. If the substring is the empty string, the index where the -search starts is returned (zero or custom). -``` - .indexOf() -> - .indexOf(, ) -> -``` -Examples: - -```javascript -'hello mellow'.indexOf('') // returns 0 -'hello mellow'.indexOf('ello') // returns 1 -'hello mellow'.indexOf('jello') // returns -1 -'hello mellow'.indexOf('', 2) // returns 2 -'hello mellow'.indexOf('ello', 2) // returns 7 -'hello mellow'.indexOf('ello', 20) // error -``` - ---- - -### lastIndexOf - -Returns the integer index of the last occurrence of the search string. If the -search string is not found the function returns -1. - -The function also accepts an optional position which represents the last index -to be considered as the beginning of the substring match. If the substring is -the empty string, the index where the search starts is returned (string length -or custom). -``` - .lastIndexOf() -> - .lastIndexOf(, ) -> -``` -Examples: - -```javascript -'hello mellow'.lastIndexOf('') // returns 12 -'hello mellow'.lastIndexOf('ello') // returns 7 -'hello mellow'.lastIndexOf('jello') // returns -1 -'hello mellow'.lastIndexOf('ello', 6) // returns 1 -'hello mellow'.lastIndexOf('ello', -1) // error -``` - ---- - -### join - -Returns a new string where the elements of string list are concatenated. - -The function also accepts an optional separator which is placed between -elements in the resulting string. -``` - >.join() -> - >.join() -> -``` -Examples: - -```javascript -['hello', 'mellow'].join() // returns 'hellomellow' -['hello', 'mellow'].join(' ') // returns 'hello mellow' -[].join() // returns '' -[].join('/') // returns '' -``` - ---- - -### quote - -Takes the given string and makes it safe to print (without any formatting due to escape sequences). -If any invalid UTF-8 characters are encountered, they are replaced with \uFFFD. -``` - strings.quote() -``` -Examples: - -```javascript -strings.quote('single-quote with "double quote"') // returns '"single-quote with \"double quote\""' -strings.quote("two escape sequences \a\n") // returns '"two escape sequences \\a\\n"' -``` - ---- - -### replace - -Returns a new string based on the target, which replaces the occurrences of a -search string with a replacement string if present. The function accepts an -optional limit on the number of substring replacements to be made. - -When the replacement limit is 0, the result is the original string. When the -limit is a negative number, the function behaves the same as replace all. - -```javascript -.replace(, ) -> -.replace(, , ) -> -``` - -Examples: - -```javascript -'hello hello'.replace('he', 'we') // returns 'wello wello' -'hello hello'.replace('he', 'we', -1) // returns 'wello wello' -'hello hello'.replace('he', 'we', 1) // returns 'wello hello' -'hello hello'.replace('he', 'we', 0) // returns 'hello hello' -``` - ---- - -### split - -Returns a list of strings split from the input by the given separator. The -function accepts an optional argument specifying a limit on the number of -substrings produced by the split. - -When the split limit is 0, the result is an empty list. When the limit is 1, -the result is the target string to split. When the limit is a negative -number, the function behaves the same as split all. -``` - .split() -> > - .split(, ) -> > -``` -Examples: - -```javascript -'hello hello hello'.split(' ') // returns ['hello', 'hello', 'hello'] -'hello hello hello'.split(' ', 0) // returns [] -'hello hello hello'.split(' ', 1) // returns ['hello hello hello'] -'hello hello hello'.split(' ', 2) // returns ['hello', 'hello hello'] -'hello hello hello'.split(' ', -1) // returns ['hello', 'hello', 'hello'] -``` - ---- - -### substring - -Returns the substring given a numeric range corresponding to character -positions. Optionally may omit the trailing range for a substring from a given -character position until the end of a string. - -Character offsets are 0-based with an inclusive start range and exclusive end -range. It is an error to specify an end range that is lower than the start -range, or for either the start or end index to be negative or exceed the string -length. -``` - .substring() -> - .substring(, ) -> -``` -Examples: - -```javascript -'tacocat'.substring(4) // returns 'cat' -'tacocat'.substring(0, 4) // returns 'taco' -'tacocat'.substring(-1) // error -'tacocat'.substring(2, 1) // error -``` - ---- - -### trim - -Returns a new string which removes the leading and trailing whitespace in the -target string. The trim function uses the Unicode definition of whitespace -which does not include the zero-width spaces. See: -https://en.wikipedia.org/wiki/Whitespace_character#Unicode -``` - .trim() -> -``` -Examples: - - ' \ttrim\n '.trim() // returns 'trim' - - -### TrimPrefix - -The `TrimPrefix` function in CEL removes a given prefix from a string if the string starts with that prefix. - -Syntax: - - TrimPrefix(prefix, string) - -Where: - -- `prefix` is the starting substring to remove. -- `string` is the string from which the prefix will be removed. - -Examples: - -```javascript -// Removing a prefix from a string: -TrimPrefix("Mr.", "Mr. Smith") // Evaluates to "Smith" - -// Another example: -TrimPrefix("Astro", "Astronaut") // Evaluates to "naut" - -// If the prefix is not present: -TrimPrefix("Dr.", "Mr. Smith") // Evaluates to "Mr. Smith" -``` - ---- - -### TrimSuffix - -The `TrimSuffix` function in CEL removes a given suffix from a string if the string ends with that suffix. - -Syntax: - - TrimSuffix(suffix, string) - -Where: - -- `suffix` is the ending substring to remove. -- `string` is the string from which the suffix will be removed. - -Examples: - -```javascript -// Removing a suffix from a string: -TrimSuffix(".jpg", "image.jpg") // Evaluates to "image" - - -// If the suffix is not present: -TrimSuffix(".png", "image.jpg") // Evaluates to "image.jpg" -``` ---- - -### lowerAscii - -Returns a new string where all ASCII characters are lower-cased. - -This function does not perform Unicode case-mapping for characters outside the -ASCII range. -``` - .lowerAscii() -> -``` -Examples: - -```javascript - 'TacoCat'.lowerAscii() // returns 'tacocat' - 'TacoCÆt Xii'.lowerAscii() // returns 'tacocÆt xii' -``` - ---- - -### - -### upperAscii - -Returns a new string where all ASCII characters are upper-cased. - -This function does not perform Unicode case-mapping for characters outside the -ASCII range. -``` - .upperAscii() -> -``` -Examples: - -```javascript - 'TacoCat'.upperAscii() // returns 'TACOCAT' - 'TacoCÆt Xii'.upperAscii() // returns 'TACOCÆT XII' -``` - ---- - -### reverse - -Returns a new string whose characters are the same as the target string, only formatted in -reverse order. -This function relies on converting strings to rune arrays in order to reverse. -It can be located in Version 3 of strings. -``` - .reverse() -> -``` -Examples: - -```javascript -'gums'.reverse() // returns 'smug' -'John Smith'.reverse() // returns 'htimS nhoJ' -``` - ---- - - - -### HumanDuration - -The `HumanDuration` function in CEL converts a duration into a human-readable format. - -Syntax: - - HumanDuration(duration) - -Where: - -- `duration` is the duration you want to convert. - -Examples: - -```javascript -// Converting a duration into a human-readable format: -HumanDuration(3600) // Evaluates to "1 hour" - -// Converting another duration: -HumanDuration(600) // Evaluates to "10 minutes" - -// Converting a longer duration: -HumanDuration(86400) // Evaluates to "1 day" -``` - ---- - -### HumanSize - -The `HumanSize` function in CEL converts a size in bytes into a human-readable format. - -Syntax: - - HumanSize(size) - -Where: - -- `size` is the size in bytes you want to convert. - -Examples: - -```javascript -// Converting a size into a human-readable format: -HumanSize(1024) // Evaluates to "1 KiB" - -// Converting another size: -HumanSize(1048576) // Evaluates to "1 MiB" - -// Converting a larger size: -HumanSize(1073741824) // Evaluates to "1 GiB" -``` - ---- - -### Semver - -The `Semver` function in CEL parses a version string and returns a map containing the major, minor, patch, prerelease, metadata, and original version. - -Syntax: - - Semver(version) - -Where: - -- `version` is the version string to parse. - -Examples: - -```javascript -// Parsing a semantic version: -Semver("1.2.3-alpha+meta") // Evaluates to a map with major: "1", minor: "2", patch: "3", prerelease: "alpha", metadata: "meta", original: "1.2.3-alpha+meta" - -Semver("2.3.4-beta+meta2") // Evaluates to a map with major: "2", minor: "3", patch: "4", prerelease: "beta", metadata: "meta2", original: "2.3.4-beta+meta2" - -// Parsing a simple semantic version: -Semver("3.4.5") // Evaluates to a map with major: "3", minor: "4", patch: "5", prerelease: "", metadata: "", original: "3.4.5" -``` - ---- - -### SemverCompare - -The `SemverCompare` function in CEL compares two semantic version strings. - -Syntax: - - SemverCompare(version1, version2) - -Where: - -- `version1` is the first version string to compare. -- `version2` is the second version string to compare. - -Examples: - -```javascript -// Comparing two semantic versions: -SemverCompare("1.2.3", "1.2.4") // Evaluates to false - -// Comparing two identical versions: -SemverCompare("2.3.4", "2.3.4") // Evaluates to true - -// Comparing with a prerelease version: -SemverCompare("3.4.5", "3.4.5-alpha") // Evaluates to false -``` - ---- - -### ReplaceAll - -The `ReplaceAll` function in CEL replaces all occurrences of a substring within a string with another substring. - -Syntax: - - ReplaceAll(old, new, string) - -Where: - -- `old` is the substring to be replaced. -- `new` is the substring to replace with. -- `string` is the original string. - -Examples: - -```javascript -// Replacing a substring: -ReplaceAll("apple", "orange", "I have an apple") // Evaluates to "I have an orange" - -// Replacing another substring: -ReplaceAll("cat", "dog", "The cat sat on the mat") // Evaluates to "The dog sat on the mat" - -// Replacing a substring with a number: -ReplaceAll("one", "1", "I have one apple") // Evaluates to "I have 1 apple" -``` - ---- - - - -### Repeat - -The `Repeat` function in CEL repeats a string for a given number of times. - -Syntax: - - Repeat(count, string) - -Where: - -- `count` is the number of times the string should be repeated. -- `string` is the string to repeat. - -Examples: - -```javascript -// Repeating a string: -Repeat(3, "apple") // Evaluates to "appleappleapple" - -``` - ---- - -### Sort - -The `Sort` function in CEL sorts a list of strings. - -Syntax: - - Sort(list) - -Where: - -- `list` is the list of strings to sort. - -Examples: - -```javascript -Sorting a list of strings: -Sort(["banana", "apple", "cherry"]) // Evaluates to ["apple", "banana", "cherry"] - -Sorting another list: -Sort(["dog", "cat", "bird"]) // Evaluates to ["bird", "cat", "dog"] - -Sorting a list with numbers: -Sort(["3", "1", "2"]) // Evaluates to ["1", "2", "3"] -``` - ---- - - ---- - - -### Title - -The `Title` function in CEL converts the first character of each word in a string to uppercase. - -Syntax: - - Title(string) - -Where: - -- `string` is the string to convert. - -Examples: - -```javascript -// Converting a string: -Title("hello world") // Evaluates to "Hello World" - -// Working with mixed case: -Title("mIxEd CaSe") // Evaluates to "MIxED CASe" -``` - ---- - - -### Indent - -The `Indent` function in CEL indents each line of a string by a specified number of spaces or a specified prefix. - -Syntax: - - Indent(width or prefix, string) - -Where: - -- `width or prefix` is the number of spaces or the prefix string to add before each line. -- `string` is the string to indent. - -Examples: - -```javascript -// Indenting with spaces: -Indent(4, "Line1\nLine2") // Evaluates to " Line1\n Line2" - -//Indenting with a prefix: -Indent("> ", "Line1\nLine2") // Evaluates to "> Line1\n> Line2" - -// Indenting with a mixed prefix: -Indent("==", "Line1\nLine2") // Evaluates to "==Line1\n==Line2" -``` - ---- - -### Slug - -The `Slug` function in CEL converts a given string into a URL-friendly slug format. - -Syntax: - - Slug(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -// Converting a string to a slug: -Slug("Hello World!") // Evaluates to "hello-world" - -// Converting a string with special characters: -Slug("Hello, World!") // Evaluates to "hello-world" - -// Converting a multi-word string: -Slug("Hello Beautiful World") // Evaluates to "hello-beautiful-world" -``` - ---- - -### Quote - -The `Quote` function in CEL adds double quotes around a given string. - -Syntax: - - Quote(string) - -Examples: - -```javascript -//Quoting a simple string: -Quote("Hello World") // Evaluates to "\"Hello World\"" - -// Quoting a string with a number: -Quote("12345") // Evaluates to "\"12345\"" - -// Quoting an already quoted string: -Quote("\"Hello World\"") // Evaluates to "\"\"Hello World\"\"" -``` - ---- - -### ShellQuote - -The `ShellQuote` function in CEL quotes a string such that it can be safely used as a token in a shell command. - -Syntax: - - ShellQuote(string) - -Examples: - -```javascript -// Shell quoting a string: -ShellQuote("Hello World") // Evaluates to "'Hello World'" - -// Shell quoting a string with special characters: -ShellQuote("Hello$World") // Evaluates to "'Hello$World'" - -// Shell quoting a string with spaces and special characters: -ShellQuote("Hello World$123") // Evaluates to "'Hello World$123'" -``` - ---- - -### Squote - -The `Squote` function in CEL adds single quotes around a given string. - -Syntax: - - Squote(string) - - - -Examples: - -```javascript -Single quoting a simple string: -Squote("Hello World") // Evaluates to "'Hello World'" - -Single quoting a string with a number: -Squote("12345") // Evaluates to "'12345'" - -Single quoting an already single quoted string: -Squote("'Hello World'") // Evaluates to "'''Hello World'''" -``` - ---- - -### SnakeCase - -The `SnakeCase` function in CEL converts a given string into snake_case format. - -Syntax: - - SnakeCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -Converting a string to snake_case: -SnakeCase("Hello World") // Evaluates to "hello_world" - -Converting a CamelCase string: -SnakeCase("HelloWorld") // Evaluates to "hello_world" - -Converting a string with spaces and special characters: -SnakeCase("Hello Beautiful World!") // Evaluates to "hello_beautiful_world" -``` - ---- - -### CamelCase - -The `CamelCase` function in CEL converts a given string into CamelCase format. - -Syntax: - - CamelCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -Converting a string to CamelCase: -CamelCase("hello world") // Evaluates to "HelloWorld" - -Converting a snake_case string: -CamelCase("hello_world") // Evaluates to "HelloWorld" - -Converting a string with spaces and special characters: -CamelCase("hello beautiful world!") // Evaluates to "HelloBeautifulWorld" -``` - ---- - -### KebabCase - -The `KebabCase` function in CEL converts a given string into kebab-case format. - -Syntax: - - KebabCase(string) - -Where: - -- `string` is the input string to be converted. - -Examples: - -```javascript -Converting a string to kebab-case: -KebabCase("Hello World") // Evaluates to "hello-world" - -Converting a CamelCase string: -KebabCase("HelloWorld") // Evaluates to "hello-world" - -Converting a string with spaces and special characters: -KebabCase("Hello Beautiful World!") // Evaluates to "hello-beautiful-world" -``` - ---- - -### WordWrap - -The `WordWrap` function in CEL wraps the input string at the specified width. - -Syntax: - - WordWrap(width, string) - -Where: - -- `width` is the number of characters at which to wrap the string. -- `string` is the input string to be wrapped. - -Examples: - -```javascript -Wrapping a string at a specified width: -WordWrap(5, "Hello World") // Evaluates to "Hello\nWorld" - -Wrapping a longer string: -WordWrap(10, "Hello Beautiful World") // Evaluates to "Hello\nBeautiful\nWorld" - -Wrapping a string with special characters: -WordWrap(5, "Hello$World") // Evaluates to "Hello\n$World" -``` - ---- - -### RuneCount - -The `RuneCount` function in CEL counts the number of runes in a given string. - -Syntax: - - RuneCount(string) - -Where: - -- `string` is the input string whose runes are to be counted. - -Examples: - -```javascript -Counting runes in a string: -RuneCount("Hello World") // Evaluates to 11 - -Counting runes in a string with special characters: -RuneCount("Hello$World") // Evaluates to 11 - -Counting runes in an empty string: -RuneCount("") // Evaluates to 0 -``` - ---- - - - -## Dates - -### timestamp - -The `timestamp` function in CEL is used to represent a point in time. It's typically used in conjunction with other functions to extract or manipulate time-related data. - -Syntax: - - timestamp("YYYY-MM-DDTHH:MM:SSZ") - -Where: - -- The string inside the function represents the date and time. - -Examples: - -```javascript -Creating a timestamp for January 1st, 2023: -timestamp("2023-01-01T00:00:00Z") - -Creating another timestamp: -timestamp("2023-07-04T12:00:00Z") -``` - ---- - -### getDate - -The `getDate` function in CEL is used to extract the date part from a timestamp. It returns a string representation of the date. - -Syntax: - - timestamp.getDate() - -Where: - -- `timestamp` is the timestamp value from which you're extracting the date. - -Examples: - -```javascript -Extracting the date from a timestamp: -"2023-01-01T12:34:56Z".getDate() // Evaluates to "2023-01-01" - -Getting the date from another timestamp: -"2023-07-04T00:00:00Z".getDate() // Evaluates to "2023-07-04" -``` - ---- - -### get[DatePart] - - - -| Function | Description | Example | -| ------------------------ | ------------------------------------------------------------ | ------- | -| `{date>.getDayOfMonth()` | A integer value representing the day of the month, with the first day being 1. | 1 - 31 | -|` .getDayOfWeek()` | eturns an integer value representing the day of the week, where Sunday is 0 and Saturday is 6. | 0 - 6 | -| `.getDayOfYear()` | an integer value representing the day of the year, with January 1st being day 1. | 1 - 366 | -| `.getDayOfMonth()` | the full year (4 digits for 4-digit years) of the specified timestamp. | | -| `.getHours()` | the full year (4 digits for 4-digit years) of the specified timestamp. | 0- 23 | -| `.getMilliseconds()` | | 0 -999 | -| `.getMinutes()` | | | -| `.getMonth()` | | 0 -11 | -| `.getSeconds()` | 0 - 59 | 0 - 59 | -| `.getHours()` | | | - - - -### duration - -The `duration` function in CEL creates a new duration from a string representation. The string format is an integer followed by a unit: `s` for seconds, `m` for minutes, `h` for hours, and `d` for days. - -Syntax: - - duration(stringRepresentation) - -Examples: - -```javascript -Creating a duration of 5 hours: -duration("5h") // Represents a duration of 5 hours - -Creating a duration of 30 minutes: -duration("30m") // Represents a duration of 30 minutes -``` - - -Durations can also be crated using arithmetic: - -| Field | Description | -| ---------------- | ------------------------------------------------------------ | -| time.Unix(epoch) | converts a UNIX time (seconds since the UNIX epoch) into a `time.Time` object | -| time.Nanosecond | converts to a time.Duration | -| time.Microsecond | | -| time.Millisecond | | -| time.Second | | -| time.Minute | | -| time.Hour | | - - ---- - - - - - -### time.ZoneName - -The `time.ZoneName` function in CEL returns the name of the local system's time zone. It doesn't require any parameters and is useful for retrieving the time zone information. - -Syntax: - - time.ZoneName() - -Examples: - -```javascript -Retrieving the local time zone name: -time.ZoneName() // Might evaluate to "PST" if the local time zone is Pacific Standard Time - -Another example of retrieving the time zone: -time.ZoneName() // Could evaluate to "EST" for Eastern Standard Time - -Yet another example: -time.ZoneName() // Might evaluate to "UTC" for Coordinated Universal Time -``` - ---- - -### time.ZoneOffset - -The `time.ZoneOffset` function in CEL returns the offset of the local system's time zone in minutes. It helps in understanding the time difference between the local time zone and UTC. - -Syntax: - - time.ZoneOffset() - -Examples: - -```javascript -Getting the time zone offset: -time.ZoneOffset() // Could evaluate to -480 for PST - -Another example of getting the offset: -time.ZoneOffset() // Might evaluate to 0 for UTC - -Yet another example: -time.ZoneOffset() // Could evaluate to 330 for IST (Indian Standard Time) -``` - ---- - -### time.Parse - -The `time.Parse` function in CEL is used to parse a given string into a time object based on a specified layout. It's handy for converting string representations of time into actual time objects. - -Syntax: - - time.Parse(layout, value) - -Where: - -- `layout` is the time layout string. -- `value` is the string representation of the time to be parsed. - -Examples: - -```javascript -Parsing a time string with a specific format: -time.Parse("2006-01-02", "2023-09-26") // Evaluates to a time object representing September 26, 2023 - -Another example with a different format: -time.Parse("02-01-2006", "26-09-2023") // Evaluates to the same time object as above - -Parsing a time with hour and minute information: -time.Parse("15:04 02-01-2006", "14:30 26-09-2023") // Includes time of day information -``` - ---- - -### time.ParseLocal - -The `time.ParseLocal` function in CEL parses a given string into a time object according to a specified layout and the local time zone. It's useful for working with local times. - -Syntax: - - time.ParseLocal(layout, value) - -Where: - -- `layout` is the time layout string. -- `value` is the string representation of the time to be parsed. - -Examples: - -```javascript -Parsing a local time string: -time.ParseLocal("2006-01-02 15:04", "2023-09-26 14:30") // Evaluates to a local time object for 14:30 on September 26, 2023 - -Another example: -time.ParseLocal("02-01-2006", "26-09-2023") // Evaluates to a local time object for September 26, 2023 - -Parsing with a different time format: -time.ParseLocal("15:04 02-01-2006", "14:30 26-09-2023") // Includes time of day information in local time zone -``` - ---- - -### time.ParseInLocation - -The `time.ParseInLocation` function in CEL parses a string into a time object according to a specified layout and time zone. It provides more control over the time zone compared to `time.ParseLocal`. - -Syntax: - - time.ParseInLocation(layout, location, value) - -Where: - -- `layout` is the time layout string. -- `location` is the string name of the time zone. -- `value` is the string representation of the time to be parsed. - -Examples: - -```javascript -Parsing a time string for a specific time zone: -time.ParseInLocation("2006-01-02", "America/New_York", "2023-09-26") // Evaluates to a time object for EST/EDT - -Another example for a different time zone: -time.ParseInLocation("02-01-2006", "Europe/London", "26-09-2023") // Evaluates to a time object for GMT/BST - -Parsing with hour and minute for a specific zone: -time.ParseInLocation("15:04 02-01-2006", "Asia/Tokyo", "14:30 26-09-2023") // Evaluates to a time object for JST -``` - ---- - -### time.Now - -The `time.Now` function in CEL returns the current time. It's a straightforward way to retrieve the current date and time according to the system's local time zone. - -Syntax: - - time.Now() - -Examples: - -```javascript -Getting the current time: -time.Now() // Evaluates to the current date and time - -Another example of retrieving the current time: -time.Now() // Will always return the current moment's date and time - -Yet another example: -time.Now() // Useful for timestamping or time-stamping events in real-time -``` - ---- - - -### time.ParseDuration - -The `time.ParseDuration` function in CEL parses a string into a duration. It supports various units like "s" for seconds, "m" for minutes, "h" for hours, etc. - -Syntax: - - time.ParseDuration(duration) - -Where: - -- `duration` is the string representation of the duration. - -Examples: - -```javascript -Parsing a duration string: -time.ParseDuration("1h30m") // Evaluates to a duration of 1 hour and 30 minutes - -Another example with a different format: -time.ParseDuration("15m30s") // Evaluates to a duration of 15 minutes and 30 seconds - -Parsing a negative duration: -time.ParseDuration("-2h45m") // Evaluates to a duration of -2 hours and -45 minutes -``` - ---- - -### time.Since - -The `time.Since` function in CEL calculates the duration that has elapsed since a given time. It is commonly used to measure the time difference between a specified time and the current moment. - -Syntax: - - time.Since(pastTime) - -Where: - -- `pastTime` is a `time.Time` object representing a past point in time. - -Examples: - -```javascript -Calculating the time elapsed since a specific past time: -time.Since(time.Parse("2006-01-02", "2023-09-26")) // Evaluates to the duration since September 26, 2023 - -Another example with a different past time: -time.Since(time.Parse("15:04 02-01-2006", "14:30 26-09-2023")) // Evaluates to the duration since 14:30 on September 26, 2023 - -Using the `time.Now` function for a real-time duration: -time.Since(time.Now()) // Always evaluates to a very small duration, as it's the time since "now" -``` - ---- - -### time.Until - -The `time.Until` function in CEL calculates the duration remaining until a specified future time. It helps in determining the time left for an event or deadline. - -Syntax: - - time.Until(futureTime) - -Where: - -- `futureTime` is a `time.Time` object representing a future point in time. - -Examples: - -```javascript -Calculating the time remaining until a specific future time: -time.Until(time.Parse("2006-01-02", "2023-10-01")) // Evaluates to the duration until October 1, 2023 - -Another example with a different future time: -time.Until(time.Parse("15:04 02-01-2006", "16:00 30-09-2023")) // Evaluates to the duration until 16:00 on September 30, 2023 - -Using the `time.Now` function for a real-time duration: -time.Until(time.Now()) // Always evaluates to zero, as it's the time until "now" -``` - ---- - - -## Random - -### random.ASCII - -The `random.ASCII` function in CEL generates a random ASCII string of a given length. The characters in the string are within the ASCII printable character range. - -Syntax: - - random.ASCII(count) - -Where: - -- `count` is the length of the random ASCII string to be generated. - -Examples: - -```javascript -Generating a 5-character random ASCII string: -random.ASCII(5) // Might evaluate to "A7!2k" - -Creating a 10-character random ASCII string: -random.ASCII(10) // Might evaluate to "3e$7^2Go1" - -Producing a 15-character random ASCII string: -random.ASCII(15) // Might evaluate to "7g$!3H8^2Kl0p9" -``` - ---- - -### random.Alpha - -The `random.Alpha` function in CEL generates a random alphabetic string containing uppercase and lowercase letters, with a specified length. - -Syntax: - - random.Alpha(count) - -Where: - -- `count` is the length of the random alphabetic string to be generated. - -Examples: - -```javascript -Generating a 5-character random alphabetic string: -random.Alpha(5) // Might evaluate to "aBcDe" - -Creating a 10-character random alphabetic string: -random.Alpha(10) // Might evaluate to "FgHiJkLmNo" - -Producing a 15-character random alphabetic string: -random.Alpha(15) // Might evaluate to "pQrStUvWxYzAbCdEf" -``` - ---- - -### random.AlphaNum - -The `random.AlphaNum` function in CEL generates a random alphanumeric string containing both letters and digits, with a specified length. - -Syntax: - - random.AlphaNum(count) - -Where: - -- `count` is the length of the random alphanumeric string to be generated. - -Examples: - -```javascript -Generating a 5-character random alphanumeric string: -random.AlphaNum(5) // Might evaluate to "a1B2c" - -Creating a 10-character random alphanumeric string: -random.AlphaNum(10) // Might evaluate to "3D4e5F6g7H" - -Producing a 15-character random alphanumeric string: -random.AlphaNum(15) // Might evaluate to "8i9J0k1L2m3N4o5" -``` - ---- - -### random.String - -The `random.String` function in CEL generates a random string based on provided character sets or bounds, with a specified length. - -Syntax: - - random.String(count, characterSetOrBounds) - -Where: - -- `count` is the length of the random string to be generated. -- `characterSetOrBounds` can be a character set string or lower and upper bounds for character codes. - -Examples: - -```javascript -Generating a 5-character random string from a character set: -random.String(5, "abc123") // Might evaluate to "1a2b3" - -Creating a 10-character random string within character code bounds: -random.String(10, 65, 90) // Might evaluate to random uppercase letters - -Producing a 15-character random string from a regex character class: -random.String(15, "[[:alnum:]]") // Might evaluate to a mix of letters and digits -``` - ---- - -### random.Item - -The `random.Item` function in CEL selects a random item from a given list of items. - -Syntax: - - random.Item(list) - -Where: - -- `list` is an array or list from which a random item is selected. - -Examples: - -```javascript -Selecting a random item from a list of fruits: -random.Item(["apple", "banana", "cherry"]) // Might evaluate to "banana" - -Choosing a random number from a list: -random.Item([1, 2, 3, 4, 5]) // Might evaluate to 3 - -Picking a random word from a list: -random.Item(["hello", "world", "foo", "bar"]) // Might evaluate to "foo" -``` - ---- - -### random.Number - -The `random.Number` function in CEL generates a random integer within a specified range. - -Syntax: - - random.Number(min, max) - -Where: - -- `min` is the minimum value of the range (inclusive). -- `max` is the maximum value of the range (inclusive). - -Examples: - -```javascript -Generating a random number between 1 and 10: -random.Number(1, 10) // Might evaluate to 7 - -Creating a random number between 50 and 100: -random.Number(50, 100) // Might evaluate to 89 - -Producing a random number between 0 and 1000: -random.Number(0, 1000) // Might evaluate to 456 -``` - ---- - -### random.Float - -The `random.Float` function in CEL generates a random floating-point number within a specified range. - -Syntax: - - random.Float(min, max) - -Where: - -- `min` is the minimum value of the range (inclusive). -- `max` is the maximum value of the range (inclusive). - -Examples: - -```javascript -Generating a random float between 0 and 1: -random.Float(0, 1) // Might evaluate to 0.572 - -Creating a random float between 5 and 10: -random.Float(5, 10) // Might evaluate to 7.283 - -Producing a random float between -1 and 1: -random.Float(-1, 1) // Might evaluate to -0.456 -``` - ---- - -## base64 - -### base64.Encode - -The `base64.Encode` function in CEL is used to encode input data into a Base64 string. The function can accept various types of input, including strings, byte slices, and types that can be converted to a byte slice. - -Syntax: - - base64.Encode(data) - -Where: - -- `data` is the input you're encoding. It can be a string, byte slice, or any type that can be converted to a byte slice. - -Examples: - -```javascript -Encoding a simple string: -base64.Encode("hello") // Expected Output: "aGVsbG8=" - -Encoding a number (which will first be converted to a string): -base64.Encode(12345) // Expected Output: "MTIzNDU=" - -Encoding a byte slice representation of a string: -base64.Encode([104, 101, 108, 108, 111]) // Expected Output: "aGVsbG8=" -``` - ---- - - - -### base64.Decode - -The `base64.Decode` function in CEL is used to decode a Base64 encoded string back to its original form. The function returns the decoded string. - -Syntax: - - base64.Decode(encodedData) - -Where: - -- `encodedData` is the Base64 encoded string you're decoding. - -Examples: - -```javascript -Decoding a Base64 encoded string: -base64.Decode("aGVsbG8=") // Expected Output: "hello" - -Decoding another example: -base64.Decode("MTIzNDU=") // Expected Output: "12345" - -Decoding an encoded special character: -base64.Decode("4pyT") // Expected Output: "✓" -``` - ---- - - -### conv.Default - -The `conv.Default` function in CEL is used to return the input value if it is true; otherwise, it returns the default value. - -Syntax: - - conv.Default(default, input) - -Examples: - - Using a truthy input value: - conv.Default("default", "input") // Evaluates to "input" - - Using a falsy input value: - conv.Default("default", "") // Evaluates to "default" - - Using a non-string input value: - conv.Default("default", 123) // Evaluates to 123 - ---- - -### conv.Dict - -The `conv.Dict` function in CEL is used to create a dictionary or map from the provided key-value pairs. - -Syntax: - - conv.Dict(key1, value1, key2, value2, ...) - -Examples: -``` - //Creating a dictionary with string keys and values: - conv.Dict("apple", "fruit", "carrot", "vegetable") // Evaluates to {"apple": "fruit", "carrot": "vegetable"} - - //Creating a mixed dictionary: - conv.Dict("name", "Alice", "age", 30) // Evaluates to {"name": "Alice", "age": 30} - - //Creating a dictionary with nested values: - conv.Dict("user", conv.Dict("name", "Alice", "age", 30), "active", true) // Evaluates to {"user": {"name": "Alice", "age": 30}, "active": true} -``` -## crypto - -### SHA1 - -The `crypto.SHA1` function in CEL is used to compute the SHA-1 hash of the input data. Note that SHA-1 is considered insecure for cryptographic purposes. - -Syntax: - - crypto.SHA1(data) - -Where: - -- `data` is the input data to be hashed. - -Examples: - -```javascript -Hashing a simple string: -crypto.SHA1("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c" - -Hashing a number represented as a string: -crypto.SHA1("12345") // Might evaluate to "8cb2237d0679ca88db6464eac60da96345513964" - -Hashing special characters: -crypto.SHA1("!@#") // Might evaluate to "8f9b6cb1cf7d70f23c16c9b9d4894d7f3b8fe15d" -``` ---- - -### SHA256 - -The `crypto.SHA256` function in CEL calculates the SHA-256 hash of the provided input data, offering a balance between security and performance. - -Syntax: - - crypto.SHA256(data) - -Where: - -- `data` is the input data to be hashed. - -Examples: - -```javascript -Hashing a simple string: -crypto.SHA256("hello") // Might evaluate to "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" - -Hashing a number represented as a string: -crypto.SHA256("12345") // Might evaluate to "d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2d2" - -Hashing special characters: -crypto.SHA256("!@#") // Might evaluate to "d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8d8" -``` ---- - -### SHA384 - -The `crypto.SHA384` function in CEL is used for computing the SHA-384 hash of the input data, which is a truncated version of SHA-512 and provides enhanced security. - -Syntax: - - crypto.SHA384(data) - -Where: - -- `data` is the input data to be hashed. - -Examples: - -```javascript -Hashing a simple string: -crypto.SHA384("hello") // Might evaluate to a long hash string - -Hashing a number represented as a string: -crypto.SHA384("12345") // Might evaluate to another long hash string - -Hashing special characters: -crypto.SHA384("!@#") // Might evaluate to yet another long hash string -``` ---- - -### SHA512 - -The `crypto.SHA512` function in CEL calculates the SHA-512 hash of the given input data. It's commonly used for data integrity verification and password storage. - -Syntax: - - crypto.SHA512(data) - -Where: - -- `data` is the input data to be hashed. - -Examples: - -```javascript -Hashing a simple string: -crypto.SHA512("hello") // Might evaluate to a very long hash string - -Hashing a number represented as a string: -crypto.SHA512("12345") // Might evaluate to another very long hash string - -Hashing special characters: -crypto.SHA512("!@#") // Might evaluate to yet another very long hash string -``` ---- - - ---- - - - ---- - - ---- - - - - - -### data.ToTOML - -The `data.ToTOML` function converts a map or an array into a TOML formatted string. - -Syntax: - - data.ToTOML(data) - -Where: - -- `data` is the map or array to be converted. - -Examples: - -```javascript -Converting a map to a TOML string: -data.ToTOML({"name": "Alice", "age": 30}) // Evaluates to "name = \"Alice\"\nage = 30" - -Handling an array (TOML arrays must be of the same type): -data.ToTOML({"people": ["Alice", "Bob"]}) // Evaluates to "people = [\"Alice\", \"Bob\"]" - -An empty map: -data.ToTOML({}) // Evaluates to an empty string -``` ---- - - -## Kubernetes - -### IsHealthy - -The `IsHealthy` function in CEL is used to determine if a Kubernetes resource is healthy. It returns a boolean value indicating the health status of the resource. - -Syntax: - - IsHealthy(resource) - -Where: - -- `resource` is the Kubernetes resource you're checking. - -Examples: - -```javascript -Checking if a pod is healthy: -IsHealthy(pod) // Evaluates to true if the pod is healthy - -Verifying the health of a service: -IsHealthy(service) // Evaluates to false if the service is not healthy - -Assessing the health of a deployment: -IsHealthy(deployment) // Evaluates to true if the deployment is healthy -``` ---- - -### GetStatus - -The `GetStatus` function in CEL retrieves the status of a Kubernetes resource as a string. It provides detailed information about the current state of the resource. - -Syntax: - - GetStatus(resource) - -Where: - -- `resource` is the Kubernetes resource whose status you're retrieving. - -Examples: - -```javascript -Retrieving the status of a pod: -GetStatus(pod) // Evaluates to "Running" if the pod is running - -Getting the status of a service: -GetStatus(service) // Evaluates to "Active" if the service is active - -Checking the status of a deployment: -GetStatus(deployment) // Evaluates to "Deployed" if the deployment is successful -``` - ---- - -### GetHealth - -The `GetHealth` function in CEL retrieves the health status of a Kubernetes resource as a map. The map contains key-value pairs providing detailed information about the resource's health. - -Syntax: - - GetHealth(resource) - -Where: - -- `resource` is the Kubernetes resource whose health information you're retrieving. - -Examples: - -```javascript -Retrieving the health information of a pod: -GetHealth(pod) // Evaluates to a map with keys and values indicating the pod's health - -Getting the health information of a service: -GetHealth(service) // Evaluates to a map with keys and values indicating the service's health - -Checking the health information of a deployment: -GetHealth(deployment) // Evaluates to a map with keys and values indicating the deployment's health -``` ---- - -## Math - - -### Greatest - -Returns the greatest valued number present in the arguments to the macro. - -Greatest is a variable argument count macro which must take at least one -argument. Simple numeric and list literals are supported as valid argument -types; however, other literals will be flagged as errors during macro -expansion. If the argument expression does not resolve to a numeric or -list(numeric) type during type-checking, or during runtime then an error -will be produced. If a list argument is empty, this too will produce an -error. -``` - math.greatest(, ...) -> -``` -Examples: - -```javascript -math.greatest(1) // 1 -math.greatest(1u, 2u) // 2u -math.greatest(-42.0, -21.5, -100.0) // -21.5 -math.greatest([-42.0, -21.5, -100.0]) // -21.5 -math.greatest(numbers) // numbers must be list(numeric) - -math.greatest() // parse error -math.greatest('string') // parse error -math.greatest(a, b) // check-time error if a or b is non-numeric -math.greatest(dyn('string')) // runtime error -``` ---- - -### least - -Returns the least valued number present in the arguments to the macro. - -Least is a variable argument count macro which must take at least one -argument. Simple numeric and list literals are supported as valid argument -types; however, other literals will be flagged as errors during macro -expansion. If the argument expression does not resolve to a numeric or -list(numeric) type during type-checking, or during runtime then an error -will be produced. If a list argument is empty, this too will produce an error. -``` - math.least(, ...) -> -``` -Examples: - - math.least(1) // 1 - math.least(1u, 2u) // 1u - math.least(-42.0, -21.5, -100.0) // -100.0 - math.least([-42.0, -21.5, -100.0]) // -100.0 - math.least(numbers) // numbers must be list(numeric) - - math.least() // parse error - math.least('string') // parse error - math.least(a, b) // check-time error if a or b is non-numeric - math.least(dyn('string')) // runtime error ---- - -### math.IsInt - -The `math.IsInt` function in CEL checks if the given input is an integer. It returns a boolean value indicating whether the input is an integer or not. - -Syntax: - - math.IsInt(value) - -Where: - -- `value` is the input value you're checking. - -Examples: - -```javascript -Checking if a number is an integer: -math.IsInt(5) // Evaluates to true - -Checking a float value: -math.IsInt(5.5) // Evaluates to false - -Checking a string that represents an integer: -math.IsInt("5") // Evaluates to true -``` ---- - -### math.IsFloat - -The `math.IsFloat` function determines if the provided value is a floating-point number. It returns a boolean indicating the result. - -Syntax: - - math.IsFloat(value) - -Where: - -- `value` is the input being evaluated. - -Examples: - -```javascript -Evaluating a floating-point number: -math.IsFloat(3.14) // Evaluates to true - -Evaluating an integer: -math.IsFloat(7) // Evaluates to false - -Evaluating a string representing a float: -math.IsFloat("3.14") // Evaluates to true -``` ---- - -### math.IsNum - -The `math.IsNum` function checks if the provided value is a number (either integer or float). It returns a boolean value. - -Syntax: - - math.IsNum(value) - -Where: - -- `value` is the input to check. - -Examples: - -```javascript -Checking an integer: -math.IsNum(42) // Evaluates to true - -Checking a float: -math.IsNum(3.14) // Evaluates to true - -Checking a non-number string: -math.IsNum("hello") // Evaluates to false -``` ---- - -### math.Abs - -The `math.Abs` function returns the absolute value of the given number. It supports both integers and floats. - -Syntax: - - math.Abs(number) - -Where: - -- `number` is the input value. - -Examples: - -```javascript -Getting the absolute value of a negative integer: -math.Abs(-5) // Evaluates to 5 - -Getting the absolute value of a float: -math.Abs(-3.14) // Evaluates to 3.14 - -Using a positive integer: -math.Abs(7) // Evaluates to 7 -``` ---- - -### math.Pow - -The `math.Pow` function calculates the power of the first number raised to the second number. It supports both integers and floats. - -Syntax: - - math.Pow(base, exponent) - -Where: - -- `base` is the base number. -- `exponent` is the exponent to which the base is raised. - -Examples: - -```javascript -Calculating the power of integers: -math.Pow(2, 3) // Evaluates to 8 - -Calculating the power of floats: -math.Pow(2.5, 3.5) // Evaluates to approximately 24.705 - -Using a negative exponent: -math.Pow(2, -3) // Evaluates to 0.125 -``` ---- - -### math.Seq - -The `math.Seq` function generates a sequence of integers from the start value to the end value, incrementing by the step value. - -Syntax: - - math.Seq(start, end, step) - -Where: - -- `start` is the starting value of the sequence. -- `end` is the ending value of the sequence. -- `step` is the increment step. - -Examples: - -```javascript -Generating a sequence from 1 to 5: -math.Seq(1, 5, 1) // Evaluates to [1, 2, 3, 4, 5] - -Generating a sequence with a step of 2: -math.Seq(1, 5, 2) // Evaluates to [1, 3, 5] - -Generating a descending sequence: -math.Seq(5, 1, -1) // Evaluates to [5, 4, 3, 2, 1] -``` ---- - -### max - -The `math.Max` function returns the maximum value among the provided numbers. It supports both integers and floats. - -Syntax: - - math.Max(a, b, ...) - -Where: - -- `a` is the first number. -- `b` is the second number. -- `...` represents additional numbers. - -Examples: - - Finding the maximum of integers: - math.Max(1, 2, 3) // Evaluates to 3 - - Finding the maximum of floats: - math.Max(1.2, 2.3, 3.1) // Evaluates to 3.1 - - Finding the maximum in a mixed list: - math.Max(1, 2.5, 3) // Evaluates to 3 ---- - -### min - -The `math.Min` function returns the minimum value among the provided numbers. It supports both integers and floats. - -Syntax: - - math.Min(a, b, ...) - -Where: - -- `a` is the first number. -- `b` is the second number. -- `...` represents additional numbers. - -Examples: - -```javascript -Finding the minimum of integers: -math.Min(1, 2, 3) // Evaluates to 1 - -Finding the minimum of floats: -math.Min(1.2, 2.3, 0.1) // Evaluates to 0.1 - -Finding the minimum in a mixed list: -math.Min(1, 2.5, 0) // Evaluates to 0 -``` ---- - -### math.Ceil - -The `math.Ceil` function returns the smallest integer greater than or equal to the provided float. - -Syntax: - - math.Ceil(value) - -Where: - -- `value` is the floating-point number. - -Examples: - -```javascript -Rounding up a positive float: -math.Ceil(2.3) // Evaluates to 3 - -Rounding up a negative float: -math.Ceil(-2.3) // Evaluates to -2 - -Using an integer: -math.Ceil(5) // Evaluates to 5 -``` ---- - -### math.Floor - -The `math.Floor` function returns the largest integer less than or equal to the provided float. - -Syntax: - - math.Floor(value) - -Where: - -- `value` is the floating-point number. - -Examples: - - Rounding down a positive float: - math.Floor(2.7) // Evaluates to 2 - - Rounding down a negative float: - math.Floor(-2.7) // Evaluates to -3 - - Using an integer: - math.Floor(5) // Evaluates to 5 ---- - -### math.Round - -The `math.Round` function rounds the provided float to the nearest integer. - -Syntax: - - math.Round(value) - -Where: - -- `value` is the floating-point number. - -Examples: - - Rounding a positive float: - math.Round(2.5) // Evaluates to 3 - - Rounding a negative float: - math.Round(-2.5) // Evaluates to -3 - - Using an integer: - math.Round(5) // Evaluates to 5 ---- - - -## Regexp - - -### regexp.Find - -The `regexp.Find` function in CEL is used to find the first occurrence of a pattern within a string. It returns the matched substring or an error if the pattern is invalid. - -Syntax: - - regexp.Find(pattern, input) - -Where: - -- `pattern` is the regular expression pattern you're looking for. -- `input` is the string you're searching within. - -Examples: - - Finding a pattern within a string: - regexp.Find("llo", "hello") // Evaluates to "llo" - - Searching for digits within a string: - regexp.Find("\\d+", "abc123def") // Evaluates to "123" - - Pattern not found in the string: - regexp.Find("xyz", "hello") // Evaluates to "" ---- - -### regexp.FindAll - -The `regexp.FindAll` function in CEL retrieves all occurrences of a pattern within a string, up to a specified count. It returns a list of matched substrings or an error if the pattern is invalid. - -Syntax: - - regexp.FindAll(pattern, count, input) - -Where: - -- `pattern` is the regular expression pattern to find. -- `count` is the maximum number of occurrences to return. -- `input` is the string to search within. - -Examples: - - Finding all occurrences of a pattern: - regexp.FindAll("a.", -1, "banana") // Evaluates to ["ba", "na", "na"] - - Limiting the number of matches: - regexp.FindAll("\\d", 2, "12345") // Evaluates to ["1", "2"] - - Pattern not found: - regexp.FindAll("z", -1, "hello") // Evaluates to [] ---- - -### regexp.Match - -The `regexp.Match` function in CEL checks if a string matches a given regular expression pattern. It returns a boolean value indicating the match status. - -Syntax: - - regexp.Match(pattern, input) - -Where: - -- `pattern` is the regular expression pattern to match. -- `input` is the string to check. - -Examples: - - Checking if a string matches a pattern: - regexp.Match("^h.llo", "hello") // Evaluates to true - - Pattern does not match the string: - regexp.Match("^b", "apple") // Evaluates to false - - Matching digits in a string: - regexp.Match("\\d+", "abc123") // Evaluates to true ---- - -### regexp.QuoteMeta - -The `regexp.QuoteMeta` function in CEL quotes all regular expression metacharacters inside a string. It returns the quoted string. - -Syntax: - - regexp.QuoteMeta(input) - -Where: - -- `input` is the string containing metacharacters to be quoted. - -Examples: - - Quoting metacharacters in a string: - regexp.QuoteMeta("a.b") // Evaluates to "a\\.b" - - String without metacharacters: - regexp.QuoteMeta("abc") // Evaluates to "abc" - - Quoting a complex pattern: - regexp.QuoteMeta("[a-z].*") // Evaluates to "\\[a\\-z\\]\\.\\*" ---- - -### regexp.Replace - -The `regexp.Replace` function in CEL replaces occurrences of a pattern within a string with a specified replacement string. It returns the modified string. - -Syntax: - - regexp.Replace(pattern, replacement, input) - -Where: - -- `pattern` is the regular expression pattern to replace. -- `replacement` is the string to replace the pattern with. -- `input` is the original string. - -Examples: - - Replacing a pattern in a string: - regexp.Replace("a.", "x", "banana") // Evaluates to "bxnxna" - - Pattern not found: - regexp.Replace("z", "x", "apple") // Evaluates to "apple" - - Replacing digits: - regexp.Replace("\\d+", "num", "abc123") // Evaluates to "abcnum" ---- - -### regexp.ReplaceLiteral - -The `regexp.ReplaceLiteral` function in CEL replaces occurrences of a pattern within a string with a specified replacement string, without interpreting the pattern as a regular expression. It returns the modified string or an error if the pattern is invalid. - -Syntax: - - regexp.ReplaceLiteral(pattern, replacement, input) - -Where: - -- `pattern` is the substring to replace. -- `replacement` is the string to replace the pattern with. -- `input` is the original string. - -Examples: - - Replacing a substring: - regexp.ReplaceLiteral("apple", "orange", "apple pie") // Evaluates to "orange pie" - - Substring not found: - regexp.ReplaceLiteral("z", "x", "apple") // Evaluates to "apple" - - Replacing a pattern without regex interpretation: - regexp.ReplaceLiteral("a.", "x", "a.b c.d") // Evaluates to "x.b c.d" - ---- - -### regexp.Split - -The `regexp.Split` function in CEL splits a string into a slice of substrings separated by a pattern. It returns the slice of strings or an error if the pattern is invalid. - -Syntax: - - regexp.Split(pattern, count, input) - -Where: - -- `pattern` is the regular expression pattern that separates the substrings. -- `count` is the maximum number of splits. Use -1 for no limit. -- `input` is the string to split. - -Examples: - - Splitting a string by a pattern: - regexp.Split("a.", -1, "banana") // Evaluates to ["", "n", "n"] - - Limiting the number of splits: - regexp.Split("\\s", 2, "apple pie is delicious") // Evaluates to ["apple", "pie is delicious"] - - Pattern not found: - regexp.Split("z", -1, "hello") // Evaluates to ["hello"] ---- - diff --git a/mission-control/docs/reference/scripting/functions.md b/mission-control/docs/reference/scripting/functions.md deleted file mode 100644 index c99f9c88..00000000 --- a/mission-control/docs/reference/scripting/functions.md +++ /dev/null @@ -1,73 +0,0 @@ -Functions in scripts are a combination of gomplate and sprig - - - -| Function | Description | Lang | -| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| `len` | | `gotemplate` | -| `index` | Returns the referenced element of an array/slice, string, or map | `gotemplate` | -| `and` (&&), `or` ( | | ), `not` (!), eq` (==), `lt` (<) `le`, (<=) `gt` (>), `ge` (>=) | Equality operators | `gotemplate` | -| `print`, `printf`, `println` | Aliases for Go’s [`fmt.Print`](https://golang.org/pkg/fmt/#Print), [`fmt.Printf`](https://golang.org/pkg/fmt/#Printf), and [`fmt.Println`](https://golang.org/pkg/fmt/#Println) functions | | -| [ternary](https://docs.gomplate.ca/functions/test/#testternary) | Returns one of two values depending on whether the third is true. | | -| `humanizeBytes` | Returns a human readable value for bytes .e.g. `1mb` | | -| `humanizeTime` | | | -| `humanizeDuration` | | | -| [`base64.encode`](https://docs.gomplate.ca/functions/base64/#base64encode) | | | -| [`base64.decode`](https://docs.gomplate.ca/functions/base64/#base64decode) | | | -| [`strings.Abbrev`](https://docs.gomplate.ca/functions/strings/#stringsabbrev) | | | -| [`strings.Contains`](https://docs.gomplate.ca/functions/strings/#stringscontains) | | | -| [`strings.HasPrefix`](https://docs.gomplate.ca/functions/strings/#stringshasprefix) | | | -| [`strings.HasSuffix`](https://docs.gomplate.ca/functions/strings/#stringshassuffix) | | | -| [`strings.Indent`](https://docs.gomplate.ca/functions/strings/#stringsindent) | | | -| [`strings.SkipLines`](https://docs.gomplate.ca/functions/strings/#stringsskiplines) | | | -| [`strings.Split`](https://docs.gomplate.ca/functions/strings/#stringssplit) | | | -| [`strings.Quote`](https://docs.gomplate.ca/functions/strings/#stringsquote) | | | -| [`strings.Repeat`](https://docs.gomplate.ca/functions/strings/#stringsrepeat) | | | -| [`strings.ReplaceAll`](https://docs.gomplate.ca/functions/strings/#stringsreplaceall) | | | -| [`strings.Slug`](https://docs.gomplate.ca/functions/strings/#stringsslug) | | | -| [`strings.ShellQuote`](https://docs.gomplate.ca/functions/strings/#stringsshellquote) | | | -| [`strings.Title`](https://docs.gomplate.ca/functions/strings/#stringstitle) | | | -| [`strings.ToLower`](https://docs.gomplate.ca/functions/strings/#stringstolower) | | | -| [`strings.ToUpper`](https://docs.gomplate.ca/functions/strings/#stringstoupprt) | | | -| [`strings.Trim`](https://docs.gomplate.ca/functions/strings/#stringstrim) | | | -| [`strings.TrimPrefix`](https://docs.gomplate.ca/functions/strings/#stringstrimprefix) | | | -| [`strings.TrimSpace`](https://docs.gomplate.ca/functions/strings/#stringstrimspace) | | | -| | | | -| [`strings.TrimSuffix`](https://docs.gomplate.ca/functions/strings/#stringstrimsuffix) | | | -| [`strings.Trunc`](https://docs.gomplate.ca/functions/strings/#stringstrunc) | | | -| [`strings.CamelCase`](https://docs.gomplate.ca/functions/strings/#stringscamelcase) | | | -| [`strings.SnakeCase`](https://docs.gomplate.ca/functions/strings/#stringssnakecase) | | | -| [`strings.KebabCase`](https://docs.gomplate.ca/functions/strings/#stringskebabcase) | | | -| [`strings.WordWrap`](https://docs.gomplate.ca/functions/strings/#stringswordwrap) | | | -| [`strings.RuneCount`](https://docs.gomplate.ca/functions/strings/#stringsrunecount) | | | -| [`strings.KebabCase`](https://docs.gomplate.ca/functions/strings/#stringskebabcase) | | | -| [regexp.Find](https://docs.gomplate.ca/functions/regexp/#regexpfind) | Returns a string holding the text of the leftmost match in `input` of the regular expression `expression`. | | -| [regexp.FindAll](https://docs.gomplate.ca/functions/regexp/#regexpfindall) | Returns a list of all successive matches of the regular expression. | | -| [regexp.Match](https://docs.gomplate.ca/functions/regexp/#regexpmatch) | Returns `true` if a given regular expression matches a given input. | | -| [regexp.Replace](https://docs.gomplate.ca/functions/regexp/#regexpreplace) | Replaces matches of a regular expression with the replacement string. | | -| [regexp.Split](https://docs.gomplate.ca/functions/regexp/#regexpsplit) | Splits `input` into sub-strings, separated by the expression. | | -| | | | -| [json](https://docs.gomplate.ca/functions/data/#datajson) | Converts a JSON string into an object | | -| [jsonArray](https://docs.gomplate.ca/functions/data/#datajsonarray) | Converts a JSON string into a slice. Only works for JSON Arrays. | | -| [yaml](https://docs.gomplate.ca/functions/data/#datayaml) | Converts a YAML string into an object. | | -| [yamlArray](https://docs.gomplate.ca/functions/data/#datayamlarray) | Converts a YAML string into a slice. Only works for YAML Arrays. | | -| [toml](https://docs.gomplate.ca/functions/data/#datatoml) | Converts a [TOML](https://github.com/toml-lang/toml) document into an object. | | -| [csv](https://docs.gomplate.ca/functions/data/#datacsv) | Converts a CSV-format string into a 2-dimensional string array. | | -| [csvByRow](https://docs.gomplate.ca/functions/data/#datacsvbyrow) | Converts a CSV-format string into a slice of maps. | | -| [csvByColumn](https://docs.gomplate.ca/functions/data/#datacsvbycolumn) | Like [`csvByRow`](https://docs.gomplate.ca/functions/data/#csvByRow), except that the data is presented as a columnar (column-oriented) map. | | -| [toJSON](https://docs.gomplate.ca/functions/data/#datatojson) | Converts an object to a JSON document | | -| [toJSONPretty](https://docs.gomplate.ca/functions/data/#datatojsonpretty) | Converts an object to a pretty-printed (or *indented*) JSON document | | -| [toYAML](https://docs.gomplate.ca/functions/data/#datatoyaml) | Converts an object to a YAML document | | -| [toTOML](https://docs.gomplate.ca/functions/data/#datatotoml) | Converts an object to a [TOML](https://github.com/toml-lang/toml) document. | | -| [toCSV](https://docs.gomplate.ca/functions/data/#datatocsv) | Converts an object to a CSV document. The input object must be a 2-dimensional array of strings (a `[][]string`). | | -| [sha1](https://docs.gomplate.ca/functions/crypto/#cryptosha1-cryptosha224-cryptosha256-cryptosha384-cryptosha512-cryptosha512_224-cryptosha512_256) | Compute a checksum with a SHA-1 or SHA-2 algorithm as defined | | -| [time.Now](https://docs.gomplate.ca/functions/time/#timenow) | | | -| [time.Parse](https://docs.gomplate.ca/functions/time/#timeparse) | Parses a timestamp defined by the given layout | | -| [time.ParseDuration](https://docs.gomplate.ca/functions/time/#timeparseduration) | Parses a duration string. This wraps [`time.ParseDuration`](https://golang.org/pkg/time/#ParseDuration). | | -| [time.Since](https://docs.gomplate.ca/functions/time/#timesince) | Returns the time elapsed since a given tim | | -| [time.Unix](https://docs.gomplate.ca/functions/time/#timeunix) | Returns the local `Time` corresponding to the given Unix time | | -| [time.Until](https://docs.gomplate.ca/functions/time/#timeuntil) | Returns the duration until a given time. | | -| [uuid.V1](https://docs.gomplate.ca/functions/uuid/#uuidv1) | Create a version 1 UUID | | -| [uuid.V4](https://docs.gomplate.ca/functions/uuid/#uuidv4) | Create a version 4 UUID - this function consumes entropy | | -| | This function consumes entropy. | | - diff --git a/mission-control/docs/reference/scripting/gotemplate.md b/mission-control/docs/reference/scripting/gotemplate.md deleted file mode 100644 index 17cf5c0b..00000000 --- a/mission-control/docs/reference/scripting/gotemplate.md +++ /dev/null @@ -1,2203 +0,0 @@ -# Go Templates - -`template` expressions use the [Go Text Template](https://pkg.go.dev/text/template) library with some additional functions provided by the [gomplate](https://docs.gomplate.ca/) library. -In this example we get the current exchange rate: - -```yaml title="display-with-gotemplate.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-check -spec: - http: - - name: USD - url: https://api.frankfurter.app/latest?from=USD&to=GBP,EUR,ILS,ZAR - display: - template: "$1 = €{{.json.rates.EUR}}, £{{.json.rates.GBP}}, ₪{{.json.rates.ILS}}" -``` - - -## Encoding - -### Encode - -Encode data as a Base64 string. Specifically, this uses the standard Base64 encoding as defined in [RFC4648 §4](https://tools.ietf.org/html/rfc4648#section-4) (and _not_ the URL-safe encoding). - -```go -{{ base64.Encode "hello world" }} // aGVsbG8gd29ybGQ= -{{ "hello world" | base64.Encode }} // aGVsbG8gd29ybGQ= -``` - -### Decode - -Decode a Base64 string. This supports both standard ([RFC4648 §4](https://tools.ietf.org/html/rfc4648#section-4)) and URL-safe ([RFC4648 §5](https://tools.ietf.org/html/rfc4648#section-5)) encodings. - -This function outputs the data as a string, so it may not be appropriate for decoding binary data. Use [`base64.DecodeBytes`](#base64.DecodeBytes) -for binary data. - - - -```go -{{ base64.Decode "aGVsbG8gd29ybGQ=" }} // hello world -{{ "aGVsbG8gd29ybGQ=" | base64.Decode }} // hello world -``` - -##### Implementation Note -For the functions that return an array, a Go `[]interface{}` is returned, regardless of whether or not the input was a different type. - -## Collection - -### dict - -Dict is a convenience function that creates a map with string keys. Provide arguments as key/value pairs. If an odd number of arguments is provided, the last is used as the key, and an empty string is set as the value. - -All keys are converted to strings. - -This function is equivalent to [Sprig's `dict`](http://masterminds.github.io/sprig/dicts.html#dict) function, as used in [Helm templates](https://docs.helm.sh/chart_template_guide#template-functions-and-pipelines). - -For creating more complex maps, see [`data.JSON`](../data/#data-json) or [`data.YAML`](../data/#data-yaml). - -For creating arrays, see [`coll.Slice`](#coll-slice). - - - -```go -{{ coll.Dict "name" "Frank" "age" 42 | data.ToYAML }} - -// age: 42 -// name: Frank - -{{ dict 1 2 3 | toJSON }} // {"1":2,"3":""} - -``` -```go -{{ define "T1" }}Hello {{ .thing }}!{{ end -}} -{{ template "T1" (dict "thing" "world")}} -{{ template "T1" (dict "thing" "everybody")}} - -// Hello world! -// Hello everybody! - -``` - -### slice - -Creates a slice (like an array or list). Useful when needing to `range` over a bunch of variables. - - - -```go -{{ range slice "Bart" "Lisa" "Maggie" }}Hello, {{ . }}{{ end }} - -// Hello, Bart -// Hello, Lisa -// Hello, Maggie -``` - - -### has - -Reports whether a given object has a property with the given key, or whether a given array/slice contains the given value. Can be used with `if` to prevent the template from trying to access a non-existent property in an object. - - - -```go -{{ $l := slice "foo" "bar" "baz" }}there is {{ if has $l "bar" }}a{{else}}no{{end}} bar // there is a bar - -``` - -```go -{{ $o := dict "foo" "bar" "baz" "qux" }} -{{ if has $o "foo" }}{{ $o.foo }}{{ else }}THERE IS NO FOO{{ end }} // bar - -``` - - -### jsonpath - -Extracts portions of an input object or list using a [JSONPath][] expression. - -Any object or list may be used as input. The output depends somewhat on the expression; if multiple items are matched, an array is returned. - -JSONPath expressions can be validated at https://jsonpath.com - -[JSONPath]: https://goessner.net/articles/JsonPath - - -```go -{{ .books | jsonpath `$..works[?( @.edition_count > 400 )].title` }} // [Alice's Adventures in Wonderland Gulliver's Travels] - -``` - - -### jq - -Filters an input object or list using the [jq](https://stedolan.github.io/jq/) language, as implemented by [gojq](https://github.com/itchyny/gojq). - -Any JSON datatype may be used as input (NOTE: strings are not JSON-parsed but passed in as is). If the expression results in multiple items (no matter if streamed or as an array) they are wrapped in an array. Otherwise a single item is returned (even if resulting in an array with a single contained element). - -JQ filter expressions can be tested at https://jqplay.org/ - -See also: - -- [jq manual](https://stedolan.github.io/jq/manual/) -- [gojq differences to jq](https://github.com/itchyny/gojq#difference-to-jq) - - -Where books is from https://openlibrary.org/subjects/fantasy.json -```go -{{ .books | jq `[.works[]|{"title":.title,"authors":[.authors[].name],"published":.first_publish_year}][0]` }} - -// map[authors:[Lewis Carroll] published:1865 title:Alice's Adventures in Wonderland] - -``` - - -### Keys - -Return a list of keys in one or more maps. - -The keys will be ordered first by map position (if multiple maps are given), then alphabetically. - -See also [`coll.Values`](#coll-values). - - -```go -{{ coll.Keys (dict "foo" 1 "bar" 2) }} // [bar foo] - -``` - - -### Values - -Return a list of values in one or more maps. - -The values will be ordered first by map position (if multiple maps are given), then alphabetically by key. - -See also [`coll.Keys`](#coll-keys). - - - - -```go -{{ coll.Values (dict "foo" 1 "bar" 2) }} // [2 1] - -``` - - -### append - -Append a value to the end of a list. - -_Note that this function does not change the given list; it always produces a new one._ - - -```go -{{ slice 1 1 2 3 | append 5 }} // [1 1 2 3 5] -``` - - -### prepend - -Prepend a value to the beginning of a list. - -_Note that this function does not change the given list; it always produces a new one._ - - - -```go -{{ slice 4 3 2 1 | prepend 5 }} // [5 4 3 2 1] -``` - -### uniq - -Remove any duplicate values from the list, without changing order. - -_Note that this function does not change the given list; it always produces a new one._ - - - -```go -{{ slice 1 2 3 2 3 4 1 5 | uniq }} // [1 2 3 4 5] -``` - - -### flatten - -Flatten a nested list. Defaults to completely flattening all nested lists, but can be limited with `depth`. - -_Note that this function does not change the given list; it always produces a new one._ - - - -```go -{{ "[[1,2],[],[[3,4],[[[5],6],7]]]" | jsonArray | flatten }} // [1 2 3 4 5 6 7] -{{ coll.Flatten 2 ("[[1,2],[],[[3,4],[[[5],6],7]]]" | jsonArray) }} // [1 2 3 4 [[5] 6] 7] -``` - - -### reverse - -Reverse a list. - -_Note that this function does not change the given list; it always produces a new one._ - - - -```go -{{ slice 4 3 2 1 | reverse }} // [1 2 3 4] -``` - - -### Sort - -Sort a given list. Uses the natural sort order if possible. For inputs that are not sortable (either because the elements are of different types, or of an un-sortable type), the input will simply be returned, unmodified. - -Maps and structs can be sorted by a named key. - -_Note that this function does not modify the input._ - - -```go -{{ slice "foo" "bar" "baz" | coll.Sort }} // [bar baz foo] -``` -```go -{{ sort (slice 3 4 1 2 5) }} // [1 2 3 4 5] -``` - - -### Merge - -Merge maps together by overriding src with dst. In other words, the src map can be configured the "default" map, whereas the dst -map can be configured the "overrides". Many source maps can be provided. Precedence is in left-to-right order. - -_Note that this function does not modify the input._ - - -```go -{{ $default := dict "foo" 1 "bar" 2}} -{{ $config := dict "foo" 8 }} -{{ merge $config $default }} - -// map[bar:2 foo:8] -``` -```go -{{ $dst := dict "foo" 1 "bar" 2 }} -{{ $src1 := dict "foo" 8 "baz" 4 }} -{{ $src2 := dict "foo" 3 "bar" 5 }} -{{ coll.Merge $dst $src1 $src2 }} - -// map[foo:1 bar:5 baz:4] -``` - - -Given a map, returns a new map with any entries that have the given keys. - -All keys are converted to strings. - -This is the inverse of [`coll.Omit`](#coll-omit). - -_Note that this function does not modify the input._ - - -```go -{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} -{{ $pickedData := coll.Pick "foo" "baz" $data }} -{{ $pickedData }} - -// map[baz:3 foo:1] -``` - -Given a map, returns a new map without any entries that have the given keys. - -All keys are converted to strings. - -This is the inverse of [`coll.Pic`](#coll-pick). - -_Note that this function does not modify the input._ - - -```go -{{ $data := dict "foo" 1 "bar" 2 "baz" 3 }} -{{ $newData := coll.Omit "foo" "baz" $data }} -{{ $newData }} - -// map[bar:2] -``` - -## Convert - -### bool - -**Note:** See also [`conv.ToBool`](#conv-tobool) for a more flexible variant. - -Converts a true-ish string to a boolean. Can be used to simplify conditional statements based on environment variables or other text input. - - -```go -{{ $FOO := true }} -{{ if $FOO }}foo{{ else }}bar{{ end }} // foo -``` - -### default - -Provides a default value given an empty input. Empty inputs are `0` for numeric types, `""` for strings, `false` for booleans, empty arrays/maps, and `nil`. - -Note that this will not provide a default for the case where the input is undefined (i.e. referencing things like `.foo` where there is no `foo` field of `.`), but [`conv.Has`](#conv-has) can be used for that. - - - -```go -{{ "" | default "foo" }} // foo -{{ "bar" | default "baz" }} // bar -``` - -### Dict - -Dict is a convenience function that creates a map with string keys. Provide arguments as key/value pairs. If an odd number of arguments -is provided, the last is used as the key, and an empty string is set as the value. - -All keys are converted to strings. - -This function is equivalent to [Sprig's `dict`](http://masterminds.github.io/sprig/dicts.html#dict) function, as used in [Helm templates](https://docs.helm.sh/chart_template_guide#template-functions-and-pipelines). - -For creating more complex maps, see [`data.JSON`](../data/#data-json) or [`data.YAML`](../data/#data-yaml). - -For creating arrays, see [`conv.Slice`](#conv-slice). - - - -```go -{{ $dict := conv.Dict "name" "Frank" "age" 42 }} -{{ $yaml := data.ToYAML $dict }} -{{ $yaml }} - -// age: 42 -// name: Frank - -{{ dict 1 2 3 | toJSON }} // {"1":2,"3":""} -``` - -### slice - -Creates a slice (like an array or list). Useful when needing to `range` over a bunch of variables. - - - -```go -{{ range slice "Bart" "Lisa" "Maggie" }}Hello, {{ . }}{{ end }} -// Hello, Bart -// Hello, Lisa -// Hello, Maggie -``` - -### has - -Reports whether a given object has a property with the given key, or whether a given array/slice contains the given value. Can be used with `if` to prevent the template from trying to access a non-existent property in an object. - - - -```go -{{ $l := slice "foo" "bar" "baz" }}there is {{ if has $l "bar" }}a{{else}}no{{end}} bar // there is a bar -``` -```go -{{ $o := dict "foo" "bar" }} // Defining a map with keys and values -{{ if has $o "foo" }}{{ index $o "foo" }}{{ else }}THERE IS NO FOO{{ end }} // bar -``` -```go -{{ $o := dict "baz" "quix" }} -{{ if has $o "foo" }}{{ index $o "foo" }}{{ else }}THERE IS NO FOO{{ end }} // THERE IS NO FOO - -``` - - -### join - -Concatenates the elements of an array to create a string. The separator string `sep` is placed between elements in the resulting string. - - - -```go -{{ $a := slice 1 2 3 }}{{ join $a "-" }} // 1-2-3 -``` - - -### urlParse - -Parses a string as a URL for later use. Equivalent to [url.Parse](https://golang.org/pkg/net/url/#Parse) - -Any of `url.URL`'s methods can be called on the result. - -```go -{{ ($u := conv.URL "https://example.com:443/foo/bar").Host }} // example.com:443 -{{ (conv.URL "https://user:supersecret@example.com").Redacted }} // https://user:xxxxx@example.com -``` - -### ParseInt - -_**Note:**_ See [`conv.ToInt64`](#conv-toint64) instead for a simpler and more flexible variant of this function. - -Parses a string as an int64. Equivalent to [strconv.ParseInt](https://golang.org/pkg/strconv/#ParseInt) - - - -```go -{{ $hexVal := "7C0" }} {{/* Equivalent to 1984 in decimal */}} -{{ $val := int64 0 }} {{/* Initialize $val to ensure it's of the right type for ParseInt */}} -{{- $val = conv.ParseInt $hexVal 16 32 -}} -The value in decimal is {{ $val }} - -// The value in decimal is 1984 -``` - -### ParseFloat - -_**Note:**_ See [`conv.ToFloat`](#conv-tofloat) instead for a simpler and more flexible variant of this function. - -Parses a string as an float64 for later use. Equivalent to [strconv.ParseFloat](https://golang.org/pkg/strconv/#ParseFloat) - - - -```go -{{ $pi := "3.14159265359" }} -{{ $piFloat := conv.ParseFloat $pi 64 }} -{{- if gt $piFloat 3.0 -}} -pi is greater than 3 -{{- end }} - -// pi is greater than 3 -``` - -### ParseUint - -Parses a string as an uint64 for later use. Equivalent to [strconv.ParseUint](https://golang.org/pkg/strconv/#ParseUint) - - - -```go -{{ $BIG := "FFFFFFFFFFFFFFFF" }} -{{ $maxInt64 := conv.ParseInt $BIG 16 64 }} is max int64 // 9223372036854775807 is max int64 -{{ $maxUint64 := conv.ParseUint $BIG 16 64 }} is max uint64 // 18446744073709551615 is max uint64 - -``` - -### ToBool - -Converts the input to a boolean value. Possible `true` values are: `1` or the strings `"t"`, `"true"`, or `"yes"` (any capitalizations). All other values are considered `false`. - -```go -{{ conv.ToBool "yes" }} {{ conv.ToBool true }} {{ conv.ToBool "0x01" }} // true true true -{{ conv.ToBool false }} {{ conv.ToBool "blah" }} {{ conv.ToBool 0 }} // false false false -``` - -### ToBools - -Converts a list of inputs to an array of boolean values. Possible `true` values are: `1` or the strings `"t"`, `"true"`, or `"yes"` (any capitalizations). All other values are considered `false`. - - -```go -{{ conv.ToBools "yes" true "0x01" }} // [true true true] -{{ conv.ToBools false "blah" 0 }} // [false false false] -``` - -### ToInt64 - -Converts the input to an `int64` (64-bit signed integer). - -This function attempts to convert most types of input (strings, numbers, and booleans), but behaviour when the input can not be converted is undefined and subject to change. Unconvertable inputs may result in errors, or `0` or `-1`. - -Floating-point numbers (with decimal points) are truncated. - - - -```go -{{conv.ToInt64 "9223372036854775807"}} // 9223372036854775807 -{{conv.ToInt64 "0x42"}} // 66 -{{conv.ToInt64 true }} // 1 -``` - -### ToInt - -Converts the input to an `int` (signed integer, 32- or 64-bit depending on platform). This is similar to [`conv.ToInt64`](#conv-toint64) on 64-bit platforms, but is useful when input to another function must be provided as an `int`. - -On 32-bit systems, given a number that is too large to fit in an `int`, the result is `-1`. This is done to protect against -[CWE-190](https://cwe.mitre.org/data/definitions/190.html) and [CWE-681](https://cwe.mitre.org/data/definitions/681.html). - -See also [`conv.ToInt64`](#conv-toint64). - - - -```go -{{conv.ToInt "9223372036854775807"}} // 9223372036854775807 -{{conv.ToInt "0x42"}} // 66 -{{conv.ToInt true }} // 1 -``` - -### ToInt64s - -Converts the inputs to an array of `int64`s. - -This delegates to [`conv.ToInt64`](#conv-toint64) for each input argument. - - - -```go -{{ conv.ToInt64s true 0x42 "123,456.99" "1.2345e+3"}} // [1 66 123456 1234] -``` - -### ToInts - -Converts the inputs to an array of `int`s. - -This delegates to [`conv.ToInt`](#conv-toint) for each input argument. - - - -```go -{{ conv.ToInts true 0x42 "123,456.99" "1.2345e+3"}} // [1 66 123456 1234] -``` - -### ToFloat64 - -Converts the input to a `float64`. - -This function attempts to convert most types of input (strings, numbers, and booleans), but behaviour when the input can not be converted is undefined and subject to change. Unconvertable inputs may result in errors, or `0` or `-1`. - - - -```go -{{ conv.ToFloat64 "8.233e-1"}} // 0.8233 -{{ conv.ToFloat64 "9,000.09"}} // 9000.09 -``` - -### ToFloat64s - -Converts the inputs to an array of `float64`s. - -This delegates to [`conv.ToFloat64`](#conv-tofloat64) for each input argument. - - - -```go -{{ conv.ToFloat64s true 0x42 "123,456.99" "1.2345e+3"}} // [1 66 123456.99 1234.5] -``` - -### ToString - -Converts the input (of any type) to a `string`. - -The input will always be represented in _some_ way. - - - -```go -{{ conv.ToString 0xFF }} // 255 -{{ dict "foo" "bar" | conv.ToString}} // map[foo:bar] -{{ conv.ToString nil }} // nil -``` - -### ToStrings - -Converts the inputs (of any type) to an array of `string`s - -This delegates to [`conv.ToString`](#conv-tostring) for each input argument. - - - -```go -{{ conv.ToStrings nil 42 true 0xF (slice 1 2 3) }} // [nil 42 true 15 [1 2 3]] -``` - - -## Cryptography - -### crypto.SHA1 - - -Compute a checksum with a SHA-1 or SHA-2 algorithm as defined in [RFC 3174](https://tools.ietf.org/html/rfc3174) (SHA-1) and [FIPS 180-4](http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf) (SHA-2). - -These functions output the binary result as a hexadecimal string. - -_Warning: SHA-1 is cryptographically broken and should not be used for secure applications._ - - -```go -{{ crypto.SHA1 "foo" }} // f1d2d2f924e986ac86fdf7b36c94bcdf32beec15 -{{ crypto.SHA512 "bar" }} // cc06808cbbee0510331aa97974132e8dc296aeb795be229d064bae784b0a87a5cf4281d82e8c99271b75db2148f08a026c1a60ed9cabdb8cac6d24242dac4063 -``` - - -## Data - -### json - -Converts a JSON string into an object. Works for JSON Objects, but will also parse JSON Arrays. Will not parse other valid JSON types. - -For more explict JSON Array support, see [`data.JSONArray`](#data-jsonarray). - - -```go -{{ ('{"hello":"world"}' | json).hello }} // world -``` - - -### jsonArray - -Converts a JSON string into a slice. Only works for JSON Arrays. - - -```go -{{ ('[ "you", "world" ]' | jsonArray) 1 }} // world -``` - - -### yaml - -Converts a YAML string into an object. Works for YAML Objects but will also parse YAML Arrays. This can be used to access properties of YAML objects. - -For more explict YAML Array support, see [`data.JSONArray`](#data-yamlarray). - - -```go -{{ $FOO := "hello: world" }} -Hello {{ (yaml $FOO).hello }} // Hello world -``` - - -### yamlArray - -Converts a YAML string into a slice. Only works for YAML Arrays. - -```go -{{ $FOO := "hello: world" }} -Hello {{ (yaml $FOO).hello }} // Hello world -``` - - -### toml - -Converts a [TOML](https://github.com/toml-lang/toml) document into an object. This can be used to access properties of TOML documents. - -```go -{{ $t := `[data] -hello = "world"` }} -Hello {{ (toml $t).data.hello }} //Hello world -``` - - -### csv - -Converts a CSV-format string into a 2-dimensional string array. - -By default, the [RFC 4180](https://tools.ietf.org/html/rfc4180) format is supported, but any single-character delimiter can be specified. - - -``` -{{ $c := `C,32 -Go,25 -COBOL,357` }} -{{ range ($c | csv) }} -{{ index . 0 }} has {{ index . 1 }} keywords. -{{ end }} -``` - -```go -C has 32 keywords. -Go has 25 keywords. -COBOL has 357 keywords. -``` - -### csvByRow - -Converts a CSV-format string into a slice of maps. - -By default, the [RFC 4180](https://tools.ietf.org/html/rfc4180) format is supported, but any single-character delimiter can be specified. - -Also by default, the first line of the string will be assumed to be the header, but this can be overridden by providing an explicit header, or auto-indexing can be used. - -``` -{{ $c := `lang,keywords -C,32 -Go,25 -COBOL,357` }} -{{ range ($c | csvByRow) }} -{{ .lang }} has {{ .keywords }} keywords. -{{ end }} -``` - -```go -C has 32 keywords. -Go has 25 keywords. -COBOL has 357 keywords. -``` - - -### csvByColumn - -Like [`csvByRow`](#csvByRow), except that the data is presented as a columnar (column-oriented) map. - - -``` -{{ $c := `C;32 -Go;25 -COBOL;357` }} -{{ $langs := ($c | csvByColumn ";" "lang,keywords").lang }} -{{ range $langs }} -{{ . }} -{{ end }} - -``` - -```go -C -Go -COBOL -``` - - -### toJSON - -Converts an object to a JSON document. Input objects may be the result of `json`, `yaml`, `jsonArray`, or `yamlArray` functions, or they could be provided by a `datasource`. - - - -```go -{{ (`{"foo":{"hello":"world"}}` | json).foo | toJSON }} // {"hello":"world"} -``` - - - -### toJSONPretty - -Converts an object to a pretty-printed (or _indented_) JSON document. Input objects may be the result of functions like `data.JSON`, `data.YAML`, `data.JSONArray`, or `data.YAMLArray` functions, or they could be provided by a [`datasource`](../general/datasource). - -The indent string must be provided as an argument. - -```go -{{ `{"hello":"world"}` | data.JSON | data.ToJSONPretty " " }} -``` - -```go -{ - "hello": "world" -} -``` - -### toYAML - -Converts an object to a YAML document. Input objects may be the result of `data.JSON`, `data.YAML`, `data.JSONArray`, or `data.YAMLArray` functions, or they could be provided by a [`datasource`](../general/datasource). - - - -_This is obviously contrived - `data.JSON` is used to create an object._ - - -```go -{{ (`{"foo":{"hello":"world"}}` | data.JSON).foo | data.ToYAML }} // hello: world -``` - - -### toTOML - -Converts an object to a [TOML](https://github.com/toml-lang/toml) document. - - - -```go -{{ `{"foo":"bar"}` | data.JSON | data.ToTOML }} // foo = "bar" -``` - - -### toCSV - -Converts an object to a CSV document. The input object must be a 2-dimensional array of strings (a `[][]string`). Objects produced by [`data.CSVByRow`](#conv-csvbyrow) and [`data.CSVByColumn`](#conv-csvbycolumn) cannot yet be converted back to CSV documents. - -**Note:** With the exception that a custom delimiter can be used, `data.ToCSV` outputs according to the [RFC 4180](https://tools.ietf.org/html/rfc4180) format, which means that line terminators are `CRLF` (Windows format, or `\r\n`). If you require `LF` (UNIX format, or `\n`), the output can be piped through [`strings.ReplaceAll`](../strings/#strings-replaceall) to replace `"\r\n"` with `"\n"`. - - -```go -{{ $rows := (jsonArray `[["first","second"],["1","2"],["3","4"]]`) -}} -{{ data.ToCSV ";" $rows }} -``` - -```go -first,second -1,2 -3,4 -``` - - - -## filepath - -### Base - -Returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns `.`. If the path consists entirely of separators, Base returns a single separator. - -A wrapper for Go's [`filepath.Base`](https://golang.org/pkg/path/filepath/#Base) function. - - - -```go -{{ filepath.Base "/tmp/foo" }} // foo -``` - -### Clean - -Clean returns the shortest path name equivalent to path by purely lexical processing. - -A wrapper for Go's [`filepath.Clean`](https://golang.org/pkg/path/filepath/#Clean) function. - - - -```go -{{ filepath.Clean "/tmp//foo/../" }} // /tmp -``` - -### Dir - -Returns all but the last element of path, typically the path's directory. - -A wrapper for Go's [`filepath.Dir`](https://golang.org/pkg/path/filepath/#Dir) function. - - - -```go -{{ filepath.Dir "/tmp/foo" }} // /tmp -``` - -### Ext - -Returns the file name extension used by path. - -A wrapper for Go's [`filepath.Ext`](https://golang.org/pkg/path/filepath/#Ext) function. - - - -```go -{{ filepath.Ext "/tmp/foo.csv" }} // .csv -``` - -### FromSlash - -Returns the result of replacing each slash (`/`) character in the path with the platform's separator character. - -A wrapper for Go's [`filepath.FromSlash`](https://golang.org/pkg/path/filepath/#FromSlash) function. - - - -```go -{{ filepath.FromSlash "/foo/bar" }} // /foo/bar -``` - -### IsAbs - -Reports whether the path is absolute. - -A wrapper for Go's [`filepath.IsAbs`](https://golang.org/pkg/path/filepath/#IsAbs) function. - - - -```go -{{ (filepath.IsAbs "/tmp/foo.csv") }} // true -``` - -### Join - -Joins any number of path elements into a single path, adding a separator if necessary. - -A wrapper for Go's [`filepath.Join`](https://golang.org/pkg/path/filepath/#Join) function. - - - -```go -{{ filepath.Join "/tmp" "foo" "bar" }} // /tmp/foo/bar -``` - -### Match - -Reports whether name matches the shell file name pattern. - -A wrapper for Go's [`filepath.Match`](https://golang.org/pkg/path/filepath/#Match) function. - - - -```go -{{ filepath.Match "*.csv" "foo.csv" }} // true -``` - -### Rel - -Returns a relative path that is lexically equivalent to targetpath when joined to basepath with an intervening separator. - -A wrapper for Go's [`filepath.Rel`](https://golang.org/pkg/path/filepath/#Rel) function. - - - -```go -{{ filepath.Rel "/a" "/a/b/c" }} // b/c -``` - -### Split - -Splits path immediately following the final path separator, separating it into a directory and file name component. - -The function returns an array with two values, the first being the diretory, and the second the file. - -A wrapper for Go's [`filepath.Split`](https://golang.org/pkg/path/filepath/#Split) function. - - -```go -{{ $p := filepath.Split "/tmp/foo" }}{{ $dir := index $p 0 }}{{ $file := index $p 1 }}dir is {{$dir}}, file is {{$file}} // dir is /tmp/, file is foo -``` - -### ToSlash - -Returns the result of replacing each separator character in path with a slash (`/`) character. - -A wrapper for Go's [`filepath.ToSlash`](https://golang.org/pkg/path/filepath/#ToSlash) function. - - -```go -{{ filepath.ToSlash "/foo/bar" }} // /foo/bar -``` - -### VolumeName - -Returns the leading volume name. Given `C:\foo\bar` it returns `C:` on Windows. Given a UNC like `\\host\share\foo` it returns `\\host\share`. On other platforms it returns an empty string. - -A wrapper for Go's [`filepath.VolumeName`](https://golang.org/pkg/path/filepath/#VolumeName) function. - - - -```go -{{ filepath.VolumeName "C:/foo/bar" }} // C: -{{ filepath.VolumeName "/foo/bar" }} // -``` - - - -## math - -Returns the absolute value of a given number. When the input is an integer, the result will be an `int64`, otherwise it will be a `float64`. - - - -```go -{{ math.Abs -3.5 }} {{ math.Abs 3.5 }} {{ math.Abs -42 }} // 3.5 3.5 42 -``` - - -### Add - -Adds all given operators. When one of the inputs is a floating-point number, the result will be a `float64`, otherwise it will be an `int64`. - - - -```go -{{ math.Add 1 2 3 4 }} {{ math.Add 1.5 2 3 }} // 10 6.5 -``` - -### Ceil - -Returns the least integer value greater than or equal to a given floating-point number. This wraps Go's [`math.Ceil`](https://golang.org/pkg/math/#Ceil). - -**Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. - - - -```go -{{ range (slice 5.1 42 "3.14" "0xFF" "NaN" "Inf" "-0") }}ceil {{ printf "%#v" . }} = {{ math.Ceil . }}{{"\n"}}{{ end }} - -// ceil 5.1 = 6 -// ceil 42 = 42 -// ceil "3.14" = 4 -// ceil "0xFF" = 255 -// ceil "NaN" = NaN -// ceil "Inf" = +Inf -// ceil "-0" = 0 -``` - - -### Div - -Divide the first number by the second. Division by zero is disallowed. The result will be a `float64`. - - - -```go -{{ math.Div 8 2 }} {{ math.Div 3 2 }} // 4 1.5 -``` - -### Floor - -Returns the greatest integer value less than or equal to a given floating-point number. This wraps Go's [`math.Floor`](https://golang.org/pkg/math/#Floor). - -**Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. - - - -```go -{{ range (slice 5.1 42 "3.14" "0xFF" "NaN" "Inf" "-0") }}floor {{ printf "%#v" . }} = {{ math.Floor . }}{{"\n"}}{{ end }} - -// floor 5.1 = 4 -// floor 42 = 42 -// floor "3.14" = 3 -// floor "0xFF" = 255 -// floor "NaN" = NaN -// floor "Inf" = +Inf -// floor "-0" = 0 -``` - -### IsFloat - -Returns whether or not the given number can be interpreted as a floating-point literal, as defined by the [Go language reference](https://golang.org/ref/spec#Floating-point_literals). - -**Note:** If a decimal point is part of the input number, it will be considered a floating-point number, even if the decimal is `0`. - - - -```go -{{ range (slice 1.0 "-1.0" 5.1 42 "3.14" "foo" "0xFF" "NaN" "Inf" "-0") }}{{ if (math.IsFloat .) }}{{.}} is a float{{"\n"}}{{ end }}{{end}} - -// 1 is a float -// -1.0 is a float -// 5.1 is a float -// 3.14 is a float -// NaN is a float -// Inf is a float -``` - -### IsInt - -Returns whether or not the given number is an integer. - - - -```go -{{ range (slice 1.0 "-1.0" 5.1 42 "3.14" "foo" "0xFF" "NaN" "Inf" "-0") }}{{ if (math.IsInt .) }}{{.}} is an integer{{"\n"}}{{ end }}{{end}} - -// 42 is an integer -// 0xFF is an integer -// -0 is an integer -``` - -### IsNum - -Returns whether the given input is a number. Useful for `if` conditions. - - - -```go -{{ math.IsNum "foo" }} // false -{{ math.IsNum 0xDeadBeef }} // true -``` - -### Max - -Returns the largest number provided. If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. The same special-cases as Go's [`math.Max`](https://golang.org/pkg/math/#Max) are followed. - - - -```go -{{ math.Max 0 8.0 4.5 "-1.5e-11" }} // 8 -``` - -### Min - -Returns the smallest number provided. If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. The same special-cases as Go's [`math.Min`](https://golang.org/pkg/math/#Min) are followed. - - - -```go -{{ math.Min 0 8 4.5 "-1.5e-11" }} // -1.5e-11 -``` - - -### Mul - -Multiply all given operators together. - - - -```go -{{ math.Mul 8 8 2 }} // 128 -``` - - -### Pow - -Calculate an exponent - _bn_. This wraps Go's [`math.Pow`](https://golang.org/pkg/math/#Pow). If any values are floating-point numbers, a `float64` is returned, otherwise an `int64` is returned. - - - -```go -{{ math.Pow 10 2 }} // 100 -{{ math.Pow 2 32 }} // 4294967296 -{{ math.Pow 1.5 2 }} // 2.2 -``` - - -### Rem - -Return the remainder from an integer division operation. - - -```go -{{ math.Rem 5 3 }} // 2 -{{ math.Rem -5 3 }} // -2 -``` - -### Round - -Returns the nearest integer, rounding half away from zero. - -**Note:** the return value of this function is a `float64` so that the special-cases `NaN` and `Inf` can be returned appropriately. - - - -```go -{{ range (slice -6.5 5.1 42.9 "3.5" 6.5) }}round {{ printf "%#v" . }} = {{ math.Round . }}{{"\n"}}{{ end }} - - // round -6.5 = -7 -// round 5.1 = 5 -// round 42.9 = 43 -// round "3.5" = 4 -// round 6.5 = 7 -``` - -### Seq - -Return a sequence from `start` to `end`, in steps of `step`. Can handle counting down as well as up, including with negative numbers. -Note that the sequence _may_ not end at `end`, if `end` is not divisible by `step`. - - - -```go -{{ range (math.Seq 5) }}{{.}} {{end}} // 1 2 3 4 5 -{{ conv.Join (math.Seq 10 -3 2) ", " }} // 10, 8, 6, 4, 2, 0, -2 -``` - -### Sub - -Subtract the second from the first of the given operators. When one of the inputs is a floating-point number, the result will be a `float64`, otherwise it will be an `int64`. - - -```go -{{ math.Sub 3 1 }} // 2 -``` - -## Path -### Base - -Returns the last element of path. Trailing slashes are removed before extracting the last element. If the path is empty, Base returns `.`. If the path consists entirely of slashes, Base returns `/`. - -A wrapper for Go's [`path.Base`](https://golang.org/pkg/path/#Base) function. - - - -```go -{{ path.Base "/tmp/foo" }} // foo -``` - -### Clean - -Clean returns the shortest path name equivalent to path by purely lexical processing. - -A wrapper for Go's [`path.Clean`](https://golang.org/pkg/path/#Clean) function. - - - -```go -{{ path.Clean "/tmp//foo/../" }} // /tmp -``` - -### Dir - -Returns all but the last element of path, typically the path's directory. - -A wrapper for Go's [`path.Dir`](https://golang.org/pkg/path/#Dir) function. - - - -```go -{{ path.Dir "/tmp/foo" }} // /tmp -``` - -### Ext - -Returns the file name extension used by path. - - -```go -{{ path.Ext "/tmp/foo.csv" }} // .csv -``` - -### IsAbs - -Reports whether the path is absolute. - -A wrapper for Go's [`path.IsAbs`](https://golang.org/pkg/path/#IsAbs) function. - - -```go -{{ (path.IsAbs "/tmp/foo.csv") }} // true -{{ (path.IsAbs "../foo.csv") }} // false -``` - -### Join - -Joins any number of path elements into a single path, adding a separating slash if necessary. - -A wrapper for Go's [`path.Join`](https://golang.org/pkg/path/#Join) function. - - - -```go -{{ path.Join "/tmp" "foo" "bar" }} // /tmp/foo/bar -``` - -### Match - -Reports whether name matches the shell file name pattern. - -A wrapper for Go's [`path.Match`](https://golang.org/pkg/path/#Match) function. - - - -```go -{{ path.Match "*.csv" "foo.csv" }} // true -``` - -### Split - -Splits path immediately following the final slash, separating it into a directory and file name component. - -The function returns an array with two values, the first being the directory, and the second the file. - -A wrapper for Go's [`path.Split`](https://golang.org/pkg/path/#Split) function. - - -```go -{{ index (path.Split "/tmp/foo") }} // tmp -``` - -## Random -### ASCII - -Generates a random string of a desired length, containing the set of printable characters from the 7-bit [ASCII](https://en.wikipedia.org/wiki/ASCII) set. This includes _space_ (' '), but no other whitespace characters. - - - -```go -{{ random.ASCII 8 }} // _woJ%D&K -``` - -### Alpha - -Generates a random alphabetical (`A-Z`, `a-z`) string of a desired length. - - - -```go -{{ random.Alpha 42 }} // oAqHKxHiytYicMxTMGHnUnAfltPVZDhFkVkgDvatJK -``` - -### AlphaNum - -Generates a random alphanumeric (`0-9`, `A-Z`, `a-z`) string of a desired length. - - - -```go -{{ random.AlphaNum 16 }} // 4olRl9mRmVp1nqSm -``` - -### String - -Generates a random string of a desired length. - -By default, the possible characters are those represented by the regular expression `[a-zA-Z0-9_.-]` (alphanumeric, plus `_`, `.`, and `-`). - -A different set of characters can be specified with a regular expression, or by giving a range of possible characters by specifying the lower and upper bounds. Lower/upper bounds can be specified as characters (e.g. `"q"`, or escape sequences such as `"\U0001f0AF"`), or numeric Unicode code-points (e.g. `48` or `0x30` for the character `0`). - -When given a range of Unicode code-points, `random.String` will discard non-printable characters from the selection. This may result in a much smaller set of possible characters than intended, so check the [Unicode character code charts](http://www.unicode.org/charts/) to verify the correct code-points. - - - -```go -{{ random.String 8 }} // FODZ01u_ -{{ random.String 16 `[[:xdigit:]]` }} // B9e0527C3e45E1f3 -{{ random.String 20 `[\p{Canadian_Aboriginal}]` }} // ᗄᖖᣡᕔᕫᗝᖴᒙᗌᘔᓰᖫᗵᐕᗵᙔᗠᓅᕎᔹ -{{ random.String 8 "c" "m" }} // ffmidgjc -``` - -### Item - -Pick an element at a random from a given slice or array. - - - -```go -{{ random.Item (seq 0 5) }} // 4 -{{'["red", "green", "blue"]' | jsonArray | random.Item }} // blue -``` - -### Number - -Pick a random integer. By default, a number between `0` and `100` (inclusive) is chosen, but this range can be overridden. - -Note that the difference between `min` and `max` can not be larger than a 63-bit integer (i.e. the unsigned portion of a 64-bit signed integer). The result is given as an `int64`. - - - -```go -{{ random.Number }} // 55 -{{ random.Number -10 10 }} // -3 -{{ random.Number 5 }} // 2 -``` - -### Float - -Pick a random decimal floating-point number. By default, a number between `0.0` and `1.0` (_exclusive_, i.e. `[0.0,1.0)`) is chosen, but this range can be overridden. - -The result is given as a `float64`. - - - -```go -{{ random.Float }} // 0.2029946480303966 -{{ random.Float 100 }} // 71.28595374161743 -{{ random.Float -100 200 }} // 105.59119437834909 -``` - -## regexp -### Find - -Returns a string holding the text of the leftmost match in `input` of the regular expression `expression`. - -This function provides the same behaviour as Go's -[`regexp.FindString`](https://golang.org/pkg/regexp/#Regexp.FindString) function. - - - -```go -{{ regexp.Find "[a-z]{3}" "foobar"}} // foo - -no {{ "will not match" | regexp.Find "[0-9]" }}numbers // no numbers -``` - -### FindAll - -Returns a list of all successive matches of the regular expression. - -This can be called with 2 or 3 arguments. When called with 2 arguments, the `n` argument (number of matches) will be set to `-1`, causing all matches to be returned. - -This function provides the same behaviour as Go's -[`regexp.FindAllString`](https://golang.org/pkg/regexp/#Regexp.FindAllString) function. - - -```go -{{ regexp.FindAll "[a-z]{3}" "foobar" | toJSON}} // ["foo", "bar"] - -{{ "foo bar baz qux" | regexp.FindAll "[a-z]{3}" 3 | toJSON}} // ["foo", "bar", "baz"] -``` - -### Match - -Returns `true` if a given regular expression matches a given input. - -This returns a boolean which can be used in an `if` condition, for example. - - - -```go -{{ "hairyhenderson"| regexp.Match `^h`) }} // true -``` - -### QuoteMeta - -Escapes all regular expression metacharacters in the input. The returned string is a regular expression matching the literal text. - -This function provides the same behaviour as Go's -[`regexp.QuoteMeta`](https://golang.org/pkg/regexp/#Regexp.QuoteMeta) function. - - - -```go -{{ `{hello}` | regexp.QuoteMeta }} // \{hello\} -``` - -### Replace - -Replaces matches of a regular expression with the replacement string. - -The replacement is substituted after expanding variables beginning with `$`. - -This function provides the same behaviour as Go's [`regexp.ReplaceAllString`](https://golang.org/pkg/regexp/#Regexp.ReplaceAllString) function. - - -```go -{{ regexp.Replace "(foo)bar" "$1" "foobar"}} // foo -{{ regexp.Replace "(?P[a-zA-Z]+) (?P[a-zA-Z]+)" "${last}, ${first}" "Alan Turing"}} // Turing, Alan -``` - -### ReplaceLiteral - -Replaces matches of a regular expression with the replacement string. - -The replacement is substituted directly, without expanding variables -beginning with `$`. - -This function provides the same behaviour as Go's [`regexp.ReplaceAllLiteralString`](https://golang.org/pkg/regexp/#Regexp.ReplaceAllLiteralString) function. - - -```go -{{ regexp.ReplaceLiteral "(foo)bar" "$1" "foobar"}} // $1 - -{{ `foo.bar,baz` | regexp.ReplaceLiteral `\W` `$` }} // foo$bar$baz -``` - -### Split - -Splits `input` into sub-strings, separated by the expression. - -This can be called with 2 or 3 arguments. When called with 2 arguments, the `n` argument (number of matches) will be set to `-1`, causing all sub-strings to be returned. - -This is equivalent to [`strings.SplitN`](../strings/#strings-splitn), except that regular expressions are supported. - -This function provides the same behaviour as Go's [`regexp.Split`](https://golang.org/pkg/regexp/#Regexp.Split) function. - -```go -{{ regexp.Split `[\s,.]` "foo bar,baz.qux" | toJSON}} // ["foo","bar","baz","qux"] -{{ "foo bar.baz,qux" | regexp.Split `[\s,.]` 3 | toJSON}} // ["foo","bar","baz"] -``` - - -## Strings - - -### Abbrev - -Abbreviates a string using `...` (ellipses). Takes an optional offset from the beginning of the string, and a maximum final width (including added ellipses). - -_Also see [`strings.Trunc`](#strings-trunc)._ - - - -```go -{{ "foobarbazquxquux" | strings.Abbrev 9 }} // foobar... -{{ "foobarbazquxquux" | strings.Abbrev 6 9 }} // ...baz... -``` - -### Contains - -Reports whether a substring is contained within a string. - - -```go -{{ "foo" | strings.Contains "f" }} // true -``` - - -### HasPrefix - -Tests whether a string begins with a certain prefix. - - -```go -{{ "http://example.com" | strings.HasSuffix "http://")}} // true -``` - -### HasSuffix - -Tests whether a string ends with a certain suffix. - - - -```go -{{if not ("http://example.com" | strings.HasSuffix ":80")}}:80{{end}} // :80 -``` - -```go -http://example.com:80 -``` - - -### Indent - -Indents a string. If the input string has multiple lines, each line will be indented. - - -This function can be especially useful when adding YAML snippets into other YAML documents, where indentation is important: - - -``` -foo: -{{ `{"bar": {"baz": 2}}` | json | toYAML | strings.Indent " " }} -{{- `{"qux": true}` | json | toYAML | strings.Indent " " }} - quux: -{{ `{"quuz": 42}` | json | toYAML | strings.Indent " " -}} -``` - -``` -//output -foo: - bar: - baz: 2 - qux: true - quux: - quuz: 42 -``` - -### Sort _(deprecated)_ -**Deprecation Notice:** Use [`coll.Sort`](../coll/#coll-sort) instead - -Returns an alphanumerically-sorted copy of a given string list. - - - -```go -{{ (slice "foo" "bar" "baz") | strings.Sort }} // [bar baz foo] -``` - -### Split - -Creates a slice by splitting a string on a given delimiter. - - -Use on its own to produce an array: -```go -{{ "Bart,Lisa,Maggie" | strings.Split "," }} // [Bart Lisa Maggie] -``` - -Use in combination with `range` to iterate over all items: -```go -{{range ("Bart,Lisa,Maggie" | strings.Split ",") }}Hello, {{.}}{{end}} -// Hello, Bart -// Hello, Lisa -// Hello, Maggie -``` - -Use in combination with `index` function to pick a specific value from the resulting array -```go -{{index ("Bart,Lisa,Maggie" | strings.Split ",") 0 }} // Bart -``` - - -### SplitN - -Creates a slice by splitting a string on a given delimiter. The count determines the number of substrings to return. - -```go -{{ range ("foo:bar:baz" | strings.SplitN ":" 2) }}{{.}}{{end}} -// foo -// bar:baz -``` - - -### Quote - -Surrounds an input string with double-quote characters (`"`). If the input is not a string, converts first. `"` characters in the input are first escaped with a `\` character. - - -```go -{{ "in" | quote }} // "in" -{{ strings.Quote 500 }} // "500" -``` - -### Repeat - -Returns a new string consisting of `count` copies of the input string. - -It errors if `count` is negative or if the length of `input` multiplied by `count` overflows. - -This wraps Go's [`strings.Repeat`](https://golang.org/pkg/strings/#Repeat). - - - -```go -{{ "hello " | strings.Repeat 5 }} // hello hello hello hello hello -``` - - -### ReplaceAll - -Replaces all occurrences of a given string with another. - -```go -{{ strings.ReplaceAll "." "-" "172.21.1.42" }} // 172-21-1-42 -{{ "172.21.1.42" | strings.ReplaceAll "." "-" }} // 172-21-1-42 -``` - -### Slug - -Creates a a "slug" from a given string - supports Unicode correctly. This wraps the [github.com/gosimple/slug](https://github.com/gosimple/slug) package. See [the github.com/gosimple/slug docs](https://godoc.org/github.com/gosimple/slug) for more information. - - -```go -{{ "Hello, world!" | strings.Slug }} // hello-world -``` - -### ShellQuote - -Given a string, emits a version of that string that will evaluate to its literal data when expanded by any POSIX-compliant shell. -Given an array or slice, emit a single string which will evaluate to a series of shell words, one per item in that array or slice. - - -```go -{{ slice "one word" "foo='bar baz'" | shellQuote }} -// 'one word' 'foo='"'"'bar baz'"'"'' -``` -```go -{{ strings.ShellQuote "it's a banana" }} -// 'it'"'"'s a banana' -``` - - -### squote - -Surrounds an input string with a single-quote (apostrophe) character (`'`). If the input is not a string, converts first. - -`'` characters in the input are first escaped in the YAML-style (by repetition: `''`). - -```go -{{ "in" | squote }} // 'in' -{{ "it's a banana" | squote }} // 'it''s a banana' -``` - - -### Title - -Convert to title-case. - -```go -{{strings.Title "hello, world!"}} // Hello, World! -``` - -### ToLower - -Convert to lower-case. - -```go -{{strings.ToLower "HELLO, WORLD!"}} // hello, world! -``` - -### ToUpper - -Convert to upper-case. - -```go -{{strings.ToUpper "hello, world!"}} // HELLO, WORLD! -``` - -### Trim - -Trims a string by removing the given characters from the beginning and end of -the string. - -```go -{{ "_-foo-_" | strings.Trim "_-" }} //foo -``` - -### TrimPrefix - -Returns a string without the provided leading prefix string, if the prefix is present. - -This wraps Go's [`strings.TrimPrefix`](https://golang.org/pkg/strings/#TrimPrefix). - - -```go -{{ "hello, world" | strings.TrimPrefix "hello, " }} // world -``` - - -### TrimSpace - -Trims a string by removing whitespace from the beginning and end of -the string. - - -```go -{{ " \n\t foo" | strings.TrimSpace }} // foo -``` - -### TrimSuffix - -Returns a string without the provided trailing suffix string, if the suffix is present. - -This wraps Go's [`strings.TrimSuffix`](https://golang.org/pkg/strings/#TrimSuffix). - -```go -{{ "hello, world" | strings.TrimSuffix "world" }}jello // hello, jello -``` - -### Trunc - -Returns a string truncated to the given length. - -_Also see [`strings.Abbrev`](#strings-abbrev)._ - - -```go -{{ "hello, world" | strings.Trunc 5 }} // hello -``` - -### CamelCase - -Converts a sentence to CamelCase, i.e. `The quick brown fox` becomes `TheQuickBrownFox`. - -All non-alphanumeric characters are stripped, and the beginnings of words are upper-cased. If the input begins with a lower-case letter, the result will also begin with a lower-case letter. - -See [CamelCase on Wikipedia](https://en.wikipedia.org/wiki/Camel_case) for more details. - - -```go -{{ "Hello, World!" | strings.CamelCase }} // HelloWorld - -{{ "hello jello" | strings.CamelCase }} // helloJello -``` - -### SnakeCase - -Converts a sentence to snake_case, i.e. `The quick brown fox` becomes `The_quick_brown_fox`. - -All non-alphanumeric characters are stripped, and spaces are replaced with an underscore (`_`). If the input begins with a lower-case letter, the result will also begin with a lower-case letter. - -See [Snake Case on Wikipedia](https://en.wikipedia.org/wiki/Snake_case) for more details. - - - -```go -{{ "Hello, World!" | strings.SnakeCase }} // Hello_world -{{ "hello jello" | strings.SnakeCase }} // hello_jello -``` - -### KebabCase - -Converts a sentence to kebab-case, i.e. `The quick brown fox` becomes `The-quick-brown-fox`. All non-alphanumeric characters are stripped, and spaces are replaced with a hyphen (`-`). If the input begins with a lower-case letter, the result will also begin with a lower-case letter. -See [Kebab Case on Wikipedia](https://en.wikipedia.org/wiki/Kebab_case) for more details. - - - -```go -{{ "Hello, World!" | strings.KebabCase }} // Hello-world -{{ "hello jello" | strings.KebabCase }} // hello-jello -``` - -### WordWrap - -Inserts new line breaks into the input string so it ends up with lines that are at most `width` characters wide. The line-breaking algorithm is _naïve_ and _greedy_: lines are only broken between words (i.e. on whitespace characters), and no effort is made to "smooth" the line endings. When words that are longer than the desired width are encountered (e.g. long URLs), they are not broken up. Correctness is valued above line length. - -The line-break sequence defaults to `\n` (i.e. the LF/Line Feed character), regardless of OS. - - -```go -{{ "Hello, World!" | strings.WordWrap 7 }} // Hello, -World! -``` -```go -{{ strings.WordWrap 20 "\\\n" "a string with a long url http://example.com/a/very/long/url which should not be broken" }} // a string with a long -url -http://example.com/a/very/long/url -which should not be -broken -``` - -### RuneCount - -Return the number of _runes_ (Unicode code-points) contained within the input. This is similar to the built-in `len` function, but `len` counts the length in _bytes_. The length of an input containing multi-byte code-points should therefore be measured with `strings.RuneCount`. - -Inputs will first be converted to strings, and multiple inputs are concatenated. - -This wraps Go's [`utf8.RuneCountInString`](https://golang.org/pkg/unicode/utf8/#RuneCountInString) function. - - -```go -{{ range (slice "\u03a9" "\u0030" "\u1430") }}{{ printf "%s is %d bytes and %d runes\n" . (len .) (strings.RuneCount .) }}{{ end }} -// Ω is 2 bytes and 1 runes -// 0 is 1 bytes and 1 runes -// ᐰ is 3 bytes and 1 runes -``` - -### contains - -**See [`strings.Contains`](#strings-contains) for a pipeline-compatible version** - -Contains reports whether the second string is contained within the first. Equivalent to [strings.Contains](https://golang.org/pkg/strings#Contains) - - -```go -{{ $FOO := "foo" }} -{{ if contains $FOO "f" }}yes{{ else }}no{{ end }} // yes -``` - -### HasPrefix - -**See [`strings.HasPrefix`](#strings-hasprefix) for a pipeline-compatible version** - -Tests whether the string begins with a certain substring. Equivalent to [strings.HasPrefix](https://golang.org/pkg/strings#HasPrefix) - - - - -```go -{{ $URL := "http://example.com" }} -{{ if hasPrefix $URL "https" }}foo{{ else }}bar{{ end }} // bar -``` - -### HasSuffix - -**See [`strings.HasSuffix`](#strings-hassuffix) for a pipeline-compatible version** - -Tests whether the string ends with a certain substring. Equivalent to [strings.HasSuffix](https://golang.org/pkg/strings#HasSuffix) - - - - -```go -{{ $URL := "http://example.com" }} -{{ $URL }}{{ if not (hasSuffix $URL ":80") }}:80{{ end }} // http://example.com:80 -``` - -### split - -**See [`strings.Split`](#strings-split) for a pipeline-compatible version** - -Creates a slice by splitting a string on a given delimiter. Equivalent to [strings.Split](https://golang.org/pkg/strings#Split) - - - -```go -{{ range split "Bart,Lisa,Maggie" "," }} -Hello, {{ . }} -{{ end }} - -// Hello, Bart -// Hello, Lisa -// Hello, Maggie -``` - -### splitN - -**See [`strings.SplitN`](#strings-splitn) for a pipeline-compatible version** - -Creates a slice by splitting a string on a given delimiter. The count determines the number of substrings to return. Equivalent to [strings.SplitN](https://golang.org/pkg/strings#SplitN) - - -```go -{{ range splitN "foo:bar:baz" ":" 2 }} -{{ . }} -{{ end }} - -// foo -// bar:baz -``` - -### Trim - -**See [`strings.Trim`](#strings-trim) for a pipeline-compatible version** - -Trims a string by removing the given characters from the beginning and end of the string. Equivalent to [strings.Trim](https://golang.org/pkg/strings/#Trim) - -```go -{{trim " world " " "}} // world -``` - -## Test - -### Fail - -Cause template generation to fail immediately, with an optional message. - -```go -{{ fail }} // template: :1:3: executing "" at : error calling fail: template generation failed -{{ test.Fail "something is wrong!" }} // template: :1:7: executing "" at : error calling Fail: template generation failed: something is wrong! -``` - -### IsKind - -Report whether the argument is of the given Kind. Can be used to render different templates depending on the kind of data. - -See [the Go `reflect` source code](https://github.com/golang/go/blob/36fcde1676a0d3863cb5f295eed6938cd782fcbb/src/reflect/type.go#L595..L622) for the complete list, but these are some common values: - -- `string` -- `bool` -- `int`, `int64`, `uint64` -- `float64` -- `slice` -- `map` -- `invalid` (a catch-all, usually just `nil` values) - -In addition, the special kind `number` is accepted by this function, to represent _any_ numeric kind (whether `float32`, `uint8`, or whatever). This is useful when the specific numeric type is unknown. - -See also [`test.Kind`](test-kind). - - -```go -{{ $data := "hello world" }} -{{ if isKind "string" $data }}{{ $data }} is a string{{ end }} - -// hello world is a string -``` -```go -{{ $object := dict "key1" true "key2" "foobar" }} -{{ if test.IsKind "map" $object }} -Got a map: -{{ range $key, $value := $object }} - - "{{ $key }}": {{ $value }} -{{ end }} -{{ else if test.IsKind "number" $object }} -Got a number: {{ $object }} -{{ end }} - -// Got a map: -// - "key1": true -// - "key2": foobar -``` - -### Kind - -Report the _kind_ of the given argument. This differs from the _type_ of the argument in specificity; for example, while a slice of strings may have a type of `[]string`, the _kind_ of that slice will simply be `slice`. -If you need to know the precise type of a value, use `printf "%T" $value`. - -See also [`test.IsKind`](test-iskind). - - - -```go -{{ kind "hello world" }} // string -{{ dict "key1" true "key2" "foobar" | test.Kind }} // map -``` - - - -### ternary - -Returns one of two values depending on whether the third is true. Note that the third value does not have to be a boolean - it is converted first by the [`conv.ToBool`](../conv/#conv-tobool) function (values like `true`, `1`, `"true"`, `"Yes"`, etc... are considered true). - -This is effectively a short-form of the following template: - -``` -{{ if conv.ToBool $condition }}{{ $truevalue }}{{ else }}{{ $falsevalue }}{{ end }} -``` - -Keep in mind that using an explicit `if`/`else` block is often easier to understand than ternary expressions! - - - -```go -{{ ternary "FOO" "BAR" false }} // BAR -{{ ternary "FOO" "BAR" "yes" }} // FOO -``` - -## Time -### Now - -Returns the current local time, as a `time.Time`. This wraps [`time.Now`](https://golang.org/pkg/time/#Now). - -Usually, further functions are called using the value returned by `Now`. - -Usage with [`UTC`](https://golang.org/pkg/time/#Time.UTC) and [`Format`](https://golang.org/pkg/time/#Time.Format): - -```go -{{ (time.Now).UTC.Format "Day 2 of month 1 in year 2006 (timezone MST)" }} // Day 14 of month 10 in year 2017 (timezone UTC) -``` - -Usage with [`AddDate`](https://golang.org/pkg/time/#Time.AddDate): - -```go -$ date -Sat Oct 14 09:57:02 EDT 2017 -{{ ((time.Now).AddDate 0 1 0).Format "Mon Jan 2 15:04:05 MST 2006" }} // Tue Nov 14 09:57:02 EST 2017 -``` - -_(notice how the TZ adjusted for daylight savings!)_ -Usage with [`IsDST`](https://golang.org/pkg/time/#Time.IsDST): - -```go -{{ $t := time.Now }}At the tone, the time will be {{ ($t.Round (time.Minute 1)).Add (time.Minute 1) }}. -It is{{ if not $t.IsDST }} not{{ end }} daylight savings time. -... ... BEEP - -// At the tone, the time will be 2022-02-10 09:01:00 -0500 EST. -// It is not daylight savings time. -// ... ... BEEP -``` - -### Parse - -Parses a timestamp defined by the given layout. This wraps [`time.Parse`](https://golang.org/pkg/time/#Parse). - -A number of pre-defined layouts are provided as constants, defined -[here](https://golang.org/pkg/time/#pkg-constants). - -Just like [`time.Now`](#time-now), this is usually used in conjunction with other functions. - -_Note: In the absence of a time zone indicator, `time.Parse` returns a time in UTC._ - - -Usage with [`Format`](https://golang.org/pkg/time/#Time.Format): - -```go -{{ (time.Parse "2006-01-02" "1993-10-23").Format "Monday January 2, 2006 MST" }} // Saturday October 23, 1993 UTC -``` - -### ParseDuration - -Parses a duration string. This wraps [`time.ParseDuration`](https://golang.org/pkg/time/#ParseDuration). - -A duration string is a possibly signed sequence of decimal numbers, each with -optional fraction and a unit suffix, such as `300ms`, `-1.5h` or `2h45m`. Valid -time units are `ns`, `us` (or `µs`), `ms`, `s`, `m`, `h`. - - - -```go -{{ (time.Now).Format time.Kitchen }} // 12:43AM -{{ ((time.Now).Add (time.ParseDuration "2h30m")).Format time.Kitchen }} // 3:13AM -``` - -### ParseLocal - -Same as [`time.Parse`](#time-parse), except that in the absence of a time zone indicator, the timestamp wil be parsed in the local timezone. - - -Usage with [`Format`](https://golang.org/pkg/time/#Time.Format): - -```go -{{ (time.ParseLocal time.Kitchen "6:00AM").Format "15:04 MST" }} // 06:00 EST -``` - -### ParseInLocation - -Same as [`time.Parse`](#time-parse), except that the time is parsed in the given location's time zone. - -This wraps [`time.ParseInLocation`](https://golang.org/pkg/time/#ParseInLocation). - - - -Usage with [`Format`](https://golang.org/pkg/time/#Time.Format): -```go -{{ (time.ParseInLocation time.Kitchen "Africa/Luanda" "6:00AM").Format "15:04 MST" }} // 06:00 LMT -``` - -### Since - -Returns the time elapsed since a given time. This wraps [`time.Since`](https://golang.org/pkg/time/#Since). - -It is shorthand for `time.Now.Sub t`. - -```go -{{ $t := time.Parse time.RFC3339 "1970-01-01T00:00:00Z" }}time since the epoch:{{ time.Since $t }} // 423365h0m24.353828924s -``` - -### Unix - -Returns the local `Time` corresponding to the given Unix time, in seconds since January 1, 1970 UTC. Note that fractional seconds can be used to denote milliseconds, but must be specified as a string, not a floating point number. - - -_with whole seconds:_ -```go -{{ (time.Unix 42).UTC.Format time.Stamp}} // Jan 1, 00:00:42 -``` - -_with fractional seconds:_ -```go -{{ (time.Unix "123456.789").UTC.Format time.StampMilli}} // Jan 2 10:17:36.789 -``` - -### Until - -Returns the duration until a given time. This wraps [`time.Until`](https://golang.org/pkg/time/#Until). - -It is shorthand for `$t.Sub time.Now`. - -```go -{{ $t := time.Parse time.RFC3339 "2020-01-01T00:00:00Z" }}only {{ time.Until $t }} to go... // only 14922h56m46.578625891s to go... -``` - -Or, less precise: -```go -{{ $t := time.Parse time.RFC3339 "2020-01-01T00:00:00Z" }}only {{ (time.Until $t).Round (time.Hour 1) }} to go... // only 14923h0m0s to go... -``` - -### ZoneName - -Return the local system's time zone's name. - - - -```go -{{time.ZoneName}} // EDT -``` - -### ZoneOffset - -Return the local system's time zone offset, in seconds east of UTC. - - - -```go -{{time.ZoneOffset}} // -14400 -``` - -## UUID -### V1 - -Create a version 1 UUID (based on the current MAC address and the current date/time). - -Use [`uuid.V4`](#uuid-v4) instead in most cases. - - - -```go -{{ uuid.V1 }} // 4d757e54-446d-11e9-a8fa-72000877c7b0 -``` - -### V4 - -Create a version 4 UUID (randomly generated). - -This function consumes entropy. - - - -```go -{{ uuid.V4 }} // 40b3c2d2-e491-4b19-94cd-461e6fa35a60 -``` - -### Nil - -Returns the _nil_ UUID, that is, `00000000-0000-0000-0000-000000000000`, -mostly for testing scenarios. - - - -```go -{{ uuid.Nil }} // 00000000-0000-0000-0000-000000000000 -``` - -### IsValid - -Checks that the given UUID is in the correct format. It does not validate whether the version or variant are correct. - - -```go -{{ if uuid.IsValid "totally invalid" }}valid{{ else }}invalid{{ end }} // invalid -{{ uuid.IsValid "urn:uuid:12345678-90ab-cdef-fedc-ba9876543210" }} // true -``` - -### Parse - -Parse a UUID for further manipulation or inspection. - -This function returns a `UUID` struct, as defined in the [github.com/google/uuid](https://godoc.org/github.com/google/uuid#UUID) package. See the docs for examples of functions or fields you can call. - -Both the standard UUID forms of `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` and `urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` are decoded as well as the Microsoft encoding `{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}` and the raw hex encoding (`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`). - - -```go -{{ $u := uuid.Parse uuid.V4 }}{{ $u.Version }}, {{ $u.Variant}} // VERSION_4, RFC4122 -{{ (uuid.Parse "000001f5-4470-21e9-9b00-72000877c7b0").Domain }} // Person -``` diff --git a/mission-control/docs/reference/scripting/javascript.md b/mission-control/docs/reference/scripting/javascript.md deleted file mode 100644 index 629fa6a9..00000000 --- a/mission-control/docs/reference/scripting/javascript.md +++ /dev/null @@ -1,55 +0,0 @@ -# Javascript - -`javascript` expressions use to the [otto](https://github.com/robertkrimen/otto) Javascript VM - -```yaml title="display-with-javascript.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-check -spec: - http: - - name: USD - url: https://api.frankfurter.app/latest?from=USD&to=GBP,EUR,ILS - display: - javascript: | - currencyCodes = { "EUR": "€", "GBP": "£", "ILS": "₪"} - display = "" - for (var currency in json.rates) { - if (display != "") { - display += ", " - } - display += currency + " = " + currencyCodes[currency] + json.rates[currency] + ", " - } - "$1 = " + display -```` - - - -:::tip Troubleshooting -You can print to the console for rapid development e.g. `console.log(JSON.stringify(json))`, this will only be shown in the logs -::: - -### Underscore - - -The [underscore](https://underscorejs.org/) library is automatically imported so you can do the following: - -```yaml title="display-format-with-underscore.yaml" -apiVersion: canaries.flanksource.com/v1 -kind: Canary -metadata: - name: http-check -spec: - http: - - name: USD - url: https://api.frankfurter.app/latest?from=USD&to=GBP,EUR,ILS - display: - javascript: | - currencyCodes = { "EUR": "€", "GBP": "£", "ILS": "₪"} - "$1 = " + _.map(json.rates, function(rate, currency) { - return currencyCodes[currency] + rate; - }).join(", "); -``` - -## \ No newline at end of file diff --git a/mission-control/docs/reference/scripting/overview.md b/mission-control/docs/reference/scripting/overview.md deleted file mode 100644 index 7e288b35..00000000 --- a/mission-control/docs/reference/scripting/overview.md +++ /dev/null @@ -1,7 +0,0 @@ -# Scripting - -Canary checker is a fully scriptable platforms, scripts can be used in multiple places including: - -1. To `test` the result of a check to see if it is healthy -2. To `display` info / error messages based on the result of a check -3. To `transform` responses into multiple individual checks