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

Returns

''
Str(nm:NativeMethod) Source: stdlib.ngs:913
String representation of native method.

Returns

"<NativeMethod NAME(PARAMS)>"

Example

(%).Arr()[0].Str().echo()  # Outputs: <NativeMethod %(a:Int, b:Int)>
Str(ntc:NormalTypeConstructor) Source: stdlib.ngs:920
String representation of normal type constructor. NormalTypeConstructor

Returns

"<NormalTypeConstructor>"

Example

Box.constructors.Arr()[0].Str().echo()  # Outputs: <NormalTypeConstructor>
Str(c:UserDefinedMethod) Source: stdlib.ngs:930
String representation of a closure

Returns

Str

Example

Real.constructors[-1].Str().echo()  # Outputs: <UserDefinedMethod Real at /usr/share/ngs/stdlib.ngs:350>
Str(t:Type) Source: stdlib.ngs:965
String representation of a type

Returns

"<Type NAME>"

Example

Real.Str().echo()  # Outputs: <Type Real>
Str(i:NormalTypeInstance) Source: stdlib.ngs:1033
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(cpm:c_pthread_mutex_t) Source: stdlib.ngs:1211
Convert c_pthread_mutex_t to Str for displaying to humans.
Str(cpma:c_pthread_mutexattr_t) Source: stdlib.ngs:1214
Convert c_pthread_mutexattr_t to Str for displaying to humans.
Str(r:Range) Source: stdlib.ngs:1372
Convert range to human readable representation
Str(s:Str) Source: stdlib.ngs:3370
No-op constructor

Returns

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

Returns

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

Returns

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

Returns

Str
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3500
Convert anything to Str of a given width
Str(s:Str, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3507
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:3529
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:3917
Undocumented
Str(t:Thread) Source: stdlib.ngs:3918
Undocumented
Str(p:Path) Source: stdlib.ngs:4198
String representation of a Path (or it's sub-type)

Returns

Str

Example

find_in_path("ls").Str()  # The string: <Path path=/bin/ls>
Str(p:Pipe) Source: stdlib.ngs:4465
Undocumented
Str(f:File) Source: stdlib.ngs:4521
String representation of File

Example

open(File("tmp/v8/LICENSE"), "r").Str().echo()  # Output: <File path=tmp/v8/LICENSE fd=4>
Str(r:CommandRedir) Source: stdlib.ngs:4647
Convert Redit to human-readable string.

Returns

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

Returns

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

Returns

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

Parameters

formatstrftime(3) format
gmtUse GMT time zone (defaults to local time zone)
Str(rd:ResDef) Source: autoload/Res.ngs:29
Converts resource definition to a string, for displaying purposes.
Str(i:ArrIter) Source: autoload/Iter.ngs:302
Textual representation of ArrIter.

Returns

Str
Str(i:HashIter) Source: autoload/Iter.ngs:343
Textual representation of HashIter.

Returns

Str
Str(r:Res) Source: autoload/Res.ngs:127
Converts resource to a string, for displaying purposes.
Str(r:AWS::Vpc) Source: autoload/AWS.ngs:299
String representation of AWS Vpc
Str(ds:DelimStr) Source: autoload/DelimStr.ngs:31
Undocumented
Str(s:Set) Source: autoload/Set.ngs:42
Convert the set to a human-readable representation
Str(mp:MethodParams) Source: autoload/MethodParams.ngs:38
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:3495
Repeat string n times

Example

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

Returns

New Str

Example

"ab" + "cd"  # "abcd"
+(s:Str, a:Eachable1) Source: stdlib.ngs:3603
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:3613
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:5617
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:5635
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:5652
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:5848
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:749
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.
.(h:Hash, field:Str) Source: stdlib.ngs:1540
Get hash key.

Example

h = {"a": 1}
h.a  # 1, Same as h["a"]
.(a:Arr, field:Str) Source: stdlib.ngs:1578
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 exeption
[{"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:3921
Undocumented
.(p:Process, field:Str) Source: stdlib.ngs:4663
Get process "stdout"

Parameters

field"stdout"

Returns

Str
.(p:Process, field:Str) Source: stdlib.ngs:4679
Get process "stderr"

Parameters

field"stderr"

Returns

Str
.=(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
.=(h:Hash, field:Str, v:Any) Source: stdlib.ngs:1546
Set hash key.

Returns

v

Example

h = {"a": 1}
h.a = 2  # 2, Same as h["a"] = 2
.=(a:Arr, field:Str, v:Any) Source: stdlib.ngs:1588
Set field of every element in array to v

Returns

v

Example

a=[{"x": 1}, {"x": 2}]
a.y = 10
# a == [{"x": 1, "y": 10}, {"x": 2, "y": 10}]
.=(p:Process, field:Str, v:Any) Source: stdlib.ngs:4671
Set process "stdout"

Parameters

field"stdout"

Returns

Unspecified, do not count on this value
.=(p:Process, field:Str, v:Any) Source: stdlib.ngs:4687
Set process "stderr"

Parameters

field"stderr"

Returns

Unspecified, do not count on this value
/(a:Str, b:Str) Source: stdlib.ngs:4204
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:4211
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:4220
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:4232
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:5835
Regular expression constructor.

Automatically called by NGS for syntax

/myregex/

Returns

RegExp

Example

my_re = /blah/
<(a:Str, b:Str) Source: stdlib.ngs:3577
Case sensitive LessThan comparison for strings

Returns

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

Returns

Bool
==(a:Str, b:Str)
Compare strings
>(a:Str, b:Str) Source: stdlib.ngs:3582
Case sensitive GreaterThan 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:3434
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:3444
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:3458
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:5874
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/MethodParams.ngs:29
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:6576
Undocumented

Automatically called by NGS for syntax

\name attr1=val1 attr2=val2 ... [ ... ]
Arg(x:Str) Source: stdlib.ngs:4918
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/ArgvMatcher.ngs:30
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(condition:Bool, msg:Str) Source: stdlib.ngs:75
Throws AssertFail with givens message if condition is false

Returns

Unspecified, do not count on this value

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_array(actual:Any, title:Str=null) Source: autoload/test.ngs:110
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/test.ngs:44
A helper used by other assert_* methods. Please do not use directly.
assert_bool(actual:Any, title:Str=null) Source: autoload/test.ngs:88
Assert actual is a Bool. Throws TestFail.

Returns

actual
assert_eq(actual:Any, expected:Any, title:Str=null) Source: autoload/test.ngs:59
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) Source: autoload/test.ngs:177
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) Source: autoload/test.ngs:213
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) Source: autoload/test.ngs:100
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/test.ngs:132
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') Source: autoload/test.ngs:148
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) Source: autoload/test.ngs:69
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) Source: autoload/test.ngs:79
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) Source: autoload/test.ngs:164
Assert actual is of at least specified length. Throws TestFail.

Returns

actual
assert_output_has(pp:ProcessesPipeline, expected:RegExp, title:Str=null) Source: autoload/test.ngs:190
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/test.ngs:201
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/test.ngs:235
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) Source: autoload/test.ngs:223
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) Source: autoload/test.ngs:120
Assert actual is a string. Throws TestFail.

Returns

actual
basename(s:Str) Source: stdlib.ngs:4545
Get basename of the file. Uses BASENAME(1).
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_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:4308
Change directory. Uses CHDIR(2).

Parameters

sDirectory to cd to.

Returns

null
code(s:Str) Source: stdlib.ngs:3725
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:1483
EXPERIMENTAL! Do not use!
column(t:Table, k:Str) Source: autoload/Table.ngs:86
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:5493
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:5511
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(s:Str) Source: stdlib.ngs:3989
Same as debug('default', s)
debug(facility:Str, s:Str) Source: stdlib.ngs:3997
Debug to standard error. "DEBUG" environment variable must be non-empty string to activate. Otherwise nothing is outputted. TODO: Not output 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:971
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, hints:Hash={}) Source: stdlib.ngs:5286
Attempt to decode JSON. Uses decode_json().
decode(s:Str, hints:Hash) Source: stdlib.ngs:5295
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:5304
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:5314
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:5402
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, tyically an Arr at top level. If s is empty string - null.
decode(s:Str, hints:Hash) Source: stdlib.ngs:5464
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:5475
Parse the output of "locate" command.

Parameters

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

Returns

Arr of Str
decode_base64(s:Str)experimental Source: stdlib.ngs:6537
Undocumented
decode_hex(s:Str) Source: stdlib.ngs:6408
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:6430
Decodes URI component, unsecaping %XX hexadecimals

Example

decode_uri_component("ab%2Bc%25")  # "ab+c%"
die(s:Str, status:Any=1) Source: stdlib.ngs:4035
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:5931
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:4243
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:4251
List directory contents and call cb with Path() of each found item. Warning: "." and ".." are included.

Returns

unspecified at this time, do not count on it

Example

's=Stats(); dir("tmp/v8", {s.push(A.typeof().name)}, true); s  # <Stats: {File=23, Dir=16}>'
each(s:Str, cb:Fun) Source: stdlib.ngs:3397
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)
Print given string and a newline to stdout.

Returns

Unspecified

Example

echo("blah")  # Output: blah
echo(fd:Int, s:Str)
Print given string and a newline to a file referenced by descriptor.

Returns

Unspecified

Example

echo(2, "blah")  # Output on stderr: blah
echo(t:Terminal, s:Str) Source: autoload/Terminal.ngs:47
Undocumented
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:6526
Undocumented
encode_base64(s:Str, wrap:Int=0)experimental Source: stdlib.ngs:6532
Undocumented
encode_hex(s:Str) Source: stdlib.ngs:6397
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:6449
Encodes HTML. Escapes &, < and > .

Returns

Str

Example

"ab>+c%&'".encode_html()  # "ab&gt;+c%&amp;'"
encode_html_attr(s:Str) Source: stdlib.ngs:6457
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:6422
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:3555
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:4007
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.
exit(s:Str, status:Any=1) Source: stdlib.ngs:4043
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:4608
read() and decode() the given file

Example

fetch("1.json")  # Data structure, the parsed JSON
fetch(url:Str, decode_hints:Hash={}) Source: stdlib.ngs:4616
Fetch HTTP(S) file and decode() it

Example

fetch('https://api.myip.com')  # Data structure, the parsed JSON
filter(something:Eachable1, field:Str, predicate:Any)deprecated Source: stdlib.ngs:339
DEPRECATED! Do not use! Use something.filter({field: predicate}) instead.
find_in_path(executable_name:Str) Source: stdlib.ngs:4181
Finds given binary and returns it's full path. Throws ExecutableNotFound 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/bin:/usr/bin:/bin:/sbin:/usr/sbin

Returns

Path

Example

find_in_path("ls")  # <Path path=/bin/ls>
finished_ok(p:Process, field_name:Str, ok:NumRange)internal Source: stdlib.ngs:4719
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:4725
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:4733
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:4739
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:4786
Undocumented
get(e:Eachable1, field:Str) Source: stdlib.ngs:1600
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:1608
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:4284
Work in progress, do not use!
global_not_found_handler(name:Str) Source: stdlib.ngs:1256
Called when reading undefined global. Implements autoloading. Searches in $NGS_DIR/autoload/GLOBAL_NAME.ngs WARNING: May have security implications when looking up a name from untrusted source.

Example

test("My web server runs") do { .... }  # $NGS_DIR/autoload/test.ngs is automatically loaded.
Hash(arr:Arr, field:Str) Source: stdlib.ngs:2639
Create Hash with keys being the given field of array elements and the values being corresponding arr 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:2674
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:3425
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) Source: autoload/MethodParams.ngs:32
Check whether named parameter exists.
init(e:Exception, message:Str) Source: bootstrap.ngs:7
Initialize an Exception.

Parameters

messageGoes into .message

Returns

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

Returns

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

Returns

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

Parameters

fieldDEPRECATED name of the field that holds the underlying array.
init(e:CException, message:Str) Source: stdlib.ngs:1115
CException constructor. In addition to storing message field, adds errno and errno_name fields.
init(e:CException, errno:Int, message:Str) Source: stdlib.ngs:1123
CException 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:1148
Initialize LockFail exception.
init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:3831
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:3862
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:3946
Initializes ExitException.
init(p:Path, s:Str) Source: stdlib.ngs:4139
Path constructor

Parameters

spath
init(f:File, path:Str) Source: stdlib.ngs:4507
Create File object from the given path. The file is not open.

Example

f = File('/tmp/myfile')
init(lines:Lines, s:Str) Source: autoload/Lines.ngs:11
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:6241
Undocumented
init(rd:AWS::ResDef, _ngs_name:Str) Source: autoload/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/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/AWS2.ngs:227
Undocumented
init(rd:AWS2::SecGroup, GroupName:Str, VpcId:Any) Source: autoload/AWS2.ngs:607
Initialize SecGroup from security group name and vpc.

Example

AWS::SecGroup("https-server", AWS::Vpc(...))
init(rd:AWS2::Zone, Name:Str) Source: autoload/AWS2.ngs:1340
Undocumented
init(ds:DelimStr, s:Str, delim:Str=':') Source: autoload/DelimStr.ngs:9
DelimStr constructor
init(ds:DelimStr, a:Arr, delim:Str=':') Source: autoload/DelimStr.ngs:15
DelimStr constructor
init(n:Doc::Node, name:Str, children:Arr=null, **attrs:Hash) Source: autoload/Doc.ngs:50
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/Doc.ngs:67
Initialize text fragment of a document

Example

Doc::Text(':')
init(tf:TestFail, message:Str) Source: autoload/test.ngs:10
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(s:Str) Source: stdlib.ngs:6015
Inspect Str

Returns

Lines
Int(s:Str, base:Int)
Convert Str to Int.

Example

Int("100", 2)  # 8
Int("80", 16)  # 128
Int(s:Str) Source: stdlib.ngs:3326
Convert base-10 string 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) Source: autoload/TestsResults.ngs:36
Undocumented
join(arr:Arr, s:Str)
Join strings using s as glue

Parameters

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

Returns

Str
join(a:Arr, s:Str) Source: stdlib.ngs:2255
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
len(s:Str)
Get Str length in bytes

Returns

Int
limit(s:Str, n:Int, marker:Str='') Source: stdlib.ngs:3635
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:3587
Split s to strings using end-of-line separators. Same as Lines(s).Arr()

Returns

Arr
lines(s:Str, cb:Fun) Source: stdlib.ngs:3594
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:3985
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/Res.ngs:42
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) Source: autoload/Res.ngs:132
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:4101
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:3567
Case-insensitive LessThan or Equal comparison for strings

Returns

Bool
mapo(s:Str, mapper:Fun) Source: stdlib.ngs:3622
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:3973
Do not use directly!
open(f:File, flags:Str) Source: stdlib.ngs:4531
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) Source: autoload/Res.ngs:211
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/Res.ngs:214
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:3651
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:4127
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(typeof).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:3411
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:6312
Pick random character from a string

Returns

Str of length 1
rand(a:Str, n:Int) Source: stdlib.ngs:6314
Undocumented
read(fname:Str) Source: bootstrap.ngs:97
Fetches the whole file

Parameters

fnameFile name to read

Returns

Whole file as a string
read(fname:Str) Source: stdlib.ngs:6492
Read whole file
Real(s:Str) Source: stdlib.ngs:886
Convert a string to real (floating) number, inefficiently

Returns

Real

Example

Real("1.1")  # 1.1
replace(s:Str, src:Str, dst:Str) Source: stdlib.ngs:3716
Replace all occurrences of src with dst in s
replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:5892
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"
report(tr:TestsResults, group_name:Str, test_name:Str, result:Result, critical:Bool) Source: autoload/TestsResults.ngs:14
Undocumented
req_prop(rd:ResDef, name:Str, props:Hash) Source: autoload/Res.ngs:218
Get resource property, looking up in properties first and then in anchor
require(fname:Str) Source: bootstrap.ngs:116
Runs the given file

Returns

Typically whatever the last expression in the file evaluates to
run(r:AWS::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/AWS.ngs:120
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/AWS.ngs:190
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 Source: autoload/AWS2.ngs:129
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/AWS2.ngs:194
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:228
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:2304
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:3474
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:5858
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:3543
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:4087
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(tr:TestsResults, group_name:Str, test_name:Str, s:Str) Source: autoload/TestsResults.ngs:29
Undocumented
status(t:Terminal, s:Str) Source: autoload/Terminal.ngs:52
Undocumented
status(at:AnsiTerminal, s:Str) Source: autoload/AnsiTerminal.ngs:39
Undocumented
status(it:ItermTerminal, s:Str) Source: autoload/ItermTerminal.ngs:56
Undocumented
stdlib_aws_straighten_tags(s:Str) Source: stdlib.ngs:5392
Do not use directly. Subject to change. A no-op
store(filename:Str, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:4631
encode() and write() the data to the file

Returns

null (but subject to change)
strftime(tm:c_tm, format:Str) Source: stdlib.ngs:6225
Low-level function. Do not use directly. Use Time type.
Table(name:Str, tr:TestsResults) Source: autoload/TestsResults.ngs:66
Undocumented
test(name:Str, f:Fun) Source: autoload/test.ngs:18
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) Source: autoload/test.ngs:35
EXPERIMENTAL! Do not use! Runs f as a test in a test group
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:939
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:944
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType2([MyParent1, MyParent2, ...])
warn(s:Str) Source: stdlib.ngs:4016
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:5866
Get string with all occurrences of r removed

Returns

Str

Example

"x10ab20c30y".without(/[0-9]+/)  # "xabcy"
write(s:Str, fd:Int)deprecated Source: stdlib.ngs:4387
DEPRECATED! Do not use!
write(fd:Int, s:Str) Source: stdlib.ngs:4397
Write data to a file referenced by file descriptor. WARNING: Incomplete implementation. TODO: handle errors, throw exceptions. TODO: handle possible EINTR.

Parameters

fdFile descriptor to write to

Returns

unspecified at this time, do not count on it
write(s:Str, p:Pipe)deprecated Source: stdlib.ngs:4478
DEPRECATED! Do not use!
write(p:Pipe, s:Str) Source: stdlib.ngs:4484
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:5198
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:6502
Write whole file
write(s:Str, f:File) Source: stdlib.ngs:6514
Write whole file if it's closed, write to file descriptor if it's open
write(f:File, s:Str) Source: stdlib.ngs:6519
Undocumented
write(t:Terminal, s:Str) Source: autoload/Terminal.ngs:42
Undocumented
~(haystack:Str, needle:Str, offset:Int=0) Source: stdlib.ngs:3660
Find substring in string. Uses pos().

Returns

MatchResult

Example

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

Returns

MatchResult

Example

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

Returns

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

Returns

MatchResult

Example

"abcde" ~ Sfx("de")  # <MatchSuccess matches=['de'] before=abc after=>
"abcde" ~ Pfx("xy")  # <MatchFailure >
~(s:Str, r:RegExp, offset:Int=0, options:Int=0) Source: stdlib.ngs:5713
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'] named={} positions=[[1,4],[2,3]] 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:3679
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

Example

["key=value", "key2=value2"].map(F(kv) {
  m = kv ~ "="
  [m.before, m.after]
}).Hash()  # {'key': 'value', 'key2': 'value2'}
~~(s:Str, r:RegExp, collect_unmatched:Bool=false) Source: stdlib.ngs:5756
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) Source: autoload/AWS.ngs:934
Declarative primitive for waiting for AWS Instance resource to reach given state

Parameters

state_nametypeically "running" or "stopped" (less common)

Returns

r
AWS::add_to_known_hosts(r:AWS::Instance, prop_name:Str)experimental Source: autoload/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/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/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/AWS.ngs:1611
Undocumented
AWS::util::world_open_port(port:Int, proto:Str='tcp') Source: autoload/AWS.ngs:1506
Undocumented
AWS::util::world_open_port(port:Arr, proto:Str='tcp') Source: autoload/AWS.ngs:1512
Undocumented
AWS2::wait_state(r:AWS2::InstanceRes, state_name:Str) Source: autoload/AWS2.ngs:1029
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 Source: autoload/AWS2.ngs:1074
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
AWS2::route53_resource_id(id:Str) Source: autoload/AWS2.ngs:1342
Undocumented
AWS2::q(s:Str, **kw:Hash) Source: autoload/AWS2.ngs:1905
Undocumented
AWS2::is_resource_code(s:Str) Source: autoload/AWS2.ngs:1914
Undocumented