std::Echo
(echo)std::Eval
(eval)std::IsCommandDefined
(is_command_defined)std::Noop
(noop)std::Not
(not)std::Print
(print)std::Println
(println)std::ReadUserInput
(read)std::Release
(release)std::ShowCommandDocumentation
(man)std::collections
std::collections::Array
(array)std::collections::ArrayClear
(array_clear)std::collections::ArrayConcat
(array_concat)std::collections::ArrayContains
(array_contains)std::collections::ArrayGet
(array_get)std::collections::ArrayIsEmpty
(array_is_empty)std::collections::ArrayJoin
(array_join)std::collections::ArrayLength
(array_length, arrlen, array_size)std::collections::ArrayPop
(array_pop)std::collections::ArrayPush
(array_push, array_add, array_put)std::collections::ArrayRemove
(array_remove)std::collections::ArraySet
(array_set)std::collections::IsArray
(is_array)std::collections::IsMap
(is_map)std::collections::IsSet
(is_set)std::collections::Map
(map)std::collections::MapClear
(map_clear)std::collections::MapContainsKey
(map_contains_key)std::collections::MapContainsValue
(map_contains_value)std::collections::MapGet
(map_get)std::collections::MapIsEmpty
(map_is_empty)std::collections::MapKeys
(map_keys)std::collections::MapLoadProperties
(map_load_properties)std::collections::MapPut
(map_put, map_add)std::collections::MapRemove
(map_remove)std::collections::MapSize
(map_size)std::collections::MapToProperties
(map_to_properties)std::collections::Range
(range)std::collections::ReadProperties
(read_properties)std::collections::Set
(set_new)std::collections::SetClear
(set_clear)std::collections::SetContains
(set_contains)std::collections::SetFromArray
(set_from_array)std::collections::SetIsEmpty
(set_is_empty)std::collections::SetPut
(set_put, set_add)std::collections::SetRemove
(set_remove)std::collections::SetSize
(set_size)std::collections::SetToArray
(set_to_array)std::collections::WriteProperties
(write_properties)std::debug::DuckscriptSDKVersion
(duckscript_sdk_version)std::debug::DuckscriptVersion
(duckscript_version)std::debug::DumpInstructions
(dump_instructions)std::debug::DumpState
(dump_state)std::debug::DumpVariables
(dump_variables)std::env::EnvToMap
(env_to_map)std::env::FindExecutable
(which)std::env::GetCpuCount
(cpu_count, get_cpu_count)std::env::GetHomeDirectory
(get_home_dir)std::env::GetOSFamily
(os_family)std::env::GetOSName
(os_name)std::env::GetOSRelease
(os_release)std::env::GetOSVersion
(os_version)std::env::GetUserName
(whoami, get_user_name)std::env::GetVar
(get_env)std::env::IsWindows
(is_windows)std::env::PrintCurrentDirectory
(pwd, print_current_directory)std::env::PrintEnv
(print_env, printenv)std::env::SetCurrentDirectory
(cd, set_current_dir, set_current_directory)std::env::SetVar
(set_env)std::env::UName
(uname)std::env::UnsetVar
(unset_env)std::error::GetLastError
(get_last_error)std::error::GetLastErrorLine
(get_last_error_line)std::error::GetLastErrorSource
(get_last_error_source)std::error::SetError
(set_error)std::error::SetExitOnError
(exit_on_error, set_exit_on_error)std::error::TriggerError
(trigger_error)std::flowcontrol::ForIn
(for)std::flowcontrol::Function
(function, fn)std::flowcontrol::GoTo
(goto)std::flowcontrol::If
(if)std::flowcontrol::While
(while)std::fs::Append
(appendfile)std::fs::CPGlob
(glob_cp, cp_glob)std::fs::CopyPath
(cp)std::fs::CreateDirectory
(mkdir)std::fs::CreateEmptyFile
(touch)std::fs::DeleteEmptyDirectory
(rmdir)std::fs::DeletePath
(rm)std::fs::Exists
(is_path_exists)std::fs::GetCanonicalPath
(canonicalize)std::fs::GetFileName
(basename)std::fs::GetFileSize
(get_file_size, filesize)std::fs::GetLastModifiedTime
(get_last_modified_time)std::fs::GetParentDirectory
(dirname)std::fs::GitIgnorePathArray
(gitignore_path_array)std::fs::GlobArray
(glob_array, globarray)std::fs::IsDirectory
(is_directory, is_dir)std::fs::IsFile
(is_file)std::fs::IsPathNewer
(is_path_newer)std::fs::IsReadonly
(is_readonly)std::fs::JoinPath
(join_path)std::fs::List
(ls)std::fs::MovePath
(mv)std::fs::Print
(cat)std::fs::ReadBytes
(readbinfile, read_binary_file)std::fs::ReadText
(readfile, read_text_file)std::fs::SetMode
(chmod)std::fs::SetModeGlob
(glob_chmod, chmod_glob)std::fs::TempDirectory
(temp_dir)std::fs::TempFile
(temp_file)std::fs::WriteBytes
(writebinfile, write_binary_file)std::fs::WriteText
(writefile, write_text_file)std::hash::Digest
(digest)std::hash::Sha256Sum
(sha256sum, sha256sum)std::hash::Sha512Sum
(sha512sum, sha512sum)std::json
std::json::Encode
(json_encode)std::json::Parse
(json_parse)std::lib::alias::Set
(alias)std::lib::alias::Unset
(unalias)std::lib::command::Remove
(remove_command)std::math::Calc
(calc)std::math::GreaterThan
(greater_than)std::math::HexDecode
(hex_decode)std::math::HexEncode
(hex_encode)std::math::LessThan
(less_than)std::net::Hostname
(hostname)std::net::HttpClient
(http_client)std::net::WGet
(wget)std::net::ftp::Get
(ftp_get)std::net::ftp::GetInMemory
(ftp_get_in_memory)std::net::ftp::List
(ftp_list)std::net::ftp::NLst
(ftp_nlst)std::net::ftp::Put
(ftp_put)std::net::ftp::PutInMemory
(ftp_put_in_memory)std::process::Execute
(exec)std::process::Exit
(exit, quit, q)std::process::ProcessID
(pid, process_id)std::process::Spawn
(spawn)std::process::Watchdog
(watchdog)std::random::Range
(random_range, rand_range)std::random::Text
(random_text, rand_text)std::scope::Clear
(clear_scope)std::scope::PopStack
(scope_pop_stack)std::scope::PushStack
(scope_push_stack)std::semver::IsEqual
(semver_is_equal)std::semver::IsNewer
(semver_is_newer)std::semver::Parse
(semver_parse)std::string::Base64
(base64)std::string::Base64Decode
(base64_decode)std::string::Base64Encode
(base64_encode)std::string::BytesToString
(bytes_to_string)std::string::CamelCase
(camelcase)std::string::Concat
(concat)std::string::Contains
(contains)std::string::EndsWith
(ends_with)std::string::Equals
(equals, eq)std::string::IndexOf
(indexof)std::string::IsEmpty
(is_empty)std::string::KebabCase
(kebabcase)std::string::LastIndexOf
(last_indexof)std::string::Length
(length, strlen)std::string::Lowercase
(lowercase)std::string::Replace
(replace)std::string::SnakeCase
(snakecase)std::string::Split
(split)std::string::StartsWith
(starts_with)std::string::StringToBytes
(string_to_bytes)std::string::SubString
(substring)std::string::Trim
(trim)std::string::TrimEnd
(trim_end)std::string::TrimStart
(trim_start)std::string::Uppercase
(uppercase)std::test::Assert
(assert)std::test::AssertEquals
(assert_eq)std::test::AssertError
(assert_error)std::test::AssertFail
(assert_fail)std::test::AssertFalse
(assert_false)std::test::TestDirectory
(test_directory)std::test::TestFile
(test_file)std::thread::Sleep
(sleep)std::time::CurrentTimeMillies
(current_time)std::var::GetAllVarNames
(get_all_var_names)std::var::GetByName
(get_by_name)std::var::IsDefined
(is_defined)std::var::Set
(set)std::var::SetByName
(set_by_name)std::var::Unset
(unset)std::var::UnsetAllVars
(unset_all_vars)
echo [arg]*
The echo command will printout all provided arguments.
After all input is done, an end of line will be printed as well.
Any number of arguments may be provided and will be printed.
The amount of arguments printed.
# Print multiple arguments:
echo hello world
# Print multiple spaces between words
echo "hello world"
echo
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}.
Any number of arguments which will construct a line to evaluate and execute.
The result of the evaluated line.
command = set echo
eval ${command} hello world
eval
var = is_command_defined key
Returns true if the provided command name exists.
The command name.
True if the command exists.
exists = is_command_defined exec
is_command_defined
noop
Empty function that does nothing and returns none.
All parameters are ignored
None
noop
noop
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.
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.
The switched value of the input.
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
not
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.
- 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.
The amount of arguments printed.
# 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
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.
- 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.
The amount of arguments printed.
# 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
println
var = read
Reads the user input into the output variable.
If the user didn't insert any input, none will be returned.
None
The user input or none if no input was entered.
echo Enter Full Name:
name = read
if is_empty ${name}
echo You didn't enter any value
else
echo Your name is: ${name}
end
read
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/...
- Optional recursive (-r/--recursive) flag (default false)
- The handle name.
- true - If a handle was found and removed
- false - If no handle was found
release ${array_handle}
release
var = man command
Prints and returns the help documentation of the provided command.
The command name.
The help documentation or if not found, none.
man set
man
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.
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.
Any number of arguments which will construct the array.
A handle to the array.
handle = array ${var} "hello world" 5 ${another_var}
# once done we should release the handle
release ${handle}
array
result = array_clear handle
Clears the provided array.
The array handle.
True if successful.
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}
array_clear
handle = array_concat [handle]*
Concats all provided arrays and returns a handle to a new array with all items.
Any number of array handles.
A handle to the new array.
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}
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}
array_concat
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.
- The array handle.
- The value
The value index in the array or false if not found.
handle = array value1 value2 value3
index = array_contains ${handle} value2
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}
array_contains
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.
- The array handle.
- The element index.
The element at the given index from the array or none.
handle = array 1 2 3
element = array_get ${handle} 2
assert_eq ${element} 3
array_get
var = array_is_empty handle
Returns true if the provided array handle is an empty array.
The array handle.
True if the provided handle belongs to an empty array.
values = array
out = array_is_empty ${values}
Show Source
scope::array_is_empty::length = array_length ${scope::array_is_empty::argument::1}
equals 0 ${scope::array_is_empty::length}
array_is_empty
var = array_join handle separator
Joins all values in the provided array with the provided separator in between each value.
- An array handle
- The separator to put between each item pair
The joined string value
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
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}
array_join
var = array_length handle
Returns the array length based on the provided array handle.
The array handle.
The array length.
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}
array_length, arrlen, array_size
var = array_pop handle
Returns the last element of the array or none if the array is empty.
The array handle.
The last element of the array or none if the array is empty.
handle = array 1 2 3
last_element = array_pop ${handle}
assert_eq ${last_element} 3
array_pop
var = array_push handle value
Pushes an additional value to an existing array.
The array handle.
True if a new value was pushed.
handle = array 1 2 3
array_push ${handle} 4
last_element = array_pop ${handle}
assert_eq ${last_element} 4
array_push, array_add, array_put
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.
- The array handle.
- The element index.
True if successful.
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}
array_remove
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.
- The array handle.
- The element index.
- The element value.
True if successful.
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
array_set
var = is_array handle
Returns true if the provided value is an array handle.
The array handle.
True if the provided value is an array handle.
arr = array 1 2 3
value = is_array ${arr}
assert ${value}
released = release ${arr}
assert ${released}
is_array
var = is_map handle
Returns true if the provided value is a map handle.
The map handle.
True if the provided value is a map handle.
map_handle = map
value = is_map ${map_handle}
assert ${value}
released = release ${map_handle}
assert ${released}
is_map
var = is_set handle
Returns true if the provided value is a set handle.
The set handle.
True if the provided value is a set handle.
handle = set_new 1 2 3
value = is_set ${handle}
assert ${value}
released = release ${handle}
assert ${released}
is_set
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.
None
A handle to the map.
handle = map
# once done we should release the handle
release ${handle}
map
result = map_clear handle
Clears the provided map.
The map handle.
True if successful.
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}
map_clear
var = map_contains_key handle key
Returns true if the provided key was found in the map.
- The map handle.
- The key
True if the key was found in the map.
handle = map
map_put ${handle} key value
found = map_contains_key ${handle} key
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
map_contains_key
var = map_contains_value handle value
Returns true if the provided value was found in the map.
- The map handle.
- The value
True if the value was found in the map.
handle = map
map_put ${handle} key value
found = map_contains_value ${handle} value
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}
map_contains_value
value = map_get handle key
Returns a the value corresponding to the key from the map.
- The map handle.
- The key.
The value corresponding to the key from the map.
handle = map
result = map_put ${handle} key value
assert_eq ${result} true
value = map_get ${handle} key
assert_eq ${value} value
release ${handle}
map_get
var = map_is_empty handle
Returns true if the provided map handle is an empty map.
The map handle.
True if the provided handle belongs to an empty map.
handle = map
map_put ${handle} key value
empty = map_is_empty ${handle}
Show Source
scope::map_is_empty::length = map_size ${scope::map_is_empty::argument::1}
equals 0 ${scope::map_is_empty::length}
map_is_empty
keys = map_keys handle
Returns a handle to an array holding all keys in the provided map handle.
- The map handle.
A handle to an array holding all map keys.
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}
map_keys
var = map_load_properties [--prefix prefix] handle text
Parsers and loads all properties to the provided map.
- Optional --prefix and the prefix value
- The map handle.
- The properties text.
True if successful.
handle = map
result = map_put ${handle} key value
assert_eq ${result} true
value = map_get ${handle} key
assert_eq ${value} value
release ${handle}
map_load_properties
var = map_put handle key value
Inserts a key-value pair into the map.
- The map handle.
- The key.
- The new value.
True if a new value was inserted.
handle = map
result = map_put ${handle} key value
assert_eq ${result} true
value = map_get ${handle} key
assert_eq ${value} value
release ${handle}
map_put, map_add
value = map_remove handle key
Removes a the value corresponding to the key from the map and returns it.
- The map handle.
- The key.
The value corresponding to the key from the map.
handle = map
result = map_put ${handle} key value
assert_eq ${result} true
value = map_remove ${handle} key
assert_eq ${value} value
release ${handle}
map_remove
var = map_size handle
Returns the map size based on the provided map handle.
The map handle.
The map size.
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}
map_size
text = map_to_properties [--prefix prefix] handle
Converts the provided map to properties text.
- Optional --prefix and the prefix value
- The map handle.
The properties text.
handle = map
map_put ${handle} a 1
map_put ${handle} b 2
map_put ${handle} a.b.c 123
text = map_to_properties ${handle}
map_to_properties
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.
- The start numeric value
- The end numeric value which cannot be smaller than the start value.
A handle to the array.
handle = range 1 10
# once done we should release the handle
release ${handle}
range
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.
- Optional --prefix and the prefix value
- The text to parse.
The properties count.
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
read_properties
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.
Any number of arguments which will construct the set.
A handle to the set.
handle = set_new ${var} "hello world" 5 ${another_var}
# once done we should release the handle
release ${handle}
set_new
result = set_clear handle
Clears the provided set.
The set handle.
True if successful.
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}
set_clear
var = set_contains handle value
Returns true if the set contains the provided value.
- The set handle.
- The value
True if the value was found in the set.
handle = set_new value1 value2 value3
found = set_contains ${handle} value2
set_contains
set_handle = set_from_array array_handle
Returns a set handle created from the provided array values.
The array handle.
The new set handle.
array_handle = array value1 value2 value3
set_handle = set_from_array ${handle}
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}
set_from_array
var = set_is_empty handle
Returns true if the provided set handle is an empty set.
The set handle.
True if the provided handle belongs to an empty set.
handle = set
set_put ${handle} value
empty = set_is_empty ${handle}
Show Source
scope::set_is_empty::length = set_size ${scope::set_is_empty::argument::1}
equals 0 ${scope::set_is_empty::length}
set_is_empty
var = set_put handle value
Pushes an additional value to an existing set.
The set handle.
True if a new value was pushed.
handle = set_new 1 2 3
set_put ${handle} 4
size = set_size ${handle}
assert_eq ${size} 4
set_put, set_add
removed = set_remove handle value
Removes a the value from the set and returns true/false if it was removed.
- The set handle.
- The value to remove.
True if the value was found and removed from the set.
handle = set_new
result = set_put ${handle} value
assert_eq ${result} true
removed = set_remove ${handle} value
assert ${removed}
release ${handle}
set_remove
var = set_size handle
Returns the set size based on the provided set handle.
The set handle.
The set size.
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}
set_size
array_handle = set_to_array set_handle
Converts the provided set to an array and returns the new array handle.
The set handle.
The array handle or false in case of error.
set_handle = set_new value1 value2 value3
array_handle = set_to_array ${set_handle}
set_to_array
text = write_properties [--prefix prefix] [names]
Creates a properties string from the provided list of variable names (not values).
- Optional prefix which will be added to all written properties.
- A list of variable names.
The properties text value.
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
write_properties
var = duckscript_sdk_version
Returns the duckscript SDK version.
None
The duckscript SDK version.
version = duckscript_sdk_version
duckscript_sdk_version
var = duckscript_version
Returns the duckscript runtime version.
None
The duckscript runtime version.
version = duckscript_version
duckscript_version
value = dump_instructions
Returns all script instructions structure (not script text) in textual form.
None
The script instructions.
value = dump_instructions
found = contains ${value} dump_instructions
assert found
dump_instructions
value = dump_state
Returns all script state in textual form.
None
The script state.
numbers = range -5 15
text = dump_instructions
found = contains ${text} -5
assert found
dump_state
value = dump_variables
Returns all script variables in textual form.
None
The script variables.
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
dump_variables
handle = env_to_map
Converts all environment variables to a map and returns the map handle.
None
The map handle.
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}
env_to_map
var = which executable
Returns the path to the executable if it exists.
If not found it will return an empty string.
The executable to find.
The executable path or empty string if not found.
path = which echo
which
var = cpu_count
Returns the number of CPUs.
None
The CPU count.
count = cpu_count
cpu_count, get_cpu_count
var = get_home_dir
Returns the user home directory path.
In case of any error, false will be returned.
None
The user home directory path or false in case of any error.
directory = get_home_dir
get_home_dir
var = os_family
Returns the OS family (windows, linux, mac).
None
The OS family (windows, linux, mac).
name = os_family
os_family
var = os_name
Returns the OS name.
None
The OS name.
name = os_name
os_name
var = os_release
Returns the OS release.
This command is not supported on windows.
None
The OS release.
release = os_release
os_release
var = os_version
Returns the OS version.
This command is not supported on windows.
None
The OS version.
version = os_version
os_version
var = whoami
Returns the current user name.
None
The current user name.
name = whoami
whoami, get_user_name
var = get_env key
Returns the environment variable value for the provided key.
First argument is the environment variable key.
The environment variable value.
home = get_env HOME
get_env
var = is_windows
Returns true if the current OS family is windows.
None
True if the current OS family is windows.
windows = is_windows
Show Source
scope::is_windows::os = os_family
equals ${scope::is_windows::os} windows
is_windows
var = pwd
Prints and also returns the current directory.
None
The current directory path.
# Print the current directory:
pwd
# Print and also store the current directory:
directory = pwd
pwd, print_current_directory
var = printenv
Prints and returns all environment variables.
None
All environment variables printout text.
set_env TEST_PRINT_ENV TRUE
text = printenv
valid = contains ${text} TEST_PRINT_ENV=TRUE
assert ${valid}
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}
print_env, printenv
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.
The new current directory.
The new current directory or none in case of any error such as target directory not found.
# Move to user home directory and store the path in the home variable
home = cd
# Move to the requested directory
cd ./scripts
cd, set_current_dir, set_current_directory
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.
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
true if successful
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}
set_env
var = uname [-a]
Acts similar to uname on unix like systems.
- Optional -a for extended information (not supported on windows).
The OS name and optionally extra information.
value = uname -a
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}
uname
unset_env key
Removes the environment variable defined by the provided key.
The name of the environment variable to remove
None
unset_env HOME
unset_env
var = get_last_error
In case of any runtime error, this function will return the error message.
None
The last error message or none
# This will trigger an error
assert_fail
error = get_last_error
echo Error Message: ${error}
get_last_error
var = get_last_error_line
In case of any runtime error, this function will return the error line (if available).
None
The last error line or none
# This will trigger an error
assert_fail
line = get_last_error_line
echo Error Line: ${line}
get_last_error_line
var = get_last_error_source
In case of any runtime error, this function will return the error source (such as file name) if available.
None
The last error source or none
# This will trigger an error
assert_fail
source = get_last_error_source
echo Error Source File: ${source}
get_last_error_source
set_error message
Sets the last error which is accessible via get_last_error.
This command will not trigger the on_error command flow.
The error message.
None
set_error "my error message"
error = get_last_error
assert_eq ${error} "my error message"
set_error
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.
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.
The current/updated state as true/false value
# 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}
exit_on_error, set_exit_on_error
trigger_error [message]
Triggers an error that will trigger the on_error flow.
Optional error message.
None
trigger_error "my error message"
error = get_last_error
assert_eq ${error} "my error message"
trigger_error
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.
- 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
None
# 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
for
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.
- 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.
The function invocation returns the output provided by the return command.
# 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}
function, fn
goto :label
The goto command enables you to jump to any position in the script, if that position has a label value.
A single valid label value.
None
goto :good
echo bad
:good echo good
goto
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.
- 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
None
# 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
if
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.
- 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
None
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
while
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.
- The target file
- The text content to write
true/false based if it was able to write the text to the file.
out = appendfile ./target/tests/writefile.txt "line 1\nline 2"
appendfile
result = glob_cp source_glob target
This command will copy all files that match the given glob.
- The source glob, for example ./*.txt
- The target path
The amount of paths (files) copied or false in case of any error.
count = glob_cp ./**/*.txt ../target
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}
glob_cp, cp_glob
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.
- The source path to copy
- The target path
true if the path was copied.
# copy a single file
copied = cp ./file1.txt ./file2.txt
# copy a directory
copied = cp ./source ./target
cp
var = mkdir directory
This command will create the requested directory (and needed parent directories) and return true/false if it was successful.
The directory name to create.
The operation success value - true if directory exists, else false.
exists = mkdir ./dir/subdir
mkdir
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.
The file path.
If the file exists after the command, it will return true.
In case of any error, it will return false.
exists = touch ./dir/file.txt
touch
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.
A single parameter holding the directory path.
true if the directory was deleted.
deleted = rmdir ./mydir
rmdir
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.
- Optional flags (currently only -r is supported which indicates recursive deletion)
- The path/s to delete
true if all paths were deleted.
# 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
rm
var = is_path_exists path
This command will return true/false based if the provided path points to an existing file system entry.
The path to check.
True if the path points to an existing file system entry.
existing = is_path_exists ./dir
existing = is_path_exists ./dir/somefile.txt
is_path_exists
var = canonicalize path
This command will return the c path for the provided input.
In case unable, it will return the original input.
The file/directory path to canonicalize.
The canonicalized path, or if unsuccessful, the original path.
path = canonicalize ./target
canonicalize
var = basename path
This command will return the last path element of the provided path.
If unable, it will return none.
The path to extract the last element from.
The last path element or none if unsuccessful.
file = basename ./dir/file.txt
basename
var = get_file_size path
This command will return the size of the file in bytes.
The path to check.
The size of the file in bytes or false in case path is a directory or does not exist.
size = get_file_size ./dir/somefile.txt
get_file_size, filesize
var = get_last_modified_time path
This command will return the last modified time in millies from unix epoch.
The path to check.
The last modified time in millies from unix epoch or false in case path does not exist.
time = get_last_modified_time ./dir/somefile.txt
get_last_modified_time
var = dirname path
This command will return the parent path of the provided path.
If the parent path is empty, it will return none.
The path to extract the parent path from.
The parent path or none.
directory = dirname ./dir/file.txt
dirname
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.
The root path.
The array handle.
handle = gitignore_path_array ./src
for path in ${handle}
echo ${path}
end
gitignore_path_array
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.
The glob pattern.
The array handle.
handle = glob_array ./somedir/**/*.txt
for path in ${handle}
echo ${path}
end
glob_array, globarray
var = is_dir path
This command will return true/false based if the provided path points to an existing directory.
The path to check.
True if the path points to an existing directory.
existing_dir = is_dir ./dir
is_directory, is_dir
var = is_file path
This command will return true/false based if the provided path points to an existing file.
The path to check.
True if the path points to an existing file.
existing_file = is_file ./dir/somefile.txt
is_file
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.
- newer - The file/directory path to check.
- older - The file/directory path to check.
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.
newer = is_path_newer ./new_file.txt ./old_file.txt
is_path_newer
var = is_readonly path
This command will return true/false based if the provided path exists and is set to readonly.
The path to check.
True if the provided path exists and is set to readonly.
readonly = is_readonly ./dir/somefile.txt
is_readonly
result = join_path path [path]*
Concats all paths and makes sure there is a / character between each path element.
- A list of paths to join
The joined path
joined = join_path /test /dir1 /dir2 dir3 //dir4// /dir5
assert_eq ${joined} /test/dir1/dir2/dir3/dir4/dir5
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}
join_path
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
- Optional flags (currently only -l is supported)
- Optional path (if not provided, current working directory is used)
true is operation was successful.
# 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
ls
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.
- The source path to copy
- The target path
true if the move was successful.
# 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
mv
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.
Multiple file paths.
The file content or none if the file does not exist.
cat ./docs/sdk.md
cat
handle = read_binary_file file
Reads a raw file and returns a handle to the binary data.
A single parameter holding the file path.
The binary data handle.
handle = read_binary_file ./Cargo.toml
text = bytes_to_string ${handle}
readbinfile, read_binary_file
var = readfile file
The readfile command will read the requested file and return the value to the output variable.
A single parameter holding the file path.
The file content or none in case file does not exist.
text = readfile ./Cargo.toml
readfile, read_text_file
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.
- The new mode, for example 755
- The path
The new mode as decimal number or false in case of any error.
chmod 777 ./myfile.txt
chmod
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.
- The new mode, for example 755
- The path glob
The amount of path entries affected by the operation or false in case of any error.
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}
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}
glob_chmod, chmod_glob
path = temp_dir
This command will return the system temporary directory path.
None
The directory path.
path = temp_dir
echo ${path}
temp_dir
path = temp_file [extension]
This command will create a new empty temporary file and return its path.
Optional file extension.
The file path.
path = temp_file toml
echo ${path}
temp_file
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.
- The target file
- The binary data handle
true/false based if it was able to write the binary data to the file.
handle = string_to_bytes "some text"
result = write_binary_file ./target/tests/data.bin ${handle}
writebinfile, write_binary_file
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.
- The target file
- The text content to write
true/false based if it was able to write the text to the file.
result = writefile ./target/tests/writefile.txt "line 1\nline 2"
writefile, write_text_file
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.
- --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)
The hash value in hex or false in case of error.
hashed = digest --algo sha256 "hello world\n"
assert_eq ${hashed} A948904F2F0F479B8F8197694B30184B0D2ED1C1CD2A1EC0FB85D299A192A447
hashed = digest --algo sha512 --file ./myfile.txt
digest
var = sha256sum file
Runs SHA-256 hash on the provided file returns the hashed value in hex.
The file to hash
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.
hashed = sha256sum ./myfile.txt
Show Source
scope::sha256sum::output = digest --algo sha256 --file ${scope::sha256sum::argument::1}
scope::sha256sum::output = lowercase ${scope::sha256sum::output}
sha256sum, sha256sum
var = sha512sum file
Runs SHA-512 hash on the provided file returns the hashed value in hex.
The file to hash
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.
hashed = sha512sum ./myfile.txt
Show Source
scope::sha512sum::output = digest --algo sha512 --file ${scope::sha512sum::argument::1}
scope::sha512sum::output = lowercase ${scope::sha512sum::output}
sha512sum, sha512sum
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
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.
- 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)
The JSON string
# 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}
json_encode
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.
- Optional --collection flag to parse and return value/map/array
- The JSON string to parse.
The root value/handle.
# 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}
json_parse
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.
Any number of arguments which will be added to the already defined arguments set during the aliasing.
true if the alias was created, else false.
# 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
alias
unalias name
Removes previously defined alias and return true/false based if an alias was actually removed.
The alias name to remove.
A true/false value in case an alias with the provided name existed.
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
unalias
remove_command name
Removes a command and all its aliases.
The command or alias name to remove.
A true/false value in case a command was removed.
remove_command set
remove_command
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.
Any number of arguments which will construct a line to calculate.
The result of the mathematical calculation.
# result is 36
result = calc 1 + 5 * 7
calc
var = greater_than left right
This command returns true/false based on left > right calculation.
Two numeric values to compare.
True if first argument is bigger than second argument.
result = greater_than 2 1.5
greater_than
num = hex_decode str
Decode a hexadecimal string to the corresponding integer number.
No support for negative numbers.
A hexadecimal string.
The corresponding integer number.
hex_num = set 0xff
num = hex_decode ${hex_num}
res = calc ${num} + 1
assert_eq ${res} 256
hex_decode
str = hex_encode num
Converts an integer number to the corresponding hexadecimal string.
No support for negative numbers.
An integer number.
The corresponding hexadecimal string.
str = hex_encode 255
assert_eq ${str} 0xff
hex_encode
var = less_than left right
This command returns true/false based on left < right calculation.
Two numeric values to compare.
True if first argument is smaller than second argument.
result = less_than 1 1.5
less_than
var = hostname
Returns the hostname.
None
The hostname
name = hostname
hostname
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.
- 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
The response text or in case of output redirection to file, the response size.
In case of errors, it will return false.
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
http_client
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.
- 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
The response text or in case of output redirection to file, the response size.
In case of errors, it will return false.
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
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}
wget
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.
- --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
true if operation was completed.
ftp_get --host myhost --username someuser --password 12345 --remote-file README.md --local-file README.md
ftp_get
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.
- --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
The binary data handle.
handle = ftp_get_in_memory --host myhost --username someuser --password 12345 --remote-file README.md
text = bytes_to_string ${handle}
ftp_get_in_memory
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.
- --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
A handle to an array holding all entries.
handle = ftp_list --host myhost --username someuser --password 12345
for entry in ${handle}
echo ${entry}
end
ftp_list
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.
- --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
A handle to an array holding all entries.
handle = ftp_nlst --host myhost --username someuser --password 12345
for entry in ${handle}
echo ${entry}
end
ftp_nlst
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.
- --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
true if operation was completed.
ftp_put --host myhost --username someuser --password 12345 --remote-file README.md --local-file README.md
ftp_put
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.
- --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
true if operation was completed.
ftp_put_in_memory --host myhost --username someuser --password 12345 --remote-file README.md --content "This is the README content"
ftp_put_in_memory
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.
- --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.
Optionally a base name to access the process stout, stderr and exit code information.
# 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}
exec
code = exit [code]
Exits the script with the given code stored in the output variable.
A number as exit code or none for 0.
The exit code.
# exit with code '0'
code = exit
# exit with code '1'
code = exit 1
exit, quit, q
var = pid
Returns the current process ID.
None
The current process ID.
id = pid
pid, process_id
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.
- 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.
The process pid.
pid = spawn echo test
echo PID: ${pid}
spawn
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.
- --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.
The amount of invocations or false in case of any error.
count = watchdog --max-retries 0 -- echo test
assert_eq ${count} 1
count = watchdog --max-retries 3 --interval 10 -- echo test
assert_eq ${count} 4
watchdog
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.
- min - The min range value (inclusive)
- max - The max range value (exclusive)
The generated numeric value.
value = random_range -10 10
echo ${value}
random_range, rand_range
output = random_text [length]
Generates random alphanumeric text with the requested length (length is 1 if not provided).
Optional text length. Length is defaulted to 1 if not provided.
The generated alphanumeric value.
value = random_text 50
echo ${value}
random_text, rand_text
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.
The scope name.
None.
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}
clear_scope
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.
Optional variable names to keep.
None.
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}
scope_pop_stack
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.
Optional variable names to keep.
None.
var1 = set 1
var2 = set 2
scope_push_stack --copy var2
defined = is_defined var1
echo ${defined}
defined = is_defined var2
echo ${defined}
scope_push_stack
output = semver_is_equal value1 value2
Returns true if both semver values are valid and equal.
Two semver values to compare.
True if both semver values are valid and equal, else false.
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}
semver_is_equal
output = semver_is_newer newer older
Returns true if both semver values are valid and first value is newer.
- The expected newer value
- The expected older value
True if both semver values are valid and first value is newer, else false.
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}
semver_is_newer
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
The semver value.
The major, minor and patch values.
version = semver_parse 1.2.3
echo ${version.major}
echo ${version.minor}
echo ${version.patch}
semver_parse
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.
- 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.
- In case of encoding, the base64 textual value will be returned.
- In case of decoding, a handle to the binary data will be returned.
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"
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}
base64
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.
The handle to the binary data to encode.
The encoded textual value.
handle = string_to_bytes "hello world"
text = base64_encode ${handle}
release ${handle}
assert_eq ${text} "hello world"
base64_decode
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.
The handle to the binary data to encode.
The encoded textual value.
handle = string_to_bytes "hello world"
text = base64_encode ${handle}
release ${handle}
assert_eq ${text} "hello world"
base64_encode
text = bytes_to_string handle
Converts the provided UTF-8 binary array to string and returns it.
A handle to a binary array holding UTF-8 text.
The textual data.
handle = string_to_bytes "hello world"
text = bytes_to_string ${handle}
release ${handle}
assert_eq ${text} "hello world"
bytes_to_string
var = camelcase text
Converts the provided string into camel case. All non-alphanumeric characters are ignored.
The string to convert.
The converted string.
string = camelcase "hello, world!"
assert_eq ${string} "HelloWorld"
camelcase
var = concat [value]*
Concats the provided input into a single string and returns it.
Any number of values to concat.
The result of the concatenation of all input values.
output = concat 1 2 3 4
assert_eq ${output} 1234
output = concat 1 "2 3" 4
assert_eq ${output} "12 34"
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}
concat
var = contains all partial
Returns true if the first argument contains the value of the second argument.
- The full text to search in
- The text to search for
true if contains.
# valid conditions
result = contains abcd bc
value = set "some text"
result = contains ${value} "me tex"
# will return false
result = contains abcd b1c
contains
var = ends_with all partial
Returns true if the first argument ends with the value of the second argument.
- The full text to search in
- The suffix text to search for
true if ends with.
# 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
ends_with
var = eq value1 value2
Returns true if both provided values are equal.
Two values to evaluate if they are equal
true if equal.
# 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
equals, eq
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.
- The text to search in
- The text to find
The index of the text found or none if not found.
index = indexof " some text " some
indexof
var = is_empty value
Returns true if the provided value is none or an empty string.
The value to validate.
True if the provided value is none or an empty string.
value = set "hello world"
empty = is_empty ${value}
is_empty
var = kebobcase text
Converts the provided string into kebob case. All non-alphanumeric characters are ignored.
The string to convert.
The converted string.
string = kebobcase "Hello, World!"
assert_eq ${string} "hello-world"
kebabcase
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.
- The text to search in
- The text to find
The index of the text found or none if not found.
index = last_indexof " some text " some
last_indexof
var = length text
Returns the text length.
The text to extract the length from.
The text length value.
len = length "Hello World"
length, strlen
var = lowercase text
Converts the provided string into lowercase.
The string to convert.
The converted string.
string = lowercase "Hello World"
assert_eq ${string} "hello world"
lowercase
var = replace text from to
Returns new value of text after replacing all from values to the provided to values.
- The full text
- The from text
- The to text
The updated text.
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"
replace
var = snakecase text
Converts the provided string into snake case. All non-alphanumeric characters are ignored.
The string to convert.
The converted string.
string = snakecase "Hello, World!"
assert_eq ${string} "hello_world"
snakecase
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.
- The text to split
- The pattern to split by
A handle to the values array.
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
split
var = starts_with all partial
Returns true if the first argument starts with the value of the second argument.
- The full text to search in
- The prefix text to search for
true if starts with.
# 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
starts_with
handle = string_to_bytes text
Converts the provided string into binary format and returns a handle to the binary data.
The text to convert.
A handle to the binary data.
handle = string_to_bytes "hello world"
text = bytes_to_string ${handle}
release ${handle}
assert_eq ${text} "hello world"
string_to_bytes
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.
- 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.
The substring value or false in case of error.
# 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}
substring
var = trim value
Returns the provided value with leading and trailing whitespace removed.
The value to trim.
The trimmed value. If no input provided, this command will return none.
# trimmed will now hold "some text"
trimmed = trim " some text "
trim
var = trim_end value
Returns the provided value with trailing whitespace removed.
The value to trim.
The trimmed value. If no input provided, this command will return none.
# trimmed will now hold " some text"
trimmed = trim_end " some text "
trim_end
var = trim_start value
Returns the provided value with leading whitespace removed.
The value to trim.
The trimmed value. If no input provided, this command will return none.
# trimmed will now hold "some text "
trimmed = trim_start " some text "
trim_start
var = uppercase text
Converts the provided string into uppercase.
The string to convert.
The converted string.
string = uppercase "Hello World"
assert_eq ${string} "HELLO WORLD"
uppercase
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.
- The value to evaluate
- Optional error message
true if truthy.
# 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"
assert
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.
- Two values to evaluate if they are equal
- Optional error message
true if equal.
# 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"
assert_eq
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.
Optional error message.
None
assert_error
assert_error "This is my error message"
assert_error
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.
Optional error message.
None
assert_fail
assert_fail "This is my error message"
assert_fail
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.
- The value to evaluate
- Optional error message
true if falsy.
# 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}
assert_false
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.
- 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.
true if successful.
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
test_directory
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.
- The file name containing the test functions.
- Optional pattern for the test function to limit invocation of only those tests.
true if successful.
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
test_file
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.
A positive numeric value.
The amount of milliseconds waited.
# will sleep for 10 milliseconds
time = sleep 10
echo Waited for ${time} milliseconds.
sleep
var = current_time
Returns the current time in milliseconds (from January 1, 1970 UTC).
None
The current time in milliseconds.
result = current_time
echo ${result}
current_time
handle = get_all_var_names
Creates an array holding all currently known variable names and returns the array handle.
None
A handle to the array.
handle = get_all_var_names
# once done we should release the handle
release ${handle}
get_all_var_names
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.
The variable name.
The variable value or none if no such variable exists.
var = set test
value = get_by_name var
defined = is_defined value
assert ${defined}
assert_eq ${value} test
get_by_name
var = is_defined key
Returns true if the provided variable name (not value) exists.
The variable name.
True if the variable is defined.
key = set "hello world"
exists = is_defined key
is_defined
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
The argument to set or an 'or' conditional arguments.
The first truthy value
# 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
set
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.
- The variable name.
- The new variable value, if not provided, the variable will be unset.
The new variable value.
var = set test
value = get_by_name var
defined = is_defined value
assert ${defined}
assert_eq ${value} test
set_by_name
unset [names]*
Undefines all the variable names provided.
A list of variable names to undefine.
None
var = set 1
defined = is_defined var
assert ${defined}
unset var
defined = is_defined var
assert_false ${defined}
Show Source
for scope::unset::name in ${scope::unset::arguments}
set_by_name ${scope::unset::name}
end
unset
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.
- Optional variable name prefix
None
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
unset_all_vars
Developed by Sagie Gur-Ari and licensed under the Apache 2 open source license.