Str type
Direct parent types
- Eachable1
Eachable which each() calls the callback with one argument Direct subtypes: 17
Constructors
- Str(regexp:RegExp)
Represents RegExp Returns
The string <RegExp>
- Str(r:Real)
Convert Real to Str
- Str(n:Int)
Convert Int to Str
- Str(mm:MultiMethod) Source: stdlib.ngs:428
Undocumented
- Str() Source: stdlib.ngs:473
Make empty string Returns
''
- Str(nm:NativeMethod) Source: stdlib.ngs:501
String representation of native method. Returns
"<NativeMethod NAME(PARAMS)>"Example
(%).Arr()[0].Str().echo() # Outputs: <NativeMethod %(a:Int, b:Int)>
- Str(c:UserDefinedMethod) Source: stdlib.ngs:509
String representation of a closure Returns
StrExample
Real.constructors[-1].Str().echo() # Outputs: <UserDefinedMethod Real at /usr/share/ngs/stdlib.ngs:350>
- Str(i:NormalTypeInstance) Source: stdlib.ngs:773
String representation of normal type instance i Normal type is a user defined type. In addition some types defined by NGS are also normal types. Returns
"<TYPE_NAME field1=val1 field2=val2 ...>"Example
{ type T # nti - Normal type instance nti = T() nti.a = 1 nti.b = 2 echo(Str(nti)) # <T a=1 b=2> }
- Str(a:ArrLike) Source: stdlib.ngs:1941
Convert ArrLike to a human-readable representation
- Str(s:Set) Source: stdlib.ngs:2211
Convert the set to a human-readable representation
- Str(ntc:NormalTypeConstructor) Source: stdlib.ngs:2400
String representation of normal type constructor. NormalTypeConstructor Returns
"<NormalTypeConstructor>"Example
Box.constructors.Arr()[0].Str().echo() # Outputs: <NormalTypeConstructor>
- Str(t:Type) Source: stdlib.ngs:2407
String representation of a type Returns
"<Type NAME>"Example
Real.Str().echo() # Outputs: <Type Real>
- Str(cpm:c_pthread_mutex_t) Source: stdlib.ngs:2593
Convert c_pthread_mutex_t to Str for displaying to humans.
- Str(cpma:c_pthread_mutexattr_t) Source: stdlib.ngs:2596
Convert c_pthread_mutexattr_t to Str for displaying to humans.
- Str(r:Range) Source: stdlib.ngs:2688
Convert range to human readable representation
- Str(r:Results) Source: stdlib.ngs:4400
Undocumented
- Str(s:Str) Source: stdlib.ngs:4731
No-op constructor Returns
s
- Str(n:Null) Source: stdlib.ngs:4735
Convert Null to string Returns
the string "null"
- Str(b:Bool) Source: stdlib.ngs:4736
Undocumented
- Str(a:Arr) Source: stdlib.ngs:4740
Convert Arr to string Returns
Str
- Str(h:Hash) Source: stdlib.ngs:4744
Convert Hash to string Returns
Str
- Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:4889
Convert anything to Str of a given width
- Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:4896
Pad a string to given width with spaces Parameters
target_width Positive pads on right, negative pads on left Example
Str("x", 3) # 'x ' Str("x",-3) # ' x'
- Str(n:Int, target_width:Int, ch:Str=' ') Source: stdlib.ngs:4918
Convert a number to a string and pad it Parameters
target_width Positive pads on left, negative pads on right Example
Str(10, 4) # ' 10' Str(10, -4) # '10 '
- Str(t:c_pthread_t) Source: stdlib.ngs:5415
Undocumented
- Str(t:Thread) Source: stdlib.ngs:5416
Undocumented
- Str(p:Path) Source: stdlib.ngs:5716
String representation of a Path (or it's sub-type) Returns
StrExample
find_in_path("ls").Str() # The string: /bin/ls
- Str(p:Program) Source: stdlib.ngs:5969
Undocumented
- Str(p:Pipe) Source: stdlib.ngs:6148
Undocumented
- Str(r:CommandRedir) Source: stdlib.ngs:6349
Convert CommandRedir to human-readable string. Returns
Str
- Str(p:Process) Source: stdlib.ngs:6558
Wait for the process to finish and return its standard output. Returns
Str
- Str(pp:ProcessesPipeline) Source: stdlib.ngs:6563
Wait for the processes to finish and return standard output of the last process in pipeline. Returns
Str
- Str(s:SubSeq) Source: stdlib.ngs:7481
Undocumented
- Str(t:Time, format:Str='%F %T %Z', gmt:Bool=false) Source: stdlib.ngs:8253
String representation of Time Parameters
format strftime(3) format gmt Use GMT time zone (defaults to local time zone)
- Str(rd:ResDef)
Converts resource definition to a string, for displaying purposes.
- Str(i:ArrIter)
Textual representation of ArrIter. Returns
Str
- Str(i:HashIter)
Textual representation of HashIter. Returns
Str
- Str(r:Res)
Converts resource to a string, for displaying purposes.
- Str(r:AWS::Vpc)
String representation of AWS Vpc
- Str(ds:DelimStr)
Undocumented
- Str(t:Table)
Undocumented
- Str(mp:MethodParams)
Undocumented
- Str(pf:ProcessFail)
Undocumented
- Str(d:Description)
Undocumented
- Str(tvi:ThisVersionIndex)
Undocumented
- Str(md:MarkdownDescription)
Undocumented
- Str(nd:NamespaceDescription)
Undocumented
- Str(gnd:GlobalNamespaceDescription)
Undocumented
Methods
- *(s:Str, n:Int) Source: stdlib.ngs:4884
Repeat string n times Example
"abc" * 3 # "abcabcabc"
- +(s1:Str, s2:Str) Source: stdlib.ngs:2879
Concatenate strings Returns
New StrExample
"ab" + "cd" # "abcd"
- +(s:Str, a:Eachable1) Source: stdlib.ngs:5009
Prepend each line in a with s Returns
Type of ret is same as type of aExample
"a " + ["1", "2"] # ["a 1", "a 2"]
- +(a:Eachable1, s:Str) Source: stdlib.ngs:5019
Append s to each line in a Returns
Type of ret is same as type of aExample
["1", "2"] + " a" # ["1 a", "2 a"]
- +(a:Path, b:Str) Source: stdlib.ngs:5754
Concatenate Returns
Path
- +(a:Str, b:Path) Source: stdlib.ngs:5758
Concatenate Returns
Path
- -(s:Str, pfx:Pfx) Source: stdlib.ngs:7491
Return string without the prefix. Throws InvalidArgument if pfx is MustPfx but s does not start with it. Parameters
s original string pfx prefix to get rid of Returns
s without pfxExample
"abcde" - Pfx("ab") # "cde" "abcde" - Pfx("xy") # InvalidArgument exception "abcde" - MaybePfx("xy") # "abcde"
- -(s:Str, sfx:Sfx) Source: stdlib.ngs:7509
Return string without the suffix. Throws InvalidArgument if pfx is MustSfx but s does not end with it. Parameters
s original string sfx suffix to get rid of Returns
s without pfxExample
"abcde" - Sfx("de") # "abc" "abcde" - Sfx("xy") # InvalidArgument exception "abcde" - MaybeSfx("xy") # "abcde"
- -(s:Str, ifx:Ifx) Source: stdlib.ngs:7526
Return string without the infix. Throws InvalidArgument if ifx is MustIfx but s does not contain it. Parameters
s original string ifx infix to get rid of Returns
s without ifxExample
"abcde" - Ifx("bc") # "ade" "abcde" - Ifx("xy") # InvalidArgument exception "abcde" - MaybeIfx("xy") # "abcde"
- -(s:Str, r:RegExp) Source: stdlib.ngs:7760
Returns the string with one occurrence of regexp cut out of it. Throws InvalidArgument if s does not contain r. Returns
StrExample
"abc01def23" - /[0-9]+/ # "abcdef23"
- .(regexp:RegExp, field:Str)
Get fields of a RegExp. Throws FieldNotFound if field is not one of the allowed values. You should not use this directly. Use "~" and "~~" operators. Parameters
field "options" or "names" Returns
Int for "options". Hash of names/indexes of named groups for "names".Example
/abc/i.options # 1 - case insensitive (C_PCRE_CASELESS) /(?P<name1>abc)/i.names # Name to index Hash: {name1=1}
- .(pa:c_pthread_attr_t, attr:Str)
Get pthread attribute. Currently returns null for unknown attributes. Will throw exceptions in future. Parameters
attr One of: detachstate, guardsize, inheritsched, stacksize.
- .(obj:BasicType, field:Str)
Get BasicType (Int, Arr, Hash, ...) field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Parameters
field Field to get. Currently only "name" and "constructors" are supported. Returns
Str for "name" and MultiMethod for "constructors".Example
Hash.name # String: Hash Hash.constructors # MultiMethod
- .(obj:NormalType, field:Str)
Get NormalType (a type that is typically defined by user) field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Parameters
field Field to get. Currently only "name", "constructors", "parents" and "user" are supported. Returns
Str for "name", MultiMethod for "constructors", Arr for "parents", Any for "user".
- .(obj:NormalTypeInstance, field:Str)
Get NormalType (a type that is typically defined by user) instance field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Returns
AnyExample
type T; t=T(); t.x=1; t.x # 1
- .(h:Hash, field:Str) Source: stdlib.ngs:835
Get hash key. Example
h = {"a": 1} h.a # 1, Same as h["a"]
- .(al:ArrLike, s:Str) Source: stdlib.ngs:1927
Return array made of given field of each element of given array. Will throw KeyNotFound if any of the elements does not have the desired field. Use get() to handle missing field differently.
- .(t:Type, field:Str) Source: stdlib.ngs:2285
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES.NamedInstances
Example
echo(Color.NamedInstances is Namespace) # true
- .(a:Arr, field:Str) Source: stdlib.ngs:2843
Return array made of given field of each element of given array. Will throw KeyNotFound if any of the elements does not have the desired field. Use get() to handle missing field differently. Returns
ArrExample
[{"x": 1}, {"x": 2}].x # [1, 2] [{"x": 1}, {"y": 2}].x # KeyNotFound exception [{"x": 1}, {"y": 2}].get("x") # [1] - skip [{"x": 1}, {"y": 2}].get("x", null) # [1, null] - use default value
- .(t:Type, field:Str) Source: stdlib.ngs:5419
Undocumented
- .=(obj:NormalType, field:Str, v:Any)
Set NormalType (a type that is typically defined by user) field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field = v
Parameters
field Field to set. Currently only "user" is supported. Returns
v
- .=(obj:NormalTypeInstance, field:Str, v:Any)
Set Normal type (a type that is typically defined by user) instance field Automatically called by NGS for syntax
obj.field = v
Returns
vExample
type T; t=T(); t.x=1
- .=(h:Hash, field:Str, v:Any) Source: stdlib.ngs:841
Set hash key. Returns
vExample
h = {"a": 1} h.a = 2 # 2, Same as h["a"] = 2
- .=(t:Type, field:Str, ns:Namespace) Source: stdlib.ngs:2292
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ...
- .=(t:Type, field:Str, a:Arr) Source: stdlib.ngs:2311
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ['SOME', 'NAMES', ...]
- .=(a:Arr, field:Str, e:Eachable1) Source: stdlib.ngs:2853
Set field of every element in array to corresponding item in e. Uses Iter(e) internally. Returns
aExample
a=[{"x": 1}, {"x": 2}] a.y = [10, 20] # a == [{"x": 1, "y": 10}, {"x": 2, "y": 20}]
- /(a:Str, b:Str) Source: stdlib.ngs:5722
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later. Returns
StrExample
mydir="tmp" mydir / "myfile" # "tmp/myfile"
- /(a:Str, b:Str) Source: stdlib.ngs:5729
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later. Returns
StrExample
mydir="tmp/" mydir / "myfile" # "tmp/myfile"
- /(a:Str, b:Str) Source: stdlib.ngs:5738
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later. Returns
StrExample
mydir="./" mydir / "myfile" # "myfile"
- /(a:Path, b:Str) Source: stdlib.ngs:5750
Concatenate two Path-s using /(a:Str, b:Str) Returns
PathExample
Path("tmp") / "v8" # <Path path=tmp/v8>
- //(regexp:Str, flags:Str) Source: stdlib.ngs:7747
Regular expression constructor. Automatically called by NGS for syntax
/myregex/
Returns
RegExpExample
my_re = /blah/
- ::(t:Type, k:Str) Source: stdlib.ngs:2324
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES::INSTANCE_NAME
Example
echo(Color::RED) # <Color numval=4 name=RED>
- <(a:Str, b:Str) Source: stdlib.ngs:4971
Case sensitive LessThan comparison for strings Returns
Bool
- <=(a:Str, b:Str) Source: stdlib.ngs:4961
Case sensitive LessThan or Equal comparison for strings Returns
Bool
- ==(a:Str, b:Str)
Compare strings
- >(a:Str, b:Str) Source: stdlib.ngs:4976
Case sensitive GreaterThan comparison for strings Returns
Bool
- >=(a:Str, b:Str) Source: stdlib.ngs:4966
Case sensitive GreaterThan or Equal comparison for strings Returns
Bool
- [](lib:CLib, symbol:Str)
Unfinished feature. Don't use!
- [](s:Str, range:NumRange)
Get substring Example
"abcd"[1..3] # "bc"
- [](ms:MatchSuccess, name:Str) Source: stdlib.ngs:1014
Get capture by name
- [](s:Str, i:Int) Source: stdlib.ngs:4796
Get given character (currently byte) of the string Parameters
s Original string i Index of the character to return Example
"abc"[0] # "a"
- [](s:Str, i:Int) Source: stdlib.ngs:4806
Get given character (currently byte) of the string (negative indexes handler). Throws IndexNotFound if abs(i) > len(s). Parameters
s Original string. i Negative index of the character to return Example
"abc"[-1] # "c"
- [](s:Str, r:NumRange) Source: stdlib.ngs:4820
Get a substring. Indexes in s are specified by NumRange. Parameters
s Original string r NumRange with negatve .end Returns
StrExample
"(Look ma, no parens)"[1..-1] # "Look ma, no parens"
- [](s:Str, r:RegExp) Source: stdlib.ngs:7785
Get substring of a string that corresponds to first match of given regular expression Example
"x10ab20c30y"[/[0-9]+/] # "10"
- [](mp:MethodParams, k:Str)
Get named parameter
- []=(s:Str, range:NumRange, replacement:Str)
Change substring Returns
replacementExample
s="abcd"; s[1..3]="X"; s # "aXd"
- \(name:Str, attributes:Hash, children:Arr)experimental Source: stdlib.ngs:8663
Undocumented Automatically called by NGS for syntax
\name attr1=val1 attr2=val2 ... [ ... ]
- after_last(s:Str, delim:Str) Source: stdlib.ngs:4870
Split the string by delimiter and return the last part Returns
Str
- Arg(x:Str) Source: stdlib.ngs:6580
Convert to string, appropriate for using as argument to external process. No-op for Str: return the same string. Automatically called by NGS for syntax
$(mycommand $str) # str is Str
- ArgvMatcher(option:Str, value:Any, f:UserDefinedMethod)
Sets ARGV matching option. Parameters
option Option name. The only supported option at this time is "positionals". value Option value. Example
# Any command line argument that is not "allreg" goes to "filters" parameters. ArgvMatcher('positionals', 'filters') do F main(filters:Arr, allreg:Bool=false) ...
- assert(val:Any, pattern:Any, msg:Str='Assertion failed') Source: stdlib.ngs:301
Throws AssertFail with given message if val does not match the pattern Returns
valExample
my_template.get('concept', []).assert(Arr) assert(loginResult, {'access_token': Str}, "access_token must be present in response")
- assert(val:Any, msg:Str='Assertion failed') Source: stdlib.ngs:324
Throws AssertFail with given message if val is falsy Parameters
val if evaluates to false, causes AssertFail exception msg message for the exception, defaults to "Assertion failed" Returns
valExample
my_array=[] # ... Code that adds elements to my_array ... assert(my_array.len() > 3, "my_array must have more than 3 elements") # AssertFail exception, with the given message
- assert(f:Fun, t:Type, msg:Str='Assertion failed') Source: stdlib.ngs:334
Throws AssertFail with given function does not throw exception of the given type. Parameters
f Fun t Subtype of Exception Returns
The exceptionExample
assert({1/0}, DivisionByZero)
- assert_array(actual:Any, title:Str=null)
Assert actual is an Arr. Throws TestFail. Returns
actual
- assert_base(actual:Any, expected:Any, comparison:Any, display_comparison:Any, title:Str, ok_prefix:Any='')internal
A helper used by other assert_* methods. Please do not use directly.
- assert_bool(actual:Any, title:Str=null)
Assert actual is a Bool. Throws TestFail. Returns
actual
- assert_eq(actual:Any, expected:Any, title:Str=null)
Assert equality. Throws TestFail. Returns
actualExample
test("Heavy load on instance", { # do the load assert_eq(`curl -m 1 192.168.10.10/health`, 'OK') })
- assert_exit_code(pp:ProcessesPipeline, expected:Int, title:Str=null)
Assert process exits with the specified exit code. Throws TestFail. Returns
ppExample
p = $(true); assert_exit_code(p, 0) # OK p = $(false); assert_exit_code(p, 1) # OK p = $(false); assert_exit_code(p, 0) # Throws TestFail
- assert_has(actual:Any, expected:Any, title:Str=null)
Assert having specific element or substring (checks with "has"). Throws TestFail. Returns
actualExample
assert_has("abc", "xyz") # Throws TestFail assert_has([1,2,3], 3) # OK
- assert_hash(actual:Any, title:Str=null)
Assert actual is a Hash. Throws TestFail. Returns
actual
- assert_hash_keys(actual:Any, expected:Arr, title:Str='Must be a hash with keys')
Assert actual is a Hash and it has the expected keys. Throws TestFail. Returns
actualExample
assert_hash_keys({}, ['kk']) # Throws TestFail. assert_hash_keys({'kk': 7}, ['kk']) # OK
- assert_hash_keys_values(actual:Any, expected:Hash, title:Str='Must be a hash with keys and values')
Assert actual is a Hash and it has the expected keys with expected values. Throws TestFail. Returns
actualExample
assert_hash_keys_values({'kk': 7}, {'ll': 7}) # Throws TestFail assert_hash_keys_values({'kk': 7, 'll': 8}, {'kk': 7}) # OK
- assert_in(actual:Any, expected:Any, title:Str=null)
Assert element is in an array (or other Eachable1). Throws TestFail. Returns
actualExample
assert_in(10, [10, 2], "test in")
- assert_match(actual:Any, expected:Any, title:Str=null)
Assert actual matches expected. Throws TestFail. Returns
actualExample
assert_match("abc", /^a/, "test match") == "abc"
- assert_min_len(actual:Any, expected:Any, title:Str=null)
Assert actual is of at least specified length. Throws TestFail. Returns
actual
- assert_output_has(pp:ProcessesPipeline, expected:RegExp, title:Str=null)
Assert process has given output. Throws TestFail. Example
assert_output_has($(echo abc), /xyz/) # Throws TestFail p = $(echo abc); assert_output_has(p, /c$/) # OK
- assert_output_has(pp:ProcessesPipeline, expected:Str, title:Str=null)
Assert process has given output. Throws TestFail. Example
assert_output_has($(echo abc), "xyz") # Throws TestFail p = $(echo abc); assert_output_has(p, "bc") # OK
- assert_path_exists(p:Any, title:Str='Check that path exists')
Assert given path exists. Parameters
p Str or Path Returns
p
- assert_resolvable(h:Str, title:Str='Check that host is resolvable', times:Any=45, sleep:Any=2, check:Any=method)
Assert given host is resolvable. Uses "dig" command line utility. Retries "times" times, sleeping "sleep" seconds in between. Throws TestFail. Returns
don't count on return valueExample
assert_resolvable("my_new_host.example.com")
- assert_string(actual:Any, title:Str=null)
Assert actual is a string. Throws TestFail. Returns
actual
- basename(s:Str) Source: stdlib.ngs:6225
Get basename of the file.
- before_first(s:Str, delim:Str) Source: stdlib.ngs:4859
Split the string by delimiter and return the last part Returns
Str
- c_access(pathname:Str, mode:Int)
Call ACCESS(2)
- c_chdir(dir:Str)
Call CHDIR(2)
- c_dlopen(filename:Str, flags:Int)
Unfinished feature. Don't use!
- c_execve(filename:Str, argv:Arr, envp:Arr)
Call EXECVE(2)
- c_lseek(fd:Int, offset:Int, whence:Str)
Call LSEEK(2). Parameters
whence One of: set, cur, end Returns
Int: new offset or -1
- c_lstat(pathname:Str)
Call LSTAT(2) Example
c_lstat("/tmp") # <Stat st_dev=... st_ino=... st_mode=... ...>
- c_open(pathname:Str, flags:Str)
Open a file. Uses OPEN(2). Parameters
flags r - O_RDONLY; w - O_WRONLY | O_CREAT | O_TRUNC; a - O_WRONLY | O_CREAT | O_APPEND Returns
Int - file descriptor or -1
- c_opendir(name:Str)
Call OPENDIR(3)
- c_pcre_compile(regexp:Str, flags:Int)
Throws RegExpCompileFail on errors. Returns
RegExp
- c_pcre_exec(regexp:RegExp, subject:Str, offset:Int, options:Int)
Search string for regular expression. Uses PCRE_EXEC(3). Do not use this function directly! Returns
Int or Arr of Int
- c_realpath(path:Str)
Real path. Uses REALPATH(3). Returns
Str or null
- c_send(socket:Int, buffer:Str, flags:Int)
Undocumented
- c_sockaddr_un(path:Str)
Undocumented
- c_stat(pathname:Str)
Call STAT(2)
- c_strcasecmp(a:Str, b:Str)
Call STRCASECMP(3)
- c_strcmp(a:Str, b:Str)
Call STRCMP(3)
- c_strftime(tm:c_tm, format:Str)
Call STRFTIME(3)
- c_strptime(buf:Str, format:Str)
Call STRPTIME(3) Returns
Arr. [number_of_parsed_chars:Int, result:c_tm]
- c_write(fd:Int, s:Str)
Write to a file. Uses WRITE(2). Returns
Int - number of bytes written or -1
- chdir(s:Str) Source: stdlib.ngs:5848
Change directory. Uses CHDIR(2). Parameters
s Directory to cd to. Returns
null
- code(s:Str) Source: stdlib.ngs:5129
Convert a Str to NGS code that would produce the string when executed. Not fully functional yet. BUG: Does not do escaping. Returns
Str
- collector(s:Str, body:Fun) Source: stdlib.ngs:2786
EXPERIMENTAL! Do not use!
- column(t:Table, k:Str)
Get values in the given table column. Returns
Arr
- compile(code:Str, fname:Str)
Compile NGS source to bytecode. Parameters
fname Source file name for backtraces and error messages. Returns
Str - bytecodeExample
# From bootstrap.ngs, require() definition program_text = fetch(fname) program_bytecode = compile(program_text, fname) program_func = load(program_bytecode, "require()d file: $fname") ret = program_func()
- config(k:Str) Source: stdlib.ngs:7408
Get configuration for the given key. Lookup order / first wins: (1) Environment variable NGS_$k (2) previously set config(k, v) Parameters
k Configuration key Returns
Any. If data found in environment variable, it will be decode()d or returned as Str if decode() fails.Example
conf = config("table_${t.name}")
- config(k:Str, v:Any) Source: stdlib.ngs:7426
Set configuration. To be used with config(k:Str). Example
config('table_Instances', %[InstanceId tag_Name tag_env tag_role IPs InstanceType State KeyName SecurityGroups AZ RestOfTags])
- debug(facility:Str, str_or_producer:Any) Source: stdlib.ngs:5495
Debug to standard error. "DEBUG" environment variable must be non-empty string to activate. Otherwise nothing is outputted. TODO: Exclude thread ID if there is only one thread. TODO: Timestamps? Timestamps acquiring might not be safe after fork before exec.
- decode(s:Str, t:Type)experimental Source: stdlib.ngs:2414
Decode (parse) strings such as command line arguments or environment variables to result given type TODO: Consider renaming to UnArgv or decode_arg
- decode(s:Str, p:Type) Source: stdlib.ngs:5919
Decode Path and its subtypes Returns
instance of Path or a subtype.
- decode(s:Str, hints:Hash={}) Source: stdlib.ngs:7075
Attempt to decode JSON. Uses decode_json().
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7084
EXPERIMENTAL. KVS (key-value separator) hint for decode() Example
decode('a b\nc d', {'KVS': ' '}) == {'a': 'b', 'c': 'd'}
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7093
EXPERIMENTAL. FS (field separator) hint for decode() Example
decode('a b\nc d', {'FS': ' '}) # [['a', 'b'], ['c', 'd']]
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7103
EXPERIMENTAL! Do not use! Handle fields_names hint - run decode() and make Arr[Hash] from Arr[Arr] using provided fields_names Example
backup_list = fetch('backup.list', {'FS': ' ', 'fields_names': %[env role]})
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7113
Decode "curl -i" to {"code": Int, "message": Str, "headers": Hash, "headers_arr": Hash, "body": Str} .body is not recursively decoded Returns
Hash
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7213
Parse the output of "aws" command. Extracts the array (see "s" below"). For "describe-instances", flattens the instance list. Parameters
s Str containing JSON with a Hash at top level with exactly one Arr as value hints hints.process.command.argv[0] must be 'aws' Returns
data structure, typically an Arr at top level. If s is empty string - null.
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7379
Parse the output of "find" command which does not use "-printf". Handles "-print0". Parameters
hints hints.process.command.argv[0] must be 'find' Returns
Arr of Str
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7390
Parse the output of "locate" command. Parameters
hints hints.process.command.argv[0] must be 'locate' Returns
Arr of Str
- decode(s:Str, hints:Hash={}) Source: stdlib.ngs:8849
Decodes JSON Web Token (JWT)
- decode_base64(s:Str)experimental Source: stdlib.ngs:8628
Undocumented
- decode_hex(s:Str) Source: stdlib.ngs:8453
Decodes each two hex digits into a character (byte). Reverse of encode_hex() Returns
Str
- decode_json(s:Str)
Decode (parse) JSON. Returns
AnyExample
decode_json('{"a": 1}') # {a=1}
- decode_uri_component(s:Str) Source: stdlib.ngs:8475
Decodes URI component, unsecaping %XX hexadecimals Example
decode_uri_component("ab%2Bc%25") # "ab+c%"
- die(s:Str, status:Any=1) Source: stdlib.ngs:5546
Write message in s to standard error and exit, printing backtrace Parameters
status converted to exit code using ExitCode()
- digest(a:Arr, chunk_size:Int, marker:Str='(...)') Source: stdlib.ngs:7911
Convert an array to a possibly shorter version, for displaying to human. Parameters
chunk_size number of elements to retain at the beginning and at the end. marker how to mark the cut elements in the middle. Returns
ArrExample
my_array = Arr(1...100) digest(my_array, 2).each(echo) # 1 # 2 # (...) # 99 # 100
- dir(dirname:Str, subtype:Any=false, **kwargs:Hash) Source: stdlib.ngs:5769
List directory contents. Warning: "." and ".." are included. Throws DirFail when directory can not be listed. Parameters
subtype Select type of returned items: true for Path sub-type, false for Path type Returns
Arr of Path or it's sub-typeExample
dir("tmp/v8", true).filter(File) # [ ..., <File path=tmp/v8/README.md fd=null>, <File path=tmp/v8/LICENSE.valgrind fd=null>, ... ] dir("tmp/v8", true).filter(Dir) # [ ..., <Dir path=tmp/v8/tools>, <Dir path=tmp/v8/infra>, ... ]
- dir(dirname:Str, cb:Fun, subtype:Any=false, raw:Any=false) Source: stdlib.ngs:5777
List directory contents and call cb with Path() of each found item. "." and ".." are excluded. Returns
unspecified at this time, do not count on itExample
's=Stats(); dir("tmp/v8", {s.push(A.Type().name)}, true); s # <Stats: {File=23, Dir=16}>'
- each(s:Str, cb:Fun) Source: stdlib.ngs:4759
Iterates over all string characters (currently bytes). Parameters
cb Function to be called with each character from s Returns
sExample
"abc".each(echo) # Output: # a # b # c
- echo(s:Str) Source: stdlib.ngs:141
Print given string and a newline to stdout. Returns
nullExample
echo("blah") # Output: blah
- echo(fd:Int, s:Str) Source: stdlib.ngs:6080
Write a string followed by newline character to a file descriptor. Throws WriteFail on failure. Returns
nullExample
echo(2, "blah") # Output on stderr: blah"
- echo(pp:ProcessesPipeline, s:Str) Source: stdlib.ngs:6959
Write s and newline character(s) to pp
- echo(f:File, s:Str) Source: stdlib.ngs:8570
Write a string followed by newline character to a File. Throws WriteFail on failure. Returns
nullExample
echo(File("1.txt"), "blah")
- echo(t:Terminal, s:Str)
Undocumented
- echo_cli(s:Str)experimental Source: stdlib.ngs:8942
Echo the value before exiting the program, when the value is a result of evaluating the whole program.
- encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:8616
Undocumented
- encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:8622
Undocumented
- encode_hex(s:Str) Source: stdlib.ngs:8442
Encodes each character in a string as two uppercase hexadecimal digits Returns
StrExample
encode_hex("ab") # "6162"
- encode_html(s:Str) Source: stdlib.ngs:8492
Encodes HTML. Escapes &, < and > . Returns
StrExample
"ab>+c%&'".encode_html() # "ab>+c%&'"
- encode_html_attr(s:Str) Source: stdlib.ngs:8500
Encodes HTML attribute. Escapes &, <, >, " and ' . Returns
StrExample
"ab>+c%&'".encode_html_attr() # "ab>+c%&'"
- encode_uri_component(s:Str) Source: stdlib.ngs:8467
Encodes URI component, escaping with %XX hexadecimal codes. Returns
StrExample
encode_uri_component("ab+c%") # "ab%2Bc%25"
- ends_with(haystack:Str, needle:Str) Source: stdlib.ngs:4944
Check whether a string ends with another string Returns
BoolExample
"abcd".ends_with("cd") # true "ab".ends_with("cdab") # false
- error(s:Str) Source: stdlib.ngs:5508
Write error message to standard error. Example
error("Failed to read configuration file. Will clean up and exit now.") # Approximate output on stderr: # [ERROR 2018-01-01 00:00:00 YOUR_TZ] Failed to read configuration file. Will clean up and exit now.
- exec(prog:Str, argv:Arr=[], env:Hash=ENV) Source: stdlib.ngs:6659
Call EXECVE(2) Parameters
argv argv, without the program
- exec(prog:Str, env:Hash=ENV) Source: stdlib.ngs:6662
Call EXECVE(2)
- exit(s:Str, status:Any=1) Source: stdlib.ngs:5554
Write message in s to standard error and exit Parameters
status converted to exit code using ExitCode()
- fetch(filename:Str, decode_hints:Hash={}) Source: stdlib.ngs:6299
read() and decode() the given file Example
fetch("1.json") # Data structure, the parsed JSON
- fetch(url:Str, decode_hints:Hash={}) Source: stdlib.ngs:6307
Fetch HTTP(S) file and decode() it Example
fetch('https://api.myip.com') # Data structure, the parsed JSON
- find_in_path(executable_name:Str) Source: stdlib.ngs:5699
Finds given binary and returns it's full path. Throws ProgramNotFound if the binary was not found. Search strategy: "/" in the name of the binary means that given executable_name is a path so it's returned as-is (wrapped in Path). If PATH environment variable exists, the given directories are searched. If PATH is not set built-in value for PATH is used to search: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin Returns
PathExample
find_in_path("ls") # <Path path=/bin/ls>
- finished_ok(p:Process, field_name:Str, ok:NumRange)internal Source: stdlib.ngs:6377
Decide whether a process finished normally. Example
$(ok:0..10 ls no-such-file)
- finished_ok(p:Process, field_name:Str, ok:Arr)internal Source: stdlib.ngs:6383
Decide whether a process finished normally. Example
$(ok:[0,1,2] ls no-such-file)
- finished_ok(p:Process, field_name:Str, ok:Int)internal Source: stdlib.ngs:6391
Decide whether a process finished normally. Example
$(ok:1 ls no-such-file) # No exception $(ok:10 ls no-such-file) # ProcessFail exception
- finished_ok(p:Process, field_name:Str, ok:Bool)internal Source: stdlib.ngs:6397
Decide whether a process finished normally. Example
# 'ok' option is set to true when the value is missing after ':' $(ok: ls no-such-file)
- finished_ok(program_name:Str, ok:Any)experimental Source: stdlib.ngs:6444
Undocumented
- get(e:Eachable1, field:Str) Source: stdlib.ngs:2866
Return array made of given field of each element of given Eachable1 where present Returns
ArrExample
[{"x": 1}, {"y": 2}].get("x") # [1] ``aws ec2 describe-instances``.Tags.get("role").uniq() # Returns Arr of Str with roles. Does not crash if some machines do not have "role" tag.
- get(e:Eachable1, field:Str, dflt:Any) Source: stdlib.ngs:2874
Return array made of given field of each element of given Eachable1 where present or default value where the field is not present. Returns
ArrExample
[{"x": 1}, {"y": 2}].get("x", null) # [1, null]
- glob(pattern:Str, start_dir:Any='.') Source: stdlib.ngs:5826
Work in progress, do not use!
- global_not_found_handler(name:Str) Source: stdlib.ngs:8772
Called when reading undefined global. Implements autoloading. Searches for autoload/globals/GLOBAL_NAME.ngs in NGS_PATH WARNING: May have security implications when looking up a name from untrusted source. Example
test("My web server runs") do { .... } # autoload/globals/test.ngs is automatically loaded.
- group(e:Eachable1, field:Str) Source: stdlib.ngs:4116
Group items from e by the given field Returns
Hash with Arr valuesExample
[{"id": 100, "a": 1}, {"id": 200, "a": 2}, {"id": 300, "a": 2}].group("a") # {1=[{id=100, a=1}], 2=[{id=200, a=2},{id=300, a=2}]}
- Hash(e:Eachable1, field:Str) Source: stdlib.ngs:3983
Create Hash with keys being the given field of elements and the values being corresponding elements. Returns
HashExample
Hash([{'x': 1}, {'x': 2}], 'x') # {1: {'x': 1}, 2: {'x': 2}}
- Hash(e:Eachable1, key_field:Str, val_field:Str) Source: stdlib.ngs:4018
Create Hash from Arr of something that has key and value fields Parameters
e Eachable1 with all the keys and values key_field Name of the field holding the keys of newly created Hash val_field Name of the field holding the values of newly created Hash Returns
HashExample
Hash([{"Name": "n1", "Value": "v1"},{"Name": "n2", "Value": "v2"}], "Name", "Value") # {"n1": "v1", "n2": "v2"}
- in(symbol:Str, lib:CLib)
Unfinished feature. Don't use!
- in(field:Str, obj:NormalTypeInstance)
Check whether NormalType (a type that is typically defined by user) instance has the given field. Automatically called by NGS for syntax
field in obj
Returns
BoolExample
type T; t=T(); t.x=1; "x" in t # true
- in(needle:Str, haystack:Str) Source: stdlib.ngs:4787
Determine if needle substring occurs at least once in haystack Parameters
needle The string to find haystack The string to search in Returns
BoolExample
"bc" in "abcd" "x" not in "abcd"
- in(k:Str, mp:MethodParams)
Check whether named parameter exists.
- init(e:Exception, message:Str) Source: stdlib.ngs:98
Initialize an Exception. Parameters
message Goes into .message Returns
Exception with .backtrace and .message
- init(e:Exception, message:Str, cause:Exception) Source: stdlib.ngs:110
Initialize an Exception. Returns
Exception with .backtrace, .message, and .cause
- init(e:IndexNotFound, message:Str, container:Any, key:Any) Source: stdlib.ngs:294
IndexNotFound exception constructor Returns
IndexNotFound object with the given message, container and key fields
- init(c:Capture, name:Str, pattern:Any=method) Source: stdlib.ngs:1142
Make a pattern that captures the matching value. The matched value will be stored in MatchContext.named[name] Parameters
pattern Optional pattern to match. Defaults to Any. Example
m = {"a": 1, "b": 2} =~ {"a": Capture("arg1"), "b": Capture("arg2")}; m.named.arg1 + m.named.arg2 # 3 m = {"a": 1, "b": 2} =~ {"a": Capture("arg1", Int), "b": Capture("arg2", Str)} # Doesn't match - b is Int
- init(al:ArrLike, field:Str=null) Source: stdlib.ngs:1880
Throws NotImplemented if field is specified Parameters
field DEPRECATED name of the field that holds the underlying array.
- init(e:CError, errno:Int, message:Str) Source: stdlib.ngs:2508
CError constructor. In addition to storing message field, adds errno and errno_name fields.
- init(e:CError, message:Str) Source: stdlib.ngs:2514
CError constructor. In addition to storing message field, adds errno and errno_name fields.
- init(e:LockFail, op:Str, code:Int, msg:Str) Source: stdlib.ngs:2533
Initialize LockFail exception.
- init(re:ResultsException, msg:Str, results:Results) Source: stdlib.ngs:4407
Undocumented
- init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:5247
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
- init(t:Thread, name:Str, f:Fun) Source: stdlib.ngs:5285
Creates and runs a thread. The code that the created thread runs is f without arguments.
- init(ee:ExitException, message:Str, exit_code:Int=1) Source: stdlib.ngs:5441
Initializes ExitException.
- init(p:Path, s:Str) Source: stdlib.ngs:5657
Path constructor Parameters
s path
- init(p:Program, name:Str) Source: stdlib.ngs:5947
External Program
- init(f:File, path:Str) Source: stdlib.ngs:6190
Create File object from the given path. The file is not open. Example
f = File('/tmp/myfile')
- init(lines:Lines, s:Str) Source: stdlib.ngs:7854
Split s to strings using end-of-line separators. UNIX and Windows line endings supported (Windows - not tested yet). Warning: Max OS <= 9 line separation of CR (\r) is not supported Example
"xx\nyy".lines() # %[xx yy]
- init(t:Time, s:Str, format:Str) Source: stdlib.ngs:8205
Undocumented
- init(t:Time, s:Str) Source: stdlib.ngs:8216
Parse known date/time formats
- init(rd:AWS::ResDef, _ngs_name:Str)
Initialize ResDef from _ngs_name. Sets .regions to null, .Tags to empty hash and .Name to _ngs_name.
- init(rd:AWS::SecGroup, Name:Str, VpcId:Any)
Initialize SecGroup from security group name and vpc. Example
AWS::SecGroup("https-server", AWS::Vpc(...))
- init(p:AWS2::Parameter, res_type:Type, param_name:Str, param_value:Any)
Undocumented
- init(rd:AWS2::SecGroup, GroupName:Str, VpcId:Any)
Initialize SecGroup from security group name and vpc. Example
AWS2::SecGroup("https-server", AWS2::Vpc(...))
- init(rd:AWS2::Zone, Name:Str)
Undocumented
- init(ds:DelimStr, s:Str, delim:Str=':')
DelimStr constructor
- init(ds:DelimStr, a:Arr, delim:Str=':')
DelimStr constructor
- init(n:Doc::Node, name:Str, children:Arr=null, **attrs:Hash)
Initialize document node Example
Doc::Node('span', class='inline-param') with [ Doc::Text(param.name) Doc::Text(':') Doc::Text(param.type.name) ... ]
- init(t:Doc::Textual, txt:Str)
Initialize text fragment of a document Example
Doc::Text(':')
- init(tv:TableView, name:Any=null, view_name:Str=null, columns:Arr=null)
Undocumented
- init(stvc:SimpleTableViewColumn, name:Str)
Undocumented
- init(tf:TestFail, message:Str)
Initialize TestFail.
- init(md:MarkdownDescription, tvi:ThisVersionIndex, output_name:Str, file_path:Path)
Undocumented
- init(nd:NamespaceDescription, containing_nd:NamespaceDescription, name:Str, namespace:Hash)
Undocumented
- init(td:TypeDescription, containing_nd:NamespaceDescription, name:Str, type:Type)
Undocumented
- init(mmd:MultiMethodDescription, containing_nd:NamespaceDescription, name:Str, multimethod:MultiMethod)
Undocumented
- init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, mmd:MultiMethodDescription, method:Fun)
Undocumented
- init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, method:Fun)
Undocumented
- inspect(path:Arr, s:Str)internal Source: stdlib.ngs:624
Internal method. Please do not use. Inspect Str Returns
Arr of Str
- Int(s:Str, base:Int)
Convert Str to Int. Example
Int("100", 2) # 8 Int("80", 16) # 128
- Int(s:Str, base:Any=10) Source: stdlib.ngs:4673
Convert to Int. Throws InvalidArgument if the number in s is not well-formatted. Returns
IntExample
Int(" 100 ") # 100
- is_blocked_group(tr:TestsResults, group_name:Str)
Undocumented
- join(arr:Arr, s:Str)
Join strings using s as glue Parameters
arr Arr of Str
- join(al:ArrLike, s:Str) Source: stdlib.ngs:1922
Join items to a single string using given separator s Returns
Str
- join(a:Arr, s:Str) Source: stdlib.ngs:3527
Join non-strings. Converts elements to string first, then uses native join(). Parameters
a Array to join s Delimiter Returns
StrExample
[1,2,3].join("::") # The string 1::2::3
- JsonData(s:Str) Source: stdlib.ngs:5161
Convert Str into JSON compatible data structure - string
- len(s:Str)
Get Str length in bytes Returns
Int
- limit(s:Str, n:Int, marker:Str='') Source: stdlib.ngs:5042
Truncate a string if necessary so it would have maximum n characters (currently bytes). Parameters
s The string to (possibly) truncate. n Maximum characters marker The truncation marker Returns
Either s or new Str of length nExample
"abc".limit(5, "...") # "abc" "abcdef".limit(5, "...") # "ab..." "abcdef".limit(2) # "ab"
- lines(s:Str) Source: stdlib.ngs:4981
Split s to strings using end-of-line separators. Same as Lines(s).Arr() Returns
Arr
- lines(s:Str, cb:Fun) Source: stdlib.ngs:4988
Split s to strings using end-of-line separators and call cb for each one of the lines. TODO: More efficient implementation, which would not have temporary array of all lines. Parameters
cb Function to be called with each line
- ll_resolve_global_variable(name:Str)
Do not use directly! Get global variable index by name.
- load(bytecode:Str, func_name:Str)
Load compiled bytecode. Parameters
bytecode compile() result. func_name Name of function to create. Used for backtraces and debugging purposes. Returns
Fun - function with no parameters that runs the loaded bytecode when called.Example
# From bootstrap.ngs, require() definition program_text = fetch(fname) program_bytecode = compile(program_text, fname) program_func = load(program_bytecode, "require()d file: $fname") ret = program_func()
- log(s:Str) Source: stdlib.ngs:5480
Log to standard error. Later log output will be treated specially by the shell. It will have suitable representation in the UI. Use log() when it's semantically a log.
- log(rd:ResDef, method:Str, s:Str)
Formats and logs message s for resource definition rd. Parameters
method the name of calling method which also goes to the formatted message.
- log(r:Res, method:Str, s:Str)
Formats and logs message s for resource r. Parameters
method the name of calling method which also goes to the formatted message.
- lstat(pathname:Str) Source: stdlib.ngs:5627
Issue lstat() system call. Throws StatFail if the call fails. Returns
StatExample
stat("/usr/bin/cal").st_mode # 33261 lstat("/usr/bin/cal").st_mode # 41471
- lte(a:Str, b:Str) Source: stdlib.ngs:4956
Case-insensitive LessThan or Equal comparison for strings Returns
Bool
- mapo(s:Str, mapper:Fun) Source: stdlib.ngs:5029
Map a string, character by character. Returns
StrExample
"abcd".mapo(F(x) if x == "b" then "X" else x) # "aXcd" "abcd".mapo(X.when("b", "*")) # "a*cd"
- maybe_print_stacktrace(env_var:Str, pfx:Str)internal Source: stdlib.ngs:5468
Do not use directly!
- open(f:File, flags:Str) Source: stdlib.ngs:6208
Open a file and set the "fd" field to the file descriptor. Uses OPEN(2). Throws InvalidArgument if file is already open. Throws FileIOFail if an underlying error occurs. Parameters
flags Currently "r", "w" or "a" for read/write/append Returns
f
- opt_prop(rd:ResDef, name:Str, props:Hash)
Get optional resource property, looking up in properties first and then in anchor. Returns
Box
- opt_prop(rd:ResDef, name:Str, props:Hash, cb:Fun)
Run cb with optional resource property if it exists, uses opt_prop(ResDef, Str, Hash)
- ord(s:Str, idx:Int)
Get character (byte) ordinal value. Throws InvalidArgument if idx is not pointing into s. Parameters
idx Index of the character to get value of Returns
IntExample
ord("A", 0) # 65 on my machine
- ord(s:Str) Source: stdlib.ngs:5058
Get character (currently byte) code. Throws InvalidArgument if s is not of length 1. Example
ord("A") # 65 on my machine
- Path(s:Str, subtype:Any=false) Source: stdlib.ngs:5652
Path constructor Parameters
s path subtype Return Path sub-type, depending on lstat() call Returns
Path or sub-type of PathExample
Path(".") # <Path path=.> Path(".", true) # <Dir path=.> ``find tmp/v8``.map(Path(X, true)).map(Type).name.Stats() # <Stats: {Dir=287, File=9220}>
- pos(haystack:Str, needle:Str, start:Int)
Find substring position Parameters
start Non-negative Int, position where the search starts Returns
Int or null. Not -1 as in many languages
- pos(haystack:Str, needle:Str) Source: stdlib.ngs:4773
Find substring in a string. Parameters
haystack The string to search in needle The string to find Returns
Int or nullExample
pos("abc", "cd") # null pos("abcdef", "cd") # 2
- rand(a:Str) Source: stdlib.ngs:8336
Pick random character from a string Returns
Str of length 1
- rand(a:Str, n:Int) Source: stdlib.ngs:8338
Undocumented
- read(fname:Str) Source: stdlib.ngs:8535
Read whole file
- Real(s:Str) Source: stdlib.ngs:2378
Convert a string to real (floating) number, inefficiently Returns
RealExample
Real("1.1") # 1.1
- realpath(path:Str) Source: stdlib.ngs:8586
Undocumented
- replace(s:Str, src:Str, dst:Str) Source: stdlib.ngs:5120
Replace all occurrences of src with dst in s
- replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:7813
Replace all occurrences of r Parameters
mapper Function that will be called with one matching string at a time that provides the replacement Returns
StrExample
"x10ab20c30y".replace(/[0-9]+/, F(match_text) "[$match_text]") # "x[10]ab[20]c[30]y"
- replace(s:Str, r:RegExp, replacement:Str) Source: stdlib.ngs:7823
Undocumented
- report(tr:TestsResults, group_name:Str, test_name:Str, result:Result, critical:Bool)
Undocumented
- req_prop(rd:ResDef, name:Str, props:Hash)
Get resource property, looking up in properties first and then in anchor
- require(fname:Str) Source: stdlib.ngs:8693
Runs the given file Returns
Typically whatever the last expression in the file evaluates to
- require(fname:Str) Source: stdlib.ngs:8704
Undocumented
- retry_assert(val:Any, pattern:Any, msg:Str='Assertion failed')experimental Source: stdlib.ngs:8415
Similar to assert(). Caught and ignored by nearest retry() on all but last retry.
- retry_assert(val:Any, msg:Str='Assertion failed')experimental Source: stdlib.ngs:8424
Similar to assert(). Caught and ignored by nearest retry() on all but last retry.
- run(r:AWS::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal
Run a command. Internal method. Please do not use outside the AWS library.
- run(rd:AWS::ResDef, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal
Run an external command related to the resource definition. Will not run the command if rd.dry_run is true. Parameters
do_decode Whether to decode the output Returns
Either parsed output or finished CommandsPipeline (processes in CommandsPipeline finished)
- run(r:AWS2::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal
Run a command. Internal method. Please do not use outside the AWS library.
- run(rd:AWS2::ResDef, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal
Run an external command related to the resource definition. Will not run the command if rd.dry_run is true. Parameters
do_decode Whether to decode the output Returns
Either parsed output or finished CommandsPipeline (processes in CommandsPipeline finished)
- set(obj:Any, field:Str, val:Any) Source: stdlib.ngs:745
Sets the given field to the given value Returns
The modified objExample
s.len() != 1 throws InvalidArgument("ord() argument must be of length 1 exactly").set('given', s) # Would else be written as if s.len() != 1 { e = InvalidArgument("ord() argument must be of length 1 exactly") e.given = s throw e }
- sort(a:Arr, field:Str, lte:Fun=method) Source: stdlib.ngs:3579
Sort an array based on field value Parameters
lte Less-then-or-equal function to use for comparison of the items' fields Returns
ArrExample
[{'x': 1}, {'x': 5}, {'x': 3}].sort('x') # [{'x': 1}, {'x': 3}, {'x': 5}]
- split(s:Str, delim:Str, max_parts:Int=0) Source: stdlib.ngs:4836
Split string by substring Parameters
s String to split delim Delimiter to split by max_parts Maximum number of resulting parts, 0 - unlimited Returns
Arr of StrExample
":a:bc:d:".split(":") # ["", "a", "bc", "d", ""] "bucket_name/dir/file".split("/", 2) # ["bucket_name", "dir/file"] ":a:bc:d:".split("bc") # [":a:", ":d:"]
- split(s:Str, r:RegExp) Source: stdlib.ngs:7770
Split string by regexp Returns
Arr of StrExample
"x10ab20c30y".split(/[0-9]+/).join(" :: ") # "x :: ab :: c :: y"
- starts_with(haystack:Str, needle:Str) Source: stdlib.ngs:4932
Check whether a string starts with another string Returns
BoolExample
"abcd".starts_with("ab") # true "ab".starts_with("abcd") # false
- stat(pathname:Str) Source: stdlib.ngs:5613
Issue stat() system call. Throws StatFail if the call fails. Returns
StatExample
stat("/tmp") # <Stat st_dev=51714 st_ino=25 st_mode=17407 ...>
- status(s:Str) Source: stdlib.ngs:5528
Undocumented Returns
s
- status(tr:TestsResults, group_name:Str, test_name:Str, s:Str)
Undocumented
- status(t:Terminal, s:Str)
Undocumented
- status(at:AnsiTerminal, s:Str)
Undocumented
- stdlib_aws_straighten_tags(s:Str) Source: stdlib.ngs:7203
Do not use directly. Subject to change. A no-op
- store(filename:Str, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:6322
encode() and write() the data to the file Returns
null (but subject to change)
- strftime(tm:c_tm, format:Str) Source: stdlib.ngs:8189
Low-level function. Do not use directly. Use Time type.
- Table(name:Str, tr:TestsResults)
Undocumented
- test(name:Str, f:Fun)
Runs f as a test. Parameters
name Human readable name of the test. f A Fun that will either throw TestFail, return TestMessage. Other values are ignored by the testing framework.
- test(results:TestsResults, group:Str, name:Str, f:Fun, critical:Bool=true)
EXPERIMENTAL! Do not use! Runs f as a test in a test group
- TODO(s:Str='TODO') Source: stdlib.ngs:244
EXPERIMENTAL! Do not use!
- trim(s:Str) Source: stdlib.ngs:4880
Trim whitespace
- Type(name:Str, doc:Any, ns:Any)
Create a new type. Do not use directly. Automatically called by NGS for syntax
type MyType
- Type(t:Str, doc:Any, ns:Any, parent:Type) Source: stdlib.ngs:77
Create a new type. Do not use directly. Automatically called by NGS for syntax
type MyType2(MyType1)
- Type(t:Str, doc:Any, ns:Any, parents:Arr) Source: stdlib.ngs:82
Create a new type. Do not use directly. Automatically called by NGS for syntax
type MyType2([MyParent1, MyParent2, ...])
- uniq(e:Eachable1, field:Str) Source: stdlib.ngs:3183
Return unique values. Warning: uses Hash so comparison is not using == but a built-in hash keys comparison. Returns
Of same type as eExample
[{"id": 100, "a": 1}, {"id": 200, "a": 2}, {"id": 300, "a": 2}].uniq("a") # [{"id": 100, "a": 1}, {"id": 200, "a": 2}]
- warn(s:Str) Source: stdlib.ngs:5517
Write warning message to standard error. Prints backtrace if NGS_TRACE_WARNINGS environment variable is not an empty string. Example
warn("Could not open input file $my_file , skipping it.") # Approximate output on stderr: # [WARNING 2018-01-01 00:00:00 YOUR_TZ] Could not open input file ./my_file , skipping it.
- without(s:Str, r:RegExp) Source: stdlib.ngs:7777
Get string with all occurrences of r removed Returns
StrExample
"x10ab20c30y".without(/[0-9]+/) # "xabcy"
- words(s:Str) Source: stdlib.ngs:5000
Split string to words. Word is any non-whitespace. Returns
Arr of Str
- write(s:Str, fd:Int)deprecated Source: stdlib.ngs:6036
DEPRECATED! Do not use!
- write(s:Str) Source: stdlib.ngs:6043
Write a string to stdout. Does not add a newline character, while echo() does. Returns
1, the standard output file descriptor
- write(fd:Int, s:Str) Source: stdlib.ngs:6054
Throws WriteFail on failure. Parameters
fd File descriptor to write to s String of bytes to write Returns
fd
- write(s:Str, p:Pipe)deprecated Source: stdlib.ngs:6161
DEPRECATED! Do not use!
- write(p:Pipe, s:Str) Source: stdlib.ngs:6167
Write to Pipe. TODO: document if it throws. Returns
unspecified at this time, do not count on it
- write(pp:ProcessesPipeline, s:Str) Source: stdlib.ngs:6952
Write to first process of ProcessesPipeline Example
p = (|cat -n | tac >/tmp/1) p.write("one\n") p.write("two\n") p.close()
- write(fname:Str, s:Str) Source: stdlib.ngs:8545
Write whole file
- write(s:Str, f:File) Source: stdlib.ngs:8557
Write whole file if it's closed, write to file descriptor if it's open
- write(f:File, s:Str) Source: stdlib.ngs:8561
Write whole file if it's closed, write to file descriptor if it's open
- write(t:Terminal, s:Str)
Undocumented
- ~(haystack:Str, needle:Str, offset:Int=0) Source: stdlib.ngs:5067
Find substring in string. Uses pos(). Returns
MatchResultExample
"abc" ~ "bc" # <MatchSuccess ...> "abc" ~ "X" # <MatchFailure>
- ~(s:Str, pfx:Pfx) Source: stdlib.ngs:7541
Check whether s starts with pfx. Returns
MatchResultExample
"abcde" ~ Pfx("ab") # <MatchSuccess matches=[ab] pattern=<MustPfx ab> before= after=cde> "abcde" ~ Pfx("xy") # <MatchFailure >
- ~(s:Str, i:Ifx) Source: stdlib.ngs:7550
Check whether s contains i. Same as s ~ i.val Returns
MatchResult
- ~(s:Str, sfx:Sfx) Source: stdlib.ngs:7557
Check whether s ends with sfx. Returns
MatchResultExample
"abcde" ~ Sfx("de") # <MatchSuccess matches=[de] pattern=<MustSfx de> before=abc after=> "abcde" ~ Pfx("xy") # <MatchFailure >
- ~(s:Str, r:RegExp, offset:Int=0, options:Int=0) Source: stdlib.ngs:7626
Find PCRE regular expression in s. Empty string without options returns MatchFailure. Throws Error if more than 20 captures are used or if there is an error during matching. Automatically called by NGS for syntax
my_str ~ my_regexp
Parameters
offset search start offset options options to pass to underlying PCRE_EXEC(3). Returns
MatchResultExample
globals().keys().filter(/^C_PCRE/) # lists possible options "xabcy" ~ /a(.)c/ # <MatchSuccess matches=[abc,b] pattern=<RegExp> named={} positions=[<NumRange 1..4 include_start=true include_end=false step=1>,<NumRange 2..3 include_start=true include_end=false step=1>] whole=abc before=x after=y> m = ("xabcy" ~ /a(?P<mychar>.)c/) echo(m.named.mychar) # Outputs: b
- ~~(haystack:Str, needle:Str, collect_unmatched:Bool=false) Source: stdlib.ngs:5082
Find all non-overlapping matches of a substring in a string. Returns
if collect_unmatched - Arr with each element being MatchSuccess or Str, if not collect_unmatched - Arr of MatchSuccess
- ~~(s:Str, r:RegExp, collect_unmatched:Bool=false) Source: stdlib.ngs:7670
Find all non-overlapping matches of regular expression in a string. Returns
if collect_unmatched - Arr with each element being MatchSuccess or Str, if not collect_unmatched - Arr of MatchSuccessExample
("x10ab20c30y" ~~ /[0-9]+/).whole.map(Int).sum() # 60 arr = (~~)("x10ab20c30y", /[0-9]+/, true) arr .= map(F(elt) if elt is MatchSuccess "[${elt.whole}]" else elt) arr.join("") # "x[10]ab[20]c[30]y"
- AWS::wait_state(r:AWS::InstanceRes, state_name:Str)
Declarative primitive for waiting for AWS Instance resource to reach given state Parameters
state_name typically "running" or "stopped" (less common) Returns
r
- AWS::add_to_known_hosts(r:AWS::Instance, prop_name:Str)experimental
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
- AWS::q(id:Str, **kw:Hash)WIP
Work in progress, do not use! Example
AWS::q("vpc-11111111") # references specific vpc
- AWS::q(id:Str, **kw:Hash)WIP
Work in progress, do not use! Example
AWS::q("vpc") # references all vpcs AWS::q("vpc", Tags={"env": "proxy-lab"})
- AWS::is_resource_code(s:Str)
Undocumented
- AWS::util::world_open_port(port:Int, proto:Str='tcp')
Undocumented
- AWS::util::world_open_port(port:Arr, proto:Str='tcp')
Undocumented
- AWS2::wait_state(r:AWS2::InstanceRes, state_name:Str)
Declarative primitive for waiting for AWS Instance resource to reach given state Parameters
state_name typeically "running" or "stopped" (less common) Returns
r
- AWS2::add_to_known_hosts(r:AWS2::Instance, prop_name:Str)experimental
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
- AWS2::route53_resource_id(id:Str)
Undocumented
- AWS2::q(s:Str, **kw:Hash)
Undocumented
- AWS2::is_resource_code(s:Str)
Undocumented