duckscript/docs/sdk.md
sagie gur ari abe5d7538b release
2024-01-19 07:58:20 +00:00

139 KiB

Table of Contents

std::Echo

echo [arg]*

The echo command will printout all provided arguments.
After all input is done, an end of line will be printed as well.

Parameters

Any number of arguments may be provided and will be printed.

Return Value

The amount of arguments printed.

Examples

# Print multiple arguments:
echo hello world

# Print multiple spaces between words
echo "hello    world"

Aliases:

echo

std::Eval

eval command arguments

The eval command enables to run dynamically created commands.
The command and arguments passed can be variables in the form of ${name}.

Parameters

Any number of arguments which will construct a line to evaluate and execute.

Return Value

The result of the evaluated line.

Examples

command = set echo
eval ${command} hello world

Aliases:

eval

std::IsCommandDefined

var = is_command_defined key

Returns true if the provided command name exists.

Parameters

The command name.

Return Value

True if the command exists.

Examples

exists = is_command_defined exec

Aliases:

is_command_defined

std::Noop

noop

Empty function that does nothing and returns none.

Parameters

All parameters are ignored

Return Value

None

Examples

noop

Aliases:

noop

std::Not

output = not [command|value|condition]

Enables to switch falsy to true and truthy to false.
The not commands accept either:

  • A command with optional arguments and invokes it
  • A single value which doesn't match any known command
  • A condition statement

If the result is one of the following:

  • No output
  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

It will return true, otherwise it will return false.

A condition statement is made up of values, or/and keywords and '('/')' groups.
Each must be separated with a space character.

Parameters

A command and its arguments to invoke and evaluate its output, if a single value is provided an no such command exists, it is evaluated as a value.

Return Value

The switched value of the input.

Examples

fn test_not_true
    value = not true

    assert_false ${value}
end

fn test_not_false
    value = not false

    assert ${value}
end

fn test_not_command_true
    value = not set true

    assert_false ${value}
end

fn test_not_command_false
    value = not set false

    assert ${value}
end

fn test_not_condition_true
    value = not true and false or true and false or ( true and true or false )

    assert_false ${value}
end

fn test_not_condition_false
    value = not true and false or true and false or ( true and true or false ) and false

    assert ${value}
end

Aliases:

not

std::Print

print [--style|-s bold|underline|italic|dimmed|blink|strikethrough]* [--color|-c black|red|green|yellow|blue|magenta|cyan|white|bright_<color>|rgb_<red>_<green>_<blue>] [--background-color|-bgc black|red|green|yellow|blue|magenta|cyan|white|bright_<color>|rgb_<red>_<green>_<blue>] [arg]*

The print command will printout all provided arguments with optional color values.
No end of line will be added.
The style will continue to additional printouts until an echo/println is used to close the line.
Not all colors and all styles are supported on every terminal.

Parameters

  • Optional styles - To support multiple styles, add the option as much as needed.
  • Optional color - The text color. For RGB, use the rgb_ prefix with the values separated by a _ character.
  • Optional background color (also supports rgb_ prefix)
  • Any number of arguments may be provided and will be printed.

Return Value

The amount of arguments printed.

Examples

# Print multiple arguments:
print hello world

# Print multiple spaces between words
print "hello    world"

# Print with style/color values
print --style underline --color red My Bold Red Text
echo
print -s underline -s bold -c bright_green -bgc red Hello World
echo

Aliases:

print

std::Println

println [--style|-s bold|underline|italic|dimmed|blink|strikethrough]* [--color|-c black|red|green|yellow|blue|magenta|cyan|white|bright_<color>|rgb_<red>_<green>_<blue>] [--background-color|-bgc black|red|green|yellow|blue|magenta|cyan|white|bright_<color>|rgb_<red>_<green>_<blue>] [arg]*

The println command will printout all provided arguments with optional color values.
Not all colors and all styles are supported on every terminal.

Parameters

  • Optional styles - To support multiple styles, add the option as much as needed.
  • Optional color - The text color. For RGB, use the rgb_ prefix with the values separated by a _ character.
  • Optional background color (also supports rgb_ prefix)
  • Any number of arguments may be provided and will be printed.

Return Value

The amount of arguments printed.

Examples

# Print multiple arguments:
println hello world

# Print multiple spaces between words
println "hello    world"

# Print with style/color values
println --style underline --color red My Bold Red Text
println -s underline -s bold -c bright_green -bgc red Hello World

Aliases:

println

std::ReadUserInput

var = read

Reads the user input into the output variable.
If the user didn't insert any input, none will be returned.

Parameters

None

Return Value

The user input or none if no input was entered.

Examples

echo Enter Full Name:
name = read

if is_empty ${name}
    echo You didn't enter any value
else
    echo Your name is: ${name}
end

Aliases:

read

std::Release

release [-r|--recursive] handle

Releases an internal handle stored in the runtime memory.
Certain commands (such as array) will create a handle and the variable will only hold a reference to that handle.
In order to release those handles once they are no longer needed, the release command should be used.
By providing the recursive flag, it will also go over the data values (array items, map values, set keys, ...) and release each one of them as well if they are handles to other arrays/maps/sets/...

Parameters

  • Optional recursive (-r/--recursive) flag (default false)
  • The handle name.

Return Value

  • true - If a handle was found and removed
  • false - If no handle was found

Examples

release ${array_handle}

Aliases:

release

std::ShowCommandDocumentation

var = man command

Prints and returns the help documentation of the provided command.

Parameters

The command name.

Return Value

The help documentation or if not found, none.

Examples

man set

Aliases:

man

std::collections

The collections module contains commands which enable to interact with different data models such as arrays, sets and maps.

  • Arrays are simple ordered list of items
  • Sets are unordered unique collection of items
  • Maps are key/value (dictionary) structure where the keys are unique

Access to these data structures are done via handles.
Handles are provided by the data structure creation command (such as: array, range, map, set) and are used in all other commands to read/modify those data structures.
Once done with a specific data structure, you must release it via release command to prevent any memory leaks.

std::collections::Array

handle = array value1 value2 value3 ...

Creates an array from the input arguments and returns a handle to that array.
This handle can be passed to other commands which support arrays using handles.
Once the array is no longer used, it should be released using the release command.

Parameters

Any number of arguments which will construct the array.

Return Value

A handle to the array.

Examples

handle = array ${var} "hello world" 5 ${another_var}

# once done we should release the handle
release ${handle}

Aliases:

array

std::collections::ArrayClear

result = array_clear handle

Clears the provided array.

Parameters

The array handle.

Return Value

True if successful.

Examples

handle = array

result = array_push ${handle} 1

result = array_is_empty ${handle}
assert_false ${result}

result array_clear ${handle}
assert ${result}

result = array_is_empty ${handle}
assert ${result}

release ${handle}

Aliases:

array_clear

std::collections::ArrayConcat

handle = array_concat [handle]*

Concats all provided arrays and returns a handle to a new array with all items.

Parameters

Any number of array handles.

Return Value

A handle to the new array.

Examples

input1 = range 1 4
input2 = range 4 6
input3 = range 6 8

# new array will contain values from 1-7
arr = array_concat ${input1} ${input2} ${input3}

Source:

Show Source

for scope::array_concat::arg in ${scope::array_concat::arguments}
    if not is_array ${scope::array_concat::arg}
        trigger_error "Invalid input, non array handle or array not found."
    end
end

scope::array_concat::array = array

for scope::array_concat::arg in ${scope::array_concat::arguments}
    for scope::array_concat::item in ${scope::array_concat::arg}
        array_push ${scope::array_concat::array} ${scope::array_concat::item}
    end
end

set ${scope::array_concat::array}

Aliases:

array_concat

std::collections::ArrayContains

var = array_contains handle value

Returns the first index of the array with the same value as provided.
If not found, false will be returned.

Parameters

  • The array handle.
  • The value

Return Value

The value index in the array or false if not found.

Examples

handle = array value1 value2 value3
index = array_contains ${handle} value2

Source:

Show Source

scope::array_contains::index = set false
scope::array_contains::value = set ${scope::array_contains::argument::2}

scope::array_contains::counter = set 0
for scope::array_contains::next_value in ${scope::array_contains::argument::1}
    scope::array_contains::found = equals ${scope::array_contains::next_value} ${scope::array_contains::value}

    if ${scope::array_contains::found}
        scope::array_contains::index = set ${scope::array_contains::counter}
        scope::array_contains::argument::1 = set
    end

    scope::array_contains::counter = calc ${scope::array_contains::counter} + 1
end

set ${scope::array_contains::index}

Aliases:

array_contains

std::collections::ArrayGet

var = array_get handle index

Returns the element from the array at a given index or none if the index is bigger than the array length.

Parameters

  • The array handle.
  • The element index.

Return Value

The element at the given index from the array or none.

Examples

handle = array 1 2 3
element = array_get ${handle} 2
assert_eq ${element} 3

Aliases:

array_get

std::collections::ArrayIsEmpty

var = array_is_empty handle

Returns true if the provided array handle is an empty array.

Parameters

The array handle.

Return Value

True if the provided handle belongs to an empty array.

Examples

values = array
out = array_is_empty ${values}

Source:

Show Source

scope::array_is_empty::length = array_length ${scope::array_is_empty::argument::1}
equals 0 ${scope::array_is_empty::length}

Aliases:

array_is_empty

std::collections::ArrayJoin

var = array_join handle separator

Joins all values in the provided array with the provided separator in between each value.

Parameters

  • An array handle
  • The separator to put between each item pair

Return Value

The joined string value

Examples

function test_to_string
    arr = array hello world
    string = array_join ${arr} ", "

    release ${arr}

    assert_eq ${string} "hello, world"
end

function test_numbers
    arr = range 1 5
    string = array_join ${arr} ", "

    release ${arr}

    assert_eq ${string} "1, 2, 3, 4"
end

function test_empty_separator
    arr = range 1 5
    string = array_join ${arr} ""

    release ${arr}

    assert_eq ${string} "1234"
end

Source:

Show Source

if not is_array ${scope::array_join::argument::1}
    trigger_error "Invalid input, non array handle or array not found."
end

if not array_is_empty ${scope::array_join::argument::1}
    for scope::array_join::item in ${scope::array_join::argument::1}
        scope::array_join::string = set "${scope::array_join::string}${scope::array_join::item}${scope::array_join::argument::2}"
    end

    if not is_empty ${scope::array_join::argument::2}
        scope::array_join::separatorlen = strlen ${scope::array_join::argument::2}
        scope::array_join::stringlen = strlen ${scope::array_join::string}
        scope::array_join::offset = calc ${scope::array_join::stringlen} - ${scope::array_join::separatorlen}
        scope::array_join::string = substring ${scope::array_join::string} 0 ${scope::array_join::offset}
    end
end

set ${scope::array_join::string}

Aliases:

array_join

std::collections::ArrayLength

var = array_length handle

Returns the array length based on the provided array handle.

Parameters

The array handle.

Return Value

The array length.

Examples

handle = array a b c "d e"
len = array_length ${handle}
released = release ${handle}
echo Array length: ${len} released: ${released}

handle = range 0 10
len = array_length ${handle}
released = release ${handle}
echo Array length: ${len} released: ${released}

Aliases:

array_length, arrlen, array_size

std::collections::ArrayPop

var = array_pop handle

Returns the last element of the array or none if the array is empty.

Parameters

The array handle.

Return Value

The last element of the array or none if the array is empty.

Examples

handle = array 1 2 3
last_element = array_pop ${handle}
assert_eq ${last_element} 3

Aliases:

array_pop

std::collections::ArrayPush

var = array_push handle value

Pushes an additional value to an existing array.

Parameters

The array handle.

Return Value

True if a new value was pushed.

Examples

handle = array 1 2 3
array_push ${handle} 4
last_element = array_pop ${handle}
assert_eq ${last_element} 4

Aliases:

array_push, array_add, array_put

std::collections::ArrayRemove

result = array_remove handle index

Removes the item from the array at the given index.
If the array is not found or the index is greater than the array size, this command will return false.
Otherwise it will return true.

Parameters

  • The array handle.
  • The element index.

Return Value

True if successful.

Examples

arr = array old

element = array_get ${arr} 0
assert_eq ${element} old

result = array_remove ${arr} 0
assert ${result}

empty = array_is_empty ${arr}
assert ${empty}

Aliases:

array_remove

std::collections::ArraySet

result = array_set handle index value

Updates the array at a given index with the provided value.
If the array is not found or the index is greater than the array size, this command will return false.
Otherwise it will return true.

Parameters

  • The array handle.
  • The element index.
  • The element value.

Return Value

True if successful.

Examples

arr = array old

element = array_get ${arr} 0
assert_eq ${element} old

result = array_set ${arr} 0 new
assert ${result}

element = array_get ${arr} 0
assert_eq ${element} new

Aliases:

array_set

std::collections::IsArray

var = is_array handle

Returns true if the provided value is an array handle.

Parameters

The array handle.

Return Value

True if the provided value is an array handle.

Examples

arr = array 1 2 3

value = is_array ${arr}
assert ${value}

released = release ${arr}
assert ${released}

Aliases:

is_array

std::collections::IsMap

var = is_map handle

Returns true if the provided value is a map handle.

Parameters

The map handle.

Return Value

True if the provided value is a map handle.

Examples

map_handle = map

value = is_map ${map_handle}
assert ${value}

released = release ${map_handle}
assert ${released}

Aliases:

is_map

std::collections::IsSet

var = is_set handle

Returns true if the provided value is a set handle.

Parameters

The set handle.

Return Value

True if the provided value is a set handle.

Examples

handle = set_new 1 2 3

value = is_set ${handle}
assert ${value}

released = release ${handle}
assert ${released}

Aliases:

is_set

std::collections::Map

handle = map

Creates an empty map and returns a handle to that array.
This handle can be passed to other commands which support maps using handles.
Once the map is no longer used, it should be released using the release command.

Parameters

None

Return Value

A handle to the map.

Examples

handle = map

# once done we should release the handle
release ${handle}

Aliases:

map

std::collections::MapClear

result = map_clear handle

Clears the provided map.

Parameters

The map handle.

Return Value

True if successful.

Examples

handle = map

result = map_put ${handle} a 1

result = map_is_empty ${handle}
assert_false ${result}

result map_clear ${handle}
assert ${result}

result = map_is_empty ${handle}
assert ${result}

release ${handle}

Aliases:

map_clear

std::collections::MapContainsKey

var = map_contains_key handle key

Returns true if the provided key was found in the map.

Parameters

  • The map handle.
  • The key

Return Value

True if the key was found in the map.

Examples

handle = map
map_put ${handle} key value
found = map_contains_key ${handle} key

Source:

Show Source

scope::map_contains_key::value = map_get ${scope::map_contains_key::argument::1} ${scope::map_contains_key::argument::2}
is_defined scope::map_contains_key::value

Aliases:

map_contains_key

std::collections::MapContainsValue

var = map_contains_value handle value

Returns true if the provided value was found in the map.

Parameters

  • The map handle.
  • The value

Return Value

True if the value was found in the map.

Examples

handle = map
map_put ${handle} key value
found = map_contains_value ${handle} value

Source:

Show Source

scope::map_contains_value::found = set false
scope::map_contains_value::not_empty = not map_is_empty ${scope::map_contains_value::argument::1}

if ${scope::map_contains_value::not_empty}
    scope::map_contains_value::value = set ${scope::map_contains_value::argument::2}
    scope::map_contains_value::key_array_handle = map_keys ${scope::map_contains_value::argument::1}

    for scope::map_contains_value::item in ${scope::map_contains_value::key_array_handle}
        scope::map_contains_value::next_value = map_get ${scope::map_contains_value::argument::1} ${scope::map_contains_value::item}
        scope::map_contains_value::found = equals ${scope::map_contains_value::next_value} ${scope::map_contains_value::value}

        if ${scope::map_contains_value::found}
            release ${scope::map_contains_value::key_array_handle}
        end
    end
end

release ${scope::map_contains_value::key_array_handle}
set ${scope::map_contains_value::found}

Aliases:

map_contains_value

std::collections::MapGet

value = map_get handle key

Returns a the value corresponding to the key from the map.

Parameters

  • The map handle.
  • The key.

Return Value

The value corresponding to the key from the map.

Examples

handle = map

result = map_put ${handle} key value
assert_eq ${result} true

value = map_get ${handle} key
assert_eq ${value} value

release ${handle}

Aliases:

map_get

std::collections::MapIsEmpty

var = map_is_empty handle

Returns true if the provided map handle is an empty map.

Parameters

The map handle.

Return Value

True if the provided handle belongs to an empty map.

Examples

handle = map
map_put ${handle} key value
empty = map_is_empty ${handle}

Source:

Show Source

scope::map_is_empty::length = map_size ${scope::map_is_empty::argument::1}
equals 0 ${scope::map_is_empty::length}

Aliases:

map_is_empty

std::collections::MapKeys

keys = map_keys handle

Returns a handle to an array holding all keys in the provided map handle.

Parameters

  • The map handle.

Return Value

A handle to an array holding all map keys.

Examples

handle = map

result = map_put ${handle} key1 value1
assert_eq ${result} true
result = map_put ${handle} key2 value2
assert_eq ${result} true

keys = map_keys ${handle}
for key in ${keys}
    value = map_get ${handle} ${key}
    echo Key: ${key} Value: ${value}
end

release ${handle}
release ${keys}

Aliases:

map_keys

std::collections::MapLoadProperties

var = map_load_properties [--prefix prefix] handle text

Parsers and loads all properties to the provided map.

Parameters

  • Optional --prefix and the prefix value
  • The map handle.
  • The properties text.

Return Value

True if successful.

Examples

handle = map

result = map_put ${handle} key value
assert_eq ${result} true

value = map_get ${handle} key
assert_eq ${value} value

release ${handle}

Aliases:

map_load_properties

std::collections::MapPut

var = map_put handle key value

Inserts a key-value pair into the map.

Parameters

  • The map handle.
  • The key.
  • The new value.

Return Value

True if a new value was inserted.

Examples

handle = map

result = map_put ${handle} key value
assert_eq ${result} true

value = map_get ${handle} key
assert_eq ${value} value

release ${handle}

Aliases:

map_put, map_add

std::collections::MapRemove

value = map_remove handle key

Removes a the value corresponding to the key from the map and returns it.

Parameters

  • The map handle.
  • The key.

Return Value

The value corresponding to the key from the map.

Examples

handle = map

result = map_put ${handle} key value
assert_eq ${result} true

value = map_remove ${handle} key
assert_eq ${value} value

release ${handle}

Aliases:

map_remove

std::collections::MapSize

var = map_size handle

Returns the map size based on the provided map handle.

Parameters

The map handle.

Return Value

The map size.

Examples

handle = map

result = map_put ${handle} a 1
result = map_put ${handle} b 2
result = map_put ${handle} c 3

result = map_size ${handle}
assert_eq ${result} 3

release ${handle}

Aliases:

map_size

std::collections::MapToProperties

text = map_to_properties [--prefix prefix] handle

Converts the provided map to properties text.

Parameters

  • Optional --prefix and the prefix value
  • The map handle.

Return Value

The properties text.

Examples

handle = map
map_put ${handle} a 1
map_put ${handle} b 2
map_put ${handle} a.b.c 123

text = map_to_properties ${handle}

Aliases:

map_to_properties

std::collections::Range

handle = range start end

Creates an array from the input start and end range values and returns a handle to that array.
This handle can be passed to other commands which support arrays using handles.
Once the array is no longer used, it should be released using the release command.

Parameters

  • The start numeric value
  • The end numeric value which cannot be smaller than the start value.

Return Value

A handle to the array.

Examples

handle = range 1 10

# once done we should release the handle
release ${handle}

Aliases:

range

std::collections::ReadProperties

count = read_properties [--prefix key] text

Parses the properties (based on java properties format) text and sets them as variables.
This command will also return the count of properties read.
If prefix is provided, all properties read, will be stored as variables with the prefix. as their prefix.

Parameters

  • Optional --prefix and the prefix value
  • The text to parse.

Return Value

The properties count.

Examples

count = read_properties "a=1\nb=2\na.b.c=3"
assert_eq ${count} 3

assert_eq ${a} 1
assert_eq ${b} 2
assert_eq ${a.b.c} 3

count = read_properties --prefix config a=1\nb=2\na.b.c=3
assert_eq ${count} 3

assert_eq ${config.a} 1
assert_eq ${config.b} 2
assert_eq ${config.a.b.c} 3

Aliases:

read_properties

std::collections::Set

handle = set_new value1 value2 value3 ...

Creates a new set from the input arguments and returns a handle to that set.
This handle can be passed to other commands which support sets using handles.
Once the set is no longer used, it should be released using the release command.

Parameters

Any number of arguments which will construct the set.

Return Value

A handle to the set.

Examples

handle = set_new ${var} "hello world" 5 ${another_var}

# once done we should release the handle
release ${handle}

Aliases:

set_new

std::collections::SetClear

result = set_clear handle

Clears the provided set.

Parameters

The set handle.

Return Value

True if successful.

Examples

handle = set

result = set_put ${handle} 1

result = set_is_empty ${handle}
assert_false ${result}

result set_clear ${handle}
assert ${result}

result = set_is_empty ${handle}
assert ${result}

release ${handle}

Aliases:

set_clear

std::collections::SetContains

var = set_contains handle value

Returns true if the set contains the provided value.

Parameters

  • The set handle.
  • The value

Return Value

True if the value was found in the set.

Examples

handle = set_new value1 value2 value3
found = set_contains ${handle} value2

Aliases:

set_contains

std::collections::SetFromArray

set_handle = set_from_array array_handle

Returns a set handle created from the provided array values.

Parameters

The array handle.

Return Value

The new set handle.

Examples

array_handle = array value1 value2 value3
set_handle = set_from_array ${handle}

Source:

Show Source

if not is_array ${scope::set_from_array::argument::1}
    trigger_error "Invalid input, non array handle or array not found."
end

scope::set_from_array::set = set_new
for scope::set_from_array::next_value in ${scope::set_from_array::argument::1}
    set_put ${scope::set_from_array::set} ${scope::set_from_array::next_value}
end

set ${scope::set_from_array::set}

Aliases:

set_from_array

std::collections::SetIsEmpty

var = set_is_empty handle

Returns true if the provided set handle is an empty set.

Parameters

The set handle.

Return Value

True if the provided handle belongs to an empty set.

Examples

handle = set
set_put ${handle} value
empty = set_is_empty ${handle}

Source:

Show Source

scope::set_is_empty::length = set_size ${scope::set_is_empty::argument::1}
equals 0 ${scope::set_is_empty::length}

Aliases:

set_is_empty

std::collections::SetPut

var = set_put handle value

Pushes an additional value to an existing set.

Parameters

The set handle.

Return Value

True if a new value was pushed.

Examples

handle = set_new 1 2 3
set_put ${handle} 4
size = set_size ${handle}
assert_eq ${size} 4

Aliases:

set_put, set_add

std::collections::SetRemove

removed = set_remove handle value

Removes a the value from the set and returns true/false if it was removed.

Parameters

  • The set handle.
  • The value to remove.

Return Value

True if the value was found and removed from the set.

Examples

handle = set_new

result = set_put ${handle} value
assert_eq ${result} true

removed = set_remove ${handle} value
assert ${removed}

release ${handle}

Aliases:

set_remove

std::collections::SetSize

var = set_size handle

Returns the set size based on the provided set handle.

Parameters

The set handle.

Return Value

The set size.

Examples

handle = set

result = set_put ${handle} 1
result = set_put ${handle} 2
result = set_put ${handle} 3

result = set_size ${handle}
assert_eq ${result} 3

release ${handle}

Aliases:

set_size

std::collections::SetToArray

array_handle = set_to_array set_handle

Converts the provided set to an array and returns the new array handle.

Parameters

The set handle.

Return Value

The array handle or false in case of error.

Examples

set_handle = set_new value1 value2 value3
array_handle = set_to_array ${set_handle}

Aliases:

set_to_array

std::collections::WriteProperties

text = write_properties [--prefix prefix] [names]

Creates a properties string from the provided list of variable names (not values).

Parameters

  • Optional prefix which will be added to all written properties.
  • A list of variable names.

Return Value

The properties text value.

Examples

a = set 1
b = set 2
a.b.c = set 3

# text will be equal to:
# a=1
# b=2
# a.b.c=3
text = write_properties a b a.b.c

# text will be equal to:
# P.a=1
# P.b=2
# P.a.b.c=3
text = write_properties --prefix P a b a.b.c

Aliases:

write_properties

std::debug::DuckscriptSDKVersion

var = duckscript_sdk_version

Returns the duckscript SDK version.

Parameters

None

Return Value

The duckscript SDK version.

Examples

version = duckscript_sdk_version 

Aliases:

duckscript_sdk_version

std::debug::DuckscriptVersion

var = duckscript_version

Returns the duckscript runtime version.

Parameters

None

Return Value

The duckscript runtime version.

Examples

version = duckscript_version 

Aliases:

duckscript_version

std::debug::DumpInstructions

value = dump_instructions

Returns all script instructions structure (not script text) in textual form.

Parameters

None

Return Value

The script instructions.

Examples

value = dump_instructions
found = contains ${value} dump_instructions
assert found

Aliases:

dump_instructions

std::debug::DumpState

value = dump_state

Returns all script state in textual form.

Parameters

None

Return Value

The script state.

Examples

numbers = range -5 15

text = dump_instructions
found = contains ${text} -5
assert found

Aliases:

dump_state

std::debug::DumpVariables

value = dump_variables

Returns all script variables in textual form.

Parameters

None

Return Value

The script variables.

Examples

one = set 1
two = set 2
values = array 1 2 yes true
numbers = range -5 15

text = dump_variables
found = contains ${text} two
assert found
found = contains ${text} 2
assert found
found = contains ${text} handle
assert found

Aliases:

dump_variables

std::env::EnvToMap

handle = env_to_map

Converts all environment variables to a map and returns the map handle.

Parameters

None

Return Value

The map handle.

Examples

set_env env_to_map_test test_value

handle = env_to_map

value = map_get ${handle} env_to_map_test
assert_eq ${value} test_value

release ${handle}

Aliases:

env_to_map

std::env::FindExecutable

var = which executable

Returns the path to the executable if it exists.
If not found it will return an empty string.

Parameters

The executable to find.

Return Value

The executable path or empty string if not found.

Examples

path = which echo

Aliases:

which

std::env::GetCpuCount

var = cpu_count

Returns the number of CPUs.

Parameters

None

Return Value

The CPU count.

Examples

count = cpu_count

Aliases:

cpu_count, get_cpu_count

std::env::GetHomeDirectory

var = get_home_dir

Returns the user home directory path.
In case of any error, false will be returned.

Parameters

None

Return Value

The user home directory path or false in case of any error.

Examples

directory = get_home_dir

Aliases:

get_home_dir

std::env::GetOSFamily

var = os_family

Returns the OS family (windows, linux, mac).

Parameters

None

Return Value

The OS family (windows, linux, mac).

Examples

name = os_family

Aliases:

os_family

std::env::GetOSName

var = os_name

Returns the OS name.

Parameters

None

Return Value

The OS name.

Examples

name = os_name

Aliases:

os_name

std::env::GetOSRelease

var = os_release

Returns the OS release.
This command is not supported on windows.

Parameters

None

Return Value

The OS release.

Examples

release = os_release

Aliases:

os_release

std::env::GetOSVersion

var = os_version

Returns the OS version.
This command is not supported on windows.

Parameters

None

Return Value

The OS version.

Examples

version = os_version

Aliases:

os_version

std::env::GetUserName

var = whoami

Returns the current user name.

Parameters

None

Return Value

The current user name.

Examples

name = whoami

Aliases:

whoami, get_user_name

std::env::GetVar

var = get_env key

Returns the environment variable value for the provided key.

Parameters

First argument is the environment variable key.

Return Value

The environment variable value.

Examples

home = get_env HOME

Aliases:

get_env

std::env::IsWindows

var = is_windows

Returns true if the current OS family is windows.

Parameters

None

Return Value

True if the current OS family is windows.

Examples

windows = is_windows

Source:

Show Source

scope::is_windows::os = os_family
equals ${scope::is_windows::os} windows

Aliases:

is_windows

std::env::PrintCurrentDirectory

var = pwd

Prints and also returns the current directory.

Parameters

None

Return Value

The current directory path.

Examples

# Print the current directory:
pwd

# Print and also store the current directory:
directory = pwd

Aliases:

pwd, print_current_directory

std::env::PrintEnv

var = printenv

Prints and returns all environment variables.

Parameters

None

Return Value

All environment variables printout text.

Examples

set_env TEST_PRINT_ENV TRUE

text = printenv

valid = contains ${text} TEST_PRINT_ENV=TRUE
assert ${valid}

Source:

Show Source

scope::print_env::map = env_to_map
scope::print_env::text = map_to_properties ${scope::print_env::map}
release ${scope::print_env::map}

echo ${scope::print_env::text}
set ${scope::print_env::text}

Aliases:

print_env, printenv

std::env::SetCurrentDirectory

cd path

Sets the current directory based on the input path.
If no path is provided, it will default to the user home directory.
If the path does not exist, it will return none.

Parameters

The new current directory.

Return Value

The new current directory or none in case of any error such as target directory not found.

Examples

# Move to user home directory and store the path in the home variable
home = cd

# Move to the requested directory
cd ./scripts

Aliases:

cd, set_current_dir, set_current_directory

std::env::SetVar

var = set_env (key value | --handle map_handle)

Sets the environment variable defined by the provided key to the provided value.
If --handle is provided, the second arg will be used as a handle to a map and all keys/values in the map will be set.

Parameters

The function can be invoked in the following ways:

  • Key/Value pair - Two arguments are required:
    • key - The name of the environment variable to set
    • value - The new environment variable value
  • Map handle - Two arguments are required:
    • --handle
    • The map handle

Return Value

true if successful

Examples

set_env HOME /usr/me

handle = map
map_put ${handle} mapkey1 mapvalue1
map_put ${handle} mapkey2 mapvalue2
set_env --handle ${handle}

# load env file
text = readfile ./test.env
handle = map
map_load_properties ${handle} ${text}
set_env --handle ${handle}

Aliases:

set_env

std::env::UName

var = uname [-a]

Acts similar to uname on unix like systems.

Parameters

  • Optional -a for extended information (not supported on windows).

Return Value

The OS name and optionally extra information.

Examples

value = uname -a

Source:

Show Source

scope::uname::extended_info = equals -a ${scope::uname::argument::1}
scope::uname::info = os_name

scope::uname::not_windows = not is_windows

if ${scope::uname::extended_info} and ${scope::uname::not_windows}
    scope::uname::release = os_release
    scope::uname::version = os_version
    scope::uname::info = set "${scope::uname::info} ${scope::uname::release} ${scope::uname::version}"
end

set ${scope::uname::info}

Aliases:

uname

std::env::UnsetVar

unset_env key

Removes the environment variable defined by the provided key.

Parameters

The name of the environment variable to remove

Return Value

None

Examples

unset_env HOME

Aliases:

unset_env

std::error::GetLastError

var = get_last_error

In case of any runtime error, this function will return the error message.

Parameters

None

Return Value

The last error message or none

Examples

# This will trigger an error
assert_fail

error = get_last_error
echo Error Message: ${error}

Aliases:

get_last_error

std::error::GetLastErrorLine

var = get_last_error_line

In case of any runtime error, this function will return the error line (if available).

Parameters

None

Return Value

The last error line or none

Examples

# This will trigger an error
assert_fail

line = get_last_error_line
echo Error Line: ${line}

Aliases:

get_last_error_line

std::error::GetLastErrorSource

var = get_last_error_source

In case of any runtime error, this function will return the error source (such as file name) if available.

Parameters

None

Return Value

The last error source or none

Examples

# This will trigger an error
assert_fail

source = get_last_error_source
echo Error Source File: ${source}

Aliases:

get_last_error_source

std::error::SetError

set_error message

Sets the last error which is accessible via get_last_error.
This command will not trigger the on_error command flow.

Parameters

The error message.

Return Value

None

Examples

set_error "my error message"

error = get_last_error

assert_eq ${error} "my error message"

Aliases:

set_error

std::error::SetExitOnError

var = exit_on_error value

Enables to cause the script execution to stop in case of any error.
By default all errors simply trigger the on_error command which the default SDK stores and provides access to.
However, with this command you can change the on_error command to instead stop the script execution.

Parameters

If no argument is provided, it will return the current state.
If an argument is provided, it will modify the state and return it as true/false.

Return Value

The current/updated state as true/false value

Examples

# Get current state
will_exit = exit_on_error
echo Current state: ${will_exit}

# Update the current state
will_exit = exit_on_error true
echo Current state: ${will_exit}

Aliases:

exit_on_error, set_exit_on_error

std::error::TriggerError

trigger_error [message]

Triggers an error that will trigger the on_error flow.

Parameters

Optional error message.

Return Value

None

Examples

trigger_error "my error message"
error = get_last_error
assert_eq ${error} "my error message"

Aliases:

trigger_error

std::flowcontrol::ForIn

args = array a b c
for arg in ${args}
    # commands
end
release args

The for/in command enables to iterate over an array (see array command).
The first argument will contain the current iteration value from the array.
Once all values have been read, it will exit the loop.

Parameters

  • for
    • The variable name which will hold the current iteration value
    • The string "in"
    • The handle to the array of values to iterate
  • end - no parameters

Return Value

None

Examples

# Simple example iteration over the list of letters:
args = array a b c

for arg in ${args}
    echo current arg is: ${arg}
end

release args

# Example nested loops:
args = array 1 2 3
for i in ${args}
    for j in ${args}
        echo i: ${i} j: ${j}
    end
end

Aliases:

for

std::flowcontrol::Function

fn my_function
    # function content
    return output
end

fn <scope> another_function
    # function content
end

This command provides the function language feature as a set of commands:

  • function/fn - Defines a function start block
  • end - Defines the end of the function block
  • return - Allows to exit a function at any point and return an output
  • <scope> - Optional annotation which enables to use a new scope during the function invocation.
  • function name - Dynamically created commands based on the function name which are used to invoke the function code.

When a function command is detected, it will search for the end command that comes after.
That entire block is considered the function code block (functions cannot be nested in outer functions)

In order to invoke the function, simply call the function name with any amount of parameters.
Those parameters will be set as ${1}, ${2}, ... and so on.
Since variables are global, it will overwrite any older values stored in those variables.

To exit a function and return a value, simply use the return command with the value you want to return.
The variable that was used when the function was originally called, will now store that value.
The return command can be used to exit early without any value.
In case the code reached the end call, the function will exit but will not return a value.

The <scope> annotation enables to start a new scope when running the function.
All variables defined will not be available except the variables provided to the function as arguments.
All variables created during the function invocation will be deleted once the function ends, except the return value.
This enables a clean function invocation without impacting the global variables.

Parameters

  • function - The function name used later on to invoke the function
  • end - no parameters
  • return - optional single parameter to return as an output of the function call
  • <scope> - Optional annotation which enables to use a new scope during the function invocation.
  • function name - Any number of arguments which will automatically be set as global variables: ${1}, ${2}, ... as so on.

Return Value

The function invocation returns the output provided by the return command.

Examples

# Simple example of a function definition which echo 'hello world' and exits.

# function start
fn hello_world
    echo hello world
end

# function invocation
hello_world

# Example of calling a function and returning a value
fn get_hello_world
    return "hello world"
end

# function invocation
text = get_hello_world

# this will print "hello world"
echo ${text}

# Example of passing arguments
# Also the function is with scope annotation so it has no access
# to any variable except those provided during the function invocation.
fn <scope> print_input
    # ${1} is set with the value 'hello'
    # ${2} is set with the value 'world'
    echo ${1} ${2}
end

print_input hello world

# Functions can call other functions
fn get_one
    return 1
end

fn get_number
    number = get_one
    return ${number}
end

output = get_number

# this will print 1
echo ${output}

Aliases:

function, fn

std::flowcontrol::GoTo

goto :label

The goto command enables you to jump to any position in the script, if that position has a label value.

Parameters

A single valid label value.

Return Value

None

Examples

goto :good

echo bad

:good echo good

Aliases:

goto

std::flowcontrol::If

if [command|value|condition]
    # commands
elseif [command|value|condition]
    # commands
else
    # commands
end

This command provides the if/elseif/else condition language feature as a set of commands:

  • if - Defines an if condition
  • elseif - Defines optional secondary condition blocks
  • else - Optinoal fallback block
  • end - Defines the end of the entire if/else block

if and elseif commands accept either:

  • A command with optional arguments and invokes it
  • A single value which doesn't match any known command
  • A condition statement

If the result is one of the following:

  • No output
  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

It is considered falsy.
In case of falsy value, it will skip to the next elseif/else block.
If a truthy (non falsy) output is found, it will invoke the commands of that code block and ignore all other elseif/else blocks.

if blocks can be nested in other if blocks (see examples).

A condition statement is made up of values, or/and keywords and '('/')' groups.
Each must be separated with a space character.

Parameters

  • if/elseif - A command and its arguments to invoke and evaluate its output, if a single value is provided an no such command exists, it is evaluated as a value.
  • else/end - no parameters

Return Value

None

Examples

# Simple example of an if statement that evaluates the argument value as true and echos "in if"
if true
    echo in if
end

# Example of using **not** command to reverse the output value
if not false
    echo in if
end

# Example of an if statement that evaluates the command as true and echos "in if"
if set true
    echo in if
end

# Example of if condition returning a falsy result and navigation goes to the else block which echos "in else"
if set false
    echo should not be here
else
    echo in else
end

# Example of if condition returning a falsy result and navigation goes to the elseif block has a truthy condition
if set false
    echo should not be here
elseif set true
    echo in else if
else
    echo should not be here
end

# Nested if example:
if set false
    echo should not be here
elseif set true
    echo in else if but not done yet

    if set true
        echo nested if
    end
else
    echo should not be here
end

valid = set false
if true and false or true and false or ( true and true or false )
    valid = set true
end
assert ${valid}

if true and false or true and false or ( true and true or false ) and false
    assert_fail
end

Aliases:

if

std::flowcontrol::While

while [command|value|condition]
    # commands
end

This command provides the while loop language feature as a set of commands:

  • while - Defines a while condition and start of loop
  • end - Defines the end of the while block

The while command accept either:

  • A command with optional arguments and invokes it
  • A single value which doesn't match any known command
  • A condition statement

If the result is one of the following:

  • No output
  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

It is considered falsy.
In case of falsy value, it will skip to the next line after the while block.
If a truthy (non falsy) output is found, it will invoke the commands of that code block and go back to the start of the while condition.

while blocks can be nested in other while blocks (see examples).

A condition statement is made up of values, or/and keywords and '('/')' groups.
Each must be separated with a space character.

Parameters

  • while - A command and its arguments to invoke and evaluate its output, if a single value is provided an no such command exists, it is evaluated as a value.
  • end - no parameters

Return Value

None

Examples

top_count = set 0
inner_count = set 0
counter = set 0
while not equals ${top_count} 10
    top_count = calc ${top_count} + 1
    inner_count = set 0

    while not equals ${inner_count} 10
        inner_count = calc ${inner_count} + 1
        counter = calc ${counter} + 1
    end
end

assert_eq ${counter} 100

Aliases:

while

std::fs::Append

result = appendfile file text

This command enables to write the provided text into the requested file.
It will return true/false value based if it was able to write the text to the file.
In case the file doesn't exist, it will create it.
If the file exists, it will append the text to it.

Parameters

  • The target file
  • The text content to write

Return Value

true/false based if it was able to write the text to the file.

Examples

out = appendfile ./target/tests/writefile.txt "line 1\nline 2"

Aliases:

appendfile

std::fs::CPGlob

result = glob_cp source_glob target

This command will copy all files that match the given glob.

Parameters

  • The source glob, for example ./*.txt
  • The target path

Return Value

The amount of paths (files) copied or false in case of any error.

Examples

count = glob_cp ./**/*.txt ../target

Source:

Show Source

scope::glob_cp::contains_glob = contains ${scope::glob_cp::argument::1} *
scope::glob_cp::target = set ${scope::glob_cp::argument::2}
scope::glob_cp::output = set 0

if ${scope::glob_cp::contains_glob}
    scope::glob_cp::handle = glob_array ${scope::glob_cp::argument::1}
    scope::glob_cp::glob_empty = array_is_empty ${scope::glob_cp::handle}

    if not ${scope::glob_cp::glob_empty}
        scope::glob_cp::is_relative = starts_with ${scope::glob_cp::argument::1} .
        if not ${scope::glob_cp::is_relative}
            scope::glob_cp::top_dir_without_glob = set ${scope::glob_cp::argument::1}
            while contains ${scope::glob_cp::top_dir_without_glob} *
                scope::glob_cp::top_dir_without_glob = dirname ${scope::glob_cp::top_dir_without_glob}
            end

            scope::glob_cp::absolute_prefix_length = strlen ${scope::glob_cp::top_dir_without_glob}
        end

        for scope::glob_cp::entry in ${scope::glob_cp::handle}
            scope::glob_cp::is_file = is_file ${scope::glob_cp::entry}

            if ${scope::glob_cp::is_file}
                if ${scope::glob_cp::is_relative}
                    scope::glob_cp::target_file = join_path ${scope::glob_cp::target} ${scope::glob_cp::entry}
                else
                    scope::glob_cp::target_file = substring ${scope::glob_cp::entry} ${scope::glob_cp::absolute_prefix_length}
                    scope::glob_cp::target_file = join_path ${scope::glob_cp::target} ${scope::glob_cp::target_file}
                end

                scope::glob_cp::done = cp ${scope::glob_cp::entry} ${scope::glob_cp::target_file}

                if ${scope::glob_cp::done}
                    scope::glob_cp::output = calc ${scope::glob_cp::output} + 1
                end
            end
        end
    end

    release ${scope::glob_cp::handle}
else
    scope::glob_cp::is_file = is_file ${scope::glob_cp::argument::1}

    if ${scope::glob_cp::is_file}
        scope::glob_cp::filename = basename ${scope::glob_cp::argument::1}
        scope::glob_cp::done = cp ${scope::glob_cp::argument::1} ${scope::glob_cp::target}/${scope::glob_cp::filename}
        if ${scope::glob_cp::done}
            scope::glob_cp::output = set 1
        end
    end
end

set ${scope::glob_cp::output}

Aliases:

glob_cp, cp_glob

std::fs::CopyPath

var = cp source target

This command copies the requested file or directory to the target location.
If the source directory is not empty, its entire contents will be copied as well.

Parameters

  • The source path to copy
  • The target path

Return Value

true if the path was copied.

Examples

# copy a single file
copied = cp ./file1.txt ./file2.txt

# copy a directory
copied = cp ./source ./target

Aliases:

cp

std::fs::CreateDirectory

var = mkdir directory

This command will create the requested directory (and needed parent directories) and return true/false if it was successful.

Parameters

The directory name to create.

Return Value

The operation success value - true if directory exists, else false.

Examples

exists = mkdir ./dir/subdir

Aliases:

mkdir

std::fs::CreateEmptyFile

var = touch file

This command will create an empty file and return true/false if the file exists.
If file exits, it will not be modified.

Parameters

The file path.

Return Value

If the file exists after the command, it will return true.
In case of any error, it will return false.

Examples

exists = touch ./dir/file.txt

Aliases:

touch

std::fs::DeleteEmptyDirectory

var = rmdir path

This command delete the requested empty directory and returns true if successful.
If the path leads to a file or a directory which is not empty, this command will fail.

Parameters

A single parameter holding the directory path.

Return Value

true if the directory was deleted.

Examples

deleted = rmdir ./mydir

Aliases:

rmdir

std::fs::DeletePath

var = rm [-r] [path]+

This command delete the requested file/s, empty directories or recursively deletes directories and all their content (files and sub directories) if the -r flag is provided.

Parameters

  • Optional flags (currently only -r is supported which indicates recursive deletion)
  • The path/s to delete

Return Value

true if all paths were deleted.

Examples

# delete a file or empty directory
deleted = rm ./target

# deletes a directory and all its content
deleted = rm -r ./target

# delete all provided paths
deleted = rm -r ./dir ./somefile ./anotherdir/subdir/file

Aliases:

rm

std::fs::Exists

var = is_path_exists path

This command will return true/false based if the provided path points to an existing file system entry.

Parameters

The path to check.

Return Value

True if the path points to an existing file system entry.

Examples

existing = is_path_exists ./dir
existing = is_path_exists ./dir/somefile.txt

Aliases:

is_path_exists

std::fs::GetCanonicalPath

var = canonicalize path

This command will return the c path for the provided input.
In case unable, it will return the original input.

Parameters

The file/directory path to canonicalize.

Return Value

The canonicalized path, or if unsuccessful, the original path.

Examples

path = canonicalize ./target

Aliases:

canonicalize

std::fs::GetFileName

var = basename path

This command will return the last path element of the provided path.
If unable, it will return none.

Parameters

The path to extract the last element from.

Return Value

The last path element or none if unsuccessful.

Examples

file = basename ./dir/file.txt

Aliases:

basename

std::fs::GetFileSize

var = get_file_size path

This command will return the size of the file in bytes.

Parameters

The path to check.

Return Value

The size of the file in bytes or false in case path is a directory or does not exist.

Examples

size = get_file_size ./dir/somefile.txt

Aliases:

get_file_size, filesize

std::fs::GetLastModifiedTime

var = get_last_modified_time path

This command will return the last modified time in millies from unix epoch.

Parameters

The path to check.

Return Value

The last modified time in millies from unix epoch or false in case path does not exist.

Examples

time = get_last_modified_time ./dir/somefile.txt

Aliases:

get_last_modified_time

std::fs::GetParentDirectory

var = dirname path

This command will return the parent path of the provided path.
If the parent path is empty, it will return none.

Parameters

The path to extract the parent path from.

Return Value

The parent path or none.

Examples

directory = dirname ./dir/file.txt

Aliases:

dirname

std::fs::GitIgnorePathArray

handle = gitignore_path_array path

Returns an array handle containing all path entries found from the provided root path that should be included based on the gitignore definitions.

Parameters

The root path.

Return Value

The array handle.

Examples

handle = gitignore_path_array ./src

for path in ${handle}
    echo ${path}
end

Aliases:

gitignore_path_array

std::fs::GlobArray

handle = glob_array pattern

Returns an array handle containing all path entries found from the provided glob pattern.
The pattern can be a relative path from current directory or an absolute path.

Parameters

The glob pattern.

Return Value

The array handle.

Examples

handle = glob_array ./somedir/**/*.txt

for path in ${handle}
    echo ${path}
end

Aliases:

glob_array, globarray

std::fs::IsDirectory

var = is_dir path

This command will return true/false based if the provided path points to an existing directory.

Parameters

The path to check.

Return Value

True if the path points to an existing directory.

Examples

existing_dir = is_dir ./dir

Aliases:

is_directory, is_dir

std::fs::IsFile

var = is_file path

This command will return true/false based if the provided path points to an existing file.

Parameters

The path to check.

Return Value

True if the path points to an existing file.

Examples

existing_file = is_file ./dir/somefile.txt

Aliases:

is_file

std::fs::IsPathNewer

var = is_path_newer newer older

This command will return true if the 'newer' path last modified time is after the 'older' path last modified time.

Parameters

  • newer - The file/directory path to check.
  • older - The file/directory path to check.

Return Value

True if the 'newer' path last modified time is after the 'older' path last modified time. Otherwise or in case of an error, false will be returned.

Examples

newer = is_path_newer ./new_file.txt ./old_file.txt

Aliases:

is_path_newer

std::fs::IsReadonly

var = is_readonly path

This command will return true/false based if the provided path exists and is set to readonly.

Parameters

The path to check.

Return Value

True if the provided path exists and is set to readonly.

Examples

readonly = is_readonly ./dir/somefile.txt

Aliases:

is_readonly

std::fs::JoinPath

result = join_path path [path]*

Concats all paths and makes sure there is a / character between each path element.

Parameters

  • A list of paths to join

Return Value

The joined path

Examples

joined = join_path /test /dir1 /dir2 dir3 //dir4// /dir5

assert_eq ${joined} /test/dir1/dir2/dir3/dir4/dir5

Source:

Show Source
scope::join_path::added = set false

for scope::join_path::path in ${scope::join_path::arguments}
    if ${scope::join_path::added}
        scope::join_path::output = set "${scope::join_path::output}/${scope::join_path::path}"
    else
        scope::join_path::output = set ${scope::join_path::path}
        scope::join_path::added = set true
    end
end

while contains ${scope::join_path::output} //
    scope::join_path::output = replace ${scope::join_path::output} // /
end

set ${scope::join_path::output}

Aliases:

join_path

std::fs::List

var = ls [flags] [path]

Lists the file/directory contents.
If no path is provided, the current working directory will be used.
The supported flags are:

  • -l - Shows extended information

Parameters

  • Optional flags (currently only -l is supported)
  • Optional path (if not provided, current working directory is used)

Return Value

true is operation was successful.

Examples

# prints current directory content
ls

# prints current directory content
ls .

# prints examples directory content
ls ./examples

# prints examples directory content with extended info
ls -l ./examples

# prints current directory content with extended info
ls -l

# prints file name
ls ./examples/ls.ds

# prints file name with extended info
ls -l ./examples/ls.ds

Aliases:

ls

std::fs::MovePath

var = mv source target

This command moves the requested source path to the target path.

  • If the source and target paths define a file, it will move the file as defined.
  • If target path is a directory path, it will move the source file/directory into that target directory path.

All missing parent directories in the target path will be created as needed.

Parameters

  • The source path to copy
  • The target path

Return Value

true if the move was successful.

Examples

# move a single file
moved = mv ./file1.txt ./file2.txt

# move a single file into the target directory
moved = mv ./file1.txt ./somedir

# move entire directory into another directory
moved = mv ./source ./target/subdir

Aliases:

mv

std::fs::Print

var = cat [file]+

The cat command will print out the requested file/s.
In addition it will also return the value to the output variable.

Parameters

Multiple file paths.

Return Value

The file content or none if the file does not exist.

Examples

cat ./docs/sdk.md

Aliases:

cat

std::fs::ReadBytes

handle = read_binary_file file

Reads a raw file and returns a handle to the binary data.

Parameters

A single parameter holding the file path.

Return Value

The binary data handle.

Examples

handle = read_binary_file ./Cargo.toml
text = bytes_to_string ${handle}

Aliases:

readbinfile, read_binary_file

std::fs::ReadText

var = readfile file

The readfile command will read the requested file and return the value to the output variable.

Parameters

A single parameter holding the file path.

Return Value

The file content or none in case file does not exist.

Examples

text = readfile ./Cargo.toml

Aliases:

readfile, read_text_file

std::fs::SetMode

result = chmod mode path

This command will update the mode for the given path.
This command is currently only available for unix like systems and will return false for all others such as windows.

Parameters

  • The new mode, for example 755
  • The path

Return Value

The new mode as decimal number or false in case of any error.

Examples

chmod 777 ./myfile.txt

Aliases:

chmod

std::fs::SetModeGlob

result = glob_chmod mode glob

This command will update the mode for the given glob pattern.
This command is currently only available for unix like systems and will return false for all others such as windows.

Parameters

  • The new mode, for example 755
  • The path glob

Return Value

The amount of path entries affected by the operation or false in case of any error.

Examples

file1 = set ./target/_duckscript_test/glob_chmod/modify1.txt
touch ${file1}
file2 = set ./target/_duckscript_test/glob_chmod/modify2.txt
touch ${file2}

count = glob_chmod 777 ./target/_duckscript_test/glob_chmod/**/*.txt
assert_eq ${count} 2

readonly = is_readonly ${file1}
assert_false ${readonly}
readonly = is_readonly ${file2}
assert_false ${readonly}

count = glob_chmod 444 ./target/_duckscript_test/glob_chmod/**/*.txt
assert_eq ${count} 2

readonly = is_readonly ${file1}
assert ${readonly}
readonly = is_readonly ${file2}
assert ${readonly}

Source:

Show Source

scope::glob_chmod::handle = glob_array ${scope::glob_chmod::argument::2}
scope::glob_chmod::output = array_length ${scope::glob_chmod::handle}

for scope::glob_chmod::entry in ${scope::glob_chmod::handle}
    scope::glob_chmod::result = chmod ${scope::glob_chmod::argument::1} ${scope::glob_chmod::entry}

    if equals ${scope::glob_chmod::result} false
        release ${scope::glob_chmod::handle}
        scope::glob_chmod::output = set false
    end
end

release ${scope::glob_chmod::handle}

set ${scope::glob_chmod::output}

Aliases:

glob_chmod, chmod_glob

std::fs::TempDirectory

path = temp_dir

This command will return the system temporary directory path.

Parameters

None

Return Value

The directory path.

Examples

path = temp_dir

echo ${path}

Aliases:

temp_dir

std::fs::TempFile

path = temp_file [extension]

This command will create a new empty temporary file and return its path.

Parameters

Optional file extension.

Return Value

The file path.

Examples

path = temp_file toml

echo ${path}

Aliases:

temp_file

std::fs::WriteBytes

result = write_binary_file file handle

This command enables to write binary data of the provided binary handle into the requested file.
It will return true/false value based if it was able to write the binary data to the file.

Parameters

  • The target file
  • The binary data handle

Return Value

true/false based if it was able to write the binary data to the file.

Examples

handle = string_to_bytes "some text"
result = write_binary_file ./target/tests/data.bin ${handle}

Aliases:

writebinfile, write_binary_file

std::fs::WriteText

result = writefile file text

This command enables to write the provided text into the requested file.
It will return true/false value based if it was able to write the text to the file.

Parameters

  • The target file
  • The text content to write

Return Value

true/false based if it was able to write the text to the file.

Examples

result = writefile ./target/tests/writefile.txt "line 1\nline 2"

Aliases:

writefile, write_text_file

std::hash::Digest

var = digest --algo (sha256|sha512) (--file path|content)

Runs the requested hash on the provided file or string content and returns the hashed value in hex.

Parameters

  • --algo and algorithm to use (currently sha256 and sha512 are supported)
  • Optional --file and file path
  • Optional the string content to hash (if file is not provided)

Return Value

The hash value in hex or false in case of error.

Examples

hashed = digest --algo sha256 "hello world\n"
assert_eq ${hashed} A948904F2F0F479B8F8197694B30184B0D2ED1C1CD2A1EC0FB85D299A192A447

hashed = digest --algo sha512 --file ./myfile.txt

Aliases:

digest

std::hash::Sha256Sum

var = sha256sum file

Runs SHA-256 hash on the provided file returns the hashed value in hex.

Parameters

The file to hash

Return Value

The hash value in hex or false in case of error. The result will be in lowercase, same as with the core utils with the same name.

Examples

hashed = sha256sum ./myfile.txt

Source:

Show Source

scope::sha256sum::output = digest --algo sha256 --file ${scope::sha256sum::argument::1}
scope::sha256sum::output = lowercase ${scope::sha256sum::output}

Aliases:

sha256sum, sha256sum

std::hash::Sha512Sum

var = sha512sum file

Runs SHA-512 hash on the provided file returns the hashed value in hex.

Parameters

The file to hash

Return Value

The hash value in hex or false in case of error. The result will be in lowercase, same as with the core utils with the same name.

Examples

hashed = sha512sum ./myfile.txt

Source:

Show Source

scope::sha512sum::output = digest --algo sha512 --file ${scope::sha512sum::argument::1}
scope::sha512sum::output = lowercase ${scope::sha512sum::output}

Aliases:

sha512sum, sha512sum

std::json

The json module provides json parsing and encoding capabilities.
Parsing and encoding JSONs can be do to/from simple variables or to collections (maps/arrays).
By default, when parsing a JSON string, the structure will be represented by simple variables.
The root object (or simple value) will be set in the json_parse output variable and any sub structure will be defined as variables with prefix of the root variable name.
Object nodes, will have the value of: [OBJECT].
Array nodes will have a length variable defined, for example: arr.length
If the --collections flag is provided, parsing will return the JSON value or a handle to a collection which will hold the values (or sub collections).
These collections are better way to handling unknown json structures but must be released with the release --recursive command.

Because duckscript variables have no type, the json_encode will define every boolean/numeric value as JSON string.

Below is a simple example showing how to parse and encode values of all types when using the default behaviour of storing to variables.

fn test_simple_types
    str = json_parse \"myvalue\"
    assert_eq ${str} myvalue
    jsonstring = json_encode str
    assert_eq ${jsonstring} \"myvalue\"

    number = json_parse 500
    assert_eq ${number} 500
    jsonstring = json_encode number
    # numeric value is encoded as string
    assert_eq ${jsonstring} \"500\"

    bool = json_parse true
    assert_eq ${bool} true
    jsonstring = json_encode bool
    # boolean value is encoded to string
    assert_eq ${jsonstring} \"true\"

    arr = json_parse "[1, 2, 3]"
    # arr.length is not part of the JSON structure but added as a variable to enable
    # to loop over the array using the range command
    assert_eq ${arr.length} 3
    # direct array location access example
    assert_eq ${arr[0]} 1
    assert_eq ${arr[1]} 2
    assert_eq ${arr[2]} 3
    # array loop example
    arr_range = range 0 ${arr.length}
    for index in ${arr_range}
        expected_value = calc ${index} + 1
        value = get_by_name arr[${index}]
        assert_eq ${value} ${expected_value}
    end

    object = json_parse "{\"str\": \"my string value\", \"number\": 500, \"bool\": true, \"array\": [1, 2, 3]}"
    assert_eq ${object} [OBJECT]
    assert_eq ${object.str} "my string value"
    assert_eq ${object.number} 500
    assert_eq ${object.bool} true
    assert_eq ${object.array.length} 3
    assert_eq ${object.array[0]} 1
    assert_eq ${object.array[1]} 2
    assert_eq ${object.array[2]} 3
    jsonstring = json_encode object
    found = contains ${jsonstring} "\"str\":\"my string value\""
    assert ${found}
    found = contains ${jsonstring} "\"number\":\"500\""
    assert ${found}
    found = contains ${jsonstring} "\"bool\":\"true\""
    assert ${found}
    found = contains ${jsonstring} "\"array\":[\"1\",\"2\",\"3\"]"
    assert ${found}

    # we can cleanup all variables created from the json parse starting from the root object
    unset_all_vars --prefix object
    defined = is_defined object
    assert_false ${defined}
    defined = is_defined object.str
    assert_false ${defined}
    defined = is_defined object.array.length
    assert_false ${defined}
end

std::json::Encode

string = json_encode (--collection handle | var_name)

This function will encode all variables, starting from the root variable as a JSON string.
Since duckscript is untyped, all boolean and numeric values will be encoded as strings.
If --collection is passed, the provided value is considered as string or a map/array handle which is used to fetch the tree data and create the json string.

Parameters

  • Option --collection flag to make the encoding use the maps/arrays and values
  • The root variable name (or a handle/value in case --collection is provided)

Return Value

The JSON string

Examples

# will parse and encode to plain variables
package = json_parse "{\"name\": \"my package\", \"version\": 1, \"publish\": false, \"keywords\": [\"test1\", \"test2\"], \"directories\": {\"test\": \"spec\"}}"
jsonstring = json_encode package

# will parse and encode to maps/arrays
package = json_parse --collection "{\"name\": \"my package\", \"version\": 1, \"publish\": false, \"keywords\": [\"test1\", \"test2\"], \"directories\": {\"test\": \"spec\"}}"
jsonstring = json_encode --collection ${package}

Aliases:

json_encode

std::json::Parse

var = json_parse [--collection] string

This function will parse the provided JSON string and will create variables based on the parsed data.
The variables will reflect the json structure.
Object keys will have name using the json path standard, for example root.child
And arrays will have the array access annotation and length variable, for example:

root.child[5]
root.child.length

In case the --collection flag is provided, it will instead create maps/array as needed and return the root handle (or primitive value) of the json data. Make sure to use the release with the recursive flag on the root object to release the entire memory once done.

Parameters

  • Optional --collection flag to parse and return value/map/array
  • The JSON string to parse.

Return Value

The root value/handle.

Examples

# parse to simple variables
package = json_parse "{\"name\": \"my package\", \"version\": 1, \"publish\": false, \"keywords\": [\"test1\", \"test2\"], \"directories\": {\"test\": \"spec\"}}"

assert_eq ${package} "[OBJECT]"
assert_eq ${package.name} "my package"
assert_eq ${package.version} 1
assert_eq ${package.publish} false
assert_eq ${package.keywords.length} 2
assert_eq ${package.keywords[0]} test1
assert_eq ${package.keywords[1]} test2
assert_eq ${package.directories.test} spec

# parse to maps/arrays
package = json_parse --collection "{\"name\": \"my package\", \"version\": 1, \"publish\": false, \"keywords\": [\"test1\", \"test2\"], \"directories\": {\"test\": \"spec\"}}"
name = map_get ${package} name
assert_eq ${name} "my package"
version = map_get ${package} version
assert_eq ${version} 1
public = map_get ${package} public
assert_false ${public}
keywords_handle = map_get ${package} keywords
length = array_length ${keywords_handle}
assert_eq ${length} 2
value = array_pop ${keywords_handle}
assert_eq ${value} test2
value = array_pop ${keywords_handle}
assert_eq ${value} test1
directories = map_get ${package} directories
directory = map_get ${directories} test
assert_eq ${directory} spec
release --recursive ${package}

Aliases:

json_parse

std::lib::alias::Set

var = alias command arguments

This command enables to define new commands with default arguments.
The new alias can be invoked with additional arguments that will be appended to the default set.

Parameters

Any number of arguments which will be added to the already defined arguments set during the aliasing.

Return Value

true if the alias was created, else false.

Examples

# This example creates a new **my_echo** alias that will print the prefix before the requested arguments.
created = alias my_echo echo [ECHO]

# This will print "[ECHO] hello world "
created = my_echo hello world

Aliases:

alias

std::lib::alias::Unset

unalias name

Removes previously defined alias and return true/false based if an alias was actually removed.

Parameters

The alias name to remove.

Return Value

A true/false value in case an alias with the provided name existed.

Examples

alias my_echo echo [ECHO]

# This will print "[ECHO] hello world "
my_echo hello world

unalias my_echo

# This will error
echo The script will now error as my_echo is no longer defined
my_echo hello world

Aliases:

unalias

std::lib::command::Remove

remove_command name

Removes a command and all its aliases.

Parameters

The command or alias name to remove.

Return Value

A true/false value in case a command was removed.

Examples

remove_command set

Aliases:

remove_command

std::math::Calc

var = calc [operation]

The calc command accepts multiple arguments which make up a mathematical operation which will be calculated and its result will be returned.

Parameters

Any number of arguments which will construct a line to calculate.

Return Value

The result of the mathematical calculation.

Examples

# result is 36
result = calc 1 + 5 * 7

Aliases:

calc

std::math::GreaterThan

var = greater_than left right

This command returns true/false based on left > right calculation.

Parameters

Two numeric values to compare.

Return Value

True if first argument is bigger than second argument.

Examples

result = greater_than 2 1.5

Aliases:

greater_than

std::math::HexDecode

num = hex_decode str

Decode a hexadecimal string to the corresponding integer number.
No support for negative numbers.

Parameters

A hexadecimal string.

Return Value

The corresponding integer number.

Examples

hex_num = set 0xff
num = hex_decode ${hex_num}
res = calc ${num} + 1

assert_eq ${res} 256

Aliases:

hex_decode

std::math::HexEncode

str = hex_encode num

Converts an integer number to the corresponding hexadecimal string.
No support for negative numbers.

Parameters

An integer number.

Return Value

The corresponding hexadecimal string.

Examples

str = hex_encode 255

assert_eq ${str} 0xff

Aliases:

hex_encode

std::math::LessThan

var = less_than left right

This command returns true/false based on left < right calculation.

Parameters

Two numeric values to compare.

Return Value

True if first argument is smaller than second argument.

Examples

result = less_than 1 1.5

Aliases:

less_than

std::net::Hostname

var = hostname

Returns the hostname.

Parameters

None

Return Value

The hostname

Examples

name = hostname

Aliases:

hostname

std::net::HttpClient

var = http_client [--method method] [--payload payload] [--output-file file] URL

Invokes a HTTP request.
The request method by default is GET but can be modified by the --method parameter.
The --output-file parameter will redirect a valid response output to the provided file, otherwise all response text will be set to the output variable.
When redirecting to file, the output would be the response size.
The --payload parameter enables to pass a payload to POST http requests.
In case of errors or error HTTP response codes, false will be returned.

Parameters

  • Optional HTTP Method, for example --method GET or --method POST (currently only GET and POST are supported).
  • Optional post payload via --payload parameter.
  • Optional redirection of output to file via --output-file parameter.
  • The target URL

Return Value

The response text or in case of output redirection to file, the response size.
In case of errors, it will return false.

Examples

function test_get
    response = http_client https://www.rust-lang.org/

    found = contains ${response} Rust

    assert ${found}
end

function test_get_to_file
    file = set ./target/_duckscript_test/http_client/page.html
    rm ${file}

    response_size = http_client --output-file ${file} https://www.rust-lang.org/

    response = readfile ${file}
    found = contains ${response} Rust

    assert ${found}
    assert ${response_size}
end

function test_post
    payload = set {\"login\":\"login\",\"password\":\"password\"}
    response = http_client --method POST --payload ${payload} https://reqbin.com/echo/post/json

    found = contains ${response} success

    assert ${found}
end

Aliases:

http_client

std::net::WGet

var = wget [--method=HTTP-method] [--post-data=payload] [-O file] URL

Invokes a HTTP request.
The request method by default is GET but can be modified by the --method parameter.
The -O parameter will redirect a valid response output to the provided file, otherwise all response text will be set to the output variable.
When redirecting to file, the output would be the response size.
The --post-data parameter enables to pass a payload to POST http requests.
In case of errors or error HTTP response codes, false will be returned.

Parameters

  • Optional HTTP Method, for example --method=HTTP-GET or --method=HTTP-POST (currently only GET and POST are supported).
  • Optional post payload via --post-data parameter.
  • Optional redirection of output to file via -O parameter.
  • The target URL

Return Value

The response text or in case of output redirection to file, the response size.
In case of errors, it will return false.

Examples

function test_get
    response = wget https://www.rust-lang.org/

    found = contains ${response} Rust

    assert ${found}
end

function test_get_to_file
    file = set ./target/_duckscript_test/wget/page.html
    rm ${file}

    response_size = wget -O ${file} https://www.rust-lang.org/

    response = readfile ${file}
    found = contains ${response} Rust

    assert ${found}
    assert ${response_size}
end

function test_post
    payload = set {\"login\":\"login\",\"password\":\"password\"}
    response = wget --method=HTTP-POST --post-data=${payload} https://reqbin.com/echo/post/json

    found = contains ${response} success

    assert ${found}
end

Source:

Show Source

scope::wget::url = array_pop ${scope::wget::arguments}

scope::wget::method = set GET

scope::wget::lookingfor = set flag
for scope::wget::arg in ${scope::wget::arguments}
    if equals ${scope::wget::lookingfor} flag
        if starts_with ${scope::wget::arg} --method=HTTP-
            scope::wget::len = strlen --method=HTTP-
            scope::wget::method = substring ${scope::wget::arg} ${scope::wget::len}
        elif starts_with ${scope::wget::arg} --post-data=
            scope::wget::len = strlen --post-data=
            scope::wget::payload = substring ${scope::wget::arg} ${scope::wget::len}
        elif equals ${scope::wget::arg} -O
            scope::wget::lookingfor = set file
        end
    elif equals ${scope::wget::lookingfor} file
        scope::wget::file = set ${scope::wget::arg}
        scope::wget::lookingfor = set flag
    end
end

http_client --method "${scope::wget::method}" --output-file "${scope::wget::file}" --payload "${scope::wget::payload}" ${scope::wget::url}

Aliases:

wget

std::net::ftp::Get

result = ftp_get --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>] [--type <A/I>] --remote-file <file name> --local-file <file name>

Invokes the FTP GET command from the given connection and file details.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on
  • --type - Optional setting of the transfer type as A (ascii) I (image, binary)
  • --remote-file - The remote file to download
  • --local-file - The target local file name

Return Value

true if operation was completed.

Examples

ftp_get --host myhost --username someuser --password 12345 --remote-file README.md --local-file README.md

Aliases:

ftp_get

std::net::ftp::GetInMemory

handle = ftp_get_in_memory --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>] [--type <A/I>] --remote-file <file name>

Invokes the FTP GET command from the given connection and file details.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on
  • --type - Optional setting of the transfer type as A (ascii) I (image, binary)
  • --remote-file - The remote file to download

Return Value

The binary data handle.

Examples

handle = ftp_get_in_memory --host myhost --username someuser --password 12345 --remote-file README.md
text = bytes_to_string ${handle}

Aliases:

ftp_get_in_memory

std::net::ftp::List

handle = ftp_list --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>]

Invokes the FTP LIST command from the given connection details and path.
Returns a handle to an array of all response entries.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on

Return Value

A handle to an array holding all entries.

Examples

handle = ftp_list --host myhost --username someuser --password 12345

for entry in ${handle}
    echo ${entry}
end

Aliases:

ftp_list

std::net::ftp::NLst

handle = ftp_nlst --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>]

Invokes the FTP NLST command from the given connection details and path.
Returns a handle to an array of all response entries.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on

Return Value

A handle to an array holding all entries.

Examples

handle = ftp_nlst --host myhost --username someuser --password 12345

for entry in ${handle}
    echo ${entry}
end

Aliases:

ftp_nlst

std::net::ftp::Put

result = ftp_put --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>] [--type <A/I>] --remote-file <file name> --local-file <file name>

Invokes the FTP PUT command from the given connection and file details.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on
  • --type - Optional setting of the transfer type as A (ascii) I (image, binary)
  • --remote-file - The remote file to upload
  • --local-file - The source local file to upload

Return Value

true if operation was completed.

Examples

ftp_put --host myhost --username someuser --password 12345 --remote-file README.md --local-file README.md

Aliases:

ftp_put

std::net::ftp::PutInMemory

result = ftp_put_in_memory --host <hostname> [--port 21] [--username <user name>] [--password <password>] [--path <path>] [--type <A/I>] --remote-file <file name> --content <content>

Invokes the FTP PUT command from the given connection and file details.

Parameters

  • --host - The host name or IP to connect to
  • --port - Optional port number to use (by default 21)
  • --username - Optional user name used to login (if not user or password provided, no login operation will be invoked)
  • --password - Optional password used to login (if not user or password provided, no login operation will be invoked)
  • --path - Optional path on the remote server to invoke operation on
  • --type - Optional setting of the transfer type as A (ascii) I (image, binary)
  • --remote-file - The remote file to upload
  • --content - The textual content to upload

Return Value

true if operation was completed.

Examples

ftp_put_in_memory --host myhost --username someuser --password 12345 --remote-file README.md --content "This is the README content"

Aliases:

ftp_put_in_memory

std::process::Execute

exec [--fail-on-error|--get-exit-code] [--input value] command [args]*

output = exec command [args]*
stdout = set ${output.stdout}
stderr = set ${output.stderr}
exit_code = set ${output.code}

exit_code = exec --get-exit-code command [args]*

Executes the provided native command and arguments.
If no output variable is set, the command output will be flushed to the main out/err stream of the parent process.
In addition, in order to fail the command in case of the child process failed, add the --fail-on-error flag.
If an output variable is set, it will be used as a base variable name from which the command stout, stderr and exit code information can be pulled from.
The actual output variable name will not be modified, instead new variables will be created using that variable name as a baseline:

  • output.stdout - Will hold the stdout text content.
  • output.stderr - Will hold the stderr text content.
  • output.code - Will hold the process exit code.

If an output variable is set and the --get-exit-code flag is provided, the output will only contain the exit code.

Parameters

  • --fail-on-error - If no output variable is provided, it will cause an error in case the executed process exits with an error exit code.
  • --get-exit-code - If an output variable is provided, it will contain the exit code.
  • --input - Optional content to be sent to the child process input stream.
  • The command to execute and its arguments.

Return Value

Optionally a base name to access the process stout, stderr and exit code information.

Examples

# Example of running a command and flushing its output to the parent process.
exec echo hello world

# Example of running a command and storing its output.
output = exec echo hello world

stdout = set ${output.stdout}
stderr = set ${output.stderr}
exit_code = set ${output.code}

echo stdout: ${stdout}
echo stderr: ${stderr}
echo exit code: ${exit_code}

Aliases:

exec

std::process::Exit

code = exit [code]

Exits the script with the given code stored in the output variable.

Parameters

A number as exit code or none for 0.

Return Value

The exit code.

Examples

# exit with code '0'
code = exit

# exit with code '1'
code = exit 1

Aliases:

exit, quit, q

std::process::ProcessID

var = pid

Returns the current process ID.

Parameters

None

Return Value

The current process ID.

Examples

id = pid

Aliases:

pid, process_id

std::process::Spawn

pid = spawn [--silent] [--input value] command [args]*

Executes the provided native command and arguments.
It will not wait for the process to finish and will return the process pid.

Parameters

  • Optional --silent flag to suppress any output.
  • --input - Optional content to be sent to the child process input stream.
  • The command to execute and its arguments.

Return Value

The process pid.

Examples

pid = spawn echo test

echo PID: ${pid}

Aliases:

spawn

std::process::Watchdog

count = watchdog [--max-retries value] [--interval value] [--input value] -- command [arguments]*

Executes the provided native command and arguments.
In case the command exited it will be executed again up to the max retries provided.
The watchdog will wait the specified interval in milliseconds between invocations.
In case of an invalid command, the watchdog will not reattempt the invocation and will exit without retries.

Parameters

  • --max-retries - Value of max retries (excluding the first invocation). value < 0 for unlimited retries. Default is unlimited.
  • --interval - The amount in milliseconds between retries. 0 for no waiting between invocations. Default is no wait.
  • --input - Optional content to be sent to the child process input stream.
  • The command to execute (preceded by a -- separator).
  • The command arguments.

Return Value

The amount of invocations or false in case of any error.

Examples

count = watchdog --max-retries 0 -- echo test
assert_eq ${count} 1

count = watchdog --max-retries 3 --interval 10 -- echo test
assert_eq ${count} 4

Aliases:

watchdog

std::random::Range

output = random_range min max

Generate a random value in the range of min and max values provided, i.e. inclusive of min and exclusive of max.

Parameters

  • min - The min range value (inclusive)
  • max - The max range value (exclusive)

Return Value

The generated numeric value.

Examples

value = random_range -10 10
echo ${value}

Aliases:

random_range, rand_range

std::random::Text

output = random_text [length]

Generates random alphanumeric text with the requested length (length is 1 if not provided).

Parameters

Optional text length. Length is defaulted to 1 if not provided.

Return Value

The generated alphanumeric value.

Examples

value = random_text 50
echo ${value}

Aliases:

random_text, rand_text

std::scope::Clear

clear_scope name

Clears all variables which are prefixed with the provided name + ::.
For example, if the value provided is my_scope all variables that start with my_scope:: will be removed.

Parameters

The scope name.

Return Value

None.

Examples

testscope = set true
testscope::1 = set 1
testscope::subscope::1 = set 1

assert_eq ${testscope} true
defined = is_defined testscope::1
assert ${defined}
assert_eq ${testscope::1} 1
defined = is_defined testscope::subscope::1
assert ${defined}
assert_eq ${testscope::subscope::1} 1

clear_scope testscope

assert_eq ${testscope} true

defined = is_defined testscope::1
assert_false ${defined}
defined = is_defined testscope::subscope::1
assert_false ${defined}

Aliases:

clear_scope

std::scope::PopStack

scope_pop_stack [--copy name1 name2 ...]

Removes all known variables except for the variables provided by the optional --copy argument and than restores the previously pushed stack.
Functions with the annotation will automatically invoke this command when they end or return a value.

Parameters

Optional variable names to keep.

Return Value

None.

Examples

var1 = set 1
var2 = set 2

scope_push_stack --copy var2

defined = is_defined var1
echo ${defined}
defined = is_defined var2
echo ${defined}

var3 = set 3
var4 = set 4

scope_pop_stack --copy var4

defined = is_defined var1
echo ${defined}
defined = is_defined var2
echo ${defined}
defined = is_defined var3
echo ${defined}
defined = is_defined var4
echo ${defined}

Aliases:

scope_pop_stack

std::scope::PushStack

scope_push_stack [--copy name1 name2 ...]

Removes all known variables except for the variables provided by the optional --copy argument.
Functions with the annotation will automatically invoke this command and keep only the relevant function arguments in the new scope.

Parameters

Optional variable names to keep.

Return Value

None.

Examples

var1 = set 1
var2 = set 2

scope_push_stack --copy var2

defined = is_defined var1
echo ${defined}
defined = is_defined var2
echo ${defined}

Aliases:

scope_push_stack

std::semver::IsEqual

output = semver_is_equal value1 value2

Returns true if both semver values are valid and equal.

Parameters

Two semver values to compare.

Return Value

True if both semver values are valid and equal, else false.

Examples

equal = semver_is_equal 1.2.3 1.2.3
assert ${equal}

equal = semver_is_equal 1.2.3 2.2.3
assert_false ${equal}

Aliases:

semver_is_equal

std::semver::IsNewer

output = semver_is_newer newer older

Returns true if both semver values are valid and first value is newer.

Parameters

  • The expected newer value
  • The expected older value

Return Value

True if both semver values are valid and first value is newer, else false.

Examples

newer = semver_is_newer 3.2.3 2.2.3
assert ${newer}

newer = semver_is_newer 1.2.3 2.2.3
assert_false ${newer}

newer = semver_is_newer 1.2.3 1.2.3
assert_false ${newer}

Aliases:

semver_is_newer

std::semver::Parse

base = semver_parse value

Parses the provided value and sets the major, minor and patch variables.
The variable names are based on the output variable name, for example if the output variable name is out:

  • out.major - Holds the output major version
  • out.minor - Holds the output minor version
  • out.patch - Holds the output patch version

Parameters

The semver value.

Return Value

The major, minor and patch values.

Examples

version = semver_parse 1.2.3

echo ${version.major}
echo ${version.minor}
echo ${version.patch}

Aliases:

semver_parse

std::string::Base64

var = base64 [-e] [-encode] [-d] [-decode] value

Invokes the base64 encode/decode command with the provided value.
This command allows for a more similar cli command which wraps the base64_encode and base64_decode commands.

Parameters

  • Optional -e or -encode flags to set the mode to encode (default)
  • Optional -d or -decode flags to set the mode to decode
  • The value, in case of encoding this is the binary handle, in case of decoding this is the base64 textual value.

Return Value

  • In case of encoding, the base64 textual value will be returned.
  • In case of decoding, a handle to the binary data will be returned.

Examples

handle = string_to_bytes "hello world"
text = base64 ${handle}
release ${handle}
assert_eq ${text} aGVsbG8gd29ybGQ=

handle = base64 -decode ${text}
text = bytes_to_string ${handle}
release ${handle}
assert_eq ${text} "hello world"

Source:

Show Source

scope::base64::input_data = array_pop ${scope::base64::arguments}
scope::base64::encode = set true

for scope::base64::arg in ${scope::base64::arguments}
    if equals ${scope::base64::arg} -e
         scope::base64::encode = set true
    elif equals ${scope::base64::arg} -encode
         scope::base64::encode = set true
    elif equals ${scope::base64::arg} -d
         scope::base64::encode = set false
    elif equals ${scope::base64::arg} -decode
         scope::base64::encode = set false
    end
end

if ${scope::base64::encode}
    scope::base64::output = base64_encode ${scope::base64::input_data}
else
    scope::base64::output = base64_decode ${scope::base64::input_data}
end

scope::base64::output = set ${scope::base64::output}

Aliases:

base64

std::string::Base64Decode

text = base64_encode handle

Encodes using base64 the provided binary data and returns the encoded text value.
The binary data is provided as a handle.

Parameters

The handle to the binary data to encode.

Return Value

The encoded textual value.

Examples

handle = string_to_bytes "hello world"
text = base64_encode ${handle}

release ${handle}

assert_eq ${text} "hello world"

Aliases:

base64_decode

std::string::Base64Encode

text = base64_encode handle

Encodes using base64 the provided binary data and returns the encoded text value.
The binary data is provided as a handle.

Parameters

The handle to the binary data to encode.

Return Value

The encoded textual value.

Examples

handle = string_to_bytes "hello world"
text = base64_encode ${handle}

release ${handle}

assert_eq ${text} "hello world"

Aliases:

base64_encode

std::string::BytesToString

text = bytes_to_string handle

Converts the provided UTF-8 binary array to string and returns it.

Parameters

A handle to a binary array holding UTF-8 text.

Return Value

The textual data.

Examples

handle = string_to_bytes "hello world"
text = bytes_to_string ${handle}

release ${handle}

assert_eq ${text} "hello world"

Aliases:

bytes_to_string

std::string::CamelCase

var = camelcase text

Converts the provided string into camel case. All non-alphanumeric characters are ignored.

Parameters

The string to convert.

Return Value

The converted string.

Examples

string = camelcase "hello, world!"
assert_eq ${string} "HelloWorld"

Aliases:

camelcase

std::string::Concat

var = concat [value]*

Concats the provided input into a single string and returns it.

Parameters

Any number of values to concat.

Return Value

The result of the concatenation of all input values.

Examples

output = concat 1 2 3 4
assert_eq ${output} 1234

output = concat 1 "2 3" 4
assert_eq ${output} "12 34"

Source:

Show Source

scope::concat::output = set ""
for scope::concat::arg in ${scope::concat::arguments}
    scope::concat::output = set "${scope::concat::output}${scope::concat::arg}"
end

set ${scope::concat::output}

Aliases:

concat

std::string::Contains

var = contains all partial

Returns true if the first argument contains the value of the second argument.

Parameters

  • The full text to search in
  • The text to search for

Return Value

true if contains.

Examples

# valid conditions
result = contains abcd bc

value = set "some text"
result = contains ${value} "me tex"

# will return false
result = contains abcd b1c

Aliases:

contains

std::string::EndsWith

var = ends_with all partial

Returns true if the first argument ends with the value of the second argument.

Parameters

  • The full text to search in
  • The suffix text to search for

Return Value

true if ends with.

Examples

# valid conditions
result = ends_with abcd abc

value = set "some text"
result = ends_with ${value} "me text"

# will return false
result = ends_with abcd abc

Aliases:

ends_with

std::string::Equals

var = eq value1 value2

Returns true if both provided values are equal.

Parameters

Two values to evaluate if they are equal

Return Value

true if equal.

Examples

# valid conditions
is_same = eq yes yes
is_same = eq false false

value = set "some text"
is_same = eq ${value} "some text"

# will return false
is_same = eq 1 2

Aliases:

equals, eq

std::string::IndexOf

var = indexof full_text text_to_find

This command will attempt to find the text from the second argument inside the text in the first argument.
If found, an index value will be returned, otherwise none is returned.

Parameters

  • The text to search in
  • The text to find

Return Value

The index of the text found or none if not found.

Examples

index = indexof "    some  text   " some 

Aliases:

indexof

std::string::IsEmpty

var = is_empty value

Returns true if the provided value is none or an empty string.

Parameters

The value to validate.

Return Value

True if the provided value is none or an empty string.

Examples

value = set "hello world"
empty = is_empty ${value}

Aliases:

is_empty

std::string::KebabCase

var = kebobcase text

Converts the provided string into kebob case. All non-alphanumeric characters are ignored.

Parameters

The string to convert.

Return Value

The converted string.

Examples

string = kebobcase "Hello, World!"
assert_eq ${string} "hello-world"

Aliases:

kebabcase

std::string::LastIndexOf

var = last_indexof full_text text_to_find

This command will attempt to find the text from the second argument inside the text in the first argument.
If found, an index value will be returned, otherwise none is returned.
Unlike the indexof command, this command will search for text starting at the end, going backwards.

Parameters

  • The text to search in
  • The text to find

Return Value

The index of the text found or none if not found.

Examples

index = last_indexof "    some  text   " some

Aliases:

last_indexof

std::string::Length

var = length text

Returns the text length.

Parameters

The text to extract the length from.

Return Value

The text length value.

Examples

len = length "Hello World"

Aliases:

length, strlen

std::string::Lowercase

var = lowercase text

Converts the provided string into lowercase.

Parameters

The string to convert.

Return Value

The converted string.

Examples

string = lowercase "Hello World"
assert_eq ${string} "hello world"

Aliases:

lowercase

std::string::Replace

var = replace text from to

Returns new value of text after replacing all from values to the provided to values.

Parameters

  • The full text
  • The from text
  • The to text

Return Value

The updated text.

Examples

text = set "my large text value with lots of text"
updated = replace ${text} text stuff

assert_eq ${updated} "my large stuff value with lots of stuff"

Aliases:

replace

std::string::SnakeCase

var = snakecase text

Converts the provided string into snake case. All non-alphanumeric characters are ignored.

Parameters

The string to convert.

Return Value

The converted string.

Examples

string = snakecase "Hello, World!"
assert_eq ${string} "hello_world"

Aliases:

snakecase

std::string::Split

handle = split text pattern

Splits the provided text based on the provided pattern and return a handle the created array with all the split values.

Parameters

  • The text to split
  • The pattern to split by

Return Value

A handle to the values array.

Examples

handle = split a23b23c23d23e 23

len = array_length ${handle}

value = array_pop ${handle}
assert_eq ${value} e
value = array_pop ${handle}
assert_eq ${value} d
value = array_pop ${handle}
assert_eq ${value} c
value = array_pop ${handle}
assert_eq ${value} b
value = array_pop ${handle}
assert_eq ${value} a

release ${handle}

assert_eq ${len} 5

Aliases:

split

std::string::StartsWith

var = starts_with all partial

Returns true if the first argument starts with the value of the second argument.

Parameters

  • The full text to search in
  • The prefix text to search for

Return Value

true if starts with.

Examples

# valid conditions
result = starts_with abcd abc

value = set "some text"
result = starts_with ${value} "some te"

# will return false
result = starts_with abcd bcd

Aliases:

starts_with

std::string::StringToBytes

handle = string_to_bytes text

Converts the provided string into binary format and returns a handle to the binary data.

Parameters

The text to convert.

Return Value

A handle to the binary data.

Examples

handle = string_to_bytes "hello world"
text = bytes_to_string ${handle}

release ${handle}

assert_eq ${text} "hello world"

Aliases:

string_to_bytes

std::string::SubString

var = substring text
var = substring text start end
var = substring text start
var = substring text -end

The substring command will create a new string value from the text provided in the range requested.

Parameters

  • The text to substring from
  • Additional parameters
    • None - start index is 0 and end index is the text length
    • Two arguments - First is the start index and second is the end index
    • One argument
      • If >= 0 it defines the start index and end index is the text length
      • If < 0 it defines the end index going backwards from the end of the text. Start index is 0.

Return Value

The substring value or false in case of error.

Examples

# string is 'Hello World'
string = substring "Hello World"
echo ${string}

# string is 'll'
string = substring "Hello World" 2 4
echo ${string}

# string is 'llo World'
string = substring "Hello World" 2
echo ${string}

# string is 'Hello W'
string = substring "Hello World" -4
echo ${string}

Aliases:

substring

std::string::Trim

var = trim value

Returns the provided value with leading and trailing whitespace removed.

Parameters

The value to trim.

Return Value

The trimmed value. If no input provided, this command will return none.

Examples

# trimmed will now hold "some  text"
trimmed = trim "  some  text   "

Aliases:

trim

std::string::TrimEnd

var = trim_end value

Returns the provided value with trailing whitespace removed.

Parameters

The value to trim.

Return Value

The trimmed value. If no input provided, this command will return none.

Examples

# trimmed will now hold "  some  text"
trimmed = trim_end "  some  text   "

Aliases:

trim_end

std::string::TrimStart

var = trim_start value

Returns the provided value with leading whitespace removed.

Parameters

The value to trim.

Return Value

The trimmed value. If no input provided, this command will return none.

Examples

# trimmed will now hold "some  text   "
trimmed = trim_start "  some  text   "

Aliases:

trim_start

std::string::Uppercase

var = uppercase text

Converts the provided string into uppercase.

Parameters

The string to convert.

Return Value

The converted string.

Examples

string = uppercase "Hello World"
assert_eq ${string} "HELLO WORLD"

Aliases:

uppercase

std::test::Assert

assert value [error message]

Used to validate the input is truthy.
If the value is one of the following:

  • No output
  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

It is considered falsy and will exist with an error.

Parameters

  • The value to evaluate
  • Optional error message

Return Value

true if truthy.

Examples

# valid conditions
assert ok
assert true
assert yes

value = set "some text"
assert ${value}

# error conditions (each one will break the execution)
assert
assert false
assert 0
assert false "This is my error message"

Aliases:

assert

std::test::AssertEquals

assert_eq value1 value2 [error message]

Used to validate the input is the same.
If they are not, the command will exist with an error.

Parameters

  • Two values to evaluate if they are equal
  • Optional error message

Return Value

true if equal.

Examples

# valid conditions
assert_eq yes yes
assert_eq false false

value = set "some text"
assert_eq ${value} "some text"

# error conditions (each one will break the execution)
assert_eq 1 2
assert_eq 1 2 "This is my error message"

Aliases:

assert_eq

std::test::AssertError

assert_error [error message]

This command will cause a runtime error which will not stop the script execution.
If error message is provided, it will be used as part of the error output.

Parameters

Optional error message.

Return Value

None

Examples

assert_error

assert_error "This is my error message"

Aliases:

assert_error

std::test::AssertFail

assert_fail [error message]

This command will exist with an error.
If error message is provided, it will be used as part of the error output.

Parameters

Optional error message.

Return Value

None

Examples

assert_fail

assert_fail "This is my error message"

Aliases:

assert_fail

std::test::AssertFalse

assert_false value [error message]

Used to validate the input is falsy.
If the value is one of the following:

  • No output
  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

It is considered falsy.

Parameters

  • The value to evaluate
  • Optional error message

Return Value

true if falsy.

Examples

# valid conditions
assert_false
assert_false false
assert_false 0
assert_false false "This is my error message"

# error conditions (each one will break the execution)
assert_false ok
assert_false true
assert_false yes

value = set "some text"
assert_false ${value}

Aliases:

assert_false

std::test::TestDirectory

test_directory directory [pattern]

This command can be used to run unit tests written in duckscript.
It will run all duckscript files in the directory tree ending with test.ds and for each file, it will run all functions that start with test_.
Each such function is considered as a test and can run any type of code and check itself using assert commands.

Parameters

  • The root directory of all test files (all files ending with test.ds in the directory tree will be checked)
  • Optional pattern for the file name or test function to limit invocation of only those tests.

Return Value

true if successful.

Examples

This is an example of a test function:

function test_set_get_unset
    unset_env TEST_SET_GET_UNSET
    value = get_env TEST_SET_GET_UNSET
    assert_false ${value}

    value = set_env TEST_SET_GET_UNSET "test value"
    assert ${value}
    value = get_env TEST_SET_GET_UNSET
    assert_eq ${value} "test value"
end

Aliases:

test_directory

std::test::TestFile

test_file file [test name]

This command can be used to run unit tests written in duckscript.
It will run all test functions that start with test_ in the given file.
Each such function is considered as a test and can run any type of code and check itself using assert commands.

Parameters

  • The file name containing the test functions.
  • Optional pattern for the test function to limit invocation of only those tests.

Return Value

true if successful.

Examples

This is an example of a test function:

function test_set_get_unset
    unset_env TEST_SET_GET_UNSET
    value = get_env TEST_SET_GET_UNSET
    assert_false ${value}

    value = set_env TEST_SET_GET_UNSET "test value"
    assert ${value}
    value = get_env TEST_SET_GET_UNSET
    assert_eq ${value} "test value"
end

Aliases:

test_file

std::thread::Sleep

sleep millies

Will cause the script execution to half for the given amount of milliseconds.
The command will also return the amount of milliseconds waited.

Parameters

A positive numeric value.

Return Value

The amount of milliseconds waited.

Examples

# will sleep for 10 milliseconds
time = sleep 10
echo Waited for ${time} milliseconds.

Aliases:

sleep

std::time::CurrentTimeMillies

var = current_time

Returns the current time in milliseconds (from January 1, 1970 UTC).

Parameters

None

Return Value

The current time in milliseconds.

Examples

result = current_time
echo ${result}

Aliases:

current_time

std::var::GetAllVarNames

handle = get_all_var_names

Creates an array holding all currently known variable names and returns the array handle.

Parameters

None

Return Value

A handle to the array.

Examples

handle = get_all_var_names

# once done we should release the handle
release ${handle}

Aliases:

get_all_var_names

std::var::GetByName

var = get_by_name name

This command returns the variable value based on the given variable name.
It is similar to

var = set ${name}

However, it allows for a dynamic variable name.

Parameters

The variable name.

Return Value

The variable value or none if no such variable exists.

Examples

var = set test
value = get_by_name var
defined = is_defined value

assert ${defined}
assert_eq ${value} test

Aliases:

get_by_name

std::var::IsDefined

var = is_defined key

Returns true if the provided variable name (not value) exists.

Parameters

The variable name.

Return Value

True if the variable is defined.

Examples

key = set "hello world"
exists = is_defined key

Aliases:

is_defined

std::var::Set

var = set arg [or arg]*

The set command will simply return the provided argument and set it to the output variable.
In case the argument is falsy it will attempt to provide another value if an 'or' keyword is set.

A value is considered falsy if it is one of the following:

  • false (case insensitive)
  • 0
  • no (case insensitive)
  • Empty value

Parameters

The argument to set or an 'or' conditional arguments.

Return Value

The first truthy value

Examples

# Return simple 'hello' text value
var = set hello

# Return expanded value: 'home: ....'
var = set "home: ${HOME}"

value = set test or false
assert_eq ${value} test

value = set 0 or no or false or NO or FALSE
assert_eq ${value} FALSE

Aliases:

set

std::var::SetByName

var = set_by_name name [value]

This command sets the variable value based on the variable name.
It is similar to

name = set ${value}

However, it allows for a dynamic variable name.

Parameters

  • The variable name.
  • The new variable value, if not provided, the variable will be unset.

Return Value

The new variable value.

Examples

var = set test
value = get_by_name var
defined = is_defined value

assert ${defined}
assert_eq ${value} test

Aliases:

set_by_name

std::var::Unset

unset [names]*

Undefines all the variable names provided.

Parameters

A list of variable names to undefine.

Return Value

None

Examples

var = set 1
defined = is_defined var
assert ${defined}
unset var
defined = is_defined var
assert_false ${defined}

Source:

Show Source

for scope::unset::name in ${scope::unset::arguments}
    set_by_name ${scope::unset::name}
end

Aliases:

unset

std::var::UnsetAllVars

handle = unset_all_vars [--prefix value]

Removes all known variables.
If the prefix is provided, only variables starting with the prefix value will be removed.

Parameters

  • Optional variable name prefix

Return Value

None

Examples

fn test_remove_all
    a = set 1
    b = set 2

    defined = is_defined a
    assert ${defined}
    defined = is_defined b
    assert ${defined}

    unset_all_vars

    defined = is_defined a
    assert_false ${defined}
    defined = is_defined b
    assert_false ${defined}
end

fn test_remove_by_prefix
    root1 = set true
    root1.child = set true
    root12 = set true

    root2 = set true

    defined = is_defined root1
    assert ${defined}
    defined = is_defined root1.child
    assert ${defined}
    defined = is_defined root12
    assert ${defined}
    defined = is_defined root2
    assert ${defined}

    unset_all_vars --prefix root1

    defined = is_defined root1
    assert_false ${defined}
    defined = is_defined root1.child
    assert_false ${defined}
    defined = is_defined root12
    assert_false ${defined}
    defined = is_defined root2
    assert ${defined}
end

Aliases:

unset_all_vars

License

Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license.