Str type
Direct parent types
- Eachable1
Eachable which each() calls the callback with one argument Direct subtypes: 18
Constructors
- Str(r:Real)
Convert Real to Str
- Str(n:Int)
Convert Int to Str
- Str(mm:MultiMethod) Source: stdlib.ngs:526
Undocumented
- Str() Source: stdlib.ngs:580
Make empty string Returns
''
- Str(nm:NativeMethod) Source: stdlib.ngs:608
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:616
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:881
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:2109
Convert ArrLike to a human-readable representation
- Str(s:Set) Source: stdlib.ngs:2424
Convert the set to a human-readable representation
- Str(ntc:NormalTypeConstructor) Source: stdlib.ngs:2636
String representation of normal type constructor. NormalTypeConstructor Returns
"<NormalTypeConstructor>"Example
Box.constructors.Arr()[0].Str().echo() # Outputs: <NormalTypeConstructor>
- Str(t:Type) Source: stdlib.ngs:2643
String representation of a type Returns
"<Type NAME ...>"Example
Real.Str().echo() # Outputs: <Type Real with 3 constructor(s) and 1 meta entries>
- Str(cpm:c_pthread_mutex_t) Source: stdlib.ngs:2844
Convert c_pthread_mutex_t to Str for displaying to humans.
- Str(cpma:c_pthread_mutexattr_t) Source: stdlib.ngs:2847
Convert c_pthread_mutexattr_t to Str for displaying to humans.
- Str(r:Range) Source: stdlib.ngs:2949
Convert range to human readable representation
- Str(r:Results) Source: stdlib.ngs:4738
Undocumented
- Str(s:Str) Source: stdlib.ngs:5072
No-op constructor Returns
s
- Str(n:Null) Source: stdlib.ngs:5076
Convert Null to string Returns
the string "null"
- Str(b:Bool) Source: stdlib.ngs:5077
Undocumented
- Str(a:Arr) Source: stdlib.ngs:5081
Convert Arr to string Returns
Str
- Str(h:Hash) Source: stdlib.ngs:5085
Convert Hash to string Returns
Str
- Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5263
Convert anything to Str of a given width
- Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5266
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:5289
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:5814
Undocumented
- Str(t:Thread) Source: stdlib.ngs:5815
Undocumented
- Str(p:Path) Source: stdlib.ngs:6200
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:6475
Undocumented
- Str(p:Pipe) Source: stdlib.ngs:6654
Undocumented
- Str(r:CommandRedir) Source: stdlib.ngs:6858
Convert CommandRedir to human-readable string. Returns
Str
- Str(p:Process) Source: stdlib.ngs:7189
Wait for the process to finish and return its standard output. Returns
Str
- Str(pp:ProcessesPipeline) Source: stdlib.ngs:7194
Wait for the processes to finish and return standard output of the last process in pipeline. Returns
Str
- Str(s:SubSeq) Source: stdlib.ngs:8142
Undocumented
- Str(r:RegExp) Source: stdlib.ngs:8531
Regular expression literal, same as code(r) Returns
Str
- Str(t:Time, format:Str='%F %T %Z', gmt:Bool=false) Source: stdlib.ngs:8992
String representation of Time Parameters
format strftime(3) format gmt Use GMT time zone (defaults to local time zone)
- Str(rd:ResDef) Source: autoload/globals/Res.ngs:28
Converts resource definition to a string, for displaying purposes.
- Str(i:ArrIter) Source: autoload/globals/Iter.ngs:298
Textual representation of ArrIter. Returns
Str
- Str(i:HashIter) Source: autoload/globals/Iter.ngs:340
Textual representation of HashIter. Returns
Str
- Str(r:Res) Source: autoload/globals/Res.ngs:126
Converts resource to a string, for displaying purposes.
- Str(r:AWS::Vpc) Source: autoload/globals/AWS.ngs:299
String representation of AWS Vpc
- Str(ds:DelimStr) Source: autoload/globals/DelimStr.ngs:29
Undocumented
- Str(t:Table) Source: autoload/globals/Table2.ngs:403
Undocumented
- Str(mp:MethodParams) Source: autoload/globals/MethodParams.ngs:36
Undocumented
- Str(c:Cond) Source: autoload/globals/Cond.ngs:16
String representation of Cond
- Str(pf:ProcessFail) Source: autoload/globals/ProcessFail.ngs:8
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:5259
Repeat string n times Example
"abc" * 3 # "abcabcabc"
- +(s1:Str, s2:Str) Source: stdlib.ngs:3146
Concatenate strings Returns
New StrExample
"ab" + "cd" # "abcd"
- +(s:Str, a:Eachable1) Source: stdlib.ngs:5384
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:5396
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:6238
Concatenate Returns
Path
- +(a:Str, b:Path) Source: stdlib.ngs:6242
Concatenate Returns
Path
- -(s:Str, pfx:Pfx) Source: stdlib.ngs:8152
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:8170
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:8187
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:8448
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. Parameters
field "pattern", "options", "arg_options", "names", or "newline" Returns
Str for "pattern". Int for "options" (effective options), "arg_options" (options passed to PCRE2_COMPILE(3)), and "newline". Hash of names/indexes of named groups for "names".Example
/abc/i.pattern # abc /abc/i.options # 8 - case insensitive (C_PCRE2_CASELESS) /^abc/i.arg_options # 8 - .options has C_PCRE2_ANCHORED too /(?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:c_sockaddr, field:Str)
Get c_sockaddr field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Parameters
field "sa_family" Returns
IntExample
c_sockaddr().sa_family # 0
- .(obj:c_sockaddr_un, field:Str)
Get c_sockaddr_un field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Parameters
field One of: "sun_family", "sun_path" Returns
Int for "sun_family", Str for "sun_path"Example
c_sockaddr_un("/tmp/my.sock").sun_path # "/tmp/my.sock"
- .(obj:c_sockaddr_in, field:Str)
Get c_sockaddr_in field. Throws FieldNotFound. Automatically called by NGS for syntax
obj.field
Parameters
field One of: "sin_family", "sin_port", "sin_addr" Returns
Int for "sin_family" and "sin_port" (host byte order), Str for "sin_addr" (dotted-decimal)Example
c_sockaddr_in("127.0.0.1", 8080).sin_port # 8080
- .(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:944
Get hash key. Example
h = {"a": 1} h.a # 1, Same as h["a"]
- .(al:ArrLike, s:Str) Source: stdlib.ngs:2092
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:2511
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:3105
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:5818
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:950
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:2518
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ...
- .=(t:Type, field:Str, a:Arr) Source: stdlib.ngs:2537
Undocumented Automatically called by NGS for syntax
SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ['SOME', 'NAMES', ...]
- .=(a:Arr, field:Str, e:Eachable1) Source: stdlib.ngs:3115
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:6206
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:6213
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:6222
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:6234
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:8432
Regular expression constructor. The pattern syntax is PCRE2's, see pcre2pattern(3). Automatically called by NGS for syntax
/myregex/
Parameters
regexp The pattern flags Zero or more flag letters, in any order: i - caseless matching (PCRE2_CASELESS); m - multiline: ^ and $ also match at internal newlines (PCRE2_MULTILINE); s - dot also matches newline (PCRE2_DOTALL); x - extended: unescaped whitespace outside character classes and #-comments in the pattern are ignored (PCRE2_EXTENDED); a - anchored: the match must start at the start position of the search (PCRE2_ANCHORED). With ~~, each next match must start where the previous one ended. Any other character throws RegExpCompileFail. Returns
RegExpExample
my_re = /blah/ Bool("ABC" ~ /b/i) # true ("a\nb" ~~ /^./m).whole # ["a", "b"] ("ababxab" ~~ /ab/a).whole # ["ab", "ab"]
- ::(t:Type, k:Str) Source: stdlib.ngs:2550
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:5346
Case sensitive LessThan comparison for strings Returns
Bool
- <=(a:Str, b:Str) Source: stdlib.ngs:5336
Case sensitive LessThan or Equal comparison for strings Returns
Bool
- ==(a:Str, b:Str)
Compare strings
- >(a:Str, b:Str) Source: stdlib.ngs:5351
Case sensitive GreaterThan comparison for strings Returns
Bool
- >=(a:Str, b:Str) Source: stdlib.ngs:5341
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 Parameters
range NumRange, exclusive end. Non-negative Int .start. Non-negative Int .end, or null .end for the end of the string Example
"abcd"[1..3] # "bc" "abcd"[1..null] # "bcd"
- [](ms:MatchSuccess, name:Str) Source: stdlib.ngs:1149
Get capture by name
- [](s:Str, i:Int) Source: stdlib.ngs:5137
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:5147
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:5161
Get a substring. Indexes in s are specified by NumRange. Parameters
s Original string r NumRange with negative .end Returns
StrExample
"(Look ma, no parens)"[1..-1] # "Look ma, no parens"
- [](s:Str, r:NumRange) Source: stdlib.ngs:5172
Get a substring. Indexes in s are specified by NumRange. Parameters
s Original string r NumRange with negative .start Returns
StrExample
"abcd"[-2..null] # "cd"
- [](s:Str, r:RegExp) Source: stdlib.ngs:8473
Get substring of a string that corresponds to first match of given regular expression Example
"x10ab20c30y"[/[0-9]+/] # "10"
- [](mp:MethodParams, k:Str) Source: autoload/globals/MethodParams.ngs:27
Get named parameter
- []=(s:Str, range:NumRange, replacement:Str)
Change substring Parameters
range NumRange, exclusive end. Non-negative Int .start. Non-negative Int .end, or null .end for the end of the string Returns
replacementExample
s="abcd"; s[1..3]="X"; s # "aXd" s="abcd"; s[1..null]="XY"; s # "aXY"
- \(name:Str, attributes:Hash, children:Arr)experimental Source: stdlib.ngs:9456
Undocumented Automatically called by NGS for syntax
\name attr1=val1 attr2=val2 ... [ ... ]
- after_first(s:Str, delim:Str) Source: stdlib.ngs:5224
Split the string by delimiter and return the part after the first occurrence Returns
Str
- after_last(s:Str, delim:Str) Source: stdlib.ngs:5247
Split the string by delimiter and return the last part Returns
Str
- Arg(x:Str) Source: stdlib.ngs:7211
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) Source: autoload/globals/ArgvMatcher.ngs:27
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:333
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:361
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:373
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) Source: autoload/globals/test.ngs:107
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 Source: autoload/globals/test.ngs:41
A helper used by other assert_* methods. Please do not use directly.
- assert_bool(actual:Any, title:Str=null) Source: autoload/globals/test.ngs:85
Assert actual is a Bool. Throws TestFail. Returns
actual
- assert_eq(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:52
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) Source: autoload/globals/test.ngs:171
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) Source: autoload/globals/test.ngs:208
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) Source: autoload/globals/test.ngs:97
Assert actual is a Hash. Throws TestFail. Returns
actual
- assert_hash_keys(actual:Any, expected:Arr, title:Str='Must be a hash with keys') Source: autoload/globals/test.ngs:127
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') Source: autoload/globals/test.ngs:143
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) Source: autoload/globals/test.ngs:65
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) Source: autoload/globals/test.ngs:75
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) Source: autoload/globals/test.ngs:161
Assert actual is of at least specified length. Throws TestFail. Returns
actual
- assert_output_has(pp:ProcessesPipeline, expected:RegExp, title:Str=null) Source: autoload/globals/test.ngs:186
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) Source: autoload/globals/test.ngs:197
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') Source: autoload/globals/test.ngs:231
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) Source: autoload/globals/test.ngs:219
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) Source: autoload/globals/test.ngs:117
Assert actual is a string. Throws TestFail. Returns
actual
- basename(s:Str) Source: stdlib.ngs:6731
Get basename of the file.
- before_first(s:Str, delim:Str) Source: stdlib.ngs:5214
Split the string by delimiter and return the first part Returns
Str
- before_last(s:Str, delim:Str) Source: stdlib.ngs:5240
Split the string by delimiter and return the part before the last occurrence 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_pcre2_compile(regexp:Str, flags:Int)
Throws RegExpCompileFail on errors. Returns
RegExp
- c_pcre2_match(regexp:RegExp, subject:Str, offset:Int, options:Int)
Search string for regular expression. Uses PCRE2_MATCH(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_in(address:Str, port:Int)
Make c_sockaddr_in with sin_family AF_INET, sin_addr from INET_PTON(3) and sin_port in network byte order. Do not use directly. Parameters
address IPv4 address, passed to INET_PTON(3) port Port in host byte order, truncated to 16 bits Returns
c_sockaddr_in or null if INET_PTON(3) fails
- c_sockaddr_in(address:Str, port:Int) Source: stdlib.ngs:9415
Make IPv4 socket address. Throws InvalidArgument on invalid address or port. Parameters
address IPv4 address in dotted-decimal notation, without leading zeros in octets port Port, 0 to 65535 Returns
c_sockaddr_inExample
bind(socket(C_PF_INET, C_SOCK_STREAM), c_sockaddr_in("127.0.0.1", 0)) # 0
- 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:6332
Change directory. Uses CHDIR(2). Parameters
s Directory to cd to. Returns
null
- code(s:Str) Source: stdlib.ngs:5508
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:3048
EXPERIMENTAL! Do not use!
- column(t:Table, k:Str) Source: autoload/globals/Table.ngs:84
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:8069
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:8087
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:5982
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. Parameters
str_or_producer The message. If str_or_producer is a Fun, the result of str_or_producer() is the message; it is called only when debug is enabled for the facility.
- debug_enabled(facility:Str) Source: stdlib.ngs:5971
Undocumented
- decode(s:Str, t:Type) Source: stdlib.ngs:2161
Fallback for types without decode(). Throws DecodeFail.
- decode(s:Str, literal:AnyOf(Str, Int, Bool)) Source: stdlib.ngs:2168
Decode to the given literal. Throws DecodeFail if s does not decode to literal. Returns
literalExample
"5".decode(5) # 5
- decode(s:Str, a:AnyOf) Source: stdlib.ngs:2178
Try to decode to any of the alternatives in a. Throws DecodeFail if none of the alternatives worked. Returns
result of decoding one of the alternatives in a.
- decode(s:Str, t:Type)experimental Source: stdlib.ngs:2653
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:6410
Decode Path and its subtypes Returns
instance of Path or a subtype.
- decode(s:Str, hints:Hash={}) Source: stdlib.ngs:7699
Attempt to decode JSON. Uses decode_json().
- decode(s:Str, hints:Hash={}) Source: stdlib.ngs:7706
Detects single line, no whitespace, scheme://... Returns
URLExample
"https://example.com/a".decode().host # "example.com"
- decode(s:Str, hints:Hash) Source: stdlib.ngs:7727
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:7736
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:7746
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:7756
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:7856
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:8026
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:8037
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:9655
Decodes JSON Web Token (JWT)
- decode_base64(s:Str)experimental Source: stdlib.ngs:9398
Undocumented
- decode_hex(s:Str) Source: stdlib.ngs:9205
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:9227
Decodes URI component, unescaping %XX hexadecimals Example
decode_uri_component("ab%2Bc%25") # "ab+c%"
- deep_copy(s:Str) Source: stdlib.ngs:12
Returns a copy
- die(s:Str, status:Any=1) Source: stdlib.ngs:6031
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:8607
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:6247
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:6257
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:5100
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:175
Print given string and a newline to stdout. Returns
nullExample
echo("blah") # Output: blah
- echo(fd:Int, s:Str) Source: stdlib.ngs:6586
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:7593
Write s and newline character(s) to pp
- echo(f:File, s:Str) Source: stdlib.ngs:9328
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) Source: autoload/globals/Terminal.ngs:39
Undocumented
- echo_cli(s:Str)experimental Source: stdlib.ngs:9779
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:9375
Undocumented
- encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:9382
Undocumented
- encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:9389
Undocumented
- encode_hex(s:Str) Source: stdlib.ngs:9194
Encodes each character in a string as two uppercase hexadecimal digits Returns
StrExample
encode_hex("ab") # "6162"
- encode_html(s:Str) Source: stdlib.ngs:9247
Encodes HTML. Escapes &, < and > . Returns
StrExample
"ab>+c%&'".encode_html() # "ab>+c%&'"
- encode_html_attr(s:Str) Source: stdlib.ngs:9255
Encodes HTML attribute. Escapes &, <, >, " and ' . Returns
StrExample
"ab>+c%&'".encode_html_attr() # "ab>+c%&'"
- encode_uri_component(s:Str) Source: stdlib.ngs:9219
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:5319
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:5995
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:7288
Call EXECVE(2) Parameters
argv argv, without the program
- exec(prog:Str, env:Hash=ENV) Source: stdlib.ngs:7292
Call EXECVE(2)
- exit(s:Str, status:Any=1) Source: stdlib.ngs:6039
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:6802
read() and decode() the given file Example
fetch("1.json") # Data structure, the parsed JSON
- fetch(url:Str, decode_hints:Hash={}) Source: stdlib.ngs:6810
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:6186
Finds given binary and returns it's full path. Throws ProgramNotFound if the binary was not found. Throws InvalidArgument if the name contains "/". 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:6886
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:6892
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:6900
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:6906
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:6959
Undocumented
- get(e:Eachable1, field:Str) Source: stdlib.ngs:3128
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:3141
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:6308
Work in progress, do not use!
- global_not_found_handler(name:Str) Source: stdlib.ngs:9586
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:4403
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:4270
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:4305
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:5128
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) Source: autoload/globals/MethodParams.ngs:30
Check whether named parameter exists.
- init(e:Exception, message:Str) Source: stdlib.ngs:132
Initialize an Exception. Parameters
message Goes into .message Returns
Exception with .backtrace and .message
- init(e:Exception, message:Str, cause:Exception) Source: stdlib.ngs:144
Initialize an Exception. Returns
Exception with .backtrace, .message, and .cause
- init(e:IndexNotFound, message:Str, container:Any, key:Any) Source: stdlib.ngs:331
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:1271
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:2038
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:2755
CError constructor. In addition to storing message field, adds errno and errno_name fields.
- init(e:CError, message:Str) Source: stdlib.ngs:2761
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:2780
Initialize LockFail exception.
- init(re:ResultsException, msg:Str, results:Results) Source: stdlib.ngs:4745
Undocumented
- init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:5626
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:5664
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:5890
Initializes ExitException.
- init(ss:SemanticOutput, category:Str, s:Any) Source: stdlib.ngs:5915
Undocumented
- init(p:Path, s:Str) Source: stdlib.ngs:6144
Path constructor Parameters
s path
- init(p:Program, name:Str) Source: stdlib.ngs:6438
External Program
- init(f:File, path:Str) Source: stdlib.ngs:6696
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:8562
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:8947
Undocumented
- init(t:Time, s:Str) Source: stdlib.ngs:8958
Parse known date/time formats
- init(rd:AWS::ResDef, _ngs_name:Str) Source: autoload/globals/AWS.ngs:180
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) Source: autoload/globals/AWS.ngs:503
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) Source: autoload/globals/AWS2.ngs:241
Undocumented
- init(rd:AWS2::SecGroup, GroupName:Str, VpcId:Any) Source: autoload/globals/AWS2.ngs:623
Initialize SecGroup from security group name and vpc. Example
AWS2::SecGroup("https-server", AWS2::Vpc(...))
- init(rd:AWS2::Zone, Name:Str) Source: autoload/globals/AWS2.ngs:1343
Undocumented
- init(ds:DelimStr, s:Str, delim:Str=':') Source: autoload/globals/DelimStr.ngs:5
DelimStr constructor
- init(ds:DelimStr, a:Arr, delim:Str=':') Source: autoload/globals/DelimStr.ngs:11
DelimStr constructor
- init(n:Doc::Node, name:Str, children:Arr=null, **attrs:Hash) Source: autoload/globals/Doc.ngs:42
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) Source: autoload/globals/Doc.ngs:67
Initialize text fragment of a document Example
Doc::Text(':')
- init(tv:TableView, name:Any=null, view_name:Str=null, columns:Arr=null) Source: autoload/globals/Table2.ngs:9
Undocumented
- init(stvc:SimpleTableViewColumn, name:Str) Source: autoload/globals/Table2.ngs:28
Undocumented
- init(tf:TestFail, message:Str) Source: autoload/globals/test.ngs:8
Initialize TestFail.
- init(t:Test, name:Str, body:Fun) Source: autoload/globals/test.ngs:249
Test constructor. Inside ns { }, also sets the namespace's member name to the test. Returns
TestExample
t = Test("addition", { assert(1 + 1, 2) }) n = ns { Test("addition", { assert(1 + 1, 2) }) } # n.addition is the Test
- init(c:Cond, name:Str='', lock:Lock=null) Source: autoload/globals/Cond.ngs:5
Initialize Cond
- 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:731
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:5006
Convert to Int. Surrounding whitespace is ignored. Throws InvalidArgument if the number in s is not well-formatted. Returns
IntExample
Int(" 100 ") # 100
- is_blocked_group(tr:TestsResults, group_name:Str) Source: autoload/globals/TestsResults.ngs:33
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:2087
Join items to a single string using given separator s Returns
Str
- join(a:Arr, s:Str) Source: stdlib.ngs:3814
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:5540
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:5412
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:5356
Split s to strings using end-of-line separators. Same as Lines(s).Arr() Returns
Arr
- lines(s:Str, cb:Fun) Source: stdlib.ngs:5363
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:5964
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) Source: autoload/globals/Res.ngs:41
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) Source: autoload/globals/Res.ngs:131
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:6114
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:5331
Case-insensitive LessThan or Equal comparison for strings Returns
Bool
- mapo(s:Str, mapper:Fun) Source: stdlib.ngs:5408
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:5952
Do not use directly!
- open(f:File, flags:Str) Source: stdlib.ngs:6714
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) Source: autoload/globals/Res.ngs:210
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) Source: autoload/globals/Res.ngs:213
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:5437
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:6132
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:5114
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:9082
Pick random character from a string Returns
Str of length 1
- rand(a:Str, n:Int) Source: stdlib.ngs:9084
Undocumented
- read(fname:Str) Source: stdlib.ngs:9290
Read whole file
- Real(s:Str) Source: stdlib.ngs:2605
Surrounding whitespace is ignored. Returns
RealExample
Real("1.1") # 1.1
- realpath(path:Str) Source: stdlib.ngs:9347
Undocumented
- replace(s:Str, src:Str, dst:Str) Source: stdlib.ngs:5499
Replace all occurrences of src with dst in s
- replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:8504
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:8514
Undocumented
- report(tr:TestsResults, group_name:Str, test_name:Str, result:Result, critical:Bool) Source: autoload/globals/TestsResults.ngs:11
Undocumented
- req_prop(rd:ResDef, name:Str, props:Hash) Source: autoload/globals/Res.ngs:217
Get resource property, looking up in properties first and then in anchor
- require(fname:Str) Source: stdlib.ngs:9486
Runs the given file Returns
Typically whatever the last expression in the file evaluates to
- require(fname:Str) Source: stdlib.ngs:9498
Undocumented
- retry_assert(val:Any, pattern:Any, msg:Str='Assertion failed')experimental Source: stdlib.ngs:9164
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:9173
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 Source: autoload/globals/AWS.ngs:118
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 Source: autoload/globals/AWS.ngs:185
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 Source: autoload/globals/AWS2.ngs:141
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 Source: autoload/globals/AWS2.ngs:203
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:853
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:3862
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:5181
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:8458
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:5307
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:6100
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:6015
Undocumented Returns
s
- status(tr:TestsResults, group_name:Str, test_name:Str, s:Str) Source: autoload/globals/TestsResults.ngs:26
Undocumented
- status(t:Terminal, s:Str) Source: autoload/globals/Terminal.ngs:44
Undocumented
- stdlib_aws_straighten_tags(s:Str) Source: stdlib.ngs:7846
Do not use directly. Subject to change. A no-op
- stdlib_split_on_delim(s:Str, delim:Str, fname:Str) Source: stdlib.ngs:5233
Undocumented
- store(filename:Str, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:6825
encode() and write() the data to the file Returns
null (but subject to change)
- strftime(tm:c_tm, format:Str) Source: stdlib.ngs:8931
Low-level function. Do not use directly. Use Time type.
- Table(name:Str, tr:TestsResults) Source: autoload/globals/TestsResults.ngs:64
Undocumented
- test(name:Str, f:Fun) Source: autoload/globals/test.ngs:16
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) Source: autoload/globals/test.ngs:32
EXPERIMENTAL! Do not use! Runs f as a test in a test group
- TODO(s:Str='TODO') Source: stdlib.ngs:279
EXPERIMENTAL! Do not use!
- trim(s:Str) Source: stdlib.ngs:5255
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:111
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:116
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:3450
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}]
- validate(val:Any, param:Str, pattern:Any) Source: stdlib.ngs:396
Throws InvalidArgument naming the parameter if val does not match the pattern. Use for checking arguments. Parameters
val Argument value to check param Name of the parameter pattern Pattern val must match Returns
valExample
validate(-5, 'x', Int) # InvalidArgument: Invalid argument 'x', got -5, expected Int validate(-5, 'x', { A > 0 }) # InvalidArgument: Invalid argument 'x', got -5, expected to pass the check at my.ngs:10
- warn(s:Str) Source: stdlib.ngs:6004
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:8465
Get string with all occurrences of r removed Returns
StrExample
"x10ab20c30y".without(/[0-9]+/) # "xabcy"
- words(s:Str) Source: stdlib.ngs:5375
Split string to words. Word is any non-whitespace. Returns
Arr of Str
- write(s:Str, fd:Int)deprecated Source: stdlib.ngs:6542
DEPRECATED! Do not use!
- write(s:Str) Source: stdlib.ngs:6549
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:6560
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:6667
DEPRECATED! Do not use!
- write(p:Pipe, s:Str) Source: stdlib.ngs:6673
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:7586
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:9300
Write whole file
- write(s:Str, f:File) Source: stdlib.ngs:9312
Write whole file if it's closed, write to file descriptor if it's open
- write(f:File, s:Str) Source: stdlib.ngs:9316
Write whole file if it's closed, write to file descriptor if it's open
- write(t:Terminal, s:Str) Source: autoload/globals/Terminal.ngs:34
Undocumented
- ~(haystack:Str, needle:Str, offset:Int=0) Source: stdlib.ngs:5441
Find substring in string. Uses pos(). Returns
MatchResultExample
"abc" ~ "bc" # <MatchSuccess ...> "abc" ~ "X" # <MatchFailure>
- ~(s:Str, pfx:Pfx) Source: stdlib.ngs:8202
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:8211
Check whether s contains i. Same as s ~ i.val Returns
MatchResult
- ~(s:Str, sfx:Sfx) Source: stdlib.ngs:8218
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:8299
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 PCRE2_MATCH(3). Returns
MatchResultExample
globals().keys().filter(/^C_PCRE/) # lists possible options "xabcy" ~ /a(.)c/ # <MatchSuccess matches=[abc,b] pattern=/a(.)c/ 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:5458
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:8340
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) Source: autoload/globals/AWS.ngs:934
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 Source: autoload/globals/AWS.ngs:979
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
- AWS::q(id:Str, **kw:Hash)WIP Source: autoload/globals/AWS.ngs:1586
Work in progress, do not use! Example
AWS::q("vpc-11111111") # references specific vpc
- AWS::q(id:Str, **kw:Hash)WIP Source: autoload/globals/AWS.ngs:1605
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) Source: autoload/globals/AWS.ngs:1611
Undocumented
- AWS::util::world_open_port(port:Int, proto:Str='tcp') Source: autoload/globals/AWS.ngs:1504
Undocumented
- AWS::util::world_open_port(port:Arr, proto:Str='tcp') Source: autoload/globals/AWS.ngs:1512
Undocumented
- AWS2::wait_state(r:AWS2::InstanceRes, state_name:Str) Source: autoload/globals/AWS2.ngs:1032
Declarative primitive for waiting for AWS Instance resource to reach given state Parameters
state_name typically "running" or "stopped" (less common) Returns
r
- AWS2::add_to_known_hosts(r:AWS2::Instance, prop_name:Str)experimental Source: autoload/globals/AWS2.ngs:1077
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
- AWS2::route53_resource_id(id:Str) Source: autoload/globals/AWS2.ngs:1345
Undocumented
- AWS2::q(s:Str, **kw:Hash) Source: autoload/globals/AWS2.ngs:1908
Undocumented
- AWS2::is_resource_code(s:Str) Source: autoload/globals/AWS2.ngs:1917
Undocumented