Str type

String type. Contains sequential bytes.

Direct parent types

Eachable1
Eachable which each() calls the callback with one argument
Direct subtypes: 16

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:369
Undocumented
Str() Source: stdlib.ngs:414
Make empty string

Returns

''
Str(nm:NativeMethod) Source: stdlib.ngs:437
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:445
String representation of a closure

Returns

Str

Example

Real.constructors[-1].Str().echo()  # Outputs: <UserDefinedMethod Real at /usr/share/ngs/stdlib.ngs:350>
Str(i:NormalTypeInstance) Source: stdlib.ngs:667
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:1546
Convert ArrLike to a human-readable representation
Str(s:Set) Source: stdlib.ngs:1744
Convert the set to a human-readable representation
Str(ntc:NormalTypeConstructor) Source: stdlib.ngs:1926
String representation of normal type constructor. NormalTypeConstructor

Returns

"<NormalTypeConstructor>"

Example

Box.constructors.Arr()[0].Str().echo()  # Outputs: <NormalTypeConstructor>
Str(t:Type) Source: stdlib.ngs:1933
String representation of a type

Returns

"<Type NAME>"

Example

Real.Str().echo()  # Outputs: <Type Real>
Str(cpm:c_pthread_mutex_t) Source: stdlib.ngs:2139
Convert c_pthread_mutex_t to Str for displaying to humans.
Str(cpma:c_pthread_mutexattr_t) Source: stdlib.ngs:2142
Convert c_pthread_mutexattr_t to Str for displaying to humans.
Str(r:Range) Source: stdlib.ngs:2233
Convert range to human readable representation
Str(r:Results) Source: stdlib.ngs:3920
Undocumented
Str(s:Str) Source: stdlib.ngs:4321
No-op constructor

Returns

s
Str(n:Null) Source: stdlib.ngs:4325
Convert Null to string

Returns

the string "null"
Str(b:Bool) Source: stdlib.ngs:4326
Undocumented
Str(a:Arr) Source: stdlib.ngs:4330
Convert Arr to string

Returns

Str
Str(h:Hash) Source: stdlib.ngs:4334
Convert Hash to string

Returns

Str
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:4479
Convert anything to Str of a given width
Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:4486
Pad a string to given width with spaces

Parameters

target_widthPositive 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:4508
Convert a number to a string and pad it

Parameters

target_widthPositive pads on left, negative pads on right

Example

Str(10,  4)  # '  10'
Str(10, -4)  # '10  '
Str(t:c_pthread_t) Source: stdlib.ngs:4993
Undocumented
Str(t:Thread) Source: stdlib.ngs:4994
Undocumented
Str(p:Path) Source: stdlib.ngs:5298
String representation of a Path (or it's sub-type)

Returns

Str

Example

find_in_path("ls").Str()  # The string: /bin/ls
Str(p:Pipe) Source: stdlib.ngs:5707
Undocumented
Str(r:CommandRedir) Source: stdlib.ngs:5907
Convert CommandRedir to human-readable string.

Returns

Str
Str(p:Process) Source: stdlib.ngs:6116
Wait for the process to finish and return its standard output.

Returns

Str
Str(pp:ProcessesPipeline) Source: stdlib.ngs:6121
Wait for the processes to finish and return standard output of the last process in pipeline.

Returns

Str
Str(s:SubSeq) Source: stdlib.ngs:6904
Undocumented
Str(t:Time, format:Str='%F %T %Z', gmt:Bool=false) Source: stdlib.ngs:7652
String representation of Time

Parameters

formatstrftime(3) format
gmtUse 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(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:4474
Repeat string n times

Example

"abc" * 3  # "abcabcabc"
+(s1:Str, s2:Str) Source: stdlib.ngs:2451
Concatenate strings

Returns

New Str

Example

"ab" + "cd"  # "abcd"
+(s:Str, a:Eachable1) Source: stdlib.ngs:4599
Prepend each line in a with s

Returns

Type of ret is same as type of a

Example

"a " + ["1", "2"]  # ["a 1", "a 2"]
+(a:Eachable1, s:Str) Source: stdlib.ngs:4609
Append s to each line in a

Returns

Type of ret is same as type of a

Example

["1", "2"] + " a"  # ["1 a", "2 a"]
-(s:Str, pfx:Pfx) Source: stdlib.ngs:6914
Return string without the prefix. Throws InvalidArgument if pfx is MustPfx but s does not start with it.

Parameters

soriginal string
pfxprefix to get rid of

Returns

s without pfx

Example

"abcde" - Pfx("ab")  # "cde"
"abcde" - Pfx("xy")  # InvalidArgument exception
"abcde" - MaybePfx("xy")  # "abcde"
-(s:Str, sfx:Sfx) Source: stdlib.ngs:6932
Return string without the suffix. Throws InvalidArgument if pfx is MustSfx but s does not end with it.

Parameters

soriginal string
sfxsuffix to get rid of

Returns

s without pfx

Example

"abcde" - Sfx("de")  # "abc"
"abcde" - Sfx("xy")  # InvalidArgument exception
"abcde" - MaybeSfx("xy")  # "abcde"
-(s:Str, ifx:Ifx) Source: stdlib.ngs:6949
Return string without the infix. Throws InvalidArgument if ifx is MustIfx but s does not contain it.

Parameters

soriginal string
ifxinfix to get rid of

Returns

s without ifx

Example

"abcde" - Ifx("bc")  # "ade"
"abcde" - Ifx("xy")  # InvalidArgument exception
"abcde" - MaybeIfx("xy")  # "abcde"
-(s:Str, r:RegExp) Source: stdlib.ngs:7179
Returns the string with one occurrence of regexp cut out of it. Throws InvalidArgument if s does not contain r.

Returns

Str

Example

"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

attrOne 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

fieldField 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

fieldField 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

Any

Example

type T; t=T(); t.x=1; t.x  # 1
.(al:ArrLike, s:Str) Source: stdlib.ngs:1532
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:1811
Undocumented

Automatically called by NGS for syntax

SUBTYPE_OF_NAMEDINSTANCES.NamedInstances

Example

echo(Color.NamedInstances is Namespace)  # true
.(h:Hash, field:Str) Source: stdlib.ngs:2390
Get hash key.

Example

h = {"a": 1}
h.a  # 1, Same as h["a"]
.(a:Arr, field:Str) Source: stdlib.ngs:2415
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

Arr

Example

[{"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:4997
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

fieldField 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

v

Example

type T; t=T(); t.x=1
.=(t:Type, field:Str, ns:Namespace) Source: stdlib.ngs:1818
Undocumented

Automatically called by NGS for syntax

SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ...
.=(t:Type, field:Str, a:Arr) Source: stdlib.ngs:1837
Undocumented

Automatically called by NGS for syntax

SUBTYPE_OF_NAMEDINSTANCES.NamedInstances = ['SOME', 'NAMES', ...]
.=(h:Hash, field:Str, v:Any) Source: stdlib.ngs:2396
Set hash key.

Returns

v

Example

h = {"a": 1}
h.a = 2  # 2, Same as h["a"] = 2
.=(a:Arr, field:Str, e:Eachable1) Source: stdlib.ngs:2425
Set field of every element in array to corresponding item in e. Uses Iter(e) internally.

Returns

a

Example

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:5304
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later.

Returns

Str

Example

mydir="tmp"
mydir / "myfile"  # "tmp/myfile"
/(a:Str, b:Str) Source: stdlib.ngs:5311
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later.

Returns

Str

Example

mydir="tmp/"
mydir / "myfile"  # "tmp/myfile"
/(a:Str, b:Str) Source: stdlib.ngs:5320
Concatenate two path parts using STDLIB_PATH_SEP (currently "/") but should be platform-specific later.

Returns

Str

Example

mydir="./"
mydir / "myfile"  # "myfile"
/(a:Path, b:Str) Source: stdlib.ngs:5332
Concatenate two Path-s using /(a:Str, b:Str)

Returns

Path

Example

Path("tmp") / "v8"  # <Path path=tmp/v8>
//(regexp:Str, flags:Str) Source: stdlib.ngs:7166
Regular expression constructor.

Automatically called by NGS for syntax

/myregex/

Returns

RegExp

Example

my_re = /blah/
::(t:Type, k:Str) Source: stdlib.ngs:1850
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:4561
Case sensitive LessThan comparison for strings

Returns

Bool
<=(a:Str, b:Str) Source: stdlib.ngs:4551
Case sensitive LessThan or Equal comparison for strings

Returns

Bool
==(a:Str, b:Str)
Compare strings
=~(x:Str, s:SubSeq, _mc:MatchContext) Source: stdlib.ngs:7026
Checks subsequence presence

Parameters

sSubSeq of Str

Returns

Bool
>(a:Str, b:Str) Source: stdlib.ngs:4566
Case sensitive GreaterThan comparison for strings

Returns

Bool
>=(a:Str, b:Str) Source: stdlib.ngs:4556
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"
[](s:Str, i:Int) Source: stdlib.ngs:4386
Get given character (currently byte) of the string

Parameters

sOriginal string
iIndex of the character to return

Example

"abc"[0]  # "a"
[](s:Str, i:Int) Source: stdlib.ngs:4396
Get given character (currently byte) of the string (negative indexes handler). Throws IndexNotFound if abs(i) > len(s).

Parameters

sOriginal string.
iNegative index of the character to return

Example

"abc"[-1]  # "c"
[](s:Str, r:NumRange) Source: stdlib.ngs:4410
Get a substring. Indexes in s are specified by NumRange.

Parameters

sOriginal string
rNumRange with negatve .end

Returns

Str

Example

"(Look ma, no parens)"[1..-1]  # "Look ma, no parens"
[](s:Str, r:RegExp) Source: stdlib.ngs:7204
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

replacement

Example

s="abcd"; s[1..3]="X"; s  # "aXd"
\(name:Str, attributes:Hash, children:Arr)experimental Source: stdlib.ngs:8023
Undocumented

Automatically called by NGS for syntax

\name attr1=val1 attr2=val2 ... [ ... ]
after_last(s:Str, delim:Str) Source: stdlib.ngs:4461
Split the string by delimiter and return the last part

Returns

Str
Arg(x:Str) Source: stdlib.ngs:6138
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

optionOption name. The only supported option at this time is "positionals".
valueOption 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:257
Throws AssertFail with given message if expr does not match the pattern

Returns

val

Example

my_template.get('concept', []).assert(Arr)
assert(loginResult, {'access_token': Str}, "access_token must be present in response")
assert(expr:Any, msg:Str='Assertion failed') Source: stdlib.ngs:269
Throws AssertFail with given message if expr evaluates to false

Parameters

exprif evaluates to false, causes AssertFail exception
msgmessage for the exception, defaults to "Assertion failed"

Returns

expr

Example

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:279
Throws AssertFail with given function does not throw exception of the given type.

Parameters

fFun
tSubtype of Exception

Returns

The exception

Example

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

actual

Example

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

pp

Example

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

actual

Example

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

actual

Example

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

actual

Example

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

actual

Example

assert_in(10, [10, 2], "test in")
assert_match(actual:Any, expected:Any, title:Str=null)
Assert actual matches expected. Throws TestFail.

Returns

actual

Example

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

pStr 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 value

Example

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:5784
Get basename of the file.
before_first(s:Str, delim:Str) Source: stdlib.ngs:4449
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

whenceOne 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

flagsr - 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:5408
Change directory. Uses CHDIR(2).

Parameters

sDirectory to cd to.

Returns

null
code(s:Str) Source: stdlib.ngs:4717
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:2334
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

fnameSource file name for backtraces and error messages.

Returns

Str - bytecode

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()
config(k:Str) Source: stdlib.ngs:6833
Get configuration for the given key. Lookup order / first wins: (1) Environment variable NGS_$k (2) previously set config(k, v)

Parameters

kConfiguration 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:6851
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:5073
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:1940
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:Any) Source: stdlib.ngs:5480
Decode Path and its subtypes

Returns

instance of Path or a subtype.
decode(s:Str, hints:Hash={}) Source: stdlib.ngs:6593
Attempt to decode JSON. Uses decode_json().
decode(s:Str, hints:Hash) Source: stdlib.ngs:6602
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:6611
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:6621
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:6631
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:6726
Parse the output of "aws" command. Extracts the array (see "s" below"). For "describe-instances", flattens the instance list.

Parameters

sStr containing JSON with a Hash at top level with exactly one Arr as value
hintshints.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:6804
Parse the output of "find" command which does not use "-printf". Handles "-print0".

Parameters

hintshints.process.command.argv[0] must be 'find'

Returns

Arr of Str
decode(s:Str, hints:Hash) Source: stdlib.ngs:6815
Parse the output of "locate" command.

Parameters

hintshints.process.command.argv[0] must be 'locate'

Returns

Arr of Str
decode(s:Str, hints:Hash={}) Source: stdlib.ngs:8181
Decodes JSON Web Token (JWT)
decode_base64(s:Str)experimental Source: stdlib.ngs:7988
Undocumented
decode_hex(s:Str) Source: stdlib.ngs:7813
Decodes each two hex digits into a character (byte). Reverse of encode_hex()

Returns

Str
decode_json(s:Str)
Decode (parse) JSON.

Returns

Any

Example

decode_json('{"a": 1}')  # {a=1}
decode_uri_component(s:Str) Source: stdlib.ngs:7835
Decodes URI component, unsecaping %XX hexadecimals

Example

decode_uri_component("ab%2Bc%25")  # "ab+c%"
die(s:Str, status:Any=1) Source: stdlib.ngs:5128
Write message in s to standard error and exit, printing backtrace

Parameters

statusconverted to exit code using ExitCode()
digest(a:Arr, chunk_size:Int, marker:Str='(...)') Source: stdlib.ngs:7321
Convert an array to a possibly shorter version, for displaying to human.

Parameters

chunk_sizenumber of elements to retain at the beginning and at the end.
markerhow to mark the cut elements in the middle.

Returns

Arr

Example

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:5343
List directory contents. Warning: "." and ".." are included. Throws DirFail when directory can not be listed.

Parameters

subtypeSelect type of returned items: true for Path sub-type, false for Path type

Returns

Arr of Path or it's sub-type

Example

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:5351
List directory contents and call cb with Path() of each found item. "." and ".." are excluded.

Returns

unspecified at this time, do not count on it

Example

'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:4349
Iterates over all string characters (currently bytes).

Parameters

cbFunction to be called with each character from s

Returns

s

Example

"abc".each(echo)
# Output:
# a
# b
# c
echo(s:Str) Source: stdlib.ngs:125
Print given string and a newline to stdout.

Returns

null

Example

echo("blah")  # Output: blah
echo(fd:Int, s:Str) Source: stdlib.ngs:5639
Write a string followed by newline character to a file descriptor. Throws WriteFail on failure.

Returns

null

Example

echo(2, "blah")  # Output on stderr: blah"
echo(pp:ProcessesPipeline, s:Str) Source: stdlib.ngs:6480
Write s and newline character(s) to pp
echo(f:File, s:Str) Source: stdlib.ngs:7933
Write a string followed by newline character to a File. Throws WriteFail on failure.

Returns

null

Example

echo(File("1.txt"), "blah")
echo(t:Terminal, s:Str)
Undocumented
echo_cli(s:Str)experimental Source: stdlib.ngs:8262
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:7976
Undocumented
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:7982
Undocumented
encode_hex(s:Str) Source: stdlib.ngs:7802
Encodes each character in a string as two uppercase hexadecimal digits

Returns

Str

Example

encode_hex("ab")  # "6162"
encode_html(s:Str) Source: stdlib.ngs:7854
Encodes HTML. Escapes &, < and > .

Returns

Str

Example

"ab>+c%&'".encode_html()  # "ab&gt;+c%&amp;'"
encode_html_attr(s:Str) Source: stdlib.ngs:7862
Encodes HTML attribute. Escapes &, <, >, " and ' .

Returns

Str

Example

"ab>+c%&'".encode_html_attr()  # "ab&gt;+c%&amp;&#39;"
encode_uri_component(s:Str) Source: stdlib.ngs:7827
Encodes URI component, escaping with %XX hexadecimal codes.

Returns

Str

Example

encode_uri_component("ab+c%")  # "ab%2Bc%25"
ends_with(haystack:Str, needle:Str) Source: stdlib.ngs:4534
Check whether a string ends with another string

Returns

Bool

Example

"abcd".ends_with("cd")  # true
"ab".ends_with("cdab")  # false
error(s:Str) Source: stdlib.ngs:5090
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:6217
Call EXECVE(2)

Parameters

argvargv, without the program
exec(prog:Str, env:Hash=ENV) Source: stdlib.ngs:6220
Call EXECVE(2)
exit(s:Str, status:Any=1) Source: stdlib.ngs:5136
Write message in s to standard error and exit

Parameters

statusconverted to exit code using ExitCode()
fetch(filename:Str, decode_hints:Hash={}) Source: stdlib.ngs:5857
read() and decode() the given file

Example

fetch("1.json")  # Data structure, the parsed JSON
fetch(url:Str, decode_hints:Hash={}) Source: stdlib.ngs:5865
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:5281
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

Path

Example

find_in_path("ls")  # <Path path=/bin/ls>
finished_ok(p:Process, field_name:Str, ok:NumRange)internal Source: stdlib.ngs:5935
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:5941
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:5949
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:5955
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:6002
Undocumented
get(e:Eachable1, field:Str) Source: stdlib.ngs:2438
Return array made of given field of each element of given Eachable1 where present

Returns

Arr

Example

[{"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:2446
Return array made of given field of each element of given Eachable1 where present or default value where the field is not present.

Returns

Arr

Example

[{"x": 1}, {"y": 2}].get("x", null)  # [1, null]
glob(pattern:Str, start_dir:Any='.') Source: stdlib.ngs:5386
Work in progress, do not use!
global_not_found_handler(name:Str) Source: stdlib.ngs:8128
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:3633
Group items from e by the given field

Returns

Hash with Arr values

Example

[{"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:3499
Create Hash with keys being the given field of elements and the values being corresponding elements.

Returns

Hash

Example

Hash([{'x': 1}, {'x': 2}], 'x')  # {1: {'x': 1}, 2: {'x': 2}}
Hash(e:Eachable1, key_field:Str, val_field:Str) Source: stdlib.ngs:3534
Create Hash from Arr of something that has key and value fields

Parameters

eEachable1 with all the keys and values
key_fieldName of the field holding the keys of newly created Hash
val_fieldName of the field holding the values of newly created Hash

Returns

Hash

Example

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

Bool

Example

type T; t=T(); t.x=1; "x" in t  # true
in(needle:Str, haystack:Str) Source: stdlib.ngs:4377
Determine if needle substring occurs at least once in haystack

Parameters

needleThe string to find
haystackThe string to search in

Returns

Bool

Example

"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:94
Initialize an Exception.

Parameters

messageGoes into .message

Returns

Exception with .backtrace and .message
init(e:Exception, message:Str, cause:Exception) Source: stdlib.ngs:106
Initialize an Exception.

Returns

Exception with .backtrace, .message, and .cause
init(e:IndexNotFound, message:Str, container:Any, key:Any) Source: stdlib.ngs:250
IndexNotFound exception constructor

Returns

IndexNotFound object with the given message, container and key fields
init(al:ArrLike, field:Str=null) Source: stdlib.ngs:1485
Throws NotImplemented if field is specified

Parameters

fieldDEPRECATED name of the field that holds the underlying array.
init(e:CError, errno:Int, message:Str) Source: stdlib.ngs:2055
CError constructor. In addition to storing message field, adds errno and errno_name fields.
init(e:CError, message:Str) Source: stdlib.ngs:2061
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:2079
Initialize LockFail exception.
init(re:ResultsException, msg:Str, results:Results) Source: stdlib.ngs:3927
Undocumented
init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:4835
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:4866
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:5019
Initializes ExitException.
init(p:Path, s:Str) Source: stdlib.ngs:5239
Path constructor

Parameters

spath
init(p:Program, name:Str) Source: stdlib.ngs:5508
External Program
init(f:File, path:Str) Source: stdlib.ngs:5749
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:7267
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:7609
Undocumented
init(t:Time, s:Str) Source: stdlib.ngs:7617
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(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:553
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:4263
Convert to Int. Throws InvalidArgument if the number in s is not well-formatted.

Returns

Int

Example

Int(" 100 ")  # 100
is_blocked_group(tr:TestsResults, group_name:Str)
Undocumented
join(arr:Arr, s:Str)
Join strings using s as glue

Parameters

arrArr of Str
join(al:ArrLike, s:Str) Source: stdlib.ngs:1527
Join items to a single string using given separator s

Returns

Str
join(a:Arr, s:Str) Source: stdlib.ngs:3098
Join non-strings. Converts a elements to string first, then uses built-in join().

Parameters

aArray to join
sDelimiter

Returns

Str

Example

[1,2,3].join("::")  # The string 1::2::3
JsonData(s:Str) Source: stdlib.ngs:4749
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:4631
Truncate a string if necessary so it would have maximum n characters (currently bytes).

Parameters

sThe string to (possibly) truncate.
nMaximum characters
markerThe truncation marker

Returns

Either s or new Str of length n

Example

"abc".limit(5, "...")     # "abc"
"abcdef".limit(5, "...")  # "ab..."
"abcdef".limit(2)         # "ab"
lines(s:Str) Source: stdlib.ngs:4571
Split s to strings using end-of-line separators. Same as Lines(s).Arr()

Returns

Arr
lines(s:Str, cb:Fun) Source: stdlib.ngs:4578
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

cbFunction 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

bytecodecompile() result.
func_nameName 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:5058
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

methodthe 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

methodthe name of calling method which also goes to the formatted message.
lstat(pathname:Str) Source: stdlib.ngs:5209
Issue lstat() system call. Throws StatFail if the call fails.

Returns

Stat

Example

stat("/usr/bin/cal").st_mode   # 33261
lstat("/usr/bin/cal").st_mode  # 41471
lte(a:Str, b:Str) Source: stdlib.ngs:4546
Case-insensitive LessThan or Equal comparison for strings

Returns

Bool
mapo(s:Str, mapper:Fun) Source: stdlib.ngs:4618
Map a string, character by character.

Returns

Str

Example

"abcd".mapo(F(x) if x == "b" then "X" else x)  # "aXcd"
maybe_print_stacktrace(env_var:Str, pfx:Str)internal Source: stdlib.ngs:5046
Do not use directly!
open(f:File, flags:Str) Source: stdlib.ngs:5767
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

flagsCurrently "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

idxIndex of the character to get value of

Returns

Int

Example

ord("A", 0)  # 65 on my machine
ord(s:Str) Source: stdlib.ngs:4647
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:5234
Path constructor

Parameters

spath
subtypeReturn Path sub-type, depending on lstat() call

Returns

Path or sub-type of Path

Example

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

startNon-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:4363
Find substring in a string.

Parameters

haystackThe string to search in
needleThe string to find

Returns

Int or null

Example

pos("abc", "cd")     # null
pos("abcdef", "cd")  # 2
rand(a:Str) Source: stdlib.ngs:7719
Pick random character from a string

Returns

Str of length 1
rand(a:Str, n:Int) Source: stdlib.ngs:7721
Undocumented
read(fname:Str) Source: stdlib.ngs:7897
Read whole file
Real(s:Str) Source: stdlib.ngs:1904
Convert a string to real (floating) number, inefficiently

Returns

Real

Example

Real("1.1")  # 1.1
realpath(path:Str) Source: stdlib.ngs:7949
Undocumented
replace(s:Str, src:Str, dst:Str) Source: stdlib.ngs:4708
Replace all occurrences of src with dst in s
replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:7226
Replace all occurrences of r

Parameters

mapperFunction that will be called with one matching string at a time that provides the replacement

Returns

Str

Example

"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:7236
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:8054
Runs the given file

Returns

Typically whatever the last expression in the file evaluates to
require(fname:Str) Source: stdlib.ngs:8062
Undocumented
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_decodeWhether 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_decodeWhether 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:639
Sets the given field to the given value

Returns

The modified obj

Example

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:3150
Sort an array based on field value

Parameters

lteLess-then-or-equal function to use for comparison of the items' fields

Returns

Arr

Example

[{'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:4426
Split string by substring

Parameters

sString to split
delimDelimiter to split by
max_partsMaximum number of resulting parts, 0 - unlimited

Returns

Arr of Str

Example

":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:7189
Split string by regexp

Returns

Arr of Str

Example

"x10ab20c30y".split(/[0-9]+/).join(" :: ")  # "x :: ab :: c :: y"
starts_with(haystack:Str, needle:Str) Source: stdlib.ngs:4522
Check whether a string starts with another string

Returns

Bool

Example

"abcd".starts_with("ab")  # true
"ab".starts_with("abcd")  # false
stat(pathname:Str) Source: stdlib.ngs:5195
Issue stat() system call. Throws StatFail if the call fails.

Returns

Stat

Example

stat("/tmp")  # <Stat st_dev=51714 st_ino=25 st_mode=17407 ...>
status(s:Str) Source: stdlib.ngs:5110
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:6716
Do not use directly. Subject to change. A no-op
store(filename:Str, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:5880
encode() and write() the data to the file

Returns

null (but subject to change)
strftime(tm:c_tm, format:Str) Source: stdlib.ngs:7593
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

nameHuman readable name of the test.
fA 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:202
EXPERIMENTAL! Do not use!
trim(s:Str) Source: stdlib.ngs:4470
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:73
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:78
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:2755
Return unique values. Warning: uses Hash so comparison is not using == but a built-in hash keys comparison.

Returns

Of same type as e

Example

[{"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:5099
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:7196
Get string with all occurrences of r removed

Returns

Str

Example

"x10ab20c30y".without(/[0-9]+/)  # "xabcy"
words(s:Str) Source: stdlib.ngs:4590
Split string to words. Word is any non-whitespace.

Returns

Arr of Str
write(s:Str, fd:Int)deprecated Source: stdlib.ngs:5595
DEPRECATED! Do not use!
write(s:Str) Source: stdlib.ngs:5602
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:5613
Throws WriteFail on failure.

Parameters

fdFile descriptor to write to
sString of bytes to write

Returns

fd
write(s:Str, p:Pipe)deprecated Source: stdlib.ngs:5720
DEPRECATED! Do not use!
write(p:Pipe, s:Str) Source: stdlib.ngs:5726
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:6473
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:7907
Write whole file
write(s:Str, f:File) Source: stdlib.ngs:7919
Write whole file if it's closed, write to file descriptor if it's open
write(f:File, s:Str) Source: stdlib.ngs:7924
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:4656
Find substring in string. Uses pos().

Returns

MatchResult

Example

"abc" ~ "bc"  # <MatchSuccess ...>
"abc" ~ "X"   # <MatchFailure>
~(s:Str, pfx:Pfx) Source: stdlib.ngs:6964
Check whether s starts with pfx.

Returns

MatchResult

Example

"abcde" ~ Pfx("ab")  # <MatchSuccess matches=[ab] pattern=<MustPfx ab> before= after=cde>
"abcde" ~ Pfx("xy")  # <MatchFailure >
~(s:Str, i:Ifx) Source: stdlib.ngs:6973
Check whether s contains i. Same as s ~ i.val

Returns

MatchResult
~(s:Str, sfx:Sfx) Source: stdlib.ngs:6980
Check whether s ends with sfx.

Returns

MatchResult

Example

"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:7045
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

offsetsearch start offset
optionsoptions to pass to underlying PCRE_EXEC(3).

Returns

MatchResult

Example

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:4671
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:7089
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 MatchSuccess

Example

("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_nametypically "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_nametypeically "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