外观
util
原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793390583/FIN+5.3.1+util 中文整理基于 FIN 5.3.1
导读: JSON API 提供 Fantom 和 JavaScript 对象表示法(JSON)之间的基本序列化。有关 JSON 的更多信息,请参阅 json.org。
以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。
目录(导读)
- classes
- facets
- errs
- docs
- JSON
- Type Mapping
- Writing Json
- Reading Json
- Slot Details
- appName
- argFields
- helpOpt
- homeDir
- log
- main
- optFields
- parseArgs
- printProps
- run
- runServices
- runtimeProps
- usage
- help
- clear
- copyFrom
- eachTrue
- fill
- get
- getAndSet
- make
- set
- size
- cur
- debug
- err
- group
- groupEnd
- height
- info
- prompt
- promptPassword
- table
- warn
- width
- wrap
- delimiter
- eachRow
- readAllRows
- readRow
- trim
- isQuoteRequired
- writeCell
- writeRow
- col
- compare
- equals
- file
- hash
- inputs
- isUnknown
- line
- makeFile
- synthetic
- toStr
- unknown
- loc
- dir
- filename
- onOpen
- writeLogRec
- writeStr
- makeF4
- makeF8
- sort
- makeS1
- makeS2
- makeS4
- makeS8
- makeU1
- makeU2
- makeU4
- readJson
- escapeUnicode
- prettyPrint
- prettyPrintToStr
- writeJson
- writeJsonToStr
- lock
- unlock
- apply
- keys
- pattern
- aliases
- findAllFiles
- findAllPodNames
- findFile
- path
- tempDir
- vars
- workDir
- makeSecure
- makeSeeded
- next
- nextBool
- nextBuf
- nextFloat
- create
- delete
- deleteOnExit
- exists
- in
- list
- mmap
- modified
- moveTo
- normalize
- open
- osPath
- out
- parent
- …(其余标题见英文正文)
API 正文(英文)
errs
| FileLocErr | Exception with a file location |
docs
JSON
The json APIs provide basic serialization between Fantom and Javascript Object Notation (JSON). Refer to json.org for more information about JSON.
Type Mapping
JSON types are mapped to Fantom types as follows:
JSON Fantom
------ --------
object Str:Obj?
array Obj?[]
string Str
number Int or Float
true Bool
false Bool
null nullIn addition when writing Fantom objects the following is supported:
- Simples are written as a JSON string
- Serializables are written as JSON objects with each non-static, non-transient field being written as a key/val pair
Writing simples or serializables do not "roundtrip". For example if you write a Date it is written and will be read back as a normal string.
Writing Json
Writing is accomplised via JsonOutStream. To write to standard out:
map := ["key":"value", "intKey":123]
JsonOutStream(Env.cur.out).writeJson(map)You can also use the writeToStr as a convenience to write to an in-memory string.
Reading Json
Reading JSON is accomplised via JsonInStream which takes raw JSON from a stream and produces of the core JSON types. For example:
str := """{"k1":"v1", "k2":3.4159, "k3":[1,2,3], "k4": {"m1":true, "m2":null}}"""
Str:Obj? data := JsonInStream(str.in).readJson
data["k1"] => v1AbstractMain
abstract class AbstractMain : Obj
AbstractMain provides conveniences for writing the main routine of an app. Command line arguments are configured as fields with the Arg facet:
@Arg { help = "source file to process" }
File? srcArguments are ordered by the field declaration order. The last argument may be declared as a list to handle a variable numbers of arguments.
Command line options are configured as fields with the Opt facet :
@Opt { help = "http port"; aliases=["p"] }
Int port := 8080Bool fields should always default to false and are considered flag options. All other arg and opt fields must be a Str, File, or have a type which supports a fromStr method.
Option fields may include the "Opt" suffix, and arguments the "Arg" suffix. These suffixes can be used when a field conflicts with an existing slot name.
AbstractMain will automatically implement usage and parseArgs based on the fields which are declared as options and arguments. In general subclasses only need to override run. If writing a daemon main, then you'll probably want to configure your services then call runServices.
See example.
Fields
| helpOpt | Print usage help. |
Methods
| appName | Get the application name. |
| argFields | Get all the fields annotated with the @Arg facet. |
| homeDir | Home directory for the application. |
| log | Log for this application; defaults to appName. |
| main | Main performs the following tasks |
| optFields | Get all the fields annotated with the @Opt facet. |
| parseArgs | Parse the command line and set this instances fields. |
| printProps | Print a map of key/value pairs to output with values justified. |
| run | Run the application. |
| runServices | Run the set of services |
| runtimeProps | Get map of the standard runtime props including |
| usage | Print usage of arguments and options. |
Slot Details
appName
virtual Str appName()
Get the application name. If this is a script it is the name of the script file. For a precompiled class called "Main" this is the pod name, otherwise it is the type name.
argFields
virtual Field[] argFields()
Get all the fields annotated with the @Arg facet.
helpOpt
@Opt { help="Print usage help"; aliases=["?"] } Bool helpOpt := false
Print usage help.
homeDir
virtual File homeDir()
Home directory for the application. For a script this defaults to directory of the script. For pods the default is "{Env.cur.workDir}/etc/{pod}".
log
virtual Log log()
Log for this application; defaults to appName.
main
virtual Int main(Str[] args := Env.cur().args())
Main performs the following tasks:
- Calls
parseArgsto parse command line - If args were incomplete or -help was specified then dump usage and return 1
- Call
runand return 0 - If an exception is raised log it and return 1
optFields
virtual Field[] optFields()
Get all the fields annotated with the @Opt facet.
parseArgs
virtual Bool parseArgs(Str[] toks)
Parse the command line and set this instances fields. Return false if not all of the arguments were passed.
printProps
static Void printProps(Str:Obj props, [Str:Obj]? opts := null)
Print a map of key/value pairs to output with values justified. Values that are lists are indented and separated by newlines. Options:
out: OutStream to print to (default is Env.cur.out)indent: Str spaces (default is "")
run
abstract Int run()
Run the application. This method is called after the command line has been parsed. See runServices to launch a deamon application. Return status code, zero for success.
runServices
virtual Int runServices(Service[] services)
Run the set of services:
- call install on each service
- call start on each service
- put main thread to sleep.
- on shutodwn call stop on each service
- then call uninstall on each service
runtimeProps
static Str:Obj runtimeProps([Str:Obj]? acc := null)
Get map of the standard runtime props including:
- java version info if JVM
- node version if running in NodeJS
- fan version Map vals are Strs or Lists to indent. Also see
printProps
usage
virtual Int usage(OutStream out := Env.cur().out())
Print usage of arguments and options. Return non-zero.
Arg
@Serializable facet class Arg : Obj, Facet
Facet for annotating an AbstractMain argument field.
Fields
| help | Usage help, should be a single short line summary |
Slot Details
help
const Str help := ""
Usage help, should be a single short line summary
BoolArray
@Js class BoolArray : Obj
Optimized fixed size array of booleans packed into words of 32-bits. The array values default to false.
Constructors
| make | Create a array of given size |
Methods
| clear | Set entire array to false |
| copyFrom | Copy the booleans from that array into this array and return this. |
| eachTrue | Iterate each index set to true |
| fill | Fill this array with the given boolean value. |
| get | Get the boolean at the given index. |
| getAndSet | Set the value at given index and return the previous value. |
| set | Set the boolean at the given index. |
| size | Get number of booleans in the array |
Slot Details
clear
This clear()
Set entire array to false
copyFrom
This copyFrom(BoolArray that)
Copy the booleans from that array into this array and return this.
eachTrue
Void eachTrue(|Int| f)
Iterate each index set to true
fill
This fill(Bool val, Range? range := null)
Fill this array with the given boolean value. If range is null then the entire array is filled, otherwise just the specified range. Return this.
get
@Operator Bool get(Int index)
Get the boolean at the given index. Negative indices are not supported.
getAndSet
Bool getAndSet(Int index, Bool val)
Set the value at given index and return the previous value.
make
static new make(Int size)
Create a array of given size
set
@Operator Void set(Int index, Bool val)
Set the boolean at the given index. Negative indices are not supported.
size
Int size()
Get number of booleans in the array
Console
@Js abstract const class Console : Obj
Console provides utilities to interact with the terminal console. For Java this API is designed to use jline if installed. In browser JavaScript environments this APIs uses the JS debugging window.
Methods
| clear | Clear the console of all text if supported |
| cur | Get the default console for the virtual machine |
| debug | Print a message to the console at the debug level |
| err | Print a message to the console at the error level |
| group | Enter an indented group level in the console. |
| groupEnd | Exit an indented, collapsable group level |
| height | Number of lines that fit vertically in console or null if unknown |
| info | Print a message to the console at the informational level |
| prompt | Prompt the user to enter a string from standard input. |
| promptPassword | Prompt the user to enter a password string from standard input with echo disabled. |
| table | Print tabular data to the console |
| warn | Print a message to the console at the warning level |
| width | Number of chars that fit horizontally in console or null if unknown |
| wrap | Construct a console that wraps an output stream. |
Slot Details
clear
abstract This clear()
Clear the console of all text if supported
cur
static Console cur()
Get the default console for the virtual machine
debug
abstract This debug(Obj? msg, Err? err := null)
Print a message to the console at the debug level
err
abstract This err(Obj? msg, Err? err := null)
Print a message to the console at the error level
group
abstract This group(Obj? msg, Bool collapsed := false)
Enter an indented group level in the console. The JS debug window can specify the group to default in a collapsed state (this flag is ignored in a standard terminal).
groupEnd
abstract This groupEnd()
Exit an indented, collapsable group level
height
abstract Int? height()
Number of lines that fit vertically in console or null if unknown
info
abstract This info(Obj? msg, Err? err := null)
Print a message to the console at the informational level
prompt
abstract Str? prompt(Str msg := "")
Prompt the user to enter a string from standard input. Return null if end of stream has been reached.
promptPassword
abstract Str? promptPassword(Str msg := "")
Prompt the user to enter a password string from standard input with echo disabled. Return null if end of stream has been reached.
table
abstract This table(Obj? obj)
Print tabular data to the console:
- List of list is two dimensional data where first row is header names
- List of items with an each method will create column per key
- List of items without each will map to a column of "val"
- Anything else will be table of one cell table
warn
abstract This warn(Obj? msg, Err? err := null)
Print a message to the console at the warning level
width
abstract Int? width()
Number of chars that fit horizontally in console or null if unknown
wrap
static Console wrap(OutStream out)
Construct a console that wraps an output stream. The returned console instance is not thread safe.
CsvInStream
@Js class CsvInStream : InStream
CsvInStream is used to read delimiter-separated values as specified by RFC 4180. Format details:
- rows are delimited by a newline
- cells are separated by
delimiterchar - cells may be quoted with
"character - quoted cells may contain the delimiter
- quoted cells may contain newlines (always normalized to "\n")
- quoted cells must escape
"with"" - the
trimflag trims leading/trailing whitespace from non-quoted cells (note that RFC 4180 specifies that whitespace is significant)
Also see CsvOutStream.
Constructors
| make | Wrap the underlying input stream. |
Fields
| delimiter | Delimiter character; defaults to comma. |
| trim | Configures whether unqualified whitespace around a cell is automatically trimmed. |
Methods
| eachRow | Iterate through all the lines parsing each one into delimited-separated strings and calling the given callback functions. |
| readAllRows | Read the entire table of rows into memory. |
| readRow | Read the next line as a row of delimiter-separated strings. |
Slot Details
delimiter
Int delimiter := 44
Delimiter character; defaults to comma.
eachRow
Void eachRow(|Str[]| f)
Iterate through all the lines parsing each one into delimited-separated strings and calling the given callback functions. The input stream is guaranteed to be closed upon completion.
make
new make(InStream in)
Wrap the underlying input stream.
readAllRows
Str[][] readAllRows()
Read the entire table of rows into memory. The input stream is guaranteed to be closed upon completion.
readRow
virtual Str[]? readRow()
Read the next line as a row of delimiter-separated strings. Return null if at end of stream.
trim
Bool trim := true
Configures whether unqualified whitespace around a cell is automatically trimmed. If a field is enclosed by quotes then it is never trimmed.
CsvOutStream
@Js class CsvOutStream : OutStream
CsvOutStream is used to write delimiter-separated values as specified by RFC 4180. Format details:
- rows are delimited by a newline
- cells are separated by
delimiterchar - cells containing the delimiter,
"double quote, or newline are quoted; quotes are escaped as""
Also see CsvInStream.
Constructors
| make | Wrap the underlying output stream. |
Fields
| delimiter | Delimiter character; defaults to comma. |
Methods
| isQuoteRequired | Return if the given cell string contains |
| writeCell | Write a single cell. |
| writeRow | Write the row of cells with the configured delimiter. |
Slot Details
delimiter
Int delimiter := 44
Delimiter character; defaults to comma.
isQuoteRequired
Bool isQuoteRequired(Str cell)
Return if the given cell string contains:
- the configured delimiter
- double quote
"char - leading/trailing whitespace
- newlines
make
new make(OutStream out)
Wrap the underlying output stream.
writeCell
virtual This writeCell(Str cell)
Write a single cell. If isQuoteRequired returns true, then quote it.
writeRow
virtual This writeRow(Str[] row)
Write the row of cells with the configured delimiter. Also see writeCell.
FileLoc
@Js const class FileLoc : Obj
FileLoc is a location within a text file or source string. It includes an optional one-base line number and column number. This class provides a standardized API for text based tools which need to report the line/column numbers of errors.
Constructors
| make | Constructor for filename string |
| makeFile | Constructor for file |
Fields
| col | One based line column number or zero if unknown |
| file | Filename location |
| inputs | Constant for tool input location |
| line | One based line number or zero if unknown |
| synthetic | Constant for synthetic location |
| unknown | Constant for an unknown location |
Methods
| compare | Comparison operator |
| equals | Equality operator |
| hash | Hash code |
| isUnknown | Is this the unknown location |
| toStr | Return string representation as "file", "file(line)", or "file(line,col)". |
Slot Details
col
const Int col
One based line column number or zero if unknown
compare
virtual override Int compare(Obj that)
Comparison operator
equals
virtual override Bool equals(Obj? that)
Equality operator
file
const Str file
Filename location
hash
virtual override Int hash()
Hash code
inputs
const static FileLoc inputs := FileLoc.make("inputs", 0)
Constant for tool input location
isUnknown
Bool isUnknown()
Is this the unknown location
line
const Int line
One based line number or zero if unknown
make
new make(Str file, Int line := 0, Int col := 0)
Constructor for filename string
makeFile
static new makeFile(File file, Int line := 0, Int col := 0)
Constructor for file
synthetic
const static FileLoc synthetic := FileLoc.make("synthetic", 0)
Constant for synthetic location
toStr
virtual override Str toStr()
Return string representation as "file", "file(line)", or "file(line,col)". This is the standard format used by the Fantom compiler.
unknown
const static FileLoc unknown := FileLoc.make("unknown", 0)
Constant for an unknown location
FileLocErr
@Js const class FileLocErr : Err
Exception with a file location
Constructors
| make | Constructor with message, location, and optional cause |
Fields
| loc | File location |
Methods
| toStr | Return "loc: msg" |
Slot Details
loc
const FileLoc loc
File location
make
new make(Str msg, FileLoc loc, Err? cause := null)
Constructor with message, location, and optional cause
toStr
virtual override Str toStr()
Return "loc: msg"
FileLogger
const class FileLogger : ActorPool
FileLogger appends Str log entries to a file. You can add a FileLogger as a Log handler:
sysLogger := FileLogger
{
dir = scriptDir
filename = "sys-{YYMM}.log"
}
Log.addHandler |rec| { sysLogger.writeLogRec(rec) }See filename for specifying a datetime pattern for your log files.
Constructors
| make | Constructor must set dir and filename |
Fields
| dir | Directory used to store log file(s). |
| filename | Log filename pattern. |
| onOpen | Callback called each time the file logger opens an existing or new log file. |
Methods
| writeLogRec | Append string log message to file. |
| writeStr | Append string log message to file. |
Slot Details
dir
const File dir
Directory used to store log file(s).
filename
const Str filename
Log filename pattern. The name may contain a pattern between {} using the pattern format of DateTime.toLocale. For example to maintain a log file per month, use a filename such as "mylog-{YYYY-MM}.log".
make
new make(|This|? f := null)
Constructor must set dir and filename
onOpen
const |OutStream|? onOpen
Callback called each time the file logger opens an existing or new log file. Callback should write any header information to the given output stream. The callback will occur on the logger's actor, so take care not incur additional actor messaging.
writeLogRec
Void writeLogRec(LogRec rec)
Append string log message to file.
writeStr
Void writeStr(Str msg)
Append string log message to file.
FloatArray
@Js class FloatArray : Obj
Optimized fixed size array of 4 or 8 byte unboxed floats. The array values default to zero.
Methods
| copyFrom | Copy the floats from that array into this array and return this. |
| fill | Fill this array with the given float value. |
| get | Get the float at the given index. |
| makeF4 | Create a 32-bit float array. |
| makeF8 | Create a 64-bit float array. |
| set | Set the float at the given index. |
| size | Get number of floats in the array |
| sort | Sort the floats in this array. |
Slot Details
copyFrom
This copyFrom(FloatArray that, Range? thatRange := null, Int thisOffset := 0)
Copy the floats from that array into this array and return this. The thatRange parameter may be used to specify a specific range of floats from the that parameter (negative indices are allowed) to copy. If thatRange is null then the entire range of that is copied. Or thisOffset specifies the starting index of this index to copy the first float. Raise an exception if this array is not properly sized or is not of the same signed/byte count as the that array.
fill
This fill(Float val, Range? range := null)
Fill this array with the given float value. If range is null then the entire array is filled, otherwise just the specified range. Return this.
get
@Operator Float get(Int index)
Get the float at the given index. Negative indices are not supported.
makeF4
static FloatArray makeF4(Int size)
Create a 32-bit float array.
makeF8
static FloatArray makeF8(Int size)
Create a 64-bit float array.
set
@Operator Void set(Int index, Float val)
Set the float at the given index. Negative indices are not supported.
size
Int size()
Get number of floats in the array
sort
This sort(Range? range := null)
Sort the floats in this array. If range is null then the entire array is sorted, otherwise just the specified range. Return this.
IntArray
@Js class IntArray : Obj
Optimized fixed size array of 1, 2, 4, or 8 byte unboxed integers. The array values default to zero.
Methods
| copyFrom | Copy the integers from that array into this array and return this. |
| fill | Fill this array with the given integer value. |
| get | Get the integer at the given index. |
| makeS1 | Create a signed 8-bit, 1-byte integer array (-128 to 127). |
| makeS2 | Create a signed 16-bit, 2-byte integer array (-32_768 to 32_767). |
| makeS4 | Create a signed 32-bit, 4-byte integer array (-2_147_483_648 to 2_147_483_647). |
| makeS8 | Create a signed 64-bit, 8-byte integer array. |
| makeU1 | Create a unsigned 8-bit, 1-byte integer array (0 to 255). |
| makeU2 | Create a unsigned 16-bit, 2-byte integer array (0 to 65_535). |
| makeU4 | Create a unsigned 32-bit, 4-byte integer array (0 to 4_294_967_295). |
| set | Set the integer at the given index. |
| size | Get number of integers in the array |
| sort | Sort the integers in this array. |
Slot Details
copyFrom
This copyFrom(IntArray that, Range? thatRange := null, Int thisOffset := 0)
Copy the integers from that array into this array and return this. The thatRange parameter may be used to specify a specific range of integers from the that parameter (negative indices are allowed) to copy. If thatRange is null then the entire range of that is copied. Or thisOffset specifies the starting index of this index to copy the first integer. Raise an exception if this array is not properly sized or is not of the same signed/byte count as the that array.
fill
This fill(Int val, Range? range := null)
Fill this array with the given integer value. If range is null then the entire array is filled, otherwise just the specified range. Return this.
get
@Operator Int get(Int index)
Get the integer at the given index. Negative indices are not supported.
makeS1
static IntArray makeS1(Int size)
Create a signed 8-bit, 1-byte integer array (-128 to 127).
makeS2
static IntArray makeS2(Int size)
Create a signed 16-bit, 2-byte integer array (-32_768 to 32_767).
makeS4
static IntArray makeS4(Int size)
Create a signed 32-bit, 4-byte integer array (-2_147_483_648 to 2_147_483_647).
makeS8
static IntArray makeS8(Int size)
Create a signed 64-bit, 8-byte integer array.
makeU1
static IntArray makeU1(Int size)
Create a unsigned 8-bit, 1-byte integer array (0 to 255).
makeU2
static IntArray makeU2(Int size)
Create a unsigned 16-bit, 2-byte integer array (0 to 65_535).
makeU4
static IntArray makeU4(Int size)
Create a unsigned 32-bit, 4-byte integer array (0 to 4_294_967_295).
set
@Operator Void set(Int index, Int val)
Set the integer at the given index. Negative indices are not supported.
size
Int size()
Get number of integers in the array
sort
This sort(Range? range := null)
Sort the integers in this array. If range is null then the entire array is sorted, otherwise just the specified range. Return this.
JsonInStream
@Js class JsonInStream : InStream
JsonInStream reads objects from Javascript Object Notation (JSON).
See pod doc for details.
Constructors
| make | Construct by wrapping given input stream. |
Methods
| readJson | Read a JSON object from this stream and return one of the follow types |
Slot Details
make
new make(InStream in)
Construct by wrapping given input stream.
readJson
Obj? readJson()
Read a JSON object from this stream and return one of the follow types:
- null
- Bool
- Int
- Float
- Str
- Str:Obj?
- Obj?[]
See Str.in to read from an in-memory string.
JsonOutStream
@Js class JsonOutStream : OutStream
JsonOutStream writes objects in Javascript Object Notation (JSON).
See pod doc for details.
Constructors
| make | Construct by wrapping given output stream. |
Fields
| escapeUnicode | Flag to escape characters over 0x7f using \uXXXX |
| prettyPrint | Write JSON in pretty-printed format. |
Methods
| prettyPrintToStr | Convenience for pretty-printing JSON to an in-memory string. |
| writeJson | Write the given object as JSON to this stream. |
| writeJsonToStr | Convenience for writeJson to an in-memory string. |
Slot Details
escapeUnicode
Bool escapeUnicode := true
Flag to escape characters over 0x7f using \uXXXX
make
new make(OutStream out)
Construct by wrapping given output stream.
prettyPrint
Bool prettyPrint := false
Write JSON in pretty-printed format. This format produces more readable JSON at the expense of larger output size.
prettyPrintToStr
static Str prettyPrintToStr(Obj? obj)
Convenience for pretty-printing JSON to an in-memory string.
writeJson
This writeJson(Obj? obj)
Write the given object as JSON to this stream. The obj must be one of the follow:
- null
- Bool
- Num
- Str
- Str:Obj?
- Obj?[]
- simple (written as JSON string)
- serializable (written as JSON object)
writeJsonToStr
static Str writeJsonToStr(Obj? obj)
Convenience for writeJson to an in-memory string.
LockFile
const class LockFile : Obj
LockFile is used to acquire an exclusive lock to prevent two different processes from using same files
Constructors
| make | Construct with given file |
Methods
| file | Backing file we use to lock/acquire |
| lock | Acquire the lock or raise CannotAcquireLockFileErr |
| unlock | Release the lock if we are holding one |
Slot Details
file
File file()
Backing file we use to lock/acquire
lock
This lock()
Acquire the lock or raise CannotAcquireLockFileErr
make
new make(File file)
Construct with given file
unlock
This unlock()
Release the lock if we are holding one
Macro
@Js const class Macro : Obj
Macro provides a way to replace macro expressions within a pattern using a pluggable implementation for the macro resolution. See apply for macro syntax.
Constructors
| make | Create a macro for the given pattern. |
Fields
| pattern | The unresolved macro pattern |
Methods
| apply | The pattern text is scanned for keys delimited by {{ and }}. |
| keys | Get a list of all the macro keys in the order they appear in the macro pattern. |
Slot Details
apply
Str apply(|Str->Str| resolve)
The pattern text is scanned for keys delimited by {{ and }}. The text between the delimiters is the key. The supplied callback is invoked to resolve the key and the macro is replaced with that value in the text. Returns the resulting Str after the macro has been applied. Throws ParseErr if the pattern contains invalid macros.
Macro("{{hello}} {{world}}!").apply { it.upper } => HELLO WORLD!
Macro("{{notTerminated").apply { it.upper } => ParseErrNo lexical restriction is placed on the macro keys. The callback is entirely reponsible for validating keys. For example, all the following are perfectly acceptable keys as far as parsing the macro goes:
{{}}- empty key{{ }}- all white space{{ foo }}- leading and trailing white space
keys
Str[] keys()
Get a list of all the macro keys in the order they appear in the macro pattern. Duplicates are not removed.
Macro("{{hello}} {{world}}! Good-bye {{world}}").keys
=> ["hello", "world", "world"]make
new make(Str pattern)
Create a macro for the given pattern.
pattern
const Str pattern
The unresolved macro pattern
Opt
@Serializable facet class Opt : Obj, Facet
Facet for annotating an AbstractMain option field.
Fields
| aliases | Aliases for the option |
| help | Usage help, should be a single short line summary |
Slot Details
aliases
const Str[] aliases := Str[,]
Aliases for the option
help
const Str help := ""
Usage help, should be a single short line summary
PathEnv
const class PathEnv : Env
PathEnv is a simple implementation of a Fantom environment which uses a search path to resolve files.
Constructors
| make | Constructor initializes the search path using the FAN_ENV_PATH environment variable (see Env.vars). |
Fields
| vars | Get the environment variables as a case insensitive, immutable map of Str name/value pairs. |
Methods
| findAllFiles | Search path for all versions of given file. |
| findAllPodNames | Search path for all "lib/fan/*.pod" files. |
| findFile | Search path for given file. |
| path | Search path of directories in priority order. |
| tempDir | Temp directory is always under workDir. |
| workDir | Working directory is always first item in path. |
Slot Details
findAllFiles
virtual override File[] findAllFiles(Uri uri)
Search path for all versions of given file.
findAllPodNames
virtual override Str[] findAllPodNames()
Search path for all "lib/fan/*.pod" files.
findFile
virtual override File? findFile(Uri uri, Bool checked := true)
Search path for given file.
make
new make()
Constructor initializes the search path using the FAN_ENV_PATH environment variable (see Env.vars).
path
virtual override File[] path()
Search path of directories in priority order. The last item in the path is always the Env.homeDir
tempDir
virtual override File tempDir()
Temp directory is always under workDir.
vars
virtual const override Str:Str vars
Get the environment variables as a case insensitive, immutable map of Str name/value pairs. The environment map is initialized from the following sources from lowest priority to highest priority:
- shell environment variables
- Java system properties (Java VM only obviously)
- props in "fan.props" prefixed with "env."
workDir
virtual override File workDir()
Working directory is always first item in path.
Random
@Js abstract class Random : Obj
Random provides different implementation of random number generators with more flexibility than the methods available in sys. Also see Int.random, Float.random, Range.random, and List.random.
Methods
| makeSecure | Construct a cryptographically strong random number generator. |
| makeSeeded | Construct a repeatable, seeded random number generator. |
| next | Generate 64-bit integer within the given range. |
| nextBool | Generate random boolean. |
| nextBuf | Generate a randomized number of bytes. |
| nextFloat | Generate 64-bit floating point number between 0.0f and 1.0f. |
Slot Details
makeSecure
static Random makeSecure()
Construct a cryptographically strong random number generator.
makeSeeded
static Random makeSeeded(Int seed := DateTime.nowTicks())
Construct a repeatable, seeded random number generator.
next
abstract Int next(Range? r := null)
Generate 64-bit integer within the given range. If range is null, assume full range of 64-bit integers
nextBool
abstract Bool nextBool()
Generate random boolean.
nextBuf
abstract Buf nextBuf(Int size)
Generate a randomized number of bytes.
nextFloat
abstract Float nextFloat()
Generate 64-bit floating point number between 0.0f and 1.0f.
SyntheticFile
const class SyntheticFile : File
SyntheticFile provides default no-op implementation of File API
Constructors
| make | Constructor |
Fields
| modified | No-op |
Methods
| create | Raise IOErr |
| delete | Raise IOErr |
| deleteOnExit | Raise IOErr |
| exists | Return false |
| in | Raise IOErr |
| list | Return empty list |
| mmap | Raise IOErr |
| moveTo | Raise IOErr |
| normalize | Return this |
| open | Raise IOErr |
| osPath | Return null |
| out | Raise IOErr |
| parent | Return null |
| plus | Return another instance of SyntheticFile |
| size | Return null |
Slot Details
create
virtual override File create()
Raise IOErr
delete
virtual override Void delete()
Raise IOErr
deleteOnExit
virtual override File deleteOnExit()
Raise IOErr
exists
virtual override Bool exists()
Return false
in
virtual override InStream in(Int? bufferSize := 4096)
Raise IOErr
list
virtual override File[] list(Regex? pattern := null)
Return empty list
make
new make(Uri uri)
Constructor
mmap
virtual override Buf mmap(Str mode := "rw", Int pos := 0, Int? size := this.size())
Raise IOErr
modified
virtual override DateTime? modified
No-op
moveTo
virtual override File moveTo(File to)
Raise IOErr
normalize
virtual override File normalize()
Return this
open
virtual override Buf open(Str mode := "rw")
Raise IOErr
osPath
virtual override Str? osPath()
Return null
out
virtual override OutStream out(Bool append := false, Int? bufferSize := 4096)
Raise IOErr
parent
virtual override File? parent()
Return null
plus
virtual override File plus(Uri uri, Bool checkSlash := true)
Return another instance of SyntheticFile
size
virtual override Int? size()
Return null
TestRunner
@Js class TestRunner : Obj
TestRunner executes Test classes and reports success/failure.
Fields
| isVerbose | Should tests be run in verbose mode |
| out | Output stream for built-in reporting |
Methods
| main | Run with given command line arguments |
| onSetup | Callback to invoke setup |
| onTeardown | Callback to invoke teardown |
| printUsage | Print usage |
| printVersion | Print version |
| reportFailure | Report the failure and exception raised |
| reportStart | Report the start of a test method |
| reportSuccess | Report the success and number of verifies |
| reportSummary | Report summary of tests |
| runAll | Run on every installed pod |
| runMethod | Run test method |
| runPod | Run all tests in given pod |
| runTarget | Run target from an argument string |
| runTargets | Run list of targets from an argument string |
| runType | Run all test methods on a given type |
Slot Details
isVerbose
Bool isVerbose
Should tests be run in verbose mode
main
static Int main(Str[] args)
Run with given command line arguments
onSetup
virtual Void onSetup(Test test)
Callback to invoke setup
onTeardown
virtual Void onTeardown(Test test)
Callback to invoke teardown
out
OutStream out := Env.cur().out
Output stream for built-in reporting
printUsage
Void printUsage()
Print usage
printVersion
Void printVersion()
Print version
reportFailure
virtual Void reportFailure(Type type, Method method, Err err)
Report the failure and exception raised
reportStart
virtual Void reportStart(Type type, Method method)
Report the start of a test method
reportSuccess
virtual Void reportSuccess(Type type, Method method, Int verifies)
Report the success and number of verifies
reportSummary
virtual Void reportSummary()
Report summary of tests
runAll
virtual This runAll()
Run on every installed pod
runMethod
virtual This runMethod(Type type, Method method)
Run test method
runPod
virtual This runPod(Pod pod)
Run all tests in given pod
runTarget
virtual This runTarget(Str target)
Run target from an argument string
runTargets
virtual This runTargets(Str[] targets)
Run list of targets from an argument string
runType
virtual This runType(Type type)
Run all test methods on a given type